Adding constraint to the "main view" in a xib

Question: I have a UIView defined in a .xib file. I need to set translatesAutoresizingMaskIntoConstraints = NO. This means that the frame is not translated to constraints so I need to set the size constraints by myself.
I have created a working category method for a UIView:
-(NSArray*)setSizeConstraints:(CGSize)size
{
    NSLayoutConstraint* height = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1  constant:size.height];
    NSLayoutConstraint* width = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1  constant:size.width];

    [self addConstraint:height];
    [self addConstraint:width];

    return [NSArray arrayWithObjects:height, width, nil];
}

But I would like to set these constraints from the Xcode interface builder, but all my AutoLayout controls are greyed out:

Is there a way to do this in the interface builder?
Answer: This actually is possible.
Simply put the view you'd like to constrain into another view, like the highlighted view here.

Then, add your desired constraints.
Finally, pull the view you just added constraints to out of its parent view. You can now add constraints to that view.
Comment: Can you really do this with the _main view_? Putting the main view in another view creates a copy and I dont see any way to set the copied view as the main view again.
Answer: As you've surely found out by now, it looks like there's currently no way to set Autolayout constraints at the main UIView level from Interface Builder.
I had a similar problem here (Launch Screen XIB: Missing Width / Height Constraints (Xcode 6)), while working with the launch screen of my app.
The only workarounds I found, if you want to keep working with IB, are:

Using a UIViewController and its UIView inside the XIB, instead of just a UIView
Working only with Storyboards (and, once again, UIViewController)

However, I understand these approaches may not be ideal or "clean", especially if you simply have a subclass of UIView and you want to draw its interface in a good old XIB.


Dúvida quanto ao uso de vários user control na mesma página

Question: O mais difícil aqui é formular a pergunta do modo certo para não receber downvote, mas vamos lá. Tentarei explicar bem, pois a dúvida é complexa ou chata. Vou fazer perguntas pontuais para evitar perguntas com várias respostas. Aí vai.
Tenho 3 user control, mas minha aplicação só usa um ee preciso dos demais. Fui ver o código do formulário principal e o colega registrou o mesmo uc 3 vezes. Veja parte do código de como ficou.
Page Title="" Language="C#" MasterPageFile="~/Core.Master" AutoEventWireup="true" MaintainScrollPositionOnPostback="true" CodeBehind="frmCadastroBens.aspx.cs" Inherits="Scania.SOMC.Web.frmCadastroBens" %>
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc1" %>
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc2" %>
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="css/cadastroBens.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <asp:HiddenField ID="hdfCdProcesso" runat="server" Value="0" />
    <asp:HiddenField ID="hdfSomenteLeitura" runat="server" />
    <asp:HiddenField ID="hdfNmUsuario" runat="server" />
    <asp:HiddenField ID="hdfCdUsuario" runat="server" />
    <asp:HiddenField ID="hdfAdministrador" runat="server" />
    <asp:HiddenField ID="hdfCdTipoProcesso" runat="server" />
    <asp:HiddenField ID="hdfWucChamador" runat="server" />
    <asp:HiddenField ID="hdfPreencheDocumentoCadFornecedor" runat="server" />

Bens em aquisição / garantia

    <uc1:wucCadastroBens ID="wucCadastroBensNovoPV" runat="server" />

    <uc2:wucCadastroBens ID="wucCadastroBensUsadosPV" runat="server" />

    <uc3:wucCadastroBens ID="wucCadastroConfissaoDividaPV" runat="server" />

Desta forma não consigo, por exemplo, usar o wucBensUsados, somente o wucBensNovos. A pergunta é: Devo registrar também o wucBensUsados? Esse é o procedimento correto?
Comment: Da uma olhada na atualização da minha resposta.
Answer: Sim, para poder utilizar na pagina você deve registrar o controle.
Tem um modo mais fácil de fazer isso do que ir de página em página, basta registrar no web.config, como por exemplo
configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="uc1" src="WUC/wucCadastroBens.ascx" tagName="wucCadastroBens"/>
      </controls>
    </pages>
  </system.web>

E no seu caso, você registrou o mesmo user control 3 vezes, creio que esse seja o problema.
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc1" %>
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc2" %>
<%@ Register src="WUC/wucCadastroBens.ascx" tagname="wucCadastroBens" tagprefix="uc3" %>

Comment: O meu problema é com os demais uc. Tenho um wucBensUsados, que eu registrei no frmCadastroBens.aspx e não consigo trabalhar com ele. Nesse wuc eu tenho um HiddenField que eu não consigo atribuir valor a ele. Dá erro de como se ele não existisse. E por essa razão não consigo atribuir nada a nenhum campo em meu wucBensUsados, apenas no wucBensNovos.
Comment: Ao menos eu nao vi voce registrar esse UC na pagina que colocou o código aqui.
Comment: Desculpe-me, é assim que está no original. Eu fiz um registro, removendo o segundo registro e substituindo pelo novo uc e não deu certo.


Navigation bar disappears after navigating - HTML

Question: I'm currently developing an asp.net core web app, and I'm struggling on correctly navigating through the app.
Here is my directory structure, note that I'm using Areas.

Now, the exact problem is that I'm able to navigate through the pages that are in the main folder like Index, Index1 and Private, but once I go to the Area, I am no longer able tonavigate correctly.
It is remarkable to say that the Layout code of the _Layout and _LaunchLayout is almost the same, only changes the name of the navigation items and their destinations.
Once I click any item on the navigation bar to navigate, the corresponding page shows up but the navigation bar disappears.
I'd appreciate some help on this, thanks to you all beforehand.

EDIT: Link to the project
https://github.com/Rogeraj2001/GraphicProofOfConcept.git
Comment: Could you provide your whole project for us to test it? Just structure is difficult to find the solution.
Comment: Yes , sorry @XinranShen . Now I've updated the question.
Answer: _ViewStart.cshtml file should be in root view folder Views/_ViewStart.cshtml  not the Views/Shared folder, So move your _ViewStart.cshtml file out of shared folder:

Then modify the code to
@{
    Layout = "~/Areas/LaunchArea/Views/Shared/_LaunchLayout.cshtml";
}

Now the area can load layout page successfully.
Comment: Hi @Roger Almirall Jou, Have you solved this issue now?
Comment: Hi @Xinran Shen , thanks for your suggestion. This change did not resolve my issue, since the reason for the `_LaunchLayout.cshtml` to be there was that if not I get this error:
`
InvalidOperationException: The view '_ViewStart' was not found. The following locations were searched: /Areas/LaunchArea/Views/Home/_ViewStart.cshtml /Areas/LaunchArea/Views/Shared/_ViewStart.cshtml /Views/Shared/_ViewStart.cshtml
`
Comment: However, if I navigate directly with the route to that page, I get the same as your picture.
Comment: I'm glad for your help, but I found a quite clean workaround, I'll post an answer myself.
Answer: Well, after trying some things I found a workaround. That has been to specify the view route in the controller action:
public IActionResult _ViewStart() {
    return View("~/Areas/LaunchArea/Views/_ViewStart.cshtml");
}


Celtic folk music bass technique

Question: Few days ago I joined a Celtic folk music band as a bass player.
I've never play that kind of music, but I found it very different to play compared to rock music, especially with the right hand.
Almost every line is played alternating two notes, like country music. For example: D - A - D - A... (Third and fourth string). Here is an example.
Does anyone know how is called this technique? I can't find anything related but I want to research and practice it, because I'm having problems to stop the string with my right hand, especially when playing an open string.
Any tips?
Comment: Only play an open string when you want it to ring and *not* be damped; open strings are usually saved for the roots of chords.
Answer: It's just called alternate bass.
Regarding stopping the strings... well, practice! – that's actually a crucial ability to have on bass, in any genre.
I guess the problem you're referring here is specifically that you're always changing the string after every note, i.e. you can't just use the next-plucking finger to damp the previous note, as you would in (assuming you pluck with two fingers)
X:1
L:1/8
M:C
K:C
%%score B
V:B            clef=bass-8 transpose=-12
% 1
[V:B]  "i"A,, "m"z "m"A,, "i"z "i"A,, "m"z "m"A,, "i"z

When switching strings, you'd instead damp with the previous-plucking finger:
X:1
L:1/8
M:C
K:C
%%score B
V:B            clef=bass-8 transpose=-24
% 1
[V:B]  "m"D, "m"z "i"A,, "i"z "m"D, "m"z "i"A,, "i"z

This is done with a sort of rocking back and forth motion of the plucking hand.
Note that single-finger stopping generally doesn't work 100% – you don't so much stop the note as squelch it to an overtone. On option is to damp with the whole palm, but this is quite unpractical at tempo.
I personally don't generally bother with any of that, and just damp primarily with the fretboard hand. I hardly use open strings at all on electric bass, especially not in sequence. So for D-A, just play both of them on the A string, then you can easily damp with both hands. For E-B, I'd play them on the A- and E-strings on 7th fret, fingering with pinky and ring finger, respectively, while the index finger rests over the 5th fret.
An alternative, which is arguably more appropriate for folk, is to go with full double bass technique, i.e. you pluck most notes with the side (rather than tip) of your index finger. This is much more effective at damping undesired strings, especially the lower ones.
Comment: Thank you so much for your response! That's it, alternate bass! But I can't find any tutorial no YouTube about this. I'll practice to mute the string with the previous finger. Generally I use to stop strings with my left hand, which makes it feel tired faster, that's why I want to learn to stop it with my right hand.
Answer: Firstly, why play open strings? Of course they'll need damping to stop them, but if you fretted each note, it's simple to stop them sounding - you let go!
So, playing 1s and 5s (which is what you will be doing), wherever 1 is, 5 will be on the same fret, lower string, or two frets up, next higher string. It's a very basic bass pattern, that most bass players will have come across early on in their playing career.
Using fingers instead of pick or thumb will also help tidy up the playing, as you can keep a finger touching the string it's going to play before plucking, and every bit of damping tidies up the playing.
Comment: That's just the pattern I play in every song of this band haha, but in the linked song I need to play a E - B (fourth and third string) sequence, so I need to play the open fourth string, which makes it sound louder and dirty. Maybe I can play E - B just in the fourth string, I'll give it a try. I play with fingers (index and middle) and I tried to damp the string with the finger that plucked the string, but the style it's not folk, it's rock and folk! Haha, so the tempo is very high and I'm always late to damp the string. Thanks for your response!

Celtic folk music bass technique


How to show a description when a select box item has been selected

Question: On my "node/add" form I have a "topic" taxonomy term field a user has to select. I would like to be able to display a description about a selected text next to the box, see red box in screenshot:

I'm sure there are CSS/javascript hacks out there, just wondering if there is a "Drupal way" for doing this?
Cheers
Comment: Do you have the description stored alongside the taxonomy term as a field?
Comment: yeah, that would be a great place to store the text rather than hardcoding it
Comment: Cool, if you check my answer, it uses the default taxonomy term description field :-)
Answer: This isn't strictly theming, but the following works for me:
Put the following in a custom module:
function tax_desc_menu() {
  $items = array();

  $items['termdescription/%'] = array(
    'title' => 'Term description callback',
    'page callback' => 'tax_desc_get_description',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function tax_desc_get_description($tid) {

  if (!is_numeric($tid)) {
    return drupal_json_output('Select a term');
  }

  $term = taxonomy_term_load($tid);

  $description = $term->description;

  return drupal_json_output($description);

}

This is simply a menu hook that calls a function.  You will be calling this menu link to get the description data for the taxonomy term.  The second function takes the term ID that will be passed in the ajax call, and gets the term object.  From that, it pulls the description set using the standard taxonomy term description.
Next, you'll need to add the following javascript and reference it in your module .info file:
(function($){
  Drupal.behaviors.taxdescGetDesc = {
    attach: function (context) {

      $(".page-node-add-article #edit-field-tags-und").after('
Select a term
');

      $(".page-node-add-article #edit-field-tags #edit-field-tags-und").click(function(){
        $.ajax({
          cache: false,
          type: 'POST',
          url: "/termdescription/" + $(this).val(),
          context: document.body,
          dataType: "json",
          success: function (json){
            $('#mycontainer').html(json)
          }
        })
      })
    }
  }
})(jQuery);

You'll probably want to change the ID's and classes that I've used, as I've just used a standard article type for this.
This Javascript will put a div with the ID of mycontainer below the select box (this can be styled/positioned with CSS so it matches your image).
when you click the select box, the term description will populate the div created earlier called mycontainer.
Just in case, your .info file will look like the following:
name = taxonomy description
description = taxonomy description from list

core = 7.x

scripts[] = tax_desc.js

Comment: I also forgot to mention, if this form is using the seven admin theme, you won't be able to put the CSS in your own theme file.  You'll probably want to include a CSS file in the module using `stylesheets[]` in your info file so it's applied regardless of theme :-)
Answer: You may use jQuery the click() event. Read more on http://api.jquery.com/click/.
jQuery("#idofselectbox").click(function() {
  jQuery("#idofreddiv").html('
Hello All
' + jQuery(this).val());
});


Second order approximations of expected exponentiated sums of dependent Bernoulli random variables

Question: I would like to approximate $\mathbb{E}[e^y]$ for
$y=\sum_i^n c_i x_i$, and $x_i\sim \text{Bernoulli}(p_i)$ ($p_i$'s distinct) using $p_i$ and $\text{cov}(x_i,x_j)$. The $c_i\in \mathbb{R}$ are fixed, and the $x_i$ are not independent.

Currently, I am estimating $\mathbb{E}[e^y]$ by assuming the $x_i$ are independent. That is, I take $\mathbb{E}[e^y]\approx \prod_i[ (1-p_i)+p_i e^{c_i}]$, which only requires me to know $p_i=\mathbb{E}[x_i]$.
However, in addition to knowing $p_i$, I also know $\text{cov}(x_i,x_j)$, but I am not using this information. I am searching for a way to improve my estimation of $\mathbb{E}[e^y]$ by making use of the covariances.
I have tried a few things. Each has problems which I will attempt to illustrate with a toy example. First a bit more notation: Let $\mu=\mathbb{E}[y]$, $\sigma^2=\text{var}[y]$, and take $\hat{y}=\sum_i^n c_i\hat{x}_i$ with $\hat{x}_i\sim \text{Bernoulli}(p_i)$ all independent.
Now a toy example. Suppose $y=7x_1+5x_2-8x_3$, $P(x_1=1,x_2=1,x_3=0)=P(x_1=0,x_2=1,x_3=1)=0.2$, and all other assignments of $x_1,x_2,x_3$ occur with probability $0.1$.
Then, $\text{cov}(x_1,x_3)=-0.05$, $\text{cov}(x_1,x_2)=\text{cov}(x_2,x_3)=0$, and $\mathbb{E}[e^y]=32,681.07$.
Methods of approximation:
1) Ignore the dependencies: $\mathbb{E}[e^y]\approx \mathbb{E}[\text{exp}(\hat{y})]$. This approach only uses first order information ($p_i$). On the toy example we get $\mathbb{E}[\text{exp}(\hat{y})]=24,553.48$.
2) Taylor series approximation: $\mathbb{E}[e^y]\approx e^\mu(1+\tfrac12 \sigma^2)$. This approach gives terrible approximations for large $c$'s. On the toy example we get $e^\mu(1+\tfrac12 \sigma^2)=7.697877$.
3) Log-normal approximation: $\mathbb{E}[e^y]\approx e^{\mu+\tfrac12 \sigma}$. This approach overshoots very badly which is problematic for my application. On the toy example $e^{\mu+\tfrac12 \sigma}=165,585,792$. But note that $\mathbb{E}[e^y]$ is bounded between $\text{exp}({\sum_i \mathbb{1}_{\{c_i<0\}}c_i}) \le \mathbb{E}[e^y] \le \text{exp}({\sum_i \mathbb{1}_{\{c_i>0\}}c_i})=162,754.8$.
4) Treat $x_i$ as independent, but correct the second moment: Note that $\mathbb{E}[e^y]=\sum_{k=0}^\infty \frac{1}{k!}\mathbb{E}[y^k]$, then we might consider $\mathbb{E}[e^y]\approx \mathbb{E}[\text{exp}(\hat{y})]+\tfrac12 \mathbb{E}[y^2]-\tfrac12 \mathbb{E}[\hat{y}^2]$. I'm not sure this is well principled, and I empirically observe very small corrections when the coefficients $c_i$ are large (as in the toy example). In this case, this approximation gives a value of $24,556.28$.

More details:
The above problem arises from the following. Imagine an $n\times m$ matrix $R$ of indicator vectors, i.e. each row is an independent random vector in $\{0,1\}^m$ that takes at most a single 1 (all other positions being zero), the probabilities of which are known. Then $y=\tfrac12 \text{tr}(R^T C R)$ where $C$ is a symmetric matrix of constants with zeros on the main diagonal. In the above formulation $x_i$ is an off diagonal element of the matrix $RR^T$. I presented the problem in that way because I thought it makes the problem more clear. I've given these additional details in case they are important in some way.
For what it's worth, in my problems $n$ is usually $O(10^1)-O(10^2)$ and some of the $c_i$ may be large in magnitude (e.g. $\ge O(10^1)$).
Answer: Without further restrictions on the dependence structure, knowing the covariance matrix is not generally very useful in computing or approximating $\mathbb{E}[e^y]$.
If the joint distribution of $(x_1,x_2,\cdots,x_n)$ was multivariate normal then knowledge of the covariance matrix $\text{cov}(x_i,x_j)$, combined with knowledge of the individual $\mathbb{E}[x_i]$, would completely determine the value of $\mathbb{E}[e^y]$. However, in this case the joint distribution of $(x_1,x_2,\cdots,x_n)$ is not determined fully by knowledge of the covariances, except of course in the special case where $n=2$.
Here's an example of what can happen in the case $n=3$. For $n>3$ there are more 'degrees of freedom' so similar things can happen but the notation becomes more complicated. Let $p_{ijk}$ denote $P(x_1=i,x_2=j,x_3=k)$. Suppose that $p_{ijk}=f(i+j+k)$ for some function $f$ i.e. the joint probability of a sequence of $x_i$ values depends only on the number of non-zero entries. For simplicity suppose that $p_1=p_2=p_3=\frac{1}{2}$, which means that $f(1)+2f(2)+f(3)=\frac{1}{2}$. Covariances are determined by the value of $\mathbb{E}[x_1 x_2]=P(x_1=1,x_2=1)=f(2)+f(3)$; let's fix this value at $\frac{1}{4}$. We also require that the probabilities sum to $1$, so $f(0)+3f(1)+3f(2)+f(3)=1$.
You can check that $(f(0),f(1),f(2),f(3))=(\frac{1}{4},0,\frac{1}{4},0)$ and $(f(0),f(1),f(2),f(3))=(0,\frac{1}{4},0,\frac{1}{4})$ both satisfy all the above constraints. In particular they both lead to the same covariances. However, in the case where all the $c_i$ are large and positive, it is clear that $\mathbb{E}[e^y]$ is dominated by the term $f(3)e^{c_1+c_2+c_3}$, which will be very different for these two possible functions.
So, to get any further using the covariances you'd need to have further restrictions on the dependence structure in the $x_i$ variables, such that the covariances restrict higher order dependencies.
Alternative approach if you can calculate the joint probabilities (can be used regardless of the signs of the $c_i$): look for the values of $(x_1,x_2,x_3)$ which maximise $\sum c_i x_i$; suppose that these values have joint probability $p$. Then approximate $\mathbb{E}[e^y]\approx p\exp(\sum c_i x_i)$. In your example I get $0.2\times \exp(12)\approx 32551$, which doesn't seem too bad.
Comment: I like your alternative approach. I will try to see if it works in my problem. I wonder if the structure of my problem $y=\tfrac{1}{2}\text{tr}(R^TCR)$ can be exploited better.


Random image with link on load, without loading them all

Question: I do not want all of the images to load, only the one randomly chosen image. I cannot figure out if the other images are hidden but loading in the background. Each image needs a hyperlink attached.

Comment: why have you tagged this as jQuery? Never-mind how terrible this is, there certainly isn't any jQuery involved.
Comment: I apologize, been coding all day and forgot its not jquery related. Just looking for some help.
Answer: Only the chosen image (the one in b[i]) should get loaded. You only have simple uninterpreted strings until you call document.write, then one of your strings gets interpreted as HTML and the browser will discover that there is an image to load.
You could clear your browser cache and watch your web server's access logs to verify my claims.
Answer: I don't see anything wrong with your existing code.  Only one image will get written in the document.write() call.  Everything else is just a string in memory.  The code could be cleaned up a lot through.  I would suggest changing your code to this:
writeRandomImage(baseURL, max) {
    var rand = Math.floor(Math.random() * max) + 1;
    var str = "";
    document.write(str);
}

writeRandomImage("main_theme/top_gallery/gallery", 5);

This should also eliminate any concerns about any other images being loaded since the other URLs aren't even constructed.
Comment: Elegant! But how would I pass custom links to each image?
Comment: I don't understand your question.  This function was based on the example you posted.  If you want to change the baseURL, just pass a different value in the function call to writeRandomImage.  If you want each image to be completely different and not algorithmically related as in your example, then you can create an array of the candidate URLs, pass that into the function and choose a random index from the array.


Partial Fraction problem expansion dead end

Question: I am having a problem solving this partial fraction,
$$\frac{18+21x-x^2}{(x-5)(x+2)^2}$$
Which Solves to:
$$\frac{2}{x-5}-\frac3{x+2}+\frac4{(x+2)^2}$$
However no matter how hard I try I always end here,
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Comment: Please type out your last image using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). I have done the first two - you can use this to see how to do your handwritten image which I am struggling to read
Comment: No embedded pictures for computations, please. This is unreadable.
Answer: Consider \begin{align*}\frac{18+21x-x^2}{(x-5)(x+2)^2}&=\frac{A}{x-5}+\frac{B}{x+2}+\frac{C}{(x+2)^2}\\
\iff 18+21x-x^2&=A\cdot(x+2)^2+B\cdot(x-5)(x+2)+C\cdot (x-5)\\
\iff -x^2+21x+18&= x^2\cdot (A+B)+x\cdot(4A-3B+C)+(4A-10B-5C)
\end{align*}
Since the coefficients of the polynomials must be identic \begin{cases}-1=A+B\\
21=4A-3B+C\\
18=4A-10B-5C\end{cases}
Now it's really a matter of solving the system. You might want to use for instance the Gaussian Algorithm. Notwithstanding, I believe that this can be solved faster: Observe that after multiplying the second equation with $5$ and adding it to the third, you obtain $$123=24A-25B$$ Combined with the first equation $-1=A+B$, you have $A=2, B=-3$. Substitute these values in another equation containing $C$ in order to obtain $C=4$.
Answer: $$\frac{18+21x-x^2}{(x-5)(x+2)^2}=\frac{-x^2-4x-4+25x+22}{(x-5)(x+2)^2}=$$
$$=-\frac{1}{x-5}+\frac{25x+22}{(x-5)(x+2)^2}=-\frac{1}{x-5}+\frac{25x-125+147}{(x-5)(x+2)^2}=$$
$$=-\frac{1}{x-5}+\frac{25}{(x+2)^2}+\frac{147}{(x-5)(x+2)^2}=$$
$$=-\frac{1}{x-5}+\frac{25}{(x+2)^2}+\frac{21}{x+2}\left(\frac{1}{x-5}-\frac{1}{x+2}\right)=$$
$$=-\frac{1}{x-5}+\frac{4}{(x+2)^2}+3\left(\frac{1}{x-5}-\frac{1}{x+2}\right)=$$
$$=\frac{2}{x-5}+\frac{4}{(x+2)^2}-\frac{3}{x+2}.$$
Answer: $$\lim_{x\to5}(x-5)\left(\frac a{x-5}+\frac b{x+2}+\frac c{(x+2)^2}\right)=a=\lim_{x\to5}\frac{18+21x-x^2}{(x+2)^2}=\frac{98}{49}=2.$$
$$\lim_{x\to-2}(x+2)^2\left(\frac a{x-5}+\frac b{x+2}+\frac c{(x+2)^2}\right)=c=\lim_{x\to-2}\frac{18+21x-x^2}{x-5}=\frac{-28}{-7}=4.$$
Then
$$\frac{18+21x-x^2}{(x-5)(x+2)^2}-\frac2{x-5}-\frac4{(x+2)^2}=-\frac3{x+2}.$$


