Having trouble with CustomValidator that checks RadioButtonList and TextBox values in asp.net

Question: I have a form with contains, among others, a TextBox called "wmi_cell_phone" and a RadioButtonList "wmi_send_sms".
Basically, I need to create a validator that checks whether the value of the selected radio is "Y". If this is the case, then it checks if the TextBox value is empty or not. If it is empty, then it should notify the user to enter a value.
Here is my .aspx code:
<asp:TextBox ID="wmi_cell_phone" runat="server" MaxLength="100" Width="200px"></asp:TextBox>
<asp:RadioButtonList ID="wmi_send_sms" RepeatDirection="Horizontal" runat="server" Width="140px" CssClass="radio"></asp:RadioButtonList>

and code-behind (VB):
wmi_send_sms.Items(0).Value = "Y"
wmi_send_sms.Items(1).Value = "N"

My validator
<asp:CustomValidator ID="val_wmi_send_sms" runat="server"
ClientValidationFunction="ValidateSMS"
Display= "Dynamic"
ErrorMessage="Please enter a valid phone number."> </asp:CustomValidator>

Bu it doesn't seem to work.. Maybe I'm accessing the RadioButtonList in the wrong way..
Comment: What means `it doesn't seem to work`?
Do you have debugged the js-function? Post also the markup of your Validator.
Comment: I mean, it's not doing what it's supposed to do... if the user select the Radio with the value of "Yes", and leaves the TextBox empty, it should alert the user that he's supposed to enter a value in the TextBox.. but it doesn't do anything
Comment: Do you have debugged if the js-function is called? Use developer tools for ie: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=95e06cbe-4940-4218-b75d-b8856fced535 or FireBug for Firefox: https://addons.mozilla.org/en-US/firefox/addon/1843/
Answer: You should first debug if the ClientValidationFunction gets called by the Validator.

Use developer tools for ie: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=95e06cbe-4940-4218-b75d-b8856fced535
FireBug for Firefox: https://addons.mozilla.org/en-US/firefox/addon/1843/

If the Validator should work even if nothing was selected you have to set ValidateEmptyText to true.

Does the ValidationGroup value match in all 3 places: the submit button, the validator control, and the control to validate?
Does the submit button have CausesValidation=true?
Does the RadioButtonList has CausesValidation=true?
Answer:
"Maybe I'm accessing the
  RadioButtonList in the wrong way.."

Yep.
Look at the markup generated, it will be something like this:

      <input id="wmi_send_sms_0" type="radio" name="wmi_send_sms" value="Y" />
      Y

      <input id="wmi_send_sms_1" type="radio" name="wmi_send_sms" value="N" />
      N

Your <%= wmi_send_sms.ClientID %> tag is getting the ID of the table enclosing the radio button list.
Personally, when working on the client side, I find it much easier to avoid RadioButtonList. Just create two RadioButton controls, using the GroupName property to associate them with each other.
<asp:RadioButton ID="wmi_send_sms_y" runat="server" GroupName="wmi_send_sms" Text="Y" />
<asp:RadioButton ID="wmi_send_sms_n" runat="server" GroupName="wmi_send_sms" Text="N" />

