My field is displayed on second row instead of third row

Question: I have this form (first image) and it has 3 columns and 3 rows. When I change the radiobutton Buscar por mês to Buscar por dias It changes a little bit (second image).

Formatação needs to keep on 2 column and 3 row but it doesn't happen.
I have tried to add a hidden div like

 to occupy some space but I failed.

My HTML

        <button class="btn btn-default toggle-dropdown just-icon" data-toggle="dropdown" aria-expanded="false" aria-haspopup="true">

        </button>

Buscar por período

Buscar por mês

Buscar por dias

Tela Teste - Buscar por período

Tela Teste - Buscar por mês

Tela Teste - Buscar por dias

        <form>

                        <input onClick="checkPeriodo()" type="radio" id="f-option1" name="selector" checked>
                        Buscar por período

                    <input onClick="checkMes()" type="radio" id="f-option2" name="selector">
                    Buscar por mês

                    <input onClick="checkDias()" type="radio" id="f-option3" name="selector">
                    Buscar por dias

                        Data Inicial:

                            <input type="date" class="form-control" name="bday">

                        Mês inicial:

                            <select class="form-control" id="sel1">
                                <option>Fevereiro</option>
                                <option>Dezembro</option>
                                <option>Janeiro</option>
                                <option>Julho</option>
                            </select>

                            <select class="form-control" id="sel1">
                                <option>2016</option>
                                <option>2015</option>
                                <option>2014</option>
                                <option>2013</option>
                            </select>

                        Últimos dias:

                            <input type="radio" name="options" id="option5">10
                            <input type="radio" name="options" id="option6">30
                            <input type="radio" name="options" id="option7">60
                            <input type="radio" name="options" id="option8">90

                        Mês final:

                            <select class="form-control" id="sel1">
                                <option>Dezembro</option>
                                <option>Dezembro</option>
                                <option>Janeiro</option>
                                <option>Julho</option>
                            </select>

                            <select class="form-control" id="sel1">
                                <option>2016</option>
                                <option>2015</option>
                                <option>2014</option>
                                <option>2013</option>
                            </select>

                        Data Final:

                            <input type="date" class="form-control" name="bday">

                        Intervalos:

                            <select class="form-control" id="sel1">
                                <option>0</option>
                                <option>1</option>
                            </select>
                            <select class="form-control" id="sel1">
                                <option>0</option>
                                <option>1</option>
                            </select>
                            <select class="form-control" id="sel1">
                                <option>0</option>
                                <option>1</option>
                            </select>
                            <select class="form-control" id="sel1">
                                <option>0</option>
                                <option>1</option>
                            </select>
                            <select class="form-control" id="sel1">
                                <option>0</option>
                                <option>1</option>
                            </select>

                        Formatação:

                            <select class="form-control" id="sel1">
                                <option>Porcentagem</option>
                                <option>Percentil</option>
                                <option>Média</option>
                            </select>

                        Veículo:

                            <select class="form-control" id="sel1">
                                <option>Locomotiva</option>
                                <option>Trem</option>
                            </select>

                    Posto:

                            <select class="form-control" id="sel1">
                                <option>Azul</option>
                                <option>Vermelho</option>
                                <option>Verde</option>
                                <option>Branco</option>
                            </select>

                    <button type="submit" class="btn btn-default">Consultar</button>

        </form>

Fiddle
https://jsfiddle.net/marquesm91/jkk034qj/1/
Comment: is that Bootstrap?
Comment: Yes, I am using bootstrap and JQuery to hide and show the fields I want
Comment: can you create a fiddle?
Comment: Sure, just a sec and I will update the question.
Comment: Have you considered changing the structure of your html? Instead of first dividing columns (class="col-md-4") and then creating rows (class="row") you could try to first create 3 rows (so 100% width) and then divide them in three columns each. Then each element would stay in their row.
Comment: @Dovi I have consireded that. This will be my last shot. First, I written here to see if anyone has a nice answer. It is a bad habit to divide into columns and then rows like I did?
Comment: Your JSFiddle has an error: "ReferenceError: checkPeriodo is not defined".
Comment: @MiquelAl.Vicens JSFiddle updated. https://jsfiddle.net/marquesm91/jkk034qj/1/
Comment: @marquesm91 in my opinion I think is better first rows and then columns, at least is how bootstrap is supposed to be used (just look at their examples http://getbootstrap.com/css/#grid). But it is always up to you :)
Comment: @Dovi yes, I will study more to implement this problem better. Thanks to answer me.
Answer:

$('#f-option1').on('click', function(){
  $('#titulo-periodo').show();
    $('#buscar-periodo-inicial').show();
    $('#buscar-periodo-final').show();
    $('#buscar-periodo-intervalos').show();

    $('#titulo-mes').hide();
    $('#buscar-mes-inicial').hide();
  $( '#row-final' ).show();
    $('#buscar-mes-final').hide();
    $('#buscar-mes-formatacao').hide();
    $('#buscar-veiculo').show();

    $('#titulo-dias').hide();
    $('#buscar-dias').hide();
    $('#botao-consulta-dias').hide();
    $('#buscar-dias-espaco').hide();
    $('#buscar-dias-veiculo').hide();

});

$('#f-option2').on('click', function(){
  $('#titulo-periodo').hide();
    $('#buscar-periodo-inicial').hide();
    $('#buscar-periodo-final').hide();
    $('#buscar-periodo-intervalos').hide();

    $('#titulo-mes').show();
    $('#buscar-mes-inicial').show();
  $( '#row-final' ).show();
    $('#buscar-mes-final').show();
    $('#buscar-mes-formatacao').show();
    $('#buscar-veiculo').show();

    $('#titulo-dias').hide();
    $('#buscar-dias').hide();
    $('#botao-consulta-dias').hide();
    $('#buscar-dias-espaco').hide();
    $('#buscar-dias-veiculo').hide();

});
$('#f-option3').on('click', function(){
  $('#titulo-periodo').hide();
    $('#buscar-periodo-inicial').hide();
    $('#buscar-periodo-final').hide();
    $('#buscar-periodo-intervalos').hide();

    $('#titulo-mes').hide();
    $('#buscar-mes-inicial').hide();
  $( '#row-final' ).hide();
    $('#buscar-mes-final').hide();
    $('#buscar-mes-formatacao').show();
    $('#buscar-veiculo').show();

    $('#titulo-dias').show();
    $('#buscar-dias').show();
    $('#botao-consulta-dias').show();
    $('#buscar-dias-espaco').show();
    $('#buscar-dias-veiculo').show();

});

    $('[data-toggle="tooltip"]').tooltip();

    $('#titulo-mes').hide();
    $('#buscar-mes-inicial').hide();
    $('#buscar-mes-final').hide();
    $('#buscar-mes-formatacao').hide();

    $('#titulo-periodo').show();
    $('#buscar-periodo-inicial').show();
    $('#buscar-periodo-final').show();
    $('#buscar-periodo-intervalos').show();

    $('#titulo-dias').hide();
    $('#buscar-dias').hide();
    $('#botao-consulta-dias').hide();

    $('#opcao-dropdown li').on('click', function(){
        var option = $(this).text();

        if(option === "Buscar por período") {
            $('#titulo-periodo').show();
            $('#buscar-periodo-inicial').show();
            $('#buscar-periodo-final').show();
            $('#buscar-periodo-intervalos').show();

            $('#titulo-mes').hide();
            $('#buscar-mes-inicial').hide();
            $('#buscar-mes-final').hide();
            $('#buscar-mes-formatacao').hide();
            $('#buscar-veiculo').show();

            $('#titulo-dias').hide();
            $('#buscar-dias').hide();
            $('#botao-consulta-dias').hide();
            $('#buscar-dias-espaco').hide();
            $('#buscar-dias-veiculo').hide();
        }
        else if (option === "Buscar por mês") {
            $('#titulo-periodo').hide();
            $('#buscar-periodo-inicial').hide();
            $('#buscar-periodo-final').hide();
            $('#buscar-periodo-intervalos').hide();

            $('#titulo-mes').show();
            $('#buscar-mes-inicial').show();
            $('#buscar-mes-final').show();
            $('#buscar-mes-formatacao').show();
            $('#buscar-veiculo').show();

            $('#titulo-dias').hide();
            $('#buscar-dias').hide();
            $('#botao-consulta-dias').hide();
            $('#buscar-dias-espaco').hide();
            $('#buscar-dias-veiculo').hide();

        }
        else if (option === "Buscar por dias") {
            $('#titulo-periodo').hide();
            $('#buscar-periodo-inicial').hide();
            $('#buscar-periodo-final').hide();
            $('#buscar-periodo-intervalos').hide();

            $('#titulo-mes').hide();
            $('#buscar-mes-inicial').hide();
            $('#buscar-mes-final').hide();
            $('#buscar-mes-formatacao').show();
            $('#buscar-veiculo').show();

            $('#titulo-dias').show();
            $('#buscar-dias').show();
            $('#botao-consulta-dias').show();
            $('#buscar-dias-espaco').show();
            $('#buscar-dias-veiculo').show();
        }
    });

    if($('input[name="selector"]').is(':checked')){
        $('input[name="selector"]:checked').trigger('click');
    }
.form-control {
  padding-left: 5px;
}

label {
    /* Other styling.. */
    text-align: right;

    float:left;
    margin-right: 15px;
}

label[for=buttons] {
    /* Other styling.. */
    margin-right: 0px;
}

.space-top {
  padding-top: 20px;
  padding-bottom: 20px;
}

.container {
  background-color: #eee;
}

body {
  background-color: black;
}

label {
  padding-top: 6px;
  white-space: nowrap;
}

.panel-heading .btn-group {
   float: right;
}

.btn-group-horizontal .btn {
display: inline !important;
}

.panel-heading {
   padding-right: 15px;
}

.just-icon {
    padding: 0;
    border: none;
    background: none;
    background-color: #fff;
}

.toggle-dropdown,
.toggle-dropdown:hover,
.toggle-dropdown:focus {
    border-color: #fff;
    background-color: #fff;
    /*color: #357ebd;*/
    outline: none !important;
}

.glyphicon-search {
    font-size: 150%;
}

.btn-default {
    outline: none !important;

}

.btn-group btn btn-default:focus {
    background-color: black;
}

.btn:active,
.btn.active {
    -webkit-box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.5);
            box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.5);
}

.padd-left1 {
    margin-left:-0.4%;
}

