How to read multiple NetCDF files from MODIS which have variables in groups?

Question: Recently I tried to read MODIS Cloud properties data. I tried to merge/ combine MOIDS NetCDF files however both ncrcat or CDO didn't work. Then I found that variables data in MODIS was collected in each group.
a='MCD06COSP_M3_MODIS.A2002182.061.2020181145824.nc'

b=nc.Dataset(a)
print(b.groups.keys())
c=b.groups['Cloud_Mask_Fraction']
print(c.variables['Mean'])

then it will give results
dict_keys(['Solar_Zenith', 'Solar_Azimuth', 'Sensor_Zenith', 'Sensor_Azimuth', 'Cloud_Top_Pressure', 'Cloud_Mask_Fraction', 'Cloud_Mask_Fraction_Low', 'Cloud_Mask_Fraction_Mid', 'Cloud_Mask_Fraction_High', 'Cloud_Optical_Thickness_Liquid', 'Cloud_Optical_Thickness_Ice', 'Cloud_Optical_Thickness_Total', 'Cloud_Optical_Thickness_PCL_Total', 'Cloud_Optical_Thickness_Log10_Liquid', 'Cloud_Optical_Thickness_Log10_Ice', 'Cloud_Optical_Thickness_Log10_Total', 'Cloud_Particle_Size_Liquid', 'Cloud_Particle_Size_Ice', 'Cloud_Water_Path_Liquid', 'Cloud_Water_Path_Ice', 'Cloud_Retrieval_Fraction_Liquid', 'Cloud_Retrieval_Fraction_Ice', 'Cloud_Retrieval_Fraction_Total'])

<class 'netCDF4._netCDF4.Variable'>
float64 Mean(longitude, latitude)
    _FillValue: -999.0
    title: Cloud_Mask_Fraction: Mean
    units: none
path = /Cloud_Mask_Fraction
unlimited dimensions:
current shape = (360, 180)
filling on

There are other variables in many groups, and I need to read all the other files or merge these files. So I am wondering how can I read multiple NetCDF files with groups? How can I have arrays for each variable with a new dimension time since I have to read these data for years? Does CDO or ncrcat or xarray in python can merge this kind of nc files?
Thanks a lot.
Yuhang
Comment: Please add a link to the data
Answer: I would recommend to use xarray as the state-of-the-art 4D grid data handler in python.
You have to install netcdf4 and I recommend h5netcdf because of faster processing.
path_to_file = 'MCD06COSP_M3_MODIS.A2002182.061.2020181145824.nc'
# if h5netcdf is installed:
data = xarray.open_dataset(path_to_file, engine='h5netcdf')
# if just netcdf4 is installed:
data = xarray.open_dataset(path_to_file)

# access variables:
data[<variable_name>]
data.<variable_name>

# inspect whole file:
data

You can load multiple files into one dataset:
datasets = xarray.open_datasets([path_to_file_1, path_to_file_2], parallel=True)

I expect some errors in case that you have different time spans but you can find ways to work around such an issue.
I added parallelisation here to enhance the parsing speed.
Please add test data via link to a cloud storage or similar otherwise the community can not help you more like these suggestions.
PS: Please choose variable names wisely ;)


Title field input textbox way too long in firefox browser

Question: This looks a very simple question but I seem to find it rather difficult to find a very easy solution...
Textboxes in forms are way too long when looking at it using Firefox but not in Chrome. In Chrome, container widths are respected so the textbox width does not go over containers' width. However, default size of 60 when using Firefox just breaks the container width declaration and does not get respected...
Comment: Use some css to define the width maybe?
Answer: I had the same css issue.
you need to address the input field correctly with the inputtype "text":
e.g.
<code>.mywrapper-form input[type="text"] {
   width: 100px;
}
</code>
Comment: i guess i was thinking of a solution that don't need css like a tweak within the admin page directly perhaps. So you wont have to go back and forth if you have a thousand forms. hopefully also this will become standard across all browsers.
Comment: i should because a pixel is a pixel in each browser, while the size="1" is an abstract unit
Comment: and why not make size equate to pixels


Error: Because project requires SDK version >=2.16.2 <3.0.0, version solving failed

Question: I just tried to reactivate an old project, but it doesn't work.
I get this message in my "output":
Because random_number requires SDK version >=2.16.2 <3.0.0, version solving failed.
pub get failed (1; Because random_number requires SDK version >=2.16.2 <3.0.0, version solving failed.)
exit code 1

But I already tried fluttter update
This is the output I get for flutter --version:
PS C:\Users\Simon\Desktop\Simon\Programmieren\App Entwickeln\Projekte\random_number> flutter --version
Flutter 2.10.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision c860cba910 (12 days ago) • 2022-03-25 00:23:12 -0500
Engine • revision 57d3bac3dd
Tools • Dart 2.16.2 • DevTools 2.9.2

And this is what I have in my pubspec.yaml:
environment:
  sdk: ">=2.16.2 <3.0.0"

Does anyone know where I have made my mistake?
Comment: you could be having multiple dart installs
Answer: I have an idea, if your project is relatively small, then just copy the code files from your old project to your new one, Ctrl + C and Ctrl + V, it will take 10 minutes at most, I can't guess how old the version of your previous project is, so try my method above, it will most likely help.
Answer: the same mistake as you,
update fluter to 2.10.5,it is solved.
C:\Users\zdz\fvm\default>flutter --version
Flutter 2.10.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 5464c5bac7 (4 weeks ago) • 2022-04-18 09:55:37 -0700
Engine • revision 57d3bac3dd
Tools • Dart 2.16.2 • DevTools 2.9.2


Pegar dados específicos do banco

Question: Bom galera, estou fazendo um projeto com as seguintes páginas pedidos.php e anexa.php. O action dos pedidos vai para a página anexa, nela tenho o envio do conteúdo para o banco de dados e e-mail, através da função mail(), tudo funciona perfeitamente. Porém, desejo em outra página, chamada "Meus pedidos", exibir os dados do pedido realizado.
Mas não sei como fazer essa inclusão especifica, todo os pedidos vão para o mesmo banco, e de pessoas diferentes que realizam o login.
Alguém me ajuda com essa dúvida! Por favor! Desde Já agradeço.
Página anexa.php
<?php
    $nome        = $_POST['nome_empresa'];
    $telefone    = $_POST['telefone'];
    $email       = $_POST['email'];
    $material    = $_POST['material'];
    $cor         = $_POST['cor'];
    $quantidade  = $_POST['quantidade'];
    $acabamento  = $_POST['acabamento'];
    $formato     = $_POST['formato'];
    $altura      = $_POST['altura'];
    $largura     = $_POST['largura'];
    $papel       = $_POST['papel'];
    $gramatura   = $_POST['gramatura'];
    $descricao   = $_POST['descricao'];
    $aleatorio=rand(1,99999);

    $sql = mysql_query("INSERT INTO pedidos (nome_empresa, telefone, email, material, cor, quantidade, acabamento, formato, altura, largura, papel, gramatura, descricao, aleatorio) VALUES ('$nome', '$telefone', '$email', '$material', '$cor', '$quantidade', '$acabamento', '$formato', '$altura', '$largura', '$papel', '$gramatura', '$descricao', '$aleatorio')");
?>

    <?php
        include ("Mail.php");
        include ("Mail/mime.php");

        $up=0;

        $nome        = $_POST['nome_empresa'];
        $telefone    = $_POST['telefone'];
        $email       = $_POST['email'];
        $material    = $_POST['material'];
        $cor         = $_POST['cor'];
        $quantidade  = $_POST['quantidade'];
        $acabamento  = $_POST['acabamento'];
        $formato     = $_POST['formato'];
        $altura      = $_POST['altura'];
        $largura     = $_POST['largura'];
        $papel       = $_POST['papel'];
        $gramatura   = $_POST['gramatura'];
        $descricao   = $_POST['descricao'];

        $recipients = 'email@example.com';

        $headers = array (
            'From'    => 'firstname.lastname@example.com',
            'To'      => $recipients,
            'Subject' => "Pedido N#$aleatorio"
        );

        $crlf = "\r\n";
        $text = "
Um novo pedido foi realizado por: $nome

            DETALHES DO PEDIDO:

            Pedido de Numero:#$aleatorio

            Telefone: $telefone

            Email: $email

            ____________________________________

            Material: $material

            Acabamento: $acabamento

            Formato: $formato

            Tamanho = $altura x $largura

            Cor: $cor

            Papel : $papel

            Gramatura: $gramatura

            Quantidade: $quantidade

            Descricoes: $descricao
        ";

        $html = "$text";

        $mime = new Mail_mime($crlf);
        $mime->setHTMLBody($html);

        for( $i = 0; $i < count($_FILES['anexo']['name']); $i++ ) {
            if (is_uploaded_file($_FILES['anexo']['tmp_name'][$i])) {
                $caminho[$i] = "/home/conexaografica/www/areaderevendedor/tmp/".$_FILES['anexo']['name'][$i];

                if(copy($_FILES['anexo']['tmp_name'][$i],$caminho[$i])) {
                    $mime->addAttachment($caminho[$i]);
                    unlink($caminho[$i]);
                    echo "Seu arquivo foi anexado!
";
                }
            } else {
                echo "
O arquivo não foi transferido!
";
                echo "
Caminho ou nome de arquivo Inválido
";
            }
        }

        $body = $mime->get();
        $headers = $mime->headers($headers);

        $params = array (
            'auth' => true,
            'host' => 'smtp.conexaografica.com.br',
            'username' => 'contato=conexaografica.com.br',
            'password' => 'conexaografica'
        );

        $mail_object = Mail::factory('smtp', $params);
        $result = $mail_object->send($recipients, $headers, $body);
        if (PEAR::IsError($result)) {
            echo "Algo deu errado... (" . $result->getMessage(). ")";
        } else {
            echo(
                "
$nome, Seu pedido foi realizado com sucesso.
".
                "Pedido de Numero:#$aleatorio
".
                "
DETALHES DO PEDIDO:
".
                "Telefone: $telefone
".
                "Email: $email
".
                "
____________________________________
".
                "Material: $material
".
                "Acabamento: $acabamento
".
                "Formato: $formato
".
                "Tamanho = $altura x $largura
".
                "Cor: $cor
".
                "Papel : $papel
".
                "Gramatura: $gramatura
".
                "Quantidade: $quantidade

".

                "OBS: Salve o numero do seu pedido."
            );
        }
    ?>

    <?php
        date_default_timezone_set('America/Sao_Paulo');
        $date = date('H:i d/m/Y');
        echo ("Hora e Data: $date");
    ?>

