how to use 'or' operator when dealing with two different types

Question: I have a function that takes an argument with two types.
Refer to the typsescript docs, this SO question, and this SO question related to TS functions and types.
Function
  public onKeydown(ev: KeyboardEvent | EventTarget): void {
    if (ev.keyCode === 13) {
      this.sendMessage();
      ev.target.blur();
    } else {
      this.chatService.emitTyping();
    }
    return;
  }

HTML for the page
          <textarea
            autosize
            [minRows]="1"
            [maxRows]="4"
            [(ngModel)]="message"
            placeholder="escribe aqui"
            class="msg-input"
            (keydown)="onKeydown($event)"
            (click)="scrollToBottom()"
          ></textarea>

I cannot see that the function onKeyDown has two different types. Because the or doesn't seem to have the same effect in Angular as the docs of Typescript say. For example, if the 'Enter' key is pressed then blur() the keyboard and send the message. Am I going to have to make a separate function just to blur the keyboard?
This is the error I am getting:

ERROR in src/Components/chat/chat.component.ts(72,12): error TS2339: Property 'keyCode' does not exist on type 'EventTarget | KeyboardEvent'.
[ng]   Property 'keyCode' does not exist on type 'EventTarget'.
[ng] src/Components/chat/chat.component.ts(74,10): error TS2339: Property 'target' does not exist on type 'EventTarget | KeyboardEvent'.
[ng]   Property 'target' does not exist on type 'EventTarget'.
Comment: Maybe use a generic type on function parameters and cast with `as` later? https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html
Answer: Problem is typescript is confused because what you are doing is not doable on both EventTarget and KeyboardEvent. So you should tell him directly which one is it in the function. Such as:
public onKeydown(ev: KeyboardEvent | EventTarget): void {
    if (<KeyboardEvent>ev.keyCode === 13) { // changed line
      this.sendMessage();
      ev.target.blur();
    } else {
      this.chatService.emitTyping();
    }
    return;
  }

