Criptografar senha e se logar PHP e PDO

Question: Arquivo login.php
    <?php

    session_start();

    require_once '../includes/config.php';

    if(isset($_REQUEST["post_back"])){

    $tb = $conn->prepare("select nm_usuario, imgPerfil, nome from usuario where nm_usuario=:usuario and senha_usuario=:senha");
    $tb->bindParam(":usuario", $_POST["usuario"], PDO::PARAM_STR);
    $tb->bindParam(":senha", $_POST["senha"], PDO::PARAM_STR);
    $tb->execute();
    $l = $tb->fetch(PDO::FETCH_ASSOC);
    $tb = null;
    if(!empty($l)){

    $_SESSION["usuario"] = $l["nm_usuario"]; // Pegar o Usuario logado
    $_SESSION["imgPerfil"] = $l["imgPerfil"]; // Pegar a imagem do perfil
    $_SESSION["nome"] = $l["nome"];           // Pegar o nome do Usuario logado
    header("Location: ../inicial.php");

    }else{

    echo("");
    echo("");

    }

    }
    ?>

Abaixo o arquivo verifica.php
    <?php
    session_start();
    if(!isset($_SESSION["usuario"])){
    header("Location: index.php");
    exit;
    }
    ?>

Abaixo o arquivo sair.php
    <?php
    session_start();

    unset($_SESSION["usuario"]);
    unset($_SESSION["imgPerfil"]);
    unset($_SESSION["nome"]);
    session_destroy();

    header("Location: ../index.php");
    ?>

E abaixo o arquivo index.php onde sera feito o login:
    <?php
    session_start();
    if(isset($_SESSION["usuario"])){
    header("Location: inicial.php");
    exit;
    }
    ?>

    <meta charset="utf-8" />
    <title>Painel de Controle - Portal WVD</title>
    <link rel="stylesheet" type="text/css" href="css/default.css" media="screen" />

        <form id="form1" name="form1" method="post" action="acoes/login.php">

Painel de Controle

            Usuario:
            <input type="text" name="usuario" id="user-name" />

            Senha:
            <input type="password" name="senha" id="user-pass" />

            v<input type="submit" name="post_back" id="user-login"                value="Iniciar Sessão" />

    </form>

Gostaria de saber se este código está correto, se tem como simplificar e gostaria de criptografar a senha mais ainda não tenho experiência em qual criptografia usar.
Answer: O PHP já vem com algumas funções que lhe podem ajudar para encriptar e decriptar.
Veja a documentação:
MD5 e
Crypt
Entretanto é sempre bom ter um algoritmo próprio de encriptação.
Ex:
<?php
class Hash {
private $hasBlowfish;
public function __construct() {
    self::$hasBlowfish = ( CRYPT_BLOWFISH === 1 ) ? TRUE : FALSE;
}
/**
 * Gera um 'salt' único de 22 chars para encriptar password
 * com o algoritmo blowfish.
 *
 * @return String - A unique salt string.
 */
public static function uniqueSalt() {
    return substr( sha1( mt_rand() ), 0, 22 );
}
/**
 * Cria um hash a partir de uma string/password.
 *
 * O hash é gerado com o algortitmo blowfish com um
 * custo 10.
 *
 * @return String - A blowfish, cost-10, hashed password.
 */
public static function hashPassword( $pass ) {
    // if ( ! self::$hasBlowfish ) {
    //     die( 'O servidor não suporta encriptação blowfish...' );
    // }
    return crypt( $pass, '$2a$10$' . self::uniqueSalt() );
}
/**
 * Verifica se um plain password é igual ao password
 * já hasheado. O password já hasheado vem do DB, por exemplo.
 *
 * @return Boolean TRUE if the passwords are the same, FALSE otherwise.
 */
public static function checkPasswords( $DbHashedPassword, $plainPassword ) {
    // Na verdade, nem precisa explicitamente pegar os primeiros 29 chars,
    // já que crypt() automaticamente descarta caracteres excedentes.
    $salt = substr( $DbHashedPassword, 0, 29 );
    $newHash = crypt( $plainPassword, $salt );
    return ( $DbHashedPassword == $newHash );
}
}

Criptografar senha e se logar PHP e PDO


Is there a way to modify a power bi field parameters via rest api?

Question: There is something called  Field parameters in Power BI Desktop. If a am to embed it on Web Applications, is there a way now to directly change it's value?
Answer: You can create multiple field parameters in Power BI Desktop and With the Edit API and In edit mode you can switch between the parameters. But can't change the parameter formula itself in the Embedded


Somar o valor total de determinada coluna para cada tabela - MySQL

Question: Tenho a seguinte query:
SELECT FORMAT(valor,2,'de_DE') AS valor,
       DATE_FORMAT(data_vencimento, '%d/%m/%Y') AS data_vencimento,
       realizado,
       DATE_FORMAT(data_realizado, '%d/%m/%Y') AS data_realizado,
       parcelas,
       numero_parcela,
       observacoes,
       lancamento,
       tipo_movimento,
       tipo,
       id_usuario
FROM
  (SELECT r.valor_receita AS valor,
          r.data_vencimento AS data_vencimento,
          r.recebido AS realizado,
          r.data_recebimento AS data_realizado,
          r.parcelas AS parcelas,
          r.numero_parcela AS numero_parcela,
          r.observacoes AS observacoes,
          'Receita' AS lancamento,
          re.tipo_recebimento AS tipo_movimento,
          tr.tipo_receita AS tipo,
          r.id_usuario AS id_usuario
   FROM receitas AS r
   INNER JOIN tipo_receita AS tr ON (r.id_tipo_receita = tr.id_tipo_receita)
   INNER JOIN tipo_recebimento AS re ON (r.id_tipo_recebimento = re.id_tipo_recebimento)
   UNION SELECT d.valor_despesa AS valor,
                d.data_vencimento AS data_vencimento,
                d.pago AS realizado,
                d.data_pagamento AS data_realizado,
                d.parcelas AS parcelas,
                d.numero_parcela AS numero_parcela,
                d.observacoes AS observacoes,
                c.nome_categoria AS lancamento,
                tp.tipo_pagamento AS tipo_movimento,
                td.tipo_despesa AS tipo,
                d.id_usuario AS id_usuario
   FROM despesas AS d
   INNER JOIN tipo_despesa AS td ON (d.id_tipo_despesa = td.id_tipo_despesa)
   INNER JOIN tipo_pagamento AS tp ON (d.id_tipo_pagamento = tp.id_tipo_pagamento)
   INNER JOIN categorias AS c ON (td.id_categoria = c.id_categoria)) AS origem
WHERE id_usuario = 1

Quero saber como fazer para adicionar duas colunas, uma que some o valor_receita (total) da tabela receitas, e a outra que some o valor_despesa (total) da tabela despesas.
Tabelas: https://pastebin.com/rexcXTKw
Answer: Você pode fazer assim, coloca antes do FROM.
(SELECT SUM(valor_receita) FROM tabela_receitas) AS total_receita,
(SELECT SUM(valor_despesa) FROM tabela_despesas) AS total_despesa
Comment: Seria mais ou menos isso, porém, estou passando alguns filtros no código PHP pra incrementar a query. Aí tem que ser o valor total baseado nesse filtro tbm.
Comment: SUM(r.valor_receita) AS total_receita, ai vai somar só os valores dos registros encontrados
Comment: Dessa forma só retorna um registro.. e não todos
Comment: Dá um GROUP BY id_receita, id_despesas, você pode simplificar e fazer duas consultas, uma para saber o valor de receitas e outra de despesas.
Answer: tenta assim, talvez tenha de fazer outro group by/sum
SELECT FORMAT(valor_receita,2,'de_DE') AS valor_receita,
       FORMAT(valor_despesa,2,'de_DE') AS valor_despesa,
       DATE_FORMAT(data_vencimento, '%d/%m/%Y') AS data_vencimento,
       realizado,
       DATE_FORMAT(data_realizado, '%d/%m/%Y') AS data_realizado,
       parcelas,
       numero_parcela,
       observacoes,
       lancamento,
       tipo_movimento,
       tipo,
       id_usuario
FROM
  (SELECT r.valor_receita AS valor_receita,
          0 as valor_despesa,
          r.data_vencimento AS data_vencimento,
          r.recebido AS realizado,
          r.data_recebimento AS data_realizado,
          r.parcelas AS parcelas,
          r.numero_parcela AS numero_parcela,
          r.observacoes AS observacoes,
          'Receita' AS lancamento,
          re.tipo_recebimento AS tipo_movimento,
          tr.tipo_receita AS tipo,
          r.id_usuario AS id_usuario
   FROM receitas AS r
   INNER JOIN tipo_receita AS tr ON (r.id_tipo_receita = tr.id_tipo_receita)
   INNER JOIN tipo_recebimento AS re ON (r.id_tipo_recebimento = re.id_tipo_recebimento)
   UNION
   SELECT   0 AS valor_receita,
            d.valor_despesa AS valor_despesa,
            d.data_vencimento AS data_vencimento,
            d.pago AS realizado,
            d.data_pagamento AS data_realizado,
            d.parcelas AS parcelas,
            d.numero_parcela AS numero_parcela,
            d.observacoes AS observacoes,
            c.nome_categoria AS lancamento,
            tp.tipo_pagamento AS tipo_movimento,
            td.tipo_despesa AS tipo,
            d.id_usuario AS id_usuario
   FROM despesas AS d
   INNER JOIN tipo_despesa AS td ON (d.id_tipo_despesa = td.id_tipo_despesa)
   INNER JOIN tipo_pagamento AS tp ON (d.id_tipo_pagamento = tp.id_tipo_pagamento)
   INNER JOIN categorias AS c ON (td.id_categoria = c.id_categoria)) AS origem
WHERE id_usuario = 1


Expected time for $N$ cars to move $N$ spaces without overtaking

