Having a hard time getting elements to line up correctly

Question: I thought I was doing everything correctly but am having a hard time getting the elements in my html to center and position correctly, everything looks off but I don't know if it's my nav bar or if the actual div blocks are off.
Tried margin: 0 auto; tried text aligning everything to center. I used position relative to put a poor band-aid on the problem but I know it's not the best way to do it.
.flex{
    display: flex;
    flex-wrap: nowrap;
}

.testimonial{
position: relative;
top: 250px;
left: 10px;
float: left;
width: 33%;
height: 500px;
padding: 10px;
margin: 0 auto;
text-align: center;
}

.testimonial img{
position: relative;
left: 50%;
top: 65px;}

.testimonial p{
position: relative;
text-align: center;
top: 150px;
}

.testimonial a{
position: relative;
text-align: center;
top: 150px;
}

ABOUT US

Come to Hi-Bar Tractor Services to get all of your tractor
servicing needs. Our dedication to excellence and customer satisfaction
makes us the go to resource for all of San Diego.

SERVICES

Field/Pasture disc service, manure, junk, debris hauling, demolition
and more! Visit our services page for more awesome things that we can do
for you!

  Learn More!

INDUSTRY LEADER

Sean has been working with tractor repair and landscaping his whole
life making him a wealth of knowledge about any problems that you might
encounter. Call him now!

Comment: add u r html code also
Comment: Start from the beginning and use flexbox, it will be much easier.
Comment: @Dark0ctane please add your HTML code, so that we can see the performance issues in rendering of Your HTML
Comment: https://imgur.com/a/NI2T4hd this is what it looks like
Answer: I've pasted your code into a Codepen here: https://codepen.io/blueocto/pen/ZEzjxwK

First of all, margin: 0 auto on an element that is floated will not work. When it floats, it is taken out of the flow of the document
You don't need to position: relative all the things
I assumed you wanted to centrally align the image, title, paragraph and link ... this will happen as the text-align: center on your testimonial will cascade
I've added some styles for your images (placeholders) so they centrally align above your title

I hope that is what you were looking to achieve.
If my answer did help solve your issue, I'd really appreciate the upvote, thank you.
Answer: You have to turn your position: relative to position: initial
Example
Answer: The performance issues because of CSS
The problem in your CSS is
.testimonial a{
position: relative;
............
............
............
}

every time the browser reads position relative, browser try to re-render the dom!
So please try your CSS like this
.testimonial{
    position: relative;
    }

   a{
.........
.........
    }
img{
....
....
}

so that re-rendering does not cause an issue.
You can use Chrome DevTools for checking Performance issues at the browser end.
https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/


Xml Tag base64Binary C#

Question: Tenho a seguinte tag xml (vou resumir por questão de tamanho):
<docZip schema="procNFe_v3.10.xsd" NSU="000000000001868">H4sIAAAAAAAEAN1aWY+jyLJ+Pv..bla bla bla</docZip>

O tipo do campo é base64Binary, é um arquivo Gzip.
Já revirei a internet procurando uma forma de "ler" o XML e pegar esta tag e gerar o arquivo Gzip que está contido nela.
Como faço para pegar esta tag que está em base64Binary e gerar o arquivo que está contido?
Testei com esse código de exemplo porem sem sucesso:
using System;
using System.Text;

public class Base64Decoder
{
  public static void Main ()
  {
        string inputText = "This is some text.";
        Console.Out.WriteLine ("Input text: {0}", inputText);
        byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);

        string encodedText = Convert.ToBase64String (bytesToEncode);
        Console.Out.WriteLine ("Encoded text: {0}", encodedText);

        byte [] decodedBytes = Convert.FromBase64String (encodedText);
        string decodedText = Encoding.UTF8.GetString (decodedBytes);
        Console.Out.WriteLine ("Decoded text: {0}", decodedText);

        Console.Out.Write ("Press enter to finish.");
        Console.In.ReadLine ();

        return;
  }
}

Answer: Olá, eu tentaria fazer da seguinte forma:
byte[] buffer = Convert.FromBase64String("H4sIAAAAAAAEAN1aWY+jyLJ+Pv..bla bla bla");
File.WriteAllBytes(@"c:\home\arquivo.rar", buffer);

Espero ter ajudado.
Resposta editada a partir de mensagem postada abaixo para facilitar a outros com a mesma dúvida.
Comment: Ok Robss, não foi nada. Tomei a liberdade de editar minha resposta para que outras pessoas pudessem ter acesso a um código funcional, creio que seja mais "pedagógico". Abraço
Comment: Obrigado pela ajuda, porem o arquivo gerado está vazio. Porem gerei com o código File.WriteAllBytes(@"c:\home\arquivo.rar", buffer); mas sua resposta resolveu minha duvida.
Comment: Valeu jovem....
Answer: Galera usei a base deste tópico para me ajudar, e nada mais justo que compartilhar um ajuste, pois o conteúdo que vem da tag  é um xml então para a conversão direta fiz o seguinte:
        String base64 = "H4sIAAAAAAAEAIVSXW+CMBT9K4Z3...";

        byte[] buffer = Convert.FromBase64String(base64);
        byte[] xmlret = Decompress(buffer);

        File.WriteAllBytes(@"C:\retorno.xml", xmlret);

O metodo Decompress:
        static byte[] Decompress(byte[] gzip)
        {
           using (GZipStream stream = new GZipStream(new
           MemoryStream(gzip),CompressionMode.Decompress))
        {
            const int size = 4096;
            byte[] buffer = new byte[size];
            using (MemoryStream memory = new MemoryStream())
            {
                int count = 0;
                do
                {
                    count = stream.Read(buffer, 0, size);
                    if (count > 0)
                    {
                        memory.Write(buffer, 0, count);
                    }
                }
                while (count > 0);
                return memory.ToArray();
            }
        }
    }

Espero que ajude mais pessoas!

Xml Tag base64Binary C#


EMC PowerPath Support Matrix

Question: I know this is a stupid question, but I've found nothing online.  Does anyone know where EMC has hidden the support matrix documentation so that I know what version of PowerPath is supported with which version of FLARE?
Answer: I don't know if you already checked, but EMC's Powerlink is where you should check at the first place.
http://powerlink.emc.com/
There you can find all sort of infos about it, and all others EMC's products.
Comment: Try to provide explanation too,links might be not available after some time.
Comment: I spent hours looking through Powerlink before I posted this question and wasn't able to find anything.
Comment: There is also the https://elabnavigator.emc.com/eln/hostConnectivity that you can access thru the PowerLink. Have you also looked at there? Cause I could find the a list with several versions, and the Storage OS that are compatible... (https://elabnavigator.emc.com/eln/components?26/2/73907/71952/64569)

EMC PowerPath Support Matrix


Prove that number of divisors of any nonzero number is finitive

Question: Prove that number of divisors of any nonzero number is finitive.
I know the formula that using that we can show that they are finitive.
But we had this question befor learning this and we cannot use it I tried to dividing it to an other number and prove the theorm using induction But I can't.Any ideas?
Comment: If $a \mid b$, and $b \neq 0$, what can you say about the relation between $\lvert a\rvert$ and $\lvert b\rvert$?
Comment: How many integers with $\lvert k \rvert \leqslant \lvert n\rvert$ are there for a nonzero integer $n$?
Comment: Trivially the number of (positive) divisor of $n$ is $\le n$, because a divisor cannot be $>n$
Comment: @DanielFischer  $\mid b \mid\ge \mid a \mid$ But what to do with this?
Comment: @DanielFischer Well why don't you post an answer.Your comment is a full answer.
Answer: From the multiplicativity of the modulus it follows that for $n \in \mathbb{Z}\setminus \{0\}$ we have $k \mid n \implies \lvert k\rvert \leqslant \lvert n\rvert$. Since $\{ k \in \mathbb{Z} : \lvert k\rvert \leqslant \lvert n\rvert\}$ has only finitely many elements (namely $2\lvert n\rvert + 1$), it follows that $n\in \mathbb{Z}\setminus \{0\}$ has only finitely many divisors. (Of course the bound on the number of divisors obtained from this argument is abysmal.)
Answer: You can prove it by induction.
Clearly $1$ has only 1 divisor: namely, $1$ itself.
Next, fix a positive integer $n>1$ and suppose that all numbers less than $n$ have only finitely many divisors. Let $p$ be any prime dividing $n$. Then, $1\leq\frac{n}{p}<n$. Hence, by our inductive assumption, $\frac{n}{p}$ has only finitely many divisors. Since $p$ is prime, its only divisors are $1$ and $p$. Thus, $n=p\cdot\frac{n}{p}$ has only finitely many divisors.


How to normalize a slope?

Question: Say I have two slopes and two averages for a sample:
$m=4{,}000$ dollars/day, average $a=50{,}000$
$n=80{,}000$ dollars/day, average $b=700{,}000$
Graphically, $n$ is very 'steep' compared to $m$. But I know that $n$ is not very steep relative to it's average size ($b=700{,}000$). Is there a way that I could get a 'percent slope', so that I could compare the slopes of these two values relative to the average size?
Comment: Sure, and it can be done exactly how you're thinking: you can say, for instance, that '$n$'s rate of change is 14% of its average value', while '$m$'s rate of change is 8% of its average value'.  (Note that $n$ is still 'steeper' than $m$ compared to its average!)
Answer: You can simply express this relative change as a fraction, namely
$$\frac ma=0.080=8.0\%\qquad\text{resp.}\qquad\frac nb\approx0.114=11.4\%$$

How to normalize a slope?


Sum of an infinite series of integrals between two bounds

Question: The Fundamental Theorem of Calculus states that:
$$\int_a^ b f(x) \, dx = F(b) - F(a)$$
We also know that any definite integral of any function bounded by the same two points is equal to zero.
$$\int_a^ a f(x) \, dx = 0$$
So, my question is, if we add up an infinite number of integrals of a function whose bounds are the same within every integral but incremented by a very, very small number between each subsequent integral, will that be equal to the integral bounded by the explicit two points or zero? Sorry if this question is confusing, hopefully the notation below will better describe it.
$$\int_a^ b f(x) \, dx = \int_a^{a} f(x) \, dx + \int_{a+n}^{a+n} f(x) \, dx + \int_{a+2n}^{a+2n} f(x) \, dx + ...+\int_{b}^{b} f(x) \, dx$$
Where n is a very, very small number.
This confuses me, because I would assume that each of these individual integrals are equal to zero.
Edit:
You can split an integral up like shown below:
$$\int_0^a f(x) \, dx = \int_{0}^{a/2} f(x) \, + \int_{a/2}^{a} f(x) \, $$
Why is it once the bounds are the same between each split up integral that suddenly it will be equal to zero?
Comment: every integral you have written is zero, how are you concluding that the LHS is equal to the RHS?
Comment: @qbert I think that is the question.
Comment: @SimpleArt I don't understand why the OP thinks it should be....
Comment: Is that supposed to be "Where $n$ is a very, very small number"?
Answer: No.
You've written $[a, b]$ as a union of points, which is not right. You should write this as a union of open intervals.
Answer: Assuming the existence of a primitive you have written
$$
F(a)-F(a)+F(a+n)-F(a+n)+.....+F(b)-F(b)\ne F(b)-F(a)
$$
Comment: @AlecBell Because you have not split the integral correctly.  See my answer to see how you should split it up.
Comment: sigh. Why the downvote?
Comment: I downvoted because I found this answer not useful, as it seems to me that the OP is more concerned with the reasoning for why this is the case.  From the last line, it appears he is aware of what you've written, even when the primitive doesn't exist, and explicitly asks for **why** they are inequal, it seems.
Comment: @SimpleArt interesting that you downvoted after your answer was downvoted by someone else....
Comment: I just honestly feel like this doesn't answer the question, that's all.  Anyways, cheers.
Comment: See my edit. Why does splitting up the integral into an infinite number of integrals not work, but splitting up the integral into a finite number of integrals does?
Answer: Actually, you'd be performing a limit.
See that
$$\int_0^af(x)dx=\int_0^{a_1}f(x)dx+\int_{a_1}^af(x)dx$$
$$=\int_0^{a_1}f(x)dx+\int_{a_1}^{a_2}f(x)dx+\int_{a_2}^af(x)dx$$
$$\vdots$$
$$=\int_0^{a_1}f(x)dx+\int_{a_1}^{a_2}f(x)dx+\dots \int_{a_n}^af(x)dx$$
For some sequence $0<a_1<a_2<a_3<\dots<a_n<a$.
To simplify, have $\epsilon>0$.
$$\int_0^af(x)dx=\underbrace{\int_0^{\epsilon}f(x)dx+\int_{\epsilon}^{2\epsilon}f(x)dx+\int_{2\epsilon}^{3\epsilon}f(x)dx+\dots \int_{a-\epsilon}^af(x)dx}_{a/\epsilon}$$
Particularly, we want to take the limit $\epsilon\to0^+$.  Doing this gives us
$$\lim_{\epsilon\to0^+}\underbrace{\int_0^{\epsilon}f(x)dx+\int_{\epsilon}^{2\epsilon}f(x)dx+\int_{2\epsilon}^{3\epsilon}f(x)dx+\dots \int_{a-\epsilon}^af(x)dx}_{a/\epsilon}=0\times\infty$$
which is a limit of the form $0\times\infty$.  This allows it to evaluate to some value.
Also note that evaluating the limit is equivalent to Riemann sums.

