Propositional modal logic: infinite models required in systems with finite model property?

Question: A system of propositional modal logic has the "finite model property" if any consistent sentence is satisfiable at a model with finitely many possible worlds. Some systems have this property and others do not.
An infinite set of sentences is consistent if each of its finite subsets is consistent.
For systems that do have the finite model property, are there infinite consistent sets of sentences which are not satisfiable by a finite model? What is an example of such a set, for some system?
Comment: I think not, it sounds a bit against the definition, but am unable to proof it , ps "An infinite set of sentences is consistent if each of its finite subsets is consistent." is not true (and rather impossible as well , there is no "each of its subsets", i guess you mean "if an infinite set of sentences is inconsistent then one of its finite subsets is inconsistent." which is true
Comment: @Willemien: when I read "An infinite set of sentences is consistent if each of its finite subsets is consistent." it makes perfect sense as a mathematics sentence in English; it means the same as "An infinite set of sentences is consistent if all of its finite subsets are consistent." I don't think the original sentence is remarkable.
Comment: @Willemien - why "impossible" ? It is *compactness*. Moreover, let $\Sigma = \{ \sigma_i \}$ *infinite*; assume that "if $\lnot Cons(\Sigma)$, then $\exists \Gamma \subset \Sigma$, such that $\lnot Cons(\Gamma)$" is *true*, then, by contraposition : "if $\forall \Gamma$, $Cons(\Gamma)$, then $Cons(\Sigma)$" must also br *true*.
Comment: @CarlMummert in't there a problem that all finite subsets of an infinite set are not enumerable, so how can you even start checking  their consistency?
Comment: @Willemien: who said anything about enumerating the subsets? The compactness theorem in the form I know it simply says that a theory is consistent if and only if each of its finite subsets is consistent. This does not presume that we have a way to effectively determine the consistency of even one finite subset, much less of all of them.
Comment: @CarlMummert you are right , I just don't like the definition (it refers to something that is humanly impassible to check ) i prefer the negative one. that is a slightly bit easier to check
Answer: If we use the definitions in the question, the answer is yes. Take any common propositional modal logic (e.g. S5) that has the finite model property for sentences. Work in a language with infinitely many propositional variables $X_i$, and consider the set $T$ of sentences that contains, for every finite set $D$ of propositional variables and every function $s \colon D \to \{+,-\}$, the formula
$$
\Box \left ( \bigwedge_{X_i \in D} s(X_i) X_i \right)
$$
where $+X_i$ is $X_i$ and $-X_i$ is $\lnot X_i$. For example, when $D = \{A,B,C\}$, we get 8 sentences
$$
\Box(A\land B \land C)\\
\Box(A\land B \land \lnot C)\\
\Box(A\land \lnot B \land C)\\
\Box(A\land \lnot B \land \lnot C)\\
\Box(\lnot A\land B \land C)\\
\Box(\lnot A\land B \land \lnot C)\\
\Box(\lnot A\land \lnot B \land C)\\
\Box(\lnot A\land \lnot B \land \lnot C)
$$
The infinite set of sentences $T$ is consistent (certainly every finite subset is consistent). But there is no finite Kripke frame that satisfies the entire set, because if we just look at just the sentences involving some finite subset $D$ of the propositional variables, the model will have to contain at least $2^{|D|}$ worlds.
Comment: I don't understand this answer. All of the 8 sentences contradict each other in S5, so how would a set containing at least two of them be consistent? It only makes sense when 'consistency' of a set here means that simply each of its statements is satisfiable (but not necessarily together with other statements). Then, however, it makes no sense to take them as sets.
Comment: Yes, that's right. After thinking about it some more I believe I found a similar example. Thanks.


Best way to place two html sections side by side

Question:
Summarize the problem

The purpose of this question is to find the best way to display two sections of html side by side. Ideally, I'd like to be able to break the UI up like so

Rather than the current setup

Describe what you've tried

I've tried modifying the html on my own, but I would like to get advice from a more experienced develop on how to do this.

Show some code

Section 5.2 Word Matching Exercise

              User Input:

                  <input id="el1" type="text" value="">

                  <input id="el2" type="text" value="">

                  <input id="el3" type="text" value="">

                  <input id="el4" type="text" value="">

                  <input id="el5" type="text" value="">

              Result in HTML:

                  <input id="dl1" type="text" value="">

                  <input id="dl2" type="text" value="">

                  <input id="dl3" type="text" value="">

                  <input id="dl4" type="text" value="">

                  <input id="dl5" type="text" value="">

                <button id ="one" class="button" type="button" onClick="process_input()">generate html</button>

Comment: Both ```flexbox``` and ```grid``` would work for this!
Comment: Note that the `` tag has been obsolete for many years. Do not use it.
Comment: Stacking elements one after the other is the typical HTML behaviour. To modify it, you must use styling. You can copy&paste an answer from here, but I think you are missing the basic of HTML programming. I would advise you to read some tutorial like this one https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout. It will save you time in the future!
Answer: You can try to learn CSS Flexbox. For example:

.row {
  display: flex;
}

.column {
  flex: 50%;
  text-align: center;
}

.column-1 {
  background-color: red;
}

.column-2 {
  background-color: blue;
}

Column 1

Colum 2

Answer: You can use flexbox for this.
The all the inputs are enclosed within inputBoxes where display:flex;. The center tag is not used anymore so justify-content: center; was used to align the flex boxes. Similiarly all the text was aligned to the center using  text-align: center;

    <title>Document</title>

Section 5.2 Word Matching Exercise

         User Input:

<input id="el1" type="text" value="">

<input id="el2" type="text" value="">

<input id="el3" type="text" value="">

<input id="el4" type="text" value="">

<input id="el5" type="text" value="">

          Result in HTML :

<input id="dl1" type="text" value="">

<input id="dl2" type="text" value="">

<input id="dl3" type="text" value="">

<input id="dl4" type="text" value="">

<input id="dl5" type="text" value="">

                <button id ="one" class="button" type="button" onClick="process_input()">generate html</button>


LINQ Date formatting not allowed to group by a formatted date YearMonth

Question: I need in the query bellow to group information by year and month, but its showing the following error:
{"LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression."}
The query:
var query = (from TABLE_01 in Context.payment
         join TABLE_02 in Context.documents on TABLE_01.code_doc     equals TABLE_02.cod_doc
         join TABLE_03 in Context.dispatch  on TABLE_01.cod_dispatch equals TABLE_03.code_dispatch
         where (new int[] { 1, 13, 14 }).Contains(TABLE_01.type_cust)
            && (TABLE_02.status < 14)
            && (TABLE_03.id_file_creation == 1)
            && (TABLE_03.creation_date >= initialDate && TABLE_03.creation_date <= finalDate)
         group new { TABLE_02,
                     TABLE_01,
                     TABLE_03 } by new { TABLE_02.code_person,
                                         yearMonth = TABLE_03.creation_date.ToString("yyyyMM"),
                                         TABLE_01.type_cust }
         into result
         orderby result.Key.code_person, result.Key.yearMonth
         select new
         {
             mtEpg = result.Key.code_person,
             yearMonth = result.Key.yearMonth,
             value_payment = ((int)(result.Sum(x => x.TABLE_01.value_payment) * 100)),
             type_cust = result.Key.type_cust == 1 ? 991 : 992
         }).ToList();

Answer: So, ToString(Format) translation is not supported. So make it correctly: split date by parts.
var query =
    from TABLE_01 in Context.payment
    join TABLE_02 in Context.documents on TABLE_01.code_doc     equals TABLE_02.cod_doc
    join TABLE_03 in Context.dispatch  on TABLE_01.cod_dispatch equals TABLE_03.code_dispatch
    where (new int[] { 1, 13, 14 }).Contains(TABLE_01.type_cust)
        && (TABLE_02.status < 14)
        && (TABLE_03.id_file_creation == 1)
        && (TABLE_03.creation_date >= initialDate && TABLE_03.creation_date <= finalDate)
    group new { TABLE_02,
                TABLE_01,
                TABLE_03 } by new { TABLE_02.code_person,
                                    Year = TABLE_03.creation_date.Year,
                                    Month = TABLE_03.creation_date.Month,
                                    TABLE_01.type_cust }
    into result
    orderby result.Key.code_person, result.Key.Year, result.Key.Month
    select new
    {
        mtEpg = result.Key.code_person,
        result.Key.Year,
        result.Key.Month,
        value_payment = ((int)(result.Sum(x => x.TABLE_01.value_payment) * 100)),
        type_cust = result.Key.type_cust == 1 ? 991 : 992
    };

Comment: Thanks! My mind was blocked to obvious because I was focused on specific issue.


Definir o nome do input select a partir do banco de dados

Question: Como faço para que apareça a descrição do item(que vem do banco) no select ao invés da frase "Selecione a Conta patrimonial"
quero que apareça o : $listar3["DES_CONTA_PATRIMONIAL"]  referente ao item selecionado.
<select class="form-control" name="contaPatrimonial" onchange="this.form.submit();" <?php if(!isset($_GET["revenda"]) ) { ?> hidden  <?php } ?>  >
                       <option value="" disabled selected>Selecione a Conta patrimonial</option>

                       <?php
                            $linha3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);
                            foreach($linha3 as $listar3){
                        ?>
                        <option value="<?php echo $listar3["CONTA_PATRIMONIAL"]; ?>"> <?php echo utf8_encode($listar3["DES_CONTA_PATRIMONIAL"]);?> </option>

                        <?php } ?>
                </select>

Banco

if ( isset($_GET["revenda"]) ) {
    $var1 = $_GET["revenda"];
    $query = ("SELECT REVENDA, CONTA_PATRIMONIAL, DES_CONTA_PATRIMONIAL FROM AFX_CONTA_PATRIMONIAL WHERE REVENDA like :rev ");
    $stmt3 = $pdo->prepare($query);
    $stmt3->bindValue(':rev', '%' . $var1 . '%', PDO::PARAM_STR);
    $stmt3->execute();
}

Answer: Uma das varias formas possíveis.
<select class="form-control" name="contaPatrimonial" id="contaPatrimonial" onchange="this.form.submit();" <?php if(!isset($_GET["revenda"]) ) { ?> hidden  <?php } ?>  >
    <option disabled selected value="">Selecione algo</option>
    <?php
    $linha3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);

    foreach($linha3 as $listar3){
        ?>
        <option value="<?php echo $listar3["CONTA_PATRIMONIAL"]; ?>"> <?php echo utf8_encode($listar3["DES_CONTA_PATRIMONIAL"]);?> </option>

    <?php } ?>
</select>

Comment: Nao rolou.. o select ficou com varias repetições de resultados e ja ta vindo com um item do banco pré-definido ..
Comment: Ops! faltou uma coisa.
Comment: eu gostaria de manter a frase "Selecione a conta.." e depois que o usuário selecionar a pagina vai atualizar e o select ficar com o resultado selecionado
Comment: Já adicionei o que faltava, desculpa a falha!
Comment: deu quase certo.. agora o select ta ficando sempre com o primeiro resultado
Comment: todos os options estão iguais?
Comment: não.. estão mostrando os resultados certo.. mas quando a pagina atualiza o select fica selecionado no primeiro item e não no qual eu selecionei
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/92849/discussion-between-leonardo-barros-and-fernando-fefu).


How can I use logistic regression betas + raw data to get probabilities