.padd-left2 {
    margin-left:-0.6%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

            <button class="btn btn-default toggle-dropdown just-icon" data-toggle="dropdown" aria-expanded="false" aria-haspopup="true">

            </button>

Buscar por período

Buscar por mês

Buscar por dias

Tela Teste - Buscar por período

Tela Teste - Buscar por mês

Tela Teste - Buscar por dias

            <form>

                            <input type="radio" id="f-option1" name="selector" checked>
                            Buscar por período

                        <input type="radio" id="f-option2" name="selector">
                        Buscar por mês

                        <input type="radio" id="f-option3" name="selector">
                        Buscar por dias

                            Data Inicial:

                                <input type="date" class="form-control" name="bday">

                            Mês inicial:

                                <select class="form-control" id="sel1">
                                    <option>Fevereiro</option>
                                    <option>Dezembro</option>
                                    <option>Janeiro</option>
                                    <option>Julho</option>
                                </select>

                                <select class="form-control" id="sel1">
                                    <option>2016</option>
                                    <option>2015</option>
                                    <option>2014</option>
                                    <option>2013</option>
                                </select>

                            Últimos dias:

                                <input type="radio" name="options" id="option5">10
                                <input type="radio" name="options" id="option6">30
                                <input type="radio" name="options" id="option7">60
                                <input type="radio" name="options" id="option8">90

                            Mês final:

                                <select class="form-control" id="sel1">
                                    <option>Dezembro</option>
                                    <option>Dezembro</option>
                                    <option>Janeiro</option>
                                    <option>Julho</option>
                                </select>

                                <select class="form-control" id="sel1">
                                    <option>2016</option>
                                    <option>2015</option>
                                    <option>2014</option>
                                    <option>2013</option>
                                </select>

                            Data Final:

                                <input type="date" class="form-control" name="bday">

                            Intervalos:

                                <select class="form-control" id="sel1">
                                    <option>0</option>
                                    <option>1</option>
                                </select>
                                <select class="form-control" id="sel1">
                                    <option>0</option>
                                    <option>1</option>
                                </select>
                                <select class="form-control" id="sel1">
                                    <option>0</option>
                                    <option>1</option>
                                </select>
                                <select class="form-control" id="sel1">
                                    <option>0</option>
                                    <option>1</option>
                                </select>
                                <select class="form-control" id="sel1">
                                    <option>0</option>
                                    <option>1</option>
                                </select>

                            Formatação:

                                <select class="form-control" id="sel1">
                                    <option>Porcentagem</option>
                                    <option>Percentil</option>
                                    <option>Média</option>
                                </select>

                            Veículo:

                                <select class="form-control" id="sel1">
                                    <option>Locomotiva</option>
                                    <option>Trem</option>
                                </select>

                        Posto:

                                <select class="form-control" id="sel1">
                                    <option>Azul</option>
                                    <option>Vermelho</option>
                                    <option>Verde</option>
                                    <option>Branco</option>
                                </select>

                        <button type="submit" class="btn btn-default">Consultar</button>

            </form>

Comment: However, notice that you are not setting a good layout in Bootstrap.
Comment: I just ran your snippet and it remained the same. Did you modify something? Why it is not a good layout?
Comment: I added a `row-final` id and its functionality.
Comment: You are not using `.row`s as well as [Bootstrap's documentation](http://getbootstrap.com/css/#grid-intro) remarks.
Comment: Hum, I think I could use columns and rows freely. `row-final` doesn't helped me because do the same as `buscar-mes-final`.
Comment: It is not true: `row-final` and `buscar-mes-final` do not make the same.
Answer: Here is a codepen
Add this code to CSS styles
.space {
  margin-top: 35px;
}

and this JS code
$('#buscar-mes-formatacao').addClass('space');

to (it is 44 code row) $('#f-option3').on('click', function()
And do not forget to remove class space from option 1 and 2 by adding
$('#buscar-mes-formatacao').removeClass('space');

respectively to $('#f-option1') and $('#f-option2')
This may be not the best option, but it solves the problem
Comment: You did great. In fact, that solution solves the problem. But like Miquel Al. Vicens said, I need to see the Bootstrap documentation with more attention and write again this grid.


python re match string in a file

Question: I want to match all the lines in a file either starting with 0D and has 15 Characters or just having 15 digits. How  can i do this
p_number = re.compile(r'(\d{15})')
f=open(infile)
for l in f:
  aa=re.findall(p_number,l)
  if aa > 0:
     print aa
f.close()

EDIT
If only the pattern is in the starting of the line.
Comment: re.findall returns a list, so comparing it to 0 is meaningless. What is your error?
Answer: To find matches only at the beginning of the line, use re.match. This regex matches all non-whitespace characters if the 0D prefix is present; if you want to match fewer characters, let me know.
>>> p_number = re.compile(r'(0D[\S]{13}|\d{15})')
>>> for s in ['0Dfannawhoopowe foo',
              'foo 012345678901234',
              '012345678901234 foo']:
...     match = p_number.match(s)
...     if match:
...         print match.groups()
...
('0Dfannawhoopowe',)
('012345678901234',)

For a sense of the difference between match, search, and findall, see the following examples.
findall (naturally) finds all occurrences of the match:
>>> for s in ['0Dfannawhoopowe foo',
              'foo 012345678901234',
              '012345678901234 foo']:
...     match = p_number.findall(s)
...     if match:
...         print match
...
['0Dfannawhoopowe']
['012345678901234']
['012345678901234']

search finds an occurrence of the string anywhere in the string, not just at the beginning.
>>> for s in ['0Dfannawhoopowe foo',
              'foo 012345678901234',
              '012345678901234 foo']:
...     match = p_number.search(s)
...     if match:
...         print match.groups()
...
('0Dfannawhoopowe',)
('012345678901234',)
('012345678901234',)

Comment: I am not able to match the following 0D57000000FFrsy
Comment: You shouldn't be able to match that. It doesn't contain 15 digits. You said "either starting with 0D and has 15 digits or just having 15 digits," which I interpreted to mean strings like this: `0Dddddddddddddddd` or like this: `ddddddddddddddd`. The example in your comment is neither. Did I misunderstand something?
Answer: import re
with open(infile) as f:
 print re.findall('^(0D.{15}|\d{15})$',f.read(),re.MULTILINE)

Answer: If you want to do this with regular expressions, of course you can do it:
with open(infile) as f:
  for l in f:
     if re.match('(0D)?[0-9]{15}', l):
       print l

But you can solve the task without regular expressions at all:
with open(infile) as f:
  for l in f:
     if (len(l) == 15 and l.is_digit()) or (l[:2]='0D' and len(l)==17 and l[2:].is_digit()):
       print l

Comment: And how to check that the line should start with one such expression or else proceed to next line
Comment: @Levon: That's right; i didn't noted that condition; thank you!
Comment: @Rajeev: that makes `match` automatically
Comment: I am not able to match the following 0D57000000FFrsy
Comment: No need to reinvent the wheel with `only_digits`. `'15'.isdigit() == True`; `'15f'.isdigit() == False`.

python re match string in a file


Incorrect syntax in sql script

Question: not sure what I am doing wrong here.
SELECT DISTINCT
  managername,
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed
FROM (SELECT
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed,
  workbkname
FROM tbldb2midtierresponse
WHERE username IS NOT NULL
AND username <> 'User Name') a
INNER JOIN (SELECT DISTINCT
  managername,
  workbkname
FROM tbldb2midtierresponse
WHERE managername NOT IN ('Mid Tier', 'User Access Management', 'Reporting Manager')
AND managername IS NOT NULL) b

INNER JOIN (SELECT
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed,
  workbkname
FROM tbldb2midtierresponse
WHERE username IS NOT NULL
AND username <> 'User Name/ID Owner') c
  ON b.workbkname = c.workbkname

Error I am getting is  at the last line.
Please help where I am doing wrong is this script?
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'workbkname'.
Answer: Simplfied:
select *
from (select ...) a
inner join  (select ... ) b -- [!] missing on x.attr = b.attr statement
inner join (select ... ) c on b.workbkname = c.workbkname

You didn't join table b right (no common attribute specified)
Comment: OP is also missing table aliases for the outer select which will cause an ambiguous column error.
Comment: @user300485 OP = Original Post, at least that is what I read it as from all of the comments I am pretty new too
Answer: you need to add
a.workbkname = b.workbkname

select distinct managername, username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed
from
(select username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed,workbkname from tbldb2midtierresponse
where username is not null and username <> 'User Name' ) a
inner join
(select distinct managername ,workbkname from tbldb2midtierresponse where managername not in ('Mid Tier','User Access Management','Reporting Manager') and managername is not null ) b
on a.workbkname = b.workbkname
inner join
(select username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed,workbkname from tbldb2midtierresponse where username is not null and username <> 'User Name/ID Owner' ) c
on b.workbkname = c.workbkname

Comment: OP is also missing table aliases for the outer select which will cause an ambiguous column error
Answer: So you actually have a couple of issues.

Missing On Condition between table aliases a & b
Missing Table Aliases for what table to pull the columns from it will through an ambiguous column error
and lastly inner joins back to the same table may not be necessary.

In your code it appears that you are getting all users then joining to make sure the workbkname also has a manager that is not in Mid tier... and is not null.  Then joining to Get everyone else that works on work book....
I would guess you are actually trying to get all users that are not 'User Name' or 'User Name/ID Owner' that have a managername that is NOT IN ('Mid Tier','User Access Management','Reporting Manager').  If so I would do it as follows:
SELECT DISTINCT
    a.managername
    ,a.username
    ,a.UserStatus
    ,a.Usertitle
    ,a.Loginid
    ,a.Server
    ,a.DBName
    ,a.Response
    ,a.busjustify
    ,a.Comments
    ,a.dtaccessnoneed
FROM
    tbldb2midtierresponse a
    LEFT JOIN tbldb2midtierresponse m
    ON a.workbkname  = m.workbkname
    AND m.managername NOT IN ('Mid Tier','User Access Management','Reporting Manager')
    AND m.managername IS NOT NULL
WHERE
    username IS NOT NULL
    AND username NOT IN ('User Name','User Name/ID Owner')
    AND m.username IS NOT NULL

Incorrect syntax in sql script


Which statistical test should I use? Pre-post intervention comparisions and post-post comparisons

Question: In my experiment I compare the jump height of participants pre and post 2 separate interventions.
All participants completed baseline measures of jump height. Participants then underwent a training intervention followed by post test measurements. On a separate occasion the same participants completed a different intervention before post test measurements were taken.
I believe I should use paired t-tests to compare these groups as the same participants were tested pre and post. However, I also want to compare the post test scores from intervention 1 with the post test scores from intervention 2 (to see if there were significant differences between the two interventions).
Is there a test I should use to achieve this in one? Or do I use the paired t-tests for pre and post comparisons and a further test for the post-post comparison?
Thanks in advance!
Comment: I'm not clear on the experiment. All participants were exposed to the two interventions? So for the 'post-post' analysis you are comparing the difference between having just one intervention as opposed to the same people having both interventions.
Comment: I think a repeated measures ANOVA would be appropriate in your case. I'm make the assumption that @Simon asks about above, that all participants experienced both interventions.
Answer: Sorry, I'm new to the network.
I do not know which statistical program you use, I use SPSS.
If I understood correctly (I'm not native to the language) you have three measures of the same individuals.
If your data have a normal distribution, if there is homogeneity of variances and if the variances of the three measurements are not different (p> 0.05) you can use Anova for repeated measures.
Comment: This is a definite improvement, but you still should try to explain/justify your answer in more detail,  If you can, please edit


What are good sources for studying geometric control theory?

Question: I am studying geometric control theory, and I am focusing on the concepts of manifolds, Lie algebra and Lie brackets, distributions and the Frobenius theorem.
My problem is that I am having a lot of difficulties on undestanding the concepts. I have tried searching different sources, but I still don't have these concepts clear.
Can somebody provide me some material where these concepts are explained clearly?
Comment: The first pages of your book on geometric control should list the prerequisites.
Answer: There two-three standard books that everyone refers, which are:
(1) Agrachev, Sachkov, Control theory from geometric viewpoint.
(2) V.Jurdjevic, Geometric control theory.
(3) Jerzy Zabczyk, Mathematical Control theory.
But these are heavily mathematical which is not a surprise because the subject itself is. If you don't have any background on Topology, differential geometry then don't pick up the above books mentioned, as these books starts with compact lie groups and vector fields etc.

I am focusing on the concepts of manifolds, Lie algebra and Lie brackets, distributions and the Frobenius theorem

Keeping this in mind, i would suggest you to go through (1) $\textit{Introduction to topological manifolds}$ by John Lee, maybe chapter two and three, then (2)$\textit{ Introduction to smooth manifolds}$ by Lee where you'll find necessary background on  smooth structures, tangent space, vector bundles, Lie groups and Lie abgebra etc. Another good reference is Lafontaine's differential manifolds. There's two other books which i would also recommend
(4) Abraham, Marsden, Foundations of mechanics
(5) Darryl Holm, Geometric mechanics part I
You can also start with any of these two to build up the background on geometry, topology and lie groups. Compared to Marsden (which is considered as bible of geometric mechanics and control) Holm's book is quite readable and precise specially the lie group and algebra, matrix lie group section, and full of examples but his treatment of abstract manifold is restricted to submanifolds, i.e consider the unit sphere $\mathbb{S}^2$ which is itself a manifold irrespective of the ambient space it's embedded on, while Holm's always consider it as something which is embedded in $\mathbb{R}^3$ but it won't be a big issue. Anyway, learning all the basics first is a dead machine, so it's better to start somewhere at the middle, move upwards as enlarging your base as you go along. Good luck !
Answer: If you are new to manifolds, Lie brackets, and Frobenius, read something more intuitive to start with. Not everyone loves Applied Differential Geometry by Bill Burke but I do. Manifolds and Differential Geometry by Jeffrey Lee is a good book, as are the texts by John Lee mentioned above.
Milnor's books on Differential Topology and on Morse Theory are mathematical and quite nice. Or you may want to read about general relativity if you are inclined to learn some physics as a bonus in the process.
I fear that if you try to learn differential geometry from the control literature, your progress will be slow and intuition incomplete. But that's just a very personal opinion.
Answer: Geometric control theory is a study of a family of tangent vector fields on a manifold.  Therefore, the necessary background includes the concept of a manifold, tangent vector field, and tangent space.  Arnol'd's "Ordinary differential equations" will give you the basic background on manifolds, tangent spaces, Lie bracket, and on the study of one vector field on a manifold.  (The same author's "Mathematical methods of classical mechanics" gives a somewhat more comprehensive introduction to manifolds, the tangent bundle, and Lie groups.)
If you want an extremely thorough introduction to manifolds and tangent spaces, there is a chapter in the 2nd volume of Zorich's "Mathematical analysis", although he loves to use a lot of notation, so see if it's to your taste.
Once you have a solid grasp on the geometric theory of ODE (that's Arnol'd:), i.e., on the study of one tangent vector field on a manifold, I next recommend reading, not a book, but a paper: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.649.6659&rep=rep1&type=pdf  This paper should help you see the high-level picture of geometric control theory and gauge what material (and, hence, what sources on differential geometry and geometric control) would be best to go to next.


"The website encountered an unexpected error. Please try again later." error show on cache clear

Question: My Drupal 8 site is working fine but when I am clearing the cache then my site display below errors.

The website encountered an unexpected error. Please try again later.

Please suggest me what is the problem ?  I have checked status report and it shows the error below
Comment: Let us see the first_module routing file and the controller or we cannot help you. You may not have declared the namespace in your controller class file.
Comment: have you given the name of the controllers and file according to PSR that drupal 8 is using?
Comment: It would help to see the controller class in "first_module".
Answer: I was also getting the same error. The reason is given in the error message,i.e. Drupal is not able to find the specified controller. In my case, in the routing yml, the controller's path is "hello_world\Controller\HelloController", whereas my HelloController.php file was contained in the hello_world\src folder instead of the required path (**hello_world\src\Controller** folder).
My hello_world.routing.yml contents
<code>hello_world.content:
 path: '/hello'
defaults:
 _controller: '\Drupal\hello_world\Controller\HelloController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'
</code>
Answer: this work for me:

update script in settings.php i.e $settings['update_free_access'] = TRUE;
and then run { website url}/update.php

Note: After running update.php set 'update_free_access' to FALSE.


Understanding the Gaussianity Under Linear Transformations

Question: Problem
Time-series model:
$$\begin{align*}
x_{t+1} = Ax_t + w, w \sim N(0,Q) \newline
y_{t} = Cx_{t} + v, v \sim N(0, R)
\end{align*}$$
where $w,v$ are i.i.d. Guassian noise variable, assume that $p(x_0)= N (\mu_0, \Sigma_0)$, What is the form of $p(x_0,x_1,...,x_T)$?
The solution provided by author is :

The joint distribution is Gaussian: $p(x_0)$ is Gaussian, and $x_{t+1}$ is a linear/affine transformations of $x_t$. Since affine transformations leave the Gaussianity of the random variable invariant, the joint distribution must be Gaussian.

My question
I don't understand what doesn this means:"Since affine transformations leave the Gaussianity of the random variable invariant, the joint distribution must be Gaussian."

Can I think of joint distribution $p(x_0,x_1,...x_T)$ as green circle, and if we stretch it, the distribution still the same?
What is random variable invariant?
Comment: The correct understanding of your target sentence should be

> Affine transformations leave the **Gaussianity** [of the random variable] **invariant**.

So it is **Gaussianity** which remains **invariant**, NOT random variables.
Answer: Your questions touch the domain of discrete stochastic linear dynamical systems. (Partial) answer for your questions are:

A gaussian stochastic multivariable $z \in \mathcal{N}(\mu, \Sigma)$ has a mean vector $\mu \in \mathbb{R}^n$ and a positive covariance matrix $\Sigma \in \mathbb{R}^{n \times n}$, as you picture.
Although the variables $v$ and $w$ are stochastic, their models do not change along variables t i.e. invariant.

I try to predict your future questions: The solution for time series $x_{t+1}$ as you define is given by expression below:
$$x_t = A^t x_0 + \sum\limits_{i=0}^{t-1} A^i w$$
Comment: For 1. you mean:"Multivariate gaussian distribution"? Thus $p(x_1,x_2,...x_t)\sim \mathcal{N} (\mu, \Sigma) $?
Comment: If the distribution $p$ we mention is time series, it has mean vector $A^t \, x_0$ and a standard value equal to $E[w^\intercal \, B^\intercal B \, w]$.


Let $B_n = H_{n+1} \cap \dots \cap H_{n+ [\log_2\log_2 n]}$, $H_n$ probability $n$th coin heads. How are $\{B_n\}_n^\infty$ not independent?

Question: I think title is pretty self explanatory. Consider infinite fair coin tossing. Let $H_n$ be the the event that the $n^\text{th}$ coin comes up heads. Define
$$B_n = H_{n+1} \cap H_{n+2} \cap \dots \cap H_{n+ [\log_2\log_2 n]}$$
Why are the $B_n$ not independent of each other?
Also, related to this (and perhaps why I am misunderstanding), does it make sense to consider values of $n$ where $\log_2\log_2 n$ is not an integer? If so, how is this interpreted?
I mean, I think I get why: The $B_n$ overlap each other (to varying extents). But that the overlap is not apparent to me right now.
More specifically, $\log_2(\log_2 n)$ tends to be pretty small, even for large $n$. If we consider only values of $n$ where $\log_2(\log_2 n)$ is a whole number, the dependence of $\{ B_n\}$ is not obvious to me, because such values of $n$ seem to be very far apart (far enough to prevent overlap, I think?).
If we allow $\log_2(\log_2 n)$ to not be an integer, then I can see how the $B_n$ are not independent (because then we have $n+1, n+2,\dotsc, n+4$ for one value of $n$ and then $(n+1) +1 = n+2,\dotsc, (n+1) +4.xxxx$ for the next), but then I don't know how to interpret, for example, $H_{n+4.90689}$ (when $n=2^{30}$).
Thanks.
Comment: 1) The [] notation indicates some sort of rounding to an integer, possibly floor but it depends on whether you've transcribed it accurately, so $H_{n+[4.90689]}$ is really either $H_{n+4}$ or $H_{n+5}$.  2) It is immediately obvious from this interpretation that $B_n$ and $B_{n+1}$ overlap so long as $\log \log n$ is large enough to be $>1$.
Comment: @BCLC Yes, Rosenthal. $3.4$
Comment: Is this from Rosenthal? If not where?
Comment: @ErickWong I believe I transcribed it correctly, but perhaps not. Now that I think about it though, given that I'm looking at a pdf scan perhaps the character recognition changed the floor or ceiling notation to regular square brackets, $[$ and $]$. (In other words, perhaps I transcribed it correctly from an incorrect transcription...)
Answer: I'll assume the $H_n$'s are independent with $0 < P(H_n) = p < 1$
You can show the $B_n$'s are not independent by showing that they are not pairwise independent.
$$B_n = H_{n+1} \cap H_{n+2} \cap \cdots \cap H_{n+ [\log_2\log_2 n]}$$
$$B_{n+1} = H_{n+2} \cap H_{n+3} \cap \cdots \cap H_{n+1+ [\log_2\log_2 (n+1)]}$$
$$P(B_n) = p^{n+ [\log_2\log_2 n] - (n+1) + 1} = p^{[\log_2\log_2 n]}$$
$$P(B_{n+1}) = p^{n+1+ [\log_2\log_2 (n+1)] - (n+2) + 1} = p^{[\log_2\log_2 (n+1)]}$$
Now just show that
$$P(B_n, B_{n+1}) \ne p^{[\log_2\log_2 (n)]} p^{[\log_2\log_2 (n+1)]} $$
I believe that $\{B_n, B_{n+1}\} = H_{n+2} \cap \cdots \cap H_{n+ [\log_2\log_2 n]}$


Filtro e ordenação de tags usando JavaScript

Question: Preciso fazer um filtro usando JavaScript puro.
Porém ao fazer o filtro e ordenar por Nome (a, b), por exemplo, só consigo ordenar os elementos do texto fora do contexto e não o bloco completo.
Por exemplo:
Preciso que o bloco
 seja ordenado junto ao :

  C

  B

  A

O código que tenho é esse:

    window.onload=function(){
      var div = document.querySelector('#produto'),
      para = document.querySelectorAll('.item span.titulo');
      var paraArr = [].slice.call(para).sort(function (a, b) {
        return a.textContent > b.textContent ? 1 : -1;
      });
      paraArr.forEach(function (p) {
       div.appendChild(p);
  });
    }
 .item{
      display: block;
      border: 1px solid #DFDFDF;
      padding: 8px;
      margin: 8px;
    }
<!DOCTYPE html>

      C

      B

      A

Answer: "Ordenar" diretamente o html é mais complicado que gerar um novo com base em dados que tenha. E até acontece que no seu caso acaba a fazer appendChild para adicionar um elemento que já existe no local onde está a ser adicionado mas não como filho direto e sim como neto. Também não tem forma direta de ordenar um elemento e mover outro, no caso ordenar o titulo e levar o item, sem ser navegando no DOM. Para além disso, se a ordenação é para ser feita sobre textos então deve-se basear no localeCompare.
Mais simples seria ter um array com os titulos ou algo que represente a informação que tem de mostrar, e uma forma de gerar o html correspondente. Depois apenas precisa de ordenar o array e recriar o html.
Exemplo:

const titulos = ["B", "C", "A"];

window.onload = function() {
  const divProduto = document.getElementById("produto");

  //função que cria o html de cada titulo
  const htmlTitulo = (titulo) => {
    return `

              ${titulo}

`;
  };

  //função que constroi o html total do produto "mapeando" cada titulo
  //no seu html e juntando tudo para colar no div produto
  const mostrar = () => divProduto.innerHTML = titulos.map(htmlTitulo).join("");

  document.getElementById("crescente").addEventListener("click", () => {
    titulos.sort((a, b) => a.localeCompare(b)); //ordenação com localeCompare
    mostrar();
  });

  document.getElementById("decrescente").addEventListener("click", () => {
    titulos.sort((a, b) => b.localeCompare(a)); //ordenação com localeCompare
    mostrar();
  });

  mostrar(); //quando carrega inicialmente também mostra
}
.item {
  display: block;
  border: 1px solid #DFDFDF;
  padding: 8px;
  margin: 8px;
}
<!DOCTYPE html>

  <button id="crescente">Crescente</button>
  <button id="decrescente">Decrescente</button>

Comment: Obrigada :D
realmente criar os elementos acaba se tornando mais fácil


How to parse offset with colon using DateTimeFormatter?

Question: I have the following string: String timeStamp = "2020-01-31 12:13:14 +03:00".
And I tried to parse it using Java 8 DateTimeFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format );
tmpTimestamp = ZonedDateTime.parse( timeStamp, formatter );

where format is one of:
"yyyy-MM-dd' 'HH:mm:ss' 'Z",
"yyyy-MM-dd' 'HH:mm:ss' 'X",
"yyyy-MM-dd' 'HH:mm:ss' 'x",
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd HH:mm:ss X",
"yyyy-MM-dd HH:mm:ss x",

None is working. Always I got DateTimeParseException either pointing to '+' or to ':' character in offset substring "+03:00"
According to JavaDocs: Class DateTimeFormatter "+03:00" shall be supported by any of: Z, X and x.
So the question is how to construct formatter string to parse it?
Comment: @MS90 - not `LocalDateTime`, but rather `OffsetDateTime` (since it has an offset).
Answer: From the javadoc

Offset Z: This formats the offset based on the number of pattern
  letters. One, two or three letters outputs the hour and minute,
  without a colon, such as '+0130'. The output will be '+0000' when the
  offset is zero. Four letters outputs the full form of localized
  offset, equivalent to four letters of Offset-O. The output will be the
  corresponding localized offset text if the offset is zero. Five
  letters outputs the hour, minute, with optional second if non-zero,
  with colon. It outputs 'Z' if the offset is zero. Six or more letters
  throws IllegalArgumentException.

You need 5 Z's
String format = "yyyy-MM-dd HH:mm:ss ZZZZZ";

Demo
Answer: You should use the times X (yyyy-MM-dd HH:mm:ss XXX):
String timeStamp = "2020-01-31 12:13:14 +03:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
ZonedDateTime tmpTimestamp = ZonedDateTime.parse(timeStamp, formatter);

From the docs:

Offset X and x: This formats the offset based on the number of pattern letters.
One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'.
Two letters outputs the hour and minute, without a colon, such as '+0130'.
Three letters outputs the hour and minute, with a colon, such as '+01:30'.
Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
Six or more letters throws IllegalArgumentException.
Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

Alternative you can use five letters (XXXXX) and you also can use ZZZ or ZZZZZ instead of XXX or XXXXX.
Answer: You don't need to fiddle with a format pattern string.
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_DATE)
            .appendLiteral(' ')
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .appendLiteral(' ')
            .appendOffsetId()
            .toFormatter();
    String timeStampString = "2020-01-31 12:13:14 +03:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(timeStampString, formatter);
    System.out.println(dateTime);

It's wordier, but harder to get wrong. I'm just assembling the formatter from built-in parts. Output is:

2020-01-31T12:13:14+03:00

I am also parsing into an OffsetDateTime instead of a ZonedDateTime. Since the string contains an offset (+03:00) and no time zone (such as America/Boa_Vista), even though it would probably work with a ZonedDateTime, OffsetDateTime is the correct class to use.


Como fazer o ORDER BY DESC funcionar no MySQL?

Question: Estou tentando fazer uma consulta na minha tabela usando o OREDER BY DESC, mesmo usando a sintaxe correta recebo o erro: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY IDADE DESC' at line 5".
A tabela que estou usando como exemplo é essa:
CREATE TABLE PESSOA
    (`nome` varchar(8), `idade` int, `estado_nascimento` varchar(2))
;

INSERT INTO PESSOA
    (`nome`, `idade`, `estado_nascimento`)
VALUES
    ('joao', 12, 'sp'),
    ('maria', 26, 'rj'),
    ('joao', 15, 'mg'),
    ('fernanda', 30, 'ce')
;

E a consulta que estou fazendo é essa:
SELECT NOME
FROM PESSOA
WHERE ESTADO_NASCIMENTO NOT IN ('CE')
LIMIT 1
ORDER BY IDADE DESC;

Segue o link do SQL Fiddle com a tabela e a consulta para maior comodidade: http://sqlfiddle.com/#!9/caf268/1
Alguém saberia dizer o que estou errando?
P.S.: Estou usando MySQL 5.6
Comment: Tem que excluir essa pergunta?
Answer: É necessário que mova o "LIMIT 1" para o final da query.
Segue um exemplo do W3 School :
https://www.w3schools.com/sql/trymysql.asp?filename=trysql_select_limit
SQL:
SELECT NOME FROM PESSOA WHERE ESTADO_NASCIMENTO NOT IN ('CE') ORDER BY IDADE DESC LIMIT 1;

segue o link com o resultado da query:
http://sqlfiddle.com/#!9/caf268/4


What are the corresponding fields to set in libtiff or libgeotiff, given a minimal ESRI ASCII file?

Question: I have an ESRI ASCII file of the form:
ncols         5
nrows         4
xllcorner     0
yllcorner     0
cellsize      10
NODATA_value  -9999
25.4 26.1 27 28.6 27.7
25 26 26.4 27.9 27.4
25.1 25.8 26.8 28.6 27.6
27.5 28 27.7 30.6 28.3

And I need to use libtiff.net ( or its C++ equivalent, libtiff, or libgeotiff, or GDAL, or any other C# or C++ libraries) to convert it to a geotiff file.
But I simply don't know what are the fields to set, there are a lot of fields such as TIFFTAG_IMAGEWIDTH, TIFFTAG_SAMPLESPERPIXEL or TIFFTAG_BITSPERSAMPLE which I don't know whether they are relevant or not.
Given an ESRI ASCII file as per above, how to use the libtiff.net or libtiff library to create a geotiff file?
Why am I doing this?
In my application, I have a mesh, and I would have to convert the mesh to a raster file. I want to create such a geotiff raster file directly from the mesh sampling, without creating an intermediate ASCII file first because the intermediate file size is very big compared to the final geotiff output file.
The only approach I can think of is to directly manipulate the geotiff file using  libtiff.net while I am obtaining the grid points on the mesh.
How to do this, or is there a better approach?
Answer: Even if you are planning not to use GDAL in your application (more on that later), nothing prevents you from generating a geotiff from the ESRI ASCII GRID (gdal_translate -of "GTiff" in.asc out.tif), and inspect the TIFF tags of the generated file (these are the necessary tags to generate a geotiff from the given grid).
AsTiffTagViewer gives the following output (similar to TiffTags utility output):
TagCode (Count DataType): Value  // my comments

ImageWidth (1 Short): 5    // ncols
ImageLength (1 Short): 4   // nrows
BitsPerSample (1 Short): 32
Compression (1 Short): Uncompressed
Photometric (1 Short): MinIsBlack
StripOffsets (1 Long): 260
SamplesPerPixel (1 Short): 1
RowsPerStrip (1 Short): 4    //nrows
StripByteCounts (1 Long): 80
PlanarConfig (1 Short): Contig
SampleFormat (1 Short): 3
33550 (3 Double):
33922 (6 Double):
42113 (6 ASCII): -9999    // NODATA_value

As you can see there are 11 standard Tiff tags and 3 non standard tags (but we know the Data Types and more importantly the dimensions of that last 3 tags, 3,6,6). Let's confirm we have 2 GeoTiff tags and one non standard GDAL-specific tag.
Libgeotiff C library is distributed with listgeo utility for dumping GeoTIFF metadata. The output:
Geotiff_Information:
   Version: 1
   Key_Revision: 1.0
   Tagged_Information:
      ModelTiepointTag (2,3):
         0                0                0
         0                40               0
      ModelPixelScaleTag (1,3):
         10               10               0
      End_Of_Tags.
   Keyed_Information:
      End_Of_Keys.
   End_Of_Geotiff.

Corner Coordinates:
Upper Left    (       0.000,      40.000)
Lower Left    (       0.000,       0.000)
Upper Right   (      50.000,      40.000)
Lower Right   (      50.000,       0.000)
Center        (      25.000,      20.000)

By the dimensions of the Tagged_Information we can identify the following 2 tags. Also, since the grid is regular (equal X and Y spacing, and there are no skewed grid lines) we can establish the following formulas:
33550 tag:
ModelPixelScaleTag = [ cellsize , cellsize , 0 ]

33922 tag:
ModelTiepointTag = [ 0 , 0 , 0 , UpperLeftCorner_X , UpperLeftCorner_Y , 0]

    where
            UpperLeftCorner_X = xllcorner

            UpperLeftCorner_Y = yllcorner + cellsize * nrows

That leaves the last tag 42113. The geotiff format does not have a standard tag for a nodata value. GDAL stores band nodata value in the non standard TIFFTAG_GDAL_NODATA ASCII tag (code 42113).
Finally, as an example, we can write a function that relates the header of the grid (ncols, nrows, cellsize, xllcorner, yllcorner) with the Tiff tags, using Libgeotiff C library:
void SetUpTIFFDirectory(TIFF *tif)
{
    double tiepoints[6];
    double pixscale[3];

    double upperLeftCorner_X, upperLeftCorner_Y;

    upperLeftCorner_X = xllcorner;

    upperLeftCorner_Y = yllcorner + (cellsize*nrows);

    tiepoint[0] = 0.0;
    tiepoint[1] = 0.0;
    tiepoint[2] = 0.0;
    tiepoint[3] = upperLeftCorner_X;
    tiepoint[4] = upperLeftCorner_Y;
    tiepoint[5] = 0.0;

    pixscale[0] = cellsize;
    pixscale[1] = cellsize;
    pixscale[2] = 0.0;

    TIFFSetField(tif,TIFFTAG_IMAGEWIDTH,    ncols);
    TIFFSetField(tif,TIFFTAG_IMAGELENGTH,   nrows);
    TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE, 32);
    TIFFSetField(tif,TIFFTAG_COMPRESSION,   COMPRESSION_NONE);
    TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,   PHOTOMETRIC_MINISBLACK);
    TIFFSetField(tif,TIFFTAG_STRIPOFFSETS,  260L);
    TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL, 1);
    TIFFSetField(tif,TIFFTAG_ROWSPERSTRIP, nrows;
    TIFFSetField(tif,TIFFTAG_STRIPBYTECOUNTS, 80L);
    TIFFSetField(tif,TIFFTAG_PLANARCONFIG,  PLANARCONFIG_CONTIG);
    TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,  3;

    TIFFSetField(tif,GTIFF_TIEPOINTS, 6,tiepoints);
    TIFFSetField(tif,GTIFF_PIXELSCALE, 3,pixscale);

}

Note: When you say you can't use GDAL, there's an In Memory Raster format that can probably be used as a temporary placeholder for you raster while you are adding mesh samples:
Link
Comment: Hi, I am unsure why I wrote the "can't use GDAL"-- Actually I can, I am platform agnostic. I can use GDAL after all. You want to include an example of how to sue GDAL to do the job?
Comment: GDAL documentation can be very cryptic sometimes. I normally take a look at the automated tests suite to get a feeling how things work. For the Memory driver: https://svn.osgeo.org/gdal/trunk/autotest/gdrivers/mem.py
Comment: I see. In your above sample for geotiff, you only show how to write the meta-data, but what about writing the _values_ of the cell? can show a full example?
Answer: Actually this task can be easily done by using GDAL library ( or its .Net equivalent, GDAL.Net). There is even an example here in Python:
ncols         174
nrows         115
xllcorner     14.97
yllcorner     -34.54
cellsize      0.11

And the Python script:
if __name__ == '__main__':
# Import libs
import numpy, os
from osgeo import osr, gdal

# Set file vars
output_file = "out.tif"

# Create gtif
driver = gdal.GetDriverByName("GTiff")
dst_ds = driver.Create(output_file, 174, 115, 1, gdal.GDT_Byte )
raster = numpy.zeros( (174, 115) )

# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
dst_ds.SetGeoTransform( [ 14.97, 0.11, 0, -34.54, 0, 0.11 ] )

# set the reference info
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS("WGS84")
dst_ds.SetProjection( srs.ExportToWkt() )

# write the band
dst_ds.GetRasterBand(1).WriteArray(raster)

Converting the code to .Net should be trivial enough.


How to prove that $m+(4/m^2)>=0$ for every m greater or equal to 0

Question: I have a problem with proving this simple theorem. I've already figured out that the best strategy is to factorise is, so that to get eg. a square or another expression that from the definition has to be non-negative, but have no idea how exactly should I do it. Could you help me guys?
Comment: For $m=0$: $\dfrac{4}{m^2}$ doesn't exist.
Comment: You know that $m\ge0$, and $m^2>0$ (assuming $m\ne0$), so $\frac{4}{m^2}>0$ also. Thus $m+\frac{4}{m^2}>0$ for $m>0$.
Comment: If the right side of your inequality should be $3$ you should **immediately** edit your question's title to ask the correct question. Otherwise you are wasting the time of people who are trying to help you. Also note Vladimir's comment that your statement cannot be true for $m=0$, so you should edit your restriction on $m$.
Comment: Maybe prove $m^3 + 4 \geq 0$ instead?
Comment: Thanks! Actually, how to deal with $m+(4/m^2)>=3$ for every m >= 0 ? Of course I multiplied it by $m^2$ and got $m^3+4-3m^2>=0$ and have no idea how to proceed
Comment: @applicant, no it was just remarked that you can't take $m = 0$.
Comment: Is the problem supposed to read "Prove that $$m + \frac{4}{m^2} \geq 3$$ for every $m \geq 0$"?
Comment: I see you have modified the question and re-posted it. Remember to "accept" the answer here that helped you the most. You have not accepted an answer yet--if you don't start you may not get many more answers.
Answer: Let $m > 0$. Then we have that:
$$m^3 >0$$
which implies that:
$$m^3 + 4 > 0 $$
dividing both sides by $m^2$ you get:
$$m + \frac{4}{m^2} > 0$$
and you are done (for the case where $m=0$ you are dividing by 0).
Answer: Consider the following, if I have a positive real number and I add a positive real number to it, the result will be a positive real number (Closure under addition). Furthermore, if I take a positive real number and divide by a positive real number, the result will be a positive real number (Closure under multiplication). Also, if I square a real number it will be a positive real number (Closure under multiplication). Given those statements, you have m a positive real number plus 4/m^2 which is a positive number because it is the quotient of two positive numbers. Thus the result must be positive.
Answer: Apparently you needed to prove it for $m + (4/m^2) \ge 3$, given $m > 0$.
Multiply by $m^2$.
Take derivative: $3m^2 - 6m$, and check that there is a local top in $m = 0$ and local minimum at $m = 2$.
Given the positive sign of the $m^3$ term, you can plot the graph.
Fill in $m = 2$, to check that equality occurs, but it is a local minimum on $R^+$
Answer: By applying AM-GM inequality on $$\frac{m}{2},\frac{m}{2},\frac{4}{m^2}$$
We get
$$\frac{\frac{m}{2}+\frac{m}{2}+\frac{4}{m^2}}{3}\ge \sqrt[3]{\frac{m}{2}\cdot\frac{m}{2}\cdot\frac{4}{m^2}}$$
$$\frac{m}{2}+\frac{m}{2}+\frac{4}{m^2} \ge 3$$
$$\Rightarrow m+\frac{4}{m^2} \gt 0$$


Statistics and probability

Question: How can I  choose which to use permutation or combination to solve a given statistical problem in maths.
Eg. In how many ways can the letters of word: "ARRANGE" be arranged? How many of these arrangements are there in which
a) the two R's together
b)the two R's and two A's come together
Comment: If you do a search on this website for "ARRANGE" you'll find lots of questions like this
Comment: @MartinHansen thankyou martin the answer is correct ,but my basic question is if there is a way to decide methods from permutation and combination when solving such problems just by looking
Comment: I've added an explanation - hope it makes sense.
Answer: The answer to the first question is $\frac {7!} {2! \cdot 2!} = 1260$ and the answer to $(a)$ is $\frac {6!} {2!} = 360$ and answer to $(b)$ is $5! = 120.$
Comment: Although correct, it helps to explain why each number was chosen and the thought process on how to approach the problem.
Answer: Part b) is easier so I'll do that first.
Imagine you have 5 cards on which is written
$$ aa : rr : n : g : e$$
You are going to place these cards is a line on a table,
There are 5 possible cards you could place first, then four second, three third, two fourth and then what ever card is left in your hand goes down last.
So that's, $$5 \times 4 \times 3 \times 2 \ 1 = 5! = 120$$
With part a) you have 6 cards on which is written
$$ a : a : rr : n : g : e$$
So repeating the argument above there are 6! ways of placing the cards.
There is a catch however which is the two 'a' cards that look the same.
So you can't tell the difference between, for example,
$$n \implies a_1 \implies rr \implies g \implies a_2 \implies e$$
and
$$n \implies a_2 \implies rr \implies g \implies a_1 \implies e$$
so the 6! needs dividing by 2!, i.e. 2, giving an answer of 360
Hope that helps !