Then you can check if the "Y" one is checked in your validator by accessing <%= wmi_send_sms_y.ClientID %>
Comment: Thanks Carson63000 for your input, I appreciate it! Unfortunately, I'm working on a existing project for a client at the company I work for. I can't change the design of the application (so I won't be able to change from RadioButtonList to RadioButton).. All I'm allowed to do is add the Validator to the existing code :( You know how it is!
Comment: Fair enough. OK, with a bit of fiddling, I couldn't find any super easy way to grab the client ID of an individual button inside a RadioButtonList. But <%= wmi_send_sms.ClientID %> gets you the table which you can look inside - ultimately, you'll need to find the actual  elements and see which is checked. jQuery would make this a lot easier, if you can use that.
Comment: Alternatively, you *could* just assume that the ID of the first  will be the ClientID of the RadioButtonList with "_0" on the end of it; i.e. getElementsByName('<%= wmi_send_sms.ClientID %>_0') But I'm not 100% sure that this would be safe or guaranteed to never change.


How to reset Git LFS Storage?

Question: I started to use git LFS because I worked on .wav files.
But for no reason I receive github mails saying that my account is blocked for exceeded quota with 1.5GB over 1GB.
However I want to reset this storage but I don't know how to do so.
Can someone help me ?
Answer: This method works FOR me :)

Delete those repositories in GitHub.com
Create some blank repositories to refresh your git LFS storage.
Note: you can't reset your bandwidth by yourself. You must wait 30 days to avoid
a problem that causes limit storage

Try this:
https://weirdbearddev.com/resources/learning/configuring-git-lfs-to-use-dropbox/
The official doc from github:  https://docs.github.com/en/repositories/working-with-files/managing-large-files/removing-files-from-git-large-file-storage#git-lfs-objects-in-your-repository

How to reset Git LFS Storage?


Is there a way to get a node via a Map value in LEMON Graph library?

Question: I am the using LEMON Graph library and was wondering if there is an efficient way to receive a ListDigraph::Node x via the value of its corresponding ListDigraph::NodeMap?
I was thinking about something like:
lemon::ListDigraph lg;
lemon::ListDigraph::NodeMap<std::string> nodeColor(lg);

lemon::ListDigraph::Node n = lg.addNode();
nodeColor[n] = "red";

lemon::ListDigraph::Node m = lg.addNode();
nodeColor[m] = "green";

# now I'd like to have something like:
lemon::ListDigraph::Node x = nodeColor.getNodeFromColor("red");

Does something like this already exist in LEMON? If there is no other way than writing my own map, how do I return the key (Node)? Can I iterate over the underlying values of the map?
Answer: Unfortunately, it is not possible to obtain the keyset (or the respective nodes) from Lemon's NodeMap, see the NodeMap reference.
There is also no way to iterate over the map. The best way to overcome this is to write your own map, as you write yourself, or use additional helper maps (or similar containers).
Answer: As far as I know, that's not possible in Lemon out of the box. In particular, because the NodeMap is not necessarily one-to-one. There is nothing stopping you from giving all nodes the value "red", and so the backwards query would not have a unique correct result.
You also cannot directly iterate over the contents of a NodeMap. You can, however, iterate over all nodes in the graph, and ask for the corresponding values:
for (lemon::ListDigraph::NodeIt n(lg); n != lemon::INVALID; ++n) {
    if (nodeColor[n] == "red) {
        // do something
    }
}

Or, as you mentioned, you can define your own map:
#include <unordered_map>

lemon::ListDigraph lg;
lemon::ListDigraph::NodeMap<std::string> nodeColor(lg);
std::unordered_map<std::string, lemon::ListDigraph::Node> color2node;

lemon::ListDigraph::Node n = lg.addNode();
nodeColor[n] = "red";
color2node.emplace("red", n);

lemon::ListDigraph::Node m = lg.addNode();
nodeColor[m] = "green";
color2node.emplace("green", m);

lemon::ListDigraph::Node x = node2color.at("red");


GetAsyncKeyState and Numpad numbers [C++]

Question: How would you detect a numpad number keypress? I know this is a stupid question, but I just started recently getting into programming a few days ago and working my way into C/C# and C++.
Here's what I have so far:
<code>if (GetAsyncKeyState(VK_NUMPAD0) {
    // do this
}
</code>
Comment: Are you trying to learn C, C# *and* C++ at the same time? It's like learning Swedish, Danish and Norwegian all att the same time.
Comment: @JoachimPileborg Nope. I'm doing C and C++ first. :/
Comment: I still suggest you learn one language at a time. While C and C++ are similar, they are still *very* different languages.
Comment: @JoachimPileborg Okay. Will keep that noted. Thanks! :D
Answer: I figured out my own question. The code above does work. I just forgot to close the main with another bracket. Silly mistake. Sorry!


Two questions on surface fibrations

Question: Let $X$ be a smooth surface and $f\colon X\to B$ a fibration, with $B$ a smooth curve.
(Q1) Why is the normal bundle of any fiber $F$ trivial?
It is clear to me that it has to be of degree zero since $0=F^2=\deg(O_F(F))$, but why is $O_F(F)=O_F$ ?
For the second question I will assume that $B=\Bbb{P}^1$ and that $X$ is regular, i.e. $H^1(O_X)=0$.
(Q2) Why can we find a short exact sequence of the form
$$0\to\omega_X\to\omega_X\otimes O_X(F_1+\cdots+F_r) \to \oplus O_{F_i}\to0$$
where $r$ is big enough and $F_i$ are general fibres (I guess smooth is enough) ?
What I understand is that by adjunction and (Q1) for each smooth fibre $F$ we have an iso $\omega_X\otimes O(F)\simeq O_F$. But I do not manage to cook up a map as in the sequence above such that the kernel is $\omega_X$.
Answer: If $F=f^{-1}(p)$, then the normal bundle is the pull back of the normal bundle of $p\in B$ and this of course is trivial. The second sequence doesn't look right. You should have $\omega_{F_i}$ s on the right. You always have the natural exact sequence, $0\to O_X\to O_X(F_1+\cdots+F_r)\to \oplus O_{F_i}\to 0$, since $O_{F}(F)=O_F$. Tensoring with $\omega_X$ and noting that by adujunction, $\omega_X\otimes O_F=\omega_F$, you get what I said.
Comment: Dear Mohan, thank you for the prompt answer. Here is the source paper: http://www.math.lsa.umich.edu/~idolga/cortona81.pdf (see top of p.130)

Two questions on surface fibrations


How to build jfreechart-1.0.19 from sources?

Question: I'm trying to build this project:
git clone --depth 1 --branch v1.0.19 https://github.com/jfree/jfreechart.git

With "mvn install" command, there are following errors:
Failed tests:   testFifteenMinIncludedAndExcludedSegments(org.jfree.chart.axis.SegmentedTimelineTest)
  testFifteenMinSegmentedTimeline(org.jfree.chart.axis.SegmentedTimelineTest): expected:<-2208956400000> but was:<-2208967200000>
  testMondayThroughFridaySegmentedTimeline(org.jfree.chart.axis.SegmentedTimelineTest): expected:<-2208988800000> but was:<-2208999600000>
  testFindDomainBounds(org.jfree.data.time.TimeSeriesCollectionTest): expected:<1.199142E12> but was:<1.1991348E12>

Then I trying to build with ANT script
cd ant
ant

And I got jfreechart-1.0.19-bundle.jar 8M weight which is very different from MAVEN's jar https://repo1.maven.org/maven2/org/jfree/jfreechart/1.0.19/ . Please tell me how to build  jfreechart version 1.0.19 form sources?
Answer: Try building from the original source distribution found here. Verify the checksum, unzip the file and build with ant:
$ java -version
java version "11.0.10" 2021-01-19 LTS…
$ md5 jfreechart-1.0.19.zip
MD5 (jfreechart-1.0.19.zip) = 69a5c88439566ac9d7e74cf34c69b7e0
$ unzip -qq jfreechart-1.0.19.zip
$ pushd jfreechart-1.0.19
$ pushd ant ; ant ; popd
…
BUILD SUCCESSFUL

For lib/jfreechart-1.0.19.jar, I get a size of 1_565_109 bytes, comparable  to the 1_565_065 bytes seen here. You also need jcommon-1.0.23.jar, included in the lib directory and found here.
Addendum: Starting from a clone of the repository, a similar approach also works, producing a 1_565_051 byte JAR in lib and an 8M jfreechart-1.0.19-bundle.jar:
$ git clone https://github.com/jfree/jfreechart.git jfreechart
$ pushd jfreechart
$ git fetch --tags
$ git tag --list
…
v1.0.19
…
$ git checkout v1.0.19
Note: switching to 'v1.0.19'…
$ pushd ant ; ant ; popd
…
BUILD SUCCESSFUL
$ git checkout master
$ git status
…
Untracked files:
  (use "git add <file>..." to include in what will be committed)
    jfreechart-1.0.19-bundle.jar
    jfreechart-1.0.19-javadocs.zip
    jfreechart-1.0.19.tar.gz
    jfreechart-1.0.19.zip
    lib/
 …

Comment: Out of curiosity, I tried something similar to your approach. I see the 8M bundle, as well as the `lib` files. More above.


Submersion with contractible fibers

Question: Let $f: M\to N$ be a surjective submersion of manifolds with contractible fibers. Is it true that $M$ and $N$ are homotopy equivalent?
Comment: If $f$ is proper then, as a surjective submersion, it is a fibration, and in this case it is true that it is a homotopy equivalence under the assumption on its fibres. On the other hand it is not true that every surjective submersion is proper, and there are surjective submersions which are not fibrations.
Comment: @Tyrone: Surprisingly, in this setting $f$ is a homotopy equivalence. This is a rather nontrivial result due to Meigniez.
Answer: Surprisingly, your question has positive answer:
Theorem 1. Suppose that $f: M\to N$ is a surjective submersion with contractible fibers. Then $f$ is a fibration (in the sense of Serre). In particular, $f$ is a homotopy-equivalence.
See Corollary 13 in
G. Meigniez, Submersions, fibrations and bundles. Trans. Amer. Math. Soc. 354 (2002), no. 9, 3771–3787.
In fact, this result is proven under a weaker assumption, $f$ is only required  to be a "homotopy submersion".
Remark. In the same paper it is proven (Corollary 31)
Theorem 2. Suppose that $f: M\to N$ is a surjective submersion with fibers diffeomorphic to $R^p$ for some $p$. Then $f$ is a locally trivial (in $C^\infty$ category) fiber bundle.
However, you do not need this stronger conclusion.

Submersion with contractible fibers


Cramer-Rao Lower Bound Proof (fuzzy step)

Question: The following is the derivation of the Cramer-Rao lower bound as detailed on p.336 of Casella and Berger's Statistical Inference:
$\frac{d}{d\theta}E[W(\bf{X})|\theta] = \int_{\chi}W(\bf{x})\left[\frac{\partial}{\partial\theta}f(\bf{x}|\theta)\right]dx=E\left[W(\bf{X})\cdot\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)|\theta\right]$
the derivation then applies the condition $W(\bf{X}) = 1\quad$ therefore:
$0=\frac{d}{d\theta}E[1] =E\left[1\cdot\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)|\theta\right]$
and
$Cov\left[W(\bf{X})\cdot\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)|\theta\right]=\frac{d}{d\theta}E[W(\bf{X})|\theta]$
$Var\left[\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)|\theta\right]=E\left[\left(\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)\right)^2|\theta\right]$
Leading to the lower bound inequality:
$Var(W(\bf{X})|\theta) \ge \frac{(\frac{d}{d\theta}E[W(\bf{X})|\theta])^2}{E\left[\left(\frac{\partial}{\partial\theta}log\;f(\bf{x}|\theta)\right)^2|\theta\right]}$
(this arises directly from the Cauchy-Schwarz inequality where $Cov(X,Y)^2 \leq Var(X)Var(Y)$)
However it seems to me that this crucially depends on $W(\bf{X}) = 1$, (which would mean that if my estimator is not 1 then CRLB doesn't apply). I'm certain there's something I'm missing here and I'm hoping someone could help me out
Answer: The authors' use of $W(X)=1$ is admittedly a bit confusing. They don't want to say that the estimator has to be 1 for all samples of $X$ (which would be absurd). Rather, they want to emphasize that the expectation $E_\theta(\frac{\partial}{\partial \theta}\log f(X|\theta))$ can simply be calculated using the identity labelled (7.3.7) in their book.
What they are really doing here is proving the important result that, under certain regularity conditions, the expected value of the score function is always 0. To see this, write the expectation as an integral (or, for discrete values of $X$, a sum):
\begin{align}
E_\theta(\frac{\partial}{\partial \theta}\log f(X|\theta)) &= \int_X \frac{\partial}{\partial \theta}\log f(x|\theta) f(x|\theta) dx \\ &= \int_X \frac{\frac{\partial}{\partial \theta}f(x|\theta)}{f(x|\theta)}f(x|\theta)dx \\ &= \int_X \frac{\partial}{\partial \theta}f(x|\theta)dx.
\end{align}
If the regularity conditions are met, we can switch the order of integration and differentiation, giving
\begin{align}
\int_X \frac{\partial}{\partial \theta}f(x|\theta)dx = \frac{\partial}{\partial \theta} \int_X f(x|\theta)dx = \frac{\partial}{\partial \theta}1 = 0.
\end{align}
Note that here, we just used that by definition, the integral of a probability distribution over its support is 1, and that the derivative of any constant function is 0.
More on wikipedia: https://en.wikipedia.org/wiki/Score_(statistics)#Properties.
Comment: Thank you, that clears it up!


Save multiple plots as individual PDFs with unique names in R

Question: I have a function that creates a plot and saves it as a pdf file. I plan on running this function in a loop for 100+ columns of a dataset. My question is how to make each pdf file uniquely named so it doesnt overwrite the previous file every time a new one is made. I tried to make it work with C integer format
pdf(file = "~/PTY/Data/ROC Curves/ROC%03d.pdf", onefile = F, width = 7, height = 7)
with the intended outcome of titling each plot ROC001, ROC002... but it still overwrites each new one as ROC001.
createROC <- function(x) {

  ROCtable <- createNAtable(x) #create dataset w/out NAs
  x_NA <-x[!is.na(x)]          #create analyte vector w/out NAs

  #create ROC variable
  newROC <- rocit(score = x_NA, class = ROCtable$DSM, negref = "0", method = "non")

  #create pdf
  pdf(file = "~/PTY/Data/ROC Curves/ROC%03d.pdf", onefile = F, width = 7, height = 7)

  #create ROC plot
  plot(newROC, legend = F)

  dev.off()
  }

My function takes a vector (data1$IL6, data1$age, etc) as an input. Ideally, I would be able to title each plot after the input (IL6, age, etc).
Thank you ahead of time for your help
Comment: Difficult to help you without a sample of your data!
Comment: Pls provide minimal reproducible example
Answer: The problem is that you are opening and closing the graphics device with each plot, and the counter resets at 001 each time. You need one call to pdf(), followed by all of your calls to plot(), followed by dev.off(), like so:
# Some data with named columns
df <- data.frame(a = 1:10, b = 11:20, c = 21:30)

# A plotting function without `pdf()` and `dev.off()`
create_plot <- function(x, main) {
  plot(x, main = main)
}

# Open graphics device
pdf(file = "filename-%03d.pdf", onefile = FALSE)

# Apply plotting function to each column of `df` in a loop
for (j in 1:3) {
  create_plot(df[, j], names(df)[j])
}

# Close graphics device
dev.off()

This should generate filename-001.pdf, filename-002.pdf, and filename-003.pdf in your working directory.


True or False: $A_i$ Set Theory

Question: $\displaystyle
\bigcap_{i=1}^nA_i\subseteq \bigcap_{i=1}^{m+n}A_i\
$ and
$m>0$
I have to describe whether or not this statement is true. From my understanding it is False, but I'm not sure if my logic is flawed.
I took an example where $m=1$ and $n=1$
$\displaystyle
\bigcap_{i=1}^1A_i\subseteq \bigcap_{i=1}^{1+1}A_i\
$
$A_1 \subseteq (A_1 \cap A_2)$
So as $m$ increases the intersection would have a smaller probability of being a superset of $\displaystyle \bigcap_{i=1}^nA_i$
Comment: Don't think about *probability* (although your intuition is correct). Try to give a concrete example in which the claim fails.
Comment: possible duplicate of [Set notation & Identities (Proof)](http://math.stackexchange.com/questions/670307/set-notation-identities-proof)
Answer: You are exactly right. Anyway, you should give an example of $A_1$ and $A_2$. You could take $A_1=\{\emptyset\}$, $A_2=\emptyset$.

True or False: $A_i$ Set Theory


Mostar imagem caso esteja sem conexao com a internet

Question: Mostrar uma imagem caso o dispositivo esteja sem conexao com internet
Boa tarde senhores sou novo em programação Android, estou usando o Android Studio
Seguinte estou desenvolvendo um app que simplesmente chama um webVier, que direciona para meu site, e gostaria de saber como fazer com que se o celular estiver sem conexao com a internet em vez de chamar o webvier ele abra uma imagem.
meu codigo no manifest
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

e estou usando aqui no Main activy
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView delivery;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    leve=findViewById(R.id.site);
    leve.getSettings().setJavaScriptEnabled(true);
    leve.setFocusable(true);
    leve.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    leve.getSettings().setAppCacheEnabled(true);
    leve.getSettings().setDomStorageEnabled(true);
    leve.setWebViewClient(new WebViewClient());
    leve.loadUrl("https://meusite.com.br");
}

}
Espero que tenha sido claro Obrigado por enquanto
Comment: Isto responde à sua pergunta? [Como identificar alteração do estado de conetividade à Internet para executar um método ao conetar?](https://pt.stackoverflow.com/questions/88569/como-identificar-altera%c3%a7%c3%a3o-do-estado-de-conetividade-%c3%a0-internet-para-executar-um)
Answer: Uma opção, seria na sua activity fazer un check para ver se tem internet(google example) e caso não tenha, ao invés de inserir uma imagem na webView, eu usaria um ImageView com a sua imagem de problema de conexão(ou com outra coisa que queira mostrar) e controlaria a visibilidade de um e de outro com base na conexão. Se tenho conexão Webview.visibility = true (posso deixar o ImagemView por default in false) se não tenho conexão faz Webview.visibility = false e ImageView.visibility = true


ngFor not showing data Ionic 4

Question: I tried to loop my data in *ngFor but it's not showing data but in my console, it's showing. Below is my code that I tried.
api.service.ts
    getOrder(orderId): Observable<CustomerOrder> {
       return this.http
      .get<CustomerOrder>(this.apiUrl + 'OrderProduct/' + orderId)
      .pipe(
        retry(2),
        catchError(this.handleError)
      )
  }

orderdetails.component.ts
orderData: any[] = [];

ngOnInit() {
   this.orderId = this.activatedRoute.snapshot.params.orderId;
   this.apiService.getOrder(this.orderId).subscribe(res => {
  Object.assign(this.orderData, res);
  console.log(res);
});
}

orderdetails.page.html
<ion-card *ngFor="let ord of orderData">
      <ion-card-title>

{{ord.Customer?.Name}}

{{ord.OrderNo}}

      </ion-card-title>
      <ion-card-content>
       <ion-list>
          <ion-item>

Items:

            <ion-label>{{ord.OrderProducts?.Product}}</ion-label>
          </ion-item>
          <ion-item>

Quantity:

            <ion-label>{{ord.Quantity}}</ion-label>
          </ion-item>
          <ion-item>

Item Price:

            <ion-label>{{ord.ItemPrice}}</ion-label>
          </ion-item>
        </ion-list>
       </ion-card-content>
      <ion-button type="button" color="primary"
                  style="float: right; padding-right: 5px;padding-bottom: 3px;"
        (click)="closeOrder()">
        Close
      </ion-button>
      <ion-button type="button" color="danger"
                  style="float: left; padding-left: 5px;padding-bottom: 3px;">
        Cancel
      </ion-button>

    </ion-card>

In console it's showing data below it is
Answer: I fixed it. In the ts file, I wrapped data like this.
 this.apiService.getOrder(this.orderId).subscribe(res => {
  this.orderData = [res];
   console.log(res);
});

Comment: Ahhh I see now your order result is not an array. Your approach works, but its a bit of a hack :)  No reason to iterate over what you know to be a single result. Try going back to the old way and using *ngif="orderData" and initializing orderData to null. The you can just refer to orderData.OrderId and such.
Answer: This actually has nothing to do with Ionic and is all about change detection in Angular.
It is because you are not waiting for the data to return before rendering the page.
The simplest way for the current state of your code would be to wrap your ion-card element with an NgContainer like so.
<ng-container *ngIf="orderData.length>1">
add you card HTML here
</ng-container>