Your attempt in disguise:
$$\int_0^af(x)dx=\int_0^0f(x)dx+\int_a^af(x)dx$$
$$=\int_0^0f(x)dx+\int_{a/2}^{a/2}f(x)dx+\int_a^af(x)dx$$
$$\vdots$$
$$\int_0^a f(x) \, dx = \int_0^0 f(x) \, dx + \int_{n}^{n} f(x) \, dx + \int_{2n}^{2n} f(x) \, dx + ...+\int_{a}^a f(x) \, dx$$
See the difference in how we constructed the expansion?

Also note that your idea of the limit is incorrect, as you can see with the following limit:
$$\lim_{n\to\infty}\underbrace{\frac1n+\frac1n+\frac1n+\dots\frac1n}_n=1$$
despite the individual terms approaching $0$, the total limit is equal to $1$.
Comment: this is not the series the op wrote
Comment: @qbert Yes, I know.  Regardless, I think it actually clears the OP's confusion rather than reinforcing it, which is what I think was in need here.
Comment: I don't think the OP meant the above since they said "if we add up an infinite number of integrals of a function whose bounds are the same within every integral but incremented by a very, very small number between each subsequent integral" and wrote the sentence mathematically, but we shall see
Comment: Why you can take a limit of each integral and obtain a result as the difference between the two bounds approaches zero? Wouldn't the limit of each of these integrals just be equal to zero?
Comment: @AlecBell What is the following limit: $$\lim_{n\to\infty}\underbrace{\frac1n+\frac1n+\frac1n+\dots\frac1n}_n$$?  Consider cases $n=1,2,3,\dots$.  I have also updated the answer, so I hope it is more clear now.
Comment: Hm, why the many downvotes?  I think this is a good answer for the question.
Comment: @AlecBell Also, I have considered that the result would be $0$, but that we'd be adding it infinitely many times, thus the indefinite form mentioned $0\times\infty$ if done correctly.
Answer: Your equation is not true.
In order to talk about integrals we must first define what one is.
Integration is often defined by Riemann sums, so I'll assume you're
familiar with the definition or can look it up.
In particular, an introduction to integral calculus is likely to
show examples of Riemann sums using a uniform grid, that is,
dividing the interval $[a,b]$ into some number of equal pieces.
I believe in a correct understanding of Riemann integration,
nobody really cares what the function is doing at each of the finite
number of points in the "grid" between $a$ and $b$.
What we really care about is what the function is doing at all the
points in between each pair of consecutive grid points.
The only reason we look at the grid points is because
(under certain reasonable assumptions) they give us
a clue about what the function is doing in between them.
What your sum of integrals represents is the integral of the function
at each of the input values $a, a+n, a+2n, \ldots, b$.
In other words, you've covered a set of points we don't really care about,
and left out the points in between, which we really do care about.
Simply presenting an infinite sequence of finer and finer grids doesn't
change this. Until you do something that covers some interval along the
real number line, you will have integrated essentially nothing.

