String literal reference class

Question: In C++1y, can I have a reference class that binds to a string literal but not to char* or char[]& or similar?
class LitRf{
  const char* data_;
  size_t size_;
public:
  LitRf(const char* /*?*/ s) : data_{s},size_{sizeof(s)} { /*?*/ }
};

Comment: I know. You cannot change that. Constness can always be added, but not removed. You can only add a non-const overload, but `=delete` it.
Comment: The best I can come up with is to provide a templated overload that static_asserts, or use the explicit keyword.
Comment: @Borgleader But i don't think there is a way to distinguish between a string literal and a const char array.
Comment: @Borgleader How would you `static_assert` that something is a string literal? And how could `explicit` help here? Actually, if you can `static_assert` that something is a string literal, you can also use the same condition with SFINAE to control overload resolution not to bind to the function in the first place.
Comment: @Borgleader Please share it.
Comment: I guess the best you can do is to use `const char (&s)[N]` (with `template`) as the parameter type. But it also binds to any const char array other than a string literal.
Comment: @HolyBlackCat [Well it sort of does](http://coliru.stacked-crooked.com/a/e8ea43728651593c), like I said "the best i can come up with" or i should have said closest. I dont think what OP wants/needs is doable 100%.
Comment: Demo code for my last comment: http://ideone.com/d9olzv
Comment: @Borgleader None of your test calls is called with a string literal. They both use variables, not literals. I understand the question that exactly that is what should be probihited...
Comment: @leemes your solution also binds to non-const char arrays.
Comment: Did you really mean `sizeof(s)`? Because that's 1 in your case... You probably meant `strlen(s)` or `sizeof(s) - 1` if `s` is an array. Or `sizeof(s)` even in that case? Note the terminating zero, which is included in the array size, but not in the string size (strlen).
Comment: @leemes `sizeof` is usually 4 (32 bit archs, CHAR_BIT==8) or 8 (64 bit archs) for a pointer, or the storage size (including the terminating 0) for a literal or array. I meant for my `size_` to store the storage size (exactly like in your answer), but subtracting or not subtracting 1 from the size bears little relevance to the question. ;-)
Comment: Yeah, I meant 4 of course ;)
Answer: C++11 removed the only formal way to detect a string literal as such, namely via its implicit conversion to pointer to non-const.
Anyway using the little trick one had to employ a macro.
In C++11 and later the best you can do is to establish a strong convention that an array of const character type is a literal.
I.e., with your example,
class LitRf
{
private:
    const char* data_;
    Sz size_;

    template< size_t n >
    LitRf( char (&)[n] ) = delete;

public:
    template< size_t n >
    LitRf( char const (&s)[n] )
        : data_{s}, size_{sizeof(s) - 1}
    {}
};

Note the use of size_t instead of a possibly signed type Sz. This ensure that the code will compile with g++. Unfortunately that compiler, or older versions of it, has a bug where it's quite insistent on size_t, or else it refuses to accept the code.
Comment: Thanks. `char const []` ~ `string literal` is a reasonable compromise. Unfortunately, this will also initialize from a non-const char array. (Never mind the `Sz`. I didn't know it was anything -- I use it as a `typedef` for `std::size_t` in my namespace)
Comment: But you can't differentiate between an array of `const char` and a `const` array of `char`
Comment: Why `sizeof(s) - 1`? I know, the terminating 0, but OP didn't subtract that originally.
Comment: Ah, forget it - I guess OP didn't mean to do `sizeof(s)` because that's 1 in his case - he probably meant `strlen` which in turn would indeed match your code.
Comment: Added an inaccessible and deleted constructor to prevent construction from array of non-`const` `char`.
Answer: I guess the best you can do is to use const char (&s)[N] (with template<size_t N>) as the parameter type. But it also binds to any const char array other than a string literal.
Add a deleted non-const char array constructor to prohibit calling it with a non-const array.
class LitRf
{
    const char* data_;
    Sz size_;
public:
    template<size_t N>
    LitRf(char const (&s)[N])
        : data_{s}, size_{N}
    {}

    template<size_t N>
    LitRf(char (&s)[N]) = delete;
};

Other than that, you can use a macro wrapper, which (when the constructor is never used without it) makes it only possible to construct an object from a literal, not even via a variable.
#define MakeLitRf(s) LitRf(s "")

The idea is to concatenate two string literals, of which the second one is just an empty string. This is only possible if the first is also a string literal; putting a variable there is a syntax error. After macro expansion, the compiler sees something like LitRf("foo" "") which is equivalent to LitRf("foo"). Some examples:
auto x = MakeLitRf("foo");  // works

const char *foo = "foo";
auto x = MakeLitRf(foo);    // fails

auto x = LitRf(foo);        // works, but we want it to fail...

In the last case, the user unintentionally (or intentionally?) didn't use the macro, making our work worthless. To make it fail too, add a hidden parameter to the constructor, which is required to be added when called directly (and in the macro's definition, of course):
class LitRf
{
    const char* data_;
    Sz size_;
public:
    // Called by the macro MakeLitRf. Unlikely to be called directly unless the user knows what he's doing.
    LitRf(const char *s, void *)
        : data_{s}, size_{N}
    {}

    // Called without macro! Throw a compiler error, explaining what's wrong.
    LitRf(const char *s)
    {
        static_assert(false, "Please use the macro `MakeLitRf` with a string literal to construct a `LitRf`.");
    }
};

#define MakeLitRf(s) LitRf(s "", nullptr)

Answer: class LitRf{
  const char* data_;
  Sz size_;
public:
  LitRf(const char* /*?*/ s) : data_{s},size_{sizeof(s)} { /*?*/ }
  LitRf(char*) = delete;
};

String literal reference class


items of listwidgets in pyqt4 doesn't work properly

Question: <code>    self.pushButton.clicked.connect(self.search)

def search(self):
    import subprocess
    keyword = str(unicode(self.lineEdit.text()))
    subprocess.call(["some command"])
    video_list = []
    self.listWidget.clear()
    video_ret = parse_vid(video_list)
    self.listWidget.addItems(video_ret)
    self.listWidget.itemDoubleClicked.connect(self.surf)

#######################################################################
def surf(self):
    print "hello"
</code>
This code work fine for first time. But if I click pushbutton for the second time item click in listwidget gives me two execution of surf method. If I click pushbutton third time item click in listwidget execute surf method three time. Can any one help me with this weird problem??
Answer: A signal can be connected to multiple slots, in your case whenever you use the search function you are adding a new slot, it is better to add it once.
<code>    self.listWidget.itemDoubleClicked.connect(self.surf)
    self.pushButton.clicked.connect(self.search)

def search(self):
    import subprocess
    keyword = str(unicode(self.lineEdit.text()))
    subprocess.call(["some command"])
    video_list = []
    self.listWidget.clear()
    video_ret = parse_vid(video_list)
    self.listWidget.addItems(video_ret)

#######################################################################
def surf(self):
    print("hello")
</code>


Utilizar boas práticas ou a forma correta de se armazenar um ID

Question: Atualmente quando preciso alterar algum dado de clientes, armazeno o ID em um input hidden, mas isso fica visível caso você inspecione elemento dando a liberdade para alguém que tenha mais experiência manipular o sistema.
Existe alguma forma correta de se fazer isso? Alguma boa prática?
Comment: É o seu backend que deve decidir o que é válido. Tudo no front está sujeito a alteração. Se o cliente consegue ver o ID, alterar e passar outro ID como se fosse "válido" pro backend, então seu sistema tem falhas graves.
Answer: Não fica muito visível. Fica suficientemente visível.
Se o seu sistema permite que algo errado seja feito só porque alguém sabe qual é o ID, então seus sistema é muito falho. Conserte ele, não tente inventar proteções artificiais em sentido.
Está errado qualquer sistema que não valide cada mínima ação do usuário antes de tomar uma decisão e uma ação que mude estado no sistema. E adivinhe? Uns 99% dos sistemas permitem usuários fazer coisas não esperadas e comprometer em algum grau o que não poderia fazer.
As pessoas precisam aprender desenvolver software do jeito correto e esse jeito nunca é pegando uma informação aqui ou ali. É necessário método científico, aprendizado estruturado, entendimento profundo de toda a base do que está fazendo e saber qual é seu contexto, por isso nunca procure por boas práticas.
Boas práticas servem como alerta para algo que alguém já pensou sobre o assunto, não como guia definitivo do que fazer. A maioria tem falhas e não foco no seu contexto.
Tudo o que vem de fora do sistema, principalmente as que podem ser acionadas por um usuário de forma legítima ou não deve ser validada. Só deve aceitar o que for possível. Um dos erros que se comete é tentar impedir o errado. Você nunca saberá tudo o que pode ser errado. Então proibia tudo e aceite só aquilo que é aceitável naquele contexto.
A pessoa pode ver determinada informação se passar o ID? Ok, então mande pra ela. Se ela não puder não mande. Se pode em dada circunstância, se pode se ela for uma pessoas com uma determinada credencial, ok, então verifique se atende os critérios antes de mandar. Isso se torna ainda mais importante se ela puder mudar o dado.
Se o dado for mudado, será que precisa de autorização extra de alguém? Em alguns casos precisa, então faça um passo extra. De qualquer forma registre tudo oque foi alterado, ou mesmo acessado em boa parte dos casos.
Há situações que um sistema de alerta é um meio termo entre só registrar o que o foi feito e pedir para alguém autorizar a ação. Existe um mecanismo chamado alçada e é um termo que quase nenhum programador usa, um enorme erro.

al·ça·da
substantivo feminino

Limite dos poderes concedidos.

Jurisdição, supremacia.

[Figurado]  Esfera de .ação.

Apelação.

Tribunal ambulante que administrava justiça e alçava agravos.

"alçada", in Dicionário Priberam da Língua Portuguesa [em linha],
2008-2013, https://www.priberam.pt/dlpo/al%C3%A7ada [consultado em
28-07-2018].

Usar validação via cliente é suficiente?
Coloquei no GitHub para referência futura.


Using GTK/GIO async reads in Python

Question: I'm trying to do asynchronous reads with GTK/GIO in Python, but while the read itself works okay (in that the callback is called only after the wanted number of bytes has been input), I haven't been able to find any way to actually access the result.
Given this code:
from gi.repository import Gtk, GLib, Gio
import sys

def callback(stream, task):
        result = stream.read_all_finish(task)
        print(stream, task, task.get_user_data(), task.get_task_data(), result, buf)
        Gtk.main_quit()

buf = bytearray(4)

stream = Gio.UnixInputStream.new(sys.stdin.fileno(), False)
stream.read_all_async(buf, GLib.PRIORITY_DEFAULT, None, callback)

Gtk.main()

When run, it'll wait until at least 4 bytes have been input, so a single a<return> will not cause it to exit, but a second one will. The print will result in something like:
<Gio.UnixInputStream object at 0x7f1045dc3708 (GUnixInputStream at 0x1b8c160)> <Gio.Task object at 0x7f1045dc3bd0 (GTask at 0x1b8e860)> 28890912 28207104 (True, bytes_read=4) bytearray(b'\x00\x00\x00\x00')

