Deducing finitary Hales-Jewett from infinitary Hales-Jewett

Question: I have at my disposal the infinitary Hales-Jewett theorem. Denote by $\operatorname{Seq}(n)$ the set of all nonempty finite words generated by an $n$-letter alphabet.

If $\operatorname{Seq}(n)$ is finitely partitioned into $k$ parts, then for some $i \in \{1, \ldots, k\}$ part $i$ contains a combinatorial line.

I want to deduce the following finitary version of the theorem.

For any $n, k \in \mathbb{N}$ there exists $N \in \mathbb{N}$ such that for any $d > N$, if $n^d$ is partitioned into $k$ parts, then at least one of the parts contains a combinatorial line.

I'm approaching this by contradiction. Hence for any $N \in \mathbb{N}$, there is some $d > N$ such that $\{1,\ldots,n\}^d$ can be partitioned into $k$ parts but none of the parts contain a combinatorial line. Hence, for each $N \in \mathbb{N}$, we have some $d_N$ so that $\{1,\ldots,n\}^d$ can be made into a "bad partition".
I'm unsure how to proceed exactly. I think the idea is to extend the bad partition of $\{1, \ldots, n\}^d$ to a partition of $\operatorname{Seq}(n)$, but doing so is not obvious. I can of course extend every word in every part "upwards" by considering all its extensions, but this only gets me halfway to a partition of $\operatorname{Seq}(n)$; I also need to extend downwards. Doing so is tricky because words coming from different parts of the bad partition might have common prefixes. Instead, I thought perhaps I can bin all the words of length less than $d$ into a new part to form a partition of $\operatorname{Seq}(n)$. But then if I apply the infinitary Hales-Jewett, it could be that the combinatorial line is in this new part, and I'm unsure how to handle that. In fact, even if the combinatorial line that the infinitary Hales-Jewett theorem gives me is in one of the parts corresponding to a piece of the original bad partition, it's unclear to me how exactly I can use it to obtain a combinatorial line.
We saw this material in the context of ultrafilters (we used nonprincipal ultrafilters in the Stone-Cech compactification of $\operatorname{Seq}(n)$ to prove the infinitary Hales-Jewett theorem) so I believe I should use an argument involving an ultrafilter.
Answer: First, to prove that there exists some $N$ such that $n^N$ can be finitely partitioned into $m$ pieces in any way and have a combinatorial line in one of the pieces, suppose to the contrary that there is no such $N$. Then for every $N$ we have a bad partition into $m$ pieces, such that no piece contains a combinatorial line. For each stage $N$, enumerate the pieces of the bad partition by $P_{i,N}$ for $i \in [m]$. Define the family of sets
$$
P_i = \bigcup_{j < \omega} P_{i,j}
$$
for every $i \in [m]$. Note that this family of sets is a partition of $\operatorname{Seq}(n)$.
By the infinitary Hales-Jewett theorem, there exists a piece, say $P_i$, in this partition that contains a combinatorial line, say $L$ generated by the variable word $w$ of length $l$. But then this combinatorial line is contained in $P_{i,l}$, which contradicts that the family of $P_{j,l}$ over $j < \omega$ is a bad partition.
Hence, no matter how $n^N$ is finitely partitioned into $m$ pieces, one of the pieces contains a combinatorial line.
Now we want to show that for any $d \geq N$, $n^d$ can be finitely partitioned in any way and have a piece with a combinatorial line.
We proceed by induction on $d$. The base case $d = N$ is covered by the above argument. Now for the step case suppose that $n^{d+1}$ is partitioned into $m$ pieces. We want to find a combinatorial line in one of the pieces. This induces a partition on the set of all words in $n^{d+1}$ that end in 1, which we can identify with words in $n^d$. Hence, this induces a partition on $n^d$, which by the induction hypothesis can be finitely partitioned in any way and have a piece with a combinatorial line, say $L$ generated by the variable word $w$ of length $d$. We can extend $w$ to $w^\prime \in n^{d+1}$ by appending the letter $1$. But then this generates a combinatorial line in the partition piece of $n^{d+1}$ corresponding to piece $i$ in $n^d$. Hence one of the pieces of $n^{d+1}$ contains a combinatorial line.


How do i make text stand center right to an img in html/css

Question: I want to make text stand next to an image(center)
f.eks. I want to have 3 image and 3 paragraphs of text. Each paragraph standing center-right to one of the images. Is this possible?
it feels like i have tried everything but nothing works.
(sorry for my bad english)

.container{
  display: flex;
  align-items: center;
  justify-content: center;
}
img{
  max-width: 100%;
  position: absolute;
  left: 200px;
  top: 0px
text-align: right;
}
.img-col{
  flex-basis: 50%
}
p{
  text-align: justify;
  vertical-align: middle;
}
span{
  vertical-align: middle;
}

    Hallo

Comment: Can you visually represent what you are trying to do?
Answer: Try this :

.container{
  display: flex;
  align-items: center;
  justify-content: center;
}
  img{
    max-width: 100%;
    position: absolute;
  left: 200px;
  top: 0px;
  text-align: right;
  display: inline-block;
    position: inherit;
  }
  .img-col{
    flex-basis: 50%;

  }
  p{
    text-align: justify;
    vertical-align: middle;
  }
span{
  vertical-align: middle;
}

Hallo

Answer: I think the easiest way, is to work with a display flex. Look at this:

Div A

Div B

http://jsfiddle.net/bezptfy3/
Here the two divs, in your case, the image and the text, are in a div with display flex. to align them to the center, you can use align-items: center and justify-content: center
For more information on positioning check out:
https://developer.mozilla.org/de/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container
Answer: I think you are searching for
flex-wrap: wrap;

otherwise i think you require an order property by wrapping img and text in a new container like wrapper-one and so on
.wrapper-one {order:1}

Answer: For overlapping HTML elements, I prefer to use CSS grid.

            Hallo


What is the meaning characterizing a model as "conditional mean"

Question: I've been going through time series material of late, trying to re-invent myself as a practitioner in the field.  Until I got to the point of actually trying to Matlab some models, I had never run across the characterization of models as "conditional mean".  This term is pervasive throughout the entire documentation set; from what I can tell, it carries a particular significance in terms of modelling.
I haven't been able to wrap my head around what this significance is.  It is explained as the expression of the expectation of a variable of interest, conditional upon the values of other variables.  All the time series models that I've seen (indeed, all regression models) fall under this definition.  So I'm not sure how the term classifies models of interest, or identifies a subset, or identifies features that have modelling implications.  Nothing I've found on line makes it any clearer.
Thanks if anyone can provide a clarification, elaboration, or explanation of this.  My question arose in the context of Matlab (it just happens to be what I am using), but it is a conceptual question that isn't necessarily tied to Matlab.  It has been posted to:
What is the meaning characterizing a model as "conditional mean",
https://stackoverflow.com/questions/30406645/what-is-the-meaning-characterizing-a-model-as-conditional-mean, and
http://groups.google.com/forum/#!topic/comp.soft-sys.matlab/zQK8yScPFkk
Comment: Examples of models for conditional variance (rather than conditional mean): ARCH and GARCH models (and their numerous offsprings), stochastic volatility models.
Answer: The first time you usually see this concept is in linear regression.
Let's suppose that we have a hypothetical relationship between two random variables that looks like
$$ Y = aX + b + \epsilon $$
where $\epsilon$ is some unobserved variable that is symmetric about it's mean of zero.  Now suppose we take some observations of $X$ and $Y$ and want to use them to figure out a good guess at the parameters $a$ and $b$ in the relationship.  Well, the value of $X$ clearly influences the value of $Y$, so we may want to proceed in two stages:

Given that I know a value of $X$ already, what can I deduce about the distribution of $Y$?
What is the distribution of $X$?

A first cut at the first question is asking:

If I know a value of $X$ already, what is the mean of $Y$?

And this is the conditional expectation of $Y$ given $X$, usually notated $E(Y \mid X)$ (and referred to as some as the conditional mean).  This is the quantity that linear regression aims to estimate, because:
$$ \begin{align}
  E(Y \mid X) &= a*E(X \mid X) + bE(1 \mid X) + E(\epsilon \mid X) \\
  &= aX + b + 0 \\
  &= aX + b
  \end{align}
$$
Figuring out what's going on in each of these steps, and possibly what I left unsaid that is needed to make the calculation go through, is a nice way to test your understanding of the concept.
In time series, you often build autoregressive models, which assume a relationship like:
$$ Y_k = a_0 + a_1 Y_{k-1} + a_2 Y_{k-2} + \epsilon_k $$
for example.  Here the same kind of reasoning tells you that you would really like to know the mean of $Y_k$, given that you already know the values of $Y_{k-1}$ and $Y_{k-2}$.  This is called $E(Y_k \mid Y_{k-1}, Y_{k-2})$.  The comma on the right of the condition symbol means and in this context.

I get what you explained, and I guess my confusion is...what regression or projection model of interest isn't conditional mean? In other words, how is that characterization adding any information about the model that one is interested in? If there were models of interest that don't fall under that characterization, I can understand how that characterization conveys information. But the only characterization I can think of that isn't conditional mean is a pure noise source. But as I said, I'm new in the field, so I think I must be missing an entire body of models (of interest).

Notice that I got to the conditional mean by asking myself:

What's something simple I would want to know about the distribution of $Y$, given that I already know $X$?

Well, there are plenty of things I could ask:

Whats the mean of $Y$ given $X$?
What's the median of $Y$ given $X$?
What's the $90$'th percentile of $Y$ given $X$?