Página login.php
<?php
    if(isset($_POST['entrar']) && $_POST['entrar'] == "login"){
        $usuario = $_POST['usuario'];
        $senha = $_POST['senha'];

        if(empty($usuario) || empty($senha)){
            echo 'Preencha todos os campos!';
        }else{
            $query = "SELECT nome, usuario, senha FROM usuarios WHERE usuario = '$usuario' AND senha = '$senha'";
            $result = mysql_query($query);
            $busca = mysql_num_rows($result);
            $linha = mysql_fetch_assoc($result);

            if($busca > 0){
                $_SESSION['nome'] = $linha['nome'];
                $_SESSION['usuario'] = $linha['usuario'];
                header('Location: logado.php');
                exit;
            }else{
                echo 'Usuário ou senha inválidos.';
            }
        }
    }
?>

Página pedidos.php
<?php
    include_once("settings/setting.php");
    @session_start();

    $nome = $_SESSION['nome'];
    $usuario = $_SESSION['usuario'];

    if(!isset($_SESSION['nome']) && !isset($_SESSION['usuario'])){
        header('Location: login.php');
        exit;
    }
?>

Comment: Qual é o script de login ?
Comment: Dica: Selecionar todo o código e clicar **`Ctrl + K`** deixa ele formatado.
Comment: coloquei como resposta!
Comment: Ok, já foi excluída, sou novo no site, não sabia com funciona as coisas ainda!
Comment: Normal :) aproveite para fazer um [tour] e ver as paginas de [faq]
Comment: `pedidos` está de alguma forma relacionado com o usuário ?
Comment: Bom, editei a pergunta com o topo do pedidos.php.
Answer: Primeiramente: nunca, nunca, nunca, nunca, nunca, nunca coloque variáveis não tratadas nas suas queries pro banco de dados. Nunca. Jamais. Isso é pedir pra ter seu sistema hackeado por crianças. Use essa função para evitar esse problema.
Agora, seu problema principal é que você não está usando seu banco de dados direito. Você quer listar os pedidos realizados pelo usuário que está logado, correto? Então você precisa incluir a chave primária (o ID) do usuário nos seus pedidos. Crie uma coluna para guardar a chave do usuário na hora que ele faz o pedido e depois é só fazer um SELECT pelo id de usuário logado. Algo como:
SELECT * FROM pedidos WHERE usuario_id = $usuario_id

Nesse caso nem precisaria tratar, pois você já tratou no login, mas trate assim mesmo. Ah! E você vai precisar colocar o id do usuário na sua SESSION também, claro.

Pegar dados específicos do banco


How do I modify the result?

Question: Having an issue with HOOK_views_pre_render and HOOK_views_post_render, trying to alter the rendered output of the view. There are similar questions like: Hide view results with hook but I am not seeing the results as I am expecting under $view['result']
There is what looks like a full entity and not the markup that I'm expecting.
Comment: What are you trying to modify?
Comment: Sorry, I wanted to modify the views result row. Specifically a field and was exploring the different views hooks as I've used them many times in D7 and expected to see an array of rows in markup.
Comment: In my case, the solution that worked was to use the HOOK_preprocess_views_view_field, but during my research, I found links like the one I posted in the question that don't seem to work any longer. I just was not able to see how we would change the views markup in pre or post render hooks other then delete a result row.

How do you interact to set/change values in a views ResultRow object?
Answer: You can use HOOK_views_post_execute() and cycle through the results rows,  updating the row with something like:
<code>        foreach ($viewExecutable->result as $key => $rr) {
          $title = $rr->_entity->getTitle();
          // update $title value...
          $viewExecutable->result[$key]->_entity->set('title', [['value' => $title]]);
        }
</code>
Comment: Thanks very much @jons for the answer. I was getting a PHP error that was causing a white screen of death - Call to undefined method Drupal\\taxonomy\\Entity\\Term::getTitle()  which is odd since the title is on a node and not a taxonomy. It was not always throwing this error though.
Answer: Thanks @jons, your answer allowed me to move further and I was able to set other fields in the view result now:
<code>// Testing how we can update view result title value
$title = 'This is a custom title';
$newurl = 'http://www.nextide.ca';
$view->result[$key]->_entity->set('title', $title);
$view->result[$key]->_entity->set('body', 'This is a custom content');
$view->result[$key]->_entity->set('field_coned_site_course_url', $newurl);
</code>

How do I modify the result?


How do you reconcile a statistically insignificant logistic regression with a significant AUC?

Question: Suppose I run logistic regression with one continuous predictor. The Wald tests of significance show a p-value that is not significant at the 5% level. Looking at the receiver operating characteristics curve though shows an AUC that is significant, with DeLong's method.
How can I interpret these results?
Comment: Is the significance/non-significance borderline? Do you have a simulated example? Of course, the two tests ask slightly different questions...
Answer: The AUC in this case with a single continuous predictor has a simple interpretation: among all the pairs of observations with different outcomes, it's the fraction of pairs that had the correct order of the predictor value. It's closely related to the non-parametric Mann-Whitney U test for comparing a continuous predictor between two groups. It doesn't care about the shape of the relation between the predictor value and outcome probability.
The logistic regression model, on the other hand, tests a much more restrive hypothesis: that the log-odds of group membership is linearly related to the value of the continuous predictor. If there is a relation between the continuous predictor and group membership probability that does not meet this linearity assumption, it could well fail a Wald test in logistic regression but pass a non-parametric test for a significant AUC.
You might want to test the linearity assumption in your logistic regression and try  transformations or spline modeling of the continuous predictor to improve the logistic regression performance.


Will RSTP BPDUs be encapsulated in tagged Ethernet frames?

Question: RSTP(Rapid Spanning Tree) is configured on a bridge. All ports of this bridge are "trunk" ports and are part of vlan "x". Will the BPDUs sent out of this bridge be tagged?
Comment: I think you're missing the point of this site. It's not a Wiki to list questions and answers as trivia, it's a tool to ask questions that represent real, actual problems that need solving.
Comment: True... but this guy was getting a lot of downvotes, so I figured that was the reason why. Not questions for the sake of trivia, but questions for a purpose. Which begs the question, why all the downvotes?
Comment: @Bigbio2002 - incorrect. You are totally allowed to share your knowledge here in q/a by answering your own questions. There's even a special button to click when you're asking that makes this even easier. Not only is it permitted, it's encouraged by the Stack Exchange network.
Answer: No. RSTP BPDUs are never tagged irrespective of the port type(access/trunk). Because RSTP BPDUs on being received by a bridge are sent to the CPU for processing if the bridge understands RSTP or are discarded. So, they need not be forwarded.
Comment: MST maintains a single topology for the VLAN's and ports assigned to it.  PVST(+) is configured on a per-VLAN basis.  The win with the former is a lot fewer BPDU's being propagated, which improves scalability considerably.  Depending on the implementation both can be implemented as rapid (802.1w) or standard (802.1d) spanning tree.
Comment: I think 802.1q tags are present on BPDUs in Cisco's PVST+?
Comment: On Juniper Networks switches, i have verified that it does not send out tagged BPDUs. This seems correct because when you have different ports on a bridge part of different VLANs, and you enable RSTP on the bridge, then all the ports of the bridge are treated as if they were all in same VLAN for all RSTP convergence events.

I mean that if two ports in 2 separate VLANs are connecting to the same bridge on the other side, then RSTP will block one port and forward data only on the other port.
Comment: PVST+ is RSTP running separately in each individual VLANs. So, separate spanning trees are formed for each VLAN in case of Cisco's PVST+ or Juniper's VSTP.
Comment: Sounds right!  It might be worth adding a note to the answer that those variants on RSTP behave differently.  And I'm not sure how MST behaves - I assume there's no tags, but it might be worth confirming!


Determine the model of iPhone device

Question:
Possible Duplicate:
How to deal with iPhone 5 screen size?

So with the release of iPhone 5 today and a larger screen height, how do we accommodate for different screen sizes across the different iPhone variants in our apps. I understand that apps which are not updated for iPhone 5 will be "letter boxed", but what about backwards compatibility?
Is there a way to check whether the app is running on an iPhone 3, 4 or 5?
Comment: I'd say this question is a superset of that question in that its asking how to determine device version, not just screen size.
Comment: Sure. By checking for the device version just to do different things only because the screen size is different is not the right approach then: if you have code that must be different because the screen size is different, you should check the screen size, not the hardware model and make some assumptions on its screen size. (actually the user may also use an external screen with arbitrary resolution too to display the content of its iPhone…)
Answer: You normally don't need that, because checking the hardware is not the right approach.
If you need to base decisions in your app on the screen size, like accomodate to the screen size for your UI, you should… test the screen size, not make some conditions on the hardware. Always test what is really necessary.
Use [UIScreen mainScreen].bounds for that (as you should always have done). Note that even before iPhone 5, one could plug its iPhone on a videoprojector or external screen and display its app on a screen with different resolution than the iPhone. That's why I hope that you never use magic numbers in your code (And if you did, you know why it's bad now ;)) and was already using constants or asking at runtime for the size of your screen.

Anyway, to accomodate for different screen sizes, if you configured your autoresizing mask correctly in your views, your applications will resize automagically. You just need to provide a email@example.com launch image and your app will take the full size of the 4" screen.
Moreover, starting iOS6, you will be able to use AutoLayout to do finer constrainted layout of your views. See the WWDC'12 videos sessions that explains it in detail.
Comment: Thanks. Appreciate your help.
Answer: Checkout the UIDevice-Hardware extension, it was even recently updated to add support for the iPhone 5.

Determine the model of iPhone device


Django + Apache + mod_wsgi: Why is wsgi script executed multiple times?

Question: I'm relatively new to all the server technology and I followed this tutorial to deploy my django app on an Apache Webserver, using mod_wsgi:
http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/
Here is my virtual hosts file:
<VirtualHost *:80>
        ServerName www.abcxyz.org
        ServerAlias abcxyz.org
        WSGIScriptAlias / /var/www/abcxyz/django/abcxyz/wsgi_prod.py
        Alias /static/ /var/www/abcxyz/static/
        <Location "/static/">
            Options -Indexes
        </Location>
</VirtualHost>