In other words...

get_user_data() and get_task_data() seem to be of no help, since they return integers (whose meaning I have no clue about)
The return value from read_all_finish() seems to be of no help, since it's just a success/fail bool plus a bytes_read integer field
The buffer that we gave to read_all_async() seems to be of no help, since it remains unchanged, even though one might expect it to hold the result of the read...

I've also tried...

Inspecting the same things before the read_all_finish() call, just in case that call did something like clear the buffer for some reason - no dice, that gives the same result
Using array('b', [0]*4) instead of the bytearray - that gives the same effect as well
Using an integer count in place of buf (because it seems that an older version of the API worked that way) - that just results in TypeError: Must be sequence, not int
Using a file instead of stdin - no change
Using read_async()/read_finish() instead - no change
...and probably a few more things I can't even remember anymore

At this point, I'm really at my wit's end here - Am I just doing something horribly wrong, or is GIO's python binding horribly broken with respect to the async methods?
Answer: Despite not complaining about a standard python bytearray/array, it won't actually work with those; You need to use a GLib.ByteArray for it to work.
In other words, this'll work:
from gi.repository import Gtk, GLib, Gio
import sys

def callback(stream, task):
        result = stream.read_all_finish(task)
        print(buf)
        Gtk.main_quit()

buf = GLib.ByteArray.new_take(bytes(4))

stream = Gio.UnixInputStream.new(sys.stdin.fileno(), False)
stream.read_all_async(buf, GLib.PRIORITY_DEFAULT, None, callback)

Gtk.main()

Using GTK/GIO async reads in Python


Pulling xml data in Flash with a button

Question: I have been failing to do a thing with Flash actionscript2.0; Here is the problem-
My xml file name is: sea.xml
On my fla file, there is a button named: do; and a movieClip named: loader;
What I am trying to do is- load xml only when the button is pressed. So I tried this-
myXML:XML = new XML;

do.onRelease = function(){
myXML.load("sea.xml");
}