To put it another way, there are simply too many real numbers $x$
between any two numbers $a$ and $b$ (with $a < b$) for you to
"add up" the the value of the integral in the way you're attempting.
Any sum of that form (with each integral starting and ending at the
same value of $x$) will look at $f(x)$ at only a finite number of
values of $x$ between $a$ and $b$
(because in standard analysis, if $n$ is not exactly zero
then $b < a + Qn$ for some integer $Q$),
which is precisely $0\%$ of all the values of $x$
that lie between $a$ and $b$.
You could extend this to an infinite number of values of $x$
by taking an infinite sequence of these sums with smaller and smaller
values of $n$, but in so doing you would still have covered
precisely $0\%$ of all the values of $x$
that lie between $a$ and $b$.
Comment: In some sense the integral $\int_a^b f(x)\,dx$ is "adding up" (though maybe we should say it's "averaging") the values of $f(x)$ for every $x$ between $a$ and $b$. It's what we use _instead_ of $+\cdots+$ for these particular kinds of "sums".
Comment: Hm, can I do it with only the irrational numbers, ignoring the rationals?
Comment: One term for each irrational number would give you an uncountable number of terms. How do you write such a sum, even with $+\cdots+$?
Comment: No idea, but your answer inspired that thought.


@Rollback is not working in Spring+Hibernate+Junit testing

Question: while testing a DAO function in spring+hibernate application, data rollback is not happening. I am trying to do the rollback a junit test case by @Rollback annotation
transactionManager config:
<code><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf" />
</bean>
</code>
In my main code I am using hibernateTemplate() to do CRUD operations
test code:
<code>@Test
@Transactional
@Rollback(true)
public void test_populateObject() throws Exception {

    // TransactionDefinition def = new DefaultTransactionDefinition();
    // TransactionStatus status = transactionManager.getTransaction(def);

    manualObj= new ManualObj();

    manualObj.setName("TestObj001");
    manualObj.setRefId("TestObj001");
    manualObj.setCallback("TestObj001");
    m
    TestObject obj=orderService.createTestObject(manualObj);

    Assert.assertNotNull(obj);

    // transactionManager.rollback(status);

}
</code>
The created object is not being deleted by rollback.
So, What could be the reason that @Rollback is n't happening?
Edit 1:
I am using Spring Data JPA and hibernateTemplate based data access in same application. Both using the same transaction manager specified like the above bean config.
Answer: Did you configure your test to use the xml configuration, and did you specify the SpringJUnit4ClassRunner to run your test?
You can do it like this:
<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class YourTest{ ... }
</code>
Comment: It is using a test configuration file
Comment: Ok, and are you sure you need the @Rollback annotation? Normally the Transactional annotation already rollbacks changes after each test.
Comment: It does not matter. If rollback happens that is fine. Seems the problem is with the transaction manager. I use two data access tools hibernateTemplate and Spring data JPA. The testcase uses hibernateTemplate to access data but I created transaction manager with org.springframework.orm.jpa.JpaTransactionManager. So I am looking on changing it.
Comment: As I said in previous comment, the issue is because of transactionmanager bean configuration. So changed the bean to

. Done.


How to change this jquery fiddle to have the first div open/active by default?

Question: I found this fiddle (http://jsfiddle.net/m6aRW/109/) that does exactly what I need it to do for me. However, how can I alter it so that #div1 is open on page load? Just using display:block keeps that div open even if you click the others.

jQuery(function ($) {
    $('.showSingle').click(function () {
        var itemid = '#div' + $(this).attr('target'); //id of the element to show/hide.

        //Show the element if nothing is shown.
        if ($('.active').length === 0) {
            $(itemid).slideDown();
            $(itemid).addClass('active');

            //Hide the element if it is shown.
        } else if (itemid == "#" + $('.active').attr('id')) {
            $('.active').slideUp();
            $(itemid).removeClass('active');

            //Otherwise, switch out the current element for the next one sequentially.
        } else {
            $('.active').slideUp(function () {
                $(this).removeClass('active');
                if ($(".targetDiv:animated").length === 0) {
                    $(itemid).slideDown();
                    $(itemid).addClass('active');
                }
            });
        }
    });
});
.targetDiv {
    display: none
}

Div 1

Div 2

Div 3

Div 4

Lorum Ipsum1

Lorum Ipsum2

Lorum Ipsum3

Lorum Ipsum4

Answer: You can trigger the first showSingle element click event:
$('.showSingle:first').trigger('click');

http://jsfiddle.net/m6aRW/110/
Answer: If you want the div to be visible by default when the page loads, add the active class to div1 and change the css to be
.targetDiv:not(.active) {
   display: none
}

If you want it to slide down once the page has loaded, instead add some jQuery to do so
$(document).ready(function() { $("#div1").trigger("click"); });

Answer: Here you have it!
$( document ).ready(function() {
   $("#div1").slideDown();
   $("#div1").addClass('active');
});

http://jsfiddle.net/m6aRW/111/


How to find out what consumes Linux pty's

Question: The number of allocated ptys (/proc/sys/kernel/pty/nr) on my linux server is constantly growing, and exceeds the number of active logins, terminals and screen sessions by orders of magnitude. Only a system restart resets seems to reset it.
How can I find out which process is eating up the pty's?
I tried the suggestion in answer 1, but
# lsof -n | grep pts | wc -l
137
# cat /proc/sys/kernel/pty/nr
696

# uname -a
Linux spitzer 2.6.32-34-server #77-Ubuntu SMP Tue Sep 13 20:54:38 UTC 2011 x86_64 GNU/Linux

Answer: Ptys are file handles. You can use lsof to find out which process is keeping which files open.
# lsof -n | grep pts

Comment: Doesn't quite work though (main question edited).
Comment: Which kernel/distribution are you running?
Comment: Try `lsof -n | grep 136,`
Comment: @DavidSchwartz That includes process ids and memory segments that would happen to match as well.
Answer: According to grawity's answer on superuser, what you are seeing is due to a bug in linux. /proc/sys/kernel/pty/nr is not decremented when a pty is no longer used. That is why lsof is showing a lower number. This was noticed in November 2009 but not fixed until August 2011.
Answer: A pty can have more than one 'file' associated with it.  If you take that into account, the kernel.pty.nr number will match the lsof number.
cat /proc/sys/kernel/pty/nr

10

lsof -n | fgrep pts | wc -l

58

lsof -n | fgrep pts | sed 's/  */ /g' | cut -f9 -d' ' | sort | uniq | wc -l

10


Expectation of a squared Ito integral

Question: I want to evaluate the following expectation:
$$
     \mathbb{E}\left[ \left(\int_0^T W_t^2 d W_t \right)^2\right],
$$
where $W_{t}$ is a Brownian motion. For now, I have
$$
\left(\int_{0}^{T}W^{2}_{t}\, d W_{t}\right)^2=\frac {1}{9}W^{6}_{T}+\left(\int_{0}^{T}W_{t}\, d t\right)^2-\frac {2}{3}W^{3}_{T}\int_{0}^{T}W_{t}\, d t.
$$
I think I can deal with the $\frac {1}{9}W^{6}_{T}$ part. There are two issues I don't know how to approach. One is that I don't know the variance of $\int_{0}^{T}W_{t}\, d t$. The other one is about how to compute the expectation of $\frac {2}{3}W^{3}_{T}\int_{0}^{T}W_{t}\, d t$.
Comment: For the variance-type term, write $\left(\int_0^T W_t dt\right)^2 = \int_0^T W_t dt \int_0^T W_sds = \int_0^T\int_0^T W_tW_sdtds$. Can you do this part now?
Comment: In fact, you need not even perform the expansion : the first term can be simplified because of the [Ito isometry](https://en.wikipedia.org/wiki/It%C3%B4_isometry).
Comment: @SarveshRavichandranIyer Yes, I can do the computation writing in this way, and it gives me $T^3/3$. I wonder how to compute the last product term, just to verify the Ito isometry.
Comment: I'm not fully sure about the other term just as yet. Once I'm sure I'll write an answer.
Answer: $\newcommand{E}{\mathbb E}$
For the variance-term, use $$
\left(\int_0^T W_t dt\right)^2 = \int_0^T \int_0^T W_tW_sdtds
$$
whence $$
\mathbb E\left(\int_0^T W_t dt\right)^2 = \int_0^T \int_0^T \mathbb E[W_tW_s]dtds = \int_0^T \int_0^T (t \wedge s) dtds
$$
Where the Fubini theorem for exchanging the expectation and double integral applies since $\int_0^T \int_0^T \mathbb E|W_tW_s|dtds < \infty$ (for that, see the argument here).
For the other , imagine we had a function $f(t)$ in place of $W_t$. The resulting integral would look like $\frac 23 f(T)^3 \int_0^T f(t)dt$. Now, $f(T)^3$ is just a constant, therefore one can slip it inside and write $\frac 23 \int_0^T f(T)^3f(t)dt$. Since the integral of a Brownian motion evaluated at a sample point $\omega$ is just the integral of some continuous function, the same logic holds on an $\omega$-by-$\omega$ basis and therefore $$
\frac 23 W_T^3 \int_0^T W_tdt = \frac 23 \int_0^T W_T^3W_tdt
$$
whence $$
\mathbb E\left[\frac 23 W_T^3 \int_0^T W_tdt\right] = \frac 23 \mathbb E\left[\int_0^T W_T^3W_tdt\right] = \frac 23\int_0^T \E[W_T^3W_t]dt
$$
where we can exchange the expectation and integral using the Fubini theorem once again , because $\int_0^T \mathbb E|W_T^3W_t| dt<\infty$. To see this, use an argument very similar to the one earlier: $$
|W_T^3W_t| = |(W_t + (W_T- W_t))^3W_t| \\
\leq |W_t^4| + 3|W_t^3||W_T-W_t| +3|W_t^2||(W_T-W_t)^2| + |W_t||(W_T-W_t)^3|
$$
and the expectation of the RHS is some polynomial in $t$ , which is obviously integrable on $[0,T]$. Once this is done,  you can use the fact that $$
\E[W_T^3W_t] = \E[(W_t +(W_T-W_t))^3W_t] \\ = \E[W_t^4] + 3\E[W_t^3]\E[W_T-W_t] + 3\E[W_t^2]\E[(W_T-W_t)^2] + \E[W_t]\E[(W_T-W_t)^3]
$$
using the independence of increments. Using the usual formulas, this comes to $3t^2 + 3t(T-t)$, which you can integrate over $[0,T]$ and multiply by $\frac 23$ to get the value of that respective term.
Comment: Why are we not using Ito isometry and the fact that the fourth moment of $W_t$ is $3t^2$?
$$
\textstyle\mathbb E[(\int_0^tW_s^2\,dW_s)^2]=\mathbb E[\int_0^tW^4_s\,ds]=\int_0^t\mathbb E[W^4_s]\,ds=3\int_0^ts^2\,ds=t^3\,.
$$
Comment: @KurtG. Because I thought the exercise was to illustrate the Ito isometry for this example. That is, show using "other methods" that the Ito isometry is true for $X_t = W_t^2$. I would have used it, you can see the comment thread above, but the OP mentioned they had to "verify" the Ito isometry rather than use it.
Comment: Small typo: the final result seems to me like it should be $3t^2 + 3t(T-t)$.
Comment: @JoseAvilez Corrected, thanks.

Expectation of a squared Ito integral


$(n+1)$th derivative by differentiating

Question: I've tried to answer this question many time but always wrong so can you help me please ?
 Thanks
Let $f(x) = \ln(1 + x)$.
Use mathematical induction to prove that the
following statement is true.
$$f^{n}(x) = \frac{(−1)^{n+1} (n − 1)!}{(1 + x)^n}$$
 for all $n ∈ \mathbb N$.
Comment: @copper.hat Ooooh, take it easy. Not too fast. That may solve the problem.
Comment: Have you tried differentiating $f^{(n)}$????
Comment: @ClementC.: I am not a fan of indolence :-).
Comment: Well, if one does not try anything, then one won't make any mistake, right?
Comment: I keep trying to learn by making mistakes, but have found that repeating the same mistake doesn't make the learning go faster :-).
Comment: Yes I did differentiating and got 1/x+1 ?!
Comment: @Yassmin for the induction step, you differentiate $f^{(n)}$, not $f$.
Comment: OK I'll try now
Answer: Induction start
$$f'(x)=\frac{1}{1+x}.$$
Induction step
\begin{align*}f^{(n)}(x)=(f^{(n-1)})'(x)&=\left(\frac{(-1)^{n}(n-2)!}{(1+x)^{n-1}}\right)' \\ & =\frac{(-1)^{n}(n-2)!}{(1+x)^{n}}\cdot (-(n-1))\\ &=\frac{(-1)^{n+1}(n-1)!}{(1+x)^{n}}\end{align*}
Where I only used that $(x^k)'=k\cdot x^{k-1},\forall k\neq 0$
Comment: I presume because the policy is to answer only if effort is shown. In this case I must admit to have decided to answer anyway because the OP said to have tried to solve the problem, so I believed him.
Comment: I think downvoters should provide reasons.
Comment: Why the downvote?
Comment: Also, there appears to be a typo. the $n-1!$ should be $(n-2)!$, shouldn't it? (two occurrences)
Comment: absolutely. I'll correct it straight away. (I was typing from my phone... not funny, I'll tell you)
Comment: So this is the last answer ?!
Comment: What do you mean? This is *an* answer, which gives a proof of the statement.
Answer: Hint:$$f^{(n+1)}(x) = (f^{(n)}(x))' = \left(\frac{(-1)^{n+1}(n-1)!}{(1+x)^n}\right)' = \quad???$$
Answer: Let $$f(x)=\ln(1+x)$$ and
$$f^{n}(x) = \frac{(−1)^{n+1} (n − 1)!}{(1 + x)^n}$$ be the statement.
Clearly $$f'(x)=\frac{1}{1+x}=\frac{(−1)^{1+1} (1 − 1)!}{(1 + x)^1}$$
Thus the result is true for $n=1$.
Now suppose that the result is true for $n=p$.
That is $$f^{p}(x) = \frac{(−1)^{p+1} (p − 1)!}{(1 + x)^p}$$
Now observe that ,
$$f^{p+1}(x)=\frac{d[f^{p}(x)]}{dx} $$
$$f^{p+1}(x)=\frac{d\left[\frac{(−1)^{p+1} (p − 1)!}{(1 + x)^p}\right]}{dx} $$
$$f^{p+1}(x)=(−1)^{p+1} (p − 1)!\frac{d\left[\frac{1}{(1 + x)^p}\right]}{dx} $$
$$f^{p+1}(x)=(−1)^{p+1} (p − 1)!\frac{(-p)}{(x+1)^{p+1}} $$
$$f^{p+1}(x)=(−1)^{(p+1)}(-1)^1 (p − 1)!(p)\frac{1}{(x+1)^{p+1}} $$
$$f^{p+1}(x)=\frac{(−1)^{(p+1)+1} \left((p+1)-1\right)!}{(x+1)^{p+1}} $$

$(n+1)$th derivative by differentiating


Extract RA and DEC values

Question: Im using Excel 2010
I am having trouble extracting the correct values from a RA and DEC values.
I want to extract each value from the RA and DEC and place the deg, min, sec in separate columns.
Essentially just rewrite the values in separate columns. I cant do this individually as i have over 3500 items to convert.
Eg.
column A .....| B ...| C .| D
19:24:59.38  |  19  | 24  | 59.38
Here is what i have at the moment.
The RA appears as '7:24:59 PM' in the text bar formatted as time "[h]:mm:ss.s" this appears as 19:24:59.59 in the cell A1.
to get deg:B1 = TEXT(TRUNC(A1,2)*24,"00") --> this produces 19 - correct
to get min:C1 = MID((TRUNC(A1,5)*24-B1)*60,1,2) --> this produces 24 - correct
to get sec:D1 = MID((((TRUNC(A1,5)*24-B1)*60)-C1)*60,1,5) --> this produces 58.46 - wrong. This should be 59.59 (decimal form) or preferably 59.38 (decimal degrees)
Can anyone tell me how to extract the correct values?
Thanks in advance.
Answer: You should use [h]:mm:ss.00 for the format - then it will display the right value.
For B1 you can use =HOUR(A1) and for C1 you can use =MINUTE(A1) but for D1 you cannot use =SECOND(A1) because it truncates the decimal points so use =MOD(A1*86400,60) instead.
Perhaps a screenshot might help?
Comment: I did as you suggest, the formatting you suggest just adds 00 after the decimal point making 59.59, 59.00.
Comment: Also the MOD() calculations for the second seems to truncate the decimal point just like the SECOND() calculation.
Comment: I have Excel 2010 and I made a spreadsheet with the formulas before I posted the answer.  I don't see how your results would be different from mine but it really did work on my machine.

Extract RA and DEC values


C++ Validating Comma Placement in Numerical Input

Question: I'm taking my first cs course and I'm currently learning the different ways to validate numerical inputs. Below is a bool function I wrote to check comma positions, but when I enter 65,000 it thinks the comma is in the wrong place.
bool commas(string input) {
    bool commas = true;
    long len = input.length();
    int counter = 0;

    for(int z = len-1; z >= 0; --z) {
        if(counter == 3) {
            if(input[z] != ',') {
                commas = false;
            counter = 0;
            }
        }
        else {
            if(input[z] == ',') {
                commas = false;
            }
            else {
                ++counter;
            }
        }
    }
    return commas;
}

Comment: The comma in `65,000` is at index `2`. At index `4` it has a `0`. I suggest you consider how far `z` is from the _end_ of the string, not how far it is from the beginning. After all, `1,000,000` has commas at indices `2` and `6`, whereas `10,000,000` has them at indices `3` and `7`.
Comment: Also consider the risk of false positives. I assume you don't want something that thinks `1,0,0,0,0,0,0` has commas in the correct spots. How would you detect that?
Comment: Wouldn't it be easier if you started from the right side of the string and loop backwards instead of the left?
Comment: The reason why you want to start from the right side and go backwards is that each iteration **must** have the correct character.  If you start from the left side as you're doing now, you don't know if that `,` after the `5` is valid or not -- you have to wait until you get to some position in the string to say "oh yeah, that comma I saw before really wasn't good".  For example `65,00` -- How do you know that the comma is in the correct position if you start from the left side and go forward?  Now start from the right side and go backwards -- that comma is immediately known to be bad.
Comment: c++14 also provide a **[digit separator](https://stackoverflow.com/questions/27767781/why-was-the-space-character-not-chosen-for-c14-digit-separators)** feature.
Comment: @PaulMcKenzie I just updated it so that the for loop iterates backward but it's still returning false when commas are in the correct places, any idea why?
Comment: @userh16xx0 -- First, do not change your original post -- add to it with the edited program.  Hint, don't use the `z` in the formula.  Just simply use another counter that increases on each iteration.  Here's why going backwards is easier -- you know *exactly* where the commas are supposed to be -- at iteration 3, 6, 9, 12, etc. if you go backwards.  I suggest you work this out on paper.
Comment: I rolled back the edits you made to the original post -- the question now fits what you originally was trying to do.
Answer: The easiest way to figure out if the comma is in the correction position is to go backwards (starting from the rightmost character) within the string.
The reason why this is easier is that if you were to start from the leftmost character and go forward, when you encounter a ,, you don't really know at that point whether that comma is in a valid position.  You will only know until later on within the iteration process.
On the other hand, when you go from right-to-left, you know that if you encounter a comma, that comma is in a valid position -- there is no need to wait until you've gone further in the string to determine if the comma is valid.
To do this, it takes an adjustment in the loop to go backwards, and an additional counter to track the current group of 3 digits, since a comma can only occur after a group of 3 digits has been processed.
This is an untested example (except for the simple tests in main):
#include <string>
#include <cctype>
#include <iostream>

bool commas(std::string input)
{
    // if the string is empty, return false
    if (input.empty())
        return false;

    // this keeps count of the digit grouping
    int counter = 0;

    // loop backwards
    for (int z = static_cast<int>(input.size()) - 1; z >= 0; --z)
    {
        // check if the current character is a comma, and if it is in
        // position where commas are supposed to be
        if (counter == 3)
        {
            if (input[z] != ',')
                return false;

            // reset counter to 0 and process next three digits
            counter = 0;
        }
        else
        // this must be a digit, else error
        if (input[z] == ',')
            return false;
        else
            // go to next digit in group of 3
            ++counter;
    }

    // the first character must be a digit.
    return isdigit(static_cast<unsigned char>(input[0]));
}

int main()
{
    std::string tests[] = { "123,,345",
                            "123,345",
                            "123,345,678",
                            "12,345",
                            "1223,345",
                            ",123,345",
                            "1",
                            "",
                            "65,00",
                            "123"};

    const int nTests = sizeof(tests) / sizeof(tests[0]);
    for (int i = 0; i < nTests; ++i)
        std::cout << tests[i] << ": " << (commas(tests[i]) ? "good" : "no good") << "\n";
}

Output:
123,,345: no good
123,345: good
123,345,678: good
12,345: good
1223,345: no good
,123,345: no good
1: good
: no good
65,00: no good
123: good

The way this works is simple -- we just increment a counter and see if the current position we're looking at (position z) in the string is a position where a comma must exist.
The count simply counts each group of 3 digits -- when that group of 3 digits has been processed, then the next character (when going backwards) must be a comma, otherwise the string is invalid.  We also check if the current position is where a comma cannot be placed.
Note that at the end, we need to check for invalid input like this:
,123
This is simply done by inspecting the first character in the string, and ensuring it is a digit.
Comment: This explanation makes sense to me, thank you!! The only problem now is using that logic to fit my code. Since my string is not in an array, it's just one input, I changed a few things. I can't say I did it right because my function isn't returning true for the inputs that have commas in the right places. Are you able to see what I may have missed or interpreted incorrectly? If not that's okay, I appreciate your help!


Question of $\Diamond$ in Generic Extension

Question: Let $M$ be a countable transitive model of $ZFC$, $\mathbb{P}\in M$ a forcing notion and $G$ a $\mathbb{P}$-generic filter over $M$.
Assume $( \mathbb{P}$ is c.c.c and $|\mathbb{P}|\leq \omega_{1})^{M}$  and $\Diamond$ holds in $M$.
I want to show  $\Diamond$ is holds in $M[G]$.
How to use $ \Diamond $  in $ M $?
Comment: Apply $\diamondsuit$ to the $\mathbb{P}$-names for subsets of $\omega_1$?  (By the ccc, you can code such a name as an $\omega_1$-sequence of countable subsets of $\mathbb{P}$.)
Comment: Oops! That's the other direction! Sorry! :-)
Answer: Here are the details on Paul's comments (just copy pasting from my tex files - Replace $\kappa$ and $S$ by $\omega_1$ below):
For a regular uncountable cardinal $\kappa$ and a stationary $S \subseteq \kappa$,
$\diamondsuit_S$ is the statement: There exists a sequence $\langle A_{\alpha} : \alpha \in S \rangle$ such that each $A_{\alpha} \subseteq \alpha$ and for every $A \subseteq \kappa$, the set $\{\alpha \in S : A_{\alpha} = A \cap \alpha\}$ is stationary in $\kappa$.
Claim: Suppose $\kappa$ is a regular uncountable cardinal and $S$ is a stationary subset of $\kappa$. Let $P$ be a $\kappa$-c.c. poset of size $\leq \kappa$. Assume $\diamondsuit_S$ holds in $V$. Let $G$ be $P$-generic over $V$. Then $V[G] \models \diamondsuit_S$
[Why? Using $|P| = \kappa$, nice $P$-names for subsets of $\kappa$ (union of sets of form $W \times \{\alpha\}$ where $\alpha < \kappa$ and $W$ is an antichain in $P$) can be thought of as subsets of $\kappa$ by identifying $P \times \kappa$ with $\kappa$. If $A \subseteq \kappa$ codes such a nice name, then let $n(A)$ denote the corresponding $P$-name. Fix a $\diamondsuit_S$ witnessing sequence $\langle A_{\alpha} : \alpha \in S \rangle$ in $V$. In $V[G]$, define $\langle B_{\alpha} : \alpha \in S \rangle$ by $B_{\alpha} = \text{eval}_G(n(A_{\alpha})) \cap \alpha$ if $A_{\alpha}$ codes a nice name for a subset of $\kappa$, otherwise $B_{\alpha} = 0$. Fix a code $A$ for a nice $P$-name $n(A)$ for a subset of $\kappa$. Then for each $\alpha < \kappa$, $A \cap \alpha$ also codes a nice name. Moreover, using $\kappa$-ccness of $P$, the set $\{\alpha < \kappa : \text{eval}_G(n(A \cap \alpha)) \cap \alpha = \text{eval}_G(n(A)) \cap \alpha \}$ contain a club. Since $A \cap \alpha = A_{\alpha}$ on a stationary subset of $S$, $B_{\alpha} = \text{eval}_G(n(A)) \cap \alpha$ on this stationary subset as well. Hence $\langle B_{\alpha} : \alpha \in S \rangle$ witnesses $\diamondsuit_S$ in $V[G]$.]


Is it possible to simplify $\frac{2^{2x-1} - 2^{x-1}}{2^{2x-1}}$?

Question: Is it possible to simplify this expression?
$\frac{2^{2x-1} - 2^{x-1}}{2^{2x-1}}$
Comment: Try http://www.wolframalpha.com/input/?i=simplify+%5Cfrac%7B2%5E%7B2x-1%7D+-+2%5E%7Bx-1%7D%7D%7B2%5E%7B2x-1%7D%7D
Comment: Remember if you ever have a "is it possible" question, try wolfram alpha first!
Answer: $$\begin{align}\frac{2^{2x-1} - 2^{x-1}}{2^{2x-1}}
&=\frac{2^{2x-1}}{2^{2x-1}}-\frac{2^{x-1}}{2^{2x-1}}
\\
&=1-2^{(x-1)-(2x-1)}
\\
&=1-2^{-x}
\end{align}$$
Answer: Yeah you can do this: $$\frac{ 2^{x-1} \Bigl[ 2^{x}-1\Bigr]}{2^{2x-1}} = \frac{2^{x}-1}{2^{x}}$$
Comment: or $1-2^{-x}$ .


prove or disprove: $((-2)^{(p-1)/2})^{p^{k-1}}\equiv \pm 1\bmod p^k\Leftrightarrow (-2)^{(p-1)/2} \equiv \pm 1 \bmod p$

Question:
Prove or disprove: if $p$ is an odd prime number and $k\ge 1$, then $((-2)^{(p-1)/2})^{p^{k-1}}\equiv 1\bmod p^k\Leftrightarrow (-2)^{(p-1)/2} \equiv 1\bmod p$  and $((-2)^{(p-1)/2})^{p^{k-1}}\equiv -1\bmod p^k\Leftrightarrow (-2)^{(p-1)/2} \equiv -1\bmod p$.

The reverse implication in both cases seems to hold, but I'm not sure how to prove the forward implication in either case. For the reverse implication for the first case, if $(-2)^{(p-1)/2}\equiv \pm 1\bmod p,$ then $(-2)^{(p-1)/2})^{p^{k-1}} = (xp \pm 1)^{p^{k-1}}$ for some $x\in \mathbb{Z}$, and by the Binomial theorem it is easy to see that this expression is equivalent to $\pm 1$ modulo $p^k$.
Answer: We assume the following:
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv \pm 1 \pmod {p^k}$$
It now rests us to show that (where $\pm$ should be chosen the same in the two equations):
$$(-2)^{(p-1)/2} \equiv \pm 1 \pmod p$$
We will take the first equation modulo $p$ (we may since $p^k \equiv 0 \pmod p$) and get:
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv \pm 1 \pmod {p}$$
Since $p$ is an odd prime number we know that:
$$(-2)^{(p-1)/2} \in \{ -1, +1 \} \pmod p$$
Also, since $p$ is odd we get that $p^{k-1}$ is odd, thus:
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv + 1 \pmod {p} \implies (-2)^{(p-1)/2} \equiv +1 \pmod{p}$$
and
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv - 1 \pmod {p} \implies (-2)^{(p-1)/2} \equiv -1 \pmod{p}$$
Exactly what we wanted to show.
Answer: We suppose $k\ge 1$.
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv \pm 1 \pmod {p^k} \implies ((-2)^{(p-1)/2})^{p^{k-1}} \equiv \pm 1 \pmod {p}.$$
By Fermat little Theorem:
$$((-2)^{(p-1)/2})^{p^{k-1}} \equiv  ((-2)^{(p-1)/2})^{p^{k-2}}\equiv\cdot\cdot\cdot  \equiv(-2)^{(p-1)/2}\pmod {p}.$$
Then $$((-2)^{(p-1)/2})^{p^{k-1}} \equiv \pm 1 \pmod {p^k} \implies (-2)^{(p-1)/2} \equiv \pm 1 \pmod {p}.$$
Comment: @Mike that should be in my original post.
Comment: Yes I see that now


Class variable undefined inside function

Question: Just trying to learn Angular 2+ (8 specifically) and for the life of me, I can't understand why a class variable is 'undefined' inside a class function, but accessible if I write the function with ES6 style.
I tried setting in constructor instead, but that doesn't make sense.
export class GameControlComponent implements OnInit {

    myVar;
    counter = 0;

    constructor() {}  ngOnInit() {}

    handleClickStart() {

        this.myVar = setInterval(this.myFunc, 1500);
    }

    myFunc() {
        this.counter++;
        console.log(this.counter);
    }
}

Once 'handleClickStart' is called, this outputs NaN every 1.5 seconds. Why????
I would have expected 1 2 3....
Implementing handleClickStart this way gives me the desired results:
handleClickStart() {
    this.myVar = setInterval(() => {
      console.log(this.counter + 1);
      this.counter++;
    }, 1500);
}

But still can't figure out why it didn't work out the first way.
Comment: Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript)
Answer: This behaviour has to do with scopes, arrow functions,this and how Javascript functions/objects work.
Functions in JavaScript run in a specific context and using this accesses the current context. this.counter in the sample code is not available/defined inside setInterval() function, so we get undefined.
Now, in Arrow functions, things are special/different. Arrow Functions always lexically bind the context (Lexical Scoping means that it uses this from the code that contains the Arrow Function.) and therefore this will refer to the originating context, ie the class.
A simpler example might make it more clear.
const obj = {
  myVar: 'foo',
  myFunc: function() {
    console.log('Actual Variable value: ',this.myVar)

    setTimeout(() => {
      console.log('Set timeout using Arrow function: ',this.myVar)
    }, 1000);
    setTimeout(function () {
      console.log('Set timeout using Normal function: ',this.myVar)
    }, 1000);
  }
}
obj.myFunc();

Output
Actual Variable value: foo
Set timeout using Arrow function:  foo
Set timeout using Normal function:  undefined

Read more

Arrow functions
this keyword


Como impedir refresh após submit na mesma página?

Question: Tenho um formulário básico HTML que envia os dados através do método POST para a mesma página, ou seja, faço o submit para a própria página.
Como nessa página tem ações em Javascript, após esse submit a página reseta, acontecendo um refresh, resetando checkbox por exemplo e eu gostaria que as escolhas que a pessoa realizou ficassem mantidas.
É possível impedir esse refresh após clicar no botão submit do formulário?
Comment: a página vai sempre fazer refresh se o action do seu form está pra essa página. crie uma funcão JS para tratar do submit dos dados do form.
Answer: O caminho lógico e mais fácil seria efetuar essa requisição post com Ajax! O que manteria a seleção dos campos conforme o usuário optou.
Mas se está submetendo para a mesma página, você pode acessar os valores através da variável $_POST do php.
exemplo teste.php:
 <form action='teste.php' method='POST'>
   <input type='text' name='nome' value="<?= (!empty($_POST['nome']))?
   $_POST['nome'] : '' ?>">
 </form>

Ou seja se houver valor na variavel NOME enviada por POST adicione no atributo value do campo de texto chamado nome caso contrário adicione vazio.
Conteúdo adicional : PHP POST
Comment: Compreendi. Vou trabalhar em cima disso e verei se deu certo. Obrigado pela dica e atenção.
Answer: Não, não é possível impedir esse refresh fazendo o submit do form para a própria página.
Você deve efectuar essa requisiçãi via ajax - guardava na Base de Dados mas não retornava nada para o html.
Assim conseguiria inserir os dados e manter os dados.
Alternativa
Se o seu objectivo é manter os dados, você pode verificar se $_POST contém dados (após fazer o submit irá conter). Se conter, pode escrever esses dados nos values dos insputs do form. Desta forma, faria o refresh no entanto iria preencher os campos com os valores inseridos antes do submit e que foram enviados.
Comment: Entendi. Já que não pode, trabalharei em cima dessas dicas para chegar no que pretendo. Agradeço sua atenção, obrigado.
Answer: Primeiro: - Impedir o submit.
Segundo: - Enviar o submit via ajax.
Terceiro: Dependendo da resposta do ajax, sair, mostrar msg, etc.
EXEMPLO:
Para impedir o submit:
Usando jQuery:

jQuery(function($){
  $("#formulario_tal").on("submit",function(e){
    e.preventDefault(); // impedir o evento submit

    // aqui entra o codigo ajax. pesquisar no google "jquery ajax" para mais detalhes

  });
});

Um exemplo prático:
https://codepen.io/fixonweb/pen/jOOPwPL
Answer: Basta inserir no codigo do submit o return false.
ex:
<input type="submit" onclick="calcular();return false" />


Spaces with fundamental group isomorphic to a free group with $(n-1)$ generators

Question: I'm trying to solve the following question:
Let $X=A\cup B$ be an open cover of $X$ where $A,B$ are simply connected and $A\cap B$ consists of $n \ge 2$ path connected components.
I want to show that $\pi_1(X)$ is isomorphic to a free group with $(n-1)$ generators.
I tried to start with the case for $n=2$ But I failed..(someone even asked it here but the answer wasen't detailed enugth and I didn't understand it).
I want to solve it with rudimentary tools (without groupoids).
Comment: But $X$ is path connected, since both $A$ and $B$ are simply connected and $A\cup B$ is not empty. The fundamental group depends on the choice of base point but this choice makes no difference as long as the space $X$ is path-connected. @freakish
Comment: Munkres' book "Topology" gives an indication in Section 63.1 of the ingredients needed for a covering space argument.  But I tend to agree that group arguments are appropriate for path connected spaces with a single base point, and so are more  rudimentary than using the algebra of groupoids.
Comment: The concept of the fundamental group doesn't really make sense for non-path connected spaces. $\pi_1(X)$ with respect to what point?
Comment: Do you know Seifert-van Kampen?
Comment: @DanRobertson Yes, but van Kampen's theorem applies when $A\cap B$ is path connected, which is not the case in my question.
Comment: Why do you want to solve it without groupoids?  The old saying is: horses for courses.
Answer: I'm going to sketch roughly how I would try to prove this.
So we know we don't have to think about these cases, observe that we must have $A\not\subset B$ nonempty and $B\not\subset A$ nonempty.
Let the connected components of $A\cap B$ be $C_1,\,C_2,\dots,C_n.$ Now pick a point $x\in A-B\subset X$ and we shall try to compute $\pi_1(X,x).$ As $A$ is simply connected, any path that does not meet $B-A$ must be path-homotopic to the point. Now pick a point $y\in B-A$ and pick points $z_i\in C_i\subset A\cap B$. Because $A,B$ are simply connected there are unique (up to path homotopy) paths $\gamma_i : x\rightsquigarrow z_i \rightsquigarrow y$
The object is then to show that every loop at $x$ in $X$ must be homotopic to a composition $\gamma_{i_1}\cdot\bar\gamma_{j_1}\cdots\gamma_{i_k}\cdot\bar\gamma_{j_k}.$ It would be nice if this was the same as the path going from $A$ to $C_{i_1}$ to $C_{j_1}$ and so on but that's sadly not the case. I'm not really sure how I'd prove this step.
The second part (which should perhaps come first) is to show that no $\gamma_i$ can be homotopic to $\gamma_j$ for $i\ne j.$
The third part is to then observe that any path homotopic to a decomposition as above can also be decomposed uniquely as a composition of loops of the form $\delta_i =\gamma_i\cdot\bar\gamma_n$ for $i=1,\dots,n-1,$ that if $\delta_i$ is homotopic to $\delta_j$ then $i=j$ and that therefore all paths in $x_i$ are homotopic to a unique path generated by $\delta_i$ and so the fundamental group of $X$ is the free group on generators $\delta_1,\delta_2,\dots,\delta_{n-1}.$
I'm afraid that's a bit messy and incomplete so sorry about that.


filtering a DATETIMEOFFSET column to a local date range

Question: If I have a DATETIMEOFFSET column in a SQL Server table, what's the right way to filter results to a range of local (not UTC) dates?  By "local" I mean date boundaries are relative to the timezone of each stored value (which may differ between rows), not relative to a single fixed local timezone.
I assume it's not this, because the DATE literals will be assumed to be UTC. Correct?
WHERE EventTime >= '20140401' AND EventTime < '20140501'

So is this the right solution?
WHERE CAST (EventTime AS DATE) >= '20140401' AND CAST (EventTime AS DATE) < '20140501'

Or does the CAST function prevent efficient use of indexes on the EventTime column?  If so, what's the right way to "align" date literals on the same timezone as the DATETIMEOFFSET column?
Answer: Yes, you can cast the EventTime column to a date type, which will strip away all time and offset information, leaving you with the local date.  But as you pointed out, there will be a performance cost if you cast the column at time of query.
You should consider creating a separate column of type date for this purpose.  You can do this in a view, or you can simply create a computed column.  You can then create an index on this column.  For example:
CREATE TABLE Events (
    EventID int NOT NULL,
    EventTime datetimeoffset NOT NULL,
    LocalDate AS (CONVERT(date, EventTime)),  -- this is the computed column
    CONSTRAINT PK_Events PRIMARY KEY CLUSTERED (EventID)
)
CREATE NONCLUSTERED INDEX IX_Events_LocalDate ON Events (
     LocalDate
)

You can then query by the LocalDate field and it will have the info you need and the appropriate index.


sort mat-table according to the selected value of mat-select

Question: this TypeError: Cannot set property 'active' of undefined keeps occurring in the console and the sorting does not work at all. please help me to figure out what should I do to sort the table according to the selected value of mat-select.
.component.ts file
import {Component, OnInit, ViewChild} from '@angular/core';
import { FormControl } from '@angular/forms';
import {MatTableDataSource} from '@angular/material/table';
import {PointTableService} from "./point-table.service";
import {MatSort, Sort} from "@angular/material/sort";

@Component({
  selector: 'app-point-table',
  templateUrl: './point-table.component.html',
  styleUrls: ['./point-table.component.css']
})
export class PointTableComponent implements OnInit {

  displayedColumns: string[] = ['club', 'points', 'wins', 'looses', 'draws', 'goals_scored', 'goals_received'];
  dataSource: MatTableDataSource<PointTable>
  disableSelect = new FormControl(false);

  constructor(private tableService: PointTableService ) { }

  @ViewChild(MatSort) sort: MatSort;

  selectedColumn = 'points';

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource<PointTable>();

    this.tableService.getClubs().subscribe((data) => {
      this.dataSource = new MatTableDataSource<PointTable>(data['response']);
    })

    this.dataSource.sort = this.sort;
    this.changeSortedColumn();
  }

  changeSortedColumn() {
    const sortState: Sort = {active: this.selectedColumn, direction: 'asc'};
    this.sort.active = sortState.active;
    this.sort.direction = sortState.direction;
    this.sort.sortChange.emit(sortState);
  }

}

