Can I calculate a 95% confidence interval with 20 samples of a measure?

Question: I am conducting a experiment that takes lots of time, and I want to report 95% CI of area under the curve (AUC) measures, is it possible to calculate this stat with only 20 samples?
Answer: Yes, in principle that is possible. Depending on the variability the CI may be so wide that it hardly tells you anything. You probably want to check how precise an answer you need.
Answer: The confidence interval depends on the distribution of these measurments,  just compute it on your sample and see whether it gives you a bound which is narrow enough for you.


Deducing the periodicity of basis functions from the periodicity of a particular linear combination

Question: Let $y_1$ and $y_2$ be linearly independent solutions for $$y''+q(t)y=0, t\in [0,\infty),$$ for some continuous periodic function $q(t)$ on $[0,\infty)$ with period $T$. Suppose that the given ODE has a  a non-trivial solution $y_*$ which is periodic with the same period $T$, then how can we calculate the value of $y_1(T)+y_2'(T)$? I feel the value is nothing but $y_1(0)+y_2'(0)$. But I cannot connect the periodicity of $y_*$ with the periodicity of $y_1$ and $y_2$. How can we use the fact $$y_*(t)=c_1y_1(t)+c_2y_2(t)=c_1y_1(t+T)+c_2y_2(t+T)$$ here?
Comment: See Floquet theory, not all solutions have to be periodic. But as one Floquet exponent is zero, and the coefficient of the first derivative is zero, there might be more information to be found.
Comment: This did indeed remind me of an older question: https://math.stackexchange.com/questions/3266352/yaxyx-0-quad-ax-is-continuous-function-with-period-t, for flavor a similar question is https://math.stackexchange.com/questions/2878686/existence-of-periodic-solution-of-a-2nd-order-homogeneous-ode, the basics of Floquet theory in https://math.stackexchange.com/questions/277255/periodic-differential-equation-proof,
Answer: By linear independence there exists a matrix $A$ with
$$
\Phi(T)=A\Phi(0),~~\Phi(t)=\pmatrix{y_1(t)&y_2(t)\\y_1'(t)&y_2'(t)}.
$$
By existence and uniqueness it follows that
$$
\Phi(T+t)=A\Phi(t),~~~\Phi(nT+t)=A^n\Phi(t).
$$
This just for completeness, it is not that important for this task.
By general Wronski theory we know that $\det\Phi(t)$ is constant, as $p(t)=0$ for the coefficient of the first derivative. Thus $\det A=1$.
That a non-trivial periodic solution exists implies that $A$ has one eigenvalue $1$, and thus that this is the only eigenvalue.
Now if it were $\Phi(0)=I$, the result $y_1(T)+y_2'(T)=trace(\Phi(T))=trace(A)=2$ would follow. But we only know $A=I+N$ with some nilpotent $N$, which might be non-zero


Qual é a diferença entre criar um método dentro do construtor ou dentro da propriedade prototype?

Question: Quando eu vejo o código JS de outros programadores alguns definem os métodos dentro dos próprios construtores outros definem os métodos na propriedade prototype como, por exemplo:
function Mouse() {
   this.btnLeft = function() { // Método no construtor.
       alert('Click 1');
   }
}

Mouse.prototype.btnRight = function() { // Método na propriedade prototype.
   alert('Click 2');
};