you could also do
if ((ev as KeyboardEvent).keyCode === 13) {

note that sometimes Angular still fails to find the property you need even if it exists in the DOM object, you can then concat the types like
type KeyboardCustom = KeyboardEvent & { customProp?: string };

meaning that it is both interfaces at the same type (but the second one is purely optional, hence, it will not throw errors when lacking). You could go further with Partials.
type CustomInterface = KeyboardEvent & Partial<KeyboardInterface>

where KeyboardInterface has any kind of structure.
Comment: Wow thank you for the help! However, when trying to do the same for `.target.blur()` I try to do `(ev as EventTarget).target.blur()` but still get the issue `Property 'target' does not exist on type 'EventTarget'`
Comment: but just so you know. It probably happened cuz you copied exactly the target: string part. This made Typescript expect a string from the target property. And strings have no 'blur' method. Hence the error. If target is an object with a blur property it will stop giving errors. It's super hacky though, so stick to whatever you find better
Comment: this is what I was talking about in angular being weird. Then change the `ev` to `ev`

Angular usually has problems with DOM objects for some weird reason I don't know. A quick workaraound for tighter cases is simply adding  behind the object. But only do it if you are at the end or know what you are doing, because this throws the whole purpose of typescript out the window.
Comment: I think I am going to have to disable this, because even with that type conversion now I am getting `property 'blur' does not exist on type 'EventTarget & string'`. I changed it to `(ev as KeyboardEvent & { target?: string }).target.blur();` because the Linter was complaining about the syntax you provided earlier. Thank you for your help again! Still new to Typescript and Angular
Comment: this is probably due to misusage. Either do  instead of the complex typing. Or be very specific: `EventTarget & { target?: { blur: Function } }`. **you are welcome!** feel free to ask anything though!
Comment: Yea I had to disable the linter and  since the linter complains with  since we have to be specific.


Instalar o SQL Server com a aplicação

Question: Estou finalizando uma aplicação e irei compilar usando o Inno Setup. O sistema estou usando o SQL Server.
Irei instalar o sistema em outros computadores.
A base de dados é instalada nos computadores que receberão a aplicação ou terei que instalar o SQLerver em cada computador?
Estou usando o Visual Studio 2013 Express.
Comment: Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Depende do que você fez, mas eu diria que não é necessário instalar em todos computadores, em geral ele só é necessário no computador que será o servidor.
É claro que se você fez tudo sem pensar nisto antes pode ter problemas para acessar o servidor e terá que arrumar a configuração da aplicação. Uma coisa é fazer para rodar na sua máquina, outra é fazer para rodar remotamente. Obviamente no servidor terá que instalar o SQL Server, e se já tem uma base de dados básica para começar rodar a aplicação, ele deve ser colocada lá.
Se usou algum biblioteca extra para a cessar o SQL Server que não as padrões do .NET, terá que distribuí-la na sua instalação.
Há casos que a aplicação pode precisar do banco de dados no cliente também. Aí não é recomendado o uso do SQL Server. Pelo menos não na sua versão completa. É melhor o uso do SQL Server Compact que é um banco de dado embutido na aplicação. Ou melhor ainda, usar o SQLite, até porque o SQL Compact foi descontinuado.
Comment: Não sei se entendi o que quer dizer mas sim, é possível, dá até para incluir o SQL Server na instalação. O que não quer dizer que ele possa ser instalado sem pagar nada. Fora do desenvolvimento ele precisa ser licenciado e custa caro. Eu acho que a não ser que tenho um bom motivo o banco instalado localmente ou é *demo* ou tem alguma coisa característica muito específica. Claro que se precisa de uma pequena base de dados local muito simples o mais comum é usar o SQLite. Antes se recomendava o uso do SQL Server Compact mas nem a Microsoft incentiva mais com a veemência de antes e fala em SQLite
Comment: Entendi... mas se for instalar localmente? Pois vejo alguns programas que baixamos da internet e que são instalados localmente. Isso seria possível?
Comment: Acho que o no seu caso deveria usar o SQLlite mesmo como o @bigown disse. Instalar várias instâncias do SQL Server seria trabalhoso e bem caro. Qual tamanho da sua aplicação? Se for grande e o acesso ao banco de dados for intenso, ai já é melhor pensar em ter um servidor para centralizar o banco de dados.
Comment: Certo. A aplicação é pequena. Uma agenda para a sala de reuniões que ficará com a recepcionista. Conterá apenas o nome do solicitante, a data e as horas de entrada e entrega.... Nesse caso, como eu faria para aplicar o SQLite na minha aplicação? Ele está atualmente no SqlServer ( que veio com o Visual Studio Express 2013 )
Comment: De fato parece ser algo simples demais e que faz sentido ficar só localmente, mas aí já é outra pergunta. Veja o [tour] e a [help]. Para resumir: a não ser que tenha feito pensando na troca, o que não parece ser o caso, tem que reescrever todo mecanismo de acesso a dados da aplicação.

Instalar o SQL Server com a aplicação


Include custom node id when POST'ing data through the REST API

Question: Is it possible to include a custom node id when POST'ing a node using the REST API? Knowing the node id in advance makes it easier to update the nodes in a future stage.
Answer: I think the default REST services don't allow that. You could implement yor own. It would need logic that prevents that existing nodes are overwritten exactly.


Ball goes out of bounds inside box

Question: So during a soccer game I refereed, a kid took a goal kick and somehow managed to kick the ball out of bounds before it left the box, like in my beautiful diagram below. Would this be a redo of the goal kick, because it never left the box, or would this be considered going out of bounds, and would be a corner kick?
Answer: This is a retake. The ball was never put back into play.

Law 16 - The Goal Kick, Section 1 - Procedure:

The ball is in play when it leaves the penalty area

Law 9 - The Ball In and Out of Play, Section 1 - Ball Out of Play:

The ball is out of play when:

it has wholly passed over the goal line or touchline on the ground or in the air.

The contradiction between Law 9 and Law 16 is resolved by reading the provision in Law 16 as:

the ball is out of play until it leaves the penalty area

which despite not being logically equivalent to the original text, is the only possible interpretation that doesn't lead to absurdities e.g. considering the ball as in play yet having wholly passed over the goal line.
Take your pick out of the following two clauses as to which is applicable here (they provide for the same result). The first is I believe what the lawmakers would intend to have apply to this situation, but once again, the wording isn't a perfect match
Law 16 - The Goal Kick, Section 2 - Offences and Sanctions:

If the ball does not leave the penalty area or is touched by a player before it leaves the penalty area the kick is retaken.
...
For any other offence the kick is retaken.

Ball goes out of bounds inside box


jQuery UI Multiple Droppable - drag whole div element & clone

Question: I've just started using jQuery UI to drag divs into a columns in a table. I have a couple different draggable divs with different background-colors and text inside them, and I need them to be able to dragged up to the drop area as a clone. This worked fine by using jQuery UI's example shopping cart code, but I've edited it so the whole object is dragged instead of just the text, but this then eliminates the clone functionality for some reason, even though I have helper:clone.
Here is my code:

Example column:

Draggable element:

<div style="background-color:#<?=$bgColor?>;color:<?=$textColor?>;" id="drag" class="<?=$subject?>"><?=$row['name']?>

It's essentially a timetable setup tool. Thank you for the help
Here is a jsFiddle for reference: http://jsfiddle.net/x5T4h/
Comment: I don't see any error. I'am up to help you if your provide a http://jsfiddle.net/
Comment: @Bouillou Here is my issue: http://jsfiddle.net/x5T4h/ thank you
Comment: Your fiddle is working with clone functionalities, what are you expecting?
Comment: What do you mean by the clone functionalities? Opacity?
Comment: @Bouillou as in I would theoretically be able to drag each one an infinite amount of times so I could have a column full of just English divs as an example
Answer: Not sure that it is exactly what you want, but here is a good start for your : http://jsfiddle.net/x5T4h/2/
Basically, I removed the second draggable object declaration, and I added clone function to duplicate your element inside drop event $( ui.draggable ).clone().appendTo( this );
$(function() {
    $( "ul li" ).each(function(){
        $(this).draggable({
            helper: "clone"
        });
    });

    $( ".day" ).droppable({
        activeClass: "ui-state-hover",
        hoverClass: "ui-state-active",
        accept: ":not(.ui-sortable-helper)",
        drop: function( event, ui ) {
            var targetElem = $(this).attr("id");
            $( ui.draggable ).clone().appendTo( this );
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $( this ).removeClass( "ui-state-default" );
        }
    });
});

Comment: Just call the draggable plugin on the cloned element. For removing, set up another drop target that checks if the element is a clone and if so, removes it from the DOM.
Comment: Yes this is perfect, thank you very much. You wouldn't happen to know off the top of your head if there's a way for the user to drag DIVs between columns (i.e to reorganize them) and then to be able to remove it completely from a column by dragging it away? If not it's ok don't worry about it. Thanks
Comment: breaks with 1.11.0, can you let me know why it only runs with 1.8.3


Prove of the Danes drop theorem in Banach Spaces

Question: I have searched a lot the prove of the Danes drop Theorem in Banach Spaces but I dont achievement find it. If anyone could tell me where I can read it or know the prove I will be grateful. The statement is the following:
Let $(X, || \cdot ||)$ be a Banach space. Let $A \subset X $ be a nonempty closed and $B \subset X$ a nonempty closed bounded and convex set such that
\begin{equation}
d(A, B) = \inf \{ || a - b ||: a \in A, b \in B \} > 0
\end{equation}
Then, for each $x_0 \in A$ there exists $x^* \in X$ such that:
\begin{equation}
x^* \in A \cap D(x_0, B) \hspace{.2cm}\text{and}\hspace{.2cm} \{ x^* \} = A \cap D(x^*, B)
\end{equation}
Note that the "drop" generated by $x \in X$ and $B \subset X$ is defined to be the set
\begin{equation}
D(x, B) := \{ tx + (1 - t)b: \hspace{.2cm}b \in B, t \in [0, 1] \}
\end{equation}
Update: The issue now, because of
the paper https://dml.cz/bitstream/handle/10338.dmlcz/106385/CommentatMathUnivCarol_026-1985-3_2.pdf is how the generalized K.M. Lemma (Lemma GKZ in paper) implies the Generalized Drop Theorem (the Danes' drop theorem here, Generalized drop theorem in the paper).
Comment: What does the notation $D(x_0, B)$ mean?
Comment: The "drop" generated by $x \in X$ and $B \subset X$ is defined to be the set $D(x, B) := \{ tx + (1 - t)b: \hspace{.2cm}b \in B, t \in [0, 1]\} $
Comment: I suggest drawing a 2D example to give you an idea for what $x^*$ should be.
Comment: ccI guess that $x^*$ must be in the border of A but I don't have idea of the prove.
Answer: A possibility to find the proof would be a pdf-request via scinapse: https://scinapse.io/papers/73432139
A hint on how to prove it is in this paper by Danes: https://dml.cz/bitstream/handle/10338.dmlcz/106385/CommentatMathUnivCarol_026-1985-3_2.pdf
Another option would be to extract a proof from the generalization of Danes drop theorem to locally convex spaces which can be found here: https://www.researchgate.net/publication/254488994_Danes'_Drop_Theorem_in_locally_convex_spaces
which, at first glance, seems quite doable without too much time investment.
Comment: The proof does not appear in this paper. How the generalized K.Z. Lemma implies the Generalized drop theorem?
Comment: You are absolutely right, I should have been a bit more careful there.
Comment: I just get the related article, do you want it for trying answer?


AR process with a constant

Question: I am having trouble understanding the estimation of an AR process. In some textbooks, the AR(1) process is defined as follows: $y_{t}=\theta y_{t-1}+ϵ_t$ (which does not contain a constant). So the OLS estimator is biased. I am confused about the cause of the bias. It is explained that $y_{t-1}$ is dependent on $ϵ_{t-1}$ although it is independent of $ϵ_t$. However in linear regression, if the equation does not contain a constant, we cannot make sure the expectation of disturbance is zero. So the OLS estimator is bias without a constant. Does it mean that the OLS estimator is unbiased if I add a constant in AR process?
Comment: Have you tried to write the equation for $y_t$ by substituting for the analogous expression for $y_{t-1}$ and then go on, recursively backwards? Then insert what you will have find in the formula of the OLS estimator, and all will become clear then.
Comment: I have tried it.It shows that both are biased while the AR process with a constant is more biased.
Answer: In the AR(1) model $y_{t}=\theta y_{t-1}+ϵ_t$, with, say $y_0 = \tilde y$, the OLS estimator is
$$\hat \theta_{OLS} = \frac {\sum_{t=1}^Ty_{t-1}y_t}{\sum_{t=1}^Ty_{t-1}^2} = \frac {\sum_{t=1}^Ty_{t-1}(\theta y_{t-1}+ϵ_t)}{\sum_{t=1}y_{t-1}^2} = \theta + \frac {\sum_{t=1}^Ty_{t-1}ϵ_t}{\sum_{t=1}^Ty_{t-1}^2}$$
So
$$E[\hat \theta_{OLS}]-\theta = E\left(\frac {\tilde yϵ_1}{\sum_{t=1}^Ty_{t-1}^2}+\frac {y_1ϵ_2}{\sum_{t=1}^Ty_{t-1}^2}...+\frac {y_{T-1}ϵ_T}{\sum_{t=1}^Ty_{t-1}^2}\right)$$
The usual way of proving/examining unbiasedness when regressors are stochastic, is to use the Law of Iterated Expectations and calculate the expected value of the estimator conditional on the regressors:
$$E[\hat \theta_{OLS}]-\theta = E\left[E\left(\frac {\tilde yϵ_1}{\sum_{t=1}^Ty_{t-1}^2}+\frac {y_1ϵ_2}{\sum_{t=1}^Ty_{t-1}^2}...+\frac {y_{T-1}ϵ_T}{\sum_{t=1}^Ty_{t-1}^2}\mid \{y_0, y_1,...,y_{T-1}\}\right)\right]$$
All terms are included in the conditioning set (are "measurable" with respect to it) except the last one so we have
$$E[\hat \theta_{OLS}]-\theta = E\left[\frac {\tilde yϵ_1}{\sum_{t=1}^Ty_{t-1}^2}+\frac {y_1ϵ_2}{\sum_{t=1}^Ty_{t-1}^2}...+\frac {y_{T-1}E\left(ϵ_T\mid \{y_0, y_1,...,y_{T-1}\}\right)}{\sum_{t=1}^Ty_{t-1}^2}\right]$$
$$E[\hat \theta_{OLS}]-\theta = E\left[\frac {\tilde yϵ_1}{\sum_{t=1}^Ty_{t-1}^2}+\frac {y_1ϵ_2}{\sum_{t=1}^Ty_{t-1}^2}...+\frac {y_{T-2}ϵ_{T-1}}{\sum_{t=1}^Ty_{t-1}^2}\right] + 0$$
so we are back to unconditional expectations. But
$$E\left[\frac {\tilde yϵ_1}{\sum_{t=1}^Ty_{t-1}^2}\right] \neq \frac {E\left[\tilde yϵ_1\right]}{E\left[\sum_{t=1}^Ty_{t-1}^2\right]}=0$$
because $\epsilon_1$ is included also in the denominator, and the expected value cannot be applied separately. Likewise for the other expected values. So the bias is non-zero.
Matters get worse when a constant term is included, since then the sample averages of the dependent variable enter also the formula for the OLS estimator, strengthening the correlation that leads to the existence of bias.
If in the above expressions, instead of $y_{t-1}$ we write $x_t$ for some regressor that is assumed independent of all disturbances i.e. not only the concurrent one, then we can see why unbiasedness holds -and this is the assumption (stict exogeneity) that makes it happen, nothing less than that. From these expressions also one can see that assuming only that $x_t$ is independent of $\epsilon_t$, but possibly dependent of past disturbances, is not enough to make the estimator unbiased.

AR process with a constant


How to ignore compilation warnings when running phoenix server

Question: I'm trying to run phoenix server from the command line with iex -S mix phx.server but I keep getting warnings on compilation about unused variables.
Compilation failed due to warnings while using the --warnings-as-errors option
I don't care about these warnings as i am in the middle of development and these vars will eventually be used or tossed out.  I have tried passing -h and other sensible options, but none of them work and I can't find anything in the docs about how to get phx.server to pass or override options to the compiler.
I've seen these docs and they haven't helped

https://hexdocs.pm/mix/Mix.Tasks.Run.html
https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Server.html

I have tried passing the --no-compile option but this is a no-go since it leaves me unable to recompile during development.  I am currently using IO.inspect to call the vars and this seems to be "good enough" for me to pass the unused vars check, but I would rather be able to disable this flag in the compiler rather than littering my code with IO.inspect
Answer: The error message is pretty clear on that:

Compilation failed due to warnings while using the --warnings-as-errors option

You have this specific flag enabled on the compiler, it returns a non-zero exit code on warnings. Since you're not passing the option manually in the command-line, it's possible that it's being:

Set via an ENV variable (possibly by an Elixir version manager)
Being passed in a mix alias or task
But most probably it's hardcoded in your Mixfile under elixirc_options. You can disable it like this:
# mix.exs
elixirc_options: [warnings_as_errors: false]

On a side note, to get help on compiler options, you should use elixirc:
± % elixirc --help
Usage: elixirc [elixir switches] [compiler switches] [.ex files]

  -o                        The directory to output compiled files

  --help, -h                Prints this message and exits
  --ignore-module-conflict  Does not emit warnings if a module was previously defined
  --no-debug-info           Does not attach debug info to compiled modules
  --no-docs                 Does not attach documentation to compiled modules
  --verbose                 Prints compilation status
  --version, -v             Prints Elixir version and exits
  --warnings-as-errors      Treats warnings as errors and return non-zero exit code

** Options given after -- are passed down to the executed code
** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS
** Options can be passed to the Erlang compiler using ERL_COMPILER_OPTIONS

Also see: Get the compiler to exit if a compile-time warning is raised
Comment: adding `elixirc_options: [warnings_as_errors: false]` to `project/0` in `mix.exs` has no effect.
Comment: I understand why it's happening.  I need to know how to turn it off.
Comment: Then there's probably an env variable or mix alias that's passing it as a flag. Take a look at the env flags exported by your elixir version manager and all tasks/aliases defined by your application.
Answer: If you run mix compile --warnings-as-errors=false first, then you can run iex -S mix phx.server without issues as it will already be compiled and should just start up.


Select com Laravel/Eloquent

Question: Tenho o seguinte select no meu controller:
$turmaAlunos = DB::select('
    SELECT alunos.ST_ALUNO_ALU, alunos.ID_ALUNO_ALU
    FROM alunos WHERE alunos.ID_ALUNO_ALU NOT IN (
        SELECT turma_alunos.ID_ALUNO_ALU
        FROM turma_alunos
        INNER JOIN turmas ON turma_alunos.ID_TURMA_TUR = turmas.ID_TURMA_TUR
        WHERE turma_alunos.ID_TURMA_TUR = ?
    )
', [$id]);

Ele me retorna o que preciso, porém como stdClass e isso está me causando o seguinte erro na view quando tento percorrer com o foreach:
Undefined property: stdClass::$NM_MATRICULA_ALU

Minha view está assim:
@foreach($turmaAlunos as $turmaAluno)

         <input type="checkbox" name="alunos[]" value="{{ $turmaAluno->ID_ALUNO_ALU }}">
         {{ $turmaAluno->NM_MATRICULA_ALU }}
         {{ $turmaAluno->ST_ALUNO_ALU }}

 @endforeach

Como posso resolver isso?
Aproveitando, existe uma maneira melhor de fazer esse select sem precisar de uma subquery? E como eu faço do jeito que está sem ser com DB::select bruto?
Agradeço quem puder me ajudar!
Answer: Você precisa colocar a coluna NM_MATRICULA_ALU na sua consulta ao banco porque ela não está sendo retornada.
Muda a primeira linha do SQL para isso:
SELECT alunos.ST_ALUNO_ALU, alunos.ID_ALUNO_ALU, alunos.NM_MATRICULA_ALU
Comment: Erro primário esse meu :/
Muito obrigado!

Select com Laravel/Eloquent


android shell mkdir out of memory

Question: I use adb shell to access an Android 4.4.2 tablet through a USB connection.
When trying to create a folder in the internal storage (/storage/sdcard0) I get the error 'Out of memory'.
The device has 20+ GB of free space and also has a second sd card mounted as /storage/sdcard1 where the folder can be created just fine.
Both volumes are using msdos.
I tried fsck_msdos to /dev/block/vold/179:9 (the physical path) but found no errors.
Any ideas before factory resetting the thing?
Comment: Your sdcard0 might not have been mounted correctly. Maybe use

    `remount /storage/sdcard0`

and try it again?
Comment: This was really weird! I did a mount -o remount /storage/sdcard0 and worked as you suggested! Many thanks!
Answer: What suggested by Saehun was the correct answer but because I can't give the credits to him I close my own question. Thanks again Saehun!

android shell mkdir out of memory


Determine whether the given binary relation is equivalence relation

Question: $D$ is the binary relation defined on $R$ as follows: For all $x,y\in R,xDy\Leftrightarrow xy >0$.
Determine whether the given binary relation is equivalence relation and if it is, give the reason why, and if it is not, give the reason why as well.
I'm confused whether it's equivalence or not, considering that if you count $0$, then it won't be equivalence because $0\times0$ isn't $> 0$, but if $0$ isn't counted, then it is equivalence.
Answer: Whether a binary relation is a equivalence relation or not depends on the underlying set. As you said, if $D$ is defined on $\mathbb{R}$ it can not be a equivalence relation since $\langle 0, 0\rangle \not \in D$. If you change your underlying set to be $\mathbb{R}\setminus \{0\}$ you get a different relation.


How do I set up an Internet Search Path object store for ActiveX installs?

Question: To control which ActiveX components users are allowed to install, I was considering setting up a machine as an Object Store, and then setting up the Internet Search Path to divert requests for ActiveX installs from the web to the Object Store under my control.
I was wondering, do you know anybody who's set this up successfully, and is there any kind of guide on how to setup a machine as an Object Store?
Thanks.
Internet Search Path is described here:
http://msdn.microsoft.com/en-us/library/aa741211(v=vs.85).aspx#Internet_Search_Path
Answer: The functionality goes back to 1996, but I've never seen an implementation of the "object store" part of the system by anybody. I'm not aware of Microsoft releasing a reference implementation, either.
It wouldn't be a tremendously hard thing to write. It just needs to receive POST requests and return a redirection to the "best" object URL (based on the requested MIME type, CLSID, and taking into account the language and MIME types the client says it's expecting).
I'm not sure I see the advantage to using this functionality, though. What are you looking for?

Addt'l integrity assurance? You should only be allowing signed controls to install anyway, so it's not like having your own repository is going to allow you some addt'l measure of integrity assurance.
Decreased bandwidth utilization by clients? Downloads of controls are done over HTTP, so a caching HTTP proxy would minimize the bandwidth used in code downloads as effectively as redirecting clients to a central object store.

Using a central object store doesn't really do anything with client user rights, which is what I see as the major problem associated with control installation.
Presumably your users don't have "Administrator" rights so they can't install arbitrary code (machine-wide) anyway. If you have "modern" versions of Windows you can use the ActiveX Installer Service to "whitelist" ActiveX component installs for non-Administrator user. You can do this w/o a central object store.
IE 8 does allow non-admin ActiveX control installations (installing to HKEY_CURRENT_USER instead of HKEY_CLASSES_ROOT) but the user will only be able to mess up their own environment with these installations (provided, of course, that they don't have "Administrator" rights). This functionality can be disabled by Group Policy, as well.


Verify question about complements

Question: I have the following question:
$$A = \big\{ x\in \mathbb{R} \mid x^3 < x^2\big\}$$
Write the set definition of $A^C$.
If I understand correctly, the complement of $A$ would be anything not in $A$, therefore the definition of $A^C$ would simply be $x^3 > x^2$. Is this logic correct?
Comment: Not quite. It should be $x^3\ge x^2$.
Comment: You're very welcome :)
Answer: Well, if I understand you, the (universal) complement of any set is really just, assuming that $U$ is the universal set:
$$A^C=U\setminus A.$$
Your question, however, asks for the set definition of $A^C$. Then, simply put, the definition of $A^C$ would be would be:
$$A^C = \left\{x\in\mathbb{R}\mid x^3\geq x^2\right\}.$$

Verify question about complements


Carriage return in a bash variable

Question: I have a bash variable that ends with \r\n:
$ # Not the real command to get VAR's value, just an example
$ VAR="$(echo -en 'hello\r\n')"
$ hexdump -C <<< "$VAR"
00000000  68 65 6c 6c 6f 0d 0a                              |hello..|
00000007

I would like to drop the \r (the \n itself is correctly handled by bash).
I may trim it (VAR="$(tr -d '\r' <<< "$VAR")"), but that implies to run a process just for that task.
I tried using "Remove matching suffix pattern" bash feature, but cannot find which pattern to use (e.g., ${VAR%\r}, ${VAR%\x0d}, ${VAR%[\r]}—but neither of them does work).
Any idea how to drop the \r without creating a subprocess?
Comment: I did know that bash handles newlines, I did not know _how_.  Thank you for that info.
Comment: `the \n itself is correctly handled by bash` Hope you know, that `$(...)` _removes_ the newline, and variable does not have a newline, and then `<<<` _adds_ the newline to the input of `hexdump`.
Answer: Use the ANSI C quotes. With substitution, use
var=${var//$'\r'}

If you want to only remove the \r before the final \n, you can use
var=${var%$'\r\n'}$'\n'

i.e. you have to remove both the \r and \n, so you need to add the \n back.
Comment: Indeed, bash itself handles the final `\n`, so `${VAR%$'\r'}` does work.  Cf. also KamilCuk's comment.
Comment: @audeoudh: If you "have a variable that ends with `\r\n`", then you need to handle it yourself. If bash already removed the `\n`, you can just `var=${var%$'\r'}`.

Carriage return in a bash variable


Most reasonable solution to encrypting my paypal API credentials?

Question: I understand that i'm never going to be completely safe ... but paypal documentation seems to stress that I should never plain-text store the API credentials in my code (ie, web.config or in some C#).
1) What is a reasonable way to protect it... without going OVERBOARD?
2) If I encrypt the keys in my web.config... where do I store the encryption key... in the database, right? But then... the connection strings to my database are also visible in the web.config... so I don't understand why this is considered safety...
My website is an ecommerce store and will probably be on Arvixe business shared server.
Comment: I have one more question... please see comments to the answer below.
Answer: I would encrypt the Paypal credentials and store this encrypted information in the web.config. Do the decryption in a separate DLL and obfuscate this DLL. You could also protect this DLL with an external protection system but we have had issues in the past where protected libraries don't always work correctly in shared web environments.
Comment: so the encryption/decryption key should be store in the DLL also?
Comment: one more followupquestion -- I just downloaded Eazfuscator.net to obfuscate my dll.  I see it has a built in feature to obfuscate... and to DEOBFUSCATE. What prevents a malicious hacker from just taking my obfucated dll and de-ofuscating it to get my encryption key?
Comment: It will be extremely difficult for them to get to your DLL. If they can get access to your web site then there is nothing preventing them from modifying the code to accept deposits into another account or using it to steal credit cards. You can do some basic encryption of the decryption key in the DLL as well but if they get access to your libraries then that is the least of your concerns. If you are really concerned, you can use an off the shelf protection system to encrypt and lock down the obfuscated DLL and then test it with your hosting company.
Comment: thanks gray, I guess your right.  It seems what you proposed above is the "reasonable" solution without going too overboard...


G note on my guitar dies out quickly and has a 'thump' kind of noise

Question: I have a Merida DG 15-SPOMCES guitar. It is a nice resonant guitar but sadly the G note just doesn't sound as good as other notes especially on the 10th fret of the 5th string (is little better on the 5th fret of the 4th string and a little better on the third string - the open G). The note produces a 'thump' kind of noise and dies out quickly. Can anyone explain the reason for this and any possible remedy? I would be very grateful for any response! Thank you!
Comment: Have you inspected the nut and bridge?  There could be something caught near there that's deadening the sound.
Comment: only G and on three different strings in three different fret locations?
Comment: Yes, I had removed all the strings and checked inside I could find nothing suspicious. And yes, it is only G on the top three strings. The problem remains the same even if i change the scale of the strings, the problem just shifts to other frets.
Answer: The explanation matches exactly the phenomenon of a dead spot: a resonance in the guitar's neck that causes the mechanical impedance at that frequency to almost vanish, thus quickly draining that note's energy.
This isn't an issue many guitarists think too much about (though quite a few instruments have slight dead spots, they're usually not so pronounced that it's really a problem), but it's quite a common plague for bass, and people think a lot about good solutions. Most tricks amount to altering the neck's response through extra mass, generally at the free space on the headstock. The most crude implement for this is a woodworking C-clamp, but perhaps a capodaster will already do or a clip tuner – both are useful to have the anyway! There are also purpose-built weights available, Fender markets this under the name fatfinger.
The problem can also have something to do with a badly embedded truss rod; a luthier might be able to tell.
Comment: That seems the most likely problem to me too.  Another possibility is a resonance in the body that absorbs a particular frequency.  But I suspect this is more likely in violins and cellos than in guitars.
Comment: Would you suggest any solution to it!
Comment: @Amish: write `@ScottWallace` to reply to another commenter so they will then be notified. Or were you accosting me? In case this is due to a neck resonance, I already gave suggestions.


Why did they choose the diatonic scale?

Question: I have many questions, but all related to the necessity (if any) of the diatonic scale and the consequences of this choice. First: what are the reasons behind the choice of the Western Music diatonic scale with its definite pattern of tones and half-tones?
Who made this choice and why? Was this choice a limiting one? Does it rule out a wealth of non-diatonic music? Were they some important composers and instrument builders who used different scales or just wrote music out of the chromatic scale?
What if the music I have in my mind is non-diatonic? I know I can constraint it into a diatonic melody, but it is not the same music and can be more or less beautiful than the original, depending on the tune. It looks to me I can still harmonize it by combining notes. Yes, the number of combinations mathematically explodes, but the constraints of (ease of) playability on a certain instrument reduces all possible choices quite a bit. And of course it is up to the artist to choose for the better.
Are there other music theories not based on the diatonic scale? Why some out-of-scale chords sometimes embellish a melody better than in-scale chords? Does this make music theory arbitrary and useless because it is based on a too restrictive premise like the diatonic scale?
Comment: Have a look at [this question](http://music.stackexchange.com/questions/32971/why-does-the-scale-have-seven-or-five-notes-why-not-six) and maybe [this question](http://music.stackexchange.com/questions/23945/why-seven-principal-tones/23953#23953).
Comment: The diatonic scale (or family of scales) is popular in western culture, and central to things like the layout of the piano and the way pitches in standard notation are represented. However, though the diatonic scale is popular, there has been no overriding 'choice' made that applies to music in general; There exists a large body of music that can be seen as non-diatonic, and there are of course ways of thinking about music outside of analysing it diatonically. So while you ask *Who made this choice?* it might make this a more focused question if you could define who you think the 'who' is...
Comment: I don't have a source for this answer but maybe, at least in Western music, the other Greek modes fell out of use when more complex rules of harmony were developed. It is quite difficult for me to write modal music with just triads without the music sounding like it is either major or minor. The modes sort of collapse into one or the other (except Locrian). If you use extensions it is possible to write modal music but this was not common in the time period we are talking about to my knowledge.
Comment: syntonicC-- the Greek modes were long gone by the time Western music (as you mean it here) began to coalesce.  I think you meant Medieval modes.  If you did, then the rest of your comment is correct.
Answer: The question is a little confused. First, many cultures evolved completely different scale systems and conceive of music quite differently. There have been many attempts to tie in the diatonic and polyphonic system that evolved in "Western" music to the harmonic series. It's an interesting exercise and much can be learned (I would recommend Paul Hindemith's "The Craft of Musical Composition, Vol. 1" as a starting point), but I think we can safely spare ourselves at this point from constricting our thought in this way. With the tools we presently have at our command (particularly computers), I don't see any reason to bother with such speculation.
Comment: so you mean we should depart from the tradition and just use frequencies freely in making music, particularly electronic music, because we have the computer now? But can a computer sound like matter? I do not think equations of waves are solvable so that we can perfectly synthetize a drum, for example.
Comment: This is nothing new. This kind of tradition in Western music fell to pieces during the first half of the 20th century. You are wrestling with a question that is extremely old and has been studied quite precisely and extensively. Again, other cultures have very different traditions. You can do almost anything with a computer. Sampling, synthesis, algorithmic composition, sophisticated analysis, etc. The major limiting factors of the medium are difficulty and price, and that could change dramatically over the next few decades as prices continue to plummet and useable AI is improved.
Comment: @AntonioBonifati There are lots of instruments that can use frequencies freely - fretless instruments, instruments with slides, the human voice - if computers don't appeal.
Answer: Who made this choice of the diatonic scale? It probably goes back to primitive man chanting and beating drums.  It is inculcated in our minds.  It's hard to hum a tune that isn't diatonic.
Anyway, here's an interesting web site that seems to dig deeply into some of the questions you are asking.  It's long and has many references that may take you further along in your quest.
A lot to think about, but hopefully you will find some answers there.
The Creation of Musical Scales from a mathematic and acoustic point of view, Part II, by Thomas Váczy Hightower  http://vaczy.dk/htm/scales2.htm
Comment: Sorry, Gary, but you're just plain wrong.  The diatonic scale as we know it didn't develop until the early Renaissance and has virtually nothing to do with 'primitive man.'  Primitive cultures have at most pentatonic scales, and many of them have even simpler ones than that.  What we call diatonicism grew out of the Medieval modes through a process of increasing popularity of the Ionian and Aeolian modes, and decreasing popularity of the others.
Comment: To me it is very simple to think up pleasant non-diatonic tunes. It is true I can "transpose" such tunes into the diatonic structure and I am forced to do so every time I play a diatonic instrument, but the music I imagine, whistle and hum is hardly perfectly diatonic. I do not think there is something special to me. It is more probable that diatonicism is a man-made restriction and it is difficult to stick to it when using our "natural" musical instruments.
Comment: You have answered your own question.  The Western diatonic scale, at least the equal tempered version, is logical in providing tones that are more or less the kind of small-integer ratios you find in the natural harmonic series- but only more or less, and there are alternatives that are just as "natural".
Comment: I apologize for the tone of my comment immediately above.  I sound like I think I'm God or something and can't now edit to make it better.  Please imagine that I said "In my opinion" several times, especially at the beginning.  That's what I meant.  Sorry I didn't say it that way.

Why did they choose the diatonic scale?


Why c++ standard support function strftime but not strptime?

Question: Why C++ standard support function strftime() but not strptime()?  strftime() is available to change a time to string, but there isn't a function which can change a string back to time.
On Posix strptime() is available as a C-like function, using it need to take care of the potential problem of mixed C and C++ code.
Comment: I think the main reason is that not only it depends on the locale, but also you have tons of different methods to write a date in a given locale. That would have made either a big module, or an incomplete solution. (at least that's my 2 cents)
Comment: It is a Posix function.  Standards don't try to cater to specific operating system apis, even if they *look* like C library functions.
Comment: I almost +1'd this because it seems like a fair question (this functionality _doesn't_ exist in C, and it _does_ seem odd), but then I reconsidered because I don't think the question is actually answerable.
Comment: Good question. I think there are in general only few and bulky functions to serialize time and date in C++. If expected more from C++11 chrono
Comment: @LightnessRacesinOrbit Well, people involved in the C++ standardisation process *do* frequent SO, so they might have an (f)actual answer.
Comment: @Angew: Yes, true (you mean the C standardisation process), but the likelihood that even _they_ can back this up with any sort of meaningful rationale is fairly low.
Answer: I'm not a part of the standards committee, but here goes:
strptime is defined by the ISO/IEC 9945 documents (essentially the Single Unix Specification / POSIX). It is not part of the 9899:1990 or 9899:1999 C standards documents (and I don't think it is part of 9899:2011, though I can't be sure as I don't have that one in my possession yet).
Since the C++ standards only mandate levels of compatibility with their C cousin, you won't find strptime mandated by the 14882:1998 or 14882:2011 C++ standards documents.
Comment: It seems like that `strptime()` is not supported by the C standards, and the C++ standards just inherit it. But I'm still puzzled that why the C standars don't support `strptime()`... And then I found that function `std::time_get::get()` is added in c++11, and does similar thing like `strptime()`, and can be used with `std::time_put::put()` in pairs. Thanks for your answer any way.
Comment: The reality is that if strptime is available in the C environment, you should be able to use it from C++, you just can't count on it in a portable application (unless your only portability concern is to POSIX compatible platforms).
Comment: Yes, the compatibility may be a problem. Anyway I've tried and it works well on my Linux. But have to pay attentoin to that the C global locale must fit with the C++ global locale especially when it has no name.
Comment: Just curious, why the "unaccept" of this answer? In what way is it now not the best answer of the one answer listed? :)
Comment: It isn't a complete answer for me. The main reason is just that `strptime()` is not a part of C standards, hmmm, so why the C standards don't support it? Is there a more appropriate function for using with `strftime()`? Maybe there is not a reasonable answer for the question from the beginning... :)
Comment: Fair enough, maybe you should rephrase the question. The question "why does C++ not support the strptime function" is clearly answered here. "Why does C not mandate strptime" is a different question which you apparently now want answered.

