Help Finding Orthonormal Frame and Coframe Based on First Fundamental Form

Question: Given the metric (for $x^2<1$)
$g=dx^2+2x dxdy+dy^2$ (in first fundamental form)
I'm trying to find the orthonormal frame and its coframe
I have found (I think) the orthonormal frame to be
$e_1=\frac{\partial}{\partial x},e_2=\frac{\frac{\partial}{\partial y}-x\frac{\partial}{\partial x}}{\sqrt{1-x^2}}$
And I think the coframe is $e^1=dx,e^2=\sqrt{1-x^2}dy$, and each works for $e^ie_j=\delta^i_j$ except for the case $e^1e_2$ so I'm wondering if my orthogonal frame is right, and if so what am I missing to get the coframe
Comment: If $e_2$ contains both $\partial_x$ and $\partial_y$, then $e^2$ has to contain both $dx$ and $dy$...
Comment: So what would it be then? My main problem is how to construct $e^1$ since that's really the only thing it could be given my orthonormal frame. Is my Orthonormal frame wrong then?
Answer: This is too long for a comment and I would like to leave the OP with a chance to iron out some of the details . . .
Given any non-zero vector field $e_{1}$, one can always apply the Gram-Schmidt Process to extend it to an orthonormal frame on its domain of definition.
Now, if you have a purported orthonormal frame and you want to verify this, you simply want to very that $g(e_i, e_j) = \delta_{ij}$.  Based on the question above, it appears that you realize this.
In this case, it perhaps easiest to identify the metric $g$ with the matrix $\begin{pmatrix} 1 & x \\ x &1\end{pmatrix}$ and realizing that for any two vectors $\vec{u}, \vec{v}$, one has
$$
g(\vec{u}, \vec{v}) = \vec{u}^{t} \begin{pmatrix} 1 & x \\ x & 1\end{pmatrix} \vec{v},
$$
where we are identifying our vectors as column vectors with respect to the coordinate frame $\frac{\partial}{\partial x}$ and $\frac{\partial}{\partial y}$ and $\vec{u}^{t}$ denotes the transpose of the vector $\vec{u}$.
In this case, one has $e_{1} = \begin{pmatrix} 1 \\ 0\end{pmatrix}$ and $e_{2} = \begin{pmatrix} -\frac{x}{\sqrt{1 - x^2}}\\ \frac{1}{\sqrt{1 - x^2}}\end{pmatrix}$.
In regards to the purported  orthonormal frame from the question, one should be able to check quickly and see that it is indeed an orthonormal frame.
Finally, concerning the matter of the coframe, this is mostly a matter of (point-wise) linear algebra and understanding how the change in the frame results in a corresponding change in the coframe.
In general, any two frames are related by an invertible matrix $A$ and you would like to know what the corresponding relationship between their respective coframes is.
In this instance, you have $\begin{pmatrix} e_{1} & e_{2} \end{pmatrix} = \begin{pmatrix} \frac{\partial}{\partial x} & \frac{\partial}{\partial y} \end{pmatrix} A$, where $A = \begin{pmatrix} 1 & \frac{-x}{\sqrt{1 - x^2}}\\ 0 & \frac{1}{\sqrt{1 - x^2}}\end{pmatrix}$.  Note that this also gives
$$
\begin{pmatrix} e_1 & e_2 \end{pmatrix} A^{-1}  = \begin{pmatrix} \frac{\partial}{\partial x} & \frac{\partial}{\partial y} \end{pmatrix}.
$$
Your corresponding coframe $e^{1}, e^{2}$ can be expressed in terms of the coframe $dx, dy$ that is dual to the frame $\frac{\partial}{\partial x}, \frac{\partial}{\partial y}$ as
\begin{align}
e^{1} &= \alpha dx + \beta dy\\
e^{2} &= \gamma dx + \delta dy,\\
\end{align}
or $\begin{pmatrix} e_1 \\ e_2 \end{pmatrix} = B \begin{pmatrix} dx \\ dy \end{pmatrix}$, where $B = \begin{pmatrix} \alpha & \beta \\ \gamma & \delta\\\end{pmatrix}$ and $\alpha, \beta, \gamma, \delta$ are functions on the surface.
Charged with the task of identifying the components of the matrix $B$, one can simply evaluate the one forms $e^{1}$ and $e^{2}$ on the vectors of the original frame: $\frac{\partial}{\partial x}$ and $\frac{\partial}{\partial y}$, where you will want to make use of the fact that you know $\frac{\partial}{\partial x}$ and ${\partial}{\partial y}$ in terms of $e_{1}$ and $e_{2}$ via the relationship $\begin{pmatrix} e_1 & e_2 \end{pmatrix} A^{-1}  = \begin{pmatrix} \frac{\partial}{\partial x} & \frac{\partial}{\partial y} \end{pmatrix}$
For example, when one evaluates $e^{1} = \alpha dx + \beta dy$ on the vector $\frac{\partial}{\partial x}$, one will find that  $e^{1}\left(\frac{\partial}{\partial x}\right) = \alpha$ and that by expressing $\frac{\partial}{\partial x}$ in terms of the frame $e_1$ and $e_2$, one can express $\alpha$ in terms of the components of the matrix $A$ (or $A^{-1}$).
Paying attention to the individual computations, you will see that one is able to learn how to automatically change the coframe by using the same matrix (with the appropriate adjustments) that were used in the change of frame.
This ended up being a longer answer than I intended, but I hope that you find it helpful.


Override function in non derived c# class

Question: I have the following class
public class classB : classA

which contains function dostuff
Now I have a class SUPER, which has an instance of B amongst its variables
classB SUPER_B;

and that has a 'redefinition' of 'dostuff' amongst its methods.
Basically, what I need is that when classB calls 'dostuff', it does not call its internal dostuff, but SUPER's dostuff implementation instead.
Substantially, I would need that, on SUPER's initialization, classB's 'dostuff' be replaced with SUPER's dostuff.
It'd sort of make sense if there was a way to retrieve B's 'dostuff''s reference, but I don't know how to achieve that.
I've looked into virtual and Func, but they seem to require that SUPER be a derivate of B
Comment: Please post the full code of the implementations of `dostuff` as defined on `classB` and `classA`, so we understand exactly what you are doing.
Comment: You've got some great suggestions here but that's as close as anyone can come without seeing some code or at least a statement of what your design motivation is.
Comment: Thanks all for the extraordinary support and suggestions. Posting code is troublesome since the class names I'm using are abstractions of multi page real classes. What I am eventually trying to achieve is what @dasblinkenlight suggested: "replacing a function with another function", through the settable delegate, I didn't know the methodology nor definition, so I was unable to search for that differently.
Answer: You cannot force a method change upon a class from the outside. There are ways to achieve functionality like that when either (1) classB is designed in such a way as to support replacing its methods, e.g. though a settable delegate, or (2) if classB implements an interface, which you can implement, wrap classB inside it, and replace a method.
Example #1 - settable delegate:
class ClassB {
    public Action<int> dostuff {get;set;}
    public ClassB() {
        dostuff = myDoStuff;
    }
    void myDoStuff(int n) {
    }
}

class Program {
    public static void Main() {
        var myB = new ClassB();
        myB.dostuff = myOverride;
    }
    void myOverride(int n) {
    }
}

Example #2 - interfaces.
interface IClassB {
    void dostuff(int n);
    void dosomething();
}
class ClassB : IClassB {
    void dostuff(int n) {
    }
    void dosomething() {
    }
}
class Program {
    public static void Main() {
        var bb = new Override(new ClassB());
    }
    class Override : IClassB {
        private readonly IClassB inner;
        public Override(IClassB inner) {
            this.inner = inner;
        }
        void dostuff(int n) {
            // do not call inner.dostuff
        }
        void dosomething() {
            inner.dosomething();
        }
    }
}

Answer: It sounds like you need to use decorator pattern: class SUPER has an instance of classB and uses it's methods. SUPER decorates all necessary methods of classB, and adds some new. For example:
public class SUPER {
  private classB SUPER_B = new classB();
  public void foo()  {
     SUPER_B.foo();
  }
  public void bar()  {
     SUPER_B.bar();
  }
  ...
  public void dostuff()
  {
       // don't call SUPER_B.bar(), but write your implementation
  }
}

Comment: @Dexter: OP says an instance of `classB` is a member of `SUPER`. I suppose that inheritance is not an option in his case. Otherwise, there is no question, since derived class can always overwrite non-sealed method.
Comment: In this case, why not just inherit classB?
Comment: @Dexter: cause you in this case enable access to ALL public/protected members of classB, which may be OP doesm't want. Cause this could be substantial change in your program architecture. Cause, may be, you can not as class is sealed....
Comment: This is actually one very good solution, too. Regarding prerequisites, a1ex07's intuitions are correct.
Answer: You can't do that easily.
Instead you should design your classB for extensibility, such as add events to classB which you can handle in your SUPER class.


Split Simulated dataset into train and test dataset?

Question: I am working on my thesis, and I wonder how the paradigm with splitting your dataset into training and test dataset works for simulated data.

Does it make sense to split a dataset that is simulated into train and test?