Question: I was asked this problem at an interview, I had no clue of how to solve it, can someone help?
Suppose that we have $N$ cars parked in a line occupying spaces $1$ to $N$. Spaces $N+1$ to $2N$ are empty. Every minute, a car is considered eligible to move forward one space if:
a) the space in front of them (space $i+1$) is empty, and
b) its space number, $i$, is less than $2N$.
Suppose that every minute, if a car is eligible to move, then it has a $1/2$ chance of moving forward by one space. What is the expected number of minutes before the cars occupy squares $N+1$ to $2N$?
Comment: "I had no clue of how to solve it"  Have you thought about working through some simple cases?  What if $N=1$? or $N=2$?  Can you work it out in those cases and try to generalize?
Comment: [this question](https://math.stackexchange.com/questions/4733006/interesting-expected-value-question-about-cars) was asked before though it received no complete solution.  There are some numerically computed results on the duplicate.  I would imagine that the goal is to get asymptotics for the growth, but perhaps I am missing something.
Comment: So the upper bound is $O(N^2)$. However, I am guessing the true time is $O(N^{1.5})$, at least that seems achievable since intuitively if we wait order $N^{.5}$ time before sending out each new car, with "high" probability we will not have collisions/blockages. So $N(N^{.5})+2N =O(N^{1.5})$.
Comment: What does (b) mean? Ostensibly it suggests car $N$ can never move since $N^2>2N$ (assuming $N>2$).
Comment: @Michael I think that it is clear from the context of the question that the spots the cars are parked on are squares.  Hence each square has a number from 1 through $2N$.  These squares are mentioned in the second sentence of the problem, and in the last paragraph.
Comment: Oh. It calls the locations "spaces" several times and I didn't notice it once referred to a space as a "square." I assumed (b) referred to self-multiplying either a location index or a car index,neither made sense.
Comment: @Michael I don't **think** it is talking about squaring numbers.  I **think** that those squares are the locations of cars.
Comment: You can get a simple upper bound on the time by waiting until the car in front reaches its forward-most position before letting any other car move. For example it takes avg time $2N$ for the front car to reach its final position, followed by another $2N$ and so on. The difficulty is that many cars can move at once and the Markov state is complicated.
Comment: I've edited the problem statement to clear out the confusion.
Comment: are you expecting a precise formula or just asymptotics?
Comment: Not a precise formula but kind of algorithm/steps to get to answer for a given N
Answer:
The problem is more complicated than I thought in the first place. All I could manage is to produce this picture (every column is one configuration of parking, black dots are the cars, white spots are empty lots, there are N=20 cars).
It is quite clear, that $N-1$ is the minimum number of parking configurations one has to go through.
However, allowing the advancement of a car only with probability $p=1/2$ implies that the first car, which is never blocked by another car, arrives parking spot $2N$ after a negative binomial time (parameters N and 1/2). That gives an average $2N$ for the time until the first car hits parking slot $2N$.
For the other cars it is more complicated. They block each other sometimes. The simulation shows how that slows down the other cars.
Searching on a famous search engine, i could find only similar problems that are called "parking functions". There are a number of papers on that topic, beginning from the 60s, but is not the same setup as here. But maybe there are some references somewhere in there.
I cannot imagine this to be an interview question. Either there is a trivial answer that I do not see. Or, it is an open problem and the interviewer wanted to see your reaction on non-trivial, hard problems. Sorry, I cannot provide any answers. But the simulation shows at least, that $N^2/2$ is not the answer (for the simulation above, i got 180.9 as an average after 20 runs).
Either way, it is an interesting question!
Comment: Yeah, I worked through a couple of small cases, realized that the complexity was likely to be quite high, and decided that I didn't really care enough about the problem to continue.  I don't see an obvious way of obtaining a "nice" closed formula, though (as you point out) there are some easy-ish lower bounds.  It may be that the solution is to just run a bunch of simulations (which is probably where I would have landed in an interview:  "Oh, even small cases blow up; here are some obvious lower bounds; let's simulate."
Answer: Ran a simulation for cars ranging from $1\ldots M$, doing 10 runs per number of cars. These are the results I got (see pics). I've also attached the source code in case my way of simulating is wrong.
It looks like it's almost perfectly linear as a function of M (haven't tested really large values yet)
EV parking from $N$ in $1$ to $100$, $10$ per $N$:

src code 1
src code 2
EDIT: I realized I forgot to remove the upper bound of $1000$ on the minutes. Haven't updated the pictures but for those who want to run the script, just remove that as a condition checked in the while loop
EDIT 2: src code as text as requested:
import random
import time
import sys
import matplotlib.pyplot as plt
import numpy as np

# check whether all of the cars
# are in their required positions
def match_positions(pos):
    N = len(los)//2
    M = len(pos)
    for i in range(N, M):
        if pos[i] == 0:
            return False

    return True

def run(N):
    minutes = 0

    # this represents the
    # occupied positions
    # pos[i] = 1 --> ith car park space is filled

    pos = []
    # represents the positions
    # of ith car
    car_pos = []
    for i in range(N):
        pos.append(1)
        car_pos.append(i)
    for _ in range(N):
        pos.append(0)

    can_move = [0]*N

    while not match_positions(pos):
        for i in range(N):
            # simulate by a coin toss with whether
            # or not the ith car can move
            # that is, if can_move[i] = 1 then ith car
            # tries to move 1 step up
            can_move[i] = random.randint(0, 1)

        for i in range(N):
            if can_move[i] == 1:
                prev_pos = car_pos[i]

                inc = prev_pos + 1
                # if ith car can move and it's not blocked up ahead
                # it moves up 1 step from its previous pos
                if inc < 2*N and pos[inc] != 1:
                    # incremented car park position gets occupied. previous is 0
                    pos[inc] = 1
                    pos[prev_pos] = 0

        minutes += 1 # increment time-step

    return minutes

if __name__ == "__main__":

    # repeat experiment for 1..N cars
    N = int(input("Enter the range of N: "))
    # for k cars, run experiment M times
    M = int(input("Enter M: "))
    averages = []
    for k in range(1, N+1):
        times = []
        for _ in range(M):
            times.append(run(k))
        mean = sum(times)/len(times)
        averages.append(mean)

    plt.plot(averages)
    plt.show()

    # sample correlation coeff against the number of cars
    n_cars = [ k for k in range(1, N+1) ]
    coeff = np.corrcoeff(n_cars, averages)[0, 1]
    print(coeff)

As a follow-on, using the linearity of expectation I get $O(N)$ behaviour. Can anyone confirm this?
Comment: Would you be willing to transcribe the source code into your answer body such that folks can see it and understand the process without clicking a link?
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Src code transcribed


Where to store data for module

Question: I recently developed my first module. Part of its functionality is to store names, e-mails, and phone numbers of people on a newsletter. They sign up through the front-end and the admin can review and modify them on the backend.
In addition it also stores SMS messages and their details (date sent, number sent from, message, etc) that come in from a short code. This process is triggered by an HTTP request. Again, the admin can review and modify these in the admin of the website.
And finally, the same install will host 15-20 tables with ~20 columns and ~170 rows of health, education, and water quality statistics that can be queried from the website.
So that's everything: newsletter list, sms messages, data
I've never worked with a CMS and added so much to the default database. I also lack a lot of knowledge about databases. So my question is Should I store all this extra information in a different database? My current hosting allows for 20, and I'm only utilizing one.
Let me know if you need any extra information. Thanks in advance!
Comment: Quoting a [very clever guy](http://stackoverflow.com/users/27535/gbn): _Performance is determined by queries and indexes (at the most basic level): not number of objects_. If it was me I'd keep them all in the same database and not worry about the number of tables, unless you notice a serious performance decrease
Answer: I'm afraid you need a long answer for this..
But using a data*base* to store different values like this is not the best way I guess.
You can use multiple databases with Drupal and switch them without a problem. But real question would be, why.
However, you can store categories in different table,and refer the category ID from the main sms message table. It's much easier to JOIN queries and get the data you want,rather than having a table for each category.
Also, I'd suggest using core functionality  when you can. With new entity system in Drupal 7,you can make a new entity, an SMS, and attach fields like category it to.
If you are storing settings of the module, consider using system_settings_form to store settings. You can set/get them using variable_set and variable_get. But make sure that you don't store big text using this.
Good luck!
Comment: ayesh Thank you for directing me towards the entity system. I've been browsing around that and it looks very powerful.

clive Thanks for the quote, that provides a great larger statement for my question.

My reputation doesn't allow me to give either of you credit :(

Where to store data for module


How can I get only some value in list?

Question: import psutil
applist = list(psutil.process_iter())
for app in applist:
    print(app)

It's a script to get running Process in macOS, I got the list and it showed
psutil.Process(pid=12723, name='Google Chrome', status='running', started='13:54:23')

But I only want to get the 'Google Chrome' part, how can I do that? I want to use split(), but it said 'Process' object has no attribute 'split'.
Answer: You can do
import psutil
applist = list(psutil.process_iter())
for app in applist:
    print(app.name())

If you want to know more read relevant psutil.Process docs piece.

How can I get only some value in list?


Let $f(x)$ be a degree $r$ polynomial where $f(0)=p$. Show that $f(kp)$ is divisible by $p$

Question: I am currently taking Real Analysis and am trying to work on the following problem:

You may assume that a polynomial of degree $r$ has at most $r$ roots. Suppose that $$f(x)=\sum_{i=0}^r a_ix^i \quad a_i \in \mathbb{Z} $$
  and that $f(0)=p$. Show that for every integer $k$, $f(kp)$ is divisible by $p$.

I'm not too sure how to go about solving this. I know that
$$f(0) = p \Rightarrow \sum_{i=0}^r a_i = p$$ and that
$$f(kp) = \sum_{i=0}^r a_i (kp)^i = \sum_{i=0}^r a_i k^i p^i$$
and that I seek to show that $f(x) = p\cdot g(x)$ for some other polynomial $g(x)$.
Any suggestions or hints would be appreciated.
Comment: This is wrong: $f(0) = p \implies \sum_{i=0}^r a_i = p$. What you need is: $f(0) = p \implies a_0 = p$.
Answer: If $f(0)=p$, then $a_0=p$ so that $f(kp)=\sum_{i=1}^r a_i(kp)^i+p$ which is clearly divisible by $p$.
Comment: Because $a_0=f(0)$.
Comment: Perhaps you can create another question to deal with (b). Remember to type out all given info in full. Good luck.
Comment: How do you conclude that $f(0) = p$ implies $a_0 = p$?
Comment: How could I show that $f(kp)=p$ with what we have just established?
Comment: We have $f(kp)=\sum_{i=1}^r a_i(kp)^i+p$ so if you want $f(kp)=p$ for any $k$, then either $p=0$ or $a_1=\cdots=a_r=0$. So unless you have either of these, $f(kp)=p$ $\forall k$ is untrue in general.
Comment: Weird, the homework must be wrong then? I'll email the prof tonight and ask about it.
Comment: The homework asks that you show $f(kp)$ is divisible by $p$. It doesn't ask you to show that $f(kp)=p$, does it?
Comment: Part (b) asks to prove that using part (a)


The set of invertible elements of a monoid is closed under multiplication

Question: Let $M$ be a monoid and let $U(M)$ be the set of invertible elements of $M$. How can I prove that $U(M)$ is closed under the binary operation on $M$, i.e., that that $a \in U(M)$ and $b \in U(M)$ implies that $ab \in U(M)$?
Comment: Is $U$ the binary operation on $M$?
Comment: M is a Monoid and U(M) is the set of elements in M that are invertible.
Comment: Thus, you hav to prove that, if $a$ and $b$ are *invertible*, also $ab$ is.
Comment: You have to exploit the definition of [invertible element](https://en.wikipedia.org/wiki/Monoid#Properties) of a monoid.
Comment: yes i know this but still cant see how it works
Answer: Hint: if $a^{-1}$ is the inverse of $a$ and $b^{-1}$ is the inverse of $b$, compute $(ab)(b^{-1}a^{-1})$ and $(b^{-1}a^{-1})(ab)$. What can you conclude?
Comment: That (ab) has an inverse!


How can I permanently increase max_input_vars? The php.ini approach periodically gets overridden

Question: I manage a VPS, where I would like to increase the max_input_vars for one of the WordPress sites that is hosted on the VPS.  To do this, I headed over to /var/www/vhosts/system/example.com/etc/ and entered the following into the enclosed php.ini file:
max_input_vars =4000
Whilst this worked, the file gets overridden periodically and thus I lose my modification.
Is there an alternative way to achieve this modification, without the worry of the php.ini being automatically overridden?
I have tried the following but all have resulted in the website being taken offline:
.htaccess
php_value max_input_vars 4000
wp-config
@ini_set( 'max_input_vars' , 4000 );
Update:  09/01/2020
I have also tried entering php_admin_flag max_input_vars On into the /etc/apache2/apache2.conf file followed by entering max_input_vars =4000 into the /var/www/vhosts/system/example.com/etc/php.ini file.
Unfortunately, the max_input_vars =4000 still gets overridden with the default of 1000 being reset.  Furthermore, this approach produces the following notifications; within the server:

Could I be doing something wrong here?
Comment: You can't set `max_input_vars` using `ini_set`. To make it work in `.htaccess` you need to have specified `AllowOverride Options` or `AllowOverride All`.
Comment: Where would I need to enter `AllowOverride Options` or `AllowOverride All`?
Answer: So, max_input_vars is PHP_INI_PERDIR which means it can be set in either php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3).
PHP only has one solution for preventing local directive overrides (local directives override master directives in PHP so it bubbles from the bottom up) and that's to set an admin_flag on the directive, thus preventing the master configuration from being override locally. To do this it will depend on which PHP SAPI you're using.
mod_php (Apache httpd)
You can set php_admin_flag in your apache config (i.e. virtualhost file or httpd.conf) using php_admin_flag max_input_vars On in your httpd config. This will prevent the loaded value from your php.ini to be overridden by .htaccess or ini_set().
php-fpm (fastcgi)
You can set the php_admin_flag in your php-fpm config or individual pool configs with the syntax php_admin_flag[max_input_vars] = On.
N.B.
However, before proceeding please take under advisement the importance of not setting this directive too high as it can cause a known Denial of Service attack in PHP. From the manual...

Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
Comment: Having run the `apachectl -V` command, it appears the Server Config File can be found at `/etc/apache2/apache2.conf`.  Is this Ubuntu's variant of the `Apache httpd` file you mentioned in your answer?  If so, would I simply need to enter `php_admin_flag max_input_vars On` at the bottom of this `apache2.conf` file?  Does this file not get automatically updated?  How would this prevent the `max_input_vars =4000` entry from being overridden within the `php.ini` file that is located within the `/var/www/vhosts/system/example.com/etc/` directory?  Does it just stop the `php.ini` file being updated?
Comment: It doesn't stop php.ini from being updated. But it will prevent anything lower level than php.ini from overriding a php.ini. It goes like this in PHP (in order of loading configurations) 1. Hardcoded PHP defaults 2. php_admin_value config 3. php.ini 4. Runtime user-level php ini or .htaccess type config 5. runtime ini_set. So if you wanted to prevent even php.ini from changing it you could also set a `php_admin_value`. The `php_admin_flag` simply enforces that the loaded configuration cannot be overridden by runtime configuration directive like those found in .htaccess or ini_set().
Comment: Thank you for your continued support.  Unfortunately, your suggestion is triggering an error as well as resulting in the `max_input_vars =4000` still being overridden.  Could I be misunderstanding your guidance?  I have updated my question with the error message I am seeing.
Comment: You have to set it after mod_php is loaded
Comment: I have tried to get a better understanding of your answer but feel I am just confusing myself here.  You state `This will prevent the loaded value from your php.ini to be overridden by .htaccess`.  I assume this is the `.htaccess` within each websites' `httpdocs` folder?  If so, I cannot seem to change the `max_input_vars` within the `.htaccess` file plus I want to be able to override the `php.ini` file.  I just want to be able to change the `max_input_vars` without it being overridden.
Comment: Those are two contradicting things. I can't help you do both A and B since A directly conflicts with B, but I can help you do one or the other. To be able to override `php.ini` you simply have to do nothing. Leave everything the way it is. All local configurations already override master configurations. To do the exact opposite (*prevent people from overriding php.ini*) you have but to follow the very simple and straight-forward advice given in the answer above. Not sure how else I can possibly answer your question.
Comment: Thank you for your time with the answer.  I have since learned that your suggestion  does not work for some sites that use WooCommerce; since WooCommerce is calling the `max_input_vars` from another source.
Comment: I have no idea what that means, but my suggestions are universal in PHP.


How to show this function is increasing?

Question: Define function
$$f(\alpha)=\frac{-(4-5\alpha-4\alpha^{2})+\sqrt{32\alpha^{3}+\alpha^{2}-40\alpha+16}}{(1-2\alpha)\alpha}=\frac{-(4-5\alpha-4\alpha^{2})+\sqrt{(4-5\alpha-4\alpha^{2})^{2}+8\alpha^2(1+\alpha)(1-2\alpha)}}{(1-2\alpha)\alpha}$$
where $\alpha \in (0,\frac{1}{2})$, in limiting situation, $\alpha$ can tend to $0$ or $0.5$.
I can verify that:
(1) $f(\alpha)\geq 0$ always holds when $\alpha \in (0,\frac{1}{2})$
(2) Using L'Hôpital's rule to show $f(0)=0$ and $f(\frac{1}{2})=6$
I can plot this function via MATLAB and observe this function is increasing when $\alpha \in [0,\frac{1}{2}]$.
My goal is to prove $f(\alpha)$ is increasing in $\alpha \in [0,\frac{1}{2}]$, the geometric graph is simple as following but the verification of increasing is not easy. How to show it?
Comment: Check the sign of the derivative.
Comment: The difficult part is just the first derivative seems to be complex and the sign is not easy to determine(I know it must be positive via simulation). Though the graph is very simple. So I want to know other tricks or some features I ignore.
Comment: Did you try $\alpha = \sin x$ and $x\in (0,\pi/6)$. I don't know if that work. Just idea.
Comment: To determine the sign of the derivative, it suffices to note the derivative is continuous and to find the zeroes of the derivative. Then you only need to check one point.
Comment: i would calculate $$f'(\alpha)$$
Answer: Here is an alternative proof. Since your function is a bit complicated, I've chosen to do this using a function for computing Gröbner bases in Mathematica. The calculation of Gröbner bases can definitely be carried out by hand. However, this proof also relies on your ability to find roots of a single-variable polynomial. As previously noted, $f$ is continuously differentiable in $(0, 1/2)$, so we first test $f'$ at some point in $(0, 1/2)$. For example, $$f'\left(\frac{1}{4}\right) = 8\left(7-\frac{67}{\sqrt{105}}\right)\approx 3.69 > 0$$ Therefore, as $f'$ is continuous in $(0, 1/2)$, if $f'(x) < 0$ for any $x\in (0, 1/2)$, we must have some $x'$ between $x$ and $1/4$ where $f'(x') = 0$. Now, we are left to check for zeroes of $f'$ in $(0, 1/2)$. If we define $$s = \sqrt{32\alpha^3+\alpha^2-40\alpha+16}$$ then we have $$f'(\alpha) = \frac{-96 \alpha ^4+46 \alpha ^3+41 \alpha ^2-20 \alpha +4 \alpha  s^2-s^2+14 \alpha ^2 s-16 \alpha  s+4 s}{\alpha ^2 (2 \alpha -1)^2 s}$$ To confirm that this does, in fact, exist for all $\alpha\in (0, 1/2)$, we can find the $\alpha$ where $s = 0$ (they are approximately $-1.295$, $0.518$, and $0.746$, so we're good). Any point $(\alpha, s)$ where $f'(\alpha) = 0$ will be contained in the intersection of the zero sets of the polynomials $$s^2-(32\alpha^3+\alpha^2-40\alpha+16)$$ and $$-96 \alpha ^4+46 \alpha ^3+41 \alpha ^2-20 \alpha +4 \alpha  s^2-s^2+14 \alpha ^2 s-16 \alpha  s+4 s$$ We use an elimination order to get rid of $s$:
<code> GroebnerBasis[{2 (9 a^3 + 16 a^4 + a (42 - 8 s) + 2 (-4 + s) +
      a^2 (-60 + 7 s)), -16 + 40 a - a^2 - 32 a^3 + s^2}, {a}, {s}] </code>
and we are then left with the output
<code> {-4 a^2 + 24 a^3 - 29 a^4 - 76 a^5 + 212 a^6 - 160 a^7 + 32 a^8} </code>
This tells us that the only $\alpha$ satisfying $f'(\alpha) = 0$ are zeroes of $$32\alpha^8-160\alpha^7+212\alpha^6-76\alpha^5-29\alpha^4+24\alpha^3-4\alpha^2 = \alpha^2(2\alpha-1)^2(8\alpha^4-32\alpha^3+19\alpha^2+8\alpha-4)$$ That last factor has a zero at $\alpha\approx 0.361$, but we can check $f'$ at this point to determine that it is not actually a zero of $f'$. No other zeroes of this polynomial fall in $(0, 1/2)$, so $f'$ must be positive everywhere in this interval, which implies that $f$ is increasing on $(0, 1/2)$.
Comment: Thanks very much! Computational approach transforms the primal problem into the root solution and verification. It is very helpful and an inspiration to me.


Override logging in WildFly

Question: I used tomcat and simply override default logging system. How to enable logging with logback on wildfly in my spring app?
My Logback.xml owrking on tomcat
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework" level="WARN" />
    <logger name="com.citronium.planstery" level="INFO" />
    <logger name="org.apache.http.impl.conn.tsccm" level="ERROR" />

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Comment: I can't exactly answer your questions but I can give you pointers. Please check this [thread](https://community.jboss.org/thread/222437?tstart=0). It is not pretty straigh forward to override JBossLogging anymore. With their new modular classloading architecture, it has become pretty much an overhead to override the logging framework. We had similar issues and decided to go with SLf4J+JBossLogging combination.
Comment: Maxim see date. My question was previously
Answer: You can use logback to configure logging in your application. You can't use logback to configure logging for the server.
To use logback in your configuration you'll need to change the add-logging-api-dependencies to false or create a jboss-deployment-structure.xml that excludes the subsystem. You'll also need to include logback and slf4j in your deployment.
The first option of changing the add-logging-api-dependencies is a global setting for all deployments. The follow CLI command will change the value:
/subsystem=logging:write-attribute(name=add-logging-api-dependencies,value=false)

This option simply doesn't add any of the implicit logging dependencies to your deployment.
The second option of using a jboss-deployment-structure.xml will disable the logging subsystem for your deployment only. The following is an example file:
<jboss-deployment-structure>
  <deployment>

     <exclude-subsystems>
        <subsystem name="logging" />
    </exclude-subsystems>
  </deployment>
</jboss-deployment-structure>

Comment: After using the jboss-deployment-structure.xml I am getting this exception: Caused by: java.lang.NoClassDefFoundError: Lorg/apache/commons/logging/Log;
Comment: Make sure you include commons-logging as a library in your deployment or add an explicit org.apache.commons.logging dependency to the jboss-deployment-structure.xml. That said why exclude logging if you're using commons-logging?
Comment: I don't use commons logging. I use log4j. My logging was not at all working. After adding exclude subsystem and adding the commons-logging.jar in my war it started working. Thanks James. But I still don't understand this. Where can I get more info? Everywhere it's so convoluted. I get confused.
Comment: There are several reasons it may not be working. It all depends on your setup. Feel free to post a detailed question https://community.jboss.org/en/wildfly. WRT commons-logging it's likely one of your dependencies requires it.
Comment: ya may be Spring needs it.
Comment: Where is the /subsystem=logging:write-attribute(name=add-logging-api-dependencies,value=false) command placed?
Comment: Into CLI, e.g. `$JBOSS_HOME/bin/jboss-cli.sh`.
Answer: Here is how we do this, by the way, we are using wildfly-8.1.0-Final.
First, make a jar file containing this class:
https://gist.github.com/xiaodong-xie/219491e0b433f8bd451e
Then put this jar file into "wildfly-8.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main", and add a reference to this jar file in the module.xml file in the exact same folder.
Then put "logback-classic-1.1.2.jar" and "logback-core-1.1.2.jar" (You can use any version of logback you choose) into "wildfly-8.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main", and reference those 2 jar files in the module.xml file.
Add the following to the "subsystem:logging" in the standalone.xml you are using:
<custom-handler name="logback" class="org.slf4j.bridge.SLF4JBridgeHandler" module="org.jboss.logmanager"></custom-handler>

And reference this handler in the root-logger element following:
        <root-logger>
            <level name="INFO"/>
            <handlers>
                <handler name="CONSOLE"/>
                <handler name="logback"/>
            </handlers>
        </root-logger>

Here is an example of logback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"/>

<appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${JBOSS_HOME}/standalone/log/server-logback.log</file>
    <append>true</append>
</appender>
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="LOGFILE"/>
</appender>
<root level="INFO">
    <appender-ref ref="ASYNC"/>
</root>
</configuration>

And put this logback.xml file into "wildfly-8.1.0.Final/standalone/configuration" folder.
Add the following to the "standalone.sh" or equivalent in the "wildfly-8.1.0.Final/bin" folder.
-Dlogback.configurationFile=file:$JBOSS_CONFIG_DIR/logback.xml

Just under "-Dlogging.configuration=file:$JBOSS_CONFIG_DIR/logging.properties" line. There are 2 places in "standalone.sh" file.
=================================================================================
Or you can do it in a simpler way. :)
Put the 2 logback jar files to the "jboss.logmanager" module, and add "-Dorg.jboss.logging.provider=slf4j" to the "standalone.sh" file, the same position.
I found there are some logging missing if going this by the way, since Wildfly itself still using its own logging facility if going this way.
Have fun. :-)
Comment: Is it somehow possible to include the configuration in your application? Like placing it in the EAR/WAR-file on delivery? Seems to be the correct way to me, if you disable your logger via `jboss-deployment-structure.xml`.

