Prove or disprove that $\forall n \in N$ $, \, n! \in \mathcal{O}(2^n)$

Question:
Prove or disprove that $\forall n \in N$ $, \, n! \in \mathcal{O}(2^n)$

My attempt:
$f(n) = n!$
$g(n) = 2^n$
First I checked if I needed to prove or disprove this statement, and to do so I computed the $\lim_{n \to \infty}{\frac{f(n)}{g(n)}}$ = $\lim_{n \to \infty}{\frac{n!}{2^n}}$ which equals $\infty$ so this statement is false.
So to disprove it, I supposed that the statement was true. Then by the definition of big-oh, there would be a $C>0$ and $n_0 > 0$ such that $n! \leq C * 2^n $ for all $n \geq n_0$. So,
$$n! \leq C * 2^n $$
$$\frac{n!}{2^n} \leq C $$
$$2^{-n}n! \leq C $$
So we have constant $C \gt 0$ and $n_0 \geq 0$ such that $2^{-n}n! \leq C $.
But I don't think this can be possible since when looking at the values as n gets larger it increases:
$$\begin{array}{c|c|c|}
 & \text{1} & \text{2} & \text{3} & \text{4} & \text{5} \\ \hline
\text{$2^{-n}n!$} & 0.5 & 0.5 & 0.75 & 1.5 & 3.75 \\ \hline
\end{array}$$
Is this the correct way to approach this question and is my solution correct? Thank you to those who help.
Comment: Another way to solve this would be via an inductive proof.
Comment: Listing the first few values of $2^{-n}n! $ does not constitute a proof.
Comment: You don't need the universal quantifier there; big-O notation already contains the appropriate quantifier.
Answer: Close to done - you still need to formalise the contradiction you're looking for. You've reduced it to showing that $a_n=\frac{n!}{2^n}$ isn't bounded, and indeed, it is not.
Noting that $a_n=\frac{n}{2}a_{n-1}$, we see that for $n\ge3$, $a_n\ge\frac{3}{2}a_{n-1}$, which gives that $a_n\ge \left(\frac{3}{2}\right)^{n-3}a_3$ by induction.
Hence, $a_n$ grows exponentially and thus is certainly not bounded, and your claim is proven.
Answer: What you have written down is not the claim you are trying to prove. It is the function $ n\mapsto n! $ itself that is not in $\mathcal{O}(n\mapsto 2^n) $, not each element of that function.
(EDIT: As Qiaochu Yuan said in his comment)


Multiplicity of $z=0$ on $f(z)=z\cos(z)-\sin(z)$

Question: I'm trying to find the multiplicity of $z=0$ on $f(z)=z\cos(z)-\sin(z)$ using complex analysis.
I'm new to complex analysis and the argument principle/Rouché's theorem so I'm not quite sure where to start. I can prove how many zero's this function has but I'm not quite sure what theorem would help me determine the multiplicity of this root, can someone point me in the right direction or provide a proof?
Thank you
Answer: Hint!
Use the expansion in power series of $\cos z$ and $\sin z$. the order of $z=0$ is the order of the power series, i.e. the degree of the lowest degree term.
Comment: Thank you for your kind appreciation. My general philosophy is  to help people find the details by themselves,  giving the starting point. It seems it worked in your case.
Comment: Your hint was excellent and I was able to piece it together before the other answer, but I marked his as the accepted one due to it being more detailed. Thank you much for the help.
Answer: $$z\cos z -\sin z = z(1-z^2/2+z^4/24+...)-z+z^3/6-z^5/120-....)=$$
$$-z^3/3+z^5/{30} +...$$
Thus it is a zero of multiplicity  $3$


Cocoa Touch - How to check if a non-rectangular object in a UIImageView intersects another object?

Question: Say I have a UIImageView that contains an image of an object that is not rectangular, i.e. a round ball. How can I check if another UIImageView (rectangular or not) intersects, or contains a point in, that object (not its frame)?
Basic example:
I have two balls rolling around on the screen, and I want to check for collision. But I don't want to check if their rects intersects eachother, since the balls are not rectangular.
Answer: I think if you have limited set of possible shapes then it is better to perform the check for each possible pair of object shapes rather then some generic algorithm. For example two circles intersect if the distance between their centers is less then the sum of their radiuses etc.
Comment: Wow, simplicity at its best. Thanks so much, I didn't even think of that! It's going to work since I will most likely only work with round objects for now.


posting php variable that contains apostrophe

Question: I am having trouble posting a php variable to another page. The variable is retrieved from a dropdown selected by the user and if it contains an apostrophe, I only get the part prior to the apostrophe posted.  I.E. If I want to post "Cooper's Hawk" I am only receiving "Cooper".  How do I escape this properly so that I can post the entire string?
This is what I have:
 echo '<form method="POST" action="advanced_search2.php">';
 $dropdown_english_name = "<select class = 'dropdown' name='english_name'>     <option>ALL</option>";

$query = "SELECT DISTINCT english_name FROM moth_sightings WHERE user_id ='$username'ORDER BY english_name asc";
                $result = mysql_query($query) or die(mysql_error());
                echo "
English Name:	";
                while($row = mysql_fetch_assoc($result))
                    {
                       $dropdown_english_name .= "\r\n<option class = 'dropdown_active' value='{$row['english_name']}'>{$row['english_name']}</option>";
                    }
                $dropdown_english_name .= '\r\n</select>';
                echo '' .  $dropdown_english_name .'
';

on different page
$posted_value = ($_POST['english_name']);
 echo $posted_value;die;

So, to clarify from the above code, the posted string is "cooper's hawk" but the echoed output is "Cooper".
Thanks in advance for any tips.
Comment: Most likely you're using single quotes to wrap the options' value attribute and not escaping them before echoing those in the php.
Comment: There's no "Cooper's Hawk" option in the select box. SHow us how this is generated.
Comment: ` echo;$posted_value;die;` isn't exactly valid syntax...
Comment: Ok, I have added the details of option so you can see how it is generated.  @Mark B, the echo; was an error in my post but in the original code.  Thanks for spotting.
Answer: You've probably broken you form by generating it as
 <select ...><option value='cooper's hawk'>...</option></select>
                                  ^---

with that construct, you get a submitted value of cooper, and the option tag ends up with two unknown attributes s and hawk. Be careful when building html forms like that. You HAVE to make sure that embedded quotes in your data don't fundamentally alter the structure of the html, e.g. use mixed quotes, or encoded quotes:
values="cooper's hawk"
values="cooper's hawk"

would both work. note the different quoting styles.
Comment: To be safe, always use [htmlspecialchars](http://www.php.net/manual/en/function.htmlspecialchars.php) to escape special characters.
Comment: @user1658170: you got your hint: use htmlspecialchars to escape the special characters.
Comment: I think this might be the problem, but I am not sure about how to repair it. Any hints. Note I have now included the source fo the option value in the code above.
Answer: You could use php function addslashes($variable)


monotonicity of a univariate function

Question: I am considering the function
$$
f(x) = (a + e^x)^{-b} + (a + e^{-x})^{-b}
$$
where $a, b \in (0, \infty)$. What are the conditions on $a$ and $b$ that make $f(x)$ monotonic? Straightforward differentiation reduces it to showing that the transcendental equation
$$
{a y + y^2 \over a y + 1} = y^{2 \over 1 + b}
$$
has no solution on $(1, \infty)$. Any ideas? Thanks!
Comment: Increasing/decreasing over which sets? $f(x)$ is an even function, so it is not monotonic over the whole $\mathbb{R}$.
Comment: @AmirHoseinSadeghiManesh: that probably is the most reasonable interpretation, but I would like the OP to clearly state it.
Comment: Anyway, for $a=3$ and $b=2$ we have equality between $\frac{ay+y^2}{ay+1}$ and $y^{\frac{2}{b+1}}$ at $y\approx 18$.
Comment: Thank you guys for your inspirations. So I think the right question to ask is the following: What are the conditions on $a, b$ that make $f(x)$ montonic? The transcendental equation reformulation is still valid. If $b$ is a rational number i.e. $b=p/q$, the equation can be reduced to $a z^{2q+p} + z^q - z^{2p+q} - a z^p = 0$. Can one use polynomial theories to find the conditions on $a, p, q$? I obtained the above equation by leting $y = z^{p+q}$.
Comment: @JackD'Aurizio Since the questioner at the end is mentioning the interval $(1,\infty)$ for $y$, it means he is interested in $(0,\infty)$ for $x$ not the whole $\mathbb{R}$.
Answer: It's not necessarily monotone for small $a$. The only reason it appeared to be monotone is because when $a$ is sufficiently large, the $(a+e^{−x})^{−b}$ term is effectively constant.
It would be interesting to see if the exact value of $a$ for which $f$ on $(0,\infty)$ is monotone can be found.

monotonicity of a univariate function


Jupyter-Themes Not Loading

Question: I am running v3.9 notebook and have installed jupyter-themes without issue/warning. I then ran jt -t oceans16 -f roboto -fs 12 -cellw 100% with no error.
However, the notebook doesn't look like it's updating. I have restarted the kernel and tried it on different browsers to make sure it wasn't a cache issue.
Any ideas?
Answer: Make sure that you've installed the module in Python 3.9 by using pip3.9 to install it.
Comment: Yes, I've done that.
Answer: I had the same issue. I completely shut down Jupyter Notebooks, cleared my browser cache and reopened Jupyter Notebook and it worked.

Jupyter-Themes Not Loading


counting special characters in a user generated string

Question: So I have this program that is supposed to to take any user generated string and display the amounts of white space, letters, numbers, and special characters. I do not want to duplicate a question. It seems to be a little more specific then talked about in other posts.
My error lies in the special characters. The specific error is return 0. I referenced stack overflow already in about every discussion they had on the matter. Which helped me form the special character method.
I have to keep the main method clear and call aforementioned methods
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string");
userInput = kbd.nextLine();

countletter(userInput);
countnumber(userInput);
countspecial(userInput);
countSpace(userInput);

}