Question: I have a model fitted (from the literature). I also have the raw data for the predictive variables.
What's the equation I should be using to get probabilities? Basically, how do I combine raw data and coefficients to get probabilities?
Answer: The link function of a logistic model is $f: x \mapsto \log \tfrac{x}{1 - x}$. Its inverse is $g: x \mapsto \tfrac{\exp x}{1 + \exp x}$.
In a logistic model, the left-hand side is the logit of $\pi$, the probability of success:
$f(\pi) = \beta_0 + x_1 \beta_1 + x_2 \beta_2 + \ldots$
Therefore, if you want $\pi$ you need to evaluate $g$ at the right-hand side:
$\pi = g( \beta_0 + x_1 \beta_1 + x_2 \beta_2 + \ldots)$.
Comment: @user333, your question was about logistic regression, if you want answers about ordinal regression too, please add that to the question.
Comment: How about ordinal logistic regression? What would be the logic then?
Comment: @user333: Well... I haven't played much with ordinal logistic regression... but I think one uses the same link function. In any case, the logic is the same: inverse the link function to get the response variable...
Comment: yeah... but how do I know which probabilities are mapped to which target categories?
Answer: Here is the applied researcher's answer (using the statistics package R).
First, let's create some data, i.e. I am simulating data for a simple bivariate logistic regression model $log(\frac{p}{1-p})=\beta_0 + \beta_1 \cdot x$:
> set.seed(3124)
>
> ## Formula for converting logit to probabilities
> ## Source: http://www.statgun.com/tutorials/logistic-regression.html
> logit2prop <- function(l){exp(l)/(1+exp(l))}
>
> ## Make up some data
> y <- rbinom(100, 1, 0.2)
> x <- rbinom(100, 1, 0.5)

The predictor x is a dichotomous variable:
> x
  [1] 0 1 1 1 1 1 0 1 0 1 0 1 0 0 1 1 1 0 1 1 1 1 1 1 0 0 1 1 1 1 0 0 1 0 0 1 0 0 0 1 1 1 0 1 1 1 1
 [48] 1 1 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 1 1 0 0 1 0 0 0 0 1 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0
 [95] 1 1 1 1 1 0

Second, estimate the intercept ($\beta_0$) and the slope ($\beta_1$). As you can see, the intercept is $\beta_0 = -0.8690$ and the slope is $\beta_1 = -1.0769 $.
> ## Run the model
> summary(glm.mod <- glm(y ~ x, family = "binomial"))

[...]

    Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -0.8690     0.3304  -2.630  0.00854 **
x            -1.0769     0.5220  -2.063  0.03910 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

[...]

Third, R, like most statistical packages, can compute the fitted values, i.e. the probabilities. I will use these values as reference.
> ## Save the fitted values
> glm.fitted <- fitted(glm.mod)

Fourth, this step directly refers to your question: We have the raw data (here: $x$) and we have the coefficients ($\beta_0$ and $\beta_1$). Now, let's compute the logits and save these fitted values in glm.rcdm:
> ## "Raw data + coefficients" method (RDCM)
## logit = -0.8690 + (-1.0769) * x
glm.rdcm <- -0.8690 + (-1.0769)*x

The final step is a comparison of the fitted values based on R's fitted-function (glm.fitted) and my "hand-made" approach (logit2prop.glm.rdcm). My own function logit2prop (see first step) converts logits to probabilities:
> ## Compare fitted values and RDCM
> df <- data.frame(glm.fitted, logit2prop(glm.rdcm))
> df[10:25,]
> df[10:25,]
   glm.fitted logit2prop.glm.rdcm.
10  0.1250000            0.1250011
11  0.2954545            0.2954624
12  0.1250000            0.1250011
13  0.2954545            0.2954624
14  0.2954545            0.2954624
15  0.1250000            0.1250011
16  0.1250000            0.1250011
17  0.1250000            0.1250011
18  0.2954545            0.2954624
19  0.1250000            0.1250011
20  0.1250000            0.1250011
21  0.1250000            0.1250011
22  0.1250000            0.1250011
23  0.1250000            0.1250011
24  0.1250000            0.1250011
25  0.2954545            0.2954624

Comment: Note that `glm(y ~ x)` does not give you a logistic regression, You have to set `family=binomial(link="logit")`. Note the output says `Dispersion parameter for gaussian family`, not `binomial family`. If you do it right, `fitted(glm.mod)` actually returns the estimated probabilities, not the logits. You get the logits with `predict(glm.mod, type="link")`.
Comment: the package arm has the function invlogit, which is your function logit2prop.
Comment: Aua! I have fixed that. Thanks a lot, @caracal, for correcting me! This is really embarrassing (it is even more embarrassing as I have already given the correct answer in [another SO thread](http://stats.stackexchange.com/questions/2335/output-of-logistic-model-in-r)).
Comment: Should not we have obtained exactly the same numbers for `glm.fitted` and `logit2prop.glm.rdcm.`? There are some very very small differences. I could not get why we haven't got exactly the same numbers in your example. When I check; `library(arm); data.frame(logit2prop(glm.rdcm), invlogit(glm.rdcm))` produces exactly same results for `logit2prop` and `invlogit`. Hence, equally, I ask why `glm.fitted` and `invlogit` return not the exactly same numbers?


Why using -> operator used in Struct does not work in C

Question: I'm kind of new in C and I have thoroughly searched for an answer. Why -> operator does not compile in my code on a struct.
#include<stdio.h>
#include<time.h>

float t1=0.0f;
float t2=0.0f;
void main()
{
    int i;
    float a,t1,t2;
    struct timespec ts;

    clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&ts);
    t1 =(float)ts->tv_sec;
    printf(" Tiempo 1 %f\n",t1);
    a=0;
    for (i=0;i<10000000;i++)
    {
        a+=1;
    }

    clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&ts);
    t2 = (float)ts -> tv_sec;
    printf(" Tiempo 2 %f\n",t2);
    printf(" Delta  %f\n",t2-t1);
    printf("%f\n",a);
}

Compile error:
c1.c: In function 'main':
c1.c:27:14: error: invalid type argument of '->' (have 'struct timespec')
 t1 =(float)ts->tv_sec;
              ^
c1.c:37:15: error: invalid type argument of '->' (have 'struct timespec')
 t2 = (float)ts->tv_sec;

I have seen ts.tv_sec works but I don not why -> does not work in main function and it does when it's inside a different funcion ... I'm kind of confused. I would really appreciate your help.
Thanks
Comment: It's `int main(void)`, not `void main()`. Whoever advised you to use `void main()` does not know C very well. Find a better source of information.
Comment: use `->` in case of pointers .
Answer: At least in C, ts->tv_sec can be thought of as syntactic sugar for (*ts).tv_sec.
Since ts is not a pointer, your code does not compile. Just write ts.tv_sec instead.

why -> does not work in main function and it does when it's inside a different funcion

Because that other function probably accesses a timespec through a pointer parameter?
Comment: Make me sense now. Thanks


Gumbel distribution

Question: I have a silly question:
If X has a Gumbel distribution with parameters mu (location) and beta>0 (scale)
Then what would be the distribution of A.X,
where A is constant.
thank you all.
Answer: Probably your question is better suited for Cross Validated and a google search would give you the answer. That being said, if X is Gumbel distributed than a*X would be Gumbel distributed as well (a is constant, lower case is used to avoid ambiguity). Using that E[a*X] = a*E[X] and Var[a*X] = a^2*Var[X], where E[] and Var[] are the mean and variance, respectively.
Then using the formulas which express the connection between mean, variance and distribution parameters (mu, beta), e.g. from here, one can show that a*X has the following parameters (denoted by underscore):
mu_ = A*mu and beta_ = A*beta
a*X ~ Gum(mi_, beta_)

Gumbel distribution


What happens if you move an object without move constructor?

Question: What happens if std::move() is called on a user defined object, that defines no move constructor? Is it simply copied?
Comment: Note that `std::move` by itself does nothing to an object. So the answer depends on the context. For example, the moved from object could be used for a move assignment. Or something entirely different. So it is not totally dependent on the type being move constructible
Comment: You mean with a deleted move constructor? Because if you don't define a move constructor yourself, and all of the objects members have a move constructor, a trivial move constructor is generated.
Comment: `std::move` does not move, and `std::forward` does not forward.
Answer: Yes, move will fall back to copy. This is how standard containers like std::vector can implement resizing in terms of move, but remain compatible with classes which can only be copied.
However, the class may have an implicitly defined move constructor - see this guidance. http://en.cppreference.com/w/cpp/language/move_constructor#Implicitly-declared_move_constructor


How can I let a user select my Drupal Commerce product to either be shipped or downloaded?

Question: I am using the Drupal Commerce module. I want to download the digital file. I am using the Commerce License and Commerce File modules.
But now I need to add an option to let the user select between Shippable or Download. If the user selects Shippable, the product will be shipped, while if the user selects Download, the user will be able to download the file.
I want to do it like in the product page:

If the user selects Shippable, the user doesn't have a FILES tab in the User profile page.
If the user selects Download, the user has a FILES tab in the User profile page.

How can I implement this using Drupal Commerce?.
Any suggestions?
Answer: Required steps
Step 1
Create a taxonomy, let's say it's called "Delivery methods", with terms "Shipable" and "Download".
Step 2
For each product type, add a field like "Delivery method", which is a field "term reference" (and refer to the "Delivery methods" taxonomy).
Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).
Step 3
Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for the Delivery methods taxonomy.
Video tutorials
For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13).
Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.
Commerce Backoffice
Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce.


Flex: use the selectedItem of DateGrid in an function

Question: I'm using a spark Datagrid in an mobile Flex (4.6) application. When a row is selected in the grid I want to trigger a function and use the content of the selected item in that same function. This is my Datagrid
<s:DataGrid id="patientGrid" x="317" y="211" width="393" height="177"
            dataProvider="{patientInfo}" gridClick="patientSelect(event)">
    <s:columns>
        <s:ArrayList>
            <s:GridColumn dataField="FirstName" headerText="First Name"/>
            <s:GridColumn dataField="LastName" headerText="Last Name"/>
            <s:GridColumn dataField="DateOfBirth" headerText="Date Of Birth"/>
            <s:GridColumn dataField="Gender" headerText="Gender"/>
        </s:ArrayList>
    </s:columns>
</s:DataGrid>

And when a item is selected the patientselected function needs the ability to work with the content of that selected item.
I hope my question is clear, and thanks for helping!
Answer: Use the GridSelectionEvent.SELECTION_CHANGE event instead for two reasons:

it will provide information on which cells have been selected
it is fired whenever the selection changes (if you only react on mouse clicks, you ignore keyboard navigation/selection)

.
<s:DataGrid id="dg" selectionChange="onSelectionChange(event)" />

private function onSelectionChange(event:GridSelectionEvent):void {
    var index:int = event.selectionChange.rowIndex;
    var patient = dg.dataProvider.getItemAt(index);
    patientSelect(patient);
}


How do I disable update checks for locked projects?

Question: I am using drush @sites cron in order to get update notifications in a Drupal 7 multisite configuration.
However, I need to have some projects locked, using drush up --lock=context_mobile_detect.
Example:
.var.vhosts.drupalmulti#example.com           >>  Name                     Installed Version  Proposed version  Message
.var.vhosts.drupalmulti#example.com           >>  Context Mobile Detect    7.x-1.3            7.x-2.0-alpha1    **Locked via drush.**
.var.vhosts.drupalmulti#example.com           >>  (context_mobile_detect)                                       (Installed version not
.var.vhosts.drupalmulti#example.com           >>                                                                supported)

Since this command checks many sites, it sends many unnecessary emails of the form: "New release(s) available for example.com", although most of the time no module needs to be updated.
Is there a way, using code or not, to disable update checking of locked projects?
Answer: drush cron will trigger the default update manager search, whereas locked project are only locked during drush pm-updatestatus. If you want to prevent Update Manager from checking for particular modules, you'll need a custom module that implements hook_update_projects_alter. All you have to do then is unset($projects['context_mobile_detect']);.
E.g.
/**
 * Implements hook_update_projects_alter().
 */
