null conditional operator not working with nullable types?

Question: I'm writing a piece of code in c#6 and for some strange reason this works
var value = objectThatMayBeNull?.property;

but this doesn't:
int value = nullableInt?.Value;

By not works I mean I get a compile error saying Cannot resolve symbol 'Value'.
Any idea why the null conditional operator ?. isn't working?
Comment: You should use the `??` operator in this situation. As in `nullableInt ?? 0`.
Comment: did you tried: int value = (nullableInt?).Value; ???
Answer: Okay, I have done some thinking and testing. This is what happens:
int value = nullableInt?.Value;

Gives this error message when compiling:

Type 'int' does not contain a definition for `Value'

That means that ? 'converts' the int? into the actual int value. This is effectively the same as:
int value = nullableInt ?? default(int);

The result is an integer, which doesn't have a Value, obviously.
Okay, might this help?
int value = nullableInt?;

No, that syntax isn't allowed.
So what then? Just keep using .GetValueOrDefault() for this case.
int value = nullableInt.GetValueOrDefault();

Comment: Well I would have thought this would have been one of the main use-cases for this operator, especially since it's just sintactic sugar.
Answer: The reason for this is that accessing the value with a null conditional operator would be pointless:

When you apply x?.p where p is a non-nullable value type T, the result is of type T?. By the same token, the result of nullableInt?.Value operation must be nullable.
When your Nullable<T> has a value, the result of nullableInt?.Value would be the same as the value itself
When your Nullable<T> does not have a value, the result would be null, which is, again, the same as the value itself.

Although it does not make sense to access Value with the ?. operator, it does make sense to access other properties of nullable value types. The operator works consistently with nullable value types and with reference types, so these two implementations produce identical behavior:
class PointClass {
    public int X { get; }
    public int Y { get; }
    public PointClass(int x, int y) { X = x; Y = y; }
}
struct PointStruct {
    public int X { get; }
    public int Y { get; }
    public PointStruct(int x, int y) { X = x; Y = y; }
}
...
PointClass pc = ...
PointStruct? ps = ...
int? x = pc?.X;
int? y = ps?.Y;

In case of a nullable struct the operator lets you access a property of the underlying type PointStruct, and it adds nullability to the result in the same way that it does for non-nullable properties of the reference type PointClass.
Comment: That's not the case here. It's because, just as with the null-coalescing operator, `?.` resolves to the wrapped `int`, not the nullable type itself.
Comment: @dasblinkenlight `DateTime? dt=DateTime.Now; int? day=dt?.Day;`. After `?.` should come property of `DateTime` not property of `DateTime?`.
Comment: Now that you pointed this out I realize how moronic my logic was. Not a good day for science.
Comment: They don't compile because the result of `?.` when the nullable is non-null is the actual `int` inside it which doesn't have `Value` or `HasValue` properties. As in my answer, try `nullableInt?.ToString()`.
Comment: "because ?. may return null" > wrong, it returns an `int`. So the end result of `someInt?.XXX` would be the same as `someInt.GetValueOrDefault().XXX`.
Comment: @PatrickHofman: No, it would be: `someInt.HasValue ? someInt.GetValueOrDefault().XXX : null`
Answer: With regards to nullable types, the ?. operator is saying if not null, use the wrapped value. So for a nullable int, if the nullable has value 8, the result of ?. would be 8, not the nullable that contains 8. Since Value is not a property of an int, you get an error.
So, the example of trying to use property Value quite rightly fails, but the following would work,
var x = nullableInt?.ToString();
Consider the null-coalescing operator, ??.
var x = nullableInt ?? 0;
Here, the operator says, if null, return 0, otherwise return the value inside the nullable, which in this case is an int. The ?. operator is performing similarly with regards to extracting the content of the nullable.
For your specific example, you should use the ?? operator and an appropriate default rather than the ?. operator.
Comment: @Suncat2000 that's verifiably not true.

https://dotnetfiddle.net/NDPJ44
Comment: `var x = nullableInt ?? 0` won't compile because `nullableInt` and `0` are different types: `Nullable` and `int`, respectively. You must use `nullableInt.GetValueOrDefault(0)`; or, `nullableInt.GetValueOrDefault()`, since `default(int)` is `0`.
Answer: I basically agree with the other answers.  I was just hoping that the observed behavior could be backed up by some form of authoritative documentation.
Since I can't find the C# 6.0 specification anywhere (is it out yet?), the closest I found to "documentation" are the C# Language Design Notes for Feb 3, 2014. Assuming the information found in there still reflects the current state of affairs, here are the relevant parts that formally explain the observed behavior.

The semantics are like applying the ternary operator to a null equality check, a null literal and a non-question-marked application of the operator, except that the expression is evaluated only once:
e?.m(…)   =>   ((e == null) ? null : e0.m(…))
e?.x      =>   ((e == null) ? null : e0.x)
e?.$x     =>   ((e == null) ? null : e0.$x)
e?[…]     =>   ((e == null) ? null : e0[…])

Where e0 is the same as e, except if e is of a nullable value type, in which case e0 is e.Value.

Applying that last rule to:
nullableInt?.Value

... the semantically equivalent expression becomes:
((nullableInt == null) ? null : nullableInt.Value.Value)

Clearly, nullableInt.Value.Value can't compile, and that's what you observed.
As to why the design decision was made to apply that special rule to nullable types specifically, I think dasblinkenlight's answer covers that nicely, so I won't repeat it here.

Additionally, I should mention that, even if, hypothetically, we didn't have this special rule for nullable types, and the expression nullableInt?.Value did compile and behave as you originally thought...
// let's pretend that it actually gets converted to this...
((nullableInt == null) ? null : nullableInt.Value)

still, the following statement from your question would be invalid and produce a compilation error:
int value = nullableInt?.Value; // still would not compile

The reason why it would still not work is because the type of the nullableInt?.Value expression would be int?, not int.  So you would need to change the type of the value variable to int?.
This is also formally covered in the C# Language Design Notes for Feb 3, 2014:

The type of the result depends on the type T of the right hand side of the underlying operator:

If T is (known to be) a reference type, the type of the expression is T
If T is (known to be) a non-nullable value type, the type of the expression is T?
If T is (known to be) a nullable value type, the type of the expression is T
Otherwise (i.e. if it is not known whether T is a reference or value type) the expression is a compile time error.

But if you would then be forced to write the following to make it compile:
int? value = nullableInt?.Value;

... then it seems pretty pointless, and it wouldn't be any different from simply doing:
int? value = nullableInt;

As others have pointed out, in your case, you probably meant to use the null-coalescing operator ?? all along, not the null-conditional operator ?..
Comment: Ah!  Gotcha!  I actually found this thread, because, when I got an Obj Ref err doing "long? nullableLongVariable = objectVariable.NullableLongProperty.Value;", I had a brain fart, and changed it to "long? nullableLongVariable = objectVariable.NullableLongProperty?.Value;", when I could've just made it "long? nullableLongVariable = objectVariable.NullableLongProperty;".
Answer: Simply because (based on sstan's answer above)
var value = objectThatMayBeNull?.property;

is evaluated by compiler like
var value = (objectThatMayBeNull == null) ? null : objectThatMayBeNull.property

and
int value = nullableInt?.Value;

like
int value = (nullableInt == null) ? null : nullableInt.Value.Value;

when nullableInt.Value.Value is Cannot resolve symbol 'Value' syntax error!
Answer: int doesn't have a Value property.
Consider:
var value = obj?.Property

Is equivalent to:
value = obj == null ? null : obj.Property;

That makes no sense with int and hence not with int? via ?.
The old GetValueOrDefault() does though make sense with int?.
Or for that matter, since ? has to return something nullable, simply:
int? value = nullableInt;

Comment: this is not an int it is an int?
Answer: The null conditional operator also unwraps the nullable variable. So after the "?." operator, the "Value" property is no longer needed.
I wrote a post that goes more into detail on how I came across this. In case you're wondering
http://www.ninjacrab.com/2016/09/11/c-how-the-null-conditional-operator-works-with-nullable-types/


Validar explode

Question: Código:
$pessoa = "CARLOS";

$nome = explode ( " ", $pessoa, 2)[0];

$sobreNome = explode ( " ", $pessoa, 2 )[1] == null
             ? "VAZIO"
             : "sobreNome: " . explode ( " ", $pessoa, 2 )[1] ;

print "Nome: " . $nome . "
";
print "sobreNome: " . $sobreNome;

Objetivo:
Se explode ( " ", $pessoa, 2 )[1] não for possível poque a pessoa só cadastrar apenas 1 nome, sobrenome fica com o termo VAZIO
Como fazer?
Obs.: Da forma que fiz dá o seguinte erro.
Notice: Undefined offset: 1 in D:\Trabalhos\host\htdocs\hotplateprensas.com.br\teste.php on line 9
Nome: CARLOS
VAZIO

Em tempo:
Caso eu faça:
$pessoa = "CARLOS ALBERTO";

Então não dá erro.
Answer: Se o nome completo da pessoa não possuir um espaço em branco, a função explode irá retornar um array de apenas um elemento no índice zero; você não pode acessar o índice 1 assumindo que ele existirá, pois quando não existir dará o erro citado.
Além disso, você chamou a função explode 3 vezes para a mesma string em 2 linhas de código basicamente; isso é um claro sinal que você deve refatorá-lo.
$nomeCompleto = "Carlos";

$nomes = explode(" ", $nomeCompleto, 2);

$nome = array_shift($nomes);
$sobrenome = array_shift($nomes) ?? "Vazio";

Assim, $nomes será o array retornado por explode; a função array_shift irá remover o primeiro elemento retornando-o para $nome. Se não houver o sobrenome, a função array_shift irá retornar NULL e através do operador de coalescência nula é atribuído o valor "Vazio" quando isso ocorrer.
Mas você pode simplificar ainda para:
$nome = $nomes[0];
$sobrenome = $nomes[1] ?? "Vazio";

Pois o operador de coalescência nula intrinsecamente verificará se o índice 1 existe no array antes de retorná-lo.
Comment: vou aceitar sua resposta mas gostaria de uma orientação. O que você acha dessa abordagem? $sobreNome = ! isset ( explode ( " ", $pessoa, 2 )[1] )
     ? "VAZIO"
    : explode ( " ", $pessoa, 2 )[1] ;
Comment: @CarlosRocha Desnecessária. Por que executar a mesma função 2x?

Validar explode


Ajax add command to open a new URL

Question: in a custom module, I created a custom form. On this form, I have an ajax button to open a specific file (.pdf).
Here is my code in a custom submit function :
<code>  $url = 'myfileUrl';
  $response = new AjaxResponse();
  $command = new RedirectCommand($url);
  $response->addCommand($command);
</code>
It's ok and the file is opened when I click on the button. But, the page is closed to open the file. How can I specify an attribute "target" to open the file in a new window? If not possible, is there another ajax command to open an external URL?
Thanks.
Comment: https://stackoverflow.com/questions/4907843/open-a-url-in-a-new-tab-and-not-a-new-window-using-javascript
Comment: @kevin, I don't see a clear response in your link. Can you explain me if I can use a target attribute in a RedirectCommand ajax? e.g. $command = newRedirectCommand($url, 'target=_blank', or newOpenUrl...). Thanks.
Comment: According to [RedirectCommand Documentation](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21RedirectCommand.php/class/RedirectCommand/8.2.x) RedirectCommand set `window.location` , and it's not possible to redirect with target _blank with window.location, only with window.open(url,'_blank'); can redirect to new window, see the answer in the link commented by @kevin in the first comment.
Comment: @berramou, I understand the behavior of the RedirectCommand function. But, what should I use to open a new window (and open a file) if I click on a button? I tried to use the OpenDialogCommand without sucess. Or, should I use a custom submit and forget the ajax functions? Thanks.
Answer: I found a solution to resolve my problem.
After having readed several posts, i have decided to create a custom Ajax Command to open my files (pdf/csv).
Create a custom command - link
In my custom module, I have built the required files for this and call in my CallBack function this new ajax command ('OpenFileCommand') :
<code>    $ajax_response = new AjaxResponse();
    $command = new OpenFileCommand($file_url);
    $ajax_response->addCommand($command);
</code>
Here is the simple code for this command:
<code>use Drupal\Core\Ajax\CommandInterface;

/**
 * Class OpenFileCommand.
 */
class OpenFileCommand implements CommandInterface {

  // Create a new property.
  protected $file_url;

  // Construct the File Url property.
  public function __construct($file_url) {
    $this->file_url = $file_url;
  }

  /**
  * Render custom ajax command.
  *
  * @return ajax command function
  */
  public function render() {
    return [
      'command' => 'OpenFileCommand',
      'file_url' => $this->file_url
    ];
  }

}
</code>
Now, I can open a file when I click on a ajax button.
Thanks for all for your help. This solution can help someone...
Answer: You can open a new window which can be achieved using javascript. Call function like below using on click method. You have to pass the URL to open and title for the window.
<code>    function openWindow(url, title){
      var left = (screen.width/2)-(700/2);
      var top = (screen.height/2)-(500/2);
      var win = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=700, height=500, top='+top+', left='+left);
      //setTimeout(function () { win.close(); }, 10000); <- You can give timeout also so window will get automatically closed
    }
</code>
Hope this will help to open your pdf file in new window, I will post another answer if I found to open a new tab on redirect.

Ajax add command to open a new URL


Product of character values

Question: From Isaac's character theory book;
$3.12$ Let $x\in Irr(G)$ and $g,h\in G$. Show that
$$\chi(g)\chi(h)=\dfrac{\chi(1)}{|G|}\sum_{z\in G}\chi(gh^z)$$
I had thought that it was related to $3.9)$;
$$K_iK_j=\sum_{v}a_{ijv}K_v$$
where $K_i$ is the sum of the $i$ th conjugacy classes and
$$a_{ijv}=\dfrac{|\mathfrak{K_i}||\mathfrak{K_j}|}{|G|}\sum_{\chi\in Irr(G)}\dfrac{\chi(g_i)\chi(g_j)\overline{\chi(g_v)}}{\chi(1)}$$
But by using above equalites, I found that $$\chi(g)\chi(h)=\sum_{\chi\in Irr(G)}\dfrac{\chi(g)\chi(h)}{\chi(1)}$$.
I could not proceed more. Any help would be appreciated.
Answer: Let $\rho:G\rightarrow GL(V)$ be your irreducible representation.
1-Prove that $f=\frac{\chi(1)}{|G|}\cdot\sum_{z\in G}\rho(z)\rho(h)\rho(z^{-1})$ commutes with every $\rho(t)$ and therefore by Schur's lemma it is a homothety of ratio $\frac{Tr(f)}{\chi(1)}=\chi(h)$.
2-It follows that $\chi(gf)=\operatorname{Tr}(\rho(g)(\chi(h)\cdot1_V))=\chi(h).
\chi(g)$
Comment: I do not know what "homothety of ratio" is. I can only use the tools mentioned in cheapter $3,2,1$.
Comment: It is $\chi(h)1_V$
Answer:
Theorem Let $\chi \in Irr(G)$, and $x,y \in G$, then
$$\chi(x)\chi(y)=\frac{\chi(1)}{|G|}\sum_{z \in G}\chi(xy^z)$$

Before proving this theorem we need to set notation and an observation. Wrtie $\mathfrak{X}$ for any representation affording the character $\chi$. Let $x \in G$, then the $\color{blue}{conjugacy \ class}$ of $x$ in $G$ is denoted by $\color{blue}{K_x}$ and the $\color{darkgreen}{sum \ of \ its \ elements}$  as central element of the group algebra $\mathbb{C}[G]$ is denoted by $\color{darkgreen}{\hat{K}_x}$. As is well-known, the Schur Lemma implies the formula
$$\mathfrak{X}(\hat{K}_x)=\omega_{\chi}(\hat{K}_x)I$$
where $I$ is the identity matrix of dimension $\chi(1)$, and taking traces yields
$$\omega_{\chi}(\hat{K}_x)=\frac{\chi(x)|K_x|}{\chi(1)}$$
Observe that if we let $y$ run over $G$, and look at $x^y$, each element of $K_x$ appears $|C_G(x)|$ times. Hence we have the useful equality in $\mathbb{C}[G]$:

$$|C_G(x)|\hat{K}_x=\sum_{y \in G} x^y$$

Now let us proceed proving the theorem. Working in $\mathbb{C}[G]$ and applying the previous formula, we have
$$\sum_{z \in G}xy^z=\sum_{z \in G}xz^{-1}yz=x\sum_{z \in G}y^z=x|C_G(y)|\hat{K}_y$$
This gives
$$\mathfrak{X}(\sum_{z \in G}xy^z)=\sum_{z \in G}\mathfrak{X}(xy^z)=\mathfrak{X}(x)|C_G(y)|\omega_{\chi}(\hat{K}_y)I$$
Taking traces at both sides in the formula above gives
$$\sum_{z \in G}\chi(xy^z)=\chi(x)|C_G(y)|\omega_{\chi}(\hat{K}_y)=\chi(x)|C_G(y)|\frac{\chi(y)|\hat{K}_y|}{\chi(1)}=\chi(x)\chi(y)\frac{|G|}{\chi(1)}$$
which proves the theorem.$\square$
Corollary Let $\chi \in Irr(G)$. Then

$$\sum_{x,y \in G}\chi([x,y])=\frac{|G|^2}{\chi(1)}.$$

Proof In the Theorem, put $y=x^{-1}$. Then the formula yields
$$|\chi(x)|^2=\chi(x)\chi(x^{-1})=\frac{\chi(1)}{|G|}\sum_{z \in G}\chi([x^{-1},z]).$$
Since $\chi$ is irreducible we have $\sum_{x^{-1} \in G}|\chi(x^{-1})|^2=\sum_{x \in G}|\chi(x)|^2=|G|$, so summing over all $x \in G$ in the formula above gives the desired result.$\square$

Corollary Let $\chi \in Irr(G)$, and $x,y \in G$, then
$$\chi(x)\chi(y)=\frac{\chi(1)}{|G|^2}\sum_{g,h \in G}\chi(x^gy^h)$$

Proof The theorem tells us that
$$\sum_{g,h \in G}\chi(x^gy^h)=\sum_{g\in G}(\sum_{h \in G}\chi(x^gy^h))=\sum_{g\in G}\frac{|G|}{\chi(1)}\chi(x^g)\chi(y)=\sum_{g\in G}\frac{|G|}{\chi(1)}\chi(x)\chi(y)=\frac{|G|^2}{\chi(1)}\chi(x)\chi(y).$$
Comment: Thank you, Nicky. It was 7 years ago, so I need to remember the question :)
Comment: As always Mesel, thanks! I ran into your question by coincidence and decided to provide the proof.

Product of character values


$\lim_{x \rightarrow 0^-}e^{(1/x)}(1 - \frac{x+2}{x^2})$

Question: $$\lim_{x\to 0^-}e^{1/x}\left(1-\frac{x+2}{x^2}\right)$$
I tried to say that $t = 1/x$ but it doesnt work. Then I also tried Lhopital and got nowhere. Wolfram Mathematica also says that it cannot show step by step for this problem. Does anybody know how to solve it?
Comment: Why does $t = 1/x$ not work? Try it again.
Answer: Let $t=-1/x,$ so that we send $t$ towards positive infinity. Then we get $$\frac{-2t^2+t+1}{e^t}\,\to\,0.$$
Answer: $$y=e^{\frac{1}{x}} \left(1-\frac{x+2}{x^2}\right)\implies \log(y)=\frac{1}{x}+\log\left(1-\frac{x+2}{x^2}\right)$$
Using equivalents
$$\log\left(1-\frac{x+2}{x^2}\right)\sim -\frac{x+2}{x^2}=-\frac{1}{x}-\frac{2}{x^2}$$
$$\log(y) \sim -\frac{2}{x^2} \quad \to  -\infty \implies y \to 0$$


Azure VM with SQL Server database - backup and file recovery

Question: I have an Azure VM - Windows (Windows Server 2008 R2 Datacenter). It has Microsoft SQL Server 2008 R2 running on it (version v10.50.6549).
The Azure VM has backups running according to a policy - and I can see in the backups blade for the VM that they are running nightly.
If I have an issue with the SQL Server, and need to roll back to a prior version of the database, will the File Recovery option from the VM backup be adequate?
Or should I also be running SQL Server backups via a maintenance plan on the server on the VM?
Answer:
If I have an issue with the SQL Server, and need to roll back to a
  prior version of the database, will the File Recovery option from the
  VM backup be adequate?

Maybe.  VM Backups don't always give you consistent SQL backups.  They usually work, but not always.  If you have everything setup just right and get consistent VM backups, it might be ok-- but you are running a fairly old OS on that VM, so I'd be nervous.  Very nervous. If the data is really important to you, then you should backup the data, not just the VM.  Sometimes you want to restore just the data to another VM to investigate, not the entire server.  I also hope you have more than just "last night's VM backup" at any given time.  Sometimes bad things happen on Friday and you don't notice until Monday.

Or should I also be running SQL backups via a maintenance plan on the
  server on the VM?

Yes, you should be running SQL backups if you your data is important. If your data is really important (you don't want to lose half a day of it), you should be doing full backups periodically (e.g. nightly) transaction log backups many times per hour, and keeping a few weeks worth of backups in rotation.  If your data is super-important (you don't want to lose more than a few seconds), you should be mirroring it over to another database server in near-time (asynchronously).  If it is critical (you don't want to lose any data), then you want to mirror to another server in real-time (synchronously).
Of course, if you are already running in Azure and don't have a DBA, managing a database is a lot easier, safer, more available, and generally cheaper if you use Azure SQL rather than trying to manage your own instance SQL Server in a VM-- oh yeah, and backups are handled for you, with millisecond point-in-time recovery for up to 45 days-- and they handle the mirroring for you to.  If you want to mirror to another region across the country, you do have to pay extra for that, though.
Comment: Agree 100%. Azure SQL is the way to go. We find that while our support staff prefer going the SQL-On-A-VM approach, that's because it looks just like they are used to, and they know how to manage patching, backups, performance monitoring etc. The thing is as @Tim says though, once you go Azure SQL almost all of this is done for you!


Investigating the solutions of $9^{x}+k(3^{x})+2=0$

Question: I have worked this one through but still not 100% sure.

the discriminant is $D=(k-2\sqrt{2})(k+2\sqrt{2})$.
the quadratic equation gives $3^{x}=\dfrac{-k\pm\sqrt{k^2-8}}{2}$.
as the RHS must be at least $0$ for this equation to have any solutions I did some work using inequalities

I concluded that this equation:

cannot have repeated roots when $k=-2\sqrt{2}$
has two distinct roots when $k<-2\sqrt{2}$

But not too sure about the details for the case when the equation has two distinct roots. How would you determine this?
Thank you
Comment: yep, you can also check using wolfram...http://www.wolframalpha.com/input/?i=9%5Ex%2B8%5E(1%2F2)(3%5Ex)%2B2+%3D+0
Comment: you must have $3^x > 0$ if you are to finally get an $x$ out of it.
Answer: To be able to compute the roots of $3^{2x} + k3^x +2$ with respect to $3^x$ you have immediately the condition $k^2 - 8 \geq 0$. So $k\leq -2\sqrt{2}$ or $k\geq 2\sqrt{2}$. In case of either equality, you have zero discriminant.
You must also meet the condition
$$-k \pm \sqrt{k^2-8} > 0. $$
This leaves you with $k < -2\sqrt{2}$.

Solving analytically the inequality $-k \pm \sqrt{k^2-8} > 0$ can be prone to mistakes so make sure to double check.

When in doubt, I can always use my rudimentary geogebra skills to draw a picture and get a feeling for what's going on. The green line is $f(x) = -x$ and blue and red lines are $g(x) = \sqrt{x^2-8}$ and $h(x) = -g(x)$ respectively.
Comment: Thank you. This makes sense now.


Triangle inequality question.

Question: For triangle ABC, there is a point X such that B-A-X. There is any point P on bisector of exterior angle CAX. Prove that PB+PC>AB+AC.
I have tried for many hours, but i have no idea how to solve it.
actually, i have shown PB>AB.
This is a question in 9th grade level, so please give solution by use of triangle congruency and triangle inequality.. Please don't use simillarity.
Comment: @Adriano I believe he means that the points on the line are $B, A, X$ in that order, IE that $X$ lies on the extended line.
Answer: Hint: Construct point $C'$ on $BA$ extended, such that $AC= AC'$.
Prove that $AP$ is the perpendicular bisector of $CC'$. Hence $PC=PC'$.
Hint: Apply triangle inequality to triangle $PBC'$.
Comment: How you have got this idea?I mean it is verrrry hard for me. please tell me on what type of questions, we required constructions. THANK YOU.
Comment: @user91374 Think of how to relate the lines to each other. These kind of triangle inequality often require some reflection / rotation / translation argument. We know that we must transform $AB+AC$ into a straight line, which motivates the construction of $C'$. We then need $PC' = PC$, and so use the definition of $P$.
Comment: INTELLEGNT!!!!!

Triangle inequality question.


AngularJS - how to have a directive with a dynamic sub-directive

Question: Really struggling with this - have tried every way I can think of.  Hopefully, somebody can help.
I have a directive which creates the outline of a custom control for me.  The central part of the custom control is to be represented by a further dynamically-generated directive based on the value of a scope variable on the outer directive.  The scope variable contains the name of the inner directive.  I am doing this because my page will have multiple dynamically-generated elements all with a common layout but different inner content.
i.e. an example of my outer directive:

{{inner}} is set to the name of a further directive - in this case search.  My page should therefore become:

with search on the lower div also being replaced by the content of that directive.
Any ideas?
UPDATE
Here's a basic jsFiddle representing the issue I have - note the third div is not displayed.
Comment: Didn't you mean to write  instead of
Answer: I have create a fiddle here.
These are the directives.

And here you do dynamic loading

See if this helps you, and solves your purpose. I am making each directive into a template and then using ng include
Comment: Perfect!  Thanks so much.  If I could pass you a virtual gold star I would, and it's a nice elegant solution too.
Answer: Try this fiddle http://jsfiddle.net/xpKwb/12/
You can use ngSwitch

Comment: does this not create both templates and only plays with their visibility?


Proving a product is real based on two given complex numbers

Question: We have two numbers $z=4e^{5\pi i/3}$ and $w=3e^{2\pi i/3}.$
Let $u$ be a complex number such that $u^2 = w.$

Prove that $z \times u$ is real.

Attempt:

I thought one way is give $u$ an algebraic form and establish two equations for its real and imaginary parts based on $u^2 = w$. So $u = a + ib$, and we get $a^2 - b^2 = -3/2$ and $2ab = 3\sqrt{3}/2.$ Then we can solve for $a,b.$

Alternatively, we can start with the calculation of the imaginary part of $z \times u$ directly: i.e., $$ \frac{z u - \bar{z}\bar{u}}{2i} =c \tag{1}$$ and to show $c$ is zero. But I get stuck quickly after $z u - \bar{z}\bar{u} = 2c i$ and multiplying by $\bar{u}$:

$$
z w - \bar{z}|u|^2 = 2c i u \tag{2}
$$
But we still have a $u$ on the rhs, and I don't know how to make progress towards showing $c=0$ from here.

Question:

Which of the two approaches is more fitting here? Any hints as to how to make progress where I am stuck would be much appreciated.
Answer: Hint: $5/3 + 1/3 = 2$. Think about what multiplying complex numbers does to their polar angles.
Answer: Hint: Show that $z^2u^2$ is real and positive.
Comment: Cool idea! So with the idea to show at the end that if $z^2 u^2$ is real, positive, its square-root is real positive too, right?
Comment: @user929304: Not exactly $-$ its square root is real, but not necessarily positive.
Comment: ty, very elegant approach!
Answer: It's as simple as stating $u = \pm \sqrt 3 e^{\frac{\pi i}3}$ so $zu = \pm 4\sqrt 3 e^{5\frac{\pi i}3 +\frac{\pi i}3 } = \pm 4 \sqrt 3 e^{2 {\pi i}} =  \pm 4 \sqrt 3  \in \mathbb{R}$


Accounting for ties in combinatorics?

Question: In this problem, there is a race between 6, and then 7, horses.
These horses can tie, so how many different possibilities are there for each scenario?
I know that this is how you would start:
no ties - 6! (7! for the second problem)
all same - 1 possibility
and there would be factorials involved. I don't really know how to account for the ties.
EDITED: if I accounted for a tie between 2 horses, would I use C(6,2)?
How would I go about calculating the coefficients?
Answer: One way is to set up a recursion based on the number of horses that tie for last place.  If you have $n$ horses, this number can be anything from $1$ to $n$.  The relevant recursion turns out to be
$$S(n)=\sum_{k=1}^n{n\choose k}S(n-k)$$
where $S(n)$ is the desired number of outcomes, with $S(0)=1$ to get things started.  Thus
$$S(1)={1\choose1}S(0)=1\cdot1=1$$
$$S(2)={2\choose1}S(1)+{2\choose2}S(0)=2\cdot1+1\cdot1=3$$
$$S(3)={3\choose1}S(2)+{3\choose2}S(1)+{3\choose0}S(0)=3\cdot3+3\cdot1+1\cdot1=13$$
and so forth.  If you don't want to do the calculations to get to $S(6)$ and $S(7)$ yourself, you can find them at A000670 in the OEIS.
Answer: Hint: Try enumerating all the different scenario you can possibly have.
In the case when you have no tie, it is straightforward (and you got it).
For a tie between two horses, the tie could be in first place, or second, or third place, etc...
If you are allowing a tie between multiple horses, then you will have to take into account the tie between three horses, four horses and so on.
Edit: I will expand a bit more upon what I was to convey. They are probably easier way to find the answer to the problem, but here is another way.
Also pointed out by user Barry Sipra, this reasoning only takes into account for multiple ties.
If you have 6 horses racing with a possibility of ties (I will assume that more than two horses can be tied to a certain position).
case 1: no tie. In this case there is $6!$ possibilities.
case 2: tie between two horses. Since the order between the two horses that are tied does not matter, you can use a combination and obtain $6 \choose 2$ $\times 4!$. Since here you can have a tie for the 1st, 2nd, 3rd, 4th and 5th place, you will have in the end $5\times$$6 \choose 2$ $\times 4!$ configurations.
To be more general, if you had $n$ horses and there is possibility for two of them to end up in a tie, you will have $$\underbrace{(n-\overbrace{2}^{\text{number of horses tied}}+1)}_{\text{number of positions to be tied in}}\times
\underbrace{{n\choose 2}}_{\text{the number of couple that can get in a tie}}\times\underbrace{(n-2)!}_{\text{# arrivals of horses not tied}}$$ different configurations.
case 3: tie between three horses. Using the same logic as above, you will have $4\times$$6\choose 3$$\times 3!$.
case 4: tie between four horses. You will get $3\times$$6\choose 4$$\times2!$.
case 5: tie between 5 horses. You will get $2\times$$6\choose 5$$\times 1!$.
case 6: tie between all 6. You will get $1\times$$6\choose 6$$\times 0!$.
For your final answer, you will sum the result you obtain from all the different cases namely:
$$
6!+5\times {6 \choose 2} \times 4!+4\times {6 \choose 3} \times 3! +
3\times {6 \choose 4} \times 3!+2\times {6 \choose 5} \times 1! +1\times {6 \choose 6} \times 0!.
$$
If I did not make any mistake, you should get $3283$ ways.
Comment: I think its trickier than this.
Comment: @Omnitic, I expanded upon what I meant.
Comment: @ZanCoul, your answer disagrees with what the OEIS gives (the link is in my answer).  You are omitting multiple ties, e.g. two horses tie for first and another two tie for last place.
Comment: @Omnitic, that's right! I forgot to account for that. Thanks for pointing it out.
Comment: that last part was due to @BarryCipra, who also answered the question correctly.
Comment: @Omnitic: fixed, thanks for pointing out. Since there is a better answer, should I delete what I have here, or leave it as log?

Accounting for ties in combinatorics?


Query to show old and new values from another table - query the latest ChangeDate

Question: I have 3 tables in SQL Server 2012.
Table History is the history of all the changes made to the values in Table A. It can have many changes done to PRICE, LOT, INTEREST, but in most cases the value is only changed once.
Table A
AID PRICE   LOT    INTEREST
------------------------
1   1500    9000   0.5
2   2500    20     1.5

Table B
BID AID
--------
11  1
22  2

Table History
BID     ChangeField     OldValue    NewValue   ChangeDate
------------------------------------------------------------
11      PRICE           1700        1500       1/1/22
11      LOT             10000       8000       12/15/21
11      LOT             8000        9000       2/2/22

I need a query that shows Table A with the old and new values from Table History. If there are more than 1 changes, then for the Old value, get the most recent previous value. In the above example, the most recent previous value for Lot is 8000 from 2/2/22 (not 10000 from 12/15/21).
Example:
AID OldPRICE    NewPRICE    OldLot  NewLot  OldInterest NewInterest
----------------------------------------------------------------
1   1700        1500        8000    9000    0.5         0.5
2   2500        2500        20      20      1.5         1.5

This query returns OldLot = 10000 (the biggest value for Lot), instead of 8000 (the most recent previous value)
SELECT A.AID,
   MAX(CONVERT(numeric(30, 2),ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.OldValue
   END,A.LOT))) OldLot,
   MAX(CONVERT(numeric(30, 2),ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.NewValue
   END,A.LOT))) NewLot
FROM A
LEFT JOIN B ON A.AID = B.AID
LEFT JOIN History h ON B.BID = h.BID
WHERE H.BID = 11
GROUP BY A.AID

That returns below (notice OldLot = 10000 instead of 8000)
AID OldLot  NewLot
--------------------
1   10000    9000

Thank you
Comment: So the "answer" you marked to your previous question on the same problem is not really an answer. And why do you need to convert anything? Are OldValue and NewValue stored as strings? Regardless, are you wedded to this design? A far easier, simpler approach is to simply store the complete row when changed rather than a row per value changed.
Comment: And clarify your logic / goal. Lot changed twice in your sample data but only one change is shown for the role as a whole. The very first lot value was 10000 - why is that NOT the old value?
Comment: This is a bit confusing as your example seems to just require the previous value, you're showing the current value and the last value?
Comment: I need to convert the values because columns OldValue and NewValue in table History are varchar(200) , so if I didn't convert it to numeric 8000 is bigger than 10000. On my previous question, I didn't realize the answered query doesn't work when there are more than 1 changes per Change Field.
Comment: Lot value 10000 was the original value, not the most recent value before it was changed to 9000. The previous value was 8000 before it was changed to 9000. So, I would like the OldLot to be 8000, the new lot to be 9000
Answer: If I understand your requirement correctly you are just after the most recent history value per field which you can do using a row_number partition, then you just need to pivot the rows to columns to combine with the current values:
with h as (
    select b.aid, h.*,
      Row_Number() over(partition by h.bid, h.changefield order by h.changedate desc) rn
    from history h
    join b on b.bid=h.bid
)
select a.aid,
  isnull(h.oldprice, a.price) OldPrice, a.PRICE newprice,
  isnull(h.oldLot, a.lot) OldLot, a.Lot NewLot,
  isnull(h.oldInterest, a.interest) OldInterest, a.Interest newInterest
from a
outer apply (
  select
    max(case when changefield = 'LOT' then oldvalue end) OldLot,
    max(case when changefield = 'PRICE' then oldvalue end) OldPrice,
    max(case when changefield = 'INTEREST' then oldvalue end) OldInterest
  from h
  where h.aid = a.aid and h.rn = 1
)h

Demo Fiddle
Also note, if you were using a more current version of SQL Server (2016+) there is inbuilt functionality for this using system versioning with its own extentions to t-sql for this kind of querying.
Comment: Thank you for your help. That works !


IPv6 doesn't work correctly on AWS ELB

Question: I configured my Elastic Load Balancer to work as dualstack. I created records set on Route 53 with types A and AAAA pointing to Elastic Load Balancer. Over IPv4, it works
I used this site to test my site over IPv6: ipv6-test.com/validate.php
And it returns the following:

What I need to do to get the others two steps working?
VPC, Subnets and instances are configured to accept IPv6
Edit:
Route table:
Comment: Did you test an individual instance before you tested the ELB? Did you follow the instructions in the [AWS EC2 IP6 guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-migrate-ipv6.html)? You didn't mention security group rules above, you may need to allow IP6 there or your NACLs.
Comment: Are your EC2 instances in a private or public subnet? Your route table has both EIGW and an IGW. The EIGW is for a private subnet. Also you have a static route for "2600:1....". If your EC2 instances are in a public subnet, remove the EIGW and the 2600... static route. If your EC2 instances are in a private subnet, create new a route table for the private subnet and put a NAT Gateway and EIGW in the private subnet route table and remove the EIGW and the 2600 .... from the public route table.
Comment: Yes, I tested and worked. According to Amazon, ELB communicate with instance over IPv4 independently user connection type, however, the instances are configured to accept both. My security groups and NACLs are ok to IPv6 too.
Comment: Not much anyone can do to help you with the information you've given. You're going to have to use a process of elimination.
Comment: I understand.. I tried to search but I didn't found something to help. Maybe someone faced the same issue and found some solution. But thanks to try @Tim
Comment: When you setup the Route53 records pointing to the load balancer did you create the records as ALIAS entries? Does the Route53 entry contain the "dualstack" part?
Comment: Specifically, as @Tim mentioned, the security group associated with the balancer itself needs to allow inbound IPv6 traffic, with rules referencing source address `::/0`.  A rule for `0.0.0.0/0` only allows IPv4.  Do you have this?
Comment: @JohnHanley Yes, those are alias and has dualstack part.
Comment: @Michael Yes, the security group has that inbound rule
Comment: One item that I just noticed. There is no check mark next to "IPv6 DNS server". Can you try another IPv6 site that provides more details on your IPv6 configuration? Everything that you describe appears correct. I am leaning towards a DNS issue.
Comment: @JohnHanley I think you are right. I enabled ping on my ELB and the ping command is working but ping6 isn't.. It returns: ``ping6: UDP connect: No route to host``. But when I use ping6 from my instance, it works. But unfortunately I don't how to solve this
Comment: Post your route table in your question. Add after an ----EDIT---- line.
Comment: @JohnHanley I've updated the question. Let me know if you need another info
Comment: @JohnHanley thank you so much!! I just replace EIGW for IGW and it's working. Provide an answer and I'll mark as solved
Comment: Can you tell me which part of my last answer you implemented? I will then create an answer.
Comment: @JohnHanley sure.. My instances and subnets are public, so I only changed the route table where was ``eigw`` by ``igw``
Comment: If you are not using the EIGW, delete it. I believe that there is a per hour charge.
Comment: Do not delete the 2600xxx static route. Since you had this blacked out I assumed that it was the static IPv6 address of one of your load balancers that you were testing with. This should be your IPv6 local network.
Answer: There is a long thread of comments on this question.
The solution is to change the route table to use the IGW (Internet Gateway) instead of the EIGW (Egress-Only Internet Gateway) to route the IPv6 traffic. Routing the IPv6 traffic thru the EIGW, in effect, makes the load balancers private and not publicly accessible.
Comment: I wasn`t using EIGW but turns out my VPC routing table was missing a gateway row for IPv6. It had only 0.0.0.0/0 set to igw-12345678. Once I added row ::/0, also for igw-12345678, it started working.
Comment: I had also a similar problem. A quick way to test if it's about the VPC settings is to see if `curl -v -6 http::[IPv6 address]/` succeeds from an instance inside the VPC. In my case, it succeeded, so it was about VPC settings.
Answer: I had similar problem but without Egress-Only Internet Gateway.
It was happening because my Application Load Balancer was configured with
ELBSecurityPolicy-TLS-1-2-2017-01 and ipv6-test.com only supports up to ELBSecurityPolicy-2016-08.

