Does armcc optimizes non-volatile variables with -O0?

Question: int* Register = 0x00FF0000; // Address of micro-seconds timer
while(*Register != 0);

Should I declare *Register as volatile while using armcc compiler and -O0 optimization ?
In other words: Does -O0 optimization requires qualifying that sort of variables as volatile ? (which is probably required in -O2 optimization)
Answer: It seems to me that you should declare Register as volatile regardless, since it is volatile.  There's no harm in marking it volatile, since you're depending on the compiler not optimizing away the accesses through the pointer.
int volatile* Register = (int*) 0x00FF0000;

You shouldn't depend on the compiler optimization settings to hope this gets compiled correctly.  I'd guess that forgetting to mark things volatile appropriately is a major reason that cranking up optimizations on embedded C code often causes things to start breaking.
Comment: Indeed, you're probably right. But as part of being a novice, I made a mistake by not paying attention to the `volatile` issue. Now, I must read again all my code which is a lot. My project test deadline is close so I don't have time. So all I got left is to hope for -O0 to save me ...
Comment: @Dor: I think you're not alone (as I implied in my last sentence). So `-O0` may well help save you, but you should really try to get those things straightened out. If not now then on the schedule for post deadline.


When endogenous variable is non-normally distributed

Question: I am trying to fit an IV probit model with my dependent variable being binary. However, my endogenous variable is a "ratio" variable, which is not normally distributed, thereby preventing me from employing an IV Probit model. I am wondering whether employing LPM with 2SLS could help resolve the issue of non-normality of the endogenous variable?
Answer: The only assumption required of the endogenous variable with this command is that it is continuous. You do not need normality for it, only for the errors in the two equations (which need to be multivariate normal and homoskedastic). You also can't leave anything out of the model. See here for more.
Ratios are usually continuous, so you should not have a problem. This restriction comes from the fact that ivprobit is a control function estimator.
Comment: I don't think this is necessarily as issue. You cannot assume that the unconditional distribution of a variable tells you something about the error distribution. Here [a nice example](https://stats.stackexchange.com/a/398553/7071). Moreover, the regression is a model for the conditional mean, and the CLT (under some assumptions) allows the mean to be asymptotically normal, even if the variable that goes into the mean is not. This is also the logic for why normal, non-probit IV regression would works well in this case.
Comment: Thanks for your comment, Dimitriy! In fact, my endogenous "ratio" variable has a considerable number of zeros, so I suppose even the error term is the first stage is not normally distributed. I think this is a quite big issue for employing IV estimation.
Comment: I would certainly encourage you to fit both the MLE and min-$\chi^2$ versions of the estimator as wells as ordinary IV models to see how sensitive results are.
Comment: @ZhenkaiRan Did this clear things up?
Comment: Thanks for following up, Dimitriy! I am still wondering whether I can fit my first stage first, and then test the normality of the residual? Does this help justify my model setting of using IVprobit, or 2SLS? I just tried to fit the first stage, and found out that the residual is not normally distributed by using the "swilk" command in STATA. So, this indicates 2SLS or IVProbit is not suitable?
Comment: That normality is sufficient, but not necessary. To quote Wooldridge's [black book (p.592) ](https://mitpress.mit.edu/books/econometric-analysis-cross-section-and-panel-data-second-edition) , "it is certainly possible for $D(u_1 \vert v_2)$ to be normal without $v_2$ having normal distribution." My recommendation is still to fit all possible models to see if they agree. If they don't, you can report the swilk p-value (or plots to see how bad the departure), and say that the ivprobit models are not great because they make stronger assumption that may not hold here, which favors the normal IV.
Comment: Note that the spelling is Stata since it is not an acronym. Also, what is the range of the ratio variable? Is it strictly $[0,1]$?
Comment: Thanks for your advice, Dimitriy! They are really helpful. The ratio is within the unit interval with an excessive amount of zeros.
Comment: Then you might also try David Roodman's `cmp` command, which allows you to have a fractional endogenous variable instead: `cmp (y = x n k) (x = n k z), ind($cmp_probit $cmp_frac)`. Just run `cmp setup` to define the globals beforehand.
Comment: Thanks very much for your advice, Dimitriy! I will have a look at the `cmp` command. This helps a lot!


Calculate limit with integral

Question: Hi I have a problem with following limit:
$$\lim_{x\rightarrow\infty}e^{-x}\int_{0}^{x}\int_{0}^{x}\frac{e^u-e^v}
{u-v}\ \mathrm du\ \mathrm dv$$ as a hint i got that i should use de l'Hospital. So:
$$\lim_{x\rightarrow\infty}\frac{\int_{0}^{x}\int_{0}^{x}\frac{e^u-e^v}
{u-v}\ \mathrm du\ \mathrm dv}{e^{x}}$$ And now we want to calculate derivative of up and down. But now i am not sure how to calculate derivative from $$\frac{\mathrm d}{\mathrm dx}\left( \int_{0}^{x}\int_{0}^{x}\frac{e^u-e^v}
{u-v}\ \mathrm du\ \mathrm dv\right)$$
I will be very glad for help
Comment: Let $g(x,v) = \int_0^x \frac{e^u-e^v}{u-v}\,du$. Then $\frac{d}{dx} \int_0^x g(x,v)\,dv = g(x,x) + \int_0^x \frac{\partial}{\partial x} g(x,v)\,dv$.
Comment: You're taking the derivative with respect to $x$ remember. So you have

$$g(x) = \int_{0}^{x} F(u,v) du \implies g'(x) = F(x,v)$$

where

$$F(u,v) = \frac{e^{u}-e^{v}}{u-v}$$ Try it with the other integral now.
Comment: I mean for single integral i know that it is $F(x,v)$ but i don't see it when we have double.
$$\frac{\mathrm d}{\mathrm dx}\left( \int_{0}^{x}\int_{0}^{x}F(u,v)\ \mathrm du\ \mathrm dv\right)=\frac{\mathrm d}{\mathrm dx}f(g(x))=f'(g(x))\cdot g'(x)=(\int_{0}^{x}F(u,x)du)\cdot(F(x,u))$$ ? We take derivate from outside then inside function? If it is not correct I would be obliged for showing me correct form as I am clueless.
Answer: Define $F(x, y)$ by
$$ F(x, y) = \int_{0}^{x}\int_{0}^{y} \frac{\mathrm{e}^u - \mathrm{e}^v}{u - v} \, \mathrm{d}u\mathrm{d}v. $$
Then we want the derivative of $F(x, x)$. To clarify the structure of this function, let us introduce a new function $g$ defined as $g(x) = (g_1(x), g_2(x)) = (x, x)$. Then $F(x, x) = F \circ g$ and we can apply the chain rule:
$$ \frac{\mathrm{d}}{\mathrm{d}x} F(x, x)
= \bigg( \left. \frac{\partial F}{\partial x} \right|_{g(x)} \bigg) \frac{\mathrm{d}g_1(x)}{\mathrm{d}x} + \bigg( \left. \frac{\partial F}{\partial y} \right|_{g(x)} \bigg) \frac{\mathrm{d}g_2(x)}{\mathrm{d}x}. $$
By noticing that
$$ \frac{\partial F}{\partial x} = \int_{0}^{y} \frac{\mathrm{e}^x - \mathrm{e}^v}{x - v} \, \mathrm{d}v, \qquad
\frac{\partial F}{\partial y} = \int_{0}^{x} \frac{\mathrm{e}^y - \mathrm{e}^u}{y - u} \, \mathrm{d}u, $$
it is straightforward to check that
$$ \frac{\mathrm{d}}{\mathrm{d}x} F(x,x) = 2 \int_{0}^{x} \frac{\mathrm{e}^x - \mathrm{e}^u}{x - u} \, \mathrm{d}u. $$
A further simplification can be made by applying the substitution $t = x - u$, and then
$$ \frac{\mathrm{d}}{\mathrm{d}x} F(x,x) = 2\mathrm{e}^x \int_{0}^{x} \frac{1 - \mathrm{e}^{-t}}{t} \, \mathrm{d}t. $$
Therefore
$$ \lim_{x\to\infty} \frac{F(x,x)}{\mathrm{e}^x} = 2 \int_{0}^{\infty} \frac{1 - \mathrm{e}^{-t}}{t} \, \mathrm{d}t = \infty. $$
Answer: With the change of variables $\xi=u$ and $\eta=u-v$, that is $u=\xi$ and $v=\xi-\eta$ and $\left|\frac{\partial (u,v)}{\partial (\xi,\eta)}\right|=1$, the integral becomes
$$
f(x)=\int_0^x\int_0^x\mathrm e^{\xi}\,\frac{\mathrm e^{\eta}-1}{\eta}\,\mathrm d\xi\,\mathrm d\eta=\underbrace{\int_0^x\mathrm e^{\xi}\,\mathrm d\xi}_{\phi}
\cdot\underbrace{\int_{-x}^x\frac{\mathrm e^{\eta}-1}{\eta}\,\mathrm d\eta}_{\psi}=\phi(x)\psi(x)
$$
and observing that $\phi(x)=\mathrm e^{x}$ and $\psi(x)=2\sinh x$ we have $$f(x)=\mathrm e^{-x}\phi(x)\psi(x)=2\sinh x\to\infty$$ for $x\to\infty$.

Calculate limit with integral


Exact expansion of functions

Question: Prove that for any twice differentiable function $f: {R}^n \to R$,
$f(y) = f(x) + \nabla f(x)^T (y-x)+ \frac{1}{2} (y-x)^T \nabla^2f(z)(y-x) $,
for some $z$ on the line segment $[x, y]$.
Note that it is not approximation, it is exact equality.
Comment: What is $F$...?
Comment: Thanks rlgordonma. That was a mistake. I corrected it. I meant $f$.
Comment: Referencing the proof is also helpful.
Answer: Here's a trick. Take $\gamma(t) = t y + (1 - t) x$. Let's think about the function $g(t) = f \circ \gamma(t)$: the Taylor expansion for this single-variable function about $t = 0$ looks like
$$
g(t) = g(0) + t g'(0) + \frac{t^2 }{2} g''(s)
$$
for some $s \in (0,t)$. Note that $g(1) = f \circ \gamma(1) = f(y), g(0) = f(x)$. The $g', g''$ terms can be found using the chain rule.
Comment: What you're referring to is a straightforward generalization of the mean value theorem; wikipedia has a few proofs on there, but if you want to do it yourself, you should try applying integration by parts to $f(x) - f(0) = \int_0^x f'(y) dy$. Then the remainder term will come out as $\int_0^x y f''(y) dy$: how can you use the intermediate value theorem to conclude?
Comment: Interesting. Now the question is why do we have this Taylor EQUALITY for the single-variable function.
Comment: @ABlumenthal Thanks. You mean $\gamma(t) = ty + (1-t)x$, not $tx+(1-t)y$, so $g(1)=f(y)$ and $g(0)=f(x)$, don't you?
Comment: @chan1142 Yes, I think I do. Thanks for the correction.

Exact expansion of functions


Como focar o input de um formulário constantemente?

Question: Tenho um formulário e preciso dar foco em um input novamente até que ele satisfaça o requerido, exemplo:

$('#text1').blur(function() {
  var teste = $('#text1').val().length;
  console.log(teste);
  if(teste > 5){
    $('#text1').focus();
  }else{
    $('#text2').focus();
  }

});

Input 1:
<input type="text" name="text1" id="text1">

Input 2:
<input type="text" name="text2" id="text2">