As to why C doesn't mandate it, I can only hazard a guess, and it is alluded to in the comments to the question: date parsing is very locale & culture specific, and it is much easier to format a date with differing component orders than it is to parse a date unambiguously.
Comment: OK, maybe I will ask a new question for C, and thanks for your answer(guess?) for it. :)
Comment: Thanks! My answer was definitely not a guess (as least as far at the C90, C99, C++98, C++03, & C++11 standards go). I looked at them specifically, and they do not reference the ISO/IEC 9945 standard. But yes, a good question would be "Why does C mandate strftime but not strptime?"


Asp.Net Web API, Unity container, what happens to the object between sessions?

Question: Sorry for the title, feel free to update it if you have a better one.
Basically, I am writing a web api using ASP.Net Web API. I have configured a Unity container like this:
<code>string xmlFilePath = "some/path"

var unity = new UnityContainer();
unity.RegisterType<PlayerController>();
unity.RegisterType<IRepository, XmlRepository>(
    new ContainerControlledLifetimeManager(),
    new InjectionConstructor(xmlFilePath));
config.DependencyResolver = new IoCContainer(unity);
</code>
XmlRepository has some objects in it that represent the state of the xml file, and a timer that will write the state to an xml file every 60 seconds. This is to avoid having to rewrite the xml file every time the state changes, while limiting the maximum amount of state changes that can be lost to 60 seconds.
My question is this.. The unity container creates a singleton of XmlRepository that is available to my web api throughout every call. However, what happens to the object between calls? Is it in some serialized form somewhere, or does it stay in it's original form so my timer will continue to function?
Answer: Singleton objects stay in memory. In your case it will be managed by the Unity container. It will not be serialized and if you have started some timers on it they will continue to work ... until IIS decides to recycle your AppDomain. Now go and read The Dangers of Implementing Recurring Background Tasks In ASP.NET
Comment: That's all I needed to know. Thanks a lot!
Comment: No, that's not all you needed to know. I was still updating my when you typed your comment answer. Now take a look at my answer. The last sentence is very important.


