Keep bottom sheet on top of any pages in masterDetailPage Xamarin

Question: I'm pretty new on developing apps with xamarin for android and ios in c#. So I created an app for my music station to play music and it contains a MasterDetailPage. On the top left is the menu to select different kinds of pages. But I want to have a static bottom sheet slider form on the bottom where you can start or stop the music which must be displayed all the time and keeps playing while switching other pages. But I also would like to give the user the option to slide this particular form up to see which song is playing and some other info. And the music must keep playing while navigating through other pages.
By now, my app starts with:
MainPage = new MainPage();
And in the MainPage.xaml is:
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            xmlns:views="clr-namespace:Test.Views"
            x:Class="Test.Views.MainPage">

    <MasterDetailPage.Master>
        <views:MenuPage />
    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <NavigationPage>
            <NavigationPage.Icon>
                <OnPlatform x:TypeArguments="FileImageSource">
                    <On Platform="iOS" Value="tab_feed.png"/>
                </OnPlatform>
            </NavigationPage.Icon>
            <x:Arguments>
                <views:ItemsPage />
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>

</MasterDetailPage>

And then it calls MenuPage which loads the menu and stuff.
What is the best way and how can I do this?
Example
Comment: Do you mean the botton sheet do the thing of Menu page? Do you wat to do something like screenshot: https://imgur.com/HeY3j0Y Use the bottom sheet as Menu Page?
Comment: @WendyZang-MSFT Yes indeed. But also visible on all pages when I open another page. I would like to keep that slider always visible because it shows the streaming music player and track information. So I think it stops playing when another page is displayed and the user cannot control it than, eg stop or pause the music. Thanks!
Answer: For the bottom sheet, you could refer to the code below.
  <RelativeLayout>

    <StackLayout Padding="10,20,0,0">

    </StackLayout>
    <Frame
        x:Name="bottomSheet"
        Padding="1,4,1,0"
        BackgroundColor="#faf9f8"
        CornerRadius="8"
        HasShadow="true"
        RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,
                                                               Property=Height,
                                                               Factor=1,
                                                               Constant=0}"
        RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
                                                              Property=Width,
                                                              Factor=1,
                                                              Constant=0}"
        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
                                                          Property=Height,
                                                          Factor=.9,
                                                          Constant=0}">
        <Frame.GestureRecognizers>
            <PanGestureRecognizer PanUpdated="OnPanUpdated" />
        </Frame.GestureRecognizers>
        <StackLayout Spacing="5">
            <BoxView
                BackgroundColor="Gray"
                CornerRadius="2"
                HeightRequest="5"
                HorizontalOptions="Center"
                WidthRequest="50" />
            <SearchBar
                x:Name="SearchBox"
                BackgroundColor="Transparent"
                Focused="SearchBar_Focused"
                Placeholder="Search by Ingredient"
                 />
            <StackLayout x:Name="GridFilter">
                <Button />
            </StackLayout>
        </StackLayout>
    </Frame>
</RelativeLayout>

Code Behind:
public Page7()
    {
        InitializeComponent();
    }
    public double getProportionCoordinate(double proportion)
    {
        return proportion * Height;
    }

    private void SearchBar_Focused(object sender, FocusEventArgs e)
    {
        GridFilter.IsVisible = true;
        openBottomSheet();
    }
    void openBottomSheet()
    {
        var finalTranslation = Math.Max(Math.Min(0, -1000), -Math.Abs(getProportionCoordinate(.85)));
        bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 150, Easing.SpringIn);
    }
    // Important Code Lives Below
    double x, y;
    private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
    {
        // Handle the pan
        switch (e.StatusType)
        {
            case GestureStatus.Running:
                // Translate and ensure we don't y + e.TotalY pan beyond the wrapped user interface element bounds.
                var translateY = Math.Max(Math.Min(0, y + e.TotalY), -Math.Abs((Height * .25) - Height));
                bottomSheet.TranslateTo(bottomSheet.X, translateY, 20);
                break;
            case GestureStatus.Completed:
                // Store the translation applied during the pan
                y = bottomSheet.TranslationY;

                //at the end of the event - snap to the closest location
                var finalTranslation = Math.Max(Math.Min(0, -1000), -Math.Abs(getClosestLockState(e.TotalY + y)));

                //depending on Swipe Up or Down - change the snapping animation
                if (isSwipeUp(e))
                {
                    bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 250, Easing.SpringIn);
                }
                else
                {
                    bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 250, Easing.SpringOut);
                }

                //dismiss the keyboard after a transition
                SearchBox.Unfocus();
                y = bottomSheet.TranslationY;

                break;

        }
    }

    public bool isSwipeUp(PanUpdatedEventArgs e)
    {
        if (e.TotalY < 0)
        {
            return true;
        }
        return false;
    }
    //TO-DO: Make this cleaner
    public double getClosestLockState(double TranslationY)
    {
        //Play with these values to adjust the locking motions - this will change depending on the amount of content ona  apge
        var lockStates = new double[] { 0, .5, .85 };

        //get the current proportion of the sheet in relation to the screen
        var distance = Math.Abs(TranslationY);
        var currentProportion = distance / Height;

        //calculate which lockstate it's the closest to
        var smallestDistance = 10000.0;
        var closestIndex = 0;
        for (var i = 0; i < lockStates.Length; i++)
        {
            var state = lockStates[i];
            var absoluteDistance = Math.Abs(state - currentProportion);
            if (absoluteDistance < smallestDistance)
            {
                smallestDistance = absoluteDistance;
                closestIndex = i;
            }
        }

        var selectedLockState = lockStates[closestIndex];
        var TranslateToLockState = getProportionCoordinate(selectedLockState);

        return TranslateToLockState;
    }

Screenshot:
Comment: Ok, but if I have a MasterDetailPage where all my pages are being displayed? Works that the same?
Comment: You could add the code for the details page or create a base page with the bottom sheet.
Comment: I have used this option. Everything working well but when using a ListView inside StackLayout (Main Body content) last two items not showing


How to print only the surname from a data frame column in ggplot2 (R)?

Question: Suppose there's a data frame with all US presidents, a snippet of which is here:
    year winner           win_party
    1860 Abraham Lincoln  Rep.
    1864 Abraham Lincoln  Rep.

Using other code that isn't relevant here, I plot their names on a graph in ggplot2. However, I don't want the full name to be printed, just the surname (so e.g. Lincoln, not Abraham Lincoln). The problem is somewhere here:
library('ggplot2')
library('ggrepel')

geom_text_repel(
    aes(label = ifelse(winner %in% c("Joe Biden", "Donald Trump"), paste(winner, year), winner))

In this situation, "Joe Biden" and "Donald Trump" from the list of presidents would be pasted. Instead, I just want "Biden" and "Trump". Does anyone know where I can edit this for this to be possible?
Answer: If we want to create a new column of substring, word can be used to extract the second word from 'winner' column and it can be passed as label
library(dplyr)
library(stringr)
df1 <- df1 %>%
   mutate(last_name = word(winner, 2))


How to find a pattern in this recursive sequence algorithmically?

Question: I'm trying to find the closed-form of a sequence algorithmically.
Here is the recursive sequence:
$$w_k=w_{k-2}+k, \forall k \in \Bbb{Z} | k \geq 3, w_1=1, w_2=2$$
which produces this sequence: $1,2,4,6,9,12,16,22,25,30,...$
which has the following explicit formula after a bit of trial and error:
$$w_n=\begin{cases}
({\frac{n+1}{2}})^2 \text{if } n \text{ is odd}\\
\frac{n}{2}(\frac{n}{2}+1) \text{if } n \text{ is even}\\
\end{cases}$$
How can I do this without randomly guessing or trial and error?
Answer: Well you could do it by telescoping. Since the jump here is $2$ i.e we get $w_k$ from $w_{k-2}$ it is clever to divide it into odd and even cases.Suppose we want to find $\{w_{2k}\}$
Now see that $w_{2k+2}-w_{2k}=2k+2$ sum this for $k=1$ to $k=n-1$ then get $w_{2n}-w_2=n(n-1)+2n-2=n^2+n-2\implies w_{2n}=n^2+n$ precisely the formula for $n=$ even.Similarly we get $w_{2n+1}-w_{2n-1}=2n+1$ and summing over we have $w_{2n+1}=(n+1)^2$.This is the method that will work here.
Comment: Why did you sum it from k=1 to k=n-1? And I don't see how you got $w_{2n}-w_2=n(n-1)+2n-2=n^2+n-2\implies w_{2n}=n^2+n$.
Comment: Ummm summing to $n-1$ means the last term left is $w_{2(n-1)+2}=w_{2n}$ and the equality holds since $w_2=2$ and $n(n-1)+2n-2=n^2+n-2$ I hope this is understandable since there is nothing except plain arithmetic in it.Hope this helps.


Iterating over nested objects in Stylus

Question: I have a build script that complies my stylus and passes some data in.
stylus(stylFile)
  .set('filename', 'index.css')
  .define('data', require('./data.json'))
  .render(...)

The data.json file contains an object of groups, and each group is composed of more objects that represent items.
{
  "group1": {
    "item1": {
      "width": 1
    },
    "item2": {
      "width": 2
    }
  },
  "group2": {
    "item3": {
      "width": 3
    }
  }
}

In my Stylus file I want to iterate through the groups, and then through their items like so
for group, items in data
  #{group}
    for id, item in items
      #{id}
        width item.width

I would expect the output of this to be
#group1 #item1 {
  width: 1;
}
#group1 #item2 {
  width: 2;
}
#group2 #item3 {
  width: 3;
}

Instead I get
ParseError: index.css:118:1
   114|   #{group}
   115|     for id, item in items
   116|       #{id}
   117|         width item.width
   118|
--------^

expected "indent", got "outdent"

Comment: I have a feeling that this has something to do with Stylus' built in "hashes" which my data must get coerced into.
Answer: I don't know how you get the json in stylus but with hash objects you can do this:
STYLUS
data={
  "group1": {
    "item1": {
      "width": 1
    },
    "item2": {
      "width": 2
    }
  },
  "group2": {
    "item3": {
      "width": 3
    }
  }
}

for group in data
  #{group}
    items = data[group]
    for item in items
      #{item}
        for property, value in items[item]
          {property} value

OUTPUT
#group1 #item1 {
  width: 1;
}
#group1 #item2 {
  width: 2;
}
#group2 #item3 {
  width: 3;
}

UPDATE
You can get the json from stylus file and convert in hash object:
data = json('data.json', { hash: true })

for group in data
  #{group}
    items = data[group]
    for item in items
      #{item}
        for property, value in items[item]
          {property} value