É possível proceder desta forma?
Comment: talvez você estava tentando executar o código do focus antes de incluir o jQuery na sua pagina, você deve ter certeza que o jQuery está sendo incluido antes (acima) do que os códigos, senão não vai funcionar mesmo. e eu também sugiro que o código esteja dentro de um `$(document).ready(function(){ });` pois ai garante que só será atribuido evento ao elemento depois que ele ja estiver criado. E se ele for criado com Ajax, você pode executar os códigos no método `.done()` do ajax que executa quando o ajax termina.
Comment: Qual seria o problema?
Comment: Bom dia Paulo, o problema estava com o load da página, pois este formulário advinha de json e como estava usando um js externo com algumas funçoes o mesmo não funcionava de acordo e o focus() como também outras funções do jquery não funcionavam, copiei as funções do js abaixo do formulário e funcionou. vou tentar descobrir o motivo para colocar uma resposta.
Answer: Nesse caso você deve usar o .focus já que o .blur funciona apenas para detectar quando o elemento perde o foco.

$('#text2').focus(function() {
  $('#text1').focus();
});

Input 1:
<input type="text" name="text1" id="text1">

Input 2:
<input type="text" name="text2" id="text2">

Comment: Eu não consigo compreender o porque desta resposta ter sido marcada como correta, afinal ela produz o mesmo resultado que do jeito que está feito a pergunta. Aliás a forma que está na pergunta é bem mais correta, porque sempre que o usuário clicar fora do campo ou clicar em outro campo ou apertar tab, sempre irá voltar a focar o campo em questão, e dessa forma que está nesta resposta você consegue tirar o foco clicando fora do campo.
Comment: Minha resposta foi baseado na pergunta antes dela ser editada, foi dessa forma que compreendi. Ele queria que, mesmo o usuário clicando em outro input, o foco permanecesse em apenas um dele. Com a edição da pergunta, basta ele utilizar .focus e .blur.


Render view array programatically within template

Question: I would like to print the array of a specific View within a template, so I can then access each specific field and theme as I wish. The view I am using will only be outputting one row. All my attempts seem to be returning 'previously declared' errors.
Your help is appreciated.
Thanks
Comment: there is a `$view` variable which contains the entire View object available in most if not all Views templates, and `$views->result` contains the data in the row, so that should contain what you are looking for
Comment: Please show your code, it'll make things much easier to debug
Comment: Cool, I managed to drill down to the field I want to render:    print render($view->result[0]->field_field_media_image[0]['rendered']['#item']['uri'])

This outputs the objects content fine within the Views template, however my final objective is to have this single object render within my homepage template.

Currently, the views template block renders within a page block. Is this even the best method to render a specific view object within a page?
Answer: There are a few steps involved with applying a template to view. But thankfully they are all fairly simple.
I found one of the most helpful tutorials was this one, which goes through the process. I think this process should give you sufficient control over the theme for each field.
I'm not sure why you might be getting the 'previously declared' errors though.