public static void countletter(String userInput) {
    int countletter = 0;
    for (int i = 0; i < (userInput.length() - 1); i++) {
        char location = userInput.charAt(i);
        boolean x = Character.isLetter(location);
        if (x) {
            countletter++;
        }

    }
    System.out.println("The number of Letters is: " + countletter);
}

public static void countnumber(String userInput) {
    int countnumber = 0;

    for (int i = 0; i < userInput.length() - 1; i++) {
        char location = userInput.charAt(i);
        boolean x = Character.isDigit(location);
        if (x) {
            countnumber++;
        }

    }
    System.out.println("The number of digits is: " + countnumber);
}

public static void countSpace(String userInput) {
    int countSpace = 0;

    for (int i = 0; i < userInput.length() - 1; i++) {
        char location = userInput.charAt(i);
        boolean x = Character.isWhitespace(location);
        if (x) {
            countSpace++;
        }

    }
    System.out.println("The number of white spaces is: " + countSpace);
}

public static void countspecial(String userInput) {

    if (userInput == null || userInput.trim().isEmpty()) {
        return 0;
    }
    int countSpecial = 0;
    for (int i = 0; i < userInput.length(); i++) {
        if (userInput.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
            countSpecial++;
        }
    }
    System.out.println("The number of special chars is: " + countSpecial++);
}
}

My initial attempt at countSpecial:
public static void countspecial(String userInput) {
   int countSpecial = 0;

    for (int i = 0; i < (userInput.length() - 1); i++) {
        if (userInput.substring(i, 1).matches("[^A-Za-z0-9]")) {
            countSpecial++;
        }

   }
   System.out.println("The number of special chars is: " + countSpecial++);
}
}

Where am I going wrong and why?
Answer: Even easier, don't loop. Just replace all non-special chars with nothing and count the length:
int countSpecial = userInput.replaceAll("[A-Za-z0-9\\s]", "").length();

You can apply this technique to all your character categories.
Comment: @AmerQarabsa what has substring to do with my answer (which works by the way)?
Comment: your second answer works, userInput.substring(i, 1).matches("[^A-Za-z0-9\\s]") this does not work
Answer: in your initial attemp you have problem with your substring
substring second parameter would be the index of your last character in the substring +1, and so you need to iterate until userInput.length() not userInput.length() -1.
And i dont know why would you increment the count after printing it , it actually does nothing but still makes no sense.
      public static void countspecial(String userInput) {
        if (userInput == null || userInput.trim().isEmpty()) {
          return ;
        }
        int countSpecial = 0;

        for (int i = 0; i < userInput.length(); i++) {
           if (userInput.substring(i, i+1).matches("[^A-Za-z0-9]")) {
              countSpecial++;
           }

        }
        System.out.println("The number of special chars is: " + countSpecial);
        }

A better way instead of subtring you could use "(userInput.charAt(i)+"").matches".
But a better solution would be counting all the digits and letters and subtract their sum form the total length of the string , this would give you the number of special characters as it is not recommended to use regex for simple requirement like this.
Comment: the increment at the end was an accident I apologize. Your explanation was helpful to my understanding. Thank you.
Comment: if (userInput == null || userInput.trim().isEmpty()) {
          return ;

after setting the userInput to null what is trim().isEmpty()) actually doing, I am trying to understand this line of code. I haven't learned about .trim yet
Comment: trim() will remove the leading and trailing white spaces from the string
Answer: Look at the javadocs for substring.
Some languages that use a flavor of substring(int beginIndex, int length) where beginIndex is where you start the substring and length is how many characters are in the substring.
Java uses substring(int beginIndex, int endIndex) where beginIndex is where you start the substring and endIndex is the position of the ending character.
userInput.substring(i, 1);

Where i = 2 means you want to start the substring at index position 2 and end it at index position 1 and an exception is thrown.
Answer: If you're defining anything other than a letter, digit or whitespace character to be "special" then you should really test for it in the same way as the other tests so you don't miss anything because of different definitions of what constitutes a letter or digit. Character.isLetter() will return true for any Unicode letter, for example, not just ASCII A-Z or a-z. For consistency you should write:
char c = userInput.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c) && !Character.isWhiteSpace(c)) {
   countSpecial++;
}

But the problem in your original code is that the second parameter to String.substring() is the 'to' index, not a length. So if you were going to do with a regex it should be
if (userInput.substring(i, i+1).matches("[^A-Za-z0-9 ]")) {
   countSpecial++;
}

Is this a practical example or are you asking for help doing an assignment? :-)


Pandas merging selected columns into 1

Question: I have a df like this:
ID1 ID2 Day Text1 Text2 Text3 ....
111 A   1   a     b     c
222 B   2   i     j     k
333 C   3   x     y     z

My goal is to create a new columns that contain all values of Text1, Text2, Text3, and so on.
ID1 ID2 Day Text1 Text2 Text3 ....  Text
111 A   1   a     b     c           a, b, c...
222 B   2
333 C   3   x           y           x, y, ....

I've tried:
list(zip(df.Text1,df.Text2,df.Text3,...)):

This works but the format isn't desirable.
And:
df.apply(lambda x: ', '.join(x.astype(str)), axis=1):

This gives the desired format but the answer will contains all fields.
What would be the best approach this? Many thanks!
Answer: Vectorized solution:
In [65]: df['Text'] = df.filter(regex='^Text\d+').add(', ').sum(1).str.rstrip(', ')

In [66]: df
Out[66]:
   ID1 ID2  Day Text1 Text2 Text3     Text
0  111   A    1     a     b     c  a, b, c
1  222   B    2     i     j     k  i, j, k
2  333   C    3     x     y     z  x, y, z

Answer: Your code is very close. You just need to use apply on a df[text_cols] where text_cols is a list of the columns you want to merge into a new one.
df['Text'] = df[text_cols].apply(lambda x: ''.join(x), axis=1)

Answer: There is also a vectorized join:
>>> df['Text'] = df.filter(regex='^Text\d+').sum(1).str.join(', ')
>>> df
   ID1 ID2  Day Text1 Text2 Text3     Text
0  111   A    1     a     b     c  a, b, c
1  222   B    2     i     j     k  i, j, k
2  333   C    3     x     y     z  x, y, z

Answer: The other solutions are awesome, and I would like offer an answer that uses the cat() function.
df['text'] = df[0].str.cat([df[i] for i in df.columns[1:]],sep=',')

Hope it helps : )

Pandas merging selected columns into 1


Use Mvvmcross Binding with MonoTouch.Dialog (Lists and Commands)

Question: 1. Binding Lists
I wonder how I could bind a ObservableCollection to a Radiogroup:
new Section(){
                new RootElement("Mandanten", new RadioGroup("mandanten", 2)) {
                    new Section(){
                        new RadioElement("Kupus", "mandanten"),
                        new RadioElement("Kajmak", "mandanten")
                    }
                }
            }

as you see here I'm creating 2 Items/Elements manually but I miss something like an "ItemsSource".
If its not possible, what recommendation would you give me? To use witch Control (to bind Lists)?
2. CommandBinding
As I see theres no "button" in MonoTouch.Dialog. So I saw that we'll use "StringElement".
I tried it, but after tapping on the "button" nothing happened:
new StringElement("Login").Bind(this, "SelectedCommand LoginCommand")

I'm not sure whats wrong, maybe I need to use here the new "variant", like that:
new EntryElement ("User", "Loginuser", ViewModel.User).Bind(target, v => v.Value, t => t.User),

But I'm not sure how to build that similiar code to bind a command for a particular "stringelement" (in that case - a button with the ontap event)..
Any help appreciated!
Comment: If you can, please do ask one question per question - makes it easier to read, to search and to answer
Answer: 1. Binding lists
An example of binding dynamic ObservableCollection lists is in https://github.com/slodge/MvvmCross-Tutorials/blob/master/DialogExamples/DialogExamples.Touch/Views/ThirdView.cs - it uses some custom elements from https://github.com/slodge/MvvmCross-Tutorials/tree/master/DialogExamples/DialogExamples.Touch/BindableElements - which was based on the sample from https://github.com/asednev/MvvmCross.AlexeysExtensions
Because of the way Radio lists are internally implemented, I don't know if the same ObservableCollection binding approach would work for radio lists - someone would need to prototype and experiment to work this out. However, a simple fixed radio list is shown in https://github.com/slodge/MvvmCross-Tutorials/blob/master/DialogExamples/DialogExamples.Touch/Views/FirstView.cs
2. CommandBinding
See an example in: https://github.com/slodge/MvvmCross-Tutorials/blob/master/DialogExamples/DialogExamples.Touch/Views/FirstView.cs
                new Section("Action")
                    {
                        new StringElement("Second").Bind(bindings, element => element.SelectedCommand, vm => vm.GoSecondCommand),
                        new StringElement("Bindable Elements").Bind(bindings, element => element.SelectedCommand, vm => vm.BindableElementsCommand)
                    },


How to calculate radius of flush arch between two intersecting lines?