Qual é a diferença entre definir um método para um objeto no caso dos dois exemplos acima, entre o construtor e a propriedade prototype? existe alguma relevância em usar um ou outro?
Comment: Isto responde à sua pergunta? [Qual a diferença entre utilizar o metodo da classe e o prototype Javascript?](https://pt.stackoverflow.com/questions/44191/qual-a-diferen%c3%a7a-entre-utilizar-o-metodo-da-classe-e-o-prototype-javascript)
Comment: https://pt.stackoverflow.com/questions/44191/qual-a-diferença-entre-utilizar-o-metodo-da-classe-e-o-prototype-javascript Olá, pelo que pude entender pela resposta que achei no link acima a grande diferença é em questão de memória e de unicidade. também tem esse texto bem legal do DevMedia sobre prototype que talvez possa lhe ajudar ! https://www.devmedia.com.br/prototype-javascript/7063 Espero ter ajudado !!
Comment: Não é a diferença principal, mas no primeiro caso o btnLeft só existirá para instancias, ou seja manipular a "classe" para sobreescreve-la será impossivel da forma que você fez, já no segundo o prototype é o objeto da "classe" (estou chamando de classe mas não é bem o nome correto), então o prototipe retorna um objeto que se modificado irá representar para todas instancias existentes. Tem um pouco mais sobre isso, mas vou ver se não tem uma resposta já mais completa sobre o assunto.
Comment: @Guilherme Nascimento, porque na propriedade `prototype` mostra os métodos definidos, mas não as propriedades não era para demostrar tudo? já que na propriedade `prototype` é definido as coisas que serão herdadas?
Comment: Não é só isso, é bem mais, como disse no prototype o comportamento é diferente, no primeiro código só existe em instancias, no segundo existe um objeto que representa todas instancias de uma classe e até na classe (não na instancia) existirá um "objeto" dentro que representa a interface do que você descrever.
Answer: Com o prototype, seus objetos compartilharam a mesma "tabela" de funções, (herdando as funções do prototype), enquanto que declarando as funções dentro do construtor ira criar ponteiro para cada tabela de cada instancia, permite você decidir com laços se declara ou não uma função, ou se ela vai ser diferente da de outra instancia, eles também poderão ser individualmente sobrescritos depois...
o prototype ajuda a padroniza e diminui o uso de memoria...embora seja bem pouco...
[Obj][Obj][Obj][Obj]
  v    v    v    v
[prototype (ponteiro para função_1) (ponteiro para função_2)]

[Obj (ponteiro para função_1) (ponteiro para função_2)]
[Obj (ponteiro para função_1) (ponteiro para função_2)]
[Obj (ponteiro para função_1) (ponteiro para função_2)]
[Obj (ponteiro para função_1) (ponteiro para função_2)]

então, o prototype seria o 'static' da classe, propriedades comum a todas as instâncias, como em uma linguagem C like..., mas como javascript é muito mais permissivo que uma linguagem compilada, é um pouco difícil comparar, espero ter ajudado..., embora parece um pouco confuso...
+OBS: propriedades também podem ser atribuídas ao prototype, uma vez que funções na verdade é que são tratadas como váriaveis em javascript.
oque torna o seguinte cenário possível:
var minha_string="string qualquer";
String.prototype.CONSTANTE_TEXTO = "TEXTO";
console.log(minha_string.CONSTANTE_TEXTO);
console.log("outra string".CONSTANTE_TEXTO);
//sim, os dois retornaram "TEXTO" ao console

e a adição de ganchos (Hooks) em codigos objetos já declarados, sem ter de acessar cada um, oque pode ser útil para descobrir como algum código funciona...
Answer: Completando a resposta
quando um objeto recebe uma mensagem (para acessar um atributo ou um método), primeiramente é verificado se tal propriedade existe no objeto, caso não exista, ele vai no prototype para ver se existe
quando você altera o prototype, voce altera todas as instancias de uma classe / função
quando voce altera no construtor, você altera apenas para aquela instância
function A(val) { this.my_func = function() { return val; }};
A.prototype.my_func = function() { return "default"; };

a = new A(10);

A.prototype.my_other_func = function() { return "other"; };

a = new A(10);
b = new B(20);

a.my_func(); // retorna 10
a.my_other_func(); // retorna "other"
a.my_other_func = function () { return 100; };
a.my_other_func(); // retorna 100

b.my_func(); // retorna 20
b.my_other_func(); // retorna "other"

Observe que:

a declaração de my_other_func foi feita após a instancia a ser inicializada e ainda funciona
ainda posso alterar a instancia a sem problemas alterando o seus métodos
alterações feitas à inst anão afetam a instância b


Python-polars: Create row per unique value in a pl.DataFrame column, columns with another, and values with a third

Question: I have a Polars DataFrame that looks like this:
d = {'id': ['N/A', 'N/A', '1', '1', '2'], 'type': ['red', 'blue', 'yellow', 'green', 'yellow'], 'area': [0, 0, 3, 4, 5]}
dp = pl.DataFrame(d)
shape: (5, 3)
┌─────┬────────┬──────┐
│ id  ┆ type   ┆ area │
│ --- ┆ ---    ┆ ---  │
│ str ┆ str    ┆ i64  │
╞═════╪════════╪══════╡
│ N/A ┆ red    ┆ 0    │
│ N/A ┆ blue   ┆ 0    │
│ 1   ┆ yellow ┆ 3    │
│ 1   ┆ green  ┆ 4    │
│ 2   ┆ yellow ┆ 5    │
└─────┴────────┴──────┘

I would like to do some sort of pivot or transpose operation so that each row is an id (excluding 'N/A') and there is a column for each type, and the value is the area. If no value is given, it should be zero. So in this case, the result should look like this:
      red   blue  yellow  green
'1'    0      0     3      4
'2'    0      0     5      0

How can I do this in Polars? I would rather avoid converting the whole thing into pandas.
Answer: In Polars, you can achieve the desired result by using the pivot operation. Here's how you can do it for your specific DataFrame:
import polars as pl

d = {
    'id': ['N/A', 'N/A', '1', '1', '2'],
    'type': ['red', 'blue', 'yellow', 'green', 'yellow'],
    'area': [0, 0, 3, 4, 5]
}

dp = pl.DataFrame(d)

# Remove rows with 'N/A' in the 'id' column
dp = dp.filter(pl.col("id") != "N/A")

# Perform the pivot operation
dp = dp.pivot('id', 'type', 'area', aggfn='first')

# Fill missing values with 0
dp = dp.fill_null(0)

print(dp)

Output:
shape: (2, 4)
┌─────┬──────┬───────┬──────┐
│ id  ┆ blue ┆ green ┆ red  │
│ --- ┆ ---  ┆ ---   ┆ ---  │
│ str ┆ i64  ┆ i64   ┆ i64  │
╞═════╪══════╪═══════╪══════╡
│ 1   ┆ 0    ┆ 4     ┆ 0    │
│ 2   ┆ 0    ┆ 0     ┆ 0    │
└─────┴──────┴───────┴──────┘

Comment: This worked when I changed `aggfn` to `aggregate_function`. Maybe we're using different versions. Thanks!
Answer: (df.pivot('area', 'id', 'type', None)
   .filter(pl.col('id') != 'N/A')
)

shape: (2, 5)
┌─────┬──────┬──────┬────────┬───────┐
│ id  ┆ red  ┆ blue ┆ yellow ┆ green │
│ --- ┆ ---  ┆ ---  ┆ ---    ┆ ---   │
│ str ┆ i64  ┆ i64  ┆ i64    ┆ i64   │
╞═════╪══════╪══════╪════════╪═══════╡
│ 1   ┆ null ┆ null ┆ 3      ┆ 4     │
│ 2   ┆ null ┆ null ┆ 5      ┆ null  │
└─────┴──────┴──────┴────────┴───────┘


Administrator User on Windows 2008 R2 server gets "access denied" messages for starting/stopping services

Question: I logged into a Windows 2008 R2 server as a domain user that is part of the Administrators group on the target computer.  Executing the following command, I get access is denied errors:
<code>$> sc stop ServiceName
[SC] OpenService FAILED 5:
Access is denied.
</code>
What is strange is, as the very same user, I can open up the Services GUI (Administrative Tools > Services) and start/stop the very same service no problem.  This appears to be happening for all services that I try to start/stop, and it happens as any "Administrative" user on this computer (with the exception of the local admin user, which I don't have the creds for in order to test).  Command line fails, but GUI works.
I also know that spelling of the service name is correct, because if I alter it to be something else, I get a different error ("The specified service does not exist...").  I do notice that I can change the casing of the service name (ServiceName vs SERVICENAME) and get access denied errors on both.
I get similar access denied messages when using "net start ServiceName" instead of the sc command.
Any idea what is going on here? Needing this to work for scripting purposes. The same scripts are working fine on a Win2003 server.
Answer: Looks like you have discovered why lots of people hate User Account Control.
You should right-click on the Command Prompt icon and select "Run As Administrator"; that will allow you to actually make use of your admin rights.
Comment: Then have a look at http://riosec.com/Windows-UAC-PsExec.
Comment: -h did the trick for me (as suggested in the linked article).  Thank you kind sir!!
Comment: Problem is .... I'm trying to script this for remote execution (with psexec) from TeamCity
Comment: Or just disable UAC on the remote system altogether. I've found "when something doesn't work, disable UAC" to be pure wisdom.
Comment: BTW, you don't need PSEXEC to remotely control a service; `sc` allows you to connect to a remote machine using the syntax `sc \\ stop `.
Comment: Thanks.  I use psexec because I'm executing the command as a specific user, and could not use RUNAS because I could not provide the password inline.
Comment: It happened to me even though I ran CMD as Administrator


Use of java -server option

Question: The Oracle documentation says:

-server
Select the Java HotSpot Server VM. On a 64-bit capable jdk only the
  Java HotSpot Server VM is supported so the -server option is implicit.
  This is subject to change in a future release.
For default VM selection, see Server-Class Machine Detection

Since, it is implicit with 64-bit JDK, we don't need to add this argument while running command java, am I right?
Further documentation here says that server-class machine is one with at least 2 CPUs and at least 2GB of physical memory. Is this still true/applies with JDK7u25?
As from the documentation it is understood that it improves the performance if -server option is used with server-class machine, I would like to know is there any other specific advantage?
Answer:
Since, it is implicit with 64-bit JDK, we don't need to add this argument while running command java, am I right?

Correct. If you're running a 64-bit JVM then it makes no difference if the user passed the -server option.

Further documentation here says that server-class machine is one with at least 2 CPUs and at least 2GB of physical memory. Is this still true/applies with JDK7u25?

In light of your first quote about 64-bit JVMs, this criteria would only be used for 32-bit runtimes.

As from the documentation it is understood that it improves the performance if -server option is used with server-class machine, I would like to know is there any other specific advantage?

As your first quote mentioned, -server enables the Java HotSpot Server VM. This means the JVM will do more aggressive just-in-time (JIT) compile optimizations. This is disabled for non-server-class machines because doing the optimizations could slow down the program too much, but with modern machines you often have cores to spare, so the optimizing JIT could be off running in its own thread while your program plugs along.
Comment: Thanks for reply. So do you mean with 64-bit JDK only 1 CPU and less than 2GB physical memory can satisfy the criteria of being a server-class machine? And if yes, where it is officially documented?
Comment: @ParagJ - Nope, I meant _this criteria would only be used for 32-bit runtimes._ The fact that the 64-bit JVM only supports the Java HotSpot Server VM means that's the _only option_, so even though the machine might not be "server class" it's going to be enabled anyway. I think their rationale behind this is probably that you'd be very hard-pressed to find a 64-bit machine with only one core ("cpu") and less than 2GB of RAM.

Use of java -server option


Is it okay to use large nested Data Structures in Java using Lists and Maps?

Question: I am currently working in a project where I need to use grouping concepts. Hence I need to use a large Map like this.
Map< String,List< Map < String,List< Map< String,List< String>>>>>> objLargeMap;

So My question is, Is it okay to use large nested datastructures like this. Will I get any issues like memory full exception or some other issues?
I have analysed other alternatives. But none of them seems to be working.  Please help me understand. It is also tricky to get data from the object. So far it is running fine. But I am afraid that there may be some trouble when it comes to production.
Comment: I think your code will be hard to read and ugly, but I don't forsee any out of memory errors assuming you have enough memory allocated to the JVM.  Maybe you could include the alternatives in your question?
Comment: I'll be a bit more upfront than Tim and say: "NO - DON'T DO IT!". Java is an Object Oriented language, and as such you should create Objects (nested - if needed) and use them. the memory allocation cost is negligible and the reward for making the code (way) more readable and easier to maintain is priceless!
Comment: `I have analysed other alternatives` ?
Answer: In order to improve readability etc, you should define beans wherever possible. So your expression could be:
Map< String,List> objLargeMap;

class A{
 Map < String,List>
 //getters setters
}

class B {
 Map< String,List< String>>
 //getters setters
}

You will not have memory issues as long as you have enough heap to hold all objects.
Comment: Yeah, readable code, good variable and method names, small classes... all of that is a must for a good long-term code :D
Comment: This approach will certainly make the code slower Yet, this is perhaps the right way to go. Unreadable code is more dangerous than slow code :)


Distributed storage system with offline/cold disks

Question: I'm looking for a storage system for replacing a custom built backup system. I have looked briefly at MogileFS and OpenStack Object Storage but I still don't know if any of these suits my needs since I need to archive disks offline when they're full.
Requirements:

Free.
Can handle 100M files up to a few MiB each.
Support offline/cold disks.
Supports multiple nodes at different locations.
Supports redundancy by storing files multiple times. E.g. "this file should be stored once in both datacenter X and Y. This file should be store only once and I don't care where."
Should use a custom API and not be POSIX filesystem compatible.
Should run in an Linux or Free BSD environment.

The hardest requirement is supporting offline/cold disks. This is due to that only a few disk can be online at a time. When they are full they will be replaced with empty disks and archived in a safe place.
Which software will fit my needs?
Answer: I specifically asked a disk drive vendor if they support disks that are not powered on and stored in a specifically designed environment in a closed shelf etc. they answered that this is an unsupported mode of operation and that you cannot rely on powered-off disks to be ever usable again in case you need them.
There are special devices that power-off disks when not in use called MAID (massive array of idle disks) specifically designed to handle that.
In any case you'll need an enterprise grade object storage system that does support ILM/HSM to implement that, but they are not exactly "free".
Comment: Good point. However, we have a very tight budget and we already own the servers and the 100+ disks that we're going to use so we basically have free hardware. Redundancy is based on multiple copies spread over multiple sites. That is good enough for us.


Should a module implementing a filter delete the Drupal variables it uses, when uninstalled?

Question: I checked some modules implementing an input filter, and (if not in few occasions) I have never seen the modules removing the  module_name_$format Drupal persistent variables when they are uninstalled.
Since a module should normally delete its Drupal persistent variables when it is uninstalled, is there a reason why an input filter module doesn't normally delete its own Drupal variables, for example because this is already done by Drupal?
Answer: A module should be responsible for cleaning up after itself when it is uninstalled. There is no reason not to do this, unless some other modules depend on those variables but I very much doubt this is a case. If they depend on a module they probably depend on the entire module, not just some variables defined by it.
I, for example, use htmLawed and out of curiosity checked the .install file; it does clean the variables defined in the format "module_name_format_%".
As a best practice you should drop all the tables and delete the variables defined by your module, doing this by implementing hook_uninstall in your .install file.

Writing .install files (Drupal 6.x)


Are there any clustering algorithms that do not exclude/impute missing data?

Question: From my understanding, clustering algorithms require complete data. Based on this, if there are missing values in my dataset I have two options:

Impute missing information using some sort of imputation method
Get rid of observations that contain missing values

Sometimes I believe neither approach is appropriate, as ignoring observations can remove a lot of important information (sometimes all information, if there is always 1 missing value per obs for example) - and imputation methods are not 100% accurate.
As such, are there any clustering methods that do not require either of these options? In other words, algorithms that use the partial information from observations that don't have complete values, without discarding them? (looking at the information they do have in common)
This would allow me to assign these observations to clusters without applying any imputation methods to the data.
Comment: Then NA, 2, 3, 4, 5 and 1, 2, NA, 4, 5 and some others are all equivalent. I doubt that you can make that consistent. Do you also want NA, NA, NA, NA, NA and 1, 2, 3, 4, 5 to be equivalent?
Comment: I don't know if it makes sense. I just gather that you have specific rules for NA so that you will tolerate one NA value but not five (in this example). Where do you draw the line and why? If you try this even on a simple toy example I have to guess that it will lead to contradiction. It's also hard to find out if someone has already coded up your rules unless you know exactly what they all are.
Comment: What do you expect an algorithm to do when it sees a missing value? if you can explain that, then you might do the same beforehand.
Comment: @NickCox I guess I want the algorithm to compute the distances based on the data points two observations do have in common. For example, (1,2,3,NA,5) and (1,2,3,4,5) would have a distance of 0, even though the first observation has a missing value
Comment: @NickCox I agree that the first two would be equivalent, since the pairwise comparisons are equivalent (2, 4 and 5). However, I don't want NA, NA, NA, NA, NA to be equivalent to 1, 2, 3, 4, 5. Does this make sense?
Comment: @NickCox thank you, that totally makes sense. I hadn't thought the exact rules through
Comment: I don't have a definitive answer: I am just curious about what you expect.
Comment: Note that a similar problem arises with, e.g., NA, NA, NA, 4, 5, 6 and 1, 2, 3, NA, NA, NA. These would be equivalent of you just ignore missing values.
Comment: Why do you want to avoid imputation? Are you aware of modeled imputation and multiple imputation methods? (You can do something like K-means on multiply-imputed data and still come up with clusters in spite of the identifiability issues.)
Answer: In k-means, you can ignore the missing attributes both when computing the cluster assignment and when recomputing the cluster averages. But of course it only works for continuous data.
In k-modes you could likely do the same - skip the missing value when finding the best assignment, as well as when finding the mode.
Implementing them with support for NAs is a mess, and will make the code much slower, so people didn't do it. You'll have to do it yourself. There are a number of ugly corner cases, too: what if all points assigned to a cluster have NA in the same attribute?
For many other methods you need to provide a distance function or matrix. So you "just" need to decide how to compute this. Beware that certain approaches (such as skipping attributes in the all-NA case) cause problematic points to become too central and violate the triangle inequality. Most clustering algorithms don't require the triangle inequality though. But imputation is an easy way that doesn't have this problem.
Last but not least, you could do uncertain clustering. For points with missing values, you assume some prior distribution over the possible values, then do several runs to find the most likely assignments. Similarly, you could model a distribution over the distances. But this is quite complicated. The easiest way is to perform some kind of "random imputation" many times and find the consensus clustering.
Answer: Some clustering algorithms rely on the Expectation-Maximisation (EM) algorithm and its variants, e.g. k-means (deterministic- partition clustering), Gaussian mixture models (probabilistic, model-based clustering), etc. In these, the cluster membership of the observations are regarded as the latent variable and a version of the EM algorithm is applied to find maximum likelihood or maximum a posteriori (MAP) estimates in the existence of these latent variables
There exist extensions of the EM algorithm that can cater for missing values. Have a look at this thesis for an example of such an extension.
As a final note, and as you allude to, it is crucial  to examine the reason for the absent values before trying to address the missing data problem. In general we want to discover if the data is missing randomly Missing at Random, (MAR) or Missing Completely at Random,  (MCAR), or if the absent values are related to the response data (Not Missing at Random, NMAR). For instance, deleting missing values may give biased results when the MCAR assumption is violated.
Answer: Say feature X1 may be missing. If X1 is categorical, you could add a missing level and proceed. If X1 is continuous, you could set it to the mean value of non-missing X1's and create a categorical variable X1_missing that is True only when X1 is missing.
This assumes a clustering algorithm that can handle categorical variables.
Comment: But that causes missing values to be highly similar. There is usually little reason to assume they are all similar. So you'd probably need to make them all unique levels. IMHO this causes more trouble than it helps.
Comment: They would be overly similar on N features that were missing + 1, which is sub-optimal, but anything that tries to assign non-similar values would essentially be equivalent to imputation, which the OP ruled out.
Answer: Perhaps using binary trees (CART, C4.5, whatever version you prefer) might be of help here. You train the tree with complete data and then drop cases to be classified and label them according to the leaf where they end. Trees have their own rules when a variable is missing (stop at the current node, go with the majority, randomize, etc.); and it may well happen that a missing value is not needed anyway, because the splits only use observed values of the case to be classified.
You may find about trees in many monographies, including The Elements of Statistical Learning.


Mudar a orientação dentro de um botão com icone

Question: Sou novo com Android Studio e estou tentando fazer um botão com ícone em cima, fiz o layout no figma segue a baixo.

Entretanto no Android Studio o ícone fica ao lado do texto segue abaixo a imagem do problema.

Codigo xml do botao.
<code>    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/btnCategoriaProdutos"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:backgroundTint="@color/lsenac"
        android:backgroundTintMode="add"
        android:textAlignment="center"
        android:textSize="15dp"
        android:textStyle="bold"
        app:icon="@drawable/ic_iconcategoriaprodutos"
        android:text="CATEGORIA PRODUTOS">

    </Button>

</LinearLayout>
</code>
Answer: Resolvido segue o codigo xml para o posicionamento do icone.
<code>    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/btnCategoriaProdutos"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:backgroundTint="@color/lsenac"
        android:text="CATEGORIA PRODUTOS"
        android:textAlignment="center"
        android:textSize="15dp"
        android:textStyle="bold"
        app:icon="@drawable/ic_iconcategoriaprodutos"
        app:iconGravity="textTop"
        app:iconPadding="35dp"
        app:iconSize="40dp">

    </Button>

</LinearLayout>
</code>
Comment: Seria bom deixar claro qual propriedade resolve o problema. Acredito que seja a `app:iconGravity="textTop"`


Json data list, array

Question: Here I have got problem:
OneCar -> when I take only one argument I can see value and everything is OK
but when I try take list of arguments in ListCar1 and ListCar2 I can see only null
I believe this is small mistake but I don't know how to fix it.
[HttpPost]
        public JsonResult DodajTematSave(string OneCar, string[] ListCar1, List<string> ListCar2)
        {
        }

Here is Json action

Correct answer:

Answer: You need to add the traditional: true parameter to the $.ajax call. Details can be found in this jQuery forum thread or in this answer.
Comment: Great answer, only this small thing and is okay :) many thanks :)

