Problems with Apostol's calculus

Question: I am self teaching myself so I couldn't ask any teacher but here are somethings in Chapter 1 that I can't understand. In the book Area is defined axiomatically but some parts of it are not just making sense.

We assume there exists a class $M$ of measurable sets in the plane and a set function whose domain is $M$. -
Chapter 1,page 58

First, what does he mean by sets in a plane? Does the set themselves hold some geometric properties? Because till now I have always encountered sets having numbers and ordered pairs as elements.
And in the axiom regarding congruence of sets in plane(?), he defines congruence as one-one correspondence between points (elements?) of set such that distances are preserved.
Again what does he mean by distance and how does that make sense if a set have just numbers as elements?
These are probably very poor question but I would really like some help.
Thanks
Comment: "Sets in the plane"= subsets of $\;\Bbb R^2\;$ , which of course are sets whose elements are ordered pairs. Perhaps you should mull over studying a good introductory book/course in set theory before attempting to study these things.
Answer:
We assume there exists a class $M$ of measurable sets in the plane and a set function whose domain is $M$

Here, every member of $M$ is a subset of the plane $\Bbb R^2$, the set of ordered pairs of real numbers. Every $X\in M$ is a set of ordered pairs of reals: $X\subseteq \Bbb R^2$.
Disclaimer: I don't have a copy of Apostol's classic at hand.
If he doesn't define "measurable" by page 58, I'm sure he does somewhere, perhaps in an appendix. At very least you should assume that $M$ contains all basic geometric shapes (in all rotations and orientations, at all possible offsets): anything you intuitively thing of as having an "area". $M$ will also contain all finite unions of such shapes (and more still, but this is enough to think about now).
The measure $m(X)$ of a measurable set $X\in M$ is, roughly speaking, its area: whenever $X$ is a shape that has an area in the usual/intuitive sense, $m(X)$ will be that number, a nonnegative real. Thus, measure is a function $m\colon M \to \Bbb R_{\ge 0}$.
I expect that $M$ contains still more subsets of the plane than those mentioned, for example many countable unions of basic shapes. The measure of a more general "measurable set" is defined by approximating the set with unions of more basic shapes and summing their areas.

You relate that Apostol defines a congruence to be a 1-1 function of the underlying space — the plane $\Bbb R^2$, for example, or any $\Bbb R^n$ — which preserves the distance between points. "distance" is just that: the Euclidean distance you know, such as
$$d((x,y), (u,v)) = \sqrt{(x-u)^2 + (y-v)^2}
$$
in $\Bbb R^2$. In $\Bbb R$ (i.e. $\Bbb R^1$), the distance between reals $x$ and $u$ is just $\lvert x - u\rvert = \sqrt{(x-u)^2}$.
Thus, $\, f\colon \Bbb R^2 \to \Bbb R^2$ is a congruence iff $f$ is 1-to-1 and
$$d(f(x,y), f(u,v)) = d((x,y), (u,v))\qquad\text{for all $(x,y), (u,v) \in \Bbb R^2$}.
$$
Comment: Thank you. This answers a lot but I still have one questions left. You say $M$ contains all basic geometric shapes if plotted on a $X-Y plane$ but I can't figure out how a finite set of ordered pairs can form a closed figure with an area as any finite set of ordered reals can always be represented by straight lines. So all of $X\subseteq \mathbb{R}^{2}$ which are measurable must have infinite elements. Am I correct?
Comment: That's right: the elements of $M$ are **not** finite, except for "degenerate cases". Each contains not just the the boundary of a "basic shape" *but also* the interior of the shape. (A set consisting of a single point, a *singleton* $\{\bf p\}$, is "degenerate": it's a square whose lower left corner is $\bf p$ and whose sides have length $0$; its area is $0$. Any finite set of points is a finite unions of singletons, and its area/measure is also $0$.)

Problems with Apostol's calculus


Java/Flex ORM/DTO Generation Tool

Question: Is there a tool out there that I can point at a Java DTO (Data Transfer Object) and it generates a corresponding Flex/AS Domain Object? Vise-Versa?
I'm using BlazeDS for my DataService over an AMF line.
Thanks.
Answer: Granite Data Services has a tool called GAS which will generate the DTO's for you:
http://www.graniteds.org/confluence/display/DOC/2.+Gas3+Code+Generator
Comment: I have heard some one tell me about this before.  I just could not find it on google for the life of me.
Answer: Check out this AIR app for blazeDS
http://sujitreddyg.wordpress.com/2009/05/07/blazemonster/
Comment: I took a look at this and it looks great, but it doesn't work connections over SSL.
Answer: You can manually write code to map Java DTO to AS classes, but there is no tool as such that is robust.

Java/Flex ORM/DTO Generation Tool


General coders/decoders for IID sources

Question: I'm trying to understand the following theorem and its proof:

It's taken from the MIT course. Here is my understanding of the theorem: Fix the integer $n\ge 1$. We want to compute $$\text{Pr}\{D_n\le n[H[X]-\nu]\}$$Because $D_n$ is a natural number, this probability is same as $$\text{Pr}\{D_n\le \lfloor n[H[X]-\nu]\rfloor\}$$ Now let $m = \lfloor n[H[X]-\nu]\rfloor$. Since $n$ is fixed, $m$ is also determined and fixed. So the probability of interest is $$\text{Pr}\{D_n\le m\}$$ In words, we want to compute the probability that the number of bits at which the decoder can correctly decode $X_1,X_2,\dots,X_n$ is less than or equal $m$. The randomness of $D_n$ comes from the fact that $X_1,X_2,\dots,X_n$ is random and each different sequence $x_1,x_2,\dots,x_n$ leads to different value for $D_n$. If the sequence of RVs is determined, then $D_n$ is determined. So we should compute the probability of occurring certain sequences. The length of encoded binary strings for these sequences should be less than or equal $m$. Is my understanding correct? Assuming that this understanding is correct, I can't follow the proof because the decoder seems to have no role here. We should only be concerned with the binary strings that encoder generates.
Answer: That is correct since you are defining the decoder based only on how it performs on input strings. This is an abstract decoder to demonstrate what performance is possible via probabilistic bounds and relate its performance to entropy.
Its or other decoders' efficient practical implementation is another matter, especially for large blocklengths. That topic would normally be covered later on in the course or in a course on digital communications or coding theory.
If you approach the decoder design problem from a probabilistic point of view you study LDPCs, Polar Codes, Convolutional Codes.
If you approach the problem algebraically, the codes are Hamming Codes, Reed Solomon Codes, Reed Muller codes.
For modern channels, especially over wireless with fading and moving transmitter/receiver, the probabilistic approach dominates.
For more stationary channels [e.g., satellite communications, or storage channels] the algebraic codes play a larger part.
Comment: Thanks for the answer. So how does the assumption that "decoder decisions are final" come into the picture? Also I don't understand how the upper bound for the probability of occurring binary strings with length less than or equal $m$ is derived.

General coders/decoders for IID sources


Identifying a particular function of a multifunction input device using evdev

Question: I have some Python code that interacts with a wireless USB numeric keypad.  I'd like to be able to discover the device by name, but shows up as multiple input devices.  In /dev/input/by-id:
# ls -l /dev/input/by-id
total 0
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event1
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0

And using the evdev module:
>>> import evdev
>>> devices = [evdev.InputDevice(dev) for dev in evdev.list_devices()]
>>> for device in devices:
...   print(device.fn, device.name)
...
/dev/input/event1 MOSART Semi. 2.4G Keyboard Mouse
/dev/input/event0 MOSART Semi. 2.4G Keyboard Mouse

Obviously the kernel can distinguish the -kbd device from the -mouse device, but how do I make that determination in my code?  The solution I've come up with for now takes advantage of the fact that the "keyboard" device includes the KEY_KP... capabilities, so I can do this:
def is_keyboard(device):
    return evdev.ecodes.KEY_KP1 in device.capabilities()[evdev.ecodes.EV_KEY]

...but that seems more of a heuristic than a reliable test.  Is there a way to detect, using the evdev module or an alternative, whether or not a given input device is a keyboard or a mouse (or some frankenstein-like combination of the two)?
Answer: It seems no way to directly identify if a given input device is a keyboard or a mouse in evdev. But you can use subprocess as an alternative.
import subprocess

process = subprocess.run("ls -l /dev/input/by-id", shell=True, stdout=subprocess.PIPE)
devices = process.stdout.decode().split("\n")[1:-1]

Then you can get a list like:
[
    "lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0",
    "lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event1",
    "lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0"
]


How to store stream result into multiple lists or maps

Question: Is there any better way to do this? Note that the code below is working.
List<Object1> details1 = new ArrayList<>();
List<Object2> details2 = new ArrayList<>();
List<Object3> details3 = new ArrayList<>();
endPointList.parallelStream().forEach(endPoint -> {
details1.addAll(ConfigHelper.getConfig1(endPoint));
details2.addAll(ConfigHelper.getConfig2(endPoint));
details3.addAll(ConfigHelper.getConfig3(endPoint));
});