Question: I am trying to make a corner of a robot I am designing flush for aesthetic reasons as well as safety reasons but I'm not sure how to make the arch of the corner lay flush with the two lines that make up the edge.
Here is a photo of the side of the robot (top front of the starboard side).  The green lines illustrate the perimeter, the gray arch shows the angle between the two green lines (which is 72.9 degrees), and the black arch is the arch that I would like to create.  How can I find the correct radius for this black arch so it will connect the two sides without any angles?
Comment: Any radius can be used, to create an arc that will touch the two sides and make no angle.  There must be some piece of information you're not telling us, is there?
Comment: Sorry, my geometry is not too sharp.  What is in the picture is really all I know.  If there is something else that I need, I can probably find it out... But I'm not sure what it is.
Comment: OK, but what I'm saying is that you can use any sized curve you like, within reasonable limits, and make it work.
Answer: I do not know whether I am answering your question: there are many circular arcs that qualify.
Let $C$ be the centre of the desired circle. Let $A$ and $B$ be the two points of tangency, and let $O$ be where your two green lines meet at $72.9$ degrees. Let $2\theta$ be your angle, here $72.9$ degrees. So $\theta$ is $36.45$ degrees.
Let $r$ be the radius of the circle. Then
$$r=(OA)\tan\theta.$$
This is because the radial line $CA$ meets the tangent line at right angles.
Alternately, in terms of the distance $CO$, we have
$$r=(CO)\sin\theta.$$
If you specify something else than $OA$ or $CO$ that determines $r$, I can add to this answer.
Answer: One way to construct it is to choose the radius of the circle to start.  If you call it $r$, draw lines parallel to each side of the angle and inboard by $r$.  Where those lines intersect is the center of the circle.
Answer: You're already using a drawing program like Autodesk Inventor so just use a tangent constraint and inventor will calculate the radius for you.


Why does $n!+(n+1)!+(n+2)!=n!(n+2)^2$?

Question:
Why does $n!+(n+1)!+(n+2)!=n!(n+2)^2$?

Note: This is from the 1984 ARML I-7.
Comment: $$  n! \; \left( 1 + (n+1) + (n+1)(n+2) \right) $$
Comment: Note:  $(k+1)!=(k+1)\cdot k!$ is one of the defining properties of the factorial.  Rewrite the above where the **only** factorials appearing are $n!$ and combine like terms.
Answer: We have
$$\begin{align*}
 n! + (n+1)! + (n+2)! &= n! + n!(n+1) + n!(n+1)(n+2) \\
&=n!(1 + (n+1) + (n+1)(n+2))\\
&= n!(n^2 + 4n + 4) = n!(n+2)^2\;.
\end{align*}$$
Comment: @suomynonA: $$(n+1)!=(n+1)\underbrace{(n)(n-1)\ldots(2)(1)}_{n!}=(n+1)n!$$
Comment: Wait if you factor $(n+1)!$ it becomes $n!(n+1)$? Where can I learn how to manipulate equations with factorials? (online, free)
Comment: @suomynonA: I wouldn't call it "factor", it's just using the definition. The number $(n+1)!$ is by definition the product of the numbers $1, \dots, n, n + 1$ so we can write it as $(n+1)$ times the product of the numbers $1, \dots, n$ leading to $(n+1)! = (n+1) \cdot n!$. Often this is given as a (recursive) definition of $n!$.
Comment: @Brian and levap - Thanks, I see it now. Can someone answer the second part of my comment?
Comment: @suomynonA: Sorry, I'm not aware of any such places online. You might find some relevant information in Khan's academy but I'm not really familiar with it.
Answer: $$n!+(n+1)!+(n+2)!=n!+n!(n+1)+n!(n+1)(n+2)\\=n![1+(n+1)+(n+1)(n+2)]\\=n![(n+2)+(n+1)(n+2)]=n!(n+2)(n+1+1)$$
Answer: Because you can  factor $n!$:
\begin{align}n!+(n+1)!+(n+2)!&=n![1+(n+1)+(n+1)(n+2)]=n![n+2+(n+1)(n+2)]\\
&=n![(n+2)(1+(n+1)]=n! (n+2)^2.\end{align}
Comment: I lost the starting point on copying-pasting. I've added it. Thanks for pointing it!
Comment: How did you get the first part?

Why does $n!+(n+1)!+(n+2)!=n!(n+2)^2$?


Receiving error while trying to play video with AVPlayer

Question: I am trying to make local video playable with AVPlayer in xcode 10.1, swift 4.2, macOS app. I have created the AVKit Player View object in UI and made outlet in viewController.swift. Also created button in where all the actions should happen. You can see the code here -
import Cocoa
import AVKit
import AVFoundation
import AppKit

class ViewController: NSViewController {

@IBOutlet weak var playerView: AVPlayerView!

@IBAction func buttonAction(_ sender: Any) {

    let videoURL = "/Users/ramix/Downloads/test.mp4"

    let video = AVPlayer(url: URL(fileURLWithPath: videoURL))
    let videoPlayer = AVPlayerView()
    videoPlayer.player = video

    present(videoPlayer, animator:true, completion:{
        video.play()
    })

    override func viewDidLoad() {
        super.viewDidLoad()

    // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
    // Update the view, if already loaded.
        }
    }

}

I saw in multiple places that there was used AVPlayerViewController, but for some reason I dont have option to choose that method. Also this code returns this error -
Cannot invoke 'present' with an argument list of type '(AVPlayerView, animator: Bool, completion: () -> Void)'
I am new to swift, and I would like to ask for your help.
Thank you!
Answer: It seems you already created an outlet to an AVPlayerView which you probably added to the view hierarchy in Interface Builder. So you don't need to create a new player view, just assign the player to the outlet view like so:
self.playerView.player = video

Btw, the error happens because present is meant for presenting other view controllers, not for displaying views.
Comment: You should probably also store the `AVPlayer` in a property, otherwise it would get released as soon as your button click was handled.
Comment: Ok when I change to this I got this in output -
<<<< AVOutputDeviceDiscoverySession (FigRouteDiscoverer) >>>> -[AVFigRouteDiscovererOutputDeviceDiscoverySessionImpl outputDeviceDiscoverySessionDidChangeDiscoveryMode:]: Setting device discovery mode to DiscoveryMode_Presence
And nothing happens
Comment: This error should not be related. You also need to start playback with `videoPlayer.play`, maybe in `viewDidAppear`.


Machine learning *why* instances are a certain classification

Question: I know machine learning algorithms are good at determining/predicting what an instance is (classification and such) or how instances are related. Are there any algorithms that, given classified training data and classified test data, can describe (in some way, maybe pointing out attributes) why an test instance is classified a particular way.
An example might help as well. Say we're dealing with a binary-class dataset:
    Class    A    B    C    D    ...
1   T        0.5  0.7  0.3  0.9  ...
2   T        0.6  0.2  0.4  0.8  ...
3   T        0.5  0.6  0.6  0.7  ...
4   F        0.9  0.2  0.2  0.5  ...
5   F        0.9  0.8  0.4  0.5  ...
...

Now we want to train a model, given training data of this type, such that we can give a test instance and ask, "Why, or why not, is this instance class=T? What variables have the most significant impact on the classification?
So I could then give a test instance with a classification given:
    Class    A    B    C    D    ...
X   T        0.4  0.9  0.8  0.9  ...

The algorithm could then respond, maybe indicating specific attributes which seem to be indicators of distinction between the two classes or something along those lines. For example: "Instance X would tend to be classified as T because value A tends to be around 0.5 and D tends to be around 0.9." Or alternatively there may be no good reason for X to be classified as T, then the algorithm would either be inconclusive or have low confidence measure on its results.
I'm not sure if anything like this exists, but have searched around and thought it might be useful to ask here. Any help (for good or worse) is greatly appreciated. Thank you.
Comment: You wouldn't have another algorithm to tell you why your classifier produced this output. You would just study your classifier itself.
Comment: @gung in this scenario, I don't have access to the classifier. I just have it's results.
Comment: Do you know anything about the classifier that was used (eg, random forest, neural network, etc)? How it was trained? Etc.
Comment: @gung I should clarify, having access to the classifier is unnecessary or at least not helpful. Take this scenario, we have a dataset of restaurants. I now say for each restaurant, if `average_price` is above $10, class = `expensive`, else, class = `inexpensive`. Now remove the attribute `average_price` from all data. Train a model to figure out *why* some restaurants are expensive, regardless of average price. Basically trying to fit a model to an artificially created classification. Does this example help more?
Answer: Decision tree learning produces models that are very easy to interpret.  You can just trace an input's path down the tree and see exactly why it ended up in the class it landed in.  That direct interpretability is actually a key strength of decision trees.  Similarly, random forests,
 which are made of decision trees, have a similar benefit.  But interpretation is less direct because there are many trees to consider for a single input.
More complex, nonlinear, or highly dimensional models (like neural networks) still have rules that govern input to output relationships.  Those rules are usually even deterministic, so you can trace the inputs in the same way as with decision trees.  The problem arises from interpreting that information in a meaningful way.
A toy example about house price prediction might help demonstrate what I mean.

A decision tree can directly tell you that a house ended up in the 500K-750K bucket because it has 2 bathrooms, 2 bedrooms, between 1200 and 1400 square feet, and is newer than 5 years old.
A neural net making the same prediction will directly tell you that 100 inputs to 50 tanh functions across 3 layers gave a softmax output that corresponds to 500K-750K.

The latter is much more difficult to interpret, but not a lost cause.
Look up model/prediction interpretation for the type of model you're interested in to see how others have approached the problem.
Answer: You are talking about variable or feature selection, of which the literature is vast.
Various methods exist, which can be broadly characterized in three categories:

Filter methods: these methods typically use univariate statistics to filter out or select features in function of your target variable.
Wrapper methods: these methods incrementally add/remove features which are best/worst performing.
Embedded methods: these methods instantly give you a score along with your prediction. As the answer above, Random Forests for example, will be able to give you along with your trained model an output which is called variable importances.

An overview of review papers concerning the topic of variable selection can be found here.


What does General Cache Wipe mean

Question: The definition of CACHE_TEMPORARY used in cache_set reads as follows.

CACHE_TEMPORARY: Indicates that the item should be removed at the next
  general cache wipe.

I am just curious as to what General Cache Wipe means and what constitutes to General Cache Wipe other than obvious cron.
Answer: Any action that makes a call to either cache_clear_all(NULL, $table); on all core cache tables or a call to cache_clear_all(); can be termed as General Cache Wipe
I could list down following based on a quick grep search for these functios.

Cron : Very obvious.
When a vote is submitted on a poll.
Any operation performed on admin/content page like

Node Multiple Delete. (Handled as a special case with confirmation form)
Any other operation like

When node access is rebuilt. (Like change of permissions)
When menu cache is cleared. (Node module clears all the caches [node_menu()])
Node Form Submission. [Creation or Updation]
Node Deletion
Comment Form Submission
Any operation performed on admin/content/comment page
Block administration. Any action performed on admin/structure/block
Create, Delete/Update any custom block.
Any forum form submit.
Any System Theme settings are changed.
When aggregator parses a feed.
Profile fields are edited/updated/deleted or their weights and categories are changed.
When a user account is cancelled.
When taxonomy term/vocabulary is added/deleted/updated.
Comment: So, if I call cache_set with CACHE_TEMPORARY, followed by cache_clear_all(), then the entry should be deleted from the database and a subsequent cache_get should not return the cached item? That doesn't seem to be the case :-(

What does General Cache Wipe mean


Do query in firebase-realtime-database

Question: I have this structure in my firebase-realtime-database:
- child_n
  - child_n_1
   - $id_child_n_1
    - $subid_child_n_1
     - dates
      * 20180102: true
      * 20181102: true
      * 20181120: true
   - $id_child_n_2
    - $subid_child_n_2
     - dates
      * 20181103: true
      * 20181105: true
      * 20181204: true

I need to query under child dates and return those objects(id_child's) that contain dates from specific range.
I already tried something like:
query = db.reference(..).child(child_n/child_n_1).order_by_child(dates).start_at('specific_date').end_at('specific_date').get() not working, and return 0 objects!

I used ".indexOn":
"database_id":  {
      "child_n": {
        "child_n_1": {
          ".indexOn": ["dates_subid_child_n_1"]
        }
      }
    },

query = db.reference(..).child(child_n/child_n_1).order_by_child(dates).end_at('specific_date').get() working but return all objects.

Any idea how I can to perform this query???
Comment: I'm using firebase_admin
Answer: You're almost there. When you use order_by_child, the nodes are ordered by the value of that child property. In this case you want to order by the key of each child node, which you do with order_by_key:
db.reference(..).child(child_n/child_n_1/dates).order_by_key().start_at('specific_date').end_at('specific_date').get()

Comment: how about child 'id_child_n_1' and 'subid_child_n_1', path that you mention will try to find 'dates' in child_n/child_n_1 node, where this doesn't exist, this are placed in: 'child_n/child_n_1/$id_child_n_1/$id_child_n_1/'
Comment: and this doesn't return any 'child_n_1' objects
Comment: Firebase Database queries work on a list of nodes. If you're trying to query a tree of nodes, that probably won't work. The probably here is because I find it hard to understand the actual meaning of your data structure. Consider updating your question with the actual concrete values, instead of abstract ids and numbers, to make it easier to understand the context.
Comment: So path that I can take in query is 'child_n/child_n_1' rest of path is specific id's that I dont know from start, and I need to find some solution if this is possible.

Do query in firebase-realtime-database


Need help defining IE specific stylesheet with Zen Starter-kit and Conditional Stylesheet Module

Question: I need help defining a conditional IE stylesheet in my .info file.
I am using the Zen starterkit as my base theme, and I have the conditional stylesheet module installed and enabled. I have added an ie.css file added to my css directory along with my other stylesheets. In that ie.css file, I have changed the background to an obnoxious color to confirm when the stylesheet is being used appropriately.
However, I have been struggling with what I need to put in my .info file. I have researched as much as I could and read the help.txt file multiple times.
I just want this stylesheet to target IE. I do not want to create one for each version. This site will not support ie6 and ie7 anyways.
Here is what I currently have defined in my .info file for it:
stylesheets-conditional[if IE][all][] = css/ie.css

I have also tried this that just results with that stylesheet loading for all browsers:
stylesheets-conditional[!IE][all][] = css/ie.css

So far with all of my attempts, I can either get it to act as a normal stylesheet, having it override my other styles, or not having it load at all. Is there something I need to add in my page templates that I am overlooking?
I have this in the head of my html.tpl.php as well (I have my actual theme name in there):

Other resources that I have used:
1) Conditional Stylesheets Set-up: Using the Module
2) Add conditional stylesheet CSS for internet explorer only (not trying to use this method)
Answer: If this link is in your head it is like if the css file is in a folder under the currrent one. You need a first backslash:
As you can see in the answer you linked the definition in .info file has to look like
stylesheets-conditional[IE][all][] = css/ie.css