Json data list, array


Add JavaScript and css to page with nodes only if there is no tag in any of the nodes

Question: I wrote a module that adds javascript and css to a page with nodes of type 'rower', now I need to add javascript and css to the page only if there is no tag with id == 1503 in any of the nodes. I tried to do it myself but it does not work because the variable $containsOutletTag == TRUE only at last node. Can you please tell me how I can do this? Here's what I have for now:
<code><?php
function countdown_preprocess_node(&$vars)
{
  if ($vars['type'] === 'rower') {
    $containsOutletTag = false;

    foreach ($vars['field_product_tags']['und'] as $tag) {
      if ($tag['tid'] == 1503) {
        $containsOutletTag = true;
      }
    }

    if (!$containsOutletTag) {
      drupal_add_css(drupal_get_path('module', 'countdown') . '/src/countdown.css');
      drupal_add_js(drupal_get_path('module', 'countdown') . '/src/countdown.js');
    }
  }
}
</code>
Comment: Why don't you just set your JS to ignore the node if it has that value?
Comment: To add to what @Jaypan said, you should use the Drupal settings mechanism to pass values such as IDs from PHP to JavaScript, so as to keep your JS nice and clean.
Comment: Remove `$containsOutletTag = true;` and place the `drupal_add_...` code there.
Comment: This does not work for me, because I need to add javascript, only if neither node has no tag value $tag['tid'] == 1503
Answer: you shouldn't have use hook_preprocess_node as it gets fired on each node separately, so if only one of the node doesn't have that specific tag the css and javascript will be added to the page unless other nodes have, so rather than hook_preprocess_node use hook_preprocess_page and there you can find an array of nodes (use dsm function with devel module enabled to see variable structure) and you can iterate over that array and check for condition
Comment: Thanks for the answer, I tried hook_preprocess_page, but it does'nt work for me


How do I accept two different types of network connections using iptables

Question: I need to setup iptables for a mongodb database server, such that it allows only two types of INPUT connections:

one connection to port 27017, monogdb's default port, from our main web-app
one ssh connection from my main network, which has a different IP address from our web-app

The issue is that these rules needs to be chained.
Here's what I tried:
iptables -A INPUT -p tcp --dport ssh -j ACCEPT # allows all connections via ssh (port 22)

iptables -A INPUT -s web-app-IP -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -d web-app-IP -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

iptables -P INPUT DROP
iptables -P OUTPUT DROP

The first line allows all incoming connections on port 22, while the second and third lines allow all connections from thw web-app-IP to and from the mongodb server only.
It seems that the first line is getting blocked by the second and third line. Is there a logical OR operator for iptables? If not, how do I setup the rules to allow for both of these types of connections?
Answer: You're not allowing ESTABLISHED connections out from ssh.  I'd go with a slightly simpler:
iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp --destination-port 22 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -s web-app-IP -p tcp --destination-port 27017 -m state --state NEW -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT DROP

Comment: Also, you might want to allow some ICMP in/out, but that's out of scope for this!
Comment: Could you please explain this line: `iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT` in particular, I don't understand the `-m` flag and what does it mean to be `ESTABLISHED` ? Thanks
Comment: `-m state` means "load the state module" (which is where we get --state from).  The `ESTABLISHED` state is packets in a tcp session we've already allowed (which we did with `--state NEW` on the ssh and 27017 lines)


chmod -R makes files in child folders ureadable for some reason

Question: I was adjusting the permissions when setting up some WordPress themes, and ran chmod 664 -R theme-dir/* It worked fine on the files in the root of the directory, but all the files in subdirectories now read like this when I ls -l:
?---------  ? ? ? ?            ? core_functions.php
?---------  ? ? ? ?            ? css
?---------  ? ? ? ?            ? custom_functions.php
?---------  ? ? ? ?            ? images
?---------  ? ? ? ?            ? import_settings.php
?---------  ? ? ? ?            ? js
?---------  ? ? ? ?            ? options_trim.php
?---------  ? ? ? ?            ? page_templates
?---------  ? ? ? ?            ? post_thumbnails_trim.php
?---------+ ? ? ? ?            ? shortcodes

I can't cd to any of the subdirectories, and I also can't delete them. I've never seen anything like this, anybody ever run into something similar?
Comment: @alexus no corruption, just perms
Comment: run `chmod -R u+rwX,go+rX,go-w theme-dir/*`
Comment: looks like corrupted file system..
Comment: @dusan.bajic That worked, thanks. Still no idea why it happened in the first place though.
Comment: I think I saw something like that when I did chown 644 (or whatever) versus chmod, but I really don't feel like testing again on a working system
Answer: Accessing the contents (or more specifically file metadata except for filename) of a directory requires that the directory have the execute bit set.
Your recursive chmod removed that permission, so you lost that access. If you are using the -R option of chmod is better to avoid using the numeric version of the permissions, and instead run (using your desired state as an example) chmod -R ug=rwX,o=rX. The capital X there means set the X bit only on directories or files that have at least one x set. Also you might want to use 644 (u=rwX,go=rX) unless you really need group users to write.
Comment: X means set X on directories _and files that already have execute permission for some user_ (which is usually what you want)
Comment: @tomclegg: Right. I updated my answer appropriately. It does seem odd that they never added a true directory specific version, or even better a pre-operation letter (like the u, g, o, or a) that means apply this change only to directories.
Answer: From the Wordpress documentation:
If you have shell access to your server, you can change file permissions recursively by using the following commands:
For Directories:
find /path/to/your/wordpress/install/ -type d -exec chmod 755 {} \;

For Files:
find /path/to/your/wordpress/install/ -type f -exec chmod 644 {} \;

Comment: I've noticed in more security sensitive environments (Magento and Health Care Systems recently) that vendors and open source systems are moving to recommending ONLY using the file method since it gives you kite granular control over the above condition and also allows fine grained control of application of setuid, setgid and also the infamous "sticky bit". It probably is more work to map this out for this use case but the bet answer is always the most secure method that achieves the desired outcome. I believe Security should always be Feature #1 if its possible to afford it.
Comment: An overkill for this particular problem, but very useful in other cases :)


Como paginar um array Laravel 7?

Question: Existe alguma maneira simples de paginar um Array em Laravel?
Eu tenho um array $atendimentos que data uma pesquisa faz o retorno do tipo:

Até a versão 5 existia o método
Paginator::make($atendimentos, count($atendimentos), 10);

No qual passava o array, o tamanho dele e o numero de registro que você queria por pagina. Entretanto ela foi retirada e pesquisei muito, mas não encontrei nada nas nova versões.
Editado: Eu estou usando no sistema LengthAwarePaginator no resto do sistema e imagino necessário neste caso também, pois meu array de $atendimentos vem de uma pesquisa. Porém se houver alguma maneira com o Paginator aceito sugestões.
Comment: @novic reaberto, fique a vontade para formalizar uma resposta, apesar de acreditar que a pergunta precisa de esclarecimentos, pois tem casos que terá que ser  `Illuminate\Pagination\Paginator` e outros `Illuminate\Pagination\LengthAwarePaginator`
Comment: https://laravel.com/docs/8.x/pagination#manually-creating-a-paginator tem sim
Answer: Na documentação do Laravel, ainda Paginator como mencionado na sua pergunta, no caso da edição foi especificado LengthAwarePaginator, então crie uma instância seguindo todo o namespace que é descrito na documentação:
Ressalvas:

1 - a variável $atendimentos só deve vir o total de itens que serão apresentados na sua View (pode ter filtros e ordenação);
2 - a variável $atendimentosTotal é a quantidade geral de registros (pode ter ou não filtros e está bem relacionado ao item 1, só que difere porque aqui é o total de registro e no item 1 é a parte que vai ser apresentado geralmente demonstrado pela pagina atual do item 4);
3 - a variável $atendimentosTotalPorPagina é o count($atendimentos) e;
4 - a variável $pagina é o número da página atual.

Código:
$page = new \Illuminate\Pagination\LengthAwarePaginator(
    $atendimentos,
    $atendimentosTotal,
    $atendimentosTotalPorPagina
    $pagina
);

Como é manual tem que calcular essa variáveis antes de passar nesse classe para que ela organize todas as informações e te apresenta corretamente os dados.
Referencias

LengthAwarePaginator
Pagination
Comment: Tem como exemplificar a sua variavel atendimentos? tem como colocar na pergunta?
Comment: https://www.php.net/manual/pt_BR/function.array-slice.php @PauloMartins
Comment: @PauloMartins porque você não faz direto na `builder` do seu Eloquent?

Como paginar um array Laravel 7?


Alinhamento de imagem responsiva com Bootstrap

Question: Estou com dificuldade de alinhar ao centro uma imagem responsiva do Bootstrap.
Minha imagem está com a classe (.img-responsive) devidamente aplicada e inserida dentro de uma row e duma div com a classe .col-md-12.
No momento que aplico a classe .img-responsive, a classe .text-center deixa de fazer efeito e a imagem fica alinhada à esquerda.
Alguém consegue me dar uma ajuda? Desde já agradeço.

Answer: Isso acontece porque a class .img-responsive adiciona a propriedade - display:block; à imagem.
Para resolver isso e fazer com que um elemento com display:block; seja alinhado ao centro terás que adicionar ao mesmo uma - margin:0 auto;, que neste caso este estilo, será implementado à class - .img-responsive.
No meu entender estás a utilizar a class .text-center não só para alinhar a imagem ao centro mas principalmente para alinhar textos, certo? Então o que podes fazer aqui é criar o código CSS da seguinte maneira:
.text-center .img-responsive {
    margin: 0 auto;
}

Desta forma tudo o que estiver dentro da class .text-center será alinhado ao centro, e este estilo será apenas aplicado à class .img-responsive caso esta esteja dentro da class .text-center como é o que acontece no caso do teu código HTML, dando assim a opção de poderes usar a class .img-responsive livremente das duas maneiras, usá-la do modo padrão, ou centralizada adicionando a class .text-center como div parent para accionar a sua centralização.
Tens aqui um EXEMPLO ONLINE NO JSFIDDLE do código em ação.
Comment: Perfeito Chun. É exatamente isso. Muito obrigado pela ajuda.
Comment: Funcionou certinho para mim, Chun. Muito obrigado!


O que significa este trecho de código?

Question: Recentemente me deparei com uma pedra no sapato, estava eu indo comentar um código, mas percebi que estava enchendo linguiça ao comenta-lo, pois não sei qual é o real uso do código abaixo:
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
lblResolucao.setText(+d.width +" x " +d.height);

No caso é um código em Swing para capturar a resolução do dispositivo, mas eu não faço ideia do real motivo delas estarem ali (é meio confuso até para explicar).
Gostaria que vocês me explicassem as 2 primeiras linhas DETALHADAMENTE para que eu possa assim, realmente entender o código.
Answer: A Toolkit é uma super classe que contém diversas informações sobre os mais diversos tipos de janelas e frames em Java. Entenda como se ela contivesse diversas informações brutas sobre as janelas, como não é aconselhado acessar estas informações diretamente você utiliza outras classes para obter as informações refinadas desta primeira.
No seu caso você usa a classe Dimension para obter informações de dimensão da janela do seu dispositivo. Para mais informações acesse a documentação da classe Toolkit.
http://docs.oracle.com/javase/6/docs/api/java/awt/Toolkit.html
Answer: Leitura que se faz do código:
Na linha Toolkit tk = Toolkit.getDefaultToolkit(); você faz uso do método estático getDefaultToolkit() para retornar o Toolkit específico da plataforma, sendo Toolkit uma superclasse de todas as atuais implementações de Abstract Window Toolkit(AWT), e salva na referência tk, do tipo Toolkit.
Na linha Dimension d = tk.getScreenSize(); você acessa o método getScreenSize() do seu objeto tk, que retorna um objeto do tipo Dimension, que encapsula os valores width e height com a largura e altura da tela.
/*
 * Output:
Screen width = 1280
Screen height = 1024
 */