export interface PointTable {
  clubName: string;
  points: number;
  wins: number;
  defeats: number;
  draws: number;
  goalsScored: number;
  goalsReceived: number;
}

.component.html

Points Table

<mat-form-field appearance="fill" class="sort-select">
    <mat-label>Sort by</mat-label>
    <mat-select [(value)]="selectedColumn" (selectionChange)="changeSortedColumn()">
      <mat-option value="points" id="points">Points</mat-option>
      <mat-option value="wins" id="wins">Wins</mat-option>
      <mat-option value="goalsScored" id="goalsScored">Goals Scored</mat-option>
    </mat-select>
</mat-form-field>

    <ng-container matColumnDef="club">
         CLUB
         {{element.clubName}}
    </ng-container>

    <ng-container matColumnDef="points">
         P
         {{element.points}}
    </ng-container>

    <ng-container matColumnDef="wins">
         W
         {{element.wins}}
    </ng-container>

    <ng-container matColumnDef="looses">
         L
         {{element.defeats}}
    </ng-container>

    <ng-container matColumnDef="draws">
         D
         {{element.draws}}
    </ng-container>

    <ng-container matColumnDef="goals_scored">
         GS
         {{element.goalsScored}}
    </ng-container>

    <ng-container matColumnDef="goals_received">
         GR
         {{element.goalsReceived}}
    </ng-container>