The change in data will trigger a change detection which will cause the page to re-render.
But since you are using observables...a better way to do this would be:

Add an async listener to your HTML which consumes the returned data:

<ng-container *ngIf="orderData$ | async as orderData">
<ion-card *ngFor="let ord of orderData">
      <ion-card-title>

{{ord.Customer?.Name}}

{{ord.OrderNo}}

      </ion-card-title>
      <ion-card-content>
       <ion-list>
          <ion-item>

Items:

            <ion-label>{{ord.OrderProducts?.Product}}</ion-label>
          </ion-item>
          <ion-item>

Quantity:

            <ion-label>{{ord.Quantity}}</ion-label>
          </ion-item>
          <ion-item>

Item Price:

            <ion-label>{{ord.ItemPrice}}</ion-label>
          </ion-item>
        </ion-list>
       </ion-card-content>
      <ion-button type="button" color="primary"
                  style="float: right; padding-right: 5px;padding-bottom: 3px;"
        (click)="closeOrder()">
        Close
      </ion-button>
      <ion-button type="button" color="danger"
                  style="float: left; padding-left: 5px;padding-bottom: 3px;">
        Cancel
      </ion-button>
</ion-card>
</ng-container>

And then in your typescript file:

orderData$: Observable<Record<string, unknown>[]>;

ngOnInit() {
   this.orderId = this.activatedRoute.snapshot.params.orderId;
   this.orderData$ = this.apiService.getOrder(this.orderId);
}

ngFor not showing data Ionic 4


Jest: Class extends value # is not a constructor or null

Question: I've setup a jest.env.js file - which I add to the jest.config.js testEnvironment: './jest.env.js' - to handle TextEncoder and TextDecoder. But with my configuration I do get this error in my tests (jest@28):
TypeError: Class extends value #<Object> is not a constructor or null

>  7 | module.exports = class CustomTestEnvironment extends NodeEnvironment {
     |                                                      ^
   8 |   async setup() {
   9 |     await super.setup()
  10 |     if (typeof this.global.TextEncoder === 'undefined') {

I would like to understand the error itself and of course I would like to know how to fix it
My test would work, if I add
global.TextEncoder = require('util').TextEncoder
global.TextDecoder = require('util').TextDecoder

at the beginning of my testfile instead of using testEnvironment.
jest.env.js
const NodeEnvironment = require('jest-environment-node')

module.exports = class CustomTestEnvironment extends NodeEnvironment {
  async setup() {
    await super.setup()
    if (typeof this.global.TextEncoder === 'undefined') {
      const { TextEncoder } = require('util')
      this.global.TextEncoder = TextEncoder
    }
    if (typeof this.global.TextDecoder === 'undefined') {
      const { TextDecoder } = require('util')
      this.global.TextDecoder = TextDecoder
    }
  }
}

Comment: did you manage to find a solution for this error? I am experiencing the same issue.
Comment: @obaqueiro I just use `import { TextDecoder, TextEncoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;`
Answer: You must import TestEnvironment like this:
const NodeEnvironment = require("jest-environment-node").TestEnvironment;
Mentionned here in the doc


Bootstrap Buttons "Loading..." When Clicked

Question: I cannot figure out how to get this feature on my buttons.
http://getbootstrap.com/2.3.2/javascript.html
If you click "buttons" it should take you to the clickable loading button.
<input class="btn btn-xs btn-primary btn-block" type='submit' value='Get Quotes' data-loading-text="Loading...">

I think my issue is that I'm not sure where to put the JS to get this working. Any help would be great.
Thanks!
Answer: You need to instantiate the button() component on the input, and then change it's state accordingly when the button is clicked..
$('#myBtn').button();

$('#myBtn').click(function(){

  $('#myBtn').button('loading');

  /* perform processing then reset button when done */
  setTimeout(function() {
       $('#myBtn').button('reset');
  }, 1000);

});

Bootply
Comment: Still wish I knew what you were talking about.
Comment: The button 'loading..' state just doesn't happen automatically. You need to use jquery (as shown) to get this to happen when the button in clicked.
Answer:

Then call the function 'ValidateFormSignUp' on the CLICK of the button like so
<button type="submit" role="button" runat="server" id="SignUpBtn" name="SignUpBtn" onclick="ValidateSignUpForm(); return false;" class="btn btn-primary" validationgroup="EmailBlast" data-loading-text="Saving..." causesvalidation="true"> Subscribe</button>

Answer:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">`

<button type="submit" id="myBtn" class="btn btn-primary mr-2" >
 enter code hereSubmit
</button>


Unable to compile MeshLab from source on Ubuntu 16.10

Question: I've downloaded the MeshLab sources and updated my Qt installation to the latest (Qt Creator 4.2.0 built on Dec 9, 2016).  On my first attempt to compile the meshlab_full project I found that I had to rename the io_txt folder under plugins_experimental to io_TXT.  But after that it fails with this error:

In file included from ../../src/common/meshmodel.h:32:0,
                   from ../../src/common/filterparameter.cpp:32: ../../src/common/ml_mesh_type.h:4:33: fatal error:
  vcg/complex/complex.h: No such file or directory  #include

                                   ^ compilation terminated.

Indeed there is no vcg folder.  How do I get it?
Thanks,
Rich
Answer: You need to get vcg lib. It must be at the same level than your meshlab directory :
yourdevelfolder/
 |
 ├──meshlab
 │   ├──docs
 │   ├──README.md
 │   ├──src
 │   ├──...
 │   └──...
 └──vcglib
     ├──apps
     ├──doc
     ├──eigenlib
     ├──...
     └──...

Than you must get vgclib sources :
$ git clone https://github.com/cnr-isti-vclab/vcglib.git
$ cd vcglib
$ git checkout devel

Instructions for compilation are there
Comment: Thanks Eric - I appreciate the help  ;)

I downloaded the vcg files and put them in the correct place, then built the external.pro project.  That got me past the error I was seeing before but still can't build meshlab full or mini.  The error I get says "error: 'ColorConverter' has not been declared".  I've done a fair amount of poking around and can't tell if ColorConverter is a Qt thing or a MeshLab thing.  Do you have any insights?  Thanks, Rich
Comment: Give some detailed logs. vcglib is maybe not in the good location. The main problem I met with vcglib was that I did not checkout to devel branch.
Comment: Sorry for the delay @Eric - I had to find a suitable method for sharing the compiler output.  Here it is:  https://drive.google.com/file/d/0B2i1fbB8wvDySnVZMzMzVTZXQU0/view?usp=sharing   Thanks!
Comment: Rename `meshlab-2016.12` directory to `meshlab`. You must find `meshlab` and `vcglib` directories in `/home/rich/Downloads/3dTools/MeshLab/Source`.

Here is a log from my compilation :

`cd common/ && ( test -e Makefile || /opt/Qt/5.7/gcc_64/bin/qmake /home/eric/dev/3D/meshlab/meshlab/src/common/common.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug -o Makefile ) && make -f Makefile
make[1] : on entre dans le répertoire « /home/eric/dev/3D/meshlab/meshlab/build-meshlab_full-Desktop_Qt_5_7_1_GCC_64bit-Debug/common »`
Comment: Thanks again @Eric.  That got me farther down the path, but now I have a different error.  Compile output:  https://drive.google.com/file/d/0B2i1fbB8wvDyOWJFQjA4NGt0dG8/view?usp=sharing   Here is my folder structure:  https://drive.google.com/file/d/0B2i1fbB8wvDyZXNPdjBKbmlNSlU/view?usp=sharing   I need to continue in a different comment...
Comment: It says it cannot find -ljhead.  I'm not an expert at compiling but it looks like it's looking for jhead in the /home/rich/Qt/5.7/gcc_64/lib folder, right?  There is none there but there is a libjhead.a in /home/rich/MeshLab/meshlab/src/build-external-Desktop_Qt_5_7_1_GCC_64bit-Release/lib/linux-g++   and there is a jhead.o in /home/rich/MeshLab/meshlab/src/build-external-Desktop_Qt_5_7_1_GCC_64bit-Release/jhead-2.95   Any idea what I have wrong?
Comment: Compiled librairies must be copied manually to `meshlab/src/external/lib/linux-g++`. You may have problems when compiling with "Shadow Build' checked. I fixed the issue with this commit : https://github.com/eboudrand/meshlab/commit/1e8f64b3457f3fddef1cd081d7d47e40f0d8c728
Comment: Success!  Thank you @Eric Boudrand!   I appreciate all your help :)
Answer: Update
As commented by @AlessandroMuntoni , we can use --recursive option, and VCG would automatically be available as a submodule:
git clone --recursive https://github.com/cnr-isti-vclab/meshlab

Original post
In meshlab.pro it is commented:
# MESHLAB_SOURCE_DIRECTORY: the directory where is placed the main meshlab.pro

In general.pri it is set:
# VCG directory
VCGDIR = $$MESHLAB_SOURCE_DIRECTORY/../vcglib

Therefore, I forked and cloned the VCG library inside:
 |
 └──meshlab (Git clone)
     ├──docs
     ├──README.md
     ├──src (`meshlab.pro` is inside this)
     ├──...
     ├──...
     └──vcglib (Git clone)

It worked for me =)
Comment: Now, vcglib is a submodule of meshlab. When cloning meshlab, you just need to use the flag `--recursive`.


Extra text in mail body when using phpmailer

Question: I am using phpmailer for a simple email form (no html or attachments) on my website.
The mails have the following after the mail body:
cpsession - closed

cprelogin - no

__utmt - 1

__utma - 128921630.1494146512.1453467768.1453480322.1453518059.4

__utmb - 1289216126.96.36.1993518059

__utmc - 128921630

__utmz - 128921630.1453467768.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

Please let me know how to prevent this from appearing at the end of email body.
Thanks a lot in advance..
Here is the sending part:
<?php
require("lib/class.phpmailer.php");

$mail = new PHPMailer();

$email_subject = "Message from Website";

foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name - $value\n\r";
}
$email_from = $_REQUEST['email'];
$name_from = $_REQUEST['name'];

$email_to = "email@example.com";
$email_cc = "firstname.lastname@example.com";

$mail->AddAddress($email_to);
$mail->AddCC($email_cc);
$mail->AddReplyTo($email_from , $name_from);

$mail->Body = $body;
$mail->IsHTML(false);
$mail->Subject = $email_subject;

if(!$mail->Send())
{   echo "";
}
else {echo "";}

echo "";
?>

and Here is the form:
<form id="contact" action="conmailer.php"  method="post" name="contact">
                         <fieldset id="personal">
                            <input class="validate[required] text-input medinp" name="name" type="text" placeholder="Your Name" tabindex="1" />

                            <input class="validate[required,custom[email]] text-input medinp " name="email" type="text" placeholder="Your Email" tabindex="2" />
                            <input name="address" class="addr" type="text" />

                            <input class="medinp" name="phone" type="text" placeholder="Your Phone No." tabindex="3" />

                            <input class="biginp" name="subject" type="text" placeholder="Subject" tabindex="4" />

                            <textarea class="validate[required] text-input" name="msg" placeholder="Message" tabindex="5"></textarea>

                            <input class="button1" type="submit" value=" SEND" />
                        </fieldset>
                    </form>