Comment: @RiteshChouhan Never write into a non-thread-safe data structure (like `ArrayList`) from inside a parallel stream.
Comment: suppose this [post](http://javarevisited.blogspot.com/2015/03/5-ways-to-convert-java-8-stream-to-list.html) has many approaches to your issue.
Comment: No, they all are story into one list only, but in my issue I have to multiple list.
Comment: So the code above works, you just want to know if there's a better way to accomplish the same thing?
Comment: Who would upvote this?  There's no explicit question here because we have no idea what data types any of the variables are.
Comment: Do you always have 3 lists? Also, using a parallel stream along with an `ArrayList` will lead to nasty errors, as stated in the previous comment.
Answer: I do not think that there is a built-in way to do this. But if you have to do it very often, it might be worth writing your own Collector. This will not make it shorter, but it will look more like other collectors when using it.
public static class ConfigCollector implements Collector<EndPoint, ConfigCollector, ConfigCollector>
{
    List<Config1> config1s = new CopyOnWriteArrayList<>();
    List<Config2> config2s = new CopyOnWriteArrayList<>();
    List<Config3> config3s = new CopyOnWriteArrayList<>();

    public List<Config1> getConfig1s() { return config1s; }
    public List<Config2> getConfig2s() { return config2s; }
    public List<Config3> getConfig3s() { return config3s; }

    @Override
    public BiConsumer<ConfigCollector, EndPoint> accumulator()
    {
        return (cc, e) -> {
            cc.config1s.addAll(ConfigHelper.getConfig1(endPoint));
            cc.config2s.addAll(ConfigHelper.getConfig2(endPoint));
            cc.config3s.addAll(ConfigHelper.getConfig3(endPoint));
        };
    }

    @Override
    public Set<java.util.stream.Collector.Characteristics> characteristics()
    {
        HashSet<java.util.stream.Collector.Characteristics> set = new HashSet<>();
        set.add(Characteristics.IDENTITY_FINISH);
        set.add(Characteristics.UNORDERED);
        set.add(Characteristics.CONCURRENT);
        return set;
    }

    @Override
    public BinaryOperator<ConfigCollector> combiner()
    {
        return (cc1, cc2) -> {
            cc1.config1s.addAll(cc2.config1s);
            cc1.config2s.addAll(cc2.config2s);
            cc1.config3s.addAll(cc2.config3s);
            return cc1;
        };
    }

    @Override
    public Function<ConfigCollector, ConfigCollector> finisher()
    {
        return Function.identity();
    }

    @Override
    public Supplier<ConfigCollector> supplier()
    {
        return ConfigCollector::new;
    }
}

Using it like this:
ConfigCollector configs = endPointList.parallelStream().collect(new ConfigCollector());
configs.getConfig1s();
configs.getConfig2s();
configs.getConfig3s();

This will make it easier to deal with what the other commenters mentioned about concurrency (as you deal with it inside the collector instead of inside your business code). Maybe you have not run into this issue because your stream is small enough so that it has not done anything in paralllel yet.


How can I modify a page's HTML with AWS Cloudfront running a Lambda@Edge function?

Question: I'm running a CloudFront distribution, which has a Lambda@Edge function running on it.
I'd like to manipulate the DOM of the page that CloudFront is in front of. Specific example: add a custom script to the page inside the head.
On Cloudflare this can be done easily in a worker (roughly equivalent product) using their HTMLRewriter class.
How can I do this on AWS CloudFront?
My working theory is:

Observe the request for the HTML page
Do some kind of manipulation of the body of the response - parse it into the DOM object and manipulate as needed

I haven't managed to get this working yet. Interested in other approaches or if I'm missing something obvious.
Answer: Do a replace on the body of the request where uri === '/', to modify the string of HTML.
I tried that and it works fine.
The request where uri === '/' should be the request for the HTML page.
So in my specific case, I simply did a replace on the body of that request (which is stringified HTML):
body.replace(
      `</head>`,
      `</head>`
    )

And this worked.
You could also bring in some kind of DOM-parsing library to do this kind of manipulation in a more elegant fashion.
Comment: You were able to get this to work for a response trigger? This says it's not possible: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-updating-http-responses.html

*When you're working with the HTTP response, Lambda@Edge does not expose the body that is returned by the origin server to the origin-response trigger.*

How did you set this up?
Comment: @lou1989 can you provide a code snippet of a Lambda@Edge function?
Answer: I've created a method to add GTM scripts inside  and , using the @lou1989 response. Here are the code and some explanation.
Comment: That link you provided is deal


Proving that : $ \frac{W(x)}{xe^x}=\sum\limits_{n=0}^{\infty} \frac{(-1)^n}{n!}T(n)x^n $

Question: How to prove that:
$$ \frac{W(x)}{xe^x}=\sum_{n=0}^{\infty} \frac{(-1)^n}{n!}T(n)x^n $$
where
$T(n)$
counts the number of forests of rooted labeled trees using labels in a subset of
$\{1,\ldots,n\}$ and $W(x)$ is the Lambert $W$ function?
Also, as shown in this video at 6:54, does $T (n)=n^{n-2} $ ?
Comment: See *[On the Lambert W Function](https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf)* by Corless, Gonnet, Hare, Jeffrey and Knuth.
Answer: This is not an answer.
This is a problem of Taylor series composition using
$$W(x)=\sum_{n=1}^\infty (-1)^n\,\frac{n^{(n-1)}}{n!}x^n$$ (have a look here)
$$e^{-x}=\sum_{n=0}^\infty (-1)^n\,\frac{x^n}{n!}$$ So, computing the first terms, we have, as a series,
$$\frac{W(x)}{xe^x}=1-2 x+3 x^2-\frac{29 x^3}{6}+\frac{53 x^4}{6}-\frac{2117 x^5}{120}+\frac{2683
   x^6}{72}-\frac{82403 x^7}{1008}+O\left(x^8\right)$$ making the $T_n$ to be the sequence
$$\{1,2,6,29,212,2117,26830,412015\}$$ which is sequence $A088957$ in $OEIS$.
In a comment, Alex Chin wrote that these coefficients are "the number of rooted subtrees (for a fixed root) in the complete graph on $n$ vertices" (please : do not ask me what this means !).
Answer: Start   by  making   some   definitions.    The  combinatorial   class
$\mathcal{T}$ of labelled trees has the specification
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}\mathcal{T} =
\mathcal{Z} \times \textsc{SET}(\mathcal{T})$$
which gives the functional equation
$$T(z) = z \exp T(z).$$
We   have   by   Cayley   that
$$T(z) = \sum_{n\ge 1} n^{n-1} \frac{z^n}{n!}.$$
We seek to prove that
$$\bbox[5px,border:2px solid #00A000]{
W(z) = z \exp(z) \sum_{n\ge 0} (-1)^{n} Q_n
\frac{z^n}{n!}}$$
where $Q_n$ is the number of rooted  subtrees for a fixed root in the
complete graph $K_{n+1}$  on $n+1$ vertices. These have  from $k=0$ to
$k=n$ nodes not  including the fixed root and represent  a forest that
is   attached    to   the   root.    (Specification    as   in   OEIS
A088957,  example given  by  A. Chin.)   The
combinatorial class $\mathcal{F}$ of forests is given by
$$\mathcal{F} = \textsc{SET}(\mathcal{T})$$
and hence has EGF
$$F(z) = \exp T(z) = \frac{1}{z} T(z).$$
We also have by construction that
$$Q_n = \sum_{k=0}^{n} {n\choose k}
k! [z^k] F(z).$$
Here we chose  the labels that go into the  forest and substitute them
into the  forest respecting the  ordering of  the nodes in  the source
forest. It follows by convolution of  EGFs that (recall that $n! [z^n]
\exp(z) = 1$)
$$Q(z) = \sum_{n\ge 0} Q_n \frac{z^n}{n!}
= \exp(z) \frac{1}{z} T(z).$$
Now by definition the principal branch of the Lambert W function
is
$$W(z) = \sum_{n\ge 1} (-1)^{n-1} n^{n-1} \frac{z^n}{n!}$$
and hence we obtain
$$\bbox[5px,border:2px solid #00A000]{
\sum_{n\ge 0} Q_n
\frac{z^n}{n!}  = \frac{1}{z} T(z) \exp(z)
= - \frac{1}{z} W(-z) \exp(z).}$$
The claim now follows by replacing $z$ by $-z$ to get
$$\sum_{n\ge 0} (-1)^n Q_n
\frac{z^n}{n!}  = \frac{1}{z} W(z) \exp(-z).$$


how to style navigation sub-menu?

Question: I need to display dash (-) in front of each sub-menu element. For example, the output should be

Home

About

- Process

- Process 101

- Compnay

Useful Links

I tried the following:
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }

   $output = l($element['#title'], $element['#href'], $element['#localized_options']);
   return '
' . $output . $sub_menu . "
\n";
  }

Comment: So you would like to display the dash *only* in front of a sub-menu element, right?
Answer: You can do this with CSS
ul.menu ul.menu li a:before {
  content: "- ";
}

Or, you can do something similar with list-style-image or a background-image.
Keeping stuff like that out of markup makes things cleaner.
Comment: Thank you for advice, but IE7 doesn't support content property. Is there an alternate way to do it? Does drupal offer templates for navigation?
Comment: The typical way is to add some `padding-left` to the `li` and then add a `background-image` attached `left center`.  Take a look at http://paulirish.com/2011/tiered-adaptive-front-end-experiences/ for a good read on having to have an identical experience in all browsers.

how to style navigation sub-menu?


IE does not pick up form processing data in inputs in a jQuery Dialog

Question: I have an HTML5 page with several data inputs inside a jQuery Dialog box.  I sweep this data into form processing with the input attribute form=dataInput.  It works fine in Firefox and Chrome, but not in IE because IE does not support the input form attribute.  Something about the Dialog widget makes input box elements 'invisible' to form processing.  The form attribute fixes this for browsers that support HTML5, but no released IE has this support.  I tried $('.ui-dialog').appendTo('form'); in the Dialog open: option, but it does not fix the problem. Is there a way to get IE to sweep input data out of a Dialog widget and into $_POST ?
Here is a sample of an input box inside the Dialog
<input type="radio" id="unitedStates"  name="country" form="dataInput" value="US">United States

I use the jQuery Form plug-in to perform the submit. It has some options, like beforeSubmit and beforeSerialize, but I don't understand the documentation or the submit process well enough to know if they can be used to solve this problem. Please be specific with code or tutorials. I'm new enough to this that I don't follow general instructions well.  ;-)  (BTW, IE has the other feature support I need, just not this one.)
Here's my code with Andrew Hagner's suggestion and my modification.  Dialog works, but IE does not set a value for the country. What needs to change?
var countrySelected = $("input[type=radio][name=country]").val(); //set earlier by W3C geocoding
var countryChooser = $('#countryChoices').dialog( {
    autoOpen: false,
    bgiframe: true,
    height: 300,
    width: 850,
    resizable: false,
    draggable: true,
    title: "Click to select another country",
    open: function () {
            $('#regions').tabs(
                {
                event: "mouseover",
                })
        },
    buttons: {
        'Close / continue location input': function ()
                {
                countrySelected = $('input[name=country]:checked').val();
                $(this).dialog('close');
                }
            }
});
//then later on
getCityFromGeonames3Step(countrySelected);

Comment: I'd suggest using a class name for the inputs rather than a non-compliant attribute such as `form`.  You can then have jQuery pick up all of the elements with the given class you've assigned.
Comment: @cale_b I understand class. I process the submit with the JQuery ajaxForm plug-in to handle data, images, spinner, and user feedback. What ajaxForm option would handle a class of data - or some question like that?
Answer: Updated:
// Before you enter dialog, assign the element you will
// be grabbing the info from to a variable.
var countrySelectionElement = $("input[type=radio][name=country]").val();
var countrySelected = "";

var countryChooser = $('#countryChoices').dialog( {
autoOpen: false,
bgiframe: true,
height: 300,
width: 850,
resizable: false,
draggable: true,
title: "Click to select another country",
open: function () {
        $('#regions').tabs(
            {
            event: "mouseover",
            })
    },
buttons: {
    'Close / continue location input': function ()
            {
            // Since jQuery won't work in here, use the variable
            // we assigned above to access value.
            countrySelected = countrySelectionElement.val();
            $(this).dialog('close');
            }
        }
});