not
stylesheets-conditional[if IE][all][] = css/ie.css

(I just have it from this answer - never used this module). Honestly I would not install a module just to add conditional comments for IE. It is easier and saves performance eating module to put them simply into the html.tpl.php - you just have to keep the right paths.
stylesheets-conditional[!IE][all][] = css/ie.css

Makes absolutely no sence - I do not know if this module could interprete that. But at least no browser in the world would read a css file in such a conditional comment: every browser except IE ignores conditional comments. So you tell the only browser who reads them that this file is notfor it to use... you got it :)
Comment: I changed my definition in the .info file to what you mentioned and altered my line in my html.php.tpl with exactly what you had (with my theme name) without success.

I agree with you on not needing the module at all.  Since what you mentioned did not work, I tried to disable the module and give it a try; no success.  Changed it to be formatted like the other "normal" stylesheets in .info file; no success.

I did clear the cache with each attempt.  If I remove  in the html then it works. I am using IE 11 so that might be the problem.  I am not sure what else to try.
Comment: I have tried everything I can think of.  I even tried the older way by adding it through template.php with the appropriate hooks and that did not work either.  It looks like there is another issue preventing the conditional stylesheets from working.
Comment: Turns out after testing emulation modes with ie11, this stylesheet is picked up for all old versions but 10 and 11(edge).  I now do not know how to make this stylesheet work for 10 and 11.
Comment: http://msdn.microsoft.com/en-us/library/ie/hh801214%28v=vs.85%29.aspx - conditional comments are not supported any more starting with IE10


Corrupted index in a particular set

Question: We are experiencing a problem involving missing records using a secondary key. A set namely user contains the following bins: name, email, password, role and private_token- with a secondary key on the bin private_token.
Regarding the issue:
As of the previous week, four nodes in Google Cloud. The secondary key of the user set was working fine.
During the end of last week, we created a new node and now this specific set stopped returning any data when querying it using a secondary key. Regarding all the other set having a similar configuration, they kept returning the correct values.
The namespace n1 of the user set is using a non local SSD storage.
In order to troubleshoot the issue, we created a new namespace, namely test, that is stored in memory.
Here is a script that fails in the n1 namespace but succeed in the test namespace:
INSERT INTO test.user (PK, name, email, password, role, private_token) VALUES ('firstname.lastname@example.com', 'Test 1', 'firstname.lastname@example.com', 'password_test_1', 'role_test_1', 'private_token_1')
INSERT INTO test.user (PK, name, email, password, role, private_token) VALUES ('email@example.com', 'Test 2', 'firstname.lastname@example.com', 'password_test_2', 'role_test_2', 'private_token_2')
CREATE INDEX user_private_token ON test.user(private_token) STRING

SELECT * FROM test.user WHERE private_token = 'private_token_2'

Here is the output in test namespace:
+----------+------------------+-------------------+---------------+-------------------+
| name     | email            | password          | role          | private_token     |
+----------+------------------+-------------------+---------------+-------------------+
| "Test 2" | "email@example.com" | "password_test_2" | "role_test_2" | "private_token_2" |
+----------+------------------+-------------------+---------------+-------------------+
1 row in set (0.001 secs)

And here in n1 namespace:
0 rows in set (0.001 secs)

Version of aerospike:
$ dpkg -l | grep aerospike
ii  aerospike-amc-community                   3.6.4                         all          AMC Community Version is a web UI based monitoring tool for Aerospike Community Edition Server releases after 2.6.3 (March 2013)
ii  aerospike-server-community                3.6.4-1                       amd64        The Aerospike distributed datastore allows fully scalable and reliable data storage with elastic server properties.
ii  aerospike-tools                           3.6.3                         amd64        Aerospike server tools.

Trying to troubleshoot in asadm:
$ asadm
Aerospike Interactive Shell, version 0.0.13
Found 6 nodes
Online:  10.240.0.3:3000, 10.240.0.4:3000, 10.240.0.5:3000, 10.240.0.2:3000, 10.240.0.6:3000
Offline: 10.240.0.9:3000

Admin> info network
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Network Information~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          Node               Node                                           Fqdn                Ip   Client     Current     HB          HB
             .                 Id                                              .                 .    Conns        Time   Self     Foreign
10.240.0.9       000000000000000    10.240.0.9:3000                                10.240.0.9:3000      N/E         N/E    N/E         N/E
aerospike-vm-1   BB90300F00A0142    aerospike-vm-1.c.citiservi-ads.internal:3000   10.240.0.3:3000       38   193339236      0   249014840
aerospike-vm-2   BB90500F00A0142    aerospike-vm-2.c.citiservi-ads.internal:3000   10.240.0.5:3000       37   193339236      0   194991137
aerospike-vm-3   BB90400F00A0142    aerospike-vm-3.c.citiservi-ads.internal:3000   10.240.0.4:3000       34   193339236      0   229395269
aerospike-vm-4   BB90200F00A0142    aerospike-vm-4.c.citiservi-ads.internal:3000   10.240.0.2:3000       45   193339236      0   224245394
aerospike-vm-5   *BB90600F00A0142   aerospike-vm-5.c.citiservi-ads.internal:3000   10.240.0.6:3000       37   193339236      0    17162917
Number of rows: 6

Admin> info service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Service Information~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          Node   Build   Cluster      Cluster     Cluster    Free   Free    Migrates        Principal    Objects       Uptime
             .       .      Size   Visibility   Integrity   Disk%   Mem%   (tx,rx,q)                .          .            .