import java.awt.Dimension;
import java.awt.Toolkit;

public class MainClass {
  public static void main(String[] args) {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    System.out.println("Screen width = " + d.width);
    System.out.println("Screen height = " + d.height);

  }
}

Comment: AWT não é uma classe.
Comment: Certo. Vou corrigir. Esse erro foi uma tradução errada e equivocada do trecho "This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of the Toolkit class are used to bind the various components to particular native toolkit implementations. " da documentação da classe Toolkit.
Comment: Outra coisa, o que with e height encapsula? Ficou muito vago isso.
Comment: Corrigido. Encapsula valores de largura e altura da tela.

O que significa este trecho de código?


How to upload static files to a remote server in Drupal 7 instead of local filesystem?

Question: I've recently had to migrate from Django to Drupal 7 due to web server constraints. One of the aspects of my old Django setup that I would like to preserve is hosting static content like images and other media on a remote server as I have free access to a massive server for this purpose.
With Django, this was as simple as editing a line or two in the settings.py file. My search for how to do this in Drupal has so far been pretty fruitless. Can someone please suggest a relatively simple way of doing this automatically?
The website in question will have multiple contributors, most of whom will be non-technical, so this should be something that is handled automatically.
Comment: Did you end up figuring this out? Pretty surprised Drupal doesn't have a way to do this, as it's the first thing you'd need to do when you add a second Drupal instance to serve traffic. I've just posted http://drupal.stackexchange.com/questions/106638/unsafe-to-use-nfs-to-share-sites-default-files-between-many-drupal-instances, would you please take a look?
Answer: You should look into the CDN project.
I am think of implementing it myself, but have no practical experience to impart.
Answer: I have never seen it done like you're asking for using Drupal's settings file. However I've seen people (including myself) add a rule to the Apache virtual host for your local site that automatically detects links to images and makes Apache serve the images from your web host instead of your local host. That avoids having to download the images every time.
Answer: CDN module does the trick. You can just give the address of remote host in CDN module configs. You can also specify which files or paths need to be serverd from your remote host (i.e CDN).


encrypt/decrypt with rot13 using a lambda?

Question: I need to crypt/decrypt using a lambda and I got some problem with it. My function create_rot13() must not receive an argument, only my lambda should.
This my current code so far, not using any lambda as I couldn't find one (after several days of looking around). How to put so lines of code into it.
def create_rot13(message):
    crypted = ""
    letters = "abcdefghijklmnopqrstuvwxyz"

    for car in message:
        if car in letters:
            num = letters.find(car)
            num = num + 13
            if num >= len(letters):
                num = num - len(letters)
            crypted = crypted + letters[num]
    else:
        crypted = crypted + car

    crypted = crypted[:-1]
    return crypted

print(create_rot13("jbeyq"))
print(create_rot13("world"))

Anyone have tips or something to help me out to find the solution to my problem?
It should look sort of like that, except this 1 change only a number:
def create_rot13():
 my_fonction = lambda x : x + 13
 return my_fonction

coding = create_rot13()
print(coding(4))

Comment: Why do you need a lambda for this? Python's lambda is only really useful when you're passing a function as an argument to some other function (otherwise you could just use a nested `def`). It's also not clear why you need to write a function factory. That would make sense if the function returned by the factory was different each time, but ROT13 is ROT13.
Comment: It for a homework and its how we are forcing to do it haha, else I would do it in another ways for sure.. kinda why I ask for tip to find out a solution instead of the full solution haha. and I also use this code (with some modifications) for others encryption method
Comment: It is pretty fanciful in this day and age to describe Rot13 as encryption. Julius Caesar thought so, but that's 2000 years ago.
Comment: @user207421: just because it's bad encryption by today's standard doesn't mean it's not encryption. DES is still encryption, even though it's effectively broken.
Answer: Here's a simple one which (ab)uses the codecs module (and a lambda).  Note that you need the codecs module here instead of just a normal call to .encode('rot13') as you're doing a text -> text encoding.
import codecs
rot13 = lambda s: codecs.encode(s, 'rot13')

Here's some sample usage:
>>> rot13('foo')
'sbb'

Answer: If you want to do it with a lambda, then you need to capture the letters variable with the lambda and also use map. You want something like this:
def encode_rot13(message):
    offset = ord('a')
    result = map(lambda c: chr((ord(c) + 13 - offset) % 26 + offset), message)
    return "".join(result)

I use chr and ord so we don't need to keep around a string with all letters. The idea here is that we are getting an integer that represents the codepoint for any given character, so we can do some math instead of using find.
Answer: Here's my solution:
rot13 = lambda m: ''.join(chr(ord(c)+13) if 'a' <= c.lower() < 'n' else chr(ord(c)-13) if 'm' < c.lower() <= 'z' else c for c in m)

I just used it on this, which is precisely rot13-encoded:
import this
# output
print(rot13(this.s))
# same output

I'm making the lambda take a string and return a string. I'm doing this on a joined generator, and only rotating non-accented letters, regardless of case. My version accepts a rotation length and filters it for the [0-26] interval:
rot = lambda n, m: ''.join(chr(ord(c)+n) if 'a' <= c.lower() <= chr(ord('z')-n) else chr(ord(c)+n-26) if chr(ord('z')-n) < c.lower() <= 'z' else c for c in m) if 0 < n < 27 else ''

In order to use it, you need to pass the message and the number of letters to rotate. So, rot13 would be the same as a partial application on rot, such that rot13(message) == rot(13, message). You could then define rot13 like this:
rot13 = lambda m: rot(13, m)


hook_form_alter help (almost there!)

Question: There are two parts of a third-party module that I am trying to alter.

When the user clicks submit
When the user clicks reset

This is the function from that module.
function linkedin_user_settings_form($form, &$form_state, $account) {
  // Just fetch forms from submodules.
  $form['linkedin']['elements'] = module_invoke_all('linkedin_user_settings_page', $account);
  // We will need the account at submit
  $form['#account'] = $account;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );
  $form['linkedin']['reset'] = array(
    '#type' => 'submit',
    '#description' => t('Click here to unlink your LinkedIn account.'),
    '#value' => t('Unlink'),
  );

  return $form;
}

This is the code in my module.
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'linkedin_user_settings_form') {
    $form['#submit'][] = 'my_module_form_submit';
  }
}

function my_module_form_submit($form,$form_state) {
  // on submit do this
  drupal_set_message(t('You Saved'));

  // on reset do this
  drupal_set_message(t('You Reset'));
}

How can I check which button on the form has been clicked from the users?
Answer: You should be able to just copy what that linkedin code is doing in it's own linkedin_user_settings_form_submit submit function:
$op = $form_state['values']['op'];
if ($op == $form['linkedin']['reset']['#value']) {
 drupal_set_message(t('LinkedIn preferences have been reset'));
} else {
  drupal_set_message(t('LinkedIn preferences have been saved'));
}

hook_form_alter help (almost there!)


Solving constrained minimisation problem using unconstrained optimization of the generalized Lagrangian

Question: My textbook, Deep Learning by Goodfellow, Bengio, and Courville, says the following in a section on constrained optimization:

The Karush-Kuhn-Tucker (KKT) approach provides a very general solution to constrained optimization. With the KKT approach, we introduce a new function called the generalized Lagrangian or generalized Lagrange function.
To define the Lagrangian, we first need to describe $\mathbb{S}$ in terms of equations and inequalities. We want a description of $\mathbb{S}$ in terms of $m$ functions $g^{(i)}$ and $n$ functions $h^{(j)}$ so that $\mathbb{S} = \{ \boldsymbol{\mathcal{x}} \mid \forall i, g^{(i)}(\boldsymbol{\mathcal{x}}) = 0 \ \text{and} \ \forall j, h^{(j)} (\boldsymbol{\mathcal{x}}) \le 0 \}$. The equations involving $g^{(i)}$ are called the equality constraints, and the inequalities involving $h^{(j)}$ are called inequality constraints.
We introduce new variables $\lambda_i$ and $\alpha_j$ for each constraint, these are called the KKT multipliers. The generalized Lagrangian is then defined as
$$L(\boldsymbol{\mathcal{x}}, \boldsymbol{\lambda}, \boldsymbol{\alpha}) = f(\boldsymbol{\mathcal{x}}) + \sum_i \lambda_i g^{(i)} (\boldsymbol{\mathcal{x}}) + \sum_j \alpha_j h^{(j)}(\boldsymbol{\mathcal{x}}) \tag{4.14}$$
We can now solve a constrained minimisation problem using unconstrained optimization of the generalized Lagrangian. As long as at least one feasible point exists and $f(\boldsymbol{\mathcal{x}})$ is not permitted to have value $\infty$, then
$$\min_{\boldsymbol{\mathcal{x}}} \max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) \tag{4.15}$$
has the same optimal objective function value and set of optimal points $\boldsymbol{\mathcal{x}}$ as
$$\min_{\boldsymbol{\mathcal{x}} \in \mathbb{S}} f(\boldsymbol{\mathcal{x}}). \tag{4.16}$$
This follows because any time the constraints are satisfied,
$$\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = f(\boldsymbol{\mathcal{x}}),$$
while any time a constraint is violated,
$$\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = \infty$$
these properties guarantee that no infeasible point can be optimal, and that the optimum within the feasible points is unchanged.

I'm having difficulty understanding how $$\min_{\boldsymbol{\mathcal{x}}} \max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}})$$
has the same optimal objective function value and set of optimal points $\boldsymbol{\mathcal{x}}$ as
$$\min_{\boldsymbol{\mathcal{x}} \in \mathbb{S}} f(\boldsymbol{\mathcal{x}})$$
Specifically, I am not seeing how the latter claim that any time the constraints are satisfied,
$$\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = f(\boldsymbol{\mathcal{x}}),$$
while any time a constraint is violated,
$$\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = \infty$$
I would greatly appreciate it if people could please take the time to clarify this.
Answer: Starting with:

$$L(\boldsymbol{\mathcal{x}}, \boldsymbol{\lambda}, \boldsymbol{\alpha}) = f(\boldsymbol{\mathcal{x}}) + \sum_i \lambda_i g^{(i)} (\boldsymbol{\mathcal{x}}) + \sum_j \alpha_j h^{(j)}(\boldsymbol{\mathcal{x}}) \tag{4.14}$$

If the constraints are satisfied, then $g^{(i)}(x)=0$ and $h^{(j)}(x)\leq0$. Therefore, the terms with $\lambda$ all vanish, and the terms with $\alpha$ attain their maximum over $\alpha_j$ at $\alpha_j=0$ (because the last term cannot be positive), so also those terms vanish, leaving you with $f(x)$.
On the other hand, suppose a constraint is not satisfied. If $g^{(i)}(x)\neq 0$ for some $i$, you can let $\lambda_i g^{(i)}(x)$ go to infinity by letting $\lambda_i$ go to $\infty$ if $g^{(i)}(x)>0$, and $\lambda_i \to -\infty$ otherwise. Similarly, if $h^{(j)}(x)>0$ for some $i$, you can let $\alpha_j h^{(j)}(\boldsymbol{\mathcal{x}})$ go to $\infty$ by letting $\alpha_j \to \infty$.
Answer: If $x\in S$ then $f(x) \ge L(x,\lambda,\alpha)$ for all $\lambda,\alpha$ with $\alpha\ge0$.
If $x\not\in S$ then one of the constraints is violated,i.e., $h_i(x)\ne0$ or $g_j(x)\>0$ for some $i$ or $j$. By taking the corresponding multiplier $\lambda_i$ or $\alpha_j$ large enough, one see $\sup_{\lambda,\alpha\ge0} L(x,\lambda,\alpha)=+\infty$.
Comment: Equality is between $f(x)$ and $\max_{\alpha,\lambda} L$ not between $f(x)$ and $L$ for arbitrary values of $\lambda,\alpha$.
Comment: But how do you reconcile your first claim with the claim that $\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = f(\boldsymbol{\mathcal{x}})$?
Comment: But that still contradicts $\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = f(\boldsymbol{\mathcal{x}})$, doesn't it? That's why I'm confused.
Comment: Also with regards to your second claim, why must it be true? It isn't obvious to me that a violation constraint necessarily results in $\max_{\boldsymbol{\mathcal{\lambda}}} \max_{\boldsymbol{\mathcal{\alpha, \alpha}}\ge 0} L(\boldsymbol{\mathcal{x}}, \boldsymbol{\mathcal{\lambda}}, \boldsymbol{\mathcal{\alpha}}) = \infty$, as is claimed?
Comment: If $x$ is feasible the $f(x) \ge L(x,\dots)$ and equality is attained for $\lambda$ and $\alpha$ being zero
Comment: The textbook doesn't claim that the equality is attained for only $\lambda$ and $\alpha$ being zero; rather, it says that the equality is attained **any time the constraints are satisfied**, so I'm still very confused about all of this.


Equalize on Mixer vs equalize on Instrument

Question: i'm really newbie on the topic and i was wondering what changes and where is the proper way to equalize an Instrument (e.g. digital piano, acoustic guitar) on a PA System or during Home recording.
It's better on the equalize control embedded on the instrument or in the mixer?
Thank you very much.
Comment: Whichever sounds best.
Answer: I started writing a long answer about the different responsibilities of the performer (make the sound you want the audience to hear) and the engineer (convey that sound as accurately as possible, using imperfect equipment in an imperfect space - and ALL equipment and spaces are imperfect to some extent).
But it's not like that any more.  Performer, instrument and PA/recorder are parts of a system that must be aware of and accommodate each other.  You all do what it takes.  And that's your answer.  Work together.
One point to consider.  EQ can only cut or boost content that exists.  If you cut the bass on your instrument to sound good in YOUR monitor, but the room is bass-light, the engineer can't put it all back.
Answer: For home recording it's generally better to get as much of the signal as possible ( without distortion ) as completely flat as you can....then use onboard or external EQ to get where you want. If you a special environment, a room with perfect ecko for example....but...what your ear is hearing and how to get that in a mic in that perfect room can be difficult. In performance...you need to have a relationship with the engineer. THEY ARE PART OF YOUR PERFORMANCE. No matter how well you sound at home, each environment is different, and hopefully the engineer knows his room....hard to tell whats coming out of the mains versus the monitors...it's trust....it's good to have a trusted set of ears in the audience...if you think your mix sounds bad and you are fussing with the eq on your guitar...its dangerous and distracting from the music your supposed to be focusing on.  Good luck.
Answer: EQ should only be used as a last resort. Hopefully, the sound engineer has profiled the room they're working in, so they know where it cuts and boosts frequencies. They'll have the sound desk EQ set up to accommodate those changes.
When it's time to record, a good engineer will spend hours moving microphones to get the best signal for each instrument - and may use more than one microphone for each instrument in order to get a good selection of signals to work from (e.g front/back/inside for a Cahon, front/inside/piezo for a guitar, etc). If EQ is absolutely needed, then it should be notched as closely as possible to the offending frequency so that the sound from the rest of the instrument isn't affected.


How to find the recurrence polynomial?

Question: Problem:
If $f$ is a polynomial with unknown roots $x_1,-x_1,x_2,-x_2\ldots,x_b,-x_b \quad (b \in \mathbb{N})$ and can be expressed as (known expansion):
$$f(x)=\sum_{a=0}^{2b}f_ax^a\quad(b \in \mathbb{N})$$
How to find $g$, such the roots of $g$ is just $x_1,x_2,\ldots,x_b$?
Details:
Looks like the main problem is solve
$g(x){(-1)}^bg(-x)=f(x)$.
But I don't know if this is suficient to force $g$ be of the form $\prod_{i=1}^{b}(x-x_i)$.
Looks like using this way, we get a indeterminated system, but if we can express all solutions there's no problem.
Using mathematica an easy problem couldn't be solved, see:
f[x_]:=(x-1)(x+1), RSolve[-g[x]g[-x]==f[x],g[x],x]. The software calculate and calculate...I didn't get answer.
So, using the definition of $f$ above ($f(x)=\sum_{a=0}^{2b}f_ax^a$) how to find the polynomial $g$ with roots $x_1,x_2,\ldots,x_b$?
How can we solve this recursion ($g(x){(-1)}^bg(-x)=f(x)$) and find all $g$ to satisfies it?
If someone knows a computable way to do it, I'd like to know too. If is using Mathematica is more interesting to me.
Comment: The question is underspecified since you have given no way to distinguish $x_j$ from $-x_j$. E.g., given the polynomial $x^2+1$, $x+i$ is an answer, but so is $x-i$; in higher degrees, it gets worse.
Comment: Quite unclear. How can a degree $b$ polynomial have $2b$ roots in $\pm$ pairs?
Comment: @J.M. In the sum is 2b. Edited.
Comment: Anyway, this should be interesting to you: `With[{n = 6}, {#, x /. Solve[# == 0, x]} &[Collect[Expand[Apply[Times, Sqrt[x] + (C /@ Range[n])] Apply[Times, Sqrt[x] - (C /@ Range[n])]], x, Simplify]]]` Change the value of `n` to something higher or lower; you should see a pattern.
Answer: Since $f(x)=x^{2b}+a_{2b-1}x^{2b-1}+\cdots +a_1x+a_0$ is a polynomial with roots $x_1, -x_1, ..., x_b, -x_b$ (For the sake of simplicity, let us assume that $x_1, ..., x_b$ are positive real numbers). So $f$ must be of the form$$f(x)=(x-x_1)(x+x_1) \cdots (x-x_b)(x+x_b)=\prod_{i=1}^b(x^2-x_i^2).$$As we know, the coefficients of a polynomial $p$ of degree $n$ with roots $r_1, r_2, ..., r_n$ are elementary symmetric polynomials in the roots of $p$; that is,$$p(x)=\prod_{i=1}^n(x-r_i)=\sum_{k=0}^n\sum_{1 \le j_1 \lt ... \lt j_k \le n}(-1)^kr_{j_1} ... r_{j_k}x^{n-k}.^{\, \dagger}$$ So, the coefficient of $x^{2b-2}$ in $f(x)$ equals $$a_{2b-2}=-\sum_{i=1}^bx_i^2.$$Suppose that there is a general algebraic way (By "algebraic way" I mean a way involving a finite number of the operations of addition, multiplication, and exponentiation with constant rational exponents) to find a polynomial $g$ with roots $x_1, ..., x_b$,$$g(x)=\prod_{i=1}^b(x-x_i)=\sum_{k=0}^b\sum_{1 \le j_1 \lt ... \lt j_k \le b}(-1)^kx_{j_1} ... x_{j_k}x^{b-k},$$ from knowing $f$. So, this implies that we can find the coefficient of $x^{b-1}$ in $g(x)$, that is, $\sum_{i=1}^bx_b$, which implies the fact that there is a general algebraic way to find the sum of the square roots of an arbitrary polynomial $f$ in terms of the coefficients of $f$, which is a contradiction (In brief, if such a way exists, then one can algebraically find a root of a polynomial which is non-solvable by radicals, which is impossible). $\ddagger$
Thus, there is no general algebraic way to find a polynomial $g$ with roots $x_1, ..., x_b$.

Footnote
$\dagger$ For the proof, please see this answer.
$\ddagger$ For the proof, please see this answer.

How to find the recurrence polynomial?


Drupal 7 - FAPI - Multistep form - with add another option