All these are valid questions, and there is a model for each of them.  To get at the conditional mean of $Y$ given X, you minimize the expected squared error:
$$ E(Y \mid X) = arg\,min_f E\left( (Y - f(X))^2 \right)$$
To get at the conditional median you minimize the expected absolute error:
$$ Median(Y \mid X) = arg\,min_f E\left( \left| Y - f(X) \right| \right)$$
To get at the 90'th percentile you do something else clever.  The last two cases are covered by a theory called quantile regression.  It has nice properties like resilience to outliers and asymmetry in the same way that the median does.
Comment: I get what you explained, and I guess my confusion is...what regression or projection model of interest *isn't* conditional mean?  In other words, how is that characterization adding any information about the model that one is interested in?  If there were models of interest that don't fall under that characterization, I can understand how that characterization conveys information.  But the only characterization I can think of that isn't conditional mean is a pure noise source.  But as I said, I'm new in the field, so I think I must be missing an entire body of models (of *interest*).
Comment: @StatSmartWannaB I added an example of a non-conditional mean model.
Comment: Huh.  OK.  I get that one can characterize the heck out of the uncertainty due to the nuisance parameter.  I've just never seen such a preoccupation with that particular detail in the context of regression or time-series.  I thought I was missing something big whenever I saw mention of conditional mean models, but if it's just a reminder that in other contexts, you could characterize processes by other metrics, I guess I can translate "conditional mean model" to "regression or time series".  In other words, I won't worry too much about it.  Thanks for clearing that up, Matthew.
Comment: P.S. I realize I abused the term "regression", since it's way more than ordinary least squares.  I looked up the quantile regression.  Interesting.  For some reason, it smells like rank order statistics, though if I think more than a minute about it, the connection is quite tenuous.


What output from PCA do I use for a Mahalanobis distance analysis?

Question: I am working with dental metric data to perform a biological distance analysis. The standard procedure in my field is to perform a PCA on the cleaned, imputed dataset to reduce correlation and then determine Mahalanobis Distance for each individual in the dataset. I've never done this type of analysis before, and I'm assuming it must be so obvious, because no one really explains how they move from Step 1 to Step 2.
I've completed a PCA using FactoMineR in R on my dataset; I'm keeping the first four principal components, which all have eigenvalues >1 (the standard in my field). However, I don't know what output from the PCA I should keep to run the distance analysis. The PCA function returns 3 values for individuals: coordinates for each dimension, cos2 for each dimension, and contribution for each dimension.
I'm guessing it's coordinates, but I'd rather be sure before I move on.
Answer: Yes it is under $ind$coord. You need to subset the columns based on the cut off you defined, for example:
library(FactoMineR)
res.pca <- PCA(iris[,1:4], scale.unit=TRUE, graph = FALSE)
# here i am using 0.5 not 1
keep = res.pca$eig[,1] > 0.5
PCs = res.pca$ind$coord[,keep]

Not very sure what kind of m you are calculating, but let's say we go for pairwise, using the solution from this post
cholMaha <- function(X) {
 dec <- chol( cov(X) )
 tmp <- forwardsolve(t(dec), t(X) )
 dist(t(tmp))
}
pairwise_Ma = cholMaha(PCs)

And simple cluster:
plot(PCs[,1:2],col=factor(kmeans(pairwise_Ma,3)$cluster))

Comment: Awesome, thank you! I am calculating pairwise, and the code worked perfectly.
Comment: you're welcome ! glad it works for u


MONGO_URL doesn't work with meteor reset

Question: You can use MONGO_URLenv variable to tell meteor to connect to your instance of mongodb. Great.
For instance:
MONGO_URL=mongodb://localhost:27017/my_project meteor works. I see the new documents in my robomongo on localhost in a database named my_project.
But if I do:
MONGO_URL=mongodb://localhost:27017/my_project meteor reset, the database my_project stays unchanged. meteor reseting works when I use the meteor-provided mongodb (when I don't supply MONGO_URL).
Things I tried:

EXPORTing MONGO_URL instead of putting it in front of the command. Doesn't help.

Also to what mongo instance do meteor connects to if I just run meteor (the default one) ? I can't find any meteor database on my localhost
Comment: To open robomongo on default mongo server created by meteor: In robomongo: `File > Connect > Create > name: 'Meteor default', address: 'localhost:3001' > Connect`. Your collections are in `Meteor > collections`. `meteor` server must be started for this to work.
Answer: If you don't specify a MONGO_URL, then mongo will create a database in your .meteor directory tree and run it on 127.0.0.1:3001. The mongo reset command seems to just remove the local files for those. To reset your external mongo db for your meteor app you can just remove the my_project db: mongo my_project -> db.dropDatabase().
Comment: Thanks. I would have loved to be able to `meteor reset` on my specific database `my_database`. Is there a way ?
Comment: Meteor does run `127.0.0.1:3001` once my meteor server is started. I could connect robomongo to it. This is very handy.
Answer: From the source code for the 'reset' command
if (options.args.length !== 0) {
  process.stderr.write(
    "meteor reset only affects the locally stored database.\n" +
    "\n" +
    "To reset a deployed application use\n" +
    "  meteor deploy --delete appname\n" +
    "followed by\n" +
   "  meteor deploy appname\n");
  return 1;
}


Extensão do google chrome não mostra popup padrão

Question: Comecei ontem a desenvolver extensões para o google chrome, e segui como manda o google:
Declarei meu manifesto e adicionei a página com a popup:
{
    "name": "ODM Integration",
    "description": "Open Download Manager integration for google chrome",
    "version": "1.0",
    "manifest_version": 2,
    "default_locale": "en_US",
    "author": "Samuel Ives",

    "browser_action":{
        "default_popup": "popup.html"
    },

    "permissions":[
        "pageCapture"
    ]
}

Página html:
<!DOCTYPE html>

        <title>ODM Integration<title>
        <meta charset = "UTF-8" />

Files

porém o que ele retorna quando clico na extensão é um quadrado de uns 12 x 12 pixels em branco.
Answer: Primeiro problema, para usar
 "default_locale": "en_US"

é necessário que exista a pasta _locales, já o segundo problema é que você não fechou a tag title:
 <title>ODM Integration<title>

O HTML está sendo gerado assim:

Ou seja tudo esta sendo considerado texto, o correto seria:
 <title>ODM Integration</title>

HTML inteiro:
<!DOCTYPE html>

        <title>ODM Integration</title>
        <meta charset = "UTF-8" />

Files

Comment: Realmente não tinha percebido a tag title não tinha feichado a tag title, isso se deve ao costume do sublime text automaticamente abrir e feichar tags, colchetes etc... , mas porém já tenho uma pasta chamada _locales e dentro tenho en_US e pt_BR ambos com messages.json. Apenas feichei a tag e funcionou perfeitamente.


JavaFX app icon fails to show 9/10 times

Question: I have an application which opens absolutely fine, but am having trouble setting an icon for it. The icon I give the path to is there, and changing to another imagine in that directory shows the icon 9/10 times, but this image never shows. There is always a question mark in it's place. So even on another file, which I know will work (ie. isn't corrupted), how come it only shows so rarely?
Below is the code of MyApplication.java
package MyApp;

import MyApp.Variables.Constants;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Forms/FormMain.fxml"));

        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/img/appicon.png")));
        primaryStage.setTitle("MyApp " + Constants.VERSION_NAME + " (" + Constants.RELEASE_ID + ")");
        primaryStage.setScene(new Scene(root, 1000, 800));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Below is the project directory structure relating /img/ to Main.java:

I have tried all the solutions here but nothing fixed my issue.
Running on Ubuntu 16.04, intelliJ IDEA for the IDE, though the problem persists with an exported JAR file.
Comment: Use [new Image("File:/img/appicon.png")] if it works. also check this http://download.java.net/jdk8/jfxdocs/javafx/scene/image/Image.html as for the jar you have to use [new Image(getClass().getResourceAsStream("/img/appicon.png");]
Comment: I'm afraid that didn't work. I've had a look on the docs but I'm not really sure what to gain from it, I have tried using various constructors, passing in a stream instead of a string, background loading, nothing worked.
Comment: when you export it as a jar you have to get it as a Stream using new Image(getClass().getResourceAsStream("/img/appicon.png"); can you provide an image of how your project is constructed?
Comment: Image has been added to main post. I have changed my code to use getClass().getResourceAsStream(...) but still to no avail.
Comment: Use a constructor `Main()` and there load the icon with `new Image(MainApp.class.getResource(filename with extension).toExternalForm())` in a variable. In your `start()` method add the variable to your icons.
Comment: There is a Main(String[] args) constructor present which is the one that automatically gets called. If I initialise the variable before it runs launch(args), it says Internal Graphics not intialised yet. If I initialise the variable after, it is null when used, because launch involves running start. Can I initialise internal graphics manually somehow?
Comment: And you should be aware of the thing with the dash, explained [here](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-)
Comment: main(string[] args) is not a constructor! It's a method. But I think you should remvoe the first dash or add a dot in front of it.
Comment: That's good to know, thank you.
Comment: Oh yes, my bad! I'll try that now.
Comment: Removing the dash causes Unable to construct Application instance: class MyApp.Main.
Comment: @Mike Croall when you export the jar run it with cmd or terminal what error you get there? java -jar myjar.jar
Comment: Absolutely no errors. It simply shows the default question mark, and doesn't throw any errors in terminal.
Comment: Class Image doesn't throw errors on creation, this is for convenience. It stores errors in a property.
Answer: Loading Data from your disk is time consuming, so you be able to start loading the icon while the object is constructed. Place it in a constructor and save it in a instance member. Normally you need to add more than one icon, because each platform needs it own sizes (for links and so on).
package MyApp;

import MyApp.Variables.Constants;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class Main extends Application {

    private Image icon;

    public Main() {
      icon = new Image(Main.class.getResource("/img/appicon.png").toExternalForm());
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Forms/FormMain.fxml"));

        primaryStage.getIcons().add(icon);
        primaryStage.setTitle("MyApp " + Constants.VERSION_NAME + " (" + Constants.RELEASE_ID + ")");
        primaryStage.setScene(new Scene(root, 1000, 800));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

My icon was this:
and the app structure in Netbeans looks like that:

and the running app look like that:
Comment: getResource only accepts a string, it refuses to take no parameters.
Comment: I did try that while you were making the edit - it still Cannot construct Application instance etc, due to InvocationTargetException in native code, due to NullPointerException from getResource being null. Removing the full stop at the beginning causes getResource to no longer be null, application launches, but icon still doesn't show.
Comment: Hm, I've done some points, and on my machine this is running and showing the app icon. Maybe you need to load more icons in different resolutions like 16, 22, 24, 32, 48 and so on. This is needed for other platforms like Mac or Windows where you have different Icon sizes on different places.
Comment: Okay, I'll look into it. Many thanks for your efforts!
Comment: So adding in the sizes I want the icon to be make it work more, but still only sometimes. For example, I make it 16x16, run it, icon shows. Close it, run it again with no changes, default icon shows instead of mine.
Comment: Well you need to add a lot of icon sizes to `primaryStage.getIcons()`, because it is a ObservableList you can add multiple sizes of the same icon.
Comment: I am now adding multiple different sizes of icon, and it's still being inconsistent, no matter the combination of icon sizes. It may just be ubuntu causing problems as I don't know why else this could happen now.
Comment: That sounds strange. I don't have any problems with my app on Ubuntu 16.04, it loads all icons as aspected.
Comment: Interesting. I currently have sizes 16,22,24, and 32 all being added to the icons list. I run it once: shows my icon, stop it and run it again (no changes to anything): fails to show my icon. Thanks for the help anyway!
Comment: default app launcher icon size is 48px.
Comment: But why would it show it the first time and not the second?
Comment: How long you are waiting between these two calls?
Comment: Whether it's a couple seconds or a whole minute, it behaves the same.


Present value of cash flow

Question:
You are given interest rates $i_0=i_1=0.25$ and $i_2=i_3=1$. You have entered into a business transaction where you will receive $2$ at time $0$, $5$ at time $3$, $10$ at time $4$, in return for a payment by you of $3$ at time $2$. In place of all these cash flows, you are offered a single payment made to you at time $1$. What is the smallest payment you would accept?

$i_k=v(k+1,k)-1$
$\therefore i_0=v(1,0)-1 \rightarrow v(0,1)=0.8$
Similarly, $v(1,2)=0.8$
$v(2,3)=v(3,4)=0.5$
Therefore,
$v(0)=1, v(1)=0.8, v(2)=0.8^2, v(3)=(0.8)^2(0.5),v(4)=(0.8)^2(0.5)^2$
Present value of first cash flow
$=(2)(1)+(0)(.8)+(-3)(.8)^2+(5)(.8)^2(.5)+(10)(.8)^2(.5)^2=3.28$
For an equivalent cash flow at time $1$,
$3.28=(x)(0.8) \rightarrow x=4.1$

But I am uncertain of my work. Please crosscheck the working.
Answer: $$ FV_1 = 2*(1+i_0)^2(1+i_2)^2 - 3(1+i_2)^2 + 5*(1+i_2)+10 = 20.5$$
$$FV_2 = C(1+i_1)(1+i_2)^2 = 5C$$
where $i_1 = i_0$ and $i_2 = i_3$
Equating these two
You get $C = \frac{20.5}{5} = 4.1$
Yes, You are correct on your answer.
Answer: You do not need to discount to time 0 and then yield interest $i_0$. But that aside, your solution is more than sufficient.
I like to illustrate my work progress, so that I am sure I get the right expression for the present value at time 1. I find that a good tool for many students who are new to this stuff. See my figure below:

Present value of cash flow


NUTS algorithm efficient transition kernel

Question: I'm reading this paper, but I'm struggling to understand the following transition kernel.
$T(w^{'}|w,\mathcal{C})=\left\{\begin{matrix}
\frac{\mathbb{I}[w^{'}\in\mathcal{C}^{new}]}{|\mathcal{C}^{new}|}& if \ \ |\mathcal{C}^{new}|>|\mathcal{C}^{old}| \\
 \frac{|\mathcal{C}^{new}|}{|\mathcal{C}^{old}|}\frac{\mathbb{I}[w^{'}\in\mathcal{C}^{new}]}{|\mathcal{C}^{new}|}+(1-\frac{|\mathcal{C}^{new}|}{|\mathcal{C}^{old}|})\mathbb{I}[w^{'}=w]& if  \ \ |\mathcal{C}^{new}|\leq |\mathcal{C}^{old}|
\end{matrix}\right.$
This transition kernel proposes a move from the $\mathcal{C}^{old}$  to a random state in $\mathcal{C}^{new}$, where $\mathcal{C}^{old}\cap\mathcal{C}^{new}=\varnothing$. Generally the acceptance probability to make a move from $\mathcal{C}^{old}$ to $\mathcal{C}^{new}$ is   $\frac{|\mathcal{C}^{new}|}{|\mathcal{C}^{old}|}$.
1) In this transition kernel we have this term $\mathbb{I}[w^{'}=w]$ . Does this mean that NUTS can generate states that are already observed? But we know that $\mathcal{C}^{old}$ and $\mathcal{C}^{new}$ are disjoint, so this means that $\mathbb{I}[w^{'}=w]$ will always be zero?
2) Also what is the interpretation of the restriction inequalities? I believe that when $|\mathcal{C}^{new}|>|\mathcal{C}^{old}|$ we are freely to choose a state from $\mathcal{C}^{new}$ but when $|\mathcal{C}^{new}|\leq \mathcal{C}^{old}|$ we have to multiply the probability $\frac{\mathbb{I}[w^{'}\in\mathcal{C}^{new}]}{|\mathcal{C}^{new}|}$ with the weight of actually making a move to $\mathcal{C}^{new}$ , $\frac{|\mathcal{C}^{new}|}{|\mathcal{C}^{old}|}$.
Answer: The way to interpret this is as a function that could be applied to any potential $w'$. Specifically,
When $\lvert \mathcal C^\mathit{new} \rvert > \lvert \mathcal C^\mathit{old} \rvert$, $T$ picks among $\mathcal C^\mathit{new}$ uniformly.
When $\lvert \mathcal C^\mathit{new} \rvert \le \lvert \mathcal C^\mathit{old} \rvert$, then with probability $\lvert \mathcal C^\mathit{new} \rvert / \lvert \mathcal C^\mathit{old} \rvert$, it will pick uniformly among $\mathcal C^\mathit{new}$. (So the case where the two sets are of equal size could be put into the other case as well.) When it doesn't do that uniform pick, i.e. with probability $1 - \lvert \mathcal C^\mathit{new} \rvert / \lvert \mathcal C^\mathit{old} \rvert$, it will choose to keep $w'$ the same as $w$ (keep the walk in the same place, like a Metropolis rejection step).
In both cases, if you pass in a $w'$ that's not either in $\mathcal C^\mathit{new}$ or $w$, then it'll return 0 (because the indicators will all be 0), i.e. no probability of that happening.


Problema na importação de fontes CSS

Question: Galera, estou com um pequeno problema na importação de fontes, quando coloco as fontes nativas funciona, com excessão da Helvetica, e quando vou importar uma fonte local ou por url é como se não conseguisse acessar a fonte e então o browser usa a default.

@font-face {
  font-family: 'Futura';
  src: local('../../../css/font/Futura/Futura.ttc'), url('http://www.projetogiulia.com.br/assets/css/font/Futura/Futura.ttc') !important;
}

Há algo de errado com meu código?
Desde já agradeço
Comment: no lugar de `local` coloque `url` e remova o `url` com o link. (removendo o important também)
Answer: Experimenta importar e depois adicionar, assim:
@import url('http://www.projetogiulia.com.br/assets/css/font/Futura/Futura.ttc');
font-family: 'Futura', sans-serif;

outra forma seria em vez de usar o import url usar um link
<link href="http://www.projetogiulia.com.br/assets/css/font/Futura/Futura.ttc" rel="stylesheet">

Problema na importação de fontes CSS


No exact matches in call to instance method error message in Swift

Question: I never get this before, What is the meaning of this error message in Swift:

No exact matches in call to instance method 'dataTask(with:completionHandler:)'

Here is my code block:
var request: NSMutableURLRequest? = nil
let task = URLSession.shared.dataTask(
            with: request,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {
                  /// ...
                })
            })
task.resume()

Bug Report
Reported via feedbackassistant.apple.com: FB7717686
Note: The Error still exists in the Xcode Version 14.3 on 2023, May 1
Comment: The error message can be MISLEADING! For me I was passing **two** optionals as arguments for my function — while both needed to be non-optional. **If** I did correct one of the inputs then the error would instead be something meaningful: "Value of optional type 'String?' must be unwrapped to a value of type 'String'". The compiler is able to show the correct error message when a single parameter is passed incorrectly. Yet when it's two, the compiler gives you a misleading/hard to interpret message. FWIW some answers point to some other misleading error. So your case might be diff
Answer: Why Xcode Yelling?
Maybe the message text seems a little bit self-explanatory but because Xcode does not precisely point to the parameter itself, a little bit hard to figure out the first time.
Xcode is yelling because the method wants to see exact parameter types on the method call, that is easy.
Solution for the Question:
var request: URLRequest? = nil

let task = URLSession.shared.dataTask(
            with: request!,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {

                })
            })
task.resume()

Just used the URLRequest instead of the NSMutableURLRequest.
A SwiftUI Case
Let's assume this is your UI:
        ZStack() {
            Image(systemName: "photo")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(12)
            Text(getToday())
                .font(.headline)
            }
        }

And this is the method that you're calling in the Text(...):
    func getToday() -> Any?
    {
        let now = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: now)
        return components.day

    }

Solution
In the example above solution would be changing the Any? to a String type.
A NSURL Case
if let url = NSURL(String: "http://example-url.com/picture.png") {
  // ...
}

Solution
if let url = URL(String: "http://example-url.com/picture.png") {
  // ...
}

ℹ No exact matches in call
to instance method '* * *'
This is a general error message for using the wrong type in the method calls. That's why I added here to help others.
I hope this answer will help some of you guys.
Best.
Comment: You might want to file a bug report with Apple. Surely the diagnostic could be better than this.
Comment: The error still appears almost 2 years later in Xcode 12.4 in the same confusing way: I was using `session.dataTask(with: url)` but hadn't changed the surrounding function to pass the url yet (`url` was undeclared) and that's the error I got, even though `dataTask(with:) exists.
Comment: Thank you @matt, I reported via https://feedbackassistant.apple.com.
Answer: I was using dataTask with URL, but I was unwrapping the URL as NSURL, and that is why it was giving me an error.
I was doing this:
if let url = NSURL(String: "http://myyrl.com/filename.jpg") {
      //my code
}

What fixed the error was replacing NSURL with URL:
if let url = URL(String: "http://myyrl.com/filename.jpg") {
      //my code
}

Comment: Thank you for your answer. It's about Xcode and it's a general error message. It can cause in so many situations. Best.
Answer: If you're getting this error in a Text element, try wrapping your value in String(describing: value). Fixed my case.
Text("Leading text \(String(describing: value))")

Source
Comment: Might not be the exact answer to the question, but in general is a way to workaround this. Often it is just an unwrapped optional, and this way you will discover
Answer: Xcode gives this error when you add SKPaymentQueue methods (such as SKPaymentQueue.default().add() to your code before making the current class conform to the SKPaymentTransactionObserver protocol.
Just make your class conform to the SKPaymentTransactionObserver protocol to solve this error if this is the case.
Comment: My class was missing `SKPaymentTransactionObserver`, this was the only helpful comment, thanks!
Answer: Also check if the url is the actual url and not a String
URLSession.shared.dataTask(with: url) { data, response, error


How to paste the text in command-line mode in vim?

Question: I have copied a word to search from the file.
Is there a command to paste that word in command-line mode.
For eg. I have copied the word 'static' from the code below in default register and I want to paste that in command-line mode, as below
/static
1275 static const struct of_device_id omap_mcspi_of_match[] = {
1276         {
1277                 .compatible = "ti,omap2-mcspi",
1278                 .data = &omap2_pdata,
1279         },
1280         {
1281                 .compatible = "ti,omap4-mcspi",
1282                 .data = &omap4_pdata,
1283         },
1284         { },
1285 };

Answer: While in either command mode or in search mode, type Ctrl+R" to paste from the default register. That is, type Ctrl+R, release it and then type ".
For any other named register, you can just to Ctrl+R followed by the name of the register, like a or b.
Alternately, if you enter search mode using the command q/ instead of just /, you can simply use p to paste, the same way you would in a normal buffer.
Answer: There are a couple of ways to do this.

Check :h c_^r. On the command-line you can say /<C-R>" to copy the contents of the default register " and it will get converted to /static
Alternately, a more convenient way (in most cases) is to use :h c_^r^w to copy the current word under the cursor denoted by <cword>. So you can say /<C-R><C-W> and that will get converted to /static given that your cursor is on the word static.
Comment: : `"` answers the question as asked, but `` is almost certainly the answer to the underlying problem!
Answer: What about simply hitting * with the cursor in static?
Comment: Agreed, if the intent was merely to search for the word, this would be the most effective solution.
Comment: @merlin2011 If the intent was to built a pattern including the word this solution is still usable: After pressing `*` you can press `/` and `` to get the last search pattern, which is the word.


Reparametrization trick in VAE at Evaluation time

Question: So I've been trying to implement the Variational Auto-Encoder model of Kigma et.al, but something has been bugging me. While I understand the need for reparametrization trick at training time, the rational behind the usage of the same trick at evaluation time is escaping me.

At training time we turn the random (latent) variable $z$ into a deterministic function in order to allow gradients to flow through it:
$$= +⋅$$
where $∼N(0,1)$. However, at evaluation time such trick is not required, since we can directly sample the latent variable $$ from the parametric model (encoder network) $(∣,)$ of the true posterior.
Yet, most implementations of VAE I have come across still perform the reparametrization trick at evaluation time.
So my question is "What is the rational behind using the reparametrization trick at testing time?".
Answer:
However, at evaluation time such trick is not required, since we can
  directly sample the latent variable $$ from the parametric model
  (encoder network) $(∣,)$ of the true posterior.

To nitpick, $q$ is not the true posterior, just an approximation of it.
To answer your question: because it doesn't cost more than not using the trick, and also because now you can reuse code instead of writing the same function in two different ways.


Undefined method 'host' in rspec

Question: I have the following methods in a Ruby script:
def parse_endpoint(endpoint)
    return URI.parse(endpoint)
end

def verify_url(endpoint, fname)
    url = "#{endpoint}#{fname}"
    req = Net::HTTP.new(url.host, url.port)
    res = req.request_head(url.path)
    if res.code == "200"
        true
    else
        puts "#{fname} is an invalid file"
        false
    end
end

Testing the url manually like so works fine (returns true since the url is indeed valid):
endpoint = parse_endpoint('http://mywebsite.com/mySubdirectory/')
verify_url(endpoint, "myFile.json")

However, when I try to do the following in rspec
describe 'my functionality'

    let (:endpoint) { parse_endpoint("http://mywebsite.com/mySubdirectory/") }

    it 'should verify valid url' do
        expect(verify_url(endpoint, "myFile.json").to eq(true))
    end
end

it gives me this error
"NoMethodError:
undefined method `host' for "http://mysebsite.com/mySubdirectory/myFile.json":String"

What am I doing wrong?
Answer: url is a String object, and you are trying to access a method called host which does not exist in String:
url = "#{endpoint}#{fname}"
req = Net::HTTP.new(url.host, url.port)

EDIT you probably need an URI object. I think this is what you want:
2.2.1 :004 > require 'uri'
 => true
2.2.1 :001 > url = 'http://mywebsite.com/mySubdirectory/'
 => "http://mywebsite.com/mySubdirectory/"
2.2.1 :005 > parsed_url = URI.parse url
 => #<URI::HTTP http://mywebsite.com/mySubdirectory/>
2.2.1 :006 > parsed_url.host
 => "mywebsite.com"

So just add url = URI.parse url before using url.host.
Comment: That's exactly what the answer needed. Nice! Worth noting that `URI.parse` can throw exceptions, so be prepared for the unexpected in production code.
Comment: That identifies the problem but not the solution. What about `URI.parse`?
Comment: @tadman Yes, URI has a 'host' method. I edited my answer explaining how to solve the problem using URI.
Answer:
Testing the url manually like so works fine (returns true since the url is indeed valid):
endpoint = parse_endpoint('http://mywebsite.com/mySubdirectory/')
verify_url(endpoint, "myFile.json")

It seems you missed something when you tested code above (maybe you tested old version) because it can't work as it is now.
Look at these lines of code:
url = "#{endpoint}#{fname}"
req = Net::HTTP.new(url.host, url.port)

You're creating a string variable url from other two variables endpoint and fname. So far, so good.
But then you're trying to access method host on url variable, which doesn't exist (but it exists on the endpoint variable), that's why you get this error.
You may want to use this code instead:
def verify_url(endpoint, fname)
  url = endpoint.merge(fname)
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.head(url.path)
  end
  # it's actually a bad idea to puts some text in a query method
  # let's just return value instead
  res.code == "200"
end

Undefined method 'host' in rspec


Why does Python Flask throw a HTTP 404 error

Question: It is several years since I have used Flask, starting on a new project.
I get a HTTP 404 error. The requested URL is not found??
The index and the requested URL are both in the templates folder.
I don't understand why it is throwing a HTTP 404 error??
Any pointers appreciated, thanks.
Clive
I have a code snippet in routes.py.
@app.route('/service_response', methods=['GET','POST'])
def service_response():
  servicesql = "SELECT * FROM DASHBOARD_SERVICE_RESPONSE"
  data = list(conn.execute(servicesql))

  return render_template('service_response.html', service_response=servicesql)

In index.html I have:

BCC Report Period

Answer: Your code points to src="service_response.html" while what you want to do is to point to /service_response which will render the 'service_response.html' jinja template.


Customizar ProgressBar Android

Question: Gostaria de desenvolver uma ProgressBar customizada para utilizar em minha aplicação, mas estou com dúvida de como fazer isto.
É necessário criar uma sub classe da ProgressBar? Dá pra fazer somente em xml?
Gostaria que me dessem um exemplo básico de como customizar este componente.
segue meu código, sem customização nenhuma.
Arquivo main_activity.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="250dip"
        android:layout_height="wrap_content"
        android:max="100"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        style="?android:attr/progressBarStyleHorizontal"/>

</RelativeLayout>

Classe MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.widget.ProgressBar;

public class MainActivity extends Activity{

    private ProgressBar progressBar;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
    }

    //Mais código

}

Comment: Que tipo de customização você quer fazer? A `ProgressBar` do Android é bem limitadazinha, então as chances de você ter que criar uma subclasse e *override* a view são grandes.
Comment: A customização que quero fazer é: mudar cor fundo de quando carrega, mudar borda, tirar os cantos arredondados e tals... Caso tenha algum componente melhor, mais customizável e com a mesma finalidade, agradeço se me disser :)
Answer: Eu não sei te explicar direito como fazer mais vou mostrar esse exemplo que eu uso:
<ProgressBar
        style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:id="@+id/progressBar"
        android:layout_below="@+id/edittext_url"
        android:layout_centerHorizontal="true"
        android:progressDrawable="@drawable/custom_progressbar" />

Atenção para a linha android:progressDrawable="@drawable/custom_progressbar"
custom_progressbar.xml (res\drawable)
<?xml version="1.0" encoding="utf-8"?>
<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <gradient
                    android:startColor="#ff49a8a6"
                    android:centerColor="#ff49a8a6"
                    android:endColor="#ff49a8a6"
                    android:angle="270.0" android:centerY="1.0"  />
            </shape>
        </clip>
    </item>
</layer-list>

Resultado:
Comment: Justamente o que eu precisava! Obrigado...

Customizar ProgressBar Android


Why does tomcat7 log into both catalina.out and catalina.YYYY-MM-DD.log?

Question: On OpenBSD 5.2, the default installation of tomcat-7.0.29 seems to be logging all errors into both catalina.out and catalina.YYYY-MM-DD.log.
Cns# ll /var/tomcat/logs/catalina.*
-rw-r--r--  1 _tomcat  _tomcat      3067 Jan 16 20:47 /var/tomcat/logs/catalina.2013-01-16.log
-rw-r--r--  1 _tomcat  _tomcat   1313285 Jan 17 21:47 /var/tomcat/logs/catalina.2013-01-17.log
-rw-r--r--  1 _tomcat  _tomcat     19668 Jan 18 17:33 /var/tomcat/logs/catalina.2013-01-18.log
-rw-r--r--  1 _tomcat  _tomcat      2479 Jan 23 15:25 /var/tomcat/logs/catalina.2013-01-23.log
-rw-r--r--  1 _tomcat  _tomcat      1580 Jan 26 22:58 /var/tomcat/logs/catalina.2013-01-26.log
-rw-r--r--  1 _tomcat  _tomcat     48165 Jan 27 19:30 /var/tomcat/logs/catalina.2013-01-27.log
-rw-r--r--  1 _tomcat  _tomcat     34526 Jan 28 16:41 /var/tomcat/logs/catalina.2013-01-28.log
-rw-r--r--  1 _tomcat  _tomcat    141985 Jan 29 23:56 /var/tomcat/logs/catalina.2013-01-29.log
-rw-r--r--  1 _tomcat  _tomcat    123254 Jan 30 23:25 /var/tomcat/logs/catalina.2013-01-30.log
-rw-r--r--  1 _tomcat  _tomcat    145209 Jan 31 22:30 /var/tomcat/logs/catalina.2013-01-31.log
-rw-r--r--  1 _tomcat  _tomcat      2615 Feb  1 09:01 /var/tomcat/logs/catalina.2013-02-01.log
-rw-r--r--  1 _tomcat  _tomcat     10068 Feb  2 19:18 /var/tomcat/logs/catalina.2013-02-02.log
-rw-r--r--  1 _tomcat  _tomcat     50541 Feb  3 23:49 /var/tomcat/logs/catalina.2013-02-03.log
-rw-r--r--  1 _tomcat  _tomcat     17519 Feb  4 21:29 /var/tomcat/logs/catalina.2013-02-04.log
-rw-r--r--  1 _tomcat  _tomcat      1158 Feb  5 22:18 /var/tomcat/logs/catalina.2013-02-05.log
-rw-r--r--  1 _tomcat  _tomcat    179466 Feb  6 23:51 /var/tomcat/logs/catalina.2013-02-06.log
-rw-r--r--  1 _tomcat  _tomcat  14585534 Feb  7 14:15 /var/tomcat/logs/catalina.2013-02-07.log
-rw-r--r--  1 _tomcat  _tomcat  16680119 Feb  7 14:15 /var/tomcat/logs/catalina.out

(Note how the total files size of catalina.YYYY-MM-DD.log is about the same as catalina.out, and the logs do seem duplicated.)
Is there a way to make it log only into catalina.YYYY-MM-DD.log, and not into catalina.out?
Comment: @kubanczyk: How exactly did you de-configure catalina.xxx.log?
Comment: I prefer to keep catalina.out and rotate it. I de-configure catalina.xxx.log as in the most general case it contains less messages (it ignores `System.out` and `System.err`; programmers sometimes use these in a hurry).
Comment: Related: https://stackoverflow.com/questions/51985958/what-is-the-difference-between-catalina-out-and-catalina-yyyy-mm-dd-log-log
Answer: After reading some info at http://tomcat.apache.org/tomcat-7.0-doc/logging.html, it seems like commenting out or removing all mentions of java.util.logging.ConsoleHandler from /etc/tomcat/logging.properties should do the trick.
After that, somehow the file still gets opened up for writing by tomcat (as stdout and stderr), but it doesn't seem to be puffed up with anything anymore.
Cns# stat /var/tomcat/logs/catalina.out
1136 3949577 -rw-r--r-- 1 _tomcat _tomcat 15763648 16695929 "Feb  7 14:58:46 2013" "Feb  7 14:58:37 2013" "Feb  7 14:58:37 2013" 16384 32672 0 /var/tomcat/logs/catalina.out
Cns# fstat | fgrep -e USER -e 3949577
USER     CMD          PID   FD MOUNT        INUM MODE       R/W    SZ|DV
_tomcat  java        8994    1 /var      3949577 -rw-r--r--   w 16695929
_tomcat  java        8994    2 /var      3949577 -rw-r--r--   w 16695929
Cns#

Answer: There are two possible solutions supported by Tomcat wiki:

Prevent application to log on System.out or System.err using logging frameworks.
Suppress capture it by swallowOutput. Where does System.out go?
First two steps of instruction how to do this.

additionally one remark about rolling it. How do I rotate catalina.out?


What can a musician determine from the below examinations about the student, and how?

Question: In my university's musics and fine arts department, all the instrument courses have some sort of interview for the students from the other departments.For example, for violin courses, they played 4 different notes on piano and after each note, I have asked to sing "aaaa". After that, they gave me some rhythm by clapping their hands, and I was asked to repeat that rhythm with clapping my hands.
So my question is, what can a musician, or a lecturer on music, determine from these kind of examinations about the student, and how ?
Comment: At uni. level this seems way too easy. It's the sort of thing that gets asked at grade 3 or 4 music exams. It's really to ascertain how good a candidate's ear is to pitch and rhythm. Some can do this naturally, others have to learn how, and practice doing it. A few never get there, so maybe it weeds them out, although I can't think why someone lacking in this area would want to be on a uni. course.
Comment: This sounds like a very basic diagnostic exam that would be used to determine whether you can start at the normal starting point for an Aural Skills sequence instead of beginning with something a bit more remedial than that. A prospective student that failed to do the things you talked about would probably not be able to handle Aural Skills I (or whatever it's called at your university) without falling behind.
Comment: At some schools, *practical* music courses for performance, joining music school orchestras and bands, etc, are (in theory) open to *all* students - but just because you were accepted for a degree course by the Law or History faculties, for example,  doesn't say anything about your practical ability as a *musician* - whether or not you have any formal musical training.
Answer: Literally those two questions test pitch sense and pitch imitation and rhythm sense and imitation. You have to at least be able to hear the differences between pitches and rhythms to be able to be taught music. Supposedly some people are not able to discern the difference in pitches ("tone deafness"), but I've never met anyone like that in real life.
Like Tim, I'm a little surprised. I remember being taught to recognize and clap rhythms at age 8, in the general music class that all students went to for about an hour every day.
Comment: Unfortunately, we're seeing more and more students entering college that have *zero* skills training. This is often a test to see who can enter the "regular" curriculum and which students need to be placed in a remedial curriculum.
Comment: @onurcanbektas I think Todd's answer holds true even with your edit. As for the "ah" sound, most schools are less interested in the tone quality of the singing and more interested in whether you match the pitch. So think less about "how to make the 'ah' sound" and more about matching the pitch the give you.
Comment: @Richard and Todd, please see my edit.
Comment: By the way, for the first test, i.e saying "aaa" with note, how should the student make the "aaa" sound so that it is understood that s/he has the sense of pitch ?
Comment: @Richard - sadly quite true. Even when I went was training to be a teacher, 50 odd yrs ago, there were students of 18 yrs old who needed extra lessons to get them up to 11+ standard,(an exam for grammar school, at 11), in maths. Frightening!
Comment: When the Blair government was busy "deskilling" the education system in the UK in the 1990s, to meet their nonsense target of "50% of all young people should get a degree," they could have saved a lot of wasted time and money (both for students and teachers) by just issuing every child with a randomly chosen set of qualifications at birth. Why waste your youth actually trying to *learn* stuff - it's all on the web anyway!!! Just saying...
Comment: @alephzero - you're right - it is all on the web. Trouble is, so is an awful lot - and a lot of awful - rubbish, which some will take as gospel. Thus perpetuating ignorance...   'deskilling' - for that, read 'killing'.


Lógica para comparar quatro valores e encontrar o menor

Question: É correto comparar 4 valores dessa forma?
Se (A < B && A <  C && A < D){
    Escreva A;
};

Senao Se (B < A && B <  C && B < D){
   Escreva B;
};
Senao Se (C < A && C <  B && C < D){
   Escreva C;
};
Senao Se(D < A && D <  B && D < C){
   Escreva D;
}
Senao{
   Escreva 0;
}

Comment: Você disse no comentário de uma resposta que quer pegar o menor valor, certo? E caso houver dois valores menores iguais, por exemplo, **A=0**, B=1, **C=0** e D=3?
Answer: Pode otimizar e acho que tem um erro:
Se (A < B && A < C && A < D) {
    Escreva A;
} Senao Se (B < C && B < D) {
   Escreva B;
} Senao Se (C < D) {
   Escreva C;
} Senao {
   Escreva D;
}

Coloquei no GitHub para referência futura.
Se A não é menor que os outros 3 não tem mais porque verificá-lo. Depois o mesmo com B, e finalmente com C. Se nenhum é menor que D então D é o menor. Não entendi porque poderia resultar em 0. Só se tinha algum requisito não descrito.
Comment: Entendi. O zero é so se caso desse erro do jeito que eu tava comparando.
Comment: Valeu Mano.....
Answer: Isso até funciona, se os valores forem todos diferentes (se tiver dois ou mais valores iguais, dará errado). Entretanto, o número de verificações dentro dos Ses vai crescer de maneira insustentável quanto mais variáveis você tiver, pois se você tiver N variáveis, precisará de N² - N testes com operadores relacionais.
A abordagem do Maniero reduz o número de verificações pela metade ((N² - N) / 2), mas existe uma abordagem simples que usa apenas N - 1 verificações:
MenorValor := A
Se (B < MenorValor) MenorValor := B;
Se (C < MenorValor) MenorValor := C;
Se (D < MenorValor) MenorValor := D;
Escreva MenorValor;

Comment: Então, Victor. O problema é que eu vou comparar 4 métodos. O que retornar o menor valor eu irei usá-lo. Não vejo uma maneira de fazer isso usando essa lógica.
Comment: @Hacker O que você quer dizer por "*comparar 4 métodos*"? Se A, B, C e D são variáveis, você simplesmente usa isso. Se forem chamadas a funções ou procedimentos, você salva o resultado de cada uma em uma variável e faz isso (o que também impede que elas sejam executadas mais do que uma vez). Qual é o impedimento?
Answer: Repare que da forma que você implementou é possível precisar de mais de três comparações. É possível encontrar mínimo de quatro valores com apenas três comparações em qualquer circunstância (ou seja, com melhor desempenho), isso de várias maneiras.
Por exemplo, pode-se encontrar o mínimo "M1" de "A" e "B" (M1=( A<B ? A : B );), depois encontrar o mínimo "N" de "C" e "M" (M2=( C<M1 ? C : M1 );) e finalmente retornar o mínimo de "D" e "M2" (return( D<M2 ? D : M2 );).
Outra forma (que pode ser melhor se puder paralelizar) é encontrar o mínimo "M" de "A" e "B" (M=( A<B ? A : B );) e paralelamente encontrar o mínimo "N" de "C" e "D" (N=( C<D ? C : D );), então é só retornar o mínimo de "M" e "N" (return( M<N ? M : N );).
Se quiser implementar este segundo sem usar temporários "M" e "N", pode-se usar a seguinte penca de comparações que utiliza o mesmo raciocínio, mas talvez não seja tão bem otimizado mesmo por bons compiladores.
if( A<B ){
    if( C<D ) return( A<C ? A : C );
    else return( A<D ? A : D );
}
else {
    if( C<D ) return( B<C ? B : C );
    else return( B<D ? B : D );
}

Se quiser generalizar o problema para encontra o mínimo de "n" números "a[0], a[1], ..., a[n-1]", pode-se de várias formas calcular o mínimo deles com "n-1" comparações. Uma delas é a seguinte, que é generalização do primeiro algoritmo citado.
T = a[0] ;
for( i=1 ; i<n ; i=i+1 ){
    if( T>a[i] ) T = a[i] ;
}
return T ;

Já a generalização do segundo requer recursão, coisa que somente vale a pena se der para compilar de forma otimizada (sem precisar de empilhamento) e neste caso é bom que há meios de se calcular paralelamente.
Isso se faz encontrando o mínimo "M" da primeira metade dos números, o mínimo "N" da segunda metade e depois retornar o mínimo de "M" e "N", onde a parada da recursão é a sequência de tamanho um, que aí o único número trabalhado é o mínimo.
Alguma dúvida?


Issue with references upgrading to TypeScript 0.9.0.alpha

Question: We have about a hundred .ts files in our project and a dozen .d.ts files. On TypeScript 0.8.3 to handle the references we had a single file called _references.d.ts that listed all of the definition files in the order of dependency and made sure that it appeared before any other typescript items in the project's .csproj file.
<ItemGroup>
  <TypeScriptCompile Include="Scripts\_references.d.ts" />
  ...

This way all references were resolved correctly without us having to add any references in any of the typescript source files. However, this doesn't seem to work anymore after upgrading to TypeScript 0.9.0.alpha. Right now it does not work even if we make a reference to _references.d.ts in every source file and have to go through all of them and include direct references to each definition file. This is going to be a pain, also I don't like this approach because we won't be able to know unused references in each .ts file and there's no easy way to clean them up. So my question is, is this pain by design, or is there any other way we can make the compiler happy about references?
Thanks!
Comment: I prefer to use the latest version in production environment. It's only generating javascript and that is human observable. If it was generating binary I would have steered clear :)
Comment: Not only does 0.9 introduce breaking changes to 0.8. You're using an alpha release in a production project. I'd consider at least waiting until it's out of alpha.
Comment: It is on a separate branch. So we want to be compatible with the latest as much as possible and report issues that can affect our code.
Answer: Its better to have a clear pipeline for TypeScript compilation from the command line, and I suppose that is what has happened.
I like to have a reference.ts in my project. That in turn references all the files in my project. And then each file in my project references this main file as :
/// <reference path="references.ts" />

Notice .ts instead of .d.ts
Typescript will work out circular dependencies (between file references ... not types) and you do not need to worry about this.
Compile your project as :
tsc --out output.js --declaration

and you get a single js + output.d.ts file for reuse in other projects.
Comment: I tried **.ts** instead of **.d.ts** but I see no difference. I don't see anything in the [specs](https://typescript.codeplex.com/downloads/get/672560) (See section 11.1.1) either that say dependencies are handled differently for source files and definition files. The only difference I see is that for **.ts** files a source map file is created but not for **.d.ts** files.
Comment: Will not have an impact if all your **.d.ts** contains are file references to **.ts** files. But if you put declarations inside **.d.ts** they will not become a part of the generated **.d.ts**. See : http://stackoverflow.com/a/16687938/390330
Answer: I think I found what was the problem. In our _references.d.ts file, there was an Interface that was declared at the top of the file before any references. The compiler did not give any informative errors and just ignored those references.
So all /// <reference path="..." />'s need to come first in the file.
Answer: I'm not entirely sure, but this feature might simply be lacking in the alpha version. Take into account that it's a preview of 0.9 and not all features are hence supported yet. There are other known features lacking in 0.9 alpha as well. To be sure, you might want to go over to the TypeScript project site and ask them directly.
BTW that's a nice little trick to make sure each file references the definitions, although I agree with BASarat that with this setup you can't build it from command line.
At our project we only use those references for actual definition files, all other modules are imported as intented. We provide a few wrapper definition files like for example general_libraries.d.ts and myproject.core.d.ts. This way we can easily add or remove definition files of libraries without having to update this in each and every place they're references.
Also note that when you've got 2 modules, A & B, and A references a definition file C and B imports A, B knows about C without having to reference it again.


Change Database Output

Question: I have a form setup and the data goes into a mysql database. There are several parts where the choice is both a numerical and a written rating - 1 - poor, 2 - fair, 3 - good, 4 - excellent. The field in the database is set to varchar with a length of 20. However, the output only returns the written portion - poor, fair, good, excellent, dropping the numerical. I want to either include the numerical with the written or just use the numerical itself. Can someone explain how I would set this up.
I am assuming the changes I need to make are in the php form itself - I am supplying a sample of the code and what I think I need to change - just want to verify before I do so.
<code><select name="programRating" class="pure-input-1">
                        <option value="">Select Rating...</option>
                        <option value="Poor" <?php if($_POST['programRating'] == "Poor") echo "selected"; ?>>1 - Poor</option>
                        <option value="Fair" <?php if($_POST['programRating'] == "Fair") echo "selected"; ?>>2 - Fair</option>
                        <option value="Good" <?php if($_POST['programRating'] == "Good") echo "selected"; ?>>3 - Good</option>
                        <option value="Excellent" <?php if($_POST['programRating'] == "Excellent") echo "selected"; ?>>4 - Excellent</option>
                      </select>

<select name="programRating" class="pure-input-1">
                        <option value="">Select Rating...</option>
                        <option value="Poor" <?php if($_POST['programRating'] == "1-Poor") echo "selected"; ?>>1 - Poor</option>
                        <option value="Fair" <?php if($_POST['programRating'] == "2-Fair") echo "selected"; ?>>2 - Fair</option>
                        <option value="Good" <?php if($_POST['programRating'] == "3-Good") echo "selected"; ?>>3 - Good</option>
                        <option value="Excellent" <?php if($_POST['programRating'] == "4-Excellent") echo "selected"; ?>>4 - Excellent</option>
                      </select>
</code>
Comment: You can use dictionary table or [enum](https://dev.mysql.com/doc/refman/5.0/en/enum.html). I'd prefer the former, and [that's why](http://komlenic.com/244/8-reasons-why-mysqls-enum-data-type-is-evil/).
Answer: The values which are stored in your database are the ones you specify in the "value" attribute of each "option".
So put the numbers in the "value" attribute instead of the text.
Comment: Can you have both numbers and text in the value field, so that it returns both, or am I limited to either the number or the text.

Change Database Output


Linear program with only inequalities between decision variables

Question: Suppose we have a linear program of the form $$\min_{x} c^T x$$ for $c \in \mathbb{R}^n, x \in \mathbb{R}^N$, subject to the constraints

$$x_i \leq x_j \qquad \forall (i, j) \in \Gamma$$
$$-1 \leq x_i \leq 1 \qquad \forall i$$

where $\Gamma$ is some index set consisting of pairs $(i, j)$. Here, the constraints only consist of inequalities between decision variables $x_i$, and restrictions on the domain of $x_i$.
Currently, I trying to model the constraints as a graph of inequalities between the $x_i$, where an edge $x_i \rightarrow x_j$ denotes that $x_i \leq x_j$. We can then reduce the size of the linear program by quotienting over strongly connected components, since variables in the same strongly connected component are equal.
My question:

Are there any further ways to reduce the size of this program?
Are any greedy strategies to solve this linear program in strongly polynomial time?
Comment: Is there an application behind this problem? (which may help reformulating constraints)
Answer: You can check for vertices that have only incoming our outgoing edges. Say vertex $i$ only has outgoing edges. Then if $c_i \geq 0$, without loss of generality, you may set $x_i = -1$. Then you can remove these vertices from the graph, along with their edges, and check if there's any new vertices with only outgoing edges.
A similar procedure can be done for vertices with only incoming edges. And you can combine them both to reduce your graph even more.


Manage display not updating user account display

Question: This is a new D7.14 site started only 3 days ago. There is no use of organic groups in this site. I added several fields (i.e. First Name, Last Name, City, State, Zip - as text and list fields). I set these to show on user registration form and to display publicly. I came back about a day later and changed the display settings on User Account to hide the labels and to change the display order. I also hid one of the fields completely on User Account. I opened a new browser and navigated to the user account for a random user - the labels still appear and the order has not been updated. I cleared cache - no difference. I ran cron - no difference. I subsequently updated a few modules and had to run update.php - no difference.
Any suggestions?
Answer: Are you sure you edited the right viewmode? Have a look at the viewmodes which are enabled. Probably you moved the fields not on the viewmode "Full Content" (or "Full Profile") but on the "Default" instead. Or maybe the "Full Profile" is not activated?
Comment: Well - I checked the User account check box.  And everything shows on the user profile page - it just isn't updating my changes.  When I go back to /admin/config/people/accounts/display my changes do show there - just not on the actual user account pages.
Comment: AH!  So you pointed me right to the answer!  I had been clicking on the expandable Custom Display Settings and checking the User Account - thinking that would update the user account - silly me!  LOL  So as you insinuated - you must actually click on the User account "button"ish thing to the top right and then make the changes there.
Comment: Right, thats how you configure the different viewmodes :-)


Convert an interval variable to ordinal in SPSS

Question: I am currently conducting a study on reverse mortgages for my master thesis, and I'd like to convert one interval variable into ordinal in order to run a ordinal probit regression analysis.
My interval variable is: "A reverse mortgage is generally a good deal" --> 1-7 Likert scale (where 1 = totally disagree, 4 =neutral, 7 = totally agree).
How can I how transform this variable?
Comment: @ttnphns: "It is you, who decides whether a likert-type rating scale **is** interval". I disagree, it **is** ordinal. Period. However, you may decide to **treat it as interval** which is called making the [assumption of equal intervals](http://www.spss-tutorials.com/assumption-of-equal-intervals/).
Comment: @ttnphns: I insist it's an important distinction. Not making it is adding to the confusion about the nature of measurement levels, making some believe you can turn ordinal variables into interval. "Philosophical discussions" are often useful and sometimes even necessary to clarify what we're *really* talking about.
Comment: Likert items are ordinal, not interval. A scale constructed from multiple Likert items becomes interval by assuming the ordinal components are interval (rendering the scale items able to be added).
Comment: It is you, who decides whether a likert-type rating scale is interval (the liberal decision) or ordinal (the conservative decision). Note also, that ordinal means "unknown true distances between the scale grades". So, because in interval scale you know them, converting interval to ordinal implies amnesia.
Comment: @Glen_b Correct, naturally, but OP seems to want to go the other way.
Comment: Andrea - if you want to treat something as ordinal, you just need to treat the values as ordered categories instead of as values. You don't necessarily need to change the data values themselves.
Comment: For completeness, if you are estimating this using say the `PLUM` command, you don't need to convert the variable to anything in SPSS. If you are using `GENLIN` or `GENLINMIXED`, the variable *level* likely needs to be specified as ordinal. An example would be `VARIABLE LEVEL YourVar (ORDINAL).`
Comment: @Ruben, let us not start philosophical/linguistic discussions. For me, a thing can be "this and not that" but due to the decision of my consciousness. Period. Any _specific_ being is thus an assumption.
Comment: @Ruben, nope. Logical erratum. If I arbitrarily declare "It is A, not B" it doesn't mean I can "turn" A into B, i.e. `A->B`. I can re-decide, which implies `A->nothing->B`, which is different.
Answer: This is unclear.

If your variable is on a 1(1)7 scale already, then it's ordinal already; how you tell SPSS that is a detail beyond the scope of this site. See the Help Center for advice on software-related questions.
If your variable is currently in some other form, then you need to explain what that form is to get advice on how to convert.

I find it hard to imagine how a variable answering the question "A reverse mortgage is generally a good deal" can be on an interval scale, but that's what you need to explain.


How to ignore the automatic page breaks?

Question: I am using Excel Interop to create a report.
I am trying to programatically set the page breaks. I've been successful in doing so by using:
        this.ActiveWorksheet.HPageBreaks.Add(this[row + 1, 9].Range);
        this.ActiveWorksheet.VPageBreaks.Add(this[row + 1, 8].Range);

(the this[row...col] code refers to our base Excel generator but ultimately refers to a range with a given column / row).
When the report generates I can see my manually added page breaks; however the automatic page breaks still show up and they're in the wrong places so ultimately this makes my code useless. I need to make use of only my page breaks and ignore the automatic ones.
Is it possible to do so?
I've tried resetting the page breaks to no avail. I've also tried setting the FitToPagesWide property on the worksheet page setup property with no luck.
Comment: That's very strange. Using the same code as you, Excel set my page breaks as requested and only began the automatic ones beyond the manual ones (i.e. there were no automatic ones inside the ranges covered by the manual ones). What version of Excel are you using? Perhaps seeing some more of your code might help.
Comment: How strange. My code literally shoves data cell by cell into the Excel workbook - nothing special other than setting a ranges values and then I call those lines where necessary.
Answer: I solved the issue by setting
PageSetup.Zoom = false;
before setting FitToPagesWide = 1
It appears that unless you explicitly set zoom to false, the FitToPagesWide/Tall properties are ignored.


Defining global variables in MobileFirst Platform Adapters

Question: Suppose I have a MobileFirst Adapter implementation like this;
var count = 0;
function doStuff() {

}

Is the count value the same throughout the MobileFirst server (and other client apps)? Or are they maintained per client (i.e safe to use)?
Answer: Variables defined in an adapter are not available in/shareable with other  adapters.
If you'd like to share this variable, what you can do is send the data to another adapter via an action called "adapter mashup". This is explained in the following tutorial: Advanced adapter usage and mashup. This is not ideal for all cases, so make sure it fits yours.
Comment: So it is safe to store client specific data. Thanks Idan Adar.


Integral of $\cos^2(2x+1)$

Question: I'm having trouble with how I go about integrating the following equation:
$\int_0^1 \cos^2(2x+1) \,dx,$
I am familiar with the addition formula
$ \cos(x+a)= cos(x)cos(a)-sin(x)sin(a)$
However I'm not sure how this works with regards to $\cos^2(x+a)$
My question is, what is the integral of the above function, and how do I work this out?
Comment: Try starting with a trig identity for half-angles.  There is one that expresses \cos^2(2x)\ in terms of cos(x).
Answer: HINT
Substitue $2x+1=t$, and use the following Lemma.
$\cos^2(t)=\frac{1+\cos 2t}{2}$.
Using this, we get that the value of the integral is $\frac{4-\sin 2 +\sin 6}{8}$.
I think you can find the solution from here.
Answer: We have that
$$\int\cos^2x\,dx=\frac12\int\left(\cos 2x+1\right)dx=\frac12\left(\frac12\sin 2x+x\right) +C$$
Now use this after you substitute $\;u:=2x+1\;$ in you integral
Answer: $$\int\cos^2(2x+1)\space\text{d}x=$$

Use $\cos^2(x)=\frac{\cos(2x)+1}{2}$:

$$\int\frac{\cos(2(2x+1))+1}{2}\space\text{d}x=\frac{1}{2}\int\left[\cos(4x+2)+1\right]\space\text{d}x=$$
$$\frac{1}{2}\left[\int\cos(4x+2)\space\text{d}x+\int1\space\text{d}x\right]=\frac{1}{2}\left[\int\cos(4x+2)\space\text{d}x+x\right]=$$

Substitute $u=4x+2$ and $\text{d}u=4\space\text{d}x$:

$$\frac{1}{2}\left[\frac{1}{4}\int\cos(u)\space\text{d}u+x\right]=\frac{1}{2}\left[\frac{\sin(u)}{4}+x\right]+\text{C}=\frac{1}{2}\left[\frac{\sin(4x+2)}{4}+x\right]+\text{C}$$

Integral of $\cos^2(2x+1)$


This is regarding a song from Indian music

Question: I'm from india...and I was listening to a song which starts in F major scale with chords like F, Csus4, Fm and C#... later on some instrumental part is played  and they used chords like G D A#(here I think the scale is changed)...and again the pitch changes and at the ending the song ends with the chords A and E...
Can anyone tell me what music concept they have used here....I'm wondering is this a modal interchange or something??!
Please answer...
Thank you
Link to the song is http://kannadamasti.com/mp3/files/A%20to%20Z/G/Gaalipata/Kavithe%20Kavithe.mp3
Comment: Can you add to your question?  You are from India but were you listening to Indian Classical music?  Chords are usually not part of Indian music.  There is no Harmony theory in Indian classical music as it is highly improvisational.  Modern Indian pop and movie music merges western music with Indian ideas.  This is sort of a hybrid.  Or, are you asking about western music from an Indian's point of view?  Please clarify, as I find this interesting.
Comment: Hello mr ggcg....Actually I never mentioned about the classical music In my question...this song was sung by a Carnatic singer Vijay Prakash in Kannada language...the song starts in F major...but it has some off chords as well as change of notes( from F to G major, Dmajor, then A major E major) and all...so I wanted to know under what term of western musicians can understand this concept...Thank you
Comment: Without hearing the song it's hard to say.  Songs do modulate (change key), but also, if the melody does not fit into a Western scale the supporting roles need to adjust to best fit what is happening.  Like I said a lot of modern music from the East is a hybrid of Eastern and Western ideas.  There may not be a term that describes this.  Please give me the name of the song.  I just looked him up and it appears to be a sort of classical - modern fusion.  I've seen this before with Jazz - Indian Classical fusion, Dave Holland and Zakir Hussien.  You can't put this a western box.
Comment: Quite frankly the "chords" behind the melody act as drone notes in classical Indian music, but just change (the Western component).  I've heard this type of fusion.  The Western rules typically aren't being followed but it sounds nice.
Comment: Hey please listen to the song and let me know the concept behind it....Song name: KAVITHE KAVITHE...Listen it using the following link...http://kannadamasti.com/mp3/files/A%20to%20Z/G/Gaalipata/Kavithe%20Kavithe.mp3
Comment: Please reply sir
Answer: I am going to attempt to turn some of our conversation into an answer.
In short, using chords that are not in the key of a song is (or can be) modulation as b3ko pointed out.  But this, to me, is a specific device of western music.  You are referring to a form of eastern music, Carnatic, from south India.  The ragas of India do not all map easily to one of the diatonic scales of western music.  In western music harmony can be achieved by using three distinct chords that are contained in the scale I, IV, and V (and V7).  This doesn't mean that there are only three chords in the key, but that one can develop a 3 and 4 voice harmony using just these three chords.  The standard treatment of including multiple voices with the same rhythm as the melody is called homophonic harmony.  For this to be possible the melody needs to be structured and predictable.  Indian music is highly improvisational and the improvised melodies using ragas take precedence over any other aspect of musical expression (based on my experience).  Rhythm is important too but there is no "orchestration" in Indian music.  The main instrumentalist (or vocalist) explores the melodic and rhythmic terrain using raga and rhythms as they see fit.  In classical (or traditional) Indian music (and Carnatic music is quite old) the melodic support (harmony for lack of a better word) is achieved purely using drone notes, no actual harmony in the western sense takes place.
While modulation is a viable explanation for what you are describing, that could be seen as an example of Ethnocentrism (no offense).  Using western music theory to draw a conclusion about Indian music attributes.
Based on what I've said about the use of chords that are in the scale and the fact that the ragas do not necessarily line up with western diatonic modes the question may not be fair at all.
I would ask you to do the following:
(1) Get the exact raga being used in the song you are listening to
(2) find the notes on a piano or guitar if possible (the western equivalent)
(3) first see if the chords you are describing actually use notes from the raga (If they do then they are actually in the raga and hence harmonically consistent with that raga, hence there is no "modulation" relative to this scale)
(4) if they do not fit in the raga ask yourself if there is a change in raga used that correlates with the change in chords used (maybe this is an Indian version of modulation), or ask yourself if the scale simply does not fit on the piano.  In this case there may be no "western music theory" explanation for what is happening.  We can get trapped into thinking that western music theory simply IS music theory but this is a horrible example of Ethnocentrism.
Many ragas can be mapped to notes on the chromatic scale but not the diatonic.  Turkish music uses quarter tones in their scales and some Indian Ragas may as well.  If this occurs then you cannot describe harmony using classic (church based) homophonic voicing.  That whole paradigm goes out the window!  You will not find quarter tones on a piano.
The rules of harmonization in western music are derived in part from choosing notes from the same scale to harmonize a melody.  So I would say that if the chords are in the raga there is no modulation.  We do sometimes add out of key notes for texture but in western music this is done on occasion.  If you judge a raga by comparing it to a diatonic mode you may conclude that the melody is "always out of key".  But again this is an example of ethnocentrism.
In the case of Indian - Jazz, or Indian - western fusion there may be no theoretical basis for the choice, just that some chords that are not offensive are chosen to complement the vocalist.  I found your question interesting and I hope my explanations were helpful (or at least interesting).
Answer: perhaps Modulation.

In music, modulation is most commonly the act or process of changing from one key (tonic, or tonal center) to another. This may or may not be accompanied by a change in key signature. Modulations articulate or create the structure or form of many pieces, as well as add interest.


Windows XP shows low disk space - WinDirStat shows 50GB  entry

Question: We run 12 Dell Optiplex 755 desktop computers. All of them have the exact same hardware and softawre, configured exactly the same. As such, they are all:

running Windows XP
on the same network
denied access to the internet
running with Windows updates up to as recently as November 2011
running with virus definitions up to as recently as November 2011

One computer today reported that it was running low on disk space - indeed it reported that it had less than 6GB remaining of an 80GB drive. All of the other computers are sitting in the realm of 64 GB free on their hard drives.
I ran a check through the file system and could only account for maybe 6-7 GB on the file system, so I ran WinDirStat and it reported that there was a 50 GB block of data labled as "Unknown".
I did my research and did the following things:

Ran WinDirStat as an administrator, so the app had access to everything
I checked System Restore - It is configured to only use up to 9GB for it's restore points.
The Volume Shadow Copy service is not running, and is set to be manually run.
Chkdsk completed with no errors.

The only difference between this computer and the rest in production is that this machine was recently one of two that were deployed (several months ago) to replace a couple that failed for unrelated reasons. The other computer has not exhibited any symptoms.
We cannot figure out what this massive inaccessible block of hard drive space is, and we would like it back. Any help would be greatly appreciated.
Comment: Has the computer ever been connected to the internet? If so, it might be worth checking for a root kit that might be hiding files on the file system.
Comment: So there's no file in the filesystem, but 50GB of disk space is somehow occupied? Is the partition table intact?
Answer: As I read this 3 obvious causes come to mind:

root-kit: You're best bet is to boot from clean media (like a Linux live-cd) and scan the disk from there using one of the online virusscanners. Even if the scanner doesn't see anything suspicious you might see some very large files or weirdly named folders on the disk that would otherwise be invisible from the infected system.
Some sort of disk-corruption that chkdsk misses. Did you ran chkdsk during boot instead of on the online file-system already ? If not try that first. (Run chkdsk c: /X from a cmd prompt to force it into a boot-time chkdsk.) If that is clean too a disk-corruption issue seems unlikely.
Some sort of hidden file (like an ADS stream) that got completely out of hand. Try clearing the Internet Explorer cache. This is full of ADS streams that are completely invisible and sometimes get 'run away'. There is a tools to hunt ADS files down in the SysInternals Suite. You can give that a try too.
Answer: Check your System32 folder for junk content. In particular, look for files that have been copied from the root of other drives.
In my situation, there are at least two drives that have had content copied off their root system to my System32 folder.
Using WinDirStat to check after deleting folders that I KNOW shouldn't be there, I found the size of "unknown" reduced.
If anyone can help figure out which of these files shouldn't be there, it'll help my clean up efforts!
I have posted this issue to Microsoft support at http://social.technet.microsoft.com/Forums/systemcenter/en-US/877b155a-9c66-4aa6-9c64-9efc2e787978/junk-content-in-system32?forum=w8itprogeneral


How to change the text format of the body field of 200 nodes at once?

Question: I need to change the Text format of the body field of 200 node of the "flats" content type.
I guess I can do it in the database but I don't know where to look.
Comment: drupal 7. Right now I will try: `update field_data_body set body_format =REPLACE(body_format, 'plain_text', 'full_html');`
Comment: Yeah that's how I'd do it too, remember to clear the caches after you're done so the changes get picked up. Maybe add a `WHERE entity_type = 'node' AND bundle = 'flats'` so you don't update it for the wrong content type
Comment: Is this for Drupal 6 or 7?
Answer: The query you suggested is great but if you want to make sure you're only including body fields from the content type you want to update you need to extend it slightly:
UPDATE field_data_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'

You'll also need to run the same query for the field_revision_body table or nothing will happen:
UPDATE field_revision_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'


Converting to DNF. Demorgans then moved brackets. Correct/incorrect?

Question: Disjunction normal form (DNF) consists of disjunctions of conjunctions (if I understand correctly). Ex. $(p \land q) \lor (p \land r \land s)$
I am facing this problem: $(t \implies \neg s) \land \neg t$
I have to convert to DNF.
This is my solution:
$\neg t \lor (\neg s \land \neg t)$
What I basically did was get rid of the implication sign using Demorgan's Law. Then, I moved the brackets. That's it.
Is this correct or incorrect?
Comment: Pleas use MathJax to format your mathematical expressions. See [here for a guide](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: First some corrections to your description / terminology:
Disjunctive normal form. A formula is in DNF if it is a disjunction of conjunctions of literals; here a literal is a propositional atom, or the negation of a propositional atom.
Material implication is the name of the rule that $A\to B$ is equivalent to $\lnot A\lor B$.
De Morgan's laws are the following laws:
\begin{align}
\lnot(A\land B)\equiv \lnot A\lor\lnot B\\
\lnot(A\lor B)\equiv \lnot A\land\lnot B
\end{align}
You don't need them in this exercise, but they are very useful in getting to normal forms, since they can bring an "outside" negation to the "inside" of a conjunction / disjunction. They have nothing to do with implications, however.

Now your exercise:
Your formula is equivalent by material implication to:
$$(t\to \lnot s)\land \lnot t\quad\equiv\quad(\lnot t\lor\lnot s)\land \lnot t$$  Simply moving the brackets around to get something resembling an answer is not allowed! You could make a truth table to see that the following formulas are not equivalent:
$$
p\land (q\lor r)\quad\text{ and }\quad (p\land q)\lor r
$$
What you have to do, is use the distributivity laws:
\begin{align}
(A\lor B)\land C\equiv(A\land C)\lor (B\land C)\\
(A\land B)\lor C\equiv(A\lor C)\land (B\lor C)
\end{align}
Using these laws we can see that: $$(\lnot t\lor\lnot s)\land\lnot t\quad\equiv\quad(\lnot t\land\lnot t)\lor(\lnot s\land \lnot t).$$
Comment: not sure what i would do without this community. being brand new to the world of logic, i greatly appreciate your help!


How do I report a 95% CI in a one sample t test?

Question: How do I report a negative 95% CI in a one sample t test? What does this mean?
Comment: Maybe this can help: http://stats.stackexchange.com/questions/167972/why-is-there-a-need-for-a-sampling-distribution-to-find-confidence-intervals/167998#167998
Answer: A one-sample $t$-test is a test of whether your observed mean is equal to some pre-specified null value (usually $0$).  That is equivalent to seeing if the 95% CI for your observed mean includes the null value.  They want you to report a 95% CI for the mean of your data.
Comment: (+1) except for the last sentence. The CI is for the true mean, not for the mean of the data.


How do I display username in a custom block?

Question: Am new to Drupal so this is a very fundemental question.
How do I display the current username ? In a custom Block? I beleive is the $user->name session variable.
Do I create a Custom Block Type?  If so how do I reference the username?
Do I edit files on the file system?  If so which files?
Do I create new files? If so where?
In other web frameworks the templating engine allows server script tags... ex.. like
<%= username %>
Ive tried putting
$user->name  and {{app.user}}
into the custom block editor but nope, I've learned it's a WYSISYG with no way to render
All I want to do is display a user name in a block I can add a label too.
Any help appriciated.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/90093/discussion-on-question-by-kickaha-how-do-i-display-username-in-a-custom-block).
Answer: You can do this in sevaral ways, one of this could be use a preprocess function. In your custom module in the .module file or your custom theme in the .theme file (recommended) write this:
/**
 * Implements hook_preprocess_HOOK().
 */
function [my_module_or_theme]_preprocess_block(&$variables) {
  $variables['username'] = \Drupal::currentUser()->getUsername();
}

and then in your template suggestions of block.twig.html print the variable {{ username }}
Comment: This pointer looks very helpful, thankyou. It points out how to do the username lookup programmatically which as a beginner is an important step to really understanding Drupal. I'll come back to accept once I'm up successfully and running with a custom module / theme.
Comment: Not exactly the answer I needed, but close enough to have helped.  Thanks.
Answer: To answer my question I created a custom module with a block.
That needed a folder for the module, a .info.yml file and a file for the block.
1) A folder for the module modules/custom/my_show_user
2) The file modules/custom/my_show_user/my_show_user.info.yml
name: Show User Module
description: Displays the logged in user name in a block.
package: Custom

type: module
core: 8.x

dependencies:
  - drupal:block

php: 5.6

3) The file modules/custom/my_show_user/src/Plugin/Block/UserNameBlock.php
<?php

namespace Drupal\my_show_user\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'User Name' Block.
 *
 * @Block(
 *   id = "my_show_user",
 *   admin_label = @Translation("Show User"),
 *   category = @Translation("Show User"),
 * )
 */

class UserNameBlock extends BlockBase {

    /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t(\Drupal::currentUser()->getUsername()),
    );
  }

}

That's it done. .
fyi, any time a change is made clear the cache to see it
Manage>Configuration>Performance>Clear All Caches
In Structure > Place Block a block called UserNameBlock can now be selected and it displays the current logged in user.
Adding the dependency - drupal:block  and keeping the commented annotations @Block and @inheritdoc was key.
the line
'#markup' => $this->t('any html string can go here ' .
                        \Drupal::currentUser()->getUsername() .
                        ' concatenated with data in the template, in this case username' ),
is the entry point for your 'custom template'.
Answer: public function build() {
return [
'#markup' => $this->t(\Drupal::currentUser()->getUsername()),
];
}


Power BI: excluding a visual from a slicer

Question: I have two different visuals on the same page of a Power BI doc, but one is being affected by the page slicer while the other one isn't. I have other visuals on the same tab that I want to slice by the slicer, so I want to select which visuals are affected by the page-level slicer.
Visual that isn't being affected by slicer
Visual that IS being affected by slicer
I followed the tab for "Control which page visuals are affected by slicers" on this site but it's not working. I want the second visual series to look like the first, how do I do it?
Answer: On the Power BI Desktop menu, select the Format menu under Visual Tools, and then select Edit interactions.
You need to have the slicer selected. Only then you see the according Filter on/off symbols next to the visuals. When the visuals are close to each other it's sometimes hard to tell which filter switch belongs to which visual. Try pulling them temporarily apart.
Comment: I realized that the slicer itself needed to be selected, rather than selecting the visual I wanted unfiltered. It worked!