function MYMODULE_update_projects_alter(&$projects) {
  unset($projects['context_mobile_detect']);
}

I do this quite a lot for Features modules, or custom code.
Comment: +1. That is the code suggested for modules not hosted on drupal.org, such as custom modules, but it does its job also for modules you don't want to update for any reason.


Root mean square speed of the Boltzmann distribution in the kinetic gas model

Question: Why can I simply say that multiplying the Boltzmann distribution function with $v^2$ and integrating from 0 to $\infty$ leads to the mean square speed?
$\langle v^2\rangle = \int\limits_{0}^{\infty} v^2 \cdot 4\pi \left( \frac{M}{2\pi RT}\right)^{\frac{3}{2}}v^2\exp\left(-Mv^2/RT\right)\;\mathrm{d}v=\frac{3RT}{M}$
My Physical Chemistry textbook says only that it is calculated that way and doesn't go any further.
Thanks for helping
Answer: The Boltzmann distribution states that the probability of having a particle with velocity $\vec v$ is proportional to $e^{-\frac{E}{kT}}d^3v$, where $E=\frac12 mv^2$ and $k$ is Boltzmann's constant.
So $$p(\vec v)=Ce^{-\frac{mv^2}{2kT}}$$
You get the integration constant $C$ from $\int p(\vec v)d^3v=1$, where you integrate over the entire space. Since the energy is direction independent, you can integrate the angular part, and you get $$\int_{angles}d^3v=4\pi v^2dv$$Then
$$C4\pi\int_0^\infty v^2e^{-\frac{mv^2}{2kT}}dv=1$$
This yields $$C=\left(\frac{m}{2\pi kT}\right)^{3/2}$$
You can use $R=N_Ak$ and $M=N_A m$to get $$p(\vec v)=\left(\frac{M}{2\pi RT}\right)^{3/2}e^{-\frac{Mv^2}{2RT}}$$
To get the average value of $v^2$, we need to do $$\langle v^2\rangle=\int v^2p(\vec v)d^3v=4\pi\int_0^\infty v^2v^2p(v)dv$$
One of the $v^2$ comes from the quantity you want to average, the other from transformation of the integral from $3D$ to $1D$. Plugging in the probability you now get the formula in your question. Note that there is a factor of $1/2$ in the exponential missing from your formula.
Comment: Thank you very much for doing this so precisely but I'm fully aware how the integral is derived.  I just don't understand why

$\langle v^n \rangle = \int \vec{v^n} p(\vec{v})\;\mathrm{d}\vec{v}$

is true,
Comment: It's a weighted mean, where the weight is the probability. See https://en.wikipedia.org/wiki/Expected_value


Let $n\geq 1$ and let $A$ be a $n\times n$ matrix with real entries such that $A^k=O$, then find value of $\det(I+A)$

Question: Let $n\geq 1$ and let $A$ be a $n\times n$ matrix with real entries such that $A^k=O$, for some $k\geq 1$. Let $I$ be the $n\times n$ identity matrix. Then find value of $\det(I+A)$ .
My Attempt
Since $A^k=O$ we have $\det(A)=0$ and also $A^k=A^{k+1}=A^{k+2}=...=O$
Let $p\in \Bbb N$ where $p\geq k$
$(I+A)^p=I+\binom{p}{1}A+\binom{p}{2}A^2+...+\binom{p}{k-1}A^{k-1}+O$
(since $A^k=A^{k+1}=A^{k+2}=...=O$)
$A^{k-1}(I+A)^p=A^{k-1}$
$\det(A^{k-1}(I+A)^p)=\det(A^{k-1})=0$
I wonder if I am doing right because I cannot justify further steps
Comment: $A^{k-1}(I+A)^p=A^{k-1}$; I didn't get this.
Answer: Hint:

If $A$ is nilpotent, then $p(\lambda) = \det(\lambda I - A) = \lambda^n$.

Further hint:

What will happen if you plug in $\lambda = -1$ into both forms of $p(\lambda)$?


Constructing an increasing sequence of numbers from a set

Question: I have an infinite set $A$ of real numbers and I wish to construct a strictly increasing sequence using elements of $A$. This is what came to my mind -
Pick any element from $A$ and name it $a_1$. Pick a different element from $A$. If this is greater than $a_1$, call it $a_2$. If not, rename the first element $a_2$ and the new one $a_1$. Suppose I have chosen $a_1<a_2<…<a_n$. Pick an element $a$ different from all these. If $a>a_n$, name it $a_{n+1}$. If $a<a_1$, rename $a_i$ as $a_{i+1}$ for all $i$, and $a$ as $a_1$. If $a_k<a<a_{k+1}$, rename $a$ to $a_{k+1}$ and $a_i$ to $a_{i+1}$ for $i\geq k+1$. This way I have $a_1<a_2<…<a_n<a_{n+1}$. Then by induction I have my increasing sequence $(a_n)$.
Am I allowed to do this? Did I invoke any axiom while doing this?
Comment: What if your set is not countable?  You couldn't do this with the real numbers for instance.  Or the set of all irrational numbers.
Comment: @fleablood: I disagree. We can do this with both the reals and the irrationals. Consider the sequence $a_n=\pi+n.$
Comment: TonyK's answer is the one you want. Mine only gets you partway there with "not necessarily," but his shows that you simply can't do it.
Comment: @fleablood: the question doesn't say that the sequence has to contain _all_ the elements of $A$.
Comment: @TonyK you're right I thought it did say that.
Answer: You are not allowed to do this. As a counter-example, suppose your set $A$ consists of the negative integers: $A=\{-1,-2,-3,\ldots\}$. Then there exists no strictly increasing  infinite sequence of elements of $A$!
Comment: "This way I have a1<a2<…<an<an+1. Then by induction I have my increasing sequence"  Your mistake is by induction you can have a sequence of any *finite* length.  That doesn't mean you can have a sequence of *infinite* length.
Comment: Very nice example. Which line in my "proof" was incorrect then?
Comment: @fleablood That is the answer I was hoping to get. Because this is something that has confused me for a long time. In our class we have always constructed sequence "by induction". Like "after choosing $a_n$ do this and get $a_{n+1}$. Thus we have our sequence by induction." But induction only says when a subset of naturals is the whole set.
Comment: Okay, ... in those cases you are adding numbers, one at a time, adding each *to the end of a sequence* with each number having the property.  In this case each step you are make a new *sequence* (not a new *number*) by adding a number in *different* places.  So what you get is a sequence of *sequences*.  Each sequence is increasing and finite and there are an infinite number of sequences but there is no final sequence in the end.
Comment: Your first sequence is $a_1 = \{a_{1,1}\}$ a sequence of one term.  You second sequence is $a_2 = \{a_{2,1},a_{2,2}\}$ a sequence of two terms.  Your $k$th sequence is $a_k=\{a_{k,1},a_{k,2},....,a_{k,}\}$  a sequence of $k$ terms.  Your final result is $\{a_1,a_2, a_3....\}$ an infinite sequence *of sequences* where each sequence is a *finite* increasing sequence.  But you haven't found a way to convert this sequence of sequences into a single infinite sequence *of numbers*.
Answer: This proves you can create an increasing sequence of any finite length (because if a sequence of length $n$ can be made, then a sequence of length $n+1$ can be made) but not an increasing sequence of infinite length (because for any $n$ you can "go one more" to length $n+1$ but adding one will never get you to length $\infty$) .
It's a subtle but important point that induction can give you a conclusion for all natural values but not for a countable infinite value.[1]
In this case it will be possible that for an infinite number of attempts we will find a number $<$ than $a_1$ and thus a new $a_1$ will be assigned an infinite number of times and there will be no "final" $a_1$ for the infinite sequence.
As Tony Ks answer shows  the set is $\{-1,-2, -3, ....\}$ then the first sequence will be $\{a_1\} = \{-1\}$ and the second sequence will be $\{a_1, a_2\} = -2, -1$, and so on.  Then $n$ sequence will be $\{a_1, ....  a_n\} = \{-n, -n+1, ...., -1\}$.  But each sequence will always have a different $a_1$ and there will be no "agreed upon" $a_1$ for an infinite sequence.
[1]  A false proof that all real numbers between $0$ and $1$ is rational:  If every decimal with $n$ places is rational then a decimal with $n+1$ spaces $0.a_1a_2....a_na_{n+1} = 0.a_1a_2.....a_n + \frac {a_{n+1}}{10^{n+1}}$ is the sum of two rational numbers and hence rational.  So by induction every decimal with any number of places is rational.  As every real number between $0$ and $1$ can be written a decimal with some number (possibly infinite) places, every such real number is rational.
The catch is that induction only proves something about decimals with finite number of places.  Not infinite number of places.  Although we can "add $1$" an infinite number of times to get an infinite number of numbers, those numbers are all finite.  We can never "add $1$" and ever get $\infty$.
Comment: Is the axiom of choice at all used while constructing a sequence from a set?


kicking user from Client.users.fetch()

Question: I am looking to kick a user via a bot, I have their id and am using Client.users.fetch(ID) to get there user. The error is ".kick not a function".
Here is a snippet of my code.
var User = Client.users.fetch(ID);

User.then(function(Result) {
    Result.kick();
});

Any help will be appreciated.
Comment: Only members can be kicked, not users.  You can use `.member(User).kick()` instead.
Comment: Would User still be var User = Client.users.fetch(ID);?
Comment:  doesn't work at all? I even tried message.guild and it doesn't work
Comment: If your function is async, try `const User = await client.users.fetch('ID here')` and then `message.guild.member(User).kick()`.  Don't forget to make sure your ID is a string, not a number.
Comment: "await is only available in async function"
Answer: You cannot kick a user in discord, you must understand the differences between a member and a user. The following possibilities are listed below:
a) You are trying to find the user and kick it from ever server that is possible.
var id = 'YOUR_ID_HERE';
<client>.guilds.cache.forEach(guild => { // Parses every guild
  if(guild.members.cache.has(id)){ // Checks if member exists
    var member = guild.members.cache.get(id); // Fetches the member
    if(member.kickable){ // Checks if kickable
      member.kick() // Kicks the member
    }
  }
})

b) kicking from current guild:
var id = 'YOUR_ID_HERE';
if(message.guild){ // If you are in a guild
  let member = message.guild.members.cache.get(id); // Fetches member
  if(member && member.kickable){ // Checks if member exists and is kickable
    member.kick() // Kicks member
  }
}

c) you are trying to kick from a targeted guild
var guildID = 'YOUR_TARGETTED_GUILD_ID';
var id = 'YOUR_TARGETTED_USERID';

const guild = <client>.guilds.cache.get(guildID); // Gets guild
if(guild){ // Checks if exists
  let member = guild.members.cache.get(id); // Gets member
  if(member){ // If member exists
    if(member.kickable){ // Checks if kickable
      member.kick() // Kicks member
    }
  }
}

Comment: Apparently member is nil? The id is literally a string copied from right clicking on there profile and pressing copy id. The whole guild thing is fine, and I just want to kick it from the current guild.
Comment: Oh the current guild is b) you would have to change the id every time you use it, or you can use an argument parse, e.g.
var id = args[0];
Answer: You can actually bypass having to get the user object since <guild>.member() accepts a user resolvable, which includes the ID as a snowflake (string).  Assuming you have a message object, you can use message.guild.member('ID here').kick()
Comment: message.guild.member(Choice).kick();

I get the error: "Unable to read property kick of null". Choice is a string and the correct id.

kicking user from Client.users.fetch()


Product status defaulting to disabled