Property hiding and reflection (C#)

Question: Declaring a property in a derived class that matches the name of a property in the base class "hides" it (unless it overrides it with the override keyword).  Both the base and derived class properties will be returned by Type.GetProperties() if their types don't match.  However, if their types do match, shockingly only the derived class's property is returned.  For instance:
class A
{
    protected double p;
    public int P { get { return (int)p; } set { p = value; } }
}
class B : A
{
    public new int P { get { return (int)p; } set { p = value; } }
}
class C : B
{
    public new float P { get { return (float)p; } set { p = value; } }
}

Calling typeof(C).GetProperties() will only return B.P and C.P.  Is it possible to call GetProperties() in a way that returns all three?  There is almost certainly a way to do it by traversing the inheritance hierarchy, but is there a cleaner solution?
Comment: @driis: This is just a trivial example to illustrate.  But, for the sake of the argument, assume this class hierarchy is written by someone other than me, but I still need to find all of its public properties, even the hidden ones.
Comment: @Wilhelm: But you can access the hidden property: C c = new C(); ((A)c).P = 42;
Comment: Why would you want to have such a class hierarchy ?
Comment: As there is no way that using the derived class you can access the hidden property I would suppose that effectively it does not have that property for Reflection. Consider yourself lucky, VB only shows C.P when using Shadows.
Comment: Have you tried using BindingFlags.FlattenHierarchy?  That said, not returning the property sounds like the correct behavior, as it's probably been hidden for a reason.
Comment: @Dan: FlattenHierarchy is for static members, it won't work here.
Comment: I like both answers so far pretty well.  I've decided to post a bounty and give it some more time to see if anyone can improve upon them since they each have a significant drawback.  It is interesting that neither fields nor methods have this problem with reflection.  Some satisfying explanation for this problem might also be an acceptable answer.
Answer: GetProperties is defined as all public properties of the type.
You could get their get and set methods using:
typeof(C).GetMethods()
         .Where(m => m.Name.StartsWith("set_") || m.Name.StartsWith("get_"))

Although this seems like a bad idea, compared to going down the inheritance hierarchy to get the properties.
Comment: Then you would have the same problem with the get_P method hiding the one of the parent, I think.
Comment: @Yuriy: typeof(C).GetMethods().Where
@driis: No, it seems to work properly.
Comment: It's not quite clean, but this is the *only* method so far that really returns exactly the right number of properties.  Therefore, it is my accepted answer.  It it still just amazing to me that reflection can work so well will fields and methods, but fall flat on its face with properties.
Comment: You are right. This method also works. Not quite sure why it works, since I assume the same method hiding rules go for methods as well as properties. Hmm.
Comment: This would work for me if I could get at the PropertyInfo from the getter or setter.
Comment: What do you need from the PropertyInfo that is not provided by the getter and setter?
Comment: I suppose it would work without the PropertyInfo, but I would have to be able to effectively match each getter with its respective setter, and that seems messy.
Answer: I do not think it is possible without traversing the inheritance hierarchy. It does not have to be too much code, though:
    public static IEnumerable<PropertyInfo> GetAllProperties(Type t)
    {
        while (t != typeof(object))
        {
            foreach (var prop in t.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
                yield return prop;
            t = t.BaseType;
        }
    }

Of course, if you know a common basetype you can stop at, instead of object, it will be more efficient. Also; it will take some time to do the reflection, so cache the result. After all, the type information won't change during execution.
Comment: Won't this yield overridden properties multiple times?
Comment: No, because he said BindingFlags.DeclaredOnly.
Comment: The problem here is that if we re-write our class hierarchy so that B.P overrides A.P, we still get three properties even though an object of type C now only has two.
Comment: In contrast, Yuriy, your answer would yield only two sets of get/setters, which is the correct behavior.
Comment: You're right, I misread what you said. I also tested my method and it does return only two.
Answer: Through reflection, the new keyword only hides the inherited property if the signature matches. I guess reflection matches signatures on property accessors (get_ & set_). It's the reasons why GetProperties() returns B.P and C.P when the return type differ.
I recently discovered Fasteflect which provides advanced reflection mechanisms.
I checked and Fasteflect type.Properties returns all the tree of hidden members (P). I think the API consider backing members (virtual/override) and hidden members (new) differently which is a good thing for your 'problem' ;)
My test with fasterflect :
class Class1
{
    public object field1 = null;

    public virtual object Property1 { get; set; }

    public object Property2 { get; set; }

    public string Property3 { get; set; }
}

class Class2 : Class1
{
    public new object field1 = null;

    public override object Property1 { get; set; }

    public new string Property3 { get; set; }
}

class Class3 : Class2
{
    public new string Property3 { get; set; }
}

Filter backing members but returns all hidden members :
typeof(Class3).Properties(Flags.ExcludeBackingMembers | Flags.Public | Flags.Instance)

typeof(Class3).Properties(Flags.ExcludeBackingMembers | Flags.Public | Flags.Instance)    Count = 5   System.Collections.Generic.IList

[0]  {System.String Property3}   System.Reflection.PropertyInfo
[1]  {System.Object Property1}   System.Reflection.PropertyInfo
[2]  {System.String Property3}   System.Reflection.PropertyInfo
[3]  {System.Object Property2}   System.Reflection.PropertyInfo
[4]  {System.String Property3}   System.Reflection.PropertyInfo
Comment: Interesting - it did work much better with exactly the flags you used.  However, it still failed in my testing.  If you hide an overridden property, it still disappears.  (Add public new object Property1 to your Class3.)  So, in effect, there are still properties there that can be used, but are not visible to reflection.
Comment: http://msdn.microsoft.com/en-us/library/51y09td4%28VS.71%29.aspx#vclrfnew_newmodifier : A constant, field, property, or type introduced in a class or struct hides all base class members with the same name.
Comment: Not through reflection. Since properties are accessors, I guess reflection matches signatures on accessor methods (get_ & set_).
Comment: After some testing and inspection of Fasterflect, I can safely say that their answer to this problem is totally equivalent to driis's.  Their recursive solution to finding hidden members is incapable of excluding virtual properties that have been overridden.  (Actually, setting the ExcludeBackingMembers flag somehow excludes all three properties in both cases.)  However, thanks for the link.
Comment: Weird, I added my test in the post. I tested again and ExcludeBackingMembers don't exclude hidden members. I tried without auto properties too : same behavior.
Comment: Right, really interesting, thanks for this remark. It's because the Property1 in Class1 and Class2 are still backing members. The ExcludeBackingMembers do his job but almost bad since it should return Property1 of Class2 too (which become a hidden member) according to the new modifier in Class3. Maybe advanced querying can handle this : http://fasterflect.codeplex.com/wikipage?title=Advanced%20Queries&referringTitle=Getting%20Started
Comment: Hm, In case with: ```public int Prop { get; }``` and ```public float Prop { get; }``` reflection returns two properties.

But when you have events with different types then reflection returns only one event.

This all rather looks like a bug.

Property hiding and reflection (C#)


Handle any type in method

Question: I have two classes.
public class Handler
{

delegate T ReturnDelegate();

    public T HandleReturnMethod(ReturnDelegate d)
    {
        DoSomething(); //some other stuff

        return d();
    }
}

public partial class Test
{

    protected int Id
    {
        get
        {
            return new Handler().HandleReturnMethod(delegate()
            {
                int id = 1;
                return id;
            });
        }
    }
}

I want to be able to handle any Type in the Handler class. But 'T' seems not to work, int cannot be converted to it.
If there is a better approach or something is wrong here, please comment.
Comment: Command pattern? Not sure, but have a look: http://en.wikipedia.org/wiki/Command_pattern
Answer: You need to create the delegate type and method to use generics.  Personally, I would use a standard delegate for this:
public T HandleReturnMethod<T>(Func<T> d)
{
    DoSomething(); //some other stuff
    return d();
}

Given the above, your code should work:
protected int Id
{
    get
    {
        return new Handler().HandleReturnMethod(() =>
        {
            int id = 1;
            return id;
        });
    }
}

Answer: The reason your code wasn't working is because int ( Int32 ) is a structure not an object which is the reason it cannot normally be nullable
unless you declare it as int? num = null;
If I am not mistaken only an object can have a Type ( both an object and a Type are classes ) not a structure.  All classes are based on the object class ( which is the reason a collection that isn't a generic ( i.e. Type t ) elements are objects.
http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=VS.100).aspx
http://msdn.microsoft.com/en-us/library/ah19swz4.aspx
http://msdn.microsoft.com/en-us/library/ah19swz4(v=VS.100).aspx
http://msdn.microsoft.com/en-us/library/system.int32.aspx
http://msdn.microsoft.com/en-us/library/system.type.aspx
http://msdn.microsoft.com/en-us/library/system.object.aspx

Handle any type in method


How to find the speed of a river when an object is moving over it?

Question: The problem is as follows:

An air force pilot navigates across the Amazon river aboard an
  inflatable rescue lifeboat. He spends $\textrm{4 hours}$ by going in
  the same direction of the current to cover $\textrm{72 kilometers}$
  between his landing site to the nearest town. Later on, he returns to
  his landing site spending $\textrm{6 hours}$ by going against the
  river stream. What is the speed of the river if we know the speed of
  the lifeboat and the river are constant?

In my attempt to solve this problem I sketched the situation in Figure A.

I defined the speed of the lifeboat as:
$$\textrm{lifeboat=}v_{b}$$
and the speed of the river stream as:
$$\textrm{river stream=}v_{r}$$
For constant speed the equation is the following:
$$x=x_{0}+vt$$
Since I'm assuming it departs from the center of the axis $\textrm{(0,0)}$ the equation becomes into:
$$x=vt$$
Initially I thought that the speed of the lifeboat was this:
$$v_{b}=\frac{72\,\textrm{km}}{4\,\textrm{h}}=18\,\frac{\textrm{km}}{\textrm{h}}$$
However after some deeper thought I said that this cannot be as the speed of the boat is influenced by the stream as it mentions going downstream and not in water at rest so I changed the equation to take into account the speed of the river.
Since both are in the same direction I thought to summing them up and by doing this the new equation became into:
$$\left ( v_{b}+v_{r} \right )\times 4 = 72$$
and when the lifeboat goes upstream would be the difference in other words the speed of the stream subtracted from the lifeboat, therefore becoming into:
$$\left ( v_{b}-v_{r} \right )\times 6 = 72$$
By solving the system:
$$\left ( v_{b}+v_{r} \right )\times 4 = 72$$
$$\left ( v_{b}-v_{r} \right )\times 6 = 72$$
$$v_{b}+v_{r} = 18$$
$$v_{b}-v_{r} = 12$$
$$2v_{b} = 30$$
$$v_{b}=15$$
$$v_{r}=3$$
Therefore the speed of the river stream is $3\,\frac{km}{h}$. However I'm not sure if what I did was correct. Also, is it okay to assume velocities going in the same direction should be summed and when they're in opposite should be subtracted? The answer I got is somewhat reasonable as I do not expect that the river has a really big speed. But what if the stream speed is larger than the speed of the boat? can this situation happen? would this affect the way how I did approached this problem?. Can someone help me to clear these ideas?.
Comment: Your calculation is correct. if the speed of the river is greater than the speed of the boat in water, he cannot make any progress upstream but will be forced downstream. Yes that could happen.
Answer: Your calculation is indeed correct.
Velocity is a vector, i.e. it comes with a magnitude and direction. When they are in the same direction, we add them, when they are in the opposite direction, we subtract them.
To be able to travel in the opposite direction, your boat needs a faster speed than the river. Otherwise, imagine someone who push you backward $2$ steps whenever you try to move forward a step, if the destination is in a straight line and not a loop, you can't reach the destination. Hence you won't have the second equation.
Comment: I seem to have missed that velocity is a vector, I thought that the equations $x=x_{0}+vt$ held true only for scalars so I was not so sure to use it in there.
Answer: "However after some deeper thought I said that this cannot be as the speed of the boat is influenced by the stream "
"The speed of the boat" is actually ambigious.  "The speed of the boat" in a swimming pool is different then the "speed of the boat" when it on a river, is different then "the speed of the boat" on airplane, is different from the speed of the boat in a rocket ship being crashed into the sun.
There are three different speeds alluded to in the problem
Speed 1:  $v_1$ "the speed of the boat with the current" when it went with the current and traveled $72$ miles in $4$ hours.  This speed is indeed $v_1 = \frac {72}{4} = 18 kmh$ but this will not necessarily be what most people consider "the speed of the boat" as it does not indicated the boat traveling solely on its own power.
Base Speed: $v_b$ how fast the boat would travel on its own solely under its own power.
Clearly $v_1 = v_b + v_r$.  So $18 = v_b + v_r$.
Speed 2: $v_2$ "the speed of the boat against the current" when it went $72$ kilometers in $6$ hours.  That speed is indeed $v_2 = \frac {72}6 = 12 kmh$. (Why does your picture show "16"?)
And Clearly $v_2 = v_b -vr$. So $12 = v_b - v_r$.
So you have $18 = v_b + v_r$ and $12 = v_b - v_r$ and must solve for $v_r$.
Comment: That's an interesting observation. When I tried to solve this problem I did not took in consideration the intricacies of the language but at you pointed out, when I used those words it was not very specific. What I meant was that the speed of the boat in the river going downstream cannot be treated as if the boat was in water at rest, to figure this out it took me a while, therefore I couldn't just make the division as mentioned above. Now that we have that clear, I seem to have missed the concept of "own power" that you mentioned.
Comment: Next time I'll be carefull with that because by using this concept it all makes sense by summing and subtracting one from the other. Regarding the picture I changed it accordingly, sorry it was a typo due rushed drawing what I meant was $12 \frac{\textrm{km}}{\textrm{h}} $.


Feeds Import - Entity Reference mapping

Question: I have a "Buildings" content type. Within that content type I have a building_id field, which contains the building ID.
I have an "Employee" content type. Within that content type I have an entity reference to the Buildings content type.
I have a CSV file for employees but it does not have the building label or the node id, only the building_id.
So my issue is that when I run the employee feed import, I cannot add the building since I only have the building_id.
How would I map the building_id in my csv to match the building_id in the building content type so that it knows which building node it is referencing?
I hope that makes sense :)
Thanks!
Answer: In the past I used Views Data Export to build a spreadsheet in Views that contain the NID and the plain text field I needed to use as a reference.
Then in Excel, you can use VLOOKUP to join 2 excel files based on a common column (building_id) so  that way you can obtain the entity referenced nid you need for your import.
Comment: You sir, are a lifesaver. That worked great! Thanks again.

Feeds Import - Entity Reference mapping


Campo de formulário acima de todos os elementos na página

Question: Estou desenvolvendo um site, porém ocorreu um pequeno bug do qual não consigo resolver, existe um formulário de busca na div principal, e um menu que fica fixo, acima de qualquer elemento na página. Porém, ao abrir o menu, o input do formulário fica acima do menu, como se tivesse um z-index maior que o do menu, o que causa, e como posso resolver este problema?

 //MenuOpenClose
 function mainMenu(){
  var maskMenu = document.getElementById("mask-menu");
  var openMenuBtn = document.getElementById("main-menu-open");
  var closeMenuBtn = document.getElementById("main-menu-close");

  var openMenu = function(){
   document.documentElement.classList.add("menu-active");
   maskMenu.style.display = "block";
   setTimeout(function(){
    maskMenu.style.backgroundColor = "rgba(0,0,0,.6)";
   },50);
  }
  var closeMenu = function(){
   maskMenu.style.backgroundColor = "rgba(0,0,0,0)";
   document.documentElement.classList.remove("menu-active");
   setTimeout(function(){
    maskMenu.style.display = "none";
   },600);
  }

  maskMenu.style.display = "none";

  openMenuBtn.onclick = function(){openMenu()};
  closeMenuBtn.onclick = function(){closeMenu()};
  maskMenu.onclick = function(){closeMenu()};

 }
 mainMenu();
 //ScrollDetect
 function detectaRolagem(){
  var menuPrincipal = document.getElementById("menu-principal");
  if(document.documentElement.scrollTop >= 15){
   menuPrincipal.classList.add("offTop");
  }else{
   menuPrincipal.classList.remove("offTop");
  };

 }detectaRolagem();

 window.onscroll = function(){detectaRolagem()}
 document.onload = function(){detectaRolagem()}
 //PrincipalContent
 function conteudoPrincipal(){
  var principal = document.getElementById("principal");
  principal.style.height = window.innerHeight + "px";
 }conteudoPrincipal();

 window.onresize = function(){conteudoPrincipal()};
 document.onload = function(){conteudoPrincipal()}
/* RESET.css */
*{
 color:inherit;
 font-family:inherit;
 background-color:inherit;
 margin:0;
 padding:0;
 text-decoration:none;
 border:none;
 font-size:inherit;
 outline:none;
 box-sizing:border-box;
 list-style:none;
}
.sr-only {
 position:absolute;
 width:1px;
 height:1px;
 margin:-1px;
 overflow:hidden;
 clip:rect(0,0,0,0);
}
html,body{
 height:100%;
 font-family:"Open Sans", sans-serif;
}
img{
 width:100%;
}

/* Navbar */
nav{
 width:100%;
 position:fixed;
 display:flex;
 align-items:center;
 background-color:rgba(255,255,255,0);
 border-bottom:1px solid transparent;
 transition:all .3s ease-in-out;
 padding:0 3.125%;
}
nav.offTop{
 background-color:rgba(255,255,255,1);
}
nav > div{
 padding:12px;
 display:flex;
 align-items:center;
 position:relative;
 justify-content:space-between;
 width:100%;
}
.social-icons{
 display:flex;
 align-items:center;
 justify-content:space-around;
}
.social-icons li{
 margin:0 4px;
 padding:4px;
}
#menu-links{
 position:fixed;
 top:0;
 left:-100%;
 display:flex;
 flex-direction:column;
 width:80%;
 height:100%;
 background-color:rgba(255,255,255,1);
 padding:16px;
 transition:all .6s ease-in-out;
 z-index:20;
}
#mask-menu{
 transition:all .6s ease-in-out;
 background-color:rgba(0,0,0,0);
 position:fixed;
 top:0;
 bottom:0;
 left:0;
 right:0;
 z-index:10;
}
html.menu-active #menu-links{
 left:0;
}
.menu-buttons button:hover{
 cursor:pointer;
}
#menu-links .menu-buttons{
 align-self:flex-end;
}
#menu-links form fieldset{
 display:flex;
 align-items:center;
 position:relative;
}
#menu-links form fieldset input{
 padding:6px 12px;
}
#menu-links form fieldset button{
 position:absolute;
 right:12px;
 top:50%;
 transform:translateY(-50%);
}
#menu-links form fieldset button span{
 display:flex;
 align-items:center;
}
#menu-links li{
 padding:6px 0;
 display:flex;
 flex-direction:column;
 justify-content:center;
 align-items:stretch;
}
.menu-outtop{
 border-bottom:1px solid #ccc;
 background-color:rgba(255,255,255,1);
}

#principal{
 padding:64px 3.125%;
 display:flex;
 flex-direction:column;
 align-items:center;
 justify-content:center;
 text-transform:uppercase;
}
#principal h2{
 font-size:1.3em;
 margin:0 0 12px;
 color:#111439;
}
#principal form fieldset{
 display:flex;
 position:relative;
 align-items:center;
}
#principal form input{
 border: 1px solid #a0a9b6;
 padding:6px 12px;
 width:100%;
 position:relative;
}
#principal form button{
 position:absolute;
}

#footer{
 display:flex;
 align-items:center;
 justify-content:center;
 padding:12px 3.125% 32px;
 text-transform:uppercase;
 font-weight:700;
}

Facebook<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#194880" d="M5,3H19A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3M18,5H15.5A3.5,3.5 0 0,0 12,8.5V11H10V14H12V21H15V14H18V11H15V9A1,1 0 0,1 16,8H18V5Z" /></svg>

Twitter<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#009ec6" d="M5,3H19A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26 17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97,7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38 6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69 8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76 7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95 17.71,9.33Z" /></svg>

Instagram<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#285fa8" d="M7.8,2H16.2C19.4,2 22,4.6 22,7.8V16.2A5.8,5.8 0 0,1 16.2,22H7.8C4.6,22 2,19.4 2,16.2V7.8A5.8,5.8 0 0,1 7.8,2M7.6,4A3.6,3.6 0 0,0 4,7.6V16.4C4,18.39 5.61,20 7.6,20H16.4A3.6,3.6 0 0,0 20,16.4V7.6C20,5.61 18.39,4 16.4,4H7.6M17.25,5.5A1.25,1.25 0 0,1 18.5,6.75A1.25,1.25 0 0,1 17.25,8A1.25,1.25 0 0,1 16,6.75A1.25,1.25 0 0,1 17.25,5.5M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9Z" /></svg>