10.240.0.9       N/E         N/E   N/E          N/E           N/E    N/E   N/E         N/E                   N/E   N/E
aerospike-vm-1   3.6.4         5   True         True           61     68   (0,0,0)     aerospike-vm-5   58.618 M   1710:56:06
aerospike-vm-2   3.6.4         5   True         True           61     69   (0,0,0)     aerospike-vm-5   57.594 M   1472:30:21
aerospike-vm-3   3.6.4         5   True         True           61     68   (0,0,0)     aerospike-vm-5   57.430 M   1638:33:39
aerospike-vm-4   3.6.4         5   True         True           61     68   (0,0,0)     aerospike-vm-5   58.242 M   1824:25:55
aerospike-vm-5   3.6.4         5   True         True           61     71   (0,0,0)     aerospike-vm-5   57.774 M   102:48:57
Number of rows: 6

Admin> info sindex
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/bin/asadm/__main__.py", line 20, in <module>
  File "/usr/bin/asadm/asadm.py", line 339, in main
  File "/usr/lib/python2.7/cmd.py", line 141, in cmdloop
    line = self.precmd(line)
  File "/usr/bin/asadm/asadm.py", line 108, in precmd
  File "/usr/bin/asadm/lib/controllerlib.py", line 176, in execute
  File "/usr/bin/asadm/lib/controllerlib.py", line 120, in __call__
  File "/usr/bin/asadm/lib/controllerlib.py", line 176, in execute
  File "/usr/bin/asadm/lib/controller.py", line 158, in do_sindex
TypeError: string indices must be integers, not str

How can I fix the set and have a working index again?
Thanks in advance
Answer: Unlikely to still be an issue, but the Managing Indexes article of the Operations manual has information on how to repair an index. There has also been quite a lot of work done on secondary indexes since the version 3.6 you where quoting.

Corrupted index in a particular set


How to prove that in a closed, convex, and not bounded set from every point there is a closed half-line that is in the set?

Question: Let $K \subseteq \mathbb{E}^n$ a closed, convex, and not bounded set. How to show that then from every point of $K$ there is a closed half-line that is in $K$.
Comment: Is that supposed to be $K \subseteq \Bbb R^n$?
Comment: @araomis ... then what to do with all those arbitrarily large segments?
Answer: Wlog the point in $K$ we want to find a half-line from is the origin.
For $r>0$, let $U_r=\frac1r\cdot K^\complement$, which is open.
Assume $\bigcup_{r>0}U_r$ covers the unit sphere $S^{n-1}$. Then by compactness a finite cover suffices, $S^{n-1}\subseteq U_{r_1}\cup\ldots\cup U_{r_n}$.
Let $R=\max\{r_1,\ldots,r_n\}$. As $K$ is unbounded, pick $x\in K$ with $|x|>R$.
Then $\frac1{|x|}x\in S^{n-1}$ and therefore $\in U_{r_i}$ for some $1\le i\le n$.
Then $y:=\frac{r_i}{|x|}x\in K^\complement$. But $0<\frac {r_i}{|x|}$ so that $y$ is on the line segment between $0$ and $x$, and so $0\in K$, $x\in K$, $y\notin K$ contradicts the convexity of $K$.
We conclude that $\bigcup_{r>0}U_r$ does not cover the unit sphere. If $v\in S^{n-1}$ is left out, this means that $rv\in K$ for all $r>0$.


php5.6-fpm high cpu usage

Question: I am currently running a Wordpress website using php-fpm and nginx and have it using extremely high cpu rates.

Here is my www.conf file:
<code>[www]
user = www-data
group = www-data
listen = 127.0.0.1:9000
listen.owner = www-data
listen.group = www-data
pm = ondemand
pm.max_children = 10
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.process_idle_timeout = 10s
ping.path = /ping
pm.status_path = /status
pm.max_requests = 30
request_terminate_timeout = 20
</code>
I am using wp total cache and fastcgi. Any files you know I can find I can show.
My website gets around 800 views a day and it having content added around 5-6 times a day.
Answer: Wordpress uses a lot of CPU on a busy website. Using the CPU isn't a problem - I don't see a problem here. If you're getting very few visitors that CPU may be excessive, but you haven't given us that information.
Caching plugins reduce CPU a little, but you still have to call PHP to render the page. Caching at the web server layer (Nginx) is much faster, for anonymous users, and it can generate pages live for logged in users.
Nginx page caching for anonymous users can significantly reduce CPU usage. I have a tutorial on that here, and there's an Nginx tutorial here. If your site changes frequently you can look at microcaching.
Comment: Sorry, the website gets about 800 views a day and is really slow. I am trying to improve load speeds.
Comment: Please edit your question to add more information to your question around load, server specifications (CPU and RAM), and top output when the server is busy / not busy. You might check the logs to see if there's anything relevent. 800 users a day is about one every minute, that should be negligible load.
Answer: Check the contents of your Wordpress PHP files, make sure some nasty code hasn't been inserted in them after a compromise. Attackers usually insert the code in all PHP files, so you should only need to check a few random ones in the base directory.

php5.6-fpm high cpu usage


Como selecionar um radio ao clicar no texto ao lado dele?

Question: É bem simples fazer fazer botões do tipo radio. Eu já vi uns inputs desse gênero por aí que permitem clicar diretamente dentro do circulo ou em cima do texto que se refere a cada botão radio.
Como que se faz isso?
Comment: Procure sobre `label` do HTML.
Comment: Oh... BEM mais simples do que eu poderia imaginar. Obrigado.
Answer: Basta você colocar o texto dentro de um elemento  que aponte para o ID do input correspondente:
<input type="radio" name="cores" id="vermelho">vermelho
<input type="radio" name="cores" id="verde">verde
<input type="radio" name="cores" id="azul">azul

Comment: Ou então `` que não precisa apontar pro ID ;)
Comment: É mesmo, não sei por que nunca faço isso!


Hello world with German umlauts and other unusual characters ä ö ü ß @  ♫ Ꞧ € ᴀ ꟽ ㍻

Question: Unicode chars in the eclipse console are not the same as in the class file. But all other views show the right chars. is that a bug in the eclipse console? (System.out) Look at the Screenshot, Thanks
Comment: It probably just means the font being used by the console doesn't contain the characters displayed as ?
Comment: thank you, can i change that?
Comment: In the Preferences go to 'General > Appearance > Colors and Fonts' look for 'Console font' in the 'Debug' section.
Comment: i check that ... i change with "edit default" and all views change the font but the ? chars in the console is still here
Answer: You probably got an inappropriate console encoding in your launch configuration. You can change it in Run -> Run Configurations... in the Common tab (see screenshot). The default encoding comes either from the project properties or the workbench setting at Preferences -> General -> Workspace.

Hello world with German umlauts and other unusual characters ä ö ü ß @ ￼ ♫ Ꞧ € ᴀ ꟽ ㍻


How do you manipulate GUID's when programming C or C++ in Windows?

Question: How do you manipulate GUID's when doing Windows programming in C or C++?
Comment: Don't answer a question in a question.
Answer: Under Win32 if you want to manipulate GUID's you can use the UuidXXX() Network/RPC functions:

UuidCompare()
UuidCreate()
UuidCreateNil()
UuidCreateSequential()
UuidEqual()
UuidFromString()
UuidHash()
UuidIsNil()
UuidToString()
Answer: I use boost::uuid : http://www.boost.org/doc/libs/1_43_0/libs/uuid/index.html
That way it is guaranteed to still work if I port my application on another plaftorm.


Asymptotic solution of matrix differential equation expanded in powers of $1/x$

Question: Consider the differential equation
$$
\frac{\text{d} y}{\text{d} t} = \left(c_0 + c_1 t^{-1} + c_2 t^{-2} + \dots c_n t^{-n} \right) y ;\quad y(1) = y_0 > 0; t \geq 1.
$$
where $c_i > 0$ for each $i$. This can be solved directly and we find, for some $\alpha \neq 0$, that
$$
y(t) \sim  \alpha t^{c_1} e^{c_0 t}.
$$
where $f(t) \sim g(t)$ if $\lim_{t \to \infty} y(t)/g(t) = 1$.
I'm interested in the generalization of this result to the case of a system of differential equations. Basically, I think something like the following is probably true or almost true:

Prop. 1. Let $A_0$ be a $d \times d$ non-negative irreducible matrix with Perron-Frobenius eigenvalue $\lambda$, and let $A_1, A_2 \dots A_n$ be nonnegative $d \times d$ matrices. Then, the system $$ \frac{\text{d} \mathbf{y}}{\text{d} t} = \left(A_0 + A_1 t^{-1} + A_2 t^{-2} + \dots A_n t^{-n} \right) \mathbf{y} ;\quad \mathbf{y}(1) = \mathbf{y}_0 > \mathbf{0}; t \geq 1. $$ has, for some $\alpha_i \neq 0$ and some $\beta_i$, $$ |\mathbf{y}_i(t)| \sim \alpha_i t^{\beta_i} e^{\lambda t} \quad 1 \leq i \leq d. $$