Statistics and probability


Empirical probability and Dirac distribution

Question: According to Deep Learning p.65(Ian Goodfellow and Yoshua Bengio and Aaron Courville, available online):

(...) This can be accomplished by defining PDF using the Dirac delta
  function $\delta(x)$: $$p(x)=\delta(x-\mu)$$
(...) By defining $p(x)$ to be $\delta$ shifted by $\mu$ we obtain
  infinitely narrow and infinitely high peak of probability mass where
  $x=\mu$. A common use of Dirac delta distribution is as a component of
  an empirical distribution,
  $$\widehat{p}(x)=\frac{1}{m}\sum_{i=1}^{m}\delta\left(x-x^{(i)}\right)$$(where
  $x^{(i)}$ are our data empirical datapoints).

My questions are:
1) Can we think of $\widehat{p}(x)$ as a kernel density estimator with the kernel $K()$ defined as the Dirac function at zero?
2) How can we calculate the mean of Dirac function?
3) What is the intuition behind the above empirical probability distribution $\widehat{p}(x)$?
4) If $x=x^{(i)}$ then $\widehat{p}\left(x=x^{(i)}\right)=+\infty$?
Comment: (1) and (3) are answered at http://stats.stackexchange.com/questions/73623.  (2) is trivial: when all the probability is assigned to the value $\mu$, the mean obviously is $\mu$.  (4) expresses the intuition given in the question, but is not mathematically correct: $\delta$ is actually a probability *measure*.  It does not really have a PDF.
Comment: @Xi'an When I wrote the first comment I figured somebody might come along with that correction--but I was hoping they wouldn't. :-)
Comment: The Dirac delta does have an interpretation, either as a measure or a generalized function.  But attempts to interpret it as a probability density are risky, because they can lead to mathematically invalid conclusions.
Comment: So generally we can say that dirac function and dirac PDF  is a ''concept'' used to define derivative of empirical cummulative density function, without interpretation itself?
Comment: Minor correction: A Dirac measure $\delta_{x_0}$ has a density against any measure that puts positive mass on $x_0$. Therefore, the density of $\hat{p}$ against the counting measure on the set $\{x^ {(1)},\ldots,x^ {(n)}\}$ exists and is $1/n$ at each of the $x^ {(i)}$' s and zero elsewhere.
Answer: As noted by whuber your question was answered to the great extent in his answer to another question on similar topic.