My thoughts:
The datasets simulated are very controlled in the sense, that the data that are simulated is within a given range, hence the test set will look like the training set. Then you loose the natural variability in data taken from observations in nature. The simulation approach taken is simulatation with Halton sequence and then apply a transformation to get samples within the ranges.
Hope someone can clarify.
Answer: Whether a simulation with cross-validation makes sense, very much depends on what your goal is.
Generally, simulating data is a highly recommended step in order to understand and test the behavior of a model under controlled settings. And if you do so, you should try to exactly replicate the analytic framework which you intend to apply to your real data. If it involves cross-validation (e.g. because you care about the generalizability of your model), then you should apply cross-validation to your simulated data as well.
In most cases, simulated data will be more well-behaved than real-world data, e.g. with respect to extreme outliers. So yes, you might overestimate the performance of your model and you should keep that in mind.
For the simulation, try to investigate the properties of your real data as good as possible. That is: which distributions can describe your features? What are the characteristics of the parameters that describe these distributions? (e.g., the range of means and SDs in case you assume normal distributions). Is there a correlation structure between features?
Try to reproduce these characteristics as closely as possible. But again, how much work you may put into this depends on the goal of your simulation. Your goal may simply be a sanity check - show that your model predicts well if you include features that are correlated to your target variable; or show that the model predicts at chance level if you only feed it with noise - in which case a simple procedure for simulated data generation will suffice most of the time. By contrast, if the goal of your simulation is e.g. to compare different models given the specific properties of your data, then you will have to try to reproduce these properties as precisely as possible to draw meaningful conclusions.


problem of proving one member of union is sigma-algebra

Question: Suppose $\mathscr{A}$ is $\sigma$-algebra. Let $A\in\mathscr{A}$. If $B\cup A\in \mathscr{A}$, is $B\in \mathscr{A}$? Can someone give hint?
Comment: Hint: Is there an unmeasurable subset of $[0,2]$? (Lebesgue)
Comment: @MikeBrown The hint Moya gave was to consider $A=[0,2]$ and have $B\subset A$.  Then $A\cup B = A$ is an element of the borel sigma algebra, satisfying your *if* portion of the statement.  Try to think about what $B$ can be.  Are there any particularly strange sets you've seen?
Comment: I did not get your meaning.
Answer: My hint was a little bit more advanced for beginning measure theory, so here's a trivial example. Let $\mathcal{A}=\{\emptyset, X\}$ for some $X$ nonempty. You can show that this defines a sigma algebra. Then $X$ nonempty means there is $x\in X$, so $\{x\}\subset X$. Then $\{x\}\cup X=X$ but $\{x\}\not\in \mathcal{A}$
Edit: Yes, you need to assume $|X|\geq 2$, or else $X=\{x\}$ and the result does hold.
Now, for my comment. This is going to be based on Chapter 1 of Folland's Real Analysis, but you can also read about it here, it's called the Vitali Set.
Here's the basic idea: We have a $\sigma-$algebra on $\mathbb{R}$ which is generated by open intervals (unions, intersections, complements) called the Borel $\sigma-$algebra. Now, to every interval, we associate a natural size $m((a,b))=b-a$, and we want to extend this so that points $m(\{x\})=0$ and $m(\bigsqcup_n U_n)=\sum_nm(U_n)$, where this union is disjoint (this is an intuitive description of Lebesgue measure). From topology, every open set is a countable disjoint union of open intervals, and a little more work can show then that every element of our Borel $\sigma-$algebra has a well defined size (possibly infinite). We're also going to want translational invariance $m(r+U)=m(U)$ for $r$ real and if $U\subset V$, then $m(U)\leq m(V)$
If we agree on this, we proceed. We're going to construct a terrible subset of $[-1,2]$. Define an equivalence relation on $(0,1)$ by $x\sim y\iff x-y\in\mathbb{Q}$. Now consider $(0,1)/\sim$, the equivalence classes, and for each one pick an element from each class, and put them all into a set $N\subset (0,1)$. Now, enumerate the rationals $r_n=\mathbb{Q}\cap [-1,1]$ and consider the sets $N_n=N+r_n$ and take the union $\mathcal{N}=\bigsqcup N_n$. I leave it to you to check the union is disjoint. You also need to check that we have $[0,1]\subset \mathcal{N}\subset [-1,2]$.
Now here's where things start to break down. $m([0,1])=1$, $m([-1,2])=3$. Then $$1\leq m(\mathcal{N})\leq 3\Rightarrow 1\leq \sum_n m(N_n)\leq 3\Rightarrow 1\leq m(N)\sum_n\leq 3$$Now we're in trouble. The sum doesn't converge so we need $m(N)=0$, but this implies $1\leq 0$. If $m(N)>0$, then $\infty\leq 3$. Both are impossible, so $m(N)$ must not exist. But we agreed above that every element of our $\sigma-$algebra has a size. So $N$ cannot be a member of this. But $N\subset (0,1)$, so $N\cup (0,1)=(0,1)$ is a member of the set.
Edit 2: I did a fairly standard construction of the Vitali set, but it relies heavily on the idea of Lebesgue measure and accepting certain things as fact. Here's an example of a non-Borel set due to Lusin using continued fractions.
Comment: You need to add the condition that $|X|\geq 2$, it doesn't work for $X=\{x\}$.
Comment: Maybe insert your comment with the answer too? It certainly was a great comment.
Answer: Hint: Suppose it were true. Then it would be true whenever $B \subset A$. Is every subset of a set in a $\sigma$-algebra also contained in the $\sigma$-algebra. You should be able to choose appropriate $A$ and $\sigma$-algebra to figure this out.


Building test environment inside Hyper-V - Adding machines into a Domain

Question: I am currently building a test environment with 4 servers inside Hyper-V.
One of the servers is a Domain Controller, the other servers will be a member of that domain.
All machines are on an internal hyper-V network, I have then set up the wireless network adapter on the host machine to allow the internal network to share this connection. This works fine and the machines can access the internet.
All machines have dynamic IP Addresses.
Now comes the problem: How do I get all the machines into the domain? Do I need to use static IP Addresses? Do I need to manually add them to the DNS? I will be setting up 2 of the machines in a NLB cluster will I need static ip addresses for that?
Edit
The ip address was being supplied by the DHCP allocator in the Internet Connection Sharing component of the wireless adapter.
Answer: You should set the Domain Controller to have a static IP and act as internal DHCP with itself as DNS, then the other computers use DNS to find the domain controller.
Now, the trick is: This is TOTALLY unrelated to Hyper-V. The absolutely same would apply to real machines. Please think your headlines through a little more.
Comment: Thanks for your answer. Currently it appears that Hyper-V is acting as a DHCP server. If one of the servers inside Hyper-V also has the DHCP role, will there be a conflict?
Comment: Hyper-V does NEVER act as a DHCP server. It does nto care about your network. If someone isntalled a DHCP server on the physical machine, that is not hyper-v acting as dhcp, but the dhcp server someone installed. Naturally thy will interfere. At this piont I would suggest reading the documentation how DHCP and DNS and Domains interact. You can also hardocde the static IP of the DC into the clients so they find the domain, or use forwarders in whatever dns they point to.
Comment: All the machines on the internal Hyper-V network are getting a 192 address, the host machine is on a 10 network. DNS, DHCP and default gateway are all set to 192.x.x.1
Comment: So do your job and find out why they get 192.* addresses. Some may be no addrese, autoconfigured due to missing DHCP. Sadly as you consider that confidentail I can not say....
Comment: Autoconfig should show up as a 169.254.*.* so they are getting it from somewhere else.  Double check with ipconfig /all, you may have more than one adapter, my own network we have VPNs on 10 and internal on 192.168 and a computer could hold on to address from both.


What does "tail" mean in probability distribution? And what do we mean by heavy or light tail?

Question: I have seen this word so many times while studying the probability distributions, till I should probably want to know exactly what it means, to boost my understanding of probability concepts.
Answer: You can find the relevant definitions
here
In essence, a distribution is called heavy-tailed if the tail probability $P[X > x]$ decreases slower then exponentially. Formally :
$\lim_{x\to\infty} e^{tx} P[X>x] = \infty $ for all $t>0$


Identificar item selecionado ListView

Question: Tenho um ListView que carrega valores do meu banco de dados.
Gostaria de saber como faço para identificar o item selecionado para que eu possa recuperar o valor do campo CODIGO_PRODUTO e fazer um UPDATE/DELETE no banco de dados.

Lembrando que minha ListView tem a opção de selecionar múltiplas linhas, basicamente preciso recuperar os CODIGO_PRODUTO de todas as linhas selecionadas para aplicar o DELETE.

private DataSet _dataSet;
private SqlDataAdapter _dataAdapterProducts;

public void getDados()
{
    SqlConnection conn = new SqlConnection(strConnection);
    string strSql = "SELECT * FROM PRODUTOS";
    conn.Open();
    try
    {
        _dataSet = new DataSet();
        _dataAdapterProducts = new SqlDataAdapter(strSql, conn);
        _dataAdapterProducts.Fill(_dataSet, "PRODUTOS");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Erro: " + ex.Message.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void carregaLista()
{
    getDados();

    DataTable dtable = _dataSet.Tables["PRODUTOS"];
    lvEstoque.Items.Clear();
    for(int i = 0; i < dtable.Rows.Count; i++)
    {
        DataRow drow = dtable.Rows[i];
        if(drow.RowState != DataRowState.Deleted)
        {
            ListViewItem lvItem = new ListViewItem(drow["CODIGO_PRODUTO"].ToString());
            lvItem.SubItems.Add(drow["DESCRICAO"].ToString());
            lvItem.SubItems.Add(drow["QUANTIDADE"].ToString());
            lvItem.SubItems.Add(drow["VALOR_INICIAL"].ToString());
            lvItem.SubItems.Add(drow["VALOR_FINAL"].ToString());
            lvItem.SubItems.Add(drow["LUCRO"].ToString());
            lvEstoque.Items.Add(lvItem);
        }
    }
}

Comment: você tem que usar os eventos `SelectedIndexChanged` ou `ItemSelectionChanged`
Comment: Vamos supor que tenho 10 produtos cadastrados, com Código de Produto do 1 ao 10, clico no produto de Código 5, como eu recupero esse valor 5? Poderia montar um bloco de código para eu ter base?
Answer: Você pode usar o SelectedIndexChanged. Exemplo:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count > 0)
    {
        MessageBox.Show("Código do produto escolhido: " + listView1.SelectedItems[0].SubItems[0].Text);
    }
}