Question: I'm looking for a reference which shows that Prop. 1 is true, or true provided with some other technical condition. It seems similar to Theorem 19.1 of Asymptotic Expansions for Ordinary Differential Equations by Wasow but I don't fully see the connection.
Answer: Let's find directly the asymptotic result of Prop.1.
Diagonalize the matrix $A_0$, with $D$ the diagonal matrix having diagonal elements equal to $(\lambda_i)$ for $i=1,...,d$ and $U$ the matrix of eigenvectors.
$$A_0 = U^{-1}DU$$
The system of equation is then equivalent to
$$\begin{align}
&\Longleftrightarrow \frac{d }{d t}\mathbf{y} = \left(U^{-1}DU + A_1 t^{-1} + A_2 t^{-2} + \dots A_n t^{-n} \right) \mathbf{y}\\
&\Longleftrightarrow \frac{d }{d t}(U\mathbf{y}) = \left(DU + UA_1 t^{-1} + UA_2 t^{-2} + \dots UA_n t^{-n} \right) \mathbf{y} \\
&\Longleftrightarrow \frac{d }{d t}(U\mathbf{y}) = \left(D + UA_1U^{-1} t^{-1} + UA_2U^{-1} t^{-2} + \dots UA_nU^{-1} t^{-n} \right) (U\mathbf{y}) \tag{1}\\
\end{align}$$
Let's denote $\mathbf{z} = U\mathbf{y}$, then
$$(1) \Longleftrightarrow \frac{d }{d t}\mathbf{z} = \left(D + UA_1U^{-1} t^{-1} + UA_2U^{-1} t^{-2} + \dots UA_nU^{-1} t^{-n} \right) \mathbf{z} \tag{2}$$
The $i^{\text{th}}$ equation of $(2)$, for $i=1,...,d$ has the following form
$$\frac{d z_i }{d t}(t) = \lambda_i z_i(t)+ t^{-1}\sum_{j=1}^d (\alpha_{1j}z_{j}(t))  + \color{red}{t^{-2}}\sum_{j=1}^d (\alpha_{2j}z_{j}(t)) + \dots + \color{red}{t^{-n}}\sum_{j=1}^d (\alpha_{nj}z_{i}(t))  \tag{3} $$
For $t$ large ($t\to +\infty$), the terms in red color become small. By the same argument as for the unidimensional case, we can ignore these terms, and then, for $i=1,...,d$, we have
$$(3) \implies \frac{d z_i }{d t}(t) \sim \lambda_i z_i(t) + \frac{1}{t}\sum_{j=1}^d (\alpha_{1j}z_{j}(t))  \qquad \forall i=1,...,d  \tag{4}$$
Let's solve the system of equations $(4)$, we have
$$\begin{align}
(4) &\Longleftrightarrow \left(e^{-\lambda_i t} z_i(t)  \right)' = \frac{1}{t}\sum_{j=1}^d \left(\alpha_{ij} e^{-\lambda_i t}z_{j}(t)  \right) \qquad \forall i=1,...,d
\end{align}$$
For the sake of simplicity, let's denote $p_i(t) = e^{-\lambda_i t} z_i(t)$, and $ \mathbf{p} =\left(p_1(t),...,p_d(t)  \right)$. The matrix form of the relation between $p_i(t)$ and $z_i(t)$ is
$$\mathbf{p} = \Gamma^{-1}\mathbf{z}$$
with $\Gamma$ - a diagonal matrix having elements $e^{\lambda_i t}$ for $i=1,...,d$
And the matrix form of the new system of equation is
$$\frac{d}{dt} \mathbf{p} = \frac{1}{t} UA_1U^{-1} \mathbf{p} \tag{5}$$
Diagonalize the matrix $A_1$ with $H$ the diagonal matrix having diagonal elements $\beta_1,...,\beta_d$ and $V$ the matrix of eigenvectors.
$$A_1 = V^{-1}HV$$
then
$$\begin{align}
(5) &\Longleftrightarrow \frac{d}{dt}\mathbf{p} = \frac{1}{t} UV^{-1}HVU^{-1} \mathbf{p} \\
 &\Longleftrightarrow \frac{d}{dt}(VU^{-1}\mathbf{p} )= \frac{1}{t} H (VU^{-1} \mathbf{p}) \tag{6}\\
\end{align}$$
$(6)$ can be solved easily. Indeed, each equation of $(6)$ has the following form
$$\frac{d}{dt}q_i(t) = \frac{\beta_i}{t}q_i(t) \Longleftrightarrow q_i(t) = c_it^{\beta_i} \qquad \forall i=1,...,d $$
Then
$$\begin{align}
(6)&\Longleftrightarrow VU^{-1}\mathbf{p} = \begin{pmatrix}
           c_1t^{\beta_1} \\
    c_2t^{\beta_2} \\
\cdot \cdot \cdot\\
c_dt^{\beta_d} \\
  \end{pmatrix} \\
&\Longleftrightarrow
VU^{-1}\Gamma^{-1}\mathbf{z} = \begin{pmatrix}
           c_1t^{\beta_1} \\
    c_2t^{\beta_2} \\
\cdot \cdot \cdot\\
c_dt^{\beta_d} \\
  \end{pmatrix} \\
&\Longleftrightarrow
\Gamma^{-1}VU^{-1}\mathbf{z} = \begin{pmatrix}
           c_1t^{\beta_1} \\
    c_2t^{\beta_2} \\
\cdot \cdot \cdot\\
c_dt^{\beta_d} \\
  \end{pmatrix} \qquad \text{as } \Gamma \text{ is diagonal matrix}\\
&\Longleftrightarrow
VU^{-1}U\mathbf{y} = \Gamma\begin{pmatrix}
           c_1t^{\beta_1} \\
    c_2t^{\beta_2} \\
\cdot \cdot \cdot\\
c_dt^{\beta_d} \\
  \end{pmatrix} \\
&\Longleftrightarrow
\color{red}{\mathbf{y} = V^{-1} \begin{pmatrix}
           c_1t^{\beta_1} e^{\lambda_1 t}\\
    c_2t^{\beta_2}e^{\lambda_2 t} \\
\cdot \cdot \cdot\\
c_dt^{\beta_d}e^{\lambda_d t} \\
  \end{pmatrix}}  \tag{7} \\
\end{align}$$
with $V$ the matrix of eigenvectors defined by $A_1 = VHV^{-1}$.
$(7)$ is the more accurate solution than the one in your Prop.1. If we seek only the most major term for each $y_i(t)$, then we can do as follows
$$\color{red}{y_i(t) = \sum_{j=1}^d v_{ij}c_jt^{\beta_j}e^{\lambda_j t}} \sim v_{i\color{blue}{g}(i)}c_{\color{blue}{g}(i)} t^{\beta_{\color{blue}{g}(i)}}e^{\lambda{_\color{blue}{g}(i)} t} \qquad \forall i=1,...,d $$
with $\color{blue}{g}(i) =\underset{j=1,...,d}{\operatorname{argmax}}   \{\lambda_j  | v_{ij}c_j \ne 0\}$.
Remark: if all the coefficients $v_{ij}, c_j$ for $1\le i,j \le d$ are not $0$, then for all $i=1,...,d$, we have $\color{blue}{g}(i) = \color{blue}{g} =\underset{j=1,...,d}{\operatorname{argmax}}   \{\lambda_j \}$ be the index $j^{th}$ such that $\lambda_j=\color{purple}{\lambda}$ (the P.E eigenvalue), and so we have
$$y_i(t) \sim v_{i\color{blue}{g}}c_\color{blue}{g} t^{\beta_\color{blue}{g}}e^{\color{purple}{\lambda} t} \qquad \forall i=1,...,d $$
Comment: Perfect, thanks so much!
Comment: Thanks for your answer, but how would all of the diagonal elements of $D$ be equal to $\lambda$? Shouldn't only one of them be equal to $\lambda$ since the P.F. eigenvalue is unique?
Comment: @Mr.G I suppose that all the eigenvalues are equal to $\lambda$ such that we have the results in your Prop.1. However, if we relax this assumption and suppose that the eigenvalues may be different, we still have closed form solution (I can change the solution) and the result is not the one that you expected in Prop.1
Comment: @Mr.G It's done. The answer is for general form of matrix $A_0$ with different eigenvalues. The information of Perron-Frobenius eigenvalue $\lambda$ ( $= \max_{i=1,...,d}\lambda_i$) is not necessary (as we know the matrix $A_0$).
Comment: If $g$ is anything other than the index corresponding to the P.F. eigenvalue then $\lim_{t \to \infty} \frac{\color{red}{y_i(t)}}{v_{ig} c_{g} t^{\beta_g} e^{\lambda_g t}}$ will either be $0$ or $\infty$ though won't it?
Comment: Well, it might be something else if $\lambda_g$ is complex, but the point is that the term with the factor $e^{\lambda t}$ where $\lambda$ is the P.F. should always dominate?
Comment: @Mr.G I just realized that there is a small typo at the last result. And after changing it, we  have the expected result (if $v_{ij}c_j \ne 0$ (for $1\le i,j\le d$)): the dominating term $e^{\lambda t}$ appears in all $y_i(t)$
Comment: @Mr.G You're welcome!


Descricao grafico em pizza sobreposicao

Question: Como resolver isso? Legendas do grafico em pizza se sobrepondo a outras.
Answer: Resolvi isso com:
<code>counts.plot(kind='pie', labels = None, figsize=(11,8), legend=True)
</code>

Descricao grafico em pizza sobreposicao


Como exibir os dados do ultimo registro salvo no banco

Question: como faço para exibir na view somente os dados do último registro salvo no banco? consigo exibir todos os dados chamando o método All() no controle, e o bom e velho foreach na view para exibir os dados. Porém, queria que quando o usuário finaliza-se o cadastro ele fosse redirecionado para uma página, onde ele pudesse conferir os dados que cadastrou.
obs:estou usando laravel, eloquent orm, mysql
no controle tenho essa action para pegar todos os dados

public function exibe(){
  $dados = Denuncia::all();
  return view('AdminDenunciaView.exibeInformacao',['dados'=>$dados]);
}

na view uso este foreach para exibir os dados

@foreach ($dados as $item)
   {{$item->crime}}.

   {{$item->infrator}}.

@endforeach

Mas como mencionei, não preciso que todos os dados sejam mostrados, apenas os dados ultimo registro
Comment: mysqli_insert_id - Retorna o id gerado automaticamente na última consulta. Com isso vc faz seu select com where nomeColuna = id gerado automaticamente na ultima consulta   https://www.php.net/manual/pt_BR/mysqli.insert-id.php
Answer: Na query você poderia dar um order by, para listar o ultimo registro.
Exemplo: select * from clientes order by cliente_id desc
Assim retornaria o ultimo registro cadastrado.
Comment: valeu pelo feedback, mas dessa forma é retornado todos registros, porém na ordem decrescente. A idea é lista apenas o último registro
Comment: Você pode colocar o limit 1(MYSQL).
Answer: para ordenar pelo último registro você pode fazer o select order by desc
Exemplo
select * from tabelaExemplo order by tabelaExemplo_id  desc