myXML.onLoad = function(success){
if (success){
loadMovie(myXML.firstChild.childNodes[00.firstChild.nodeValue, loader);
}

BUT it's not working. How can I get what I want?
Answer: myXML:XML = new XML;

do.onRelease = function(){
myXML.load("sea.xml");
}

myXML.onLoad = function(success){
if (success){
trace(myXML.toString());
}

and post here the output please.

Pulling xml data in Flash with a button


Two-part model ordinal data

Question: A response scale has the categories (strongly agree, midly agree, midly disagree, strongly disagree, do not know). A two-part model uses a logistic regression model for the probability of a DK (don't know) response and a separate ordinal model per the ordered categories conditional on response in one of those categoeries.
I'd like to fit these two part simultaneously but I'm stucked.
I think of it as an Hurdle model for the Poisson situation, where the 0 process is different than the counting process and there's no mixture (so no Zero inflation).
I wonder if it exists a way to deal with situation in R.
Someone would told me to treat DK response either as missing values or neutral values (so put them in the central order). But I'd like to use a model like the Hurdle one for counting data. So a logit model (DK versus notDK) and a Proportional Odds Model per the ordinal part.
I've looked for some literature on the argument but I have found nothing in particular. Any suggestion? Does it make sense, anyway, as approach?
Answer: It is very difficult to know how to position or analyze the "don't know" answer.  It is often best to not change the definition of the variable by creating a new category for it, but rather to use multiple imputation to multiply impute values after setting "don't know"s to missing.  The multiple imputation model would be a richer model that would include variables you don't even want in the outcome model.  This would preserve the meaning of the data, while properly penalizing you for not knowing some of the values.
Comment: I would hazard against setting "don't knows" to missing and imputing them, as the participant is telling you something: They don't know. This could be because they are uncomfortable about answering, don't have enough information, or feel neutral. But the data should not be replaced by imputations, in my opinion. This is especially because the data are certainly not missing with any randomness; the "don't knows" just represent a different psychological process than the other four possible answers.
Comment: I see your point, you're telling me to analyze them as missing values and the use multiple imputation. This could be a way but I'm more interested in a so called partially ordered model where we have two procesess (one DK versus NOTDk) and the other process I'd like to model with a POM (Partial Odds Model).
Comment: I think that this is an unordered model with respect to "don't know" unless you make an assumption.  But you might have informative missingness that makes "don't know" effectively steal information that you don't want to include in your interpretation of the final result.  Worth more thought at least.
Comment: It is possible that don't knows are informative, but if not, multiple imputation is the way to go IMHO.
Answer: I am finding in my reading about hurdle models is that they may not be as simultaneous as they seem to me, despite being done in one R command. (See my question recently posted here on CV.)
I have dealt with this before, and this was my reasoning:
The only way that I would put "don't know" in the middle is that if the measurement tool actually positioned it in the middle of the scale. I don't agree with this measurement style, but I think that participants might interpret "don't know" to be "neutral" if the scale looks like, on the survey that the participant sees:
strongly disagree - mildly disagree - don't know - mildly agree - strongly agree

If this is the case, then I think it would be fair to just do one ordinal model, although I think the problem is with the measurement being confusing to the participant—not necessarily a statistical issue.
However, if the measurement tool placed "don't know" on the outside like I've seen others do, e.g.:
strongly disagree - mildly disagree - mildly agree - strongly agree || don't know

Then I think your two-step approach is totally valid. It is similar to and in the spirit of hurdle models (as far as I know about them—see the above link for evidence that I am still somewhat confused). The only thing I might change is:

Do a multinomial logistic regression, using "don't know" as the reference category and collapsing the two agree values together and the two disagree values together. That way you can predict the odds of people moving from don't know to agree and don't know to disagree. This can be done by recoding strongly/mildly agree into "agree" and recode strongly/mildly disagree into "disagree," then making "don't know" the first level in a factor variable that represents this three-category dependent variable. I've only fit these models in Stan, but it seems pretty straightforward using the multinom function from the nnet package, although I would suggest reading up on it to see if everything matches what you think it is doing.
Do an ordered logistic regression, excluding the cases that are "don't know" from the sample. This can be done by assigning your dependent variable as factor with levels ordered correctly, and then using the clm function from the ordinal package:
model2 <- ordinal::clm(dv ~ iv, data = dat)

This two-step approach is similar to the hurdle model in that you are explicitly modeling two different kinds of processes: First, having no opinion vs. agreeing or disagreeing; Second, level of agreement.
Lastly, if you are interested in trying to predict whether or not people have an opinion—regardless of direction (disagree or agree)—then you should do a logistic regression predicting don't know versus any other response. It depends on what you are interested in at that point.
Answer: Let $\pi_1, \cdots, \pi_J$ denote the probabilities of the ordinal categories [$\pi_1 = P(y=1) = P(y \le 1)$ and $\pi_2 = P(y=2) = P(y \le 2) - P (y \le 1)$] and $\pi_{DK}$ denote the probability of don't know.  We would like to model $\pi_{DK}$ as a logistic regression model and $\pi_1, \cdots, \pi_J$ as a cumulative logistic model subject to the constrain that $\pi_1 + \cdots + \pi_J + \pi_{DK} = 1$.
Usually cumulative logistic models only differ in intercept parameters, but we can allow for a different slope matrix and intercept parameter for the don't know category.  Specifically define
\begin{eqnarray}
\pi_{DK} &=& \frac{\exp\left(\alpha_0 + \beta_{\ast}^{\prime}\boldsymbol{x}\right)}{1+\exp\left(\alpha_0 + \beta_{\ast}^{\prime}\boldsymbol{x}\right)} \\
\pi_1 &=& \frac{\exp\left(\alpha_1 + \beta^{\prime}\boldsymbol{x}\right)}{1+\exp\left(\alpha_1 + \beta^{\prime}\boldsymbol{x}\right)} \\
\pi_j &=& \frac{\exp\left(\alpha_j + \beta^{\prime}\boldsymbol{x}\right)}{1+\exp\left(\alpha_j + \beta^{\prime}\boldsymbol{x}\right)} - \frac{\exp\left(\alpha_{j-1} + \beta^{\prime}\boldsymbol{x}\right)}{1+\exp\left(\alpha_{j-1} + \beta^{\prime}\boldsymbol{x}\right)} \quad \mbox{for} \quad j=2,...,J-1 \\
\pi_J &=& 1 - \pi_{DK} - \sum_{j=1}^{J-1}\pi_{j}
\end{eqnarray}
Next define a multinomial loglikelihood as usual, but with these probabilities.

Two-part model ordinal data


CSS Not being Applied, and Styles showing as blank?

Question: Ive added some CSS to my page via the CSS file.
However when I loadup the page the CSS isnt being applied.
When I look into firebug the CSS styles show as empty, i.e
.logomain img {
}
.logocorn {
}

However when I click on source edit they show ?? i.e
.logomain img {
    width: 40% !important;
    padding-left: 40px !important;
}

.logocorn {
    float: right !important;
}

Any ideas what is happening ?
Edit : The CSS file is shown below :
body {
    color: #7E7171;
    font-family: 'Open Sans',sans-serif;
    font-weight: 300;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
h1 {
    color: #3B3B3B;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 38px;
    font-weight: 700;
    line-height: 50px;
    margin-bottom: 0;
}
h2 {
    color: #3B3B3B;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 28px;
    font-weight: 700;
    line-height: 50px;
}
h3 {
    color: #3B3B3B;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 20px;
    font-weight: 700;
}
h4 {
    color: #7E7171;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: 700;
    line-height: 14px;
}
h5 {
    color: #3B3B3B;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 13px;
    font-weight: 700;
    line-height: 13px;
}
p {
    color: #7E7171;
    font-size: 16px;
    line-height: 25px;
    margin-top: 10px;
}
a {
    text-decoration: none;
    transition: all 0.2s ease-out 0s;
}
code {
    background-color: #F7F4F2;
    color: #7E7171;
    font-size: 14px;
    line-height: 22px;
}
pre {
    background-color: #F7F4F2;
    border: medium none;
    border-radius: 0;
    color: #7E7171;
    font-size: 14px;
    line-height: 22px;
}
blockquote {
    border-left: 5px solid #F7F4F2;
}
blockquote p {
    font-size: 24px;
    line-height: 45px;
    margin-top: 0;
}
input {
    padding: 6px;
}
.arrow-down {
    border-left: 5px solid rgba(0, 0, 0, 0);
    border-right: 5px solid rgba(0, 0, 0, 0);
    border-top: 5px solid #404040;
    height: 0;
    position: absolute;
    right: 48px;
    top: 0;
    width: 0;
}
.social-header.active .arrow-down {
    top: 50px;
}
a:hover {
    color: #333333;
    cursor: pointer;
    text-decoration: none;
}
header ul li {
    display: inline;
}
header {
}
.top-header {
    background-color: #F16252;
    padding-bottom: 14px;
}
.home-template .bottom-header {
    background-color: #404040;
    padding-bottom: 50px;
    padding-top: 50px;
    text-align: center;
}
.home-template h5 {
    color: #FFFFFF;
    font-family: 'Roboto',sans-serif;
    font-size: 40px;
    font-weight: 100;
    line-height: 62px;
    text-align: center;
}
.home-template .bottom-header a {
    display: none;
}
.archive-template .bottom-header {
    background-color: #404040;
    padding-bottom: 50px;
    padding-top: 50px;
    text-align: center;
}
.archive-template h5 {
    color: #FFFFFF;
    font-family: 'Roboto',sans-serif;
    font-size: 40px;
    font-weight: 100;
    line-height: 62px;
    text-align: center;
}
.archive-template .bottom-header a {
    display: none;
}
h1.logo {
    margin-top: 9px;
}
h1.logo a {
    color: #FFFFFF;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 38px;
    font-weight: 700;
    line-height: 50px;
}
h1.post_title a {
    font-size: 22px;
    line-height: 25px;
}
.excerpt {
    font-size: 13px;
}
h1.post_title {
    line-height: 19px;
    margin-bottom: 10px;
    margin-top: 10px;
}
.social-header {
    background-color: #404040;
    color: #FFFFFF;
    height: 50px;
    line-height: 50px;
    margin-top: -50px;
    text-align: right;
    transition: all 0.2s ease-out 0s;
}
.social-header .container {
    position: relative;
}
.social-header.active {
    margin-top: 0;
}
.social-header a {
    color: #FFFFFF;
}
.social-header a:hover {
    color: #3DD765;
}
.social {
    height: 40px;
    margin-top: 25px;
    text-align: right;
}
.social-header ul li {
    padding-left: 20px;
}
.social ul li {
    padding-left: 20px;
}
.social a {
    color: #FFFFFF;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: bold;
    line-height: 30px;
    text-transform: uppercase;
}
.social a:hover {
    color: #333333;
}
.social-icons {
}
.social-icons a {
    padding-left: 20px;
}
.close-social {
    border-left: 3px solid;
    margin-left: 15px;
    padding-left: 15px;
}
.main {
}
.post h1 a {
    color: #333333;
}
.post h1 a:hover {
    color: #333333;
}
.post-template .author-mobile {
    display: none;
}
.author {
    margin-top: 20px;
}
.author ul li {
    text-align: center;
}
.author-image span img {
    border-radius: 100%;
    height: 100px;
    overflow: hidden;
    width: 100px;
}
.author-image span .info {
    border-radius: 100%;
    height: 100px;
    width: 100px;
}
.author-name {
    color: #F16252;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 20px;
    font-weight: 700;
    margin-top: 10px;
    text-transform: uppercase;
}
.post-date {
    color: #7E7171;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: 700;
    line-height: 14px;
    margin-top: 5px;
}
.author-mobile {
    color: #7E7171;
    float: left;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 12px;
    font-weight: 300;
    line-height: 14px;
    margin-top: 5px;
}
.author-mobile img {
    border-radius: 100%;
    height: 30px;
    width: 30px;
}
.author-mobile span {
    color: #F16252;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 12px;
    font-weight: 700;
    line-height: 14px;
}
.author-mobile time {
    color: #7E7171;
    display: block;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 12px;
    font-weight: 700;
    line-height: 14px;
}
.post-template .author-mobile time {
    display: inline;
}
.author-name {
    color: #F16252;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 20px;
    font-weight: 700;
    margin-top: 10px;
    text-transform: uppercase;
}
.post-date {
    color: #7E7171;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: 700;
    line-height: 14px;
    margin-top: 5px;
}
span.tags {
    color: #7E7171;
    display: block;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 12px;
    font-weight: 700;
    height: 27px;
}
span.tags i {
    margin-right: 5px;
}
.post-container a.more {
    background-color: #F16252;
    color: #FFFFFF;
    float: right;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: bold;
    line-height: 19px;
    padding: 10px;
    text-transform: uppercase;
}
.post-container a.more:hover {
    background-color: #3DD765 !important;
    color: #FFFFFF !important;
}
.post-container div.content {
    display: none;
}
p.content {
    margin-top: 50px;
}
.post-container {
    background-color: #FFFFFF;
    margin-top: 70px;
    transition: all 0.2s ease-out 0s;
}
.post-container:hover {
    background-color: #F5F5F5;
}
.post-container:hover .post-bottom {
    border-top: 1px solid #CCCCCC;
}
.post-container:hover article {
    border: medium none;
}
article {
    padding-top: 15px;
}
.post-bottom {
    border-top: 1px solid #EEEEEE;
    bottom: 0;
    padding-bottom: 15px;
    padding-top: 15px;
    position: absolute;
    width: 100%;
}
.post-container article {
    border-bottom: 2px solid #EEEEEE;
    height: 390px;
    position: relative;
}
h1.post_title a:hover {
    color: #F16252;
}
.postimg-slider {
    background-color: #FFFFFF;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    height: 150px;
    position: relative;
}
.loading {
    background-image: url("../images/loading.gif");
}
.postimg-slider ul li {
}
.postimg-slider .prev {
    background-color: #FFFFFF;
    border-radius: 3px;
    display: block;
    font-size: 10px;
    height: 20px;
    padding-left: 5px;
    padding-top: 2px;
    right: 40px;
    width: 20px;
}
.postimg-slider .next {
    background-color: #FFFFFF;
    border-radius: 3px;
    display: block;
    font-size: 10px;
    height: 20px;
    padding-left: 5px;
    padding-top: 2px;
    right: 15px;
    width: 20px;
}
.postimg-slider ul {
    list-style-image: none !important;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.postimg-slider ul {
    width: 100%;
}
.postimg-slider ul li {
    height: 150px;
    margin: 0;
    padding: 0;
    width: 100%;
}
.post .postimg-slider ul li img {
    width: 100%;
}
.rslides {
    position: absolute;
}
.rslides_nav {
    position: absolute;
    top: 15px;
    z-index: 9999;
}
.post {
    padding-bottom: 30px;
}
.post a {
    color: #F16252;
}
.post a:hover {
    color: #3DD765;
}
.paginate {
    margin-bottom: 50px;
    margin-top: 50px;
}
.paginate .older {
    margin-top: 13px;
    text-align: left;
}
.paginate .older a i {
    padding-right: 10px;
}
.paginate .page-nr {
    color: #7E7171;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 40px;
    font-weight: 300;
    text-align: center;
    text-transform: uppercase;
}
.paginate .newer {
    margin-top: 13px;
    text-align: right;
}
.paginate .newer a i {
    padding-left: 10px;
}
.paginate a {
    color: #333333;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: bold;
    line-height: 30px;
    text-transform: uppercase;
}
.paginate a:hover {
    color: #F16252;
}
.paginate a i {
    font-size: 13px;
    line-height: 3px;
}
footer {
    background-color: #404040;
    font-family: "Open Sans";
    font-weight: 400;
    height: 80px;
}
footer p {
    color: #FFFFFF;
    font-size: 12px;
    line-height: 15px;
    margin-top: 18px;
    text-align: center;
}
footer a {
    color: #3DD765;
}
footer a:hover {
    color: #FFFFFF;
}
.post-template .bottom-header {
    background-color: #404040;
    height: 66px;
    padding-top: 0;
    text-align: left;
}
.post-template .bottom-header a {
    color: #FFFFFF;
    font-family: 'Roboto Condensed',sans-serif;
    font-size: 14px;
    font-weight: bold;
    line-height: 66px;
    text-transform: uppercase;
}
.post-template .bottom-header a i {
    margin-right: 10px;
}
.post-template .back:hover {
    color: #F16252;
}
.post-template h5 {
    display: none;
}
.post ul {
    list-style-image: url("img/red.png");
}
.post li {
    color: #7E7171;
    font-family: "Open Sans";
    font-size: 13px;
    line-height: 30px;
    margin-left: 17px;
}
.full img {
    max-width: 100%;
}
.share {
    border-bottom: 1px solid #E0E0E0;
    margin-bottom: 50px;
    margin-top: -50px;
}
.share a {
    color: #FFFFFF;
    text-align: center;
}
.share a:hover {
    color: #333333;
}
.share h3 {
    color: #7E7171;
    font-size: 14px;
    line-height: 62px;
    text-align: center;
    text-transform: uppercase;
}
.share_social {
    height: 40px;
    margin-bottom: 40px;
}
.share span {
}
.share span a {
    background: none repeat scroll 0 0 #F16252;
    border-radius: 3px;
    display: inline-block;
    height: 40px;
    line-height: 39px;
    margin-left: 6px;
    margin-right: 6px;
    text-align: center;
    width: 40px;
}
.share span a:hover {
    background-color: #3DD765;
    color: #FFFFFF;
}
@media (max-width: 410px) {
}
@media (max-width: 455px) {
.social {
    margin-left: -30px;
}
}
@media (max-width: 767px) {
.newer span, .older span {
    display: none;
}
.newer a i, .older a i {
    font-size: 22px;
}
.newer a, .older a {
    font-size: 22px;
}
}
@media (min-width: 768px) {
}
@media (max-width: 992px) {
.post-template .author-mobile {
    display: block;
}
.post-template span.tags {
    clear: both;
    padding-top: 10px;
}
.author {
    display: none;
}
}
@media (min-width: 1200px) {
}
#add_this {
    margin: 0 auto;
    width: 242px;
}
.col-md-9 img:nth-of-type(1) {
    width: 0;
}
.logomain img {
    padding-left: 40px !important;
    width: 40% !important;
}
.logocorn {
    float: right !important;
}

Comment: Please show **both** your HTML and CSS, the problem can be anywhere in either of them.
Comment: The CSS file seems to be in the correct format, see this [jsFiddle](http://jsfiddle.net/FT35a/). Do the other CSS styles get applied to your page? If not, it may seem that the whole CSS file is not being correctly loaded - and that solution requires a lot more information on your environment =)
Comment: Check if any rule is not closed properly (curl braces missing, colon missing, etc)
Comment: I think the css file is cached. Try opening the css file in the browser and refresh a couple of times.
Comment: The source code is showing that the page is returning the css file with the correct class values for CSS (??)
Comment: Can you link to your stylesheet or add it to the question?
Comment: Is the CSS embedded in the head of the HTML file? Or is it in a .css file?
Comment: It's a separate file. I'll upload shortly...and add to question
Answer: The CSS file seems to be in the correct format, see this jsFiddle.
Do the other CSS styles get applied to your page, e.g.
body {
    color: #7E7171;
    font-family: 'Open Sans',sans-serif;
    font-weight: 300;
}

? If not, it may seem that the whole CSS file is not being correctly loaded - and that solution requires a lot more information on your environment =)
Any error messages in the console?
Comment: Nope and if I copy and paste the CSS back into firebug 'edit live source' if works (??)
Answer: Your ending brace for your @media (min-width:1200px) aren't closed correctly.
    @media (min-width: 1200px) {

    #add_this {
        margin: 0 auto;
        width: 242px;
    }
    .col-md-9 img:nth-of-type(1) {
        width: 0;
    }
    .logomain img {
        padding-left: 40px !important;
        width: 40% !important;
    }
    .logocorn {
        float: right !important;
    }

}

You closed the @media before any styles. In your post you have @media (min-width:1200px) { }
Comment: This should be fine as the sample provided shows the correct closing brace.
Comment: In your original post, the enclosing braces are incorrect.
Answer:
first you just check  tag call correctly if u call css as external css,
then check... did close all brackets of css? and semicolon also for each style,
then also check media query brackets closed properly?,
finally run in browser and press Ctrl + F5 for refresh... it will remove cache in old stlyes..
Answer: I'm wondering where you have your class set, is it to a
 which would expand the width of the screen or container or something like a  or an . Try it on the
 if not.
Also, If you are using bootstrap for example you could try the classes .pull-left and .pull-right as they already have good rules associated to them.
Comment: In the end I just used bootstrap .pull-xxx style. Though this is more of a work around, rather then knowing what the actual issue was.


C# - Throw an exception if can't connect to remote server

Question: I am trying to get an exception thrown if the function in my method fails, my code is as follows so far:
 if (sourceFile.Exists)
            // Would be nice to add ticker / spinner, while the file header on the remote server is being read!!
            {
                var request = (HttpWebRequest)WebRequest.Create(@"http://google.com/test.zip");
                request.Method = "HEAD";
                var response = (HttpWebResponse)request.GetResponse();

                if (response.LastModified > sourceFile.LastWriteTime)
                {

                    Download_Click(sender, e);

                    // use response.GetStream() to download the file.
                }

Comment: @ba__friend How can I catch an exception, if no network connectivity is available
Comment: Don't help, it already happens.
Answer: According to the HttpWebRequest docs, a WebException is thrown from GetResponse if the request times out or another error occurs while processing it.
You should be able to catch that in your code.
Answer: try/catch HttpException
http://msdn.microsoft.com/en-us/library/system.web.httpexception.aspx


Running Web.py as an IIS CGI Script

Question: I recently wrote a web.py-based stand alone web service. Due to unforeseen circumstances, the service has to run through IIS. I've heard that it's possible to run web.py as a CGI in IIS, but I'm having trouble setting it up. I can run Python CGI scripts, but I get internal server errors when I try to run the web.py-based script. The error states:
CGI Error

The specified CGI application misbehaved by not returning a complete set of HTTP headers.

For reference, the script is:
import web
urls = (
   '/(.*)','hello'
)
class hello:
    def GET(self,name):
        i = web.input(times=1)
        if not name: name = 'world'
        for c in xrange(init(i.times)): print 'Hello, '+name+'!'
if __name__=="__main__":
    web.run(urls)

Where are the log files for IIS that would have internal server error information?
Do I have to employ a Rewrite ISAPI filter to use web.py on IIS?
Do I need to employ a WSGI-ISAPI bridge to use web.py on IIS?
Has anyone done this before?

This thread mentions using a hacked version of flup to avoid socket creation, which I've done, but to no avail.
Comment: This question on SO may cover what you need: http://stackoverflow.com/questions/5975131/problem-deploying-web-py-script-on-iis7-via-pyisapie
Answer: Here is some info:
http://support.microsoft.com/kb/145661
Here is a suggestion:
http://support.microsoft.com/kb/238788
Here is a bugfix:
http://support.microsoft.com/kb/884764
If you are running IIS7, (you didn't really specify), the last one can probably just be ignored

Running Web.py as an IIS CGI Script


NFS, Quotas & root not liking each other

Question: I have a few CentOS servers i would like to backup nightly.
I have created a NFS server with the following mounts :

/backup/server1
/backup/server2
/backup/server3

On the CentOS servers i have mounted the nfs share as /backup and everything works fine with read and writes.
The issue is that the files sent over NFS are always ending up with root or nobody permissions (if all_root_squash is set).
How can i properly set quotas when my NFS clients all are using the same UID and the same root user?
Comment: That is perfect! with anonuid i can simply map them to my local users and enforce quotas! Thank you so much HBrujin
Answer: In your exports file you can use the anonuid and anongid to explicitly set the uid and gid of the anonymous account.
This option is especially useful in combination with the all_squash option which maps all uids and gids to the anonymous user,  which you can then use to enforce your quota:
/backup/server1       server1(rw,all_squash,anonuid=1001,anongid=1001)
/backup/server2       server2(rw,all_squash,anonuid=1002,anongid=1002)

Comment: That is perfect! with anonuid i can simply map them to my local users and enforce quotas! Thank you so much HBrujin –


In C++, how do I write a 3-dimensional array?

Question: Thanks for looking!
Background
I am building a quadcopter and am placing on each of it's four arms a strip of RGB LEDs which are individually addressable.  There are 6 LEDs per strip.
Further, there are six steps in a sequence to how I wish to toggle the lights so all six lights on the strip don't necessarily toggle at once.
In pseudo code, here is what I am trying to create:
someArray = A group of 4 LED strips {Strip 1: [
    Step 1: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
    . . .,
    Step 6: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
],
. . .,
Strip 4: [
    Step 1: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
    . . .,
    Step 6: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
]};

I am using an Arduino to drive the lights, and the code is in C++ with which I am not very familiar.
What I have tried so far:
Here is the code I have tried so far, but when I compile in the Arduino IDE, I get an error that says "Braces around scalar initializer for type 'int'".
int gpsHoldArr[4][6][6] = {
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
};

What am I missing here?
Intended Usage
Intended use would be something like this:
//iterate each of the 6 sets of RGB values and assign them to the correct (sequential) LED
void toggleLights(int lights[]){
  for(int i = 0; i <= 6; ++i)
  {
    set_color_led(i, lights[i][0], lights[i][1], lights[i][2]);
  }
}

toggleLights(gpsHoldArr[1][0]);//Get the first step of the second arm.

Thanks in advance.
Answer: You wrote the initialization for a 4d array as RGB has 3 components. You probably want to do something like this:
struct rgb {
  int r, g, b;
};

rgb gpsHoldArr[4][6][6] = {
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
};

Or, change your declaration to this:
int gpsHoldArr[4][6][6][3]

Comment: Ahhh--the change of declaration did it.  Thanks Pubby!
Answer: Use a byte and cut the memory usage in half
typedef struct rgb_t {
  byte r;
  byte g;
  byte b;
};

rgb_t gpsHoldArr[4][6][6] = {


phpmyadmin/CSV(Excel) Problems

Question: I have an excel workbook where the .csv file is outputted with quotes with this vba code:
<code> 'Set up Delimiters
DELIMITER = ","
QUOTE = """"

 'Set up file to save, ask user for name
GetFileName = InputBox("Enter Name for semi-colon delimited file: (Do not enter file extension)", "FILENAME")
  'CurrentPath = Application.ActiveWorkbook.Path
 PathtoUse = "C:\Users\David\Desktop\"
 FileNametoUse = PathtoUse & GetFileName & ".csv"

 'Find cells to cycle through
With ActiveSheet.UsedRange
    LastRow = .Cells(.Cells.Count).Row
    LastCol = .Cells(.Cells.Count).Column
End With

 'Assign a handle to next file#
FileNum = FreeFile

 'Open and write to file named above
Open FileNametoUse For Output As #FileNum

 'Cycle through rows and cols
For Each CurrentRow In Range("A1:A" & LastRow)
    With CurrentRow 'Now cycle through each cell in the row
        For Each CurrentCell In Range(.Cells, Cells(.Row, LastCol))
             'If the cell contains Non-Numeric (IsNumeric=False) then put quotes around the info
            If IsNumeric(CurrentCell.Text) = False Then
                CellData = QUOTE & CurrentCell.Text & QUOTE
            Else 'The cell contains numeric, use contents as is
                CellData = CurrentCell.Text
            End If
             'as the code cycles, keep adding each col info to string
            LineOutput = LineOutput & DELIMITER & CellData
        Next CurrentCell

         'Remove the first 2 chars in the line (since the delimiter is put in first)
        LineOutput = Mid(LineOutput, 2)
         'Print the line to the file
        Print #FileNum, LineOutput
          'Clear out the variable
        LineOutput = Empty
    End With
Next CurrentRow

 'Close the file
Close #FileNum
</code>
This outputs the file correctly for example:
<code>"FirstName","Surname","YBC","BTBA","JTE","EnteringAverage","DOB","Game1","Game2","Game3","Game4","Game5","Game6","Game7","Game8","IndividualTotal","Average","TeamTotal"
"David","Passmore","Bowlplex Poole",116016,193,179,"05/08/1994",203,254,211,195,187,184,200,267,1701,212.63,3178
"Callum","Bailey","Bowlplex Poole",016015,185,189,"30/05/1996",175,145,195,117,201,265,221,158,1477,184.63,3178
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
"","","","","","","","","","","","","","","","","",""
</code>
Firstly I want to know how to remove all the blank cells, and secondly when I input this into phpMyAdmin it all works BUT it misses out the first column and it inputs the column names which I don't want, so I want it to input all the first name column and then I want it to miss out the column names.
My server's phpmyadmin version is 2.6.4 (I know its old but I can't do anything about that)
But is also does this on my local server which is version 3.3.9
UPDATE
I've fixed the first column issue by just moving the file one column to the right so that's fixed but the other two problems still exist.
Answer: You could just change your vba here:
<code> 'Set up Delimiters
DELIMITER = ","
QUOTE = """"
</code>
To this:
<code>'Set up Delimiters
DELIMITER = ";"
QUOTE = """"
</code>
Because phpMyAdmin defaults to ; as the separator.
In answser to your second point you could use this vba code to remove blank cells:
<code>Sub MacroNAME()
    ActiveWorkbook.Save
    Rows("1:1").Select
    Selection.Cut
    Sheets("sheetname").Select
    Sheets.Add
    ActiveSheet.Name = "Save"
    ActiveSheet.Paste
    Sheets("sheetname").Select
    Rows("1:1").Select
    Rows("1:1").RowHeight = 14.25
    Selection.Delete Shift:=xlUp
    Cells.Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.ClearContents
    Columns("A:A").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Rows("2:2").RowHeight = 14.25
    **Code Used above here**
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Rows("1:1").RowHeight = 0.1
    Columns("A:A").Select
    Selection.Delete Shift:=xlToLeft
    Sheets("sheetname").Select
    Rows("2:2").Select
    Selection.Insert Shift:=xlDown
    Rows("1:1").RowHeight = 10.5
    Rows("1:1").RowHeight = 14.25
    Sheets("Save").Select
    Selection.Cut
    Sheets("sheetname").Select
    Rows("1:1").Select
    ActiveSheet.Paste
    Application.DisplayAlerts = False
    Sheets("Save").Select
    ActiveWindow.SelectedSheets.Delete
    Application.DisplayAlerts = True
</code>
This will clear the column headings provided they are it the first row.
You can apply this to a button and it should work.

phpmyadmin/CSV(Excel) Problems


httaccess in Wordpress - point to subfolder + redirect to https

Question: The old .htaccess redirects automatically to https protocol :
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

But I saw there is no pointer to the subfolder via htaccess. The ex-developper used this :
[root]index.php
<?php include_once("wordpress/index.php"); ?>

It seems to create several bugs :
on the admin panel side, there is a redirection https://my-site/wp-admin/ to https://my-site/wordpress/wp-admin/ but not on the front-end.
Sometimes on the admin side, there are some redirection like this : https://my-site/wp-admin/... which generates bugs.
So... It´s confusing and I wish to clean this with a simpler way : I would like :

point the domain to the subfolder wordpress and works for front-end and back-end
keep the automatic redirection http to https

I tried this without success :
.htaccess
 <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteCond %{HTTPS} off
     RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
     RewriteCond %{HTTP_HOST} ^(www.)?docpeda.be$
     RewriteRule ^(/)?$ wordpress/index.php [L]
 </IfModule>

I´m sure it´s really easy to do it but I need some helps.
Answer: This is what you should put in the .htaccess file if it's a subfolder, hopefully this will solve your issue (just copy and paste). It will also make the site secure.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^(www.)?docpeda.be$
RewriteCond %{REQUEST_URI} !^/wordpress/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /wordpress/$1
RewriteCond %{HTTP_HOST} ^(www.)?docpeda.be$
RewriteRule ^(/)?$ wordpress/index.php [L]
</IfModule>

Comment: Where is the rule to point to the subfolder /wordpress/ ? I commented the code inside the [root]index.php to be cleaner.
Comment: Sorry but, that does not work in my context, I put your code in [root].htaccess inside `` tag.
Comment: Check my edit please :) Don't add to your old .htaccess file, just rename your old one and create a new one and then just copy and paste mine
Comment: I would like to use ONLY the root .htaccess to do this but your alternative code seems to forget the automatic https redirection.
Comment: Yes, my code should be put in the /.htaccess folder and I've added another bit for the HTTPS (which is an easy fix). Although, if my fixes don't work, you may need to add a .htaccess file into your subsites folder as well.
Comment: `https://docpeda.be/` redirect to `https://docpeda.be/wordpress/` in Firefox and I have a blank page for Chrome. So, now, everything is wrong :/
Comment: Sorry but I did.
Comment: Did you create the .htaccess file in the subfolder?
Comment: Please, can you write the code only for the [root].httacces in one piece to be sure I did  what you´re saying ?
Comment: The .htaccess in the subfolder is mandatory ? Can I simplify with only [root].htaccess ?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187433/discussion-between-ember-and-j-bizmai).


do marginal density functions derived from a joint pdf always integrate to 1 (are they valid pdf's)?

Question: If I have a joint pdf of multiple random variables, say 3 for simplicity, $f_{X,Y,Z}(x,y,z)$, is it true that the marginal density functions derived from that joint probability distribution ( $f_{X}(x)$, $f_{Y}(y)$, $f_{Z}(z)$ ) are not guaranteed to be valid probability density functions (integrate to 1) in all cases. I can see that the pdf condition holds for the marginals when the random variables are independent but not quite sure what happens when we introduce dependence between them.
Comment: By definition, a marginal distribution describes a subset of the random variables and *must* be a valid distribution.  If you do a calculation that violates that condition, then you have erred.
Comment: I just realized that my claim is equivallent to saying that the volume under the joint distribution is not 1. So dumb...
Comment: @Statisticool For closure purposes, you may want to well answer it yourself and accept your own answer :).
Answer: Using two properties of the joint pdf:
$\int\limits_{-\infty}^{\infty} \int\limits_{-\infty}^{\infty} \int\limits_{-\infty}^{\infty} f(x, y, z) \, dx \, dy \, dz = 1$,
and $f_X(x) = \int\limits_{-\infty}^{\infty} \int\limits_{-\infty}^{\infty} f(x, y, z) \, dy \, dz$
It follows that $\int\limits_{-\infty}^{\infty} f_X(x) \, dx = 1$
Comment: Notice this assumes Fubini's Theorem applies.  But you don't need it: *the marginal density is that of the variable $X,$* namely, the one obtained by *forgetting about all the other variables.*  It's that simple!


Como fazer com que uma função execute apenas no IE 10 e 11?

Question: Eu quero que um trecho de código (uma função especifica) execute apenas quando o navegador for IE 10 e 11, quando for Firefox ou Chrome por exemplo, eu quero que essa função seja ignorada. Isso é possível?
Comment: segue dica; https://modernizr.com/
Answer: Eu não faria isso, leia isso, mas se quer mesmo (não funcionará no Edge também):
<code>if (/MSIE \d|Trident.*rv:/.test(navigator.userAgent)) {
    funcao()
}
</code>
Coloquei no GitHub para referência futura.


How to compare all properties values from a two equal classes

Question: I've a class defined as follows:
Public Class DeviceConfig
    Private _maxNumCodesGlobal As Integer
    Private _maxNumCodesDataMatrix As Integer
    Private _maxNumCodesQR As Integer
    Private _maxNumCodesBarcode As Integer
    Private _partialResults As String
    Private _allowIdenticalSymbols As String
    Private _datamatrixValidation As Integer
    Private _datamatrixValidationType
'AND MUCH MORE PROPERTIES
'GETTERS & SETTERS
End Class

as you can see it's a long list of properties in this class.
I need to compare the values of the properties from an instance with the values of the properties of another instance.
Is there a way to iterate through all of them, or even better, just comparing both classes and get true/false if they have the same properties values or not?
if instance1=instance2 then true

Thank you
Comment: You could write a class method that compares it to other objects of the same class, then you only need to write the comparison iteration logic once.
Answer: I encountered the same problem and created this method. Hopefully it will help you.
It uses reflections to iterate through the public fields, ignoring those with the JsonIgnore annotation.
This method is not considering fields as List, Set, etc.
You can change it to work for properties instead of fields.
    protected <T> boolean equals(T object1, T object2) {
    Field[] fields = object1.getClass().getFields();
    for (Field field : fields) {
        if (field.getAnnotation(JsonIgnore.class)!= null) continue; //do not check the fields with JsonIgnore
        Object value1;
        Object value2;
        try {
            value1 = field.get(object1);
            value2 = field.get(object2);
        } catch (Exception e) {
            logger.error("Error comparing objects. Exception: " + e.getMessage());
            return false;
        }
        //comparing
        if (value1 == null) {
            if (value2 != null)
                return false;
        } else if (!value1.equals(value2))
            return false;

    }
    return true;
}


Why does form get submitted after onsubmit return undefined?

Question: I only tested in Chrome and Firefox.
<form method="POST" action="post.php?action=newthread&fid=170" onsubmit="return validate(this)">

    <input type="submit">
</form>

It turns out if the function validate returns undefined, the form still gets submitted. But if it returns false, the form will not get submitted which is expected. I thought undefined would stop the form from submitting. Can someone explain this behaviour? Thank you.
Comment: can you not just make sure it has a return value?
Comment: [The return Statement](http://www.ecma-international.org/ecma-262/5.1/#sec-12.9) @Popnoodles
Answer: Javascript uses exact comparisons (like === rather then ==) when testing the return value of the event handler. The only return value that prevents the default action is false. Any other return value, including undefined, allows the default action to take place.


CodeWorkout's "hidden tests" are telling me my code didn't return the right number, despite passing every test

Question: I have some code here made to create the average of any array greater than 3 elements. Basically, I need to remove the largest and smallest elements and then get the average of everything in-between.
My code is most likely terrible, but it passed all the tests on CodeWorkout except for the "hidden tests".
So essentially my issue is that I have no idea why it would print wrong. My guess is that I didn't code it to anticipate arrays lower than 2 elements, or I just didn't do it the right way. I'm not allowed to import anything, and I'm only allowed to write code for this specific method.
public int centeredAverage(int[] nums){
int cout = 0;
int smallest = nums[0];
int largest = 0;
int average = 0;

for(int i = 0; i < nums.length; i++){
    if(nums[i] < smallest){
        smallest = nums[i];
    }
    if(nums[i] > largest){
        largest = nums[i];
    }
    average += nums[i];
}
average = average - smallest - largest;
return average / (nums.length - 2);}

Comment: JavaScript and Java are not related
Comment: You probably should not assume that the largest is zero.
Comment: You're not doing any edge case / sanity checks. I can't tell if you did that before this method was invoked, or if they promise not to send that as input, but this is easily broken by sending empty array, array less than 3 elements (if 2, divide by zero exception), negative numbers...
Comment: @Nikki9696 Yeah, that makes sense. I'll check to see if I can do casing to check for negatives, as that's the only one I can assume would be in the tests.
Comment: `average = average - smallest - largest;` What if the `smallest` value appears twice in the array?  You are not compensating for it appearing twice, unless you only need to take into account each largest or smallest a single time.
Comment: @Nexevis Don't worry, it wants me to ignore copies, so I can simply take one of the copies of the largest/smallest and it'll work out. It has a test where nums = {7,7,7} and it expects 7, but if I remove copies I'll be dividing by zero anyways.
Answer: What is the exact requirement?
   Largest      Smallest
      |            |
2, 4, 16, 5, 7, 4, 1, 8, 1
          |  |  |
      Everything Between (1)

2, 4, 16, 5, 7, 4, 1, 8, 1
|  |      |  |  |     |
Everything Between (2)

For negative numbers, or in general:
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;

Arrays.sort(int[] numbers) might be helpful.
Having more than one smallest or largest might alter the average; your nums.length - 2.
You are doing integer division, 13 / 5 = 2. With rounding you would need: (I have renamed average to sum.
sum = sum - smallest - largest;
int n = nums.length - 2;
return n <= 2 ? 0 : (sum + n/2) / n;

Comment: Definitely worked and I got full points for it. If I had any rep I would've upvoted you so fast.
Comment: Pardon me for not clarifying; "everything between" is essentially any number higher than 'smallest' and lower than 'largest'. I'll see if using max_value and min_value works better.
Comment: My _"Everything Between (2)"_  leaves out 3 extremes: 16, 1, and 1.


solution to knapsack like problem.

Question: I am new to optimization. How do I solve the below problem? Is it similar to the 0-1 knapsack problem?
There will be a meeting at New York and San Francisco  offices. We will have to fly the participants to either one of these two offices. Let's say each office can accommodate half of the participants. Our goal is to assign each participant to an office in a way that the total travel cost for the company is minimized. What is this minimal cost?
<code>   SF NY
A 500 700
B 200 600
C 400 500
D 600 200
</code>
Output : 1400 (A:500 + B:200 + C:500 +D: 200)
Answer: One approach is to calculate firstly the differences (absolute value) of the travel cost San Francisco and New York for each participant.
$A:200, B:400, C:100, D:400$
Now you look after the participant where you can save at most by choosing the destination with the lower travel cost. Here it is $B$ or $D$.
$B$ travels to San Francisco: Saving $400$, Cost: $\color{blue}{200}$
$D$ travels to New York: Saving $400$, Cost: $\color{blue}{200}$
It can be saved $200$ if we choose the lowest cost for $A$. This is more than in the case of $C$.
$A$ travels to San Francisco: Saving $200$, Cost: $\color{blue}{500}$
And finally $C$ has to travel to New York: Saving: $100$, Cost: $\color{blue}{500}$

solution to knapsack like problem.


Case of equality in spectral norm matrix triangle inequality

Question: Let $(A,B)\in M_n(\mathbb{R})\times M_n(\mathbb{R})$ be two matrices. We denote by $\|\cdot\|_2$ the spectral norm.
Without any additional assumptions on $A$ and $B$, can we characterize the case of equality in the spectral norm matrix triangle inequality, i.e., when
\begin{align*}
\|A+B\|_2=\|A\|_2+\|B\|_2.
\end{align*}
If $A=U\Sigma_AV^T$ and $B=U\Sigma_BV^T$ (singular value decompositions), the equality holds but is there a full characterization?
Best wishes.
Answer: Equality holds if and only if $A$ and $B$ share a common right singular vector $v$ corresponding to the largest singular value and $Av=\sigma_1(A)u,\,Bv=\sigma_1(B)u$ for the same left singular vector $u$.
To prove this, suppose equality holds. If $\|A\|_2=\|B\|_2=0$, there is nothing to prove. So, suppose also that $A,B\ne0$. Let $v$ be a right singular vector of $A+B$ corresponding to the largest singular value. Then
$$
\begin{align}
\|(A+B)v\|_2
&\le\|Av\|_2+\|Bv\|_2\tag{1}\\
&\le\max_{\|x\|_2=1}\|Ax\|_2+\max_{\|y\|_2=1}\|Ay\|_2\tag{2}\\
&=\|A\|_2+\|B\|_2\\
&=\|A+B\|_2\\
&=\|(A+B)v\|_2.
\end{align}
$$
Therefore ties occur in both $(1)$ and $(2)$. The tie that occurs in $(2)$ means that $v$ is also a unit right singular vector of both $A$ and $B$ corresponding to their largest singular values. Therefore $Av=\sigma_1(A)u$ and $Bv=\sigma_1(B)u'$ for some unit left singular vectors $u$ and $u'$ of $A$ and $B$ respectively. However, the tie in the triangle inequality $(1)$ implies that $Av$ and $Bv$ are real positive multiples of each other. Therefore $u=u'$ and we are done.
Using the characterisation $\|A\|_2=\max_{\|x\|_2=\|y\|_2=1}x^TAy$, the necessary and sufficient condition above can be rephrased as
$$
\|A\|_2=u^TAv\quad\text{and}\quad\|B\|_2=u^TBv
$$
for some unit vectors $u$ and $v$. This is also equivalent to the condition that there exist two orthogonal matrices $U$ and $V$ such that
$$
U^TAV=\pmatrix{\sigma_1(A)\\ &A'}
\quad\text{and}\quad
U^TBV=\pmatrix{\sigma_1(B)\\ &B'}
$$
for some matrices $A'$ and $B'$.
Comment: Many thanks for your clarity!


is host id size of IP address will vary between the private and public networks?

Question: I understood that size of host id in the class c network is 8 bits(1 Octet)
Classful network
After started exploring about private networks, in the below link
Private network
The host id size of the IP address range belongs to the class C network is mentioned in as 16 byte
 192.168.0.0 - 192.168.255.255 (16-bit block private address)

My Assumption:

Class full network is applied for both private and public IP addresses. That is ifthe IP starts with 192.168.x.x is class c network and the size of the host id in the class full network is always 8(1 octet).

Is my assumption is wrong or any theory behind it?
Answer:
The Classes were deprecated in 1994. That's 20 years ago. Everything is done in VLSM using CIDR notation. What was a "Class C" is now a "/24".
The 192.168 RFC 1918 allocation is a /16, as noted in the "16-bit block" remark.
Your assumptions are based on something that was abandoned 20+ years ago.


What is the second smallest C single precision positive floating number there is? (IEEE754)

Question: Documentation on how single precision floating point numbers work in C can be found in various good places such as:

IEEE754 32-bit single precision format
https://en.wikipedia.org/wiki/Single-precision_floating-point_format
https://stackoverflow.com/questions/7644699/how-are-floating-point-numbers-are-stored-in-memory
https://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html

To simplify, it is formed with 32 bits from where:

1 bit is for signal (bit 31)
8 bits for the exponent (bits 30 to 23), being 127 the zero "offset"
23 bits for the mantissa (bits 22 to 0), leaving the leading 1 out

From wikipedia you can see that:

7f7f ffff = 0 11111110 11111111111111111111111 = $(1 − 2^{−24}) × 2^{128} ≈ 3.402823466 × 10^{38}$  (max finite positive value in single precision)
0080 0000 = 0 00000001 00000000000000000000000 = $2^{−126} ≈ 1.175494351 × 10^{−38}$ (min normalized positive value in single precision)

That is, the minimum and maximum represented in binary and a decimal approximation.
I specially like the reference link number 4 above, where it states there is an epsilon.
How would that "step" goes in binary and to what decimal represented it will go starting from zero and moving up (positive) in the smallest steps possible?
What about this statement from the size of the steps, in the wikipedia link above (number 2), in this section
The steps described there goes for integer. Does it apply to decimal discrete jumps also? In other words, depending on the size of the number $n_{1}$, the immediately "next" number $n_{2}>n_{1}$ will move further or closer to it? (error $|n_{1}-n_{2}|$ will vary?)
Comment: The your definition implicitly includes **normalized**.
Comment: The second smallest positive number would be the _denormalized_ representation represented as _0 00000000 00000000000000000000010_.
Comment: What is your definition of  **the second smallest C single precision positive floating number**, and why **second**. Henning has already given the representation. The smallest number $> 0$ would be `0 00000000 00000000000000000000001`. See Wiki 2: **denormal**.
Comment: _denormalized_? Sorry, don't get it. What would be the actual representation? If it helps, the purpose of the question is to understand the difficult problem of the "equality" of such numbers within an error margin.
Comment: After zero, that is all zeroes (`0 00000000 00000000000000000000000`), the first is easily found in the documentation to be `0 00000001 00000000000000000000000`. So the second would be the next after the gap that cannot be represented. Thanks for the denormal wiki reference.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/67019/discussion-between-dr-beco-and-gammatester).
Answer: With the machine epsilon for IEEE single precision $\epsilon_M = 2^{1-24} = 1.1920928955078125\times 10^{-7}$ N.J. Higham (Accuracy and Stability of Numerical Algorithms, 2nd ed., see [1]) gives the following
Lemma 2.1. The spacing between a normalized floating point number $x$ and an
adjacent normalized floating point number is at least $0.5\epsilon_M |x|$ and at most $\epsilon_M |x|$
In Fig.2.1 you see the relative distance graphics for single precision, showing a
wobbling saw-tooth curve.
Here are some actual values for the spacing at certain single precision numbers (showing hex instead of binary, columns: first the number, second the next number, third second-first):
<code>Spacing at min. normalized single = 1.175494351E-0038
00800000   00800001 1.40129846432482E-0045
00800001   00800002 1.40129846432482E-0045

Spacing at 1
3F7FFFFF   3F800000 5.96046447753906E-0008
3F800000   3F800001 1.19209289550781E-0007
3F800001   3F800002 1.19209289550781E-0007

Spacing at 64
427FFFFF   42800000 3.81469726562500E-0006
42800000   42800001 7.62939453125000E-0006
42800001   42800002 7.62939453125000E-0006
</code>
You can see the jumps between the values for a power of 2 and its predecessor.


WPF and VS2010 crashes on specific arabic(?) text

Question: I've just found symbols that WPF doesn't want to display (actually it freezes when i want it to display ones) - "ﻠ́ﭑ". When I pasted these symbols to XAML:
<code><TextBox Text="ﻠ́ﭑ" />
</code>
Visual Stuido has crashed. Does anybody know how to solve this? Seems that it is a microsoft wpf bug.
Comment: I repro on VS2010 SP1.  Post bug reports to connect.microsoft.com.
Comment: thanks for repro, already posted it
Answer: I can guess for such language specific Xml-unsupported characters we generally use locale based resources and refer them onto the XAML.... like this ....

Create a Resource (ResX) file in your project or you can reuse the Properties/Resources.resx file. In this add a resource named "MyArabicCharacter" and set it to "ﻠ́ﭑ"
In the Visual Studio Resource designer you have to change the Access Modifier from Internal to Public. This can be found in the top toolbar of the designer.
Add the namespace to your XAML View:
<code> xmlns:p="clr-namespace:MyProject.Properties"
</code>
The Resources can be accessed via the x:Static markup extension of XAML:
<code> <TextBlock Text="{x:Static p:Resources.MyArabicCharacter}" />
</code>

Let me know if this works.
Comment: before pasting these symbols into XAML, I tried to read them from file in my WPF application - it freezes
Comment: For VS2010 not to freeze, can you defer loading that symbol till runtime?
Comment: if I'll load that symbols at the runtime _my_ wpf app will freezes, not the vs2010. I think this is a WPF bug (vs crashes because its ui based on WPF) and already reported it to ms.
Answer: Microsoft has fixed this bug on my report https://connect.microsoft.com/WPF/feedback/details/682446/wpf-4-0-apps-i-e-vs2010-crashes-on-specific-symbols


Rings of Tangential Circles

Question: I looked at
7 circles surrounded by 12 circles
and wanted to take it further, drawing a "tight" ring of $18$ circles (identical in size to the others) around the $12$, such that (a) the $18$ circles form a ring such that neighboring circles are tangential to each other and (b) if any circle in the outer ring touches a circle in the inner ring, they touch tangentially.
Further, I would like to extend it to more rings of $24, 30, 36, \dots$ circles in each ring -- all nicely tangential.
Any help would be appreciated!
Comment: You would have to verify that the length of the edges of the outer polygon, the length of the edges of the inner polygon, and the distance from a corner of the inner polygon to the nearest corner of the outer polygon are all equal (the diameter of the circles).
Answer: As seen at the figure, up to $12$ surrounding circles are the congruent circles tangential.
For $12+6n, n=1,2,\dots \;$ surrounding circles, it seems more difficult to find a pattern (if any) that would make the circles tangential not only within the ring, but also "any circle from $(n)^{th}-$ ring tangential to a circle from the previous ring".
Comment: Your diagram looks wonderful. I suspect this is the best I can expect. Can you pl. tell me how I can draw those circles? For each circle, all I need is the (formula for its) center point. Also, for each ring, what is the (formula for the) radius of the "big" circle with its center at the origin? I see you have drawn one of those.
Comment: I drew it in GeoGebra, a free software. Without calculations. At the beginning I drew a circle, then I used exclusively transformations: symmetry, reflexion and the most often rotation. GeoGebra has all these tools. If you need coordinates or equations, they are automatically written in the left column of the GeoGebra window.
Comment: I tried my best to replicate your drawing and got the following. It seems to me that other than the first two rings with 6 and 12 circles, the circles cannot all be tangential to their two neighbors within the ring. There will be gaps. Can anyone confirm this statement?
Comment: [link](https://drive.google.com/file/d/1xhLkQ-l4LI2pVUZwVjG4oScj4_2MhpNb/view?usp=sharing) [Sorry, I don't know how to place an image in-line as you have done!]
Comment: I don't think it's possible to insert a picture into a comment. Maybe you can't put it in your question because your reputation isn't high enough. If you want, I'll do it for you.
Comment: Please do! I still do not understand why I don't get the same nice picture you have. Could you please do the GeoGebra diagram with single-pixel lines for the circles and in a larger size (maybe show only a sixth of the diagram) to see if there are any gaps?

Rings of Tangential Circles


Sound not working with PlaySound

Question: So I am trying to make a simple DLL to play sounds in another program. I am trying to use the playsound function, and I have it set up, but when I run it in the other program, I get the default beep. Here is my code.
export double sound_manage(const char* file_old,double handler)
{
    /*
    Handler values:
    0 - Play sound
    1 - Loop sound
    2 - Stop sound
    */
    bool good;
    double ret;
    double op;
    if (handler == 0) op = SND_ASYNC;
    if (handler == 1) op = SND_LOOP;
    if (handler == 2) op = SND_PURGE;
    LPCTSTR file;
    file = LPCTSTR(file_old);
    good = PlaySound(file,NULL,op);
    ret = double(good);
    return ret;
}

I have included in the linker the winmib or whatever, but I don't know what's going on.
Any help is greatly appreciated!
Answer: If you get the default beep then it is most likely that the sound file can't be found. PlaySound searches for the sound file in the current directory, then the windows directory, then the system directory and finally the PATH.
Answer: The documentation includes the following:

Three flags in fdwSound (SND_ALIAS, SND_FILENAME, and SND_RESOURCE)
  determine whether the name is interpreted as an alias for a system
  event, a file name, or a resource identifier. If none of these flags
  are specified, PlaySound searches the registry or the WIN.INI file for
  an association with the specified sound name.

So if you want to play a file on disk, you have to include the SND_FILENAME flag, for example:
if (handler == 0) op = SND_ASYNC | SND_FILENAME;
if (handler == 1) op = SND_LOOP | SND_ASYNC | SND_FILENAME;

Something else, this line is probably wrong:
file = LPCTSTR(file_old);

If you don't compile with Unicode, file_old is compatible with file so you don't need to cast. If you compile with Unicode, a typecast is not sufficient.
Comment: I tried that, but same thing occurs. I'm not sure about the unicode, but I'm using VC++ 2010 and it tells me it's wrong if I don't cast.
Comment: see [here](http://stackoverflow.com/a/332086/33499) why typecasting can be dangerous. You should try to avoid it if possible. You should use [MultiByteToWideChar](http://msdn.microsoft.com/en-us/library/dd319072%28v=vs.85%29.aspx) to convert the string. But it is probably easier if you use `PlaySoundA` instead, that should avoid the typecast.
Comment: I tried multibyte to wide char and it says its wrong... Also, what is PlaySoundA? (I am a C++ newb.)
Comment: PlaySoundA is the ansi version of the PlaySound function. If you don't add the A, you will use PlaySoundW automatically because of your compiler settings. See [this](http://msdn.microsoft.com/en-us/library/dd374089.aspx)
Comment: and MultiByteToWideChar is not easy to use. It is a separate topic, but you first have to call it to determine how big the result will be, then you have to allocate the memory and call it again. At the end you have to free the memory. So I can understand it will not work immediately for you.

Sound not working with PlaySound


Go : How to reference a field in an inherited struct

Question: I have 2 structs whereby one inherits values that are common amongst all stucts denoted by type Common struct {...}
type Common struct{
    Id int
    CreatedAt time.Time
    UpdatedAt time.Time
    CreatorId int
}

type Post struct{
  type Post struct{
  Common
  Status
  Title string
  ShortDescription string
  Content string
  CategoryIds []int
  TagIds []int
  Url string
  MainImageId int
  Keywords []string
}

However when I try to create a new instance of the Post struct as in the following.
post1 := &Post{
    CreatorId:   1,
    Status: 1,
    Title: "this is the title of the first post",
    ShortDescription: "this is the short description of this post",
    Content: "",
    Url: "first-post",
    MainImageId: 1,
}

It does not recognise the CreatorId field.
How would I reference this field in the new instance or modify the struct so that it registers CreatorID as part of the Post struct?
Thanks
Answer: CreatorId (which, by the way should be called CreatorID) is a part of Сommon, so the only way to initialize it in struct literal is:
post1 := &Post{
    Common: Common{CreatorID: 1},
    // ...
}

Alternatively,
post1 := &Post{
    // ...
}
post1.CreatorID = 1


How to correctly transform variables in linear models using residual plots?

Question: So I have a linear model as follows;
 Mod=lm(PRICPTM ~ DISTANCE + PCTLOAD + ORIGIN + MARKET + DEREG + PRODUCT,data=x)
 summary(Mod)
 residualPlots(model = Mod)

Data: https://docs.google.com/spreadsheets/d/1lz5ll6w9mU-S-PCi6aKO1wONbr4Kj9lVe-zyGcH7gBg/edit?usp=sharing
The residual plots didn't look linear and about the mean. SO I transformed the dependent variable by trial and error to the following.
 Mod=lm(log(PRICPTM) ~ DISTANCE + PCTLOAD + ORIGIN + MARKET + DEREG + PRODUCT,data=x)
 residualPlot(model = Mod)

So now this one looks good. But the partial residual plots are still off.

What I need to do is;
1) transform the independent variables to correct the model.
2) Understand if there is any standard technique available for transforming the variables by looking at the residual plots (ie, if residual plot is sloping upwards, do this, if it is exponentially increasing, do this etc...)
Comment: Whats wrong with partial plots? Nice linear relationships! Where is some nonlinear relationship between log(PRICPTM) and DISTANCE but linear approximation is still reasonable. If you are not satisfied with this linear approximation you can use **gam** model by the following code

library(gam)
gam.model <- gam(log(PRICPTM)~s(DISTANCE) + ORIGIN + MARKET + DEREG + PRODUCT,data = x)
plot.Gam(gam.model,se=TRUE)
Answer: Your residual plot for the log-linear model looks fairly reasonable to me, and although there are some minor issues with the partial residuals in the added-variable plots, these are an artifact of two underlying issue in your model.  Firstly, if you have a look at your data frame, you will see that the variable PRODUCT takes only three values, and they do not appear to have an effect that is proportionate to its value; in effect, this is a categorical variable.  By treating this as a continuous variable you impose an unnecessary constraint on the effects of these categories.  Secondly, even after this change, the DISTANCE variable does indeed appear to have a nonlinear relationship with the price point.  Taking a second-degree polynomial (quadratic function) gives a reasonable approximation to this relationship that improves the fit of the model and improves the residual and added-variable plots.
#Load libraries and set theme
library(MASS);
library(car);
library(ggplot2);
THEME <- theme(plot.title    = element_text(hjust = 0.5, size = 14, face = 'bold'),
           plot.subtitle = element_text(hjust = 0.5, face = 'bold'));

#Download and wrangle your data
DATA <- read.csv('Trucking.csv');
DATA$PRODUCT <- factor(DATA$PRODUCT);

#Fit the log-linear regression model
FORMULA <- formula(log(PRICPTM) ~ poly(DISTANCE, 2) + PCTLOAD + ORIGIN + MARKET + DEREG + PRODUCT);
MODEL   <- lm(FORMULA, data = DATA);

#Generate predicted values and studentised residuals
DATA$Pred <- predict(MODEL);
DATA$Res  <- studres(MODEL);

#Generate residual plot
ggplot(aes(x = Pred, y = Res), data = DATA) +
    geom_point(colour = 'blue') +
    geom_hline(yintercept = 0, colour = 'red', linetype = 'dashed') + THEME +
    ggtitle('Residual Plot') +
    labs(subtitle = '(Log-linear model for Price Point)') +
    xlab('Predicted log-Price-Point') + ylab('Studentised Residuals');

#Generate residual density plot
ggplot(data = DATA, aes(x = Res)) +
    geom_density(fill = 'blue') + expand_limits(x = c(-4, 4)) +
    stat_function(size = 1.2, fun = dt, colour = 'red', linetype = 'dashed',
                  args = list(ncp = 0, df = nrow(DATA)-1)) + THEME +
    ggtitle('Residual Kernel Density Plot') +
    labs(subtitle = '(Log-linear model for Price Point)') +
    xlab('Studentised Residual') + ylab('Density');

We can see that the residual plot displays no evidence of nonlinearity or heteroscedasticity.  The residual density plot shows some evidence of non-normality, but it is not a severe departure.  We can generate added-variable plots for this model to confirm that the explanatory variables have the appropriate functional relationship with the response variable.  For our DISTANCE variable we have used a second-degree polynomial fit, so we have two model terms corresponding to the linear part and quadratic part of this relationship.  The added-variable plots for these parts are shown below.
#Generate added variable plots
AVDATA <- avPlots(MODEL);

DATA.1 <- data.frame(AVDATA[[1]]);
names(DATA.1) <- c('DISTANCE1','LOGPRICPTM');
ggplot(aes(x = DISTANCE1, y = LOGPRICPTM), data = DATA.1) +
    geom_point(colour = 'blue') +
    geom_smooth(method = 'lm', se = FALSE,
                color = 'red', formula = y ~ x, linetype = 'dashed') + THEME +
    ggtitle('Added Variable Plot') +
    labs(subtitle = '(Log-linear model for Price Point)') +
    xlab('DISTANCE (linear part)') + ylab('Partial Residuals');

DATA.2 <- data.frame(AVDATA[[2]]);
names(DATA.2) <- c('DISTANCE2','LOGPRICPTM');
ggplot(aes(x = DISTANCE2, y = LOGPRICPTM), data = DATA.2) +
    geom_point(colour = 'blue') +
    geom_smooth(method = 'lm', se = FALSE,
                color = 'red', formula = y ~ x, linetype = 'dashed') + THEME +
    ggtitle('Added Variable Plot') +
    labs(subtitle = '(Log-linear model for Price Point)') +
    xlab('DISTANCE (quadratic part)') + ylab('Partial Residuals');

The added-variable plots show that the use of a second-degree polynomial for the DISTANCE variable is sufficient to attain linearity in the relationship between each model term and the response variable.  It is possible to use a more complicated model form, but the present model appears to be sufficient to give a reasonable fit, with a reasonable form for the relationship between the distance and the price point.
Assuming you are happy with this model form, the summary output of the model is shown below.  Under this model, the explanatory variables explain $R^2 = 91.46 $% of the variability in the log-price point.  This means that you should be able to make quite good predictions of the price point based on observed values of the explanatory variables.  (However, to test this, you would need to do a more detailed analysis involving fitting the model to training data and then making predictions on test data.)
#Generate the model output
summary(MODEL);

Call:
lm(formula = FORMULA, data = DATA)

Residuals:
     Min       1Q   Median       3Q      Max
-0.57447 -0.17764  0.00088  0.14463  0.68497

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)
(Intercept)        11.2907630  0.0597335 189.019  < 2e-16 ***
poly(DISTANCE, 2)1 -5.2274966  0.2582329 -20.243  < 2e-16 ***
poly(DISTANCE, 2)2  2.9602807  0.3108032   9.525  < 2e-16 ***
PCTLOAD            -0.0098433  0.0005868 -16.776  < 2e-16 ***
ORIGINMIA          -0.0014046  0.0544910  -0.026 0.979476
MARKETSMALL        -0.0557069  0.0450712  -1.236 0.218785
DEREGYES           -0.9792830  0.0434109 -22.558  < 2e-16 ***
PRODUCT150          0.2019289  0.0552353   3.656 0.000376 ***
PRODUCT200          0.3153911  0.0519552   6.070 1.41e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2478 on 125 degrees of freedom
Multiple R-squared:  0.9148,    Adjusted R-squared:  0.9093
F-statistic: 167.7 on 8 and 125 DF,  p-value: < 2.2e-16

Comment: Hi, Thanks. I got time to go through this just now. One question. Just by looking at the residual plot, can we know what transformation is to be made? Like how you gave quadratic form to DISTANCE variable in this problem, is there a standard set of things that we can try out for attaining the perfect model? or is it just trial and error?
Comment: And one more thing. Can you please explain how to make inferences from Added Variable plots?
Comment: @DomJo: If you fit a model with just the linear term, and then generate an added-variable plot, you should see that the residuals are curved, and the trend is given roughly by a quadratic.
Comment: There is another function called component + residual plot in car package. What does it give compared to avplot?
Comment: Never heard of it.


Node creation PHP – menu item under proper parent

Question: while I create node by PHP, I use this:
$node->menu['enabled'] = true;
$node->menu['link_title'] = $node->title;

but it puts link in 0 depth of the menu. It doesn't care for "Default parent" selected for content type. Neither this works:
$node->menu['parent'] = "menu-global-menu:961";

How to select parent then?
Answer: It looks like you need to set $node->menu['plid'] = "961"; to set the parent node.
You can have a look through the menu_link_save doco to get an idea of what is going on, or there is a smaller code snippet on this blog that explains in a simple, fast way.
As a side note, you can use node_object_prepare($node); to set default values after setting your node type, which should take care of your default menu parent. I've found this guide helpful with programmatic node creation.


How can I configure Octave to use gnuplot for plotting directly to image files?

Question: I'm using Octave in a CLI only environment. I want to export plots to image files(jpg or png or any other image format). I read from manual that I can switch to gnuplot graphics by graphics_toolkit(gnuplot).
I use the following commands in gnuplot to output a plot as file (as I can't use plot function in Octave due to absence of X11).
set terminal png
set output "test.png"

plot "data1.txt"

unset output

But I can't figure out a way to set terminal and output variables from Octave. So my question is how can I set those two variables from octave  so that running plot function from Octave generates a images file on my disk?
Note: I'm using Debian in an chroot environment which is completely CLI. So I use octave to generate data inside "data.txt" first and then use gnuplot to save my plots as image file . Later I view those plots in my host os(Android) with some image viewer.
Comment: use `figure("visible", "off")` after switching to gnuplot and before any plot command
Comment: hm? Just as normal: `graphics_toolkit("gnuplot");figure("visible", "off"); plot(1:10); print foo.png`
Comment: Then how can i save plot to an image file? How can I set terminal?
Comment: If @Andy's solution doesn't work, you could call the gnuplot command from within Octave too: `fid = popen ("gnuplot","w"); fputs(fid,"set terminal png");` etc.
Comment: i have to issue print command each time i plot something... is it possible issue that (print test.png)automatically after plot command? I'm thinking about making a custom function which will issue `print` automatically after plot but  can't figure out how to pass a whole string(like "x,y,title,blah,blah,blah" ) from that custom function to plot... any suggestion? Is that even possible?
Answer: Thanks @Andy for giving useful hints to solve this problem. So I ran those codes in interpreter and later put them in .octaverc for a permanent fix. Here's the code for a quick fix:
graphics_toolkit("gnuplot");
setenv ("GNUTERM", "png");
warning("off","print:missing_fig2dev");
warning("off","print:missing_epstool");
Note  : When I ran plot command,it gave 2 warnings(not errors). I read here that the warnings might be due in exclusion of fltk(as I'm using gnuplot in a cli only environment). The warnings didn't prevent me from plotting anything but those warnings appeared everytime I ran plot which annoyed me. So I put them in the rc file. Otherwise plot function is running fine.
Thanks @Cris Luengo for an alternate solution. But I haven't tried that actually.  ;)


How to calculate expected value if the probability will be random variable uniformly distributed over a range

Question: Let's say we are given an event that has fixed value $v$, how can we find its expected value if the probability of the event happening is uniformly distributed random variable in a range $[a, 1], a < 1$.
I tried calculating different integrals, however none of these seemed to make sense.
Comment: It's not so clear what you mean by this.  My interpretation would be: first, pick a number p uniformly from the range [a,1].  Then, sample a random variable that takes the value v with probability p and 0 with probability 1-p.  Then calculate the total expected value.  Is this the correct interpretation?
Comment: Yeah, I meant this
Answer: If the probability of the event happening is $p$, then the expected value is just $pv$.  Since $p$ was drawn uniformly from $[a,1]$, the total expected value should be given by
$$
\int_a^1 pv \cdot \frac{dp}{1-a} = \frac{v}{1-a} \cdot \frac12 (1-a^2)
$$
Comment: That's precisely the expected value of the uniform distribution multiplied by $v$: $\dfrac{v}{1-a}·\dfrac{1}{2}(1-a^2)=v\dfrac{a+1}{2}$.
Answer: $$E(V)=E[E(V|X)]=E(vx)=vE(X)=v\frac{a+1}{2}$$


NSPasteBoard _setData:forType NSImage fails for PNG file

Question: I am using the code from this site to copy an image file to clipboard. This is the full source code
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <unistd.h>
BOOL copy_to_clipboard(NSString *path)
{
  // http://stackoverflow.com/questions/2681630/how-to-read-png-image-to-nsimage
  NSImage * image;
  if([path isEqualToString:@"-"])
  {
    // http://caiustheory.com/read-standard-input-using-objective-c
    NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
    image = [[NSImage alloc] initWithData:[input readDataToEndOfFile]];
  }else
  {
    image =  [[NSImage alloc] initWithContentsOfFile:path];
  }
  // http://stackoverflow.com/a/18124824/148668
  BOOL copied = false;
  if (image != nil)
  {
    NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
    [pasteboard clearContents];
    NSArray *copiedObjects = [NSArray arrayWithObject:image];
    copied = [pasteboard writeObjects:copiedObjects];
    [pasteboard release];
  }
  [image release];
  return copied;
}

int main(int argc, char * const argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  if(argc<2)
  {
    printf("Usage:\n\n"
      "Copy file to clipboard:\n    ./impbcopy path/to/file\n\n"
      "Copy stdin to clipboard:\n    cat /path/to/file | ./impbcopy -");
    return EXIT_FAILURE;
  }
  NSString *path= [NSString stringWithUTF8String:argv[1]];
  BOOL success = copy_to_clipboard(path);
  [pool release];
  return (success?EXIT_SUCCESS:EXIT_FAILURE);
}

When I run the compiled binary with a PNG file, I get this error
$ ~/bin/imgbcopy prof/combined.png
2017-10-25 16:24:50.373 imgbcopy[80618:4292276] -[NSPasteBoard _setData:forType:index:usesPboardTypes:] returns false. Type: public.tiff, index: 0 class: NSImage.

Copying  the PNG image from bash pipe also fails
$ cat prof/combined.png | ~/bin/imgbcopy -
2017-10-25 16:27:52.856 imgbcopy[80690:4293881] -[NSPasteBoard _setData:forType:index:usesPboardTypes:] returns false. Type: public.tiff, index: 0 class: NSImage.

Testing with it another random PNG screenshot works fine. I notice the error message above says Type: public.tiff. The PNG was initially converted from SVG using ImageMagic.
What is the problem with the code, or is it a malformed PNG?
PNG File in question.
Answer: I did some tests and the results are quite remarkable.
First test:
NSData *imageData = [NSData dataWithContentsOfFile:[@"~/Downloads/combined.png" stringByExpandingTildeInPath]];
NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
[pasteBoard clearContents];

NSPasteboardItem *pasteboardItem = [[NSPasteboardItem alloc] init];
[pasteboardItem setData:imageData forType:NSPasteboardTypePNG];

NSLog(@"Write result: %i",  [pasteBoard writeObjects:@[pasteboardItem]]);

NSImage *image = [[NSImage alloc] initWithContentsOfFile:[@"~/Downloads/combined.png" stringByExpandingTildeInPath]];
NSUInteger length = [[image TIFFRepresentation] length];
NSLog(@"%f MB (%lu)", length / 1000.0 / 1000.0, length);

[pasteBoard writeObjects:@[image]];

Output:
2017-11-30 15:57:53.317349+0100 Lolo[4927:639480] Write result: 1
2017-11-30 15:57:54.831260+0100 Lolo[4927:639480] 347.824566 MB (347824566)
2017-11-30 15:57:55.293900+0100 Lolo[4927:639480] -[NSPasteBoard _setData:forType:index:usesPboardTypes:] returns false. Type: public.tiff, index: 1 class: NSImage.

I could write the image as PNG data to the pasteboard. The NSImage object can't be written like in your case. NSImage objects store themselves in multiple formats including TIFF data, so just to test I print the size of the image data it would write to the pasteboard. It's 347.824566 MB, so that might be a bit to big.
Second test:
NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
NSData *data = [pasteBoard dataForType:NSPasteboardTypeTIFF];
float length = [data length];
NSLog(@"%f MB (%f) - %@ - %@", length / 1000.0 / 1000.0, length, data, [pasteBoard types]);

Output:
2017-11-30 15:49:51.018708+0100 Lolo[4786:624058] 0.000000 MB (0.000000) - (null) - (
    "public.tiff",
    "NeXT TIFF v4.0 pasteboard type",
    "dyn.ah62d4rv4gu8zazwuqm10c6xemf1gq54uqm10c6xenv61a3k",
    PVPboardInfoPboardType
)

In the second test I opened the image in Preview. I copied the image, got no error. Checking the clipboard (pasteboard) in the Finder says it has an TIFF image, but shows nothing. Printing the contents using pasteboard code, reveals that the pasteboard contains the TIFF type, but no data.
It seems that Mac OS (macOS) is simply not capable to store a image as big as the one used.