Override logging in WildFly


How I can have different controls in different tabs and one Fragment using TabLayout in Android

Question: I am trying to understand how tabs are working but I am confused. I created a sample app with Android Studio wizard where there is one fragment.
How I can have in this one fragment but in different tabs different elements I only need to do something in onCreateView or in FragmentPagerAdapter?
The part of the adapter is:
<code>public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "CONTACTS";
            case 1:
                return "DETAILS";
            case 2:
                return "GENERAL";
        }
        return null;
    }
}
</code>
Comment: From your page adapter send different arguments to the fragment and on the onCreateView() of your fragment load the view according to the arguments received.
Comment: any example available?
Comment: getting a new instance from a Fragment class using a constructor is discouraged. Use a bundle to send arguments.
Answer: An example on how to achieve the task.
<code>//sending different arguments from the view pager adapter
public Fragment getItem(int position){
      Fragment fragment=new PlaceHolderFragment();
      //a bundle is used to wrap the data you send to the fragment
      Bundle bundle=new Bundle();
      //change whats inside the bundle based on your page
      switch(position){
          case 0:{
              bundle.putInt("dataForThisPosition",12);
              break;
          }case 1:{
              bundle.putInt("dataForThisPosition",13);
              break;
          }
          //this can continue
      }
      //attach the bundle to the fragment
      fragment.setArguments(bundle);
      return fragment;
}

