Preventing ajax call with some form validation

Question: I have a working javascript funciton with an ajax call, and the post call works perfectly upon button submission.
I just am trying to add in some validation but even when input is invalid it still submits ajax and refreshes the page.
All I'm trying to do here is make sure the number fields are only numeric and that all required fields are not empty, but if I test it with empty input, or put 'ONE' in one of the fields that expects numbers (as opposed to '1') it still calls ajax, which inserts the record, and then refreshes the page. SHould I be doing my if statements using the ID of each input field instead of my already set variables for the input 'name'?
<code>$("#save").click(function(e){

    e.preventDefault();

    var name = $("input[name=name]").val();
    var IDNumber = $("input[name=IDNumber]").val();
    var IDName2 = $("input[name=IDName2]").val();
    var IDNumber2 = $("input[name=IDNumber2]").val();
    var Number3 = $("input[name=Number3]").val();
    var ExtraName = $("input[name=ExtraName]").val();
    var category = $("input[name=category]").val();

    if(isNaN(IDNumber) || isNaN(IDNumber2) || isNaN(Number3)){
        alert('Fields must be numeric');
    }else if(name == '' ||
            IDNumber == '' ||
            IDName2 == '' ||
            IDNumber2 == '' ||
            Number3 == '' ||
            ExtraName == '' ||
            category == '')
    {
        alert('You must fill out all required fields';)
    }else{

        //perform the working ajax
    }
}
</code>
Comment: Will using the required, and type=number attributes on the input field work in the browser you are coding for? [See this for reference.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) Also, instead of .click, add a .submit to the form element instead.
Comment: just to clarify, the alerts shows but the ajaxs perform, or no alerts shows ?
Comment: Can you log all values to console, and see what's wrong?
Comment: Sorry, to clarify: The alerts do not currently show
Comment: Yeah there's something wrong with your if condition, log all values to console and see what's wrong
Comment: Yeah they log with the input that I'm typing in there
Comment: What does your html look like
Comment: Try this: give your input an id (EX: ) then use var IDNumber = $('#IDNumber').val();
Comment: Open the browser JS debugger and put a breakpoint on the first "if" line `if(isNaN(IDNumber) ...`. Is that breakpoint hit? Inspect the values of all the vars you'd set `var name =...` in the debugger; are they what you expect (empty)? In the debugger console type simply `$("input[name=IDNumber]")` - the console output should be a jQuery element object which you can inspect. Are the `$` selectors getting the actual elements you expect? As @acaputo said, show us (some of) the actual HTML this is executing on.
Answer: The semicolon is inside the alert method for the missing required fields. Try it again and see if it works! And it is much better if it is a submit event instead of just a click. And assuming your selector is for the button, selector should be on the form not on the button.
<code>$("#save").submit(function(e){ /* Should be a submit event */

    e.preventDefault();

    var name = $("input[name=name]").val();
    var IDNumber = $("input[name=IDNumber]").val();
    var IDName2 = $("input[name=IDName2]").val();
    var IDNumber2 = $("input[name=IDNumber2]").val();
    var Number3 = $("input[name=Number3]").val();
    var ExtraName = $("input[name=ExtraName]").val();
    var category = $("input[name=category]").val();

   if(isNaN(IDNumber) || isNaN(IDNumber2) || isNaN(Number3)) {
        alert('Fields must be numeric');
    } else if(name == ''|| IDNumber == '' || IDName2 == '' || IDNumber2 == '' || Number3 == '' || ExtraName == '' || category == '') {
        alert('You must fill out all required fields'); /* Put semicolon outside */
   } else {
        /* AJAX CODE HERE */
   }
}); /* another syntax error right here */
</code>


How many 5-digit whole numbers with no 0's are divisible by 6?

Question: How many 5-digit whole numbers with no 0s are divisible by 6?
I've tried different methods to approach this question but still cannot get to the answer.
Comment: The last digit must be 2,4,6 or 8 and the sum of the digits must be a multiple of 3. Can't you go from there?
Comment: I've thought of that already but it becomes long and convoluted. And also depending on the combination of the first four digits, the number of possibilities of the last digit varies. So i have no idea how to go about that approach without writing out all combinations of the first 4 digits
Comment: Welcome to MathSE.  When you pose a question here, you should include your attempt and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering.  You should do so in the question itself rather than the comments, where it might be missed.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: Pick the first three digits arbitrarily (from 1-9). That is $9^3$ possible choices.
Suppose the digit sum of those three digits is a multiple of 3. If we pick the fourth digit as $1,4,7$, then the last digit must be 2 or 8. If we pick the fourth digit as $2,5,8$ then the last digit must be 4. If we pick the fourth digit as $3,6,9$ then the last digit must be 6. So 12 choices for the last pair.
Suppose the digit sum of the first three is a multiple of 3 plus 1. If the fourth digit is $1,4,7$, then the last digit must be 4. If the fourth digit is $2,4,8$ then the last digit must be 6. If the fourth digit is $3,6,9$, then the last digit must be $2,8$. Again 12 choices.
Similarly if the digit sum of the first three is a multiple of 3 plus one, we again get 12 choices: fourth digit $1,4,7$ must be followed by 4; $2,5,8$ must be followed by 6; $3,6,9$ must be followed by $2,8$.
So total $12\cdot9^3$.
Comment: Thank you !! That's so smart. I wonder how you thought of that because under exam conditions i would never be able to think of such a way to organised the method in such a relatively straightforward way


Oracle logoff trigger to get sql's executed by session

Question: I have created a table which contains the host names of all the trusted sources. I have written a oracle log off trigger to fetch details of all the sql executed by that session if the connection's host is not amongst the snif_session table. I am taking the output to a utl_file output which contains the sid, hostname, time connected.
SQL> select * from snif_Session;

ALLOWED_HOST
--------------------------------------------------
RND1
WORKGROUP\RND1

The place where i am getting stuck is what query to use to get all the sql's executed by that particular session ( i can get the sid from v$mystat).
does this work best :
select a.sql_id
         ,b.sql_text
from dba_hist_active_sess_history a
        ,dba_hist_sqltext b
where a.sql_id=b.sql_id

or
select s.sid
         , s.serial#
         , a.sql_text
from v$session s
    join v$sqlarea a
            on a.hash_value = s.sql_hash_value ;

This is the code i have written (block) which i will be placing inside a trigger.
declare
    machine_id varchar2(50);
    val int;
    auth_terminal varchar2(50);
    check_machine varchar2(1000);
    mydate char(50);
    osuser_1 varchar2(50);
    sid_1 int;
    sql_query_1 varchar2(5000);
    machine_1 varchar2(50);
    trace_info UTL_FILE.FILE_TYPE;
begin
    select machine into check_machine
    from v$session
    where sid in (select distinct(sid) from v$mystat) ;
    select count(*) into val
    from snif_session
    where allowed_host=check_machine;
    if ( 1=val) then
        dbms_output.put_line(check_machine|| ' dont check host' );
    else
        dbms_output.put_line(check_machine || ' check host' );
    end if;
    select osuser,sid,machine
    into osuser_1,sid_1,machine_1
    from v$session
    where sid in (select distinct(sid) from v$mystat);
    SELECT TO_char(systimestamp,'mm/dd/yyyy HH24:MI:SS') into mydate
    FROM DUAL;
    dbms_output.put_line(mydate || sid_1 || '   ' || osuser_1 || '  '|| machine_1);
    trace_info := UTL_FILE.FOPEN('UTL_DIR', 'trace_info_file.txt', 'W');
    UTL_FILE.PUTF(trace_info,mydate||'  '||sid_1||'     '||osuser_1||'  '|| machine_1);
    UTL_FILE.FCLOSE(trace_info);
EXCEPTION
    WHEN utl_file.invalid_path THEN
       raise_application_error(-20000, 'ERROR: Invalid PATH FOR file.');
end;

I need to include the 'sql queries' also executed by session in the utl_file output.
Comment: What is the problem that you're trying to solve?  My guess is that you really want to use auditing rather than writing a trigger.  AWR will not have every statement that a session executed.  At best, v$active_session_history will have any SQL statement that happened to be active at the top of a second and that has not been purged from the buffer yet.  That is unlikely to be every SQL statement that a session executed particularly for long-running sessions.
Comment: But what is the underlying business problem?  As I've said, it sounds like you're trying to audit SQL statements.  If so, you should be using auditing.  If you want every SQL statement, you want auditing.  If you really just want a sample of the SQL statements, AWR is at least theoretically an option.  Not knowing what problem you're trying to solve, it's difficult to know how to help you.
Comment: I need to include the 'sql queries' also executed by session in the utl_file output
Comment: Im tyring to log the sql queris executed by the session before the log off. using auditing would be an expensive process.
Comment: Define "expensive"?  Querying the AWR is time-consuming.  Auditing generally doesn't add that much overhead.  More importantly, though, what problem are you trying to solve?  Auditing can log every SQL statement.  Querying the AWR tables cannot.
Comment: The problem here is want to check the sql queries performed by session coming from host which are not a part of the snif_Session table ( only the trusted sources hostnames are a part of this table)
Answer:
"I need to include the 'sql queries' also executed by session"

Neither of your suggested queries will give you all the SQL executed by a session.
V$SESSION is a dynamic view, so it just shows what is happening in a session right now.
DBA_HIST_ACTIVE_SESS_HISTORY is a series of snapshots of running SQL.  It is intended for performance profiling, and as such it is basically a random sub-set of active statements.  Also, it is part of the Diagnostics and Tuning Pack: you will be in breach of your license if you use it without paying the additional charge.
It appears that what you really need is an audit trail.  Instead of rolling your own, why not investigate the functionality Oracle already has?  There's AUDIT to track DDL activity.  There's Fine-grained Auditing to monitor lower-level DML.  Find out more.


Midpoint of a segment

Question: Let ABC be a triangle, I and J are two points such that : $\overrightarrow{AI}=\frac {2}{3}\overrightarrow {AB}$ and $\overrightarrow{AC}=\frac {1}{2}\overrightarrow {AJ}$.
(BC) and (IJ) intersect in O.
Show that O is the midpoint of  the segment [BC].
Comment: Hello, welcome to MSE. Can you please include your own attempts in the question? Questions that do not show that you made an effort on your own are generally poorly received here.
Answer: HINT
We have that

line $IJ:\quad P(t)=AI+t(AJ-AI)$
line $BC:\quad Q(s)=AB+s(AC-AB)$

then equate $P(t)=Q(s)$ and use that ${AI}=\frac {2}{3} {AB}$ and ${AC}=\frac {1}{2} {AJ}$ to find the intersection point $O$. Finally check that $O$ is the midpoint of $BC$.
Comment: Thank you sir for your help

Midpoint of a segment


Angular UI-Bootstrap Carousel com Multiplos slides

Question: Estou usando o Carousel UI-Bootstrap com AngularJs,  porem só mostra 1 slide por vez. Queria multiplos slides igual a esses exemplos abaixo.
Bootstrap 3 Multiple Slide Carousel, outro exemplo,
Bootstrap 3 Carousel Multiple Items Increment by 1
É possivel fazer Multiplos Slides usando Ui-Bootstrap com AngularJs? Ou teria que usar a diretiva Angular Slick?
Meu exemplo usando Ui-Bootstrap
Answer: Optei por usar Owl Carousel no AngularJs.
app.owl.js
angular
.module('appCliente.owl', []);

    function owlCarousel() {
        var directive = {
            restrict: 'E',
            transclude: false,
            link: link
        };
        return directive;

        function link(scope) {
            scope.initCarousel = function (element) {

                console.log('initcarousel');
                var defaultOptions = {};

                var customOptions = scope.$eval($(element).attr('data-options'));
                // combine the two options objects
                for (var key in customOptions) {
                    defaultOptions[key] = customOptions[key];
                }
                // Inicia o OwlCarousel
                var curOwl = $(element).data('owlCarousel');

                if (!angular.isDefined(curOwl)) {
                    $(element).owlCarousel(defaultOptions);
                }
            }
        }
    }

    angular
        .module('appCliente.owl')
        .directive('owlCarousel', owlCarousel);

owlCarousel-directive.js
angular
    .module('appCliente.owl')
    .directive('owlCarouselItem', owlCarouselItem);

function owlCarouselItem() {
    var directive = {
        link: link,
        restrict: 'A',
        transclude: false
    };
    return directive;

    function link(scope, element) {
        /* Ultimo item do ng-repeat */
        if (scope.$last) {
            console.log('1st element');
            scope.initCarousel(element.parent());
        }
    }
}

Index.html

    <link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css" rel="stylesheet" />

    <link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.css" rel="stylesheet" />

Novos Mangas

            <data-owl-carousel class="owl-carousel owl-theme" id="owl-example" data-options="vm.default">

                        {{manga.nome}}

            </data-owl-carousel>


OutputCache Bug with VaryByParam="None" with MVC RC refresh

Question: Came across to this defect with ASP.NET RC refresh while using VaryByParam="" instead of VaryByParam="None".
Caching WORKS, but page http://www.yoursite.com and http://www.yoursite.com/home/index will be cached separately it seems.
What is the difference between VaryByParam="" and VaryByParam="None"?
edit : I mean VaryByParam="" not VaryByParam="*" cause the bug still exists with VaryByParam="*"
Answer: VaryByParam="*" will create a new cache for every different parameter passed.
VaryByParam="None" will create one and only one cache, regardless of parameters.
Comment: I meant VaryByParam="" not VaryByParam="*" cause  the bug still exists with VaryByParam="*"
Comment: Instead of using VaryByParam="None" I suggest to use VaryByParam="" (empty string). Otherwise the cache will create a new entry if the user specify the `None` parameter.
Answer: Route elements are not considered parameters for OutputCache.
What is VaryByParam in asp.net?


configuring squid to use a different proxy server as its internet connection

Question: I'm setting up a squid proxy on my computer (I use ubuntu).
However, my computer is not connected to the internet directly. I connect to the internet via an authenticating proxy (incidentally, also squid). I want to set up my own squid to send all requests to the internet via the other proxy.
I was mucking around with the tutorials and documentation, and found something called cache_peer. I tried using it, but to no avail.
You may ask, "Why are you doing this?"
A: My final goal is:
If my squid recieves a request to http://fictitiouswebsite.com/page/article, then it will convert the request into http://ficticiouswebsite.com/page/artice?google.
This is just like a simple URL rewrite (I know this term from apache).
So if you know how to do that, please tell me that too.
Thanks,
jrh
PS: i've never configured a squid proxy before in my life. this is my first time.
Comment: What version of Squid are you using?
Answer: See the Squid documentation for the cache_peer directive. For a proxy on parentcache.foo.com:8080, you could use something like:
cache_peer parentcache.foo.com parent 8080 0 no-query default login=user:password
acl all src 0.0.0.0/0
never_direct allow all

Comment: Yep, that will push all traffic through a proxy with a user and password.


How to prove that an integral converges

Question: Let $(a_n)$, $(M_n)$ be sequences of positive real numbers such that ${a_n} \downarrow 0$, ${M_n} \uparrow \infty$ as $n\to\infty$. Let $\alpha>0$ and $\beta>1$. How to prove the following statement
$$\int\limits_{ - \infty }^\infty  {{e^{ - {{\left| {{a_n}u + {M_n}} \right|}^\alpha }}}{{\left| u \right|}^\beta }du}  < \infty$$
for all $n$ large enough.
Thank so much for heplping.
Comment: Have you tried bounding it by some integral that is known to converge?
Answer: $$\frac{|u|^\beta}{e^{|a u + M|^\alpha}} < \frac{1}{|u|^2}$$ for large $|u|$.

How to prove that an integral converges


Float Division and implicit round

Question: I've found a strange behaviour in a piece of code I wrote which does not happens when I try to reproduce it out of the program (i.e. with MATLAB).
I'm doing a operation over an array as follow:
a[i] = a[i] / (sqrt(b[i]) * sqrt(c[i]));

where a, b and c are arrays of type float. The values of a, b and c prior division range from 2000 to 6000000
The result of the operation is zero for all the elements of the array, but looking at the values of the numerator and denominator separately, for a given element, the operation is 89509.0 / 90240,375 which is equal to 0,991895258.
So, I wondering why the full operation within the program using float does not work, and it works separately as expected. Probably due to hours of obfuscated debugging?
Comment: You haven't given us anywhere close to enough information to help solve your problem. What are the values of `a[i]`, `b[i]`, and `c[i]` prior to the division? *Have you run your program using the debugger?*
Comment: Just guessing, but I suspect that there is a conversion to integer going on here somewhere.
Comment: What data type is `a`? `float[]`?
Comment: @slugonamission `a`,`b`,`c` are arrays of floats.
Comment: @DavidHammen be sure i run the debugger before ask in SO. I'm updated the question
Answer: When I run across a similar situation, I find that it often helps to break it down into steps and see which steps behave properly and which do not. For example, for this, it could be broken down into the following:
float sqrtb = sqrt(b[i]);
float sqrtc = sqrt(c[i]);
float divisor = srqtb * sqrtc;
float dividend = a[i];
float quotient = dividend / divisor;
a[i] = quotient;

Now I can run through each item and see where it fails (if it fails). Fact is, when I do this, I often find the problem while creating the steps, and then it is fixed.
Comment: Good advice.  Probably what I'd do ,too.
Comment: I'll investigate it further but the truth is that work as you described, which also helped me to confirm intermediate results
Comment: What surprise that I follow your suggestion and the results are correct, but not when I run the whole operation in a line.

Float Division and implicit round


Solving ODE in Scilab

Question: I am trying to do some electric circuit analysis in Scilab by solving an ODE. But I need to change an ODE depending on current value of the function. I have implemented the solution in Scala using RK4 method and it works perfectly. Now I am trying to do the same but using standard functions in Scilab. And it is not working. I have tried to solve these two ODEs seperately and it is OK.
clear
state = 0 // state 0 is charging, 1 is discharging
vb = 300.0; vt = 500.0;
r = 100.0; rd = 10.0;
vcc = 600;
c = 48.0e-6;

function dudx = curfunc(t, uu)
    if uu < vb then state = 0
    elseif uu > vt state = 1
    end

    select state
    case 0 then // charging
        dudx = (vcc - uu) / (r * c)
    case 1 then // discharging
        dudx = - uu / (rd * c) + (vcc - uu) / (r * c)
    end
endfunction
y0 = 0
t0 = 0
t = 0:1e-6:10e-3

%ODEOPTIONS=[1, 0, 0, 1e-6, 1e-12, 2, 500, 12, 5, 0, -1, -1]
y = ode(y0, t0, t, 1e-3, 1e-6, curfunc)
clear %ODEOPTIONS
plot(t, y)

so here I am solving for a node voltage, if node voltage is exceeding top threshold (vt) then discharging ODE is used, if node voltage is going below the bottom voltage (vb) then charging ODE is used. I have tried to play with %ODEOPTIONS but no luck
Comment: Could you please document the problem cases, the script as it is runs perfectly.
Answer: I think it boils down to a standard problem: The standard ODE solvers have step size control. In contrast to the fixed step size of RK4. For step size control to work, the ODE function needs to have differentiability at least of the same order as the order of the method. Jumps as in your function are thus extremely unfortunate.
Another point to consider is that the internal steps of the method are not always in increasing time, they may jump backwards. See the coefficient table for Dormand-Prince for an example. Thus event based model changes as in your problem may lead to strange effects if the first problem were circumvented.

Workaround (not really a solution)
Declare state as a global variable, since as a local variable the value gets always reset to the global constant 0.
function dudx = curfunc(t, uu)
    global state
    ...
endfunction
...
y = ode("fix",y0, t0, t, rtol, atol, curfunc)

Answer: you can also use the ode("root"...) option.
The code will ressemble to
    clear
    state = 0 // state 0 is charging, 1 is discharging
    vb = 300.0; vt = 500.0;
    r = 100.0; rd = 10.0;
    vcc = 600;
    c = 48.0e-6;
function dudx = charging(t, uu)
//uu<vt
  dudx = (vcc - uu) / (r * c)
endfunction
function e=chargingssurf(t,uu)
  e=uu-vt
endfunction

function dudx = discharging(t, uu)
//uu<vb
  dudx = - uu / (rd * c) + (vcc - uu) / (r * c)
endfunction
function e=dischargingssurf(t,uu)
  e=uu-vb
endfunction

y0 = 0
t0 = 0
t = 0:1e-6:10e-3

Y=[];
T=[];
[y,rt] = ode("root",y0, t0, t, 1e-3, 1e-6, charging,1,chargingssurf);
disp(rt)
k=find(t(1:$-1)<rt(1)&t(2:$)>=rt(1))
Y=[Y y];;
T=[T t(1:k) rt(1)];
[y,rt] = ode("root",y($), rd(1), t(k+1:$), 1e-3, 1e-6, discharging,1,dischargingssurf);
Y=[Y y];
T=[T t(k+1:$)];

plot(T, Y)

The discharging code seems to be wrong...

Solving ODE in Scilab


Mudar o valor de uma variável ao selecionar um option

Question: Em minha tabela de produtos, gostaria de fazer alguns filtros básicos, como ordenar por ordem alfabética, preço, etc...

A ideia é a seguinte, quando o usuário selecionar um option (não precisa necessariamente ser um option), mudar o valor de uma variável X, mudando também a consulta em meu SQL.

Exemplo: (Apenas para vocês compreenderem melhor)
<form action="" method="POST">
    <select>
       <option value="a">Ordem A-Z</option>
       <option value="z">Ordem Z-A</option>
       <option value="preco">Ordem por preços</option>
    </select>
</form>

<?php
    if (isset($_POST["a"])){
        $ordenar= "nome_produto";
    }
    if (isset($_POST["z"])){
        $ordenar= "nome_produto DESC";
    }
    if (isset($_POST["preco"])){
        $ordenar= "valor";
    }

// A ideia é mudar o valor diretamente na consulta, ao selecionar algum option...
$sql = "SELECT * FROM produtos ORDER BY $ordenar";
?>

Este exemplo, está incompleto, é só um exemplo, mas acho que deu para vocês entenderem o que eu quero fazer.

É possível eu fazer isso com puro PHP?
Como eu faria algo parecido que funcione?
Tem outra maneira mais "prática" ou mais certa do que essa?
Funcionaria se eu utilizasse Jquery?

Agradeço a qualquer tipo de ajuda, um ótimo dia a todos.
Comment: acredito que a melhor opção seria usando o ajax do jquery, assim, sempre que o option fosse alterado vc buscava o sql em um arquivo php separado de acordo com o option selecionado, outra coisa que reparei é q seu ... está errado, está faltando o "name" e no seu php vc teria que chamar o $_POST de acordo com o "name" e não de acordo com cada "value" igual vc fez
Comment: Pensei nessa alternativa, mas para isso eu teria que colocar um `button` do `type submit` dentro do `form` não é? não tem a possibilidade de eu fazer isso sem precisar apertar algum botão? fazer o filtro apenas selecionando o `option`...
Comment: da forma que eu passei vc não precisaria de nenhum botão, vc poderia usar o change() do proprio jquery para verificar se o  foi alterado e assim fazer o ajax
Comment: `...`
Comment: Esse trecho fará com que a form seja enviada ao mudar a opção... Não é a melhor forma, mas deve funcionar
Comment: @TalesPeres você pode me dar um exemplo na prática? sou um pouco leigo com js...
Answer: Você pode adicionar um event listener ou diretamente no elemento, uma chamada para o submit do form:
<form action="#" method="POST" name="filtro">
    <select onchange="document.getElementsByTagName('form')[0].submit()">
       <option value="a">Ordem A-Z</option>
       <option value="z">Ordem Z-A</option>
       <option value="preco">Ordem por preços</option>
    </select>
</form>

Neste caso, eu selecionei pelo nome da tag, mas em cenarios mais realistas você deveria selecionar por id ou class.
Abaixo você pode executar o código para ver como ficou:

/**
  Simulando envio, ignore
**/

var onSubmit = function(e){
  alert('form enviada');
  return false;
 };

document.getElementsByTagName('form')[0].submit = onSubmit;
<form action="#" method="POST" name="filtro">
    <select onchange="document.getElementsByTagName('form')[0].submit()">
       <option value="a">Ordem A-Z</option>
       <option value="z">Ordem Z-A</option>
       <option value="preco">Ordem por preços</option>
    </select>
</form>
Comment: Obrigado pela resposta, eu acabei fazendo um pouquinho diferente mas consegui baseado em a sua ajuda! Vou colocar a minha resposta abaixo, mas irei considerar a sua. +1
Comment: Obrigado pela resposta, isso o envia o `form` sem precisar de um `button`, porém, como eu faria para entrar na condição do `IF`? (selecionar o `option` e trazer um valor para a variável)
Comment: Se eu consegui entender, nao muda nada. Ao enviar o form, você já está pegando os valores do $_POST. Para manter o valor selecionado, basta adicionar a propriedade `selected` no option que você deseja: `>Ordem A-Z`
Comment: Nao, pera. Você precisa dar um name pro select, e pegar por ele. Nao `$_POST["a"]`
Comment: Ficaria assim no html: `...` e no php: `$_POST["filtro"]`
Answer: Consegui fazer a ordenação na tabela dessa forma

    <form action="" method="POST">
        <select name="filtro" onchange="this.form.submit()">
            <option value="a">Ordem A-Z</option>
            <option value="z">Ordem Z-A</option>
            <option value="preco">Ordem por preços</option>
        </select>
    </form>

<?php
$ordernar = 'ID_produtos DESC';

if (isset($_POST["filtro"])){
    $filtro = $_POST['filtro'];

    if ($filtro == "a") {
        $ordernar = 'produto';
    }
    if ($filtro == "z") {
        $ordernar = 'produto DESC';
    }
    if ($filtro == "preco") {
        $ordernar = 'valor';
    }
}

$sql = "SELECT * FROM produtos ORDER BY $ordernar";
?>


Closure of a set with the jungle-river metric.

Question: Consider $\mathbb{R}^2$ with the jungle river metric $d_j$.
$$d_j(x,y) = \begin{cases} |x_2-y_2|, & \text{if $x_1 = y_1$;} \\
|x_2| + |y_2| + |x_1-y_1|, & \text{if $x_1 \neq y_1 $} \end{cases}$$
Let
$$C = \{(x, 1) : x ∈ Q\}$$
What is the closure and the interior of C?
I think the closure is C as ${\overline{C}}$ = C ∪ {all limit points of C}. For any (x,1) in C we can find an "open ball" that only intersects C at (x,1) by taking B(x,ε) for ε<2. Does this mean C has no limit points and that ${\overline{C}}$=C?
For the interior I used the fact that if A ⊂ X then A$^◦$ = X \ ${\overline{(X \backslash A)}}$. I believe ${\overline{(\mathbb{R}^2 \backslash C)}}=\mathbb{R}^2$ which would make C$^◦$ = $∅$.
Comment: Third time this question is posted in a week. Is it an assignment?
Comment: @Mike that one doesn't have answers yet.  Regardless, I really don't think this should be closed, since it's asking pretty narrowly about a specific approach to the problem that is likely not duplicated elsewhere.
Comment: Ok I have added the part for the interior.
Comment: I'm inclined to answer this one as the OP has given a specific thought process that deserves addressing, but I'd like to first see OP's thoughts on the interior part of the question. @Jack W can you elaborate on what you've tried for the interior? (Best to elaborate in the question, rather than as a reply in the comments)
Comment: Does this answer your question? https://math.stackexchange.com/questions/4862342/closure-interior-of-mathbbq-times-1-in-mathbbr2-under-a-different
Answer: [Note: I realize this has been asked before this week, but as OP has given a specific thought process that is not duplicated elsewhere that I'm aware of, and that deserves addressing, I'm inclined to answer.]
While your conclusion is correct, your reasoning isn't quite right for the closure of $C$.
The fact that you can take a ball around any point in $C$ and it only intersects $C$ in that one point doesn't tell you that $C$ is closed, it tells you rather that $C$ is discrete. For example, the set $\{\frac{1}{n}\mid n\in \mathbb N\}\subset \mathbb R$ is discrete by this same argument, but is not closed, as it does not contain its limit point $0$.
Instead, you could observe that if $p\notin C$, then either $p=(x,y)$ for $y\neq 1$, whereby the open ball $B(p,|y-1|)$ does not intersect $C$, or $p=(x,1)$ for $x\notin \mathbb Q$, whereby the ball of radius $1$ does not intersect $C$.  Therefore $\mathbb R^2\backslash C$ is open, hence $C$ is closed.
For the interior, what you have written is not wrong, but it somewhat begs the question of how you determined that $\overline{\mathbb R^2\backslash C}=\mathbb R^2$ in the first place.  To conclude this, you could observe that $(x,1)=\lim_{n\to\infty} (x,1-\frac{1}{n})$.
Update.
On reflection, with a little care you could make your original argument for the closure work as well.  The fact that every point $p\in C$ has some ball around it intersecting $C$ only at $p$, of the same radius independent of $p$, indicates a stronger condition than discreteness - what we might call $\varepsilon$-discreteness (here for $\varepsilon=2$).  An $\varepsilon$-discrete metric space is complete (since every Cauchy sequence is eventually constant), hence any $\varepsilon$-discrete subset of a metric space must be closed.


Postgres connection failure when running node app using supervisor

Question: I have nodejs webapp with postresql. I am running this using supervisord on the server. The problem is that the postgresql login from nodejs is failing. The error message is:
no PostgreSQL user name specified in startup packet
which basically means no user name is being passed from the webapp while connecting to the db.
Note that I am using unix socket for connecting to postgres from my webapp.
My webapp1.conf looks like:
[program:webapp1]
user=webapp1
command = node /home/webapp1/projects/webapp1/app.js
directory = /home/webapp1/projects/webapp1
autostart = true
autorestart = true
stdout_logfile = /var/log/supervisor/webapp1.log
stderr_logfile = /var/log/supervisor/webapp1_err.log

I have confirmed that supervisor is running the webapp is running under user webapp1.
One more thing - if I start my webapp by logging in as user webapp1, it works.
Comment: Gave up finally and used [pm2](http://pm2.keymetrics.io/)
Answer: It sounds like you've got your server set up to use password-less logins to PostgreSQL-- i.e. you have local logins in your pg_hba.conf set to peer or trust so that as long as there's a user configured in postgres with the same name as your linux user, you don't have to do any further configuration to get Postgres working in your apps-- it effectively grants access to the db based on your Linux user account.
I had the same problem when running a simple nodejs script via cron.  It worked fine from the shell, but complained of missing username when running via cron.  Setting the username explicitly in code wasn't an option because I'd built my config to be as automatic as possible-- I needed it to figure out privileges by which user the script was running as.
It turns out that either the connector library or postgres itself infers the username from an environment variable.  I was able to fix it by setting USER=<cron user name> at the top of my crontab (since this was set explicitly in the env of an interactive shell, which is why this works at all).
It looks like the proper syntax to add to your webapp1.conf would be:
environment=USER="<user name here>"


frequency of each row in data.table for a specific column

Question: I have the following data.table.
    dat <- structure(list(kmers = c("TTTTTTTTTTTT", "TCCATTCCATTC", "TTCCATTCCATT",
"CCATTCCATTCC", "ATTCCATTCCAT", "CATTCCATTCCA", "TTTTATTATTTT",
"AAAATTATAAAA", "AAGACAATTTCT", "AAAGACAATTTC"), counts = c(16361L,
10090L, 9599L, 9021L, 8516L, 8325L, 5739L, 5642L, 5378L, 5326L
)), .Names = c("kmers", "counts"), class = c("data.table", "data.frame"
), row.names = c(NA, -10L), .internal.selfref = <pointer: 0x29f1d78>)

This is the table
           kmers counts
 1: TTTTTTTTTTTT  16361
 2: TCCATTCCATTC  10090
 3: TTCCATTCCATT   9599
 4: CCATTCCATTCC   9021
 5: ATTCCATTCCAT   8516
 6: CATTCCATTCCA   8325
 7: TTTTATTATTTT   5739
 8: AAAATTATAAAA   5642
 9: AAGACAATTTCT   5378
10: AAAGACAATTTC   5326

I would like to divide the column counts by the sum of all counts. For a dataframe i would do
total=sum(dat$counts)
freq <-  dat$counts/total

How can i do that for the data.table ? Each kmers is unique so i do not expect to have duplicated values in kmers column.
For example for first row it will be 16361/sum(dat$counts).
Comment: `dat[, freq := counts / sum(counts)]`
Comment: Thanks for the update!!!
Answer: Or using normal base syntax still works:
dat$countProportion = dat$counts / sum(dat$counts)


Homework Help - Calculus III / Physics / Work-Force Problem #2

Question: I'm in a similar scenario as with my other question. I have tried to answer the problem correctly, and I have found similar (and even an identical) problem in my textbook, yet I still can't seem to yield the correct answer with this specific problem.
The example problem in my textbook:
A crate is hauled 8m up a ramp under a constant force of 200 N applied at an angle of 25 degrees to the ramp. Find the work done. W = F * D cos(25) = (200)(8)cos(25) = 1450J.
Can anyone give me any advice on how to solve it?
A woman exerts a horizontal force of 4 pounds on a box as she pushes it up a ramp that is 5 feet long and inclined at an angle of 30 degrees above the horizontal.
Find the work done on the box.
I would think that the work would simply be (4)(5)cos(30), but that is not the correct answer.
(I've figured out how to accept answers now, so I'll accept the most helpful answer.)
Comment: How about exchanging cos with sin. Does $4 5 \cos(30^\circ)$ yield the correct result? (if the ramp is not inclined at all, no work should be done)
Comment: Do you have the actual numerical answer? Your method of computation seems ok. I wonder if it is a problem of units.
Comment: consider posting on Physics Exchange also.
Comment: First of all dear @Math Student as you say applied force is 4 pounds which (though i seldom work in such units) means that fore applied is 4 * g (acceleration due to gravity).
Comment: In Imperial units, the base unit is pounds as a unit of force, so you should not multiply by g.  We have slugs as a unit of mass, and also lbm to confuse things.
Answer: As Fabian said in a comment, the $\cos$ should be $\sin$
Answer: Work done is weight times vertical displacement of the center of gravity. The rest of the problem is playing with the units to get to a consistent set. Well, also friction could add to the work.
Another source of error, is the sin() function, in case it expects a number in radians and you supply it in degrees.
You answer in lbs $\times$ ft is not in Joules. Multiply by 1.35581795 to convert to Joules.
Comment: The answer is actually expected to be ft-lbs.


selenium unable to get page after opening it with python

Question: I have this code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
# import org.openqa.selenium.Keys
import datetime
import time
import unittest

cap = DesiredCapabilities().INTERNETEXPLORER
cap['ignoreProtectedModeSettings'] = True
cap['IntroduceInstabilityByIgnoringProtectedModeSettings'] = True
cap['nativeEvents'] = True
cap['ignoreZoomSetting'] = True
cap['requireWindowFocus'] = True
cap['INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS'] = True
browser = webdriver.Ie(capabilities=cap, executable_path=r'C:\IEDriverServer_x64_3.150.1\IEDriverServer.exe')
browser.implicitly_wait(2)

browser.get("https://www.google.ro/?safe=active&ssui=on")

search_form = browser.find_element_by_xpath('/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/button[1]')
search_form.click()

Any page I try to open, a timeout error is returned after awhile:
Traceback (most recent call last):
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\unittest\case.py", line 60, in testPartExecutor
    yield
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\unittest\case.py", line 672, in run
    self._callSetUp()
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\unittest\case.py", line 630, in _callSetUp
    self.setUp()
  File "C:\Users\MunteanuG\PycharmProjects\Dex_Automation\SRC\utilityTools.py", line 24, in setUp
    self.browser.get("https://www.google.ro/?safe=active&ssui=on")
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\MunteanuG\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: Timed out waiting for page to load.

I am using python 3.7 interpretator.
Post mostly code, adding text to post, test test test test
Comment: after browser.get add explicit or implicit wait till the element is available to click
Comment: Hmm, but will it help ? Beacause no page is being recognized as opened or fully loaded i guess so there's a underlying issue, i don't think a wait will do the trick but i;ll try it
Comment: check if your IE is able load same page manually
Answer: It seems like the page you are trying to load is kind of loading some sort of JavaScript or isn't reachable
Try disabling JavaScript using this
from selenium.webdriver.Ie.options import Options

options = Options()
options.preferences.update({'javascript.enabled': False})
browser = webdriver.Ie(options=options,executable_path="path")

If it still doesn't work try removing all the capabilities.
Comment: Im getting this error `AttributeError: 'Options' object has no attribute 'preferences'` from selenium.webdriver.Ie.options import Options, 'Ie' is not found, instead i replaced it with 'ie' which seems to be ok, but from options class preferences dosen't exist
Comment: Also, I tried chrome driver, it works perfectly so the problem is my internet explorer
Comment: I wish I could use chrome, I'm stuck with IE not even edge... I kinda have to make it work
Comment: hmm , I know you should be able to do it by changing the browser configuration to disable javascript by default
Comment: Disabled it from tools, it seems to behave the same, something in the page is still not loading, on any page I try to load
Answer: If you look into the Required Configuration of Internet Explorer Driver the following points are clearly mentioned :
Protected Mode
On Internet Explorer 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings you have to choose "Internet Options" from the "Tools" menu and then click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled Enable Protected Mode.

Further, @JimEvans in his article You're Doing It Wrong: IE Protected Mode and WebDriver clearly mentions :

Using the capability doesn't solve the underlying problem though. If a Protected Mode boundary is crossed, very unexpected behavior including hangs, element location not working, and clicks not being propagated, could result. To help warn people of this potential problem, the capability was given big scary-sounding names like INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS in Java and IntroduceInstabilityByIgnoringProtectedModeSettings in .NET. We really thought that telling the user that using this setting would introduce potential badness in their code would discourage its use, but it turned out not to be so.

Solution
You can access the url https://www.google.ro/?safe=active&ssui=on using the following solution:
from selenium import webdriver

driver = webdriver.Ie(executable_path=r'C:\WebDrivers\IEDriverServer.exe')
driver.get('https://www.google.ro/?safe=active&ssui=on')

References
You can find a couple of relevant detailed discussions in:

How to ignore zoom setting
Internet Explorer Protective mode setting and Zoom levels
How to ignore protected Mode Settings for Internet Explorer using setCapability() through Selenium and Java?
How to ignore zoom setting
Selenium not detecting the second window in IE


How to see a Gaussian Discriminant Analysis (GDA) as a linear model for multiclass case?

Question: In GDA we can assume that posterior probability for each of $K$ possible classes is Gaussian with same variance $\Sigma$, and different means $\mu_k$, ie.
$$p(\mathbf x|C_k):\mathcal N(\mathbf \mu_k,\mathbf \Sigma), \ k=1,\dots,K.$$
According to Bayes formula we can write
$$p(C_k|\mathbf x) = \frac{p(\mathbf x|C_k) \ p(C_k)}{\sum_{j=1}^K p(\mathbf x|C_j)\  p(C_j)} = \frac{\exp(a_k)}{\sum_{j=1}^K \exp(a_j)} $$
where $a_k$ is defined as
$$a_k = \ln p(\mathbf x|C_k) p(C_k). $$
What confuse me is that according to Bishop C. book we can represent $a_k$ as a linear model in the following way
$$a_k=\mathbf w_k^T \,\mathbf x + w_{k0} $$
with
\begin{equation}
\mathbf w_k = \mathbf \Sigma^{-1} \mathbf \mu_k, \quad w_{k0}=-\frac{1}{2} \mathbf \mu_k^T \Sigma^{-1} \mathbf \mu_k + \ln p(C_k)
\end{equation}
because (according to C. Bishop)

"We see that the $a_k$ are again linear functions of $\mathbf x$ as a consequence of the cancellation of the quadratic terms due to the shared covariances."

I don't see how the cancellation of the quadratic terms due to the shared covariances happend?
In my derivation:
\begin{align}
a_k &= \ln p(\mathbf x|C_k) p(C_k)\\
&= \ln p(\mathbf x|C_k) + \ln p(C_k)\\
&=\ln(2\pi)^{-\frac{M}{2}}|\mathbf  \Sigma|^{- \frac{1}{2}} -\frac{1}{2}  (\mathbf  x - \mathbf \mu_k)^T \mathbf  \Sigma^{-1} (\mathbf  x - \mathbf  \mu_k)+ \ln p(C_k)\\
&=
-\frac{1}{2} \color{red}{\mathbf  x^T \mathbf  \Sigma^{-1} \mathbf  x }+\mathbf  x^T\mathbf  \Sigma^{-1} \mathbf \mu_k \! -\!\frac{1}{2}\mathbf  \mu_k^T\mathbf  \Sigma^{-1} \mathbf \mu_k +\ln(2\pi)^{-\frac{M}{2}}|\mathbf  \Sigma|^{- \frac{1}{2}}
\end{align}
I still have quadratic term $\color{red}{\mathbf  x^T \mathbf  \Sigma^{-1} \mathbf  x} $!
Also I got the same linear term but in free term $w_{k0}$ I has additional constant $\ln(2\pi)^{-\frac{M}{2}}|\mathbf  \Sigma|^{- \frac{1}{2}} $.
How I can cancel previous quadratic term and get a linear model in multiclass case?
Additional note: For binary case ($K=2$) I already know the answer: we will represent posterior probability with sigmoid function and in that case we will loose quadratic term.
Answer: my feeling is that that a_k in (4.68) is not the same as the a_k in (4.63). It could be called b_k, anyhow. What is important is that the classification is made according to the highest value of all a_k's (4.68). Since the quadratic term doesn't depend on k, we can use (4.63) instead of (4.68), i.e; we can drop the quadratic term in x. The text is ambiguous (very unlike Bishop!) but the fact that the classifier can be build from a linear form in x in the end is correct.
after a few more thoughts: in fact, the new a_k in (4.68) (or say b_k) is different from the old a_k in (4.63), but softmax (a_k) = softmax(b_k) = p(C_k given x) !!! This is because the quadratic form in x can be factorized at both the numerator and denominator of softmax. We thus can use can use p(C_k given x) = softmax(b_k) = softmax (linear form in x) for classification!
I forgot to mention that softmax(a_k) is not a function of a_k 'alone', it is a function of all a_k together, k = 1:K, but still, the reasoning is correct, I think.
Comment: Please don't post multiple replies--just keep improving this one through edits.
Comment: I agree with you. $a_k$ in (4.68) in not the same as the $a_k$ in (4.63) which made confusion in the book. Since we use max of all $a_k$ we can drop the quadratic term. And you made a good point that: even we does not calculate softmax($a_k$) we can still calculate probability as softmax($b_k$) because they are the same.


How to find the closed form for $\sum_{i=1}^k 3^{-i}$

Question: How do I calculate (is closed form the correct word?) the closed form of:
$$\sum_{i=1}^k 3^{-i}?$$
I know how to calculate the geometric series:
$$\sum_{i=1}^\infty 3^{-i} = \frac1{1-(1/3)}$$
But that doesn't help since I don't know how to calculate $\sum_{i=k+1}^\infty 3^{-i}$ (without calculating the thing I want). Wolframalpha says it is $$\sum_{i=1}^k 3^{-i}=\frac12 - \frac{3^{-k}}{2}$$
But I don't know how they calculated this. Maybe there is a closed form for
$$\sum_{i=1}^k n^{-i},$$
for $n\in \Bbb N$?
Comment: The typesetting is fine - the problem is you could have easily found the answer here or elsewhere. If you google "geometric series" the first  hit answers your question: https://en.wikipedia.org/wiki/Geometric_series
Comment: Your $\sum_{i=1}^\infty 3^{-i} = \frac1{1-(1/3)}$ is wrong. It should be either

$$\sum_{i=0}^\infty 3^{-i} = \frac1{1-(1/3)}$$
or

$$\sum_{i=1}^\infty 3^{-i} = \frac{(1/3)}{1-(1/3)}$$
Comment: Do you actually know how to _calculate_ $\sum_1^\infty$? Or do you just know the answer? If you actually know how to calculate $\sum_1^\infty$ the same calculation can be used for $\sum_1^k$.
Comment: Oh no, I got downvotes :(. I tried hard to typeset this
Answer: Hint: Use the well-known formula $$\sum_{i=1}^n q^i=\frac{q^{n+1}-q}{q-1}$$ for $q\ne 1$
Answer: $S_k = (1/3)^1+(1/3)^2+....+(1/3)^k$;
$(1/3)S_k= (1/3)^2+.....+(1/3)^{k+1}$;
Subtract:
$S_k-(1/3)S_k=$
$(2/3)S_k=(1/3)^1-(1/3)^{k+1}$;
$S_k=(3/2)((1/3)-(1/3)(1/3)^k)$;
$S_k =(1/2)-(1/2)(1/3)^k$;
$S_k= (1/2)-(1/2)3^{-k}.$
Answer: If you know about the infinite geometric series sum (for $-1\le r<1$)
$$\sum_{i=1}^{\infty} r^i = \frac{r}{1-r}$$
Then a finite sum is just
$$\begin{align*}
\sum_{i=1}^{k} r^i &= \sum_{i=1}^{\infty} r^i - \sum_{i=k+1}^{\infty} r^i\\
&= \sum_{i=1}^{\infty} r^i - r^k\sum_{i=1}^{\infty} r^i\\
&= \frac{r(1-r^k)}{1-r}
\end{align*}$$
(This formula works for all $r\ne 1$, but this proof only works for $-1\le r<1$.)
Answer: we have:
$$S_k=\sum_{i=1}^k3^{-i}$$
note that the terms of a geometric series can be expressed as:
$$a_k=ar^{k-1}$$
in this case, we have: $a=\frac 13$,$r=\frac 13$. We can now use the formula:
$$S_k=a\frac{(1-r^k)}{1-r}$$
this should give you:
$$S_k=\frac{1}{2}\left(1-3^{-k}\right)$$
It can also be derived as given below

we have:
$$S_k=\frac{1}{3}+\frac{1}{3^2}+...\frac{1}{3^k}$$
which can be factorised to:
$$S_k=\frac{1}{3}\left(1+\frac{1}{3}+...\frac{1}{3^{k-1}}\right)$$
and notice that this is just the same as:
$$S_k=\frac 13\left(1+S_{k-1}\right)$$
we also know that:
$$S_k=S_{k-1}+a_k=S_{k-1}+\frac{1}{3^k}\Rightarrow S_{k-1}=S_k-\frac{1}{3^k}$$
substituting one equation into the other, we get:
$$3S_k=1+S_k-\frac{1}{3^k}$$
$$2S_k=1-\frac{1}{3^k}\Rightarrow S_k=\frac 12\left(1-3^{-k}\right)$$


"Access Denied" when trying to access AWS Lightsail database

Question: I'm trying to connect to my AWS Lightsail database instance with Navicat Premium 15.0.21 (newest available version at the time of posting).
My database is in public mode. I copied and pasted the endpoint, username, and password straight into Navicat; Port 3306. Lightsail reports the database as "Available."
These settings have not changed for over 24 hours and I have rebooted the instance multiple times but Navicat keeps telling me "Access Denied"
Here's a screenshot of the error:
image
I have also tried connecting with a VPN via multiple countries. And I have tried to connect with DBeaver; same issue (Access Denied). I'm running Navicat on MacOS Catalina 10.15.4.
Anyone know what's wrong?
Comment: Based on the error message it looks like you can connect fine, and that the problem is user / password.
Comment: @Tim Interesting. Unfortunately I have also tried changing the password, still no login luck. And dbmasteruser is just the default username it gives you when you create the instance
Answer: I had the same problem when setting up the connection in MySQL Workbench.
The cause was the following:
When you double click to copy the password from the AWS page, it appends an enter at the end. This is copied into the password field as well. So the password is not correct.
Copy the password by selecting it character by character. Then there will be no enter at the end and the connection will be correct.
Comment: Truly ridiculous! I can't believe this was the issue. Thank you! Working fine now


Find number of Sylow $3$ and Sylow $5$ subgroups of a simple Group, $G$ of order $60$

Question: So I wanted to check if what I did was correct. I'm not sure if it is and if so what would the correct way to go about this be?
So firstly  $|G| = 2^2*3*5$. This confirms there is Sylow 3 - Subgroup's and Sylow 5-Subgroups.
Now for  Sylow 3 - Subgroup's, where $n_3$ is the number of Sylow 3-Subgroups, we have, from Sylow's theorems that:
$n_3 \equiv 1$ mod $3$ and $n_3$ | $20$ so $n_3 = \{1,4,10 \} , n_3 \neq 1$ as otherwise we'd have a unique normal group and therefore G would not be simple.
From similar deduction, we arrive at $n_5 = 6$
So we must have that any two Sylow 5 - Subgroups intersect at $\{1 \}$ and so we have:
$60 - ((6-2) * 5) = 40$ elements in the remaining Sylow p - subgroups.
If $n_3 = 4$, similarly:
$40 - ((4-2) * 3) = 34$ elements in the remaining Sylow p - subgroups.
But $(\frac{34}{4}) \notin \mathbb{Z}$ where $4 = 2^2$ for Sylow 2 - subgroups.
Now if $n_3 = 10$ then 16 elements remain and $(\frac{16}{4}) = 4$ Sylow 2 - subgroups and therefore $n_3 = 10$
So upon checking my mark scheme these are the correct answers - but I am not 100% my method is correct or if its rigorous enough. If it is - is there other ways to do it?
Thanks.
Answer: You could argue as follows, since Sylow subgroups are permuted transitively under conjugation.
If the number of Sylow $3$-subgroups is $4$, then they are permuted transitively by conjugation, and this gives rise to a non-trivial homomorphism to $S_4$. But $S_4$ has order $24\lt 60$ so such a homomorphism would have a non-trivial kernel.
Comment: Ok that makes perfect sense, thank you!


Continuity correction in proportion test

Question: Can you please clarify to me when to use continuity correction in proportion test please? I'm using this formula in R and I want to know the difference in the option correct= TRUE or FALSE. Also, I noticed the p value with correction goes up, so I'm just concerned if I'm using this option (TRUE or FALSE) correctly? how this might impacts my analysis. Any help is really appreciated!
prop.test(x=c(84,105.5),n=c(99,146),correct = TRUE)

Thank you
Comment: How do you have half a success?
Answer: In order to consider what you asked, without additional material, consider the $2\times 2$ table TAB as follows:
TAB = rbind(c(80,90), c(20,15))
TAB
     [,1] [,2]
[1,]   80   90
[2,]   20   15

A chi-squared test of independence with the Yates
correction is as follows:
chisq.test(TAB)

        Pearson's Chi-squared test
        with Yates' continuity correction

data:  TAB
X-squared = 0.81215, df = 1, p-value = 0.3675

In R, prop.test compares proportions $80/100$ and
$90/105.$  A two-sided test is equivalent to the
chi-squared test above--if the 'continuity correction'
is used. Notice that the chi-squared statistic and the P-value are exactly the same. [The procedure prop.test gives more
detail.]
prop.test(c(80,90), c(100,105), cor=T)

        2-sample test for equality of proportions
        with continuity correction

data:  c(80, 90) out of c(100, 105)
X-squared = 0.81215, df = 1, p-value = 0.3675
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.16998808  0.05570236
sample estimates:
   prop 1    prop 2
0.8000000 0.8571429

For sufficiently large counts, Yates' correction is not
needed. (And in my opinion too conservative.) If parameter
cor=F is used to disable the correction, the chi-squared
test is as follows:
chisq.test(TAB, cor=F)

        Pearson's Chi-squared test

data:  TAB
X-squared = 1.1813, df = 1, p-value = 0.2771

Similarly, if cor=F is used, prop.test gives
the same test statistic and P-value as just above.
prop.test(c(80,90), c(100,105), cor=F)

        2-sample test for equality of proportions
        without continuity correction

data:  c(80, 90) out of c(100, 105)
X-squared = 1.1813, df = 1, p-value = 0.2771
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.16022617  0.04594046
sample estimates:
   prop 1    prop 2
0.8000000 0.8571429

Note: Simulated test statistics in case of expected counts
below 5, and the use of Fisher's exact test are interesting
topics, but have no direct connection with use or non-use of
the Yates correction.
Comment: R will do an expanded version of Fisher's exact test for matrices larger than the traditional $2 \times 2.$ Traditionally, Fisher's test on $2 \times 2$ tables has been used in case expected counts are so small that the validity of the chi-squared P-value is in doubt. Fisher's traditional test uses a hypergeometric distribution. Often it agrees with the chi-squared test. But there has been controversy about what Fisher's test is really testing. Generally, it is best to do **one** test (unless the chi-squared test is in doubt). I prefer the simulation option in R for the chi-squared test.
Comment: @ BruceET, I'm very grateful for your help, helping people without knowing them is very appreciated. Many thanks for your nice clarification.
Comment: In private you may want to fuss with various tests. However, professionally I think it is best to have and consistently use a 'favorite` test procedure. // Of course, it would be irresponsible to try various tests and report the one that is "significant" at the 5% level. Government approved protocols for clinical trials often require a decision in advance of taking data as to which tests will be used. Clinical trials seek to have enough subjects that small expected counts will not be an issue.
Comment: @ BruceET, I have so many significant results and I'm only afraid if it false positive that's why I want to be confident with what I got. I'm new to statistics world. thanks for guiding me.
Comment: Thank you for your detailed answer, its really appreciated. Can i do also fisher test and compare the results of the proportion test and the fisher test? all my data counts are above 5. Sorry if my question is dummy but I'm new to the statistics field. Many thanks for your help.
Answer: There are many opinions on how to best test for 2 x 2 contingency tables like this. Here the prop.test implements a chi-squared test. The issue is that in some cases data from a 2 x 2 contingency table isn't well approximated by the chi-squared distribution under the null. This can lead to p-values that are too small. Yates continuity correction adjusted for this but can lead to p-values that are too large.
There are other tests that you could use (Fisher's exact test being one) but another option in R is to simulate the distribution under the null and utilize this empirical distribution to calculate the p-value.
mat <- matrix(data = c(84, (99 - 84), 105.5, (146 - 105.5)), ncol = 2)

chisq.test(x = mat, correct = FALSE)

chisq.test(x = mat, correct = TRUE)

chisq.test(x = mat, simulate.p.value = TRUE)

Without the continuity correction, the p-value is 0.021. With the continuity correction, it's 0.031. Simulating the distribution produces a p-value of ~ 0.026. (One issue with this approach is that in R this simulation samples from a hypergeometric distribution which may not approximate your sampling situation.)
For other good threads on this see: Yates continuity correction for 2 x 2 contingency tables and Given the power of computers these days, is there ever a reason to do a chi-squared test rather than Fisher's exact test?
Comment: I can't speak to your particular situation as I don't know any of the particulars, but yes using the continuity correction is less likely to produce false positives. I'd personally favor the simulation approach except for the fact that in R the simulations works with fixed row and columns sums, which may not be an appropriate assumption in your case.
Comment: Hi @num_39. Thank you so much for answering my question, its really appreciated. So I understand from your answer is that to check the correct p-value I should perform a stimulation test as you did for ever data that I have and consider the stimulated p-value as the correct one?
Comment: Also, if I use continuity correction this means that I'm avoiding false positive results?


Botões pontudos e Balões de Texto

Question: Gostaria de saber algumas alternativas pra utilizar alguns button's customizados e também o famoso balão de texto. Atualmente eu uso uma

 que dentro tem o  e uma borda . Atualmente faço o desenho de um triângulo com o elemento #borda usando a propriedade border com uma cor transparent. Porém, acho bem custoso :'(
O objetivo é chegar nestes desenhos:

Como os tamanhos destes desenhos variam muito de acordo com o texto que há dentro dele, acredito que seja ruim usar background-image (ou não).
Como vocês implementam esses desenhos usando css?
Answer: Existe em pequeno "truque" usando as bordas no CSS o que nos permite fazer bordas triangulares.
Eu pessoalmente insiro essas bordas com :after ou :before.
Aqui vai um exemplo de como eu faria seus exemplos usando o que falei
HTML
Aqui criamos o nosso HTML, com duas divs para simular os balões de dialogo

CSS
E aqui vai a estilização necessária para eles
.balao{
    background: #000;
    border-radius: 0 30px 30px 0;
    width: 300px;
    height: 100px;

    /* Position relative para a seta não exceder os limites do balão, já que vamos usar position absolute nele */
    position: relative;

    margin-bottom: 1em;
}
.balao:after{
    /* content necessário para a criação de um elemento vazio */
    content: "";

    width: 0;
    height: 0;

    /* position: absolute para manipularmos a posição da seta */
    position: absolute;

    /* Right com valor negativo para ele ficar para fora do balão de dialogo */
    right: -32px;

    /* E aqui o truque com as bordas */
    /* 50px é a metade da altura do elemento, assim temos uma seta da mesma altura que nosso elemento */
    border-top: 50px solid transparent;
    border-bottom: 50px solid transparent;
    border-left: 50px solid #000;

    border-radius: 50%;

}
.balao2{
    background: #000;
    border-radius: 15px;
    width: 300px;
    height: 100px;

    position: relative;
}
.balao2:after{

    content: "";

    width: 0;
    height: 0;

    position: absolute;

    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #000;

    bottom: -20px;
    left: 20%;
}

Segue o exemplo no JSFiddle: http://jsfiddle.net/Wagner/m0qyayf7

.balao {
  background: #000;
  border-radius: 0 30px 30px 0;
  width: 300px;
  height: 100px;
  /* Position relative para a seta não exceder os limites do balão, já que vamos usar position absolute nele */
  position: relative;
  margin-bottom: 1em;
}

.balao:after {
  /* content necessário para a criação de um elemento vazio */
  content: "";
  width: 0;
  height: 0;
  /* position: absolute para manipularmos a posição da seta */
  position: absolute;
  /* Right com valor negativo para ele ficar para fora do balão de dialogo */
  right: -32px;
  /* E aqui o truque com as bordas */
  /* 50px é a metade da altura do elemento, assim temos uma seta da mesma altura que nosso elemento */
  border-top: 50px solid transparent;
  border-bottom: 50px solid transparent;
  border-left: 50px solid #000;
  border-radius: 50%;
}

.balao2 {
  background: #000;
  border-radius: 15px;
  width: 300px;
  height: 100px;
  position: relative;
}

.balao2:after {
  content: "";
  width: 0;
  height: 0;
  position: absolute;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #000;
  bottom: -20px;
  left: 20%;
}

Existem exemplos bem completos pela internet, e inclusive geradores automáticos para isso, basta fazer uma busca no Google por "css triangles"
Comment: http://pt.stackoverflow.com/questions/2394/criar-um-tri%C3%A2ngulo-com-css
Comment: A explicação ali está bem completa. Gostei! Eu conhecia o truque, mas não sabia como funcionava 100%, obrigado :)

Botões pontudos e Balões de Texto


Radon-Nikodym-derivative as a martingale

Question: At the beginning of all the stuff about Girsanov theorem, we introduced the Radon-Nikodym derivative as $Z_\infty := \frac{d \mathbb{Q}}{d \mathbb{P}}\vert_{\mathcal{F}_\infty}$.
Next, we considered the following:
\begin{align}
Z_t = \mathbb{E}[Z_\infty\vert\mathcal{F}_t]=\frac{d \mathbb{Q}}{d \mathbb{P}}\vert_{\mathcal{F}_t}.
\end{align}
So this last line does not seems so obvious for me. I do not understand the last equality. The conclusion is that the derivative is a martingale. Do I have to work with the definition of conditional expectation?
Answer: Let $(\Omega, \mathcal{F}_{\infty}, \mathbb{P})$ be a probability space and let $(B_t)$ be a standard Brownian motion with its natural filtration $(\mathcal{F}_t)_{t\geq 0}$. Let $\mathbb{Q}$ be a probability measure which is absolutely continuous w.r.t $\mathbb{P}$ on $(\Omega, \mathcal{F}_{\infty})$ then Radon-Nikodym theorem yields the existence of measurable function $Z_{\infty} =\left. \frac{d\mathbb{Q}}{d\mathbb{P}}\right|_{\mathcal{F}_{\infty}}$ (the Radon-Nikodym derivative).
Now define $Z_t = \mathbb{E}[Z_{\infty}|\mathcal{F}_t]$ we want to show that $Z_t$ is a martingale with respect to $\mathcal{F}_t$. Let $s \leq t$ then
$$\mathbb{E}[Z_t |  \mathcal{F}_{s}] = \mathbb{E}[\mathbb{E}[Z_{\infty}|\mathcal{F}_t] |  \mathcal{F}_{s}]$$
the tower property of conditional expectation yields that
$$\mathbb{E}[\mathbb{E}[Z_{\infty}|\mathcal{F}_t] |  \mathcal{F}_{s}] = \mathbb{E}[Z_{\infty}|\mathcal{F}_s]=Z_s.$$
Hence, $(Z_t)$ is a martingale.
Now we show that $Z_t = \left.\frac{d\mathbb{Q}}{d\mathbb{P}}\right|_{\mathcal{F}_t}$, indeed,
for any bounded $\mathcal{F}_t$-measurable function $f$ we have
\begin{align*}
\int_{\Omega}f \ d\mathbb{Q}=& \int_{\Omega} f Z_{\infty} \ d\mathbb{P} = \mathbb{E}_{\mathbb{P}}[fZ_{\infty}]\\=&\mathbb{E}[\mathbb{E}[fZ_{\infty} | \mathcal{F}_t]]= \mathbb{E}[f \mathbb{E}[Z_{\infty}|\mathcal{F}_t]] \\=& \mathbb{E}[fZ_t] = \int_{\Omega} fZ_t d\mathbb{P}.
\end{align*}
Hence, $Z_{\infty}d\mathbb{P} = Z_t d\mathbb{P}$ on $\mathcal{F}_t$ for each $t$.


Writing an abstraction layer for Playwright API

Question: We're starting to write E2E tests using Playwright in Typescript. Up until now, we were using Selenium and we wrote an a abstracation layer, or a a client, that wrapped each Selenium function that were used by our E2E test. You could see, in a simple search in Google, many different clients that different people have written to Selenium API.
However, I didn't find even a single client for Playwright and I wonder whether we should implement it or not? Maybe it's because that Playwright already provides a high-level API that is designed to be easy to use and understand.
Our main reasons for that are:

Improved reliability and Stability: Because Playwright wrappers can provide additional functionality, they can help to improve the reliability of automated tests. By making it easier to write tests that are less likely to fail, Playwright wrappers can help to ensure that tests provide accurate and consistent results.  i.e.: By using the Playwright function def fill(text: str), we can type a text into a text field. If we write a wrapper for this function that also waits, by default, until the text is displayed, we'll get more stable results. For that matter, Playwright provides async matches that will wait until the expected condition is met. Playwright encourages to do so, as specified in their documentation: these matchers allows making the tests non-flaky and resilient
Decoupling from Playwright's API: By using a client for Playwright, our test code interacts with the client's API rather than directly with Playwright's API. If Playwright undergoes significant changes or introduces breaking updates, we'll only need to update the wrapper to adapt to those changes. The rest of our test code remains unaffected, reducing the effort required to maintain your automation suite. i.e: Selenium introduced many breaking changes in version 4.0 in different functions and components. Luckily, since we're using a client that is wrapping Selenium API, the test code remained unaffected and we only needed to update the client.
Error Handling and Reporting: A wrapper can implement consistent error handling strategies and provide meaningful error messages when exceptions occur

And therefore, my question, would you recommened to write an abtraction layer over Playwright?
I've tried to find an implementation of an abtraction layer for Playwright in Google but didn't find anything.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: See this, it might be helpful- https://stackoverflow.com/a/76664504
Answer: I migrated a large number of e2e tests from selenium to playwright about a year ago. The migration was relatively painless exactly because I already used an abstraction layer in my selenium tests and mostly only had to migrate the layer itself. Based on my experience and assuming that Playwright will evolve by itself and there might be something else in the future I would strongly advice to keep your abstraction layer if possible. I personally use a hierarchy of generic, application specific and page specific page objects that are implemented as TypeScript classes that inherit from each as the abstraction layer. I hope this helps.
Comment: It is very helpful, thank you! Care to share in a few sentences  about the general picture of your architecture? I am strongly interested to understand whether you're also wrapping the elements that are being retrieved after Playwright finds them on the Page. Why? Because they also have functions, right? So you wrapped them also?
Comment: No, I'm not wrapping individual elements as my abstraction if much higher. I'm basically using a POM architecture with 3 page levels on its core: a generic page, a application specific page and the individual pages. This is combined with a large number of utility page components that abstract each component that must be tested.


Loading fully themed node with Ajax - Drupal 7

Question: I am loading node content to a specific div with Ajax. Is it possible to load a fully themed and rendered node (themed via page--node--1.tpl.php) with Ajax?
I have a custom module controlling my Ajax functions. From what I understand, the code below should be returning a fully themed node - but it is not doing so:
function ajax_reader_init() {
    drupal_add_js('misc/jquery.form.js');
    drupal_add_library('system','drupal.ajax');
}

/**
 * Implements hook_menu()
 */
function ajax_reader_menu() {
    $items['ajax-reader'] = array (
        'page callback' => 'ajax_link_response',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
    $output = _ajax_reader_load_noder($nid);
    if ($type == 'ajax'){
        $commands = array();
        $commands[] = ajax_command_replace('.main', '
'.$output.'
');
        $page = array(
            '#type' => 'ajax',
            '#commands' => $commands
        );
        ajax_deliver($page);
    } else {
        $output = '
'.$output.'
';
        return $output;
    }
}

function _ajax_reader_load_noder($nid = 0) {
    $node = node_load($nid);
    if($node) {
        $vnode = node_view($nid);
        return theme("node", $vnode);
    }
}

Answer: There is a contributed module Ajaxify Drupal with JQuery Ajax available for this. You can load any pages, nodes or anything to a div by using ajax without loosing css and ajax behaviour of loading content.

Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.
Comment: The module you suggested seems to be working, however the node being loaded is not themed via the matching tpl file. Any ideas?
Comment: I didn't get you. you can use node-contenttype.tpl.php to theme a particular type of node.


How do I count how many times element in a list are an exact match of another list - python

Question: I have two lists and want a count of how many times elements in a list are an exact match and are in the same position as another list. So for example:
list1 = [1,2,3,4]
list2 = [1,2,4,3]

would return 2.
I have the following code:
count = 0
def corrpos(list1, list2, count):
    if list1[0] == list2[0]:
            count = 1
    return count

this works to compare the first element, but I am unsure how to make it keep track for all the elements. Any tips?
Comment: you aren't returning `count`
Answer: You can make a list comprehension and calculate the number of elements of list1 that were present in list2 by using len():
print len([x for x in list1 if x in list2])

Your own code is also working, you would just have to return count (and change the input of the parameter correctly to list2):
return count

Comment: Or you could create sets: `print(len(set(list1).intersection(set(list2))))`.
Comment: If you want to calculate how many values are present in both list1 and list2 only you should use set indeed.
Answer: For the sake of completeness I will propose an answer using the built-in zip, so the last answer provided by @LMc could be rewritten as :
def corrpos(list1, list2):
    count = 0
    for elem1, elem2 in zip(list1, list2):
        if elem1 == elem2:
            count += 1
    return count

It didn't really provide something more, but zip allow you to iterate "in the same time" on two iterables and I guess this method is more intuitive than having to use the index of the elements from the first list to select those from the second list as in the example with enumerate.
Of course it can also be rewritten to be a oneliner as in the other answers :
def corrpos(list1, list2):
    return sum(1 for elem1, elem2 in zip(list1, list2) if elem1 == elem2)

or
def corrpos(list1, list2):
    return len([True for elem1, elem2 in zip(list1, list2) if elem1 == elem2])

Answer: Another way you could do this is see the intersection of these two lists using sets:
>>>set(list1) & set(list2)
set([1, 2, 3, 4])

Then you can just use the len function to get a count:
>>>len(set(list1) & set(list2))
4

Update:
Given that the elements have to be in the same index location, I would use a list comprehension:
def corrpos(list1,list2):
    return len([i for (c,i) in enumerate(list1) if list2[c]==i])

Here the enumerate function keeps track of the index location as you loop through list1 and can be used to look up the corresponding value in list2.
If you want to use a for loop, this can be rewritten as:
def corrpos(list1,list2):
    count=0
    for (c,i) in enumerate(list1):
        if list2[c]==i: count+=1
    return count


Using Fourier transforms to solve the boundary value problem

Question: Using Fourier transforms to solve the boundary value problem
$$ x =\begin{cases} u_{t}=4u_{xx}+\sin(t),  &  -\infty  \leq  x \leq \infty, t>0\\u(x,0)=e^{-x^2} \sin(x), & -\infty \leq x \leq \infty \end{cases}$$
I think I need to make the change $v=u-\cos(t)$. How to solve next?
Answer: You can solve by Fourier transforming in $x$. Or, you can work as Fourier did: First separate variables, form sums of solutions, and then isolate coefficients. As you say, start by subtracting $\cos(t)$. Then separate variables
$$
             T'(t)X(x) = 4T(t)X''(x) \\
             \frac{1}{4}\frac{T'(t)}{T(t)}= \lambda = \frac{X''(x)}{X(x)}.
$$
The parameter $\lambda$ must be negative in order to have bounded solutions in $X$, and that also gives decay in time rather than the opposite. So $\lambda=-s^2$ where $s$ is real.
$$
           X''(x)+s^2 X(x) = 0,\;\;\; T'(t)=-4s^2T(t) \\
            X(x)=e^{isx},\;\; T(t) = e^{-4s^2 t}.
$$
Then sum these solutions using an integral,
$$
               u(x,t) = \int_{-\infty}^{\infty}c(s)e^{-4s^2t}e^{isx}ds,
$$
where $c(s)$ are the coefficients in the sum, analogous to discrete sums. The coefficient function is determined by the initial condition
$$
              e^{-x^2}\sin(x) = \int_{-\infty}^{\infty}c(s)e^{isx}ds.
$$
Multiplying by $e^{-isx}$ and integrating gives $c(s)$
$$
            \frac{1}{2\pi}\int_{-\infty}^{\infty}e^{-x^2}\sin(x)e^{-isx}dx=c(s).
$$
The $1/2\pi$ is the standard normalization factor, essentially inherited from the discrete case. If you know the Fourier transform of $e^{-x^2}$, then you can reduce to that case
\begin{align}
      c(s) &=  \frac{1}{2\pi}\int_{-\infty}^{\infty}e^{-x^2}\frac{e^{ix}-e^{-ix}}{2i}e^{-isx}dx \\
      & = \frac{1}{4\pi i}\int_{-\infty}^{\infty}e^{-x^2}e^{-i(s-1)x}dx-\frac{1}{4\pi i}\int_{-\infty}^{\infty}e^{-x^2}e^{-i(s+1)x}dx.
\end{align}
You can look up the Fourier transform $\hat{f}(s)$ of $e^{-x^2}$. This gives the unknown coefficient function
$$
     c(s)=\frac{1}{\sqrt{2\pi}i}\{\hat{f}(s-1)-\hat{f}(s+1)\}
$$
The solution is then
$$
       u(x,t) = \frac{1}{\sqrt{2\pi}i}\int_{-\infty}^{\infty}\{ \hat{f}(s-1)-\hat{f}(s+1)\}e^{-4s^2 t}e^{isx}ds.
$$


Como trabalhar com vários codec's em pdf?

Question: Eu tenho um conjunto de mais de 1.000 PDFs que preciso extrair os metadados. O problema é que os PDFs tem codecs diferentes.
O primeiro exemplo deu certo, usei utf8. O segundo exemplo deu erro. É Python 3 o código:
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument

Primeiro exemplo, deu certo:
def decode_str(string):return string.decode("utf8")

fp = open('EMC 1-2017 PL678716 =- PL 6787-2016.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
dados_recuperados = doc.info[0]
author = decode_str(dados_recuperados.get("Author"))
subject = decode_str(dados_recuperados.get("Subject"))
creation_date = decode_str(dados_recuperados.get("CreationDate"))
mod_date = decode_str(dados_recuperados.get("ModDate"))

print (dados_recuperados)

Resultado -> {'Title': b'\xfe\xff\x00C\x00O\x00M\x00I\x00S\x00S\x00\xc3\x00O', 'Author': b'Ivanete de Araujo Costa', 'Subject': b'EMD ADI - Emenda Aditiva', 'Creator': b'\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x001\x000', 'CreationDate': b"D:20170314114321-07'00'", 'ModDate': b"D:20170314114321-07'00'", 'Producer': b'\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x001\x000'}

Segundo exemplo, deu erro:
def decode_str(string):
    return string.decode("utf8")

fp = open('EMC 4-2017 PL678716 =- PL 6787-2016.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
dados_recuperados = doc.info[0]
author = decode_str(dados_recuperados.get("Author"))
subject = decode_str(dados_recuperados.get("Subject"))
creation_date = decode_str(dados_recuperados.get("CreationDate"))
mod_date = decode_str(dados_recuperados.get("ModDate"))

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-21-4826dcab6968> in <module>()
      6 doc = PDFDocument(parser)
      7 dados_recuperados = doc.info[0]
----> 8 author = decode_str(dados_recuperados.get("Author"))
      9 subject = decode_str(dados_recuperados.get("Subject"))
     10 creation_date = decode_str(dados_recuperados.get("CreationDate"))

<ipython-input-21-4826dcab6968> in decode_str(string)
      1 def decode_str(string):
----> 2     return string.decode("utf8")
      3
      4 fp = open('EMC 4-2017 PL678716 =- PL 6787-2016.pdf', 'rb')
      5 parser = PDFParser(fp)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte

print (dados_recuperados)

Resultado -> {'Title': b'\xfe\xff\x00C\x00O\x00M\x00I\x00S\x00S\x00\xc3\x00O', 'Author': b'\xfe\xff\x00M\x00O\x00D\x00.\x00C\x00O\x00N\x00L\x00E\x00.\x00S\x00T\x00 \x002\x001\x003\x000\x00/\x002\x000\x001\x007\x00 \x00-\x00 \x00P\x00_\x006\x007\x003\x006\x00 \x00-\x00 \x00D\x00a\x00v\x00i\x00 \x00R\x00i\x00b\x00e\x00i\x00r\x00o\x00 \x00d\x00e\x00 \x00O\x00l\x00i\x00v\x00e\x00i\x00r\x00a\x00 \x00J\x00\xfa\x00n\x00i\x00o\x00r', 'Subject': b'EMD ADI - Emenda Aditiva', 'Creator': b'\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x001\x000', 'CreationDate': b"D:20170314114344-07'00'", 'ModDate': b"D:20170314114344-07'00'", 'Producer': b'\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x001\x000'}

Há uma forma de transformar o dados_recuperados = doc.info[0] em um codec padrão? Ou testar antes de pegar a string para saber que codec usar?
Comment: Transformar em um codec padrão? O que é codec padrão? Padrão da sua aplicação? O que você quer é detectar o codec e ver se é necessário decodificar de UTF8, então se o PDF for utf-8 decodifica para Latin, se não mantém como esta, seria isso?
Comment: Não são malucos, são diferentes codecs se misturando, tem que definir qual é o codec padrão do teu programa python que esta usando (definindo no `charset` do cabeçalho do script python geralmente) para então assim eu poder saber qual é o padrão que deseja, como eu já perguntei no comentário anterior: *O que você quer é detectar o codec e ver se é necessário decodificar de UTF8, então se o PDF for utf-8 decodifica para Latin, se não mantém como esta, seria isso?*
Comment: Isso não são "malucos", são "escapes", espera um pouco que eu já te digo como resolver isso, tem um link no site sobre isso.
Comment: Olá, obrigado. Sim, é isso. Mas veja que o metadado do segundo exemplo aparece um conjunto de caracteres maluco. Mas quando abro no Acrobat o metadado aparece. Então acho que também preciso saber qual é este codec do segundo caso.
Comment: Por exemplo, o campo author: print(author)
b'\xfe\xff\x00M\x00O\x00D\x00.\x00C\x00O\x00N\x00L\x00E\x00.\x00S\x00T\x00 \x002\x001\x003\x000\x00/\x002\x000\x001\x007\x00 \x00-\x00 \x00P\x00_\x006\x007\x003\x006\x00 \x00-\x00 \x00D\x00a\x00v\x00i\x00 \x00R\x00i\x00b\x00e\x00i\x00r\x00o\x00 \x00d\x00e\x00 \x00O\x00l\x00i\x00v\x00e\x00i\x00r\x00a\x00 \x00J\x00\xfa\x00n\x00i\x00o\x00r'
Answer: O que você quer é na verdade ler vários tipos de codificações e converte-las todas para a codificação que você esta usando no teu script python, provavelmente deve esta usando algo compatível com latin1, então recomendo que antes de qualquer coisa você defina o padrão no teu script, pois se rodar esse mesmo script em outra máquina talvez o padrão no terminal ou cmd seja totalmente diferente.
Você pode definir um padrão que desejar, vamos imaginar que você só deseja usar utf-8, então adicione isto no teu .py no topo:
# -*- coding: utf-8 -*-

Se deseja usar somente latin1 adicione isto:
# -*- coding: latin1 -*-

Então voltando, como eu disse, você provavelmente quer converter qualquer tipo de codificação para a codificação do sistema atual, no caso esse link já ajuda https://stackoverflow.com/a/15918519/1518921, o script é assim:
Adicione isto no topo do seu script:
import sys
import cchardet

Se não tiver o modulo cchardet instalado basta baixar em https://pypi.python.org/pypi/cchardet

E crie esta função
def str_decode(str):
    # Verifica qual o codec do sistema atual (codec "padrão")
    defaultcodec = sys.getdefaultencoding().lower()

    codec = cchardet.detect(str)['encoding']

    if (defaultcodec != codec.lower()):
        return str.decode(codec) # Se o codec for diferente do sistema atual então decodifica
    else:
        return str # Se o codec for o do sistema atual então mantêm

Deve ficar assim:
dados_recuperados = doc.info[0]
author = str_decode(dados_recuperados.get("Author"))
subject = str_decode(dados_recuperados.get("Subject"))
creation_date = str_decode(dados_recuperados.get("CreationDate"))
mod_date = str_decode(dados_recuperados.get("ModDate"))

Note que no tr.decode(codec) o valor de codec é o obtido via cchardet.detect(str)['encoding'], deve funcionar bem, mas não há garantias de que o documento PDF esta usando apenas um codec, ou que as strings esteja 100% corretas, podem haver documentos com problemas, mas isto é relativo.
Se você tiver definido o # -*- coding: xxxxxxx -*- então pode ajustar a função para:
# Verifica qual o codec do sistema atual (codec "padrão")
defaultcodec = xxxxxxx

O xxxxxxx seria o codec que deseja como padrão.
Comment: @ReinaldoChaves Importa o modulo `sys`. Vou editar a resposta
Comment: @ReinaldoChaves pronto editado, também expliquei aonde pode baixar o `cchardet` se não tiver em teu sistema.
Comment: Muito obrigado. Deu esse erro:
Comment: ----> 3     defaultcodec = sys.getdefaultencoding().lower()
      4
      5     codec = cchardet.detect(str)['encoding']

NameError: name 'sys' is not defined
Comment: Obrigado! Eu instalei cchardet antes. Deu certo quase tudo certo. Agora descobri que alguns campos dos metadados estão vazios em alguns PDFs, vou tentar criar um if para isso


C#: ASP.NET Web-Messenger (Chat)

Question: i programmed a Chat-Program like ICQ with C# and WCF.
Now i want to build a Web-Client-Version with ASP.NET.
Is this possible? I want that new chatrooms-popup in the window like meebo (or in a new tab).
I have to use the Client-WebService-Class from my WCF-service, right? But is it possible to react on server-side Events with ASP.NET?
New messages, new chatroom-invitations, chat events like "user goes online/offline" should be handled dynamically by the site without refresh-actions from the user.
Are there some tutorials?
Comment: I too would like some insite.
Answer: I don't think there's anything in the current technology that allows a server to refresh a browser client.  So you're not going to get something that's server-initiated to update the client (unless you're using Silverlight).
Most answers to this question have suggested that you regularly poll your server for any changes to the conversation and update the output in javascript.  Here's one from CodeProject.  Googling for ASP.NET chat or MVC Chat produces similar results.

C#: ASP.NET Web-Messenger (Chat)


Setup for evaluating $\iint_R y^2dA$

Question: $\iint_R y^2dA$, where D is the triangular region with vertices $(0,1)$, $(1,2)$, $(4,1)$.
I was trying to do this problem, and ended up with the wrong answer, $\frac{28}{13}$, instead of the correct answer of $\frac{11}{3}$. I checked my integrations on symbolab and those where coming out right, so it seems like maybe my bounds for the integrals were wrong. I got $D={(x,y)| 0<=x<=4,1<=y<=2}$ And integrated with respect to $x$, and then $y$. Is that correct? I did I figure those wrong?
Answer: Let's convert the double integral to an iterated integral with integration order $dxdy$, since the region is horizontally simple.
$R$ is bounded above by the line $x=7-3y$ and below by $x=y-1$ from $y=1$ to $y=2$. Thus the integral becomes:
$$\iint_R y^2dA=\int_1^2 \int_{y-1}^{7-3y}y^2dxdy=\int_1^2y^2x\Big{|}_{y-1}^{7-3y}dy=\int_1^28y^2-4y^3dy.$$
I trust that you can take it from here? If not, please tell me.
Comment: I found the lines which represent the vertices of the triangles by normal methods. That is, I wrote the equation of the line which connects $(0,1)$ and $(1,2)$ and the equation of the line which connects $(1,2)$ and $(4,1)$. Then, I solved those for $x$, because that is what I choose to integrate w.r.t first.
Comment: How did you get the $7-3y$ and $y-1$ for x?

Setup for evaluating $\iint_R y^2dA$


Distância entre uma linha e um ponto no espaço tridimensional

Question: Digamos que existam três pontos num espaço 3D (pontos A, B e P). Digamos também que existe uma reta que passa por A e B.
O que eu estou tentando fazer, na verdade, é descobrir se uma reta AB intercepta uma esfera de raio r que tem origem em P. Para isso eu só preciso checar se a distância da reta AB e do ponto P é menor que o raio da esfera.
Vector A, B, P; //A minha classe Vector, guarda três valores (x, y e z)

if(distance(A, B, P) < r){
   return sphere.color;
}

O meu problema é este método distance(Vector A, Vector B, Vector C)... Como eu posso calcular a distância de um ponto até uma reta (dada dois pontos da mesma), sendo que eu tenho que escrever isto em JAVA?

A distância entre um ponto e uma reta, é o comprimento de uma semirreta que começa em P, e termina na reta AB, formando um ângulo de 90 graus com a mesma.

Descobrir a distância entre um ponto e uma reta, desenhando por exemplo, é relativamente fácil, apenas traçar uma reta saindo do ponto até a outra reta e medir o tamanho.
Em 2D, isso seria fácil, já que a reta D (a distância) forma um triângulo retângulo, sendo a hipotenusa o vetor V que representa a posição do ponto P, e o cateto adjacente é este mesmo vetor projetado (que eu não sei o comprimento) na reta AB.
Desta forma eu poderia calcular a reta D, já que eu tenho meios de descobrir todos os três ângulos do triângulo (um deles é um ângulo reto, e o outro é a diferença dos ângulos da reta AB e o vetor V, e o terceiro completa 180 graus com os outros), eu posso usar o único lado que eu tenho o valor (a hipotenusa) e calcular o cateto oposto.
Acontece que eu estou trabalhando num ambiente tridimensional, onde não é tão simples achar um ângulo entre a reta AB e o vetor V para completar o triângulo. Além disso, eu não sou matemático, e sim programador, então eu queria um método de descobrir isso usando expressões algébricas (e métodos em Java), em vez de técnicas geométricas, de forma que funcionasse pra qualquer reta e ponto. Afinal a escrita matemática não é fácil de se converter em código de fato.
Por último, eu fiz esta postagem aqui, porque eu posso estar tentando achar a distância de um jeito desnecessariamente complicado, ou simplesmente errado.
Desde já, obrigado.
Comment: No caso da expressão, não me parece relacionado a programação, você pode perguntar neste outro site do Stack Exchange: [Mathematics](https://math.stackexchange.com/).
Comment: @Sorack É relacionado a programação sim: aparentemente ele quer utilizar a função para resolver o problema mas não sabe como. Aparenta não saber usar a matemática e a função em Java em conjunto. Estou cogitando que esteja tendo dificuldades para identificar o problema. Talvez encaixe mais em um [problema XY](https://pt.meta.stackoverflow.com/a/1202/839) do que o sugerido por você. Ele deve ter se encurralado na programação e achou que deveria perguntar como criar uma expressão algébrica em Java. Perguntou X (como fazer) mas disse que o problema é Y (a função). Vejo muito isso ao lecionar.
Comment: @Sorack Me perdoe se foi o que pareceu, mas eu não tenho intenção nenhuma de que _façam todo meu trabalho._ Eu irei editar a pergunta, para incluir mais detalhes de minhas reflexões sobre o assunto.
Comment: Me parece que você nem tentou criar uma solução, não procurou qual seria a expressão algébrica e nem tentou implementar nada do problema. Uma dica que eu te dou é: quebre os eu problema em parte de acordo com a teoria envolvida e traga apenas as partes que você não conseguiu resolver depois de tentar arduamente. Um outra dica é que leia o material: [**Manual de como NÃO fazer perguntas** - Achar que nós faremos o seu trabalho todo de graça](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5486#5486).
Comment: Depois de ver a resposta aceita, acredito que o @Sorack esteja correto. O texto dava a entender o contrário mas a resposta aceita aponta que a pergunta deve ser movida para o [Mathematics](https://math.stackexchange.com/), de fato.
Comment: Perguntas em português são aceitas no Mathematics? Se sim, a pergunta deveria ser movida. Se não, não vejo o problema de uma pergunta de um programador ser originária de um problema matemático. Quanto a resposta, alguém deveria edita-la usando Java (Meu Java está tão enferrujado que duvido que consiga produzir um código correto). Já recebi respostas em Matlab para perguntas em Python. Quanto ao edit na resposta original: matemática é essencial e talvez acelere seu tempo de desenvolvimento dar uma estudada no básico, principalmente algebra linear.
Comment: Se o problema fosse na implementação em Java estaria no [escopo do site](/help/on-topic), o que claramente não é o caso dada a resposta aceita. O fato de não ter um site específico para matemática em português por si só não faz com que o assunto passe a ser aceito aqui (assim como futebol, culinária e outros).
Answer: "Digamos que existam três pontos num espaço 3D (pontos A, B e P). Digamos também que existe uma reta que passa por A e B."
O que eu estou tentando fazer, na verdade, é descobrir se uma reta AB intercepta uma esfera de raio r que tem origem em P. Para isso eu só preciso checar se a distância da reta AB e do ponto P é menor que o raio da esfera.
Logo, o que você quer descobrir é, dado uma reta R = [x,y,z]t + [a,b,c] (da uma olhada aqui pra saber como escrever a equação. Você quer saber se ||R - P|| <= r
E resposta dessa inequação te da "t" onde a reta e esfera se interceptam, é de segunda ordem. Se houverem soluções reais a interseção existe, se não, não existe.
Comment: Discordo. Em alguns pontos programação e matemática estão relacionados, mas uma definitivamente não é a outra.
Comment: e aqui é um local para problemas de programação não matemática
Comment: E onde entra o Java nisso?
Comment: O problema dele é matemático e não Java.
Comment: Programação é matemática
Comment: Verdade, relacionar com igualdade é incorreto. O relacional correto seria contido
Comment: Mas uma das tags da pergunta é matemática, dar uma solução matemática é valido para a pergunta. Mas o local de perguntar ideal seria Mathematics, mas esse é o um fórum em inglês e achei que seria mais empático da minha parte dar a solução aqui mesmo.
Comment: Opinião como usuário e não como moderador: não vejo problema em ajudar o colega (muitas vezes faço isso, mas geralmente posto como wiki da comunidade ou em um site a parte tipo pastebin, quando é fora do escopo). Mas é importante entender o risco de tomar um negativo (que por acaso não é meu). Considerando que ele tira muito pouco da pontuação, acho que se a intenção é ajudar, é um preço válido a se pagar pelo problema do escopo. O mais importante mesmo é o fechamento da pergunta, assim o site não fica bagunçado, mas o autor nao sai sem solução.
Comment: Sobre o fato de ter a tag matemática, segue trecho do wiki da própria tag: _Quaisquer questões de matemática neste site devem ser relacionadas com a programação_
Comment: A pergunta é relacionada com programação. Problemas com programação podem surgir tanto de sintaxe, convenções e implementação quanto de lógica e matemática. Ainda assim achei a questão válida. E o preço é justo desde que o colega consiga resolver o problema dele.
Comment: o problema que eu tinha, que já foi resolvido, era que apesar de entender o assunto que eu estava tratando, na geometria, eu não conseguia imaginar ele dentro de um contexto de programação -- no caso em Java.

tipo, eu só tinha que desenhar uma linha que caisse na outra linha de forma perpendicular. Mas isto não significa nada pra mim sendo programador, e foi com isso que eu pedi ajuda. esta resposta em questão, nem foi tão definitiva (afinal ele me respondeu com uma verificação matemática _||R - P|| <= r_ mas a partir disso eu consegui construir o meu método.
Comment: Além disto, eu fiz uma pergunta parecida em um fórum de matemática, sobre coordenadas esféricas, que no fim se relacionava a programação, e lá recebi muitas críticas sobre exatamente isto. Por isso vim fazer esta pergunta aqui.

Até porque o motivo de eu querer uma forma numérica de representar o produto escalar que eu acabei usando, é porque eu tive que usar em Java, com programação.

Não existe nenhum modo de eu simplesmente escrever `vetor1.projetar(vetor2)`, eu tive que converter a explicação matemática do assunto e converter em código Java -- que foi  justamente o meu problema.


How to render text including video embed field

Question: I have a formatted text field, and am using the video_embed module to allow users to embed video into that field, using the video_embed_wysiwyg submodule.
I am then trying to render the field in a block, but I simply get the JSON output in the text field:

{"preview_thumbnail":"/sites/default/files/styles/video_embed_wysiwyg_preview/public/video_thumbnails/A5jNGsBHHUE.jpg?itok=7fW8O9To","video_url":"https://www.youtube.com/watch?v=********","settings":{"responsive":1,"width":"854","height":"480","autoplay":1},"settings_summary":["Embedded
Video (Responsive, autoplaying)."]}

Here is my render array:
$text=check_markup($node->get('field_html_containing_video_content')->value, $node->get('field_html_containing_video_content')->format);

    $renderArray=[
      'content'=>[
        '#type'=>'inline_template',
        '#template'=>$text
      ]
    ];

    return $renderArray;

I've got the video embed filter enabled on the relevant text format, and have tried changing the order of the filters.
Any ideas what i am doing wrong here?
We are using a bootstrap subtheme.
Thanks for any help given.
Answer: check_markup() is not able to handle attached metadata which some text filters need to work properly.
You have to use the render element processed_text:
$renderArray = [
  'content' => [
    '#type' => 'processed_text',
    '#text' => $node->field_html_containing_video_content->value,
    '#format' => $node->field_html_containing_video_content->format,
  ],
];

More info How to safely render node body on a custom variable?
Comment: Thanks 4k4 - much aprpeciated (and sorry for the slow answer acceptance and reply)