split string by char C#

Question: I have a string that contain the following text:
[l=9;f=0;r=5;p=2]
There may be more than one:
[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]
I want to get the array of strings(for second example):
[l=9;f=0;r=5;p=2]
[l=9;f=0;r=6;p=2]

I tried this but it split not correctly:
Regex.Split(seat, "(?=])");

PS. regexp not mandatory.
Comment: U need to make it with `Regex` syntax? show us result you want to get
Comment: @harry180: the result shows in question, I want to get array
Comment: 1 dimensional array or 2 dimensional array? or maybe you want a `Dictionary`?
Answer: string input = "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]";
var list = Regex.Matches(input, @"\[.+?\]")
            .Cast<Match>()
            .Select(m => m.Value)
            .ToList();

Comment: @chridam: Yes, of course. Just SO say after 5 minutes, please.
Answer: The below pattern might help you use the Split option of Regex
string input = "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]";
string pattern = @"(?<=\]);";
Regex regex = new Regex(pattern);
string[] data = regex.Split(input);

Answer: "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]".Split(new string[] { "];" }, StringSplitOptions.None)

And then append "]" back to each item in the array...
Ugly but should work.
Comment: You should mention that then OP will need to add ] for his elements inside array
Comment: @niaher: no the first element will be equal `[l=9;f=0;r=5;p=2`
Comment: You're right, so appending the "]" should do the trick.. Not the most elegant solution of course.
Answer: Why don't you use regex capturing?
The pattern \[l=(\d);f=(\d);r=(\d);p=(\d)\] will capture the values in each array.
Example:
private static IEnumerable<dynamic> Match(string text)
{
    return Regex.Matches(text, @"\[l=(\d);f=(\d);r=(\d);p=(\d)\]")
        .Cast<Match>()
        .Where(m => m.Success)
        .Select(m => new { l = m.Groups[1].Value, f = m.Groups[2].Value, r = m.Groups[3].Value, p = m.Groups[4].Value });
}