Question: I am having a weird issue from one of our client web sites. When a user goes to add a product through the /admin/commerce/products/add/product, the status form field isn't rendered (by design). The database sets the default value to 1 (active) however when the user adds the product it sets the status to "Disabled".
I have looked all around and I can't figure out how this is being changed. Any ideas where I should be looking to fix this issue?
Answer: There's no telling without seeing the code you've used to hide the status field. My bet is the way you've hidden it is causing the form system to interpret the absence of a value as the disabled status, given PHP would treat both a 0 value and a NULL value similarly.

Product status defaulting to disabled


How to format number as Kb/Gb using Java?

Question:
Possible Duplicate:
Format file size as MB, GB etc

Using NumberFormat, I would like to have my numbers formatted as scientific multipliers. In other words, I would like to have the following formatting:

1024 should be formatted as 1K
1048576 should be formatted as 1G

And obviously other numbers should be expressed using k, G, and other multiples.
How can I do that ? Or do I need some Java library ?
Comment: This might help you: http://stackoverflow.com/questions/4753251/how-to-go-about-formatting-1200-to-1-2k-in-java
Answer: Roughly, this should work. It needs some polishing regarding proper double formatting.
static String formatSize(double size) {
  String finalQ = "";
  for (String q: new String[] {"k", "M", "G"}) {
    if (size < 1024) break;
    finalQ = q;
    size /= 1024;
  }
  return size + finalQ;
}

Answer: package com.shashi.mpoole;

public class MetricPrefix {

    static int ONE_ZERO_TWO_FOUR = 1024;
    static String SEPARATOR = " ";
    enum SIZE
    {
        B, K, M, G, T, P, E, Z, Y;
//      BYTE, KILO, MEGA, GIGA, TERA, PETA, EXA, ZETTA, YOTTA;
    }

    class Result
    {
        int number = 0;
        SIZE size;

        public Result setNumber(int number)
        {
            this.number = number;
            return this;
        }

        public Result setSize(SIZE size)
        {
            this.size = size;
            return this;
        }

        public String getValue()
        {
            return this.number + SEPARATOR + this.size;
        }
    }

    public Result getResult(double howMuchBigger)
    {
        double bigNumber = howMuchBigger;
        int index = 0;
        while(howMuchBigger-ONE_ZERO_TWO_FOUR>0)
        {
            bigNumber = howMuchBigger;
            howMuchBigger = howMuchBigger/ONE_ZERO_TWO_FOUR;
            index++;
        }

        if(index == 0)
            return new Result().setNumber((int) (bigNumber)).setSize(SIZE.values()[index]);
        else
        return new Result().setNumber((int) (bigNumber/ONE_ZERO_TWO_FOUR)).setSize(SIZE.values()[index]);

    }

    public static void main(String[] args) {

        MetricPrefix j = new MetricPrefix();
        System.out.println(j.getResult(56).getValue());
    }

}