1) Can we think of $\widehat{p}(x)$ as a kernel density estimator with
  the kernel $K()$ defined as the Dirac function at zero?

If you have some kernel $K$ parametrized with bandwidth $h$, then as $h \to 0$ your kernel becomes Dirac delta. This is basically one of the intuitions behind Dirac delta as also described on Wikipedia.

2) How can we calculate the mean of Dirac function?

It accumulates all probability mass at $\mu$ and is zero elsewhere, so from the definition of expected value is $\mu$.

3) What is the intuition behind the above empirical probability
  distribution $\widehat{p}(x)$?

It's a discrete distribution, you assume that your variable can take only the values as observed in your sample (i.e. $x$'s), with probabilities equal to empirical probabilities. If your data is not discrete, then only empirical cumulative distribution function makes sense as an approximation of the true distribution. This is why histograms and kernel density estimators were developed, so that we can approximate the concinnous density function using empirical data.

4) If $x=x^{(i)}$ then $\widehat{p}\left(x=x^{(i)}\right)=+\infty$?

Dirac delta is not a function and is not infinite as $x^{(i)}$. This is just a heuristic about it, that is meant to provide an intuitive understanding of what it is, but if it was infinite, it would be useless. If you want to learn more, check Role of Dirac function in particle filters thread, where it is discussed in greater detail.
If you want intuitive understanding of it, then think of a $m$ distributions, where each of them integrates to unity and has the same probability density mass at $x^{(i)}$'s. You create a mixture of those distributions, each appearing with equal mixing proportion $1/m$. So whatever was the probability density mass at $x^{(i)}$'s, first you divide it by $m$, then multiply by $m$ (there was $m$ $\delta$'s), so in total you need to end up with same total mass equal to unity, and mass for each of the $x^{(i)}$ points would be $m$ times smaller then initially. Probability densities for $x^{(i)}$'s are huge since the area under each of the points is infinitesimally small (see Can a probability distribution value exceeding 1 be OK? to learn more about probability densities). It gets abstract and dirty, but the take-away message is that it is just a trick to use calculus with discrete values. If you stay at discrete-only reality, then basically each of the $x^{(i)}$ points has mass equal to $1/m$ so that in total their mass sums to unity by the axioms of probability.
Comment: +1.  Concerning (4), it seems one really could argue that $\hat p(x^{(i)})=\infty$ in a well-defined sense. One way is to take the limit of approximate probability densities $$\frac{1}{\mu(\mathcal{R})}\int_\mathcal{R} \hat p(x)dx$$ for a net of measurable neighborhoods of $x^{(i)}$ converging to $x$, each with Lebesgue measure $\mu(\mathcal{R})$. By definition of the Dirac delta, all of those integrals equal $1$, whence (since $\mu(\mathcal{R})\to 0$) those probability densities eventually exceed any integer $N$: that is, they converge to $+\infty$ in the extended Reals.


AEM: How to dynamically get the current page path and pass it to the request parameter for drop down

Question: options=/bin/services/myservlet.GET_DROPDOWN_VALUES.json?locale='some_locale'
if I put locale=en-us it works fine,
How can I dynamically get the current page locale and pass it to the request parameter ?
Answer: So, your servlet requires locale as one of the parameters to retrieve dropdown values. I can think of 2 options to do this.

Invoke the servlet with $Path as one of the parameters. $Path will give you the complete page path, all the way till jcr:content. options=/bin/services/myservlet.GET_DROPDOWN_VALUES.json?compNode=$PATH.

In your servlet, construct page object using $PATH, then as @jwepurchase mentioned, get the locale using page.getLanguage(false).
String compNodePath = (String) request.getParameter("compNode");
String pagePath = StringUtils.substringBefore(compNodePath, "jcr:content");
PageManager pageMgr = request.getResourceResolver().adaptTo(PageManager.class);
Page page = pageMgr.getContainingPage(pagePath);
Locale pageLocale = page.getLanguage(false);

getLanguage will look for jcr:language property in currentpage or its ancestors. This property gets set when you set the Language field in page properties (advanced  tab) of your page(usually set in the root locale page) to an appropriate value. eg: If you set the language to english(us), jcr:language will be en_us.

Similar steps as option 1, if value in page property is not set, you can use currentPage.getAbsoluteParent(DEPTH_VAL) to retrieve the locale value. Not a recommended soln though.
Answer: com.day.cq.wcm.api.Page.getLanguage(false) will return the value of the jcr:language property on the page or the first parent page where it is sent. Generally this isn't set on every page.
If you have included Adobe's global.jsp or used the <cq:defineObjects/> tag in your JSP, you should find that "currentPage" is already in scope, providing access to a Page object.
I generally have a custom taglib function to make it easier to access via EL. But as a scriptlet I expect the following would work:
<%= ((Page)getPageContext().getAttribute("currentPage")).getLanguage(false)%>
Comment: I guess you understood the OP's question wrong. The query was how to dynamically pass the locale to the servlet which provides the options for selection widget in the dialog.


Limit $\lim \limits_{x\to -\infty }\frac{\sqrt{16x^{2}+2x-3} }{x+9}$

Question: Given $$\lim \limits_{x\to -\infty }\frac{\sqrt{16x^{2}+2x-3} }{x+9} $$
Hi,  I need help for proof this limit, which could be used arguments or results. I would appreciate any suggestions. I Don't use l'Hopital rule.
Comment: Divide numerator and denominator by $x$ and see if you can simplify and then evaluate the limit.
Comment: HINT:  The equivalent of the square root term is $4|x|$ while the equivalent of $x+9$ is $x$.
Answer: $$\lim _{ x\to -\infty  } \frac { \sqrt { 16x^{ 2 }+2x-3 }  }{ x+9 } =\lim _{ x\to -\infty  } \frac { \left| x \right| \sqrt { 16+\frac { 2 }{ x } -\frac { 3 }{ { x }^{ 2 } }  }  }{ x\left( 1+\frac { 9 }{ x }  \right)  } =\lim _{ x\to -\infty  } \frac { -x\sqrt { 16+\frac { 2 }{ x } -\frac { 3 }{ { x }^{ 2 } }  }  }{ x\left( 1+\frac { 9 }{ x }  \right)  } =-4$$
Answer: As some have mentioned in the comments to your question. The key strategy is to divide numerator and denominator by $x$:
$$
\lim_{x\to -\infty}\frac{\sqrt{16x^{2}+2x-3}}{x+9} = \lim_{x\to -\infty}\frac{\sqrt{x^2(16+2/x-3/x^2)}}{x+9} = \lim_{x\to -\infty}\frac{\lvert x\rvert\sqrt{16+2/x-3/x^2}}{x+9} \\
= -\lim_{x\to -\infty}\frac{\sqrt{16+2/x-3/x^2}}{1+9/x}.
$$
Can you see what happens in the limit as $x \to -\infty$?
Answer: I suggest first simplify the denominator by changing of variable $t = x + 9$, then the numerator becomes
$$\sqrt{16(t - 9)^2 + 2(t - 9) - 3} = \sqrt{16t^2 - 286t + 1275}.$$
Hence the limit to be evaluated is
\begin{align*}
\lim_{t \to -\infty} \frac{\sqrt{16t^2 - 286t + 1275}}{t} =
-\lim_{t \to -\infty} \sqrt{16 - \frac{286}{t} + \frac{1275}{t^2}} = -4.
\end{align*}


Integrate $x^ {1/2}e^{-x}$ using integration by parts

Question: How to integrate $x^{1/2}e^{-x}$ using integration by parts?
Answer should be $\left(-\sqrt{x} e^{-x}+(1/2)\sqrt{\pi} \mbox{erf}(\sqrt{x})\right)+c$
Comment: You can figure out what u and v were chosen from the first term of the answer, since you know what that is.  That should get you closer.
Answer: I am not familiar with using e.r.f but i shall tell you the procedure. Take $u= \sqrt{x}$ and $dv = e^{-x}$. So you have $du = \frac{1}{2 \cdot \sqrt{x}} \ \rm{dx}$ and $v = -e^{-x}$. Now using the integration formula we have,
\begin{align*}
 \int \sqrt{x} e^{-x} \ \textrm{dx} &= \Bigl[ u \cdot v ] - \int v \cdot \ \textrm{du} \\ & = \Bigl [ -\sqrt{x} \cdot e^{-x}\Bigr] + \frac{1}{2} \int \frac{e^{-x}}{\sqrt{x}} \ \textrm{dx}
\end{align*}
Comment: http://en.wikipedia.org/wiki/Error_function
Comment: I just wanted to point out what $\operatorname{erf}$ means and that it is common.
Comment: @Theo: Ok. Theo no problem.
Comment: If you have following \begin{align*}
 \int \sqrt{x} e^{-x} \ \textrm{dx} &= \Bigl[ u \cdot v ] - \int v \cdot \ \textrm{du} \\\ & = \Bigl [ -\sqrt{x} \cdot e^{-x}\Bigr] + \frac{1}{2} \int \frac{e^{-x}}{\sqrt{x}} \ \textrm{dx}
\end{align*} How you get erf(\sqrt(x)) from there without substitutions
Answer: In the comment:

How you get erf(\sqrt(x)) from there without substitutions

If you leave the $1/2$ in the integral and do the most obvious substitution (recall your first step?), you will get something that should look like the definition of the function in @t.b.'s link.


Spring security remember-me with customAuthenticationProvider

Question: I'm using CustomAuthentication provider to authenticate which extends AbstractUserDetailsAuthenticationProvider. This I had to do because I wanted to authenticate against a webservice and needed both userid as well as password. This was the only class which allowed me to do so.
Now I'm facing issues implementing remember-me functionality for this, here is my security-context file -
<http auto-config="true">
    <intercept-url pattern="/j_spring_security_check" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/dashboard*" access="ROLE_USER" />
    <form-login login-page="/login.html" default-target-url="/dashboard1.html#meetings"
        authentication-failure-url="/loginFailed.html" />
    <logout logout-success-url="/login.html" />
</http>

<beans:bean name="customAuthenticationProvider" class = "com.component.WebServiceUserDetailsAuthenticationProvider"/>

<authentication-manager>
  <authentication-provider ref = "customAuthenticationProvider"/>
</authentication-manager>

</beans:beans>

Now I'm trying to implement remember me, but it's enforcing me to have user detail service that I can't have as I need both username and password to authenticate agains my web service and method exposed by userdetailservice gives only username not password and that's the reason I had to use customAuthentication at first place.
Comment: You haven't actually said what your issues are so you should probably edit your question to clarify. Also, you don't need to extend `AbstractUserDetailsAuthenticationProvider`. You can just implement the `AuthenticationProvider` interface directly.
Comment: Hi Luke, I've completed my question now. And AbstractUserDeta..... I used because I wanted to provide implementation only for method authenticate and that's what abstractUs.. is for.
Answer: Remember-me is an alternative way of authenticating a user, so when it receives a remember-me cookie it needs to validate it and load information for the user to provide it to the application. To do that it uses the UserDetailsService interface.
The basic implementation TokenBasedRememberMeServices needs access to the password in order to verify the token. If your system can't provide that, then you can't use it.
The alternative is PersistentTokenBasedRememberMeServices, which uses a database to store the remember-me tokens. It doesn't need access to the password, but you will still need to implement a UserDetailsService to allow it to load information for the authenticated user. The UserDetails object it returns doesn't need to contain a password, but it should contain the username as a minimum so that you can tell who is logged in.


How to replacement collect match word?

Question: I want change perfect match one word.
Only "x" change to "x1"
Using gsub(), however, all words include "x" change.
How can I do?
temp=c("x", "xx", "xxx")
gsub("x", "x1", temp)
("x1", "x1x1", "x1x1x1")
# I want below product
("x1", "xx", "xxx")

Answer: You could add ^ and $ at start and end of the string respectively
sub("^x$", "x1", temp)
#[1] "x1"  "xx"  "xxx"

but since this is an exact match why not use == for comparison?
temp[temp == "x"] <- "x1"

Comment: Thank you. I use ^, $. and "==" is don't know. but, i learn to new one. thanks again.

How to replacement collect match word?


How to copy few files from one folder to another folder in php and delete them in source folder

Question: How to copy files from one folder to another folder in php and delete them in source folder ?
I have two folder $incoming_file_path = /home/xmlcontainer and $processing_file_path = home/process_file. I am looping through all files in $incoming_file_path  = home/xmlcontainer and than copying it into $processing_file_path = home/process_file.
After executing below code I am not able to copy the content of files but just the name of the files also am not able to delete files which I have copies to destination folder from source folder using unlink, I am surely using unlink in wrong way and would certainly appreciate any guidance on it.
Code
foreach( glob($incoming_file_path.'/*')as $key => $value ) {
    copy($incoming_file_path.$value,$processing_file_path.$value);
    unlink($incoming_file_path.$value);
    }

Comment: +1 because ur question I resolved by big issue
Answer: First of all, just use rename if you intend to move the files.
Your loop should look like this:
foreach (glob($incoming_file_path . '/*') as $value) {
  rename($value, $processing_file_path . '/' . basename($value))
}

Inability to read file contents and/or delete a file is often a simple permissions problem. Check if the owner of your PHP process can read and write to both $incoming_file_path and $processing_file_path. You may want to run chmod -R u+rwx (or chmod -R o+rwx) on both $incoming_file_path and $processing_file_path.


How to switch the selected values between two select elements

Question: How can I switch the selected values of 2 select html elements that contain the same information.
The current scenario is the following: select the language to translate from and then to translate to.
To make it easier for the user, I want to offer the possibility to switch the source language to the target language and vice versa.
A simplified version of the HTML markup is the following one:
<select name="LangA">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="sv">Swedish</option>
    <option value="tr">Turkish</option>
    <option value="uk">Ukrainian</option>
</select>

<select name="LangB">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="sv">Swedish</option>
    <option value="tr">Turkish</option>
    <option value="uk">Ukrainian</option>
</select>

The languages are the same for both select elements. The feature I am trying to implement is very similar to google translations switch languages arrow.
The reason is that the boxes are for a translation textarea. The entire code is much bigger with much more languages, I only took out what is needed for the sake of keeping it short.
Comment: Assign each element to a variable. Then use `.attr()` to change the `name` attribute of each of them.
Comment: Is not the HTML ```` codes, code script? Now it is in more detail. I did not put JavaScript cause I do not even know were to begin in this case. I know how to switch places with each other, but not how to switch names with each other.
If I knew that i would not ask, would I?
Comment: SeekLoad, you have been given the answer already by @Barmar. I personally am more interested in the why, as that might show the real problem, and not what you try to do
Comment: @Barmar's answer is the 5th comment. Here above!
Comment: SeekLoad, its in this comment series. You were the only one talking about that other question. Anyhow, I posted an answer in plain javascript that should do the trick
Comment: AndyTurner why did I get a "-" for the question?
Comment: What have you tried? Nothing should stop you from assigning the hardcoded names just like that. For the question for the downvote, read the arrow down, it mentions clearly why people should downvote or not (no research effort, not usefull or unclear)
Comment: It is not unclear, but the question is complicated. I edited it a bit now, you down voted just 2 seconds after i posted it, I did not even have time to take a look at it and edit it a bit.
Comment: There is no script shown in your question. Showing nothing but requirements looks like a free code request. - Then, what would be the trigger to switch the names... A button? a `change` event? Your best attempt to achieve it would show something about it.
Comment: Its okay to down vote, but not after 2 seconds of posting it. Now it is more clear telling you exactly what I mean.
Comment: You still haven't shown what you tried. We're not here to do your coding for you, but we'll help you fix your code.
Comment: SeekLoad, you also could have posted a good question at once. Your question also rather seems to be an XY problem, why would you want to change the names of the elements, what reason do you have? What will happen with the selects afterwards, maybe there is another way we can solve the problem you are having. And no, html options is markup, not script
Comment: Okay how can I explain it the best way. If you have who we say ```` boxes. One is named A and the other B. How do you make A to switch name to B and B to switch name to A?
Comment: okay I will put the reason on. the reason is that the boxes are for a translation textarea. The entire code is much bigger with much more languages. Anyway the translation needs to be able to switch direction without changing the option chosen. Example as the arrows in Google Translate https://translate.google.com/#es/en/test
Comment: I will add that to the question above
Comment: I'm pretty sure that just changing the `name` attributes is not a solution for this. You should show how the languages are selected to trigger the translation function.
Comment: I never got an answer for this by @Barmar. Show me were I did get that answer?
Comment: i got an answer here https://stackoverflow.com/questions/44981212/how-to-swap-places-left-to-right-of-a-few-option-not-all-of-them-from-within/44981827#44981827 by @Osama BUT that is to another question of swapping pieces of the boxes, not the names.
Comment: So you mean to switch the places of the options WITHOUT swapping the places of the select boxes themselves. I thought of that too, but I never got how to do so, I only got how to swap places of the entire boxes.
Comment: There is ONLY ONE comment on https://stackoverflow.com/questions/44981212/how-to-swap-places-left-to-right-of-a-few-option-not-all-of-them-from-within/44981827#44981827
So were is this @Bramer you talk off? You must confuse me with somebody else or with another post I put about something else.
Comment: @Icepickle You made my day, you are the only one who understood the question. I chated about this yesterday before posting it as a question today. That is why I got so frustrated that nobody understood the question although we have a webpage online who is a perfect example.
Comment: @Icepickle Thank you for the salvation now. You down voted me and you saved me this time. the other guys talking about that I had the answer before from somebody. I do not even know what he was talking about, since this was the first time I posted this question. I only chated before with another guy were I did not show codes in the chat.
Comment: SeekLoad, can I edit your question so that it becomes more clear to potential future readers of this question what you would like to ask? Maybe it can help you formulate your questions better in the future? (I cannot promise that you wouldn't get more downvotes though)
Comment: @SeekLoad "Is not the HTML  codes, code script?" No, it isn't. Your question is about how to write the Javascript that modifies the HTML, so you should have shown your attempted Javascript code. You say that you didn't even know where to begin, so I gave a hint in my comment. Even a beginning programmer should have been able to use that to get started, but you've shown no initiative on your own, you just want someone else to write it for you.
Answer: Assuming you have the same languages in both, you could simply change the selection from one box to the other. This script will read the current selected value on both select dropdowns, and then search the option in the other one when you click on swap.
If the languages are really on the same place, the easiest option I can think of would be this:
function swapBySelectedIndex( selector1, selector2 ) {
  // get both elements and save the selectedIndex of the first element
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = elem1.selectedIndex;

  // set the first element to the second elements selectedIndex
  elem1.selectedIndex = elem2.selectedIndex;
  // set the second elements' selectedIndex to the saved index
  elem2.selectedIndex = selectedOption1;
}

function getSelectedOption( elem ) {
  return elem.options[elem.selectedIndex].value;
}

function setSelectedOption( elem, value ) {
  for (let i = 0; i < elem.options.length; i++) {
    elem.options[i].selected = value === elem.options[i].value;
  }
}

function swapByOptionValue( selector1, selector2 ) {
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = getSelectedOption( elem1 ),
      selectedOption2 = getSelectedOption( elem2 );
  setSelectedOption( elem1, selectedOption2 );
  setSelectedOption( elem2, selectedOption1 );
}

function swapBySelectedIndex( selector1, selector2 ) {
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = elem1.selectedIndex;

  elem1.selectedIndex = elem2.selectedIndex;
  elem2.selectedIndex = selectedOption1;
}
<select name="LangA">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="sv">Swedish</option>
<option value="tr">Turkish</option>
<option value="uk">Ukrainian</option>
</select>

<select name="LangB">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="sv">Swedish</option>
<option value="tr">Turkish</option>
<option value="uk">Ukrainian</option>
</select>

<button type="button" onClick="swapByOptionValue('select[name=\'LangA\']', 'select[name=\'LangB\']')">Swap selected languages</button>

<button type="button" onClick="swapBySelectedIndex('select[name=\'LangA\']', 'select[name=\'LangB\']')">Swap selected languages (using selectedIndex)</button>


Retrieve number of replies to a comment

Question: I have the following PostgreSQL table to store comments on different posts:
Comment table:
commentID | parentID | postID | content | author | created
I want now to retrieve with a single Query, given a postID, all comments to the post AND the number of replies each comment has. A comment is a reply if the parentID is not null and equals then the commentID of its parent.
I tried something like the following where I join the table on its self and look for the matches of parentID = commentID but I could not get it working and would appreciate some help :)
SELECT comments.commentID as commentID, comments.parentID as parentID, comments.postID as postID,
comments.content as content, comments.author as author, comments.created as created,
COALESCE(c1.numReplies, 0) as numReplies
FROM comments c0
LEFT JOIN (
    SELECT parentID, COUNT(*) FILTER (WHERE postID = :givenPostID) as numReplies as numReplies
    FROM comments
) c1 on c0.commentID = c1.parentID
WHERE c0.postID = :givenPostID;

Answer: This looks like a good spot for a subquery, or a lateral join:
select c.*, c1.no_replies
from comments c
cross join lateral (
    select count(*) no_replies
    from comments c1
    where c1.parentid = c.commentid
) c1
where c.postid = :givenpostid

Side note - the query you wanted to write probably is:
SELECT c0.*, COALESCE(c1.numReplies, 0) as numReplies
FROM comments c0
LEFT JOIN (
    SELECT parentID, COUNT(*) as numReplies
    FROM comments
    GROUP BY parentID
) c1 on c0.commentID = c1.parentID
WHERE c0.postID = :givenPostID

The subquery is slightly different: first, it needs a GROUP BY clause just to be valid SQL; and also, there is no need for a conditional count.

Retrieve number of replies to a comment


How to detect an android phone contacts app supports Structured Postal Address?

Question: Samsung galaxy S4 and some devices are only supporting Structured postal while using Intent Action_Insert
ArrayList<ContentValues> data = new ArrayList<ContentValues>();
...
ContentValues name = new ContentValues();
name.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
name.put(StructuredPostal.STREET, bundle.getString(StructuredPostal.STREET));
name.put(StructuredPostal.CITY, bundle.getString(StructuredPostal.CITY));
name.put(StructuredPostal.REGION, bundle.getString(StructuredPostal.REGION));
name.put(StructuredPostal.NEIGHBORHOOD, bundle.getString(StructuredPostal.NEIGHBORHOOD));
name.put(StructuredPostal.POSTCODE, bundle.getString(StructuredPostal.POSTCODE));
name.put(StructuredPostal.COUNTRY, bundle.getString(StructuredPostal.COUNTRY));
data.add(name);
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(ContactsContract.Intents.Insert.NAME, contactName);

if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB)
  intent.putParcelableArrayListExtra(Insert.DATA, data);