Youtube<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#e42c27" d="M10,16.5V7.5L16,12M20,4.4C19.4,4.2 15.7,4 12,4C8.3,4 4.6,4.19 4,4.38C2.44,4.9 2,8.4 2,12C2,15.59 2.44,19.1 4,19.61C4.6,19.81 8.3,20 12,20C15.7,20 19.4,19.81 20,19.61C21.56,19.1 22,15.59 22,12C22,8.4 21.56,4.91 20,4.4Z" /></svg>

    <button id="main-menu-open">Abrir menu<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z" /></svg></button>

     <button id="main-menu-close">Fechar menu<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" /></svg></button>

     <form method="post" action="">
      <fieldset>
       <input type="text" name="" placeholder="O que você procura?">
       <button type="submit">Pesquisar<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" /></svg></button>
      </fieldset>
     </form>

Página inicial

Sobre

Contato

Qual o seu problema?

   <form method="post" action="">
    <fieldset>
     <input type="text" name="" placeholder="Ex: Assinatura de E-mail">
     <button type="submit">Pesquisar<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" /></svg></button>
    </fieldset>
   </form>

Talvez a solução esteja aqui!

<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
Comment: Se colocares um https://pt.stackoverflow.com/help/mcve , terás mais chance de ser ajudado Murilo
Comment: Murilo basta colocares no `nav#menu-principal` um `z-index:1`. Testa lá para ver
Comment: Murilo não vou postar como porque não sei porque ocorre, nunca tive interesse suficiente por isso para aprofundar. Mas espero que alguém saiba e te consiga responder
Comment: eu mexi em todas as propriedades CSS, e o JS inteiro é para o Menu, por isso coloquei tudo
Comment: posta como resposta man, mas por que isso ocorre ?
Answer: O que acontece é que algumas vezes estruturamos o css e não nos preocupamos com a hierarquia no DOM, elementos como o inputs, tendem a sobrepor tudo o que não estiver setado com z-index adequado e ou position absolute ou relative, ainda mais quando esses elementos estão acima deles, então uma solução simples para o seu caso foi transferir o menu lateral para o final do código...

 //MenuOpenClose
 function mainMenu(){
  var maskMenu = document.getElementById("mask-menu");
  var openMenuBtn = document.getElementById("main-menu-open");
  var closeMenuBtn = document.getElementById("main-menu-close");

  var openMenu = function(){
   document.documentElement.classList.add("menu-active");
   maskMenu.style.display = "block";
   setTimeout(function(){
    maskMenu.style.backgroundColor = "rgba(0,0,0,.6)";
   },50);
  }
  var closeMenu = function(){
   maskMenu.style.backgroundColor = "rgba(0,0,0,0)";
   document.documentElement.classList.remove("menu-active");
   setTimeout(function(){
    maskMenu.style.display = "none";
   },600);
  }

  maskMenu.style.display = "none";

  openMenuBtn.onclick = function(){openMenu()};
  closeMenuBtn.onclick = function(){closeMenu()};
  maskMenu.onclick = function(){closeMenu()};

 }
 mainMenu();
 //ScrollDetect
 function detectaRolagem(){
  var menuPrincipal = document.getElementById("menu-principal");
  if(document.documentElement.scrollTop >= 15){
   menuPrincipal.classList.add("offTop");
  }else{
   menuPrincipal.classList.remove("offTop");
  };

 }detectaRolagem();

 window.onscroll = function(){detectaRolagem()}
 document.onload = function(){detectaRolagem()}
 //PrincipalContent
 function conteudoPrincipal(){
  var principal = document.getElementById("principal");
  principal.style.height = window.innerHeight + "px";
 }conteudoPrincipal();

 window.onresize = function(){conteudoPrincipal()};
 document.onload = function(){conteudoPrincipal()}
/* RESET.css */
*{
 color:inherit;
 font-family:inherit;
 background-color:inherit;
 margin:0;
 padding:0;
 text-decoration:none;
 border:none;
 font-size:inherit;
 outline:none;
 box-sizing:border-box;
 list-style:none;
}
.sr-only {
 position:absolute;
 width:1px;
 height:1px;
 margin:-1px;
 overflow:hidden;
 clip:rect(0,0,0,0);
}
html,body{
 height:100%;
 font-family:"Open Sans", sans-serif;
}
img{
 width:100%;
}

/* Navbar */
nav{
 width:100%;
 position:fixed;
 display:flex;
 align-items:center;
 background-color:rgba(255,255,255,0);
 border-bottom:1px solid transparent;
 transition:all .3s ease-in-out;
 padding:0 3.125%;
}
nav.offTop{
 background-color:rgba(255,255,255,1);
}
nav > div{
 padding:12px;
 display:flex;
 align-items:center;
 position:relative;
 justify-content:space-between;
 width:100%;
}
.social-icons{
 display:flex;
 align-items:center;
 justify-content:space-around;
}
.social-icons li{
 margin:0 4px;
 padding:4px;
}
#menu-links{
 position:fixed;
 top:0;
 left:-100%;
 display:flex;
 flex-direction:column;
 width:80%;
 height:100%;
 background-color:rgba(255,255,255,1);
 padding:16px;
 transition:all .6s ease-in-out;
 z-index:20;
}
#mask-menu{
 transition:all .6s ease-in-out;
 background-color:rgba(0,0,0,0);
 position:fixed;
 top:0;
 bottom:0;
 left:0;
 right:0;
 z-index:10;
}
html.menu-active #menu-links{
 left:0;
}
.menu-buttons button:hover{
 cursor:pointer;
}
#menu-links .menu-buttons{
 align-self:flex-end;
}
#menu-links form fieldset{
 display:flex;
 align-items:center;
 position:relative;
}
#menu-links form fieldset input{
 padding:6px 12px;
}
#menu-links form fieldset button{
 position:absolute;
 right:12px;
 top:50%;
 transform:translateY(-50%);
}
#menu-links form fieldset button span{
 display:flex;
 align-items:center;
}
#menu-links li{
 padding:6px 0;
 display:flex;
 flex-direction:column;
 justify-content:center;
 align-items:stretch;
}
.menu-outtop{
 border-bottom:1px solid #ccc;
 background-color:rgba(255,255,255,1);
}

#principal{
 padding:64px 3.125%;
 display:flex;
 flex-direction:column;
 align-items:center;
 justify-content:center;
 text-transform:uppercase;
}
#principal h2{
 font-size:1.3em;
 margin:0 0 12px;
 color:#111439;
}
#principal form fieldset{
 display:flex;
 position:relative;
 align-items:center;
}
#principal form input{
 border: 1px solid #a0a9b6;
 padding:6px 12px;
 width:100%;
 position:relative;
}
#principal form button{
 position:absolute;
}

#footer{
 display:flex;
 align-items:center;
 justify-content:center;
 padding:12px 3.125% 32px;
 text-transform:uppercase;
 font-weight:700;
}

Facebook<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#194880" d="M5,3H19A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3M18,5H15.5A3.5,3.5 0 0,0 12,8.5V11H10V14H12V21H15V14H18V11H15V9A1,1 0 0,1 16,8H18V5Z" /></svg>

Twitter<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#009ec6" d="M5,3H19A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26 17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97,7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38 6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69 8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76 7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95 17.71,9.33Z" /></svg>

Instagram<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#285fa8" d="M7.8,2H16.2C19.4,2 22,4.6 22,7.8V16.2A5.8,5.8 0 0,1 16.2,22H7.8C4.6,22 2,19.4 2,16.2V7.8A5.8,5.8 0 0,1 7.8,2M7.6,4A3.6,3.6 0 0,0 4,7.6V16.4C4,18.39 5.61,20 7.6,20H16.4A3.6,3.6 0 0,0 20,16.4V7.6C20,5.61 18.39,4 16.4,4H7.6M17.25,5.5A1.25,1.25 0 0,1 18.5,6.75A1.25,1.25 0 0,1 17.25,8A1.25,1.25 0 0,1 16,6.75A1.25,1.25 0 0,1 17.25,5.5M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9Z" /></svg>

Youtube<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#e42c27" d="M10,16.5V7.5L16,12M20,4.4C19.4,4.2 15.7,4 12,4C8.3,4 4.6,4.19 4,4.38C2.44,4.9 2,8.4 2,12C2,15.59 2.44,19.1 4,19.61C4.6,19.81 8.3,20 12,20C15.7,20 19.4,19.81 20,19.61C21.56,19.1 22,15.59 22,12C22,8.4 21.56,4.91 20,4.4Z" /></svg>

    <button id="main-menu-open">Abrir menu<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z" /></svg></button>

Qual o seu problema?

   <form method="post" action="">
    <fieldset>
     <input type="text" name="" placeholder="Ex: Assinatura de E-mail">
     <button type="submit">Pesquisar<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" /></svg></button>
    </fieldset>
   </form>

Talvez a solução esteja aqui!

     <button id="main-menu-close">Fechar menu<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" /></svg></button>

     <form method="post" action="">
      <fieldset>
       <input type="text" name="" placeholder="O que você procura?">
       <button type="submit">Pesquisar<svg style="width:24px;height:24px" viewBox="0 0 24 24"><path fill="#000000" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" /></svg></button>
      </fieldset>
     </form>

Página inicial

Sobre

Contato

<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
Answer: Você pode usar z-index negativo para resolver este problema. No seu caso ficaria:
HTML
   <input type="text" class="exemplo" name="" placeholder="Ex: Assinatura de E-mail">

CSS
   .exemplo{
   z-index:-99;
   }


Use Google Sheets to Import Data from API without Script

Question: I'm using IMPORTDATA to import data from an API.
e.g. =IMPORTDATA("https://api.bitcoinaverage.com/ticker/EUR/")
Unfortunately I have to click the cells everytime I open the spreadsheet to get the new Data from the API.
Is there any way to have the spreadsheet refresh itself every hour or so to get the new data?
Answer: If you don't want any script, then you can go to your Spreadsheet -> FILE -> Spreadsheet settings -> Calculation then make it on change every hour.
For more information, check this page.
Hope it helps you.
Comment: It says in the docu, this will only work for date and rand functions. Are you sure this works? Unfortunately in my example I can't really test this...


Como reunir um conjunto de diferentes tipos de dados em uma estrutura nomeada no python?

Question: Boa tarde, me surgiu uma dúvida de como reunir um conjunto de diferentes tipos de dados em uma estrutura nomeada no Python. Estou em processo de migração de delphi para a linguagem Python.Sou bem iniciante ainda.
 Mas quero fazer algo tipo o comando 'record' do Delphi.
Answer: Para Python 3.7+ você pode utilizar a dataclasses.dataclass:
from dataclasses import dataclass

@dataclass
class TModo:
    descricao: str
    valor_i: str
    valor_f: str
    versao: int

Devido à presença do decorador, alguns métodos serão construídos para você na classe, incluindo o método inicializador. Então, para criar uma nova instância de TModo basta fazer:
tmodo = TModo('Descrição', 'valor i', 'valor f', 1)

Vale lembrar que o Python possui tipagem dinâmica e os tipos acima são apenas anotações de tipo, ou seja, não alterarão de forma alguma na execução do código. Portanto, mesmo que indique que versão seja int, poderei atribuí-la uma string sem problemas - mas isso é uma característica da linguagem, não da implementação.

O que são dataclasses e quando utilizá-las?

Outra alternativa é você utilizar as named tuples. Para Python 3.5+ você pode utilizar a definição a partir de typing.NamedTuple:
from typing import NamedTuple

class TModo(NamedTuple):
    descricao: str
    valor_i: str
    valor_f: str
    versao: int

Ou para versões anteriores pode usar a collections.namedtuple:
from collections import namedtuple

TModo = namedtuple('TModo', ['descricao', 'valor_i', 'valor_f', 'versao'])