//then later on
getCityFromGeonames3Step(countrySelected);

Original:
Before you open the dialog assign the input to a variable:
function OpenDialog()
{
    var input = $("yourinput");

    // Open dialog, use input to work with that element.

    // If you want you can then place the entered data in a hidden field
    // using jQuery, in the same way we are using input here. Then you will
    // be able to post that data back however you like.

}

I had this problem the other day, I found this solution on jQuery's Dialog site.
http://jqueryui.com/demos/dialog/#modal-form
Comment: I believe this issue is caused because the dialog is wrapped in an iframe, or at least that is what I read on the link I posted.
Comment: You are probably correct.  I looked at the Dialog documentation. I don't get something because the OpenDialog function causes all the tabs and buttons to display and the Dialog won't open. I posted my code above in an edit. What do I need to change? A couple lines are commented out because they cause a second problem that W3C geocoding in the browser stops working.
Comment: I looked more closely at the Dialog documentation and the OpenDialog function is not necessary, and in my code, not allowed to keep the Dialog box working. My code, as modified, is above and IE does not set the variable value for the input radio button. Any idea what I need to change?
Comment: In the close function where you do:
`countrySelected = $('input[name=country]:checked').val();`
You should do:
`countrySelected = countrySelected.val();`

This is because what I said to do assigns that control to the 'countrySelected' variable. So instead of using jQuery to find it within the dialog (which is what doesn't work) you can use this variable. You don't have to assign the value to this variable like you are doing, but you can I believe.
Comment: I updated my answer to show changes, let me know if it works for you now.
Comment: Andrew Hagner, thanks. The updated code works. This exercise has uncovered several other errors in my code, so I have work to do, but this part now works. Thanks again.


class template argument deduction for template alias of an alias (C++20)

Question: I am using boost::outcome_v2::result with a custom type for the error and an alias to this type.
Now I am struggling to get class template argument deduction to work for my alias.
The code:
class my_error{ ... };

template <typename result_t>
using my_result = boost::outcome_v2::result<result_t, my_error>;

The issue is that when I return this type from a function I can't use class template argument deduction for the result type:
const my_result res = some_function();

But it works if I use boost::outcome_v2::result directly:
const boost::outcome_v2::result res = some_function();

Is there a way to write a deduction guide for my alias so that it can work as well?
Compiler Explorer link
Comment: Why not just `auto const res=/*...*/`?
Comment: @Red.Wave That is what I have at the moment. The 'problem' I have with `auto` is if the interface changes I want to fail at the assignment point, not later down in the code with where `res.has_value()` is called (or something else), `auto` hides the failure point. I also prefer explicit types over auto
Comment: I don't like adhoc tricks. But you can define a `concept` for your template and `static_assert` on `decltype`. I am not sure if a local(none argument) object can use shorthand template constraints, but if it can I'd use it.
Answer:
Is there a way to write a deduction guide for my alias so that it can work as well?

No, as alias templates are just an alias for a type, it is by design not allowed to write explicit deduction guide specifically for an alias template.
Rather, this is an inherent and known limitation of CTAD, as highlighted in P1021R6 ([Core] Filling holes in Class Template Argument Deduction)

Class Template Argument Deduction for alias templates
While Class Template Argument Deduction makes type inferencing easier when constructing classes, it doesn't work for type aliases, penalizing the use of type aliases and creating unnecessary inconsistency.
[...]
Finally, in the spirit of alias templates being simply an alias for the type, we do not propose allowing the programmer to write explicit deduction guides specifically for an alias template.

P1814R0 (Wording for Class Template Argument Deduction for Alias Templates) broke out the alias template parts of P1021, and was accepted by CWG in 2019, but Clang has not yet implemented it and GCC doesn't even list its status towards the paper.
Note however that in your case, result is also an alias template, so you are actually not comparing CTAD for alias templates vs a non-alias template. Clang, for example, rejects both cases.


How to mock jQuery with Jasmine

Question: What I want to do: We are writing some tests for an existing Javascript code base that uses jQuery heavily. For the tests, we don't want to have actual HTML elements (HTML fixtures). We'd prefer it if we had a jQuery mock object that does not do anything HTML-related.
My starting point: The most promising approach I found here:
http://eclipsesource.com/blogs/2014/03/27/mocks-in-jasmine-tests/
This creates a helper method that creates a mock by going through the functions of an object and creating a spy for each function:
window.mock = function (constr, name) {
  var keys = [];
  for (var key in constr.prototype)
    keys.push( key );
  return keys.length > 0 ? jasmine.createSpyObj( name || "mock", keys ) : {};
};

Then, if I understand him correctly, he uses that like this (adapted example from his blog post):
var el = mock($);
el('.some-not-existing-class').css('background', 'red');
expect(el.css).toHaveBeenCalledWith('background', 'red');

However, this does not work, since el is an object and not a function.
My approach to resolve this problem: I refactored his mock function to account for the case that constr is a function:
mock (constr, name) {
  var keys = [];
  for (var key in constr.prototype)
    keys.push(key);
  var result = keys.length > 0 ? jasmine.createSpyObj(name || "mock", keys) : {};

  // make sure that if constr is a function (like in the case of jQuery), the mock is too
  if (typeof constr === 'function') {
    var result2 = result;
    result = jasmine.createSpy(name || 'mock-fn');
    for (var key in result2)
      result[key] = result2[key];
  }
  return result;
}

However, the second line in the test throws a Cannot read property css of undefined error:
var el = mock($);
el('.some-not-existing-class').css('background', 'red');
expect(el.css).toHaveBeenCalledWith('background', 'red');

Other ideas: I also tried to merge the spy object into jQuery, but that did not help either.
Any ideas? I hope we're not the only ones who do it without HTML fixtures.
Answer: You may use sinon.js stubs, instead of rolling your own helper methods.
stub = sinon.stub(jQuery.fn, 'css');

// invoke code which calls the stubbed function

expect(stub.calledWith({ 'background': 'red' })).toBe(true);
stub.restore();

Comment: Tried that with the line `$('abc').css('background', 'red');` as test code. However, the assert fails, `sub.calledWith` returns false.
Answer: Found it. When my version of the mock function is set up to return the jQuery object when the jQuery function is invoked, the test works:
mock (constr, name) {
  var keys = [];
  for (var key in constr.prototype)
    keys.push(key);
  var result = keys.length > 0 ? jasmine.createSpyObj(name || "mock", keys) : {};

  // make sure that if constr is a function (like in the case of jQuery), the mock is too
  if (typeof constr === 'function') {
    var result2 = result;
    result = jasmine.createSpy(name || 'mock-fn');
    result.and.returnValue(result);
    for (var key in result2)
      result[key] = result2[key];
  }
  return result;
}

How to mock jQuery with Jasmine


In Views, how can I show users with one role before all other users?

Question: I have several views of users and I want to show all users with a certain role (example, "show_me_first") before all other users in all of these views.
I thought this would be easy, but apparently there is no "User: Role" as a sort criteria (I'm using Views 3.5 on Drupal 7.15).  I can filter by role, but I don't want to filter; I just want to show users with the role "show_me_first" before all other users.
How can I implement this?  Minimal view customization is best because I will have to repeat this for a lot of views.  If there is a way to do it without using roles, I would be open to that as well.
Comment: You may need to write your own views handler for handling this sort option.
Answer: It looks like it's not possible with one View (Sort By User Role, Sort By User Role:  A New Idea?) which does kinda suck.
One option is to make two Views, one that filters on the user role you want at the top, and then one that filters OUT the user role.
Another option (this one would probably be easier to maintain) would be to create a field on the user accounts called Weight (you could hide it with Field Permissions), and then use Rules to populate that field with a high number for your chosen role when a user is created or edited, then you should be able to sort on that field.  If you do this though don't forget to create a second rule to remove/change the value in that field if the role is removed form a user.
tl;dr

Create Weight field on users
When a user is created, fire off a rule that looks for a particular user role
If it finds it, put a number in the Weight field
Sort your view on the Weight field
Make an "opposite" rule to remove the Weight value on Role removal.
Profit
Answer: If memory serves me correctly, you use a Flags for other things along these same lines.  So, if so, how about a global 'show me first' flag that you/your admins can set on a user? Kinda like your own custom sticky bit. A quick look here only allows one to sort on the flagged time, but you could use this flag to set a hidden from the user field that you could sort on.
Answer: A common use case is to show content from "premium" users before content from other users. This is more binary than a true weighting. If this is your use case, consider using Views' attachments.

Create your view. Add relationship for Content: Author.
In main display, set filter by role to indicate that the author is not a "premium" user (e.g. User: Roles / none of / "premium", "other premium role", etc.)
Add new views display of type "attachment"
In attachment display, alter filter by role to include the roles excluded in main display
In attachment settings, select your main display for "Attach to" setting; Select "Before" for Attachment position


Grouping users help

Question: I'm building an application where a group of users interact with customers...however for each user in a group he/she has his own customers. I also need the ability to having 1 user with his/her own customer...meaning this user is not a part of any group. Should I use Organic group for this or would vanilla drupal work just fine (with taxonomy and roles?). Thank you.
Answer: I think Users can also be Organic Groups in Drupal 7, as everything related to OG are just fields now which can be attached to anything. So that might be something you could try.
Not sure what kind of communications you have in mind, but if it is meant to be private, maybe a combination of User Relationships and Privatemsg could get you started. Those modules can be integrated so that only related users can send each other private messages.
Comment: Oh thank you for your reply. The relationship is between a manager and one of his workers. One bothersome issue is I don't want to use the same signup form for managers and workers. For example, a worker that works for Manager A should just see a dropdown of managers to select from when he signs up, but when a manager signs up (say the first manager - Admin) he needs to create the group, say Group A. Now a manager and worker will have different signups..I'm not sure if I'm clear...but I'd like to hear your response.

Grouping users help


Python - How to deal with missing keys while iterating through a list of dictionaries?

Question: In the following example I iterate through a list of dictionaries and I save the 'age' on a list. However, the second dictionary does not have the key 'age'. In that case I would like the value null to be saved on the list. Any suggetsions on how to achieve this?
my_list = [{'age': 0, 'name': 'A'}, {'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]

ages = [li['age'] for li in my_list]

Comment: `dict.get(key, default=None)`
Answer: You can use dict.get(key, default_value) method, If the key not exist it will return default value. If you don't set default value it will return None
ages = [li.get('age', 0) for li in my_list]


How to perform an operation on each line in every file in a directory ending with a particular extension?

Question: I would like to perform an operation on each line for all files ending with an extension (pdb) from a particular directory. In my following code, what I can understand is that just {lines = pdbinput.read()} will not allow me to perform a startswith() operation on a line in lines.
import glob, os
os.chdir("F:/python")
for files in glob.glob("*.pdb"):
    with open(files) as pdbinput:
        lines = pdbinput.read()
        with open ('output.txt', 'w') as f1:
            for line in lines:
                if line.startswith("HETATM"):
                    print (line, file=f1)

But it allows me to print lines directly:
import glob, os
os.chdir("F:/python")
for files in glob.glob("*.pdb"):
    with open(files) as pdbinput:
        lines = pdbinput.read()
        with open ('modified.txt', 'w') as f1:
            print (lines, file=f1)

Comment: What do you mean that it "will not allow" you to do `line.startswith()`? Did it have no effect? Did it produce an error? Be more specific.
Comment: If you are looking for modifying the file's contents in-place, have a look at the [`fileinput`](https://docs.python.org/2/library/fileinput.html) module, which offers a way to do this, and also incidentally would simplify your code significantly.
Comment: Sorry for not specifying this. The first case, it doesn't give any sort of output while in the second case, it does give an output by printing all the lines of each every file ending with the extension "pdb".
Answer: pdbinput.read() reads the entire file into a single string. That means that the subsequent for line in lines will iterate over that string character by character, not line by line.
You could either use pdbinput.readlines() or (the usual way) iterate over the file directly:
with open(files) as pdbinput:
    with open ('output.txt', 'w') as f1:
        for line in pdbinput:
            if line.startswith("HETATM"):
                print (line, file=f1)

The next problem: right now, for each PDB file, a new output.txt is generated, overwriting the previous one. Just move that with block outside of the iteration:
with open ('output.txt', 'w') as f1:
    for files in glob.glob("*.pdb"):
        with open(files) as pdbinput:
            for line in lines:
                if line.startswith("HETATM"):
                    print (line, file=f1)

Comment: Thanks Tim! This is exactly where I was stuck! :)


Where do the double accidentals go in "theoretical" key signatures?

Question: Recent questions led me to discussions of theoretical keys, which are defined by Wikipedia as keys with at least one double accidental in the key signature. (Unfortunately, the source of that definition is not given.)
The key signatures on Wikipedia (and most other sources I've seen) put the double accidental in the spot where the single accidental would go. In other words, for G♯ major, the F is in the spot where F♯ would normally go (i.e., at the beginning). This, I admit, seems intuitive to me:

Although the majority of online sources notate it that way, at least one other source puts the double sharp at the end. But this is hardly the greatest source, so I was skeptical that this notation would be correct. Imagine my surprise when I saw that LilyPond's default behavior (version 2.19.80) seems to notate it the same way:

While I can understand the logic of this latter key signature—the last added accidental appears last in the key signature—it's odd to see a key signature that begins with a C♯. (With that said, I guess it's no more odd than seeing a key signature with an F!)

Is there an official rule for notating key signatures with double accidentals? Or is there no rule since these are just "theoretical" entities?
Note that, according to this discussion among the MuseScore community, the top key signature (with the F first) was custom made. The LilyPond key signature, however, exists by default.
Comment: Wow, I was sure Gardner's notation book would at least mention this sort of thing, but I don't see it. Anyone have a copy of Stone's notation book?
Comment: There is something that shows a scan of the G# signature with F## at the beginning. I don't know what the original source is though. https://translate.google.com/translate?sl=auto&tl=en&js=y&prev=_t&hl=cs&ie=UTF-8&u=http%3A%2F%2Fpoznayka.org%2Fs89796t1.html&edit-text=
Comment: Very interesting question. To me the second way is 'more intuitive' : _the last added accidental appears last in the key signature_ - the order is not determined by the note values, but by the order of appearance. _**F**_ is the first # because _**F**_  is **the first sharp**, not because it's _**F**_ .
Comment: @Richard nope it's created using musescore (see bottom of link) https://en.wikipedia.org/wiki/Theoretical_key#/media/File:G-sharp-major_e-sharp-minor.png
Comment: To be fair, you're second source was generated by Lilypond so it's not a surprise that Lilypond matches that (see attribute at the bottom of the source).
Comment: @Dom Wow, I didn't catch that. But I believe the Wikipedia source was also generated by LilyPond.
Comment: @Dom Ahh, good catch! I (stupidly) assumed the same font indicated the same notation program.
Comment: @PatMuchmore - I do but I'm away from home at the moment and wouldn't be able to check until Monday.
Comment: I would be interested in knowing the decision making over at LilyPond - what evidence resources did they use to justify their decision making process?
Comment: I'm very temped to offer a bounty on this question after days of looking for sources and examples in print turned up nothing for me. There's got to be _something_ out there that addresses this one way or another even if it's hard to find.
Answer: I cannot give you any reference, but I'll try to give a typographer's insight into the problem and state my opinion. I hope it's fine.
Typography has some basic rules, and they are in general applied in this order:

Deliver the message.
Be consistent.
Be invisible (meaning smooth, not "shocking", eye-catching at the wrong places etc.)

Applying these rules, I would go with the double sharp in the end. The reason is that primarily you want to focus on the delivered message, and that is that the key is significantly odd. Basically, we want to break the "invisibility" rule, we want the signature to stand out. And this is what you do. First, it starts with C# rather than the usual F#, and second, I believe (I can't support this by any study though) that if you only count the sharps, the one at the end is more noticeable than the one at the beginning.

Actually, purely from my mathematical point of view, I would also consider the following option viable. It best delivers the message that the key is G# major / E# minor, but the first F# is or at least could be confusing.
Comment: I think this makes a ton of sense, especially in light of the final example you provide. If we're dealing with theoretical keys, then why choose a notation that rules out the possibility of F# *and* F##? Placing the double sharp at the end (as you suggest) avoids that issue. If a satisfactorily authoritative citation doesn't exist, then I think this answer deserves the bounty because it provides the very logic one would seek in an authoritative source. If a satisfactorily authoritative citation *does* exist, then I think it should have reasons as strong as the ones you mention!
Comment: @supercat, in this context of theoretical keys, I wonder if we need to define the purpose of a double-sharp that narrowly.
Comment: I'd go along with this one.  The purpose of a double-sharp is not to alter a natural note by two semitones, but rather to raise an *already-sharp* note by one *additional* semitone.
Comment: I like the final, 'mathematical' option as it show the tonic ascending in fifths 8 times.
Comment: The bottom example was my original guess, but I didn't mention it in the original question because I never saw it anywhere!
Comment: @jdjazz: Is there any context in which one would use a F## but an unmarked F wouldn't be an F#?
Comment: @jdjazz: I think having each marking in a key signature raise one or lower pitch by one semitone compared with what it would do in one's absence seems more natural than doing anything else.
Comment: I'm not sure I agree with the premise that the sharp on both ends stands out. To me, it seems easy to look over; it's just added on to the end of a familiar key signature, and the appearance of a double sharp makes it look sort of unrelated. The option of replacing the first sharp with a double solves that problem well, since the group of "normal" sharps looks weird without incorporating it.
Comment: Putting the double sharp at the end (whether or not the single sharp also appears at the beginning) is helpful to musicians.   Many are trained to look to the last sharp to find the leading tone "ti."  Not placing it at the end would make it look more like C# major
Comment: Surely you can't have both F# *and* F double sharp in the key signature.
Answer: Gould's engraving style guide Behind bars (Key signatures, p. 91) says only the following:

The order of accidentals follows the 'cycle of fifths'.

While there is no direct instruction on what to do in case of double sharps, it seems that the only two readings that are consistent with this principle are:

Add the double sharp last, cf. the second example of the OP.
Add a single sharp at the beginning and a double sharp at the end, cf. yo's answer.
Answer: Here are some gifs I made that show the process of gradually adding sharps in the key signature until there are twelve sharps, or adding flats until there are 12 flats. The cool thing is that when you have five double-sharps in the key signature, the remaining two single sharps are E# and B#, which are enharmonically the same as F natural and C. So 12 sharps is enharmonically the same as zero sharps (and likewise 12 flats)
Comment: This is really useful for teaching!  you should an emoticon that gradually fades from smile to fear with each added flat/sharp....
Comment: No fear - I wanted to push the notation as far as I could - and it doesn't break - it's all beautifully consistent whether you have 11 sharps in the key signature or just 1. Lovely.
Comment: agreed - our notation system, while flawed, is amazingly complete and capable of capturing just about anything
Answer: Personally, I can't see any logic in having both an F sharp AND an F double sharp.  It can't be both.
I would put the F double sharp at the beginning for convenience.  You are going to notice it there more than at the end of a group of sharps.  We need to make life as uncomplicated as possible for the person reading the music.
Comment: The question is "Is there an official rule for notating such key signatures?" so your answer should address this. These keys _do_ come up although are very rare so having a reference here rather than just an opinion will greatly help the community.
Comment: While this answer makes sense, can you back it up with a reference?
Comment: In defense of this answer, I think it's worth noting that the accepted answer provides no hard reference either! Still, that answer got my upvote just like this one because they both stress a point I agree with.
Comment: No reference.  I was just giving my opinion on this theoretical question.  In practice, the composer would never use such a key.  He/she would simply add the double accidental within the appropriate bar/s.
Comment: This question specifically asks for "an official rule for notating such key signatures." Others have offered their _opinions_ on the matter in answers which have since been removed. It seems clear that OP is perfectly capable of forming an opinion, but is looking for more.
Comment: The purpose of a double-sharp is not to raise a natural note by two semitones, but to raise an already-sharp note by an additional semitone.  That's the logic for having both.
Comment: There are no "official" rules for music notation, because no international "office" has been charged with making them. Gould, Read, and others are good books which describe customary practice, but only where it exists.
Answer: Up to this question I would not have considered the double sharp as legal in the key signature. On the the other hand, I never read about a limit on the number of accidentals in the key signature and so I would have happily added an eighth (single) sharp, again at the f line.
This keeps the well-established order and appearance in place.
Update with all sparse references, which I could find:
This page lists under "extreme accidentals" 8 flats for Victor Ewald's brass quintet, (admittedly it also list John Foulds World Requiem with 6 sharps and a double sharp, so also no clear strategy here) and the German wikipedia offers under "double sharp":

Opposed to the simple sharp, the double sharp is typically not used in key signatures.
Comment: I downvoted this because of the lack of source. The Question has two sources that do very different things and without a source, this is very much just a personal preference.
Comment: So would you first have all seven sharps, and then the F as the eighth and final accidental?
Comment: Or, based on your edit, it sounds you wouldn't have any , but rather you'd start the signature off with F♯ and end with another F♯? (I might have misunderstood you.)


Magento get parent category and all his sub categories

Question: This is my category tree:
Cat_1 (This is the parent category with ID 4)
    Subcat_1
    Subcat_2
        Subsubcat_1
        Subsubcat_2
    Subcat_3
        Subsubcat_3
        Subsubcat_4
    Subcat_4

I tried this code to retrieve this category tree but i only came to the level of the subcats. I need one level deeper.
<?php
$cat = Mage::getModel('catalog/category')->load(4);
$subcats = $cat->getChildren();

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    $sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
    $sub_subcats = $sub_cat->getChildren();
    foreach(explode(',',$sub_subcats) as $sub_subCatid)
    {
          $_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
          if($_sub_category->getIsActive()) {
              echo '
getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'
';
          }
     }
  }
}
?>

Can someone help me?
Answer: Try this.
<?php
$cat = Mage::getModel('catalog/category')->load(4);
$subcats = $cat->getChildren();

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '
getURL().'" title="View the products for the "'.$_category->getName().'" category">'.$_category->getName().'';
    $sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
    $sub_subcats = $sub_cat->getChildren();
    foreach(explode(',',$sub_subcats) as $sub_subCatid)
    {
          $_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
          if($_sub_category->getIsActive()) {
              echo '
getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'
';
              $sub_sub_cat = Mage::getModel('catalog/category')->load($sub_subCatid);
              $sub_sub_subcats = $sub_sub_cat->getChildren();
              foreach(explode(',',$sub_sub_subcats) as $sub_sub_subCatid)
              {
                $_sub_sub_category = Mage::getModel('catalog/category')->load($sub_sub_subCatid);
                if($_sub_sub_category->getIsActive()) {
                    echo '
getURL().'" title="View the products for the "'.$_sub_sub_category->getName().'" category">'.$_sub_sub_category->getName().'
';
                }
              }
           }
     }
     echo '
';
  }
}