reference code for my program https://stackblitz.com/edit/angular-mat-sort-default-hwa9q2?file=app%2Ftable-sorting-example.ts
Comment: Move changeSortedColumn method inside subscribe block
Answer: async functions work without waiting. So if you want to assign something with async request you should do it inside subscribe.
ngOnInit(): void {
    this.dataSource = new MatTableDataSource<PointTable>();

    this.tableService.getClubs().subscribe((data) => {
      this.dataSource = new MatTableDataSource<PointTable>(data['response']);
       this.dataSource.sort = this.sort;
       this.changeSortedColumn();
    })
  }


Views field: how to add html 'title' attribute to link

Question: In views fields like [Content: Title] and [Content: Taxonomy] there is the possibility to have the content displayed as link. Is it also possible to equip these link with a html 'title' attribute?
Alternatively, is it possible to equip all links on a drupal site with html 'title' attributes?
Answer: This will add title attributes to most links, depends with some modules though.
<code>/**
 * Add title attribute to any link that doesnt have a title already
 */
function YOURTHEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}
</code>
Answer: There are multiple ways your issue can be addressed. Please find answers below that will resolve some of your questions.

All Menu Links created using Drupal Core Menu Module i.e using User Interface

You can use Menu Attributes module to add title attribute.

Links exposed in custom module