else
  intent.putExtra(ContactsContract.Intents.Insert.POSTAL, address);

Now for Galaxy S3 which runs on 4.2 doesn't support Structured Address and not showing the address using the above code.
So How do I find if a device supports structured postal address so that I can provide support for both?
Note: If I use intent.putExtra(ContactsContract.Intents.Insert.POSTAL, address); Galaxy S3 shows the address where as while using intent.putParcelableArrayListExtra(Insert.DATA, data); this S3 not able to show the address.
Answer: Try saving both the structured fields as you do (for phones that support them) as well as the StructuredPostal.FORMATTED_ADDRESS. You'll need to do the formatting yourself, though. That's what VCardEntry does, it seems.


Doubt with rank nullity theorem when nullity equals to zero.

Question: $V$ and $W$ are vector spaces.
$T:V\rightarrow W$ is a linear transformation
$V = \mathbb R^3 = (x,y,z)$ , dimension = 3.
$W = \mathbb R^2 = (x,y)$, dimension = 2.
$T(x,y,z) = (x,y)$
The basis of the nullity  is ${ (0,0,0) }$ (right?).
Then its dimension is 0.
The rank nullity theorem says:
$rank(T) + null(T) = dim (V)$.
so...
$rank(T) + 0 = 3$
$rank(T) = 3.$
Well, I know there is some thing wrong here. How can rank(T) = 3 if dim(W) = 2 ?
Thank you for helping!
Comment: Is $(0,0,0)$ ever the basis for *anything*? No, it is not. The empty space has dimension zero, not one. In any event, the nullity is not dimension zero here. What is $T(0,0,1)$?
Answer: The map you are describing is $T:\Bbb R^3\to\Bbb R^2$ defined by $T(x,y,z)=(x,y)$. A vector $(x,y,z)$ is in the kernel of $T$ if and only if $x=y=0$. Hence every vector in the kernel of $T$ is of the form $$(0,0,z)=z\cdot(0,0,1)$$
That is,
$$
\ker T=\operatorname{Span}\{(0,0,1)\}
$$
so $\dim\ker T=1$. Clearly $T$ is surjective so $$\operatorname{rank}T=\dim\operatorname{image}T=\dim\Bbb R^2=2$$
Thus
$$
\operatorname{rank}T+\dim\ker T=2+1=3
$$
and the Rank-Nullity theorem survives!