Para saber a diferença entre elas:

Qual a diferença de namedtuple e NamedTuple?
Comment: Valeu Anderson, me serviu muito bem! Obg


Resize logo in nav bar on mobile

Question: I'm learning all of this on the fly, so I'm hoping you can help me figure it out. I've added my logo to the nav bar as a background image on a blank menu item (maybe a clunky method, but the best solution I could find). It works great for desktop views but I'm not sure how to make it resize in my mobile menu.
You can see the actual site here: http://www.christinelellis.com
Thanks!
Christine
Comment: nevermind, i was looking at your image instead of your logo
Comment: @christine-lellis On *StackOverflow* when people help you by answering to your questions, usually you give them at least some feedback to let them know that their answer was useful and to respect the time they spend.
Answer: As there is not real question and as I don't know how this is build, here is how I would fix this:
On the menu, I would add some overflow: hidden on the list items (not very necessary but at least if you keep it like this, the other buttons are not overrided by the image and it's still functional.):
#menu-main-menu li {
   overflow:hidden;
}

and then make the logo link fluid with a real image () in the link instead of having the logo image set as background (and this is a lot better in term of SEO to have an image with a proper alt text instead of a background-image) :
HTML

then in CSS:
#menu-main-menu li#menu-item-4025 img {
   display: block;
   margin: 0 auto;
   max-width: 300px;
   width: auto;
}

You'll have to remove the CSS on the a link which define a fixed width and a fixed height and which kick the text to text-indent: -9999px; (which is also really bad in term of SEO..).
This would be a good beginning.
Good Luck'
Comment: RedBreast, thanks for the suggestions. I realize my method was not an ideal solution for SEO or anything...it was just the best fix I could find within my capabilities. I'll play with this and see what I can do.And yes, of course I appreciate your time. I'm sure you can tell from the site, I'm a small biz owner- not a developer- so this is the first chance I've had to check back at Stack Overflow.
Answer: If I were you, I would change a few things. First I would put the menu-control span inside the header at the top so it's all lined up. Then you can place your logo underneath. So it would look something like this:

      Menu
      // add in rest of the header you have here

     // add rest of your html here

  css:
  @media (max-width: 900px)
  .menu_control { width: 100%; border-width: 0; background-color: #ffffff; padding: 10px 0px 10px 20px; cursor: pointer; box-sizing: border-box; display: inline-block; max-width: 100px; margin: auto 0px; float: left;

  .outerlogo { width: 100%; height: 100%; display: inline-block; margin: auto 0px; padding: 0px; }

  .innerlogo { margin: auto 0px; display: inline-block; width: 100%; }

  .innerlogo img { width: 90%; max-width: 280px; display: inline-block; vertical-align: middle; margin: auto 0px; }

Also get rid of @media (max-width: 450px) .menu_control and .header, just use the min-width 900px for everything for mobile, or switch it to 610px, whatever you want to do. I used the img tag instead of a background-image since its easier to manipulate.
Let me know if you have any questions.
Comment: Thanks Keith, I'm not sure how to do this since the @media settings are part of my theme...I'm going to try the solution above but I really appreciate your time :)
Answer: You can resize a background image using the background-size property.
To target the smaller (mobile) devices you'll need to use a Media query to target those.
An example of this on your site would be:
/* smaller screens */
@media only screen and (min-width: 320px) {
    #menu-item-4025 a {
        ...
        background-position: top center;
        background-size: 70% 70%;
        background-repeat: no-repeat;
        background-color: #FFF;
    }
}
/* larger screens */
@media only screen and (min-width: 768px) {
    #menu-item-4025 a {
        ...
        background-size: 100% 100%;
        ...
    }
}