Mas, recomendo que utilize um DataGridView para esse propósito, e utilize também um BindingList<> para popular o mesmo. Irá simplificar seu trabalho.

Identificar item selecionado ListView


3 calendars views

Question: I'm just starting to learn Views and there is quite a lot for me to study, so I have to ask you. I am working on D7.7.x, using Calendar and Views modules.
What I want to create is this: I have an event that will be happening in 3 different cites during the period of one month but during different dates. Each city has a list of events generated as separate nodes for different days. I need only one month and it should be shown permanently - even during the month of August I should see the month of December with particular days linking to agendas. And there are 3 such calendars with the same month but different days active - the user can switch the city and the calendar will change.
What would be the easiest way to do this? Maybe even not with Calendar module?
Comment: Thanks for the accept.  Found a new site that has almost all Drupal tutorials on it.  Tutr.tv  It has nodeone.se on it and a lot of DrupalCon videos.
Answer: To learn more about Views check out these tutorials http://nodeone.se/blogg/learn-views-screencast-series-summed-up.
If you just have a new content type (Event) (that has a date field) you can Filter Criteria by Content: Type (= Event), and Sort Criteria by Event Date Descending.  You can add a Display of Type Block, Pane, etc to suit your needs then.  The calendar is possible, but I would advise you to get just a basic view working before trying to integrate the Calendar Mod with it.
There are numerous different options that are available and the best thing would be to watch the tutorials.  Each lesson is ~10 minutes long, but cover one thing really well.
Answer: Your requirements can be met using Views itself. Views is one of the most powerful parts of Drupal and once mastered so much can be achieved. So time spent here is very worthy indeed.
Comment: Maybe you could give a hint from where to start? Or maybe there is some kind of Views screencast regarding this particular issue? Just to get on track, as views module is so complex to me at this moment ...
Comment: This site has a good resource of videos http://drupalize.me/ as well as the popular http://mustardseedmedia.com/podcast.
Comment: There is also http://www.lynda.com/ all of which I have used in the past to accelerate knowledge of Drupal.

3 calendars views


Given $\Lambda\sim\mathtt{Pois}\left(\lambda\right)$ and a stochastic process $X\left(t\right)=\Lambda\cos 2\pi t.$ Seek trend and covariance function

Question:
Problem. Given $\Lambda\sim\mathtt{Pois}\left ( \lambda \right )$ and the stochastic process ${\it X}\left ( t \right )= \Lambda\cos 2\pi t.$ Seek the trend function and the covariance function of ${\it X}\left ( t \right )\!.$

Based on an old topic, I know the way to deal with it except the verification of equivalence $\mathbb{E}\left [ {\it X}\left ( t \right ) \right ]= \mathbb{E}\left [ \Lambda \right ]\mathbb{E}\left [ \cos 2\pi t \right ]{\it ?}$ I'm also a bit confused about what would covariance function work in this strange (to me) stochastic process. How simple is and I was forced to be doubtful. So I need your help.
Answer: $\cos (2\pi t)$ is not random. So $EX(t)=\cos (2\pi t) E\Lambda$ and $Var (X(t))=(\cos (2\pi t))^{2} Var \Lambda$. Also, $Cov (X(t),X(s))=\cos (2\pi t) \cos (2\pi s) Var (\lambda)$


Holding down a button in SpriteKit's GCVirtualController

Question: I am brand new to XCode, SpriteKit, and Swift in general. I am trying to develop a simple mobile game where the player can shoot fireballs using the A button of the GCVirtualController. I want one fireball to shoot when the user taps the button and multiple fireballs to steadily shoot when the player holds the button.
The issue I'm having is figuring out how to distinguish a tap from a hold. Touching the button at all causes a ton of sprites to spawn instantly as if there's no way to just shoot once. Currently I am checking if the user presses the A button within the update function since I couldn't figure out how to make it work within a touchesBegan or touchesEnded function.
Below is update and the function shootFireball which creates and moves the fireball. I know the if statement in shootFireball is stupid, but I was messing around for a while for any way to just get one fireball to spawn and shoot at a time.
Any guidance is greatly appreciated.
override func update(_ currentTime: TimeInterval) {

        // Joystick Movement //
        playPosX = CGFloat((virtualController?.controller?.extendedGamepad?.leftThumbstick.xAxis.value)!)
        playPosY = CGFloat((virtualController?.controller?.extendedGamepad?.leftThumbstick.yAxis.value)!)

        if playPosX >= 0.5 {
            player.position.x += 3
        }
        if playPosX <= -0.5 {
            player.position.x -= 3
        }

        if playPosY >= 0.5 {
            player.position.y += 3
        }
        if playPosY <= -0.5 {
            player.position.y -= 3
        }

        //  Basic Attack: A Button  //
        let aPress = virtualController?.controller?.extendedGamepad?.buttonA.isPressed

        // Check if the A button is being pressed
        if(aPress == true){
            // Temporary value. Want to get the direction of fireball from the joystick's positioning
            let direct = CGVectorMake(player.position.x, player.position.x)

            // Call method to create and shoot fireball
            let fireBullet = SKAction.run(){
                self.shootFireball(direction: direct)
            }

            // Small delay before firing another fireball
            let wait = SKAction.wait(forDuration: 1.5)

            // Execute the attack
            let fire = SKAction.sequence([fireBullet, wait])
            run(fire)

        }
}

// Create and shoot fireball
func shootFireball(direction: CGVector) {
        let fireball = SKSpriteNode(imageNamed: "fireball.png")
        fireball.setScale(0.8)
        fireball.position = player.position
        fireball.zPosition = 1
        let waits = SKAction.wait(forDuration: 2.5)

        // Lazy validation
        if(self.children.count == 1){

            // Add fireball node
            addChild(fireball)

            let moveFireball = SKAction.move(by: direction, duration: 1)
            let deleteFireball = SKAction.removeFromParent()

            let fireballSequence = SKAction.sequence([moveFireball, deleteFireball])
            fireball.run(fireballSequence)
        }

}

Answer: Just a premise, I've never used GCVirtualController as I prefer to code my own joystick, plus I'm also still learning Swift, so this is a solution, it might not be the best one though.
The issue you are facing is because the update method is called once per frame, so usually 60 times per second unless you changed the preferredFramesPerSecond property. This means that, if the A button is pressed, you are trying to shoot a lot of fireballs.
A way to achieve what you want is to create an action which repeats itself forever, run it one time and keep track if the action is already running to avoid multiple shootings (a behaviour that would usually lead to your app crashing). Then you can stop the action from running by using removeAction once the user lift his finger from the button.
Here is a simplified version of your code, isPressed is equal to virtualController?.controller?.extendedGamepad?.buttonA.isPressed in your code, while isShooting is the boolean you can use to track if the infinite-shooting action is already running or not. You should declare var isShooting = false at first.
I tested this and it works as you intended.
override func update(_ currentTime: TimeInterval) {

    // i think it's a good practice to call super
    super.update(currentTime)

    // moving player, etc...

    if isPressed, !isShooting {
        // user just pressed A but fireballs are not being shot, then setup fireball shooting

        // you set it to true, so that this block is not run again when update is called at the next frame
        isShooting = true

        let fireBullet = SKAction.run {
            self.shootFireball()
        }
        let wait = SKAction.wait(forDuration: 1.5)
        let fire = SKAction.sequence([fireBullet, wait])

        // you set up a single fire action to repeat itself forever, then you will remove this action once the user stops pressing A
        let fireForever = SKAction.repeatForever(fire)
        run(fireForever, withKey: "fireForever")

    } else if !isPressed, isShooting {
        // you just stop the fire when the user lift his finger from the button
        removeAction(forKey: "fireForever")
        // set the tracker variable to false
        isShooting = false
    } else if isPressed, isShooting {
        // user is pressing A, fireballs are being shot, do nothing
    } else if !isPressed, !isShooting {
        // user is not pressing A, fireballs are not being shot, do nothing
    }
}

The last two cases are there just to let you understand what happens in all 4 of them.
Another approach which does not involve CGVirtualController is to code your own A button, and, resorting to UIKit, using UILongPressGestureRecognizer and UITapGestureRecognizer. In this way you can handle the two different cases separately.


The cardinality of all the infinite binary sequences that don't contain 010

Question:
Find the cardinality of all the infinite binary sequences that don't contain 010

I think it's $\aleph_0$.
I marked the set all infinite binary sequences that don't contain 010 in A, and the set of All the infinite binary sequences that don't contain 01 in B. $B\subseteq A$, and $|B|=\aleph_0$, therefore $\aleph_o\le|A|$. But I don't know how to show that $|A|\le\aleph_o$ .
Thanks
Comment: Consider the set C all sequences made up of 11 and 00. Such sequences cannot contain 010. What do you think its cardinality is?
Answer: This is not $\aleph_0$, but rather $2^{\aleph_0}$, as it contains all 0-1 sequences of the form
\begin{equation}
  x_1x_1x_2x_2x_3x_3x_4x_4\ldots
\end{equation}
where $x_i\in\{0,1\}$.
Comment: I don't know of any standard meaning for $\aleph$. What does it mean here?
Comment: I apologize, I have meant the cardinality of the continuum: $2^{\aleph_0}$.
Answer: There is a bijection from the set of all binary sequences to the set of all sequences not containing 010: just replace all occurrences of 01 with 011. And the cardinality of the set of all binary sequences is...?


Database Paging in Android