You can use l function to create a link with attributes.

Views fields

You can use rewrite results option to rewrite content and add html as you like with attributes to a tag.
UPDATED:
Uncheck the setting in title field settings as shown below.
Comment: Thanks for your answers! I am however not using any menus on my site at all. I managed to achieve a rewrite for the Title field:

` [title]`
(reads funny doesn't it? ;) But when I rewrite ` [field_taxonomy]`, the title gives the full URL...
Comment: I meant, the title popup shows the full html tag: `foo`
Comment: You need to uncheck link setting in views title field settings... See my updated answer ! For taxonomy term you just need to print the term name with out any formatting.. Uncheck "Link this field to its term page"
Comment: I got it working for the title field, as I described above. Unchecking "Link this field to its term page" would remove the link. With field_taxonomy, I got it to work in plain text format, with the rewrite mentioned above and 'output field as link', link path `/cat/[field_taxonomy]` and path set absolute. Phew.


Wordpress to Drupal: Wordpress Migrate

Question: I have a fresh install Drupal 7.34 on WAMP. Token and Pathauto are already installed. The Theme, if it is relevant, is Stanford Open Framework.
I have Wordpress_migrate, migrate, migrate_extras intalled and then included features, media and media_youtube as low level diagnostic.
I follow through the instructions to use wordpress_migrate that seem self-explanatory and get this string of errors
<code>Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
No migration found with machine name WordPressAuthor
No migration found with machine name WordPressBlogEntry
No migration found with machine name WordPressPage
No migration found with machine name WordPressAttachment
No migration found with machine name WordPressComment
Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
</code>
The migration does seem to complete but the list of imports under the blog name is  0  0 0 throughout.
I can see that a partial XML file has been transferred from Wordpress.
I have also tried exporting the Xml file from Wordpress and uploading that. I get the same errors.
The string of red errors suggests the entire module is borked. Is that correct? In which case, what is the best strategy to migrate a Wordpress blog to Drupal.
If the module is not borked then any suggestions what I might have missed or misunderstood?
I clearly do not understand the underlying problem, so please do not bite my head off.  A clear orientation will be received with sincere gratitude though.
Comment: Looking at the issue queue for Wordpress Migrate, I found an issue exactly like yours: https://www.drupal.org/node/2151761 they suggest using the dev version of the module (from 2015) instead of the stable one (from 2012).
Comment: I've used the module a month or two ago to import 60+ posts to an already existing Drupal 7 site. The import went without any problems. So the module's not borked. Those don't look like 'errors' per se, rather notifications that some things are deprecated.
Answer: The module is pretty borked.
Beebee is right.  When you install using Drush, you will get the latest non-dev Wordpress_migrate and the latest Migrate - clash!  You also get no warning about needing migrate_extras features and media.
So the trick is install the latest Migrate with Drush but as of today's date, download the latest dev version of Wordpress_Migrate.
I was able to download my blog from its url. It did hang and I exited expecting a mess but all the content is there.  As I am trying to sort out content, that suits me.
So the principles --
--download migrate, migrate_extras, media, features and ctools
-- manually download the dev version of wordpress_migrate
If your blog is large, be patient. If the download borks, then try to increase the execution time or try exporting your blog to a file from inside Wordpress, use the Wordpress file splitter and try uploading by file.
Thanks Beebee.
Comment: You can download dev version of modules using drush. The command is a bit more tricky but if you want to download 2.x dev version of migrate for example, then you do: `drush dl migrate-7.x-2.x-dev`

Wordpress to Drupal: Wordpress Migrate


How to dynamically change values in drop down using other drop down change using angular?

Question: I have two drop downs. Initially both has values like "First","Second","Third",...
When 1st dropdown has value "First" the second should not offer a value "First" that is second should have other than what is selected from 1st one. I want to do this using angularjs. Values in 2nd dropdown should be changed dynamically.
<select class="form-control" ng-model="Data.firstType">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

<select class="form-control" ng-model="Data.SecondType">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

Can anyone help on this?
Thanks in advance.
Comment: Why don't you accept the solution ?
Answer: If you're items in the drop downs are static you can do this fiddle
ng-if="Data.FirstType !== First"

If they are dynamic then you can filter the items in the second list based upon the item selected in the first drop down
Here is a fiddle to dynamically filter the second list if the lists are being populated dynamically.
function MyCtrl($scope){
    $scope.Data = {};
    $scope.items = [{id:1, name:'First'}, {id:2, name:'Second'}, {id:3, name:'Third'}];
    $scope.exclude = function(x){
        return x !== $scope.Data.firstType;
    }
}

Answer: Just use a $watch:
$scope.$watch('Data.firstType', function(val) {
    //Get index of type in Data.yourArrayData
    var idx = $scope.Data.yourArrayData.indexOf(val);
    $scope.Data.yourArrayData.splice(idx, 1);
});

This assumes you are binding your second select to yourArrayData using an ng-repeat.  I haven't tested this code, but it should be what you need.
Comment: I would avoid using a watch within your controller, and instead use ng-change to call back into the controller. Explanation: http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html


Understanding the linear mixed effects model equation and fitting a random effects model with weights in R

Question: Could anybody please shed some light on me? I have $N$ individuals, divided into $K$ groups with $N>K$. Some groups have 1 individuals only, some other groups have more individuals.
Each individual has 4 features (4 variables): $F_0, F_1, F_2,$ and $F_3$, where $F_0$ is simply the group indicator. Therefore the data matrix is of size $N \times 4$. There is also a weight vector $w$ of length $N$, which gives the weights for each of the $N$ individuals in the regression.
May I ask if the following model is a random-intercept model?

There is a common beta for all N individuals.
Each group has a different within group regression line (same slope but different intercepts).
The regression line within each group crosses the "cloud" consisting of the group members. And the individual residuals scatter around the regression line, within each group.

This sounds like a "random-intercept" model to me. However, how do I explicitly write out the equation?
$$ {\boldsymbol y} = {\bf X} \beta + {\bf Z} b + \varepsilon $$
More specifically, with the three feature variables $F_1, F_2$ and $F_3$ and the group indicator variable $F_0$. I am having difficulty writing out $X$ and $Z$ explicitly. Moreover, my $F_2$ is a factor variable.
Could anybody please show me how the $X$ and $Z$ matrices look like explicitly? And what do the "$b$"'s represent here?
And how do I set up the weights in LME in R? If I would like to have "group"-weights and "individual"-weights, how shall I do it?
Thank you!
[ps1 @ Macro]
Thanks a lot Macro for your very comprehensive answer. I am continuing digesting your writings and I will consult with you  and your expertise with more questions. My first question is: you think the condition 2 and condition 3 conflict each other.
I don't understand why. Here is my thinking: even though for a certain group, the overall beta is a very crappy one for that group.
By adjusting the intercept for that group, I at least still can get the regression line passing the cloud, am I right?
More specifically, in a random intercept model (all group sharing the same beta), will the following situation arise?
All data points in a group reside on one side of the regression line of that group?

In a random intercept model, for each group, which point does the regression line pass thru? In the general OLS, we knew that it's the
point (xbar, ybar) that is passed thru by the regression line.
But for each group in a random intercept model, which point is that "central" point?

Moreover, in R, what's a convenient way to visualize what's happening within a certain group in a mixed model?
Thanks a lot for your help!
Comment: Luna, I've added some comments related to your modified question below my answer. But, I think the questions you've added (other than the clarification of why condition 2 & 3 are in conflict) are sufficiently broad as to warrant the creation of a new question, since my answers in the edit below are rather off-the-cuff. BTW, if you've found my answer helpful please consider upvoting and/or eventually accepting it! :)
Comment: Hi Macro, thanks so much for your help! I have upvoted your answer and yes, I am considering eventually accepting it... Thanks again for your help! And I have followed your suggestion and started a new discussion ...
Answer: I'll answer each of your questions one at a time.
May I ask if the following model is a random-intercept model?
1. There is a common beta for all N individuals.
2. Each group has a different within group regression line (same slope but different intercepts).
3. The regression line within each group crosses the "cloud" consisting of the group members. And the individual residuals scatter around the regression line, within each group.
Conditions (2) and (3) are in conflict with each other. If each group has the same slope but different intercepts then the within group regression line will not
pass through the cloud of group observations unless the truth is that every group has the exact same slope. You would need both a random intercept and a random slope in every predictor to guarantee that condition (3) is satisfied.
However, how do I explicitly write out the equation?
The familiar formula for the random effects model, as you pointed out, is
$$ {\bf Y}_i = {\bf X}_i {\boldsymbol \beta} + {\bf Z}_{i} {\bf b}_i + {\boldsymbol \varepsilon}_{i} $$
Where $${\bf Y}_i = \left( \begin{array}{c} y_{i1} \\ y_{i2} \\ \vdots \\ y_{i n_{i}} \end{array} \right) $$ is the vector of responses in group $i$, $n_{i}$ is the number of observations in group $i$ $(n_i$ can be $1$ for some groups but not all groups $)$.
$${\bf X}_i = \left( \begin{array}{ccccc}
1 & x_{i11} & x_{i12} & \cdots & x_{i1p} \\
1 & x_{i21} & x_{i22} & \cdots & x_{i2p} \\
\vdots & \vdots & \vdots & \vdots & \vdots \\
1 & x_{i n_{i} 1} & x_{i n_{i} 2} & \cdots & x_{i n_{i} p} \\
\end{array} \right) $$
is the matrix of the $p$ predictor variables for each observation in group $i$ with corresponding $p$-length fixed effects regression coefficient vector ${\boldsymbol \beta}$.   $${\bf b}_i = \left( \begin{array}{c} b_{i0} \\ b_{i1} \\ \vdots \\ b_{im} \end{array} \right) $$ is the $m$ length vector the vector of random effects and $${\bf Z}_i = \left( \begin{array}{cccc}
z_{i11} & z_{i12} & \cdots & z_{i1m} \\
z_{i21} & z_{i22} & \cdots & z_{i2m} \\
\vdots & \vdots & \vdots & \vdots \\
z_{in_{i} 1} & z_{i n_{i} 2} & \cdots & z_{i n_{i} m} \\
\end{array} \right) $$  be the random effects design matrix for group $i$ and
$$ {\boldsymbol \varepsilon}_i = \left( \begin{array}{c} \varepsilon_{i1} \\ \varepsilon_{i2} \\ \vdots \\ \varepsilon_{i n_i} \end{array} \right) $$ is the vector of errors. So, for example if you just had a random intercept and a random slope in the first predictor, then
$${\bf b}_i = \left( \begin{array}{c} b_{i0} \\ b_{i1} \end{array} \right),
{\bf Z}_i = \left( \begin{array}{cc}
1 & x_{i11} \\
1 & x_{i21} \\
\vdots & \vdots \\
1 & x_{i n_{i} 2} \\
\end{array} \right) $$
where $b_{i0}$ is the random intercept and $b_{i1}$ is the random slope. If you only had a random intercept and nothing else then ${\bf b}_i$ would be a scalar and ${\bf Z}_{i}$ would just be a vector of $1$s.
In your particular example, you have a categorical predictor (say with, $k$ levels), which, for modeling, is effectively like having $k-1$ dummy variables which are $1$ if variable takes on that value and $0$ otherwise. So, your ${\bf X}_{i}$ matrix will have $k+2$ columns - one column of $1$s, two columns with the values of the quantitative predictors, and $k-1$ columns with that are $0/1$ indicators of which level the categorical predictor takes. If you are going to include random slopes in every predictor, then ${\bf Z}_{i}$ will be exactly the same as ${\bf X}_{i}$. As mentioned above, if you only want a random intercept in the model then ${\bf Z}_{i}$ is just a column of $1$s.
how do I set up the weights in LME in R?
This depends on what you mean by "weights". Usually this means that certain observations are weighted (e.g. inverse-probability weights to correct for unequal probability sampling) and the criterion function that is being optimized to produce your estimates (probably the likelihood function in this case) is a weighted. For example, if the groups were sampled with unequal probability the function
$$ {\bf L} = \sum_{i=1}^{K} w_i L_i $$
where $L_i$ is the group $i$ log-likelihood may be optimized instead of the the unweighted sum. In terms of point estimation, this is effectively the same as as replicating group $i$ in the data set a number of times equal to $w_i$, which can be accomplished by doing exactly that - expand the data set based on the weights and fit the model to this expanded data set. I'm not sure if there is functionality in lme to do this automatically, so you may need to do this yourself.
Regarding weighting within a group (i.e. at the individual level), I do not recommend this in the context of random effects modeling. To see why, consider the fact that by weighting within a cluster, you're effectively creating exact copies of individuals within the cluster. Therefore, there will be pockets within the group that are perfectly correlated with each other, so the estimates of the random effect variances will be biased up, since the model will think that members of a group are more correlated than they are.
Comments related to the Edit:

The only way adding a random intercept would make it so that each group's regression line passes through the "cloud" is if each group's "cloud" was just a vertical shift of each other's group - that is, the slopes are exactly the same but the intercepts are different. More generally, the linear least squares line requires both a slope and an intercept. If you don't let the slopes vary,the random intercept will go wherever is "best" (i.e. maximizes the posterior mode, if you're trying to estimate random effects),so I don't think it could possibly appear all the way on one side or another of the "cloud".
The central point within each group would presumably be the sample means, within the group, although this would require some more thought, as would the comments made in (1), since we aren't fitting this model by least squares (although it is closely related to least squares, since it involves the Gaussian likelihood).
The only way I can see to visualize this is to plot the points for a given group, along with the fitted line within the group, the same way you would with ordinary regression. You can extract posterior estimates of the random effects using the ranef function with the argument being the lmer model fit and you can extract the fixed effects in the usual way.


Unity - different phones sizes

Question: I am using unity for develope to my android phone. I am trying to develope a 2D game. When I put new image(sprite) in my game i can see it fully in unity but when I uploaded the game to my phone, parts of the image are missing from the sides. How can I fit the images sizes on all phones?
I saw the answer for this question but for eclipes java and not unity C#.
Comment: Some more information would be helpful : is the unity game 2d? And what script / game objects are you currently using.
Comment: Yes. the game is 2d. I am using sprites.
Answer: In Unity 4.6 version, you can make you UI size adaptive:

Select the canvas where your UI resides
In the inspector, add a component called Canvas Scaler (in 4.6 beta, this is called Reference Resolution component)
Set the reference resolution to the native (or original size) of your sprite/background image
Make sure you choose the right "Screen Match Mode" if the phone's resolution is different.

That is it.
Now no matter how you resize the game view, your sprite can make best fit with it: either fit with the width or height, depending on the phone orientations and aspect ratios. In either case, however, you are guaranteed to see full image, rather than portion of it in your case. See the gif below:
Answer: Screen.width and Screen.height are the only unity specific methods you need.
Pass in height, width, and position information to your objects based on your screen size.
The harder part learning the gui.
If you need more help with syntax, take a look at unit's gui documentation and tutorials.
Answer: Use Screen.width and Screen.height to get the screen size of current device, then check your target phones screen aspect ratio:
For Window Phone, it's 5:3 and 16:9
iPhone: iPhone 3, 4 is 3:2, iPhone 5, 6, 6+ is 16:9
Android phone has many types.
After you get the that, make sure your sprites are designed in exact ratio for your target phones, and it'll be matched with screen.

Unity - different phones sizes


R studio blank white screen

Question: I am running an MCMC analysis that requires 20 million simulations and I left MCMC to run for a few days only to come back to an RStudio page that was completely blank and nothing is operational. Are there any fixes so that I don't have to restart and lose what I was attempting with my mcmc? Or a way I can save my data without viewing it? Thanks
Answer: That is the "RStudio White Screen of Death". It seems to be irreversible at that stage. I tried waiting forever for it, saving the session, to no avail. The solution seems to be buying more RAM.
https://community.rstudio.com/t/rstudio-white-screen-of-death/132309
I prepared for it by saving certain processed data as .RData file before export out in excel (required by my work) or doing other steps that take a lot of memory/run for a long time.

R studio blank white screen


Magento File Permissions + Strange errors

Question: I've just done a fresh install of Magento but I'm getting some bizarre errors:
For example within the admin area I go into System - Import / Export - Profiles ; then I just get
There has been an error processing your request
Exception printing is disabled by default for security reasons.
Error log record number: 682005239838
I'm getting this pretty much everywhere... So I thought I'd upgrade Magento so went into Connect to do an upgrade: but when trying this I'm get also getting insufficient permission errors.
So I'm probably assuming that all of this is related.
Can anybody please advise, on what chmod permission I should set and on which folders? and Will this solve all my dramas?
Best Regards
Shane
Comment: You should check error log files to see what are the actual errors
Comment: I've managed to sort the general error messages out but still Connect is playing up!
Answer: Sorted!
php safe mode was switched on by accident! Doh!
Answer: The file permissions should be:
MAGETO_ROOT/app/etc - writable
MAGETO_ROOT/media/  - writable
MAGETO_ROOT/var/ - writable
The rest folders and wiles should have regular permissions.
Now, about the error you have got. You should try open a file MAGETO_ROOT/var/reports/report/682005239838 and you will see more detailed where your problem is.
If you want to see your error reports without going to FTP -- just rename file MAGETO_ROOT/errors/local.xml.sample to MAGETO_ROOT/errors/local.xml


How to physically strum up on a guitar without pick? Trying to do the song in the linked video

Question: I'm trying to play the song here in this video

I don't really have a problem strumming down, I've been using the fleshy part of my right thumb to strum down, I don't know if it's the correct way to do it but it's been producing the sound I've been looking for so far. There's much less surface area on my thumb to hit the string on the way back up though and I don't have a nail, so I'm not really sure what to do. If someone could explain to me how to position my hand in a way that makes sense it would be much appreciated.
Answer: Based on the fact that you want to use your thumb for the downstroke but not the upstroke the most logical thing to do is use your index finger for the upstroke. Since you like the sound of the fleshy part of your thumb you probably want to get that sound on the upstroke as well. The index finger upstroke will give you that.
You can use the strumming pattern he plays using this method.
There's no reason you have to emulate exactly what is done in the video but you might be curious about what he does. He doesn't specify what fingers he is using for strumming. However it looks to me like he is strumming with a phantom pick, that is, his thumb and index finger are basically together as if he were holding a pick. He uses the nail side of his index finger for the downstroke and the nail side of his thumb for the upstroke. You will notice he gets a bright sound because of the nail combining with the finger for the strum. Your method will produce a warmer darker sound.


Python Checking Win State

Question: I'm writing a basic noughts and crosses game in Python 3.6, I want the output to print only True or False, however the code I've come up with to check the win state:
def check_the_lot(board):
    win = check_win_mid_hoz(board)
    win = check_win_bttm_hoz(board)
    win = check_win_top_hoz(board)
    print (win)

Will just overwrite the previous checks and just print only the last one? How would I fix this? I cna't figure out how to print only true or only false, and not multiple answers all at once?
Comment: Btw: you do not need any ; in python!
Comment: I offered you an answer easily scalable as it would only require adding the extra functions (verticals and diagonals) to the list.
Answer: win = check_win_mid_hoz(board) or check_win_bttm_hoz(board) or check_win_top_hoz(board)

Comment: Thanks so much for the help, greatly apriciated!!
Comment: If the answer helped you, please accept my answer (click the check symbol under the vote button)
Answer: When all the functions have the same signature (parameters and outputs) using any(map()) is a nice solution.
def check(board):
    checks = [
        check_win_mid_hoz,
        check_win_bttm_hoz,
        check_win_top_hoz,
    ]
    return any(map(lambda x: x(board), checks))

We store the functions without being called in a list. map() executes the lambda function for every element of checks. This lambda function is calling the function with the boardparameter. any() checks if any of the elements evaluates to true.

Python Checking Win State


BNF FORM of odd numbers

Question: How to write Odd number in BNF form?
Comment: Next time please post what you've tried so far
Answer: You have to define the odd digits separately.
odd ::= "1","3","5","7","9"

Then define a group containing all digits
digit ::= odd, "2","4","6","8","0"

Finally, define odd numbers as any number of digits ending with an odd using recursion
number ::= number digit | digit
oddnumber ::= number odd | odd

BNF FORM of odd numbers


How to theme form?

Question: I created a form in custom module,
Something like:
<code> $form['form00'] = array(
      '#type' => 'textfield',
      '#title' => 'dummy',
    );
$form['form01'] = array(
      '#type' => 'textfield',
      '#title' => 'dummy1',
    );
</code>
Questions are:

How do I theme the form? like wrapping them into some div, giving a class or id, and setting CSS property (e.g. float: left), etc.?
Can I control it from AJAX ? If yes,how?
Comment: You should read about render arrays and theme templates in drupal 8.
Answer: Short story for or Q1: Wrap your form01 and form02 in a container:
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Container.php/class/Container/8.2.x
Then add your classes with the #attribute variable like here:
<code>'#attributes' => array(
    'class' => 'myclass',
  )
</code>
For Q2: It's a long story, read this: Ajax API on Drupal
Regards,
Rainer
Comment: for Q1. how do i define the CSS? once i define the class (or ID) ?
Comment: Create a css file with your styles and add it to the asset library of your module. Or attach the asset just to that form with the #attached library syntax.

How to theme form?


Contradiction in calculation of barycenter of points with random weight

Question: Defining the barycentre and finding its variance
I have a set of $N$ points at the locations $x_i$ which has weights $W_i$, $i=1,\ldots, N$ and want to find the barycenter (or center of gravity)
$$ B = {\sum_{i=1}^N W_i x_i\over \sum_{i=1}^N W_i}.$$
I want to find the variance of $B$.
I assume that $W_i$ are i.i.d. and positive with expected value $Ew_i=\mu$ and variance $Var[W_i]=E[w_i-\mu]^2=\sigma^2 $.
I also assume that $N$ is large, so $\sum_{i=1}^N w_i$ is well approximated by $N\mu$ (justified below).
When I do the calculations (see one example below) I end up with
$$ Var [B] = {\sigma^2 \over  N^2 \mu^2} \sum_{i=1}^N x_i^2. $$
The contradiction
As explained below, I think that the barycentre variance should be independent of a shift of all the $x_i$, that is $Var[B]$ should not change if all $x_i$ is shifted to $x_i+c$. But $\sum_{i=1}^N x_i^2$, and therefore my estimated $Var[B]$, will change a shift of the $x_i$.
Where is the error: In my calculations, or the expectation that the variance should be independent of shift in $x$.

One derivation of the variance
$$Var [B ]
= Var \left[{\sum_{i=1}^N W_i x_i \over \sum_{i=1}^N w_i}\right]
= {1\over N^2 \mu^2} \sum_{i=1}^N x_i^2 Var [W_i]
={\sigma^2\over N^2 \mu^2} \sum_{i=1}^N x_i^2$$
Here I used that $Var [\sum_i X_i] = \sum_i Var[ X_i]$ when the $X_i$ are independent, that $Var [cX]=c^2 Var[X]$, and that $Var[ w_i] =\sigma^2$.
I have also done the same in a more direct fashion, with the same result. It is kind of messy, so I have omitted it.
Why do I expect $Var [B]$ to be invariant to a shift of $x_i$?
The expected value of $B$ is the mean of the $x_i$:
$$E[B]=E\left[{\sum_{i=1}^N E[W_i] x_i\over \sum_{i=1}^N W_i}\right]
 ={\sum_{i=1}^N E[W_i] x_i\over N\mu}
={\mu\sum_{i=1}^N x_i\over N\mu}={\sum_{i=1}^N x_i\over N}=\bar x_i.$$
Moving all $x_i$ by $c$ will move every barycentre estimate by $c$:
$$ \tilde B = {\sum_{i=1}^N W_i (x_i+c)\over \sum_{i=1}^N W_i}
= {\sum_{i=1}^N W_i x_i\over \sum_{i=1}^N W_i} +{\sum_{i=1}^N W_i c\over \sum_{i=1}^N W_i}=
{\sum_{i=1}^N W_i x_i\over \sum_{i=1}^N W_i} +c=B+c.$$
The variance of $B$ is $Var[B]=E[(B-E[B])^2]$.
Moving all the $x_i$ by $c$ adds $c$ to $B$ and $E[B]$, so $B-E[B]$ and the variance should stay the same.
To check this I did a MATLAB simulation. In that simulation the estimated variances and barycentres (after i remove the displacement $c$) are identical.
Why do I think $\sum_{i=1}^N w_i =N\mu$ is a good approximation
Although the variance of $\sum_{i=1}^N w_i$ grow with $N$, this means that the standard deviation grow with $\sqrt N$.
And since the expected value grow with $N$, the relative spread will decrease.
It is the relative spread that is important for this case. Say that for one $N$ the expected value is 100 and the standard deviation is 1. Then, if $\sum_{i=1}^N w_i $ miss $N\mu$ with one standard deviation my estimate of $B$ is off by 1%.
If I increase N by a factor of a 100, the expected value will be 10 000 and the standard deviation will be 10.
So if $\sum_{i=1}^N w_i $ miss $N\mu$ with one standard deviation my estimate of $B$ is off by 0.1%.
Which mean that for large enough N the error will be negligible.

Context
I'm trying to repeat a derivation for the variance of an estimated arrival time from this paper. The barycentre is used to find the time when the echo from the seafloor is received for seabed mapping echo sounder.
As a simplified model, the part of the time sequence used in the barycentre calculation can be modelled as a sequence of independent, identically (Rayleigh) distributed, amplitude values. These amplitude values are equally spaced in time.
In this question the $W_i$ represent the amplitudes, the $x_i$ it the sample times and $B$ is the estimated time of arrival.
The paper states that it can be show analytically that
$$Var[B]= \frac{\Delta x^2}{12(N+1)}\left(\frac{4}{\pi}-1\right)N(N+2),$$
where $\Delta x$ is the distance between the $x_i$ ($x_i=x_0+i \Delta x$).
I have translated the equation to the notation used in this question.
No reference is given, although I am searching in related papers.
The middle factor in that equation $\left(4/\pi-1\right)$ is equal to the ratio the variance and the mean value squared of a Rayleigh distributed variable.
Answer: There are a couple of mistakes in your work here.
In your derivation you replace the denominator, $\sum W_i$ with its expectation value. You say you do this because it is a good approximation, but you are ignoring the variance it contributes. Would you still do that if the numerator was a constant? If so, you would have found that $V[\hat{X}]=0$.
The more important issue is that you are assuming the $W_i$ are independent. If we make the replacement,
$$F_i = {W_i\over\sum W_i}$$
then,
$$B = \sum x_i F_i$$
Because $\sum F_i = 1$, there are only $n-1$ independent random variables $F_i,\ \  i =2...n$. The other random variable is
$$F_1 = 1 - \sum_{i=2}^{n}F_i$$
Write $B$ in terms of the remaining independent random variables:
$$B = x_1\left(1 - \sum_{i=2}^{n}F_i\right)+\sum_{i=2}^n x_i F_i=x_1+\sum_{i=2}^n (x_i-x_1) F_i$$
Then,
$$E[B] = x_1 +E[F]\sum_{i=2}^n (x_i-x_1)= x_1 + {1\over n}\sum_{i=2}^n (x_i-x_1) = {1\over n}\sum_{i=1}^n x_i = \bar{x}$$
and
$$V[B] = V[F]\sum_{i=2}^n (x_i-x_1)^2$$
For this example the variance is invariant under translation of $x_i$. In reducing the degrees of freedom to $n-1$, the term $x_1$ is treated differently from the rest; note that $V[F_1]=(n-1)V[F]$.
Comment: Yes, my answer incorrectly assumed that the $F_i$ were independent. I have edited the answer above to use the $B$ symbol and to treat the $F_i$ correctly. Hopefully now it is clear where the error was made in your calculation...
Comment: Thanks for your suggestions! I updated the notation to make my question easier to understand, although not following you completely. I disagree with your two other issues, so I added justification for my claim about the simplification in the denominator and why I expect the variance to change when $x_i\rightarrow x_i+c$. I think my simplification is valid in the denominator, although very bad in the numerator as you point out. I also think the translation $f_i \rightarrow f_i+c$ is impossible since the way $F_i$ is defined $\sum F_i$ must be 1.
Comment: Okay I removed the incorrect side remark about translating $f_i$. It doesn't change the argument. If you reformulate your problem so that the denominator is a constant, it still does not change the argument. The variance for the quantity you now call $B$ comes from the variance of the random variables $F$. Please look at the equation for $\hat{F}$. The variance clearly increases if all $x_i$ are increased. Are you surprised that the variance of $\hat{F}$ is affected when you shift the $x_i$? That equation is equivalent to your equation for B - so the same applies for $B$.
Comment: I'm sorry, but I still don't follow. Isn't it such that since $F_i=W_i/\sum W_i$, we have that $\sum F_i=\sum W_i/W_i =1$? Therefore $c\sum F_i=c$ and the last equation in your edited answer is an equality and my argument hold. To check my intuition I did a simulation and the variance were unchanged when I shifted the $x_i$. I added the link to my code in my answer.
Comment: Brilliant! This is a huge step forward for my understanding, and it seems correct. I expect that I will accept it as soon as I find the time to work trough it properly. Then I can move on to the problem of finding $V[F]$ now that I have learned that I cannot ignore the variance contribution of the denominator...
Comment: I've found one remaining problem $\sum_{i=2}^n ( x_i-x_1)$ is independent of translation of the $x_i$ but not labelling of the data points (which point is $x_1$). Lets say our $x$ values are 1, 2 and 3. If I say $x_1=1$  then $\sum_{i=2}^n ( x_i-x_1)=(2-1)^2+(3-1)^2 =5$, but if I say $x_1=2$ then $\sum_{i=2}^n ( x_i-x_1)=(1-2)^2+(3-2)^2=2$. The problem may be that the $F_i$ for $i\geq 2$ are not independent. My current guess is that we get $V[B]=V[F]\sum_{i=1}^n ( x_i-\sum_i x_i/N)$ after that is accounted for (Whatever $F$ is defined as then).
Comment: The example treats the first term differently from the rest, thus label invariance does not hold (see last sentence). The initial formulation of this problem asserts that $x_i$ are NOT outcomes of random variables, and the motivation to form a noisy estimator of their simple mean is not stated. It might help to describe the context that this $B$ might be useful. The more typical application (weighted average) is that $x_i$ are outcomes of independent random variables $X_i$ and the weights are not considered outcomes of random variables. In that case the estimator has the properties you expect.
Comment: I added the context of my question, I hope it is helpful. It should explain why  the $x_i$ is not deterministic, and why I named $B$ $\hat x$ initially.   I see why the special treatment of $x_1$ lead to its special place in the variance expression. But since there is nothing in the problem that mandate a particular value to be named $x_1$ a good solution should give the same variance regardless which value is chosen to be $x_1$.
Comment: I find this confusing. Your last comments suggests $x_i$ are not constants, but outcomes of random variable $X_i$. If that is the case, then the formulation of the problem should replace $x_i$ by $X_i$ in your definition of $B$ and the variance of $X_i$ should be included in calculating $V[B]$.
Comment: Sorry, my bad. It should say the $x_i$ is not random (or is deterministic).
Comment: If that is the case, then I go back to my original concern. If they are known constants, form the simple mean of the $x_i$: it has zero variance. You do not motivate why you want to form an estimator that has non-zero variance, when you can calculate it without variance.
Comment: This is a simplified case of a general problem where the mean value of the $W_i$ has a bell shape over $t_i$. Then the falloff of the mean value at the edges will make the expected value independent of the interval of the $t_i$, since the edges will be weighted down. A non centered interval will also be ok.
Answer: Through this PhD thesis (chapter 3.2.3) i found the following solution.
For simplicity, define
$$F_i = {W_i\over\sum W_i}, \text{ so that } B=\sum_{i=1}^N F_i x_i.$$
(As Deans answer suggest)
Then
$$E[(B-E[B])^2]={\sum_{i=1}^N \sum_{j=1}^N (x_i-\bar x) (x_j-\bar x) E[(F_i-E[F_i]) (F_j-E[F_j])} $$
$${=\sum_{i=1}^N  (x_i-\bar x)^2 E[(F_i-E[F_i])^2]}
{=\sum_{i=1}^N  (x_i-\bar x)^2 Var[F_i]}$$
if we assume that the $F_i$ are uncorrelated. $\bar x$ is the mean of the $x_i$.
The first step holds since
$${\sum_{i=1}^N \sum_{j=1}^N (x_i-\bar x) (x_j-\bar x) E[(F_i-E[F_i]) (F_j-E[F_j])}=E\left[\left(\sum_{i=1}^N (x_i-\bar x) (F_i-E[F_i])\right)^2\right],$$
and
$$\sum_{i=1}^N (x_i-\bar x) (F_i-E[F_i])=\sum_{i=1}^N( x_iF_i-x_iE[F_i]) + \bar x \sum_{i=1}^N(E[F_i]-F_i)=B-E[B].$$
Where I used that $\sum_{i=1}^NE[F_i]=1$ and $\sum_{i=1}^NF_i=1$.