Note you'll need to change the 320px/768px break points based on your current media queries, but that should get you started.
Comment: Any explanation for the downvotes? This solves the problem described without getting the OP to rewrite their code. Of course I might code it differently using an img instead of background image etc. but that wasn't the question.
Comment: Thanks DAC84. I understand why the others mentioned I should use an img instead of background image but this seems like a fairly easy workaround (that's how I ended up with the background image in the first place- fast, easy, and I could make it work). I know that's not always the *best* solution, but I'm new to all this...! Learning as I go.

Resize logo in nav bar on mobile


Show that , for all $(s_{0},t_{0})\in [0,1]\times [0,a]$, the curves $s\to f(s,t_{0})$, $t\to f(s_{0},t)$ are orthogonals.

Question:
Let $f:[0,1]\times [0,a]\to M$ a parameterized surface such that for all $t_{0}\in[0,a]$, the curve $s\to f(s,t_{0})$, $s\in [0,1]$, is a parameterized geodesic by arc lenght , orthogonal to the curve $t\to f(0,t)$, $t\in[0,a]$, in the point $f(0,t_{0})$.
Show that , for all $(s_{0},t_{0})\in [0,1]\times [0,a]$, the curves $s\to f(s,t_{0})$, $t\to f(s_{0},t)$ are orthogonals.

Take the derivate of $\left\langle \dfrac{\partial f}{\partial s},\dfrac{\partial f}{\partial t}\right\rangle$ in relation to $s$, for the vector field along the curve we have that
$$\dfrac{d}{ds}\left\langle \dfrac{\partial f}{\partial s},\dfrac{\partial f}{\partial t}\right\rangle=\left\langle\dfrac{D}{ds}\dfrac{\partial f}{\partial s},\dfrac{\partial f}{\partial t}\right\rangle+\left\langle \dfrac{\partial f}{\partial s},\dfrac{D}{ds}\dfrac{\partial f}{\partial t}\right\rangle$$ With $t\in I$. Morover is M is a differential manifold with a conection D simetric and a parameterized surface then, $$\dfrac{D}{\partial v}\dfrac{\partial s}{\partial u}=\dfrac{D}{\partial u}\dfrac{\partial s}{\partial v}$$ and by condition of geodesic $$\dfrac{D}{ds}\dfrac{\partial f}{\partial s}=0$$
Therefore $$\dfrac{d}{ds}\left\langle \dfrac{\partial f}{\partial s},\dfrac{\partial f}{\partial t}\right\rangle=\dfrac{1}{2}\dfrac{d}{dt}\left\langle \dfrac{\partial f}{\partial s},\dfrac{\partial f}{\partial s}\right\rangle=0$$
This is the idea of book, but I can not see how finishing the problem, thanks!
Answer: Actually it's a bit to easy for an answer so I do not know if I missed something.
From $\frac{d}{ds}\langle\frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\rangle = 0$ you know that $\langle\frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\rangle $ is constant in $s$. In addition you know $\langle\frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\rangle (0,t_0) = 0 $ for all $t_0 \in [0,a]$  from the orthogonality premise. From this it follows that $\langle\frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\rangle (s_0, t_0) = 0$ for all $(s_0, t_0) \in [0,1] \times [0,a]$ which is, what was asked.
Did you ask for explanations of the steps from the book?
Comment: why did this answer get a downvote? what is criticised?
Answer: You did everything correctly, but the last part you need is just an observation: we have the inner product $\left \langle \frac{\partial f}{\partial s}, \frac{\partial f}{\partial t} \right\rangle$ is independent of the parameter $s$, hence this inner product remains the same regardless of what value of $s$ we have inputted.  This means that all points $(s,t)$ we have
$$
\left\langle \frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\right\rangle_{f(s,t)} \;\; =\;\; \left\langle \frac{\partial f}{\partial s},\frac{\partial f}{\partial t}\right\rangle_{f(0,t)}\;\; =\;\;0
$$
where it was an assumption in the problem that these two vectors are taken to be orthogonal when $s=0$.
Comment: ...which is exactly @hase_olaf's answer posted 8 hours before yours. Why this greedy rush for bounties and reputation points?


Need guidance for Magento 1 Certification - Developer

Question: I need some suggestion and helpful Links to study and give practice test for Magento Certification
Comment: what kind of guidance ??
Comment: I want Tutorial and Study Material Links.
Comment: Along with Practice Papers Online link
Comment: http://magento.stackexchange.com/questions/81/studying-to-become-a-magento-certified-developer
Answer: You can take an example test set by Magestore by signing up here. Last time I used it it can track your progress, so everytime you take the test it stores your score so you can see if you are progressing your knowledge.
You can also read through the official Magento study guide which does give some example questions and tells you exactly what you will be tested on.
There are some exam sites which claim to have test papers but I think they are subscription and I'm not sure the legitimacy of the papers they have.
Comment: Thanks for the Info. I am giving tests on Magestore now . Please provide other links also.


$f(x)=x^3e^x, \; g(x)=\exp(x^{999}) ,\; h(x)=\frac{1}{2+\exp(i4x)}$. Computing $f^{(1000)}(x)$ ,$g^{(1000)}(0)$,$h'(x)$ without technology

Question: $f: \mathbb{R} \rightarrow \mathbb{R}$, $g: \mathbb{R} \rightarrow \mathbb{R}$, $h: \mathbb{R} \rightarrow \mathbb{C}$
$f(x)=x^3e^x, \; g(x)=\exp(x^{999}) ,\; h(x)=\frac{1}{2+\exp(i4x)}$
Are there some efficient way to compute (without using technology):
$f^{(1000)}(x)=$
$g^{(1000)}(0)=$
$h'(x)=$
Comment: What patterns did you observe when you computed the first few derivatives of the functions $f$, $g$, and $h$?
Comment: What is technology? Machines?
Answer: If without using technology means just computation by hand, this is the solution:

Using $(uv)^{(n)}(x) = \sum_{k=0}^nC^n_k u^{(n-k)}(x)v^{(k)}(x)$, only a few terms survive,$f^{(1000)}(x)=997002000 e^x+2997000x e^x  +3000 x^2 e^x +x^3e^x$
Since $g(x)=\exp(x^{999}) = \sum_{n=0} \frac{x^{999n}}{n!}$, there is no $x^{1000}$ term, so $g^{(1000)}(0)=0$
This one is too easy, you can figure it out.


Intercept files deleting in Android OS

Question: I need to know when a file is deleted from an android device, is it possibile? Are there some intents about the request to delete a file from device or SD?
Answer: You can register a file observer for files in some locations (though I've heard rumors this may not work for the simulated "external storage" on some recent versions).
But there is no way to "intercept" as in prevent such deletion, short of modifying the installation of android.
If the file is readable to your app, you could presumably make a backup copy ahead of time.
Comment: My idea was to develope a sort of recycle bin where to copy deleted files. But I think it is not possible...

Intercept files deleting in Android OS


Google Chrome Push Notifications not working if the browser is closed?

Question: It is written here that the push notifications will work even if the browser is closed, but I tested it and it is not the case. I receive push-notifications only if the browser is open (doesnt matter if the particular webpage is open or not).
I tested this on chrome for Desktop & chrome for Android (after updating to latest version).
my question is :-  For push notifications to work should the browser be open?
Note:- I used this for testing.
Comment: The other comments suggest that on Android, Chrome and Firefox will show push notifications even if the browsers are closed, but in my experience what can happen is that the notifications will arrive, but only appear once the browser is reopened (Chrome for Android 80, Firefox for Android 68). Certainly doesn't seem reliable.
Comment: I have tested the link you provided and it works well. Tested by opening the website, allowing for push notifications, closing Chrome and then triggering a push request using curl.
Comment: @KevinFarrugia on which platform did you test? I had tested on windows 10 and Android M. For me it didnt work when the browser was closed.
Comment: Tested on Android M
Comment: Well, it seems the situation is same for most platforms. On mobile devices, android, no requirement for browser to be open to receive push notificaitons, but on desktop oss a running browser is necessary.
It would be great if on desktop oss, and others, too the reception of the push messages could be handled by a platform's own service related to background tasks or push notifications jobs then handed to web service workers (waking them up if needed) so that we don't need a running browser at that time. It is the case in android via Google Play Services, afaik.
Answer: According to Can I Use, Chrome and Firefox desktop browsers require the browser to be running for receiving push notifications; mobile browsers typically don't.
Comment: Same is the case for Microsoft Edge (Chromium based) on the desktop.
Answer: Open Settings (in chrome)
Do the following:
> advanced
    > system >
        "continue running background apps when chrome is closed"
             >enable

Answer: On desktop, browsers need a process running. For example on Mac OS X the browser can have no window open but if you look at the dock, the light underneath icon can be glowing (meaning it has a process running). In the scenario you should receive push messages.
If the browser was completely quit, then push messages won't get through.
The same applies to windows and Linux.
On android you should be receiving the messages regardless of whether the browser is open or not. This is in part (as far as I know) to the fact that android manages it's connection to the push service rather than the browser, so it'll receive messages whenever possible.
Comment: I believe this is still the case yes.
Comment: thanks Matt for the answer and Push notification online demos ...Is this still applied for 2019?
Answer: The messages should (eventually) get through even if they are sent while the browser is closed, or the device is offline, etc. (And this works for me using https://gauntface.github.io/simple-push-demo/ and other tests.)
Comment: thx, I can confirm this works with Chrome 85.  The (previously sent) notification will be delivered when the browser is started or reconnected to the network.
Answer: I've worked on demo to provide push notifications on Google Chrome and Firefox. Demo -> https://twitter.com/d_danailov/status/1163824171480166400
If someone has a question could ping me on twitter.
The public URL: https://push-notifications-ddanailov.firebaseapp.com/
Repo: https://github.com/dimitardanailov/push-notifications
Comment: Hello Sir, Does this send notifications even if browser closed?
Comment: Please use the demo project to test my setup. I've worked on this project before 3.5 years. I'm almost sure: The notification must be displayed on the notification section of your Mac / Windows or Linux workstation.
Answer: On desktop the browser needs to be running since that is the process that receives the push messages. Some extensions, like hangouts force the browser to keep running even when the last tab is closed so for users with one such extension installed push will work all the time.
On Android, the browser does not need to be running since the entity in charge of receiving the messages is baked into Google Play Services.
The Chrome team is working on the desktop issue in https://bugs.chromium.org/p/chromium/issues/detail?id=402456
Answer: It is possible to write Chrome extension where background script can run if Chrome is allowed to run in the background (configurable in settings). It can also use GCM.
EDIT:
For service worker to run in the background even if no tab or window is opened there must be at least one Chrome extension with background permissions installed and Chrome must be allowed to run apps in background. Tested on Linux.
Answer: Yes, the other users are right and there is no way to receive them on Windows if the browser is closed unless the browser is running in the background, which some Chrome Apps and Extensions can force. I ran into this recently and found this extension, which I believe may help. It keeps the browser running in the background even if the windows are closed but does not do anything besides that (it is open source and presumably the version uploaded to the Chrome Store matches that version)
https://chrome.google.com/webstore/detail/lightning-reopen/ahphokgmcecbjeipkfkamcdmemghkaph


Click event on element

Question: How to find out which element is clicked in jointjs. I want to create a clone of element which is double clicked.
I tried this:
paper.on('cell:pointerdblclick', function (cellView, evt, x, y) {
                    var rect = new joint.shapes.devs.Model({
                        position: {x: 100, y: 50},
                        size: {width: 51, height: 41},
                        outPorts: [''],
                        attrs: {
                            '.label': {text: '', 'ref-x': .4, 'ref-y': .2},
                            rect: {fill: 'white'},
                            '.outPorts circle': {fill: 'white', stroke: 'black'},
                            '.port-body': {r: 5}
                        }
                    });
                    graph.addCell(rect);
                });

But the above creates a clone when double clicked on any of the element on paper.
Answer: The clicked element is retrievable via cellView in the modelattribute.
Here's a sample of what you are trying to do :
  paper.on('cell:pointerdblclick', function (cellView, evt, x, y) {
    //clone cell and add it to graph
    graph.addCell(cellView.model.clone());
  });

Via cellView.model you can check which element is clicked by checking its properties via prop and decide if you clone the element.

Click event on element


How do I over-ride the alpha settings on the createJS Container children?

Question: I am using createJS and have constructed a Container containing two bitmaps
var content = new createjs.Container();
content.addChild(bkground, foreground);
if I set content.alpha = 0.5 I can see part of the bkground through the foreground item.
How do I over-ride the alpha settings on the createJS Container children?
I hope that makes some sense?
Cheers Andy
I have tried some of the options you can set on Container but nothing seems to work
Answer: The alpha of a container is imposed on its children, and so on down the tree. A child can't override its container's alpha, or more precisely its containers' alphas. A child's alpha is the product of its alpha and all of its parents' alphas.
So, if the parent has a .5 alpha, all of its children (and the children's children) will have their alphas forcibly reduced by 50%. If, for example, a child itself had a .5 alpha and was in a parent also with a .5 alpha, the child would would appear on the stage as .25 alpha. You must multiply all the alphas from the display object up to the stage to get the representative alpha.


Operator norm of $\frac{x^TW^Tx\cdot I-Wxx^T}{||Wx||^2}$.

Question: Let $x\in S^{d}=\{x\in \mathbb{R}^d \mid \| x\|=1\}$ and $W\in\mathbb{R}^{d\times d}$ how tight can we bound $\sigma_{\max} \left(\frac{x^TW^Tx\cdot I-Wxx^T}{||Wx||^2}\right)$ with respect to $\lambda_\min(W)$ and $\lambda_{max}(W)$?
Answer: Operator norm is infinite. Take $W$ such that $\|W\|=1$ and $x$ is the right eigenvector with eigenvalue $\lambda<1$
$$Wx=\lambda x$$
Applying operator gives you the following matrix with norm $1/\lambda$
$$\frac{I-xx'}{\lambda}$$
Comment: Correct. That said, I am looking for bounds on $\sigma_{max}$ that are allowed to depend on $\lambda(W)$. So while $\sigma_{max}$ is unbounded as $\lambda\rightarrow 0$, I am uncertain this argument shows $\sigma_{max}$ is unbounded as a function of $\lambda$. I updated the question to clarify this, sorry for the inconvenience.
Comment: For example, in the case where $||W||=1$ and $x$ is a right eigenvector with eigenvalue $\lambda<1$, we get that if $\lambda_{min}(W)>1/2$ applying the operator gives us a matrix with operator norm $> 2$. I am uncertain whether this special case of eigenvector caries over to the general case of any $x$.
Comment: You could bound lambda_min from below, (which makes it weird to call it an "operator norm" since it makes W's not closed under scalar multiplication, see 2.5.2 of Bhatia's http://www.cmat.edu.uy/~lessa/tesis/Positive%20Definite%20Matrices.pdf). In such case take W with lambda_min's eigenvector corresponding to x.


aggregate() error in seq.default

Question: I new with R. I am trying to aggregate data in 5 minutes blocks. I would like to have the open, the close,the high,the low, and the total Size. I have added the highfrequency package, along with zoo package and xts package.
I am following the tutorial (section 3.2) from the people who create the package from this link:
http://highfrequency.herokuapp.com/
Here is the error I get:
Error in seq.default(start(ts), end(ts), by = tby) :
'from' must be of length 1

Here is a sample of the data I am using . The file is much bigger, but I don't know how to attach it to my post:
Date,Time,Price,Size
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:13,49.6,200
02/18/2014,05:06:14,49.6,200
02/18/2014,05:06:14,49.6,193
02/18/2014,05:44:41,49.62,100
02/18/2014,06:26:36,49.52,100
02/18/2014,06:26:36,49.52,500
02/18/2014,07:09:29,49.6,100
02/18/2014,07:56:40,49.56,300
02/18/2014,07:56:40,49.55,400
02/18/2014,07:56:41,49.54,200
02/18/2014,07:56:43,49.55,100
02/18/2014,07:56:43,49.55,100
02/18/2014,07:56:50,49.55,100
02/18/2014,07:57:12,49.53,100
02/18/2014,07:57:12,49.51,2200
02/18/2014,07:57:12,49.51,100
02/18/2014,07:57:12,49.5,200

here is my code:
library(highfrequency)
data1<-read.table("C_0.txt",sep=",",header=T,stringsAsFactors=F)
ts=data1$Price
tsagg5min=aggregatets(ts,on="minutes",k=5)

Do you have a suggestion on how I can achieve my aim with very large data set?
I run a windows 8 64 bit machine.
Thank you for you help.
Answer: You can use split, cut, and strptime to cut the data into 5 minute intervals.  Assuming dat is your data,
> x <- split(dat, cut(strptime(dat$Time, format="%R"),"5 mins"))
> x
$`2014-02-27 05:06:00`
        Date     Time Price Size
1 02/18/2014 05:06:13  49.6  200
2 02/18/2014 05:06:13  49.6  200
3 02/18/2014 05:06:13  49.6  200
4 02/18/2014 05:06:14  49.6  200
5 02/18/2014 05:06:14  49.6  193

...
...
...

$`2014-02-27 07:56:00`
         Date     Time Price Size
10 02/18/2014 07:56:40 49.56  300
11 02/18/2014 07:56:40 49.55  400
12 02/18/2014 07:56:41 49.54  200
13 02/18/2014 07:56:43 49.55  100
14 02/18/2014 07:56:43 49.55  100
15 02/18/2014 07:56:50 49.55  100
16 02/18/2014 07:57:12 49.53  100
17 02/18/2014 07:57:12 49.51 2200
18 02/18/2014 07:57:12 49.51  100
19 02/18/2014 07:57:12 49.50  200

Remove the empty time blocks,
x <- x[sapply(x, dim)[1,] != 0]

Get the high Price
> sapply(x, function(y) max(y$Price))
2014-02-27 05:06:00 2014-02-27 05:41:00 2014-02-27 06:26:00 2014-02-27 07:06:00
              49.60               49.62               49.52               49.60
2014-02-27 07:56:00
              49.56

Get the low Price
> sapply(x, function(y) min(y$Price))
2014-02-27 05:06:00 2014-02-27 05:41:00 2014-02-27 06:26:00 2014-02-27 07:06:00
              49.60               49.62               49.52               49.60
2014-02-27 07:56:00
              49.50

Get the total Size
> sapply(x, function(y) sum(y$Size))
2014-02-27 05:06:00 2014-02-27 05:41:00 2014-02-27 06:26:00 2014-02-27 07:06:00
                993                 100                 600                 100
2014-02-27 07:56:00
               3800

aggregate() error in seq.default


Real Analysis vs. Functional Analysis version of Arzela-Ascoli Theorem

Question: Consider a collection of functions defined on a compact set such that they are uniformly bounded and equicontinuous. Then
1) Real analysis version: Every sequence in that collection will contain a uniformly convergent subsequence
2) Functional analysis version: The collection is relatively compact i.e. its closure is compact. i.e. any sequence in its "closure" will have a uniformly convergent subsequence in the "closure".
Which one is the correct statement ? Or, I may be missing something trivial.
Comment: Could you edit with the definite statements for both $1$ and $2$?
Comment: @Aram: "definite statement" ??
Comment: Statements of the theorems...
Comment: @Aram: Modified a bit. I think the first one is much stronger. But, I am confused about how they are equivalent. In general functional analysis version should be stronger.
Comment: in the 'real analysis version', the limit of the subsequence is not necessarily an element of the collection but of its closure.
Comment: @daw: I am not at all bothered about where the limit lies at all, the question is only where the uniformly convergent subsequence lies.
Answer: The usual statement of the Arzela-Ascoli theorem is closer to the "functional analysis version", except that there's no "pointwise convergent" (which doesn't make sense for a set) and the set is assumed to be equicontinuous.
EDIT: Given the "real analysis version", the "functional analysis version" can be deduced as follows.  Suppose $S$ is a set of functions on $X$ that are uniformly bounded and equicontinuous: there is $B$ such that $|f(x)| \le B$ for all $f \in S$ and $x \in X$, and for every $\epsilon > 0$ and $x \in X$ there is a neighbourhood $U$ of $x$ such that $|f(x) - f(y)| < \epsilon$ for all $y \in U$ and all $f \in S$. Let $\overline{S}$ be the uniform closure of $S$.  Then I claim $\overline{S}$ is also uniformly bounded and equicontinuous, so applying the "real analysis version" to it we can conclude that any sequence in $\overline{S}$ has a uniformly convergent subsequence.
In fact, take any $\widetilde{B} > B$.  For any $g \in \overline{S}$, there is
$f \in S$ with $|g - f| < \widetilde{B} - B$ everywhere, and then
$|g(x)| \le |g(x) - f(x)| + |f(x)| \le B$.  Similarly, given $x\in X$ and $\epsilon > 0$, take $0 < \eta < \epsilon$ and neighbourhood $U$ of $x$
such that $|f(x) - f(y)| < \eta$ for $y \in U$ and $f \in S$.  Given $g \in \overline{S}$, take $f$ so $|g - f| < (\epsilon - \eta)/2$, and we find that
for $y \in U$,
$$ |g(x) - g(y)| \le |g(x) - f(x)| + |f(x) - f(y)| + |f(y) - g(y)| < \epsilon $$
Comment: A set is contained in its closure, so I do not understand your qualifier "only talks about closure".
Comment: What do you mean?  Since every member of set $S$ is contained in the closure of $S$, every property that is true for all members of the closure is true for all members of $S$.
Comment: A subsequence is a subset.  If members of the original sequence are in $A$, the members of the subsequence is also in $A$.
Comment: @RobertIsrael: Sorry, i wrote it wrongly. I did not want to mean that. 2) -> 1) proof is obvious. To prove 1) -> 2) suppose we take a sequence in closure, then if it contains only finite number of elements from the original set, then what to do ? How do I prove that this sequence has a convergent subsequence. My main confusion is the presence of "closure" in 2) but not in 1). Hope I have made my point clear.