Question: I'm creating a multistep form in Drupal 7 - FAPI.
In the main hook_form() the redirection to the different steps are handeled.
function hook_form($form, &$form_state) {
    if (empty($form_state['storage']['step'])) {
        $form_state['storage']['step'] = 0;
    }

    switch($form_state['storage']['step']) {
        case 0:
          $form=  _step_0($form, $form_state);
        break;
        case 1:
          $form =  _step_1($form, $form_state);
        break;
        case 2:
          $form =  _step_2($form, $form_state);
        break;
        case 3:
          $form =  _step_3($form, $form_state);
        break;
        case 99:
          $form =  _step_end($form, $form_state);
        break;
    }
    return $form;
}

function _step_2($form, &$form_state) {
    ....
    $form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 80,
        '#size' => 80,
    );

        $form['Street'] = array(
        '#title' => t('Street'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 80,
        '#size' => 80,
    );

    ......

      $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Next',
      );

    $form['add'] = array(
            '#type' => 'submit',
            '#value' => 'Collega toevoegen',
        );
}

In step 2 I have an optional button 'Add onther' which saves the form_values into storage and reloads the same form (step 2). But when it reloads this form for the seconds time. the previous form values are being represented as default form values and not a blank (new) form, which is wanted.
function inschrijven_form_submit($form, &$form_state) {
    switch ($form_state['storage']['step']) {

        case 0:
          switch($form_state['values']['op']) {
            case 'Next' :
              ....
              $form_state['storage']['step'] = 1;
            break;
          }
        break;

        case 1:
          switch($form_state['values']['op']) {
            case 'Next' :
              ....
              $form_state['storage']['step'] = 2;
            break;
          }
        break;

        case 2:
            switch($form_state['values']['op']) {
                case 'Next' :
                    ....
                    $form_state['storage']['step'] = 3;
                break;

                case 'Add another' :
                    $form_state['rebuild'] = TRUE;
                    ....
                    $form_state['storage']['step'] = 2;
                    return;
                break;

        .....

    }
}

I've try to clear the form_state['values'] manually after each submit but with no success. Who can this multistep with add another functionality be achieved?
Comment: can you pls show at least one field in the step 2 ? Most supposedly you are filling the values in there. And pls have a look at the examples module : http://drupal.org/project/examples , a similar usecase is covered there :)
Comment: Thanks for you help. I have taken a look at the examples. The different steps are working fine but the problem exists when step 2 (name, adres, etc.) is asked. And it should be possible to add another person to the list in this step, so that's why I've added another button 'add another' besides 'next'.

P.S. orginal post for _step2 form
Answer: When you want to add a new set of values, you have to build the form in a different way - the fields that should be "multiplicated" have to be in an array.
so, your
$form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',

should instead look like this :
$form['step2'][$i]['Name'] = array( ...

where $i is set to zero in the begining and increased by the callback for your "add another" button. The "step2" fieldset is there just to help you distinguish the parts that are repeated from the others - its not necessary i guess.
The aformentioned examples module has nice examples how to acheive that even with ajax, so you dont have to reload the whole thing. Dont forget to set
$form['#tree'] = TRUE;

so that you can process the several sets of results.
Comment: Thanks for your input. I will give this and the ajax methods a try.
Comment: thanks for your answer. Everything worked out fine. I've used the AJAX method inf the final result.


App Engine: Endpoints not updated

Question: I wrote 2 endpoints with Google App Engine, which run flawlessly on localhost. Let their names be A and B.
Now I wanted to add push functionality (GCM + APNS). So I downloaded the Mobile Backend Starter code from Google (https://github.com/GoogleCloudPlatform/solutions-mobile-backend-starter-java) and integrated that code into my project (which I am developing using Android Studio). This adds two endpoint classes EndpointV1 and BlobEndpoint. So far, so good.
Now whenever I run and deploy my code it seems to work normally:
<code>./gradlew backend:appengineRun
./gradlew backend:appengineUpdate
</code>
The update is successful, too:
<code># ... building ...
5% Scanning for jsp files.
20% Scanning files on local disk.
25% Initiating update.
28% Cloning 2 static files.
31% Cloning 33 application files.
40% Uploading 2 files.
52% Uploaded 1 files.
61% Uploaded 2 files.
68% Initializing precompilation...
73% Sending batch containing 2 file(s) totaling 2KB.
90% Deploying new version.
95% Will check again in 1 seconds.
98% Will check again in 2 seconds.
99% Will check again in 4 seconds.
99% Will check again in 8 seconds.
99% Will check again in 16 seconds.
99% Closing update: new version is ready to start serving.
99% Uploading index definitions.

Update for module default completed successfully.
Success.
Cleaning up temporary files for module default...

BUILD SUCCESSFUL

Total time: 1 mins 9.457 secs
</code>
The version gets deployed and I can see that it is successfully updated online (I am also using the correct version).
But whatever I do, it has completely hidden the endpoint B in the API Explorer - but the new endpoints for push are shown.
Moreover, I now reverted to my old code locally (no push endpoints). And the push endpoints are still shown in the API Explorer.
Am I completely missing something here? What am I doing wrong if the endpoints show up on localhost flawlessly?
Comment: Hi. My name is Mario and I'm a representative of the Google Cloud Platform Support. If you're still having the issue, please provide your project ID so I can open a support case to troubleshoot this further.
Comment: Hi Mario! I don't have this problem anymore. Just by sleeping over night it healed itself - the new API showed up the next morning when I checked. I will open a support case if this happens again!
Comment: Yes, it takes some time (5-10 mins) to propagate.
Comment: For me it took more than one hour…
Comment: I'm doubting about it, but it should be an abnormal situation. Please let us know if you notice that exceptional delay again.
Answer: After getting some sleep the new API showed up just the next morning. So it seems it was an internal issue with App Engine.
If you have the same problem:

Just wait a couple of hours for the problem to fix itself
or (better) open a support case for this problem and link your project ID.

App Engine: Endpoints not updated


SQL check DATE between two times for any day

Question: I have a transaction table, and my problem is keeping track of the transactionDateTime column. Using SQL, I can't seem to get the DATE or TIMESTAMP to format so that any inserted data has to be between 8am and 10pm on any given day:
    CREATE TABLE Transaction_T
      (transactionID          NUMBER(8,0)              ,
       employeeID             NUMBER(10,0)      NOT NULL,
       customerID             NUMBER(6,0)       NOT NULL,
       transactionDate        VARCHAR2(9)       NOT NULL,
       transactionPayment     VARCHAR2(10) check(transactionPayment IN('cash','credit','debit','ebt')),
       transactionType        VARCHAR2(10) check(transactionType IN('void','return','sale')),
       transactionDateTime    TIMESTAMP check(transactionDateTime < '% 22:00:00' AND transactionDateTime > '% 08:00:00') NOT NULL,
CONSTRAINT TransactionPK PRIMARY KEY (transactionID),
CONSTRAINT TransactionFK1 FOREIGN KEY (employeeID) REFERENCES Employee_T(employeeID),
CONSTRAINT TranscationFK2 FOREIGN KEY (customerID) REFERENCES Customer_T(customerID));

The table above is created, but when trying to insert a correct Date(Time), I receive format errors regarding hours between 1 and 12 or not a valid month when the time is below 12. I've used Oracle documentation format and still no luck:
INSERT INTO
transaction_T(transactionID, employeeID, customerID, transactionDate, transactionPayment, transactionType, transactionDateTime)
VALUES(00000001, 0001, 000004, '04-APR-13','ebt','sale','04-APR-13 13:25:10');

Answer: The % in your check constraint won't work here. Try this instead:
CHECK (
  EXTRACT(HOUR FROM transactionDateTime) < 22 AND
  EXTRACT(HOUR FROM transactionDateTime) >= 8)

Comment: `EXTRACT` will work on `TIMESTAMP` and `DATE` values. The documentation is [here](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm). The best insertion format is the ANSI literal: `TIMESTAMP '2013-02-27 12:34:56.789'`, or if you're dealing with time zones then it's `TIMESTAMP '1997-01-31 09:26:56.66 +02:00'`. There's more about the literals [here](http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#BABGIGCJ) - it's a huge page covering all sorts of literals, with timestamps coming about two-thirds of the way down the page.
Comment: You need to prefix it with `TIMESTAMP`, so instead of `'2013-04-04 13:25:10.789'` do it exactly like this: `TIMESTAMP '2013-04-04 13:25:10.789'`.
Comment: Will this work with timestamp or date in sql? Also, do you have any feedback on my insertion format for timestamp?
Comment: I'm still getting "not a valid month" when I try to insert this format: '2013-04-04 13:25:10.789'
Comment: Also, is there a data type equivalent to just Time?
Comment: Nope, nothing for just "time of day". There is an `INTERVAL` type that stores a time span, either as years/months or days/seconds. But if you need "time of day" you should use a `TIMESTAMP` (or a `DATE`) and extract the time of day as needed. Here's one reason: if you have just "time" then 8AM is always less than 9AM. In reality that's not always true because 8AM on 4/12/2013 is *greater than* 9AM on 4/11/2013.
Comment: Great answer, so I went with time stamp. I'll just extract certain parts from queries when needed. Thanks again
Answer: You can express your check constraint like this:
check(transactionDateTime between trunc(transactionDateTime) + 8/24 and trunc(transactionDateTime) + 22/24))


Verificar se arquivo existe por 20 segundos C#

Question: Estou fazendo um módulo que trabalha com troca de arquivos e na documentação pede para aguardar 20 segundos pelo arquivo de status xxxxxxxx.sta, porém, não sei como implementar isso em C#. Estava tentando algo nessa linha, mas parece que roda de forma assíncrona, assim não consigo pegar o resultado bool se o arquivo existe ou não na hora que eu quero:
public void ValidarArquivoStatus(int numeroSequencialDoArquivo)
{
    seq = numeroSequencialDoArquivo;
    aTimer = new Timer(1000);
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;

}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    Principal.ValidouArquivoDeStatus = false;
    previousTime = e.SignalTime;
    //int tempoMaximoTentativaExecucao = Convert.ToInt32(Funcoes.LeParametro(14, "7", false));
    int tempoMaximoTentativaExecucao = 20;
    if (ExisteArquivoDeStatus(seq))
    {
        //aTimer.Enabled = false;
        Principal.ValidouArquivoDeStatus = true;
        aTimer.Enabled = false;
    }
    nEventsFired++;
    if ((nEventsFired == tempoMaximoTentativaExecucao) || (Principal.ValidouArquivoDeStatus == true))
    {
        aTimer.Enabled = false;
    }
}

Comment: Qual a assinatura do método ao qual você realiza a verificação?
Answer: Levando em consideração que o seu método de validação não é assíncrono, irei assumir que você precisa verificar de 20 em 20 segundos se existe um arquivo em um determinado diretório.
Seguindo sua linha de raciocínio o código abaixo executa o método DoWork() através do timer_Elapsed.
Ao final da execução do DoWork(), o timer é "reiniciado" (finally) e o DoWork() é chamado novamente.
using System;
using System.Timers;

namespace LearnTemporizador
{
    class Program
    {
        private static Timer timer;

        static void Main(string[] args)
        {
            timer = new Timer();

            timer.Elapsed += timer_Elapsed;

            timer.AutoReset = false;

            timer.Enabled = true;

            timer.Interval = TimeSpan.FromSeconds(20).TotalMilliseconds;

            timer.Start();

            Console.ReadKey();
        }

        private static void DoWork()
        {
            Console.WriteLine($"Validou! {Validar()}");
        }

        private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DoWork();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                timer.Start();
            }
        }

        private static bool Validar()
        {
            return true;
        }
    }
}