Comment: provide some code related to the sending part to look for what is wrong?
Answer: You're using an old version of PHPMailer, so get the latest.
You don't show what your'e putting in $body - PHPMailer just sends whatever you put in there. In your case it looks like you're dumping the contents of the $_COOKIE superglobal into your body contents. So check what you're putting in there, and your problem will go away.
Comment: Sorry, I am a PHP beginner.. Please let me know how to prevent the $_COOKIE contents from getting to the message body. Thanks a lot.
Comment: Er, nothing, it doesn't get in there if you don't put it in there! You need to find where `$body` is set.
Comment: Is it here:
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name - $value\n\r";
}
Comment: Yes; $_REQUEST includes $_COOKIE
Comment: Your form is using the post method, so use $_POST.


Directional derivative of a norm

Question: I've been asked to compute the directional derivative of $f(x) = 0.5\cdot |Ax|^2$ where $f: \mathbb{R}^n \to \mathbb{R}$ and $v \in \mathbb{R}^n$. By definition
\begin{align}
\partial_v f(x) &= \lim_{t\to 0} \frac{|A(x+tv)|^2 - |Ax|^2}{2t}\\
&=\lim_{t\to 0} \frac{|Ax+t\cdot Av|^2 - |Ax|^2}{2t}.
\end{align}
but I can't seem to go anywhere from here without using inequalities.
Comment: Presumably the place to start is expanding the squared norm, e.g., $\|Ax\|^2=Ax\cdot Ax$. This should allow you to cancel some of the $t$ terms.
Answer: If the function is differentiable, then you're in luck, because then the directional derivative is just $\partial_v f(x)=\mathrm Df_x(v)$, where $\mathrm Df_x$ is the differential of $f$ at $x$.
Proving differentiability for things involving matrices is usually quite thankful, since their linearity makes a suitable decomposition easy. In general, a function $f$ is differentiable at $x$ iff there is a linear map $A$ (possibly depending on $x$) such that
$$f(x+h)=f(x)+A(h)+r(h),$$
where $r$ is some small remainder which goes to $0$ faster than linearly. More specifically: $\lim_{h\to0}\frac{r(h)}{\vert h\vert}=0$. And then $A$ is the differential $\mathrm Df_x$.
In this specific case we have
$$\begin{align}
f(x+h)&=\frac12\vert A(x+h)\vert^2\\
&=\frac12[A(x+h)]^tA(x+h)\\
&=\frac12(x+h)^tA^tA(x+h)\\
&=\frac12( x^tA^tAx+x^tA^tAh+h^tA^tAx+h^tA^tAh)\\
&=\frac12(x^tA^tAx+2x^tA^tAh+h^tA^tAh)\\
&=\frac12x^tA^tAx+x^tA^tAh+\frac12h^tA^tAh.
\end{align}$$
Here I used the linearity of matrix multiplication and the fact that $h^tA^tAx$ is a scalar, so transposing it does nothing, so it's equal to $x^tA^tAh$. Anyway, in the end we get three summands: the first is just $f(x)$. The second is linear in $h$, and the third is the remainder. I leave it to you to show that it actually satisfies the conditions placed on the remainder. But in the end we find that $f$ is differentiable with differential $\mathrm Df_x(h)=x^tA^tAh$. So your directional derivative is
$$\partial_v f(x)=\mathrm Df_x(v)=x^tA^tAv.$$
Comment: Thank you I forgot the identity $|Ax|^2 = (Ax)^T(Ax)$.

Directional derivative of a norm


JUnitCore.run() is ignoring @BeforeAll annotations

Question: I am working in Eclipse Oxygen.1a (4.7.1a) with the JUnit 5 library, and it seems like none of my annotated methods are running correctly when I run a test class using JUnitCore.
For example, if I call the following class using JUnitCore.run(TestClass.class) :
public class TestClass {

    @BeforeAll
    public static void beforeAll() {
        System.out.println("In TestClass.beforeAll");
    }

    @Test
    public void testMethod() {
        System.out.println("In TestClass.testMethod");
    }

    @AfterAll
    public static void afterAll() {
        System.out.println("In TestClass.afterAll");
    }

}

There is no output to System.out, and the Result object says that 1 test failed. Implying that none of these methods ran. I can use a JUnit Launcher to run the test class like so:
final LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
        .selectors(selectClass(TestClass.class)).build();
final Launcher launcher = LauncherFactory.create();
launcher.execute(request);

However, this does not give me any feedback about how many tests passed/failed, it seems to just run them. I can't find much documentation on using JUnitCore with JUnit5, is there something newer that I should be working with?
Answer: You should not use JUnitCore with JUnit 5, but instead use the platform launcher API as you did in the second part of your analysis.
launcher#execute(.) does not return any value, hence you need to use a listener to aggregate the results from the execution of your tests, as per the JUnit 5 documentation 7.1.2 Executing Tests.

There is no return value for the execute() method, but you can easily use a listener to aggregate the final results in an object of your own. For an example see the SummaryGeneratingListener.

You can for instance produce a TestExecutionSummary which may indeed provide you with the information you want to collect:
final LauncherDiscoveryRequest request =
    LauncherDiscoveryRequestBuilder.request()
                                   .selectors(selectClass(TestClass.class))
                                   .build();

final Launcher launcher = LauncherFactory.create();
final SummaryGeneratingListener listener = new SummaryGeneratingListener();

launcher.registerTestExecutionListeners(listener);
launcher.execute(request);

TestExecutionSummary summary = listener.getSummary();
long testFoundCount = summary.getTestsFoundCount();
List<Failure> failures = summary.getFailures();
...


Prove $\int_{\Sigma_r} |\nabla\varphi|^2 d\sigma_r \ge \frac{2}{u(r)^2} \int_{\Sigma_r} (\varphi - \bar{\varphi})^2 d\sigma_r $

Question: Reference: this paper

Given the deSitter-Schwarzschild metric with mass $m > 0$ and scalar
  curvature equal to $2$ is the metric
$$\bigg(  1 -\frac{r^2}{3}-\frac{2m}{r} \bigg)^{-1} dr^2 + r^2
 dg_{\mathbb S^2} \tag{1}$$
defined on $(a_0 ,b_0) \times \mathbb S^2$, where $(a_0,b_0)=\{r>0:1
 -\frac{r^2}{3}-\frac{2m}{r}>0 \}$ and $g_{\mathbb S^2}$ is the standard metric on $\mathbb S^2$ with constant Gauss curvature equal
   to $1$.