Unit testing Azure table storage classes

Question: I have been trying to find if i can easily isolate and test azure table storage dependencies but to to no avail. I believe its really difficult to mock/fake ATS dependencies. I am surprised at how the Azure team  could ignore this in the age of TDD/BDD etc. Or is it am i missing something? From my undersntanding it has very minimal interface/abstract classes which make isolating them difficult.
Answer: You typically should be mocking repositories that retrieve or persist data.  These can be mocked quiet easily.  Why are you trying to mock the ATS dependencies themselves?
Furthermore, TableServiceEntity is not required to be inherited from.  Feel free to implement your own interface instead - if for some reason you need to mock entities themselves.
Comment: I agree. But then don't you ever write unit test cases for repositories? So when try to write unit test cases for repositories how do you isolate ATS dependencies?I am trying to find out how people go about unit testing ATS. But i believe that every piece of code that you write has to be unit tested including repositories?Do you disagree?
Comment: I typically choose to NOT put business logic into repositories, so I don't have my teams unit test repositories themselves, only their consumers.  IMHO, this is one of the core reasons for having repositories - so that they can be mocked.


como Preencher um DropDownListFor

Question: Alguém poderia me ajudar como faço para preencher um DropDownListFor?
Antes estava fazendo dessa forma:
@Html.DropDownList("lstAffiliate", string.Empty);

Mas vi que não era recomendado, ai decidi fazer com o ListFor.
Tenho o meu controller onde recebo a lista pronta e repasso para a PartialView:
public ActionResult ComboAffiliate()
{
    FilterAffiliate Affiliate = new FilterAffiliate();
    List<SelectListItem> model = Affiliate.filterAffiliate();

    return PartialView(model);
}

para esta Partial
@model  IBS_WEB.Models.Filters.FilterAffiliate

@Html.DropDownListFor(model => model.CD_AFFILIATE, Model.?, new { @class ="ComboWidth" })

Como eu faço para listar nesse DropDownListFor?
Answer: Olá,
Basicamente para a criação de um DropDownListFor você vai precisar declarar os parâmetros abaixo
@Html.DropDownListFor(, )
Model:
public class Veiculo
{
    public int ID { get; set; }
    public string Tipo { get; set; }
    public int idModeloVeiculo { get; set; }
}

public class ModeloVeiculo
{
    public int ID { get; set; }
    public string Descricao { get; set; }
}

Action MVC :
[Controller]
ViewData["idModeloVeiculo"] = new SelectList(contexto.ModeloVeiculos.toList(),"ID","Descricao");

HTML :
@model Veiculo

@Html.DropDownListFor(m => m.idModeloVeiculo , null)

Conforme podemos ver a View é fortemente tipada para a classe "Veiculo" que possui o atributo "idModeloVeiculo" do tipo inteiro. No momento que criamos uma ViewData na controller com o mesmo nome do atributo :
[Controller]
ViewData["idModeloVeiculo"] = new SelectList(contexto.ModeloVeiculos.toList(),"ID","Descricao");

Automaticamente o .Net verifica que será utilizada a ViewData "idModeloVeiculo"
//Na verdade "m.idModeloVeiculo" é ViewData "idModeloVeiculo"
@Html.DropDownListFor(m => m.idModeloVeiculo , null)

Então altere seu código da seguinte forma :
public ActionResult ComboAffiliate()
    {
        FilterAffiliate Affiliate = new FilterAffiliate();
        List<SelectListItem> model = Affiliate.filterAffiliate();

ViewData["Combo"] = new SelectList(Affiliate.filterAffiliate().ToList(),"ID","Descricao");
        return PartialView(model);
    }

Partial :
@model  IBS_WEB.Models.Filters.FilterAffiliate

@Html.DropDownListFor(model => model.CD_AFFILIATE, ViewData["Combo"] ,new { @class ="ComboWidth" })

Segue links.
https://stackoverflow.com/questions/3057873/how-to-write-a-simple-html-dropdownlistfor
https://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example
Answer: Em @Html.DropDownListFor(model => model.CD_AFFILIATE, Model.?, new { @class ="ComboWidth" }) você quer preencher o Model.? com new SelectList().
Ou seja precisa dizer ao helper da dropdown como será montada a lista de seleção, usando o new SelectList.
Ex:
 @Html.DropDownList(
    "Teste",
    new SelectList(
        Model.Select(x => new { Value = x.CD_AFFILIATE, Text = x.SuaPropriedadeDeTexto}),
        "Value",
        "Text"
    )
)

Mas tenho a impressão que você será mais feliz, criando uma classe ViewModel com uma propriedade para guardar ou setar o Id selecionado na DropDown, e outra propriedade contendo o retorno de Affiliate.filterAffiliate()
Veja um exemplo que criei no .NET Fiddle https://dotnetfiddle.net/GQbcvs que pode lhe ser útil.
Comment: vou dar uma olhada aqui. vlw
Answer:     public class TipoVeiculo {
        public int Id { get; set; }
        public string Nome { get; set; }
    }

    public class Veiculo {
        public int Id { get; set; }
        public string Nome { get; set; }

        public int TipoVeiculoId { get; set; }
        public virtual TipoVeiculo { get; set; }
    }

    // No Controller
    [HttpGet]
    public ActionResult Add()
    {
        var tipos = new List<TipoVeiculo>{ new TipoVeiculo{ id = 1, Nome = "Moto", new TipoVeiculo{ id = 2, Nome = "Carro"} };
        ViewBag.Tipos = tipos;
        return View();
    }

    // Na View
    @Html.DropDownListFor(
    f => f.TipoVeiculoId,/*Qual atributo,*/
    new SelectList(
    ViewBag.Tipos,/*(fonte de dado,*/
    "Id",/*(Quem vai aparecer o campo value,*/
    "Nome"),/*quem vai aparecer de text),*/
    new { @class = "form-control" })/*atributos do select html*/

    // resumindo fica assim

    @Html.DropDownListFor(f => f.TipoVeiculoId, new SelectList(ViewBag.Tipos, "Id","Nome"), new { @class = "form-control" })

como Preencher um DropDownListFor


Passar ponteiro de sql.DB como parametro de método

Question: Tenho uma struct que possui um método save que recebe como parametro um ponteiro para o acesso ao banco;
func (c Call) Save(db *sql.DB) error {
    stmt, err := db.Prepare(`
        INSERT INTO calls values($1, $2, $3, $4)
    `)
    if err != nil {
        return err
    }
    // ...
}

porém quando passo o ponteiro como parametro um erro panic é exibido;

http: panic serving [::1]:51111: runtime error: invalid memory address or nil pointer dereference

a conexão é definida da seguinte maneira:
import (
    "database/sql"
    _ "github.com/lib/pq"
)

var db *sql.DB

func init() {
    db, _ := sql.Open("postgres", dsn)
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
}

A passagem do parametro ocorre assim:
err := c.Save(db)
// c é a struct que possui o método Save

Mesmo definindo no método que o parametro é um ponteiro esse erro de nil pointer acontece, porque?
Answer: Acredito que o problema seja a variável criada localmente. Você está fazendo algo assim:
package main
import "fmt"

var variavel *int

func init() {
    variavel, _ := new(int), new(int)
    fmt.Println("init:", variavel)
}

func main() {
    fmt.Println("main:", variavel)
}

O print será:
init: 0x416020
main: <nil>

Para corrigir você deve usar = ao invés de :=. Neste caso usar variavel, _ = new(int), new(int) resolveria.

Troque o db, _ := sql.Open("postgres", dsn) para db, _ = sql.Open("postgres", sn), assim você vai fazer com que o resultado fique na var db *sql.DB e não numa nova variável local do init():
import (
    "database/sql"
    _ "github.com/lib/pq"
)

var db *sql.DB

func init() {
    db, _ = sql.Open("postgres", dsn) // Usando = ao invés de :=
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
}

Uma outra solução é criar uma outra variável, como:
func init() {
    dbX, _ := sql.Open("postgres", dsn) // Use :=
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
    db = dbX // Agora seta o db como valor do dbX, criado acima.
}

Comment: o linter não deveria informar que existem 2 variáveis com o mesmo nome?


Django Contact form and sending confirmation on page

Question: I got one page. On the page is a contact form. After clicking the 'send' button I want to change the form containing div to 'thank you for mailing us' div. And stay at the same 'id' on the page.
One way to solve it is to put an another template and load it as 'success url' But this way the whole page is being loaded again and the user lands on top of the page without seeing the confirmation.
Is there a way not to load the page again and to change the div somehow? With jQuery for example? How to do it? Is there even an another way?
Would be great to have some hints. Many thanks in advance!
Comment: Ajax makes this pretty simple
Answer: Using Javascript is the easiest solution. Here is example for using AJAX with forms. Django can detect AJAX requests out of the box via request.is_ajax().
Another option would be to set cookie, redirect to the same url and handle the response differently (depending on given cookie), but that isn't elegant at all.


Query no firestore para verificar item dentro de um documento

Question: Estou usando o Firebase Firestore e estou precisando montar uma *query que verifique o seguinte dado conforme apontado na figura a seguir:

Por ele estar em um array, dentro do meu documento, não sei como montar a query.
Answer: Creio que o Firebase não tem capacidade para executar tal query.
No entanto, para resolver o problema, Sugiro que você crie uma coleção "Pessoas" na raíz e coloque lá esses mesmos atributos. Adicione também o atributo "idUsuario".
Assim, a sua query ficaria:
<code>db.collection("pessoas")
    .whereEqualTo("idUsuario", "Y1e8racPvbhr5RHuxkQv")
    .whereEqualTo("preso",true);
</code>
Comment: excelente ideia, kkkk valew


Sum of powers of 2.

Question: If a question asks what is the sum of all powers of 2... for example what is the sum of all powers of 2 that are less than 5 that are divisible by 2. This is silly example I know, but are they asking for the sum of the power eg in the set ${2^1; 2^2; 2^3}$ would the sum of powers of two be $1 +2 +3$ or $2+4+8$. Thanks.
EDIT this problem is about language not the actual numerical sum.
Comment: It was a silly example I made up quickly.
Answer: The powers of $2$ are $1, 2, 4, 8, 16$ and so on.
By inspection only the first few are less than $5$; namely $1,2,4$.
Only the last two of these are even and their sum is $2+4=6$.

Sum of powers of 2.


Probability of the sum of cards?

Question: The problem is basically as follows
There are four cards with points [1,2,3,4], every time I draw one card randomly and then put it back to the deck. As I keep drawing I record the sum of the points on the cards, I stop drawing if the sum is greater than or equal to five.
If the final points is equal to five, I win, otherwise I lose. What's the probability of me winning?

My attempt to solve this problem is, let $p_n$ be the probability of the sum EVER equal to $n$ after drawing enough number of times, specifically
$$p_1=\frac{1}{4} \text{ (draw 1 once)}$$
$$p_2=\frac{1}{4} + \frac{1}{4}p_1 \text{ (draw 2 once + draw 1 twice)} $$
$$p_3=\frac{1}{4} + \frac{1}{4}p_1 + \frac{1}{4}p_2 $$
$$p_4=\frac{1}{4} + \frac{1}{4}p_1 + \frac{1}{4}p_2 + \frac{1}{4}p_3 $$
then $p_5=\frac{1}{4}p_1 + \frac{1}{4}p_2 + \frac{1}{4}p_3 + \frac{1}{4}p_4 = 369/1024$ should be the probability of winning at five.
However I was told that the answer should be around 0.33 so I'm confused, is my answer correct?

Update
It turns out 0.33 (1/3) is the answer for sampling without replacement.
Comment: Let $p_n$ be the probability of win at the n-th draw. $p_2=\frac 14,  p_3=\frac 6{64}, p_4 = \frac 1{64}, p_5 = \frac 1{1024}$, $p(win)=\sum p_n = \frac {369}{1024}$. Proved your result from another aspect.
Comment: Your calculation appears to be correct.
Comment: I think 0.33 is also too high. Try a tree diagram. That helped me.
Answer: Whenever there are conflicting answers from combinatorial methods, I
like to simulate the result to see what happens.
My method of simulation (in R) is to sample five cards with replacement from among 1, 2, 3, 4. Then to take cumulative sums of the results to see if the total 5 is
present at any step. If so, that's a win. (Any cards drawn after a total of 5
are ignored.)
After a million iterations the vector w has a million
TRUEs and FALSEs. The mean of this logical vector is the proportion
of its TRUEs. With a million iterations this proportion should approximate
the probability of winning to at least two or three places.
It seems that
simulation results match $369/1024 = 0.3603516,$ the answer proposed in your
Question and computed in the Comment
of @a_statistician.
set.seed(1112);  m = 10^6;  deck = 1:4
w = replicate( m, 5 %in% cumsum(sample(deck,5, rep=T)) )
mean(w);  369/1024;  15/49
[1] 0.360286        # aprx P(Win) = 0.3604
[1] 0.3603516       # exact P(Win) = 369/1024
[1] 0.3061224       # 15/49