As I understand it, the wsgi_prod.py file should only be executed once when the server starts (or when it gets the first request - I'm not particular sure about this). But in my application it is executed multiple times, when sending requests to the server.
It is not executed on all requests but on some of them. And there are also some request, that trigger the execution of wsgi_prod.py only sometimes.
This is my wsgi_prod.py file:
import os
import sys
import site
import thread

# Add the site-packages of the chosen virtualenv to work with
site.addsitedir('/etc/Envs/abcxyz/local/lib/python2.7/site-packages')

# Add the app's directory to the PYTHONPATH
sys.path.append('/var/www/abcxyz/django')
sys.path.append('/var/www/abcxyz/django/abcxyz')

os.environ['DJANGO_SETTINGS_MODULE'] = 'abcxyz.settings.production'

# Activate your virtual env
activate_env=os.path.expanduser("/etc/Envs/abcxyz/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))

print "WSGI RUN!!!"

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Has anyone any idea what could have went wrong in my case and where I could start searching for the error?
Answer: It would be loaded once per process.
You likely are using a multiprocess configuration and subsequent requests are being handled by different process and/or processes are being recycled. Print out the process ID in the debug. Also go read:

http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html

and watch:

http://lanyrd.com/2013/pycon/scdyzk/
Comment: Awesome, I followed the instructions of your second link and it work properly now. Thanks a lot!


Location test under a bounded non-stationarity?

Question: Suppose I draw $n$ observations $X_1,X_2,\ldots,X_n$ independently from a distribution where  $X_i \sim \mathcal{N}(\mu_i,\sigma^2)$, where the mean is assumed to be Lipschitz: $\left| \mu_i - \mu_{i+1}\right| \le \gamma,$ with $\gamma$ known. I want to test the null hypothesis:
$$H_0: \mu_n = 0$$
against the local alternative $H_1: \mu_n > 0$.
A few questions:

Is this a known problem? If so, for what terms should I google search?
What is a reasonable way to perform this test? I can imagine there might be some way to do it by downweighting less recent observations--maybe throw the innovations into the noise term, then use a weighted t-test? The problem with that approach is that the change in mean may be deterministic, so I should pose the problem as a minimax problem maybe. Perhaps another approach would be to ignore the non-stationarity and use a regular t-test on some subset of the observations $X_j,X_{j+1},\ldots,X_n$, with $n-j$ chosen by some function of $\gamma, \sigma$ (probably their ratio?), and accept that the test will not maintain the nominal Type I rate. What are some better ideas?

Edit: per the excellent comments so far, I believe this question can be reformulated as follows: Let $V$ be the convex set in $\mathbb{R}^n$ defined by:
$$
V = \left\{\mathbf{x} | x_n = 0, x_{i-1} \le x_i + \gamma, x_{i-1} \ge x_i - \gamma, i = 2,\ldots,n  \right\}
$$
Observing vector $X = f + \sigma\epsilon$, where the elements of $\epsilon$ are drawn independently from a standard Gaussian, test the null hypothesis:
$$H_0: f \in V$$
In this sense, it is similar to the paper of Baraud et. al. mentioned by @Robin Girard, except the Baraud paper provides a method for the case where $V$ is a linear subspace of $\mathbb{R}^n$, not a convex polytope.
Under this formulation, it seems that, under the null, the squared distance from $X$ to $f$ should be distributed as a Chi-squared, up to the scaling factor of $\sigma^2$. Then the distance from $X$ to $V$ should be no greater than that. The proposed test would then be to find the projection of $X$ onto $V$, and test the distance from $X$ to that projection based on the Chi-squared bound. I imagine this test will have fairly low power. Perhaps truncating the observation to a final subset of the $X_i$ would have higher power...
Comment: @shabbychef, if you set up a likelihood ratio test, then under both $H_0$ and $H_1$, you have a convex program to solve for $\hat{\mu}_i$. If you look at the KKT conditions, you might even be able to find an explicit solution. Maybe try "walking backward" from $i = n$, e.g., under $H_0$, it seems that if $|X_{n-1}| > \gamma$, then $\hat{\mu}_{n-1}$ is likely equal to $\mathrm{sgn}(X_{n-1}) \gamma$. You might also look at the *fused lasso*, which has a "similar" (but not identical) form as your problem. I'm not sure that much is known about distributions of likelihood ratios in that setting.
Comment: This doesn't qualify as an answer, but I think something along the lines of a maximum entropy distribution for $\mu_{i}$, subject to your constraints $\left| \mu_i - \mu_{i+1}\right| \le \gamma$.  Set this distribution as the prior, and then set jeffreys prior for $\sigma$.  Then update using Bayes theorem to a posterior for $\mu_n$, and calculate the probability $Pr(\mu_{n}>0)$, and use it like a p-value.  Calculating the MaxEnt distribution may be difficult to do though.
Comment: @mpiktas, not in general since the constraints can force the "perfect fit" to be infeasible. Of course, if the perfect fit is feasible for $H_0$ then the LRT will be 1. But, I think that's the desired answer in that case anyway!
Comment: I fully agree with cardinal's answer, there is not a very big problem here and hence certainly no litterature (however I like the question :) +1 for that).

However this is certainly a simple particular case of what is called ["Adaptive tests of linear hypotheses by model selection by " Y. Baraud, S. Huet, and B. Laurent][1]

  [1]: http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aos/1046294463
Comment: @probabilityislogic: We can assume that $\sigma$ is known, which should simplify this computation.
Comment: @cardinal, we have the same amount of $\mu_i$ as there are data points. Will this not pose a problem for estimation?
Comment: @robin girard: The case where the $\mu_i$ are affine with slope $\gamma$ does seem to be amenable to the test of Baraud _et. al._ However, I am looking for a test which performs reasonably well under the more general case of the Lipschitz bound.
Comment: @shabbychef I was pretty sure you knew Baraud's paper (from past questions and comments...). I though it contained alternatives similar to yours I'll take a look once.
Comment: @robin, @shabbychef, maybe I was misunderstood. I think this problem is interesting. I also find disappointing the dearth of good quality work on inference for the many variants of constrained least-squares estimation that have become so popular over the last fifteen years. If @shabbychef can crack that nut, even for this particular example, it might even be publishable.
Comment: @cardinal, could you provide a link to some kind of work illustrating inference for constrained least-squares estimation. This seems really interesting.
Comment: @mpiktas, sorry, could you clarify? A link to some kind of work illustrating what?
Comment: @cardinal, you mention dearth of good quality work, so I wondered that there is plenty of low quality work :) Any links would be fine, I just want to get an idea.
Comment: @mpiktas, I didn't quite mean to suggest that. To me, there just doesn't seem to be much work at all, and certainly very little that is compelling. Knight and Fu (2000) and some of the follow-ons by others are the exception. But, very little (that I am aware of, or can remember being aware of) exists regarding constructing valid confidence intervals and performing hypothesis tests. Chatterjee & Lahiri have a paper on a modified bootstrap for the lasso (standard one is bad). Meinshausen also seems to be doing work in this area. But, the results seem sparse so far.
Comment: @cardinal, thanks, I understand that you did not mean to suggest that. It seems interesting that nobody does any work on this, there might some underlying reason for that.
Comment: @mpiktas, for one, I think it's generally difficult. And, it's much easier just to dream up some minor iteration on the lasso or $k$-means or PCA, run a few simulations, find one "real" example where your method works better than "competing" ones, and publish without saying (virtually) anything about uncertainty. It's become a veritable cottage industry. You wanted my unvarnished opinion, right? :)
Comment: @cardinal, yep, I treasure those :)
Comment: I misread the question, so I retract my answer, since I do not see for now how can I rewrite it to be useful.
Comment: @shabbychef, off the top of my head, I don't think the power will necessarily be small. Intuitively, it seems it should be roughly a monotonic function of $|\mu_n|$. I say this because under both the null and alternative, the "left-hand tail" of the sequence is allowed to float, while under the null, you've pinned the "right-hand tail" to zero.
Answer: Ok, I've thought of two possible ways to answer to this problem using Bayesian analysis.  I will assume $\sigma$ to be known throughout this answer.  First start with a "baby" case, where $n=2$ (or alternatively, only using the last two observations as a first approximation).  You would usually start this by assuming a "flat" prior for $\mu$, just proportion to 1.  But you have additional information, so we just restrict the prior to conform to this.  So the prior is:
$$f(\mu_1,\mu_2|\gamma) \propto I_{|\mu_1-\mu_2|\leq\gamma}$$
(the improper prior should be fine, because you are dealing with normal RVs, and you aren't dividing them)
Combining this prior with the likelihood, and integrating out $\mu_1$ gives (Writing $\phi(x)$ as standard normal pdf and $\Phi(x)$ as standard normal cdf):
$$f(\mu_2 | X_1,X_2,\sigma,\gamma) \propto \phi\big(\frac{\mu_2-X_2}{\sigma}\big) \Bigg[\Phi\Big(\frac{\mu_2-X_1+\gamma}{\sigma}\Big)-\Phi\Big(\frac{\mu_2-X_1-\gamma}{\sigma}\Big)\Bigg]$$
So in order to calculate the "p-value" for the hypothesis, we need to take $Pr(\mu_2 > 0 |X_1,X_2,\sigma,\gamma)=P$.  This is given by the ratio of two integrals of the posterior:
$$P=\frac{\int_{-\frac{X_2}{\sigma}}^{\infty}\phi\big(y\big) \Bigg[\Phi\Big(y+\frac{X_2-X_1+\gamma}{\sigma}\Big)-\Phi\Big(y+\frac{X_2-X_1-\gamma}{\sigma}\Big)\Bigg]dy}{\int_{-\infty}^{\infty}\phi\big(z\big) \Bigg[\Phi\Big(z+\frac{X_2-X_1+\gamma}{\sigma}\Big)-\Phi\Big(z+\frac{X_2-X_1-\gamma}{\sigma}\Big)\Bigg]dz}$$
It is beyond my abilities to do either of these integrals exactly, and even if it was possible, you probably would learn anything intuitive about the problem (except that the integral was friggin hard! you'd think it could be derived using something to do with convolutions, but I couldn't work it out).  So I would just numerically evaluate these two integrals.
For the whole data set, you will almost surely need some kind of numerical technique, or analytic approximation.  This is a rather quick numerical technique.  Okay, so it basically goes like this: if you knew $\mu_1$, then you could generate a sample of the remaining $\mu_i$ values sequentially, using the uniform distribution $(\mu_{i}|\mu_{i-1}) \sim U(\mu_{i-1}-\gamma,\mu_{i-1}+\gamma)$.  An obvious way to sample $\mu_1$ is from a gaussian with large variance $\mu_1 \sim N(0,\delta^2)$ ("large" meaning relative to your data, say $\delta\approx 10\sigma$).  Use the notation $\mu_{i}^{(b)}$ for the $b$th sample of means $b=1,\dots,B$.  Now you calculate the total likelihood for each iteration.  This will be used as a weight:
$$w^{(b)}=\prod_{i=1}^{n} \phi \Big(\frac{\mu_{i}^{(b)}-X_i}{\sigma}\Big)$$
Then you take a "weighted probability" of the alternative hypothesis:
$$\hat{P}=\frac{\sum_{b=1}^{B}w^{(b)} I(\mu_{n}^{(b)}>0)}{\sum_{b=1}^{B}w^{(b)}}$$
If $P$ is too big (in either case), then you reject the null hypothesis.  A standard value would be $P>0.95$.


Get file name with Jquery

Question: I want to get the file name that i upload and show it in my  .
this is my code:
var filename = $('#image_file').val();
$('#select_file').html(filename);

      <input type="file" id="image_file">

Answer: This is some simple example. I hope this will help to you:
$(document).ready(function() {
  $("#image_file").on("change", function() {
     $("#select_file").html(this.value);
  });
});

Edit:
 Only now I realized what the problem is.
So this is the code:
$(".upload-btn").one("click", function _handler(event) {
        _handler.oldContext = this;
        var _file = $(this).find("input[type='file']").one("change", function() {
        var oldContext =    $(_handler.oldContext);
            oldContext.find("span#select_file").html(this.value);
        $(this).attr("display", "none");
        oldContext.one("click", _handler);
    });
    _file.attr("display","block").trigger("click");
    event.stopPropagation();
});

and this is working jsfiddle:
https://jsfiddle.net/qpo8dwf9/33/
Edit2: This is working example with two inputs and attach listeners on document ready.
https://jsfiddle.net/qpo8dwf9/38/
Edit3: There is issues under Chrome and Chromium with fakepath. This is the last version.
https://jsfiddle.net/qpo8dwf9/49/
Comment: ОК. Explain the problem better please.  How exactly you upload the file? What is your back-end? Is this snippet is located into upload form?
Comment: The answer has changed. This is a very non standart solution.
Comment: hmm in the fiddle it wokrs, but when i implement it it starts automatically to open the dialog for file upload and when i do it it doesn show the text :/, can we caht pls
Comment: The answer is edited. There is improvement. We handle case when the user click cancel on upload.
Comment: Thank you very much, I already amde this the answer but if you could it explain a little would be perfect for others and me too :D
Answer:
This is some example of getting the name of a file uploaded
    $(document).ready(function(){

        $('input[type="file"]').change(function(e){

            var fileName = e.target.files[0].name; //getting the file name
            var display = $("#select_file"); //where to display
            display.html(fileName);

        });

    });

I hope this will help you :)
Comment: Hi, I have updated the code hope this will help you :).
Comment: hmm it seems to work, but i have 2 of them and when i upadte the first it also shows on the second, how to do it seperatly ?
Comment: I 'm not understanding your problem well, please explain much better the problem.
Comment: i have 2 input type file