//then in your fragment class
//receiving the data sent from pager adapter
public View onCreateView(/*parameters*/){
    Bundle receivedBundle=getArguments();
    int datForThisPosition=recievedBundle.getInt("dataForThisPosition",12/*default value*/);
    //create your view based on the info received.
}
</code>


Adding a webform to a different content type

Question: I have an "event" content type.  Now I want to add a Webform to it so that people can request purchasing and availability information.
I checked my event content type in admin/config/content/webform under Webform-enabled content types but how can I now add the form to my existing content?
Answer: Your webform is empty. You need add some fields to the webform.
You can add webform to any "event" node.
Try this: go to your_host/node/node_id/webform and you can see wizard for webform elements!


Freeze/lock an image on xlsx sheet using apache.poi

Question: I'm creating an xlsx using Apache.POI and inserting a logo at the top,how do I freeze or lock the images so that it cant be changed once the xlsx is downloaded.
      int numberOfSheets = wb.getNumberOfSheets();
            for(int i=0;i<numberOfSheets;i++)
            {
                XSSFSheet sheet = wb.getSheetAt(i);

                try {
                    //insert a logo
                    String location = "C:/Git/cc/src/main/resources/logo/VCC_logo.jpg"; // hard coded for testing
                    InputStream is = new FileInputStream(location);
                    byte[] bytes = IOUtils.toByteArray(is);
                    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
                    is.close();
                    // Create Winner sheet

                    CreationHelper creationHelper = wb.getCreationHelper();
                    Drawing drawing = sheet.createDrawingPatriarch();

                    ClientAnchor anchor =
                    creationHelper.createClientAnchor();
                    anchor.setCol1(0);
                    anchor.setRow1(0);
                    Picture pict = drawing.createPicture(anchor, pictureIdx);
                    pict.resize(2.5,2.5);
                    pict.getImageDimension().setSize(3.0,3.0);
                    sheet.createFreezePane(0,3);
                } catch (FileNotFoundException e) {
                    throw  new nException("Problem in reading VCC_logo.jpg");
                } catch (IOException io) {
                    throw  new Exception("Problem in reading VCC_logo.jpg");
                }

Answer: If your logo starts at row i and column j. You could use the API createFreezePane like :
Sheet.createFreezePane( i, j );
Comment: Yes, I tried that but it is freezing the rows and images on that pane is still movable in the sheet. I have 2 sheets on xlsx, when I open the xlsx the images is locked cant move, but as soon as I go to 2nd sheet and try to move the image it starts moving for 1st sheet as well.
Comment: you have to call createFreezePane on the sheet you want to freeze. Please post the code in the question to get better help.
Comment: Where are you calling createFreezePane ?


Saving and retrieving value in hook_node_form_alter()

Question: This is in Drupal 7.
I have managed to add a section to the node vertical tab. But I have not found out how to save the value and retrieve the value. After saving the node if i go back to the node edit form it still shows the default value. What am I missing?
function myModule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['test_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('test settings'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#group' => 'additional_settings',
   );

   $form['test_settings']['node_uaid'] = array(
    '#type' => 'textfield',
    '#title' => t('uaid'),
    '#default_value' => variable_get('node_uaid', "default"),
    '#size' => 50,
    '#maxlength' => 50,
    '#description' => t('test UAID.'),
    '#required' => FALSE,
    '#group' => 'settingsform'
   );
}

The final objective is a field in the node add/edit vertical form that is directly associated with that node. This field should be accessible in relation to the node.
Answer: Unlike building a settings form in Drupal using system_settings_form(), you need to do more than define the form field so that it's processed. You need to define a submit handler so your custom field can be processed. In your hook_form_alter() add a submit handler:
$form['#submit'][] = 'myModule_form_node_form_submit';

Then define your submit handler to process the form value for saving.
function myModule_form_node_form_submit($form, &$form_state) {
  variable_set('node_uaid', $form_state['values']['node_uaid']);
}

Comment: Thank you. I have been looking all over drupal.org for a tutorial on this and there is nothing. Some one should really build a good tutorial on drupal.org for stuff like this.
Comment: its showing the value but the problem is now its showing that value for every node. How can this value be associated with the node? If i have two nodes one with value-a and the other with value-b
Comment: You should ask this as a different question (Drupal Answers frowns on back-and-forth commentary of multiple questions). I'll leave one last comment.  You need to save a unique variable (e.g. `'node_uaid_'.$nid`) to do this. Depending on your needs it might make more sense as a field or DB table entry.
Comment: Sorry, I thought it was implied that if i'm adding a field to the node add/edit form that i want to associate that field with that node. I can't see any situation where some one would want a field on the add/edit node form that is not associated with the node. The objective is that this field should be associated with the node. I will update my question to better express that this field should be associated with the node.


Is there any way in Audacity I can remove a backing track from a guitar performance?

Question: So I have downloaded a backing track for guitar And wrote it into a cd player connected to my mixer (all independent from computer) and then I added the guitar on the mix, then I used a digital recorder to record what I play (boss BR-800) which is still not connected to PC and I recorded the whole playing and I was happy with the result, so I wrote it on a cd.
After when I got home I realised that the audio's volume was too low. When I tried to raise the volume with audacity I saw that the backing track distorted, but the guitar was just fine.
And now I am thinking if its possible to remove the backing track from the record and leave the guitar alone.
Anyone willing to help?
P.S if anyone want to take a listen to the recording here is a link (dont judge my playing, it sucks) https://drive.google.com/open?id=0Bz3Krsm113UecC03V2pwWmtIWmM
Answer: In general, it's true that you can't unmix audio that has been mixed - or at least, you need a very clever program (cleverer than Audacity!) to do so.
However, because you have the backing track separately, you may be able to take advantage of a processing trick involving phase inversion to get the guitar track on its own, if the backing track as recorded on the CD is a reasonably faithful copy of the track you downloaded. Unfortunately, you'll need to take some manual steps:

Load up your mix in one stereo track in audacity
In another stereo track in audacity, load up your backing track. Line it up exactly - sample-accurate, if you can - with the corresponding features of the mixed track.
Use Effect > Normalise... to get the volume of the backing track to match the backing track in the mix. (Look at a part of the mix where you're not playing guitar).
Use Effect > Invert to turn the waveform of the backing track upside down.

Now, when you play back, the backing track in your mix should be cancelled out
 by the upside-down copy, leaving only the guitar. You can then export that as a mixdown.
If anything here sounds confusing, google phase inversion to isolate vocals - you'll find some more descriptions of the technique.
Comment: this is the answer; especially if you have the backing track audio file and the backing track on the recording was "directly" recorded over (rather than out through speakers and back in through the microphone).  It's always difficult to absolutely get rid of it 100%, but since here OP's really looking for volume reduction this will be perfect (and may even work much beyond that)
Comment: I'll try the method above and I will tell you, its recorded over analog output not from microphones but the recording level is to low
Answer: If you have the separate tracks (not mixed) available, you can simply amplify the tracks you need. If you only have the mixed version available as a single track, unfortunately you won't be able to isolate individual parts of the sound to amplify.
Comment: I have the mixed track and the backing track which is part of the record I thought if its possible to make the program to understand which part to remove.
Answer: You tell us the backing track is not only too loud relative to the guitar but distorted.
Write this attempt off as a failure.  It's beyond rescue.  There MIGHT be some way of modifing the balance, but if there's distortion as well, and this isn't an irreplacable historic recording, just leave it.
Have another session and get the levels right.  Preferably set up a system where you're recording into a multi-track audio sequencer on your computer.  Put the backing track on one pair of tracks, monitor it on headphones while recording to another track.  Then mix at your leisure.   I think you already have most of the necessary equipment.


How can show the following inequality exponential?

Question: I was working on a problem and reduced it to showing the following inequality:
\begin{equation}
2(1-e^{-x})<x(1+e^{-x});~x>0
\end{equation}
your suggestion?
Comment: Your inequality is equivalent to
$$1 - \frac{2}{e^x + 1} = \frac{e^x - 1}{e^x + 1} < \frac{x}{2}.$$
Comment: [WolframAlpha](http://www.wolframalpha.com/input/?i=%28e%5Ex+-+1%29%2F%28e%5Ex+%2B1%29+%3C+x%2F2) shows that the inequality is valid for $x > 0$.
Answer: HINT:
The inequality can be rewritten as
$$f(x)=\frac{e^x-1}{e^x+1}<\frac{x}{2}=g(x)$$
To show it holds for all $x>0$, show that $f(0)=g(0)$ and $f'(0)=\frac{1}{2}=g'(0)$. Then, show that for all $x>0$, $f''(x)$ is strictly negative and $g''(x)=0$.


Flip two fair coins. Given that one is "tail," what is the probability that the other has a "head"?

Question: Here's what I already did-
List of possible outcomes:
1. HH
2. HT
3. TH
4. TT

Since we already know that one must be a tail, HH will not be included/eliminated.
Hence, possible outcomes:
 1. HT
 2. TH
 3. TT

Hence, the answer is 2/3.
Is my answer correct?
Comment: The probability we seek is one head and the other tail hence the event is {ht,th}.
Answer: It depends what you mean. "Given that one is tails": do you mean:

"given that this specific one is tails" (in which case the answer is $\frac{1}{2}$), or
"given that at least one is tails" (in which case you're correct and it's $\frac{2}{3}$), or
"given that exactly one is tails" (in which case it's $1$, of course)?

You might like to look up the Boy or Girl paradox, by the way.
Comment: It should be "given at least one is tails". I just needed the confirmation. Thanks so much for confirming it! :)


Parse and Render external HTML in React component

Question: I'm writing a React-based application where one of the components receives its HTML content as a string field in props. This content is returned by an API call.
I need to:

Render this content as a standard HTML (i.e. with the styles applied)
Parse the content to see if the sections within the content have "accept-comments" tag and show a "Comment" button beside the section

For example, if I receive the HTML below, I should show the "Comment" button beside section with id "s101".

Some text that needs comments

Some text that doesn't need comments

Questions:

What would be the most efficient way to parse and render the HTML as the content can get a bit large, close to 1MB at times?
How can I ensure that React does not re-render this component as it will not  be updated? I'd assume always return "false" from shouldComponentUpdate().

Things I've tried:

Render the HTML with "dangerouslySetInnerHTML" or "react-html-parser". With this option, cannot parse the "accept-comments" sections.
Use DOMParser().parseFromString to parse the content. How do I render its output in a React component as HTML? Will this be efficient with 1MB+ content?
Comment: So I assume it's a given that you cannot change what the API returns?
Comment: That's true. I cannot change what API returns. I need to work with the HTML content it returns.
Comment: Ok, so you've tried `DOMParser()`. It returns a `document`, which means you can turns its `childNodes` into elements: https://codesandbox.io/s/x9vp5452z4
Comment: Thanks Chris, the code snippet is quite helpful. I will try this with one of the largish documents and update.
Answer: This answer comes from Chris G's code in the comments. I used the code with different sizes of documents and it works well. Thanks Chris G!
Posting the code here in case the link link in the comments breaks.
The solution uses DOMParser to parse the HTML content provided by the API call and scans it to find the content that should include the "Comment" button. Here are the relevant parts.
import React from "react";
import { render } from "react-dom";

const HTML =
  "

Section 1

Section 2

";

class DOMTest extends React.Component {
  constructor(props) {
    super(props);

    const doc = new DOMParser().parseFromString(HTML, "application/xml");
    const htmlSections = doc.childNodes[0].childNodes;

    this.sections = Object.keys(htmlSections).map((key, i) => {
      let el = htmlSections[key];
      let contents = [
{el.innerHTML}
];

      if (el.hasAttribute("but")) contents.push(<button>Comment</button>);

      return
{contents}
;
    });
  }

  render() {
    return
{this.sections}
;
  }
}

const App = () => (

    <DOMTest />

);

render(<App />, document.getElementById("root"));

Comment: one thing to note is the mimetype - may want to specify `text/html` vs `application/xml` so that the DOM recognizes predefined HTML elements.
Comment: ssr causes issue with DOMParser as it is browser only.


How do I shorten super long variable labels of an SPSS file in R?

Question: Context:

I have data from a large survey (from a Qualtrics survey, exported for SPSS, .sav file format).
There are 648 variables total, because most of the questions were "check all that apply" or ranked response, where every option shows up as a binary variable.
200 variables (for the rank response questions) have variable labels that are VERY long and cumbersome. The first 150 or so words of the labels are the same for each label, containing the explanatory text for the question, and then the final 2-5 words of the label are different, containing the unique information for that variable.
Currently using haven and labelled packages for reading in the .sav file and created a data dictionary.

Problem:
I would like to be able to remove the text from all these 200 variable labels that is the same, and be left with only the unique words at the end.
Where I'm at:
I'm able to locate all 200 variable names of interest here because they all contain "RANK", with the below:
colnames(
  look_for_and_select(data,
                      "RANK",labels=FALSE,
                      values=FALSE,
                      ignore.case=FALSE),
  )

Everything I'm finding in my searches are functions to replace or add a new variable labels, but I need to be able to retain the unique text already in the label. I think maybe there's a way to use gsub()... but would appreciate any ideas or help!
Example:
Here is the text in the variable label, with the final words I'd like to retain bolded at the end. Every variable label has this same huge block of text at the beginning, and a different 2-5 words at the end:
"1.5 Which actions present the greatest opportunity to advance this scenario's goal?   Select up to 3 of your previously selected actions, drag them into the box, and rank them in order of their importance for this goal (1=most important).     Scenario Context & Assumptions     Imagine yourself as a manager responsible for planning all street tree management on a hypothetical street in your region for the next 20 years. The street has a sidewalk and low-rise development, with buildings that are approximately 1-3 stories tall. In this mostly perfect world, you have full control over the trees adjacent to the sidewalk.    Within these scenarios, assume the following will be true:      Each action you select is in comparison to not doing the actions at all     Actions will be performed according to industry standard"   Trees will not be removed by events such as vandalism, new construction, extreme storms, or pest invasions  Newly planted trees will be watered through establishment and as needed for survival    Urban form will not change (street, pavement, buildings will remain the same with reasonable maintenance)   Species planted will be adapted for any change in hardiness zone projected in 20 years due to climate change - Ranks - Opportunities to achieve this scenario's goal (rank 3) - plant native species"
Comment: It would be useful if you added a few example names to your question and how you would want the result to look
Comment: good idea - added!
Comment: Thanks. Assuming that the string given in your question fits the same pattern as all the names: you can extract all the words after the final hyphen with `sub('.*-', '', string)` (where `string` is the vector of names).
Answer: library(tidyverse)
library(labelled)

Create a data.frame with variable labels that resemble your description.
same <-
  '1.5 Which actions present the greatest opportunity to advance this scenario\'s goal? Select up to 3 of your previously selected actions, drag them into the box, and rank them in order of their importance for this goal (1=most important). Scenario Context & Assumptions Imagine yourself as a manager responsible for planning all street tree management on a hypothetical street in your region for the next 20 years. The street has a sidewalk and low-rise development, with buildings that are approximately 1-3 stories tall. In this mostly perfect world, you have full control over the trees adjacent to the sidewalk. Within these scenarios, assume the following will be true: Each action you select is in comparison to not doing the actions at all Actions will be performed according to industry standard" Trees will not be removed by events such as vandalism, new construction, extreme storms, or pest invasions Newly planted trees will be watered through establishment and as needed for survival Urban form will not change (street, pavement, buildings will remain the same with reasonable maintenance) Species planted will be adapted for any change in hardiness zone projected in 20 years due to climate change - Ranks - Opportunities to achieve this scenario\'s goal (rank 3) - '

var_labels <- paste(same, "plant native species", 1:10)

var_names <- paste("var", 1:10, sep = "_")

df <-
  var_names |>
  lapply(\(x) tibble(a = 1:10) |> set_names(x)) |>
  bind_cols() |>
  set_variable_labels(.labels = var_labels)

We can use labelled::get_variable_labels() to obtain all variable labels
and then modify them with stringr::str_remove() with a Regular Expression
(RegEx), as suggested by user20650 in their comment.
The regular expression .*- instructs str_remove() to remove all characters
until it hits a final dash/hyphen. If all of the variable labels separate
the last bit with a dash, this should work across all labels.
short_var_labels <-
  df |>
  get_variable_labels() |>
  str_remove(".*-") |>
  trimws()

short_var_labels
#>  [1] "plant native species 1"  "plant native species 2"
#>  [3] "plant native species 3"  "plant native species 4"
#>  [5] "plant native species 5"  "plant native species 6"
#>  [7] "plant native species 7"  "plant native species 8"
#>  [9] "plant native species 9"  "plant native species 10"

Now we can apply the short variable labels to the data.frame.
df <-
  df |>
  set_variable_labels(.labels = short_var_labels)

get_variable_labels(df)
#> $var_1
#> [1] "plant native species 1"
#>
#> $var_2
#> [1] "plant native species 2"
#>
#> $var_3
#> [1] "plant native species 3"
#>
#> $var_4
#> [1] "plant native species 4"
#>
#> $var_5
#> [1] "plant native species 5"
#>
#> $var_6
#> [1] "plant native species 6"
#>
#> $var_7
#> [1] "plant native species 7"
#>
#> $var_8
#> [1] "plant native species 8"
#>
#> $var_9
#> [1] "plant native species 9"
#>
#> $var_10
#> [1] "plant native species 10"

Comment: Thank you!  I'm actually looking to edit the variable labels, not the variable names. Do you have an idea for how to modify this to edit the variable labels?
Comment: I just added an example in the question
Comment: I updated my answer to work for variable labels and made it specific to your case.
Comment: thank you! This was very helpful and I learned a lot.


How to rearrange dataframe to wide format?

Question: I have a dataframe with 3 column: participant ID, questionID and a column containing wether or not they gave the correct (1) response or not (0).
It looks like this:
> head(df)
# A tibble: 6 x 3
     ID questionID correct
  <dbl>      <int>   <dbl>
1     1          1       1
2     2          2       0
3     3          3       1
4     4          4       0
5     5          5       0
6     6          6       1

And can be recreated using:
set.seed(0)
df <- tibble(ID = seq(1, 100, 1),
             questionID = rep(seq(1, 10,), 10),
             correct = base::sample(c(0, 1), size = 100, replace = TRUE))

Now I would like each question to have their own column, with the ultimate goal of fitting a 2PL model to it. The data should for that purpose look like 1 row per participant, and 11 columns (ID and 10 question Columns).
How do I achieve this?
Comment: `df %>%
  spread(questionID, correct, sep = "_")` should help.
Answer: You can use pivot_wider from the tidyr package:
df %>%
  pivot_wider(names_from = questionID,
              values_from = correct,
              names_prefix = "questionID_")

# A tibble: 100 x 11
      ID questionID_1 questionID_2 questionID_3 questionID_4
   <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
 1     1            1           NA           NA           NA
 2     2           NA            0           NA           NA
 3     3           NA           NA            0           NA
 4     4           NA           NA           NA            1
 5     5           NA           NA           NA           NA
 6     6           NA           NA           NA           NA
 7     7           NA           NA           NA           NA
 8     8           NA           NA           NA           NA
 9     9           NA           NA           NA           NA
10    10           NA           NA           NA           NA
# ... with 90 more rows, and 6 more variables: questionID_5 <dbl>,
#   questionID_6 <dbl>, questionID_7 <dbl>, questionID_8 <dbl>,
#   questionID_9 <dbl>, questionID_10 <dbl>

Answer: Using data.table you can use dcast
df <- data.frame(ID=c(1,2,3,4,5,6), questionID= c(1,22,13,4,35,8),correct=c(1,0,1,0,0,1))
 df
 ID questionID correct
1  1          1       1
2  2         22       0
3  3         13       1
4  4          4       0
5  5         35       0
6  6          8       1

setDT(df)
dcast(df,ID~questionID,value.var="correct")
   ID  1  4  8 13 22 35
1:  1  1 NA NA NA NA NA
2:  2 NA NA NA NA  0 NA
3:  3 NA NA NA  1 NA NA
4:  4 NA  0 NA NA NA NA
5:  5 NA NA NA NA NA  0
6:  6 NA NA  1 NA NA NA

# replace NA to what you want
df[is.na(df)]<- "-"


Array Flip Error Message on All Node Pages

Question: Hello i dont know where to begin. All of a sudden MY WEBSITE is displaying this error when i view a node-

Warning: array_flip() [function.array-flip]: Can only flip STRING and
  INTEGER values! in DrupalDefaultEntityController->load() (line 178 of
  /home/onlineba/public_html/onlineplac.es/includes/entity.inc).
  Warning: array_flip() [function.array-flip]: Can only flip STRING and
  INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 355
  of /home/onlineba/public_html/onlineplac.es/includes/entity.inc).

I havent added anything or changed anything. I was hoping it was because OG groups upgraded to 7.2 but i seem to get it when viewing a node that is not in a group. Let me see my page content type as thats got no OG fields attached or postable in groups.... yes exactly the same thing. its only got a title, body and image field attached to it. Oh and a term referance. Lets remove that...yes still the same.
Panels node page is disabled. Im sorry i cant tell you anymore about my problem but if anyone could be a lifesaver and offer any advice it would be gratefully reveived. I get really depressed when things like this happen. :(
thanks
Comment: ah this could be important. its all part of the same puzzle - The following token types are not defined but have tokens:

$info['types']['taxonomy_term'] oart of my flag term php (disabled) has this in it..- php print flag_create_link('flagtags', %taxonomy_term:tid) maybe i better check the flag issue queue
Comment: ah wait a sec. it goes away when i disable the php filter module. it could be a cache thingy with boost. The lines of the error seem to relate to cache. there is hope for me yet :)
Comment: ooops never meant to reply there. line 178  $passed_ids = !empty($ids) ? array_flip($ids) : FALSE; and 355 is   $entities += array_intersect_key($this->entityCache, array_flip($ids)); cache mentioned again. maybe ive got some old php blocks in my cache. i will go investigate more
Comment: yes it seems related to me enabling the php filter module. I dont hve any php blocks or panels added. Could there be some caching probs in the database with it you think? Id really like to be able to add a small bit of php for my Flag: taxonmy term link. thanks
Answer: Something is calling entity load with an incorrect $ids parameter.
This could be from something like node_load() or equivalent or node_load_multiple() or equivalent. If you pass in the wrong type of value into any of these you could end up with the error you mention.
If you want, add just above line 178 the line
<code>print_r($ids);
</code>
Then reload the problem page and you will get a bunch of text print out.
Post the text back here (if you can upload files and there is a lot of output you could paste it in a txt file and post it).
Comment: thnks rooby. I ended up sorting out the thing that was causing the error. Actually i didnt i found a way of doing things that didnt involve using php in a block. What you say is correct though. I belive it was a token that wasnt supported. Thanks for your time and attention


How to put an attribute on the root element, and only the root element, in FOR XML PATH?

Question: I'm generating XML from a SQL Server table.
This is my code:
;WITH XMLNAMESPACES
(
     'http://www.w3.org/2001/XMLSchema-instance' AS xsi
    --,DEFAULT 'http://www.w3.org/2001/XMLSchema-instance'  -- xmlns
)
SELECT
    'T_Contracts' AS "@tableName",
    (SELECT * FROM T_Contracts
     FOR XML PATH('row'), TYPE, ELEMENTS xsinil)
FOR XML PATH('table'), TYPE, ELEMENTS xsinil

I want the result to look like this (note: attribute tableName on the root element):

  <row>
    <VTR_UID>779FE899-4E81-4D8C-BF9B-3F17BC1DF146</VTR_UID>
    <VTR_MDT_ID>0</VTR_MDT_ID>
    <VTR_VTP_UID xsi:nil="true" />
    <VTR_Nr>0050/132251</VTR_Nr>
  </row>

But it duplicates the XSI namespace on the row element...

  <row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <VTR_UID>779FE899-4E81-4D8C-BF9B-3F17BC1DF146</VTR_UID>
    <VTR_MDT_ID>0</VTR_MDT_ID>
    <VTR_VTP_UID xsi:nil="true" />
    <VTR_Nr>0050/132251</VTR_Nr>
  </row>

What's the correct way to add an attribute to the root element, and only the root element ?
Note
NULL-values must be returned as <columnName xsi:nil="true" /> and not be omitted.
(And no xml.modify after the select)
Please note that this is NOT a duplicate of an existing question.
Comment: Each (sub)query using `ELEMENT XSINIL` will get its own `xsi` declaration on the element itself. This is a [well-known issue](https://feedback.azure.com/forums/908035-sql-server/suggestions/32889769-suppress-namespace-attributes-in-nested-select-for) and the chance of a solution by MS is close to zero at this point. If you don't want to post-process the results I'm afraid you're out of luck.
Comment: What's wrong with post-processing ?, you put the FOR XML PATH on a second CTE and your final query returns it with the TABLE tag modified.
Comment: @MarcGuillot: if you have a working query, you should post it as an answer. When I say "post-processing", I mean outside T-SQL.
Comment: @JeroenMostert I have added an answer with that proposal. It's far from elegant, but it should do the work.
Comment: @JeroenMostert, as it might be interesting for you: I found a solution (altough a clumsy one) without *post processing* the XML with string methods.
Answer: This annoying behaviour of repeated namespaces with sub-queries was a reported issue for more than 10 years on MS-Connect with thousands of votes. This platform was dismissed, so was this issue and there is no perspective that MS will ever solve this.
Just to be fair: It is not wrong to repeat the namespace declaration. It's just bloating the string-based output...
Even stranger is the the unsupported attribute on a root level node...
Well, if you need a head-ache, you might look into OPTION EXPLICIT :-)
The accepted answer by Marc Guillot will not produce xsi:nil="true" attributes as you seem to need them. It will just wrap your result with the appropriate root node.
Finally: This cannot be solved with XML methods, you can try this:
Update: Found a way, see below...
DECLARE @tbl TABLE(ID INT,SomeValue INT);
INSERT INTO @tbl VALUES(1,1),(2,NULL);

SELECT CAST(REPLACE(CAST(
(
    SELECT *
    FROM @tbl
    FOR XML PATH('row'),ROOT('table'),TYPE, ELEMENTS XSINIL
) AS nvarchar(MAX)),'<table ','<table tableName="T_Contracts" ') AS XML);

The result

  <row>
    <ID>1</ID>
    <SomeValue>1</SomeValue>
  </row>
  <row>
    <ID>2</ID>
    <SomeValue xsi:nil="true" />
  </row>

The idea in short:

We create the XML without a sub-query and add the attribute with a string method into the casted XML.
As the position of an attribute is not important, we can add it everywhere.
alternatively you might search for the first closing > and use STUFF() there...

UPDATE
Heureka, I just found a way, to create this without swithing to string, but it's clumsy :-)
DECLARE @tbl TABLE(ID INT,SomeValue INT);
INSERT INTO @tbl VALUES(1,1),(2,NULL);

SELECT
(
SELECT 'T_Contracts' AS [@tableName]
      ,(
        SELECT 'SomeRowAttr' AS [@testAttr] --added this to test row-level attributes
              ,*
        FROM @tbl
        FOR XML PATH('row'),TYPE, ELEMENTS XSINIL
       )
FOR XML PATH('table'),TYPE, ELEMENTS XSINIL
).query('
{/table/@*}
         {
            for $nd in /table/row
            return
            <row>{$nd/@*}
            {
                $nd/*
            }
            </row>
         }

');

The result

  <row testAttr="SomeRowAttr">
    <ID>1</ID>
    <SomeValue>1</SomeValue>
  </row>
  <row testAttr="SomeRowAttr">
    <ID>2</ID>
    <SomeValue xsi:nil="true" />
  </row>

Comment: I see you definitely had too much time ;) Thanks, that's excellent ! Completely agree with msConnect, total BS. Had the same experience with SSRS. Parameter captions still can't be translated... (but they had the time to make parameter arrangement customizable...)
Answer: Why don't you build manually the root element ?
Example:
with CTE as (
  select (select * from T_Contracts for xml path('row')) as MyXML
)
select '
' +
        MyXML +
        '
'
from CTE

Comment: @StefanSteiger, What about *NULL-values must be returned as `` and not be omitted.* ? The `FOR XML` query within the CTE will not behave like so...
Comment: Marc, although the OP did accept this, this is - at least in my eyes, not the answer for the given problem...
Comment: @Shnugo: You're right, there is no way to get rid of the extra xmlns:xsi in the rows. I thought it would not be emitted without root element, but it is.
Comment: By the way, you still need to put ISNULL(MyXML, '') around MyXML, otherwise you get NULL if the table is empty ;)
Answer: Unfortunately you cannot do this with the SQL Server out of the box nor exists an elegant way to do that. To alleviate the issue, you can replace NULLs with empty strings. This will remove xmlns, but you have to define your select list explicitly as follows. Moreover, this works only with character string data types as you cannot assign an empty string ('' in ISNULL function) to-for example-an integer.
;WITH XMLNAMESPACES
(
     'http://www.w3.org/2001/XMLSchema-instance' AS xsi
    --,DEFAULT 'http://www.w3.org/2001/XMLSchema-instance'  -- xmlns
)
SELECT 'T_Contracts' AS "@tableName",
    (
        SELECT
             ISNULL(VTR_UID, '')     'row/VTR_UID'
            ,ISNULL(VTR_MDT_ID, '')  'row/VTR_MDT_ID'
            ,ISNULL(VTR_VTP_UID, '') 'row/VTR_VTP_UID'
            ,ISNULL(VTR_Nr, '')      'row/VTR_Nr'
        FROM T_Contracts
        FOR XML PATH(''), TYPE
    )
FOR XML PATH('table'), TYPE, ELEMENTS xsinil

The result will be like below:

  <row>
    <VTR_UID>779FE899-4E81-4D8C-BF9B-3F17BC1DF146</VTR_UID>
    <VTR_MDT_ID>0</VTR_MDT_ID>
    <VTR_VTP_UID />
    <VTR_Nr>0050/132251</VTR_Nr>
  </row>


LinearRegression score

Question: #imagem seria um numero(reconhecer caractere)
novo = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)
tamanho = cv2.resize(novo, (56, 56))
converter = tamanho.astype('float32')
converter /= 255
onversao = converter.astype('int')
final = conversao.flatten()
classificador = LogisticRegression()
# conjunto de imagens
classificador.fit(x,y)
#passo somente uma imagem
previsao = classificador.predict([final])
#retorna o rotulo da imagem
return previsao

O código acima retorna o rótulo referente a imagem passada, mas eu preciso que retorne a porcentagem de acerto.
Answer: Do próprio exemplo do sklearn.linear_model.LogisticRegression:
>>> from sklearn.datasets import load_iris
>>> from sklearn.linear_model import LogisticRegression
>>> X, y = load_iris(return_X_y=True)
>>> clf = LogisticRegression(random_state=0, solver='lbfgs',
...                          multi_class='multinomial').fit(X, y)
>>> clf.predict(X[:2, :])
array([0, 0])
>>> clf.predict_proba(X[:2, :])
array([[9.8...e-01, 1.8...e-02, 1.4...e-08],
       [9.7...e-01, 2.8...e-02, ...e-08]])

Ou seja, .predict() retorna a classe prevista, enquanto .predict_proba() retorna a porcentagem de pertencer a cada classe. No exemplo, as classes previstas foram 0 para ambas as 2 entradas, enquanto que as probabilidades foram:

[9.8...e-01, 1.8...e-02, 1.4...e-08], ou seja, 0.98 de pertencer a classe 0, 0.018 de pertencer a classe 1 e praticamente 0.0 de pertencer a classe 2.
[9.7...e-01, 2.8...e-02, ...e-08], ou seja, 0.97 de pertencer a classe 0, 0.028 de pertencer a classe 1 e praticamente 0.0 de pertencer a classe 2.

LinearRegression score


Como estilizar apenas um trecho de um texto?

Question: Quero saber como posso ter um resultado como esse no meu texto:

Quero destacar certo trecho e por em negrito.

 A ferramenta é 100% online, desenvolvida com as mais modernas tecnologias

Answer: Utilize um span e uma classe CSS:

.destaque {
  font-weight: bold;
  color: #009933;
}

A ferramenta é 100% online, desenvolvida com as mais modernas tecnologias.

Ou o estilo diretamente na tag (não recomendado):
ferramenta é 100% online

Comment: Valeu, Marcus! Mas tem uma maneira de passar isso direto lá no span? Sem usar uma classe CSS...
Comment: `ferramenta é 100% online`
Comment: Muito obrigado! ;)
Answer: Você pode usar a tag Mark do html5 e personalizar sua cor, a tag mark  é usada para colocar destaque em um trecho e ajudar com SEO


Persisting of ObservableCollection to DataStore

Question: I have an ObservableCollection<T> (T being a set of entities loaded using OData) which is correctly maintaining updates to its contents.  The collection is displayed in a DataGrid and the user clicks a button in order to save the collection back to a database.
Is there any way that I can test the collection for updated items, limiting the number of writes required to those entities that have actually been updated.
Answer: If you use the .NET Entity Framework for interacting with the database, it will do a lot of this for you.
But if you want to do it from scratch the easiest way is to implement INotifyPropertyChanged on each item in the collection.  When soemthing is added to the collection, add a listener to it's PropertyChanged event.  Now you can get notified of and keep track of all changes.
Comment: Thanks,  The collection gets informed of the update but the entities within did not have any OnPropertyChanged implementation.  I took your advice and implemented INotifyPropertyChanged on a wrapper around the entity with an additional flag.  I set the flag on change and loop through the collection on save checking for updated items.  I now have the behaviour I wanted.


Derive $\frac{d}{dx} \left[\sin^{-1} x\right] = \frac{1}{\sqrt{1-x^2}}$

Question: Derive $\frac{d}{dx} \left[\sin^{-1} x\right] = \frac{1}{\sqrt{1-x^2}}$ (Hint: set $x = \sin y$ and use implicit differentiation)
So, I tried to use the hint and I got:
$x = \sin y$
$\frac{d}{dx}\left[x\right] = \sin y\frac{d}{dx}$
$\frac{dx}{dx} = \cos y \frac{dy}{dx}$
$\frac{dy}{dx} = \frac{1}{\cos y}$
$\frac{dy}{dx} = \sec y$
From here I need a little help.

Did I do the implicit
differentiation correctly?
How do I use this to help with
the original question?
Comment: The notation in the second step is not right. You need to write $\frac{d}{dx}\sin y$, not $\sin y \frac{d}{dx}$. (The derivative operator acts on what comes *after* it).
Comment: It's pretty well covered in existing answers, but [my answer on this other question](http://math.stackexchange.com/questions/15514/how-can-i-find-the-derivative-of-y-sin-arctan-x-tan-arcsin-x/15517#15517) shows a technique for organizing the algebra/trigonometry involved in getting from $x=\sin y$ and $\sec y$ to $\frac{1}{\sqrt{1-x^2}}$, though demonstrated with a different pair of functions.
Answer: Edited in response to Aryabhata's comment. From $\cos ^{2}y+\sin ^{2}y=1$, we get $\cos y=\pm \sqrt{1-\sin ^{2}y}$. For
$y\in \lbrack -\pi /2,\pi /2]$, $\cos y=\sqrt{1-\sin ^{2}y}\geq 0$, and $%
y=\arcsin x\Leftrightarrow x=\sin y$ (see Inverse trigonometric functions). Then by the rule of the inverse function we have
$$\dfrac{dy}{dx}=\dfrac{1}{\dfrac{dx}{dy}}=\dfrac{1}{\dfrac{d}{dy}\sin y}=\frac{1}{\cos y}=\dfrac{1}{\sqrt{1-\sin ^{2}y}}=\dfrac{1}{\sqrt{1-x^{2}}}.$$
Comment: @OghmaOsiris: I added a link to the Wikipedia entry.
Comment: Ok, I can understand where this is going, I just didn't know you could inverse $\displaystyle \frac{dy}{dx}$ like that...
Comment: Nitpick: $y = \arcsin x \Leftrightarrow x = \sin y$ is incorrect. You need to mention that $y \in [-\pi/2, \pi/2]$. You also need to use that fact to be able to state $\cos y = \sqrt{1 - \sin^2 y}$ (i.e. eliminate the possibility $\cos y = - \sqrt{1 - \sin^2 y}$).
Comment: @Aryabhata: I knew that, but I didn't explained it properly. Thanks! I edited my answer.
Answer: You are on the right track. All that's left is to write $\sec(y)$ in terms of $x$. To do this, recall that $y=\arcsin(x)$. That is, $y$ is some angle, sine of which yields $x$. Thus, there is a right triangle with angle $y$, the side opposite $y$ has length $x$ and the hypotenuse is $1$. You need to compute the secant of this angle $y$.
arcsin http://homepage.mac.com/shelleywalsh/MathArt/arcsin.gif
This approach generalizes to finding the derivatives of the other inverse trig functions, and is a good way to wrap your head around composing trig functions and inverse trig functions of any flavor.
Comment: @OghmaOsiris I, of course, also don't know if this is the proof your teacher wants, or even if there is one proof in particular your teacher expects. The technique I described above is (I think) fairly standard, and it's something I show my students when I teach differential calculus.
Comment: @OghmaOsiris If you think of the triangle trig definitions of the trig functions, then secant is hypotenuse/adjacent. Does that help?
Comment: @wckronholm if would be better if could draw the pic ;)
Comment: @IDIOT I agree. I'll figure out how to include images in my answers and edit to include the appropriate triangle.
Comment: @wckronholm very nice!
Comment: Visually, this help me see what I'm calculating, but I still don't understand how to interpret this for my question..
Comment: Yeah, I got that part, I just didn't know if that was the proof that my teacher wanted or not... because I assume the question is just proving the derivitive of the arcsin function.
Answer: You just need the fact that $\cos(x) = \sqrt{1-\sin^2(x)}$ and you should be able to complete it from what you already have.
Comment: $\cos x = \sqrt{1 - \sin^2 x}$ is not always right...
Comment: @Aryabhata: Ah, yes, you are correct. Bill has already corrected his answer so I'm just gonna leave mine the way it is.
Answer: You are nearly there. You just need to take $\frac{dy}{dx} = \frac{1}{\cos y}$ and express both sides in terms of $sin(x)$ (LHS) and $x$ RHS
LHS will give you LHS of your equation. And remembering $x=sin(y)$ and a formula for $cos(y)$ in terms of $sin(y)$ will get you the RHS. $sec(y)$ is a distraction best avoided.
Comment: Ok... what? does LHS = left hand side?
Comment: LHS - left hand side, RHS = right hand side.
Answer: First, note that $\displaystyle \sin^{-1}: [-1,1] \to [-\frac{\pi}{2}, \frac{\pi}{2}]$
The range is important, as for this range, you have that if $y = \sin^{-1} x$ then $\cos y  = \sqrt{1 - x^2}$, as we have $\sin y = x$ and $\cos y \ge 0$ whenever $y \in [-\frac{\pi}{2}, \frac{\pi}{2}]$.
i.e. since $\sin^2 y + \cos^2 y = 1$, we get $\cos y = \pm \sqrt{1 - x^2}$  and since $\cos y \ge 0$, we can say $\cos y = \sqrt{1- x^2}$.
Exercise
Suppose we defined $\sin^{-1}x$ as the unique angle $\theta$ in $[\frac{\pi}{2}, \frac{3 \pi}{2}]$ such that $\sin \theta = x$, what is the derivative of $\sin^{-1} x$?
Answer: You can also use implicit diff.  Begin with
$$y = \sin^{-1}(x);$$
Apply the sine function to get
$$\sin(y) = x.$$
Now differentiate.
$$\cos(y) y' = 1,$$
so
$$y' = {1\over \cos(y)}.$$
Now draw the $1$-$x$-$\sqrt{1 - x^2}$  triangle and compute and you get
$$y' = {1\over\sqrt{1 - x^2}}.$$
This technique works nicely for various inverse functions.


What does exterior algebra actually mean?

Question: This question may be too basic and even silly, but I am new to exterior algebra and reading Wikipedia.
Given $e_1, e_2,\cdots, e_n$ is a standard basis for a vector space $V$, what does $e_1\wedge e_2\cdots \wedge e_n$ actually look like? It is said to be a basis. So, it is a set of vectors? What is its dimension? Is it just a constant with dimension $1$?
Answer: $e_1 \wedge e_2 \wedge \dots \wedge e_n$ is a single vector. The $n$-th exterior power of an $n$-dimensional space, $\bigwedge^n V$, is one dimensional and $e_1 \wedge e_2 \wedge \dots \wedge e_n$ is the single vector you need to span it.
The exterior powers of a vector space are closely related to the subspaces of that vector space (this is called the Grassmann-Plücker embedding). This is because the wedge product has the convenient property that $v_1,\dots,v_k$ are linearly dependent if and only if $v_1 \wedge \dots \wedge v_k = 0$. Thus the non-zero wedges correspond to linearly independent sets of vectors.
If $v_1 \wedge \dots \wedge v_k \ne 0$ then $v_1,\dots,v_k$ are linearly independent and the wedge $v_1 \wedge \dots \wedge v_k$ corresponds to the signed basis $v_1,\dots,v_k$ of the subspace $W = \operatorname{span}(v_1,\dots,v_k)$. You can picture a signed basis as an oriented parallelepiped. For example, with two vectors, $v, w$, the wedge product $v \wedge w$ is the oriented parallelogram with vertices $v, w, v + w$ and the orientation is from $v$ to $w$. There are pictures of this on the Wikipedia entry.
If $V$ is $n$-dimensional, then $V$ has only one $n$-dimensional subspace, namely $V$, which is why $\bigwedge^nV$ is one-dimensional.
In $\mathbf R^n$ we have a notion of an orthogonal complement of a subspace. This gives a natural pairing between a $k$-dimensional subspace $W$ of $\mathbf R^n$ and the $n - k$ dimensional orthogonal subspace, $W^\perp$. Correspondingly, there should be a natural isomorphism
$$ \bigwedge^k \mathbf R^n \longleftrightarrow \bigwedge^{n - k} \mathbf R^n. $$
Given the basis $\{e_{i_1} \wedge \dots \wedge e_{i_k} : 1 \le i_1 \le \dots \le i_k \le n\}$ of $\bigwedge^k \mathbf R^n$, this bijection is described by
$$ e_{i_1} \wedge \dots \wedge e_{i_k} \mapsto e_{j_1} \wedge \dots \wedge e_{j_{n-k}} $$
where $1 \le j_1 \le \dots \le j_{n_k} \le n$ and $\{j_1,\dots,j_{n-k}\} = \{1,\dots,n\} \setminus \{i_1,\dots,i_k\}$. That is, the subspace spanned by a subset $S$ of $\{e_1,\dots,e_n\}$ is mapped to the subspace spanned by the complement, $S^c$. As you can see, this isomorphism makes sense for any $n$-dimensional vector space, not just those with a notion of orthogonal complement.
As an example, for $\mathbf R^3$ we have an isomorphism $\bigwedge^1 \mathbf R^3 = \mathbf R^3$ onto $\bigwedge^2 \mathbf R^3$. If $\hat\imath, \hat\jmath, \hat k$ are the standard basis vectors for $\mathbf R^3$ then the isomorphism is given by
$$ \hat\imath \leftrightarrow \hat\jmath \wedge \hat k,\qquad \hat\jmath \leftrightarrow \hat\imath \wedge \hat k,\qquad \hat k \leftrightarrow \hat\imath \wedge \hat\jmath. $$
Hopefully you see the relation here to the cross product:
$$ \hat\imath = \hat\jmath \times \hat k,\qquad \hat\jmath = \hat\imath \times \hat k,\qquad \hat k = \hat\imath \times \hat\jmath. $$


Determinant of a matrix having a row or columns of 1s

Question: So I read this property of determinants that
If in |A| ( i.e determinant of matrix A), if any row/column is proportional to any other corresponding row/column then its determinant is zero.
OR if,
Ri   =    kRj
then |A|=0 (zero)
AN example would look like the following in a matrix format:

a11
b12
c13

d21
e22
f23

2a31
2b32
2c33

Here, R3=2R1
Hence, determinant here would be 0.
My problem is what if one of the rows is a all 1s?
i.e.

a11
b12
c13

d21
e22
f23

131
132
133

In this case, why aren't all rows multiple of third row and determinant not 0?
Comment: Nothing then can be said, except in the general case where one of the rows is a linear combination of the other ones. A row (or column) all $\;1\,'$s doesn't indicate either way.
Comment: The whole row has to be the same multiple of the third row.  So a11=a11×1 but a12=a12×1 and they are different multiples.
Answer: Your claim $R_3=2R_1$ holds only if $(a_{31},a_{32},a_{33}) =(a_{11},a_{12},a_{13}) $. Otherwise
the replacing in the matrix the row $(a_{31},a_{32},a_{33}) $ with $(2a_{31},2a_{32},2a_{33}) $ does not make the determinant of the matrix 0, this doubles it instead. The reason is of course the fact that multiplying  a row with a non-zero constant does not make the raw to become linearly dependent on the others. Particularly a matrix containing $(1,1,\dots,1) $ row can have any deteminant.
Comment: I think  I get it. Thanks a lot. All elements of row 3 here must be multiplied by a constant to get row 1, but if row 1's elements aren't equal i.e if a11 = a12 = a13 then the determinant won't be 0
Comment: If there is a constant $c $ such that $R_j=c R_i $ for $i\ne j $ the rows are apparently linearly dependent and the determinant is 0. However if the dimension of the matrix is larger than 2 the linear dependence may be not so apparent.


Criteria do grails

Question: Alguém por favor me diz o que significa esse ${result[0][0]} por que colocaram dois par de colchetes?
def criteria = Person.createCriteria()
def result = criteria.list {
projections {
    max('age')
    min('age')
  }
}
println "The maximum age is ${result[0][0]}"
println "The minimum age is ${result[0][1]}"

Answer: Conforme o tutorial do qual o código em questão foi copiado, esse exemplo combina projeções e funções agregadas.
Projeções modificam o retorno da clausula select, de maneira que não faz sentido copiar o resultado para a entidade Person.
Na documentação do GORM encontramos a seguinte passagem:

Quando múltiplos campos são especificados na projeção, uma lista de valores será retornada. Caso contrário um único valor será retornado.

Pensando em Java, isso significa que o retorno da função será um List<Object[]> ou List<Object>.
No caso da sua função o SELECT será algo mais ou menos da forma:
SELECT max(age), min(age)
FROM Person;

Ou seja, sabemos que o resultado deve ter apenas uma linha com duas colunas representando respectivamente o retorno das duas funções agregadas (máximo e mínimo).
Como índices em Groovy começam do zero, acabamos com algo assim:
      COLUNA

L   *-----------------------------*
I   | indice  | 0       | 1       |
N   *---------*---------*---------*
H   | 0       | max(age)| min(age)|
A   *---------*---------*---------*

Ou seja, result[0][0], retorna o máximo da primeira coluna. Já result[0][1] retorna o mínimo da segunda coluna. Ambos usam apenas a primeira (e única) linha.
Na prática porém dificilmente alguém vai propagar esse resultado tabular para as camadas superiores. Geralmente o resultado da consulta passa por um ResultTransformer ou uma transformação com collect, mas esse é um tópico para outra pergunta.

Criteria do grails


How do I configure the Services OAuth sub-module?

Question: The Services module is about to release its new 3.0 version for both D6 & D7.
There's an OAuth sub-module to Services that adds a new OAuth UI within the Services configuration UI.
Does anyone know how to configure that UI?
I'm expecting the Services developers will write something up, but given that they are working hard on the official release, the documentation will be the last thing done. In the mean time, if anyone has figured it out from prior familiarity with OAuth, please share your knowledge to us less informed. (As in explaining it to someone who has not used OAuth before.)
Answer: There is a handbook page covering testing Oauth based services at http://drupal.org/node/942866 . This does assume that you have some familiarity with both oauth and the drupal oauth module.
The basic workflow as far as implementation goes is:

Set up an oauth context.
Set your service to use oauth authorisation
Configure the authorisation for all your resource operations.
Configure one or more oauth consumers

For testing you're probably going to have to write your own client code which generates the oauth signature and then passes that with your service requests.
For learning more about Oauth itself I recommend you start by reading this guide which is fairly comprehensive -
http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-i-overview/
Comment: That handbook page ends with "c) To be continued...." and speaks to an OAuth experienced individual. I'll re-read that second 'beginners guide' link again, maybe now it will make sense. FWIW, I have a Services 3 REST api done, but con't figure out the OAuth stuff. Prior experience with application keys in Services 2.x is not enough, I guess.
Answer: The OAuth Login Provider contains a pre-configured endpoint with OAuth support:
You need to create OAuth contexts for which you can create OAuth consumers. The reason we have OAuth contexts is that we don't want to tie OAuth contexts directly to endpoints - you should be able to share consumer keys between multiple endpoints and also between services and non-services projects.
In Services you select OAuth as the authentication mechanisms and select a context. You should also be able to select authentication level for each individual resource in the endpoint but I think someone accidentally removed that and we haven't yet added it back yet: http://drupal.org/node/1154420


Sever.Transfer from ASHX handler, HttpContext.Current.Session is null

Question: So I'm trying to do a Server.Transfer from a generic handler to an regular ASPX page.
It transfers okay, but it's finding the HttpContext.Current.Session is null.
Anyone know why?
Thanks for the help!
-Ev
Answer: You got to mark handler with IRequiresSessionState marker interface in order to have Session initialized. If you only need to read from session use IReadOnlySessionState marker interface, so Session State Provider can skip saving session at the end of request. In case of out of proc Session State Provider that can give some gains in performance.
Here is the example :
using System.Web.SessionState;

namespace BlahBlah
{
  public class CustomHandler : IHttpHandler, IRequiresSessionState
...
}

Comment: Thanks man. I think the Server.Transfer was a bit of a red herring for me :)


What is the relationship between a kernel function and the inner product of the corresponding Reproducing Kernel Hilbert Space?

Question: For a positive definite kernel, there exists a Reproducing Kernel Hilbert Space (RKHS) whose reproducing kernel is the kernel function.
My question is, what characteristic of the kernel function decides the inner product of the RKHS.
For example, for the second order polynomial kernel $k(x, x') = (x^Tx')^2$ where $x, x' \in \mathbb{R}^2$, its feature map is $\phi_x = k(\cdot,x) = [x_1, \sqrt2x_1x_2, x_2]$ and $\langle\cdot,\cdot\rangle$ is computed in the same way as Euclidean space.
However, for Gaussian kernel the feature map is a mapping to infinite dimensional space, and the inner product will be computed as an integral.
For those well-known kernels we know the feature map, hence we can think about the inner product of the corresponding RKHS, but when we came up with a random positive definite kernel, what characteristics of the kernel function decide the inner product and the feature map?
Answer: This is a subject that I do not master at all, I just skimmed the Wikipedia. As far as I understand, for any positive definite kernel there is a corresponding reproducing kernel Hilbert space; this is the Moore-Aronszajn theorem and it is the one you implicitly mention in the question. But I think that you are right, when you write that this theorem sheds little light on the nature of that reproducing kernel Hilbert space.
Such information seems to be provided by the Mercer theorem, which is mentioned in the same Wikipedia page. One of its consequences is that the reproducing Hilbert space $H$ corresponding to the kernel $K$ is given by
$$
H=\left\{ f\in L^2(X)\ :\ \sum_i \frac{|\langle f|\phi_i\rangle|^2}{\sigma_i}<\infty\right\}, $$
where $\sigma_i$ and $\phi_i$ are eigenvalues and eigenvectors of the integral operator
$$\tag{1}
f\mapsto \int_X K(\cdot, y)f(y)\, d\mu(y).$$

Thus, to answer your question, the properties of $H$ follow from the spectral properties of $K$.

This is a vague answer and it sweeps some details under the rug; the most important one is the fact that the theorem of Mercer assumes that a measure space $(X, \mu)$ is given a priori (otherwise, (1) makes no sense). But I hope it is useful to you anyway.


Determine the values b where $A\vec{x}=\vec{b}$ has at least 1 solution.

Question: Consider the following linear system $A\vec{x}=\vec{b}$ where,
$A=\begin{bmatrix}
         2&1&4\\
         2&-3&4\\
         3&-2&6
    \end{bmatrix}$
and $\vec{b}=\begin{bmatrix}
                   b\\
                   b\\
                   b
             \end{bmatrix}$ for a real number b.
Determine the values of b where so that $A\vec{x}=\vec{b}$ has at least 1 solution and solve the linear system.
I  have taken the augmented matrix:
$\begin{bmatrix}
         2&1&4&b\\
         2&-3&4&b\\
         3&-2&6&b
    \end{bmatrix}$ and reduced it to $\Rightarrow$ $\begin{bmatrix}
         1&0&2&\frac{3}{7}b\\
         0&1&0&\frac{1}{7}b\\
         0&0&0&\frac{4}{7}b
    \end{bmatrix}$
From here, do I conclude the that this system will only have a solution for those values of b such that $b=0$?
What else do I have to do to solve the linear system?
Edit this is what i got for my row reduction
Comment: I don't think that Gauss-Jordan reduction is correct .Check it once?
Comment: I am not sure where my error is.
Comment: In the sixth passage, you do (if I read correctly from the sheet) $\frac{5}{7}\cdot R_2+R_3\to R_3$. Where the $frac{5}{7}$ comes from?
Answer: Essentially the question is to determine the range of the matrix, that is the space spanned by it's columns. Basically what we do here is to pick a solution candidate $x$ and see what value of $b$ would have that solution.
We can immediately note that the third column is double the first so that vector is redundant in the base. We're then left with the first and second which are linearily independent.
So the values of $b$ for which the equation system has at least one solution is $b = (2s+t, 2s-3t, 3s-2t)$.