IPv6 doesn't work correctly on AWS ELB


How can we recover/restore lost/overwritten data in our MSSQL 2008 table?

Question: I am in serious trouble and I am seeking professional advices here.
We are using MSSQL server 2008. We removed primary key, replaced exiting data with new data resulted losing our critical business data in its child tables on MSSQL Server. It was completely human mistake and we didn't have disk failure.
1) The last backup file was a month ago which means it is useless.
2) We created Maintenance Plans to backup our database at 12AM everyday but those files are nohwere to be found
3) A friend of mine said we can recover from Transaction Logs. When I go to Task>Restore> Transaction log is dimmed/disabled.
4) I checked Management>Maintenance Plans. I can't find any restored point there. It seems that our maintenance plan hasn't been working.
Is there any third party tool to recover lost/overwritten data from MSSQL table? Thanks a lot.
Comment: @TeTe: why on earth didn't someone take a full backup before messing with schema and data?
Comment: What does this return for your database? `select d.name,recovery_model_desc,last_log_backup_lsn from sys.database_recovery_status r join sys.databases d on r.database_id=d.database_id`
Comment: You need a full backup and EVERY transaction Log since the Full backup (assuming you have no differential backups and assuming Full recovery model)
Comment: I think really the only hope you have left is if by some miracle the server that the database sits on has been backed up and restore the entire server.
Comment: Thanks Martin. I will try it when i get to work tomorrow morning. We got into serious trouble when our DBA was away on holiday. He did all the backup stuff and we completely neglected this whole backup thing.
Comment: @TeTe - The results you want to see from the above query are `FULL` for the recovery model and a `NOT NULL` value for `last_log_backup_lsn`. If that is `NULL` then this means your database is in auto truncate mode and your log files will be being automatically recycled rather than maintaining an unbroken history.
Comment: @Martin. It returns the result that "name: projects_production, recovery_model_desc:SIMPLE, last_log_backup_lsn:2009000000009000001". Does it mean we can recover those data?
Comment: The `NOT NULL` lsn [is explained here](http://sqlserverdownanddirty.blogspot.com/2011/04/curious-case-of-phantom-last-log-backup.html) not good news I'm afraid. I was hoping it might mean that your log files were not in auto truncate mode for some bizarre reason but that would be too much to hope for.
Comment: Thanks for your help Martin. We are just hoping our hosting service provider that handles our production server miraclly has backup of our database. I just wish we lost our data files rather than data on Database. I could have been so much easier to recover them back.
Answer: If your database is in full recovery mode and transaction chain is not broken (you have backup + transaction log since last full backup) then it might be possible to recover some or even all data by analyzing transaction log.
If transaction log is in full recovery mode then transactions are logged and can be read from t-log but unfortunately this is not an easy task.
Your options are to try and read this yourself using DBCC LOG command or third party tools such as ApexSQL Log or Quest Toad
Comment: Sadly there is no transaction chain as the db is not in full recovery mode but in simple. Read the comments on the question. -1
Comment: Yeah, I just saw the comments. Sorry about that.


Propierties of limits ad infinitum

Question: I know that
$$ \lim_{x\rightarrow c}f(x) + \lim_{x\rightarrow c}g(x) = \lim_{x\rightarrow c}(f(x)+g(x))$$ holds when $c$ is finite but also is true when $c$ is $\infty$?
Comment: Yes. Do you know the proof when $c$ is finite? It's a very instructive exercise to adapt that proof to the case $x\to\infty$.
Comment: No at all, it has to do with the difference quotient and adding a special zero? I think I view that in some place.
Comment: That is true when all the limits exist. Take $f(x)=\sin(1/x)$ for $x$ nonzero and $f(0)=0$. Define $g(x)=1-f(x)$. Then $f(x)+g(x)=1=\text{const.}$ certainly has a limit of $1$ everywhere, even though neither $f(x)$ nor $g(x)$ have limit for $x\to 0$.
Answer: It gets tricky.
If $f(x) = x$ and $g(x) = -x$, then
$$\lim_{x \to \infty}f(x) + \lim_{x \to \infty}g(x) = \infty - \infty$$
And $$\lim_{x \to \infty}\left( f(x) + g(x)\right) = \lim_{x \to \infty}0 = 0$$
And recall $\infty - \infty$ is an indeterminate form so we can't just say that it is equal to $0$
Comment: I think that would be fixed if we assume that the limit exists, that is $\lim_{x\rightarrow \infty} f(x)= \alpha$ where $\alpha$ is finite.
Comment: Indeed. I didn't see any such assumptions, hence why I provided my answer
Comment: That is because I was searching for the general case. And you example give a better understanding. Thanks.

Propierties of limits ad infinitum


Is $(-2)^{\sqrt{2}}$ a real number?

Question:
Is $(-2)^{\sqrt{2}}$ a real number?

Clarification: Is there some reason why $(-2)^{\sqrt{2}}$ is not a real number because it doesn't make sense why it shouldn't be a real number.
Mathematically we can define the value of $\sqrt{2}$ in terms of a limit of rationals. But the problem is is that some sequences will have values that are not defined for $(-2)^q$ where $q$ is a rational, such as $\dfrac{3}{2}$. Is this the reason why we can't define it or is there some other reason?
Comment: How do you define $(-2)^{\sqrt 2}$ in the first place? I.e., what is your most general definition of $a^b$? It is certainly easy to make a definition for arbitrary $a$ and $b\in\Bbb N$. Or for arbitrary $b$ and positive $a$. But here we have negative $a$ and irrational $b$.
Comment: Of course it's a complex number. If it's an integer, it's a complex number.
Comment: Because nothing is defined until one gives a definition, or better: an *acceptable* definition, where acceptable means: plays together well with other definitions
Comment: @avid19 What do you mean?
Comment: Sorry but I cannot understand what you mean to ask. Please clarify via an [edit]
Comment: Integers are a subset of complex numbers. Although it's sometimes used to mean "not real number", that's actually an incorrect use of the term complex number
Comment: @Puzzled417 Integers are complex numbers (with imaginary part $0$)
Comment: That is my question!
Comment: A negative number raised to an irrational number isn't usually defined.
Comment: Why is that the case? That is my question.
Comment: Well, how do you define a _positive_ number to an irrational number? Also, write `@AkivaWeinberger` in your comments or I won't get notified.
Comment: It's not the irrationality of the exponent that makes negative bases impossible.  Negative bases with *rational* exponents with even denominators in their lowest terms aren't allowed either.  This is because a negative bases don't have any even roots.  Irrationals are limits of converging sequence of rationals but as *rationals* exponents on negative bases are complex if the denominator is even and negative when the denominator and numerator are both odd and even when denominator is odd and numerator is even these sequences don't converge.
Comment: What?  $-2$ has argument $\pi$.  $(-2)^\sqrt{2}$ (if it is to be interpreted at all) should have argument $\pi\sqrt{2}$ (or equivalent).
Answer: I'll answer the general question of how we make sense of such expressions:
The value of such numbers is determined in one of two ways: by functional equations or by power series. A functional equation is any formula that relates the value of a function at two different points. Rules like $a^{b+c}=a^ba^c$ are examples of basic functional equations which can be rewritten as $f(a,b+c)=f(a,b)f(a,c)$ if that is preferred. An example of a function defined this way is $\Gamma(t):=\int_0^\infty x^{t-1}e^{-x}dx$. After applying integration by parts, we see that $t\Gamma(t)=\Gamma(t+1)$ holds, and we can use this to define $\Gamma(t)$ for any complex number that is not of the form $-n$ for $n\in\mathbb{N}$ (including $0$). This slightly weird way of expressing the undefined points is justified by the fact that at $-n$, $\Gamma(t)$ has a simple pole with residue $\frac{(-1)^n}{n!}$
Such values can also be determined by trying to make a power series make sense when values are plugged into it (for example, we might say $e^{i\pi}=-1$ because of what happens when we plug $i\pi$ into the power series for $e^x$). An example of a function defined this way is the matrix function $f(A)=e^A$. You can prove that the power series expression for $e^x$ around $0$ converges when interpreted as a statement about matrices. This function shares many of the properties of the complex function $f(z)=e^z$.
The wikipedia page on Analytic continuation has more info about extending (complex differentiable) functions.
We like these ways of doing things because they usually ensure that the properties we like the functions to have continue to hold. For example, extending via functional equation guarantees that the extended function also satisfies the functional equation, while power series are useful for preserving analytic properties of the function.
To deal with the question at hand now, your expression turns out to satisfy: $$(-2)^\sqrt{2}=2^{\sqrt{2}}(\cos((2k+1)\pi\sqrt{2}) + i\sin((2k+1)\pi\sqrt{2}))$$
which arises out of rewriting $a^x=\exp(x\log(a))$ and using the power series for $\exp(z)$. This is how we have chosen to define calculating generalized exponents. This is a multivalued expression, but for the principal value of $k=0$ we get $(-2)^\sqrt{2}=2^{\sqrt{2}}(\cos(\pi\sqrt{2}) + i\sin(\pi\sqrt{2}))$ which is not a real number because $\sin(\sqrt{2}\pi)\neq 0$.
Comment: Actually there's no $k$ such that $\sin\left((2k+1)\sqrt{2}\pi\right)=0$ because $\sin x=0$ iff $x$ is an integer mutiple of $\pi$, and $(2k+1)\sqrt{2}$ is non-integer for any integer $k$. So there's no reason to restrict to the principal value; no possible value of $(-2)^{\sqrt{2}}$ is real.
Comment: That's an excellent point!
Answer: By definition, $(-2)^\sqrt{2} = \exp(\sqrt{2} \log(-2))$.  This is multivalued because $\log$ is multivalued: we have $\log(-2) = \log(2) + (1 + 2 n) \pi i$ for arbitrary integer $n$.  Thus
$$ (-2)^{\sqrt{2}} = \exp(\sqrt{2} (\log(2) + (1+2n) \pi i)) = 2^{\sqrt{2}}
\exp((1+2n) \sqrt{2} \pi i)$$
In order for this to be real, we would need $ (1+2 n) \sqrt{2}$ to be an integer, and that is not the case because $\sqrt{2}$ is irrational.
Comment: Just to clarify a bit, the general definition, applicable for $a\neq 0$ and $b$ complex, is $a^b = \exp(b\log a)$.  A seeming problem is $\log a$ has infinitely many values, because there are infinitely many $c$ with $\exp c=a$.  However, this is not really a problem (at least in many circumstances)  because by convention we can take the $c$ whose argument is in $[0,2\pi)$.
Comment: We can, but we don't have to.  That's just one convention: the "principal branch".  I was **not** assuming we're taking the principal branch, as this was not specified in the OP; I showed that  **no** branch of $(-2)^{\sqrt{2}}$ is real.
Comment: Note that e.g. if you say $(-8)^(1/3) = -2$, you are **not** using the principal branch.
Answer: No. There are a countably infinite number of possible values of this expression. None of them are real. They are
$$2^{\sqrt{2}}(\cos (2k+1)\pi\sqrt{2} + i\sin(2k+1)\pi\sqrt{2})
$$
The principal value (taking $k=0$) is $2^{\sqrt{2}}(\cos\pi\sqrt{2} + i\sin\pi\sqrt{2})$.
Answer: $$\left(-2\right)^{\sqrt{2}}=\left(\left|-2\right|e^{\arg(-2)i}\right)^{\sqrt{2}}=\left(2e^{\pi i}\right)^{\sqrt{2}}=2^{\sqrt{2}}e^{\pi\sqrt{2}i}=2^{\sqrt{2}}e^{\left(2\pi k+\pi\sqrt{2}\right)i}$$
With $k\in\mathbb{Z}$
Answer: " Is there some reason why $(-2)^{\sqrt 2}$ is not a real number because it doesn't make sense why it shouldn't be."
Well, not having a sensible interpretation is a pretty good reason for something not to be a real number.
1)  $b^n$; $n \in \mathbb N; n \ge 2$ defined as $\prod_{i=1}^n b$ (or "b multiplied by itself n times") is well defined and "makes sense".
2) $b^n$; $n \le 1$ doesn't make sense because you can't multiple a number by itself 0 or a negative number of times.  You can't even multiply a number by itself 1 time.  But multiplication is invertable and is additive in nature so we can extend the definition to include $b^0 = 1$ and $b^{|n|} = (1/b)^{|n|} = (1/b)^{|n|}$ (As well as $b^1 = b$).  So now it does make sense.
3) $b^r$; $r \in \mathbb Q$ doesn't make sense because you can't multiple or divide a number a fractional number of times.  But as we can prove for any non-negative real number $b$ and integer $m \ne 0$ we can find a unique non-negative real number, c, where $c^m = b$.  We call this $c =\sqrt[m]{b}$ but as $(b^a)^m = b^{am}$.  If we called this $c =\sqrt[m]{b} = b^{\frac 1 m}$ we'd have the consistent $(b^{\frac 1 m})^m = b^1 = b$ and we can define $b^{n/m}$ as $\sqrt[m]{b}^n$ !!!!IF!!!! b is non-negative OR m is odd.  The is no real even root of a negative number.  So $(-2)^{3/2}$ is not a real number!  This definition is consistent and now makes sense.  (We have to verify this is truly consistent which I won't do here.)
4) In high school we tend to wave our hands at real numbers.  They are like rational numbers "but with the holes filled in".  So $b^x$ where x is the limit of some sequence of $\{q_i\} \subset \mathbb Q$ can be defined as the limit of {$b^{q_i}$}.  (Okay, a lot of verifying needs to be done that I will omit.)  But if $b < 0$ this sequence isn't defined for any rationals with even denominators and need not converge at all.
So $(-2)^{\sqrt{2}}$ isn't a real number and it wouldn't make sense that it were.
======
Do I want to confuse you further?  In the shower I was wondering that as for all $q \in \mathbb Q$ $q = \sup\{r \in \mathbb Q| r \le q;$ r in reduced form has an odd denominator}, if you could have modified the definition of $b^q$ as the limit of {$b^{r_i}$} where $r_i$ are a sequence of rationals with odd denominators that converge to $q$.
If so than we'd have $(-|b|)^q = -|b|^q = -\sqrt[m]{|b|}^n$. And we could define $b^x$ as the limit of $b^{q_i}$ where the $q_i$ converge to x.
Could we do that?  It would mean that $b^{1/m}$ need not be the same as $\sqrt[m] b$, but could we do that?  We'd lose complex analysis but...
Then I realized we could but then we'd no longer have the $b^x b^y = b^{x+y}$ rule.
Comment: So any irrational number can be represented as the limit of some sequence of rationals?
Comment: That is the definition of real numbers.
Comment: It's why the reals don't have "holes".  It's also why $\sqrt{2}$ is considered a "hole" but $\sqrt{-1}$ is not.
Comment: @Puzzled417 The irrational numbers are originally constructed that way using [Dedeking cuts](https://en.wikipedia.org/wiki/Dedekind_cut). Or note that e.g. $\overline{0.a_1a_2a_3a_4...}=\lim_{n\to +\infty}\sum_{i=1}^n \frac{a_i}{10^i}$.

Is $(-2)^{\sqrt{2}}$ a real number?


Error 400: Invalid prompt for Google Calendar API PHP

Question: I'm using the codes from Google documentation. Link
My codes are like this,
<code>$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
</code>
But when I run this, it's giving an error.
<code>400. That's an error.
Error: invalid_request
Invalid parameter value for prompt: Invalid prompt: select_account consent/calendar
</code>
Please help.
Thanks in advance.
Answer: If you check the source code for the libraryclient.php
<code>   /**
   * Set the prompt hint. Valid values are none, consent and select_account.
   * If no value is specified and the user has not previously authorized
   * access, then the user is shown a consent screen.
   * @param $prompt string
   */
  public function setPrompt($prompt)
  {
    $this->config['prompt'] = $prompt;
  }
</code>
I dont think you can have both i think you should be setting it to one or the other
<code>$client->setPrompt('consent');
</code>
which would imply that there is a bug in the tutorial you are following.
My code
<code>    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
    $client->setRedirectUri(getRedirectUri());
</code>
my code Oauth2Authentication.php  and oauth2callback.php
Comment: Dear @DalmTo, Thanks for your suggestion.
I've checked with both '**select_account**' and '**consent**'.
But everyone gives error.

When I used '**select_account**', it's giving
`Invalid parameter value for prompt: Invalid prompt: select_account/calendar`

When '**consent**',
`Invalid parameter value for prompt: Invalid prompt: consent/calendar`
Comment: What happens if you remove that line totally?
Comment: It's giving `Invalid parameter value for approval_prompt: 'auto/calendar' is not valid`
Comment: AS you can see i dont use the prompt
Comment: I'm getting this now `Invalid parameter value for include_granted_scopes: Invalid value, must be one of false, true: true/calendar` :(
Comment: I have no idea where you are getting theses values from you cant just put stuff in the need to be valid.


Render unicode emoji in colour in ggplot2 geom_text

Question: I have unicode text that includes emoji. I'd like to render them in a ggplot2 graphic with geom_text or geom_label in a way that includes the emoji's colour. I've looked at emojifont, emo and ggtext and none of these seem to allow this. The issue of course is that the colour of the text in geom_text is governed by the colour aesthetic. Is there any way I can get colours rendered in my text, either through geom_text or some other workaround?
Reproducible example:
library(ggplot2)

pets <- "I like    "

cat(pets)

ggplot() +
  theme_void() +
  annotate("text", x = 1, y = 1, label = pets, size = 15)

The cat(pets) works on screen in RStudio, but the graphic drawn with the last line looks like this:

Alternatively, with ggtext::geom_richtext() I get a similar black and white result and this error message:
> library(ggtext)
> ggplot() +
+   theme_void() +
+   annotate("richtext", x = 1, y = 1, label = pets, size = 15)
Warning messages:
1: In text_info(label, fontkey, fontfamily, fontface, fontsize, cache) :
  unable to translate 'RStudioGD142.6791338582677' to native encoding
2: In text_info(label, fontkey, fontfamily, fontface, fontsize, cache) :
  unable to translate 'RStudioGD142.6791338582677' to native encoding
3: In text_info(label, fontkey, fontfamily, fontface, fontsize, cache) :
  unable to translate 'RStudioGD142.6791338582677' to native encoding
4: In text_info(label, fontkey, fontfamily, fontface, fontsize, cache) :
  unable to translate 'RStudioGD142.6791338582677' to native encoding
5: In do.call(gList, grobs) :
  unable to translate 'I like    ' to native encoding

Answer: OK, here's an answer to my own question.
Overall approach: we convert each emoji to a hyperlink to an image of the emoji, and use ggtext to render the new version of combination of text and images.
First we need a vector of all emoji so down the track we will be able to recognise them:
library(tidyverse)
library(ggtext)
library(rvest)

# test vector
pets <- "I like    "

# the definitive web page with emoji:
unicode <- read_html("https://unicode.org/emoji/charts/full-emoji-list.html")

ut <- unicode %>%
  html_node("table") %>%
  html_table()

# vector of all emoji - purely for recognition purposes
all_emoji <- ut[,3]

Then I borrow with virtually no alteration several functions from this page by Emil Hvitfeldt. Emil had a similar challenge to me, but without the problem of the original emoji just being text.
emoji_to_link <- function(x) {
  paste0("https://emojipedia.org/emoji/",x) %>%
    xml2::read_html() %>%
    rvest::html_nodes("tr td a") %>%
    .[1] %>%
    rvest::html_attr("href") %>%
    paste0("https://emojipedia.org/", .) %>%
    xml2::read_html() %>%
    rvest::html_node('div[class="vendor-image"] img') %>%
    rvest::html_attr("src")
}

link_to_img <- function(x, size = 24) {
  paste0("")
}

Those links take an emoji and convert it into a hyperlink to an image of the emoji as rendered by the Apple Color Emoji font. So far so good, but I need to extract the emoji from my mixed test in the first place. To do this I wrote two more functions

to convert an individual token (where a token might be an individual emoji) into an emoji or return it as unchanged text; and
to tokenize a text string, convert any emoji tokens to images, and then paste them all back together again.

Here's those two functions:
token_to_rt <- function(x){
  if(x %in% all_emoji){
    y <- link_to_img(emoji_to_link(x))
  } else {
    y <- x
  }
  return(y)
}

string_to_rt <- function(x){
  tokens <- str_split(x, " ", simplify = FALSE)[[1]]
  y <- lapply(tokens,  token_to_rt)
  z <- do.call(paste, y)
  return(z)
}

Now we have everything we need. First I convert my pets vector into pets2, then I can use ggplot2 and ggtext to render it on screen, in glorious colour
pets2 <- string_to_rt(pets)

ggplot() +
  theme_void() +
  annotate("richtext", x = 1, y = 1, label = pets2, size = 15)

There we are:

For completeness, here's how the key objects pets, pets2 and all_emoji look when just printed in the R console:
> pets
[1] "I like \U0001f436 \U0001f431 \U0001f41f \U0001f422"
> pets2
[1] "I like    "
> all_emoji[1:10]
 [1] "face-smiling" "Browser"      "\U0001f600"            "\U0001f603"            "\U0001f604"            "\U0001f601"
 [7] "\U0001f606"            "\U0001f605"            "\U0001f923"            "\U0001f602"

Comment: Close readers will note that this workflow depends on there being spaces on either side of the emoji. I imagine some extra work would be needed to harden this for use with real data.


Why does .gitignore appear in git status?

Question: I have some perl scripts that should be under git versioning. I run ctags against them to be able to jump to definitions so a tags file has been autogenerated in the directories. Now I want git to ignore these tags files so I created a .gitignore right next to the .git folder of my repository.
If I do git status I don't see tags but I see .gitignore.
Is .gitignore supposed to appear as an untracked change?
Answer: The .gitignore file is a regular file from Git's perspective. It is normal to create and commit your .gitignore file early in the project as soon as you know what files should be ignored - There is a collation of lots of ignore files somewher on github to cover whatever languages you have in use.  In this can I presume you want this ignoring action to continue, so just commit the .gitignore file with a suitable message e.g. "Added .gitignore file", and carry on happily.
Comment: The ignore works based specifically on the file name, right?Not where a file is located correct?
Comment: Yes, and No. You can have .gitignore files all the way down providing special case processing on a per directory basis. Or you just have a the one all encompassing file at the top level. Try https://github.com/github/gitignore for those templates...


How to change layout of node add/edit form with Display Suite?

Question: Is there a way to use Display Suites to change a Layout for a Node Edit/Add form?
i.e. form at: .../node/add/
Answer: That is possible yes. Display Suite contains a submodule called 'Display Suite Forms' which allows you then to select a layout and move the fields around in that layout.
Note that it's impossible though to move the individual elements in the vertical tabs. That will always remain the same and will rendered at the bottom of the layout.
Comment: when you say it is impossible to move _individual_ elements in the vertical tabs, does that imply one can move the whole vertical tabs container using ds? If so, how?
Comment: Thank you for pointing out that the vertical tabs section will always render at the bottom of the form. I was trying to move it, and couldn't figure out what I was not doing correctly.
Comment: You can always use the [Field group](https://drupal.org/project/field_group) module to create another set of vertical tabs. If you get really crazy, you could move everything from the default vertical tabs into those and then place anything on the form anywhere you want :-p I believe the [Renderable Elements](https://drupal.org/project/rel) module would make that possible.
Comment: I spent a while trying to change the content edit form with display suite but this shows it was a dead-end.
Comment: In Drupal 8 use the Field Layout module from core instead. Display Suite Form submodule was removed from the 8.x branch of DS because of that.


How to do the Ljung-Box test in R?

Question: I'm trying to do a Ljung-Box test in R, but I'm getting an error and I don't understand where is the problem.
Let's use the code from example in "Forecasting: Principles and Practice" to get Google's daily closing stock price
library(fpp3)
google_stock <- gafa_stock  %>%
  filter(Symbol == "GOOG")  %>%
  mutate(day = row_number()) %>%
  update_tsibble(index = day, regular = TRUE)

google_2015 <- google_stock %>% filter(year(Date) == 2015)

I obtain the residuals from forecasting the series using the naïve method
aug <- google_2015 %>% model(NAIVE(Close)) %>% augment()

Now I want to do a formal test for autocorrelation in the residuals using the  Ljung-Box test
aug %>% features(.resid, ljung_box, lag=10, dof=0)

But I get this error in the output:
# A tibble: 1 x 2
  Symbol .model
  <chr>  <chr>
1 GOOG   NAIVE(Close)
Warning message:
1 error encountered for feature 1
[1] 'ts' object must have one or more observations

What am I doing wrong?
This is a sample of the dataset (with dput() ):
    > dput(head(google_stock, 10))
structure(list(Symbol = c("GOOG", "GOOG", "GOOG", "GOOG", "GOOG",
"GOOG", "GOOG", "GOOG", "GOOG", "GOOG"), Date = structure(c(16072,
16073, 16076, 16077, 16078, 16079, 16080, 16083, 16084, 16085
), class = "Date"), Open = c(554.125916, 553.897461, 552.908875,
558.865112, 569.297241, 568.025513, 565.859619, 559.595398, 565.298279,
572.769714), High = c(555.26355, 554.856201, 555.814941, 566.162659,
569.953003, 568.413025, 565.859619, 569.749329, 571.781128, 573.768188
), Low = c(550.549194, 548.894958, 549.645081, 556.95752, 562.983337,
559.143311, 557.499023, 554.975403, 560.400146, 568.199402),
    Close = c(552.963501, 548.929749, 555.049927, 565.750366,
    566.927673, 561.468201, 561.438354, 557.861633, 570.986267,
    570.598816), Adj_Close = c(552.963501, 548.929749, 555.049927,
    565.750366, 566.927673, 561.468201, 561.438354, 557.861633,
    570.986267, 570.598816), Volume = c(3666400, 3355000, 3561600,
    5138400, 4514100, 4196000, 4314700, 4869100, 4997400, 3925700
    ), day = 1:10), row.names = c(NA, -10L), key = structure(list(
    Symbol = "GOOG", .rows = list(1:10)), row.names = c(NA, -1L
), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), index = structure("day", ordered = TRUE), index2 = "day", interval = structure(list(
    year = 0, quarter = 0, month = 0, week = 0, day = 0, hour = 0,
    minute = 0, second = 0, millisecond = 0, microsecond = 0,
    nanosecond = 0, unit = 1), class = "interval"), class = c("tbl_ts",
"tbl_df", "tbl", "data.frame"))

Comment: This is a bug that is fixed in the fabletools package on github. See https://github.com/tidyverts/feasts/issues/79
Comment: please provide a sample of your dataset with `dput(head(df, 10))`
Comment: I edited the post with a sample using dput()
Comment: `ljung_box(aug[,'.resid'], lag=10,dof=0)` returns values without error, so this suggests some problem with the handling of `%>%`?
Answer: It looks like you need to select the column of interest (.resid) first, before passing onto the features() function:
aug %>%
select(.resid) %>%
features(.resid, ljung_box, lag = 10, dof = 0)
# Output
# Selecting index: "day"
# A tibble: 1 x 2
  lb_stat lb_pvalue
    <dbl>     <dbl>
1    7.91     0.637

If you don't specify .resid in the features() function, it will still work, by automatically selecting that column (as it's the only one other than the index column):
aug %>%
select(.resid) %>%
features(features = ljung_box, lag = 10, dof = 0)
# Selecting index: "day"
# Feature variable not specified, automatically selected `.var = .resid`
# A tibble: 1 x 2
  lb_stat lb_pvalue
    <dbl>     <dbl>
1    7.91     0.637

How to do the Ljung-Box test in R?


How many cases of material failure were due to all three causes?

Question: $100$
cases of material failure were investigated. In
$30$
of the cases the failure was due to just
faulty heat treatment, in
$40$
cases due to just excessive loading, in
$50$
of the cases to lack of
fatigue resistance. If
$7$
of the failure were due to two types of mechanism , how many were due to
all three?
Comment: I would start by drawing a Venn diagram.
Answer: HINT:
I would look at the inclusion-exclusion principle. If you have any further questions please comment
Answer: As @Vinyl_cape_jawa guided:
$$|A \cup B \cup C| = (|A| + |B| + |C|) - (|A \cap B| + |B \cap C| + |C \cap A|) + (|A \cap B \cap C|)$$
Now just substitute the given values.
Answer: use the inclusion-exclusion principle to solve the question.
|H∪E∪R|=100
|H|=30
|E|=40
|R|=50
|H∪E∪R|= |H|+|E|+|R|-|H∩E|-|H∩R|-|R∩E|-|H∩E∩R|
Because 7 of the failures were due to two types of mechanism, there is only one intersection, therefore:
100= 30+40+50-7-|H∩E∩R|
100= 120-7-|H∩E∩R|
100=113-|H∩E∩R|
|H∩E∩R|=113-100
|H∩E∩R|= 13


How to get current month in webdriver using java

Question: I wonder if someone can help!
I've been using following 'Get_Date' class with method 'Get_month' to return the current month but I've now decided to move onto webdriver but am not sure what the webdriver equivalent of following function be.
package hisScripts;
import com.thoughtworks.selenium.*;

public class Get_Date {

public String Get_Month(Selenium selenium) {
    return selenium.getEval("var MonthNames =  [ \"Jan 2012\", \"Feb 2012\", \"Mar 2012\", \"Apr 2012\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Nov 2011\", \"Nov 2011\", \"Dec 2011\" ];d = new Date();MonthNames[d.getMonth()];");
   }
}

Answer: Try this:
 public String get_Month(){
   Date date = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat("MMMMMMMMM");
   return formatter.format(date);
 }

In case of this month it will return April
If you need other notations, refer to SimpleDateFormat


Developing traditional style webapps with GWT

Question: In many JVM web frameworks survies and Indeed.com trends graphs, GWT looks to be the most (or among the top) popular JVM framework.
But AFAIK, GWT excels when the application is one page app -to some degree of course- (like GMail, Google Reader ..)
Does this mean that new developed Java webapps are one page apps mainly (not traditional request-new page response)?
Is it possible to develop SpringMVC or Struts2 style webapps with GWT? or it is not recommended?
Answer: Absolutely, it is definitely possible to build struts apps with GWT; at some level all the GWT is, is a convenient way of writing javascript (in my perl days, we called it 'syntactic sugar').
You can still use GWT-RPC, JSON, or HTML forms to communicate with the server.
You can attach to any arbitrary HTML element using RootPanel.get("id"); to add javascript widgets.
Almost every javascripty component on my employer's website is written in GWT: http://www.cohomefinder.com/ .  The backend is an old fork of struts.
And here's a nice, though a bit dated, article about building 'normal' websites in GWT: http://www.canoo.com/blog/2007/03/13/building-a-regular-website-with-the-google-web-toolkit/
I'm not sure, however, that this use of GWT is where it really shines.  One downside is a lot of javascript parsing on every page load.  Code splitting can help with that, some.


Permission to submit webform only for the author of the node

Question: I'm using webform 8.x for a personal project and I'd like to know if it possible to enable only the author of the node to submit the form.
In my project each node is an aquarium, and I am using webform to collect the all the daily data for that specific node ( aquarium ), like temperature, pH, KH ecc.
I was able to create a view related to the node (aquarium) where you can see the data submitted daily for that specific aquarium, but the problem is that everyone can submit the form, while I need only the author of the node to be able to submit the webform.
Can you please give me some ideas? I'm stuck..
Answer: You haven't said if this is Drupal 7 or Drupal 8 but this should work for D8
It sounds like each author already has a user account on your website, so you can go to "Settings" on your webform and then click the "Access" tab (.e.g /admin/structure/webform/manage/FORM_MACHINE_NAME/access)
And in there you can restrict the ability to create submissions to a specific user(s) only
Comment: Thanks for your answer I`m using Drupal 8. I need this to be automatic, if I'm going to have a lot of users in this way I'll have to manually edit the webform and give permissions to each user manually.
Comment: But from the sounds of it aren't you creating a new webform each time anyway? If you wanted a slicker way of doing it you should have 1 common webform and each user is associated to a aquarium and then you could retrieve all webform submissions from a specific user with would also be their own aquarium
Comment: No, I'm not creating e new webform each time.I've created a webform and I've associated it to a content type  (called my acquariums),  when a user crete a new node ( a new acquarium), the webform appears automatically.
Through a view I intercept the data entered and filter them (using a contextual filter, id from url) so I make sure that only the data entered for that node are rendered... the problem is that now anyone who registers can see and fill the webform for nodes of which they are not authors.
Answer: After consulting Allow comments only for the author of the node
 and This book
I think I can try to answer this question myself:
I made a custom module and I used hook_form_alter:
here is the function:
<code>function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
if($form['#webform_id'] == "YOUR-WEBFORM-ID"){
    $node = \Drupal::request()->attributes->get('node');
 if(!is_null($node) && $node->getOwnerId() != \Drupal::currentUser()->id()) {
     $form['#access'] = false;
 }
}
</code>
}


Getting Null Pointer Exception with Java

Question: I wrote a program to make a stack with the help of Iterator in Java. But I don't understand why I am getting the null pointer exception.
Here is my class for stack
import java.util.Iterator;

public class linkedStack1<Item> implements Iterable<Item>
{

public Iterator<Item> iterator()
{
    return new listIterator();
}

private class listIterator implements Iterator<Item>
{
    private node current = first;
    public boolean hasNext() { return current!=null;}
    public Item next()
    {
        Item item = current.item;
        current=current.next;
        return item;
    }

}

private node first=null;

private class node
{
    Item item;
    node next;
}

public boolean isEmpty()
{
    return first==null;
}

public void push(Item item)
{
    node oldFirst=first;
    first=new node();
    first.item=item;
    first.next=oldFirst;
}

public Item pop()
{
    Item item=first.item;           // ERROR SHOWING HERE
    first=first.next;
    return item;
}}

And my main class is this
import java.util.Scanner;

public class evaluate
{
public static void main(String args[])
{
    Scanner input = new Scanner(System.in);
    String s=input.nextLine();

    linkedStack1<String> ops = new linkedStack1<String>();
    linkedStack1<Double> vals = new linkedStack1<Double>();

    String op;
    double a,b;
    for(int i=0;i<s.length();i++)
    {
        if(s.charAt(i)=='(');
        else if(s.charAt(i)=='+' || s.charAt(i)=='*'
                || s.charAt(i)=='-' || s.charAt(i)=='/')
            ops.push(Character.toString(s.charAt(i)));
        else if(s.charAt(i)==')')
        {
            op =ops.pop();
            a=vals.pop();
            b= vals.pop();            // ERROR SHOWING HERE
            if(op=="+") vals.push(b+a);
            else if(op=="-") vals.push(b-a);
            else if(op=="*") vals.push(b*a);
            else if(op=="/") vals.push(b/a);
        }
        else if(s.charAt(i)==' ')
            continue;
        else
            vals.push(Double.parseDouble(Character.toString(s.charAt(i)) ));

    }

    System.out.println(vals.pop());

}
}

But when I execute this code for some input, say (1+(2*3)),
I get the null pointer exception
Exception in thread "main" java.lang.NullPointerException
    at linkedStack1.pop(linkedStack1.java:47)
    at evaluate.main(evaluate.java:25)

I have made the comments in front of the specified line numbers, so you can have a look at that,
and help me figuring out what's the bug in my code!!
Comment: possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it)
Comment: So the error says that there is a null pointer in `first.item`. If `item` where NULL you wouldn't get an error right? so `first` must be NULL? What is `first` initialized to and when is it set to another value? That will show you how/why it is still NULL now and then you can correct your code.
Answer: When your stack is empty and you call pop, first.item throws a NullPointerException since first is null.
This means you are popping more elements than exist in your stack here :
        a=vals.pop();
        b= vals.pop();            // ERROR SHOWING HERE

you should check the stack is not empty before calling pop.
Comment: But it doesn't mean that popping elements from the stack would change anything.
Comment: @RomanC when the stack is empty, `first` is null, and pop() throws `NullPointerException`. It doesn't matter if you call pop before ever calling push, or call push 4 times and then pop 5 times. The result would be the same.
Answer: Your first element is initialized to null.

private node first=null;

But you use it in the pop method running before push() where you assign a new value. Either you initialize first to a valid value or change your code to use push() before the pop().
Answer: A textbook error.
You're comparing references (==) not values (equals()).
The result of the operation is not getting pushed onto the stack
Try this:
        if(op.equals("+")) vals.push(b+a);
        else if(op.equals("-")) vals.push(b-a);
        else if(op.equals("*")) vals.push(b*a);
        else if(op.equals("/")) vals.push(b/a);

In place of:
        if(op=="+") vals.push(b+a);
        else if(op=="-") vals.push(b-a);
        else if(op=="*") vals.push(b*a);
        else if(op=="/") vals.push(b/a);

See also:
How do I compare strings in Java?


Adding/replacing/patching std libraries

Question: I have a (self-written) runtime library which I have used in various programming projects over the years. It started life as a Pascal library in the early days of Turbo Pascal and has since progressed through incarnations in C, Perl and Lua. I am now contemplating to move this over to Go (not least because there are some interesting parallels between Go and Lua). A good part of Go's std library does more or less what my own libraries do (for instance, the flag package or the regex stuff) in which case I can either use them directly or get away with writing a small interface layer.
Problems start with those packages where my model is too different from Go's for a simple interface layer to hide the differences (a case in point are the directory-walking functions). I see two ways forward: re-implement my code as a Go package; or patch some of the existing Go runtime packages.
I am leaning towards the first option, not least because this will help me to get to grips with the language. Then again, I've often patched source code for my own requirements and I am comfortable with that approach. The changes would be localised and it shouldn't be too difficult to merge future version of Go's runtime library with my changes.
So is it feasible, advisable to do that or do I have to regard the Go sources as read only?
Comment: I find it hard to imagine what might be in your personal library that makes you think that it's worth the effort to patch a whole programming language. Can't be regex handling, that's for sure.
Comment: Obviously you have not really read what I wrote. I specifically said that regexes are NO problem area. And I also said that any changes would be localised and not in any way "patching a whole programming language".
Answer:
So is it feasible ... ?

No. Everything will break once you touch the Go stdlib as every package out there relies on the stdlib.

So is it ... advisable to do that ...?

No, not at all.

[D]o I have to regard the Go sources as read only?

Yes.
Note that what you call "runtime" is not the Go runtime but the Go's standard library.
Comment: "that any patch/change would be made in such a way as not to break existing code" then I have to admit I do not have the slightest clue what you are talking about. What are changes that do not change anything? Internal (non API) code refactoring are invisible from the outside, so they are not helpful and all other changes might break existing stuff. When you change flag handling everything that depends on the original way will potentially break.
Comment: @tmsg Even your "trivial" example can easily break: Extending a `struct` with additional fields may not be backward compatible, it may even cause a compile-time error. E.g. see this example: [Go Playground](https://play.golang.org/p/QufqD6yTQ4). It compiles and runs (does nothing though). Now if you add a new `Y int` field to struct `A` (`A` by itself remains "flawless"), it won't even compile anymore: `ambiguous selector c.Y`, see this version on the [Go Playground](https://play.golang.org/p/Jb2LNzo1fR).
Comment: I should have added in my OP that any patch/change would be made in such a way as not to break existing code (in theory, in practice there may be cases where it does happen).
Comment: Trivial (AND NOT A REAL) example. Some structures in Go's std packages would need to carry more information for my purposes. I can extend those structures with new fields, add some lines in those std functions that use them and the whole thing is still 100% backwards compatible. (Of course, there may be clashes when a new version of those package is released with a new version of Go; that is where the merging part of my question comes in.)
Comment: Valid point... though to continue that point... I am patching a library whose source code I can inspect so I am able to avoid this sort of clash. Whether this approach is not too error-prone and also too much trouble to be worth it, is another matter. Probably not and that is why I wrote that I am leaning towards the other option.

Adding/replacing/patching std libraries


Como imprimir um JSON array?

Question: var listaNomeProjeto =
    [{
        "nomeProjeto": "NomeProjeto1",
        "subProjeto": [
                "Sub Projeto1",
                "Sub Projeto2",
                "Sub Projeto3",
                "Sub Projeto4",
                "Sub Projeto5",
                "Sub Projeto6",
                "Sub Projeto7"
            ]
    },{
        "nomeProjeto": "NomeProjeto2",
        "subProjeto": [
            "Sub Projeto1",
            "Sub Projeto2",
            "Sub Projeto3",
            "Sub Projeto4"
        ]
    }];

Tentando imprimir com laço de repetição:
- No $(this).val() é recebido o valor de um select box.
    for( var i = 0; i< listaNomeProjeto.length; i++){
        if(listaNomeProjeto[i].nomeProjeto === $(this).val()){
            console.log(listaNomeProjeto[i].subProjeto[0]);

        }
    }

Eu faço uma busca no nomeProjeto, se eu achar o nome eu tenho que printar todo o conteúdo dentro do subProjeto. Eu devo fazer mais um loop para percorrer a array que está dentro do subProjeto? Poderiam me ajudar?
Answer: Vou sugerir uma solucão diferente, sem usar loops. Primeiro filtre pelo que você está procurando com o método filter:
listaFiltrada = listaNomeProjeto.filter(function(e) {
    return e.nomeProjeto === 'NomeProjeto2'
});

Essa lista contém apenas os projetos que você procura. Dentro da funcão você define os critérios para filtrar os resultados. Agora vamos transformar a lista, para obter a informação que você quer, com o método map:
subProjs = listaFiltrada.map(function(e) { return e.subProjeto; });

Para exibir a lista de subProjetos, forEach:
subProjs.forEach(function(e){ console.log(e); });

Sei que em javascript não fica bonito, mas se quiser você pode fazer tudo encadeado:
listaNomeProjeto
    .filter(function(e) { return e.nomeProjeto === 'NomeProjeto2' })
    .map(function(e) { return e.subProjeto; })
    .forEach(function(e){ console.log(e); });

Acho bem mais legível do que usar loops :)

Como imprimir um JSON array?


Adding custom Button to AppBarButton in Windows Phone 8.1

Question: Just getting into Windows Phone 8.1 development.
I quite like it but I am struggling getting accurate development info.
I am working with the Page.BottomAppBar.
I want to use an png image I have created as one of the buttons.
Does this image I created have to be:

A certain size
A certain format
A certain choice of colors i.e. i can use multiple colors and not just black and white

I am looking to create a 'Login' button you see.
thanks
Answer: Please, check the official Microsoft guidelines for app bars for Windows store and guidelines for windows phone. Guidelines cover icons, sizes and formats. It's better to follow them in designing visual style of your app.
Comment: Here is the [guide for icons](http://msdn.microsoft.com/en-us/library/windows/apps/ff431806(v=vs.105).aspx).
Comment: Format is PNG (icons should be transparent), size actually can vary. Framework will resize it very well. Colors are not possible due to internal support of black and white themes (framework will invert icons for you for the black theme).
Comment: Hi, thanks for that link. I have seen it before.  This details a lot of info for Metro apps.  I am focusing on Windows Phone 8.1. I know there is a section there, but I just want to know the answers to my basic questions above. Microsoft help I have always personally found unhelpful.  I just want to find direct answers to my questions. I personally find MS tend to  obfuscates my searching for direct info. Hence, why I posted my question here. But thanks for your time :)
Comment: Hi Again :). So, 48x48 is the size limit? I cannot use colors?  What about the format i.e. ico, bmp, jpg etc. thanks for that link too :)


How to use asterisk in a shell program

Question: I want to use Asterisk in a shell Linux program more or less like this :
asterisk -r && console dial 101

How can I do that ?
Thank you.
Comment: Do you mean that you want to run an asterisk command from your shell?
Comment: I am truly sorry, I'm not fluent in English.
It's exactly that, yes
Answer: You can run an asterisk command by adding the -x option.
From the man page:
       -x command
              Connect to a running Asterisk process and execute a command on a
              command line, passing any output through  to  standard  out  and
              then  terminating  when the command execution completes. Implies
              -r when -R is not explicitly supplied.

So you can do something like:
asterisk -rx "pjsip show endpoints"

How to use asterisk in a shell program


how can i extract all the rows of the dataframe where there is a symetrical [column A = i, column B = j ] and [column A = j, column B = i]

Question: I am working on a graph problem, and want to drop the data where two nodes A and B would be connected twice
A to B
B to A.
Could you help me with that please ?
I have a dataframe data

Column A
Column B

value 1
value 2

value 1
value 3

value 2
value 3

value 2
value 1

I want to extract a dataframe of all the cases where we have these two conditions respected

Column A
Column B

value i
value j

value j
value i

in our example :

Column A
Column B

value 1
value 2

value 2
value 1

thank you very much !
I tried looping and creating lists but it's time consuming and not very aesthetic :
`l=[]
indexes=[]
for i in data['aretes']:
l.append([list(data[data['aretes']==i]['column A'])[0],list(data[data['aretes']==i]['column B'])[0]])

index = 0
for j in l:
index+=1

h=[j[1],j[0]]

if h in l:

    indexes.append(index)`

Answer: If you want to extract the all the rows in the dataframe that are duplicated, I would first create a string representation of the set of your nodes to create a sorted id:
df["id"] = df.apply(lambda x: str(set([x['a'],x['b']])),axis=1)

Then you can used the duplicated function to drop all the rows that are not duplicated according to the id:
df[df.duplicated(["id"],keep=False)]

Results:
    a           b           id
0   Value 1     Value 2     {'Value 1', 'Value 2'}
1   Value 2     Value 1     {'Value 1', 'Value 2'}

Answer: Convert your column as set then remove duplicates:
>>> df[df[['Column A', 'Column B']].agg(set, axis=1).duplicated(keep=False)]
  Column A Column B
0  value 1  value 2
3  value 2  value 1

Caveats: if you have 2 instances of (value 1, value 2), they will be extracted. You can also find a solution with NetworkX.


Use same header and footer on all webpages

Question: I'm working on an ASP.NET website, which I'm building in Visual Studio.
I want to reuse the header and footer on all pages without copying the HTML to all of them.
I have looked through the below answers, but they're both written for PHP. Can someone please help show how to do this in ASP.NET?
How to display same header and footer on different pages?
Keeping my header and footer on all webpages?
Comment: I want to re ask this question. Lets say i m working on MVC and not WebForm. Then what?
Answer: You should use ASP.NET Master Pages for this purpose:

ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

Master Pages allow you to centralize the common functionality of your pages so that you can make updates in just one place.
Comment: @mason Thanks guys for answering, Im working on WebForms but not all the pages are perticularly webForms, some are simple Web pages and i have an idea about master page, but will it be the best choice compared to using 'include' or 'user control'?
Comment: @Taqueroutlaw.shade Why not just convert all your simple HTML pages over to Web Forms .aspx? That way you can take advantage of some of the Web Forms features like Master Pages and virtual URL path resolution.
Comment: @mason i guess that's be the best way to do it. thanks


How can I compute the partial derivative under the line integral sign if the integrand is non-conservative?

Question: Consider the following integral
$$I=\int_C^{\vec{y}_{0},\vec{y}} \vec{F}(\vec{x})\cdot d\vec{x}$$
where, for simplicity, $\vec{y}_{0}$ is some constant initial point on $C$ (which is an explicitly known curve) and $\vec{y}$ is some variable end point on $C$ and it is known that
$$\oint_{C_0} \vec{F}(\vec{x})\cdot d\vec{x} \neq 0 $$
for any closed curve $C_{0}$.
Does it still make sense to speak of the gradient
$$\left(\frac{\partial}{\partial y_{1}},\frac{\partial}{\partial y_{2}},\frac{\partial}{\partial y_{3}}\right)I$$
of the integral with respect to $\vec{y} = \left(y_{1},y_{2},y_{3}\right)$ ?
If so, then three questions follow.
1) If this gradient exists then doesn't that contradict the premise that $\vec{F}$ is non-conservative?
2)  Is there an equivalent of the Leibniz integral rule which specifies such a gradient?
3) How does it depend of the curve $C$?
Otherwise, how can we characterize the variational properties of this differentiation under the integral?
Answer: $I$, as you have given it, is not a well-defined function of $y$. There may be two different curves ending at $y$, yielding two different line integrals. Which one should I choose to compute the value of $I$ at any given $y$?
Only when the vector field is conservative do we know that this function is well-defined. Only then may we take its gradient.
Comment: The Curve in question is $C$ and has been given as part of the definition of $I$. So, there cannot be two curves as you say. There is exactly one curve and its name is $C$.
Comment: @MahlomolaDanielCwele If the curve $C$ is fixed, then yes, we get a well-defined function. But it is no longer a function of three independent variables. For example, if the curve is the $y_1$ axis, then how do we define $\partial I/\partial y_2$? This function does not appear to take any $y_2$ as input.
Comment: The curve does not have to be one of the coordinate axes and, even if it is, the integral itself will still depend on the other coordinates simply because the integrand is assumed to depend of the global 3-D space.

That is, $I=I(\vec{y},C)$ depends both on the chosen curve and on the coordinate system. We know that if the integrand was conservative, the curve $C$ would be irrelevant, resulting in $I=I(\vec{y})$.
Comment: To compute $\partial I/\partial y_2$, then we must compute $(I(y_2+h)-I(y_2))/h$. But $y_2+h$ is not the endpoint of your curve $C$. So either $C$ is not fixed in which case $I$ is not defined, or else the derivative is not defined.
Comment: Those are not the only two options. The other option could be that $\frac{\partial I}{\partial y_{2}} = 0 $ globally. That's what it means for a function to NOT depend on a given variable.  But it does not imply that the function is not defined.
Comment: You do not get to dictate what $\partial I/\partial y_2$ is. Once the function $I$ is given, its derivative is uniquely defined via the standard definition. You can only find its derivative to be $0$ if you find $I$ to be constant function in the $y_2$ direction. But so far, you have not given a function $I$ at all.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/68204/discussion-between-mahlomola-daniel-cwele-and-ziggurism).