Comment: I get the json into stylus using the `define()` function in my build script. So NPM opens the JSON, turns it into a JS object, then hands that to Stylus which I presume coerces it into a hash.
Comment: Sorry, but your solution doesn't work for me when using data from JSON. I get `#id # {
  (null): 0;
}` repeated for each item.

Iterating over nested objects in Stylus


Serve Anonymous Pages when users are logged in for some pages

Question: so essentially I have a Drupal website with great performance for anonymous users and terrible performance for logged in users.
What I am looking for is a way to serve some pages that logged in users access as if they were an anonymous user.
In custom development this would be done using a:
<code>cache-control:public
</code>
header for varnish, but obviously when viewing that page anything such as the users profile information and the login status must not be shown so its not cached in varnish.
I was hoping there would be a config change or module that could perform this without having to write a custom module,
any ideas would be greatly appreciated
Comment: Do you have the internal caching modules enabled? Are you using additional cache mechanisms like memcache or redis?
Comment: Have you looked at the Big Pipe module for Drupal 8 (assuming that the site in question is Drupal 8)?
Comment: For a low level solution like the one you've mentioned in custom development you could add `$response->headers->set('Cache-Control', 'public');` in a [response subcriber](https://drupal.stackexchange.com/questions/188924/how-to-embed-drupal-content-in-other-sites-remove-x-frame-options-sameorigin/201297#201297) and in the same subscriber remove the user related content from `$response->getContent()`.
Comment: @Kevin I'm using authcache with memcached but the performance vs varnish is significantly slower. With varnish I can handle well over 2000 simultaneous users, with authcache and memcached I struggle with more than 100 users
Comment: @ScottJoudry sorry forgot to mention the site in question is drupal 7, but always interested in solutions for drupal 8 sites
Comment: @4k4 interestingly if I don't find a perfect solution I could create a small module that looks for cache-control header and if its public remove user related information, as setting the header itself is fairly simple.
Answer: You may implement ESI block caching.
Have a look at ESI module  and varnish basic tutorial. You would be able then to cache whole pages except the blocks with session data.
Additionally, @Kevin comment points a complementary way: using Redis or Memcache will substantially speed the pages when logged, by caching data and objects in server memory to reduce the number of times the data source must be read.
Comment: Obviously this will be open to interpretation but how does this compare with authcache in terms of performance for logged in users? If it has superior performance I would be very interested in moving away from authcache.
Comment: I don't know, implement both and benchmark it ;). More seriously, there are several combinations of caching methods, I use Varnish for anon and redis for logged and it blazingly fasten websites, even with complex edit forms....


Client notifications in a domain

Question: We are interested in sending notifications to our user clients in a windows domain. So for example before restarting the file server (windows server 2016) we would like to inform (with a pop-up or so on their desktops) all online users that a restart will happen. Is this possible with integrated tools or third-party software?
Comment: There is a thing called Email. :-)
Comment: E-Mail is not an option since people should be forced to see it, even if the e-mail program is not running.
Answer: You can create a scheduled basic task with GPO. There is a task action called Display a message. Use this and run the task once at the time you like. This shows a simple message box with your text.
Answer:
msg.exe in combination with psexec could be something you want to look into (requires list of all computers on your domain.):
https://community.spiceworks.com/topic/431275-sending-messages-to-all-domain-users
Group message in Skype for Business (formerly known as Lync) (requires Skype / Lync and users to be signed in)
Plain email to all users
Email with an attached calendar event with notification in the past which will pop up for the users upon receiving it (requires Outlook afaik)
Custom software which runs in the background polling a server every couple seconds / minutes for a message and displays it as a popup for the user (quite simple to implement)
Answer: Try:
shutdown -r -t <time> -c "<comment>"

Comment: This isn't what the OP is asking for. This will make an entry into the Event log of the machine being shut down. No message will be sent to users of other computers in the domain.

Client notifications in a domain


subsets and sets

Question: I'm not so bad in math however I want to understand math the way mathematicians do, so I picked up this book How to Think Like a Mathematician. The book seems the book that I'm looking for. Definitely, it gonna be very long dark tunnel to me until I see the light. Any ways, he started with sets and I came across the following
1- For any set $X$, we have $X \subseteq X$.
2- For any set $X$, we have $\emptyset \subseteq X$.
I couldn't imagine  what do the two aforementioned statements imply. For the first one, how come a set is part of or equal itself? I can imagine the equality here but not the partition. The second statement, how come a non-empty set has an empty set? For example, let $ X = \{1, 2, 3\}$, now why $\emptyset \subseteq X$?
Comment: If you already understand why $X\subseteq X$ (because the little underline means that it is possible that $X=X$), then the other question has been thoroughly chewed all across the site.
Comment: Of course, some authors skip the underline and write $X \subset X$ to mean "X is a subset of (possibly equal to) X," and would write $\{1\} \subsetneq \{1, 2\}$ to mean that the first set is a proper subset of (not equal to) the second.
Comment: @AsafKaragila, no I'm not understanding $ X \subset X$ however $X = X$ makes sense.
Comment: I didn't use $X\subset X$ on purpose there.
Answer: A very good principle when starting out in any new area of maths: get really, really clear about key definitions. Don't just make a stab at guessing (or go by the perhaps misleading everyday terminology used in labelling, or by an informal gloss on the definition): look carefully at how key notions are rigorously defined.
Now, what does $X \subseteq Y$ mean, officially?

$X \subseteq Y$ holds, by definition, if and only if, for any $x$, if $x \in X$ then $x \in Y$.

Informally, yes, you might be tempted to gloss $X \subseteq Y$  as e.g. "$X$ is a part of $Y$"; that can be useful, but as you are finding, it can also be misleading. So forget for a moment the rough informal gloss and concentrate on the official definition.
Applied to your two cases, we have first, by definition

$X \subseteq X$ if and only if, for any $x$, if $x \in X$ then $x \in X$.

Well now ask: Is it the case that for any $x$, if $x \in X$ then $x \in X$? And so what does that tell you about $X \subseteq X$?
Second, we have by definition

$\emptyset \subseteq X$ if and only if, for any $x$, if $x \in \emptyset$ then $x \in X$.

Well now ask: Is it the case that for any $x$, if $x \in \emptyset$ then $x \in X$? Recall that $x \in \emptyset$ is always false: what happens to quantified conditionals where the antecedent is always false? And so what does that tell you about $\emptyset \subseteq X$?
Comment: I found it hard to understand the explanation of the second one. Can you explain it any more clearly?
Comment: @AaKASH: Recall that $\emptyset$ is empty (has no elements). So $x\in\emptyset$ is always false... there is nothing in $\emptyset$ so surely $x$ is not in there! Now any implication like "if A then B" in which A is false is always true. So if I say "If $x\in\emptyset$, then I have cats for ears," that implication is (vacuously) true because my hypothesis is false.
Comment: In other words: I promise You, IF you give me x from empty set, I will give you a million! Did I lie?
Answer: Both questions really boil down to how mathematicians use logic.
1.) $X \subseteq X$ means that for all elements of $X$ they are elements of $X$.
2.) $\emptyset \subseteq X$ means that for all elements of $\emptyset$ they are elements of $X$.
To see why 1.) is true, consider an element $x$ in the set $X$, well then we know that $x$ is in $X$ (!) and so we have shown that all elements from $X$ are also elements of $X$.
To see why 2.) is true, we must show that given an element of $\emptyset$ it must belong to $X$. But, there are no elements of $\emptyset$ and so the implication is (trivially) satisfied.
If you've studied truth tables then this corresponds to the case for "$P \Rightarrow Q$" where "P" is false.
Comment: Of course there's no doubt about it; that's why $X\subseteq X$ :p The symbol "$\subseteq$" has been defined so that it makes sense to ask for *any* $Y$ whether $Y\subseteq X$. Hence we can ask about $X$ itself; the answer turns out to be pretty trivial, but sometimes trivial truths are good to know.
Comment: you confused me more. For 1.), you are saying "for all elements of $X$ they are elements of $X$." Is there any doubt about it? Why this unintuitive way to explain this stuff.
Comment: @MaliceVidrine, this $Y \subseteq X$ makes perfect sense to me. Also, $ X = X $; Because $ \subseteq $ implies $ X \subset X$, this is where I got confused. How come a set becomes a part of itself?
Comment: The definition of $\subseteq$ has been explained. $X\subseteq X$ *because of the very meaning of* $\subseteq$--it's a logical truth that $X$ contains all the things that $X$ contains.
Comment: @CroCo:$Y\subseteq X$ **does not** imply $Y\subset X.$  The notation $Y\subseteq X$ means $Y\subset X$ or $Y=X.$  In general $P$ or $Q$ does not imply $P$.  All it means is that at least one of the statements $P$ or $Q$ is true.  They do not both need to be true.  Applying that to this situation, you cannot use $Y\subseteq X$ to conclude that $Y\subset X.$  In particular, you cannot use $X\subseteq X$ to conclude that $X\subset X.$
Comment: The comment above assumes that the notation $Y\subset X$ is used to denote the strict subset relation.
Comment: Moreover, the actual definition of "$\subseteq$" makes *no reference* to "$=$" or "$\subset$". "$X\subseteq Y$" is an *abbreviation* of "$\forall z(z\in X\Rightarrow z\in Y)$"; if you want the answer to your question, it's all in that formula.
Answer: $X$: "Hello set $Y$, is it so that any element of you is also an element of me?"
$Y$: "Yes."
$X$: "Well let us practicize a notation that expresses this fact: $Y\subseteq X$."

If $X$ would have asked the same question to himself then the answer would have been 'yes' too, right? So in the suggested notation: $X\subseteq X$.

Concerning 2):
$X$: "Hello set $\emptyset$, is it so that any element of you is also an element of me?"
$\emptyset$: "Well, I have no elements that are not. Even stronger, I have no elements at all. So again the answer is yes"
$X$: "Well let us practicize a notation that expresses this fact: $\emptyset\subseteq X$."
Comment: Awesome dialogue!
Comment: @drhab, again with the voodoo. why is $X \subset X$ true? I'm not finding a good answer for this question.
Comment: Read carefully; it's $X \subseteq X$, not $X \subset X$.
Comment: If it is - in spite of all the answers on this question - not yet
clear to you that $X\subseteq X$ then I cannot be of help anymore.
The notation $A\subset B$ is quite often used to express that $A$
is a **proper** subset of $B$, wich means that $A\subseteq B$ **and**
$A\neq B$. That means that $X\subset X$ is simply not true. But as I said: quite often, but not always. There are
lots of authors using notation $\subset$ instead of $\subseteq$
and using notation $\subsetneq$ instead of $\subset$. In every book/script
you should check on what side the author is on.
Answer: $(1)$ Lets consider something that may seem more familiar. The symbol "$\le$" means less than on or equal to, so if we see $a\le b$, one of the following criteria hold:
$(i)\,a\lt b$ ($a$ is strictly less than $b$), or
$(ii)\, a=b$.
Now it is clear that $a\le a$ because $(ii)$ holds.
Now we will work with subsets, $Y\subseteq X$ if:
$(i)$ every element of $Y$ is an element of $X$ (but $Y\ne X$), or
$(ii)$ $Y=X$
Now it is clear that $X\subseteq X$, because $(ii)$ holds.
$(2)$ the empty set $\varnothing$ is the set consisting of no elements. It is true that for any set $X$ we have $\varnothing\subseteq X$. So let us look at this constructively, as this a good way to see how things work.
How would one create a subset of $X$? One way would be to just remove elements of $X$, then what is left over would satisfy $(i)$, and thus be a subset.
Now remove all the elements of $X$ from $X$, what are you left with? A set consisting of nothing, I.e the eempty set, but still $(i)$ holds, so we see that $\varnothing\subseteq X$
Answer: The relation $\subseteq$ is just like the relation $\le$. It is not wrong to say that $x \le x$, i.e., "$x$ is less than or equal to $x$", although it's also true that $x = x$. The first is a weaker statement than the second, in that it conveys less information. But it's certainly not false in any way. Look at it another way: $\le$ [is less than or equal to] means the same thing as $\not >$ [is not greater than]. Is it true that $x$ is not greater than $x$? Yes. Then it is true that $x$ is less than or equal to $x$.
Similarly, $\subseteq$ [is a subset of] is equivalent to saying "does not contain elements not in". For example, $X \subseteq Y$ means "$X$ does contain any element that is not in $Y$". Is it true that $X$ does not contain any element not in $X$? Yes, it is always true. So $X \subseteq X$.
Now, let's apply this definition to the statement $\phi \subseteq X$. We know that $\phi = \{\}$, and let $X = \{1, 2, 3\}$, as in your example. Now, is it true that $\phi$ does not contain any element not in $X$? Yes! So $\phi \subseteq X$.
In more formal notation:

$X \subseteq Y \Leftrightarrow (\forall x \in X, x \in Y) \Leftrightarrow (\not\exists x \in X, x \notin Y)$
$(\forall x \in X, x \in X) \Rightarrow X \subseteq X$
$\not\exists x \in \phi \Rightarrow (\not\exists x \in \phi, x \notin X) \Rightarrow \phi \subseteq X$
Comment: You seem to be rather confused. $4 \leq 4$ does *not* imply $4<4$. Obviously $3\leq 4$, but this doesn't imply $3=4$; you're making a similar mistake.
Comment: why it is not wrong to say $x < x$? Let x = 4, saying 4 < 4 makes no sense at all.

subsets and sets


How many $10$-digit numbers (allowing initial digit to be zero) in which only $5$ of the $10$ possible digits are represented?

Question: The answer I found was $$(5^{10}-|\text{only}~4~\text{digits}|-|\text{only}~ 3|-|\text{only}~ 2|-|\text{only}~1|) \cdot C(10,5)=$$
where
$|\text{only}~1~\text{digit}| = 1^{10} \cdot C(10,1)$
$|\text{only}~2| = (2^{10}-|\text{only}~1|) \cdot C(10,2)$
$|\text{only}~3| = (3^{10}-|\text{only}~2|-|\text{only}~1|) \cdot C(10,3)$ ...etc
$5^{10}$ is supposed to represent the number of $10$ digit numbers which only use $5$ or fewer of $10$ distinct digits, just as there are $2^{10}$ binary strings of length $10$. I am subtracting from $5^{10}$ the number of strings which only contain $4$ distinct digits, $3$ distinct digits, $2$ distinct digits, and $1$ distinct digit, so I get the number of strings that use exactly $5$ distinct digits. I multiply by $C(10,5)$ because there are $C(10,5)$ ways to choose $5$ distinct digits. $|\text{only}~ 1|$ means the number of strings of length $10$ with exactly $1$ distinct digit.
For some reason I am not getting the right answer. Can someone tell me what I am doing wrong and post the correct answer please?
Comment: Why do you multiply the whole thing by C(10,5)? What does the 5^10 represent? And why are you subtracting from 5^10? In sum: Can you please explain the thinking behind your formula to us? That way, we can probably pinpoint where you're going wrong. Right now, we can only make a somewhat educated guess as to what you were thinking when coming up with this formula.  Also, providing you with the correct formula doesn't really help to correct your thinking either. If you want to improve your thinking on this, you'll have to tell us what your thinking is.
Comment: Do you mean only $5$ or exactly $5$ of the ten digits are represented in the string?  You seem to be interested in calculating the number of strings in which exactly five digits appear.
Comment: 5^10 is supposed to represent the number of 10 digit numbers which only use 5 or fewer of 10 distinct digits, just as there are 2^10 binary strings of length 10. I am subtracting from 5^10 the number of strings which only contain 4 distinct digits, 3 distinct digits, 2 distinct digits, and 1 distinct digits so I get the number of strings that use exactly 5 distinct digits. I multiply by C(10,5) because there are C(10,5) ways to choose 5 distinct digits. |only 1| means the number of strings of length 10 with exactly 1 distinct digits
Comment: Please read this [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), which explains how to typeset mathematics on this site.
Answer: In what follows, I will address the following question (which appears to be the intended one):

In how many $10$-digit strings are exactly five of the ten possible digits represented?

There are $\binom{10}{5}$ ways to select which five digits are included in the string and $5$ choices for each of the ten positions in the string, which gives $$\binom{10}{5}5^{10}$$
strings that may be formed using five digits.  From these, we must subtract those strings which use fewer than five of those digits.
There are $\binom{5}{1}$ ways to exclude one of those five-digits from the string and $4$ ways to fill each of the ten positions in the string with the remaining digits.  Hence, of the $5^{10}$ strings that can be formed with the particular set of five digits we have chosen, $\binom{5}{1}4^{10}$ exclude one of those digits.  This gives us a running count of
$$\binom{10}{5}\left[5^{10} - \binom{5}{1}4^{10}\right]$$
However, we have subtracted too much since we have subtracted each string from which two of the five digits are missing twice, once for each way we could have designated one of those digits as missing.  Thus, we must add them back.
There are $\binom{5}{2}$ ways to exclude two of the five selected digits and $3$ ways to fill each of the ten positions in the string with the remaining digits.  Hence, of the $5^{10}$ strings that can be formed with the particular set of five digits we have chosen, $\binom{5}{2}3^{10}$ exclude two of those digits.  This gives us a running count of
$$\binom{10}{5}\left[5^{10} - \binom{5}{1}4^{10} + \binom{5}{2}3^{10}\right]$$
However, now we have added too much since we have not excluded strings in which three of the five selected digits are excluded.  This is because we subtracted such strings three times, once for each way we could have designated one of the digits as the missing digit, and added them three times, once for each of the $\binom{3}{2}$ ways we could have designated two of the digits as the missing digits.  Thus, we must subtract those strings in which three of the digits are missing.
There are $\binom{5}{3}$ ways to exclude three of the five selected digits and $2$ ways to fill each of the ten positions in the string with the remaining digits.  Hence, of the $5^{10}$ strings that can be formed with the particular set of five digits we have chosen, $\binom{5}{3}2^{10}$ exclude three of those digits.  This gives us a running count of
$$\binom{10}{5}\left[5^{10} - \binom{5}{1}4^{10} + \binom{5}{2}3^{10} - \binom{5}{3}2^{10}\right]$$
However, we have subtracted too much.  We subtracted strings from which four of the five selected digits are excluded four times, once for each of the four ways we could have designated one of the missing digits as the missing digit; then added them six times, once for each of the $\binom{4}{2}$ ways we could have designated two of the missing digits as the missing digit; then subtracted them four more times, once for each of the $\binom{4}{3}$ ways we could have designated three of the missing digits as the missing digits.  Therefore, we have excluded strings from which four of the selected digits are missing twice.  However, we only want to exclude them once, so we must add them back.
There are $\binom{5}{4}$ ways to exclude four of the five selected digits and $1$ way to fill each of the ten positions in the string with the remaining digit.  Hence, of the $5^{10}$ strings that can be formed with the five digits we have chosen, $\binom{5}{4}1^{10}$ exclude four of those digits.  This gives us a running count of
$$\binom{10}{5}\left[5^{10} - \binom{5}{1}4^{10} + \binom{5}{2}3^{10} - \binom{5}{3}2^{10} + \binom{5}{4}1^{10}\right]$$
Since it is not possible to form a string if we exclude all five of the selected digits, the number of $10$-digit strings in which exactly five of the ten possible digits are represented is
$$\binom{10}{5}\left[5^{10} - \binom{5}{1}4^{10} + \binom{5}{2}3^{10} - \binom{5}{3}2^{10} + \binom{5}{4}1^{10}\right]$$
This argument is based on the Inclusion-Exclusion Principle.
Answer: Your $C(10,5)$ chooses which five digits will be used.  When you want to select the strings that use only one digit, you only want to subtract the ones that use one of these five digits, so it should be $C(5,1)$


Jquery inline css with display: block overrides my main css

Question: I'm currently working on a responsive menu, but the problem I'm running into that when I open the menu in mobile/tablet mode(less than 1100px wide), and I resize back to fullscreen my responsive menu will still show.
This is because the jquery toggle function add the display:block as inline css. I need it to be removed when somebody resizes back to fullscreen but I can't find a quick fix for this.
Could somebody be willing to help me out here? I would really appreciate it!
Here is my code, if you downsize it below 1100px width you can click the responsive menu button. If you go fullscreen again you can see both menu's are visible now.
Responsive menu codepen

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font: inherit;
  font-size: 100%;
  vertical-align: baseline;
}

html {
  line-height: 1;
}

ol, ul {
  list-style: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

caption, th, td {
  text-align: left;
  font-weight: normal;
  vertical-align: middle;
}

q, blockquote {
  quotes: none;
}
q:before, q:after, blockquote:before, blockquote:after {
  content: "";
  content: none;
}

a img {
  border: none;
}

article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary {
  display: block;
}

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

/*  #Allround menu style
================================================== */
.menu ul {
  list-style: none;
  width: 100%;
}

/*  #Default menu style
================================================== */
.default-menu {
  float: right;
}
.default-menu ul {
  float: right;
  padding: 20px 0;
}
.default-menu ul li {
  margin-left: 20px;
  float: left;
}
.default-menu ul li a {
  text-decoration: none;
  color: #000;
  padding: 10px 0;
  display: block;
}

/*  #Responsive menu style
================================================== */
.responsive-menu {
  display: none;
  text-align: center;
}
.responsive-menu ul li a {
  display: block;
  text-decoration: none;
  color: #000;
  background: whitesmoke;
  padding: 3em;
}
.responsive-menu ul li:last-child {
  border: none;
}

/*  #Navigational button
================================================== */
.nav-button {
  display: none;
  position: relative;
  width: 45px;
  height: 45px;
  float: right;
  margin: 10px 20px 0 0;
}
.nav-button span, .nav-button span:before, .nav-button span:after {
  width: 28px;
  height: 3px;
  position: absolute;
  background: black;
  left: 0;
}
.nav-button span {
  -moz-transition: background 0.2s 0.5s;
  -o-transition: background 0.2s 0.5s;
  -webkit-transition: background 0.2s;
  -webkit-transition-delay: 0.5s;
  transition: background 0.2s 0.5s;
  top: 21px;
  left: 8px;
}
.nav-button span:before {
  -moz-transition: -moz-transform 0.2s 0.5s;
  -o-transition: -o-transform 0.2s 0.5s;
  -webkit-transition: -webkit-transform 0.2s;
  -webkit-transition-delay: 0.5s;
  transition: transform 0.2s 0.5s;
  top: 8px;
  content: '';
}
.nav-button span:after {
  -moz-transition: -moz-transform 0.2s 0.5s;
  -o-transition: -o-transform 0.2s 0.5s;
  -webkit-transition: -webkit-transform 0.2s;
  -webkit-transition-delay: 0.5s;
  transition: transform 0.2s 0.5s;
  bottom: 8px;
  content: '';
}

.nav-button.is-visible span {
  visibility: hidden;
  background-color: rgba(255, 255, 255, 0);
}
.nav-button.is-visible span:before {
  -moz-transform: translateY(-8px) rotate(45deg);
  -ms-transform: translateY(-8px) rotate(45deg);
  -webkit-transform: translateY(-8px) rotate(45deg);
  transform: translateY(-8px) rotate(45deg);
  visibility: visible;
}
.nav-button.is-visible span:after {
  -moz-transform: translateY(8px) rotate(-45deg);
  -ms-transform: translateY(8px) rotate(-45deg);
  -webkit-transform: translateY(8px) rotate(-45deg);
  transform: translateY(8px) rotate(-45deg);
  visibility: visible;
}

.container {
  width: 1100px;
  margin: 0 auto;
}

.column-1 {
  width: 5.58333%;
}

.column-2 {
  width: 14.16667%;
}

.column-3 {
  width: 22.75%;
}

.column-4 {
  width: 31.33333%;
}

.column-5 {
  width: 39.91667%;
}

.column-6 {
  width: 48.5%;
}

.column-7 {
  width: 57.08333%;
}

.column-8 {
  width: 65.66667%;
}

.column-9 {
  width: 74.25%;
}

.column-10 {
  width: 82.83333%;
}

.column-11 {
  width: 91.41667%;
}

.column-12 {
  width: 100%;
}

.row {
  width: 100%;
  *zoom: 1;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}

[class*="column"] {
  float: left;
  margin-left: 3%;
}
[class*="column"]:first-child {
  margin-left: 0;
}

@media only screen and (max-width: 1100px) {
  .container {
    width: 90%;
  }

  [class*="column"] {
    margin: 0;
    width: 100%;
  }

  .responsive-menu .column-2 {
    width: 16.66667%;
    text-align: center;
    margin: auto;
  }

  .nav-button {
    display: block;
  }

  .default-menu {
    display: none;
  }
}
<!doctype html>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="css/main.css">
 <title>Responsive Menu</title>

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

Link 1

Link 2

Link 3

Link 4

Link 5

Comment: I think css media queries are the best to handle this type of behaviour https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/use-media-queries?hl=en
Comment: well you could simply .removeClass but yeah, use pure CSS3 media queries
Answer: It's not typical to have two menu lists for this type of thing. You should be able to do it with one. In that case, you'd be showing the menu for tablet/desktop sizes anyway, and your problem is moot.
This gets you close.
@media only screen and (min-width: 1100px) {
  .responsive-menu {
    display: block !important;
  }
  .nav-button {display: none;}
}

Note that I've removed the second menu list. You'll need to adjust styling for desktop.
Demo
Here it is with styling closer to your original.
@media only screen and (min-width: 800px) {
  .responsive-menu {
    display: block !important;
    text-align: right;
    padding: 20px 50px;
  }
  .responsive-menu > ul {
    display: inline-block;
    width: auto;
  }
  .responsive-menu > ul > li {
    display: inline-block;
    width: auto;
  }
  .responsive-menu > ul > li a {
    padding: 5px 10px;
    width: auto;
    background: transparent;
  }
  .nav-button {display: none;}
}

Demo 2


Amazon Beanstalk Web Server with Self Signed certificate?

Question: Is it possible to start Amazon Beanstalk Web Server in SSL mode with the Self Signed certificate?
Answer: Yes, it is possible.
You first need to create a self signed certificate first as described by the article below
http://www.akadia.com/services/ssh_test_certificate.html
and then you need to upload the certificate using aws iam command line tools (http://aws.amazon.com/developertools/4143):
iam-servercertupload --aws-credential-file ./aws-credential.txt -b www.example.com.crt -k www.example.com.key -s www.example.com-2012 -v


Add a filter with OR using sqlalchemy in eve pre_GET hook

Question: I am using Eve with the sqlalchemy branch to develop a REST API.
I want to add a filter to a GET request before the request is sent to the database, however I have found no way to do this yet.
What I want to do is basically this:
from sqlalchemy import or_

def pre_GET(resource, request, lookup):
    lookup.append(_or('field1'==1, 'field2'==2))

Of course this does not work, as lookup is a dictionary. However searching to the eve source code I can see no possibility to realize an OR. The lookup variable is parsed with parse_dictionary() in this file: https://github.com/nicolaiarocci/eve/blob/sqlalchemy/eve/io/sql/parser.py
The corresponding way when using MongoDB would be this:
lookup['$or'] = [{'field1': 1}, {'field2': 2}]

However this only works with MongoDB...
Answer: I understand this is an old question.
eve-sqlalchemy is now an extension with separate lifecycle/code base.
Current code base seems to handle or condition here
May be it works now ?

Update (Feb 06, 2016)
I tested this. Following syntax works :
lookup['or_'] = [{'field1': 1}, {'field2': 2}]

Notice or_ instead of $or you expected.
Comment: Yes, it has been patched. I figured out a solution back then, but I appreciate your answer.


Sum of number of divisors for square n

Question: So I've found that you can find the sum of $\sigma_0(n)$ by using:
$\sum_{i=1}^N \sigma_0(i) = \sum_{i=1}^N \lfloor \frac{N}{i} \rfloor$
or better yet:
$\sum_{i=1}^N \sigma_0(i) = \sum_{i=1}^f 2 * \lfloor \frac{N}{i} \rfloor - f^2$ where $f = \lfloor N^\frac{1}{2} \rfloor$
Is there a similarly useful expression for:
$\sum_{i=1}^N \sigma_0(i^2) = \space?$
Comment: Welcome Willie Wickerson first take a tour of the site then you will have an idea about the site
Answer: $\sum_{i=1}^N \sigma_0(i^2) = \sum_{i=1}^N 2^{\omega(i)}\lfloor \frac{N}{i} \rfloor$
and more generally
$\sum_{i=1}^N \sigma_0(i^k) = \sum_{i=1}^N k^{\omega(i)}\lfloor \frac{N}{i} \rfloor$

Sum of number of divisors for square n


how to find 'é' character using cygwin and grep?

Question: I want to find french characters in my java files. They are 'é', 'à', 'ê', 'è'. I need to locate all the files containing theses 'evil' characters (so anywhere in a string).
If I use grep under cygwin to find them it does not find anything.

grep -r -I 'é' .
grep -r -I \x82 .

None of the above found anything but there is a file in '.' containing 'é' character.
Can someone help?
Thanx
Comment: You might also want to use -i tu make it case-insensitive
Comment: The representation of these strings in the file and your command line's locale need to match. Please add this information to your question.
Comment: added some details, 'mostly Mostacho'' s answer is working!
Answer: I'm not in cygwin, but in linux. However, I don't think their grep differs that much from the linux one. This is the simple test I did and it seems to work fine:
<code>$ mkdir a_dir
$ cd a_dir
$ echo "this is a tèst" > a_file
$ grep -rl 'tèst' .
./a_file
$ cat a_file
this is a tèst
</code>
Can you do the same and tell me if the results are the same?
Answer: Try doing like this: cat *.java | grep '[éàêè]'
Comment: The Useless Use of Cat adds no benefit whatsoever, and `grep` can't tell you which file it found the match in if you call it like this.
Comment: @tripleee: It's not a true UUOC, since the behavior differs from the version without `cat` -- for the worse, in this case.
Comment: It is useless use, i know, but i just wanted to give a clue. I usually use expressions like that to test.


SVD of a positive definite matrix.

Question: Let $A$ be $n\times n$ complex matrix, positive definite: $x^* A x>0$ for any $x$.
Is it true that eigenvalues of $A$ are equal to singular values of $A$?
If $A$ is Hermitian, then it will be true from $\sigma_i=\sqrt{\lambda_i(A^*A)}$. But without assuming that $A$ is Hermitian, is it still true?
Comment: A positive definite complex matrix is hermitian in particular.
Answer: Positive definite matrices are unitarily diagonalisable and possess positive eigenvalues. Hence $A$ has the eigendecomposition $UDU^\ast$ for some unitary matrix $U$ and positive diagonal matrix $D$. Since this by itself is a singular value decomposition, the eigenvalues and singular values of $A$ coincide.

SVD of a positive definite matrix.


Regular tilings of n-simplex

Question: Consider a regular n-simplex (the n-dimensional generalisation of a triangle/tetrahedron).
A triangle will tile the plane in a triangular pattern.
In 4, 8 and 24 dimensions. Can we tile the volume with n-simplices?
And will the vertices of those simplices give the lattices $F_4$, $E_8$ and Leech lattice in turn?
i.e. will a 5-cell tile 4D space where the vertices form the lattice $F_4$. If not what shape does?
(These are the sphere packing solutions in those dimensions). But are they also tiling of n-simplices?
Edit: I just read that in fact a 24-cell can tessellate 4D space in a $F_4$ arrangement
Answer: The angle of an equilateral triangle is a sixth of $2\pi$, so we can fit
six of them round a point. Thus it is unsurprising that one can tile the
plane with equilateral triangles.
The dihedral angle of the regular tetrahedron is $\cos^{-1}(1/3)$. That
is not a rational multiple of $2\pi$, so one cannot fit them round an edge.
Thus a space packing of regular tetrahedra is impossible.
In $n\ge4$ dimensions, the same problem happens. The dihedral angle
of the regular $n$-simplex is $\cos^{-1}(1/n)$, not a rational multiple
of $2\pi$, and again a tiling with regular simplices is impossible.
Comment: Maybe the simplices are not regular.
Answer: The point symmetry of $F_4$ is "o3o4o3o" (typewriter friendly notation of Dynkin symbol).
Polytopes representing that symmetry can be obtained by extending either nodes into true (non-zero) edges, e.g. the 24-cell with Coxeter-Dynkin symbol "x3o4o3o".
That point symmetry is extendable into a euclidean space symmetry "o3o4o3o3o". A hyper-honeycomb representing that symmetry then is be obtained quite similarily, e.g. the already mentioned packing of 24-cells with symbol "x3o4o3o3o".
Just as the cells of the 24-cell are octahedra, as can be given symbolically by "x3o4o .", so the cells of that tetracomb (4D hyper-honeycomb) are indeed 24-cells, as can be seen symbolically "x3o4o3o .". And just as the vertex figure of the 24-cell is the cube, as symbolically is obtained accordingly by ". x4o3o", so alike the vertex figure of that tetracomb is deduced from ". x4o3o3o" as the tesseract. The tesseract is known to show up 8 cubical cells, therefore you'd get accordingly eight 24-cells per vertex in that tetracomb.
Alternatively you also could have considered the tetracomb "o3o4o3o3x" of the same euclidean space group instead. The cells here are ". o4o3o3x", also known as 16-cells. The vertex figure of that tetracomb would have been "o3o4o3x .", i.e. the 24-cell. As it is known that the 24-cell has 24 cells, accordingly this tetracomb will show up twenty-four 16-cells per vertex. - Infact, those too regular tetracombs are dual to each other.
Quite similarily the point group of $E_8$ is "o3o3o3o3o3o3o *e3o" (where the "*e" part is just the typewriter friendly inline representation of the tridental Dynkin symbol: the link adjoined to "*e" is meant to revisit the e-th so far already mentioned node). Polytopes representing that symmetry can be obtained by extending either nodes into true (non-zero) edges, e.g. the 8D Gosset polytopes $4_{21}$ with Coxeter-Dynkin symbol "x3o3o3o3o3o3o *e3o", $2_{41}$ with symbol "o3o3o3o3o3o3x *e3o" or $1_{42}" with symbol "o3o3o3o3o3o3o *e3x".
This point group further can be extended similarily into the euclidean space group "o3o3o3o3o3o3o3o *f3o". Thus the according octacombs (8D hyper-honeycomb) would be either $5_{21}$ or "x3o3o3o3o3o3o3o *f3o", $2_{51}$ or "o3o3o3o3o3o3o3x *f3o", resp. $1_{52}$ or "o3o3o3o3o3o3o3o *f3x".
The cells of $5_{21}$ then are both, "x3o3o3o3o3o3o3o *f ." (or 8D simplices), 17280 per vertex, and "x3o3o3o3o3o3o . *f3o" (or 8D cross-polytopes), 2160 per vertex.
The cells of $2_{51}$ are both, ". o3o3o3o3o3o3x *f3o" (Gosset polytopes $2_{41}$), 16 per vertex, and "o3o3o3o3o3o3o3x *f ." (or 8D simplices), 128 per vertex.
And finally the cells of $1_{52}$ then are both, ". o3o3o3o3o3o3o *f3x" (Gosset polytopes $1_{42}$), 9 per vertex, and "o3o3o3o3o3o3o . *f3x" (or 8D hemi-hypercubes), 9 per vertex as well.
Obviously all 3 of those octacombs therefore no longer are regular, as this would require just a single cell type at least.
(24D finally is beyond my grasp. I never managed to wrap  my mind around that Leech lattice.)
But for sure, in any dimension you would also have the hypercube "x4o3...3o", which allows to fill the according all-space regularily, as is shown by the hyper-honeycomb "x4o3...3o4o".
OTOH, the general $n$D simplex is encoded by the Coxeter-Dynkin symbol "x3o3...3o", i.e. it belongs to the point group $A_n$ or "o3o3...3o". And that group can indeed be continued into the euclidean space group "o3o3...3o3o3*a" (closed loop Dynkin symbol). Thus there surely are according hyper-honeycombs, obtained by extending either nodes into true (non-zero) edges, e.g. "x3o3...3o3o3*a". Sadly that one (and any other choice alike) will not be regular. This is simply because the cells here would be multiple again. Infact those are "x . o3...3o3o3*a" (simplex), "x3o . o3o3...3o3o3*a" (rectified simplex), "x3o3o . o3...3o3o3*a" (birectified simplex), ..., "x3o3...3o . o3*a" (rectified simplex again), "x3o3...3o3o . *a" (simplex again).
For instance the $A_2$ group "o3o" is being extended into "o3o3o3*a", giving rise to the tiling "x3o3o*a", which shows up the tiles "x3o . *a" (triangle) and "x . o3*a" (triangle again). Thus this one is regular.
But already $A_3$ would give rise to the extended (euclidean) space group "o3o3o3o*a". For that would provide the honeycomb "x3o3o3o$*$a", and that one would have for cells the types "x3o3o . *a" (tetrahedron), "x3o . o3*a" (octahedron), and "x . o3o3*a" (tetrahedron again).
--- rk

Regular tilings of n-simplex


Need an IP Range for google's CDN to set up a firewall

Question: Our website is being accessed by a client who's firewall is setup with whitelisted IP addresses vs FQDN/DNS names.  The trouble is that the website uses google's CDN to host jQuery and jQueryUI rather than storing them on our own server.
The challenge is that pinging google.com (and other variants of it) returns a different IP address depending on your location.
Is there a way to get the IP range of google's CDN (or any other CDN for that matter) to help configure an IP-based firewall?
Answer: The answer is way more complicated than ASN 15169.  First Google has more than one ASN:

15169   Google Inc.
  16591   Google Fiber Inc.
  36039   Google Inc.
  36040   Google Inc.
  36384   Google Incorporated
  36492   Google, Inc.
  41264   Google Switzerland GmbH

Second, Google, Akamai, etc use IP ranges of their partner ASNs to host content.  So if you are a Time Warner customer, you may see Google CDN content coming from a server close to you that has an IP associated with Time Warner (via ASN) and not Google.
After all the whole point of CDNs is to distribute content efficiently.
Answer: Their ASN is 15169; just have to look up the BGP table.
Comment: http://www.google.com/search?q=google+bgp+as
Comment: Excellent - how did you figure out their ASN?
Answer: Ultimately I doubt that your client will be will be willing to whitelist/unblock all of the google ASN as it contains so many IP's and will provide access to so much of the internet.
This is the problem you have with CDN's, they are made up of hundreds if not thousands of servers and consequently IP's.
Rather than using firewall rules, the normal way to limit interest access is to put a proxy server in front of your firewall which is configured to allow or block access to the internet/specific sites for all or specific users. Using this method your client can whitelist the hostname e.g cdn.google.com as allowed through the proxy and solve your problem but if they insist upon using firewall rules your only option is to either allow all the google IP's or alternatively use a different CDN with a much smaller amount of IP's e.g the rackspace cloud files CDN.
Comment: Those IPs all belong to Google... You're not opening yourself up to the Internet, just to one company (granted there's a ton of employees there, but that's quite different than "the Internet").
Comment: This is true, but... It's not the number of employees, but the amount of third party content hosted by Google, such as docs, YouTube and blogger. A proxy probably us smarter than IP based restrictions if you want to restrict outbound requests.


select2 dropdown with selenium

Question: I have a drop down in WordPress products page which is a select2 ajax enabled.
I have managed to show the options in the drop down using selenium.
But i am not able to select one of the options from the list.
I am able to get the element using the below code. But the element is not castable to Select nor clickable.
driver.findElement(By.cssSelector("[class='multiselect attribute_values wc-enhanced-select select2-hidden-accessible enhanced']"))

Any ideas how to select any option from it?
The HTML code for the drop down is

    Name:
    Brand
    <input type="hidden" name="attribute_names[0]" value="pa_brand">
    <input type="hidden" name="attribute_position[0]" class="attribute_position" value="0">

    Value(s):
    <select multiple="" data-placeholder="Select terms" class="multiselect attribute_values wc-enhanced-select select2-hidden-accessible enhanced" name="attribute_values[0][]" tabindex="-1" aria-hidden="true">
      <option value="107">Adidas</option>
      <option value="110">Gul Ahmed</option>
      <option value="111">Khadi</option>
    </select>

<input class="select2-search__field" type="text" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="Select terms" style="width: 418.797px;" aria-owns="select2-attribute_values0-to-results" aria-activedescendant="select2-attribute_values0-to-result-d16b-111">

    <button class="button plus select_all_attributes">Select all</button>
    <button class="button minus select_no_attributes">Select none</button>
    <button class="button fr plus add_new_attribute">Add new</button>

Comment: _But the element is not castable to Select nor clickable_: What error do you see?
Comment: When i call .click() on it i get org.openqa.selenium.ElementClickInterceptedException:
When i try to cast to Select i get ClassCastException Cannot cast RemoteWebElement to Select
Answer: As per the HTML:
<select multiple="" data-placeholder="Select terms" class="multiselect attribute_values wc-enhanced-select select2-hidden-accessible enhanced" name="attribute_values[0][]" tabindex="-1" aria-hidden="true">

The WebElement is clearly a <select> node and to select one of the options from the html-select tag you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

Using cssSelector and selectByVisibleText():
new Select(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("select.multiselect.attribute_values.wc-enhanced-select.select2-hidden-accessible.enhanced[data-placeholder='Select terms']")))).selectByVisibleText("Adidas");

Using xpath and selectByValue():
new Select(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//select[@class='multiselect attribute_values wc-enhanced-select select2-hidden-accessible enhanced' and @data-placeholder='Select terms']")))).selectByValue("110");

Comment: I am getting this from your code

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.cssSelector: selec.multiselect.attribute_values.wc-enhanced-select.select2-hidden-accessible.enhanced[data-placeholder='Select terms'] (tried for 10 second(s) with 500 milliseconds interval)
Comment: @Chris There was a typo which I have corrected now. Retest and let me know the status.

select2 dropdown with selenium


Android - Activity destruida ao rotacionar o tablet

Question: Estou com o seguinte problema em meu aplicativo:

Quando o usuário desliga a tela no tablet, liga a tela novamente, gira para a posição vertical e loga no android novamente, a Activity que o usuário estava é destruída e volta para a tela de login da aplicação.
Esse problema só ocorre em Activity que possuem uma lista cujo Adapter possui um XML que contenha uma propriedade valorada utilizando @dimen.xml.

Exemplo:
View row = LayoutInflater.from(mContext).inflate(R.layout.custom_attachment_list_item,
                parent, false);

Meu XML:
<?xml version="1.0" encoding="utf-8"?>
<TextView android:layout_width="20dp"
    android:padding="@dimen/sp_gen_xl_15dp"
    android:text="@dimen/sp_box_margin_left"
    android:layout_height="10dp"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Ou seja: se eu utilizar android:padding="@dimen/sp_gen_xl_15dp" para definir o padding, a Activity é destruída. Se eu passar um valor qualquer "10dp" por exemplo, a Activity se mantém quando o usuário realiza o procedimento descrito acima.
Obs.: A Activity relatada já possui no Manifest a tag android:configChanges="orientation|screenSize que serve para não destruir a Activity quando o tablet girar.
Exemplo:
<activity
     Activity"
            android:keepScreenOn="true"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:screenOrientation="landscape"
            android:windowSoftInputMode="adjustNothing"
            android:configChanges="orientation|screenSize"></activity>

A grande questão é: Por que a tag orientation|screenSize colocada no Manifest só funciona em Activitys que não utilizam @dimen em seus XML?
Answer: Pra entender o que está acontecendo, é necessário lembrar alguns pontos:

Você pode ter diferentes xmls dependendo da configuração da tela.
Por exemplo, pode ter um xml pra quando a Activity estiver em landscape e outro pra quando estiver em portrait.
Da mesma forma que você pode ter diferentes pastas para diferentes imagens com tamanhos diferentes, você pode ter para os xmls.
Por exemplo, você pode ter o meuLayout.xml na pasta layout e o meuLayout.xml na pasta /res/layout-land, onde esse ultimo vai ser usado, automaticamente, quando a orientação do celular mudar para landscape.
É na instância do Context que todas essas variáveis ficam. Existem três implementações de Context: Acitivty, Service e o processo do seu app.

Quando a tela gira, o android tem que se re-contextualizar, como você está referenciando um atributo definido num arquivo de recurso, ele vai ter que sempre reinstaciar o Context, que no caso é a activty.
Normalmente o android:configChanges deve ser usado só em último caso.
O ideal é usar Fragments com o método setRetainInstance(true), como fragments não são implementações de Context, eles não vão ter esse comportamento das activities.
Comment: Percebi que está lançando este erro:
Binary XML file line #3: Binary XML file line #3: You must supply a layout_height attribute. Caused by: java.lang.UnsupportedOperationException: Binary XML file line #3: You must supply a layout_height attribute
Comment: Ocorre quando giro o tablet e ele tenta dar inflate no XML novamente. A impressão que tive é que o atributo perdeu o valor que veio do @dimen, ou seja, esta vazio.


What credit card swiper will work with stripe?

Question: We built an ecommerce platform (like a Shopify) that allows our customers - the merchants to accept payments for products.
As of now, all payments are accepted online. When they sign up to use our service, they also sign up for stripe and we process payments through their hosted form for ease of PCI Compliance.
In a live setting, many of our customers want to use a swiper to accept payments for their products rather than typing in a credit card number on a tablet.
Do you have any suggestions for a third party swiper provider with an API that we can integrate?
Comment: This question isn't on-topic here - it's really hard to give a recommendation that can remain valid over time.  I can tell you from personal experience, though, that if you're going to be sending the data to Stripe, it needs to be [a device Stripe supports](https://stripe.com/works-with/category/card-readers-pos).  Any  swiper (other than one that's just a pure magstripe reader, which isn't PCI compliant) has to be supported by your processor - Stripe, in this case.
Comment: @Bobson thank you for your reply. The problem with many of those providers is that they are a separate third party service, much like us, with their own ecommerce tools, built on top of stripe. I'm looking for a solution for us to integrate directly. Do you know if any hardware providers?
Comment: [CardFlight](https://cardflight.com/cardflight-for-stripe/) on that page looks like it's just the reader and SDK.  The problem is that Stripe has to have support to decrypt the data from any reader that encrypts it.  So if they don't list it as supported, you're probably out of luck.
Answer: Stripe now offers its own set of supported EMV devices:
https://stripe.com/terminal
You can also use PayWorks or CardFlight (as of today) and can find those integrations here:
https://stripe.com/works-with/type/extension/category/card-readers
Lastly, if your'e just looking to use a magstripe reader, you should email into Support https://support.stripe.com/email for more guidance.
Comment: thanks for suggestion of stripe-terminal, which I am trying to implement, but could you help me for my custom-setup? I have explained it here in details, https://github.com/stripe/stripe-terminal-android/issues/78


How can I use custom macros with lilypond-book fragments?

Question: I am preparing a booklet using lilypond-book and have some snippets formatted with \begin{lilypond}[fragment]. These generally do what I want, but I would like to use some custom macros that I defined for chant formatting:
recitingNote = {
  \once \override NoteHead  #'stencil = #ly:text-interface::print
  \once \hide Stem
  \once \override NoteHead.text = \markup { \lower #0.5 \filled-box #'(0 . 6) #'(0 . 1) #0 }
  \once \override Dots.dot-count = #0
}

recitedText = {
  \once \override LyricText.self-alignment-X = #LEFT
}

I have these in a file named chant.lyinc, and in my usual full Lilypond documents I just \include "chant.lyinc" and am set. However, when I try it in fragment mode:
\begin{lilypond}[fragment]
  \include "chant.lyinc"
  c'2 d'2 e'2 f'2
\end{lilypond}

I get the errors
Parsing...
../chant.lyinc:1:1: error: not a note name: recitingNote

recitingNote = {
../chant.lyinc:1:14: error: syntax error, unexpected '='
recitingNote
             = {
../chant.lyinc:8:1: error: not a note name: recitedText

recitedText = {
../chant.lyinc:8:13: error: syntax error, unexpected '='
recitedText
            = {

Clearly the fragment wrapper is preventing the usual definitions from taking place. How can I use my custom includes with fragment snippets?
Answer: The lilypond-book processor works by extracting fragments and wrapping them in a boilerplate .ly file. After the "cut-&-pastable-section", it opens a new music expression with {, uses \sourcefileline 123 to provide debugging tracing, blindly pastes the contents of the fragment, and closes the expression with }.
A hacky workaround to use custom functions is to close the provided music expression with no contents, include the custom definitions, and open a new music expression. This generates warnings and probably screws up debug reporting and who knows what else, but it sort-of works:
\begin{lilypond}[fragment]
  } \include "chant.lyinc" {
  \recitingNote e'2 d'2 e'2 f'2
\end{lilypond}


the vector space of Magic Squares

Question: Can anyone offer help? I have no clue how to do this problem.
Magical squares are 3 by 3 matrices with the following properties: the sum of all numbers in each row, and in each column, and in each diagonal is equal. This number is called the magical number.
(i)Prove that the set of magical squares forms a vector space with the usual matrix addition and scalar-matrix product.
(ii) Find a basis of the vector space of magical squares and determine its dimension.
Comment: You need to specify what sort of "numbers" the squares contain. Magical squares are more usually thought of as containing integers, and in that case they don't form a vector space.
Comment: Do you know how many $3\times 3$ magic square exist?
Comment: Sorry what do you mean by that?
Comment: The usual way to prove some set $W$ is a vector space is to prove that it is a subspace of some set $V4 that you already know to be a vector space. So, it there any set containing the one you're asked about that you know is a vector space? And do you know how to prove something is a subspace?
Answer: The given relations correspond to a homogeneous system of linear equations for the $9$ entries (ordered left to right, top to bottom) and the negated sum, with the following matrix:
$$
\pmatrix{
1&1&1&0&0&0&0&0&0&1\\
0&0&0&1&1&1&0&0&0&1\\
0&0&0&0&0&0&1&1&1&1\\
1&0&0&1&0&0&1&0&0&1\\
0&1&0&0&1&0&0&1&0&1\\
0&0&1&0&0&1&0&0&1&1\\
1&0&0&0&1&0&0&0&1&1\\
0&0&1&0&1&0&1&0&0&1
}
$$
This matrix has rank $7$ over the real numbers (as you can establish by hand or using Wolfram|Alpha), so the solution set is a vector space of dimension $10-7=3$. If the squares are meant to contain real numbers, their addition and scalar multiplication correspond to those of these solution vectors, so the squares also form such a vector space.
Comment: @VerkhovtsevaKatya: Yes -- though it doesn't matter which direction you take as horizontal and which as vertical.
Comment: So, there are $8$ equations for $3$ rows, $3$ columns and $2$ diagonals if we have: $$\begin{bmatrix}x_1&x_2&x_3\\x_4&x_5&x_6\\x_7&x_8&x_9\end{bmatrix}\;\;?$$
Answer: Assuming the entries of your magic square belong to some field of characteristic zero to avoid complications, the given relations tell us that a generic magic square looks like
$$\begin{pmatrix}a & 2a -4b +3c & b \\ c & a -b + c & 2a - 2b + c \\ 2a - 3b + 2c & 2b-c &a-2b+2c\end{pmatrix}$$
with magic number $3a -3b+3c$.
Thus your space has dimension $3$. (Verifying that the set of magic squares really forms a subspace of the space of $3 \times 3$ matrices with coefficients in the chosen field is routine; alternatively, this argument shows that the set of all magic squares is precisely the span of three specific magic squares, namely the ones obtained by setting exactly one of $a,b,c$ equal to $1$ and the rest to zero.)
Comment: Why do we know that if we choose different 'starting fields' $a,b$ and $c$, that we could also find such a matrix and therefore a basis?
Comment: @ViktorGlombik Could you rephrase? I don't understand your question at all.
Comment: One can show, that if you chose three numbers, all other numbers are determined by those three numbers. In you answer, you choose those numbers (I called them the ''starting squares'') $a,b$ and $c$ to be in certain positions. But how do we know that we can find such a representation for every triple of ''starting squares''?
Answer: (i) The map "compute the sum of elements in row $i$" (or in column $j$, or in one of the diagonal) is a linear map from the vector space of $3\times 3$ matrices to the base field, hence so is each difference of such maps. The set of magic squares is the intersection of the kernels  of these difference maps, hence  a subspace.
Answer: Here's an easy way to do this for general $n$: given a magic number $S$, consider the topleft $(n-1)$ by $(n-1)$ submatrix of the square. Given these values, one can fill in the margins by subtracting rows and columns of the submatrix from $S$, and the bottom-right entry by subtracting the diagonal of the submatrix from $S$.
The only equations remaining to satisfy are: (1) the sum of each new margin equals $S$ and (2) the sum of the non-principal diagonal equals $S$. The condition (1) is the same for each margin (because the last column can be determined given all the rows and all the other columns). So the conditions are, where $1\le i,j\le n$ and $1\lt k\lt n$:
$$\sum_{i}a_{ii}=(n-1)S-\sum_{ij}a_{ij}$$
$$\sum_k a_{k(n-k+1)}+\sum_j a_{1j}+\sum_i a_{i1}=S$$
These can be checked to be linearly independent for $n>2$. Allowing $S$ to be free, the dimension of our space is therefore $(n-1)^2-2+1$, which equals:
$$n^2-2n$$
Which indeed gives 3 in the case $n=3$ Meanwhile, for $n=1$ and $n=2$, the dimension is clearly 1.

the vector space of Magic Squares


Using Image file as cursor

Question: I am new to Racket and StackOverflow. I am trying to use IMAGE.png as cursor. But the white part of cursor is merged by background color.  If i hover the cursor on black-thick lines, the cursor is totally invisible as the white color become transparent. The white color is supposed to be opaque.
First, I use this  ,which has 256x256 dimensions, 32 bit depth. I resized the dimensions to 16x16 with the following codes.
<code>(require 2htdp/image)

(define mag IMAGE.png);; acutally, I used "insert image" in DrRacket IDE
(define new-mag (scale (/ 1 16) mag))
(save-image new-mag "mag.png")
new-mag
(image-width new-mag)
(image-height new-mag)
</code>
According to the documentation of cursor%, the bitmap file with 16x16 bit depth 1 must be used to create cursor. To change the bit depth to 1, following codes are applied.
<code>(require racket/gui/base)

(define bm1 (read-bitmap "mag.png"))
(define bm2 (make-object bitmap% 16 16 #t #f 1.0))
(send (send bm2 make-dc)draw-bitmap bm1 0 0)
(send bm2 save-file "mag2use.png" 'png)
(define bm (read-bitmap "mag2use.png"))
(printf "~a ~a ~a ~a~n"
    (send bm get-width)
    (send bm get-height)
    (send bm get-depth)
    (send bm is-color?))
</code>
Then I used the bitmap mag2use.png as cursor.
<code>(define zoom-cursor (make-object cursor% bm bm 0 0))
</code>
Answer: It's unfortunate that the documentation doesn't mention that the mask parameter is a transparency mask.
White pixels in the mask become transparent in the cursor, and you're using the bitmap itself as mask.
Fill the parts you want to be opaque with black in the mask.
Comment: Do I need to use different bitmap for mask? @molbdnilo
Comment: Yes, unless you want to use an all-black cursor.
Comment: I have filled black color inside the image and use for mask. White color inside the image become opaque. Thank you so much @molbdnilo

Using Image file as cursor


Sharp Fourth Scale Degree in the Goldberg Variation "Aria"

Question: My question relates to the C# in the 3rd measure.
I understand that the section eventually modulates to D major which contains that C#, but that does not seem to happen until the 9th measure. What would be the customary harmonic analysis of the 3 measure?
Comment: @phoog - doesn't playing the mordent introduce an A into the equation? The feel of bar 3 is A dominant 7.
Comment: V/V, as bar 4 is V, so bar 3 prepares for it with a dominant of that dominant.
Comment: @Tim there's no A in that measure.  It's vii/V (in first inversion, of course).
Comment: @Tim true, I overlooked the ornament.  Still feels like a vii to me.
Comment: Also, even if there were no A in the measure, the chord C#/E/G still functions as a five of five.
Comment: @phoog - so the notes in your vii(o) are C# E G. That's C#o, (the top 3 notes of A7) but as soon as the A appears, it becomes A7, although either will resolve to D.
Comment: @Tim but the A isn't structural, it's ornamental.  I find a synthesized bass line of G-D-A-D to be very awkward and also to change the harmonic character of the piece considerably. This argues in favor of analysing that measure as vii/V.  Furthermore the doubled seventh is very unusual for a V7 chord.
Answer: Although there are answers in the comments, I thought I'd provide an official one.
You're correct that the music has not yet modulated to D, as evidenced by (among other things) the C♮ that appears in the bass at the end of m. 4.
Measure 4 is clearly a V chord (D), and that C♯ clearly suggests a tonicization of that V chord. When we stack that chord in m. 3 in thirds, we get C♯–E–G, which is a vii° triad (the ° means diminished) in the key of D. With the E in the bass it's in first inversion, so this chord is best called a vii°6/V (read "seven-diminished six of five"), which is a very common occurrence in step-descent basses like this one.
And as some of the comments above discuss, if one wishes to include the A in the chord, we're left with A–C♯–E–G, which is a V7 chord in D, but now in second inversion. If you include the A, the chord is then best labeled V43/V.
Comment: A 19th century theorist would probably have said that it *does* modulate to the dominant in bars 3 and 4, back to the tonic in bar 5, and to the subdominant (and back to the tonic) in bars 5-6! But the current terminology of "secondary dominants" seems to be an improvement on the old terminology of "passing modulations" for these harmonic progressions.


multi variable regression with overlapping category variables in statsmodels

Question: I am working on creating a cost estimate for an order code, which is an order for medical procedures (category variable).   I have estimated costs by patient encounter (visit to the doctor).
I am creating dummy variables for the order codes.   I am then grouping the patient encounters so all the appropriate category variables are assigned.
I have estimates working ok when there are no overlaps in the dummy variables.   When order codes are overlapping, they are being treated independently (this is actually not a bad result).   So, if someone gets their arm and leg worked on, that's a different estimate than the arm and leg separately.
Is there any way to get dummy groups to interact with the individual dummy variables?   So, arm orders have interactions with the arm + feet order estimates?
Below is what I have working so far:
import pandas as pd
from statsmodels.formula.api import ols

df = pd.DataFrame({
  'encounter' :[124,124,123,123,111,113,234,345,645,645]
, 'cost'      :[3000,3000,3300,3300,2500,2700,3000,4000,6000,6000]
, 'order_code':['foot','arm','arm','foot','arm','arm','hip','leg','hip','leg']})

After the sample data is loaded into a dataframe, you can see encounter 124, 12 and 645 have two order_codes.  These will get merged to the same encounter row later:
   encounter  cost order_code
0        124  3000       foot
1        124  3000        arm
2        123  3300        arm
3        123  3300       foot
4        111  2500        arm
5        113  2700        arm
6        234  3000        hip
7        345  4000        leg
8        645  6000        hip
9        645  6000        leg

I create the dummy variables from the order_codes, then add the encounter & cost data:
dummy = pd.get_dummies(df.order_code).join(df[['encounter','cost']])

Then, I merge the encounters together using the .max() function to make sure a "1" is present for each dummy variable.
group = dummy.groupby(by='encounter').max()

After the merge, the data looks like this.   Notice encounters 123,124 and 645 both have multiple dummy values indicating multiple orders.
encounter  arm  foot  hip  leg  cost
111          1     0    0    0  2500
113          1     0    0    0  2700
123          1     1    0    0  3300
124          1     1    0    0  3000
234          0     0    1    0  3000
345          0     0    0    1  4000
645          0     0    1    1  6000

At this point, I apply a regression using all the dummy variables:
model = ols(formula='cost ~ arm + foot + hip + leg ',data=group).fit()

Here is the summary of that fit:
==============================================================================
Dep. Variable:                   cost   R-squared:                       0.993
Model:                            OLS   Adj. R-squared:                  0.978
Method:                 Least Squares   F-statistic:                     66.27
Date:                Wed, 03 Aug 2022   Prob (F-statistic):             0.0149
Time:                        15:51:14   Log-Likelihood:                -41.909
No. Observations:                   7   AIC:                             93.82
Df Residuals:                       2   BIC:                             93.55
Df Model:                           4
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept   1000.0000    312.250      3.203      0.085    -343.503    2343.503
arm         1600.0000    337.268      4.744      0.042     148.851    3051.149
foot         550.0000    180.278      3.051      0.093    -225.672    1325.672
hip         2000.0000    254.951      7.845      0.016     903.034    3096.966
leg         3000.0000    254.951     11.767      0.007    1903.034    4096.966
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   2.385
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.287
Skew:                           0.000   Prob(JB):                        0.867
Kurtosis:                       2.009   Cond. No.                         10.0
==============================================================================

If I just run the data back thru the predict function i can get an idea what the cost estimates are looking like:
pred = model.predict(group).to_frame().join(group)

encounter estimate arm foot  hip  leg  cost
111        2600.0    1     0    0    0  2500
113        2600.0    1     0    0    0  2700
123        3150.0    1     1    0    0  3300
124        3150.0    1     1    0    0  3000
234        3000.0    0     0    1    0  3000
345        4000.0    0     0    0    1  4000
645        6000.0    0     0    1    1  6000

The estimates are working when the category variables are unique per encounter (encounters 111,113,234, and 345), they are also working when I have multiple categories per encounter (encounter 123,124 and 645).   But, it would be really great if the individual dummy variables had some interaction with the dummy groups.
Here is the forecast just one dummy variable per encounter:
df_test = pd.DataFrame({'encounter' :[995,996,997,998]
                   , 'cost'     :[0,0,0,0]
                   , 'order_code':['foot','arm','hip','leg']})

When I run this, thru the predict function, results below:
pred_test = model.predict(group_test).to_frame().join(group_test)
print(pred_test)

encounter estimate  arm  foot  hip  leg  cost
995        1550.0    0     1    0    0     0
996        2600.0    1     0    0    0     0
997        3000.0    0     0    1    0     0
998        4000.0    0     0    0    1     0

Any suggestions on how to get the dummy groups (encounters with more than one dummy variable) and non-groups to influence each other?
Also, if there is a better way to tackle this problem, I am open to other suggestions.
Thanks!
Comment: IIUC, "arm", "foot", ... are your dummy variables. And you want them to have an interaction with the "dummy groups". But *interaction* (in the sense in which this notion is used in regression theory) exists between different variables, and I don't know what your "dummy group" *variables* are. So please clarify: What exactly do you mean by "dummy group" and what by "interaction"?
Comment: Encounters 123 and 124 are acting as a "group" as the cost estimate is only using those two encounters. I believe they are being grouped in the regression because there are two dummy variables in those encounters. Is there a way that encounter 111 and 113 could also interact with that grouping? All the "arm" dummy variables should interact across all encounters. Its a bit tricky because the "foot" dummy is hiding in the grouping.
Answer: IIUC, when you say "interaction", you are just referring to the fact that all the encounters that contain an arm treatment should have an influence on the cost estimate of an arm treatment. But this is actually already the case in your model.
In the comments you state "Encounters 123 and 124 are acting as a "group" as the cost estimate is only using those two encounters." However, the cost estimates of an arm treatment and of a food treatment are not only using those two encounters, they are using all encounters that contain an arm or a foot treatment. The model tries to find those treatment costs that satisfy the costs of all the encounters as well as possible (the total error will be minimized).
Your model presumes, that the treatment costs, when multiple treatments are done in the same encounter, simply add up. If that is indeed the case, you are all set.
Also, note that in regression theory, "interaction" means something different. E.g., you would have an interaction between arm treatment and foot treatment if the cost of the arm treatment would be different depending on whether it is combined with a foot treatment, i.e. the cost of an encounter with arm and foot treatment would not be just the sum of an arm and a foot treatment.


4-color coloring game.

Question: Similar to this question.
5-color coloring game.
Let there be two players, $$ and $$, and a map.
They now play a game such that:
Player $$ picks a region and player $$ colors it such that the region is a different color than all adjacent regions.
Player $B$ wins if at the end of the game, the map is colored such that no two adjacent regions are the same color. Player $A$ wins if at any point in time that becomes impossible.
If there are four available colors, then does player $$ have a winning strategy for every possible map?
Comment: I believe that player A doesn't have a winning strategy for some map, and that's partly reflected in the difficulty of the 4-color theorem (where you can't induct your way through it)
Comment: I'm not even convinced by the answer to the linked question which claims that A has a winning strategy with 5 colors.
Answer: A does not always have a winning strategy. Suppose the map is of a Torus. Since it is well known that 7 colors are needed to color arbitrary partitions of a Torus, B can sometimes have a completely winning strategy. It all depends on the euler characteristic of the surface of the map.
Edit: Let $E = \mathbb R^3$ be endowed with the Euclidean metric. Embed a torus $T \subset \mathbb E$ and consider it with the topology given by the Euclidean metric on $E$. Hence, we are dealing with an Euclidean map, yet there are partitions of the underlying space for which 7 colors are needed so that no two touching partitions are the same color.
Comment: @Snared Drawing a map in the plane is a default assumption. Your answer, to begin with, is nothing more than a "gotcha" like saying "well, actually, 2+2=7 can be true if we're working mod 3". If you seriously thought that toroidal maps might be relevant, you should have left a comment to check, first. (Also, a single downvote - not from me - is hardly "oblivion".)
Comment: Map must be Euclidean
Comment: Seriously? You changed your question immediately after my correct answer was posted. If you wanted to restrict to Euclidean maps you should have opened a new question. Now my answer, which _was_ correct but is now incorrect after you edited your question, is getting downvoted into oblivion and my rating is suffering unjustly. Next time just post a new question
Comment: Obviously there are geometries for which this game is impossible and that is the answer to the question. Then they changed the question to specify a geometry and ask. Now nobody even cares about the question as its relevance just immediately dropped. Yet you thought it was natural. That's crazy.
Comment: It's three downvotes not a single one @MishaLavrov all of which were added after the OP changed his question to invalidate the answer, by the way. Makes no sense. Was I supposed to delete my answer after that point?
Comment: I'm not going to ask a new question just because I didn't perfectly clarify this one, an edit is more appropriate.
Comment: @Snared This is why there are policies on Math SE which implore askers to provide details, and potential answerers to ask questions before posting answers.  Generally speaking, if you can answer a question here in a one liner, there is a good chance that the asker left off some detail.  Use the comments to seek clarification *before* answering.
Comment: That being said, @blademan9999, it is not appropriate to edit a question in a way which invalidates an existing answer.  While I do not like the "gotcha!" aspect of this question, it is a valid answer to the question you originally asked, and editing your question to invalidate the answer is not okay.  In such a case, it is better to ask a new question with the appropriate details.
Comment: I edited it to clarify and add a detail which I though was clearly implied by the question.
Comment: @blademan9999 you realize the Earth is mapped yet is a sphere? I'm not sure why you thought that a map implies that the underlying space is of dimension 2 specifically. We map tori, $n$-spheres, even non-orientable spaces using maps. What you did it add the word "Euclidean", which is still wrong, since tori can be embedded in R^3 and inherit the subspace topology metric, that being Euclidean. So either way the answer stands, if you really wanted to edit the question to be a "Gotcha" you would have specify the map further than simply being Euclidean.
Comment: The whole 4 colour theorem, planar, most maps, planar, have you ever seen a toroidal map. Plus a spherical map can easily be turned to planar one, and vice Versa. Posting a second near indentic question instead of just a doting would likely be against the rules
Comment: a spherical map cannot be turned into a planar one, since euler characteristic is invariant under isomorphisms, yet the sphere and plane have euler characteristics 1 and 2, so what you said cannot be true.. And one question is general, the other would be specific to planar maps if that is what you wish...
Comment: And yes, maps between tori are extremely natural - they will appear many times in most mathematician careers.. Tori are the product of two circles, so any pair of maps from two circles to one would produce a natural torus function. If you were playing a game where horizontal sides and vertical sides are identified... There are so many examples that I could go on and on. Anyway, I hope you can find someone to answer the more specific version of your original question, or maybe you plan to self-answer the question.. sorry for the misunderstanding, I wish I knew you meant planar in the beginning.

4-color coloring game.


What is the best way to compress postgres database dump file?

Question: I have large databases which im dumping with pg_dump and I need to make dump file smaller.
What is the best way to compress this postgres database dump file?
Answer: pg_dump comes with compression feature built-in:

-Z 0..9
--compress 0..9

Specify the compression level to use. Zero means no compression. For the custom archive format, this specifies compression of individual table-data segments, and the default is to compress at a moderate level. For plain text output, setting a nonzero compression level causes the entire output file to be compressed, as though it had been fed through gzip; but the default is not to compress. The tar archive format currently does not support compression at all.

There are 9 levels of compression - higher the level, higher the compression. 0 means no compression.
pg_dump [connection-option...] --compress=9 [dbname]

for maximum compression.
Comment: @masonrye if you believe my answer was helpful, you should consider [accepting it](https://serverfault.com/help/someone-answers) so the question won't stay as unanswered.
Answer: xz compresses data better than gzip. Running xz -6 <dumpfile> will compress the database dump with maximum compression.
Comment: "Better" is an understatement, actually. I've seen ratios of 1:100 for some dumps.
Answer: there's also parallel gzip https://zlib.net/pigz/ for when you really need to maximize all your cores on a big compression job.


Probability of complex number being real. [AMC 12 2015]

Question: This problem was taken from the AMC 12 2015 contest B.
Rational numbers $a$ and $b$ are chosen at random among all rational numbers in the interval $[0,2)$ that can be written as fractions $\frac{n}{d}$ where $n$ and $d$ are integers with $1 \le d \le 5$. What is the probability that $$(\text{cos}(a\pi)+i\text{sin}(b\pi))^4$$
My approach:
By De Moivre's Theorem, this could be rewritten as $4(\cos{4a\pi}+\sin{4b\pi})$. If this number is real, than the imaginary part must be $0$.
This occurs when $4b\pi = \pi{k}$ for any integer $k$. Or $4b = k$. Or $4\frac{p}{q}=k$ (p and q have GCF of $1$). Since $k$ is an integer, $q$ divides 4. So the denominators of the coveted fractions are factors of $4$.
These are the possible values of a or b:
$0,1,\frac12,\frac32,\frac13,\frac23,\frac43,\frac53,\frac14,\frac34,\frac54,\frac74,\frac15,\frac25,\frac35,\frac45,\frac65,\frac75,\frac85,\frac95$ (Note that other possible values of n and d are either out of the interval or simplify to the above fractions.)
Out of these there are $8$ that do the job. I felt that no matter what $a$ is, it is only up to $b$ to determine if the number is real.
So I reached a probability of $\frac25$. The answer is $\frac{6}{25}$. Where did I go wrong? Thanks.
Is De Moivre's theorem even applicable at all?
Comment: De Moivre's theorem says that $(\cos{x}+i\sin{x})^n=\cos{nx}+i\sin{nx}$. Here, $a\pi \neq b\pi$. So, I think that's where the mistake is.
Answer: Define $f(a,b) = (\cos a\pi + i \sin b\pi)^4$.  If $\sin b\pi = 0$ or $\cos a\pi = 0$, then $f(a,b)$ is real for obvious reasons.  If neither is zero, then $f(a,b)$ is real only if $$\cos^2 a \pi - \sin^2 b \pi = 0$$ which would imply $\cos a \pi = \pm \sin b \pi$, or equivalently, $$a \pm b - \frac{1}{2} \in \mathbb Z.$$  From here, enumeration is straightforward.
Answer: You cannot use De Moivre's theorem unless $a = b$.


WPF command support in ComboBox

Question: I want to have a command on my viewmodel execute on the selectionchanged of my ComboBox. Obviously Combobox does not support executing commands.
I have created a new class that inherits from Combox and implements this interface.
When I try to view the control (in the designer or in debug) the control doesn't show. I don't get any exceptions - is my control missing a visual template or something?
Thanks.
public class CommandSourceComboBox : ComboBox, ICommandSource
{
    static CommandSourceComboBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CommandSourceComboBox), new FrameworkPropertyMetadata(typeof(CommandSourceComboBox)));
    }

    #region ICommandSource Members

    public ICommand Command
    {
        get;
        set;
    }

    public object CommandParameter
    {
        get;
        set;
    }

    public IInputElement CommandTarget
    {
        get;
        set;
    }

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);

        if (this.Command != null)
        {
            RoutedCommand command = Command as RoutedCommand;

            if (command != null)
            {
                command.Execute(CommandParameter, CommandTarget);
            }
            else
            {
                ((ICommand)Command).Execute(CommandParameter);
            }
        }
    }

    #endregion
}

Answer: Not sure why its not displayed correctly. Maybe you need to execute the base constructor?
Edit, I actually tested it and it seems this line:
DefaultStyleKeyProperty.OverrideMetadata(typeof(ComboBoxWithCommand), new FrameworkPropertyMetadata(typeof(ComboBoxWithCommand)));

breaks it for me.
Here is my implementation and it works in the designer:
public class ComboBoxWithCommand : ComboBox, ICommandSource
{
    private static EventHandler canExecuteChangedHandler;

    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command",
                                                                                typeof(ICommand),
                                                                                typeof(ComboBoxWithCommand),
                                                                                new PropertyMetadata((ICommand)null,
                                                                                new PropertyChangedCallback(CommandChanged)));

    public ICommand Command
    {
        get
        {
            return (ICommand)GetValue(CommandProperty);
        }
        set
        {
            SetValue(CommandProperty, value);
        }

    }

    public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register("CommandTarget",
                                                                                typeof(IInputElement),
                                                                                typeof(ComboBoxWithCommand),
                                                                                new PropertyMetadata((IInputElement)null));

    public IInputElement CommandTarget
    {
        get
        {
            return (IInputElement)GetValue(CommandTargetProperty);
        }
        set
        {
            SetValue(CommandTargetProperty, value);
        }
    }

    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter",
                                                                                typeof(object),
                                                                                typeof(ComboBoxWithCommand),
                                                                                new PropertyMetadata((object)null));

    public object CommandParameter
    {
        get
        {
            return (object)GetValue(CommandParameterProperty);
        }
        set
        {
            SetValue(CommandParameterProperty, value);
        }
    }

    public ComboBoxWithCommand() : base() { }

    private static void CommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ComboBoxWithCommand cb = (ComboBoxWithCommand)d;
        cb.HookUpCommand((ICommand)e.OldValue, (ICommand)e.NewValue);
    }

    private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
    {
        if (oldCommand != null)
        {
            RemoveCommand(oldCommand, newCommand);
        }
        AddCommand(oldCommand, newCommand);
    }

    private void RemoveCommand(ICommand oldCommand, ICommand newCommand)
    {
        EventHandler handler = CanExecuteChanged;
        oldCommand.CanExecuteChanged -= handler;
    }

    private void AddCommand(ICommand oldCommand, ICommand newCommand)
    {
        EventHandler handler = new EventHandler(CanExecuteChanged);
        canExecuteChangedHandler = handler;
        if (newCommand != null)
        {
            newCommand.CanExecuteChanged += canExecuteChangedHandler;
        }
    }
    private void CanExecuteChanged(object sender, EventArgs e)
    {

        if (this.Command != null)
        {
            RoutedCommand command = this.Command as RoutedCommand;

            // If a RoutedCommand.
            if (command != null)
            {
                if (command.CanExecute(this.CommandParameter, this.CommandTarget))
                {
                    this.IsEnabled = true;
                }
                else
                {
                    this.IsEnabled = false;
                }
            }
            // If a not RoutedCommand.
            else
            {
                if (Command.CanExecute(CommandParameter))
                {
                    this.IsEnabled = true;
                }
                else
                {
                    this.IsEnabled = false;
                }
            }
        }
    }

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);

        if (this.Command != null)
        {
            RoutedCommand command = this.Command as RoutedCommand;

            if (command != null)
            {
                command.Execute(this.CommandParameter, this.CommandTarget);
            }
            else
            {
                ((ICommand)Command).Execute(CommandParameter);
            }
        }
    }
}

Comment: Nevermind, I figured it out. I added the following to my style template:
Comment: This is great! Does exactly waht I want. Unfortunately now all the styles I applied to ComboBox don't apply to the ComboBoxWithCommand objects. Do you know an easy way to get the styles to trickle down? Or do I need to duplicate the style and target the ComboBoxWithCommand type?

WPF command support in ComboBox


SIMULAR CLICK EM UM <a href via SELENIUM WEBDRIVER

Question: estou percorrendo um TABLE na ultima coluna tenho um link que abre um alert, mas não estou conseguindo simular o click com o Selenium, será que alguem pode me ajudar?

td class="aligncenter">
a href="javascript:void(0);" title="Visualizar Texto" onclick="BuscarTextoDecisoesPop("1537784");">
img src="../img/Find.png" style="height:20px;width:20px;" alt="Visualizar Texto">
/a>
/td>

Desde já agradeço qualquer ajuda. :-)
Answer: Acho que achei a solução.
<code>driver.findElement(By.xpath("//a[@title='Visualizar Texto']")).click();
</code>