Question: I want to get the data from a JSON URL. It contains 22 fields and it has above 6000 rows. I want to parse this JSON data and store it in an SQLite database.
I know the basics of JSON but when I use it I get an "out of memory" error.
After a lots of R&D and googling I found that I have to use GSON for Heavy URL, but I'm not familiar with it.
Can I implement paging in JSON? In other words, can I do something like getting partial data from JSON and storing it into a database and then request certain data and store it into a database, continuing the process until the full JSON file is parsed?
Answer: You must implement pagination mechanism on server side (the one, that serves you JSON data) and pass range parameters as part of the URL you mentioned.
Comment: You can go the hard way and receive JSON data as ordinary string, and then compose proper-sized JSON objects yourself, but is it worth it?
Comment: ok. can I implement the structure that "get partial data from json and store into db then get agin partial data."
Comment: Yes, this is what I said exactly. But you must do it on **server** side, not client. But it's not "structure", it's piece of code basically.
Comment: But the same URL works fine on iPhone. I dont know how ? but its not the question. My question is what should I do from Andorid side
Comment: Means there is no method or way to handle situation form Android side
Answer: If I knew I was going to have lot of rows/data, then I would run some simple SQL call to determine the size of the data. Then break up the original JSON within Android to deal with the data in smaller chunks, committing after each segment. So in your example, you know that you have 6000+ rows - store that in memory in Android as an int, then call 1000 rows at a time.
Some code after further queries:
<code>    String locationCountPath = "http://mywebserver/countAllMD5UserLocations";
    try {
        //My method to return a count of locations
        int locCount = MyJSONUtilities.countAllUsersLocations(
                locationCountPath, MyJSONUtilities.writeUserDetailsJSON(
                        username.toUpperCase(), password));
        // Compare new count with count on phone
        if (countLocs != locCount && locCount > 0) {
            try {
                // Grab the new set of locations
                askToSyncLocations();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>
So, if you replace the askToSyncLocations() method with your own way of handling your 6000+ rows in a loop as batched of 1000 at a time, it should not encounter any memory problems?
Comment: It really depends on how your data are organised, the code is too specific to put here. As I say above, can you work out in advance how many rows your primary SQL (calling a web service from android) returns? I have example code, but need to know you understand what I'm getting at first.

Database Paging in Android


How can I apply a Logistic Regression model in real life?

Question: I just run a LR multivariate analysis to class probability check. From this analysis I could see that the combination of 4-variables would increase my test accuracy.
Here is the output of this anaylsis:
logit(P) = log(P / (1 - P)) = 13.458 - 0 Variable A - 0.106 Variable B - 0.004 variable C + 0.008 Variable D, where P is Pr(y=1|x). The best threshold (or Cutoff) for the predicted P is 0.15.
Original Label: NTB/TB --> Labels in Logistic Regression: 0/1
Note) The class/response value is recommended as (Case:1 and Control:0)
<code>        Estimate     Std. Error z value Pr(>|z|)    Odds
</code>
(Intercept )    13.458    8.354      1.611      0.107   -
Variable A      0   0   -1.046  0.296   1
Variable B  -0.106  0.079   -1.338  0.181   0.9
Variable C  -0.004  0.002   -1.649  0.099   1
Variable C  0.008   0.007   1.192   0.233   1.01
My question is, I want to validate this LR model in new samples, how can I them apply it ? Should I  simply apply this form:  13.458 - 0 Variable A - 0.106 Variable B - 0.004 variable C + 0.008 Variable D??
I am a biologist with a very limited statistical background.
Many thanks to you all
Comment: Additionally, this search may be useful: https://stats.stackexchange.com/search?tab=votes&q=%5blogistic%5d%20interpret
Comment: You are not doing a multivariate analysis since there is only one dependent variable.  Your situation is usually called _multivariable_.
Answer: That form will give you the value of the logit for the new sample, but you have to apply the inverse logit function to that to get P.  Then you have to compare those values of P to your threshold to classify each point in your sample.
Here's an online tutorial that uses R, but also explains the process:
http://r-statistics.co/Logistic-Regression-With-R.html
Comment: Thanks a lot. Another question:  Why the Variable A has a value of 0 (zero) ? As in logit(P) = log(P / (1 - P)) = 13.458 - 0 Variable A - 0.106 Variable B - 0.004 variable C + 0.008 Variable D. What does it mean??
Comment: A logistic regression assumes a linear relationship between the predictors and the log-odds of the response.  If the output of the regression is a coefficient of zero for variable A, that means that variable A does not help predict Y, at least not in your sample.


Call function on pandas df with lagged values calculated in the previous row/loop

Question: I am calling a function rowise on a pandas data frame using lagged values (for  Q and S) that were calculated for the previous row. The first row already has values for Q and S so it starts on the second row. It works fine in a for loop but the df I'm ultimately applying it too has over 3000 rows so I need something faster.
I've contemplated df.shift(-1), rolling.apply() and vectorising but nothing I've tried works.
import time
import pandas as pd
import math

def myfunc(Eo, P, Smax, Sprev, Qprev):
  print("i = ", i)
  print("Qprev = ", Qprev)
  S = Sprev + Eo * math.exp(-1 * Sprev/Smax) - P + Qprev
  Q = P + S
  print("Q = ", Q)
  return S, Q

data = {'peti': {0: 0.1960418075323104, 1: 0.5796640515327454, 2: 0.737823486328125, 3: 0.222676545381546, 4: 0.8804306983947754}, 'tas': {0: 281.0088195800781, 1: 277.112060546875, 2: 273.7044372558594, 3: 277.48309326171875, 4: 279.4878845214844}, 'precip': {0: 0.0, 1: 0.0, 2: 1.5046296539367177e-05, 3: 0.0002500000118743, 4: 4.6296295295178425e-06}, 'year': {0: 2008, 1: 2008, 2: 2008, 3: 2008, 4: 2008}, 'row_id': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, 'S': {0: 90.9, 1: "nan", 2: "nan", 3: "nan", 4: "nan"}, 'Q': {0: 0.0, 1: "nan", 2: "nan", 3: "nan", 4: "nan"}}

df = pd.DataFrame.from_dict(data)

smaxval = 100

start_time = time.time()

for i in df.index[1:len(df)]: #' start on second row
  df.loc[i,["S","Q"]] = myfunc(
    df.peti[i],
      df.precip[i],
        smax_val,
          df.S[i-1],
            df.Q[i-1])

print("--- %s seconds ---" % (time.time() - start_time))

Comment: `df.shift()` gives you the last row' values
Comment: I've tried df.shift() but I need to calculate Q and S then move onto the next row. df.shift() would be great if the column values already exist.
Answer: On my machine, your code runs in 0.004 second on average for 5,000 iterations:
N = 5_000
smax_val = 100
df = pd.DataFrame.from_dict(data)
times = []

for _ in range(N):
    start_time = time.time()
    for i in df.index[1 : len(df)]:  #' start on second row
        df.loc[i, ["S", "Q"]] = myfunc(
            df.peti[i], df.precip[i], smax_val, df.S[i - 1], df.Q[i - 1]
        )
    times.append(time.time() - start_time)

print(f"--- {round(np.mean(times), 3)} second(s) on average for {N} runs ---")
print(df)

--- 0.004 seconds on average for 5000 runs ---
       peti         tas    precip  year  row_id           S           Q
0  0.196042  281.008820  0.000000  2008       0   90.900000    0.000000
1  0.579664  277.112061  0.000000  2008       1   91.133562   91.133562
2  0.737823  273.704437  0.000015  2008       2  182.563705  182.563720
3  0.222677  277.483093  0.000250  2008       3  365.163051  365.163301
4  0.880431  279.487885  0.000005  2008       4  730.349194  730.349199

One way to speed things up (4x on average on my machine) is to make computations outside of Pandas and add results back in with Pandas concat:
N = 5_000
smax_val = 100
df = pd.DataFrame.from_dict(data)
times = []

for _ in range(N):
    start_time = time.time()
    vals = [[90.9, 0.0]]
    S = 90.9
    Q = 0.0
    for i, (x, y) in enumerate(zip(df.loc[1:, "peti"], df.loc[1:, "precip"])):
        S, Q = myfunc(x, y, smax_val, S, Q)
        vals.append([S, Q])
    df = pd.concat(
        [df.drop(columns=["S", "Q"]), pd.DataFrame(vals, columns=["S", "Q"])], axis=1
    )
    times.append(time.time() - start_time)

print(f"--- {round(np.mean(times), 3)} second(s) on average for {N} runs ---")
print(df)

--- 0.001 seconds on average for 5000 runs ---
       peti         tas    precip  year  row_id           S           Q
0  0.196042  281.008820  0.000000  2008       0   90.900000    0.000000
1  0.579664  277.112061  0.000000  2008       1   91.133562   91.133562
2  0.737823  273.704437  0.000015  2008       2  182.563705  182.563720
3  0.222677  277.483093  0.000250  2008       3  365.163051  365.163301
4  0.880431  279.487885  0.000005  2008       4  730.349194  730.349199


How to categorize classifiers and matrix factorization methods?

Question: I have a classification problem which is solved by a variety of methods. Among the methods are unsupervised methods, traditional classifiers and a supervised matrix factorization methods. The problem is that I'm trying to find a categorization for the methods. The problem comes when I try to differentiate between the traditional classifiers and the matrix factorization methods.
So far I made this categorization:
1- Unsupervised methods.
2- Supervised methods.
3- Matrix factorization methods.
However the problem is that the matrix factorization methods are also supervised so they also fall into that bin. But in principal they have somehow a different motivation or so, that's why I really want to put them in a different category but I'm not able to find a correct term for them. I also thought about putting them in a Recommender Systems category, but traditional classifiers also fall into that bin. So what do you suggest?
Answer: Your taxonomy is peculiar. For starters, classification is supervised learning. When you don't know the classes, the problem is called clustering. Finally, matrix factorization is just a mathematical framework; you can apply it to either. The supervised case is obvious; the rows and columns can correspond to the input and output (or vice versa), respectively, whereas for the unsupervised case you can consider correlation matrices.
Are you writing a survey paper on recommender systems, by any chance?
Comment: For recommendation I would categorize by the type of ratings: implicit vs. explicit, rather than the mathemematical framework.
Comment: yes I'm writing my thesis and I'm using matrix factorization method and a classifier to solve a task. Thus I want to put these in two categories.


Integrate $\int_0^{\frac{\pi}{2}}\frac{\sin^3(x)}{\sin^3(x) + \cos^3(x)}dx$

Question: I am quite sure I saw this somewhere on SE but I couldn't find it. How to evaluate
$$\int_0^{\frac{\pi}{2}}\frac{\sin^3(x)}{\sin^3(x) + \cos^3(x)}dx$$
I already have
$$\int \frac{\sin^3(x)}{\sin^3(x) + \cos^3(x)}dx+\int\frac{\cos^3(x)}{\sin^3(x) + \cos^3(x)}dx = \frac{\pi}{2}$$
Ideally I would like to have something like $I_1 + I_2 = \frac{\pi}{2}$ and $I_1 - I_2 = \text{something}$. But
$$\int \frac{\sin^3(x)}{\sin^3(x) + \cos^3(x)}dx-\int\frac{\cos^3(x)}{\sin^3(x) + \cos^3(x)}dx=?$$
I tried to play around with even and odd functions' property. The problem is that $\sin^3(-x) + \cos^3(x) = -\sin^3(x) + \cos^3(x)$.
Comment: Apply the substitution $x\mapsto \frac{\pi}{2}-x$. Sum the two equivalent integrals, profit. There is no need to compute any difference.
Comment: @JackD'Aurizio Oh oh I see. Those trig things are gonna haunt me forever.
Answer: Put $u = \frac \pi 2 - x$. Then $du = -dx$, and $sin(x)=cos(u), $ and $ cos(x)= sin(u).$ For our limits of integration, $x = 0 \to u = \frac \pi 2$, $x= \frac \pi 2 \to u = 0$.
Let $I = \int_0^{\frac \pi 2} \frac {sin^3(x)}{sin^3(x) + cos^3(x)} dx$.
Then $2I= \int_0^{\frac \pi 2} \frac {sin^3(x)}{sin^3(x) + cos^3(x)} dx + \int_{\frac \pi 2}^0 \frac {cos^3(u)}{cos^3(u) + sin^3(u)} (-du)$ $=\int_0^{\frac \pi 2} \frac {sin^3(x)}{sin^3(x) + cos^3(x)} dx + \int_0^\frac \pi 2 \frac {cos^3(u)}{cos^3(u) + sin^3(u)} du$.
But u is a dummy variable. So we have now
$2I = \int_0^{\frac \pi 2} \frac {sin^3(x)}{sin^3(x) + cos^3(x)} dx + \int_0^\frac \pi 2 \frac {cos^3(x)}{cos^3(x) + sin^3(x)} dx = \int_0 ^{\frac \pi 2} \frac {sin^3(x) + cos^3(x)}{sin^3(x) + cos^3(x)}dx = \int_0^{\frac \pi 2} dx = \frac \pi 2.$
Thus $I = \frac 12 * \frac \pi 2 = \frac \pi 4$.


Are these examples C# closures?

Question: I still don't quite understand what a closure is so I posted these two examples and I want to know whether these examples are both closures or not?
Example A:
List<DirectoryInfo> subFolders = new List<DirectoryInfo>();

Action<string> FilterSubFoldersStartA =
  s => subFolders.
       AddRange((new DirectoryInfo(s)).GetDirectories().
       Where(d => d.Name.StartsWith("A")));

FilterSubFoldersStartA(@"c:\tempa");
FilterSubFoldersStartA(@"c:\tempb");

Example B:
List<DirectoryInfo> subFolders = new List<DirectoryInfo>();

string filter = "A";

Action<string> FilterSubFoldersStartGen =
  s => subFolders.
       AddRange((new DirectoryInfo(s)).GetDirectories().
       Where(d => d.Name.StartsWith(filter)));

FilterSubFoldersStartGen(@"c:\tempa");

filter = "B";

FilterSubFoldersStartGen(@"c:\tempb");

Answer: Your second example makes use of closures (technically you could say that the compiler computes a closure in both cases, but you don't make use of it in the first case).
A closure is simply "all the variables visible to this function". Nothing more, nothing less. And obviously, in both cases, those variables exist, and are determined by the compiler.
But what we usually mean when we talk about "using closures" is that lambda expressions can use all local variables visible at the place they're declared. They're all part of its closure.
In your case, d is simply the parameter to the lambda function, and since that's all you use in the first case, you're not really taking advantage of closures.
In the second case, filter is not defined in the lambda expression, it's not a parameter or anything. It's a local variable which just so happens to be visible at the place where the lambda is declared. So it is part of the lambda's closure, which allows you to reference it in the body of the lambda.
Edit
As pointed out in the comments, I didn't read your code too closely. I only noticed the second lambda expression in each example. The first lambda does use closures (it closes over subFolders in both cases.)
Comment: The first example closes over `subFolders` so it's also a closure.
Comment: Oh right, I didn't even notice the first lambda. I just saw the `d =>...` one. You're right. The first one closes over `subFolders`, and in the second case, the second lambda closes over `filter`.
Answer: Yea, a closure is nothing more than a function that "saves" some variables from the environment in which it is defined. So in both of your examples, the defined action saves the list named subFolders, which can be referenced by the functions even after the local variable is out of scope. The filter variable in the second example is also saved by the defined function.
A more precise definition here
Answer: Both examples have closures. In "A" anonymous method captures local variable subFolders. In "B" anonymous method captures local variables subFolders and filter. Also take a look here.
P.S. Also note that you are actually using closure in "A" because you are using subFolders variable.
Answer: Here's an example from http://www.agileatwork.com/a-proper-closure-in-csharp/ of something that might look a little more familiar if you're comfortable with JavaScript. A closure is created around the tax variable so the calculation is only done one time. It isn't exactly easy on the eyes, but it's cool that you can do this type of thing in C#.
public class Order
{
    public Order(ITaxCalculator taxCalculator)
    {
        CalculateTax = new Func<Func<decimal>>(() =>
        {
            decimal? tax = null;
            return () =>
            {
                if (!tax.HasValue)
                {
                    tax = taxCalculator.Calculate(this);
                }
                return tax.Value;
            };
        })();
    }

    public Func<decimal> CalculateTax { get; set; }

    ...
}

Are these examples C# closures?


Dimension of Subspace in can $\Bbb{R}^5$

Question: Dimension of Subspace
For this question, I understand the minimum dimension of $W$ must be $2$ because of the rank nullity theorem. So $5-3 = 2$. However, Would the dimension of $W$ be at most $4$? I came this conclusion because of this list of vectors : $(1,0,0,0,0)$, $(0,0,1,0,0)$, $(0,1,0,1,0)$ and $(0,0,0,1,1)$ include $e_1$ and $e_3$ but do they avoid the spaces $e_2$, $e_4$, and $e_5$?
Answer: Note $W$ cannot have dimension 5. Otherwise, $W=\mathbb{R}^5$ and $e_2,e_5,e_5$ would belong to W.
But here's a hint.
Consider the collection of points $(x_1,x_2,x_3,x_4,x_5)\in \mathbb{R}^5$ defined by $x_2-2x_4+x_5=0$.
Answer: Your subspace $W$ has $e_1$ and $e_3$ already, which are obviously independent from the rest of the basis vectors. We can just consider how many independent vectors don't contain $e_2$, $e_4$, or $e_5$ in their span. So what we're left with is basically a question of "what's the highest dimensional subspace of $\Bbb R^n$ which doesn't include any $e_i$?". It's clear that $n$ doesn't work; any $n$ dimensional subspace of $\Bbb R^n$ is just $\Bbb R^n$ itself.
However, using the same strategy you used here, we can show in general that we can have $n-1$ dimension. To do this, choose one of the basis vectors $e_k$, then the new set of vectors is $v_i = e_k + e_i$ for $i\neq k$. Clearly there are $n-1$ of these, and a linear combination of these gives us
$$ \sum c_iv_i = e_k\sum c_i + \sum c_i e_i $$
Since the $e_i$ are all independent, this only vanishes if each $c_i$ is zero, so the $v_i$ are independent. Further, if we set this equal to any $e_j$ for $j\neq k$, it's clear that $c_j = 1$ while the rest of the $c_i = 0$, but this gives us a nonzero coefficient on $e_k$. Similarly, if we set it equal to $e_k$, we need the sum of $c_i$ to be $1$, which means that some $c_j \neq 0$ and so $e_j$ will have nonzero coefficient. Thus, the span of the $v_i$'s has dimension $n-1$ but contains none of the $e_i$'s.
So, we have that $W$ has dimension at most $4$.


Cardinality and Bijections- Proof Problem

Question: Here's my question: Let A be a set. Define B to be the collection of all functions f : {1} → A. Prove that |A| = |B| by constructing a bijection F: A → B
In class, we just learned injections, surjections, bijections, cardinality, and power sets. I have a test next week and I feel like theres's going to be questions similar to this coming up.
I know that the cardinality is an attribute that describes the length of a set. I also know that a bijection by definition is injective and surjective, therefore mapping each element of the domain to exactly one element in the codomain.
In this question, since B is described as the collection of functions, does that mean that it only contains relations that have no more than one element in the codomain for any element in the domain? So, set B contains sets like <code>{{1,a1},{1,a2},{1,a3}}</code> and so on?
How do I show that the sets A and B have the same cardinality?
Can someone please give me advice as how to go about this question or possibly show me how to prove it?
How do I construct a bijection?
Can someone help me make sense of what this visually looks like in terms of mapping diagrams?
EDIT: How does constructing a bijection prove set A and B have the same cardinality? By definition for elements in the codomain, a bijection has exactly one element in the domain, meaning in terms of mapping diagrams that there's exactly one arrow pointing at each element in the codomain. So, an element in the domain is allowed to have more than one element in the codomain, right?
Comment: Well, a function is a set of ordered pairs. So the function that sends $1$ to $a_1$ would be $\{(1,a_1)\}$. So your set $B$ would actually contain elements of the form $\{(1,a)\}$ with $a\in A$.
Comment: Prove that the obvious bijection is both injective and surjective.
Comment: @Arturo Magidin So, I have to show there are as many pairs of `(1,a)` functions in set B, where a is an element of A, as there are `a`s in set A?
Comment: The length of a set is a myopic view.
Comment: Yes; but looking so closely at what a function is misses the point. To each function $f\colon \{1\}\to A$, you want to associate an element of $A$; what is the obvious element of $A$ determined by $f$? Conversely, to each element $a\in A$ you want to associate function $g\colon\{1\}\to A$. That is the obvious function that you can define given $a$?
Comment: @ArturoMagidin Sorry, but I still don't get it. Is 1 the obvious element of **_A_** determined by **_f_** . How does surjection and injection come into play here? I just edited my question above. Could you please explain how constructing a bijection proves set A and B have the same cardinality? What does this look like visually in terms of a mapping diagram?
Comment: @RealBoi: $1$ is not necessarily an element of $A$.
Answer: The deficulty is understanding concepts and using language.  If you can do that this is trivial (almost literally).
Let me clearify with a few examples.
Ex: 1) Let $A=\{dog, cat, mouse\}$
Ex: 2) Let $A =\mathbb R$.
Then $B = \{f:\{1\}\to A\}= \{K\subset \{1\}\times A|$ for each $x \in \{1\}$ there is exactly one $(x,y) \in K\}=$
$\{K\subset \{1\}\times A|$ there is exactly one $(1,y) \in K\}=$
$\{K\subset \{1\}\times A| K = \{(1,y)\}$ for some $y \in A\}=$
$\color{blue}{\big\{}\{(1,y)\}| y\in A\color{blue}{\big\}}$.
In example 1: then $B = \color{blue}{\big\{}\{(1,dog)\}, \{(1,cat)\}, \{(1,mouse)\}\color{blue}{\big\}}$.
In example 2: then $B = \color{blue}{\big\{}\small\{(1, y)\small\}|y\in \mathbb R\color{blue}{\big\}}$
...  Now try to do this on your own without reading further ...
Now it should be intuitively obvious that for every $a \in A$ there is exactly one function $f: \{1\}\to A$ so that $f(1) = a$.
And that's it.  That's your bijection:
...... try to formally define the bijection, $j: B \to A$, before reading further ......

 Let $j: B \to A$ via for any $f \in B$ we set $j(f) = f(1)$.

...  Now try to prove that that is an injection without reading further...
To formally prove $j$ is a bijection.
Surjective: For each $a\in A$ then if we define $f:\{1\} \to A$ as $f(1) =a$ then $f \in B$ and $j(f) = a$.  So $j$ is surjective.
Injective: If $j(f) = j(g)= y$ for some $y \in A$ then $f(1) = y$ and $g(1) = y$.  but then (as $1$ is the only element of $\{1\}$) for all $x \in \{1\}$ then $f(x) = g(x)$.  So $f = g$.  So $j$ is one to one.
Answer: What follows does not construct a bijection, but aims at showing the existence of a bijection from A to B. Maybe this bijection could be constructed as a composition of bijections.

Let's admit that : for any set S and any singleton {x} the cardinal product S cross {x} has the same cardinal as S, that is, lets admit there is a bijection from S to the cardinal product s cross {x}
Lets's also admit that : the inverse relation of a relation R has the same cardinal as R, that is, that there is a bijection between the two sets.
Lets admit that : the set of all singleton subsets of a set S  has the same cardinal as S, that is, that there is a bijection between the two sets.

Here I will denote as : a, b, c , d etc. the elements of the set A
(1) There is a bijection from A to  the cardinal product A cross {1}, that is from A to the set :
{ (a,1), (b,1), (c,1)... }
(2) There is a bijection from the set A cross {1}, witch is a relation, to its inverse relation, that is , to the set :
{ (1,a) , (1,b) , (1,c) ...}
(3) There is a bijection from this inverse relation to the set of all its singleton subsets, that is, to the set :
{ {(1,a)} , { (1,b)} , {(1,c)} ... }
(4) This last set is the set of all functions f from {1} to A.
(5) So there is a bijection from our previous inverse relation to the set of all functions from {1} to A, that is, to set B.
(6) Since the relation " set S and set T can be put in 1-1 correspondance " is transitive , there is a bijection from our first set, the set A, and our last set, namely the set B.
(7) So |A| = |B|


How to interpret beta in VECM?

Question: After running the Johansen test for cointegration, 1 cointegrating vector was found. Let's say the following cointegrating equation was estimated (A was normalized)
<code>A              B            C
1.000000    -0.335218   -0.63412
</code>
A 1% increase in the A leads to a 1.34% increase in the B in the
long run. Is this the correct interpretation?
Answer: Your interpretation is not correct. By only knowing the cointegrating vector you cannot be sure which of the series influence which other series, and what the effect sizes are. For example, B might influence A but not necessarily. To find out the effect of B on A, you would have to look at the estimated coefficients* in the VECM rather than the coefficients of the cointegrating vector (which technically are estimated before estimating the VECM).
(Your interpretation would be more related to the loading coefficients $\alpha$ than the cointegrating vector $\beta$, but even there the interpretation would differ a bit from your statement. Actually, if the coefficient vector above was the loadings $\alpha$, you could say that a unit increase in B leads to a -0.33 units decrease in A in the next time period.)
What the coefficients of the cointegrating vector mean is just what relative weights of the series are needed to produce a stationary combination from the original (integrated) variables.

* By estimated coefficients I mean the loading matrix $\alpha$ that premultiplies the matrix of cointegrating vectors (in your case there is only one vector, so $\alpha$ is a vector) and the $\Gamma$ matrices that multiply the lagged values of the first-differenced variables.
Comment: Thank you for the response. The main purpose was to determine cointegration, and analyse the long-run and short-run dynamics. What do you mean by estimated coefficients?  The output gives me the normalized cointegration equation (where BetaA = 1)  and error-correction. From my understanding alpha is the loading coefficient (given by the error correction), and the normalized cointegration equation gives the Betas with one variable normalized (so it can be compared to Engle-Granger). Eviews gives the estimation representation with the betas (but not normalized) so they don't make much sense.
Comment: @Adrian, By estimated coefficients I mean the loading vector $\alpha$ that premultiplies the matrix of cointegrating vectors (in your case there is only one vector, so $\alpha$ is a scalar) and the $\Gamma$ matrices that multiply the lagged values of the first-differenced variables. The EViews output should also give you the $\Gamma$ matrices, unless your VECM has zero lags (which is possible). It is the $\Gamma$ matrices that give the short-run effects while $\alpha$ gives the long-run effects. Take a look also at [Wikipedia](https://en.wikipedia.org/wiki/Error_correction_model.) (bottom).
Comment: D(X) = A(1,1)*(B(1,1)*X(-1) + B(1,2)*Y(-1) + B(1,3)*Z(-1) + B(1,4)) The B values are 0.2, .04, and 3.9 in this equation. And alphas are given by the error correction terms. I don't understand what are your referring to. I have the values of Betas and the values of alpha. I thought that running the Johansen test already estimates an unrestricted VECM in eviews.
Comment: Yes I have a VECM(0)
Comment: OK, then there are no short-run effects, only the equilibrium relationship. You can tell the speed of reversion to the equilibrium by examining $\alpha$.
Comment: Thank you. So my initial assumption is correct? EViews changes the signs of the coefficients when normalizing.
Comment: I was wrong above, your $\alpha$ is a vector, not a scalar. I also edited the answer accordingly. I was thinking about just one equation of a VECM, but for all equations taken together your $\alpha$ will be a vector. Which initial assumption? If you mean the interpretation stated in your question, then it is not correct as explained in my answer. This is independent of how many lags (if any) you have in the model.
Comment: I understand the speed of adjustment part. But I was confused about my initial assumption.

How to interpret beta in VECM?


Let $ g(z)=\frac{1+e^z}{1-e^z}$.Compute $|\exp{g(g(ir))|}$

Question: Let $f(z)=\frac{1+e^z}{1-e^z}$
Compute  $|e^{f(f(ir))|}$,
where $r\in R$ is such number that the function is defined.
I have no idea how to start with.
Tried something like this
$$\frac{1+e^z}{1-e^z}=-(\frac{-1-e^z}{1-e^z})=-(\frac{1-e^z}{1-e^z}-\frac{2}{1-e^z})=-1+\frac{2}{1-e^x}$$ and
$$|e^{f(f(ir))|}=\exp({-1+\frac{2}{1-e^{f(ir)}}})$$
But that lead quite nowhere.
Any tips and advices will be appreciated.
Answer: $$f(z)=\frac{1+e^z}{1-e^z}$$
Note that $\tan(x) = \dfrac{e^{2iz} - 1}{i(e^{2iz}+1)}$, thus we have $f(ir) = \dfrac{i}{\tan(r/2)}$, or using $\cot(x) = \dfrac{1}{\tan(x)}$ we can simplify $f(ir) = i\cot(r/2)$.
We can apply this again to find $f(f(ir)) = f(i\cot(r/2)) = i\cot(\cot(r/2)/2).$
Finally, $\exp(i\cot(\cot(r/2)/2))$ is simply $\cos(\alpha) + i\sin(\alpha)$ where $\alpha = \cot(\cot(r/2)/2)$.
But more importantly, $|\exp(i\alpha)|$ for any real $\alpha$ is $1$, as $e^{i\alpha}$ lies on the unit circle. Thus the answer is simply $1$.


Operand precedence of assignment in PHP

Question: Is it just me or is it just odd to have the precedence of assignment be higher than any other operator?
Example in PHP I just came across:
    function test($param1) {
        $result = TRUE;
        for ($i = 0; $i <; strlen($param1); $i++) {
            if (!(ord($param1[$i]) >= 65 && ord($param1[$i]) <=90)) {
                $result = $result && FALSE;
            }
        }
        return $result;
    }

The intention when calling this function is to check whether a string has all characters in the range A-Z (If there are better ways it would be great to hear about them). The key part being the $result = $result && FALSE which I had thought would evaluate the right side to FALSE then assign $result that value.
But No. This little bug/feature took some tracking down.
It appears that the the assignment of $result = $result is performed first then to no-one the operation TRUE && FALSE; is carried out.
I actually had to give explicit direction to say $result = ($result && FALSE); which does seem very bizarre.
Anyway, I don't see how this is particularly useful 'feature' to have? Any ideas or am I missing something really basic?
Comment: Just `return FALSE;` inside the if() check. No need to keep looking once you find one bad value.
Comment: Hmm, docs say that && has higher precedence than assignment.
Comment: http://php.net/manual/en/language.operators.precedence.php -- `&&` has higher precedence than `=`, so you appear to be incorrect (and you also appear to be incorrect based on a test-script I wrote).
Comment: A lot of questions claiming PHP is *wrong* today.
Comment: @AlexHowansky that would certainly make more sense. Thanks
Answer:
If there are better ways it would be great to hear about them

ctype_upper()

It appears that the assignment is performed first then the && operation

You are mistaken. You are confused by the combination of your (incorrect) test of characters against integers and the reassignment of $result in a tight loop.
As noted in the comments, fail early.
Comment: Dang, I always forget about those ctype functions...
Comment: @Alex Howansky, no worries. I'm here to help [be a better PHP Developer](http://jason.pureconcepts.net/2012/08/better-php-developer/) :)
Comment: @JasonMcCreary thanks for spotting the missing ords, was a typo in the question. The behaviour was still there in the original code though.
Answer: characters are not ints in PHP, you need to call ord on them to get meaningful comparison with the number literals.
as far as better ways are concerned, how about preg_match() with ^[A-Z]*$?
so the real problem with your code is that it never enters the innermost if.
Comment: Sorted the question regarding the ords. They were in the original code that caused the behaviour. Thanks for the tip on preg_match().
Comment: if the code you paste here is not the code that you actually use (cut down to the necessary minimum and still exhibiting the unexpected behavior), then you probably won't get meaningful answers here.  like, maybe your *real* code has `$result = $result & false` (not the single ampersand)... we'll never know.

Operand precedence of assignment in PHP


Does the javascript Window object not have local variables?

Question: When I define a local variable under global namespace, it gets overwritten by an instance variable of the same name.
var outerVar;

outerVar = 'outerVar';
this.outerVar = 'thisOuterVar';
console.log(outerVar);            // thisOuterVar

However the same does not happen while inside a function.
var fun;

fun = function() {
  var innerVar;
  innerVar = 'innerVar';
  this.innerVar = 'thisInnerVar';
  return console.log(innerVar);      // innerVar
};

fun();

This code was run in Firebug.
this.constructor                  // Window { }

If I run the same code under node, where this.constructor is [Function: Object], it returns 'outerVar' instead of 'thisOuterVar' which makes sense.
Why does it behave differently under Window?
Comment: Try `new fun();` and the result will be different (`this.innerVar` in your example without new is just the same as `window.innerVar`).
Answer: If you run code in the browser from the global space like your first sample:
var outerVar;

outerVar = 'outerVar';
this.outerVar = 'thisOuterVar';
console.log(outerVar);

Then everything runs under the basic global space: window - this is basically the base scope of all environment in browser js.
so when you define value like var outerVar it's basically like window.outerVar or this.outerVar or window['outerVar'].
But if you run your code under anonymous function/object function like:
fun = function() {
  var innerVar;
  innerVar = 'innerVar';
  this.innerVar = 'thisInnerVar';
  return console.log(innerVar);      // innerVar
};

the this refer to the function(object) and the var innerVar refer to the scope of the function (like private var in basic oop class)
You can look at this like the this.somevar is public and var othervar is private - those are different things completely.
This is also answer your node question since in node everything runs under anonymous function "behind the scenes" - this is commonjs way - so in node it's basically the same as your anonymous function sample.
Edit:
As @bfavaretto comment me correctly - the this.innerVar is defined according to how you use it - meaning if you use it as regular function of course the this will be the window - hence global - if you make an object of it(like i thought - it will be define to the instance and be "public"):
function func(){
   alert(this);
}

func(); //alerts 'window'

var f = new func(); //alerts 'object'

Comment: Actually, the `this` inside the function refers to the global object (as the call is `fun()`, not `new fun()`).
Comment: This is what I said and meant - function(object)
Comment: I'm not sure we're talking about the same thing! This is a good answer, but that part is confusing. You seem to mean that fun would be a constructor, and this would refer to the constructed instance (you even mention "public"), when that's not the case in the example from the OP (as the function is simply invoked, without the `new`  keyword)
Comment: It's the same thing - even if you define a "static" class which is an object that you don't have to run with `new` like `var SomeClass = {a:1,func: function(){var b;alert(this.a)}}` the variants inside `func` behaves the same as oop class in js - you can call without new like `SomeClass.func();` and still `var b` is like `private` and `this.a` is like public. same for if you making an instance from a function definition ("js class")
Comment: It's not the same! In your example, `this.a` *is* indeed a property of `SomeClass`; in the OP code, `this.innerVar` is **global**.
Comment: You are right ! but not completely - because this.innerVar is global only if you run the function as function like `fun();` but if you do `var f = new fun();` it is not `global` anymore - it will be the `object` - but you right - it is a bit confusing.
Answer: In the global namespace, 'a = 5;' is semantically equivalent to 'window.a = 5;', or 'this.a = 5;'
Answer: You said, "When I define a local variable under global namespace...".  That's a contradiction in terms.  When you are in global scope there is no such thing as a 'local variable'.  As for what's happening inside your function, when you declare var innerVar; you are creating a variable that only exists in the scope of that function.  When you then modify this.innerVar inside the function, you're modifying (or declaring) the variable innerVar on whatever this happens to be at the time which, in this case, is window or, basically, global scope.


Does $\dfrac{\partial f(x,t)}{\partial x}=\dfrac{\partial f(x,t)}{\partial t}$ imply $f(x_0+k,t_0)=f(x_0,t_0+k)$?

Question: Let $f:\mathbb{R}^2\to\mathbb{R}$ be a smooth function such that
$\dfrac{\partial f(x,t)}{\partial x}=\dfrac{\partial f(x,t)}{\partial t}$
for all $(x,t)\in\mathbb R^2$.
Does this imply that there exists some real numbers $x_0,t_0, C$ such that
$f(x_0+m,t_0+n)=f(x_0+n,t_0+m)+C$
for all $(m,n)\in\mathbb R^2$?
Answer: Note that if you fix a constant $K\in \Bbb R$ and define $g(y) = f(y, K-y)$, then by the chain rule
$$g'(y) = f_x(y,K-y) - f_t(y,K-y) = 0$$
Thus, $g(y)$ is a constant function, which means that $f(x,t)$ depends only on $x+t$.


How to prevent a field from wrapping in Views?

Question: I have a price field that gets squished and displays on multilines instead of a single line. The only way to solve this is to apply some css wrap magic?
Answer: With css you could set a specific width or use white-space:nowrap. I don't know how to do it other than with css or javascript


Simple Question about mathematical convention

Question: For expressions in the form:
$$\sum_{i=1}^{k}f(i),$$
does this preclude the possibility that $k$ can be non positive as well as non-integer?
Or more explicitly, can I make an induction on $k$? and take $1$ as base case? And then show that it is true for $k$ if it is true for $k-1$ ?
Thank You.
Comment: Not necessarily. Some authors define such sums so they obey laws [analogous to (in)definite integrals,](http://en.wikipedia.org/wiki/Integral#Conventions) so one gets additivity on intervals, with an analogous discrete law for reversing the limits of summation.
Answer: For expressions of the form
$\sum_{i=1}^{k}f(i) = \text{____}$
This does this preclude the possibility that $k$ can be non-positive and it precludes non-integer values of $i$. (That is, $i\in \mathbb{Z},\;0\leq i \leq k$ in your expression).
Yes, you can make an induction on $k$, taking $1$ as your base case and showing that if we take $k-1$ to be true, then $k$ is also true.
Note: I used the $\text{____}\;$ to denote some expression because to prove anything about your sum, you need to prove some claim about the sum: e.g. $\sum_{i=1}^{k}f(i) = \text{____}\;$ or that $\;\sum_{i=1}^{k}f(i) \leq \text{____}\;$.
Comment: Does $k=0$ not produce a totally valid sum?  And why not simply take $0$ as the base case and induct from there?
Comment: True, one need only take $k=0$ as one's base case; I guess I was answering with respect to the OP's reference to using $1$ as a base case. That's why I said: "to take 1 as a base case..." one needs to transform the expression.
Comment: Thanks for the answers. Yes, I would go for $k=0$. That was my typo, actually i ranges from 1 to k. That's not the main issue though.
Comment: @amWhy: Even some nice dialogue +1
Answer: This format does preclude non-integer numbers. It specifies that $i$ takes the integers between $0$ and $k$ inclusive, so yes, you could induct on $k$.
If we want to take non integer values, we can do that by specifying an "indexing set" $I$ and saying that $I$ contains all the values we want. We then write $\displaystyle \sum_{i \in I}f(i)$ to say that $i$ takes all values in the set $I$. This a commonly used in, for example, probability, where we take $I$ to be the set of all possible events and $f(i)$ the probability that $i$ occurs.


Non-parametric confidence interval about the difference of means for unpaired data

Question: Consider two samples ${(x_i)}_{i=1}^m$ and ${(y_i)}_{i=1}^n$. Assume that the $x_i$ are independent replicates from a distribution with expectation $\mu_X$ and similarly the $y_i$ are independent replicates from a distribution with expectation $\mu_Y$, and also assume that the two samples are independent. Is it possible to get a boostrap confidence interval about the difference of means $\mu_X-\mu_Y$ ? Or is there another nonparametric way to get such a confidence interval ?
EDIT : Oops - I've just seen this topic Confidence interval for the difference of two means using boot package in R Nevertheless I am interested in understanding why the method is correct. This is not a classical bootstrap procedure, isn't it ? Here we sample separately in each data sample. This is not like the classical bootstrap which is the case when there is only one data sample.
Answer: Yes, it is like a stratified bootstrap.  You sample with replacement m times for population 1 and calculate a bootstrap mean for it.  Do the same by sampling with replacement n times from population 2 calculate a bootstrap mean for it and then take the difference of the bootstrap means.  Repeat this many times to get an approximate bootstrap distribution for the mean difference.  As long as the conditions for the bootstrap mean to work are satisfied for each population the bootstrap will work on the mean difference. In my book titled Bootstrap Methods, 2nd Edition pp. 67-71, I show an example where I did this in a clinical trial looking at the mean difference in capture thresholds for two pacing leads.


Why is the MYSQL variable innodb_file_per_table changed to OFF automatically in a OPENSHIFT online gear?

Question: My application is on openshift online gear with mySQL 5.5. Recently I found that my mySQL database become very big quickly (few days increase 1G) without many operations. This made me try to do optimize database. To my surprise, every time I optimize the database, the size of db (increase 1G). /mysql/ibdata1 is huge.
After investigation, I surprisingly discovered that Innodb_file_per_table is OFF. To me it is very strange and my install and deploy scripts all set it to ON (from the beginning). I also tried manually set it ON. However, after 1 day, it was changed to OFF again. Does anyone know why? Or Anyway to know the reason. Thanks.
Comment: Whoever created the gear set that up. You can always create a custom gear based on that one.
Answer: I found when the gear restart, it changed to OFF. It seems that openshift does not run post_start_php when re-starting the gear. I need to add post_restart script to set innodb_file_per_table ON. Now it seems OK.
Comment: Remember to dump and reload your DB to actually have your DB use a different file per table.


Google map info window blocking click events

Question: I have implemented a InfoWindowAdapter that returns this inflated XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/layoutRoot"
    android:clickable="true">

    <TextView
        android:id="@+id/titleText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Medium Text"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/snippetText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Which is inflated by
public class MarkerWindowProvider implements InfoWindowAdapter {
    private LayoutInflater lInflater;
    private InfoWindowClickListener onClick;

    public MarkerWindowProvider(Context parent, InfoWindowClickListener onClick) {
        lInflater = (LayoutInflater) parent.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.onClick = onClick;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(final Marker marker) {
        View contents = lInflater.inflate(R.layout.custom_infowindow, null);
        ((TextView)contents.findViewById(R.id.titleText)).setText(marker.getTitle());
        ((TextView)contents.findViewById(R.id.snippetText)).setText(marker.getTitle());
        contents.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onClick(marker);
            }
        });
        return contents;
    }

    public interface InfoWindowClickListener {
        public void onClick(Marker marker);
    }
}

The inflated layout is displayed instead of the stock info window but the OnClick method never fires regardless of which method i choose to inflate the XML into.
I really need this functionality. Any ideas on why this is not working? Any alternatives?
Thanks.
Answer: It's said, that you can NOT handle any events from views inside your info window. This popup is not a "live" view, you even can't disable default background selector (to block blinking). Unfortunately.
So it's not recommended to put buttons and text views for input.


sudoers file errors on solaris (suspecting wildcards)

Question: I'm trying to write a universal sudoers file to control permissions for all our users across all our environments and I've been using the wildcard for the hostnames like so (all data has been anonymized)
<code>Host_Alias stg01     = *.stg01.sfo.acme.com
Host_Alias stg02     = *.stg02.sfo.acme.com
Host_Alias stg03     = *.stg03.sfo.acme.com
Host_Alias prod      = *.prod.aus.acme.com, *.prod.nyc.acme.com
Host_Alias prod02    = *.prod02.aus.acme.com, *.prod02.nyc.acme.com
Host_Alias prod03    = *.prod03.nyc.acme.com
Host_Alias db01      = *.db01.sfo.acme.com
Host_Alias db02      = *.db02.sfo.acme.com
Host_Alias db03      = *.db03.sfo.acme.com
Host_Alias hi02      = *.hi02.sfo.acme.com
Host_Alias env1      = mgmt02.stg01.sfo.acme.com, *.hiho.sfo.acme.com
Host_Alias env2      = *.prod.aus.acme.com, *.prod.nyc.acme.com, *.stg01.sfo.acme.com, *.prod02.aus.acme.com, *.prod02.nyc.acme.com, *.hiho.sfo.acme.com
Host_Alias testhosts = ws1.prod.aus.acme.com, ws2.prod.nyc.acme.com, ws1.prod.aus.acme.com, ws2.prod.nyc.acme.com
Host_Alias env3      = mgmt01.stg01.sfo.acme.com, *.hiho.sfo.acme.com
Host_Alias env4 = *.prod.aus.acme.com, *.prod.nyc.acme.com, *.stg01.sfo.acme.com
Host_Alias env5  = *.prod.aus.acme.com, *.prod.nyc.acme.com, *.stg01.sfo.acme.com, *.hiho.sfo.acme.comsfo
</code>
When I try it, I get:
<code>>>> sudoers file: syntax error, line 0 <<<
</code>
and it repeats all the way to line 16. This is on a Solaris x86 server running sunOS 5.10.
Did I do something wrong? a visudo -c -f returns fine on my linux testbox so I'm confused.
Any ideas would be appreciated!
Thanks.
Answer: Have you tried running w/o wildcard hosts and then adding one of them back to see if sudo gets bothered?  This would clear up the question as to whether wildcards on hosts are allowed.
Answer: I needed to use capital letters for all the host aliases. so STG01 instead of stg01 and so on :)