In order to deal with the metric in $(1)$, we use the warped product metric $g=dr^2 + u(r)^2 dg_{\mathbb S^2}$ on $\mathbb R \times \mathbb S^2$, where $u(r)$ is a positive real function. If we assume that $g$ has constant scalar curvature equal to $2$, then $u$ solves the following second-order differential equation
$$u''(r)=\frac{1}{2}\bigg( \frac{1-u'(r)^2}{u(r)} - \frac{u(r)}{2}  \bigg) \tag{2}$$
Considering only positive solutions $u(r)$ to $(2)$ which are defined for all $r \in \mathbb R$, we get a one-parameter family of periodic rotationally symmetric metrics $g_a = dr^2 + u_a(r)^2 g_{\mathbb S^2}$ with constant scalar curvature equal to $2$, where $a \in (0,1)$ and $u_a(r)$ satisfies $u_a(0)=a= \text{min} ~u$ and $u'_a(0) =0$. These metrics are precisely the deSitter-Schwarzschild metrics on $\mathbb R \times \mathbb S^2$ defined in $(1)$.

Next, let $(M,g)$ be a three-manifold and consider a two-sided compact surface $\Sigma \subset M$.
The mass of $\Sigma \subset M$ is defined by
$$m(\Sigma) =\ \bigg( \frac{|\Sigma|}{16\pi}  \bigg)^{1/2}   \bigg( 1
 - \frac{1}{ 16\pi } \int_{\Sigma} H^2 d\sigma
  - \frac{ \Lambda}{24\pi } |\Sigma|  \bigg) \tag{3}$$
where $\Lambda = \text{inf}_M ~ R$, $R$ is the scalar curvature of
  $M$, $H$ is the mean curvature of $\Sigma$, $K_\Sigma$ is the Gauss
  curvature of $\Sigma$, and $|\Sigma| = \int_\Sigma d\sigma$.

The first variation of $m$:
$$\frac{d}{dt}m(\Sigma(t))\bigg|_{t=0} = -
 \frac{2|\Sigma|^{1/2}}{(16\pi)^{3/2}} \int_{\Sigma} \varphi
 \Delta_\Sigma H d\sigma \\
 + \frac{|\Sigma|^{1/2}}{(16\pi)^{3/2}} \int_{\Sigma} \bigg[ 2K_\Sigma - \frac{8\pi}{|\Sigma|  }+ \bigg( \frac{1}{2|\Sigma|}\int_\Sigma H^2 d\sigma - |A|^2 \bigg)   \bigg] H \phi d\sigma \\
 + \frac{|\Sigma|^{1/2}}{(16\pi)^{3/2}} \int_\Sigma (\Lambda - R) H\varphi d\sigma \tag{4}$$

Remark $1$. It follows from $(4)$  that if a two-sphere $\Sigma \subset M$ is umbilic where $|A|^2 = \frac{H^2}{2}$ and has constant Gauss curvature and $M$ has constant scalar curvature equal to $2$ along $\Sigma$, then $\Sigma$ is a critical point of the mass in $(3)$.

Denote by $\Sigma_r$ the slice $\{r\} \times \mathbb S^2$. By Remark $1$, $\Sigma_r$ is a critical point for the mass in $(\mathbb R \times \mathbb S^2 , g_a)$, for all $r \in \mathbb R$ and $a \in (0,1)$. Moreover the mass of $\Sigma_r \subset (\mathbb R \times \mathbb S^2 , g_a)$ is constant for all $r \in \mathbb R$. It follows by a straightforward computation:
$$\frac{d}{dr} m(\Sigma_r) = \frac{1}{2} u'(r)(1-u'(r)-u(r)^2-2u(r)u''(r)) \tag{5}$$
which is zero once $u(r)$ solves $(2)$, we obtain therefore that $m(\Sigma_r)$ is constant equal to $m(\Sigma_0)$.

Now, since $g_{\Sigma_r} = u(r)^2 g_{\mathbb S^2}$, by the Poincare inequality we have
  $$ \int_{\Sigma_r} |\nabla\varphi|^2  d\sigma_r \ge \frac{2}{u(r)^2} \int_{\Sigma_r} (\varphi - \bar{\varphi})^2 d\sigma_r   = \frac{8\pi}{|\Sigma_r|}\int_{\Sigma_r} (\varphi - \bar{\varphi})^2 d\sigma_r \tag{6}$$
where $\varphi \in C^\infty(\Sigma_r)$.

Question:
Where does $(6)$ come from?
Thank you.
Answer: Although I am not really sure with my calculation, but here is my progress.
Any suggestions or corrections are very welcome.
Given the conformal metric:
\begin{align}
 g|\Sigma_r = u(r)^2 g_{\Bbb S^2} ~,
 \tag{7}
\end{align}
where $u(r)>0$ is some positive function and solves the second-order differential equation below
\begin{align}
 - 6 \Delta u +  R u = \tilde{R}_{g|\Sigma_r} u^3 \\
\int_{\Sigma_r} |\nabla u|^2 d\sigma_r +  \int_{\Sigma_r} \frac{1}{6}2 u^2 d\sigma_r = \int_{\Sigma_r}\frac{1}{6}\frac{8\pi}{|\Sigma|} u^4 d\sigma_r
\tag{8}
\end{align}
where $R =2 >0$ is the scalar curvature of the metric $g_{S^n}$ and $\tilde{R}_{g|\Sigma_r} = 2K_{\Sigma_r} = 2 . \frac{4\pi}{|\Sigma|} = \frac{8\pi}{|\Sigma|} \in \mathbb R$ is the scalar curvature of $g|\Sigma_r$.
The Yamabe invariant of a compact manifold $(M^3,g)$ :
\begin{align}
 Y(g) = \text{inf }\frac{\int_{\Sigma_r} \left( |\nabla u|^2 + \frac{1}{6}R u^2 \right) d\sigma_r}
 { \bigg( \int_{\Sigma_r} |u|^4 d\sigma_r \bigg)^{1/2}  } ~ ,
 \tag{9}
\end{align}
where $Y(g)$ is the Yamabe constant.
From $(9)$ and $(8)$, it shows that
\begin{align}
 Y(g) \bigg( \int_{\Sigma_r} |u|^4 d\sigma_r \bigg)^{1/2} = \frac{1}{6} \frac{8\pi}{|\Sigma|} \int_{\Sigma_r} u^4 d\sigma_r ~ .
 \tag{10}
\end{align}
Substitute (10) to (9) we get
\begin{align}
\int_{\Sigma_r} |\nabla u|^2 d\sigma_r  \ge\ & \frac{u^2}{6} \frac{8\pi}{|\Sigma|} \int_{\Sigma_r} u^2 d\sigma_r
\nonumber\\
%
%
& - \frac{u^2}{6} 2{u^2} \int_{\Sigma_r}  u^2  d\sigma_r
~ .
\tag{11}
\end{align}
$\int_{\Sigma_r}  u^2  d\sigma_r$ could also be written as
\begin{align}
 \int_{\Sigma_r}  u^2  d\sigma_r =\ & u \int_{\Sigma_r}  u\  d\sigma_r
 \nonumber\\
 %%
 %
 =\ & \frac{1}{|\Sigma|} u |\Sigma| \int_{\Sigma_r}  u\  d\sigma_r
 \nonumber\\
 %
 %
 =\ & \frac{1}{|\Sigma|} u \int_{\Sigma_r}  d\sigma_r \int_{\Sigma_r}  u\  d\sigma_r
 \nonumber\\
 %
 %
 =\ & \frac{1}{|\Sigma|} \int_{\Sigma_r}  u\ d\sigma_r \int_{\Sigma_r}  u\  d\sigma_r
 \nonumber\\
 %
 %
 =\ & \frac{1}{|\Sigma|} \bigg( \int_{\Sigma_r}  u\ d\sigma_r \bigg)^2 ~ ,
\tag{12}
\end{align}
Plugging $(12)$ to the second term on RHS of the inequality $(11)$ we get
\begin{align}
 \int_{\Sigma_r} |\nabla u|^2 d\sigma_r  \ge\ & \frac{u^2}{6} \frac{8\pi}{|\Sigma|} \int_{\Sigma_r} u^2 d\sigma_r
 \nonumber\\
 %
 %
 & - \frac{u^{2}}{6} \frac{2}{u^2} \frac{1}{|\Sigma|} \bigg( \int_{\Sigma_r}  u\ d\sigma_r \bigg)^2 ~ .
 \tag{13}
\end{align}
Since $\frac{8\pi}{|\Sigma|} = \frac{2}{u^2}$ and $\int_{\Sigma_r} u^2 d\sigma_r - \frac{1}{|\Sigma|} \bigg( \int_{\Sigma_r}  u\ d\sigma_r \bigg)^2 = \int_{\Sigma_r} (u - \bar{u})^2 d\sigma_r$, we could write $(13)$ as
\begin{align}
\int_{\Sigma_r} |\nabla u|^2 d\sigma_r  \ge\ & \frac{u^2}{6} \frac{2}{u^2} \int_{\Sigma_r} (u - \bar{u})^2 d\sigma_r \\
= & \frac{u^2}{6} \frac{8\pi}{|\Sigma|} \int_{\Sigma_r} (u - \bar{u})^2 d\sigma_r
\tag{14} ~ ,
\end{align}
which is kind of similar to $(6)$.
My questions now are:

Where does $\frac{u^2}{6}$ go?
Despite of the vanishing $\frac{u^2}{6}$ in $(6)$, if we use notation $u = \varphi$, why isn't it just written as

\begin{align}
\int_{\Sigma_r} |\nabla \varphi|^2 d\sigma_r  \ge\ & \frac{2}{\varphi^2} \int_{\Sigma_r} (\varphi - \bar{\varphi})^2 d\sigma_r \\
= &  \frac{8\pi}{|\Sigma|} \int_{\Sigma_r} (\varphi - \bar{\varphi})^2 d\sigma_r
\tag{15}
\end{align}
Why $\frac{2}{u^2}$ and not $\frac{2}{\varphi^2}$ ?

Is it legal if I take $\bar{\varphi}=0$ and why?

Thank you.
Answer: As mentioned by the @user99914, we just need to know the best constant in the Poincare inequality, which I will simply call here as the "Poincare constant". To be precise, here it means the largest constant $C>0$ such that
\begin{align}
C\int_M(f-\bar{f})d\mu\leq\int_M|\nabla f|^2d\mu
\end{align}
It turns out that the Poincare constant $C$ is related to the first eigenvalue $\lambda_1$ of the Laplacian on the manifold (in this case, the $2$-sphere); by this I mean $-g^{ij}\nabla_i\nabla_j f=\lambda_1f$; that is, there is a minus sign in front. In fact, we have $C=\lambda_1$. This fact probably can be found in many standard Riemannian geometry or geometric analysis texts, and I'll just quote one which I encountered: Jurgen Jost's book. In short, it follows from the following:
\begin{align}
\lambda_1=\inf\left\{\frac{\int_{M}|\nabla f|^2d\mu}{\int_{M}f^2d\mu}:f\in W^{1,2}(M), \int_{M}fd\mu=0\right\}
\end{align}
(For simplicity, I only consider the case where $M$ is compact.)
Now, it is sort of regarded as a standard fact in geometric analysis that the first eigenvalue of an $n$-sphere with radius $1/\sqrt{K}$ is equal to
\begin{align}
\lambda_1=nK
\end{align}
For a more general result which includes this as a special case, see Lichnerowicz and Obata's work. Now, the radius of our $\Sigma_r$ is $u(r)$, while its dimension is $2$. Hence
\begin{align}
C=\lambda_1=2\cdot\left(\frac{1}{u(r)}\right)^2
\end{align}
which gives you the desired result.
P/S: I haven't checked out your new questions in your answer. Maybe I'll also try to answer them when I'm free.


Is there a way to have 2 icons when using elixir-desktop?

Question: Background
I have a personal project that is an elixir desktop application for PC Windows. It works pretty well, but now I want to give it an icon.
This is usually done in the following module:
defmodule WebInterface.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  alias Desktop
  alias Manager
  alias WebInterface.{Endpoint, Telemetry}
  alias WebInterface.Live.MenuBar

  @impl true
  def start(_type, _args) do
    children = [
      Telemetry,
      {Phoenix.PubSub, name: WebInterface.PubSub},
      Endpoint,
      Manager,
      {Desktop.Window,
       [
         app: :web_interface,
         id: WebInterface,
         title: "Market Manager",
         size: {900, 960},
         menubar: MenuBar,
         icon: "static/images/resized_logo_4.png", # THIS IS WHERE THE ICON IS SET
         url: &WebInterface.Endpoint.url/0
       ]}
    ]

    opts = [strategy: :one_for_one, name: WebInterface.Supervisor]
    Supervisor.start_link(children, opts)
  end

  @impl true
  def config_change(changed, _new, removed) do
    WebInterface.Endpoint.config_change(changed, removed)
    :ok
  end
end

Problem
The issue here is that I have to use the same image for both the Windows taskbar and the top icon of the app:

The issue here is that while the logo on the bottom Windows bar (marked yellow) is nice, the one in the top is distorted and pretty horrible.
The fix to this would be to have an icon for the bottom and one for the top.
However after checking the demo app I didn't find a way of doing this.
Question
Is this possible to achieve?  If so, how?
Comment: I think you need to build wx{Widgets,Python} from the latest release yourself in order to fix the icon blurriness.
Comment: My local machine has the latest downloadable version from the wxwidgets website (Latest Stable Release: 3.2.1). Are you suggesting this version is outdated?
Comment: what about wxPython? I don't know/remember what their latest release is based on...
Comment: I have not tried wxPython. To be honest, I am not sure of how wxPython and wxWidgets relate to each other. It's not like I can remove wxWidgets and install wxPython and then have everything working the way it used to.
Comment: Furthermore, this would also force my users to install Python on the local machines, and that is too much to ask for.
Answer: At wxWidgets API level, you can specify icons in different sizes using wxTopLevelWindow::SetIcons() (notice the "s"), but I don't know if this function is available in Erlang bindings.
An alternative could be to use an icon from Windows resources but, again, not sure if you can use custom resources for an Erlang application.
Answer: Solution
After asking in several places I was able to find some answers. In fact this post can be summarized in 2 questions:

Why are the icons so distorted?
Can I have an icon for the app different from the icon on the bottom bar?

Why are the icons so distorted?
After checking with the official wxWidgets forums and getting help from the lovely folks there, I was pointed out that my icons did not confirm to the MSW standards for icons. In my case, these needed to be 32x32 or 16x16.
Research:

https://docs.wxwidgets.org/latest/classwx_top_level_window.html#a33dc013a7cb33384f631b2764ca53b06
https://forums.wxwidgets.org/viewtopic.php?f=27&t=49813

Can I have an icon for the app different from the icon on the bottom bar?
This one is a bit more tricky. There is a chance that using wxWidgets directly this could have been possible via the use of overlay icons. However, the library binding I use, elixir-desktop, does not support this, which means the icons need to be the same.
This is probably for the best, because as mentioned by the wxWidgets community, even such a use of overlay icons would not be standard amongst MSW applications, which is my case.
Research:

https://elixirforum.com/t/is-there-a-way-to-have-2-icons-when-using-elixir-desktop/51621/3
https://forums.wxwidgets.org/viewtopic.php?f=27&t=49813


How do I know by looking at a formula that I should use the chain rule?

Question: As stated in the question "How do I know by looking at a formula that I should use the chain rule," take as an example the function $f(x)=\frac{1}{x-3}$.
Comment: Use the chain rule to do what? Differentiate? You can use whatever tool you want. In this case $f = g \circ h$ where $h(x) = x-3$ and $g(y) = {1 \over y}$.
Answer: You use the chain rule when clearly f(x) = g(h(x)).  Here if h(x) = x - 3 and g(x) = 1/x then g(h(x)) = 1/(x - 3) = f(x).  So you could use the chain rule.
Although, I'm not sure to what degree I would say that is "clearly".  It screams out for the quotient rule sooner than the chain rule to me.
Comment: I always use the chain rule to differentiate $f(x)/g(x)$ because I already know the product rule and the chain rule by heart (you can't do any calculus without them) and I can't be bothered to remember the quotient rule.
Comment: The negative signs of the quotient rule always throw me off too.
Comment: @Rahul personally, I would now just use the multi-variate chain rule.  None of this required, all you have to do is break the problem into pieces you can differentiate.  But to the OP here, saying that likely isn't helpful ;-)
Answer: If your function $f(x)$ shows that it is shown to be in the form of $g[h(x)]$ where you know how to differentiate $g(x)$ and $h(x)$ but don't know how to directly differentiate $f(x)$, then yes, you should use chain rule.  In your example, the quotient rule would work just as fine and in Calculus, many different methods can be used to approach any single problem.
An example that would require chain rule more obviously would be
$f(x)=e^{e^x}$
But even so, logarithmic differentiation would work, so it's all up to you to decide how to tackle it.


Getting Array from Another class C++

Question: I am making a simple Lottery program - and am struggling with implementation. I have a class called 'Ticket Line' this class simply holds 6 numbers that the player is playing a lottery for.
What I want to do, is generate 6 randomly (got function for this already) and then store that in another class as values. To do this, I am using the following code:
  class Draw
{
private:
    int drawID;
    TicketLine* DrawnNumbers;
    bool drawn;
}

When a Draw is completed I want to generate the Random Numbers ( from the TicketLine class) and then for the Draw to be able to store those numbers into its Draw File.
How would I be able to access the functionality of the DrawnNumbers class - and store the results from the getTicketNumbers.getTicketLine()function.
int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();};

The program crashes the following code:
//int *ptr[6] = getTicketNumbers();
int *ptr[6] = getTicketNumbers();
for (int x = 0; x < 6; x++){
    cout << ptr[x];
}

TicketLine class:
private:
    int select[6]; //Array of Ticket Numbers.
int* getTicketLine(void) { return select; };

I am willing to offer a couple of virtual beers to the solution. I am as yet to find a good online pub - if you know of one then please do let me know :-)
Thanks,
Comment: "The following code doesn't work unfortunately" What do you mean ? It doesn't compile or it crashes at run time ? You don't give us enough information
Comment: @StephaneRolland Ha, he is one step ahead of you, he covered both cases with a single word.
Answer: Without knowing any more, this line:
int *ptr[6] = getTicketNumbers();