Answer: Maybe that? How to convert byte size into human readable format in java?
Comment: This is [shameless plagiarizing](http://stackoverflow.com/a/3758880/1103872) of aioobe's answer!
Comment: @MarkoTopolnik Will downvote my question as it is a duplicate.


Audio na mesma página. Play em um para o outro

Question: Estou tentando o seguinte:
Criei audio1 e audio2 com base no que aprendi aqui no fórum. Acontece que o resultado não foi o desejado, ou seja, clicando nos dois ouve-se os dois sons. Gostaria que clicando em um (play) o e outro desse pause. Não gostaria de permitir ouvi dos sons ao mesmo tempo. Aqui tem uma exemplo:
 inserir a descrição do link aqui
$(function(){
  $("#audio1").on('click', function(){
    var pe = $("#audio2").get(0);
    if(pe.paused == false)
      pe.pause();
  });
  $("#audio2").on('click', function(){
    var pe = $("#audio1").get(0);
    if(pe.paused == false)
      pe.pause();
  });
});

        <audio id="audio1" controls>
             <source src="http://w3schools.com/html/horse.mp3" type="audio/mp3" />
        </audio>

        <audio id="audio2" controls>
            <source src="http://w3schools.com/html/horse.mp3" type="audio/mp3" />
        </audio>

Alguém pode ,e ajudar. Obrigado
Comment: Daniel, é exatamente isso. Sucesso para você. Muito obrigado.
Answer: Carlos, utilize o evento play no lugar do evento click:
$(function(){

  $("#audio1").on('play', function(){
    var pe = $("#audio2").get(0);

    if(pe.paused == false)
      pe.pause();
  });

  $("#audio2").on('play', function(){
    var pe = $("#audio1").get(0);

    if(pe.paused == false)
      pe.pause();
  });

});

        <audio id="audio1" controls>
             <source src="http://w3schools.com/html/horse.mp3" type="audio/mp3" />
        </audio>

        <audio id="audio2" controls>
            <source src="http://w3schools.com/html/horse.mp3" type="audio/mp3" />
        </audio>


How can I restrict access to my website via web services only?

Question: I am getting lots of spam in my website. Here are some modules I tried as a remedy:

Honeypot
Http BL

No luck yet however.
Now I decided to make the site available only for web services only, whereas the web services are done with Services module.
So how can I allow access to my website via services only? Is there something I can achieve this from .htaccess ?
Comment: for spam control I think you can also try changing the admin url and user login url using [this module](https://www.drupal.org/project/rename_admin_paths)
Comment: @shrish, good point. I'll try that too....
Comment: have you tried any sort of Captcha for anon users?
Answer: Assume a setup like so:

Assume that for site access via Services you use an account called "ServicesUser".
Create a new role, say you call it "ServicesOnly".
Make sure that there are no other "custom" roles in your site apart from anonymous, Authenticated and Administrator (if there are any: remove them again).
Authorize only user "ServicesUser" for this role "ServicesOnly".
Tune your permissions where appropriate, so that:

No permissions are granted to Anonymous or Authenticated.
All permissions are granted to Administrator (but only in case you have a need to ever login without using services, with a userid different from user/1, if there is no need for that, then no permissions granted to Administrator either).

Granularly issue permissions to role "ServicesOnly", so that "ServicesUser" receives appropriate permissions whenever required.
Whenever the site is switched to maintenance mode (eg to apply Drupal updates), ServicesUser will not be able to login either, which is what you should want also.

With a setup like above, access via Services (and userid = ServicesUser) should work as desired. While I cannot think of any other user who can do anything on your site, except user/1 (and optionally some other user who has access to role Administrator).
With this configuration, these are the only ways around it that I can think of:

Some security issues that are exploited somehow.
Somehow getting access to the ServicesUser account

Note: no additional contributed or custom) modules needed either ...


how to display a link on a node view page?

Question: I want to display a link on a node view page just like the "Add new comment" link.
How should I do this?
I think it can be done through hook_node_view(),  but how can I use this hook?
Comment: What do you mean "how can I use this hook"? You use this hook just like you use any other hook that your module implements: by implementing an appropriately named function and waiting for Drupal to call it.
Comment: I have use the hook but nothing happens. Can you write code so that I match it with my code?
Comment: First of all, check whether your implementation of the hook is actually executed, e.g by calling [drupal_set_message](http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/drupal_set_message) inside your hook implementation.
Answer: In your implementation of hook_node_view(), add an element to the $node->content array. The element should be a renderable array as expected by drupal_render().
Comment: Can you provide me some code help?
Comment: Sure; you provide the code and I help by telling you what's wrong with it.
Comment: Ok I solved the problem using hook_node_view.
Answer: In drupal6, you could implement the hook_links (just like the node module does http://api.drupal.org/api/drupal/modules--node--node.module/function/node_link/6)
Comment: But I am using drupal 7. How could I do this in drupal 7?
Comment: have a look at http://api.drupal.org/api/drupal/modules--node--node.module/function/node_build_content/7
Answer: Use hook_node_view and add new variable $node->my_link , add template file page--my_node.tpl.php and place that link wherever you want. This is solution for dynamic link for every node.
If you just want to add some no-dynamic link to your node_type than just add it in template file.


Server Sizing Methodology

Question: Our development environment consist of JBoss 5.0.1 DB Server, SQL Server 2008, Oracle IDM. Hardware is Win 2008 32 bit, 4GB RAM. We have reached stage where our environment can not handle application resulting in JBoss shut down throwing out of memory errors and CPU reaching to 90% usage. I am looking methodology to calculate correct server sizing where I input TPS, max number of concurrent users, max CPU utilization etc.. to give me number of servers, RAM size, number of cores. I am expecting application to grow 10% annually. Load Balancer and Failover should also be taken in account while sizing.
Comment: Do you know how much of a system's resources the average transaction uses? You'll need to know this before such a calculator could be devised, and then you'd need to know what the hardware can handle in terms of resources. One way you could do the former is to enable performance counters and collect data while throwing a number of sample transactions at the system, and then study the results. As for the latter, you'll only know that after you have purchased the hardware, and you could extrapolate this from the results, but real-world results may vary - be sure to bear that in mind.
Comment: I have done profiling and have the necessary data e.g. avg response time, tps, CPU utilization etc. what I need is an algorithm based mathematical model something on line of [link](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&arnumber=1657920). This paper applies to calculate server farm but I have only 1 server
Answer: This is really pretty basic.
You know what your current server can handle before it falls over (and you presumably have profiled the system to determine what the limiting factor is - RAM, CPU, etc...).
Take either 2/3 or 3/4 of the limiting factor's value when your server falls over and declare it "the unit load", or U.
Estimate what you think your future load will be (This is left as an exercise for the reader. Only you know your growth patterns.) and call this "the target load", or T.
When in doubt, estimate high.
The number of servers you need is equal to ceil(T/U)+1.
That is:

Divide the target load by the unit load to determine the number of servers you need.
Round up for any fractional servers required. It's better to have more than less.
Add one server (or more) for redundancy & extra capacity.

Figuring out how much RAM, CPU power, disk I/O bandwidth, etc. you need is not something Server Fault can do for you.  If you don't know, you need to test and profile.
Based on your experience in your environment you can determine if you need to add more RAM or CPU to your servers to achieve a balance (the server is nearly "maxed out" on its specs and saturates CPU / RAM / Disk / etc. nearly simultaneously, so you don't have resources going to waste).
Comment: My intention was to have complete model (number of servers, RAM, CPU power etc) that helps me establish some benchmark. Of course, real world results will vary than mathematical model. Thanks for advise.
Comment: @adbrpc The problem is servers vary: the 5 machines you bought this year will not have the same specs (likely not even the same components) as ones you buy next year. That's why you benchmark (see [my fixed link above](http://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning), determine limiting factors, and plan based on that. If you know your unit load is based on 4 cores at 2GHz and 4 GB of RAM then next year's box with 12 cores at 2GHz and 12G of RAM can theoretically do the work of 3 machines (in reality it will probably expose another limiting factor…)

Server Sizing Methodology


Get node author's real name in views or convert username

Question: I currently have a content view that displays a list of nodes for a blog. I would like to display the node authors real name (John Smith) at the top, but currently I am only able to display their username (john_smith) by creating a relationship to Content: Author and then adding User: Name.
How can I grab some fields from the node authors user profile?
The fields I need are $field_first_name, $field_last_name, $field_position.
FYI: I realize that there are modules that might be able to fix this problem such as Real Name, but I am hoping to do this without it.
Answer: If you don't use any special modules and you have simply added fields to the user acount (on /admin/config/people/accounts/fields then you should be able to add those fields in the Views UI. Just like you do it with all other fields, except that you use the author relationship that you have already created.
Comment: Ha! I must have needed to save it. I swear it wasn't there. It's there now! Thanks.


Methods for comparing clustering results

Question: I am doing an unsupervised clustering analysis for a genomics project. This means that I do not know when a particular clustering analysis is good or not.
I am running different clustering algorithms and different 'sets of features'. What I mean with different 'sets of features' is that given a data frame, I choose different combination of columns depending on its biological importance. For instance, some variables measure things at the sequence level, while others are measuring a particular cellular process or some other feature that cannot be measured at the sequence level. I am playing around with the different outputs of these sets of features, running the algorithms with all the features, or ignoring some, etc .
What I want is to compare the different clusters of these different runs and see if some of my objects are being clustered similarly despite lacking some sets of features. Does this make sense?
Is there any recommendation on how can I do this?
Answer: You can use the Adjusted Rand Index or the Adjusted Mutual Information to measure the similarity (agreement) of the overall results of two clustering algorithms on an overlapping dataset.
Both scores are adjusted for chance which means that 2 random clusterings will likely have an ARI or AMI close to 0.0.
Furthermore you can use those measure for model selection (e.g. finding the number of k in k-means) by running the clustering algorithm twice on 2 overlapping samples of the datasets and measuring the agreement on the overlap. The assumption is that a high agreement on the overlap means a higher stability of the algorithm and hence a better value for k (it captures better the real structure of the dataset).
A Novel Approach for Automatic Number of Clusters Detection in
Microarray Data based on Consensus Clustering by Nguyen and Epps is probably the best reference for this method and it is further applied to microarray data.
Comment: ARI and AMI give you agreement between 2 clusterings. If you have some ground truth you can use it as a reference to compute absolute scores against it. Otherwise you will have to can just consider pairwise agreements. As for implementations have a look at: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/supervised.py
Comment: I looked on the formula for computing the ARI and AMI measures, but it's a little confusing. Say I want to compare 4 clustering algorithms using this measures, can I compute them for each clustering algorithm separately, or I need to get the representatives produced all this 4 algorithm, and compare them two by two ? Given a test dataset and a clustering algorithm that produced a set of K representatives, is it possible to compute the ARI and AMI measures for this algorithm ? Can you provide a simple pseudo-code to compute ARI and AMI measures, because the formulas are a little confusing. Thx.
Comment: @ogrisel: The link doesn't work
Comment: I just checked and it seems to work for me. The documentation is here: http://scikit-learn.org/stable/modules/clustering.html#clustering-performance-evaluation
Comment: @ogrisel sorry I didn't specify the broken link: [Nguyen](http://ee.unsw.edu.au/~nguyenv/K_detection_15.pdf)
Comment: Indeed, my bad. I contacted the author as the link is also broken on his publications page. In the mean time the following paper has a small part on consensus index too: http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf
Answer: I only complete two mentioned measures with third that is also widely used in this situation, Normalized Variation of Information, which was proposed in the last 10 years. It is also scaled to the unit interval.
In addition, I recommend that you use any ensemble clustering technique that can assign to more partitions, so called consensus partitions, where objects are often better partitioned than in the initial partitions.


Lipschitz modulus of quadratic loss function

Question: I'm trying to figure out the Lipschitz modulus of quadratic function $\ell(\xi)=\xi^{\top} Q \xi+2 q^{\top} \xi + q_0$ with positive definite $Q$. According to the definition of Lipschitz modulus $\operatorname{Lip}(\ell)=\sup \left\{\|z\|_{*}: \ell^{*}(z)<\infty\right\}$, I need to find the supremum of the dual norm in the domain of the conjugate function of the quadratic, which is $\frac{1}{2}(z-q)^{\top}Q^{-1}(z-q) - q_0$. Since $z$ could be arbitrary vector, the supremum of dual norm is $\infty$. Am I right? Any hint would be appreciated.
Answer: A quadratic function with positive definite matrix is strongly convex and for that reason, has unbounded Lipschitz modulus. First, notice that since $Q\in\mathbb{S}_{++}^n\Rightarrow \lambda_{\min}(Q)\geq m>0$, hence your quadratic function is strongly convex. Since it is $\sigma=\lambda_{\min}(Q)$ - strongly-convex, it implies that
$$ f(\mathbf{y})- f(\mathbf{x})\geq \nabla f(\mathbf{x})^T(\mathbf{y}-\mathbf{x})+\frac{\sigma}{2}\|\mathbf{y}-\mathbf{x}\|^2\overset{\textbf{C.S.}}{\geq}\|\mathbf{y}-\mathbf{x}\|(\frac{\sigma}{2}\|\mathbf{y}-\mathbf{x}\|-\|\nabla f(\mathbf{x})\|) $$
where the RHS goes to infinity since the coercive function $\|x-y\|\to\infty$ . This means that $|f(\mathbf{x})- f(\mathbf{y})|$ is unbounded, as you correctly suspected.
Comment: Many thanks for your answers. It is clear and intuitive. :)
Comment: Thank you for your answer. The explanation of strongly convex and unbounded is super clear. I am still wondering what is the relation between the unbounded |f(y) - f(x)| and Lipschitz modulus. More specifically, could you please also explain the meaning of Lipschitz modulus? or any recommended book/paper/note about it would be appreciated.
Comment: @zzgsam Lipschitz modulus means if we can bound the difference in function values of two points using the distance between these points. Since the difference in function values is related to the derivative (which is the difference between two infinitely close points), Lipschitz modulus. It can be interpreted as if the function value does change "too drastically". I suggest starting with Wikipedia [Lipschitz continuity](https://en.wikipedia.org/wiki/Lipschitz_continuity) to get a good explanation. You can then use the references there if you'd like to educate yourself more


Hibernate mapping with association column from Embeddable

Question: I'm trying to map an entity with an embeddable via a join column available on the embeddable and seems no matter how I do it, it creates an extra map key column in the table for the embeddable.
So here's the entity
<code>@Entity(name = "transaction")
@Table(name = "TRANSACTION_MASTER_V5")
@NoArgsConstructor
@Builder
@Data
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
public class TransactionMasterV5Entity implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -7817135024822644549L;

    @Id
    @Column(length = 50, name = "TRNSCTN_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "transactionSeqGen")
    @GenericGenerator(name = "transactionSeqGen", strategy = "com.financemanagement.domaindevelopment.sequencegenerators.newsequences.CommonSequenceGenerator"
            , parameters = {
            @Parameter(name = SequenceStyleGenerator.INCREMENT_PARAM, value = "1"),
            @Parameter(name = CommonSequenceGenerator.VALUE_PREFIX_PARAM, value = "TRN") })
    private String transactionId;

    @Version
    private int version;

    //@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH })

    @Column(length = 1000, name = "TRNSCTN_DSCRPTN", nullable = false)
    private String transactionDescription;

    @OneToOne(mappedBy = "parentTransaction", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @Fetch(FetchMode.JOIN)
    private TransactionCategoryV5Entity transactionCategory;

    @OneToOne(mappedBy = "transactionMasterEntity", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
    private TransactionLocationV5Entity transactionLocation;

    @Column(name = "TRNSCTN_NTS", columnDefinition = "VARCHAR2(4000)")
    private String transactionNotes;

    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH,
            CascadeType.REMOVE }, fetch = FetchType.EAGER, mappedBy = "parentTransaction")
    private Set<@Valid TransactionItemV5Entity> itemizedTransactions;

    @ElementCollection
    @CollectionTable(name = "ACCOUNT_TRANSACTION_DETAILS_V5",
            joinColumns = @JoinColumn(name = "TRN_ID"
                    , referencedColumnName = "TRNSCTN_ID"))
    @MapKeyClass(TransactionTypeV5Entity.class)
    @Builder.Default
    private Map<TransactionTypeV5Entity, AccountTransactionV5Entity> accountTransactions= new HashMap<>();

}
</code>
And here's the embeddable class
<code>@Embeddable
@NoArgsConstructor
@Builder
@Data
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
public class AccountTransactionV5Entity implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -7817135024822644549L;

    @Column(name = "TRNSCTN_ACCT_ID", nullable = false)
    private String transactionAccountId;

    @ManyToOne
    @JoinColumn(name = "TRNSCTN_TYP_CD", referencedColumnName = "TRNSCTN_TYP_CD", nullable = false)
    private TransactionTypeV5Entity transactionMethod;

    @ManyToOne
    @JoinColumn(name = "TRNSCTN_CRNCY", referencedColumnName = "CRRNCY_CD", nullable = false)
    @NotNull(message = "Transaction currency must have a value")
    private CurrencyEntity transactionCurrency;

    @Column(name = "TRNSCTN_AMT", columnDefinition = "NUMBER(20,2)")
    @Positive(message = "Transaction amount must be greater than 0.00")
    private BigDecimal transactionAmount;

    @Column(name = "TRNSCTN_DT", columnDefinition = "TIMESTAMP WITH TIME ZONE")
    @Type(type = "org.hibernate.type.OffsetDateTimeType")
    @PastOrPresent(message = "Transaction date must not be a future date")
    private OffsetDateTime transactionDate;

}
</code>
So basically what I want is to use the join column TRNSCTN_TYP_CD as the key to Map I have in the entity.
Tried using @MapKey. It throws org.hibernate.AnnotationException: Associated class not found AccountTransactionV5Entity
If I use @MapKeyColumn or @MapClass it creates an additional column which I don't want.

Is there a way around this where I can use the join column TRNSCTN_TYP_CD from the table ACCOUNT_TRANSACTION_DETAILS_V5 as the key to the map?
Appreciate any help I can get on this....!!
Answer: I would suggest you to correct your mapping in this way:
<code>@Entity
public class AccountTransactionV5Entity implements Serializable {

    // ...

    @ManyToOne
    @JoinColumn(name = "TRNSCTN_TYP_CD", referencedColumnName = "TRNSCTN_TYP_CD", nullable = false)
    private TransactionTypeV5Entity transactionMethod;
}

@Entity
public class TransactionMasterV5Entity implements Serializable {

    // ...

    @OneToMany
    @MapKey(name = "transactionMethod")
    private Map<TransactionTypeV5Entity, AccountTransactionV5Entity> accountTransactions= new HashMap<>();

}
</code>
Comment: Thanks for the feedback. Seems like a good solution.I think I was trying to experiment if AccountTransactionV5Entity could be an embeddable and not an entity. But I think that was unnecessary. The one you have suggested is a much neater solution. Thanks again.


SQL UPDATE multiple rows of matching data between two tables

Question: I'm trying to UPDATE MySQL Table1 with Table2 data with column CODE being the unique id between tables.
Table1

CODE
QTY

A
10

B
15

C
20

Table2

CODE
QTY

B
10

C
5

Desired output is Table1 QTY data is added on (not replaced) with Table2 QTY for matching codes between the two tables.
I have tried below, however does not give the expected result and throws me a syntax error.
UPDATE Table1 set QTY=(QTY +
SELECT IF(QTY IS NULL or QTY = '', '0', QTY)
from Table2)

Obviously my knowledge is limited on SQL as I'm still learning, appreciate if someone can please assist.
Answer: You can use join.  I would recommend aggregating before joining:
update table1 t1 join
       (select t2.code, sum(t2.qty) as qty
        from table2 t2
        group by t2.code
       ) t2
       using (code)
    set t1.qty = t2.qty + t1.qty;

Aggregating first ensures that you get the results you expect if multiple rows in table2 have the same code.  If you know the codes are unique in table2, you can just use a join:
update table1 t1 join
       table2 t2
       using (code)
    set t1.qty = t2.qty + t1.qty;


exit status in shell script

Question: I am running a application form the shell script. Now I like to know the exit status of the application to know whether it exit normally or abnormally ( crash etc). How I know it?
Example:
./mytestApp
Comment: how is the question significantly different from your other post in http://stackoverflow.com/questions/5451297/exit-code-when-crashed ?
Answer: Bash stores the last process' exit value in the special variable $?.
Answer: You can use special variable $? which contains an exit status of the last comand.
Answer: $? contains the exit status of the last command executed. So, if the last command was ./mytestapp, $? would contain its exit status immediately after (note that you can only retrieve this value once and it must be retrieved immediately after the command whose exit status you want to know). You may want to capture it in a variable, e.g.
#!/bin/bash
./mytestapp
APPSUCCESS=$?
# Continue doing whatever it is you're doing

This all assumes that you're using bash (sh and zsh will work as well, IIRC).
Answer: The special variable $? will contain the exit status of the last command in bash.

exit status in shell script


Tratar acentuação com Jquery

Question: Estou com problemas em tratar acentuação no jQuery.
Gostaria de remover acentos das palavras e substituir espaços por "%20".
Tentei fazer do jeito abaixo, porém, não funcionou.
cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);

cidade_tratada = cidade_sem_tratar
.replace(/[áàâã]/,'a')
.replace(/[éèê]/,'e')
.replace(/[óòôõ]/,'o')
.replace(/[úùû]/,'u')
.replace(' ','%20');
console.log(cidade_tratada);

O resultado é o seguinte:

Por gentileza, poderiam me ajudar?
Abraço e Obrigado!
Comment: Bom dia! Por que não cola o código na pergunta em vez de print? Assim poderíamos copiar e tentar reproduzir.
Comment: [Parece não ter problema com seu código](https://jsfiddle.net/h1btfu0n/)
Answer: Seu código está correto na substituição dos acentos, mas para substituir TODOS os espaços, troque o último replace por:
.replace(/\s/g,'%20')

Do jeito que está, irá substituir apenas o primeiro espaço que for encontrado.
Veja funcionando:

cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);

cidade_tratada = cidade_sem_tratar
.replace(/[áàâã]/,'a')
.replace(/[éèê]/,'e')
.replace(/[óòôõ]/,'o')
.replace(/[úùû]/,'u')
.replace(/\s/g,'%20');
console.log(cidade_tratada);

<input type="text" id="estados" value="Afonso Cláudio" />

Usando Função

function remAcentos(v){
   var c='áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
   var s='aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
   var n = '';
   for(var x=0;x<v.length;x++){
      c.search(v.substr(x,1))>=0 ?
      n+=s.substr(c.search(v.substr(x,1)),1) :
      n+=v.substr(x,1);
   }
   return n;
}

cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);
cidade_tratada = remAcentos(cidade_sem_tratar).replace(/\s/g,'%20');
console.log(cidade_tratada);