A Simple function identity

Question: Show the following identity,
$$
\int_{\mathbb R^d}|\nabla(\frac{f}{G})|^2\,G\,dx=\int_{\mathbb R^d} |\nabla f|^2\,G^{-1} \,dx \,-\,\int_{\mathbb R^d} f^2(\Delta \Phi) \, G^{-1} dx
$$
Here,
$G(x)=(2\pi)^{d/2}e^{-|x|^2/2}$,
$\Phi(x)=-log(G(x))=|x|^2/2+log(2\pi)^{d/2}$
(See that $\Delta \Phi =d$)
$f$ is a compactly supported smooth function and $\int_{\mathbb R^d}f=0$.
I can get the first term in R.H.S. but second term is not coming. I cannot even see where do I use conditions on $f$ as the rest terms involve $f^2$ and $\nabla f^2$.
Please help,
Regards,
Harish
Answer: $$
\int | \nabla (f/G) |^2 G = \int \left| G^{-1} \nabla f - G^{-2} f \nabla G \right|^2 G \\
= \int \left( |\nabla f |^2 G^{-1} - 2 (f \nabla f) \cdot (G^{-1}\nabla G) G^{-1} + f^2 |G^{-1}\nabla G|^2 G^{-1} \right) \\
= \int \left( |\nabla f |^2 G^{-1} + \left[ \nabla(f^2) \cdot (\nabla (-\log{G})) + f^2 |\nabla(-\log{G})|^2 \right] G^{-1} \right)
$$
Note also the following identity on functions:
$$
\nabla \cdot ( f^2 \nabla(-\log{G}) G^{-1} ) = \nabla(f^2) \cdot \nabla(-\log{G}) G^{-1} + f^2 \Delta(-\log{G})G^{-1} + f^2 \nabla(-\log{G}) \cdot \nabla(G^{-1}) \\
= \nabla(f^2) \cdot \nabla(-\log{G}) G^{-1} + f^2 \Delta(-\log{G})G^{-1} + f^2 \nabla(-\log{G}) \cdot(-\nabla G) G^{-2} \\
= \nabla(f^2) \cdot \nabla(-\log{G}) G^{-1} + f^2 \Delta(-\log{G})G^{-1} + f^2 \nabla(-\log{G}) \cdot \nabla(-\log{G})G^{-1}
$$
Integrating this identity over $\mathbb{R}^d$, the left-hand side vanishes because $f$ is continuous with compact support, and then it is easy to see that substituting the resulting identity between integrals into the previous equation gives the requested result. (So in fact, the identity is considerably more general than your special case: any $G>0$ bounded below on compact sets will do, and $\int f$ is also not used.)