Get file name with Jquery


$\matrix {AB}=\matrix 0$ and $\matrix A\not= \matrix 0$, then $|\matrix B|=0$ ?!

Question: Let $A$ and $B$ be two square matrices such that $\matrix {AB}=\matrix 0$, where $\matrix 0$ denotes the Null Matrix.
My textbook mentions that [without proof]: if $\matrix A\not= \matrix 0$, then $|\matrix B|=0$.
I am not sure if this is even correct:
Consider the scenario: $|\matrix B|=k$, where $k$ is a non-zero constant and $|\matrix A|=0$ with $\matrix A\not =\matrix 0$, then this above property predicts that the product $\matrix {AB}$ cannot be $\matrix 0$. Though I could not find counter-examples, this seems improbable.

Is this property true?
If not, can you provide counter-example of the kind I mentioned?
Comment: If $det(B)\neq 0$, then $B$ is invertible. $AB=0$ implies that $A=0$. Contradiction.
Comment: If B has an inverse you could right multiply to get A=0. Thus B can't have an inverse.
Comment: In fact, for any $n$-by-$n$ matrix over a fixed field $B$, there exists an $m$-by-$n$ matrix $A$ such that $AB=0$ if and only if $\det(B)=0$.  In general, for any $n$-by-$r$ matrix $B$, there exists an $m$-by-$n$ matrix $A$ such that $AB=0$ if and only if $\text{rank}(B)<n$.
Answer: Note that saying $|B|=0$ is very different from saying $B=0$ (assuming that $|B|$ denotes the determinant of $B$).
If $\det B\ne0$, then $B$ is invertible, so from $AB=0$ you get
$$
A=ABB^{-1}=0B^{-1}=0
$$

On the other hand it is easy to find nonzero matrices with zero product:
$$
\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}
\begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix}
$$
but this doesn't contradict the above: indeed both matrices have zero determinant.
Answer: We know that $dim(ker(A)) + dim(ker(B)) \geq dim(ker(AB))$.
(Sylvester rank inequality: $\operatorname{rank} A + \operatorname{rank}B \leq \operatorname{rank} AB + n$)
As $AB=0$, hence $dim(ker(AB)) = n$ (where A and B are $n \times n$ matrices.)
Hence, $dim(ker(A)) + dim(ker(B)) \geq n$.
As $A\neq0$, $dim(ker(A))<n$.
So, $dim(ker(B))>0$.
Thus, $B$ is not invertible. Hence, $|B| = 0$.
Answer: If $AB=0$ and $A\ne0$, then $aB=0$ for every nonzero row $a$ of $A$. Hence $B$ has linearly dependent rows (because $aB$ is a non-trivial linear combination of the rows of $B$) and its determinant must be zero.
Note that this proof is very basic: it works over any commutative ring (not just over fields) and the notion of determinant was devised to detect linear dependence in the first place.


How to run an svn server on a Mac completely fire-walled from the outside?

Question: Is there are way to run a local svn server on a Mac (OS X 10.6.x) such that no ports are open and accessible from outside that Mac?
If so, exactly where do any configuration scripts of any kind need to go?
Comment: By "outside" do you mean outside that computer, or outside the network?
Comment: Why bother?  If your goal a personal source repository, there are vastly better and easier to configure decentralized options.  Mercurial, git, Fossil, monotone, ...
Comment: So how do I migrate this question to programmers.stackexchange, if that's the more suitable QA forum?  (But a search showed more svn questions here than there.)
Answer: You can use subversion repositories with the file protocol tool, something like file:///opt/svn/my_repo. That way, you can use your SVN repos locally without the need for an actual server.
Another alternative could be to setup an Apache with mod_dav_svn and let it listen only to localhost (127.0.0.1).
Answer: I think that by default when you install SVN it is only accessible from the local box as it does not have a built in networking infrastructure. You usually have to tie it into an apache config or tunnel to the box with SSH.
So you should be able to install it without a worry of networking. If your install automagically installs the apache piece, you should be able to disable it in your apache conf.
Comment: You would want to use the commandline interface at this point which is really easy to use.


QUERY to merge the names of two regions and sum the number of their occurrences

Question: I have an array with states/regions in the UK. Some regions occur more than once in this list, so I have performed a COUNTIF to determine the number of times that each one occur.
Now I need to run a QUERY to list top 5 regions.
Generally, most occurrences are for the London area.
The issue is that in the regions there are 2 states that refer to the Greater London area - London and Greater London.
These two I need to merge and sum their values.
There needs to be only one region - Greater London, and its value needs to hold the sum of London and Greater London.
This is the dataset I have:
+----------------+-------+
| State/Province | count |
+----------------+-------+
| Hampshire      | 1     |
+----------------+-------+
| Kent           | 2     |
+----------------+-------+
| West Lothian   | 3     |
+----------------+-------+
| London         | 4     |
+----------------+-------+
| Greater London | 5     |
+----------------+-------+
| Cheshire       | 6     |
+----------------+-------+

I have managed to put together this QUERY so far:
=QUERY(A1:B,"select A, max(B) group by A order by max(B) desc limit 5 label max(B) 'Number of occurrences'",1)
That gives me this output:
+----------------+-----------------------+
| State/Province | Number of occurrences |
+----------------+-----------------------+
| Cheshire       | 6                     |
+----------------+-----------------------+
| Greater London | 5                     |
+----------------+-----------------------+
| London         | 4                     |
+----------------+-----------------------+
| West Lothian   | 3                     |
+----------------+-----------------------+
| Kent           | 2                     |
+----------------+-----------------------+

What I need is the Greater London and London entries to be merged under the name Greater London and their numbers of occurrences to be summed, providing this result:
+----------------+-----------------------+
| State/Province | Number of occurrences |
+----------------+-----------------------+
| Greater London | 9                     |
+----------------+-----------------------+
| Cheshire       | 6                     |
+----------------+-----------------------+
| West Lothian   | 3                     |
+----------------+-----------------------+
| Kent           | 2                     |
+----------------+-----------------------+
| Hampshire      | 1                     |
+----------------+-----------------------+