<input type="text" id="estados" value="Afonso Cláudio" />
Comment: Para tratar as palavras com acentuação não está funcionando.. mas em relação com os espaçamento está show! :) Mto obrigado
Comment: Pois é.. estou achando muito estranho esse erro. Vi que deu certo na sua simulação.. mas pra mim aparece como "Afonso%20Cláudio". Acento agudo no "á".
Comment: Não sei se é importante essa informação, mas, os dados eu estou pegando de um arquivo em JSON.
Comment: No inspecionar aparece sem acento..Afonso Cláudio
Comment: O que será que pode estar acontecendo?
Comment: É um seletor de cidades. Ele está sendo construido através de um arquivo em JSON.
Comment: @DiegoAlbuquerque Acho que não vai dar certo não. Tinha que ver o código de como vc tah pegando os dados do xml. Lá que tá o segredo.
Comment: Essa parte ajuda?              $.each(json.estados[_idEstado].cidades, function(indice){

        $('#estados').append(
          '' +
              json.estados[_idEstado].cidades[indice]  +
          '');
        });
Comment: O caso foi resolvido!! Muito obrigado pelo apoio e atenção!! :) O Rui Ferreira deu uma dica bem legal! Um abraço
Comment: @DiegoAlbuquerque Se achou a resposta útil, não deixe de marcar ✔
Answer: Verifique se a função encodeURI faz o que quer, por exemplo:
var myStr = "Afonso Cláudio";
var res = encodeURI(myStr);

função para remover acentos:
function removerAcentos( newStringComAcento ) {
  var string = newStringComAcento;
  var mapaAcentosHex    = {
    a : /[\xE0-\xE6]/g,
    A : /[\xC0-\xC6]/g,
    e : /[\xE8-\xEB]/g,
    E : /[\xC8-\xCB]/g,
    i : /[\xEC-\xEF]/g,
    I : /[\xCC-\xCF]/g,
    o : /[\xF2-\xF6]/g,
    O : /[\xD2-\xD6]/g,
    u : /[\xF9-\xFC]/g,
    U : /[\xD9-\xDC]/g,
    c : /\xE7/g,
    C : /\xC7/g,
    n : /\xF1/g,
    N : /\xD1/g
};

for ( var letra in mapaAcentosHex ) {
    var expressaoRegular = mapaAcentosHex[letra];
    string = string.replace( expressaoRegular, letra );
}

return string;
}

Pode usar a função removerAcentos e depois encodeURI para colocar %20 nos espaços
Comment: Funcionou!!!!!!!!!! Muito obrigado!!!
Comment: Testei mas não funcionou.. quando ele vai tentar utilizar o nome da cidade depois de passar pelo encode ele aparece com acento na URL. Estou tentando achar um padrão para o site: http://servicos.cptec.inpe.br/XML/listaCidades?city=Afonso%20claudio .... Eu recebo o nome das cidades com acentos, ai eu trato e depois busco. O problema está acontecendo para tratar os nomes das cidades da forma que o site aceite (sem acentuação). Obrigado pela ajuda
Comment: Como está a fazer o post?
Comment: Fico contente que tenha funcionado ;)
Answer: O replace em javascript trabalha com regex, e vc n esta passando uma regex para trocar os espacos. tenta colocar assim:
string.replace(/ /g, '%20');

Vc pode testar as regex em sites, como esse, por exemplo:
https://regex101.com/

Tratar acentuação com Jquery


Clusters of variables interpretation

Question: I am doing clustering of variables using hclustvar() function from ClustOfVar package in R. The example given in R for the decathlon data is:
data(decathlon)

tree <- hclustvar(X.quanti=decathlon[,1:10], init=NULL)

plot(tree)

The function does the PCA and then analyze projections of variables on main components to detect those variables that have similar coordinates. However I still don't know how to interprete the Y-axis on the plot which is called Height. Could anybody help me with the interpretation?
Thanks!
Answer: As stated on the package documentation – p.9, hclustvar() provides ascendant hierarchical clustering of a set of variables. In order to do this hierarchical clustering, it should compute a distance metric between variables and clusters. In the case of hclustvar(), this distance is based on correlation between variables and then between clusters – i.e group of variables (cf. the aggregation criterion defined in the package documentation. For more information, look at the paper dedicated to the package on jstatsoft. Paper title: ClustOfVar: An R Package for the Clustering of Variables).
The Y-axis (Height) is the value of this distance metric. If you see two clusters merged at a height x, it means that the distance between those clusters is x. Here for example, the minimal height is 0.3842319 and this is the distance between Shop.put and Discus which are the closest variables. This distance is equal to 1 - cor(decathlon$Shot.put, decathlon$Discus). Note that length(tree$height) ==  n-1, with n being the number of variables, since you need at least two variables to generate the first cluster.
Comment: Seems not mention how it is involved with PCA

Clusters of variables interpretation


The JSON object must be str, bytes or bytearray, not list

Question: I am trying to access JSON data but getting the above error. My code is:
with open(filepath+"decompressed_twitter_lot1file1.txt", 'rb') as fh:
    for line in fh:
        object = json.loads(line)
        urls_in_tweet = object['entities']['urls']
        domains_in_tweet = []
        print(urls_in_tweet)
        for url in urls_in_tweet:
            for key, value in url.items():
                print(key,value)
                domain = tldextract.extract(value).registered_domain
                print("domain")

My output:
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[{
  'display_url': 'msnbc.com/rachel-maddow/…',
  'indices': [67, 90],
  'expanded_url': '//www.msnbc.com/rachel-maddow/watch/trump-admin-coverage-maxim-watch-what-they-do-not-what-they-say-66934341943',
  'url': '//t/zHmMchTCIf'
}]
display_url msnbc.com / rachel - maddow / …
  domain
indices[67, 90]

After this, I get this error.I dont understand why after indices key it is not printing anything.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-90-cb728568a4f1> in <module>
      8             for key, value in url.items():
      9                 print(key,value)
---> 10                 domain = tldextract.extract(value).registered_domain
     11                 print("domain")

~/.local/lib/python3.8/site-packages/tldextract/tldextract.py in extract(url, include_psl_private_domains)
    294     url, include_psl_private_domains=False
    295 ):  # pylint: disable=missing-function-docstring
--> 296     return TLD_EXTRACTOR(url, include_psl_private_domains=include_psl_private_domains)
    297
    298