How to get mutable slice with conditions in Rust

Question: I'd like to write something similar with following code in Rust.
fn main() {
    let mut v: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut s: Vec<&mut i64> = v
        .iter_mut()
        .filter(|val| **val < 2_i64)
        .collect();
    if s.len() == 0 {
        s = v
            .iter_mut()
            .filter(|val| **val > 2_i64)
            .collect();
    }
    *s[0] = 0;
    println!("{:?}", v);
}

It's obviously making borrowing reference twice. I know it causes an error, E0384: cannot assign twice to immutable variable s cannot assign twice to immutable variable.
Could you tell me how to write this kind of work flow in Rust? I want to filter value and if it returns nothing, apply another filter and get Vec of borrowing reference.
I tried to use shared reference. After filtered the Vec, I needed to convert shared reference to borrowing one, but it was not possible.
Comment: Are you sure you want mutable reference to `i64`s? You could create a new vector with numbers directly
Comment: What do you want to do with `v` afterwards? The solution somewhat depends on it.
Comment: Actually, I'm implementing `Vec` of `struct`. But for making it easy, I'm using `i64`. And I want to change fields of struct after applying the filter.
Comment: Why don't u use a `for`?
Comment: Because I needed to know the array had elements or not. I needed two loop. Thank you very much for the answer. It's what I would like to know.
Answer: You can write something like that. I agree that it's not really beautiful, but it works:
fn main() {
    let mut v = vec![1_i64, 2, 3, 4, 5];
    let s: Vec<_> = v.iter_mut().filter(|&val| *val < 2).collect();
    let mut s = if s.len() == 0 {
        v.iter_mut().filter(|&val| *val > 2).collect()
    } else {
        s
    };

    *s[0] = 0;
    println!("{:?}", v);
}