is very suspect.
Why? Well, we haven't seen the implementation of getTicketNumbers so we don't know if it's actually allocating memory for 6 and returning such an array.
Also, you are printing the values of pointers here:
for (int x = 0; x < 6; x++){
    cout << ptr[x];
}

Where, if you intended to actually print the int values, you'd say something like this:
for (int x = 0; x < 6; x++){
    cout << *(ptr[x]);
}

My guess is that you are either:

Going out of bounds of an array that was (not) allocated, or,
Modifying actual pointer values somewhere instead of the integers they point to (as indicated by your lack of dereferencing ptr[x] in your print statement)

Edit
With more information, it seems you probably meant to say this:
int *ptr = getTicketNumbers();

instead of this:
int *ptr[6] = getTicketNumbers();

You should probably be doing some sanity checks as well to make sure that select is actually filled before calling that function (maybe giving it a default value of {0,0,0,0,0,0} in the constructor)
Comment: @KingJohnno: And that function implementation is not very expressive, because we don't know what `DrawnNumbers->getTicketLine()` does
Comment: Hi, The getTicketNumbers(); is int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();}; (as mentioned above);

Thanks for the suggestion.
Comment: @KingJohnno: Please place the code in your original question. And format it, please.
Comment: All of the code is within the original question.
Comment: Wait. `int *ptr[6]` declares `ptr` as an array 6 of pointers to int. I can bet he meant just `int (*ptr)[6]`.
Comment: Apologies - I will add it now. @AndyG added it now.
Answer: DrawnNumbers doesn't appear to be pointing to anything yet. It's a pointer, but to what?
Also, be careful about returning arrays that way. If the object or stack frame that the array resides in goes away, you'll be left pointing to bad things.
Comment: DrawNumbers is an instance of the TicketLine class ?/

Getting Array from Another class C++


Mutiple websites on IIS 6 with different IP. One site won't respond

Question: I have two websites with different domain names hosted on the IIS 6. I have different IP for each one of them with SSL. The sites are running on IIS 6. When i try accessing b.mydomain.com over SSL, i am able to browse the website. But, a.mydomain.com times out connection.
a.mydomain.com is running on the IIS. When i ping the domain, correct IP is detected. what else should i check for? Kind of puzzled because, the second website with a different domain name and ip is accessible.
any pointers would help.
UPDATE:
trying ipconfig/all didn't display the IP address for b.domain.com. trying to figure out why.
Answer: When you are trying to reach a.mydomain.com are you trying to just hit a simple file or an actual web application?  In order to simply "test" drop an empty text file on the site.  a.mydomain.com/foo.txt and see if you can at least load a blank page.  If you get nothing then you know you aren't getting to the IIS site.  Did you double check that the IP address for a.mydomain.com is for sure attached to that machine?  Do you get a ping response from that IP address (assuming you allow a ping response).  Post back with findings.
Comment: @Dave: Got a pretty basic question. When i type in the URL, it's supposed the (1) resolved the IP using the DNS and then (2) reach the server at the IP address. After this, (3) the SSL connection is established while accessing the web site. How do i know, in which step i am now?
Comment: @Dave: I tested the URL in digicert SSL checker. The error i am getting for b.domain.com is
"DNS resolves to x.x.x.x.
No certificates were found.
connect: Connection timed out connect:errno=22".
Seems i have gone past steps 1 and 2 in my previous comment. Any thoughts?
Comment: I forgot about the SSL portion when I first posted.  One thing you can do to verify if the SSL cert is failing... allow port 80 for that domain (http://) just long enough to test and see if you can load the page.  You can (in a way) test the steps in a command window.  Ping your domain (does it resolve correctly to the right IP?) then telnet to that IP on port 443.  If the connection is immediately refused then you aren't reaching it, however if it connects then you are getting there and the problem lies with the Cert.
Comment: Lastly just make sure you have correctly set up your SSL cert in IIS for that site (check it against the one you've got working correctly).


parse.com Cloud Code prevent duplication error

Question: I am following the instruction here:
https://parse.com/questions/unique-fields--2
var Profile = Parse.Object.extend("Profile");

Parse.Cloud.beforeSave("Profile", function(request, response) {

                       if (!request.object.get("entityID")) {
                            response.error('must have a entity id');
                       } else {

                       var query = new Parse.Query(Profile);
                       query.equalTo("entityID", request.object.get("entityID"));
                       query.first({

                                   success:function(object) {

                                    if (object) {
                                        response.error("already exist");
                                    }
                                    else {
                                        response.success();
                                    }

                                   },
                                   error:function(error) {
                                        response.error("couldnt validate uniqueness for this profile");
                                   }

                        });

                        }
                       });

I have a profile table and the unique key is entityID, when inserting, I need to check if the entry with the same key already exist.
The problem is, I am not able to update the entry anymore (it seems both insertion and update request trigger this cloud code.
How can i modify it so that

when i insert, if it exists, I ignore it; if not exist, insert it.
when i update, if it exist, update it; if not exist, i ignore it.
Answer: I know this is kind of old, but it should be mentioned that until Parse either implements a lock/wait system or arbitrary constraint enforcement, it is not possible to cleanly prevent duplicate entries with cloud code since you are not guaranteed that only one instance of the code is running at any given point. Even if you have something like this:
if entry exists
    update it or don't add it
else
    add it

Since there is no locking, you cannot implement your own constraint enforcement. Also, attempting to do so will double your API calls and could bump you into a more expensive plan. The Parse staff has acknowledged this several times even in recent months (just search their forums) and suggests the use of atomic increments or the automatically generated unique object id for some circumstances, but for the most part this is not practical. They also suggest running automatic jobs to remove duplicates after they are entered, but this does not guarantee that at any given point the data in your system is internally consistent, even just after the job has run.
The bottom line is if constraint enforcement and overall data integrity are essential for your application, Parse is not yet mature enough to handle your needs. I hope to see this change soon.
Answer: Instead of using Create and Update requests, you can call your custom Cloud Function that does everything that you want. Saved me some headache.
Answer: S.C. is right.
In the meantime you could go dirty and do something like:
Parse.Cloud.afterSave("Profile", function(request) {

    // Find every Profile with same entityID
    var query = new Parse.Query(Profile);
    query.equalTo("entityID", request.object.get("entityID"));

    // Order them by creation in db (oldest in DB first)
    query.ascending("createdAt");

    query.find({

        success:function(results) {

            if (results && results.length > 1) {
                // We have a least one duplicate

                // Destroy every Profile except for the original (the oldest in DB)
                for(var i = (results.length - 1); i > 0 ; i--) {
                    results[i].destroy();
                    // /!\ In case of concurrent call of afterSave,
                    // we might run in situation of concurrent deletetion
                    // of same Profile in this case we might encounter (or not?) some
                    // time out of this function buuut we will always keep
                    // the same Profile from being deleted.
                }
            }
            else {
                // No duplicates
            }

        },
        error:function(error) {
        }
     });
 });


How to sort a string (in ascending order ) which has numbers seperated with comma in javascript

Question: This is my code in my javascript:
var concatId = document.MyForm.concatIdSaved.value;

This is giving me string as 3,2,4,00201,
After 00201 iam getting comma also.
All four values are coming in a single String.
Now i want this string as 00201,2,3,4
Someone please help me on this.
Comment: are you looking for lexical or numerical order? because 201 > 2, but 0 < 2... It seems you want lexical - in which case the fact these are numbers is a red herring. Can you clarify?
Comment: ***javascript != java***. Anyway, what have you tried?
Comment: i dont know from where to start.
Comment: 00201 should come before 2. That what is creating a problem.
Comment: I recommend that you update your question to clarify. Might fix typo in title at the same time. In my experience a well phrased question gets a good answer. And often when you are done stating the question properly, the answer will stare you in the face...
Comment: Ok Floris..ill keep that in mind. Thanks.
Answer: var concatId = document.MyForm.concatIdSaved.value.split(",").sort().join();

Comment: I like this one - "high density code"!
Comment: `Containing numbers` was misleading, this default sort should work for OP. +1
Comment: Above suggestion works like a charm. but i am getting string as ,00201,2,3,4. Could you please suggest how to remove comma coming at first place.
Comment: Add .substring(1) to the end: var concatId = document.MyForm.concatIdSaved.value.split(",").sort().join().substring(1);
Comment: Sorry again:( but now string is coming as 00201,2,3,4  I need 00201,2,3,4,  comma also at the end. Could you please suggest something.
Comment: I got it. Just for info i added "," as document.MyForm.concatIdSaved.value.split(",").sort().join().substring(1)+",";  Thank you all for your help


How to fast convert (recode) int64 to character-limited String?

Question: I am looking for a method to recode a String that only consists of digits [0,1,2,...8,9] into another String of a different character set like digits and letters [0,1,...9,a,b,...z] (as an example). The resulting string should typically be shorter than the digit-only String. The method should be reversible and it should be fast. Source code in C# answers would be appreciated but gerneal ideas are also welcome ;-)
Example:
Input:  "1234567890123"
Output: "ar4cju7d"

The output of the reversing method applied to "ar4cju7d" should be "1234567890123.
Comment: The sample input you have shown overflows an `Int64` which has a maximum value of `9223372036854775807`. So you'd better change the title of your question or make your requirements a bit more specific. Also don't hesitate to show what you have tried so far to achieve your goal explaining what particular difficulties you have encountered with your code. Because at its current state your question would be more suited to a *rent-a-coder* like website, rather than StackOverflow.
Comment: "Somewhat cryptographic" goes very much against the concept of an encoding which can be reversed without a key. Maybe use base64 or base32?
Comment: The "cryptograpic" part was not well explained. I removed it. What I wanted to say was that the original number should not be easily derived from the output string but this can be easily achived by adding a secret number to the input string before encoding. It is very light cryptography but enough in this case.
Comment: @DarinDimitrov My bad. I corrected the mistake.
Answer: If your input is always an Int64, then you may check Base36 encoding. And here's a sample implementation:
// Edit: Slightly updated on 2011-03-29

///
/// A Base36 De- and Encoder
///
public static class Base36
{
    private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";

    ///
    /// Encode the given number into a Base36 string
    ///
    /// <param name="input"></param>
    /// <returns></returns>
    public static String Encode(long input)
    {
        if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");

        char[] clistarr = CharList.ToCharArray();
        var result = new Stack<char>();

        while (input != 0)
        {
            result.Push(clistarr[input % 36]);
            input /= 36;
        }

        return new string(result.ToArray());
    }

    ///
    /// Decode the Base36 Encoded string into a number
    ///
    /// <param name="input"></param>
    /// <returns></returns>
    public static Int64 Decode(string input)
    {
        var reversed = input.ToLower().Reverse();
        long result = 0;
        int pos = 0;

        foreach (char c in reversed)
        {
            result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
            pos++;
        }

        return result;
    }
}

which can be applied to your example:
long input = 1234567890123;
string encoded = Base36.Encode(input); // yields "fr5hugnf"
long originalInput = Base36.Decode(encoded); // yields 1234567890123

Comment: Nice encoding, this would fit well if the input is indeed alsways `int64`. If OP wants more obfuscation, you could do a character substituation (i.e. substitute every 'f' for a 'L' etc., simple substitution cipher), this is also reverseble and hinders people trying out common encodings (like base64, but base36 is already really uncommon). Ergo, good answer.
Comment: I certainly agree ;-)


Using cron to schedule bash script that activates virtual env and starts Django server

Question: I am trying to schedule a cron job to start a Django server but not having any luck. The code below works in terminal when I type bash filename.sh but my cron job 02 9 * * * bash home/user/filename.sh doesn't work.
The filename.sh script:
#!bin/bash
source activate my_env
cd folder
python manage.py runserver 0.0.0.0:8000

Answer: You can use the complete paths (for python and manage.py) without activating the enviroment, for example:
/home/user/.environment/your_env/bin/python /home/user/project_path/manage.py runserver 0.0.0.0:8000

Comment: Thank you this worked! I have a few questions (sorry if super basic, trying to learn this stuff). So now the django server is up and everything works. (1) how do i see the terminal shell where it exists and/or kill
Comment: I suggest you to use a process manager like *supervisord* in order to properly manage the django server process.
Comment: Also I can suggest to spawn the wsgi process with uwsgi or gunicorn if you want to speed up the requests, with runserver you spawn 1 process, with uwsgi you can multiple.
Answer: Try this
. /path_to_your_installation/my_env/bin/activate && python /path_to_your_installation/manage.py runserver 0.0.0.0:8000


DFS Replication across Hyper-V servers - duplicate GUID's

Question: 4 Hyper-V instances of Win2003 Server with 2 VHD's each (All based on same Win2003 VHD that i copied 4 times, everything seems to run just fine)
Trying to use DFS replication to keep some folders in sync but it fails with an error saying that a duplicate GUID has been detected.
I understand the error as the VHD's are copies of each other, but is there some tools that I can use to change the GUID on a VHD drive?
Comment: where these domain joined prior to cloning if so then I'd sysprep then copy the resultant vhd file.
Answer: Simple answer: Copying VHD files without running sysprep on them to reinitialize the Windows system to a new SID causes problems. You can copy the VHD files, but you need to sysprep / them.
Answer: Simple answer, why not just create another VHD and do a software mirror on one of the machines? Once the synchronization is complete, dump the VHD that matches the one on the other machine.


how to add mysqli driver to drupal 8?

Question: <code>$databases['default']['default'] = array (
  'database' => 'baba',
  'username' => 'abab',
  'password' => 'abcbc@',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['abcb']['default'] = array (
  'database' => 'ababc',
  'username' => 'abcb',
  'password' => 'Sabbs',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysqli',
);
</code>
We have mysql, pgsql and sqlite driver but I wanted to integrate a mysqli driver in drupal ?
How can I achieve it or fetch table from mysqli database in mysql database ?
Answer: Drupal 8 uses PDO, so I think mysqli is not supported.
From the documentation:

Drupal's database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon PHP's PDO (PHP Data Objects) database API, and inherits much of its syntax and semantics.
Comment: @harshal mysqli isn't a database type, it stands for "MySQL Improved", as in the improved MySQL extension for PHP. The mysqli library was used, and arguably shouldn't be used any more, to connect to MySQL databases. There's no reason, nor option, to use the old library in Drupal 8 - it's 2016, we have better ways of solving problems (i.e. PDO). Incidentally, mysqli was not supported in Drupal 7 either, so we're going back more than 5 years since this was available in Drupal at all
Comment: is there any way I can fetch tables from mysqli database  in drupal 8 ?
Comment: Yes  thanks for your comments. But the issue I am facing is I have a drupal 6 site and another drupal 8 site . and task is to fetch database from  drupal 6 table using mysqli and move it to drupal 8 website. Can this be done by using some custom module ? I was trying to use views_database_connector module to support this  but could not accomplsh it.So my last question would be can it be done in drupal 8 by some way ?
Comment: But the database itself is a mysql database, so why don't you just connect via PDO? As Clive already said, there is no mysqli database.
Comment: It is possible to write a driver that uses mysqli, and that would also probably need to re-implement all of the SQL services such as Entity Query and Views Query in addition to all of the database. The apdqc module does something similar for Drupal 7. If you're tasked with moving data from drupal 6 to drupal 8, then you should use migrate. Writing a driver in this case is probably not recommended.
Comment: mradcliffe & @Linus thanks for generous help. Would like to know how I could connect via PDO ? I would kindly request you to provide me with a link I can refer
Comment: https://www.drupal.org/upgrade/migrate. You can setup migrate to run only the migration for that specific data.
Comment: What is the performance aspect when using PDO instead of mysqli? (if any..)

how to add mysqli driver to drupal 8?


model.predict() with multiple datasets as inputs

Question: I'm trying to feed TensorFlow dataset (which is read from .csv files) into multi-input tf.keras model defined with functional API. Training works fine when I pass these datasets zipped together with labels. When I want to call predict() (presumably on some different dataset that is not labelled) it throws an error (both in eager and non-eager execution)
Here's my current code:
import tensorflow as tf
import numpy as np

tf.enable_eager_execution()

# Define model.
input_A = tf.keras.layers.Input(shape=(None, 5), name='sensor_A_input')
x_1 = tf.keras.layers.LSTM(5, return_sequences=False, recurrent_initializer='glorot_uniform')(input_A)

input_B = tf.keras.layers.Input(shape=(None, 4), name='sensor_B_input')
x_2 = tf.keras.layers.LSTM(5, return_sequences=False, recurrent_initializer='glorot_uniform')(input_B)

x = tf.keras.layers.concatenate([x_1, x_2], name='concat_test')
output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(x)

model = tf.keras.Model(inputs=[input_A, input_B], outputs=output)

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.run_eagerly = tf.executing_eagerly()

# Define input data.
# Dataset 1 is read from 10 .csv files where one file is one timeseries observation sequence of length 100 and 5 dimensions.
dataset_1 = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 100, 5))
# Dataset 2 is read from 10 .csv files where one file is one timeseries observation sequence of length 300 and 4 dimensions.
dataset_2 = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 300, 4))