Para pegar somente o ultimo registro do banco você pode fazer assim:
select * from tabelaExemplo where tabelaExemplo.id = select max(id) from tabelaExemplo

Comment: obg por tentar ajudar, mas seguindo a 1ª resposta é retornado todos os registro, porém em forma decrescente, mas a ideia é retornar apenas o ultimo registro.  Já a 2ª resposta está mostrando um erro de sintaxe
Answer: Você pode dar um order by pelo id mais alto (último adicionado) e pegar o primeiro registro da lista retornada, com o first() do eloquent.
exemplo: DB::table('tabela')->orderBy('id', 'DESC')->first();
Dessa forma o primeiro da lista vai ser o ultimo id adicionado, e essa query vai te retornar apenas 1 resultado.
Comment: Olá Sara! valeu pelo feedback, seguindo o exemplo que você  postou  obtive a seguinte resposta. Você está tentando usar o método orderBy() na coleção Eloquent. Pequisei um pouco mais e descobrir que teria que usar o método sortByDesc, pois este já classifica a coleção na ordem oposta. Logo depois, uso método First para capturar o primeiro na ordem oposta, vlw muito obrigado.

ficou assim
Denuncia::all()->sortByDesc('id')->first();
Comment: Oi, que bom que ajudei!! vlw pela resposta :)


How does the approximate Hessian update in LBFGS work?

Question: Looking at the wikipedia page for BFGS... Wikipedia
It looks like a rearranging of Newton's method, but I can't really explain why the update to the approximate Hessian would be given by the following line...
$$
B_{k+1}(\mathbf{x}_{k+1} - \mathbf{x}_k) = \nabla f(\mathbf{x}_{k+1}) - \nabla f(\mathbf{x}_{k})
$$
I don't see why simply subtracting the derivative from the derivative at the updated function evaluation would give an approximation of the Hessian. Shouldn't there be a denominator to normalize the difference by something in order to be precise, such as in the simple and traditional derivative calculation which dvides by $h$?
Answer: The Wiki page goes on:

Set $\mathbf{s}_{k}=\alpha_{k} \mathbf{p}_{k}$ and update $\mathbf{x}_{k+1}=\mathbf{x}_{k}+\mathbf{s}_{k}$
$\mathbf{y}_{k}=\nabla f\left(\mathbf{x}_{k+1}\right)-\nabla f\left(\mathbf{x}_{k}\right)$
$B_{k+1}=B_{k}+\frac{\mathbf{y}_{k} \mathbf{y}_{k}^{\mathrm{T}}}{\mathbf{y}_{k}^{\mathrm{T}} \mathbf{s}_{k}}-\frac{B_{k} \mathbf{s}_{k} \mathbf{s}_{k}^{\mathrm{T}} B_{k}^{\mathrm{T}}}{\mathbf{s}_{k}^{\mathrm{T}} B_{k} \mathbf{s}_{k}}$

where $\alpha_k$ is a step size.  So both $y_k$ and $s_k$ include a step size. The two update bits of step 5 both have two $\alpha$s in the numerator and two in the denominator (via $y_k$ or $s_k$)


What is Cromwell's rule and why is it important for Bayesians?