Apologies for not sharing a sheet, but I have security restrictions that are not allowing me to share any link to sheet outside the firm.
Answer: =QUERY(QUERY(ARRAYFORMULA(
 {SUBSTITUTE(IF(A1:A="London","♥",A1:A),"♥","Greater London"),B1:B}),
 "select Col1, sum(Col2)
  where Col1 is not null
  group by Col1"),
 "select Col1, max(Col2)
  group by Col1
  order by max(Col2) desc
  limit 5
  label max(Col2)'Number of occurrences'",1)

Answer: =QUERY(ARRAYFORMULA(SUBSTITUTE(
 IF((A1:A="London")+(A1:A="London2")+(A1:A="London3"),
 "♥",A1:A),"♥","Greater London")),
 "select Col1, count(Col1)
  where Col1 is not null and not Col1 = '#N/A'
  group by Col1
  order by count(Col1) desc
  limit 5
  label count(Col1) 'Number of occurrences'", 1)

Comment: @playr0 Great work! Does the job correctly. I'd like to ask, how can I implement another column as s condition?
What I am thinking of is to limit the `COUNT` to the records that have `1` in the additional column?...
Comment: Something of such, but with the `ARRAYFORMULA(SUBSTITUTE(IF(` part implied for both queries in the following: `={Query({Report_dataRange},"Select Col24, Count(Col24) where Col27 = 1 group by Col24 order by Count(Col24) desc limit 5 label count(Col24) ''",0),
  QUERY({Report_dataRange},"Select        Count(Col24)                 group by Col24 order by Count(Col24) desc limit 5 label count(Col24) ''",0)}`
Answer: =QUERY(ARRAYFORMULA(SUBSTITUTE(
 IF((QUERY(A1:B,"where B=1")="London")+
    (QUERY(A1:B,"where B=1")="London2")+
    (QUERY(A1:B,"where B=1")="London3"),
 "♥",QUERY(A1:B,"where B=1")),"♥","Greater London")),
 "select Col1, count(Col1)
  where Col1 is not NULL and not Col1 = '#N/A'
  group by Col1
  order by count(Col1) desc
  limit 5
  label count(Col1) 'Number of occurrences'", 1)


Time complexity analysis for recursion inside recursion

Question: I am a little confused of the time complexity of the code below:
public int getHeight(TreeNode root) {
    if (root == null) return 0;
    return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public boolean isBalanced(TreeNode root) {
    if (root == null) return true;

    int heightDiff = getHeight(root.left) - getHeight(root.right);
    if (Math.abs(heightDiff) > 1) {
        return false;
    }
    else {
        return isBalanced(root.left) && isBalanced(root.right);
    }
}

I calculate the time as: T(n) = 2 * T(n / 2) + n, which gives me O(n * log(n)). But in the book, it says the time complexity is O(n ^ 2).
Can anyone tell where my calculation is wrong? Thanks!
Answer: Your recurrence assumes that the tree is balanced, which would make isBalanced O(n lg n). It appears the book does not make that assumption, so isBalanced becomes O(n2). In the worst case, each internal node could have only one child (such a tree is sometimes called a vine, since it doesn't really branch at all).
For example, here is a worst-case input:
    1
     \
      \
       2
      /
     /
    3
   /
  /
 4
  \
   \
    5

Comment: Thank you. I think I got your idea. But then is there a way to calculate the complexity using a recurrence formula? It seems that by looking at the code, it is straightforward to get T(n) = 2 * T(n / 2) + n, which is wrong in this case.
Comment: I think the closest recurrence that would apply is T(n) = T(n-1) + T(1) + n. It captures the worst case behavior correctly, at the expense of ignoring the expected case. T(n/2) again assumes that each recursive call actually works on (roughly) half the data, which is not true of the worst case.


AuthenticationSuccessEvent never fired

Question: I writing app where user logs in using facebook.
My security config/application class:
@SpringBootApplication
@EnableOAuth2Sso
@ComponentScan(basePackages = { "app" })
public class Application extends WebSecurityConfigurerAdapter {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private OAuth2ClientContext oauth2ClientContext;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/",
                        "/login**",
                        "/webjars/**",
                        "/bower_components/**",
                        "/assets/**",
                        "/app/**",
                        "/api/auth/isAuthenticated")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and().formLogin().defaultSuccessUrl("/", true).loginPage("/login").permitAll()
                .and().logout().logoutSuccessUrl("/").permitAll()
                .and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    }

    @Bean
    @ConfigurationProperties("facebook")
    ClientResources facebook() {
        return new ClientResources();
    }

    private Filter ssoFilter() {
        CompositeFilter filter = new CompositeFilter();
        List<Filter> filters = new ArrayList<>();
        filters.add(ssoFilter(facebook(), "/login/facebook"));
        filter.setFilters(filters);
        return filter;
    }

    private Filter ssoFilter(ClientResources client, String path) {
        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
        OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
        filter.setRestTemplate(facebookTemplate);
        filter.setTokenServices(new UserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId()));
        return filter;
    }

    class ClientResources {
        private OAuth2ProtectedResourceDetails client = new AuthorizationCodeResourceDetails();
        private ResourceServerProperties resource = new ResourceServerProperties();

        public OAuth2ProtectedResourceDetails getClient() {
            return client;
        }

        public ResourceServerProperties getResource() {
            return resource;
        }
    }

My problem is that even that I configured listener:
package app;
    @Component
    public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {

        @Override
        public void onApplicationEvent(AuthenticationSuccessEvent event) {
            System.out.println("Event fired");
        }
    }

it is never fired. I tried solution provided here : Spring boot OAuth successful login listener not triggering but it does not help either.  SecurityContextHolder.getContext().getAuthentication().isAuthenticated() returns true after logging in.
Answer: OAuth SSO support does not fire AuthenticationSuccessEvent indeed. This is something I've been facing recently as well. This is implemented now but not released yet.
Comment: So is there a workaround ? I mean how can I perform some action after succesfull login?
Comment: I guess. To make things worse, I also fixed [an issue in Spring Boot](https://github.com/spring-projects/spring-boot/issues/5853) related to this. My best guess is that you should try to register `OAuth2ClientAuthenticationProcessingFilter ` yourself. Check the change in the implementation, you can probably backport that in your own extension.
Answer: To publish authentication events it's possible to override authenticationHandler's.
basic security config:
@EnableWebFluxSecurity
public class SecurityConfig {

    @Autowired
    public ApplicationEventPublisher applicationEventPublisher;

    @Bean
    public AuthenticationEventPublisher authenticationEventPublisher() {
        return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
    }

    @Bean
    public ServerAuthenticationEntryPoint serverAuthenticationEntryPoint() {
        return new HttpBasicServerAuthenticationEntryPoint();
    }

    @Bean
    public LoggerListener loggerListener() {
        return new LoggerListener();
    }

    @Bean
    public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {

        return http.authorizeExchange()
                .anyExchange().authenticated()
                .and()
                .formLogin(login -> {
                    login.authenticationSuccessHandler(new LoggingAuthenticationSuccessHandler());
                    login.authenticationFailureHandler(new LoggingAuthenticaionFailedHandler(serverAuthenticationEntryPoint()));
                })
                .build();
    }
}

success handler:
class LoggingAuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {

    @Autowired
    private AuthenticationEventPublisher eventPublisher;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        this.eventPublisher.publishAuthenticationSuccess(authentication);
        return super.onAuthenticationSuccess(webFilterExchange,authentication);
    }
}

failure handler:
class LoggingAuthenticaionFailureHandler extends ServerAuthenticationEntryPointFailureHandler  {

        @Autowired
        private AuthenticationEventPublisher eventPublisher;

        public LoggingAuthenticaionFailureHandler(ServerAuthenticationEntryPoint authenticationEntryPoint) {
            super(authenticationEntryPoint);
        }

        @Override
        public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {
            AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "anonymousUser",
                    AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
            this.eventPublisher.publishAuthenticationFailure(exception, token);
            return super.onAuthenticationFailure(webFilterExchange, exception);
        }
    }

and event listener:
public class AuthenticationEvents {

    private LoggerListener loggerListener;

    @Autowired
    public AuthenticationEvents(LoggerListener logger) {
        this.loggerListener = logger;
    }

    @EventListener
    public void onSuccess(InteractiveAuthenticationSuccessEvent success) {
        loggerListener.onApplicationEvent(success);
    }

    @EventListener
    public void onSuccess(AuthenticationSuccessEvent success) {
        loggerListener.onApplicationEvent(success);
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent failures) {
        loggerListener.onApplicationEvent(failures);
    }
}

The standard LoggerListener could be replaced with own implementation.
Keep in mind, if Your security filter chain has UsernamePasswordAuthenticationFilter then overrides the success handler is not necessary.

AuthenticationSuccessEvent never fired


Save ODBC credentials for Oracle on Windows

Question: On my dev machine (Mint Linux), I have ODBC set up with credentials so that I only have to specify DRIVER and DBQ in the connection string. Unfortunately, the script will have to run on a Windows machine. How do I set it up in Windows so that I don't have to pass in an explicit username and password?
Answer: Go to Administrative Tools> Data Sources (ODBC) and create your DSN, either User, System or File... whichever you need.
Answer: On your Windows server, set up the ODBC connection there.
Administrative Tools>Data Sources (ODBC)
I usually set these up under System DSN. Pretty straightforward - enter credentials/connection info/etc to include user/pass. It allows you test the connection as well. This stays resident, so when you run the Windows script, the connection is already established and no u/p string needs to be resent.


WebHook Azure Data Factory pass variables

Question: I have a WebHook activity in Azure Data Factory pipeline but I'm not able to pass variables here.
@json('{
"body": "@{pipeline().parameters.body}",
"name": "@{variables('name')}"
}')

There is a problem with '. I've tried with \'name\' but it does not work.
Comment: unfortunatelly it does not work. I needed to do it as below:
@json(concat('{
"name": "',variables('name'),'"
}'))
Comment: Please check updated, I've tested it in pipeline run successfully.
Answer: The body representing the payload to be be sent to endpoint must be Valid JSON or an expression that results a value of type JSON. So in WebHook activity you can just pass the JSON string rather than using the function json() again.
Checkout this example:
Use any string variable:

Using the variable and parameter in JSON string:
{
   "var":"@{variables('variable')}",
   "param":"@{pipeline().parameters.parameter}",
   "age":"23"
}

by string interpolation, the value of variable is replaced in place


"Error in deserializing body of request message for operation" happen when I use Ksoap2 to call WCF

Question: I wanted to use KSoap2 to Call WCF. But some error happened.
I don't know if I need to setting other attributes of OperationContract ?
would anyone can help me?
I will appreciate you very much
this is my WCF OperationContract
[OperationContract (Name = "HelloWorld")]
string HelloWorld(string username);

here is my WSDL
<wsdl:operation name="ComparePassWord">
<soap:operation soapAction="http://tempuri.org/IITRIService/ComparePassWord"   style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>

here are my Java Code
SoapObject request = new SoapObject(NAMESPACE, "HelloWorld");
PropertyInfo HelloWorld = new PropertyInfo();
HelloWorld.setType(String.class);
HelloWorld.setName("username");
HelloWorld.setValue(username);
request.addProperty(HelloWorld);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try {
  // Invoke web service
     androidHttpTransport.call(SOAP_ACTION_URL,envelope);
    }  catch (Exception e) {
            //Print error
            e.printStackTrace();
            //Assign error message to resTxt
            resTxt = "Error occured";
        }
        SoapObject response = null;

        try {
            // Get the response

            response = (SoapObject) envelope.bodyIn;
        }
         catch (Exception e) {
            //Print error
            e.printStackTrace();
            //Assign error message to resTxt

            return new String[]{"fail"};
        }

Answer: I solve this problem by update my WCF to  version 4.5.
WCF will show just the operations in the WSDL itself - the data structures are documented in XSD files that are linked to the WSDL file.
When I update my WCF to Version. I can got entire WSDL including all XSD elements


Redirect when translation of node is unavailable

Question: I have installed pathauto and i18n and I would like to create a node which is only available in one language. Lets say I have a Basic Page with the URL:
www.example.de/test-page-in-german
so I dont want this page to be available from
www.example.pl/test-page-in-german
because I am afraid google is gonna ban my site for double content.
Ive already selected "Require language (Do not allow Language Neutral)" for my content type and for "test-page-in-german" I have selected german and their is no translation but the node is still visible from other language domains.
Answer: I finally got it working with the Global Redirect Module
I had to enable the option Language Path Checking.
Then I got another problem with the redirects which was fixed by this patch:
https://www.drupal.org/node/1514166#comment-11657665


In What Order to Practice Holding Notes on Bansuri

Question: At the start of Bansuri practice, I try to blow each note and hold as long as possible. I do this 6 times per note, i.e. Sa Re Ga Ma Pa Dha Ni SA
But now I realize there are three octaves in Bansuri
My question is, in what order should I practice.
On one hand, everything starts with middle octave Sa, so I can practice
Sa Re Ga Ma Pa Dha Ni SA RE GA MA PA
but what about lower octaves pa da ni?
What is recommended order (per Bansuri Gurus, experienced Bansuri players, or even experts in Indian classical music) for blowing each note the longest?
Answer: You should try to cover as many notes as you can, starting from pa. After pa you should go up, like this: pa da ni Sa Re Ga Ma Pa Dha Ni SA RE GA MA PA. If you do it this, way you will cover two octaves.
Comment: Interesting. Several places say Bansuri has two octaves, others say three. Technically speaking, it covers 3 octaves, but it is slightly more than 2 octaves!


Why is the Ratio of $\ln(x)$ and $\log(x)$ a constant?

Question: I was solving some "Big-Oh" algorithm asymptotic complexity problems, when I discovered that for some constant $c$ and some variable $x$:
$$c^{\log(x)}$$ and $$x^{\log(c)}$$
grow at the same rate. When figuring this out I ended up with the expression:
$$\frac{\ln(x)}{\log(x)}=\frac{\ln(c)}{\log(c)}\approx 2.3025$$
This result was surpirsing and somewhat baffling to me. This might seem like a naive question, but could someone help me understand how the ratio of $\log_{10}(x)$ and $\ln(x)$ ends up being a constant value?
Comment: Indeed the expressions you gave are equal, not just of equal growth: $$c^{\log(x)}=e^{\log(c)\log(x)}=x^{\log(c )}$$
Comment: This is just the change of base formula for logarithms that you learn in basic algebra.
Answer: Some of the answers already provided get close to a full explanation, but not quite.
Recall that if $b > 1$ and $x > 0$, and $$\log_b x = y,$$ what this means is that $b^y = x$.  In other words, the base-$b$ logarithm of $x$ is an exponent $y$ such that when the base $b$ is raised to the $y^{\rm th}$ power, the result is $x$.  This is the definition of a (real-valued) logarithm.
So, why is it that for two bases $a$, $b$, $$\frac{\log_a x}{\log_b x}$$ is a constant not dependent on $x$?  The reason is that $\log_a x$ is an exponent, say $y$, such that $a^y = x$; and $\log_b x$ is an exponent, say $w$, such that $b^w = x$; then $$b^w = x = a^y.$$  And now, raising both sides to the $1/w$ power, we get $$b = (b^w)^{1/w} = (a^y)^{1/w} = a^{y/w}.$$  So the ratio $y/w$ does not depend on $x$.  In fact, again using the definition of logarithm, $y/w$ is the exponent for which the base $a$ must be raised to yield $b$; that is, we explicitly have $$\frac{y}{w} = \log_a b,$$ and from this, we get (with one additional algebraic step) what is known as the "change-of-base" formula $$\frac{\log_a x}{\log_a b} = \log_b x.$$
Note that only the definition of $\log$ was used, and the rule for exponents $(b^m)^n = b^{mn}$.
Answer: For all $x\neq1$, $x>0$ we have: $$\frac{\ln{x}}{\log{x}}=\frac{\ln{x}}{\frac{\log_ex}{\log_e{10}}}=\log_e10=\ln10.$$
Answer: Hint: $\ln(10)\approx 2.3025$. Given that information, your conjecture is that $\ln(x)=\ln(10)\log_{10}(x)$. Can you see a way to prove that?
Comment: I love the effort of guiding people to the answer.
Answer: If $\ln x = a_x$ and $\log_{10} x = b_x$ then
$e^{a_x} = x$ and $10^{b_x} = x$.
Bear in mind $10 = e^{\ln 10}$ so $10^k = (e^{\ln 10})^k = e^{k\ln 10}$.
So if $10^{k_x} =e^{k_x\ln 10} = x$ then......
By definition $\log_{10} x = k_x$ and $\ln x = k_x\ln 10$ and so.......
$\frac {\ln x}{\log_{10} x} = \frac {k_x\ln 10}{k_x} = \ln 10$.
It's just a conversion constant and shouldn't surprise us.
This is the very basis of the rule $\log_b x = \frac {\log_a x}{\log_a b}$ (note if $x$ is a variable and $b$ is a constant that is exactly your observation).
Answer: Take the logarithm of both expressions:
$$
\log(c^{\log x})=\log x\log c
\qquad
\log(x^{\log c})=\log c\log x
$$
So, not only $c^{\log x}$ and $x^{\log c}$ grow at the same rate: they're equal, whatever base of logarithms you use.
For the second part, note that $x=e^{\ln x}=b^{\log_bx}$ by definition. Then
$$
\ln x=\log_bx\ln b
$$
Therefore, for $x\ne1$,
$$
\frac{\ln x}{\log_bx}=\ln b
$$
Answer: $log_a b$ = $log_c b \over log_c a$ is a general rule.
Thus $log_c a = {log_c b \over log_a b}$ and your expression is the case of this when $a=10, b=x, c=e$.
Comment: Thanks.  I edited to correct
Comment: Ummm.... by your correct rule we have $$\ln(10)=\frac{\log_x(10)}{\log_x(e)}$$ which isn't what we're trying to prove.
Answer: Because $e^{cx}=10^{x}$ for all $x$ and $c:=\ln(10)\approx 2.3025$


Sending commands to uart on python

Question: I am trying to write a pyserial command to the uart port to control the robot arm.
I have some manual:
manual for arm
manual command example
I use pyserial like that:
<code>import serial
from time import sleep

port = serial.Serial("/dev/ttyUSB0", baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=8, timeout=1)

port.write(b"\x055\x55\x0B\x03\x02\x20\x03\x02\xB0\x04\x09\xFC\x03\xaa")
sleep(0.3)
#port.write(b"\x05")
#sleep(0.3)
#port.write(b"\x06")
#sleep(0.03)
#port.write(b"\x08\x01\x00")
print('send')
</code>
At first I tried to run it in one line, the buzzer will beep that the command was accepted, but the hand does not move.
Then I tried to split the Header separately for the Length in the next line and the Command with Parameters in the next.
Tell me how you can send these commands to the port, maybe there is something ready to do this in Python?
Comment: https://stackoverflow.com/questions/32018993/how-can-i-send-a-byte-array-to-a-serial-port-using-python
Does this help ?
Answer: LSC Series Servo Controller Communication Protocol V1.2 manual says:
If the user transmits the correct data to the servo
controller, the blue LED 2 on the controller will flash one time, indicating that the
correct data have been received. If the user transmits the wrong data, then the blue
LED2 will not have any reaction and will keep the bright, then the buzzer will beepbeep twice to remind the user of the data error.
The only thing in that manual about that buzzer is that it beeps 2 times if there is a data error...
Comment: Thanks for the answer. But how manage this servos if they don't move?
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32143166)

Sending commands to uart on python


drawing a model on a slope

Question: My models are axis-aligned.
I know the normal of the surface I want to draw them on; how do I compute the rotations or rotation matrix that I should use to draw the model perpendicular to the surface?
Comment: What is the context? What do you need? Do you need the math to transform all vertices of your model to a new location, do you just want to draw it in some rendering pipeline, do you just want to understand the maths behind it? What is your question?
Comment: I want to set up the GL modelview matrix so that I can draw my model in its VBO on the face (I know the xyz) and colinear to the normal
Answer: Well, if u is the unit up vector, and n is the unit surface normal, then you want a rotation that turns u into n. (This rotation isn't unique: you can compose any rotation about u before it, and any rotation about n after it.)
How to compute this rotation? Well, it depends on what framework or API you're working with, and how rotations are represented. A decent framework has an API call for this, for example in Unity 3D there's Quaternion.FromToRotation.
If you don't have an API call for that, then you can work it out for yourself. Any rotation can be represented in axis–angle form, say (a, θ). Here θ is the angle between the vectors u and n (which you can compute using the cosine rule: u · n = |u| |n| cos θ), and a is an axis perpendicular to both vectors: a = u × n. (There are two special cases: when u = n the null rotation will do, and if u = −n any half-rotation about any vector perpendicular to u will do.)
If you're using OpenGL you can now call glRotate.
And if you don't even have that ... well, you've no business asking this kind of basic question! But see Wikipedia for how to turn axis–angle representation into matrix representation.
Comment: In XNA, you could do this [sample](http://create.msdn.com/en-US/education/catalog/sample/collision_3d_heightmap_normals). The sample also contains a little piece of documentation in `HTML`-form
Comment: I see that XNA [lacks an API call](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.quaternion_members.aspx) for computing a rotation between two vectors. I'm not impressed!

drawing a model on a slope


How to create a drush command without drupal?

Question: I'm attempting to create a drush command for use outside of a Drupal install.  It's basically a script to make a copy of a distribution starter kit and do some string replacing.  I'm following the sandwich example.
I'm running into two issues...
1) I created mycommandfile.drush.inc in a new folder.  If I try to run the command it says the drush command cannot be found. So I copied the file to my /.drush folder and it finds the command.  Any idea why that would be the case?
2) The second issue is that with the file in the /.drush folder it is telling me that I need a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.  In my command declaration I have 'bootstrap' => DRUSH_BOOTSTRAP_DRUSH.
Answer: 1) Drush only searches certain folders for Drush commandfiles.  Run with --include=/path/to/your/drushcommands, or set $options['include'][] = '/path/to/your/drushcommands'; in your drushrc.php if you'd like to use a directory other than $HOME/.drush.
2) If you have in fact set your bootstrap to DRUSH_BOOTSTRAP_DRUSH, then you should not be getting that message.  Maybe there is something wrong with your commandfile definition; can't guess what it might be from the information provided, though.
For a quick start on writing a new Drush command, see the drushify project.  It will create a template for you very quickly.  Perhaps you could compare the template drushify creates with the commandfile you put together.
Comment: Thanks Greg!  That did it.  Once I added the --include option then it executed.


Cordova GZip decompression doesn't work

Question: I try enable GZip compression for improve connection performance between client and server, but it seems that WebView doesn't decompress GZip-response.
Response Header(from server) contains:
  Content-Encoding:gzip
  Content-Type:application/gzip
Body contains compressed JSON
On the Desktop browsers all fine,
but if it is android device in Chrome DevTools I see compressed body.
Mobile app doesn't decompress response body.
Created issue https://issues.apache.org/jira/browse/CB-9427
Comment: the android mobile webview and browsers are no where near desktop browsers, they probably just don't support it. I don't know for sure but that is my best guess. That is why on android I build all of my apps with crosswalk. has support for everything and blows performance through the roof: https://crosswalk-project.org/
Answer: When I have changed content type into 'application/json' problem was solved.
Here sample from Grape framework app:
<code>module App
  class Users < API

    resource :users do
      format :json
      content_type :txt, "application/json"
      parser :json, nil

      desc "Get users"
      params do
        optional :role, type: String, desc: "User's role"
      end

      get '/all' do
        users = User.all
        path = "#{Rails.root.to_s}/tmp/user_response.gz"
        FileUtils.rm_rf(path, secure: true)
        Zlib::GzipWriter.open(path){|gz| gz.write(users.to_json) }
        content_type "application/json"
        header['Content-Encoding'] = 'gzip';
        env['api.format'] = :json
        File.open(path).read
      end
    end
  end
end
</code>
Issue https://issues.apache.org/jira/browse/CB-9427 was closed.
Thanks to cordova support team!

Cordova GZip decompression doesn't work


What quadratic field is contained in the splitting field of $x^5 - 4x - 2$ over $\mathbb{Q}$?

Question: Since $x^5 - 4x - 2$ is irreducible (using Eisenstein's criterion with $p=2$), and it has precisely three real roots, it follows that the Galois group of the splitting field is $S_5$.  Therefore, there exists a quadratic extension of $\mathbb{Q}$ contained in this field, corresponding to the normal subgroup $A_5$.  In fact, since the sign map $S_5 \to \{ \pm 1 \}$ is an abelianization map, $A_5$ should be the unique (normal) subgroup of $S_5$ of index 2, so the quadratic extension should be unique.  So, I found myself wondering how one would calculate exactly what field this is.
I suppose a brute force method would be: if the roots are $\alpha, \beta, \gamma, \delta, \epsilon$, then this splitting field has basis $\{ \alpha^{0..4} \beta^{0..3} \gamma^{0..2} \delta^{0..1} \epsilon^0 \}$ as a $\mathbb{Q}$-vector space using the relations:
\begin{align*}
\alpha^5 - 4 \alpha - 2 & = 0 \\
\beta^4 + \alpha \beta^3 + \alpha^2 \beta^2 + \alpha^3 \beta + (\alpha^4 - 4) & = 0 \\
\gamma^3 + (\alpha + \beta) \gamma^2 + (\alpha^2 + \alpha \beta + \beta^2) \gamma + (\alpha^3 + \alpha^2 \beta + \alpha \beta^2 + \beta^3) & = 0 \\
\delta^2 + (\alpha + \beta + \gamma) \delta + (\alpha^2 + \alpha \beta + \beta^2 + \alpha \gamma + \beta \gamma + \gamma^2) & = 0 \\
\epsilon + (\alpha + \beta + \gamma + \delta) & = 0.
\end{align*}
Then $\frac{1}{60} \operatorname{Tr}^L_K = \frac{1}{60} \sum_{\sigma \in A_5} \sigma \cdot$ would be a projection of $L$ onto $K$ if $L$ is the splitting field and $K$ is the quadratic field.  Therefore, some basis element would have irrational trace; and then we could calculate the (quadratic) irreducible polynomial of the image of this basis element.
However, I was wondering if there might be some other method to calculate the answer which doesn't require nearly as much work.  The problem is, if I try taking a simple basis element like $\alpha^1$, then the trace of that is zero; the norm would be $\alpha^{12} \beta^{12} \gamma^{12} \delta^{12} \epsilon^{12} = 2^{12}$; etc.  In fact, I think the only basis element with irrational trace would be $\alpha^4 \beta^3 \gamma^2 \delta$ since otherwise, there's some transposition which fixes it and so $\operatorname{Tr}^L_K(x) = \frac{1}{2} \operatorname{Tr}^L_{\mathbb{Q}}(x) \in \mathbb{Q}$.
Comment: Hmm, whatever it is, it must be a complex extension: the subgroup corresponding to $L \cap \mathbb{R}$ is generated by a transposition of the two complex roots, so it's not contained in $A_5$, so $L \cap \mathbb{R}$ does not contain the quadratic field.
Answer: The quadratic extension is $\Bbb Q(\sqrt D)$ where $D$ is the discriminant
of the polynomial $x^5-4x-2$. As the polynomial is a trinomial, computing
its discriminant won't be too hard.
See here for a formula to find this discriminant.
Comment: OK, now I feel silly.  Anyway, my computation (based on numerical approximations of the roots, but the determinant formula should also work) shows that $D = -2^4 \cdot 13259$ so the quadratic field is $\mathbb{Q}(\sqrt{-13259})$.
Comment: And Wolfram Alpha agrees on the value of the discriminant.


como centralizar verticalmente uma tag  dentro da div

Question: Gostaria de deixar o texto que esta dentro desses
 centralizado verticalmente

Realizar Chamada

Realizar Chamada

Realizar Chamada

Realizar Chamada

Tentei usar o vertical align mas não consegui. como deixar cada h2 dentro dessas div centralizados verticalmente nelas?
Answer: No caso vc queria este resultado:

h2{
  text-align: center;
}

Realizar Chamada

Realizar Chamada

Realizar Chamada

Realizar Chamada

Comment: A classe `text-center` já faz isso, porém alinha horizontalmente. O OP quer alinhar verticalmente.
Comment: exatamente Phiter. Ela realiza o alinhamento horizontal. mas vertical ainda nao funciona
Answer: Você pode usar o transform como sugerido pelo nosso colega hugocsl, porém o alinhamento usando transform é considerado um "hack" do css, pois não é exatamente pra isso que ele serve, apesar de funcionar.
Um approach mais moderno é usando flexbox. Você pode usar ele pra alinhar vertical/horizontalmente os elementos, assim;

.button-disciplina {
  background-color: #0fc0fc;
  height: 100px;
  margin-bottom: 10px;
}

.text-center-hv {
  display: flex;
  align-items: center;
  justify-content: center;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Realizar Chamada

Realizar Chamada

Realizar Chamada

Realizar Chamada

Lembrando que se você estiver usando o Bootstrap 4, ele já possui as classes utilitárias align-items-center e justify-content-center, que podem ser utilizadas em conjunto com d-flex para ter o mesmo efeito.
Comment: Ao meu ver mudar o tipo de display original do elemento, que no caso da div é block para flex, apenas para faz um alinhamento seria muito mais "hake" e deselegante, do que usar  transform:translate que é justamente para ajustar as coordenas X e Y do elemento.... Mas cada um com seu ponto de vista. O legal do CSS é que da pra fazer um coisa de várias formas []´s
Comment: A propósito, quando executa o seu Snippet em "Página toda" ele não parece alinhado, nem vertical nem horizontalmente, depois olha ai. tmj
Comment: Entendi. O alinhamento horizontal está apenas no texto dentro dos quadros, e não nos próprios quadros. O rapaz pediu pra alinhar apenas o texto dentro dos quadros mesmo.
Comment: Com relação ao `translate()`, sua funcionalidade é de reposicionar um elemento no plano 2d onde ele se encontra, porém dá pra usar essa função pra mudar o "ponto âncora" do elemento (tipo no photoshop) usando as porcentagens. Realmente, tem várias formas de fazer.
Answer: No elemento pai use display: table e no elemento filho use display: table-cell. Assim o vertical-align: middle irá funcionar.

.button-disciplina{
  width: 80%;
  height: 150px;
  display: table;
  border: solid 1px #000;
  border-radius: 10px;
  margin: 10px auto;
}

h2{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Realizar Chamada

Realizar Chamada

Realizar Chamada

Realizar Chamada


Assign complex type with UUID field from a function call

Question: I am using PostgreSQL 9.3, working with plpgsql functions:
CREATE TEMP TABLE uuid_inside (
    id  uuid PRIMARY KEY
);

CREATE FUNCTION uuid_test_func(id uuid)
  RETURNS uuid_inside AS
$$
DECLARE
    res_uuid_inside uuid_inside;
BEGIN
    IF (id = '00000000-0000-0000-0000-000000000001'::uuid) THEN
        SELECT uuid_test_func('00000000-0000-0000-0000-000000000000'::uuid)
            INTO res_uuid_inside;
        RETURN res_uuid_inside;
    END IF;

    res_uuid_inside.id := id;

    RETURN res_uuid_inside;
END;
$$
LANGUAGE plpgsql;

Call:
SELECT uuid_test_func('00000000-0000-0000-0000-000000000001'::uuid);

Message:

ERROR: invalid input syntax for uuid: "(00000000-0000-0000-0000-000000000000)"
  SQL-state: 22P02

But this works fine:
SELECT uuid_test_func('00000000-0000-0000-0000-000000000002'::uuid);

The problem is not with recursive function calling - the original code is refering to some other function inside.
Answer: Simple function
The recursion in your function seems pointless. This simple sql function does the job (without nesting and without the composite type wrapper):
CREATE FUNCTION uuid_test_func(id uuid)
  RETURNS uuid AS
$func$
SELECT CASE WHEN $1 = '00000000-0000-0000-0000-000000000001'::uuid
                 THEN '00000000-0000-0000-0000-000000000000'::uuid
            ELSE $1
       END
$func$ LANGUAGE plpgsql;

But that's probably just due to simplification for the demo.
Address problem in original
As for the error message. You are running into a confusing "feature" of PL/pgSQL:
Composite type assignment expects one column per type column. Assigning composite types as a whole is not an option.
This has nothing to do with the UUID type per se.
This modified version would work:
CREATE OR REPLACE FUNCTION uuid_test_func(id uuid)
  RETURNS uuid_inside AS
$func$
DECLARE
    res_uuid_inside uuid_inside;
BEGIN
   IF (id = '00000000-0000-0000-0000-000000000001'::uuid) THEN
       SELECT * FROM uuid_test_func('00000000-0000-0000-0000-000000000000'::uuid)
       INTO   res_uuid_inside.id;
  --   INTO   res_uuid_inside;    -- would work, too - 1st col is assigned
       RETURN res_uuid_inside;
   END IF;

   res_uuid_inside.id := id;

   RETURN res_uuid_inside;
END
$func$ LANGUAGE plpgsql;
Closely related question:
Passing array of a composite type to stored procedure
Simpler function
That said, I'd suggest this simplified form (keeping the recursion and the composite result):
CREATE OR REPLACE FUNCTION uuid_test_func(id uuid)
  RETURNS uuid_inside AS
$func$
BEGIN
   IF (id = '00000000-0000-0000-0000-000000000001'::uuid) THEN
      RETURN (SELECT f FROM uuid_test_func('00000000-0000-0000-0000-000000000000'::uuid) f);
   ELSE
      RETURN row(id)::uuid_inside;
   END IF;
END
$func$ LANGUAGE plpgsql;


The intersection of all curves is the intersection of a finite number of curves

Question: let $f_1(x,y),f_2(x,y),\dots{}$  be an infinitely countable number of polynomials in $\mathbb{R}[x,y]$. Denote by $C_n$ the curve in $\mathbb{R}^2$ given by
$$
C_n = \bigl\{ (a,b) \in \mathbb{R}^2 \mid f_n(a,b) = 0 \bigr\}.
$$
If $C$ is the intersection of all curves, that is,$$ C= \bigcap^{\infty}_{n=1}C_n$$
prove that there exists $m\geq1$ such that
$$
C = \bigcap^{m}_{n=1}C_n,
$$
this is the intersection of a finite number of curves.
I think we can use Hilberts Basis Theorem, but I can't think of how to start the argument. Could you help me, please!
Hilbert's basis theorem says that a polynomial ring over a Noetherian ring is Noetherian.
Comment: Your thought is a good one. *Keep going!* How is the property of being Noetherian useful? Can you construct an ascending chain of ideals that is somehow related to this family of curves?
Comment: How do you make the ideals form an ascending chain $I_1 \subseteq I_2 \subseteq \cdots$ though?
Comment: I thought about the ideals generated by the $f_{i}$, does it make any sense?
Comment: it could be $(f_1) \subset(f_1,f_2) \subset \dots $, where $(f_1)$ is
is the generating ideal by $f_1$? Since $\mathbb{R}[x,y]$ is noetherian, the chain is stationary. From there, I don't know how to proceed.
Answer: Continuing the argument of comments, let us consider the chain
$$(f_1)\subset (f_1,f_2)\subset\cdots$$
which is stationary, say, at $(f_1,\dots,f_m)$.
That is, $f_j\in (f_1,\dots,f_m)$ and
$$f_j=a_1^{(j)}f_1+\cdots+a_m^{(j)}f_m\quad (*)$$
holds for all $j=m+1,m+2,\cdots$.
Now, for the intersection,
$$\bigcap_{n=1}^{\infty} C_n\subset \bigcap_{n=1}^m C_n$$
holds trivially. The converse also holds since if $(x,y)$ is in RHS then by the relation $(*)$ it automatically satisfy $f_j(x,y)=0\ (j=m+1,m+2,\dots )$, hence it is in LHS, too.


Expand $[\frac{\tau^2}{16}(\frac{v}{i+1}+1)^2+\frac{1}{2}]^{-a-2}$

Question: How to expand the expression as showed in the title about $v=0$, in which, $a$ is a natural number and $\tau$ is a real number and $i$ is the complex unit. Many thanks in advance.
Answer: You have $$\left[\frac{\tau^2}{16}\left(\frac{v}{i+1}+1\right)^2+\frac{1}{2}\right]^{-a-2}$$
First factor the quadratic polynomial inside the power $$\left[\frac{\tau^2}{16}\left(\frac{v}{i+1}+1\right)^2+\frac{1}{2}\right]^{-a-2}=\left[\frac{\tau}{4}\frac{v}{i+1}+\left(\frac{\tau}{4}+\frac{i}{\sqrt{2}}\right)\right]^{-a-2}\left[\frac{\tau}{4}\frac{v}{i+1}+\left(\frac{\tau}{4}-\frac{i}{\sqrt{2}}\right)\right]^{-a-2}.$$
Now use the binomial theorem with each factor:
$$\left[\sum_{k=0}^{\infty}\binom{-a-2}{k}\left(\frac{\tau}{4}\frac{v}{i+1}\right)^k\left(\frac{\tau}{4}+\frac{i}{\sqrt{2}}\right)^{-a-2-k}\right]\times\left[\sum_{k=0}^{\infty}\binom{-a-2}{k}\left(\frac{\tau}{4}\frac{v}{i+1}\right)^k\left(\frac{\tau}{4}-\frac{i}{\sqrt{2}}\right)^{-a-2-k}\right]$$
Finally, multiply the two series above.
Comment: How can I get the first equation?
Comment: @Peng You can use that $a^2+b^2=(a+ib)(a-ib)$.
Comment: Is that true for all $v$ or only for the numbers in the vicinity of $v=0$?
Comment: Or is this Taylor expansion on $v=0$?
Comment: @Peng The [series coming from the binomial expansion](http://en.wikipedia.org/wiki/Binomial_series#Convergence) have a finite interval of convergence, unless $-a-2$ is a natural (\geq0) number.
Comment: Shall I expand it as $[\frac{\tau^2}{4^2}(\frac{v}{i+1}+1)^2+\frac{1}{2}]^{-a-2}
=
\sum_{b=0}^{\infty}
\binom{-a-2}{b}
\frac{\tau^{2b}}{4^{2b}}(\frac{v}{i+1}+1)^{2b}
(\frac{1}{2})^{-a-2-b}
=
\sum_{b=0}^{\infty}
\binom{-a-2}{b}
\frac{\tau^{2b}}{4^{2b}}
\sum_{m=0}^{2b} (\frac{v}{i+1})^m
(\frac{1}{2})^{-a-2-b}$


SSRS How do I add a date range to my x-axis on a line graph?

Question: I have a Line graph and I want the data to show over a range of 60 days back from current date. How do I do this in SSRS?
Comment: Can you show us what you already have and what you've tried?
Answer: On your line chart, you would use your date field as the Category. In the Category properties, you go to the FILTER tab and filter your date to be greater than the current date - 60 days.
For the Expression, select your date field, change the Type from Text to Date. Set the Value to <code>=TODAY.AddDays(-60)</code>
For the Chart Values, you would use the field with data that you are trying to show. In my example, I was showing the total (SUM) of Members for each date (MOE_DATE).

For more info, here's the long-winded MSDN on Charts - https://msdn.microsoft.com/en-us/library/dd239351(v=sql.110).aspx
Answer: You can also specify the minimum and maximum axis range in axis options. In my example below I set the maximum to the date parameter of the report, and just used a simple datediff formula in the minimum range.


Alinhamento vertical e display inline

Question: boa tarde!
Tenho a página abaixo e por mais que eu tente não consigo fazer o menu ficar em linha com a logotipo.
Onde estou errando?
Outro problema é que a logo e o menu têm altura de 88px porem a div que os abriga tem 120px de altura e o que eu gostaria é que o bloco logo/menu ficasse alinhado middle verticalmente em relação à caixa "topo" que os abriga.
<!doctype html>

<meta charset="utf-8">
<title>Documento sem título</title>

 Home

 Media

 Contato

 Pedido

 Sobre

Comment: Poderia postar uma imagem de como está por favor?
Comment: Não entendi direito sua duvida, rodei o seu código e está alinhado... Pode ser por causa da logo, se puder upar ela também..
Comment: Coloquei no final da pergunta. Note que a logo e o menu estão colados no topo. Mas eles estão dentro uma div "topo" que tem 120px de altura sendo que a logo e o menu têm 88;19px apenas e não consigo centralizar eles
Comment: logo upada no final da pergunta
Answer: Então, existe vários problemas nesse seu layout, mas eu resolveria esse seu problema colocando um valor fixo no height da div logo, segue abaixo.

@charset "utf-8";

/* CSS Document */

@import url('http://fonts.googleapis.com/css?family=Open+Sans');
* {
  font-family: 'Open Sans';
  margin: 0;
  padding: 0;
  box-sizing: content-box;
}

body {
  font-size: 12px;
  background-color: #F00;
  margin: 0 auto;
  width: 1000px;
}

img {
  border: 0;
  max-width: 100%;
}

ul {
  list-style: none;
}

a,
a:hover {
  text-decoration: none;
}

.topo {
  clear: both;
  position: relative;
  width: 100%;
  height: auto;
  border: solid 1px;
}

.logo,
.menu {
  display: inline-block;
  vertical-align: middle;
}

.logo {
  width: 30%;
  height: 88px;
}

.menu {
  width: 69.6%;
}

.corpo {
  background-color: #CCC;
  border: #000 3px solid;
  border-radius: 30px 30px 0 0;
}

.menuAbrir,
.menuFechar {
  display: none;
}

.menuPrincipal li {
  display: inline;
}

.menuPrincipal li a {
  display: inline-block;
  vertical-align: middle;
  width: 19.6%;
  height: 88.19px;
  line-height: 88.19px;
  text-align: center;
  font-size: 24px;
  color: #FFF;
  transition: background-color 1s;
}

.menuPrincipal li a:hover {
  color: #F00;
  background-color: #CCC;
}

 Home

 Media

 Contato

 Pedido

 Sobre

Demo - Jsfiddle
Da uma procurada sobre display flex, ele facilita muito esse tipo de coisa ;)
Comment: Pois é. mas dessa forma que você fez, note que não foi possível colocar a logo e o menu middle em relação ao topo mantendo o topo em 120px e a logo e o menu em 88px
Comment: Então, acho que consegui! Só acho que não seria a forma mais coerente. Mas consegui. Adicionei  margin-top: 15px; a logo e ao menu empurrando eles para baixo até chegarem ao meio. O que acha?
Comment: @CarlosRocha Então Carlos, ainda não entendi o que você quer! Se quiser colocar o seu código modificado no jsfiddle.net, e mandar o link aqui no comentário eu dou uma olhada.
Comment: Olha, eu tenho uma div com 1000px X 120px ok? Dentro dela eu tenho uma figura de 130x88 e uma outra div de  960x88 que abriga a ul do menu. Correto? O que eu quero é somente alinhar verticalmente essa imagem e essa div (que estão display:inline entre si) dentro da div pai. Mas eu consegui, fazendo 120-88 = 32, 32/2 = 16. Peguei a imagem e o menu e coloquei margin-top: 16px.

Alinhamento vertical e display inline


Jquery-ui-slider prevent max and min beeing set to the same value

Question: I am using a jquery-slider for a selector in which you can set a min and a max value for a price.

My problem is that its posible to set max and the min selector on the same value.

Is there a way to prevent this?
I have read through all the posible options-parameters of the plugin and it seemed like there is no way to solve this without editing the plugin ?
Thank you for your help
Edit
here as example the standart slider as shown on https://jqueryui.com/slider/#range

 $( function() {
    $( "#slider-range" ).slider({
      range: true,
      min: 0,
      max: 500,
      values: [ 75, 300 ],
      slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
      " - $" + $( "#slider-range" ).slider( "values", 1 ) );
  } );
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Slider - Range slider</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

  Price range:
  <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">

Answer: The solution was to add the following code to slide:
    if(ui.values[ 0 ] +19 >= ui.values[ 1 ]){
      return false;
    }

You can also test it in the following snippet

$( function() {
    $( "#slider-range" ).slider({
      range: true,
      min: 0,
      max: 500,
      values: [ 75, 300 ],
      slide: function( event, ui ) {
        if(ui.values[ 0 ] +19 >= ui.values[ 1 ]){
          return false;
        }
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
      " - $" + $( "#slider-range" ).slider( "values", 1 ) );
  } );
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Slider - Range slider</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

  Price range:
  <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">