~/.local/lib/python3.8/site-packages/tldextract/tldextract.py in __call__(self, url, include_psl_private_domains)
    214
    215         netloc = (
--> 216             SCHEME_RE.sub("", url)
    217             .partition("/")[0]
    218             .partition("?")[0]

TypeError: expected string or bytes-like object

This is data is small part of Twitter API data. How can I access every key-value pair of this JSON data and load value in domain list?
Answer: json.loads expects a str hence the error
If you want to get the key-value pairs you can do this:
fs = [{'display_url': 'eonli.ne/33XF5V1', 'indices': [90, 113], 'expanded_url': 'eonli.ne/33XF5V1', 'url': 't.co/flhUdZcUzB'}]

for k,v in fs[0].items():
  print(f"{k}, {v}")

fs[0] is a dictionary, get the items with items()
There is not need for json.loads here
Comment: Sorry, to make it more clear I did change my question a little bit.


PDO SQLSTATE[07002]:COUNT field incorrect or syntax error

Question: Estou com problemas para fazer um decremento no sql com pdo. estou recebendo o seguinte erro

SQLSTATE[07002]: [Microsoft][ODBC Driver 11 for SQL Server]COUNT field incorrect or syntax error

código
<?php
ob_start();
include'../../classes/config.php';
session_start();
$username = $_SESSION['ID'];

$creditosplayer = (float)$_POST["creditos"];

try {
  $pdo = new PDO($pdoconnection, $user, $pass);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $query = $pdo->prepare("UPDATE [omegashop].[dbo].[cad_users] SET                         [creditos] = :creditosplayer WHERE [userid] = :user");
  $query->bindValue(':creditosplayer', $creditosplayer);
  $query->execute();

  echo 1;
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

Como deve ser o parâmetro correto para o tipo float ?
Answer: Parece que você esqueceu de definir o valor para :user
Está setando somente o valor para :creditosplayer em:

$query->bindValue(':creditosplayer', $creditosplayer);

Faça:

$query->bindValue(':creditosplayer', $creditosplayer);
$query->bindValue(':user', $username);
Comment: puts tinha me esquecido desse detalhe hehe muito obriado


Why does this alternative to the Quadratic Formula not always work? $x=\frac1a\left(-b+\sqrt{\frac12(b^2-2ac\pm b\sqrt{b^2-4ac})}\right)$

Question: I was playing with quadratic formula a while ago and I was able to accidentally arrive at:
$$x=\frac{1}{a}\left(-b+\sqrt{\frac{(b^2-2ac)±b\sqrt{b^2-4ac}}{2}}\right) \tag{1}$$
However, I have not been able to solve it from scratch but I simplified it in some way to arrive back at the general quadratic equation. Here we go:
$$x=\frac{1}{a}\left(-b+\sqrt{\frac{(b^2-2ac)±b\sqrt{b^2-4ac}}{2}}\right)$$
$$2(ax+b)^2=b^2-2ac±b\sqrt{b^2-4ac}$$
$$2a^2x^2+4abx+b^2+2ac=±b\sqrt{b^2-4ac}$$
From the original quadratic formula, we know that
$$2ax+b=±\sqrt{b^2-4ac}$$
So
$$2a^2x^2+4abx+b^2+2ac=b(2ax+b)$$
$$2a^2x^2+2abx+2ac=0 \tag{2}$$
Dividing (2) by $a$ as $a≠0$, we have
$$ax^2+bx+c=0$$
Looks practically perfect, right?
I gave this to one of the maths experts in my environment for verification. Unfortunately, he was able to give a quadratic equation for which (1) could not solve and that is:
$$x^2-4x+4=0$$
After a thorough re-check through a series of examples, if we let $x_1$ and $x_2$ be the values of (1), i realized that the formula could find only one root if and only if
$$|x_1|=|x_2|$$

Question: what could be wrong with (1)?
I am not claiming to have discovered a new quadratic formula, I am just curious about why (1) doesn't work generally.
Answer: Your formula finds a zero of the polynomial
$$
(a^2 x^2 + 3 a b x + a c + 2 b^2) (a x^2 + b x + c)
$$
So it could be a zero of $a x^2 + b x + c$, but it also could be a zero of $a^2 x^2 + 3 a b x + a c + 2 b^2$.
Comment: @Shuaib Lateef : In your question, where you say "From the original quadratic formula, we know that
$2ax+b=±\sqrt{b^2-4ac}$", you are assuming $x$ is a solution of the equation $ax^s+bx+c=0$ so it shouldn't be a surprise  that you end up with this equation at the end of your reasoning. If you hadn't used this you would have ended up with the other  equation mentioned by GEdgar as another possibility.
Comment: thanks for adding another equation for which it could probably solve. However, how is that enough to answer my question?
Answer: I see two problematic steps in your derivation. One is the very first step of your calculations. You get
$$2(ax+b)^2=b^2-2ac±b\sqrt{b^2-4ac}, \tag2$$
which is a true equation in all cases where $x$ is a solution of $p(x)=ax^2+bx+c=0.$
But it is possible that for one or both of the true roots of $p(x)$ the expression $ax+b$ is negative, whereas your formula takes the positive square root of the right-hand side of $(2)$ and therefore is consistent with the original problem only for roots $x$ such that $ax+b\geq 0.$
This causes you not to find the correct root in such cases.
The other problematic step is at the end, where you suppose it is OK to replace the $x$ on the right side of
$$a^2+2bx+c = bx \tag3$$
with the formula for the two roots of $p(x).$
By doing this, you have actually created two quadratic equations, one for each root of $p(x).$
If $x_1$ and $x_2$ are those roots, one of the equations you have created is
$$a^2+2bx+c = bx_1, \tag4$$
and while it is true that $x_1$ is a root of $(4),$ $x_2$ is not generally a root. Usually $(4)$ will have two roots and one will be spurious, that is, introduced by this step and not a solution of the original equation.
If we run your derivation backwards, it first introduces up to two spurious solutions by introducing two new quadratic equations, and then it loses up to two solutions by taking a positive square root for each of the new quadratic equations.
For example, try $x^2-3x+2.$
For that equation, $ax+b$ is negative for both roots, so your formula gives two wrong answers.
Comment: I get it now. Thanks for you answer.
Answer: Here is a better alternative for the quadratic formula:
Start with $ax^2+bx+c=0$.  We complete the square ... backwards, so to speak:
$(a-\frac{b^2}{4c})x^2+(\frac{b^2}{4c})(x+\frac{b}{2c})^2=0$
$(a-\frac{b^2}{4c})+(\frac{b^2}{4c})(1+\frac{b}{2cx})^2=0$
$(b+\frac{1}{2cx})^2=b^2-4ac$
$\color{blue}{x=\dfrac{2c}{-b\pm\sqrt{b^2-4ac}}}$
This formula finds use in computer programming, where it gives a better-conditioned result than the usual version of the quadratic formula when $|a|<|c|$. It also avoids division by zero if we are analyzing conditions where $c$ does not change sign but $a$ does so.


limit order quantity in drupal commerce

Question: In my website I would like to limit product quantity to 1, meaning is that user can order only one of a product in one order. And my question is how to configure to set maximum quantity to 1 . Any suggestion is greatly appreciated.
Thanks.
Answer: You can achieve this using Rules by following steps given below:

Event: After udpdating an already existing line item
Conditions: 1/ data comparison: commerce-line-item:type = product 2/
  data comparison: commerce-line-item:commerce-product:type = Your given
  product type 3/ data comparison: commerce-line-item:quantity is
  greater than 1
Action:
  - set data value: commerce-line-item:quantity 1
  - display custom message

Reference: https://drupalcommerce.org/questions/8066/how-limit-maximum-quantity-1-one-given-product-type
Comment: - display custom message does not find in action, I am stuck on -display custom message. thanks
Comment: Its under **System** as **Show a message on the site**
Answer: I found this link, it is very simple. http://bonify.io/blog/2014/09/limit-quantity-when-adding-product-cart

Events

Before saving a commerce line item

condition

Entity is of bundle
data selector: commerce-line-item, value: product
Data comparison
Data to compare : commerce-line-item:commerce-product:product-id, operator: equal, Value:1

Action

set a data value
data: commerce-line-item:quantity, value: 1
Save Entity
Data selector: commerce-line-item,
Show a message on the site
Message: This product only available for 1., Value: warning
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Answer: October 2022:  Running Commerce Core on Drupal 7
So I struggled with this.  On my website we sell digital products so the quantity never needed to be larger than one.  I tried using spinners to prevent double clicking on the "Add to Cart" buttons but somehow users still found ways to double click.  I still don't know how but they did.  I started my solution from trying to follow the drupal commerce user guide.
https://docs.drupalcommerce.org/commerce1/user-guide/shopping-cart/working-with-cart-rules-events
The problem I ran into was that when I tried to set the condition to
commerce-line-item:quantity > 1  it tried to force me to use data selectors which doesn't give me any value option.
The only thing I could do was set
commerce-line-item:quantity = 2 and then the routine would work.   But if someone triple and went really crazy with the clicks this would not work because the QTY would get to three before the rule would finish firing.   I then tried adding more conditions in an OR statement but found the performance of the rule was unreliable even in non stress situations.    THEN THE EUREKA MOMENT.
I didn't need any condition since everything on my website is to be set to 1.   So no product type conditions, no pre-existing quantity conditions, etc... needed to be checked.
So here is what appears to be working for me.  I'll come back and edit this if it fails at any point.

Create new Rule
Set Event to "After adding a product to the cart"
Set Actions to
1st Action:  Set a Data Value    commerce-line-item:quantity = 1
2nd Action:  Set Save Entity     commerce-line-item:order   I left "Force Immediate Save to false (or unchecked).

Comments:  On my website you must be logged in to make a purchase.  It appears to work for regular registered users and the admin role.   I'll come back and update if I have any new problems with this running.   What this routine does is make sure that after the user has finally stopped clicking the "Add to Cart" button,  line item quantity is set back to 1 and the cart is recalculated.   I imagine it increases the "Add to Cart" time a little bit.    But it should be worth it not to have calls from people that didn't realize they had overpaid because they added the product to the cart twice.  I'm a bit surprised but it happens all the time.  Especially on my website cause when I was on drupal 6 I used a different commerce solution and forcing a quantity of 1 was already coded in.  So many customers never bothered to check.

limit order quantity in drupal commerce


Beta reduction Lambda calculus example

Question: (λw. w) (λu. λv. u) (λu. λv. v) (λu. λv. u)
Can anyone give me a step by step Beta reduction of this example?
I'm really confused
Comment: What part are you stuck on? How far can you get by yourself? Do you know how to beta-reduce anything? Do you know what alpha conversion is?
Comment: [Does this example help?](https://stackoverflow.com/a/59841496/)
Answer: (λw. w) (λu. λv. u) (λu. λv. v) (λu. λv. u)
Apply (λw. w) to (λu. λv. u). As this is the identity function, nothing changes.
(λu. λv. u) (λu. λv. v) (λu. λv. u)
Apply (λu. λv. u) to (λu. λv. v). It is substituted for u in the expression. Since we now might get confused by the multiple v's in our first expression, we can alpha rename the v's in the inner expression to another variable, x.
(λv. (λu. λx. x)) (λu. λv. u)
Apply (λv. (λu. λx. x)) to (λu. λv. u). Since v does not appear in the lambda's body, the argument is effectively discarded.
(λu. λx. x)
We can now (optionally) alpha rename again to restore the original variable names.
(λu. λv. v)

Beta reduction Lambda calculus example


Consider $\left(\frac{z-2}{z}\right)^4 = 1$ then solve $z^3-3z^2+4z-2=0$

Question: Consider $\left(\frac{z-2}{z}\right)^4=1$ then solve for the roots of $z^3-3z^2+4z-2=0$
First consider $$\left(\frac{z-2}{z}\right)^4=1$$
Let $$w^4=\left(\frac{z-2}{z}\right)^4=1$$ $$w^4=1$$
Now work this into its polar form
In cartesian form $w^4=1$ $\rightarrow$ $w^4=1+0i$
Recognize that this is a straight line on the right hand side of the real axis. A triangle with opposite side 0 and adjacent 1.
$$tan^{1}(\theta) = \frac{0}{1}$$ $$\theta=0$$
Also $r = \sqrt{1^2+0^2}=1$
Hence polar form is $$w^4=e^{0i}$$
So $$w^4=(e^{0i})$$
Using De moivre's theorem we find that $$(w^4)^{\frac{1}{4}}=w=(e^{0i})^{\frac{1}{4}}$$
$$w=e^{0i}$$
Because we're finding the root to the power of 4 we have 4 answers just like real number. We can find the next 3 answers by $$0+\frac{2\pi k}{4} \space  \space  \space k=0,1,2,3,4 $$
$$\theta = 0, \frac{pi}{2}, \pi, \frac{3\pi}{2}, 2\pi$$
in which $$w=1,i,-1,-i$$
If  $$w^4=\left(\frac{z-2}{z}\right)^4$$ $$w=\left(\frac{z-2}{z}\right)=1,i,-1,-i$$
At $w=1$ w is undefined
At $w=i, \space z=\frac{1+i}{2}$
At $w=-1, \space z=1$
At $w=-i, \space z=\frac{1-i}{2}$
I got lost after that
Comment: Is my hint below helpful? If you're trying to prove $z^3-3z^2+4z-2=0$ given $z^4=(z-2)^4$ then the hint is the answer. If you're actually solving $z^3-3z^2+4z-2=0$ then the hint provides the factorisation from which the answer is immmediate: $z=1$, and $z=1\pm i$.
Comment: Hey sorry i meant to say "solve for the roots"
Comment: As I said above, the factorisation would help with that. Good luck.
Answer: Hint: $z^4-(z-2)^4=8(z-1)(z^2-2z+2)=8(z^3-3z^2+4z-2).$
Answer: Hey i got that if i you expand $w^4$ you get....
$$w^4=\frac{z^4-8z^3+24z^2-32z+16}{z^4}=1$$ $$z^4-8z^3+24z^2-32z+16=z^4$$
$$-8z^3+24z^2-32z+16=z^4-z^4$$ $$-8z^3+24z^2-32z+16=0$$ $$-8(z^3-3z^2+4z-2)=0$$
Hence $z^3-3z^2+4z-2 = 0 = -8w^4$ since constant factors do not affect roots then roots stay the same as with $w^4$ hence $z= 1+i, 1-i, 1$


Capturar dados do Json (Array) e colocar no HTML

Question: Galera, estou com uma dificuldade em capturar os itens dentro de um objeto no Json.
Segue o código abaixo para exemplificar.
 var tipos = [
    {
        "code": "258",
        "label": "Sapatos"
    },
    {
        "code": "547",
        "label": "Kits"
    },
    {
        "code": "1213",
        "label": "Whey Protein"
    },
    {
        "code": "3110",
        "label": "Bolas"
    },
    {
        "code": "4316",
        "label": "Camisas de Time"
    },
    {
        "code": "1251",
        "label": "Cuecas"
    }];

console.log(tipos)
Eu consigo capturar todo array dando o console.log()

O problema é que eu preciso associar isso no html, tipo , criar um botão (input) onde o usuário irá colar somente o nome dos tipos de produtos e irá retornar o código, ou vice e versa.
Seria mais ou menos assim
O usuário digita Bolas e deverá retornar  {"code": "3110", "label": "Bolas"},
Se ele digitar Bolas, Kits, deverá retornar {"code": "3110", "label": "Bolas"},  {"code": "547","label": "Kits"}
Muito obrigado pela ajuda!
Comment: Cara, botão não é digitável, é um elemento para receber click.
Comment: Na verdade eu me expressei mal, não seria botão , seria uma caixa de texto/pesquisa.
Comment: Utilize [**Array.filter**](https://pt.stackoverflow.com/search?q=array.filter) para filtrar os elementos.
Answer: Olha, não sei se eu entendi bem, se interpretei errado, perdoe-me, mas pelo visto, o quê procura é um sistema do tipo "autocomplete"?
Eu utilizei a biblioteca easy-autocomplete.js. Li a documentação e adaptei um dos exemplo do próprio site abaixo. Veja se é isto que procura, amigo.

var options = {
 data: [{"name": "Bolas", "code": "STZ998"}, {"name": "Sapatos", "code": "CTX456"}],

getValue: "name",

 template: {
  type: "description",
  fields: {
   description: "code"
  }
 }

};

$("#provider-json").easyAutocomplete(options);

Digite "Bolas" ou "Sapatos"
<input id="provider-json" placeholder="Digite..." />

Fonte: http://easyautocomplete.com
Answer: Pode usar .filter() depois de fazer um .split() no que foi digitado, considerando que o texto digitado pode ser separado por vírgula, conforme informado na pergunta (ex.: Kits, Bolas).
Também utilizei um .map() para fazer um .trim() (eliminar espaços nas bordas) e utilizei .toLowerCase() para deixar case insensitive (irá encontrar maiúsculas ou minúsculas) tornando mais flexível a busca.

var tipos = [ { "code": "258", "label": "Sapatos" }, { "code": "547", "label": "Kits" }, { "code": "1213", "label": "Whey Protein" }, { "code": "3110", "label": "Bolas" }, { "code": "4316", "label": "Camisas de Time" }, { "code": "1251", "label": "Cuecas" }];

function buscar(){
   var texto = document.body.querySelector("#texto").value;

   // converte em array e elimina espaços indesejados nas bordas
   // e converte para minúsculo, pare evitar o case sensitive
   var texto_array = texto.split(",").map(function(i){
      return i.trim().toLowerCase();
   });

   var resultado = tipos.filter(function(e){
      return ~texto_array.indexOf(e.label.toLowerCase());
   });

   // imprimir numa div
   var res = document.body.querySelector("#resultado");
   res.innerHTML = '';
   for(var item of resultado){
      res.innerHTML += "Código: "+item.code
      +"
Tipo: "+item.label+"

";
   }
}

Digite o que quer buscar:

<input type="text" id="texto" value="Kits, bolas,camisas de Time">

<input type="button" value="Buscar" onclick="buscar()">


Getting return value from the stored procedure

Question: I have written a procedure as following:
ALTER PROC ReturnProc
AS
BEGIN
  RETURN 5
END

I am trying to get the return value from the Procedure in the following way:
com.CommandText = "ReturnProc";
com.CommandType = CommandType.StoredProcedure;

SqlParameter parameterReturnValue = new SqlParameter();
parameterReturnValue.Direction = ParameterDirection.ReturnValue;
com.Parameters.Add(parameterReturnValue);

con.Open();
tran = con.BeginTransaction();
com.Transaction = tran;
com.ExecuteNonQuery();
tran.Commit();

//Get the return value
iReturn = Convert.ToInt64(parameterReturnValue.Value);

I failed to get the return value after execution. In the real scenario, I am concatenating the parameters with the procedure, rather than adding them in SqlParameter list.
Could anybody help me on this?
Comment: I don't know what is happening at your site - it works just fine here, I get the value "5" back (but *why* are you converting that to an `Int64` ??)
Answer: I think you have to retrieve the value from the Parameters collection. See How can I get Stored Procedure return value in C#?


How do I prove that $\min_\Phi x'x-x'\Phi(\Phi'\Phi)^{-1}\Phi'x$ equivalent to $\max_\Phi tr(x'\Phi(\Phi'\Phi)^{-1}\Phi'x)$?

Question: How do I prove that $\min_\Phi x'x-x'\Phi(\Phi'\Phi)^{-1}\Phi'x$ equivalent to $\max_\Phi tr(x'\Phi(\Phi'\Phi)^{-1}\Phi'x)$ where $x$ is an $N\times T$ matrix and $\Phi$ is an $N\times r$ matrix?
Answer: We are minimizing a function of the form $a - f(\Phi)$. Your statement follows from the fact that
$$
\min_{\Phi} a - f(\Phi) = a + \min_{\Phi} (-f(\Phi)) = a - \max_{\Phi}f(\Phi).
$$


Pythonista 3 connect sqllite3 database to table view

Question: Trying to connect sqlite3 database to my tableview in ui form (On my iPad). Used many cases but without result.
<code>      import ui
      import sqlite3

      def loadData (self):
      connection = sqlite3.connect('pythonsqlite.db')
      query = "SELECT * FROM projects"
      result = connection.execute(query)
      self.tableview1.setRowCount(0)
      for row_number, row_data in enumerate(result):
      self tableview1.insertRow(row_number)
      for column_number, data in enumerate(row_data):
      self.tableview1.setItem(row_number, column_number)
      connection.close()

      ui.load_view('MyForm').present('sheet')
</code>
It gives me
<code>     self tableview1.insertRow(row_number)
              ^
     SyntaxError: invalid syntax
</code>
Can anybody give me any direction?
Comment: what's the error you're encountering?
Comment: post your error also
Answer: <code>     import ui
     import sqlite3 as db

     tv = ui.TableView('tableview1')
     conn = db.connect('pythonsqlite.db')
     conn.row_factory = lambda cursor, row: row[0]
     c = conn.cursor()
     ids = c.execute('SELECT name FROM projects').fetchall()
     print(ids)

     tv.data_source = ui.ListDataSource(ids)
     tv.present('fullscreen')

     ui.load_view('MyForm').present('sheet')
</code>
I can create custom tableview, but can't pass data to existing one in my ui form.
Answer: Here's a minimal example showing how to refer to a UI designer element in your code.
<code>import ui

v = ui.load_view()
v['tableview1'].background_color = 'grey'

v.present('fullscreen')
</code>
Comment: Thank you so much, I did it. But how it works if you have multiple columns? Is it customtableviewcell?


Can't access download page for webform submissions

Question: Basically, we're running into an issue where we're being returned a HTTP error 500 when trying to view the webform submissions download page, i.e. the following page:
https://www.hartmanns.dk/en/admin/structure/webform/manage/hartmanns_academy_08_september/results/download
When trying to access our download page, we see a HTTP error 500 with the following logs:
<code>AH01071: Got error 'PHP message: PHP Fatal error: Declaration of Drupal\\webform\\Plugin\\WebformElement\\WebformSignature::accessFileDownload($uri) must be compatible with Drupal\\webform\\Plugin\\WebformElementFileDownloadAccessInterface::accessFileDownload(string $uri) in /var/www/vhosts/hartmanns.dk/httpdocs/web/modules/contrib/webform/src/Plugin/WebformElement/WebformSignature.php on line 30\n', referer: https://www.hartmanns.dk/en/admin/structure/webform/manage/hartmanns_academy_08_september/results/submissions
</code>
Have any of you run into this issue? We've tried clearing cache, setting the correct permissions etc., however, from the logs it seems to be an incompatibility issue.
We're running Drupal core 8.9.20 & Webform 6.1.3.
Any help is greatly appreciated. :)
Answer: I googled your error message and this webform issue was the second result.
This has already been committed so you can try upgrading to the 6.2 beta which will hopefully fix the issue-- except you are on Drupal 8, which has been unsupported since November 30, 2021, and 6.2 requires Drupal 9.2+.
Really you should update to Drupal 9 ASAP and then update Webform, but if you can't wait you could try the patches in the linked issue.
Comment: Thank you so much for reponding! What did you Google to reach this result? I felt like I had searched every variation of this issue above, and I got so many unrelated pages.. :)

I will try to implement your feedback and let you know what's up!
Comment: @OliverLauridsen The exact phrase I googled is `PHP Fatal error: Declaration of Drupal\\webform\\Plugin\\WebformElement\\WebformSignature::accessFileDownload($uri) must be compatible with Drupal\\webform\\Plugin\\WebformElementFileDownloadAccessInterface::accessFileDownload(string $uri) ` When googling Drupal error messages, you want to search for the `PHP Fatal error: ...` part but exclude `in /var/www/vhosts/hartmanns.dk/...` because that is the path unique to your site which will not have any hits.
Comment: Thank you so much Patrick. I'm very new to Drupal as you might be able to tell.. You've been tremendously helpful!


301 Redirect index.php?dir= to a folder?

Question: I want to redirect the following
http://www.example.com/folder/index.php?dir=Dir1
http://www.example.com/folder/index.php?dir=Dir1/Dir2

to
http://www.example.com/folder/Dir1
http://www.example.com/folder/Dir1/Dir2

I want to "301 Redirect" it NOT "Rewrite" i.e I want the "index.php?dir=" link to 301 redirect to folder structure.Please advice?
Answer: RewriteCond %{QUERY_STRING}  ^dir=(.*)$
RewriteRule ^folder/index\.php$  folder/%1 [L,R=302]

change to 301 once working.
Comment: This doesn't works at all! The index.php?dir= remains in the URL!
Answer: Do this in your DocumentRoot .htaccess.
Options +FollowSymLinks

RewriteEngine On
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

RewriteCond %{QUERY_STRING}  ^dir=(.*)$ [NC]
RewriteRule ^  folder/%1? [L,R=301]

RewriteRule ^folder/(.+)/? folder/index.php?dir=$1 [L,QSA]

Comment: I think you've misunderstood the question (or I haven't explained in detail). I just want the "index.php?dir=" to go away. The dir1/dir2 was just an example! Anyways your code goes into a redirection loop.
Comment: @user1170540 try now. Observe the order or rewrite rule.
Comment: Still redirection loop! Why are you suggesting 'folder/index.php?dir=Dir1/Dir2' above! Dir1 and Dir2 is just a virtual example folder. All I want is everything after /index.php?dir= to be redirected to /
Comment: @user1170540 my bad, I did a oversight. Hadn't noticed `dir=Dir1/Dir2` in my rule. Try now.
Comment: Still redirection loop! :( Any other ideas?
Comment: @user1170540 Am a bit sleepy. Gimme a min.
Comment: Just to clarify a bit more I am writing xyz.com/folder/index.php?dir=Blah and intend it to redirect it to xyz.com/folder/Blah
Comment: @user1170540 check the above. It should definitely work (if it does not conflict with any other rewrites you have in folder `folder`)