Question: I have just heard of Cromwell's rule, but I'm not sure I understand it very well. What is Cromwell's rule and why is it important for Bayesian statistics?
Comment: I beseech you, in the bowels of Christ, think it possible that you may be mistaken.
Comment: So that we make the most helpful remarks, which parts are confusing to you after looking at the [Wikipedia article on Cromwell's rule](https://en.wikipedia.org/wiki/Cromwell%27s_rule)? It begins, '_The use of prior probabilities of 1 ("the event will definitely occur") or 0 ("the event will definitely not occur") should be avoided, except when applied to statements that are logically true or false, such as 2+2 equaling 4 or 5._'
Comment: @Lennis Dindley: By the way, I *love* your username (+1 just for that).
Answer: As pointed out by others, this rule derives from the statement by the famous English General Oliver Cromwell, who stated: "I beseech you, in the bowels of Christ, think it possible that you may be mistaken."
Applied to a the context of Bayesian analysis, it recommends generally against assigning a prior probability of zero or one to an unknown event.  In lieu of this, it is recommended that events thought to be highly implausible should be assigned an extremely low probability rather than zero probability.  For a hypothesis $H$ and potential evidence $E$ Bayes' rule says that the (posterior) probability of the hypothesis given observation of that evidence is:
$$\mathbb{P}(H|E) = \frac{\mathbb{P}(E|H) \cdot \mathbb{P}(H)}{\mathbb{P}(E|H) \cdot \mathbb{P}(H) + \mathbb{P}(E|\bar{H}) \cdot \mathbb{P}(\bar{H})}.$$
If $\mathbb{P}(E|\bar{H})>0$ then using the prior probability $\mathbb{P}(H)=0$ gives the posterior probability $\mathbb{P}(H|E) = 0$, regardless of the likelihood ratio $\mathbb{P}(E|H)/\mathbb{P}(E|\bar{H})$.  This is generally seen to be a drawback of this prior stipulation, because it means that you retain the view that the hypothesis has zero probability no matter how high the likelihood ratio gets.
Whilst the rule is a useful suggestion in some contexts, pretty much every Bayesian model restricts its attention to events considered possible within a particular model form and ascribes zero probability to all other events not considered in the analysis.  Moreover, any analysis involving parameters that are treated as continuous variables will necessarily involve events with probability zero on these variables.  Consequently, you cannot take the injunction seriously as a necessary requirement of analysis.  In some instances, you may formulate a model in which a particular event is excluded from consideration and has zero probability (or a continuous outcome has zero probability density).
Here it is worth noting that Bayesian analysis has a "get out of jail free" card in cases where such an event is observed; if we observe an "impossible" event then any posterior belief is valid (see e.g., here).  In the above case, this occurs in the special case where $\mathbb{P}(E|\bar{H})=0$.  In this case the evidence $E$ is regarded as having zero probability unless the hypothesis is true.  In this case a prior stipulation that $\mathbb{P}(H)=0$ is compatible with any posterior probability $\mathbb{P}(H|E)$ between zero and one.
Answer: According to Wikipedia, the rule states that:

the use of prior probabilities of 1 ("the event will definitely occur") or 0 ("the event will definitely not occur") should be avoided, except when applied to statements that are logically true or false, such as 2+2 equaling 4 or 5.

The motivation for the rule is that if you assign a prior probability of 0 to an event $A$, then no amount of evidence $B$ can ever increase that probability to anything greater than 0, because by Bayes' Theorem:
$$
P(A|B) = \frac{P(A \cap B)}{P(B)} = \frac{0}{P(B)} = 0
$$
(You might object that $P(B)$ might also be 0, but that still doesn't provide a way to update your probability of $A$.)
An example: suppose $A$ is the event "man-sized ants will attack on Monday", and your prior probability for $A$ is $P(A) = 0$ because you think this is impossible. Suppose that on Monday you look out of the window and see a lot of man-sized ants attacking people. You still won't be able to assign $A$ a posterior probability greater than 0, so you won't be able to logically justify defending yourself from the ants.


Check if columns have a nan value if certain column has a specific value in Dataframe

Question: I'm trying to add column in Dataframe which has a result of checking if other columns have value in it.
This is a test df I made:
df = pd.DataFrame({"condition":[1,np.nan,np.nan,np.nan,1],"a":[np.nan,4,5,6,np.nan],"b":[np.nan,2,"e",2,np.nan],"c":[3,2,1,2,np.nan]})

So what I want to check is, for each row, if condition column's value is 1, "b","c","d" columns should not have values except np.nan. If "condition" has np.nan, result should be "-".
The ideal result should be something like this:
    condition    a      b      c     check_result
0    1        np.nan  np.nan    3        "X"
1    np.nan      4      2       2        "-"
2    np.nan      5      "e"     1        "-"
3    np.nan      6      2       2        "-"
4    1        np.nan  np.nan    np.nan   "O"

I've tried two ways.
First, this one:
def na_and_check(domain,var_list):
    y = ""
    for var in var_list:
        y += '(np.isnan('+domain+'["'+var+'"]))&'
    y = y[:-1]
    print(y)
    return eval(y)

df["check_result"] = np.where(df["condition"]!=1,"-",np.where(na_and_check("df",["a","b","c"]),"O","X"))

But since "b" columns has string value in it, it gives me this Error:
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

And for the second one, I tried this:
df["check_result"] = np.where(df["condition"]!=1,"-",np.where(df[["a","b","c"]].any(),"X","O"))

I wasn't confident with .any() and yes, it gives me an error:
ValueError: operands could not be broadcast together with shapes (5,) () (3,)

So um... I don't know what to do next.
Any advice or enlightenment, tips will be appreciated. I'll wait for your teach !
Thanks for stopping by. Have a wonderful day.
Answer: so you have an if-elif-else situation. Then we can use np.select for it. It needs the conditions and what to do when they are satisfied:

your if is:      "condition is 1 and a,b,c has all nan"
your elif is: "condition is nan"
what remains is else, as usual

conditions = [df.condition.eq(1) & df[["a", "b", "c"]].isna().all(axis=1),
              df.condition.isna()]

what_to_do = ["O", "-"]
else_case = "X"

df["check_result"] = np.select(conditions, what_to_do, default=else_case)

df

   condition    a    b    c check_result
0        1.0  NaN  NaN  3.0            X
1        NaN  4.0    2  2.0            -
2        NaN  5.0    e  1.0            -
3        NaN  6.0    2  2.0            -
4        1.0  NaN  NaN  NaN            O

So we don't write else's condition. It goes to default.
Comment: Oh, let me try this one. I thought np.where is the only if-elif-else one.
Thanks for trimming condition as well!
Comment: yeah np.where is if-else only, this is generalized kind of. you are welcome


Rule for stopping / starting the clock when running out of bounds with the football in NFL & NCAA

Question: What are the rules and are they the same in NCAA and NFL when it comes to stopping and starting the game clock when a player runs out of bounds with the football.
What I have found out is that according to the NFL Rule Book:

Anytime a player in possession of the ball goes out of bounds, the play clock stops. The clock is restarted once the officials spot the ball at the appropriate yard line on the field, except during the last two minutes of the first half or the last five minutes of the fourth quarter.

Is this correct and would that be the same for NCAA college football?
Answer: As of 2023 (question is now 4 years old), NFL and NCAA rules have been modified and are closer than ever regarding the clock stop after a play. Why was the NFL rule modified? To speed up the game and minimize the waste of time during loooong games (source):

According to the rules, if the player is making forward progress and he goes out of bounds with no member of the defense edging him, then the play is ruled out of bounds. If the defense attacks him and he, on purpose, goes out of bounds, then his forward progress is marked on the field while the clock keeps running.
Every minute in the NFL is crucial, and the rules were made so that no time is wasted, especially during the last minutes of the game. Most of the time, the clock stops once the ball is out of bounds and the game resumes as soon as the referee places the ball on the ground.

You can watch an official video provided by the NFL about "rule 4 - section 6".
The NCAA article "Fewer clock stoppages on first downs and more 2023 college football rule changes" explains this new rule in order to maximize play time:

Why is this important?
Originally, the game clock was stopped when a team gained a first down and the clock would resume when a referee placed a marker on the field and the team was awarded the first down. With this new rule change, for coaches, it is important to maximize each play, without the usage of possibly calling a time-out, and think of ways to score on each drive.

Excerpt from "Why Does The Clock Run After Out Of Bounds In College Football" of Game Day:

Typically, during both college football games and NFL games, the clock will stop until the next snap in the game whenever there is an incomplete pass, the team is timed out, or the play ends with a score. But, there are instances in which the clock is stopped while or after a player is out of bounds.
The moments in which the clock will stop while a player is running out of bounds only occur during college games whenever there are under 2 minutes left in the first or second half of the game. The clock will stay stopped for that out-of-bounds runner until the next snap is issued.

This is also explained in other news reports, such as Sporting News:

Running clock after first downs except for the last two minutes of each half
This is like the NFL with the exception of the final two minutes. It also is the most drastic change to the game. Previously, officials would stop the clock after each first down. ("College football's new clock rules for 2023, explained: 3 changes aim to shorten games")

NCAA 2023 Rules Book -- NFL Rules Book
Answer: College has no two minute warning.
College clock doesn't stop on out of bounds in the last 2 minutes/5 minutes.
College clock does stop briefly to move the chains on first downs.
Comment: Citing the actual rules would help a lot here.


yum - install package forcing replacing files

Question: I want to install one package with yum and not using rpm but with the same behavior like --replacefiles in rpm. I have one package that have file conflicts with other and I need to install forcing with yum. This package is mine, so I can modify spec file.
Answer: You can use trigger scriptlets for this.
For illustration, let's say that the file /etc/contested is owned by a rpm named generally, and you have another package (specifically) which wants to force-overwrite the same file.
In specifically.spec, you install the new version of the file to %{_datadir}/%{name}/etc.contested, and use this trigger scriptlet to install it to /etc:

%triggerin -- generally
install -m 0644 %{_datadir}/%{name}/etc.contested %{_sysconfdir}/contested

The scriptlet will be run every time that generally is installed or updated, as well as every time specifically is installed or updated.
RPM will still notice that the file isn't as it's expected to be, but it won't stop you from installing or uninstalling.
Comment: Thanks you very much. You helped me to fix 5 year long standing issue. Now I am no longer afraid of **yum update -y**
Answer: If you can modify spec file maybe you can remove the files that conflict in the files section ?
Do you specify a folder in that section ? or file by file ?
Comment: But, this files are dependencies with other package, can one repo delete files that use other repo with yum?
Comment: I don't get you this time.
Why do you speak of repo ? This has no link with the package itself.
From what I understood you have at least 2 packages already installed that are "owning" at least a common file.
One of these 2 packages is already installed and you want to install the second one, which fails because the file is already owned by another package. But you can modify that last package.
In that case modify the spec file of that last package before you install and remove the conflicting file from the file section.
Comment: I need to overwrite the file, I can remove the conflict, I need to make effective the sustitution
Comment: Ah okay this wasn't clear, sorry for the bad answer then, I didn't get you right.
It seems there is no way with yum.


Understanding the theorem about the almost disjoint sets partial order

Question: I have read the Kunen's set theory. But I get a struck to understand the proof of a theorem.

Let $\mathcal{A}\subset\mathcal{P}(\omega)$ be a family of pairwise almost disjoint sets, then we define $(\Bbb{P}_\mathcal{A},\le)$ as $\Bbb{P}_\mathcal{A}=\{\langle s,F\rangle : s\in [\omega]^{<\omega},\,F\in[\mathcal{A}]^{<\omega}\}$ and $\langle s,F\rangle \le \langle s',F'\rangle$  iff $s\subset s'$, $F\subset F'$ and $x\cap s'\subset s$ for each $x\in F$.

Lemma 2.8. In $\Bbb{P}_\mathcal{A}$, $\langle s,F\rangle$ and $\langle s',F'\rangle$ are compatible iff $x\cap s'\subset s$ for all $x\in F$ and $x\cap s\subset s'$ for all $x\in F'$.

Lemma 2.10. If $G$ is a filter in $\Bbb{P}_\mathcal{A}$ and $\langle s,F\rangle \in G$ then $x\cap d_G\subset s$ for each $x\in F$
(Where $d_G:=\bigcup\{s\mid\exists F:\langle s,F\rangle \in G\}$.)
Proof. If $\langle s',F'\rangle\in G$ then $\langle s',F'\rangle$ and $\langle s,F\rangle$ are compatible, so by Lemma 2.8, $x\cap s'\subset s$ for all $x\in F$.

I don't understand the proof of Lemma 2.10. Especially, I don't understand $\langle s',F'\rangle\in G$ implies the compatibility of $\langle s,F\rangle$ and $\langle s',F'\rangle$.  In this book there is no proofs of this statement (as I know) and I don't know how to prove this statement. Thanks for any help.
Answer: Given $x \in F$, note that for any $\langle s^\prime , F^\prime \rangle \in G$ we have that $\langle s^\prime , F^\prime \rangle , \langle s , F \rangle$ are compatible -- since $G$ is a filter and $\langle s , F \rangle$ also belongs to $G$ -- so by Lemma 2.8 it follows that $x \cap s^\prime \subseteq s$.
It then follows that $x \cap d_G = x \cap \bigcup_{\langle s^\prime , F^\prime \rangle \in G} s^\prime = \bigcup_{\langle s^\prime , F^\prime \rangle \in G} ( x \cap s^\prime ) \subseteq s$.

Recall that given a poset $\langle \mathcal{P} , \preceq \rangle$, a (nonempty) subset $F \subseteq \mathcal{P}$ is a filter if

whenever $p,q \in \mathcal{P}$ and $p \preceq q$, then $p \in F$ implies $q \in F$;
whenever $p,q \in F$, then $p,q$ there is an $r \in F$ with $r \preceq p , q$.

This second condition implies that every two elements of a filter are compatible as elements of the poset.


What's the practical meaning of alpha in a GLM with gamma family?

Question: I am fitting several models of the form..
<code>glm(DV ~ I(1/IV), family = Gamma(link = "log"))
</code>
.. and am looking for ways to compare the models obtained for different variables. I am wondering if the alpha value is of any practical use?
For the three plots below the alpha values are 17.85, 9.03 and 6.27. Do these values contain any information that helps me to interpret my data, or to compare the different variables?
Comment: I've bee assuming by alpha that you mean the shape parameter of the gamma; can you clarify whether you mean that or something else (such as the intercept in your model for the mean)
Comment: yes, I meant the shape parameter!
Answer: The values of the alpha-parameter of the gamma describe the shape of the distribution at any given value of IV (essentially giving an idea how skewed the conditional distribution is -- the smaller $\alpha$ is, the more skew)
In a GLM, it doesn't change the mean ...

... so it has no impact on the fitted curves in your plots; it only describes the shape of the distribution about the mean (well, it does relate to the spread but has no impact on relative weight).
The steepness of the descent of the curves in your plots is determined by the coefficient of your IV. You might find it instructive to look at your plots (of the data and the fitted model) on the log scale.
Comment: Yes, I get that, but what can I infer? E.g., is it valid to say that the higher the value the steeper the decline of y values for low x values? Or, that for small alpha values there is a less abrupt turning point between high y/low x and low y/high x?
Comment: See my edit above...
Answer: The gamma distribution can be expressed as a distribution from the exponential dispersion family and the $\alpha$ parameter works like the inverse of the dispersion parameter.
$$f(x;\theta, \phi) = h(\phi,x) \exp\left(\frac{\theta x - A(\theta)}{\phi}\right)$$
with $\phi = 1/\alpha$, $\theta = -\beta/\alpha$, $A(\theta) = -\log \theta$, $h(\phi,x) =1/\Gamma (1/\phi) x^{1/\phi-1} (1/\phi)^{1/\phi}$
The mean is
$$E[X] = A'(\theta) = -1/\theta = \alpha/\beta$$
and the variance is
$$Var[X] = \phi A''(\theta) = \phi/\theta^2 = \alpha/\beta^2$$
And $Var[X] = E[X]^2/\alpha$