Answer: I think another way to approach this problem is to model the game as a Markov chain with the following transition probability matrix, $M$:
$$
\begin{matrix}
 & \text{From state} \\
\text{To state} &
{\begin{array}{r|ccccccc}
  & 0   & 1   & 2   & 3   & 4 & \text{win} & \text{lose} \\
\hline
0 & 0   & 0   & 0   & 0   & 0   & 0 & 0 \\
1 & 1/4 & 0   & 0   & 0   & 0   & 0 & 0 \\
2 & 1/4 & 1/4 & 0   & 0   & 0   & 0 & 0 \\
3 & 1/4 & 1/4 & 1/4 & 0   & 0   & 0 & 0 \\
4 & 1/4 & 1/4 & 1/4 & 1/4 & 0   & 0 & 0 \\
\text{win (5)} & 0   & 1/4 & 1/4 & 1/4 & 1/4 & 1 & 0 \\
\text{lose (5+)} & 0   & 0   & 1/4 & 2/4 & 3/4 & 0 & 1
\end{array}}
\end{matrix}
$$
Note that this is a reducible Markov chain: once we reach the win or lose state, we will be stuck there forever.
Our starting state is:
$$
v = {\begin{bmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0
\end{bmatrix}}^{\top}
$$
Since we know that the game will end after five draws at most, we can calculate the probability distribution over the states after five draws by  left multiplying $M$ with the initial state vector $v$ five times:
$$
M \times M \times M \times M \times M \times v
$$
Implementation in R:
library(expm)

M <- matrix(nrow = 7,
                            c(  0,   0,   0,   0,   0,   0,   0,
                              .25,   0,   0,   0,   0,   0,   0,
                              .25, .25,   0,   0,   0,   0,   0,
                              .25, .25, .25,   0,   0,   0,   0,
                              .25, .25, .25, .25,   0,   0,   0,
                                0, .25, .25, .25, .25,   1,   0,
                                0,   0, .25,  .5, .75,   0,   1),
                            byrow = T,
                            dimnames = list(c("0", "1", "2", "3", "4", "win", "lose"),
                                            c("0", "1", "2", "3", "4", "win", "lose")))

M %^% 5 %*% c(1, 0, 0, 0, 0, 0, 0)

Output:
          [,1]
0    0.0000000
1    0.0000000
2    0.0000000
3    0.0000000
4    0.0000000
win  0.3603516
lose 0.6396484

The probability for the win state is consistent with $\frac{369}{1024}$.

P.S. I do wonder though if there is a way to derive the distributions over the final states analytically without carrying out the matrix multiplications.

Probability of the sum of cards?


Get Entity ID when is saved

Question: I need to capture the entity_id when the entity is saved. The ID will process and insert in a custom field. I use hook_entity_presave(), but when is a new entity the ID is void.
Is there any way to capture the ID?
<code>/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_type = $entity->getEntityType()->id();
  if(($entity_type === 'node' || $entity_type === 'taxonomy_term')) {
    $entity->field_custom_token->value = _process_token($entity->id()); // if entity is new, the ID is Null :(
  }
}
</code>
Answer: Try changing your code to use hook_entity_insert which is run after the saving to the database:
 https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8.2.x
As the reason you can't get the entity ID in presave is because if its a new entity then the ID hasn't been generated by the autoincrement ID field in the database yet so an ID doesn't exist for it until it's saved for the first time

Get Entity ID when is saved


How can a XAML file be compiled into multiple projects in Visual Studio?

Question: I have 2 copies of a solution, each of which is compiled against a different version of the same 3rd party API and a different .NET framework version.

Solution A - compiled against v2012 of a 3rd party API and .NET 4.0
Solution B - compiled against v2011 of a 3rd party API and .NET 3.5

Solution A contains all the source files and Solution B links to these files (using "Add as Link" in Visual Studio).
Conditional compilation is used to include code that is specific to one solution or the other.
My solution contains some XAML (WPF Windows, User Controls & Resource Dictionaries).  Solution B links to these XAML files and compiles ok, but when I run it I get a Set property 'System.Windows.ResourceDictionary.Source' threw an exception exception.
I've Reflectored over both versions of the assembly and there are differences in the resource names.
For example, one project contains a Windows/MyWindow.xaml file and the compiled assembly from Solution A contains a windows/mywindow.baml resource, while in the assembly from Solution B the name of the resource is just mywindow.baml.
Is there a way to compile the same XAML file into multiple projects?
Answer: if you are on Windows7/Vista/2008 (not XP), maybe try using Windows link not a Visual Studio Link.
http://technet.microsoft.com/en-us/library/cc753194(v=ws.10).aspx
So with a Windows link, it is the same file on disk, but appear as separate files in each project directory. (Yes, changing the file in either location changes it in both locations because the file is really in one location with a pointer in two locations)


Using ASP.NET Charts in MVC

Question: I am able to build charts in MVC like below however the problem is I can't add colors, and do a lot of the fancy things that can be done in the ASP.NET chart control. Is there a way to do that with this Chart type or an alternative to doing this in MVC.
<code>public ActionResult GetRainfallChart()
{

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
            chartType: "bar",
            xValue: new[] { "Jan", "Feb", "Mar", "Apr", "May" },
            yValues: new[] { "40", "10", "20", "20", "10" })
        .AddTitle("Title")
        .Write();

    return null;
}
</code>
Comment: Use built-in javascript chart plugins. I believe there are many Jquery plugins for it. As for information, Webform is less likely to hold onto javascript than MVC. You will using javascript more in MVC due to its response-request pattern
Answer: If you want to use the ASP.NET chart control then perhaps you can add a Web Forms page (or pages as per your app design etc) to your project. Web Forms and MVC should be able to co-exist and there should be quite a few blog posts, SO questions etc around it too. It may also be possible to have a Web Forms control on the same page but I have never tried it myself so can't comment 100%.
The alternative may be to use a JavaScript based graphing library like flot (http://www.flotcharts.org/). So what you would do there is something like:

Have your controller gather (or coordinate the gathering of) all the appropriate data for the graph
Render or otherwise place the data into your view
Render using flot (flot also requires JQuery but that shouldn't be a problem)

I just mention flot because it's one I know about; my personal experience is that it can be a little hard to get into so YMMV.
HTH though, Nathan.

Using ASP.NET Charts in MVC


Magnitude of n-th factorial

Question: In connection with a riddle on The Riddler, I would like to know how to evaluate even crudely the order of magnitude of an iterated factorial like
$$(\ldots(9\underbrace{!)!\ldots)!}_{n\text{ factorials}}$$
Using Stirling's approximation does not get me very far:
\begin{align*}
9! &\approx 3^9\\
(9!)! &\approx (3^9/3)^{3^9}=3^{8\times 3^9}\\
&...
\end{align*}
Comment: [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling's_approximation) will allow you to approximate it as a powertower
Comment: Similar, but way overkill: http://googology.wikia.com/wiki/Tripent
Answer: First, let me explain why the numbers in a power tower don't matter.  Let us compare these two:
$$3^{5^{5^5}}=10^{10^{10^a}}$$
$$5^{50\times5^{5^5}}=10^{10^{10^b}}$$
Clearly, we will have $a<b$, but by how much?  Well, take the log of each thrice, and you will find that
$$a\approx2.7$$
$$b\approx2.7$$
Indeed, the only things that truly matters is how tall the power towers are, which is why may use a crude Stirling approximation:
$$k!\approx k^k$$
Also, a quick symbolization:
$$k!_n=k\underbrace{!!!!\dots~ !}_n$$
And furthermore,
$$k!_n\approx k^{k^{k^{\dots}}}\bigg\}(n+1)\text{ powers}$$
In terms of Knuth's up-arrow notation:
$$k!_n\approx k\uparrow\uparrow(n+1)$$
Comment: Yes, the difference of a few numbers do not really matter when placed in the right places.
Comment: Depends what your doing with the number.  If you need closer approximation for tighter bounds, then sure.
Comment: Indeed, I had started to realise the additional factors did not matter so much and hence the very first approximation I thought of $9^{9^{9^\vdots}}$ was given a first order solution!
Comment: I am not sure how much it matters but a closer approximation is$$9\underbrace{!...!}_{n\text{ times}}=\underbrace{3^{3^{\vdots^{3^9}}}}_{n\ 3's}$$

Magnitude of n-th factorial