A Simple function identity


In Python, how do I use a dictionary to translate an RNA sequence to a protein sequence?

Question: I'm able to import an RNA sequence (eg. AUGCCGACCCGCAGUCCCAGCG) and define a dictionary for translating it into a protein sequence (eg. AUG = M, CCG = Q, ACC = T). Every 3 letters of RNA sequence codes for one letter of protein sequence, and this translation is defined in the dictionary. How do I get Python to read the RNA sequence and output the protein sequence?
I've tried this code:
for i in range(0, len(rna_sequence), 3):
    codon_dictionary = codon_dictionary + rna_sequence[i:i+3]

When I run it, nothing happens. No error message.
Edit: I forgot to add that I want the program to print the resulting protein sequence. I think RNA_sequence is defined as a string.
Comment: When I copy/paste this code and run it, I get an error because `codon_dictionary` is undefined. Please provide a [mcve] for us to help you.
Comment: Also, what do you expect to happen when you run your code? Do you include any `print()` statements? If not, you won't have any output to see the result.
Comment: `protein = ''.join([codon_dictionary[rna_sequence[i:i+3]] for i in range(0, len(rna_sequence), 3)])`
Comment: Before this part of the code runs, what is `rna_sequence`? What is `codon_dictionary`? Most importantly, **exactly how** do you want the program to communicate a result? Should `codon_dictionary` change when the code runs? Should a new value be created? If there should be a new value, what name should it have? Then, think carefully about the logic, step by step. What should the result be if there is nothing in the `rna_sequence`? When a value from the `rna_sequence` is "translated", what should happen to the result value?
Answer: Pass RNA codons as keys to the dictionary to access needed amino acids, save all amino acids iteratively in a list and then you can join the list into a string to get a string sequence.
protein_sequence = []
for i in range(0, len(rna_sequence), 3):
    protein_sequence.append(codon_dictionary[rna_sequence[i:i+3]])