# Define labels.
labels = tf.data.Dataset.from_tensor_slices(np.random.randint(0, 2, (10, 1)))

# Zip inputs and output into one dataset.
input_with_labels = tf.data.Dataset.zip(((dataset_1, dataset_2), labels)).batch(10)
model.fit(input_with_labels)

# Here's the problem - how should the input be arranged?
zipped_input = tf.data.Dataset.zip((dataset_1, dataset_2)).batch(10)
predictions = model.predict_generator(zipped_input)
print(predictions)

Here's the error:
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays: [<tf.Tensor: id=71049, shape=(10, 100, 5), dtype=float64, numpy=
array([[[0.54049765, 0.64218937, 0.31734092, 0.81307839, 0.75465237],
        [0.32371089, 0.85923477, 0.60619924, 0.68692891, 0.186234...

Full traceback:
Traceback (most recent call last):
  File "C:/xxx/debug_multiple_input_model.py", line 39, in <module>
    model.predict(zipped_input)
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1054, in predict
    callbacks=callbacks)
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training_generator.py", line 264, in model_iteration
    batch_outs = batch_function(*batch_data)
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training_generator.py", line 536, in predict_on_batch
    return model.predict_on_batch(x)
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1281, in predict_on_batch
    x, extract_tensors_from_dataset=True)
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training.py", line 2651, in _standardize_user_data
    exception_prefix='input')
  File "C:\env_path\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 346, in standardize_input_data
    str(len(data)) + ' arrays: ' + str(data)[:200] + '...')
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays: [<tf.Tensor: id=71049, shape=(10, 100, 5), dtype=float64, numpy=
array([[[0.54049765, 0.64218937, 0.31734092, 0.81307839, 0.75465237],
        [0.32371089, 0.85923477, 0.60619924, 0.68692891, 0.186234...

I've also tried calling predict() function like this:
1:
model.predict_generator(zipped_input)

results in the same error.
2:
model.predict((dataset_1, dataset_2))

throws this error:
AttributeError: 'DatasetV1Adapter' object has no attribute 'shape'

Comment: Are you sure you want zip, not concatenate?
Comment: @Sharky as far as I know concatenate creates one dataset by appending multiple datasets together. That's not what I want - `dataset_1` needs to go into `sensor_A_input` and `dataset_2` into `sensor_B_input` as they've got different shapes (length of the sequence coming into LSTM).
Answer: It turned out that a 1-element tuple should be given as the input to tf.data.Dataset.zip() function:
zipped_input = tf.data.Dataset.zip(((dataset_1, dataset_2), )).batch(10)

This produces an expected result.
Comment: Are all the `(` `)` parentheses necessary or can it just be `tf.data.Dataset.zip((dataset_1, dataset_2)).batch(10)`?
Comment: Hmmm it's been a while. As far as I remember the shape of data had to match whatever `tf.keras.Mode.predict` or `tf.keras.Mode.predict` expect (see case `2` in the second part of my question where I mention `AttributeError`). Doesn't the model throw any exceptions when you feed it with data of such a shape?
Comment: Yes, I confirmed, the extra parentheses are needed. Thanks!
Answer: One more possible workaround:
ds1_iter= dataset_1.make_one_shot_iterator()
ds1_next= ds1_iter.get_next()

ds2_iter= dataset_2.make_one_shot_iterator()
ds2_next= ds2_iter.get_next()

prediction = model.predict(x={'first_input_name':ds1_next, 'second_input_name':ds2_next}, steps=N)

where N is a length of the datasets.
Comment: That's then limited to the scenario in which I know `N`, right? Wouldn't work if I'd be reading the dataset from all files in a directory where every file has a different length, e.g. using `tf.data.experimental.CsvDataset`.


Site em PHP está fazendo download

Question: Estava tentando configurar o serverblocks (vhost) do nginx, então eu apaguei o arquivo "default" localizado em /etc/nginx/sites-enabled/default e criei um arquivo com o nome do meu site, adicionei essas linhas abaixo:
 server {
    listen   80;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name http://localhost/;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

E agora o meu site que é em PHP, testado no meu servidor, quando abro, ele faz o download! Acho que alguma linha de código que estava no arquivo "default" tinha algo de interpretar códigos PHP?
Como recuperar essa configuração?
Comment: Acho que é só colocar `location` dentro de `server`.
Comment: Não resolveu o problema?
Answer: Assim como o Vinícius comentou, a propriedade location fica dentro de server. Como respondido nessa questão do SOen,

Altere seu código para:
server {
    listen   80;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Edite o /etc/php5/fpm/php.ini e definia o valor de cgi.fix_pathinfo para 0.
Reinicie o nginx e o php5.

Site em PHP está fazendo download


Script to watch for file changes & if detected, backup the original first.

Question: As per the title I'm looking for a way to backup files (SQL queries to be specific) when they are saved over/replaced.
This is to prevent accidental saving without a decent fall back.
I think that using a combination of Powershell and .NET FileSystemWatcher might be a good combo and instead of an alert I could take the original and append datetime to it in another location.
(https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b)
So my question is, how to interrupt that save process within Windows and copy the file out before it's saved over?
I'm thinking it might not be possible without calling the PS when a save is initiated on that specific directory.
I have access to PS, VBS and elevated cmd.
TIA for any pointers or further reading.
Answer: There's no way to backup/save the previous before a newer version overwrites it as there are no OnBeforeX events in the FileSystemWatcher.

Changed: Occurs when a file or directory in the specified Path is changed.
Created: Occurs when a file or directory in the specified Path is created.
Deleted: Occurs when a file or directory in the specified Path is deleted.
Disposed: Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Error: Occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.
Renamed: Occurs when a file or directory in the specified Path is renamed.

The only way to do this would be to perform an initial back up of all the files. Then backup, with a timestamp pre/suffix, after each Changed event.
Comment: Thought it was a bit far fetched but many thanks for the explanation!

I see what you mean and that process would work just as well as there'd be a constant chain of revised editions.

Cheers Spud!


Classification theorem for specific non-Abelian groups

Question: I recently learned about the fundamental theorem of finite Abelian groups, that any finitely generated commutative group $G $is isomorphic to a direct sum: $\mathbb Z^n \displaystyle \oplus \mathbb Z_{j_1} \oplus \mathbb Z_{j_2} \oplus...\oplus\mathbb Z_{j_k}$ where the subscripts are prime powers.
What about a noncommutative group where, in particular, the operation $*$ is such that $x*y= (y*x)^{-1}$? Does a similar classification theorem exist in that case? I asked my professor about it and he mentioned something about 2-torsion groups that went over my head.
Comment: Sorry I meant that $(y*x) = (x*y)^{-1}$. I will make an edit.
Answer: Any group $G$ in which $xy=(yx)^{-1}$ for all $x,y\in G$ is automatically abelian.  To prove this, notice that if you let $y$ be the identity, this says $x=x^{-1}$ for any $x$.  Applying this with $yx$ in place of $x$ then gives $yx=(yx)^{-1}=xy$.  That is, $G$ is abelian.


How to url escape and replace correct uri?

Question: I want to escape the \/\/ from url to get thumb with Uri.UnescapeDataString("\/\/") on this url from the HTML source using request:

https:\/\/scontent.fhel5-1.fna.fbcdn.net\/v\/t15.5256-10\/fr\/cp0\/e15\/q65\/48734886_2061090874011522_801576553975644160_n.jpg?_nc_cat=107&_nc_sid=08861d&_nc_ohc=4jeujL2uPDwAX_FBn97&_nc_ht=scontent.fhel5-1.fna&oh=672481858f1d7a2bd2655da89b57bacd&oe=5F63E18C

So my thumb will be decoded and those sign replaced so it can be parsed as string in show my the picturebox imgCover.ImageLocation = _thumbURL.ToString()
My code:
   Private Sub getNFO()
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
    Dim apiURL As String = "https://m.facebook.com/watch/?v="
    Dim _videoID As String = txtURL.Text

    Try
        Dim the_request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(apiURL + _videoID)
        the_request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1"
        the_request.Timeout = 5000
        Dim the_response As System.Net.HttpWebResponse = the_request.GetResponse
        Dim stream_reader As System.IO.StreamReader = New System.IO.StreamReader(the_response.GetResponseStream())
        Dim yt_source As String = stream_reader.ReadToEnd

        If String.IsNullOrEmpty(yt_source) Then
            MessageBox.Show("Facebook ID Request Error")
        Else
            Dim r1 As Regex = New Regex("(?<=description"":"").*?([^[]+?)(?="")")
            Dim m1 = r1.Match(yt_source)
            _titleURL = m1.Value

            Dim r2 As Regex = New Regex("(?<=thumbnailUrl"":"").*?([^[]+?)(?="")")
            Dim m2 = r2.Match(yt_source)
            _thumbURL = m2.Value

        End If

        lbl_Title.Text = _titleURL.ToString()
        imgCover.ImageLocation = _thumbURL.ToString()

    Catch ex As Exception
         MessageBox.Show(ex.Message)
    End Try

End Sub

Answer: Finally make it bymyself :)
Dim decodedThumbURL = _thumbURL.Replace("\", String.Empty)


Example of a commutative noetherian ring with $1$ which is neither domain nor local and has a principal prime ideal of height $1.$

Question: I am trying to construct an example of a ring satisfying the followings.

A commutative noetherian ring with $1$ which is neither domain nor local and has a principal prime ideal of height $1.$

I know that a local noetherian ring having a height $1$ principal prime ideal is a domain. Actually I wanted to prove this without the local condition. I couldn't prove this hence I am looking for a counterexample. I need some help. Thanks.
Answer: Let $k$ be a field and $A=k[x,y]/(xy)$.  Then the ideal $(y-1)\subset A$ is a principal height $1$ prime.  (Note that this ring is not local, and the non-localness is essential to the example in that if you localize at $(y-1)$ then the ring becomes a domain.)
As a hint to what's going on here that can't happen in the local case, notice that $(y-1)x=-x$, so $x$ is divisible by $y-1$ arbitrarily many times.  In a local Noetherian ring this would imply $x=0$ by the Krull intersection theorem.
Answer: Let $R$ be a noetherian ring with principal prime ideal $P$ of height $1$.
Then $R\times R$ is Noetherian, non local, not a domain, and still has a principal prime ideal of height $1$: $P\times R$.
Comment: @quasi The prime ideals of the product have to be of the form $P\times R$ or $R\times P$ for some prime ideal $P$ of $R$. Therefore the primes contained in $P\times R$ look like $P'\times R$ for a prime ideal $P'$ contained in $P$.
Comment: So, like $\mathbb Z\times \mathbb Z$.
Comment: $P$ has height $1$ in $R$ by choice of $P$, but why does $P\times R$ have height $1$ in $R\times R\,?$
Comment: But if the prime ideal $P \times R$ has height $1$, what is the prime ideal of $R \times R$ below $P \times R\,?$ Ok, so you're saying $0\times R$ is the one below it? That makes sense. But wait; $0 \times R$ is not height $0$, is it?
Comment: Ok, I got it. If $R$ is a domain, $0 \times R$ _does_ have height $0$ in $R \times R$. If $R$ is not a domain, then whatever prime ideal $Q$ in $R$ of height $0$ was below $P$, the prime ideal $Q \times R$ is a height $0$ prime ideal of $R \times R$ which is below $P \times R$. So I withdraw my question, and thanks.
Comment: @quasi well it doesn't really matter if $R$ is a domain. I have just explained why the primes contained in $R\times P$ correspond with primes in $P$.
Comment: Yes, I observed that in the last part of my last comment. That comment was kind of written in "real-time" (by the end of the comment, I saw that R being a domain wasn't needed).
Comment: @quasi ok, I wasn't sure.


Show that $\frac{1}{\vert G\vert}\sum_{g\in G}\phi_{t}v\in V^{G}$ for $v\in V$

Question: This exercise comes from Steinberg's Representation Theory of Finite Groups.
Let $\phi :G\rightarrow GL(V)$ be a representation of a finite group $G$. Define the fixed subspace
$$V^{G}=\{ v\in V\,\vert\,\phi_{g}v=v,\forall g\in G\}$$
Show that
$$\frac{1}{\vert G\vert}\sum_{g\in G}\phi_{t}v\in V^{G}$$
for all $v\in V$.
I understand that if $v\in V^{G}$ we have $\phi_{g}v=v$ for $g\in G$. Then it follows that $$\frac{1}{\vert G\vert}\sum_{g\in G}\phi_{t}v=\frac{1}{\vert G\vert}\sum_{g\in G}v = \frac{1}{\vert G\vert}\vert G\vert v = v$$ However, I do not understand why the statement holds for $v\in V\setminus V^{G}$ as well. Is this simply an error on the author's part or have I misunderstood?
Answer: It's not an error. Since $V^G$ is a subspace the $\frac{1}{|G|}$ coefficient is irrelevant and I'm going to ignore it (let me know if I should explain further why I can do this, but I think it should be easy to figure out).
Consider what happens when you act by a fixed element $g_0\in G$, we have
\begin{align*}\phi_{g_0}(\sum_{g\in G}\phi_g v)&=\sum_{g\in G}\phi_{g_0}(\phi_g v)\\
&= \sum_{g\in G}\phi_{g_0g}v\end{align*}
Now try to figure out why this is the same thing as $\sum_{g\in G}\phi_g v$. In other words, why is the set $\{g_0g\mid g\in G\}$ the same as the set $\{g\mid g\in G\}$?
Comment: Of course! That makes perfect sense now, thanks a million!


Postfix and dovecot. TLS not available

Question: I've been trying to setup a send only SMTP server with postfix and dovecot, on Ubuntu 16.04. The problem I'm having is that when trying to send an email I get the message back.

4.7.0 TLS not available due to local problem

So I'm guessing that the problem lies within my postfix TLS setup. And if I'm checking the status of the postfix service

Sep 19 15:03:15 mail.example.org postfix[3571]: /usr/sbin/postconf: warning: /etc/postfix/main.cf: unused parameter: smtpd_tls_session_cache_header=yes
  Sep 19 15:03:15 mail.example.org postfix[3571]: /usr/sbin/postconf: warning: /etc/postfix/main.cf: unused parameter: smtpd_tls_note_starttls_offer=yes
  Sep 19 15:03:15 mail.example.org postfix[3571]: /usr/sbin/postconf: warning: /etc/postfix/main.cf: unused parameter: smtpd_tls_recieved_header=yes

So I'm guessing it has something to do with these settings. But I don't get exactly whats wrong with them, I've tried removing the lines, and the error still occurs.
Postfix Config:
<code>mydomain = branelmail.dk
myhostname = mail.branelmail.dk

myorigin = $mydomain
mydestination = $myhostname, localhost.$mydomain, localhost

unknown_local_recipient_reject_code = 550

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases

home_mailbox = /dev/null

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

debug_peer_level = 2

# TLS parameters
smtpd_use_tls = yes
smtpd_tls_cert_file=/etc/ssl/certs/mail.branelmail.dk.pem
smtpd_tls_key_file=/etc/ssl/private/mail.branelmail.dk.key
smtpd_tls_CAfile = /etc/ssl/certs/cacert.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# You can use log level 3 or 4 for more advanced troubleshooting
smtpd_tls_loglevel = 4

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
relayhost =
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_local_domain =
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_auth_enable = yes
smtpd_tls_security_level = may
smtpd_tls_auth_only = no
#smtpd_tls_note_starttls_offer = yes
#smtpd_tls_recieved_header = yes
#smtpd_tls_session_cache_header = yes
tls_random_source = dev:/dev/urandom
</code>
Comment: Please add your postfix config to the question.
Comment: The message sounds like it occurs when your mailserver tries to connect to other mailservers. You could try setting `smtp_tls_security_level = may`, the default value for that directive is `none`. Do you get any additional messages in the log file regarding TLS, maybe on server startup?
Comment: I don't get anything special in the log file. All I get is
Sep 19 16:11:14 mail postfix[4467]: Postfix is running with backwards-compatible default settings

Sep 19 16:11:14 mail postfix[4467]: See http://www.postfix.org/COMPATIBILITY_README.html for details

Sep 19 16:11:14 mail postfix[4467]: To disable backwards compatibility use "postconf compatibility_level=2" and "postfix reload"

Sep 19 16:11:14 mail postfix/master[4504]: daemon started -- version 3.1.0, configuration /etc/postfix
Answer: Okay so i found a solution, it seems that there was something wrong with the certificate we generated, after buying a certificate online, it works wit no problem. So if anyone has the same problem, just make sure that the certificates your using, are properly setup.

Postfix and dovecot. TLS not available


Expected value of $X^TY$ in matrix form

Question: I want to compute $E(\mathbf{X}^T\mathbf{Y})$, where:
$$\mathbf{X} \sim N_d(\mathbf{\mu}, 4\mathbf{I}_d)$$
$$\mathbf{Y} \sim N_d(\mathbf{\mu}, 4\mathbf{I}_d)$$
Independence would seem to imply that this is the same as $E(\mathbf{X}^T)E(\mathbf{Y})$, which would be $||\mu||^2$.
Is this correct?
Answer: $\mu$ is a vector.
$$E(X^T)E(Y)=\sum_{i=1}^d \mu_i^2=\mu^T\mu=\|\mu\|^2$$
Comment: There was an issue with bolding of my notation not showing up, fixed - it looks like we have the same answer.

Expected value of $X^TY$ in matrix form