?>

Comment: Hi Nina. That works! I just found out that also the first level is missing. Is it possible to start one level lower? Also, it would be great if the output is sorted correctly with the subcategories as a own UL in their parent category.
Comment: Edited the code. Just try. I did not test the code. If didnt work, echo the first level category appropriately. Also do some css to polish your result.
Comment: Almost! All the levels are visible now. Is it possible to have a structure like this? catsubcat?
Comment: Just not quite what I mean, but I'll figure it out so. Thank you very much!


MS Header control still draws border for custom-drawn items

Question: We are developing a custom grid control in VB6 (still need to use the classic VB - sorry :). It has a custom header based on the standard OS MS Header Control from ComCtl created using the corresponding WinAPI call to CreateWindowEx. The header items are owner drawn (the HDF_OWNERDRAW flag) and we need to draw them totally from scratch, but MS Header still draws this strange 3D border around every item.
It seems, this happens as a part of the standard functionality in the WindowProc when WM_PAINT is processed. But we cannot suppress WM_PAINT at all as in this case the WM_DRAWITEM message isn't sent and we have no place to draw our header items.
How to get rid of this standard 3D border drawing for our subclassed API header?
Answer: We used so called owner drawn items, when just "useful contents" are drawn. But in our case, to draw the whole item from scratch, we needed the general custom drawing technique available in the MS common controls. This means we should process the NM_CUSTOMDRAW notification message.
Here is an example from the real working code (the WindowProc for the control's parent):
<code>Select Case uMsg

Case WM_NOTIFY
   CopyMemory tNMH, ByVal lParam, LenB(tNMH)

   Select Case tNMH.Code

   Case NM_CUSTOMDRAW
      Dim tNMCD As NMCUSTOMDRAW
      CopyMemory tNMCD, ByVal lParam, Len(tNMCD)
      Select Case tNMCD.dwDrawStage
      Case CDDS_PREPAINT
         WindowProcParent = CDRF_NOTIFYITEMDRAW Or CDRF_NOTIFYPOSTPAINT ' CDDS_ITEMPREPAINT (below) will be raised for every item
         Exit Function
      Case CDDS_ITEMPREPAINT
         pDrawItem tNMCD
         WindowProcParent = CDRF_SKIPDEFAULT ' totally draw the column header by ourselves
         Exit Function
      Case CDDS_POSTPAINT
         pPostPaint
         Exit Function
      End Select
</code>


Show hostname for local host with powerline

Question: I am using powerline with bash, fish, and tmux. The hostname shows up when logging in to remote systems with SSH. But I want to also enable the hostname segment for local users. Here is how it looks on a remote system.

Here is how it looks on as a local user. Note that I have hostname set on the local machine.

The tmux theme works fine.

I have tried editing the default theme by omitting the priority to always show the hostname segment disregarding the display width, and also edited the "only_if_ssh": false argument. How can I enable showing the hostname in the shell prompt as well?
Answer: I had to change the following config files to show the hostname for a local system.

Change powerline/config.json to make the key ext:shell:theme point to my custom theme .json file
Customize the theme file to your liking. I have the following in addition to other entries.

{
  "segments": {
     "left": [
     {
        "function": "powerline.segments.common.net.hostname",
        "priority": 10
     }
  }
}

Edit __main__.json as follows.

{
   "segment_data": {
     "hostname": {
       "args": {
         "only_if_ssh": false
       }
     }
   }
 }


Domain access - prevent redirecting to default domain on account creation

Question: Drupal 7.36 & Domain access 7.x-3.x
I have 2x domains running curtesy of domain access. Each domain has been set up for 2 specific groups of users. The idea is that each group can create accounts, log-in and access content on their respective domain. Setting up the default domain worked fine. But, when users attempt to register on the second domain, they are redirected to the default domain instead, causing confusion.
I have Domain Strict enabled – plus I have tried Domain bonus, but the solution does not seem to be straight forward.
How you I prevent this from happening?
Answer: Apologies - it turned out that the default domain had been set as the base URL in the settings.php file. When a user requested an account, they were being returned to the default domain homepage


Return data from php file to html

Question: I am attempting to pass data between a php file back to a HTML file. I read on stack overflow that I should use AJAX or JQuery but i don't understand how to implement it (I am very new to the subject of web development so I apologize if this question is obvious). Any help would be much appreciated.
This is my HTML code:
<!DOCTYPE html>

    <canvas id="head_canvas" width="1400" height="90">Your browser does not support the HTML5 canvas tag.</canvas>

    <form action="form_submit.php" method="post">
        Search: <input type="text" name="search">

        <input type="submit" value="Submit" >
    </form>

And this is my PHP code:

        <title>Get Data</title>

        <?php

            $dbhost = 'localhost';
            $conn = mysql_connect($dbhost, 'username', 'password');
            if (!$conn) {
                die('Could not connect: ' . mysql_error());
            }
            else {
                echo "Successfully Connected To Database
";
            }

            /*
            INSERT INTO Members (MemberID, Pass, UserName) VALUES (1,'MyPas55w0rd','Johnny Bravo');
            */

            mysql_select_db("mydb",$conn);
            $sql="SELECT * FROM Members;";
            $result=mysql_query($sql);

            while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
                #echo $rows['MemberID'] . " , " . $rows['Pass'] . " , " . $rows['UserName'] . "
";
                echo array_values($rows)[1] . "
";
            }

            mysql_close();

        header('Location: index.html');
        exit;
        ?>

Comment: Suggest you study some ajax tutorials to get a better understanding of what it is and how it works....and importantly, how to debug it. This isn't a tutorial or code writing service
Comment: Doing a redirect after an `echo` doesn't make sense either
Answer: I am not sure if you are aware of this site or not but I'll give it to you anyway.  http://www.w3schools.com/php/default.asp provides lots of examples.
However, maybe you just need to copy all the information collected in your PHP code to a file that you can than read into your HTML code.  Something like:
<?php
echo copy("source.txt","target.txt");
?>

I hope one of the solutions I provided help you.
The UnderDog

Return data from php file to html


Likelihood of bernoulli trials until k successes

Question: Suppose we sample 10 data points where 4 are deemed successes. The likelihood of this given the probability of success $p$ is $p^4(1-p)^6.$
Consider now the problem of continuously sampling until we reach 4 successes. We find that after 10 samples, the $10^{th}$ happened to be the $4^{th}$ success. What is the likelihood of this?
I realize that the second case is negative binomialy distributed i.e the probability of k successes where the $n^{th}$ trial is a success is given by ${{n-1}\choose{k-1}}p^k(1-p)^k$. Maybe I can somehow deduce the likelihood from this?
Comment: What do you mean by "likelihood"? What is meant by "likelihood" in statistics is the probability density (or mass) function evaluated on fixed data, that is maximized in terms of it's parameters. So there is really nothing to deduce in here, you already have the likelihood function...
Answer: Answered in comments:
In statistics the likelihood function is just the density (or probability mass) function, but evaluated at the observed data, seen as a function of the unknown parameters:
$$
     L(\theta ; x) = f(x ; \theta)
$$
So you already have the likelihood function!  But look at What does "likelihood is only defined up to a multiplicative constant of proportionality" mean in practice?  The likelihood function is only defined up to proportionality. The combinatorial factor in the negative binomial distribution do not depend on unknown parameters, so you can take the likelihood function to be $p^4(1-p)^6$.


Why querystrings after images & css files?

Question: I have seen on various sites a querystring followed by a numbers for images and css files. When I look at the source code (via  Chrome Developer), the cached css files and images do not have the number in the query string in their names. I have also seen on sites where the number changes in the querystrings when I refresh the page.
As example:
myimage.jpg?num=12345
myStyles.css?num=82943
After refresh:
myimage.jpg?num=67948
myStyles.css?num=62972
Can anyone explain to me what could possibly be the purpose of these querystrings short of tracking?
Comment: The number changes to prevent caching as it'll always look like a different file.
Comment: possible duplicate of [What does '?' do in a Css link?](http://stackoverflow.com/questions/438821/what-does-do-in-a-css-link)
Answer: Often times developers use those query strings with random numbers (or version numbers) to force the browser to request a fresh copy and avoid caching of those files since the request is different each time.
So if you have a file /image.png but it is a generated image, like perhaps a captcha or something, you could follow it with a random number querystring /image.png?399532 which the browser would then not pull image.png from its cache, but instead will download a fresh copy from the server.
Answer:
Prevent caching (the query string can provide a unique URL each time the file is updated causing the browser to download a new copy and not load a stale one from its cache)
Versioning (similar to #1 but with a more specific purpose)
Answer: The query string is for version controling it force to the navigator to reload the css and the image instead of use the cache


Cordova iOS blank iframe

Question: In a Cordova app that I am working on there is an iframe. The problem is that when testing the app (both simulator and on device) the iframe is blank. On Android the iframe works perfectly however.
The iframe is loaded dynamicly in an Angular directive.
Within the directive link function the following code is used to load and append the iframe to the directive's element:
var iframe = angular.element('');
iframe.attr('src', url);
element.append(iframe);

I have also tried using something in the following lines:
var iframe = document.createElement('iframe');
iframe.src = url;

This results in somthing like the following (using Safari web inspector):

In my index.html file I have the following set:
<meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-eval'; connect-src * 'unsafe-eval'; object-src 'self'; style-src * 'unsafe-inline';">

I also have the following lines in my cordova config.xml:
<access origin="*" subdomains="true" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

There is also no errors or warnings in Safari Web Inspector.
So my question is, is there some trickery to get iFrames to work in Cordova iOS apps that I am missing. Or what is wrong with my current config/code?
I am using angularjs 1.5.3 and have jquery 2.2.1 (loaded before angularjs) in case that helps.
Comment: After some further testing, I have also noticed that the iframe's onload event is never fired. Just in case someone has some insight on that.
Answer: The problem was the allow-navigation tag. So to solve it I only had to put the <allow-navigation href="*" /> tag into the project's config.xml file.
I came to the solution through the output box in xcode while the simulator was running. There was a message containing the url of the iframe in question and something about "internal navigation rejected".
Comment: I had to `cordova platform rm ios`, `cordova platform add ios` to make this change work. A `cordova clean`, `cordova build` might work too.
Comment: No luck, problem is the same.
Comment: It worked for me. I just wonder why they didn't include it out of the box.
Answer: Have you tried setting child-src and/or frame-ancestors in the Content-Security-Policy meta tag?  These may need setting to * also or something more restrictive like just the iframe source URL(s) you are using.
There's information about this at content-security-policy.com
Example based on your content security policy:
<meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-eval'; child-src *; connect-src * 'unsafe-eval'; object-src 'self'; style-src * 'unsafe-inline';">

Comment: Thanks for the link. From the information in the link, it seems the child-src and frame-ancestors aren't supported by Safari. I tried them anyway, but no luck.

Cordova iOS blank iframe


How do i use property files having my application properties in WSO2 EI

Question: I wish to use property files in WSO2 ESB project.
I am using WSO EI 6.5 with Integration Profile.
To be more precise
<inboundEndpoint name="main-endpoint" onError="error-handler-flow" protocol="jms" sequence="main-flow" suspend="false" xmlns="http://ws.apache.org/ns/synapse">
    <parameters>
        <parameter name="interval">500</parameter>
        <parameter name="sequential">true</parameter>
        <parameter name="coordination">true</parameter>
        <parameter name="transport.jms.Destination">Main</parameter>
        <parameter name="transport.jms.CacheLevel">3</parameter>
        <parameter name="transport.jms.ConnectionFactoryJNDIName">QueueConnectionFactory</parameter>
        <parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
        <parameter name="java.naming.provider.url">failover:(tcp://localhost:61616)?initialReconnectDelay=100&maxReconnectDelay=5000</parameter>
        <parameter name="transport.jms.SessionAcknowledgement">CLIENT_ACKNOWLEDGE</parameter>
        <parameter name="transport.jms.SessionTransacted">false</parameter>
        <parameter name="transport.jms.ConnectionFactoryType">queue</parameter>
        <parameter name="transport.jms.ContentType">application/json</parameter>
        <parameter name="transport.jms.SharedSubscription">false</parameter>
        <parameter name="transport.jms.ResetConnectionOnPollingSuspension">false</parameter>
    </parameters>
</inboundEndpoint>

In the above Inbound Endpoint, I wish that the queue name (transport.jms.Destination) and broker URL (java.naming.provider.url) to be read from properties file which are maintained for each environment (qa, staging, production). The property files themselves are not part of CAR application.
I imagine this could be done using registry, however I am not sure and I am unable to do this for quite some time now.
Please note that I wish to avoid writing any custom class or scripts to do this. I hope that WSO2 ESB has an available way of reading external property files. Any help would be greatly appreciated.
Thank you.
Answer: The local registry acts as a memory registry where you can store static content as a key-value pair, where the value could be a static entry such as a text string, XML code, or a URL. This is useful for the type of static content often found in XSLT files, WSDL files, URLs, etc. Local entries can be referenced from mediators in the ESB profile mediation flows and resolved at runtime.
Please refer [1]
The  element is used to declare registry entries that are local to the the ESB profile instance as shown below:
<localEntry key="string" src="url">text | xml</localEntry>

These entries are top-level entries and are globally visible within the entire system. Values of these entries can be retrieved via the extension XPath function
synapse:get-property(prop-name)

[1] https://docs.wso2.com/display/EI650/Working+with+Local+Registry+Entries


Tensorflow estimator issue with datasets

Question: I'm having a strange issue with TF estimators and trying to use tf.Dataset in my input function.
First off, my model looks like this:
    model = tf.estimator.DNNClassifier(
        feature_columns=my_feature_column,
        hidden_units=[hidden_layers, hidden_layers],
        n_classes=n_classes)

and my feature colum is like this
    my_feature_column = [tf.feature_column.numeric_column(key='image', shape=[32, 32, 3])]

Now, if I train like this, it all works fine and the training runs in a couple of seconds:
    model.train(
        input_fn=tf.estimator.inputs.numpy_input_fn(
            dict({'image':X_train}),
            y_train,
            shuffle=True),
        steps=nb_epoch)

But when I try to add in tf.Datasets in the input function, it takes forever to run:
def input_fn(features, labels, batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(({'image':features}, labels))
    return dataset.shuffle(1000).batch(batch_size).repeat()

model.train(
    input_fn=lambda:input_fn(X_train, y_train, batch_size),
    steps=nb_epoch)

Can anyone see what I'm doing wrong please? It should be identical, right?
Thanks,
Paul
Comment: welcome! Have you referred the [input pipeline performance guide](https://www.tensorflow.org/guide/performance/datasets#summary_of_best_practices)? You can try things like using prefetch for example as shown there. You can aslo set the [reshuffle_each_iteration](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle) parameter to False in shuffle, if you do not want to shuffle your data every time it is repeated. Maybe these improvements can help. Also if you could shuffle and repeat your data using the fused op, it might also lead to a better performance!
Answer: Your dataset is repeating infinitely and there's no default maximum number of iterations, so tensorflow does not know when to stop.
Replace the line which says return dataset.shuffle(1000).batch(batch_size).repeat() with something like  return dataset.shuffle(1000).batch(batch_size).repeat(10), which will train for 10 epochs, and you'll be fine.


What are there guides for using Heading tags?

Question: Instantaneous I'm working on developing a portfolio site. Hereby I strive to be as accurate as possible markup. I'm currently stuck in the use of heading tags. Are there any guidelines on the use of h1, h2, h3 tags etc? I find it difficult to determine what is and what is now an h1 h3 is an example.
I like to hear of your findings.
Answer: According to w3c:

The header element typically contains the headings for a section (an h1-h6 element or hgroup element), along with content such as introductory material or navigational aids for the section.

So the header can contain h1, etc. But not every h1 should be wrapped in a header. Only if it is related to the section.
The header tag is just semantics. It helps browsers (and developers) to understand your page better.
Answer: In fact it's always up to you how to use headers and how many of them you want to use. You should always test your site without CSS enabled and you will see if your markup is correct and articles titles / page titles/ block titles are visible enough
You can look also at some resources

http://webdesign.tutsplus.com/articles/the-truth-about-multiple-h1-tags-in-the-html5-era--webdesign-16824
http://www.hobo-web.co.uk/headers/
http://accessibility.psu.edu/headingshtml
Comment: Thanks for your comments. I changed my answer and added more explanation
Comment: Also likely to be downvoted because there's no actual answer between the links, answers should not just link to an off-site resource
Answer: Another great resource that explains heading tags with reference to SEO:
https://www.thiscodeworks.com/html-heading-tags-less-than-h1-greater-than-to-less-than-h6-greater-than-html-basics-htmltags-seo/5e19e63f2f9933a537bcc72d
"Best practices for SEO and accessibility purposes when using heading tags is:
 Use once or twice with the title of the website of page
 Use for section headers inside the page. Good to have one every 200-400 words. But totally depends on the content and layout.
 -  Use as many as you want to further subsection and highlight key points in the text."
Comment: Thanks @IzaakvanDongen, edited with content included.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/25132116)


Specifying a multilevel model: an experimental psychologists nightmare

Question: Thank you greatly for your help in answering this question.
I am having some trouble figuring out how to define my multilevel model. Firstly, a description of what I have completed. This is the prelude to a wider experimental piece of work. I had participants rate 25 images for their attractiveness (outcome). The images varied in waist to hip ratio (factor: 0.6, 0.7, 0.8, 0.9, 1.0) and BMI (factor: emaciated, underweight, average, overweight, obese). I also measured the individuals sociosexual orientation (continuous: 1-100).
So, I have the following model:
Outcome: attractiveness (ordinal data on a Likert scale 1-7)
Predictors:

WHR (categorical)
BMI (categorical)
Sociosexual orientation (continuous)

What I am looking to see is whether the attractiveness scores were influenced by BMI, WHR and their interaction, and whether there was an interaction between sociosexual orientation and WHR, sociosexual orientation and BMI, and sociosexual orientation, WHR and BMI.
Basically, I want to see whether WHR and BMI of the person has an effect on attractiveness scores and whether the sociosexual orientation of the participants influences those judgements. I believe I want WHR and BMI as fixed effects, but sociosexual orientation as a random effect?
I hope this makes sense. I find multilevel models very difficult to conceptualise.
Comment: Presumably, sociosexual orientation is only measured one time per participant? If so, then it is a between participant predictor, meaning it is fixed within persons. Only predictors that vary within participant can be specified as random slopes. Given categorical within-participant predictors, you would have to include all categories as random slopes and then run interactions with sociosexual orientation. Such a model may get difficult to estimate.
Comment: Please can you include a plot of the waist-hip ratio vs BMI ?
Answer: I would start out first by plotting the data.
From the description, you have crossed random effects for subjects and items (all participants rated all 25 images, and each image was rated by each participant). So random intercepts for subject and items would be appropriate.

I believe I want WHR and BMI as fixed effects, but sociosexual orientation as a random effect?

I don' know why you thnk that sociosexual orientation should be a random effect, but since its "effect" is part of your research question, this would not make sense. A model such as:
<code>rating ~ BMI * WHR * SSO + (1 | item) + (1 | subject)
</code>
would be a good place to start.
I would also avoid categorising your data - using emaciated, underweight, average, overweight and obese for BMI and 0.6, 0.7, 0.8, 0.9, 1.0 for WHR does not make sense - it loses information, reduces statistical power and makes the model harder to interpret. A 3-way interaction, and 2 factors with 5 levels each is going to be somewhat cunbersome. Do you really want to treat someone with BMI 24.99 and one with BMI 25.00 as completely different ? I would retain the vaiables as numeric and centre them before fitting the model
Comment: Thank you, this does make a lot more sense. I'm still learning statistics as I go along! Experimental designs are far away from my comfort zone (linear models mostly). But thank you for your reply, I appreciate it!
Comment: No problem - you're welcome. Glad it could help !


Regex capaz de ignorar os prefixos de uma palavra

Question: Tenho essas regex a seguir:
regex_list = [
    '(?:arquiv|auto)(\w+) (?:auto|arquiv) (?:definitiv)',
    '(?:arquiv|auto)(\w+) (?:auto|arquiv)',
    '(?:arquiv)(\w+) (?:definitiv)'
]

Meu o objetivo é capturar frases como: "arquivados os autos", "autos arquivados", "arquivamento definitivo", etc.
Só que quando coloco desarquivamento a regex também captura.  As frases podem vir também como: "arquive-se, portanto, os autos, de modo definitivo".
Gostaria de saber como faço para ignorar os termos que vierem com prefixos (nesse caso, "desarquivamento", só quero palavras com prefixo arquiv.) e garantir que frases como essa última também sejam capturadas.
Comment: Expressão regular não parece ser a solução para o seu problema - até porque pelo visto as expressões não são regulares. Por que não utiliza alguma ferramenta de processamento natural de linguagem? Leia sobre NLTK.
Answer: Você pode usar \b, que é uma word boundary (na falta de uma tradução melhor, é algo como "fronteira entre palavras"). Basicamente, serve para indicar posições da string que possuem um caractere alfanumérico antes e um não-alfanumérico depois (ou vice-versa).
Por exemplo, colocando um \b antes do arquiv, você já elimina o caso do "desarquivamento".
Para os demais casos, não ficou muito claro todas as variações que a frase pode ter, mas pelo que entendi, os critérios são:

pode ter "arquiv" ou "auto"
pode ou não ter "arquiv" ou "auto" logo depois
"definitivo" é opcional
entre essas palavras pode ter zero ou mais palavras

Dá para fazer em uma regex só:
import re

frases = [
 "arquivados os autos",
 "autos arquivados",
 "arquivamento definitivo",
 "desarquivamento definitivo",
 "arquive-se, portanto, os autos, de modo definitivo"
]

r = re.compile(r'\b(?:arquiv|auto)(\w+).*?(?:auto|arquiv)?.*?(?:definitiv)?')
for frase in frases:
    if r.search(frase):
        print('encontrou a frase {}'.format(frase))

A regex encontra todas as frases, exceto a que tem "desarquivamento". .*? é "zero ou mais caracteres", garantindo que pode ter qualquer coisa entre as palavras desejadas.
E os ? logo depois dos parênteses tornam todo o trecho opcional, assim, tanto o segundo parênteses (com auto|arquiv) quanto o terceiro (com definitiv) são opcionais.

Lembrando que essa regex é bem "ingênua" e propensa a falsos-positivos, dependendo de quão complexas forem as frases que você quer avaliar. Dependendo do que você quer fazer, talvez seja melhor seguir a recomendação que o Anderson deu nos comentários
Comment: Grato, @hkotsubo. Na verdade, estou experimentando alternativas. Dependendo de como as coisas irão, mudarei a abordagem para melhor atender o problema. Mas suas instruções serviram para o que eu precisava no momento.
Answer: Com este regex você consegue algo parecido:
(autos?)|((?<!\w)arquiva(dos)?|(\-se)?)
Aqui você pode executar
O segredo aqui é o look behind, aqui explica bem.
(?<!\w) significa: olhe para trás e veja se tem uma palavra(conjunto de caracteres), se tiver, não corresponda.
Esse regex pode não estar 100%, mas creio que vá te ajudar.


How do you find the condition where the Cauchy-Schwarz inequality is equal?

Question:
Cauchy-Schwarz inequality: $\left| \sum\limits_{i=1}^n a_i b_i \right|^2 \leq \sum\limits_{i=1}^n |a_i|^2 \sum\limits_{i=1}^n |b_i|^2$

The answer is known to be when $a_i k + b_i = 0$ for some $k \in \mathbb{R}$, or any other equivalence (e.g. in linear algebra, when the vectors are linearly dependent).
My question is, without a priori knowledge that equality holds for Cauchy-Schwarz if and only if [condition such as $a_i k + b_i = 0$ or some equivalent condition], how do you find this condition? i.e. the question is not to prove some 'if and only if' statement, but how you go about discovering the specific condition(s) required for equality, which leads to the 'if and only if' statement.
For example, I tried experimenting with the Cauchy-Schwarz inequality in more familiar terms:
$\left| x_1 y_1 + x_2 y_2 \right|^2 = \left(\left| x_1 \right|^2 + \left| x_2 \right|^2 \right) \left( \left| y_1 \right|^2 + \left| y_2 \right|^2 \right)$
$x_1^2 y_1^2 + x_2^2 y_2^2 + 2x_1y_1x_2y_2 = x_1^2 y_1^2 + x_2^2 y_2^2 + x_1^2y_2^2 + x_2^2y_1^2$
So they are equal when $2x_1y_1x_2y_2 = x_1^2y_2^2 + x_2^2y_1^2$. But I couldn't conclude anything from this equation.
Answer: You can re-write the Cauchy-Schwarz inequality (for sequences of real numbers) as:
$$
\displaystyle\sum_{i<j} (a_ib_j - a_jb_i)^2 \geq 0
$$
But squares are non-negative, and so we only have equality when all terms are zero, i.e. when
$$
a_ib_j = a_jb_i
$$
for all $i,j$.
Verifying this alternative form is just a matter of expanding all the terms - trying it for small cases may help you to see how it works.
Answer: Here is an elementary point of view. You may observe that, for any $\lambda \in \mathbb{R}$,
$$
\sum_{i=1}^n \left(a_i\lambda+b_i \right)^2\geq0 \tag1
$$ is equivalent to
$$
\left(\sum_{i=1}^n a_i^2\right)\lambda^2+2\left(\sum_{i=1}^n a_i b_i\right) \lambda+\left(\sum_{i=1}^n b_i^2\right)\geq0 \tag2
$$ which is equivalent to (one may think in terms of the discriminant of the quadratic equation)
$$
\Delta'=\left(\sum_{i=1}^n a_i b_i\right)^2-\left(\sum_{i=1}^n a_i^2\right)\left(\sum_{i=1}^n b_i^2\right)\leq 0 \tag3
$$ giving the Cauchy-Schwarz inequality.
From $(1)$, it is clear that $\Delta'=0$ if and only if

$$\sum_{i=1}^n \left(a_i\lambda+b_i \right)^2=0 \tag4$$

that is if and only if

$$
a_i\lambda+b_i=0,\quad i=1,2,\cdots. \tag5
$$
Answer: One way of doing it:

It's simple to show that if $a=\alpha\cdot b$ where $a,b$ are vectors, then $$\langle a,b \rangle\ = \alpha \|b\|^2 = \|a\|\|b\|$$
Let's say that $a,b$ are not linearly dependent. Then, take $b'$ to be the orthogonal projection of $b$ onto $a$. Then, $b = b' + (b-b')$ and $b-b'$ is orthogonal to $a$ and $b'$ is paralel to $a$, $b'=\alpha a$ (by definition). Also, $$\|b\|^2 = \|b'\|^2 + \|b'-b\|^2$$This means that $$\langle a,b\rangle = \langle a,b'\rangle + \langle a,b-b'\rangle = \alpha \langle a,a\rangle + 0 = \alpha \|a\|^2 = \|a\|^2 \|b'\|^2 < \|a\|^2\|b\|^2$$
Comment: You have to be a little more careful: $\alpha$ might be negative.


não consigo encontrar o meu erro

Question: Esse código funciona no topo do meu site (menu), e estou tentando usar ele também no rodapé, já que tenho a aba de registro tanto no topo quanto no rodapé, mas no rodapé ele não funciona.
Alguém pode me ajudar a encontrar o erro? ou é simplesmente impossível utilizar o mesmo código no topo e no rodapé? Lembrando que estou criando todas as páginas separadas (rodapé é uma página, menu é outra, e juntando elas com php. Por esse motivo, acredito eu, que não deveria dar erro, já que, supostamente, não estão em contato direto uma página com a outra.
Alguém pode me ajudar no que devo fazer para que funcione nas duas páginas? Tenho que mudar ou acrescentar algo?

function valida_campos() {
  if (document.getElementById('name').value == '') {
    alert('The field name is obrigatory.');
    document.getElementById('name').focus();
    return false;
  }
  if (document.getElementById('lastname').value == '') {
    alert('The field lastname is obrigatory.');
    document.getElementById('lastname').focus();
    return false;
  }
  if (document.getElementById('birthday').value == '') {
    alert('Field birthday is obrigatory.');
    document.getElementById('birthday').focus();
    return false;
  }
  if (document.getElementById('email').value == '') {
    alert('The field email obrigatory.');
    document.getElementById('email').focus();
    return false;
  }
  if (document.getElementById('password').value == '' || document.getElementById('password').value != document.getElementById('password2').value) {
    alert('Password didnt mach, please try again.');
    document.getElementById('password').focus();
    return false;
  }
}
<form class="default-form" action="cadastrar.php" method="post" onSubmit="return valida_campos();">

    <input name="name" id="name" type="text" placeholder="Name">

    <input name="lastname" id="lastname" type="text" placeholder="Last Name">

    <input name="birthday" id="birthday" type="text" placeholder="birthday d/m/y">

    <input name="email" id="email" type="text" placeholder="Email">

    <input name="password" id="password" type="password" placeholder="Password">

    <input name="password2" id="password2" type="password" placeholder="Repeat Password">

  <input type="submit" placeholder="cadastrar">

</form>
Comment: Eu dei submit pelo jsfiddle e foi, tem certeza que está com erro?
Comment: @LaércioLopes, @WesleyNascimento,  esse `return` [é importante](https://pt.stackoverflow.com/a/229559/129).
Comment: Deve tah gerando duplicidade de formulário. Neste caso, terá na mesma página dois formulários idênticos, e o Javascript irá considerar apenas o primeiro. A solução é criar um mecanismo para diferenciar um formulário do outro, ou então (pra mim a melhor forma) é usar o formulário de forma dinâmica, puxando o HTML do formulário de acordo com o local em que foi chamado (topo ou rodapé).
Comment: O problema não é no script em si. Colocando o formulário no topo e no rodapé, vc está colocando o mesmo formulário 2 vezes na mesma página, e o Javascript irá reconhecer apenas o primeiro. Por isso quando vc preenche o formulário no rodapé, o Javascript irá verificar o do topo que está em branco.
Comment: Mikaela, dei um edit na pergunta. O erro que tens está presente na pergunta agora editada/formatada?
Comment: Testei também, quando os campos estão preenchidos ele identifica corretamente. Pergunta: no `onSubmit` precisar do `return`?
Comment: Acho que é indiferente a existência desse return
Comment: Pode ser outro script no seu site, porque também testei aqui e esta funcionando normalmente.
Comment: entao, eu também fiz o teste, estou usando esse script no topo (menu) e no rodapé do meu site, no topo funciona perfeitamente, mas no rodape fica dando erro, da erro em todos os input conectados com javascipt...
Comment: Qual é o erro? Ainda não falou.
Comment: isso de usar o código no topo e rodape ... aba de registro tanto no topo quanto no rodapé .... não estão em contato direto uma pagina com a outra... Está meio confuso!! Melhor postar tudo na pergunta.
Comment: O que você tem no topo e rodape? o mesmo formulario para trabalhar com o script?
Comment: Ela só descreveu o que está fazendo e que está dando erro, mas não disse qual é o erro (formulário não envia, javascript não responde, formulário em branco etc)... Pelo que percebi, talvez ela esteja usando o mesmo formulário no topo e no rodapé, aí o Javascript vai pegar apenas o formulário do topo, mesmo usando a do rodapé.
Comment: assim, eu tenho 3 paginas, o index, o rodape e o topo, todas em php, no index, eu inclui o todo e o rodape, quando eu rodo o script no topo, da tudo certo, tudo ok, quando eu rodo o script no rodape, ele fica aparecendo que os campos estao vazios, todos eles, essa é a minha pergunta, mesmo estando em paginas separadas, eu nao consigo utilizar o mesmo formulario? Com o mesmo script em javascript?
Comment: Coloca na pergunta o código que vc faz com que o formulário apareça no topo e aí podemos achar uma solução fácil pra isso. Ou ele já aparece no carregamento da página sem precisar clicar em nada?
Comment: Galera, agradeço muito a ajuda, consegui arrumar, troquei o ID dos campos do formulário e do javascript do rodapé e agora está funcionando 100%, =DDD
Comment: Isso dá certo mesmo, mas não é a melhor prática ficar com dois formulários praticamente repetidos. Quando vc quiser fazer alguma alteração em um, terá que fazer nos dois. Mas se está dando certo, sucesso!
Comment: to me debatendo mas to aprendendo hahaha, ainda tenho que descobrir como colocar os 2 em um só sem dar problemas, mas confesso que, mesmo tendo mais trabalho, estou feliz de ter conseguido hehehe
Answer: Uma forma de deixar os dois formulários repetidos e o mesmo JavaScript que faz a validação é identificar qual formulário está sendo usado (do topo ou do rodapé) e validar apenas este (ignorando o outro) é usando o código abaixo (requer jQuery):
Coloque no <form> o parâmetro this no onsubmit que servirá pra identificar o formulário, desta forma:
onSubmit="return valida_campos(this);"

A vantagem de usar o this é que deixará seu código bem mais enxuto e
  fácil de trabalhar, além de diminuir os bytes da sua página, melhorando a performance.

Adicione a variável i na função que irá receber esse parâmetro:
function valida_campos(i) {....

No início da função, adicione o código:
for(x=0;x<=$(".default-form").length;x++){
    if($(i).index() != x){
        formulario = $(".default-form:eq("+x+")").detach();
    }
}

Este código irá identificar qual dos dois formulário foi usado e
  "destacar" o outro, tornando-o fora do escopo do JavaScript.

Seu código completo ficaria assim:
HTML
<form class="default-form" action="cadastrar.php" method="post" onSubmit="return valida_campos(this);">

    <input name="name" id="name" type="text" placeholder="Name">

    <input name="lastname" id="lastname" type="text" placeholder="Last Name">

    <input name="birthday" id="birthday" type="text" placeholder="birthday d/m/y">

    <input name="email" id="email" type="text" placeholder="Email">

    <input name="password" id="password" type="password" placeholder="Password">

    <input name="password2" id="password2" type="password" placeholder="Repeat Password">

  <input type="submit" placeholder="cadastrar" value="ok">
</form>

JavaScript
function valida_campos(i) {

    for(x=0;x<=$(".default-form").length;x++){
        if($(i).index() != x){
            formulario = $(".default-form:eq("+x+")").detach();
        }
    }

  if (i.name.value == '') {
    alert('The field name is obrigatory.');
    i.name.focus();
    return false;
  }
  if (i.lastname.value == '') {
    alert('The field lastname is obrigatory.');
    i.lastname.focus();
    return false;
  }
  if (i.birthday.value == '') {
    alert('Field birthday is obrigatory.');
    i.birthday.focus();
    return false;
  }
  if (i.email.value == '') {
    alert('The field email obrigatory.');
    i.email.focus();
    return false;
  }
  if (i.password.value == '' || i.password.value != i.password2.value) {
    alert('Password didnt mach, please try again.');
    i.password.focus();
    return false;
  }
}

não consigo encontrar o meu erro


Does the man with an extra day of rest at the Australian Open have an advantage?

Question: It seems the Australian Open is the only Grand Slam event in tennis that does not have both men's singles semifinal matches on the same day.  This means the man who won his semifinal match on Thursday will have 2 days of rest before the final, and the man who won his semifinal match on Friday will only have 1 day of rest.  It would seem that the man who has 2 days of rest would have an advantage, especially if both of the semifinals went 5 sets.
Has there been any analysis or statistics (such as win-loss record) that show that the man with 2 days of rest indeed has an advantage?
Comment: It's also strange that for the 2019 AO, they put #2 seed Nadal's semifinal on Thursday and #1 seed Djokovic's semifinal on Friday.  Why give any possible advantage to the #2 seed instead of the #1 seed?
Answer: Well, after disappointment in finding the useful tennis databases failed to give match dates, decided to slog it out a bit to try to at least get you something slightly useful.
I used date-restricted Google searches (such as this one) and skimmed the news articles results that were known-legitimate publications until coming across articles showing the other semifinal was to be played the next day.  And this is what I managed to scrabble together for the finals result (using Wikipedia for result) of those players who got the extra day off by playing the earlier semifinal:
2017: Federer       Win
2016: Djokovic      Win
2015: Murray        Loss
2014: Wawrinka      Win
2013: Djokovic      Win
2012: Nadal         Loss
2011: Djokovic      Win
2010: Murray        Loss
2009: Federer       Loss
2008: Tsonga        Loss
2007: Federer       Win
2006: Baghdatis     Loss
2005: Safin         Win
2004: Safin         Loss
2003: Agassi        Win
2002: Johansson     Win
2001: Agassi        Win
2000: Agassi        Win
1999: Enqvist       Loss
1998: Korda         Win
1997: Moya          Loss
So if I made no mistakes, the extra rest lead the final match series just slightly: 12-9.
A slight advantage shown, but nowhere near statistically significant in that sample size (a binomial 95% confidence interval of winning anywhere from 34%-78%).
So, you'd absolutely need more data before a conclusion can be made.  It may seem a hint that it has an impact, but it's quite possible that it has no impact (or even a losing one!)
And, indeed, such a trend could still be masked by seeding, injuries, and a million other things.
If I've run statistics right, it looks like you'd need well over 50 years of data to be able to have much hope of drawing any conclusion even in a large case, and even more if the impact is subtle.
But long story short: it appears all hints so far... is that I'm trending towards basically everything jamauss said!
Comment: Nice research! It will be also important to know if the first semi-final is seed-influenced or not
Comment: Interesting to see the outcomes for the past 21 finals. I guess I wasn't too far off.
Answer: The sport of Tennis is way behind other professional sports as far as statistical data and analysis goes, so it's not likely you will be able to even find the data to perform this kind of analysis.
As someone who has been watching all of the grand slam tennis events for over 20 years, I can just share my opinion that the extra day of rest does not matter very much. The players at the top of the game are all very fit and their bodies are able to recover quickly. It would surprise me if there was any pattern indicating that an extra day of rest gave one player an advantage over another.
I also think you would need to take into consideration other factors such as total time on court for their previous 6 matches, distance traveled during those matches, and perhaps quality of opponent.
Comment: I would be surprised if this data is missing. Provided they pay people to send real-time data of matches for bookmakers, it is unlikely this data has not been collected already. I'd assume it is kept proprietary for the purposes of the bookmakers.
Comment: The data could be gathered (as JeopardyTemptest did) - it's just not easy to come by in the traditional sense - e.g. going to the ATP Website and looking up the date of the matches.


Execute multiple dependent commands individually with Paramiko and find out when each command finishes

Question: I am writing a program in Python which must communicate through SSH with a physical target, and send to this targets some commands automatically (it is for testing).
I start by doing this with Paramiko and everything was perfect until I have to send several commands and when for example the second one must be execute in the context of the first (for example the first one makes cd /mytargetRep and the second one is ./executeWhatIWant). I can't use exec_command to do so, because  each exec_command starts a new session.
I try to use a channel with invoke_shell(), but I have an other problem with this one: I don't know when command execution is ended by doing this. I can have some very short (in time) command execution, and some other are really more longer so I need to know when the command execution is over.
I know a workaround it to use exec_command with a shell logic operations such as && or using ;. For example exec_command("cd /mytargetRep && ./executeWhatIWant"). But I can't do that, because  it must also be possible to execute some commands manually (I have a minimalist terminal where I can send commands), so for example, the user will make cd /mytargetRep then ./executeWhatIWant and not cd /mytargetRep && ./executeWhatIWant.
So my question is: is there a solution by using Paramiko to send several commands in a same SSH session and be able to know the end of the command execution?
Thanks
Answer: It seems that you want to implement an interactive shell, yet you need to control individual commands execution. That's not really possible with just SSH interface. "shell" channel in SSH is black box with an input and output. So there's nothing in Paramiko that will help you implementing this.
If you need to find out when a specific command finishes or where an output of a specific command ends, you need to use features of a shell.
You can solve that by inserting a unique separator (string) in between and search for it in the channel output stream. With a common *nix shells something like this works:
channel = ssh.invoke_shell()
channel.send('cd /mytargetRep\n')
channel.send('echo unique-string-separating-output-of-the-commands\n')
channel.send('./executeWhatIWant\n')

Though I do not really think that you need that very often. Most commands that are needed to make a specific commands working, like cd or set, do not really output anything.
So in most cases you can use SSHClient.exec_command and your code will be a way simpler and more reliable:
Execute multiple commands in Paramiko so that commands are affected by their predecessors
Even if you need to use something seemingly complex like su/sudo, it is still better to stick with SSHClient.exec_command:
Executing command using "su -l" in SSH using Python

For a similar question, see:
Combining interactive shell and recv_exit_status method using Paramiko