Constructing rel {0,1} homotopies

Question: I was told to do this exercise:

Given paths $\alpha, \beta :I \rightarrow G$ and $e$ the constant closed path given by $e: I \rightarrow G; t \mapsto 1$, construct the rel {0,1} homotopy
$$m(\alpha) : \alpha \bullet e \simeq \alpha : [0,1] \rightarrow G$$
where $\bullet$ denotes the concatenation path.

Now, the answer turns out to be:
$$m(\alpha)(s,t) =
\begin{cases}
 \alpha(\frac{2s}{1+t},t)&\text{if}\, 0\leq s \leq \frac{1+t}{2}, 0\leq t\leq1\\
 1&\text{if}\, \frac{1+t}{2}\leq s \leq 1, 0\leq t\leq1\\
\end{cases}$$
There is a few points about this construction that are confusing to me:

How was this constructed?
$\alpha(t)$ seems two require two inputs rather than one, which I don't get because the domain of  $\alpha(t)$ is the unit interval so it should only require one input variable.
Comment: What is the purpose of $\beta$?
Comment: @PaulFrost ah sorry, $\beta$ is just another path. It is not relevant for the question.
Answer: First you should clarify what $1 \in G$ is. I guess $G$ is a topological space and $1$ is a fixed basepoint. Or do you mean a toplogical group with neutral element $1$? If that should be the case, then it is just a special case of the general topological case.
The definition of the homotopy is in fact wrong. We have to replace $\alpha(\frac{2s}{1+t},t)$ by $\alpha(\frac{2s}{1+t})$. The idea behind this definition is simple: At time $t$ divide $[0,1]$ into the subintervals $I_1(t) = [0,\frac{1+t}{2}]$ and $I_2(t) = [\frac{1+t}{2},1]$. On $I_1(t)$ take $\alpha$ and on $I_2(t)$ take $e$. For $t = 0$ we have $I_1(0) = [0,\frac{1}{2}], I_2(0)  = [\frac{1}{2},1]$ and $m(\alpha(s,0) = (\alpha \bullet e)(s)$. For $t = 1$ we have $I_1(1) = [0,1], I_2(1)  = [1,1]$ and $m(\alpha(s,1) = \alpha(s)$.

Constructing rel {0,1} homotopies


SARIMAX mathematical equation

Question: Below is the summary of my SARIMA model:
Series: diff(log(data_final_ts))
ARIMA(0,0,2)(0,0,2)[4] with non-zero mean

Coefficients:
          ma1     ma2     sma1     sma2  intercept  exogeneous_var1  exogeneous_var2
      -0.7756  0.2152  -0.5155  -0.4023     0.0413           -1e-04           0.0028
s.e.   0.1358  0.1782   0.2985   0.2311     0.0068            0e+00           0.0347
      exogeneous_var3  exogeneous_var4
              -0.0054           0.0012
s.e.           0.0035           0.0049

sigma^2 estimated as 0.0001283:  log likelihood=182.13
AIC=-344.26   AICc=-339.68   BIC=-323.49

Training set error measures:
                        ME       RMSE         MAE      MPE     MAPE      MASE        ACF1
Training set -0.0002763522 0.01042586 0.008296043 83.07064 116.4007 0.4182354 0.006248187

I want to know if the following model equation is correct:
$$(1-B)(1-B^4)Y_t=(1+\phi_1 B^4+\phi_2 B^8)(1+\theta_1 B+\theta_2 B^2)e_t+\text{const}+\beta X_t$$
with $\text{const}$ being the mean of $Y_t$ and with $X_t$ including an intercept and a few exogenous variables.
Comment: Related question [here](http://stats.stackexchange.com/questions/228667/how-to-put-the-coefficients-of-an-sarima-model-with-exogeneous-variables-in-an-e).
Comment: The leading two pairs of brackets should not be there. Why did you include them? They are for first differencing and for autoregressive terms, none of which appears in your model.
Answer: Your model is a regression with SARIMA errors (rather than a SARIMAX model) and is given by the following equations:
$$
\begin{aligned}
y_t &= 0.0413 - 0.0001 x_{1,t} + 0.0028 x_{2,t} - 0.0054 x_{3,t} + 0.0012 x_{4,t}  + u_t, \\
u_t &= (1 - 0.7756\text{B} + 0.2152\text{B}^2)(1 - 0.5155\text{B}^4 - 0.4023\text{B}^{4\cdot2}) \varepsilon_t.
\end{aligned}
$$
What is left to do is to multiply the terms in brackets in the second equation carefully and to get the time indices right due to the backshift operator $\text{B}$.
(Note that the constant enters the model in a simple way because there are no autoregressive terms in the model. If there were some, the expression would be a bit more complicated. See Rob J. Hyndman's blog post "Constants and ARIMA models in R".)
Edit: It looks like the variable supplied to the arima function that produced the output in the OP was a first difference of some other variable. Therefore, the model for the original (nondifferenced) variable would contain $(1-\text{B})$ in front of $y_t$.
Comment: SARIMAX models are a bit tedious and hence I cannot guarantee I did not make a mistake on the way. If I missed something, please notify me so that I could correct it.
Comment: Thanks for the quick answer and for the two first term i taught they where the Non-seasonal diff and the seasonal diff terms like in the link below ? https://www.otexts.org/fpp/8/9 s
Comment: @someone, but your model has `d=0` and `D=0`. Although now I see that your dependent variable is differenced *outside* the SARIMAX model (which you have not mentioned explicitly). If you ran the SARIMAX model on raw data, there would be one extra $(1-B)$ in front of $y_t$.
Comment: OK so the fact that i diff and seasonally adjusted the serie i don't have to put the 2 first terms ?
Comment: @someone, You posted a question about the model, and I answered it as such. Now  what you have done to the data before running the model is another issue.  If you differenced it, I gave the answer already. If you seasonally differenced it as well, I guess you know what to do.
Comment: Thanks a lot Richard Hardy i wasn't clear and didn't specifie what i did to the data before running the arima model. thanks again for your time !
Comment: @someone, no problem, I am glad I could help!

SARIMAX mathematical equation


How to decide we have to choose frame work or dynamic library

Question: can you just tell me for which type of requirement we should choose framework or dynamic library? I mean when should I decide to use frame work rather than using dynamic library or vice versa?
Thanks in advance.
Comment: If you have any answers worthy of acceptance, that is. Don't just accept answers to drive the number up. http://boredzo.org/blog/archives/2010-03-13/the-green-checkmark-of-acceptance
Comment: Thanks peter for sending that link. I am new to this forum and i have no much idea about this site.:)
Answer: A framework can include resources such as images, sounds, and plist files. A dylib file can't, or at least not easily and not cleanly.
If you're targeting the Mac, make a framework—there's virtually no reason not to. If you're targeting the iPhone, make a static library (which also cannot easily include resources, but frameworks aren't available on the iPhone). If you're targeting anything else (e.g., Linux), you should probably offer both static-library and shared-library targets and let people choose for themselves.


Point Class Coordinates

Question: I have an assignment explaining like this:

Write a definition of a class named Point that might be used to store and manipulate the location of a point on the plane. The point is stored as two coordinates: x and y. You will need to declare and implement the following methods:

Two constructors:
a. no-argument constructor that sets the point coordinates to (0,0), and
b. a constructor that takes x and y coordinate of the point and sets member
variables.
Method set that sets the private data after an object of this class is created.
A method to move the point by an amount along the vertical and horizontal directions specified by the first and second arguments: move(double dx, double dy)
The method to rotate the point by 90 degrees clockwise around the origin.  Hint: when point is getting rotated 90 clockwise around the origin the following  changes happen to its coordinates:   xrotated = y;     yrotated = -x .
two accessor methods to retrieve the coordinates of the point.

It should be 2 different call. these items on second one (not main class)
I will call this on main class. (I do that).
This is my code but I dont understand what I should do next.
private double x;
private double y;

public Point(double initialX, double initialY) {
    x = initialX;
    y = initialY;
}

public Point() {
    x = 0;
    y = 0;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

public void move(double dx, double dy) {
    x += dx;
    y += dy;
}

Comment: You're doing great ! Now you just have to implement `setX` , `setY`, and the `rotateBy90` methods. What problem are you having in doing that ?
Comment: I sent my code I think it is working but can you check if you are available
Answer: You have almost everything, good job. For the rotate by 90 function, you're given a pretty good clue about what to do. Imagine you have a point (1,2), and you rotate it. you'll end up with (2,-1). if you rotate it again, you'll get (-1,-2). once more gives you (-2,1), and a fourth 90 degree rotation gives (1,2), which is what you started with. come up with a function that does this. It shouldn't be longer than 3 lines.
The setter functions (functions used to set, or change, the values) are simply functions you can use to set the values of the point. so, you'd have a function "setX(...) { ... }" and a function "setY(...) { ... }". These should be very straightforward.
Feel free to ask further questions if you're still confused.
Comment: so If I have imagine point : (2,1)
first 90 clockwise  (-1,2)
sec 90 clockwise  (-2,-1)
third 90 clockwise (1,-2)
and last will be (2,1)  am I correct?
Comment: No, that's what happens when you rotate counterclockwise. The assignment asks that you rotate a point clockwise, and the example I gave   is what should happen.
Comment: I added this 2 method too
public double setX()
 {
  double xrot;
  return xrot = y;

 }

 public double setY()
 {
  double yrot;
  return yrot=-x;
 }
Comment: your function setX should take in a new value for x. imagine i wanted to set x to 5. then, all setX should do is make x = 5.
Comment: The functions setX and setY as defined in your comment aren't right. It's like you're confusing what rotate needs to do and what the setters need to do. Those functions shouldn't have anything to do with each other.
Comment: I am totally lost right now @Erik. can you write down here for me? just last part
Comment: I just edited my code under answer section. what about now? If it is still wrong I need correct one :(
Comment: We're going to discuss the "setX" function right now. Imagine I'm using your code for something. I have a point in my code. I decide I need to change the value of the x part of my point. So, i call the setX function on my point. First, what does your function need to know? Second, what does your function need to do?
Answer: private double x;
    private double y;
public Point(double dx, double dy) {
    x = dx;
    y = dy;
}

public Point() {
    x = 0;
    y = 0;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

public void SetX(double dx)
{
x = dx;
}

public void SetY(double dy)
{
y = dy;
}

public void move(double dx, double dy)
{
x = x + dx;
y = y + dy;
}

public double rotateX()
{
    double temp = x;
    x=y;
    y=temp;

return x;
}

public double rotateY()
{
    y=-y;

return y;
}

main page
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Point p = new Point();
    p.SetX(50);
    p.SetY(17);

    System.out.println("X and Y coordinates are :  \n("+p.getX()+","+p.getY()+")");
    System.out.println("after 90 degree clockwise rotate: ");
    System.out.println(p.rotateX()+","+p.rotateY());

Point Class Coordinates


Testing resource cookbook with Policyfiles & ChefSpec

Question: This problem arises when you:

Write a library cookbook (i.e. it has no recipes apart from a no-op default.rb)
Create a test cookbook under test/fixtures/cookbooks/ to exercise the library.  That is test/fixtures/cookbooks/test/recipes/system.rb
Write a ChefSpec spec that describe 'test::system'
Use Policyfiles rather than Berkshelf.

When using Berkshelf you would use group :integration do ... end to include the test cookbook only when running tests.
How do you write a Policyfile that only references the test cookbook when running tests?
Right now I have my policyfile always packaging the test cookbook.  Not ideal but acceptable to get something that just works in a test environment.
Not sustainable over the longer term.
Appreciate any hints, tips or incantations.
Answer: Create two Policyfiles.
One of them contains the recipes/attributes that you would run on a "real" node. The other contains what is needed to exercise the cookbook in test kitchen.
You can specify a Policyfile path in kitchen.rb.
suites:
  - name: default
    provisioner:
      policyfile_path: policies/kitchen.rb


O que são componentes de software?

Question: "Componente" é uma palavra usada em vários contextos e com isso imagino que fique difícil definir genericamente.
Por definição é uma parte que compõe um todo. Por exemplo, um subsistema.
Fala-se também que componentes são reutilizáveis. Fala-se também em "arquiteturas componentizáveis" ou "componentizadas".
Do Quora retirei a seguinte definição, que ajudou até certo ponto.

Um componente é um sistema autocontido que tem um ou mais canais de entrada e um ou mais canais de saída. Sem as entradas ele não tem nada para fazer. Sem as saídas ele não pode servir a um propósito.
Observe que uma função recebe entrada através de seus argumentos e retorna um resultado, então ela também tem entradas e saídas. Assim que recebe uma entrada ela retorna uma saída. A entrada e saída caminham sempre casadas.
Um componente verdadeiro pode se comportar dessa maneira também, mas os canais de entrada e saída podem também operar independentemente um do outro - isto é, as saídas não precisam caminhar casadas com as entradas.
O ponto essencial é que um componente pode receber entradas de um ou mais canais e enviar saídas para um ou mais canais, mas o que acontece entre essas operações é escondido das vistas. As preocupações do componente são todas dele mesmo - uma caixa preta para o mundo. Tudo o que o mundo exige é um contrato (do que ele precisa e o que ele fornece) através do qual algum uso pode ser feito dele em um sistema maior de componentes ligados.
Um típico DVD player é um componente. Ele recebe entrada através de um DVD inserido em sua gaveta e do seu controle remoto e retorna saídas de áudio e vídeo. Um componente de software não é diferente; entretanto, deve-se notar que seus canais de entrada/saída são tipicamente assíncronos.

Enfim, o que são componentes?
Quais exemplos do âmbito do software podemos usar para ilustrar os mesmos?
Quando sei que estou desenvolvendo um componente?
Comment: Relaciondas: [O que são "unidades de código"?](https://pt.stackoverflow.com/q/216315/91) e [O que são módulos na programação?](https://pt.stackoverflow.com/q/129254/91)
Comment: Relacionada: [Is there a difference between a component and a module?](https://softwareengineering.stackexchange.com/q/178927/93338)
Comment: Me parece que componentes e módulos são conceitos fáceis de confundir.
Answer: A definição "oficial" dada numa conferência sobre Componentes em 1996 é:
"Um componente é uma unidade de composição com interfaces especificadas contratualmente e com dependências de contexto explícitas apenas Um componente de software pode ser implantado [deployed] de forma independente e está sujeito à composição por terceiros".
Basicamente componentes de software é um pedaço de software independente, mas que pode ser usado por outros softwares.
Se assemelha muito a uma biblioteca, ou seja, uma pessoa cria um componente para acessar um banco de dados. Ao invés de eu criar uma classe ou um código para fazer o acesso ao banco de dados, eu incluo esse componente com o código já criado para fazer acesso ao meu banco de dados.
É um subconjunto de um software porque pode ser reutilizado, pode estar contido em um software, mas independente porque funciona também sozinho/ separado de outros sistemas. Componentes de software são focados em reutilização.
Este link da UFCG dá o conceito por diversos autores (incluindo a definição que coloquei):
http://www.dsc.ufcg.edu.br/~jacques/cursos/map/html/comp/definicoes.htm
Já neste link dá o mesmo exemplo que eu citei:https://www.componentsource.com/pt-br/help-support/about-us/components .Lá está escrito assim no subtítulo CBD (Component-Based Development):
"Por exemplo, se um programador criar um componente para acessar um cliente em um banco de dados corporativo, nenhum outro programador terá que escrever tal funcionalidade novamente."

Por fim este link também fala como ela supri as deficiências do desenvolvimento com paradigma de POO, que é o mais bem aceito atualmente: https://www.maxwell.vrac.puc-rio.br/5244/5244_3.PDF
Comment: Parece que toquei num assunto que rescende a um certo mofo...  componentes CORBA... coisa incomum de se ver... Isso me levanta a dúvida, alguém aqui já mexeu com componentes CORBA alguma vez? Se disser que são componentes gerais alguns vão dizer que sim, mas CORBA acredito que quase ninguém...
Comment: Pergunto isso para entender se componentes têm uso habitual dentro dessa definição que foi passada. Não é uma pergunta dirigida ao autor da resposta.

O que são componentes de software?


Trouble with some Functions

Question: so I'm trying to call my OptionA function within a if statement in my getOption function but i get a error on line 59 saying "error expected identifier or '(' before '{'" so im just wondering how i can get my code to print out my line in the OptionA function. Thanks!
#include <stdio.h>
#include <stdlib.h>

//function declaration
char getOption (void);
double OptionA;

int main(void)
{
  //local declaration
  getOption();

  return 0;
}//main

char getOption (void)
{
  //local declaration
  char option;

  //statements
  printf("\nMain Menu\n");
  printf("  A. Find the square root of a positive number.\n");
  printf("  B. Find the inverse of a positive number.\n");
  printf("  Q. Quit.\n\n");
  printf("Enter choice:");
  scanf(" %c", &option);
  if ( option == 'a' || option == 'A')
  {
     OptionA;
  }
  else if ( option == 'b' || option == 'B')
  {
    printf("\nnice");
  }
  else if ( option == 'q' || option == 'Q')
  {
    exit(0);
  }
  else
  {
    printf("\nError. Invalid Selection.\n");
    getOption();
  }
  return option;
}

double OptionA;
{
  printf("\nHey, it works.");
}

Comment: If you're just learning C, do pay very close attention to formatting, especially *indentation*. This is extremely important for readability. C is a language that is indifferent to your mistakes, it will punish you severely, so keeping things orderly and organized is critical. Every single character matters. The mistake you have here would be made obvious if you indented the code properly, it'd simply look wrong.
Comment: There is no `OptionA` function anywhere. Why do you think that it's a function?
Answer: OptionA is not a function, it's a double.
double OptionA;

To declare a function in c, you should use ()
replace :
// PROTOTYPE
double OptionA;
// this is a double, you'd say :
double OptionA();
// this is a function which returns a double;

then in the getOption() function :
if ( option == 'a' || option == 'A')
{
    OptionA();
}

and in the function :
double OptionA()
{
    printf("\nHey, it works.");
}

Hope it helps
Answer:
...call my OptionA function...

OptionA is not a function the way you have declared it, called it, and defined it. The proper syntax for any function is:
return_value FunctionName (argument_data_type argument1, etc...)

If you do not want to pass any argument to your function, then you can have an empty pair of parentheses right after the function name, or you can have the keyword void inside the parentheses that come right after function name. However, the parentheses are required, else your function name will be confused for a variable by the compiler when declared (double variable is a variable of type double, and so is double function).
When the error is dissected:

error expected identifier or '(' before '{'

It tells you that a parenthesis pair is required after the function name and the opening curly brace of the function body.
To fix this error, you should add a pair of parenthesis right after the function name at all points in your code where the function is called, declared, or defined. Change your function declaration at the top of your program from:
double OptionA;

To:
double OptionA(); // the pair of parenthesis is added here

Or:
double OptionA (void); // (void) is the same as () for this purpose.

Also change your function call to:
if ( option == 'a' || option == 'A')
{
    OptionA (); // pair of parenthesis added here too
}

And change your function header when you define it to:
double OptionA() // pair of parenthesis added he right before the function name
{
    printf("\nHey, it works.");
}

Comment: Actually, there's a big (BIG, ***BIG***) difference between `double OptionA();` and `double OptionA(void);` in C.  Both declare a function called `OptionA`, and both declare that the function returns a `double`.  However, the empty-brackets `()` version says nothing more; the function could have any (fixed) number of arguments of any type.  By contrast, the filled-brackets `(void)` version declares a prototype for the function and specifies that it takes no arguments at all.  After the declarations, the first allows `double x = OperatorA(1.23, "AAA");` and the second doesn't.
Comment: @JonathanLeffler Yeah, but those parameters cannot be used inside the function definition, since they are not given a variable name or specific data type to call jnside a function. Hence, they are unused arguments. For the purpose of OP, both methods give the same end result (I tried and tested them both).
Comment: I disagree with your assessment.
Comment: The updated answer still says "(void) is the same as () for this purpose" and it is therefore still inaccurate.  They are *not* the same!  One is a prototype declaration, the other is just a function declaration.  One provides error checking that the other does not and cannot provide.
Comment: @JonathanLeffler is it better __now__?
Comment: While you claim that empty parentheses and `(void)` are the same, your answer is wrong.

Trouble with some Functions


Appwarp cannot create room

Question: I've created a small singleplayer game which I'm now trying to adapt to multiplayer.
It's turned based so I'm using Appwarp.
I have this code but I get 'Null pointer exception' for this line:
SC_AppWarpKit.CreateTurnBaseRoom("BattleShips", userName, 2, null, 60);

Note that I did not create game objects for AppWarpKit, searched for examples online but could not find anything similar.
APIKEY and SECRETKEY are empty for privacy reasons.
private string apiKey = "";
private string secretKey = "";
private string email = "@gmail.com";
private string userName = "mrnobody";
private string roomId = "";
private List<string> rooms;
private string opponentName = "";

private bool isMyTurn = false;

void OnEnable()
{
        SC_Listener_App42.onCreatedUserApp42 += onCreatedUserApp42;
        SC_Listener_App42.OnExceptionFromApp42 += OnExceptionFromApp42;

        SC_Listener_AppWarp.onConnectToAppWarp += onConnectToAppWarp;
        SC_Listener_AppWarp.onDisconnectFromAppWarp += onDisconnectFromAppWarp;
        SC_Listener_AppWarp.OnMatchedRooms += OnGetMatchedRoomsDone;
        SC_Listener_AppWarp.OnSubscribeToRoom += onSubscribeToRoom;
        SC_Listener_AppWarp.OnUnSubscribeToRoom += onUnSubscribeToRoom;
        SC_Listener_AppWarp.OnJoinToRoom += OnJoinToRoom;
        SC_Listener_AppWarp.OnLeaveFromRoom += OnLeaveFromRoom;
        SC_Listener_AppWarp.OnCreateRoomDone += OnCreateRoomDone;
        SC_Listener_AppWarp.onGetLiveRoomInfo += OnGetLiveRoomInfo;
        SC_Listener_AppWarp.OnSendPrivateUpdate += OnSendPrivateUpdate;
        SC_Listener_AppWarp.OnStartGameDone += OnStartGameDone;
        SC_Listener_AppWarp.OnStopGameDone += OnStopGameDone;
        SC_Listener_AppWarp.OnRoomCreated += OnRoomCreated;
        SC_Listener_AppWarp.OnUserJoinRoom += OnUserJoinRoom;
        SC_Listener_AppWarp.OnUserLeftRoom += OnUserLeftRoom;
        SC_Listener_AppWarp.OnPrivateUpdateReceived += OnPrivateUpdateReceived;
        SC_Listener_AppWarp.OnPrivateChatReceived += OnPrivateChatReceived;
        SC_Listener_AppWarp.OnGameStarted += OnGameStarted;
        SC_Listener_AppWarp.OnGameStopped += OnGameStopped;
        SC_Listener_AppWarp.OnSendMove += OnSendMove;
        SC_Listener_AppWarp.OnMoveCompleted += OnMoveCompleted;
}

void OnDisable()
{
    SC_Listener_App42.onCreatedUserApp42 -= onCreatedUserApp42;
    SC_Listener_App42.OnExceptionFromApp42 -= OnExceptionFromApp42;

    SC_Listener_App42.OnExceptionFromApp42 -= OnExceptionFromApp42;
    SC_Listener_AppWarp.onConnectToAppWarp -= onConnectToAppWarp;
    SC_Listener_AppWarp.onDisconnectFromAppWarp -= onDisconnectFromAppWarp;
    SC_Listener_AppWarp.OnMatchedRooms -= OnGetMatchedRoomsDone;
    SC_Listener_AppWarp.OnSubscribeToRoom -= onSubscribeToRoom;
    SC_Listener_AppWarp.OnUnSubscribeToRoom -= onUnSubscribeToRoom;
    SC_Listener_AppWarp.OnJoinToRoom -= OnJoinToRoom;
    SC_Listener_AppWarp.OnLeaveFromRoom -= OnLeaveFromRoom;
    SC_Listener_AppWarp.OnCreateRoomDone -= OnCreateRoomDone;
    SC_Listener_AppWarp.onGetLiveRoomInfo -= OnGetLiveRoomInfo;
    SC_Listener_AppWarp.OnSendPrivateUpdate -= OnSendPrivateUpdate;
    SC_Listener_AppWarp.OnStartGameDone -= OnStartGameDone;
    SC_Listener_AppWarp.OnStopGameDone -= OnStopGameDone;
    SC_Listener_AppWarp.OnRoomCreated -= OnRoomCreated;
    SC_Listener_AppWarp.OnUserJoinRoom -= OnUserJoinRoom;
    SC_Listener_AppWarp.OnUserLeftRoom -= OnUserLeftRoom;
    SC_Listener_AppWarp.OnPrivateUpdateReceived -= OnPrivateUpdateReceived;
    SC_Listener_AppWarp.OnPrivateChatReceived -= OnPrivateChatReceived;
    SC_Listener_AppWarp.OnGameStarted -= OnGameStarted;
    SC_Listener_AppWarp.OnGameStopped -= OnGameStopped;
    SC_Listener_AppWarp.OnSendMove -= OnSendMove;
    SC_Listener_AppWarp.OnMoveCompleted -= OnMoveCompleted;

}

void Start ()
{
    SC_App42Kit.App42Init(apiKey,secretKey);
    SC_AppWarpKit.WarpInit(apiKey,secretKey);
    SC_AppWarpKit.CreateTurnBaseRoom("BattleShips", userName, 2, null, 60);
}

In a separate DLL folder I have:
App42_Unity3D_SDK_2.9.1.dll
AppWarpUnity.dll
Please assist.
Answer: Figured it out.
Was indeed using an incorrect DLL and needed to change the function call:
SC_App42Kit.App42Init(apiKey,secretKey);
    SC_AppWarpKit.WarpInit(apiKey,secretKey);
    SC_AppWarpKit.connectToAppWarp(userName);

The call to create room and so on was moved to the 'connectToAppWarp' callback.

Appwarp cannot create room


javascript: actions being run on elements for which the if's condition was not met

Question: I have the following if-test
$("div#groupA > ul").each(function(){
    if (!($("div#groupA > ul").css("display")==="none")) {
        $('div#groupA > ul > input[value="9999"]').remove();
    }
});
$("div#groupA").fadeIn();

OR
$("div#groupA > ul").each(function(){
    if ( $("div#groupA > ul").css("display")!=="none" ) {
        $('div#groupA > ul > input[value="9999"]').remove();
    }
});
$("div#groupA").fadeIn();

But both are removing <input value="9999">s that are in other divs outside of
.
How do I get it to remove only <input value="9999">s that are inside
?
Thanks!
Answer: Try this:
$('#groupA').find('ul').each(function(){
    if ($(this).is(':visible')) {
        $(this).find('input[value="9999"]').remove();
    }
});

Ease up on the super-specific selectors. They make sense for CSS but they make excessive use of sizzle and aren't as optimal as using JQuery's native traversal functions.
div#groupA > ul > input[value="9999"] makes no sense. The > symbol means the following is a direct child of the parent. Odds are your input is inside something else, like an li.
Comment: Post your HTML man. If this code doesn't work, it's your DOM that's the problem.
Comment: I tried .is(':visible') in every which way, and it just would not work, so I had to stick with the .css("display")!=="none")
Answer: I was doing something unusual with the switch statement that encased this.
switch(true){
    case (q1===0):
        // do some stuff
        // purposefully no break
    case (this.value==="bar"):
        $("div#groupA > ul").each(function(){
            if ( $("div#groupA > ul").css("display")!=="none" ) {
            $('div#groupA > ul > input[value="9999"]').remove();
            }
        });
        $("div#groupA").fadeIn();
        break;
    case (this.value==="foobar"):
        // do some other stuff
        break;
    default:
        // do some more other stuff
        break;
}

The swtich(true) was working fine, except when I did an evaluation inside of a case. Then it crapped itself (and only did bits and pieces of the if-statement).
What I ended up doing was:
if(q1===0){
    // do some stuff
}
switch(this.value){
    case ("bar"):
        $("div#groupA > ul").each(function(){
            if ( $("div#groupA > ul").css("display")!=="none" ) {
            $('div#groupA > ul > input[value="9999"]').remove();
            }
        });
        $("div#groupA").fadeIn();
        break;
    case ("foobar"):
        // do some other stuff
        break;
    default:
        // do some more other stuff
        break;
}

btw, sorry for not posting back right away: it never e-mailed me when there was a new response.


Delete Remote Branch

Question: I need to delete a remote branch, and found this technique:

git push origin :the_remote_branch

I tried passing it to Networks Push method in the following forms, but nothing seems to work (options is my login credentials):
_repo.Network.Push(_repo.Network.Remotes["origin"], "origin/:NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], ":NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], ":origin/NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], ":refs/remotes/:origin/NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], ":refs/remotes/origin/NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], "refs/heads/:origin/NewBranchForDeletion", options)
_repo.Network.Push(_repo.Network.Remotes["origin"], "refs/heads/:NewBranchForDeletion", options)

And a few other options.  I cannot get it to work at all, it returns errors such as (for the ":NewBranchForDeletion" method):

Not a valid reference "NewBranchForDeletion"

Update:
Thanks to @Rob for finding me this comment on LibGit2Sharp's repo: https://github.com/libgit2/libgit2sharp/issues/466#issuecomment-21076975
The first option fails with a NullReferenceException on objectish, and using string.Empty for objectish results in the error mentioned above.  The second option is what I am trying, except I am using the version with HTTPS validation:
repo.Network.Push(repo.Remotes["my-remote"], objectish: null, destinationSpec: "my-branch");

// Or using a refspec, like you would use with git push...
repo.Network.Push(repo.Remotes["my-remote"], pushRefSpec: ":my-branch");

Comment: Yes.  `_repo.Network.Push(branch, options);`  Hmm, I'll try that.
Comment: Have you considered the `public virtual void Push(Remote remote, string pushRefSpec)` overload? Passing a `:refs/heads/branch_to_delete` refspec should work.
Comment: I don't know this library, but why are you calling `Push` twice per line ? It seems to me like the solution would be along the lines of `Push(_repo.Network.Remotes["Origin"], "", "NewBranchForDeletion", options)`
Comment: Whoops, copy/pasta error.
Comment: Alternatively, do you have a working solution for a non-deleting push? Something that mimics `git push origin dev:master` ?
Comment: This seems to have the solution: https://github.com/libgit2/libgit2sharp/issues/466#issuecomment-21076975
Comment: @Rob I appreciate your help, but that has exactly the same error.  In fact, the second option is what I was currently trying.  I will update my question with this.
Comment: Hmm, in that case it seems like it's a bug - might have to lodge an issue with the maintainers (since the solution at least used to work, it appears)
Comment: The maintainers watch the tag, so they should see this soon.
Comment: There doesn't seem to be a test in the repo for it yet. =( https://github.com/libgit2/libgit2sharp/blob/vNext/LibGit2Sharp.Tests/PushFixture.cs
Comment: @nulltoken That worked!  I had tried `refs/heads/:branch_to_delete` before, which didn't work, I didn't think of that option.  Please post that as the answer.
Answer: As stated in the documentation, a refspec "Specif(ies) what destination ref to update with what source object. The format of a <refspec> parameter is an optional plus +, followed by the source object <src>, followed by a colon :, followed by the destination ref <dst>."
It also mentions that "Pushing an empty <src> allows you to delete the <dst> ref from the remote repository."
Considering these above, using the void Push(Remote remote, string pushRefSpec) overload, and passing :refs/heads/branch_to_delete as the pushRefSpec should do the trick.

Delete Remote Branch


How to change #weight of fields added to user register page by form_alter()?

Question: I have created some fields on my user registration page named like -
First Name (machine name - field_first_name),
Last name (machine name - field_last_name) etc..
I want to change their <code>#weight</code> according to me to appear at the place where I like them to be from the form_alter function at my custom module..
For the default name & email I used -
<code>$form['account']['name']['#weight'] = 7;
$form['account']['field_first_name']['#weight'] = 8;
</code>
& it worked..
But If I am using for added fields in this way like -
<code>$form['account']['field_first_name']['#weight'] = 6;
</code>
It's not working...
Can I get any help in this ?
Comment: it depends on where you are keeping the fields. if it is with in a fields set then the weight will only be effected with in the fields set and not out side of it.
Comment: These are not inside the fieldset
Comment: account as a whole is in a group which contains the name password etc. the one we add might be out side of that...
Comment: @MohammedShameem - You were right. It's just independent and I could set the #weight by $form['field_first_name']['#weight'] = 6; , please give answer...I will accept...
Answer: Account as a whole is in a group which contains the name password etc. The one we add might be out side of that. That is why it is not effecting the weight.
Answer: Or you can copy the field in another "container field" and change the weight , something like this:
<code>   $form['profile_one']['account'] = $form['account'];
   $form['profile_one']['account']['#weight'] = 200;

   // Hide login form from this render.
   $form['account']['#type'] = 'hidden';
</code>


Phrygian dominant scale with a major seventh

Question: The Phrygian dominant scale with a major seventh instead of a minor seventh is formed by:

a root
a minor second
a major third
a fourth
a fifth
a minor sixth
a major seventh.

My questions are:

what is the name of this scale? Is it a mode of an other scale?
Are there some known pieces using it?
Are there some known or standard licks over this scale?

Moreover, by keeping the degrees I, III, IV, V, and VII of the above scale, we obtain a kind of pentatonic scale which seems to sound very well.

I have the same questions as the above three for this scale of five
  degrees.
Comment: Harmonic Minor (b2) ?
Answer: This scale is often called double harmonic scale. In my experience (i.e., in popular music) that's the standard name for that scale. Arguably the most famous use of that scale in popular music is Dick Dale's Misirlou.
And, by the way, the double harmonic scale and the Hungarian minor scale are modes of each other.
Answer: The scale is known as the flamenco mode or Major-Phrygian and as far as I am concerned is the most popular variant of that set of notes. Off the top of my head I don't know any songs that contain this scale, but it is used all the time in flamenco music along with Phrygian dominant.
Melody wise, you would probably want to take advantage of how symmetric this scale is which can be achieved by doing any pattern with  scale degrees 1-2-3-4 and 5-6-7-8 since they are the exact same pattern.
Also the 5 note scale you picked out is actually not unique to this mode and is actually contained in the major scale so I really wouldn't consider it anything special in that regard.
Answer: Phrygian dominant with a raised 7th is Thaat Bhairav in Indian classical - of which the famous Raga Bhairav is derived.
Thaat Bhairav employs flattened 2nd and flattened 6th, keeping all other notes natural. Which means you get the following scale:
1 b2 3 4 5 b6 7 1
Hope that answered your question.


VS Code não está fazendo comentários. Alguém já se deparou com esse problema?

Question: Quando adiciono trechos de comentários no código o VS Code não os trada de forma correta.
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
         //comentario..
         /* comentario 2 */

         <title>Design Layout Responsivo</title>

Imagem do codigo
Comment: Posta seu código fonte ai fazendo favor.
Comment:

    //comentario..
    /* comentario 2 */

    Design Layout Responsivo
Comment: Provavelmente o problema pode ser é uma aspa que pode estar quebrada no seu código, e por isso o comentário não irá funcionar, nem sempre o problema está no VSCode, pode ser no código, experimente fazer comentário num arquivo em branco e veja se funciona.
Answer: Comentários HTML são feitos abrindo a tag . Exemplo:

// e /* */ são para javascript (e outras línguas). Exemplo javascript:

Comment: Se respondeu a pergunta, Marca como resposta.
Comment: Muito obrigado....to vindo de outra linguagem rsrs...valeu mesmo


Rigorous Definition of One-Sided Limits

Question: In a typical first-year Calculus course professors typically tend to put a lot of emphasis on making visual connections when working with "one-sided" limits or derivatives. This is something I find particularly distressing as I prefer to think as abstractly as possible, and most professors' emphasis on making visual connections comes at a price.
Professors will typically in their wording, refer to taking limits or derivatives approaching from the left or the right of some point. But left and right has no meaning in Mathematics. While it may make a visual connection, it is fundamentally wrong, a fallacy.

When talking about proving the existence of a limit, using two one-sided limits typical professor would say :

A limit as $x$ approaches some number $a$ exists if and only if, the limit as $x$ approaches $a$ from the left is equivalent to the limit as $x$ approaches $a$ from the right

Stated Mathematically :$$\left(\lim_{x \ \to\  a} f(x) = L\right) \Leftrightarrow \left(\lim_{x \ \to \ a^+} f(x) = L\right) \land \left(\lim_{x \ \to \ a^-} f(x) = L\right)$$
Defined (Fairly) Rigorously Using $\epsilon-\delta$ :
$$\left(\forall \epsilon > 0\  (\exists\ \delta > 0 : 0 <|x-a|<\delta \implies |f(x)-L|<\epsilon)\right) \Leftrightarrow \left[(\forall \epsilon > 0\  (\exists\ \delta > 0 : a-\delta <x<a \implies |f(x)-L|<\epsilon) \land (\forall \epsilon > 0\  (\exists\ \delta > 0 : a <x<a +\delta \implies |f(x)-L|<\epsilon)\right]$$

Question : Is this a more rigorous definition of what professors are talking about when they say "approaching from the left/right". I've attempted to answer this below.
Possible Answer :
Approaching from the left : Taking a sequence of elements as they increase and converge towards an arbitrary element $x$ which is the element acting as the limiting point in the domain $D$ (an ordered set) of $f$.
Approaching from the right : Taking a sequence of elements as they decrease and converge towards an arbitrary element $x$ which is the element acting as the limiting point in the domain $D$ (an ordered set) of $f$.

Is what I've written above correct? If not, then there has to be a deeper more rigorous definition of approaching some number from the left/right. I know that the answer to this question lies in Real Analysis, and while as a first-year undergrad I have some basic knowledge of Real Analysis based on what I've read on my own, I don't have enough to answer this question. I would assume that it would have something to do with convergence of sequences.
If there exists a more formal answer to this, using formal mathematical notation and concepts from Real Analysis, I would really like to see it, as what I've written is very, very loose and non-rigorous.
Comment: What's wrong with the $\varepsilon$-$\delta$ definition you provided?
Answer: The "left/right convergence" notion only applies when taking limits in $\mathbb R$, essentially because of the structure of the real line. The set $(a,+\infty)$ intuitively lies on the right side of $a$.
Formally, $\displaystyle \lim_{x\to a+} f(x) = l \iff \forall \epsilon>0,\exists \delta>0, \forall x\in \mathbb R, x \in (a,a+\delta)\cap D\implies |f(x)-l|<\epsilon$
Is the last line formal enough for you ?
Answer: We usually write definitions in (a kind of) english language in order to save time. All definitions you ever saw are in fact first order logic. The correct definitions are what is written after "Defined (fairly) rigorously".
Answer: $L$ is a right side limit approaching $a$ of a function $f:R\to R$ iff for all $\epsilon>0$, there is some $\delta>0$, such that for all $x$ with $a<x<a+\delta$ , $|f(x)-L|<\epsilon$. Then you can prove uniqueness, etc., and write $L=\lim_{a^+}f=\lim_{x\to a^+}f(x)$. Similar for the left side limit.

Rigorous Definition of One-Sided Limits


creating a bat file or cmd

Question: I wish to create a bat file to create some basic task. When i run this it closes the window. I'm guessing it errors. How can i stop the bat closing the window so i can view the error.
mybat.bat:
echo cd /d d:
echo sencha create jsb -a http://my.local/ext/cutter/app/index.html -p app.jsb3
echo sencha build app.jsb3 -d .

Comment: does it work?  i mean, does it do what you wish it to do?  is the only problem the fact that it closes?
Answer: Batch scripts will close the window itself after running it is not an indication of an error, if you put the word pause at the end of the script the script will stop and wait for you to press a key before proceeding
Answer: Two options:

send output to a file (command > c:\output.log)
Set a delay. In newer versions, it can be done with timeout \t xxx where xxx is the amount of seconds. In older versions, you can produce an effective delay with things like
PING 127.0.0.1 -n 6

where each ping takes about one second... but hey, you don't need precission, right? :)
Both approaches avoid being frenzy on the pause button
Comment: +1 redirecting output
Answer: The answer by Chris is correct.  However if it were actually an error, the pause would not stop the cmd shell from just exiting.  Here's how I troubleshoot this simply without redirecting output (and having to keep opening the output log file):
Run cmd.exe.  Then within the command window, run 'cmd<enter>' a couple more times.  This executes cmd.exe as a child of cmd.exe but within the same command window.
Now call the .bat / .cmd from within the command window, e.g. C:\Temp\mybat.bat  - if it errors it will exit the cmd.exe it was running in and display the error (and any other output) in the window but return processing to the parent cmd.exe process within the same command window.  As there is a parent process the batch window will not just close on error.
Answer: Run it from the commandline (cmd) and it will show you the output and not close when finished. The reason it is closing is because you are simply echoing (printing) stuff to the terminal. It isn't actually DOING anything. Take out all those echoes.
C:\>echo /?
Displays messages, or turns command-echoing on or off.

  ECHO [ON | OFF]
  ECHO [message]

Type ECHO without parameters to display the current echo setting.

creating a bat file or cmd


An irreducible topological space $X$ admits a constant sheaf iff it is indiscrete.

Question: I can't see where I've gone wrong in the following proof. The statement above is wrong, as any topological space can be endowed with a constant sheaf.
Proof. That any set $X$ endowed with the trivial topology admits a constant sheaf is obvious: for any set $E,$ let $\mathscr{F}(X) = E.$
Conversely, suppose that $X$ admits a constant sheaf. Then since $X$ is irreducible, for every nonempty open set $U$ of $X,$ the restriction $\mathscr{F}(X)\to \mathscr{F}(U)$ is a bijection$^1$. We recall that a sheaf is a functor, $\mathscr{F}\colon \mathbf{Ouv}_X^{\text{op}} \to \mathbf{Set},$ where $\mathbf{Ouv}_X$ is the category whose objects are open $U\subseteq X$ and whose morphisms are the inclusions. Functors preserve isomorphisms; therefore $\mathscr{F}(X) \cong_{\mathbf{Set}} \mathscr{F}(U)$ implies that $X \cong_{\mathbf{Ouv}_X} U,$ i.e., $X = U.$

Exercise $2.13$ in Algebraic Geometry I: Schemes, With Examples and Exercises by Ulrich Görtz and Torsten Wedhorn.
Comment: "Functors preserve isomorphisms".

Yes. But you actually use it the other way around.
Comment: For example, if $C$ is any category, the functor $F \colon C \to \mathrm{Set}$ sending any object of $C$ to a fixed singleton set is a perfectly good functor. Further, $F(A) \cong F(B)$ for any objects $A, B$ in $C$, but $A$ and $B$ need not be isomorphic.
Answer: It is not true that $\mathscr{F}(X)\cong\mathscr{F}(U)$ implies $X\cong U$!  "Functors preserve isomorphisms" goes the other direction: if $F$ is a functor and $f:A\to B$ is an isomorphism in the domain category, then $Ff:FA\to FB$ is also an isomorphism, so if $A\cong B$, then $FA\cong FB$.  The converse is not necessarily true.


Assessing differences in slope of a loess (or any smoother) fit

Question: I have continuous data for x (for example "time") and y with several groups. I would like to show/test that the slope of groupC changes over time (is positive and rises) while groups A and B do not. Below is a MRE.
I was thinking about using a GAM, but could need some inspiration of how to formulate this in R. Please note that my real data are a lot more variable than the example in case that is relevant, so it's really about using some sort of smoother and then use this as a basic for assessing differences in slope.
library(tidyverse)

set.seed(1)
data <-
  rbind(data.frame(x=seq(1, 100), y=rnorm(100, 1, 5), group="A"),
        data.frame(x=seq(1, 100), y=rnorm(100, 3, 5), group="B"),
        data.frame(x=seq(1, 100), y=jitter(seq(1, 10, length=100)^3, 1000)/20, group="C"))

data %>%
  ggplot(aes(x=x, y=y, color=group)) +
  geom_smooth() + # any smoother is fine, loess is just an example for viz
  geom_point()

Comment: The problem is that for some intervals of $x$ there are *no* significant differences in slope while for other intervals there *are* significant differences.  Thus, you need to tell us in more detail what you mean by "differences in slope."
Answer: Any continuous function on a compact space can be uniformly approximated as closely as desired by a polynomial. (Stone-Weierstrauss theorem) In this case fit a quadratic to each set and note that only C has significant linear and quadratic coefficients.
library(nlme)
fm <- lmList(y ~ x | group, data = data, pool = FALSE)
fm0 <- lmList(y ~ 1 | group, data = data, pool = FALSE)
Map(anova, fm, fm0)

and here is a plot of the points and fitted lines showing it fits well:
library(ggplot2)
ggplot(data, aes(x, y, col = group)) +
  geom_point() +
  geom_smooth(formula = y  ~ poly(x, 2, raw = TRUE), method = "lm")

(continued after graph)

We can alternately use a gam.  In the case of the data in the question it does not really make any difference but if the data in the question is not representative of your actual problem it may be useful.
library(mgcv)
Map(\(g) summary(gam(y ~ x, data = data, subset = group == g)),
  unique(data$group))

Update
Have added an ANOVA to lm model and added a gam alternative.  Note that both nlme and mgcv come with R so they do not have to be separately installed.
Comment: Polynomial approximations tend to be poor for statistical modeling: polynomials are too rigid (that is, they are determined globally by tiny amounts of local information).  Consider splines instead.
Comment: Did you even read the answer???  It worked very well and is really easy to do.
Comment: It worked well *for this toy example* which was based on a polynomial!  In general, the "smoothers" referred to in the question are *not* polynomials.  Thus, you are proposing a solution that seems to work in one special textbook case but is not going to generalize well to real data.  Moreover, you still haven't answered the question: how do you propose to interpret what "differences in slope" means and how does fitting a polynomial answer that?
Comment: Unfortunately, the Stone-Weierstrass Theorem is useless for statistical analysis: the polynomial basis is just too large and cumbersome to be of any practical use.  There are excellent reasons why you don't commonly see, say, polynomials of the 77th degree used even for enormous datasets.  Indeed, the very concept of a *smoother* precludes using polynomials except locally, because a smoother is supposed to flexibly describe the data within relatively small neighborhoods in a way that is immune to whatever happens beyond them. Piecewise polynomials--splines--are the natural solution.
Comment: Unfortunately, ridiculous polynomial degrees rapidly arise when using polynomials in an effort to smooth even modest datasets -- so implicitly, yes you are suggesting the use of such polynomials.
Comment: I used to believe (1), too, until I tested it.  There's a reason people use splines for smoothing instead of polynomials.  The burden is on you to demonstrate why the rest of the world might be using an inferior procedure.  I can't determine what you are referring to about intervals.
Comment: You can't determine what your own comment means?
Comment: Enough of the snark, please.  I cannot determine what your response to it means.  But evidently the potential for this conversation to yield anything useful is over, so I'm bowing out.
Comment: Have added an ANOVA to the lm model and noticing the request for gam in the question have added that as well.
Comment: It works in the type of case that was illustrated and likely many more since polynomials can uniformly approximate any continuous function on a compact set.  And the best part is that it is one line of code -- two if you add the plot.  Regarding what was asked it was "show/test that the slope of group C changes over time (is positive and rises) while groups A and B do not" which is what is tested here.
Comment: It shows that they are universal approximators. The `poly` function is in the base of R because polynomials are commonly used in statistics.  No one is suggesting the use of 77th degree polynomials.
Comment: Obviously that was not the case here nor would it be for similar curves.
Comment: And two other points: (1) dividing up the domain as would be done with splines involves using up more degrees of freedom and so has lower power.  What that means is that you are less likely to detect differences that exist. It would be more of a last resort than the preferred approach.  (2) Furthermore the purported "problem" of intervals in your comment below the question is not a problem at all in the answer here.


How do you get the tid from a taxonomy term page?

Question: I've got a component on a taxonomy term page and need to use the TID in it's preprocess function.
How do I actually get the tid to save as a variable?
Answer: You can use menu_get_object():
$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  $tid = $term->tid;
}


Extract all urls Href php

Question: How do I convert these links to sha1? and then return to the html already applied with sha1

$dom = new DOMDocument;
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    if (preg_match("/globo.com/i", $link->getAttribute('href'))) {
        $v = $link->getAttribute('href');
        $str = str_replace($v,'http://www.globo.com/?id='.sha1($v),$v);
        $str2 = str_replace($v,$str,$html);
        echo $str2."";
    }
}

Comment: Note that `preg_match('/something/i', $text)` is much slower than a simple `stripos($text, 'something') !== false`, which works completely fine in your situation.
Comment: So you are trying to update an existing url with a new one?
Comment: possible duplicate of [PHP preg_match regular expression problem](http://stackoverflow.com/questions/4286628/php-preg-match-regular-expression-problem)
Answer: You can just put the href back into the element:
$dom = new DOMDocument;
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    $href = $link->getAttribute('href');
    if (preg_match("/globo.com/i", $href)) {
        $newHref = 'http://www.globo.com/?id=' . sha1($v);
        $link->setAttribute('href', $newHref);
    }
}

And then export the finished HTML using saveHTML().
echo $dom->saveHTML();

Extract all urls Href php


How to show that this binomial sum satisfies the Fibonacci relation?

Question:
The binomial sum
  $$s_n=\binom{n+1}{0}+\binom{n}{1}+\binom{n-1}{2}+\cdots$$
  satisfies the Fibonacci relation.

I failed to prove that $\binom{n-k+1}{k}=\binom{n-k}{k}+\binom{n-k-1}{k}$... Any hints or suggestions?
Comment: It is actually very easy, if you have the right formula, which is: $\binom{n-k+1}{k+1}=\binom{n-k}{k}+\binom{n-k}{k+1}$..The proof is two lines long.... The formula you posted is wrong, that's why you failed ...
Comment: A combinatorial proof based on number of tiling of $n\times1$ board by squares and dominos is given in Benjamin, Quinn: Proofs that Really Count; Identity 4, [p.4](http://books.google.com/books?id=FXLGzXwbwIAC&pg=PA4).
Comment: For intuition, consider Pascal's triangle. Each binomial coefficient in the triangle is in exactly one of your $s_n$s, and every term that is in $s_n$ arises as the sum of a term from $s_{n-1}$ and a term from $s_{n-2}$, and this uses each term of $s_{n-1}$ and $s_{n-2}$ exactly once.
Comment: Write their formulas....
Comment: @N.S. But it's messy for me... Are there any combinatorial proofs?
Comment: @N.S. Well...$s_n=\sum_{k\geq 0}\binom{n-k+1}{k}$ Is it wrong? Why $\binom{n-k+1}{k+1}$?
Comment: @MartinSleziak: I was going to give the same suggestion :)
Answer: Consider the words of length $n+1$ with letters 0,1 and no two consecutive 1s.
Prove that they are counted by the Fibonacci numbers.
Now count the same kind of words that contain exactly $k$ letters 1.
Answer: This approach was explained in the above comments by N.S and
and
Henning

We can show $$\sum_{k\ge0} \binom{n-k}k=F_{n+1}$$
by induction.
Note that I did not specify the range for $k$. I am using the usual convention that $\binom pq$ is considered zero whenever $q<0$ or $q>p$. EDIT: After reading Marc van Leeuwen's answer I've realized, that this is true for non-negative $q$ only, so I've change range to $k\ge0$.
$1^\circ$ We can verify $n=-1,0,1,2$ by hand.
$2^\circ$ Inductive step: Suppose $n>1$. We want to show that this is true for $n+1$ and assume validity of the formula for $0,1,\dots,n$.
$$\sum_{k\ge0} \binom{n+1-k}k=\sum_{k\ge0} \binom{n-k}k + \sum_{k\ge0} \binom{n-k}{k-1}=
\sum_{k\ge0} \binom{n-k}k + \sum_{k\ge0} \binom{n-1-(k-1)}{k-1}=
\sum_{k\ge0} \binom{n-k}k + \sum_{j\ge0} \binom{n-1-j}{j}= F_{n+1}+F_n = F_{n+2}.$$

This proof can be visualized as follows: We are computing the sums of terms in Pascal triangle along diagonals.
It suffices to notice that each element on $k$-th diagonal is a sum of an element from $(k-1)$-th diagonal and $(k-2)$-th diagonal.
(I've taken the picture from thesis of my student I supervised some time ago.
I am not sure whether she made the picture herself or found it somewhere on the Internet.)
Answer: We begin with the identity:
$$
\binom{n+1}{k+1} = \binom{n}{k+1} + \binom{n}{k}.
$$
We apply the identity to
$$
s_n=\binom{n+1}{0}+\binom{n}{1}+\binom{n-1}{2}+\cdots
$$
to get
$$
s_n= \underbrace{\color{blue}{\binom{n}{0}} + \color{grey}{\binom{n}{-1}}}_{\text{first term}} + \underbrace{\color{blue}{\binom{n-1}{1}} + \color{brown}{\binom{n-1}{0}}}_{2\text{nd term}} +
\underbrace{\color{blue}{\binom{n-2}{2}} + \color{brown}{\binom{n-2}{1}} }_{3\text{rd term}} + \cdots
$$
Notice that the terms in are $\color{blue}{s_{n-1}}$ and those in brown/red $\color{brown}{s_{n-2}}$. (I had to work out what $s_{n-1}$ and $s_{n-2}$ was in order to catch the pattern, in case you're wondering how I knew). And so we have our fibonacci relation
$$
s_n = \color{blue}{s_{n-1}} + \color{brown}{s_{n-2}}
$$
As for the $\binom{n}{-1}$ term, just define it to be $0$...If that's not allowed, then wave your hands and mumble something.
Answer: The problem with proving $\binom{n-k+1}k=\binom{n-k}k+\binom{n-k-1}k$ is that it is not true (try $k=0$ for starters). However for $n\geq1$ one has
$$\begin{aligned}
  s_{n-1}&=\sum_{k=0}^{\lfloor\frac n2\rfloor}\binom{n-k}k\\
 &= 1+\sum_{k=1}^{\lfloor\frac n2\rfloor}(\binom{n-1-k}k+\binom{n-1-k}{k-1})\\
 &= 1+\sum_{k=1}^{\lfloor\frac {n-1}2\rfloor}\binom{n-1-k}k
     +\sum_{k=1}^{\lfloor\frac n2\rfloor}\binom{n-1-k}{k-1}\\
 &= s_{n-2}+\sum_{k=0}^{\lfloor\frac n2\rfloor-1}\binom{n-2-k}k\\
 &= s_{n-2}+s_{n-3},\\
 \end{aligned}
$$
so that the sequence $(s_n)_{n\geq-1}$ satisfies the Fibonacci recurrence (with $s_{-1}=\binom00=1$ by the same definition as $s_n$ for $n\in\mathbf N$). Since moreover $s_{-1}=s_0=1$ one has $s_n=F_{n+2}$ for all $n\geq-1$.
One wonders what is the point of starting the defining expression for $s_n$ with $\binom{n+1}0$, as the "$+1$" only increases the shift with respect to the Fibonacci sequence. To resume, one has
$$ F_n=\sum_{k=0}^{\lfloor\frac{n-1}2\rfloor}\binom{n-1-k}k
  \qquad\text{for }n\geq1.
$$
Added: although the summation runs into terms $0$ once $k>n/2$ (this is implicitly used in the argument above where we dropped the final term from the first summation in the third line), it should not be written as an unbounded (therefore infinite) summation: when one gets to terms for $k>n$, the terms are again nonzero, by the usual convention for binomial coefficients with negative upper index. This point should have been made clearer in the question.
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\norm}[1]{\left\vert\left\vert\, #1\,\right\vert\right\vert}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}\color{#66f}{\large s_{n}}&
={n+1 \choose 0} + {n \choose 1} + {n - 1 \choose 2} + \cdots
=\sum_{k\ =\ 0}^{\infty}{n + 1 - k \choose k}
\\[5mm]&=\sum_{k\ =\ 0}^{\infty}\ \overbrace{\oint_{\verts{z}\ =\ \varphi^{+}}
{\pars{1 + z}^{n + 1 - k} \over z^{k + 1}}\,{\dd z \over 2\pi\ic}}
^{\ds{=\ \dsc{n + 1 - k \choose k}}}
\end{align}

where $\ds{\varphi \equiv {1 + \root{5} \over 2}}$ is the
  Golden Ratio.
  Then,

\begin{align}
\color{#66f}{\large s_{n}}&
=\oint_{\verts{z}\ =\ \varphi^{+}}{\pars{1 + z}^{n + 1} \over z}
\sum_{k\ =\ 0}^{\infty}\bracks{1 \over z\pars{1 + z}}^{k}\,{\dd z \over 2\pi\ic}
\\[5mm]&=\oint_{\verts{z}\ =\ \varphi^{+}}{\pars{1 + z}^{n + 1} \over z}
{1 \over 1 - 1/\bracks{z\pars{1 + z}}}\,{\dd z \over 2\pi\ic}
=\oint_{\verts{z}\ =\ \varphi^{+}}{\pars{1 + z}^{n + 2} \over z^{2} + z - 1}
\,{\dd z \over 2\pi\ic}
\\[5mm]&=\oint_{\verts{z}\ =\ \varphi^{+}}
{\pars{1 + z}^{n + 2} \over \pars{z + \varphi}\pars{z - \varphi^{-1}}}
\,{\dd z \over 2\pi\ic}
={\pars{1 - \varphi}^{n + 2} \over -\varphi - \varphi^{-1}}
+{\pars{1 + \varphi^{-1}}^{n + 2} \over \varphi^{-1} + \varphi}
\end{align}

However,
  $\ds{\quad\varphi + \varphi^{-1}=\root{5}\,,\quad 1 + \varphi^{-1}=\varphi\quad}$ such that

$$
\color{#66f}{\large s_{n}}
={\varphi^{n + 2} - \pars{1 - \varphi}^{n + 2} \over \root{5}}
=\color{#66f}{\large F_{n + 2}}
$$

where $\ds{F_{m}}$ is a
  Fibonacci Number.


Who receives the yellow card if no one approaches the ball to shoot a free kick?

Question: A yellow card is usually given to free kick candidates when, in order to gain time, they take too much time to shoot.
Usually, especially for defensive free kicks, the candidate is clearly identified because it's the one a few steps from the ball, pretending to think about how he's going to shoot, making gestures to his teammates, etc.
But what if no one is near the ball and the time keeps running? The referee will still need to give someone a yellow card.
Comment: "The free kick candidate is clearly identified because it's the one a few steps to the ball" - [not always](https://sports.stackexchange.com/q/18754/15589). Sometimes multiple players will crowd round the ball, either to keep their opponents guessing about who'll take the kick and from what angle, or because they genuinely can't agree on who should take it. I've even seen feints where one player will run up and *pretend* to kick the ball, the wall moves in response, and then the second player hits the ball past them.
Comment: I agree, I'm trying to rephrase my question. I was thinking about defensive free kicks (usually by the goal keeper or a defender), when it is supposed to be be quick, but the team, leading by one goal is trying to spend time and snatch the game.
Comment: Probably to the captain, that responds for the team. Take a look at this link https://www.dailymail.co.uk/sport/football/article-2996184/Stop-referee-abuse-Yellow-card-captains-group-players-apply-pressure-send-happens-again.html
Answer: I wasn't entirely sure, so I asked in our local community about this question. Most of it got confirmed, but there's a few more things you can do as a referee in such a situation.

Talk to the captain of the team in question and remind them to take the free kick.
You can caution the captain, if they're not listening or still refuse to continue the game.

Exception: If the captain is actually willing to continue the game and the team refuses to do so you shouldn't caution the captain.

Give the team an ultimatum (1-2 mins) to take the free kick.
If they're still not playing abandon the game.
Comment: By "caution", you mean yellow card?
Comment: Yes, cautioning is just another term for showing a yellow card.
Comment: The referee has no authority to caution the captain for the behaviour of their team. Remove point 2 and this answer is perfect.
Comment: @ReinstateMonica2331977 read point 2 again. I never said they get a card for the behavior of the team. You can caution the captain for refusing to listen to the referee. If they try and the others don't listen you don't have to caution them. This point is perfectly fine and has been confimed by a highly ranked referee and several others. Actually the whole answer has been confirmed by multiple referees.
Comment: added an exception to point 2 to be more clear about it


How to interpret PCA coefficients to reduce dimension

Question: I have read about similar questions. I have data which has 68 columns and about 800 samples. The 68. column is the output the rest 67 is the input variables. I want to reduce the size of my input variables to for example 30 or 20 variables.
I have read about PCA. I already ran the PCA in Matlab and gathered a 67 x 20 matrix containing PCA coefficients. I calculated eigenvalues for each Principal component (10 eigenvalues). As far as I understand I should order these eigenvalues and select the PCA's with higher eigenvalues as important. For example, I chose PC1, PC3, and PC9.
How can I use this information to select among the original 67 variables? I mean how can I use this PCA analysis results to reduce a 67*800 matrix to a 20*800 matrix and get the variables which have higher effect on the target variable?
Comment: PCA is about dimensionality reduction (and thus misapplied here), your use case is closer to a process called feature selection.
Comment: There are methods for _principal variables analysis_ which aim at selecting variables, as nearly uncorrelated as possible. You would need to search harder for references and implementations.
Comment: PCA is a dimensionality reduction technique. However, I think what you need to do first is a feature selection technique to decide which predictors(independent variables) have higher effect on the target(dependent variable) so you will use in model building. So I wish if you could take a look at this answer to a similar question. [Answer](https://stats.stackexchange.com/a/393230/237974)
Answer: The eigenvalues that you get in Matlab with pca() are already in decreasing order, so you are guaranteed that the first n Principal Components will be the most important ones. You can see this yourself if you look at a vector latent which is a vector of eigenvalues. If then you would like to reduce your variable set to 20 variables, you can simply retain only 20 first PCs from the coeff matrix.
What you do is you project your original data set $X$ (which is 800 $\times$ 67) on a reduced PC basis:
Z = X * coeff(:,1:20)
to get the PC scores matrix $Z$ which is the representation of your original data in a 20-dimensional space instead of 67-dimensional. The matrix $Z$ is size 800 $\times$ 20.
Comment: The OP asked how to select input variables that have the greatest effect on the target variable. PCA is not designed to do this, because it's unsupervised. Using the top principal components (as suggested) maximizes variance explained for the *inputs*. But, there's no reason these components must retain information about the *output*. It's possible that informative components have small variance, and are therefore discarded.


$F=2+3x+5x^2+7x^3+ \dots$ $G=1-2x+4x^2-8x^3+ \dots$ What will be $F/G$?

Question: $F=2+3x+5x^2+7x^3+ \dots \\
G=1-2x+4x^2-8x^3+ \dots$
I didn't get the correct result, how can I compute it?
Comment: Are the coefficients of $F$ prime numbers?
Comment: Yes, they are prime numbers
Comment: @lab bhattacharjee hows it related
Comment: @ArchisWelankar, $$G$$ can be found to be $$(1+2x)^{-1}$$
Comment: Yes but what about F
Answer: Algebraically,
$$G = 1 - 2x + 4x^2 - 8x^3 + \cdots = {1\over 1+2x},$$
so $1/G=1+2x$, and
$$F/G = (2+3x+5x^2+7x^3+\cdots)(1+2x).$$
Now multiply it out:
$$\eqalign{F/G &= 2 + (3+2\cdot2)x + (5+2\cdot3)x^2+(7+2\cdot5)x^3+\cdots\cr
&= 2+7x+11x^2+17x^3+\cdots\cr}$$
Answer: $G$ is a geometric series, so when $|x|<\frac12$ it converges to $\frac{1}{1+2x}$. Hence
$$\frac FG = \left(1+2x\right)F=\sum_{n\ge 0} (p_n + 2p_{n-1})x^n = 2 + 7x+11x^2+17x^3+...$$


$\sum_{k=1}^{\infty}\frac{1}{2^k}\frac{d_k(x(k),y(k))}{1+d_k(x(k),y(k))}$, proof the product $(X,d)$ is complete.

Question:
Let $(X_n,d_n)_{n\in\mathbb{N}}$ is numerable family of pseudo-metric spaces.
  The function
$d:\prod_\limits{k\subset\mathbb{N}}^{}X_k\times\prod_\limits{k\subset\mathbb{N}}^{}X_k\to\mathbb{R}\\(x(k)_{k\subset\mathbb{N}},y(k)_{k\subset\mathbb{N}}\to\sum_{k=1}^{\infty}\frac{1}{2^k}\frac{d_k(x(k),y(k))}{1+d_k(x(k),y(k))}$
is well defined as pseudo-metric in $ \          $ $X=\prod_\limits{k\subset\mathbb{N}}^{}X_k$.
Let $(x_n)_{n\in\mathbb{N}}\in X$ be a Cauchy sequence iff for each $k\in\mathbb{N}$ the sequence $(x_n(k))_{n\in\mathbb{N}}$ is Cauchy in $(X_k,d_k)$.

Proof: If a sequence is Cauchy in $X,d$, for a given $\epsilon>0$ there exists $p(\epsilon)\in\mathbb{N}$ such as $d(x_n,x_m)\leqslant\epsilon$ if $n,m\geqslant p$, and therefore for each $k\in\mathbb{N}$
$n,m\in\mathbb{N}\:\:\:n\geqslant m\geqslant p(\epsilon)\implies\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}\leqslant 2^k\epsilon$
For $\epsilon<\frac{1}{2^{k+1}}$ we have
$n,m\in\mathbb{N}\:\:\:n\geqslant m\geqslant p(\epsilon)\implies{d_k(x_n(k),x_m(k))}\leqslant 2^{k+1}\epsilon$
Therefore the sequence $(x_n(k))_{n\in\mathbb{N}}$ is Cauchy in $(X_k,d_k)$.
Suppose that for each $k\in\mathbb{N}$ th sequence $(x_n(k))_{n\in\mathbb{N}}$ is Cauchy in $(X_k,d_k)$. Let´s fix $\epsilon>0$. We choose $q=q(\epsilon)$ in a way so that $\sum_{k=q+1}^{\infty}\frac{1}{2^k}<\frac{\epsilon}{2}$. So for each $n,m\in\mathbb{N}$,
$d(x_n,x_m)=\sum_{k=1}^{q}\frac{1}{2^k}\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}+\sum_{k=q+1}^{\infty}\frac{1}{2^k}\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}<\sum_{k=1}^{q}\frac{1}{2^k}\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}+\frac{\epsilon}{2}$
Now we can choose $p(\epsilon\in\mathbb{N})$ in a way that :
$n\geqslant m\geqslant p(\epsilon)\implies d_k(x_n(k),x_m(k))<\frac{\epsilon}{2}\:\:\:\:\forall k\in\{1,...q(\epsilon)\}$.
Then
$n\geqslant m\geqslant p(\epsilon)\implies d(x_n,x_m)<\epsilon$.
I have been stuck at this proof for two days. That is I posted this lengthy proof. I would be grateful if someone  clarified me the following points.
Questions:
1) I understood that in the first part of the proof $\epsilon<\frac{1}{2^{k+1}}$ was chosen with the purpose to ensure that $2^k\epsilon$ was smaller than one which would converge to 0 if we applied the infinite sum. However the author writes immediately afterwards "$n,m\in\mathbb{N}\:\:\:n\geqslant m\geqslant p(\epsilon)\implies{d_k(x_n(k),x_m(k))}\leqslant 2^{k+1}\epsilon$".
How can the author write"$n,m\in\mathbb{N}\:\:\:n\geqslant m\geqslant p(\epsilon)\implies{d_k(x_n(k),x_m(k))}\leqslant 2^{k+1}\epsilon$"? What for?
2) The author writes $\sum_{k=q+1}^{\infty}\frac{1}{2^k}<\frac{\epsilon}{2}$. How can the author be sure that by assuming $\sum_{k=q+1}^{\infty}\frac{1}{2^k}<\frac{\epsilon}{2}$, that $\sum_{k=q+1}^{\infty}\frac{1}{2^k}\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}<\frac{\epsilon}{2}$ is true?
Thanks in advance!
Comment: It should exists a global bound for all the metrics.
Answer: For your question 1: The function $\frac{t}{1+t}$ is strictly increasing. If  we take $t=2^{k+1} \epsilon$, then
$$
\frac{2^{k+1}\epsilon}{1+2^{k+1}\epsilon}>\frac{2^{k+1}\epsilon}{1+1}=2^{k}\epsilon,
$$
where we use the condition that $ 2^{k+1}\epsilon\leq 1$.
 So $d_k(x_{n}(k),x_{m}(k))\leq 2^{k+1}\epsilon$. Otherwise, $d_k(x_{n}(k),x_{m}(k))> 2^{k+1}\epsilon$ would imply that $\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}>2^{k}\epsilon$. A contradiction.
For your question 2: It is easy to see that $\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}\leq \frac{1+d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}= 1$. Hence, we have
$$
\sum_{k=q+1}^\infty \frac{1}{2^k}\frac{d_k(x_n(k),x_m(k))}{1+d_k(x_n(k),x_m(k))}\leq  \sum_{k=q+1}^\infty \frac{1}{2^k}
$$
Comment: Excuse me but there is one problem that I am going through when I am trying to understand point 1) which I hope you could clarify me. If you take t=2^{k+1} \epsilon, then $\frac{2^{k+1}\epsilon}{1+2^{k+1}\epsilon}>2^{k+1}\epsilon$. Imagine pick $t=5$, then $\frac{5}{1+5}>5$, which is not true once $\frac{5}{6}<1<5$. How can you have stated it only considering the fact the function is strictly increasing?
Comment: @PedroGomes Please see the update. It is a misprint, and I have make it clearer now. Hope you understand now
Comment: Thanks! Now I am getting it.