Comment: `|&&mut val| val < 2`
Comment: I'm not sure about which is better to use `|&&val|`, `|&val|` or `|val|`. Could you leave your opinion here?
Answer: We can clone the reference like this:
fn main() {
    let mut v: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut t = v.clone();
    let mut s: Vec<&mut i64> = v.iter_mut().filter(|val| **val < 2_i64).collect();
    if s.len() == 0 {
        s = t.iter_mut().filter(|val| **val > 2_i64).collect();
    }
    *s[0] = 0;
    println!("{:?}", v);
}

Comment: You should avoid cloning as long as you can.
Comment: @fx-kirin Not to counter but clone will loose the reference after the main .So why should we avoid using it .Can you please explain
Comment: for memory efficiency.


Canceclar cuenta Google Cloud en Colombia - Cancel Google Cloud account in Colombia

Question: *** Spanish (Español) ***
Me llegó un correo electrónico donde titula "[Aviso legal] Se aplicarán cambios en los impuestos asociados a tu cuenta de Google Cloud en Colombia", y no puedo cancelar la cuenta de Cloud que por error inicié.
*** English (Inglesa) ***
I received an email with the title "[Legal notice] Changes will be applied to the taxes associated with your Google Cloud account in Colombia", and I cannot cancel the Cloud account that I started by mistake.
Answer: Your Google Cloud account is tied to your Google account (GMail, YouTube, etc.) and you can't close one without closing the other. What you can do, is cancel the billing subscription associated with Google Cloud which will terminate all active services, if any.
To cancel your billing subscription:

Sign in to the Manage billing accounts page in the Google Cloud Console.
Select the name of the billing account you want to close.
In the Billing navigation menu, click Account Management.
At the top of the page, click cancel CLOSE BILLING ACCOUNT.