print(''.join(protein_sequence))


Janela WPF não ultrapassar a tela

Question: Tenho o seguinte código:

    System.Windows.Point ponto = PointToScreen(Mouse.GetPosition(this));

    JanelaAbrir.Left = ponto.X;
    JanelaAbrir.Top = ponto.Y;

    JanelaAbrir.ShowDialog();

Ele abre a Janela na posição do mouse, porém essa janela pode ultrapassar os limites do monitor, como posso fazer para ela não ultrapassar os limites?
Para ilustrar melhor segue uma imagem:

Ao abrir a janela ultrapassa a borda, limite da tela(monitor), impedindo que o usuário veja a janela completa, obrigando a arrastar.
Answer: Uma hipótese é, nesse caso, as coordenadas do rato não definirem o canto superior esquerdo da janela mas o canto superior direito.
O mesmos se pode fazer caso a janela não caiba verticalmente, em vez de definirem o canto superior esquerdo definem o canto inferior esquerdo.
Caso as duas situações se verifiquem será considerado o canto inferior direito.
<code>int x = coordenada x do rato;
int y = coordenada y do rato;
int maxX = largura da tela;
int maxY = altura da tela;
int largura = largura da janela;
int altura = altura da janela;

if(x + largura > maxX) JanelaAbrir.Left = x - Largura;
else JanelaAbrir.Left = x;
if(y + altura > maxY) JanelaAbrir.Top = y - altura;
else JanelaAbrir.Top = y;
</code>
Isto é válido se as dimensões da janela forem menores que a metade das dimensões da tela e que a origem das coordenadas está no canto superior esquerdo da tela.
Comment: Beleza, descobri o erro, em vez usar `JanelaAbrir.Left`, tava usando `this.Left`, corrigi e não deu mais o erro. Obrigado!
Comment: Funciono, mais o menos, pois tem hora que abre, e as vezes a janela fica atrás, da principal, toda branca...
Comment: Isso é causado por outra coisa. Este código apenas define as coordenadas do canto superior esquerda da janela.

Janela WPF não ultrapassar a tela


One step delay while using ShouldComponentUpdate()

Question: In my ReactJS project i have a Table and filters for it. I got JSON file using axious from Django REST host. So i have a class for my main Table:
class MainTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      results: [],
      count: 0
    };
  }

  shouldComponentUpdate(nextProps) {
    console.log(this.props.link + " : " + nextProps.link);
    return JSON.stringify(this.props.link) !== JSON.stringify(nextProps.link);
  }

  render() {
    axios.get(this.props.link)
      .then(res => {
        this.setState({results: res.data.results});
        this.setState({count: res.data.count});
    });
    return (

           We got {this.state.count} elements in our database.

                Name
                Name

              {this.state.results.map(result =>

                  {result.name}
                  {result.name}

              )}

    );
  }
}

But when i run my app, i got one step delay in it, here is log :
"http://184.108.40.206:8000/database/?limit=10& : http://22.214.171.124:8000/database/?limit=10&" bundle.js:53418:7
./src/App.js
"http://220.127.116.11:8000/database/?limit=10& : http://188.8.131.52:8000/database/?limit=10&ORIGIN=dcseltc3&"  bundle.js:53418:7
"http://126.96.36.199:8000/database/?limit=10&ORIGIN=dcseltc3& : http://126.96.36.199:8000/database/?limit=10&ORIGIN=dcseltc3&" bundle.js:53418:7
"http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcseltc3& : http://22.214.171.124:8000/database/?limit=10&ORIGIN=dcseltcall&"  bundle.js:53418:7
"http://184.108.40.206:8000/database/?limit=10&ORIGIN=dcseltcall& : http://184.108.40.206:8000/database/?limit=10&ORIGIN=dcseltcall&" bundle.js:53418:7
"http://18.104.22.168:8000/database/?limit=10&ORIGIN=dcseltcall& : http://22.214.171.124:8000/database/?limit=10&ORIGIN=dcrsutc&"  bundle.js:53418:7
"http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcrsutc& : http://126.96.36.199:8000/database/?limit=10&ORIGIN=dcrsutc&" bundle.js:53418:7
"http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcrsutc& : http://18.104.22.168:8000/database/?limit=10&ORIGIN=dcseltc3&"  bundle.js:53418:7
"http://18.104.22.168:8000/database/?limit=10&ORIGIN=dcseltc3& : http://188.8.131.52:8000/database/?limit=10&ORIGIN=dcseltc3&" bundle.js:53418:7
"http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcseltc3& : http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcseltcall&"  bundle.js:53418:7
"http://188.8.131.52:8000/database/?limit=10&ORIGIN=dcseltcall& : http://126.96.36.199:8000/database/?limit=10&ORIGIN=dcseltcall&" bundle.js:53418:7
"http://184.108.40.206:8000/database/?limit=10&ORIGIN=dcseltcall& : http://220.127.116.11:8000/database/?limit=10&ORIGIN=dcseltc3&"  bundle.js:53418:7
"http://18.104.22.168:8000/database/?limit=10&ORIGIN=dcseltc3& : http://188.8.131.52:8000/database/?limit=10&ORIGIN=dcseltc3&"

It makes data check twice and rerun my render only after next checking. Maybe i did something wrong. I'm new with ReactJS and I think it should be easy answer for it.
Comment: You shouldnt be setting state in the middle of a render.
The axios request should be in an action and the data should be populated via Redux/mobx/flux or which state manager you choose.
If you do not want to do it, You can fetch your data in componentWillMount/componentDidMount and then set the state there.
Comment: Even without state manager, api call and new setState should be made in componentDidMount step. It is considered bad practice in componentWillMount : https://facebook.github.io/react/docs/react-component.html#componentdidmount
Comment: If i will put my `axios` in `render()` without `shouldComponentUpdate`  it will hit my host a few times per second, so I wanted to change it. If i use `componentDidMount()`, my `MainTable` doesn't refresh with new data after I sent new props to it.
Answer: Render is always called after a new state instance is set, so it should refresh with the new data if you put your setState in the componentDidMount(). And setState only once.
class MainTable extends React.Component {
...
componentDidMount() {
    axios.get(this.props.link)
      .then(res => {
        this.setState({results: res.data.results, count: res.data.count});
    });
}
componentWillReceiveProps(nextProps) {
    axios.get(nextProps.link)
      .then(res => {
        this.setState({results: res.data.results, count: res.data.count});
    });
}
...
render() {
 return ...
}

Comment: But it still load my Table only once. When i change my link with filters, my `Table` is load with the same start data. In my Main i use just `` and link is an object i change with my filters to make request for `REST` data.
Comment: Well you didn't really mention it in your post, have a look at componentWillReceiveProps, it is called every time a new props is pass to the component, i'll edit my post : https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
Comment: No problem, have a deep look at this page : https://facebook.github.io/react/docs/react-component.html  It handle most problem you may face using react
Comment: Sorry, will be more precise in the future posts. Ty for answer.