Comment: Cara muito obrigado deu certo assim!
Comment: @SidneiSanches, show! :D
Answer: Se for só para aguardar esse tempo, pode usar o timer da thread.
basta adicionar o código abaixo antes da verificação do arquivo:
Thread.Sleep(20000);

Observação:
Caso não esteja usando, necessário fazer o import abaixo:
using System.Threading;


From conditional probability to conditional expectation?

Question: Conditional probability is defined in terms of conditional expectation as
$$
P(A \mid \mathcal{N}) := E(I_A \mid \mathcal{N})
$$
where $(\Omega, \mathcal{F}, P)$ is a probability space, $\mathcal{N}$ is a sub $\sigma$-algebra of $\mathcal{F}$, and $A \in \mathcal{F}$.
Conversely, can conditional expectation be represented in terms of conditional probability?
Following is one way I think might be possible, which is inspired by the case conditional on a discrete random variable, where conditional expectation  can be represented as expectation with respect to corresponding conditional probability.
If the conditional probability is regular, i.e. $\forall \omega \in \Omega, P(\cdot \mid \mathcal{N})(\omega)$ is a probability measure on $(\Omega, \mathcal{F})$, define $Y: \Omega \rightarrow \mathbb{R}$ for any random variable $X$ as
$$
Y(\omega):=\int_\Omega X \, dP(\cdot \mid \mathcal{N})(\omega).
$$
Is $Y$ a version of the conditional expectation $E(X \mid \mathcal{N})$, i.e.
$$
Y = E(X \mid \mathcal{N}) \text{ a.e. }?
$$
Thanks and regards!
Answer: the answer for your question is yes. Note that, all you need to prove is the following equality
$$
\int_{E} X\ dP
=
\int_{E} \left[\int_{\Omega} X\ dP(\cdot|\mathcal{N})(\omega) \right]
dP|_{\mathcal{N}} \qquad \qquad (1).
$$
for all $E\in\mathcal{N}$.
The simplest way to do this is start from characteristic functions and then use linearity and finally the powerfull approximation theorems of the measure theory.
Let us start with the case $X=1_{A}$ where $A\in \mathcal{F}$. In this case the above equality holds as long as
$$
P(A\cap E)=\int_{\Omega} \left[\int_{\Omega} 1_{A\cap E}\ dP(\cdot|\mathcal{N})(\omega) \right]
dP|_{\mathcal{N}}.
$$
But this is certainly true and we can prove this manipulating the rhs. Indeed
$$
\int_{\Omega} \left[\int_{\Omega} 1_{A\cap E}\ dP(\cdot|\mathcal{N})(\omega) \right]
dP|_{\mathcal{N}}
=
\int_{\Omega} \mathbb{E}(A\cap E|\mathcal{N})
dP|_{\mathcal{N}}
=
\int_{E} \mathbb{E}(A|\mathcal{N})
dP|_{\mathcal{N}},
$$
where we used in the last equality that $E$ is $\mathcal{N}$ measurable.
But the right hand side above is by the properties of conditional expectation equals to $P(A\cap E)$. So the identity (1) holds for any characteristic function and for all $E\in\mathcal{N}$.
By linearity of the integral (1) is certainly true if $X$ is any simple function. Let $X$ be any positive $\mathcal{F}-$measurable function. We know that there is a sequence of simple functions $\varphi_n \uparrow X$, here the up arrow means monotone convergence. Since at this point is clear for us that
$$
\begin{eqnarray}
\int_{E} \varphi_n\ dP
&=&
\int_{E} \left[\int_{\Omega} \varphi_n\ dP(\cdot|\mathcal{N})(\omega) \right] dP|_{\mathcal{N}}
\\
&=& \int_{E} \mathbb{E}(\varphi_n|\mathcal{N}) dP|_{\mathcal{N}},
\end{eqnarray}
$$
we can finish the proof by invoking the Monotone Convergence Theorem.
Edition. I corrected the error pointed out by Didier Piau.
Addition. Theorem. Let $(\Omega,\mathcal{F},\mu)$ be a $\sigma$-finite measure space, $\mathcal{A}$ a sub-$\sigma$-algebra of $\mathcal{B}$, and $\nu=\mu|_{\mathcal{A}}$. If $f\in L^1(\mu)$, there exist $g\in L^1(\nu)$ (thus $g$ is $\mathcal{A}$-measurable) such that
$$
\int_{E} f\ d\mu =\int_{E} g\ d\nu
$$
for all $E\in A$; if $g'$ is another such function then $g=g'$ $\nu$-a.e. (Note that $g$ is the conditional expectation of $f$ on $\mathcal{A}$. (Folland)
Comment: Thanks! I was confused about $(\omega)$ in $dP(\cdot|\mathcal{N})(\omega)$  and $dP|_{\mathcal{N}}(\omega)$, but now I understand it means different in the two.
Comment: @Tim, you are welcome. You absolutely right, I made terrible choice for the name of the dummy variable, sorry about that.
Comment: None of your fault. After all it is me who started using $P(\cdot|\mathcal{N})(\omega)$, and $\int \ldots dP(\omega)$ is one of standards used in integral (I often just write $\int \ldots dP$).
Comment: Hope you don't mind I change the notations.
Comment: @Tim Good idea.
Comment: Does the result, presented above provide a efficient way computing conditional expectations?Can anyone present an explicit example where I can use this equality?


Why can't $p^p-(p-1)^{p-1}=n^2$ be a square?

Question: Let $p$ be a prime number. Show that $p^p-(p-1)^{p-1}$ can't be a square.
In other words, there is no $n\in\mathbb{N}^{+}$ such that
$$p^p-(p-1)^{p-1}=n^2.$$
Comment: There may be some interest in Boyd, Martin, and Thom, Squarefree values of trinomial discriminants, LMS J. Comput. Math. 18 (2015), no. 1, 148–169, MR3303602, where the question of squarefree values of $n^n+(-1)^n(n-1)^{n-1}$ is discussed.
Comment: Answers below tell you quickly that $p$ would have to be $1$ mod $4$. In fact, $p$ would have to be $1$ mod $8$. It's clear that $p^p-(p-1)^{p-1}$ is odd. The only odd square mod $8$ is $1$. So $p^p-(p-1)^{p-1}\equiv 1$. But since $(p-1)$ is even, $8$ divides $(p-1)^{p-1}$ (check $p=3$ separately). So you have $p^p\equiv 1$. Since $p$ is odd, $p^p\equiv p$. So $p\equiv1$ mod $8$.
Answer: $p=2$ gives $p^p-(p-1)^{p-1}=3$, which is not a square.  All other primes are congruent to either $1$ or $3$, modulo $4$.  I can prove that no $p$ of the latter type satisfies the given equation.
Take $p^p-(p-1)^{p-1}$ modulo $p$; we get $0-(-1)^{p-1}=-1$.  Hence a solution can exist only if $-1$ is a square modulo $p$.  This happens when the Legendre symbol $(\frac{-1}{p})=1$, but for $p\equiv 3\pmod{4}$, that is not the case, by one of the parts of the Law of Quadratic Reciprocity.
Comment: @user236182 That doesn't make sense. Only answers posted during the bounty period are eligible for an automatic award, and if the bounty is given manually, the bounty starter is free to ignore the score of the answers anyway.
Comment: It's wrong to claim "a solution exists exactly when $p\equiv 1\pmod 4$. The equation has no solutions.
Comment: @user236182, thanks fixed.  And I disagree that this should be a comment; arguably this solves half of the question.
Comment: If $p\ge 3$, then $p^p=(p-1)^{p-1}+n^2$ is only possible if $p\equiv 1\pmod{4}$ simply because if $p\equiv -1\pmod{4}$, then $p^p\equiv (-1)^p\equiv -1\equiv (p-1)^{p-1}+n^2\pmod{4}$, contradiction, because a sum of two squares if $0,1,2$ mod $4$.
Comment: I don't think this deserves a downvote, and yet I really feel this doesn't deserve the bounty for being the highest-rated answer.
Comment: @DanielFischer Sorry, I did not realize the answer was ineligible, thank you for pointing this out.  Is there a simple way to discern that an answer falls outside the bounty period?  Does editing count towards the freshness criterion?
Comment: This should be a comment.
Comment: I've downvoted this answer because fedja deserves the bounty for his correct solution.
Comment: @DanielFischer I wasn't aware of the automatic bounty property, sorry.
Comment: @ErickWong might not know this too.
Answer: Let $p=2m+1$. Then $p^p=((p-1)^m+ni)((p-1)^m-ni)$. Now, the prime factorization in the Gaussian integers is unique and no factor on the right is divisible by $p$, so the only logically possible case is $p=4k+1=x^2+y^2$ and $(p-1)^m+ni=(x+iy)^p$. Then $1\equiv (p-1)^m\equiv x^p\equiv x\mod p$, so $x=1$. However, in this case the real part on the LHS is divisible by $y$ and the real part on the RHS is congruent to $1$ modulo $y$, which is a clear contradiction.
Comment: You wanted to make it short, so here are some explanations for others: $x+yi,x-yi$ are prime in $\Bbb Z[i]$ (you used this) because their norms are ordinary primes; the prime factorization in $\Bbb Z[i]$ is unique because it's a UFD (like $\Bbb Z[\sqrt{-2}]$ but unlike $\Bbb Z[\sqrt{-n}]$ for $n\ge 3$ (see [here](http://math.stackexchange.com/questions/70976/why-is-mathbbz-sqrt-n-not-a-ufd))). The units$\pm i, \pm 1$ are $p$'th powers, otherwise we'd need to check cases $(p-1)^m+ni=\pm i(x+yi)^p,\pm (x+yi)^p$; also $p\equiv 1\pmod{4}$ because $x^2+y^2\equiv \{0,1,2\}\pmod{4}$.
Comment: @user236182 $\pm i$ and $\pm 1$ are exact $p$-th powers, so why should I?
Comment: @user10676 First congruence: $m$ is even. Second congruence: all binomial coefficients ${p\choose k}$ except the two extremal cases $k=0,k=p$ are divisible by $p$ and $(iy)^p$ is purely imaginary.
Comment: I would explicitly prove $(p-1)^m+ni, (p-1)^m-ni$ are relatively prime in order to conclude they're both $p$'th powers. Why does them not being divisible by $p$ prove they're relatively prime? $p$ is not necessarily prime in $\Bbb Z[i]$, e.g. $5=(2+i)(2-i)$.
Comment: @user236182 Because having both $x+iy$ and $x-iy$ as a factor in any of them results in divisibility by $p$, which is not there (the real part is not divisible by $p$). It is not "relatively prime implies $p$-th powers" but "the two conjugate primes in the factorization of $p$ have to be completely separated, hence..."
Comment: Here's another proof of them being relatively prime: If $d\mid (p-1)^{\frac{p-1}{2}}+ni,\, (p-1)^{\frac{p-1}{2}}-ni$, then the norm $N(d)\mid (p-1)^{p-1}+n^2$, so $N(d)$ is odd. Also $d\mid 2(p-1)^{\frac{p-1}{2}}, 2ni$, so $N(d)\mid 4(p-1)^{p-1}, 4n^2$, so $N(d)\mid 4\gcd\left((p-1)^{p-1},n^2\right)=4$. But $N(d)$ is odd, so $N(d)=1$.
Comment: I may be tired but can you please explain how you get $1 \equiv (p-1)^{m} \equiv x^p \mod p$ ?
Comment: @GeoffRobinson This was already addressed above, both by fedja and by user236182.  There is no assumption here that $x,y > 0$.
Answer: I have an alternative proof not relying on the Legendre symbol of the fact that only primes satisfying $p\equiv1\operatorname{mod}4$ can possibly satisfy the equation.
If $p=2$, then $2^2-1^1 = 3$ is obviously not a square.
If $p>2$, then $p$ is odd. Therefore, $(p-1)^{(p-1)} = m^2$ is a perfect square and we have that
$$p^p = n^2 + m^2$$
is the sum of two squares. But in order for this to be true we must have $p\equiv1\operatorname{mod}4$, because if we had $p\equiv-1\operatorname{mod}4$, then $p^p\equiv-1\operatorname{mod}4$. But as every square is congruent to either $0$ or $1$ modulo $4$, $n^2+m^2$ is in $\{0,1,2\}$ modulo $4$, a contradiction (argument due to @user236182).
Comment: We must have $p\equiv 1\pmod{4}$ simply because if we had $p\equiv -1\pmod{4}$, then $p^p\equiv (-1)^p\equiv -1\equiv n^2+m^2\pmod{4}$, contradiction, because $n^2+m^2\equiv \{0,1,2\}\pmod{4}$. The theorem you link to is a lot stronger and is difficult to prove. It uses [Fermat's theorem on sums of two squares](https://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares) or if you actually see the proof in the page you gave, it uses the Legendre symbol too, and is a lot more complicated than vadim123's $\left(-1|p\right)=1\iff p\equiv 1\pmod{4}$.
Comment: @DanielRobert-Nicoud You should edit your answer (with proper attribution) to correct the false claim.  The proof in the comments does not rely on Legendre symbol, but the proof in your answer certainly does.
Comment: This also doesn't solve the problem, or doesn't lead to an elementary solution.
Comment: @user236182, why are you so hostile to people trying to contribute to this problem?
Comment: This _does_ rely on the Legendre symbol, if you see the proof of the theorem 1.1 you link to.
Comment: @user236182 Yeah, you're right. However, the argument you gave in the comments does not rely on the Legendre symbol.
Comment: I downvoted you by accident, sorry.
Answer: The remaining case $p \equiv 1 \pmod 4$ left by vadim123's answer can be settled by a 2004 result of Ellenberg that there are no positive solutions to $A^4 + B^2 = C^p$ for any prime $p>211$.  This was further sharpened by Bennett, Ellenberg and Ng to show that there are no positive solutions to $A^4 + B^2 = C^n$ for any $n > 3$: https://www.math.wisc.edu/~ellenber/BeElNgdraftFINAL.pdf
As is common nowadays, the above methods make use of the modularity theorem, so quite possibly this is massive overkill for this problem.


Does the sphere $x^2 + (y-2)^2 + z^2 = 1$ intersect the plane $z-x = 3$? If so, find a point in their intersection. If not explain why.

Question:
Does the sphere $x^2 + (y-2)^2 + z^2 = 1$ intersect the plane $z-x = 3$? If so, find a point in their intersection. If not explain why.

I feel like I can give a convincing answer with a rough sketch, and words, but I can not figure out how to solve the problem algebraically. If anyone could help I would be greatly appreciative!
Comment: It's a plane parallel to y-axis making 45 degree angle to Z and X axis with the distance of (> 1) from y-axis. The sphere is on y axis (2, 0, 0) with radius of 1.
Answer: If so, $$x^2+(y-2)^2+(x+3)^2=1$$ or
$$2(x^2+3x+4)+(y-2)^2=0,$$ which is impossible.
Comment: @Ben Jenney    A common point $(x,y,z)$ of the sphere  and of the plane it's a solution of the system: $x^2+(y-2)^2+z^2=1$ and $z=x+3,$ which gives a possibility of the substitution.
Comment: Thank you for your response! One thing I do not understand is why substituting works in the first place. Do you have any suggestion where I can look to get a better understanding how this works geometrically or conceptually?
Answer: Let consider the translation $X=x$, $Y=y-2$, $Z=z$ then

$x^2+(y-2)^2+z^2=1 \iff X^2+Y^2+Z^2=1$
$x-z=3 \iff X-Z=3$

then consider the circle and the line in the plane $Y=0$

$X^2+Z^2=1$
$X-Z=3$
Answer: Here's a geometric/algebraic answer. The well known formula for the distance from a point $P=(x_0,y_0,z_0)$ to a plane $Ax+By+Cz+D=0$ is $$d=\frac{|Ax_0+By_0+Cz_0+D|}{\sqrt{A^2+B^2+C^2}}$$.
So the distance from the center of the sphere $(0,2,0)$ to the plane $x-z+3=0$ is
$$d=\frac{|1\cdot 0+0\cdot 2+(-1)\cdot 0+3|}{\sqrt{1^2+0^2+(-1)^2}} = \frac{3}{\sqrt{2}}$$
So the distance from the center of the sphere to the plane $\frac{3}{\sqrt{2}}$ is greater than the radius of the sphere $1$. Then the sphere doesn't intersect the plane.
Comment: This is a very natural, and clever, answer! and a good formula to know. Thank you!
Answer: No. To see this notice the plane can be written at $z=x+3$. Substituting into the equation of the sphere yields:
$$ x^2 + (y-2)^2 + (x+3)^2 = 1 $$
When we expand the last term of the left hand side this gives us:
$$ 2x^2 + 6x+ (y-2)^2 = -8$$
Completing the square then gives us:
$$2\left(x+\frac{3}{2}\right)^2 + (y-2)^2 = -8+\frac{9}{2}= \frac{-7}{2}$$
Notice that the two terms on the righthand side are always greater than or equal to zero, but the lefthand side is negative. Thus, for the reals, there is no intersection.
Comment: No problem! It would be, except that you have the 2 out front, so you're really adding $2\cdot (\frac{3}{2})^2$ to both sides of the equation to complete the square.
Comment: Thank you for your response! this was the track I started going down, and this definitely makes me feel more confident. Not to nitpick, but wouldn't it be $9/4$ rather than $9/2$ given $3^2/2^2$


Partial Differential Equations fourier transform with a sin(t) term

Question: Using fourier transform and properties of fourier transform solve the given problem
$$\frac{\partial u}{\partial t}+\sin(t)\frac{\partial u}{\partial x}=0$$
$$u(x,0)=\sin(x)$$
What I've gotten so far is:
$$F(u(z,t))=A(z)e^{iz\cos(t)}$$
where
$$F(f(x))(z)$$ is the fourier transform of $f(x)$
I'm stumped after that and not sure how to get to the final conclusion. Any advice is appreciated!
Answer: Applying Fourier transform with respect to space variable $x$, you have
$$
\frac{d\hat{y}}{dt}+{\rm i}k\sin t\,\hat{y}=0
$$
with the initial condition
$$
\hat{y}(0)={\rm i\sqrt{\frac{\pi}{2}}}(\delta(k-1)-\delta(k+1)),
$$
which has the solution
$$
\hat{y}={\rm i\sqrt{\frac{\pi}{2}}}(\delta(k-1)-\delta(k+1)) \exp({\rm i}k-{\rm i}k\cos t).
$$
Taking the inverse Fourier transform you find
$$
\mathscr{F^{-1}}(\hat{y})=\sin(x+\cos t-1).
$$
Answer: I don't think this PDE can really be solved by using fourier transform.
Instead, this PDE can be solved by using method of characteristics:
$\dfrac{\partial u}{\partial t}+\sin(t)\dfrac{\partial u}{\partial x}=0$
$\csc(t)\dfrac{\partial u}{\partial t}+\dfrac{\partial u}{\partial x}=0$
Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dt}{ds}=\csc(t)$ , letting $t(0)=\dfrac{\pi}{2}$ , we have $-\cos(t)=s$
$\dfrac{dx}{ds}=1$ , letting $x(0)=x_0$ , we have $x=s+x_0=-\cos(t)+x_0$
$\dfrac{du}{ds}=0$ , letting $u(0)=f(x_0)$ , we have $u(x,t)=f(x_0)=f(x+\cos(t))$
$u(x,0)=\sin(x)$ :
$f(x+1)=\sin(x)$
$f(x)=\sin(x-1)$
$\therefore u(x,t)=\sin(x+\cos(t)-1)$


presave like option for adding vocabulary and terms similar to one provided by hook_nodeapi

Question: I'm a Drupal newbie and trying to customize the 'Add Vocabulary' and 'Add Term' provided by taxonomy using a module named Domain Taxonomy.
To customize it as per my own requirement I'm gonna have to insert the domain specific data when the term is saved without messing up over the existing code provided by domain taxonomy rather wish to override it.
I'm looking for a hook similar to hook_nodeapi where in '$op == presave' after validations and before saving node it can be customized with user added data.
To my understanding hook_nodeapi doesn't apply for stuff like taxonomy or user profile. Does something similar exist for taxonomy that i could put to use here. Kindly let me know if my understanding is flawed and provide valueable comments/feedbacks and possible solution.
Answer: You can add a validation function to the form in hook_form_alter(). If you give your module a high weight, that validation function will be added last to the validation functions array and thus be executed last. The validation function can call form_get_errors to check whether errors occurred. If no errors occurred, you can be pretty sure that the vocabulary or term will be saved to the database, making it something like hook_nodeapi($op = presave').
Note that you cannot use hook_form_FORM_ID_alter(), because these hooks are executed before hook_form_alter(). Also, I found no easy way to react on the installation of other modules.
Comment: thanks for the reply..but my trouble is there are methods provided by the domain taxonomy that take care of inserting the domain related information during a term or vocabulary insert...all i want to do is make sure the domain related information is passed by my module..else there are no troubles with validations or the insert operations...


Is this orthogonal projection a orthogonal transformation?

Question: Well, I know that orthogonal projection is a linear transformation.
Let $t$, $n$ be two orthogonal (with $\|n\| = 1 =\|t\|$) non zero vectors that span a plane $\pi$. Then $T: \mathbb{R}^3 \to \mathbb{R}^3$ given by $ T(u) =  {\rm Proj}_{\pi}(u) = \langle u,n\rangle n + \langle u,t\rangle t$ is a linear transformation.
I'm trying to show that for every $x,y \in \mathbb{R}^3$, $\langle x,y\rangle  = \langle T(x),T(y)\rangle$.
What I've got:
$$\langle T(x),T(y)\rangle  = \langle (\langle x,n\rangle n + \langle x,t\rangle t),(\langle y,n\rangle n + \langle y,t\rangle t)\rangle =\langle x,n\rangle\langle y,n\rangle +\langle x,t\rangle \langle y,t\rangle,$$ since $u$ and $v$ are a orthonormal basis. I got stuck here.
Any help would be nice. Thank you.
Answer: The orthogonal projection is not, in general, an orthogonal map. Take for instance ${\bf n} = (1,0,0)$ and ${\bf t} = (0,1,0)$. Then $T(x,y,z)= (x,y,0)$, and although $\langle (1,0,1), (0,0,1)\rangle = 1$, we have $$\langle T(1,0,1), T(0,0,1)\rangle = \langle (1,0,0), (0,0,0)\rangle = 0 \neq 1.$$
Also, note that in general you need $\langle {\bf n},{\bf t}\rangle = 0$ for the relation ${\rm proj}_\pi({\bf u}) = \langle {\bf u},{\bf n}\rangle {\bf n} + \langle {\bf u},{\bf t} \rangle {\bf t}$ to hold.