static void Main(string[] args)
{
    foreach (var result in Match("[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]"))
        Console.Out.WriteLine("Setting: {0}, {1}, {2}, {3}", result.l, result.f, result.r, result.p);

    foreach (var result in Match("[l=9;f=0;r=5;p=2]"))
        Console.Out.WriteLine("Setting: {0}, {1}, {2}, {3}", result.l, result.f, result.r, result.p);
}

Answer: Here's a LINQ approach:
Func<string, string> process = s =>
    String.Format("[{0}]",
        String.Join("];[",
            s
                .Split('[')
                .Select(x => x.Split(']'))
                .SelectMany(x => x)
                .Where(x => x != "" && x !=";")));

At the very least it works. :-)
Use it like this:
var result = process("[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]");

Answer: In your code:
Regex.Split(seat, "(?=])");

Seems like you're just missing the actual semicolon, and a backslash for the brakcet, from your regex.  This works:
 string[] data = Regex.Split(seat, ";(?=\\[)");

split string by char C#


Pages are created for each image

Question: The Drupal 7.59 installation we have a new page for each uploaded image in the files directory. (It's been like this at least since Drupal 7.39 when I joined this project.)
If the image is awesome-photo-by-Robin.jpg, we will get www.ourdomain.com/files/awesome-photo-by-robinjpg. (The missing period before the extension is not a typo.)
The problem is that these pages get indexed by search engines, and because they have no content except header, image and footer, they get very low ranking and clutters our SEO results.
Obviously, these are automatically created during the upload process, where you have no possibility to disable or choose this. However, afterwards, one can go through /admin/content/file and edit the file and voilá, some information appears.

Removing the alias doesn't help, since the page remain anyway. (I also cleared the Drupal cache to make sure.)

Can these auto-generated pages be disabled somehow?
If they can't be disabled, we're considering adding Disallow: /files/* to the robots.txt file. Do you think that would work at all to amend this issue, or maybe cause other issues down the road?
What is the actual purpose of these pages?

This is the HTML that's surrounding the IMG tag, maybe it can give you any clues?

Answer: Don't think this is to do with core. Do you have the "File entity" module installed by any chance?
There's a permission of "View files" that anonymous users will have ticked in. If you untick that any of those /files/* will get access denied for annon users
Comment: Yes, we have the "File Entity" module. I disabled "View Files" for Anonymous Users and got a "You are not authorized to access this page." message instead of the image, so the page remains. No real improvement, I'm afraid, as the search engines will find that instead.
I've checked the module settings but haven't found anything that seem related to this.
Comment: Well the improvement is these pages essentially wont get indexed by google because its getting served a 403 unauthorised message but you could also add the robots disallow as mentioned previously. Your further options are: Dont use that module. Or hack that module up to not show it if its really causing you that many problems
Answer:
What is the actual purpose of these pages?

This is not the default behavior of Drupal. So clearly a previous developer created this functionality for some reason. So backup your site before tinkering with it.

Can these auto-generated pages be disabled somehow?

Yes, either it's being created via a custom module, or contrib module, or it's being created via Rules.
So you'll need to disable the module or rule (don't disable the rules module, but the actual rule listed in /admin/config/workflow/rules)
Based on your screen shot, perhaps these pages belong to a content type. So once you disable the module or rule that is creating them, if you found no purpose for them, and want to get rid of them for good, you can delete the content type.
Comment: I have a test environment to work with, so I can pretty much anything without risking the live site :-)
Comment: We don't have the Rules module.
I guess I could go through module by module and see if I can find the culprit (if any).
I haven't found anything in any of the Content Types that would produce this.
Comment: `I haven't found anything in any of the Content Types that would produce this.` Then I conclude that a custom entity was created then by the file entity module as mentioned in the other answer.

Pages are created for each image


Help with the application of Integration in relation to a proof of a theorem in F.A. Graybill

Question: I was trying to follow the proof of Theorem 4.2.1 of F.A. Graybill's Theory and Application of the Linear Model (1976). Here is an excerpt of the proof:
$$\eqalignno{\displaystyle m_{\mathbf{Y'}\mathbf{Y}}(t)&=\mathscr{E}[e^{t(\mathbf{Y'}\mathbf{Y})}]\cr
&=(2\pi)^{-n/2}\int_{-\infty}^{\infty}\cdots\int_{-\infty}^{\infty}e^{t(\mathbf{Y'}\mathbf{Y})}e^{-\frac{1}{2}(\mathbf{y}-\mathbf{\mu})'(\mathbf{y}-\mathbf{\mu})}d\mathbf{y}\cr
&=(2\pi)^{-n/2}\int_{-\infty}^{\infty}\cdots\int_{-\infty}^{\infty}\exp(-\frac{1}{2}[(1-2t)\mathbf{y'}\mathbf{y}-2\mathbf{y'}\mathbf{\mu}+\mathbf{\mu'\mu}])d\mathbf{y} }
$$
The integral exists for all $t$ such that $t<\frac{1}{2}$, and we use Theorem 1.10.1 to evaluate it. We obtain
$$m_{\mathbf{Y'}\mathbf{Y}}(t)=(1-t)^{-n/2}\exp\left(\dfrac{2t\lambda}{1-2t}\right),\, t<\frac{1}{2}$$
Theorem 1.10.1 states that if $a_0$ and $b_0$ are scalar constants,  $\mathbf{a}$  an $n\times 1$ vector of constants, $\mathbf{b}$  an $n\times 1$ vector of constants, $\mathbf{A}$ an $n\times n$ symmetric matrix of constants, and $\mathbf{B}$ a positive definite matrix of constants, then $\displaystyle\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}\cdots\int_{-\infty}^{\infty}(\mathbf{x'Ax+x'a}+a_0)e^{(\mathbf{x'Bx+x'b}+b_0)}d\mathbf{x}=\frac{1}{2}\pi^{n/2}\lvert B\rvert^{-1/2}e^{(1/4)\mathbf{b'B^{-1}b}-b_0}[tr(\mathbf{AB^{-1})-b'B^{-1}a}+\frac{1}{2}\mathbf{b'B^{-1}AB^{-1}b}+2a_0]$
I can follow the part where we substitute the following in Theorem 1.10.1: $\mathbf{x}=\mathbf{y}$, $\mathbf{B}=(\frac{1}{2}-t)I, \mathbf{b}=-\mathbf{\mu}$ and $b_0=\dfrac{\mathbf{\mu'\mu}}{2}$, but I can't follow how $\mathbf{A}$, $\mathbf{a}$ and $a_0$ were derived apart from the fact that $\mathbf{x'Ax+x'a}+a_0=1$.
Question: Can anybody help me work this out by giving me tips or examples where the equation in Theorem 1.10.1 is applied, or is there another approach?
Answer: The integral looked scary but when I got to really work through, it was not difficult at all. But it was lengthy. A minor correction was $\mathbf{B}=\frac{1}{2}(1-2t)I$. Now it should not be difficult to see that $\mathbf{A}=\mathbf{0}$, $\mathbf{a}=\mathbf{0}$, and $a_0=1$. From there, substitution is straightforward.


Python 2.7 How can I access objects created by one class from a list stored within a different class

Question: I'm trying to create a class User that stores certain attributes about a user, and another class User_Review that has a list of the objects/instances created by class User.
class User(object):
    user_objects = []
    def __init__(self, name, age)
        self.name = name
        self.age = age
        User.user_objects.append(self)

class User_Review(User):
    user_list = # here is where I want user_objects to exist

user1 = User('leila', 23)
user2 = User('carter', 43)

# so user_list = [user1, user2]

To answer zondo and juanpa.arrivillaga, the purpose of User is to create objects with basic information, and User_Review is a method where I'd like to be able to do things with the list of users through other methods in the User_Review class, such as have methods that adds/removes users to the end of the user list, or display certain information (name only, for example).
Comment: You could do `user_list = User.user_objects`, but why do you want two references to the same thing?
Comment: Why is `User_Review` deriving from `User`? Why use a custom class at all, and not just use a `list`???
Answer: For your purposes, I think you could instead of creating both the user_objects and user_list lists inside the classes, just retain the one inside User_Review (since you want their references to be stored in another class), and get rid of the one inside User, while simultaneously appending the created User object to the user_list from inside the __init__ method rather than user_objects.
In practice, this would look something like the following.
class User(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        User_Review.user_list.append(self)

class User_Review(object):
    user_list = []

user1 = User('leila', 23)
user2 = User('carter', 43)

Printing out the name of the first user using print(User_Review.user_list[0].name) correctly outputs carter.

This approach, however, seems fairly counter intuitive:

The User_Review class inherits User which to me does not make any logical sense, since you would not want to have a method such as change_age in User_Review if it happened to be implemented in User. You would however, want to be able to access the data inside each User object, which can be accomplished by just accessing the required User inside the list.
As it stands, User_Review serves no real purpose, exactly the same thing could be achieved by just a regular list; however, if there are plans for implementing methods that rely on data from multiple or all User objects created, then this might be a viable solution.

Other solutions to this problem could be creating the list inside the User class only, and just using User_Review to access that list and do the required actions. Or more complexly creating a separate class from these two dedicated to storing, organizing, and retrieving users to and from a database.
Comment: Thank you for the clear explanation! I have a much better understanding of how these two classes interrelate, and now realize that `User_Review` does not need to inherit `User` which makes things much simpler.
Comment: Wonderful! I'd suggest reading up a bit more on object-oriented programming to get yourself familiar with inheritance and how objects and other non-primitive values are stored in memory, in addition you could come across other useful stuff to learn about like polymorphism and encapsulation and all those other fancy words which will be required to develop any kind of usable system in the future. Good luck!


Using module_invoke() and render() causes PHP warnings

Question: From within a block, I've used the following PHP to add additional blocks inside it:
$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search);
print render($user_search);

When I do so, I get the following warnings:

Warning: Invalid argument supplied for foreach() in element_children() (line 6541 of /var/www/mysite.dev/public_html/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 5998 of /var/www/mysite.dev/public_html/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 6008 of /var/www/mysite.dev/public_html/includes/common.inc).

It appears that the problem is tied to the render() function as I can call print_r($content_search) and everything looks good, but I can't render the blocks without these warnings.
Answer: Blocks aren't render arrays, they're made up of a subject and content key.
You'll probably have better luck referring to those explicitly:
$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);

Comment: Thanks, that did it -- I've never run into that problem before.
Answer: try it like this:

$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);

or use another method:

$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($render_array);
print $output;


Full URL not working with php include

Question: So, I am trying to insert a file with a php include, but for some reason it doesn't work with the full URL.
This works:
<?php include 'menu.html' ?>
But this does not:
<?php include 'http://domainname.com/menu.html' ?>
Any ideas?
Comment: Is the server running on Windows?  If so, note the [warning](http://php.net/manual/en/function.include.php) *"Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled."*
Answer: include is meant to include and evaluate a specified PHP file. If you fetch it locally, it can be processed like PHP - if you fetch it through a full URL, you will get the resulting HTML (in theory ... you may get only an error).
Supporting Docs
include 'menu.php' //Internally process a PHP file to generate HTML

or
file_get_contents('http://domainname.com/menu.php'); //Fetch resutling HTML

Comment: Ahhhhh, gotcha. Ok. Yeah,I wasn't sure if it was that or something else
Answer: check php.ini -
allow_url_include
but I have to say, if you don't have really really good reason, please don't use it. It's one of the worst php weaknesses, serious security threat.
Comment: Why is this a security threat?
Comment: Because potentially anything from who knows where could be executed
Answer: Does your php.ini allow you to use remote files with include?
If it's on your own domain then it makes no sense to require the absolute URL, as this would cause the server to open a connection to itself to retrieve the file via HTTP when a direct file operation would be so much simpler.
Comment: Well, that's the thing. The dude who desinged the site before me thought it would be better to have the blog and the site (both wordpress) on two different installs and URL's. Then he made the entire menu static without using the wordpress menu functions. Blows my mind. Anyways, just looking for a simple solution to update the navigation in both places from one file.
Answer: Don't use absolute urls. Instead, try linking from the root directory.
Like this:
$path = $_SERVER['DOCUMENT_ROOT']."/layer1/layer2/layer3/";
include($path."file.php");

Answer: An include tag is meant to be used to reference other PHP script files. If it is not a script that you are going to be processing, you might want to look into using:
$FileContents = file_get_contents("http://www.domainname.com/menu.html");

Answer: Sounds like allow_url_fopen or allow_url_include or both have been set to 0 (disabled) in php.ini.
HTML should't be included in a PHP script, though. Other answers seem to address that issue as well.
Comment: I'm using it with and .htaccess file since the rest of the pages are .html files.

Full URL not working with php include


Alternative to Simplenews, or a way to send formatted mailing lists to subscribers?

Question: I have installed simplenews on Drupal 7 but it seems all the related modules: Simplenews Content Selection (to build up the newsletter using nodes or views) and Simplenews Template are outdated (Drupal6).
Is there another way to use the nodes in the sites or at least creating a template to reuse with this module?
Or is there a way using other mailing list modules or custom code to build up newsletters from nodes?
br. onirio
Answer: Check out the new Newsletter module.
<code>Features

Multiple newsletters lists configurable on terms, not vocabularies
Plain text or HTML out of the box
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on single page.
Users can customize the terms in the list they subscribe to
Custom template per list
Statistics (CTR and Open-Rate)
Drupal 7 only
</code>
Comment: As far as you know, does Newsletter module supports the the newsletter build up using nodes or views abd views?
Comment: I have only kicked the tires on it and haven't dug deep. I know it's highly configurable though. It's worth a look.
Comment: I tried Newsletter but it seems it cannot save the newsletters only their template.
Comment: I know the module is getting a lot of development attention right now and the maintainer is currently very responsive to feedback, I would put in a support/feature request and see what you get back.
Answer: This method (or something similar) worked in D6, I guess you can still do it in D7: Add a reference field to your newsletter, load the referenced nodes in the preprocess function for your template using node_load_multiple, and render them using as a list of teasers using node_view_multiple.
Another approach would be to build a view and attach it to a newsletter node using Entity View Attachment. However that's just a thought - I haven't tried the combination of Simplenews and EVA myself.
Comment: I think I managed to attached a view to my content/content type using either Viewsfield module or 1 line of code: print views_embed_view('myViewName'), I can see the view in the preview but I receive a blank email.
Comment: If you add a field, make sure it's visible on the "manage display" page for the "newsletter" view mode (probably `/admin/structure/types/manage/simplenews/display/teaser`). If you add code directly to the template, make sure you're overriding the right template (I think it is `simplenews-newsletter-body.tpl.php`).
Comment: That is the problem: when using views insertions in newsletter the newsletter content won't pass through the simplenews-newsletter-body.tpl.php template.


How to add different icons for different links in xml loop for blogger template navbar?

Question: I am creating a social icon bar for blogger template using font awesome and bootstrap.how can I add different icons for a different link in the following XML loop?

<data:link.name/>

This loop adds the link but with the same icon for all social media links.
Comment: where does the data come from and how do you put it in the loop?
Answer:


Subtract equations: Confusion about what is meant here

Question: I am referring to
this document on Backlund transformations.
In this paper, one has equations (50),
$$
\begin{align*}
(w_1+w_0)_x&=2\lambda_1+\frac{1}{2}(w_1-w_0)^2\\
(w_2+w_0)_x&=2\lambda_2+\frac{1}{2}(w_2-w_0)^2
\end{align*},
$$
and equations (51),
$$
\begin{align*}
(w_{12}+w_1)_x&=2\lambda_1+\frac{1}{2}(w_{12}-w_1)^2\\
(w_{21}+w_2)_x&=2\lambda_2+\frac{1}{2}(w_{21}-w_2)^2
\end{align*},
$$
Then it is said:

subtract the difference of eqns (50) from the difference of eqns (51) to give
$$
0=4(\lambda_2-\lambda_1)+\frac{1}{2}[(w_{12}-w_1)^2-(w_{21}-w_2)^2-(w_1-w_0)^2+(w_2-w_0)^2]
$$

I do not understand what is meant.
What do I have to subtract from what?
I am confused.
Answer: $A=B$
$C=D$
$E=F$
$G=H$
Subtract the difference of first two equations  from the difference of second two equations means
subtract $A-C=B-D$ from $E-G=F-H$. So you get $(E-G)-(A-C)=(F-H)-(B-D)$.


How to extract top records from a column based on category information of another column

Question: Here is a problem I cannot figure out. How to find recipients received totally $1024 within top three transfers.
create table transfers (
    sender varchar not null,
    recipient varchar not null,
    amount integer not null
);

insert into receivers values ("TFC", "Apple", 2014);
insert into receivers values ("TFC", "Google", 100);
insert into receivers values ("TFC", "Google", 345);
insert into receivers values ("Facebook", "Facebook", 834);
insert into receivers values ("Facebook", "Google", 56);
insert into receivers values ("VMware", "Google", 12);
insert into receivers values ("VMware", "Google", 300);
insert into receivers values ("Google", "Facebook", 20);
insert into receivers values ("Google", "Facebook", 100);
insert into receivers values ("Google", "Facebook", 1000);

P.S.
I was able to find the solution.
The difficulty is how to get top amount records based on name. Instead of construct completed query, actually there are nice functions for it.

In postgresql, fucntion OVER (PARTITION BY) is specially for this problem.
In mysql, it is a bit harder, but you can use functions such as
group_concat + substr, substr to combine records need to be sorted,
then group_concat to inner sort.
Comment: Are looking to hire someone to do this for you?
Comment: Stack Overflow is not here to do your homework for you.
Comment: What dbms are you using?
Answer: First, get the top 3 transfers for each recipient based on amount and then check if the SUM >= 1024:
SELECT
    t1.recipient
FROM transfers AS t1
WHERE (
    SELECT COUNT(*)
    FROM transfers t2
    WHERE
        t2.recipient = t1.recipient
        AND t2.amount >= t1.amount
) <= 3
GROUP BY t1.recipient
HAVING SUM(t1.amount) >= 1024
ORDER BY t1.recipient;

Comment: Excellent solution! How to understand the nested sub query within first WHERE? I try to figure it out but I can't find a good way to show what is going on inside.
Comment: Looks like there is a small bug. When trying `SELECT t1.recipient, t1.amount
FROM transfers t1
WHERE (SELECT COUNT(*) FROM transfers t2 WHERE t2.recipient = t1.recipient AND t2.amount >= t1.amount) <= 3;`  Only 2 records from 'William' was included


How to pass unicode string from C++ to delphi?

Question: Ive found many topics about passing from Delphi to C++ but still confused about.
std::string s1(" look  here ");

What is the correct way to pass it to a delphi code?
none of this is not working, producing wrong chars
char * s = (char *)s1.c_str();
Call_Delphi_func(s);
.......
Memo1.Lines.Add(UTF8String(PChar(pointer(s))));

Comment: Have you tried `std::string s1(u8" look  here ");`?  It's possible you're running into source encoding issues and `s1` doesn't end up encoded as UTF-8 if you don't explicitly tell the compiler it should be.  You could also explicitly specify the bytes to use: `std::string s1(" look \xF0\x9F\x91\x86 here ");`
Answer: You did not say which version of Delphi you are using, but the fact that you use UTF8String the way you are implies that you are using Delphi 2009 or later. If so, PChar is PWideChar (wchar_t* in C and C++). Use PAnsiChar (char* in C and C++) explicitly instead, and get rid of your unnecessary Pointer typecast:
std::string s1 = u8" look  here ";
char * s = const_cast<char*>(s1.c_str());
Delphi_func(s);

procedure Delphi_func(s: PAnsiChar); stdcall;
begin
  Memo1.Lines.Add(UTF8String(s));
end;

Alternatively, use std::wstring with PWideChar instead:
std::wstring s1 = L" look  here ";
wchar_t * s = const_cast<wchar_t*>(s1.c_str());
Delphi_func(s);

procedure Delphi_func(s: PWideChar); stdcall;
begin
  Memo1.Lines.Add(s);
end;


SQL – What's the difference between this two codes?

Question: select sex, id from qualification where cid = ('Male' or 'Female')

vs
select sex, id from qualification where cid = 'Male' or cid = 'Female'

The first code would generate all of the items while the second gives what I want.
In a sense, we can't have or in a brackets for sql?
Comment: welcome to stackoverflow! wouldn't `('Male' or 'Female')` will resolve to `false`?
Comment: In a sense, we can't have or in a brackets for sql? - CORRECT the shorthand equivalent of your second query is cid IN('Male' , 'Female')
Comment: See http://sqlfiddle.com/#!9/9b35938 ('Male' or 'Female') is evaluated to 0
Answer: MySQL normally cast a value to another type for our convenience. One example of it would be casting a string into number.
MySQL can cast a string into a number by relying on the leading number of the said string. For example:
select cast('test' as signed); //returns 0
select cast('1test' as signed); //returns 1

This has been discussed before on another QA as Gelu pointed out.
On another note, true represented as 1 and false represented as 0 in bit.

Now let's examine your query:
select sex, id from qualification where cid = ('Male' or 'Female')

Lets resolve bit-by-bit on the where clause.
cid = ('Male' or 'Female')

The or operator accepts two boolean operand. On your case that would be 'Male' and 'Female'. Based on how MySQL handles casting, both 'Male' and 'Female' would return as 0 given they have no leading number at all.
cid = (0 or 0)

An or with both operand valued as false will result false. After resolving the ('Male' or 'Female') the where clause will be:
cid = 0

With the assumption that cid column contains string without any leading number at all, we can assert that all cid casted as 0. It will result your query to be rewritten as:
select sex, id from qualification where 0 = 0

Which also meant:
select sex, id from qualification where true

The query above will return all rows.
Edit:
Major restructuring on the answer. I feel the previous answer might be a bit confusing.
Comment: Related to the cast of the string to 0: https://stackoverflow.com/questions/22080382/mysql-why-comparing-a-string-to-0-gives-true


Problema com DLL

Question: Olá amigos sou iniciante em c++.
como posso impedir as pessoas de injetar uma dll no meu programa?
eles colocam uma dll com o nome IPHLPAPI na pasta de meu programa, então essa dll intrusa é carregada.
eu tentei fazer com que o programa feche quando essa dll intrusa fosse carregada, mas como meu programa usa a IPHLPAPI.DLL nativa do windows, então meu programa acaba fechando mesmo sem a dll intrusa.
Comment: As duas tem o mesmo tamanho?
Comment: olá, tamanhos diferentes, existe alguma forma de eu resolver isso usando o tamanho como restrição?
Comment: Creio que exista alguma forma de diferenciar os tamanhos e você pode fazer o controle por ai
Answer: Se as pessoas estão colocando para carregar no programa, isso é por quê no computador delas essa dll está em falta. Indico inicializar um download de att do NetFrameWork C++(Não sei qual é a versão, mas chuto que é a de 2015 por quê o Windows 10 está em falta de muitas dll's) assim o windows vai jogar essa dll no pasta padrão dela e tu será executado sem esbarrar um no outro.
Quanto a como o comando de att do NetFrameWorkC++, procura na internet como isso acontece no prompt, depois só adiciona a um código system do seu programa, para ficar automatizado.
Espero ter te ajudado...

Problema com DLL


Feature importances in random forest

Question: I'm using the random forest classifier (RandomForestClassifier) from scikit-learn on a dataset with around 30 features, 3000 data points and 6 classes. I'm using leave-one-group out as well as leave-one-out cross-validation.
RandomForestClassifier provides directly the importances of the features through the feature_importances_ attribute. I think the importance scores are calculated by averaging the feature importances of each tree which are retrieved by looking at the impurity.
Currently I'm fitting a random forest on the whole dataset and then I'm looking at the feature importances. Another option would be to retrieve the feature importances on each training set of each split of the cross-validation procedure and then averaging the scores.
Which one is the correct way to go?
Second, how can I calculate if one (or several) features have significant more importance than others (p-value)?
Comment: @MatthewDrury I disagree. Let's say I have different groups of features (i.e. features related to different concepts). It would be insteresting to know if the top performing features are all from the same group for example. If that is the case one could focus on that group and derive other features. I think it is always good to know and interesting which features contribute the most.
Comment: What are you using the importances to deduce?
Comment: @MatthewDrury I would like to gain insight into the features (i.e. which feature is most important) and then I would like to choose the five most important features (feature selection).
Comment: There's generally no reason to do feature selection in a random forest, at least statistically.  You shouldn't expect it to meaningfully improve the performance of the model (as long as you are properly using random forest).  I'll also point out that your reasoning is a tautology: "I want to use feature importance metrics from a random forest to tell what features are most important."  That sentence doesn't *mean* anything.  I'm sorry to be blunt, but it has no conceptual content.  WHY do you want to know that, what questions will you use it to answer?
Comment: @machinery you can't do that with RF feature importance, or at least not one shot of it. If one feature has been chosen, then another candidate feature is considered (also a good predictor). If the second doesn't add much information gain because of correlation with first feature, then it will be way down ranked in importance. Even though it might have been almost just as good as the first
Comment: @jonnor What do you mean not one shot? Should I calculate feature importance e.g. 100 times and take the average? I have fitted a random forest with 1000 trees. Each tree gives feature importance and then the average is taken over the 1000 trees which should perhaps average out the problem of correlation you mentioned. Moreover, I have excluded features having more than 90% correlation.
Comment: @jonnor Do you know another good way of calculating feature importance?
Answer: In Random forest, generally the feature importance is computed based on out-of-bag (OOB) error.
To compute the feature importance, the random forest model is created and then the OOB error is computed. This is followed by permuting (shuffling) a feature and then again the OOB error is computed. Like wise, all features are permuted one by one. Based on the increase (which is the score) in the OOB error, the feature importance is estimated. Higher this increase, higher the importance. These scores are then divided by the standard deviation of all the increases.
Apart from this, gini impurity measure can also used to estimate feature importance.
For more details refer this lecture note.

Which one is the correct way to go?

To compute the feature importance, you can use the complete dataset as the importance estimate is computed based on the OOB observations which are actually the left out observations during the bootstrap aggregation process for each tree in a Random Forest.

Second, how can I calculate if one (or several) features have
  significant more importance than others (p-value)?

Consider the feature importance values to compare the relevance of the features. To get p-value, statistical tests such as ANOVA (for parametric) or Kruskal-Wallis test (for non-parametric) could be used.

Feature importances in random forest


Is there a repository for localized common text in WinForms?

Question: I'm globalizing a Windows form application.
Is there a way to access common text in the current language for Windows?
For example, for the labels of OK, Cancel and Accept buttons; if I'm building a form that has an OK button I would like to use the same translation that Windows uses everywhere else for OK buttons.
I know I can store the translation for them myself, but Windows has to have them stored somewhere, do they give developers access to them?
Comment: File + Open + File, select c:\windows\system32\user32.dll.  LoadString() API.  Don't use this, MSFT promised to break it some day.
Comment: Worth linking to the Microsoft Terminonlogy DB @ http://www.microsoft.com/Language/en-US/Terminology.aspx
Answer: Yes, theoretically you could extract localized strings from Windows's internal system files. But don't do it. The advantages are far outweighed by the possible disadvantages. Your application shouldn't be reliant on undocumented implementation details. There's no reason to try and get this from Windows.
It's also worth pointing out that you can rename buttons (and every other control). That means it's too easy to break something if you're relying on some kind of string matching algorithm. There's no way to mark a button as being a certain "type" so that it will be automatically associated with a particular caption, and even if you could, this wouldn't cover every button present in a non-trivial UI. Also, as Joey's answer points out, there's nothing worse for the user than a partially localized UI. Consistency is the key, and you can't localize labels, group boxes, menus, tooltips, etc. this way.
Note, however, that Windows will automatically localize the captions for buttons on a message box (MessageBox). You don't have to lift a finger.
What's wrong with setting the form's Localizable property to True (you must do this at design time) and providing localized text for all of the controls in your application? Windows Forms actually has pretty comprehensive support for localization; the designer will automatically serialize all localizable elements to the form's RESX file. See MSDN: Walkthrough: Localizing Windows Forms. Make sure that you leave a sufficient amount of space to allow for the varying lengths of expressions in different languages.
Comment: I didn't know about that localizable property. That makes things way easier
Answer: This seems to have some information regarding that:

The USER32.dll is indeed the repository for localized string in Windows.
However, it does not not contains multiple string tables, only one.
I've access to some other localized Windows versions (pt-BR, es-ES, among others) and in every one of them the following positions are fixed from Window XP through Windows 7:
800 - OK
  801 - Cancel
  802 - &Abort
  ...

I'd still treat this as an implementation detail and nothing to rely on. Read Raymond Chen's blog for various horror stories of developers that took Windows-internal things for granted and eternal.
Also why not just have your own strings? You can easily put "OK" on the button yourself instead of grabbing it from the OS (and then localize it yourself if your application is intended to be localized). As a user I find it mildly confusing to have parts of an interface in another language than the rest (which would then invariably happen if your program has no localization, say, in German and is used on a German Windows machine – this would leave the interface in English with only the buttons in German).


KVM - Can't ping from physical network to virtual gateway

Question: Consider the following diagram:

This is the SERVER01 NIC's configuration:
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether d4:ae:52:c0:e6:c5 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.251/24 brd 10.0.1.255 scope global eno1
       valid_lft forever preferred_lft forever
    inet6 fe80::d6ae:52ff:fec0:e6c5/64 scope link
       valid_lft forever preferred_lft forever
3: virbr1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 52:54:00:b1:de:03 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.1/24 brd 192.168.100.255 scope global virbr1
       valid_lft forever preferred_lft forever

This server has the following routes:
default via 10.0.1.1 dev eno1 onlink
10.0.1.0/24 dev eno1 proto kernel scope link src 10.0.1.251
192.168.100.0/24 dev virbr1 proto kernel scope link src 192.168.100.1
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1

And the virtual network has the following XML:
<network connections='2'>
  <name>pxb-vn</name>
  <uuid>2445d9f0-e67c-4654-99ce-297642280b04</uuid>
  <forward mode='route'/>
  <bridge name='virbr1' stp='on' delay='0'/>
  <mac address='52:54:00:b1:de:03'/>
  <domain name='pxb-vn'/>
  <ip address='192.168.100.1' netmask='255.255.255.0'>
  </ip>
</network>

I want to server one service per each virtual server. For now it worked adding the following route to physical linux computers:
ip r add 192.168.100.0/24 via 10.0.1.251 dev eth0

And this route to virtual servers:
ip r add 10.0.1.0/24 via 192.168.100.1 dev eth0

But my company's network is a mix of Windows, Mac OS and Linux computers and I think it's not practical to configure each physical computer with this rule. As you can see, I have set a routed virtual network and I think it should be possible to ping to 192.168.100.1 from the 10.0.1.0/24 network but it's not working. I'm a KVM and networking newbie and I think I'm missing something.
Thanks in advance.
Answer:
I think it's not practical to configure each physical computer with this rule.

There are a bunch of alternatives to doing that, but for a small network they're pretty much all significantly more complicated than just setting up a static route everywhere.
The only one that might be simpler is to configure the default gateway for those physical machines to itself hold the route for the VM network.  This will result in some degree of inefficiency, as the packets travel from the physical machine, through the router, to the VM server, and onto the VM, rather than directly from the physical machine to the VM server, but the additional traffic and latency is unlikely to be noticeable in a small network.
Comment: setuo a nat might be easier
Comment: NAT has nothing to do with this problem.


Accessing multidimensional stdClassObject - Array

Question: I want to access the array properties I get as a SOAP-Resonse from a server. I use the php soapclient and and get the following output when using
$response = $client->$action($clientID);
$array = json_decode(json_encode($xml), True);

Unfortunately I cannot get access to the properties such as 'tid', 'answer' etc. How can I do this (I can either use php or c# where I import the result)
Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [0] => stdClass Object
                (
                    [tid] => 4103
                    [tdid] => 191
                    [qid] => 4103-1
                    [question] => Wie würden Sie Ihren Gesundheitszustand im Allgemeinen beschreiben ?
                    [answer] => Ausgezeichnet.
                    [score] => 100
                    [date] => 1558593404
                    [Fields] => Array
                        (
                        )

                )

            [1] => stdClass Object
                (
                    [tid] => 4103
                    [tdid] => 191
                    [qid] => 4103-2
                    [question] => Im Vergleich zum vergangenen Jahr, wie würden Sie Ihren derzeitigen Gesundheitszustand beschreiben ?
                    [answer] => Derzeit etwas besser als vor einem Jahr.
                    [score] => 75
                    [date] => 1558593404
                    [Fields] => Array
                        (
                        )

                )

Comment: `$array[1][0]->tid` what did you tried so far ?
Comment: Is it really the `var_dump($array);` that are you showing in your post ?
Comment: how have you tried to access the objects?
Comment: when I try this I get:

Notice: Undefined offset: 1 in C:\xampp\htdocs\tpsy.php on line 20
Notice: Trying to get property 'tid' of non-object in C:\xampp\htdocs\tpsy.php on line 20
Comment: that's probably because it doesn't exist in the first empty array
Comment: $tid = ($array[1][1]->tid); returns

Notice: Uninitialized string offset: 1 in C:\xampp\htdocs\tpsy.php on line 20
Comment: try `$tid = ($array[1][1])->tid` then
Comment: That returns:
Notice: Uninitialized string offset: 1 in C:\xampp\htdocs\tpsy.php on line 19
Comment: When I do a var_dump, I get

string(40000) "41031914103-1Wie würden Sie Ihren Gesundheitszustand im Allgemeinen beschreiben ?Ausgezeichnet.100.00000155859340441031914103-2Im Vergleich zum vergangenen Jahr, wie würden Sie Ihren derzeitigen Gesundheitszustand beschreiben ?Derzeit etwas besser als vor einem Jahr.75.00000155859340441031914103-3Im folgenden sind einige Tätigkeiten beschrieben, die Sie vielleicht an einem normalen Tag ausüben. Sind Sie durch I

etc...
Comment: I don't think you are var_dumping the right variable. What you've shown and the error you describe don't match, also what is $xml?  I think this needs editing
Answer: By looking at the result, can you try this?
// assuming $array is the array that you described

$tid = ($array[0])->tid;

because $array is an array of Objects, so i assume to get the data is as simple as using the property accessor ->. so $tid
you can learn more about php objects here
hope it helps!
-- EDIT --
it should be ($array[1][0])->tid. Because $array[0] is empty. you can use PHP's array_filter to remove all the empty arrays in $array.
$filtered_array = array_filter($array, function($el){
  return count($el) > 0;
});

$filtered_array should only have non-empty arrays in it. but do take note that array_filter preserves array keys.
then, you can get all the objects with foreach loops.
// say you want to put all tids in an array

$array_of_tids = [];
foreach($filtered_array as $array_of_objects){
  foreach($array_of_objects as $response_objects){
    $array_of_tids[] = $response_objects->tid;
  }
}

the simpler but more unreliable (since i don't know the API response's consistency), would be to just use the index.
$tid_of_first_object = ($array[1][0])->tid
// $tid_of_first_object would be '4103'

let me know if it's still not working!
Comment: $tid = ($array[0])->tid   returns:
Notice: Trying to get property 'tid' of non-object in C:\xampp\htdocs\tpsy.php on line 20

Same goes for $tid = ($array[0][1])->tid
Comment: hi @woofcheck can you try the edited answer? thanks! let me know if thing's are still not running.
Answer: You have an array of arrays of objects, so to access them you need to use $array[index/key][index/key] until you reach the level the object's at, then use []-> to access it.
you are presumably going to loop through so inside your loop you would need to do some checks such as is_array,isset,is_object, or a count to see if there's anything to do, it would look something like this:
foreach($result as $arr) {
    if(count($arr) < 1) continue;//there are no entries in this array
    foreach($arr as $obj) {
      if(isset($obj->tid)) {
          //do your stuff
      }
    }
}

You could possibly simplify this by pulling all the data our using array_column if you just need the tid, it depends what your goal is - but this should set you in the right direction.  You might also look at array_mapdepending on what you need


How to validate an AJAX form which uses CTools?

Question: I have a form which opens in a modal CTools window. The forms submits perfectly, but when I try to use the my_form_validate() function, it never goes to that function, it always go directly to my_form_submit() function? I have tried to "uncode" the CTools modal windows example provided with the module, but I am not able to decipher it.
Comment: How did you create the form? Is it created with a my_form() function? If so, it should validate through my_form_validate().
Comment: It is rendered with AJAX: return drupal_get_form('mymodule_form'); inside the callback function, and I have a my_module_my_form function as usual. The same form works perfectly if it is called outside the AJAX function, directly.
Answer: I have just discovered that I had mistyped mymodule_my_form_validate as my_module_my_form_validate. Your reply has made me look into the function and now it works perfectly. Somehow I thought the method was much more convoluted as involved AJAX. Sorry, this is very embarrasing. In any case, your reply saved me a lot of time.


How do I permanently assign my MIDI device to a specific channel or instrument in FL Studio?

Question: I have my AKAI MPKmini MIDI keyboard hooked up to FL Studio 12. When I focus one channel and play the keys, I hear that channel. But when I focus another channel, say, to adjust some settings, I want my keyboard to still play the first channel.
How can I create a permanent assignment between a MIDI device and a channel?
Some resources online mention a Fruity Wrapper setting. But what if you're not using Wrapper? Others mention a setting under the gear icon that no longer seems to exist in recent versions of FL Studio. Yet another post I found from 2006 outright says FL Studio doesn't support this feature.
Is there a way?
Answer: This is very surprising, but FL Studio only recently added support for this feature in 2016, for FL Studio 12.3 (release notes):

Lock MIDI notes to Channels - Right-click a Channel Button and select Receive notes from.

When you do this correctly, you'll see a lock icon appear next to the channel name:

Something key for me was selecting "All" for the MIDI channel instead of a specific channel. I thought that assigning the input and output of the MPKmini2 to channel 10 in the MIDI settings (shown above as well) would allow me to specific lock channel 10, but it doesn't appear to work. I had to select "All".


Center header logo in Bartik theme

Question: I am using the Bartik theme in Drupal 7.15 and would like to have the header logo centered rather than left-aligned, is there some little piece of CSS I can add in with drupal_add_css() that will center the logo image? I need it to center correctly based on the width of the header image, so fake centering just using left padding isn't an option.
Thanks in advance.
Answer: A rule like this should do it:
#logo {
  display: block;
  width: 100px; // width of the image
  margin: 0 auto;
}

Comment: That rule doesn't seem to center the logo, and also I don't know the width of the image because the logo will be changed by the admin relatively frequently.
Comment: Ah that's not much help then. I would try just making the container and the image itself (and maybe the wrapping `` tab) `text-align:center;`, that ought to do it
Comment: Putting in `text-align:center;` everywhere doesn't seem to do anything to the alignment of the logo image. I'm using Chrome 22.
Comment: You've probably got some other styles acting on the image already then, perhaps it's floated?
Comment: Wasn't floated, but I have got it working, thanks for your input with this.
Answer: Adding this CSS with drupal_add_css() makes the logo center:
#logo     { padding-left: 50%; }
#logo img { margin-left: -50%; }

Center header logo in Bartik theme


Is it possible to POST values to another page from the FORM SUBMIT function

Question: I have a module that allows authenticated users to book a "Facility" and then pay for it online. The module that facilitates the online payment is different from the booking module.
In the booking module I accept the details from the "authenticated" user in a form and in submit function I store the record in the DB with the following code
<code>$form['$source'] = array(
  '#type' => 'hidden',
  '#default_value' => 'obb',
);

$form['uv_amount'] = array(
  '#type' => 'hidden',
  '#default_value' => $amount_final,
);

$form['description1'] = array(
  '#type' => 'hidden',
  '#default_value' => 'OBB - Booking Charges for ' . $hall_type_code . ' ON ' . $arri_date,
);

$form['#method'] = 'post';
$form['#action'] = '/mymodule/pgi/confirm';
</code>
In the module that handles the payment gateway I pass these values to the payment gateway after calculating the mandatory HASH values etc (as per the payment gateway integration document)
During testing I figured out that the values are not being posted to the PG page. Is there a way to post the values to the PG page after I store the booking/reservation details in the form submit function? Or is there a better way of accomplishing this. Would appreciate any help.
Answer: It sounds like you are doing a multi step form (given the URL in your form is "confirm"). You don't want to be looking at $_POST values, you'll want to utilize FormAPI all the way through.
See for examples:
http://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/
http://jamesdavidson.io/blog/how-create-multi-step-form-drupal-7
http://www.webomelette.com/ctools-object-cache-multi-step-form