Why does Java compiler refuse to recognize System.exit() as a procedure termination?

Question: Java's compiler, at least the one from Oracle that I use, refuses to recognize System.exit() as a procedure termination. For example, the following code gives a compilation error:
public static int readInteger( ArrayList<String> listLines, int iLineNumber0 ){
    try {
        int value = Integer.parseInt( listLines.get( 0 ) );
        return value;
    } catch( Throwable t ) {
        System.err.println( "error reading line: " + iLineNumber0 + ": " + t );
        System.exit( -1 );
    }
}

The error is: "Missing return statement." Therefore, to make this work I have to add in a return statement like this (compiles successfully):
public static int readInteger( ArrayList<String> listLines, int iLineNumber0 ){
    try {
        int value = Integer.parseInt( listLines.get( 0 ) );
        return value;
    } catch( Throwable t ) {
        System.err.println( "error reading line: " + iLineNumber0 + ": " + t );
        System.exit( -1 );
    }
    return 0; // unreachable code
}

Ironically, the final return statement that is needed is unreachable code, although the compiler does not realize this either.
Comment: Because it's not -- it's simply a method call, indistinguishable from any other call.
Comment: You could also `return value` only after the `catch`, eliminating the need for another return statement, but that'd look weird in its own way, I suppose.
Comment: You can alter/redefine System.exit() or use a SecrutiyManager to prevent a program exiting.  It is not specified in the language what System.exit() must do.
Comment: You could do `throw new Error()` after the `exit`.  That will make the compiler happy and is actually sort of meaningful.
Comment: Or simply `throw t;`.
Answer:
Java's compiler, at least the one from Oracle that I use, refuses to recognize System.exit() as a procedure termination.

Yes, it would. As far as the compiler is concerned, it's just a void method. There's no way of indicating "this method never returns normally" in a method signature, and no such concept in the language. For example:
public void alwaysThrow()
{
    throw new RuntimeException();
}

...

alwaysThrow();
System.out.println("This line is never reached");

The last line in the above snippet is still reachable as far as the compiler is concerned, even though we know it will never execute. Likewise your extra return statement is technically reachable, but practically unreachable.
Basically this could be deemed a flaw in the language, although it's one which affects most languages as far as I'm aware. While it would be nice to be able to represent methods like this, it's rarely a real issue in real life.
If you find yourself bothered by it, you could write a helper method:
public RuntimeException systemExit(int exitValue)
{
    System.exit(exitValue);
    return new RuntimeException("Shouldn't get here");
}

Then call it as:
throw systemExit();

That will ensure that the end of the statement is unreachable as far as the compiler is concerned, so you could have:
catch (Throwable t) {
    System.err.println("error reading line: " + iLineNumber0 + ": " + t);
    throw systemExit(-1);
}

... and your compiler error would go away.
Note that there are other similar situations where reachability isn't everything we might want. For example:
int foo() {
    int x = someValue();
    if (x > 10) {
       return 1;
    }
    if (x <= 10) {
       return 20;
    }
    // Is this reachable or not?
}

We know that any value of x will either be greater than 10 or less-than-or-equal-to 10, so the final line is practically unreachable but the rules of the language don't express that... so even a smart compiler can't actually treat the above code as valid without violating the language specification.
Comment: @Absurd-Mind: A smart compiler could detect it, but it couldn't treat it as valid Java code, because it's simply *not* valid by the Java specification.
Comment: Can you explain why a smart compiler could not detect the unreachable code in your last example? I think this should be fairly easy using static code analysis.
Answer: Consider this: you've loaded a different runtime library whose System.exit does not exit. Now what will happen at the end of the method? The compiler would rather have a concrete answer about this, so it doesn't make any special assumptions about System.exit (or Runtime.exit).
If it did, this would only add complications to the language specification for no real benefit. Exit calls are not common, and indeed, your code is not a good example of using one, because even if it did not require the unreached return statement, it still hides the original exception that caused the problem. I would replace the println/exit calls with:
throw new RuntimeException("Error reading line " + iLineNumber0, t);

When an exit call is really needed in a non-void method, it is easy to add a throw null; or throw new Error(); or return ...; below it.

Ironically, the final return statement that is needed is unreachable code, although the compiler does not realize this either.

This feature can't be added as it would break existing code.
Answer: error is not because of System.exit() code but method expects return value in catch but syetm.exit return type is void.
complete scenario explanation.
Any method if it expects return value, then method should return a value under all possible circumstances and that too only one return should come in all situations.
But in your first case
you have put return only on try but not on catch, so it is complaining as expected return statement. because there is no return when exception occurs and its caught under that catch block.
in your second case,
you have put return at try and outside try/catch. then return becomes unreachable code because try is already having return, so it should not have more than one return because after try one more return which is illegal in java.
so solution
put return in try and catch both but not outside try/catch.
or
put return directly outside try and catch.
solution 1 program
public static int readInteger( ArrayList<String> listLines, int iLineNumber0 ){
 int value = 0;
    try {
        value = Integer.parseInt( listLines.get( 0 ) );
        return value;
    } catch( Throwable t ) {
        System.err.println( "error reading line: " + iLineNumber0 + ": " + t );
        System.exit( -1 );
     return value;
    }
}

solution 2 program
public static int readInteger( ArrayList<String> listLines, int iLineNumber0 ){
 int value = 0;
    try {
        value = Integer.parseInt( listLines.get( 0 ) );
        //return value;
    } catch( Throwable t ) {
        System.err.println( "error reading line: " + iLineNumber0 + ": " + t );
        System.exit( -1 );
    // return value;
    }
return value;
}

let me know for any doubts.
Answer: You could return your value outside the try-catch block:
public static int readInteger( ArrayList<String> listLines, int iLineNumber0 ){
    int value = 0;

    try {
        value = Integer.parseInt( listLines.get( 0 ) );
    } catch( Throwable t ) {
        System.err.println( "error reading line: " + iLineNumber0 + ": " + t );
        System.exit( -1 );
    }

    return value;
}


Solution trajectories of a plane autonomous system

Question: I have the plane autonomous system
$\dfrac{dx}{dt}=x(1-2x-y)$
$\dfrac{dy}{dt}=y(1-x-2y)$
I need to show that the axes of the phase plane and the line $x=y$ are solution trajectories, but I don't know how to do this.
The other part of the question is as follows.
Use the Bendixson-Dulac theorem with $phi=\dfrac{1}{xy}$ to show that there are no closed trajectories in $R=\{(x,y):x>0, y>0\}$ . (I've done this bit) Comment on whether you can prove that there are no periodic functions in the entire phase plane including the origin.
For the last part, I have plotted the phase plane and there are no closed trajectories but how can i prove the last bit properly?
Thanks for any help.
Comment: Still interested in an answer?
Answer: The first part of this question is trivial. The axes of the phase plane correspond to $x=0$ and $y=0$. On substituting $x=0$ in the first equation, we get $\frac{dx}{dt} = 0$. i.e the particle stays on the $y$-axis. Similarly for the $x$-axis.
For $x=y$ line, we find that $\frac{dx}{dt} - \frac{dy}{dt} = 0$. i.e. $v_x = v_y$ and hence, the particle continues on the line.
I am trying the last part of your problem.
Answer: To apply the Bendixson-Dulac criteria we should calculate for a suitable $\phi(x,y)$
$$
\psi(x,y)=\frac{\partial}{\partial x}\left(\phi(x,y)\dot x\right)+\frac{\partial}{\partial y}\left(\phi(x,y)\dot y\right)
$$
and then verify if $\psi(x,y)$ changes sign into the quadrant $Q=\{(x,y),x>0,y>0\}$.
Choosing $\phi(x,y) = x^my^n$ we obtain
$$
\psi(x,y) = x^m y^n (y (m+2 n+5)+2 m x+m-n x+n+3 x+2)
$$
and then choosing again $m=-\frac{11}{5},n=-\frac 75$ we get
$$
\psi(x,y) = -\frac 85
$$
which obviously doesn't changes sign into $Q$. Concluding, there are not closed trajectories inside $Q$.


Função attr jquery não funciona

Question: Criei a função attr em jquery mas não esta pegando qual seria o motivo?

    aaaaaaaaaaaaa

Comment: Não fico claro qual é o resultado esperado.
Comment: Não ficou claro o que está tentando fazer @Josimara. O que seria pegando? Para obter o valor do atributo, o segundo argumento na função é desnecessário, e não existe a propriedade `itemprop` em `teste`.
Answer: O elemento ainda não existe na ordem que você chamou, para checar se a página já foi completamente renderizada use $.ready(function() {...}) ou simplesmente $(function() {...}) (é um atalho para .ready)

    aaaaaaaaaaaaa

Como o elemento foi criado somente depois de executar a função o jQuery não tem como encontrar, um exemplo de teste:
Não funciona, retorna zero (0):

    aaaaaaaaaaaaa

Se você usar onload ou DOMContentLoaded (mais rápido) ou $.ready (equivale ao DOMContentLoaded) então eles irão colocar a função para esperar a página ser carregada, um teste, retorna um (1):

    aaaaaaaaaaaaa

Função attr jquery não funciona


Filtrar tabelas a serem mapeadas pelo Doctrine a partir do EntityManager (sem linha de comando)

Question: Estou desenvolvendo uma funcionalidade na minha aplicação que consiste em mapear e  gerar entidades automaticamente.
O problema é que o usuário pode selecionar as tabelas que deseja mapear, por isso, devo inserir um filtro com o nome das tabelas a serem convertidas. Para fazer isto em linha de comando basta inserir o parâmetro --filter conforme o exemplo abaixo:
php doctrine orm:convert-mapping --from-database --force --filter='class_name' xml /path_to_app/entities/metadata

Porém estou desenvolvendo esta funcionalidade em minha aplicação visando obter o retorno de um possível erro, utilizando a biblioteca do doctrine esctrita em PHP. Por isso estou criando a função abaixo que realiza o mapeamento de todas as tabelas para xml (prefiro neste formato), e posteriormente cria as entidades a partir do mapeamento. Entretanto não sei como filtrar o nome das tabelas que desejo mapear, ou seja, inserir a funcionalidade realizada pelo parâmetro --filter='class_name'.
public function mapearTabelasValidar() {

        //Inicializa variáveis
        $dirBin = DIR_THIRD_PARTY . 'composer/vendor/bin/';
        $dirEntidades = DIR_MODELS . 'entidades/';
        $dirMetadados = $dirEntidades . 'metadados/';
        $title = 'Modelos gerados com sucesso!';

        try {

            //Inicializa o Doctrine e a configuração do EntityManager
            $doctrine = new Doctrine();
            $em = $doctrine->em;
            $em->getConfiguration()->setMetadataDriverImpl(
                    new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
                    $em->getConnection()->getSchemaManager()
                    )
            );

            //Define os metadados
            $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
            $cmf->setEntityManager($em);
            $metadata = $cmf;

            /**
             * Exporta os metadados das entidades em format xml
             *
             * Comando similar:
             * php doctrine orm:convert-mapping --from-database --force xml /var/www/fwsibe/sistema/models/entidades/metadados
             */
            //echo "
";
            //print_r($metadata);
            //die();
            $cme = new \Doctrine\ORM\Tools\Export\ClassMetadataExporter();
            $exporter = $cme->getExporter('xml', $dirMetadados);
            $exporter->setMetadata($metadata->getAllMetadata());
            $exporter->export();

            /**
             * Gera as entidades a partir do mapeamento XML gerado anteriormente
             *
             * Comando similar:
             * php doctrine orm:generate:entities --generate-methods=1 --update-entities=1 /var/www/fwsibe/sistema/models/entidades
             */
            $generator = new \Doctrine\ORM\Tools\EntityGenerator();
            $generator->setGenerateStubMethods(true);
            $generator->setRegenerateEntityIfExists(false);
            $generator->generate($metadata->getAllMetadata(), $dirEntidades);

            //Trata a possível exeção
        } catch (Exception $exc) {
            mensagemExcecao($exc, "Falha ao mapear tabelas!", true);
        }
    }

Alguém teria alguma sugestão?
Answer: você pode tentar usar a classe MetadataFilter conforme o próprio comando disponível no projeto do Doctrine utiliza, no seu código ficaria mais ou menos assim:
...
$filter = 'string de entidades filtradas';
$metadata = MetadataFilter::filter($metadata, $filter);
$exporter->setMetadata($metadata);
...

não se esqueça de importar a classe usando a diretiva use.


Updating a taxonomy term, with extra fields - taxonomy_term_update does not exist

Question: In Drupal 7, I am trying to update and delete some taxonomy terms in the proper way. So, instead of attacking the database directly, I am using taxonomy_term_delete for deleting by tid. However I cannot find taxonomy_term_update and about taxonomy_term_save, it seems not to have access to the extra fields that I added (a few fields, text and integer).
How can I make the following pseudocode to work? ( this does not pretend to work, it is just some pseudocode in a dialect of Drupal to make the question more understandable )
 $term = taxonomy_term_load ( $tid )   // or equivalent function
 $term->extra_field_1 = 23; // extra_field_1 would be numerical
 taxonomy_term_save($term) // o taxonomy_term_update or equivalent

Result: the extra_field_1 value of that term ( with tid = $tid ) is set to 23.
Answer: try
    $terms = taxonomy_term_load($tid);
    // echo "
";
    // print_r($terms);
    // die();
    //dsm($terms);
    $terms->extra_field_1[LANGUAGE_NONE][0][$column_name] = 23;
    taxonomy_term_save($terms);

Use print_r or dsm(devel module if installed) and check the "$column_name".
After print the $terms you able to get "$column_name" replacement. Update that and save.
Comment: Thanks, I was obfuscated and believed that it was not possible, because in the doc there was no reference to the extra fields. Now I saw them as you suggested. May I suggest to use LANGUAGE_NONE instead of "und", it is something I sometimes see in the replies. Thank you very much.
Comment: Yes right. You welcome :)


Any tool recommendation for WCAG 2.0 validation?

Question: I believe everyone now a days is working hard to make web pages WCAG 2.0 compliant. Can you share any good tool for the same that you have come across?
Here are some good tools that I came across-
1.
http://www.powermapper.com/products/sortsite/index.htm
Advantages:
1. It does WCAG 2.0, WCAG 1.0, browser compatibility and many other checks
2. Low cost

Disadvantage:
1. it seems it doesn't have command line API.(as per my initial evaluation)
2. Web mode doesn't support HTML upload

2.
http://achecker.ca/checker/index.php
Advantages:

Free!!!
Supports WCAG 2.0
Has web service API

Disadvantages:

Web service API doesn't support HTML file upload. It expects that the HTML file is deployed somewhere on web
Comment: "I believe everyone now a days is working hard to make web pages WCAG 2.0 compliant." everyone? have you used any of the websites out there lately?
Comment: Is it not? ok,then read it as "everyone should be working hard"...
Comment: You can try Mauve Accessibility validator ( http://hiis.isti.cnr.it:8080/MauveWeb/  ).

Advantages:

1) Free
2) Supports WCAG 2.0 (and Stanca act).
3) Support validation throught URL, HTML file upload and direct html input.
Answer: I used to work for a company that produces a free Chrome and Firefox extension that tests against accessibility standards including WCAG 2.0, based on an open source accessibility testing library.
Slightly nervous as this might be viewed as promotion but I don't work there any more.  I will delete this answer if this is frowned upon.
Axe Chrome Extension
Axe Firefox Extension
axe-core Github Repository
Comment: @Leo - they now do an open source tool called axe-core .... github.com/dequelabs/axe-core
Comment: This addon looks good. Thanks for sharing.
Comment: No problem.  Let them know if you have any criticism or comment.  Surprised no other answers to the question.  Feel free to reward the answer with accepting it - i'm working on my reputation :-)
Comment: Looks like @Wooble is right.. Not many people are working on WCAG compliance
Comment: What does "free" mean? Is this plugin open source and GPL, or?
Comment: @Leo - no free does not imply open source at all, it is a copyrighted, commercial product. It is freely downloadable and usable as a stand alone tool - we sell a server product associated with it, which acts as a issue management tool, and can also be used to spider large websites for accessibility issues.  The license agreement for the browser extension is available on the website, if it doesn't suit your needs for an open source tool then fair enough.
Comment: Ok, thanks @iandotkelly. Yes, I prefer an open source tool. It gives me the ability to enhance it.


Which distributions cannot be captured using this representation of the joint probability?

Question: Reading through Probabilistic Graphical Models, I came across this definition along with an accompanying statement.

Let $P(x_i) = \theta_i$.
Define:
$$P(x_1, \ldots , x_n) = \prod_{i=1}^n \theta_i$$
This representation is limited, and there are many distributions that
  we cannot capture by choosing values for $\theta_i, \ldots, \theta_n$.
  This fact is obvious not only from intuition, but also from a somewhat
  more formal perspective. The space of all joint distributions is a $2^n - 1$
  dimensional subspace of $\mathbb{R}^{2^n}$ - the set $\{ (p_1, \ldots , p_{2^n}) \in \mathbb{R}^{2^n} : p_1 + \cdots + p_{2^n} = 1 \}$ .

It is not obvious or intuitive to me that there are many distributions that cannot be captured by choosing values for $\theta_i, \ldots, \theta_n$. What sort of distribution could not be captured this way? One with continuous values?
Comment: Every non-product measure. Example: $P(x,y)=(x+y)/4$ for every $x$ and $y$ in $\{0,1\}$.
Comment: Assume that $P(x,y)=\theta_x\theta_y$ for every $(x,y)$ in $\{0,1\}$ then $\theta_0^2=(0+0)/4=0$, $\theta_0\theta_1=(0+1)/4=1/4$ and $\theta_1^2=(1+1)/4=1/2$, contradiction. And yet $P$ is a legitimate probability distribution on $\{0,1\}\times\{0,1\}$ since $\sum\limits_{x,y}P(x,y)=0/4+1/4+1/4+2/4=1$.
Comment: @Did thanks for the reply. Unfortunately I seem to be missing some sort of foundational understanding of this. I do not know what I should be asking myself to see why this cannot be captured. Why is this the case?
Comment: OK I think I understand. When you state that $P(x, y) = (x + y)/4$, it can easily be shown (as you did) that it contradicts the original definition $P(x_1, \ldots, x_n)$. That's all there is to it?
Answer: Any distribution that has correlation between some variables should suffice to give a counter-example. For example, consider the classical family of Gaussian/normal distributions whose probability density function is proportional to $e^{-x^T K^{-1} x}$ for a positive definite symmetric matrix $K$ and vector of variables $x$. Just through basic matrix computations, it's fairly easy to see that you cannot represent this distribution in your graphical model form (as a product of marginal distributions as you described) unless $K$ is a diagonal matrix. This also contributes to the secondary comment that the number of degrees of freedom for a distribution is greater than for a product distribution you described, because obviously you have a lot more degrees of freedom (dimensionality) in specifying a positive definite matrix than just specifying a positive diagonal matrix.
Comment: It is going to take me some time to digest this answer, but I have a few immediate thoughts. I do not fully understand what it means for the probability density function to be proportional to $e^{-x^TK^{-1}x}$. Or rather, why is that important? Is it because that density function would not exist in $\mathbb{R}^{2^n}$ for a positive definite symmetrix matrix $K$? I can see that if $K$ is a diagonal matrix, then the probability density function is in $\mathbb{R}^n$. Is this correct?


Apache randomly stops at night with no errors in logs

Question: I have a server on AWS that has been stable for years.  It's running Apache 2.2.22 on Ubuntu 12.04.5 LTS.  I regularly run security updates at the top of the month.
Recently Apache has stopped serving requests at around midnight and sometimes at later times in the early morning (2-4 AM Central).  For us this is a period of low use but we do still have a steady stream of requests.  Our daytime activity is much higher and it never goes down during the day (so far at least).  So far, it always comes up after about 10 minutes or so and is always back to normal in the morning.  Because of the time of the issue, I don't suspect it has to do with MaxClients as several other threads suggest.
I see nothing in any of the apache error logs (we have around 10 virtual hosts) nor dmesg, nor syslog.  In fact, I read every log in /var/log this morning.  At the time of the issue, I see nothing happening.
I have been able to catch it when it's down because of a site monitor notification.  During that time, I can verify that apache is not serving requests.  I can shell in to the server though.  I had suspected network issues but it's odd that one port is fine and another isn't.  I have been able to confirm that apache won't serve requests from localhost at that server.  So, it seems to not be hardware.
Restarting the apache service does bring the sites back up but only for a few minutes.  I was tailing logs live when it went down and still nothing.  Not a thing shows in any log at the time of the issue.  Rebooting always seems to fix it (for at least another 24 hours and sometimes more).
Amazon support sees nothing wrong with the server.  I suspect either Apache is failing and the service restart isn't clean.  Or, something is going on at the kernel/network level of the OS.  And, again, this always happens when CPU load is low.  Memory looks okay.  None of the "usual suspects" are happening.  It just silently stops working.
Given the lack of information I have from the server, I have no idea what else to look for.  I am leaning towards rebuilding the server next week but would really like to figure this out.
Maybe there's something else I should look at during the problem.  Also, if there are any logs I "turn up" to get more info, let me know.  Currently I have no logs I can post that are helpful.  This whole thing seems crazy to me because I'm used to failures getting logged somehow, especially if it's apache or the kernel (we've been long-time friends).
Answer: I'd suggest next time you start it, start an strace running so that after it dies you can investigate what calls were happening last before it failed.  You can use the following command after you start it to make sure you attach to the master process and all its children and any new ones that get forked.
<code>pidlist=''; for pid in `ps ax | grep httpd | awk '{print $1}'`; do pidlist="$pidlist -p $pid"; done; strace -tt -F -f $pidlist 2>&1 |tee /root/apache_strace.out
</code>
I don't know if on your distro if the Apache process is called httpd or something else (like apache or apache2), but if it's not httpd, then swap the correct name into the command above.


Wildcard mapping for ASP.NET and issues with PHP

Question: I have an application written in .NET 3.5 with C# as the language. I'm using Web Forms, but using url routing with the routes defined in my global file. Everything is working as expected. In order for the pretty paths (see: user/665 instead of user.aspx?uid=665) to work properly, I had to add a wildcard mapping in IIS5.1 (local box, not test, staging, or production) the aspnet_isapi file for the 2.0 framework. Everything works fine.
Now, my site needs a plugin for PHP. However, the PHP files are now being serviced by ASP.NET due to the wild card mapping, and hence are not processed by the PHP interpretter. Is there any way to get around this? Would I have to add some sort of handler to my web app that will take all PHP requests being handled by the ASP.NET framework and have them routed to the PHP engine? Is there an easier way? Maybe a way to exclude them in the web.config (PHP files) and have them served by the proper PHP engine?
Thanks all!
-Steve
Answer: This is a solution, but is not an elegant way (IMHO):

Create a virtual directory
Have it point to the folder with the files (in this case, a PHP plugin)
Give it the proper permissions
Change the config options for the virtual directory in IIS and make sure the wildcard mapping for that directory is removed.

This works like a charm for my situation. However, is there any way to not have to deal with virtual directories?
Answer: The problem is that the PHP extension needs to be registered.

In IIS Manager right-click on Default Website -> Properties -> Home Directory -> Configuration
Under Application Mappings make sure that .php is added and is it pointing to PHP.EXE.  There should be an entry like this: extension .php, executable path C:\PHP\PHP.EXE %s %s
Answer: From what I gather, the problem is that ASP.NET is attempting to route your PHP requests, so what I would do is add a StopRoutingHandler() to your routes in the global.asax.  Something like this should work:
<code>routes.Add(new Route("{resource}.php/{*pathInfo}", new StopRoutingHandler()));
</code>
Edit:  Be mindful that routes are processed in order, so I would add this to the top of your routes.
Comment: Awesome. Let me give this a go and I'll get back to you.
Comment: No go. I'm guessing what happens is that the PHP file is not being serviced by the PHP interpretter and is handed off to ASP.NET due to the wild card mapping. The global.asax files puts up a StopRoute, and the PHP file just falls on its face. I need the PHP files to be serviced by the PHP engine some how.


Interface vs Class - visibilidade de métodos

Question: Eu fiz um trabalho para a escola e está a funcionar na perfeição.
No código tenho alguns métodos privados. Preciso de criar uma Interface dessa class para esconder esses métodos privados ou podem ficar na mesma class dos métodos públicos?
Neste momento tenho todos os métodos (públicos e privados) na mesma classe, mas o meu colega de grupo está a insistir que tem que criar uma Interface para esconder os métodos privados.
Comment: Seu colega está viajando. Seus métodos privados já estão... privados.
Comment: Ele insite que é preciso. Para esconder os métodos privados da class Main
Comment: Depende de quem você quer esconder, se você quer esconder da própria classe você precisa colocá-los em outra classe, mas não em uma interface pois elas não possuem implementação. Poste um [exemplo Mínimo, Completo e Verificável](http://pt.stackoverflow.com/help/mcve) para que possamos entender o que está acontecendo. Além do mais, não é possível criar um método privado em uma interface.
Comment: O trabalho funciona como deve ser e já fiz uma submissão e passou. Agora estamos só a tentar melhora-lo. O meu colega é que insiste numa Interface para os metodos privados
Comment: Amigo, se o método é privado nenhuma outra classe consegue invocá-lo (por meios "normais"). Não tem porque deixá-lo "mais escondido". Que argumento ele está usando como justificativa?
Comment: Está a dizer que "as Interfaces servem para esconder os métodos privados da main. Que são regras de Programação Orientada a Objectos."
Comment: @msm.oliveira Seguinte, se seu método `main` está na própria classe, ou se sua classe é **interna** à classe que contém a `main`, então nada vai impedir a `main` de acessar seus membros privados. Caso contrário, não é preciso fazer nada. Interfaces servem para desacoplar a "especificação" (contrato) da "implementação", não tem nada a ver com esconder membros privados (pois como disse o Math, se são privados, são privados, e ponto).
Comment: Tenho a classe Main que é a que vai interagir com o utilizador, neste caso, a consola. E tenho a classe Zombies onde está o algoritmo e as contas necessárias para o programa correr como deve ser. O programa está feito e a funcionar a 100%, o meu colega diz é que se deve por a interface por causa dos metodos privados
Answer: Interfaces nada mais são que classes puramente abstratas. Ou seja, classes que não possuem membros definidos (i.e. não impõem nenhum detalhe de implementação), e todos os seus métodos são públicos e abstratos (i.e. estabelecem um contrato que a classe implementadora deve oferecer ao código consumidor). Por essa razão, uma referência a uma interface não tem acesso a nenhum membro privado da classe concreta.
Entretanto, essa é uma condição suficiente para esconder os membros privados, mas não necessária - é perfeitamente possível se obter encapsulamento sem user interfaces. O encapsulamento por private somente não se aplica à própria classe (obviamente, pois a classe precisa ter acesso aos seus próprio campos!) e - no caso de uma classe ser interna à outra (inner class) - à classe "de fora".
Aqui está um exemplo do que está e do que não está encapsulado em várias situações:
class Main {
    private int podeAcessar;

    interface IInterna { }

    abstract class InternaAbstrata {
        private int podeAcessar2;
    }

    class Interna extends InternaAbstrata implements IInterna {
        private int podeAcessar3;
    }

    public static void main(String[] args) {
        Main a;            // pode acessar os campos privados

        Interna b;         // pode acessar os campos privados
        InternaAbstrata c; // pode acessar os campos privados
        IInterna d;        // NÃO pode acessar os campos privados

        Externa e;         // NÃO pode acessar os campos privados
        ExternaAbstrata f; // NÃO pode acessar os campos privados
        IExterna g;        // NÃO pode acessar os campos privados
    }
}

interface IExterna { }

abstract class ExternaAbstrata {
    private int naoPodeAcessar;
}

class Externa extends ExternaAbstrata implements IExterna {
    private int naoPodeAcessar2;
}

Como pode ver no exemplo acima, essa afirmação que "... tem que criar uma Interface para esconder os metodos privados" está incorreta, pois tanto no caso de Externa quanto de ExternaAbstrata o encapsulamento ocorre mesmo sem o uso de interfaces.


Why are effective divisors on $\mathbb{P}^n$ positive?

Question: I'm reading Griffiths and Harris, Principles of algebraic geometry, and it's written that

"any effective nonzero divisor on $\mathbb{P}^n$ is positive"

on page 159. Is that obvious? There doesn't seem to be any explanation in the book.
Here, a divisor is called positive if the associated line bundle has a hermitian metric whose curvature form is positive.
I know that hyperplane divisors are positive since they induce the Fubini-Study metric, but I'm not sure how to deal with a general irreducible hypersurface.
Comment: No problem. Of course, it's not literally true that every $V_i$ is linearly equivalent to a hyperplane section, but a multiple of a hyperplane section.
Comment: Do you know what the effective divisors on $\mathbb{P}^n$ look like and, more importantly, when two are equivalent?
Comment: @AlexYoucis The book defines an effective divisor on $\mathbb{P}^n$ to be a finite sum $\sum_i a_iV_i$ where $a_i \in \mathbb{Z}_{\ge 0}$ and $V_i$ are irreducible complex-analytic subvarieties. They are "linearly equivalent" if they induce the same line bundle, or equivalently, if they differ by the divisor of a global meromorphic function.
Comment: The problem reduces to showing that if $V$ is an irreducible hypersurface, then the line bundle associated to $V$ is positive.
Comment: Are you saying that every irreducible hypersurface is linearly equivalent to a hyperplane?
Comment: @AlexYoucis Oh, that's actually true and is discussed on p. 145. Thanks for your comment, that was really helpful!
Answer: Just to get this off the unanswered list.
As mentioned in the original post, an effective divisor $D$ on $\mathbb{P}^n$ is a finite sum $\displaystyle \sum_i a_i V_i$ where $a_i\in\mathbb{Z}^{\geqslant 0}$ and $V_i$ are irreducible subvarieties of $\mathbb{P}^n$. We call such a divisor positive if the associated line bundle $\mathcal{O}(D)$ has a Hermitian metric with positive curvature. It's easy to see that if $D_1,\ldots,D_m$ are positive then so is $D_1+\cdots +D_m$.
So, to see that every effective divisor on $\mathbb{P}^n$ is positive it suffices to show that every divisor of the form $V$ is positive where $V$ is a closed analytic submanifold. But, by Chow's theorem we know that $V=V(f)$ where $f$ is a homogenous polynomial in $n+1$-variables of degree $d$. But, one can quickly check by hand that $V(f)$ is then equivalent to $dH$ where
$$\mathbb{P}^{n-1}\cong H:=\{[0:z_1:\cdots:z_n]\}\subseteq \mathbb{P}^n$$
So, by our above observations it suffices to show that $H$ is positive. But, this is clear.
One can also verify the claim that every $V$ is linearly equivalent to a multiple of $H$ without appealing to Chow's theorem as follows. We know that the line bundles on $\mathbb{P}^n$ are classified by $H^1(\mathbb{P}^n,\mathcal{O}^\times)$. But, by the exponential sequence
$$0\to \underline{2\pi i\mathbb{Z}}\to \mathcal{O}\to \mathcal{O}^\times\to 0$$
we get the exact sequence
$$H^1(\mathbb{P}^n,\underline{2\pi i\mathbb{Z}})\to H^1(\mathbb{P}^n,\mathcal{O})\to H^1(\mathbb{P}^n,\mathcal{O}^\times)\to H^2(\mathbb{P}^n,\underline{2\pi i \mathbb{Z}})\to H^2(\mathbb{P}^n,\mathcal{O})$$
But,
$$H^i(\mathbb{P}^n,\underline{2\pi i \mathbb{Z}})\cong H^i_\text{sing}(\mathbb{P}^n,\mathbb{Z})=\begin{cases} \mathbb{Z} & \mbox{if}\quad i\in\{0,2,\ldots,2n\}\\ 0 & \mbox{if}\quad \text{otherwise}\end{cases}$$
and
$$H^i(\mathbb{P}^n,\mathcal{O})=\begin{cases} \mathbb{C} & \mbox{if}\quad i=0\\ 0 & \mbox{if}\quad \text{otherwise}\end{cases}$$
from where we see that
$$\mathrm{Pic}(\mathbb{P}^n)\cong H^1(\mathbb{P}^n,\mathcal{O}^\times)\cong H^1(\mathbb{P}^n,\underline{2\pi i \mathbb{Z}})\cong \mathbb{Z}$$
call the map
$$H^1(\mathbb{P}^n,\mathcal{O}^\times)\to H^2(\mathbb{P}^n,\underline{2\pi i\mathbb{Z}})\cong \mathbb{Z}$$
the 'Chern class map' and denote it by $c$. What the above shows is that a line bundle on $\mathbb{P}^n$ is entirely determined by its Chern class.
Now, it's not hard to directly check that $c(\mathcal{O}(H))=1$ and in general $c(\mathcal{O}(D))>0$ if $D$ is effective (just think about the cycle class map) from which case it follows that $\mathcal{O}(D)\cong \mathcal{O}(H)^{c(\mathcal{O}(D))}$ or, in other words, $D\sim c(\mathcal{O}(D))H$ (where $\sim$ denotes equivalence).
Comment: I was about to comment on the non-necessity of Chow's theorem, but you just gave a very nice and complete discussion. Thanks!


Generating a general term for a taylor polynomial

Question: Let $f$ be the function given by $$ f\left(x\right) = \sin\left(5x +\frac{ \pi }{4}\right)$$ Let $P\left(x\right)$ represent Taylor polynomial of $f$ centred at $x =0$. Generate the general term for $P\left(x\right)$
My Solution: $$f'\left(x\right)=5\cos\left(5x +\frac{ \pi }{4}\right) = \frac{5}{\sqrt{2}}$$
$$f''\left(x\right) =-25\sin\left(5x +\frac{ \pi }{4}\right) = -\frac{25}{\sqrt{2}}$$
$$f'''\left(x\right)-125\cos\left(5x +\frac{ \pi }{4}\right) = -\frac{125}{\sqrt{2}}$$
From here I can see that the signs alternate every two terms. I know that for a series in which the sign alternates every term I simply use $\left(-1\right)^n$ as sign representation. However, in this case I am at a loss. Would this series even be considered alternating?
For my general term I have $$\frac{5^nx^n}{\sqrt{2}n!}$$ but I do not know how to deal with the sign. Any advice? Thank you!
Answer: The simplest and most understandable way to deal with the sign is just to use cases:
$$
f^{[n]} (0) \frac{x^n}{n!}
=
\begin{cases}
(-1)^{n/2} \dfrac{5^nx^n}{\sqrt{2}n!} & \text{if } n \text{ even} \\
(-1)^{(n-1)/2} \dfrac{5^nx^n}{\sqrt{2}n!} & \text{if } n \text{ odd}
\end{cases}
$$
You can also use the floor function:
$$
(-1)^{\lfloor n/2\rfloor} \dfrac{5^nx^n}{\sqrt{2}n!}
$$
Comment: Ah thank you! I never considered using the piecewise function
Answer: Hint: It is easier use the identity
$$ \sin t = \frac{1}{2i}( e^{it} - e^{-it} ).$$


Evaluation of Complex Integral With Figure-eight Contour Using Cauchy Integral Formula

Question: I want to Evaluate
$$\int_C \frac{3z+1}{z(z-2)^2} dz$$
Where C is the above figure-eight contour.
To solve this problem, I split up the given contour $C$ into two simple closed contours $C_1$ and $C_2$. $C_1$ denotes the right-handed closed curve, that has the point $z=2$ inside it, and $C_2$ denotes the left-handed closed curve, that has $z=0$ inside it.
Then,
$$\int_C \frac{3z+1}{z(z-2)^2} dz = \int_{C_1} \frac{3z+1}{z(z-2)^2}dz- \int_{C_2} \frac{3z+1}{z(z-2)^2} dz$$
$C_2$ is clockwise or negatively oriented, so that is why I am subtracting the $C_2$ contour integral.
$$\int_{C_{1}} \frac{3z+1}{z(z-2)^2} dz = \int_{C_{1}} \frac{(3z+1)/z}{(z-2)^2} dz$$
I let $f(z) = (3z+1)/z$ which is analytic inside and on $C_1$ since the singularity point $z=0$ is exterior to $C_1$. $z_0=2$ is interior to $C_1$, and thus by Cauchy Integral Formula,
$$\int_{C_1} \frac{3z+1}{z(z-2)^2} dz = \int_{C_1} \frac{(3z+1)/z}{(z-2)^2} dz = 2\pi if'(2) = -\pi i/2$$
since $f'(z) = -1/z^2$.
For $C_2$ integral I also used Cauchy Integral formula except with $f(z) = (3z+1)/(z-2)^2$ which is analytic on and inside $C_2$. Furthermore, $z_0 = 0$ is interior to $C_2$.
Thus, $$\int_{C_{2}} \frac{3z+1}{z(z-2)^2} dz = \int_{C_{2}}\frac{(3z+1)/(z-2)^2}{z-0}dz = 2\pi if(0) = \pi i/2$$ since $f(0) = 1/(-2)^2 = 1/4$
Thus,
$$\int_C \frac{3z+1}{z(z-2)^2} dz = -\pi i/2 -\pi i/2 = -\pi i$$
I just want to check if my solution and method are correct for this problem. Thanks!
Comment: Looks awesome to me!
Comment: Great, thank you!
Answer: So the winding number about $2$ is $+1$ whilst the winding number around $0$ is $-1$ thus we have
\begin{align}
\int_C \frac{3z+1}{z(z-2)^2}dz&=2\pi \bigg((1)\frac{d}{dz}(\frac{3z+1}{z})\bigg\vert_{z=2}+(-1)\frac{3z+1}{(z-2)^2}\bigg\vert_{z=0} \bigg)\\
&=2\pi i (-\frac{1}{4}-\frac{1}{4})\\
&=-\pi i
\end{align}
which is what you got as well!!


Findall usando ElementTree não retorna resultado esperado

Question: Estou tentando achar um elemento específico dentro de um arquivo XML em python. Para isso, uso o ElementTree.
O seguinte código:
    root = ET.fromstring(response.content.decode('utf-8'))
    print(root.findall('.//*'))

Me dá como retorno a seguinte tabela:
[<Element '{http://schemas.xmlsoap.org/soap/envelope/}Header' at 0x000002034CB3B908>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}ServerVersionInfo' at 0x000002034CB16BD8>,
<Element '{http://schemas.xmlsoap.org/soap/envelope/}Body' at 0x000002034CB16CC8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/messages}ResolveNamesResponse' at 0x000002034CB16E08>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseMessages' at 0x000002034CB169F8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/messages}ResolveNamesResponseMessage' at 0x000002034CB16AE8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseCode' at 0x000002034CB59548>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/messages}ResolutionSet' at 0x000002034CB59598>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Resolution' at 0x000002034CB595E8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Mailbox' at 0x000002034CB59638>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Name' at 0x000002034CB59688>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress' at 0x000002034CB596D8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}RoutingType' at 0x000002034CB59728>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}MailboxType' at 0x000002034CB59818>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Contact' at 0x000002034CB59868>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Culture' at 0x000002034CB598B8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}DisplayName' at 0x000002034CB59908>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}GivenName' at 0x000002034CB59958>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Initials' at 0x000002034CB599A8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}CompanyName' at 0x000002034CB599F8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddresses' at 0x000002034CB59A48>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59A98>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59AE8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59B38>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}PhysicalAddresses' at 0x000002034CB59B88>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59BD8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Street' at 0x000002034CB59C28>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}City' at 0x000002034CB59C78>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}State' at 0x000002034CB59CC8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}CountryOrRegion' at 0x000002034CB59D18>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}PostalCode' at 0x000002034CB59D68>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}PhoneNumbers' at 0x000002034CB59DB8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59E08>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59E58>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59EA8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59EF8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59F48>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Entry' at 0x000002034CB59F98>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}AssistantName' at 0x000002034CBA2048>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}ContactSource' at 0x000002034CBA2098>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Department' at 0x000002034CBA20E8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}JobTitle' at 0x000002034CBA2138>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Manager' at 0x000002034CBA2188>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}OfficeLocation' at 0x000002034CBA21D8>,
<Element '{http://schemas.microsoft.com/exchange/services/2006/types}Surname' at 0x000002034CBA2228>]

Eu preciso encontrar qual o valor do elemento '{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress'
Para tal, fiz o seguinte:
teste = root.findall('{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress')
print(teste)

Pelo que li, isso deveria funcionar sem problemas. Mas o que é retornado é um array vazio. Alguém tem alguma ideia do que estou fazendo errado?
EDIT:
XML Completo (sem as informações):
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Header>
      <h:ServerVersionInfo xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" MajorVersion="15" MinorVersion="1" MajorBuildNumber="669" MinorBuildNumber="32" />
   </s:Header>
   <s:Body xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <m:ResolveNamesResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
         <m:ResponseMessages>
            <m:ResolveNamesResponseMessage ResponseClass="Success">
               <m:ResponseCode>***</m:ResponseCode>
               <m:ResolutionSet TotalItemsInView="1" IncludesLastItemInRange="true">
                  <t:Resolution>
                     <t:Mailbox>
                        <t:Name>***</t:Name>
                        <t:EmailAddress>***</t:EmailAddress>
                        <t:RoutingType>***</t:RoutingType>
                        <t:MailboxType>***</t:MailboxType>
                     </t:Mailbox>
                     <t:Contact>
                        <t:Culture>***</t:Culture>
                        <t:DisplayName>***</t:DisplayName>
                        <t:GivenName>***</t:GivenName>
                        <t:Initials />
                        <t:CompanyName>***</t:CompanyName>
                        <t:EmailAddresses>
                           <t:Entry Key="EmailAddress1">***</t:Entry>
                           <t:Entry Key="EmailAddress2">***</t:Entry>
                           <t:Entry Key="EmailAddress3">***</t:Entry>
                        </t:EmailAddresses>
                        <t:PhysicalAddresses>
                           <t:Entry Key="Business">
                              <t:Street>***</t:Street>
                              <t:City>***</t:City>
                              <t:State />
                              <t:CountryOrRegion>***</t:CountryOrRegion>
                              <t:PostalCode>***</t:PostalCode>
                           </t:Entry>
                        </t:PhysicalAddresses>
                        <t:PhoneNumbers>
                           <t:Entry Key="AssistantPhone" />
                           <t:Entry Key="BusinessFax" />
                           <t:Entry Key="BusinessPhone">***</t:Entry>
                           <t:Entry Key="HomePhone" />
                           <t:Entry Key="MobilePhone">***</t:Entry>
                           <t:Entry Key="Pager" />
                        </t:PhoneNumbers>
                        <t:AssistantName />
                        <t:ContactSource>***</t:ContactSource>
                        <t:Department>***</t:Department>
                        <t:JobTitle />
                        <t:Manager>***</t:Manager>
                        <t:OfficeLocation>***</t:OfficeLocation>
                        <t:Surname>***</t:Surname>
                     </t:Contact>
                  </t:Resolution>
               </m:ResolutionSet>
            </m:ResolveNamesResponseMessage>
         </m:ResponseMessages>
      </m:ResolveNamesResponse>
   </s:Body>
</s:Envelope>

Comment: Pode colocar o arquivo XML completo ?
Comment: Editei a pergunta e adicionei o XML.
Answer: Procure pelo atributo Tag de cada elemento, que vai ter o namespace do xml e o nome da tag. Daí, basta verificar se a tag tem como substring EmailAddress e não EmailAddresses. Se isso acontecer, encontramos a TAG do email e basta extrair o texto.
for el in root.findall('.//*'):
        if el.tag.find('EmailAddress') != -1 and el.tag.find('EmailAddresses') == -1 :
            print(el.text)

Essa solução:
root.findall('{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress')

Não vai funcionar porque EmailAddress não é um elemento filho de root. Você precisaria colocar todos os namespaces e tags até chegar em EmailAddress para esse método funcionar.


Python datetime process

Question: I am using Pandas to process my data, and my data is looks like this:
>>> df = pandas.read_sql('select * from my_table', conn)
>>> df

     time_list       open      close       mkt_cap
0   2007-01-04   4.261631   4.104547  2.745555e+10
1   2007-01-05   4.052185   3.799105  2.541244e+10
2   2007-01-08   3.796196   3.889283  2.601564e+10
3   2007-01-09   3.895101   4.014369  2.685235e+10
4   2007-01-10   4.011460   4.095820  2.739718e+10
5   2007-01-11   4.124909   4.299447  2.875925e+10
6   2007-01-12   4.395443   4.514710  3.019916e+10
7   2007-01-15   4.508892   4.741609  3.171690e+10
8   2007-01-16   4.799789   4.951055  3.311789e+10
9   2007-01-17   4.945237   4.951055  3.311789e+10
10  2007-01-18   4.930692   4.706702  3.148340e+10
11  2007-01-19   4.712520   4.930692  3.298169e+10
12  2007-01-22   4.977235   5.166318  3.455780e+10
13  2007-01-23   5.090685   5.265223  3.521938e+10
14  2007-01-24   5.236133   5.151773  3.446051e+10
15  2007-01-25   5.177954   5.061595  3.385731e+10
16  2007-01-26   5.294312   5.314675  3.555017e+10
17  2007-01-29   5.497940   5.579391  3.732087e+10
18  2007-01-30   5.855742   5.858651  3.918886e+10
19  2007-01-31   6.103004   5.564846  3.722358e+10
20  2007-02-01   5.399035   5.369945  3.591988e+10
21  2007-02-02   5.288494   5.102321  3.412972e+10
22  2007-02-05   5.032506   4.855059  3.247577e+10
23  2007-02-06   4.855059   5.096503  3.409080e+10
24  2007-02-07   5.352492   5.352492  3.580313e+10
25  2007-02-08   5.352492   5.556119  3.716520e+10
26  2007-02-09   5.576482   5.349583  3.578367e+10
27  2007-02-12   5.340856   5.617207  3.757383e+10
28  2007-02-13   5.817926   5.719021  3.825486e+10
29  2007-02-14   5.783018   5.977919  3.998665e+10
..         ...        ...        ...           ...
87  2007-05-21   8.101461   8.101461  5.419115e+10
88  2007-05-22   8.101461   8.101461  5.419115e+10
89  2007-05-23   8.101461   8.101461  5.419115e+10
90  2007-05-24   8.101461   8.101461  5.419115e+10
91  2007-05-25   8.505807   8.505807  5.689584e+10
92  2007-05-28   8.866519   8.319634  5.565051e+10
93  2007-05-29   8.430174   8.366177  5.596185e+10
94  2007-05-30   7.947286   7.947286  5.315986e+10
95  2007-05-31   7.857109   8.345814  5.582564e+10
96  2007-06-01   8.345814   8.345814  5.582564e+10
97  2007-06-04   8.345814   8.345814  5.582564e+10
98  2007-06-05   8.345814   8.345814  5.582564e+10
99  2007-06-06   8.345814   8.345814  5.582564e+10
100 2007-06-07   8.345814   8.345814  5.582564e+10
101 2007-06-08   8.345814   8.345814  5.582564e+10
102 2007-06-11   8.345814   8.345814  5.582564e+10
103 2007-06-12   8.345814   8.345814  5.582564e+10
104 2007-06-13   8.345814   8.345814  5.582564e+10
105 2007-06-14   8.345814   8.345814  5.582564e+10
106 2007-06-15   8.345814   8.345814  5.582564e+10
107 2007-06-18   8.345814   8.345814  5.582564e+10
108 2007-06-19   8.345814   8.345814  5.582564e+10
109 2007-06-20  10.562415   9.983083  6.508599e+10
110 2007-06-21  10.383174  10.981711  7.159668e+10
111 2007-06-22  11.394605  11.330591  7.387125e+10
112 2007-06-25  11.525835  11.266576  7.345389e+10
113 2007-06-26  11.266576  11.266576  7.345389e+10
114 2007-06-27  10.139918  10.312758  6.723535e+10
115 2007-06-28  10.082305   9.647006  6.289490e+10
116 2007-06-29   9.538181   8.808414  5.742759e+10

And for the column close I want to get the value of the first day and the last day of every month, and the first day is not Jan 1st on the dataframe, for Jan, it's 2007-01-04, and the last day is not the day on the calendar, is the day on the dataframe. And for March the first day maybe 0302, and the last day maybe 0328.
It's really tough for me cause the first day and the last day are hard to get since you can not get them from calendar, and I am new to Pandas, So, I just need your help. You can post your code or just write down your ideas on how to solve it.
Comment: Alternatively, you can fix your SQL statement to do this before calling it from Python and `pandas`.
Answer: groupby is your solution. Let's create an vector from your dates with month information only, and then use groupby. As the name says, you then have a group of data all with the same month. Finally you aggregate by choosing the first or the last of the group.
key = [x.strftime("%Y%m") for x in df["time_list"]]
open_month = df.groupby(key, as_index=False).first()
close_month = df.groupby(key, as_index=False).last()

Python datetime process


how to control the Animation with touchesMoved or other

Question: i have some pictures, they will show one by one when my finger moved on the screen of ipad,if my finger stoped,the stop at once,i use the following code in touchesMoved function
if (j>1199) {
        j=1000;
    }
    else {
         NSString *imgPath=[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d",j] ofType:@"png"];
         show360img.image=[UIImage imageWithContentsOfFile:imgPath];
        j;
    }

but it doesn't work well,so how can i control this Animation?thanks a lot
Comment: @sergio it does not run smoothly
Answer: j is not been incremented.
increment j and try the code
if (j>1199) {
    j=1000;
}
else {
     NSString *imgPath=[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d",j] ofType:@"png"];
     show360img.image=[UIImage imageWithContentsOfFile:imgPath];
   j++;
}


Qual é a maneira correta de enviar um formulário para uma controller via AJAX?

Question: Tenho um formulário simples, que é basicamente minha ViewModel. Estou fazendo um post via AJAX passando este formulário, porém, no lado do servidor, tudo sempre está null. Meu AJAX é o seguinte:
var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { viewModel: formData },
    success: function (data) {
        // meu callback
    }
});

Eu havia lido em uma pergunta no SO em inglês, que o problema poderia ser o contentType, por isso coloquei esse 'application/x-www-form-urlencoded; charset=UTF-8'. Porém, meu problema persiste. No lado do servidor, eu recebo ela simplesmente:
[HttpPost]
public ResultadoAjax Create(ConfiguracaoComercialViewModelEdit viewModel)
{
    // Aqui, a viewModel já vem null
    // meu código
    // ...
    return result;
}

Comment: Retire viewmodel e coloca `data: formData` e teste
Comment: @VirgilioNovic funcionou, o problema é que tenho que passar mais um parâmetro pra função
Comment: @ArturoTemplário até coloquei como resposta, qual parametro? que precisa a mais???
Answer: Tente usar na view o seguinte comanda:
@using (Ajax.BeginForm("ACTION", "CONTROLLER",
new AjaxOptions
{
    HttpMethod = "POST",
    OnBegin = "$.fn.ExibirLoading();",
    OnSuccess = "CarregarServicoTerceiroServicoComplete(data);",
    OnFailure = "$.fn.VerifyError(xhr, status, error);",
    OnComplete = "$.fn.OcultarLoading();$('#FormCadastrarServico')[0].reset();"
}, new { @id = "FormCadastrarServico" }))
                    {
    //SEU FORMULARIO
}

Ae o .net chamará automaticamente via ajax, acredito que esta seja a melhor maneira.
Os métodos OnBegin, OnSuccess, OnFailure, OnComplete chamarão js para as ações citadas.
Answer: Pelo que pude perceber tem um item atrapalhando que é o viewModel, acredito que deva fazer isso:
Troque isso
var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { viewModel: formData },
    success: function (data) {
        // meu callback
    }
});

por isso:
var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: formData,
    success: function (data) {
        // meu callback
    }
});

Comment: Excelente, desse jeito de baixo ele passou a viewModel. Mas eu tenho mais um parâmetro pra passar, por isso meu AJAX estava daquela maneira. A assinatura original do método é: `public ResultadoAjax Create(ConfiguracaoComercialViewModel viewModel, List produtos_tabela)`
Comment: Dentro do `` tem essa lista de `ProdutoTabela`, porque, se tiver corretamente é assim também???, então depende do formulário! @ArturoTemplário
Comment: O List eu monto na mão. Engraçado que se eu passo um de cada vez, funciona
Comment: é porque existe uma forma de passar, o problema é como você está passando, entendeu @ArturoTemplário, e uma coisa isso não está na pergunta original, se poderia abrir uma nova pergunta para esse determinado paramento, o que acha!


Is it possible to only update one panel (or block) as a result of a the URL clicked elsewhere?

Question: Is it possible to only update the content in a particular panel as a result of a URL clicked elsewhere? (i.e no other pages get refreshed.)
I have created Views with context filters and would be using them in Panels and would prefer for the whole page not to have to be refreshed.
I'm particularly interested in how to retain the zoomed position of a OpenLayers map, but general advice welcome. (I would consider my OpenLayers use as being a 'side' case of my general question. I think the permalink co-ords option may help me here.)
Answer: If you want your links to stay unaffected, you need to:

Attach onclick javascript event to all links. In it, send AJAX query to server.
On server side detect when links are clicked on page supporting dynamic loading (referer is a good start). Send HTTP 204 status code to prevent full page reload. Do not avoid it by returning false from event mentioned in point 1 - if you will, address bar will not match content.
In response to ajax query, server should return what IDs are supposed to get replaced, and with what.
Javascript on page needs to accept and process data from point 3.

Little explanation: HTTP 204 from server tells the browser that http request is legit, but no data from the server is needed. Normally when you want to alter url in browser window, at least part before #, browser reloads page. This is to prevent theft page from impersonating bank page and so on. So you need server-side solution to actually allow address change without reload - target server will not impersonate itself. Or if it will, it's his right to do so.
Comment: @therobyouknow Not an easy task, sorry. Would be nice if Drupal would have something like this built-in, but sadly I don't know any module to do that.
Comment: I appreciate your know-how on this subject @Mołot ! In the meantime, there may be alternative approaches for what I am trying to achieve: I am working with OpenLayer maps and by enabling permalinks option this now updates the URL on zooming. If I can work out how to 'reuse' this URL among the other page components, then what is displayed will be what I require as an entire page refresh using this URL containing this and other info will ensure all panels display what is needed. I just need to work out how to share the same URL among several Panels - a standard procedure I think, I'll follow up.
Comment: @therobyouknow the comment above deserves to be a question in it's own right. Sadly, at the moment I have no idea.
Comment: no problem! It's fine :) I think I will be able to achieve it. Once I do, I will follow up here. Thanks for your input so far.


Show Active terms from vocabulary using taxonomy menu

Question: What i want: Active terms of vocabulary in main menu.
What i have done so far:

I have used taxonomy_menu module.
Created taxonomy(Category).
Added "Status" field having boolean values (0 = Inactive, 1 = Active).
Added two terms in Category(Cat1 and Cat2).
Cat1 = Active, Cat2 = Inactive.
Configured menu from "Edit vocabulary" section.

Problem: All terms of vocabulary are included in main menu. I want that only those terms whose Status = Active should be displayed in main menu.
Community, please help. Any hint would be helpful.
Comment: You can instead disable the terms from add terms
Comment: @harshal: by disable, do you mean that i can delete them? or something else
Answer: You can do this by using hook on taxonomy insert and update inside a custom module.
Here is a sample of code (needs refactoring/cleaning/checking but that's a start and it works for me) :
function custom_module_taxonomy_menu_insert(&$item) {
  //load taxonomy to access fields
  $tax = taxonomy_term_load($item['tid']);
  //get your field display (here i called it field_status)
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  //check your value
  if($display == 0) {
    //I don't want to display this element
    $item['remove'] = TRUE;
    return $item;
  }
}

function custom_module_taxonomy_menu_update(&$item) {
  //IDEM without comments
  $tax = taxonomy_term_load($item['tid']);
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  if($display == 0) {
    $item['remove'] = TRUE;
    return $item;
  }
}

[Edit to add some details]
The menu will not update automatically, you'll have to save/update your terms to update the menu (hook_taxonomy_menu_update). For new terms, it's going to work automatically  (hook_taxonomy_menu_insert).
Comment: +1 on the use of the hooks, not so sure on the logic involved if an item is sent in that doesn't contain the field in question, but definitely the way to go from an api standpoint.


Multiprocessing BaseManager shutdown() takes twenty-seconds

Question: I'm using BaseManager to share a queue with a pool of worker processes. I call start() on it in order to have the manager run in another thread.
Under shutdown(), the documentation says "This is only available if start() has been used to start the server process." However, if I call shutdown(), the foreground process will block on the manager process for twenty-seconds before terminating, every time. If I don't call shutdown(), the foreground process leaves immediately?
What am I missing?
Also, does anyone have any idea why the documentation says, "This can be called multiple times."? Why would you send multiple shutdown signals to the manager process?
Answer: it waits for 20 Seconds by design. Please refer here  for more info
<code>        process.join(timeout=0.2)
        if process.is_alive():
            util.info('manager still alive')
            if hasattr(process, 'terminate'):
                util.info('trying to `terminate()` manager process')
                process.terminate()
                process.join(timeout=0.1)
                if process.is_alive():
                    util.info('manager still alive after terminate')
</code>
Comment: The shutdown calls `util._run_finalizers(0)` to run the finalizers that have been declared for the start process. Now if you were to refer to defination of start you will notice that there is registration of finalizers which calls `_finalize_manager`  which has a  timeout parameter used when waiting for manager to shutdown cleanly before resorting to terminate()
Comment: I don't see anything in the shutdown call or the creation of the process that indicates a delay. What makes you think that it's by design? When I don't call shutdown(), no processes seem to be left open. I question the significance of even having the call.


Derivative of tangent vector

Question: I am reading about curves in the plane and curvature. In my literature it says that if $\alpha : (a,b) \rightarrow \mathbb{R}^2$ is a $C^2$-curve parameterized by arc-length, then $\{T(s), N(s)\}$ is an orthonormal basis for $\mathbb{R}^2$. That part I understand, but then it says that this implies that $\dot{T}(s)$ has the following expansion:
$$\dot{T}(s) = \langle\dot{T}(s),T(s)\rangle T(s) + \langle \dot{T}(s),N(s)\rangle N(s). $$
(Here $T(s)$ is the unit tangent, $N(s)$ is its normal and $\langle \cdot,\cdot \rangle$ is the inner product.)
I don't understand why this expansion is true. I'm guessing that we are multiplying $\langle \dot{T}(s),T(s) \rangle$ by $T(s)$ and by $N(s)$ because $T(s)$ and $N(s)$ are basis vectors, but I'm confused about why they are multiplied by $\langle \dot{T}(s),T(s)\rangle$ specifically.
Answer: If $\{w_1,w_2\}$ is an orthonormal basis of $\mathbb R^2$, then$$(\forall v\in\mathbb R^2):v=\langle v,w_1\rangle w_1+\langle v,w_2\rangle w_2.$$This is all that is being used here.

Derivative of tangent vector


React native. I can't find my current location(Geolocation) IOS

Question: I need to access my location from GPS. So, i import geolocation to project.
first, I create following like this (install react native map, already link)
and I just already add NSLocationWhenInUseUsageDescription in my Xcode
also, I just already libRCTGeolocation.a in my Xcode
then, I just read map view in mapview from Airbnb. tell me to set showUserLocation set it to "true". when set true will ask user to access
location.
reference: https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md
finally, That is not ask anything to access
location. so, I don't know why. I can't find my current location.
and this is my picture step by step that I describe from begin
https://i.stack.imgur.com/c7VIk.jpg
I will show you my code.
Route.js
<code>import React, { Component, PropTypes } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    Dimensions,
} from 'react-native';
import MapView from 'react-native-maps';
var {height, width} = Dimensions.get('window');

export default class Route extends Component {
    constructor(props){
    super(props);
    this.state = {
        region: {
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
        }
    };
    this.onRegionChange = this.onRegionChange.bind(this);
}

onRegionChange(region) {
    this.setState({ region });
}

    render() {
        return (
            <View style={styles.container}>
        <MapView style={styles.map}
          mapType="standard"
          showsUserLocation={true}
          followsUserLocation={true}
          showsCompass={false}
          showsPointOfInterest={false}
          region={this.state.region}
          onRegionChange={this.onRegionChange}
        />
        <View style={styles.container}>
          <Text>
          Latitude: {this.state.region.latitude}{'\n'}
          Longitude: {this.state.region.longitude}{'\n'}
          LatitudeDelta: {this.state.region.latitudeDelta}{'\n'}
          LongitudeDelta: {this.state.region.longitudeDelta}
          </Text>
        </View>
      </View>
        );
    }
}

Route.navigationOptions = { //this define from App.js option in SecondScreen
  title: 'Route', //name top of StackNavigator
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    image: {
        width: 200,
        height: 200,
    },
    text: {
        color: 'white',
        fontWeight: 'bold',
        backgroundColor: 'transparent',
        marginTop: 20,
    },
    map: {
    width: width,
    height: height*2/3
  }
});
</code>
Comment: In the iOS simulator it reads a fake location.  Set a custom location using _Debug > Location > Custom Location..._ in the simulator menu.
Comment: But i need to acess my current location from GPS. What should i do?
Comment: If you run it on a real device you will get the real location.  Otherwise you can just put your current location in the menu I mentioned in my previous comment.  You can get your location a number of ways, including this: https://mylocation.org/
Comment: oh, I really thank you so much.
Answer: In the iOS simulator it reads a fake location. Set a custom location using Debug > Location > Custom Location... in the simulator menu.
If you run it on a real device you will get the real location. If you continue to use the simulator you can just put your current location using the Custom Location menu. You can get your location a number of ways, including this: http://mylocation.org/.


Commutator subgroup is normal?

Question: Let $P$ be a group, $H$ a subgroup of $P$, $G$ a normal subgroup of $P$, $[G,H]$ the subgroup of $P$ generated by commutators $[g,h] = ghg^{-1}h^{-1}$, with $g \in G$ and $h \in H$, and $P' = [P,P]$. I know that $[G,H]$ is a subgroup of $P' \cap G$. Is it a normal subgroup? How to prove it? If $H=P$, I know that $[G,H]=[G,P]$ is a normal subgroup of $P' \cap G$. How can I prove it?
Thanks
Answer: Both parts follow from the general result that, for $H,K \le G$, $[H,K]$ is normalized by $H$ and $K$.
This result follows from the commutator identities $[h',k']^h = [h'h,k'][h,k']^{-1}$ and $[h',k']^k = [h',k]^{-1}[h',k'k]$.
(I am using the definitions $[h,k]=h^{-1}k^{-1}hk$ and $h^k=k^{-1}hk$.)
Comment: Can you go further in details please? Or cite some reference? Thanks
Comment: What do you not understand? You can prove the commutator identities by just writing the left and right hand sides of the equations out in full. You can find them here: http://en.wikipedia.org/wiki/Commutator
Comment: Professor Holt, what do you mean by "$[H,K]$ is normalized by $H$"?
Comment: Now I see, you meant that $[H,K] \triangleleft H$. Ok, thanks for your help
Comment: I mean $H \le N_G([H,K])$. Since $[H,K]$ is not necessarily a subset of $H$,  we cannot always say $[H,K] \lhd H$. But it is always true that $[H,K] \unlhd \langle H,K \rangle$.
Comment: Awesome. Just another doubt. Is this $\langle H,K \rangle = \langle H \cup K \rangle$? The join?
Comment: Yes that's the same thing.

Commutator subgroup is normal?


Proper use and interpretation of chi-squared test

Question: Please help me understanding basic features of chi-squared test for distribution comparison.
As far as I understand, if we draw two samples from the same distribution, and treat one sample as "observed" and another as "expected" then
most of the time the associated chi2 value will be low and the respective p-value to reject the null hypothesis that the two samples come from the same distribution will be high. Therefore, I expect that if I repeat this process many times
and test this p-value against some predefined threshold (say 0.05), then only a in a small fraction of times (~5% in our case)
the associated p-value will be below the critical threshold. However, in my simulations this null hypothesis is rejected in about 23% of sample pairs.
What am I missing?
Below is my Python code. In this code, i generate two samples of 100 random integers between 0 and 3. I then calculate the p-value using my implementation of chi2 tests
(I verified the correctness of my chi2
test function against an online calculator) and compare this value to a threshold (ALPHA = 0.05). I repeat this process
1000 times and calculate the percentage of times where the p-value was below ALPHA
import numpy as np
import scipy.stats as stats
def chi2testTwoSamples(observed, expected):
    countO = defaultdict(int)
    countE = defaultdict(int)
    nPoints = len(observed)
    assert nPoints == len(expected)
    for o in observed: countO[o] += 1
    for e in expected: countE[e] += 1

    keysO = set(countO.keys())
    keysE = set(countE.keys())
    keys = list(keysO.union(keysE))
    keys.sort()
    countExpected = np.array([countE[k] for k in keys], dtype=float)
    countObserved = np.array([countO[k] for k in keys], dtype=float)
    sel = (countExpected != 0)
    countExpected = countExpected[sel]
    countObserved = countObserved[sel]
    chi2 = np.sum((countExpected - countObserved) ** 2 / countExpected)
    df = len(keys) - 1
    pVal = 1.0 - stats.distributions.chi2.cdf(chi2, df)
    return (chi2, pVal)

TIMES = 1000
SAMPLES = 100
ALPHA = 0.05
timesBelowAlpha = 0
np.random.seed(9999)
for i in range(TIMES):
    a = np.random.randint(0, 3, SAMPLES) #draw many integers between 0 and 3
    b = np.random.randint(0, 3, SAMPLES)
    p = chi2testTwoSamples(a, b)[1]
    if p < ALPHA:
        timesBelowAlpha += 1
percentage = 100.0 * timesBelowAlpha / TIMES
print '%.1f%%'%(percentage)

Answer: I hardly read Python but what I understand from the code of your chi2testTwoSamples function is that you consider the second sample as "expected values"; that's not the way it works!

Either you compare the four observed values $n_0, n_1, n_2, n_3$ obtained from counts of a single random sample of $N$ elements in $\{0, 1, 2, 3\}$ with the expected values $e_0 = e_1 = e_2 = e_3 = {1\over 4} N$ ;
or you have two samples of total size $N$ (resp. $M$) with counts $n_0, n_1, n_2, n_3$ (resp. $m_0, m_1, m_2, m_3$), and assuming that both samples come from the same distribution you infer the frequencies $f_0, f_1, f_2, f_3$ of the four outcomes by $f_i = {1 \over N+M} (n_i + m_i)$ and expected values are $N f_i$ (resp. $M f_i$).

In both cases, the result should follow a $\chi^2$ distribution with $3$ degrees of freedom. The computation of the number of degrees of freedom is different in the two cases, it's not every time as simple as number of categories - 1...
Comment: you understood my code correctly. Can you please clarify what are the N and M variables in your second bullet point?
Comment: @bgbg The total size of the two samples, $N = n_0 + n_1 + n_2 + n_3$ and $M = m_0 + m_1 + m_2 + m_3$. In your case $N = M = 100$.


How to make author field required?

Question: In Drupal 8. I noticed that I can create a new node or edit a current node and delete the "Authored By" name, it's blank and when I hit save the node is authored by Anonymous.
How can I make this Author field required to be a current user in the system?
And the page will show a message and will not save until a name is entered. I tried this but it does not work:
use Drupal\Core\Form\FormStateInterface;

function demo4_form_alter(&$form, $form_state, $form_id) {
$form['author']['name']['#required'] = TRUE;
}

I also tried this:
function demo4_form_alter(&$form, $form_state, $form_id) {
if ( $form_id == 'page_node_form'){
$form['author']['name']['#required'] = TRUE;
}
return $form;
}

This works only in Drupal 7 not in Drupal 8, And I changed page_node_form to node_page_form for Drupal 8
function demo4_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'page_node_form') {

$form['author']['name']['#required'] = TRUE;
 }
   return $form;
}

Comment: You don't need to return the `$form` in a form alter, it is passed by reference. Second, you have to type hint `$form_state` with `FormStateInterface`. You need the `use` statement as well.
Comment: So do it like this? use Drupal\Core\Form\FormStateInterface;
function demo4__form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$form['author']['name']['#required'] = TRUE;
}
Comment: By using the `use` statement you don't have to specify the fully qualified name - only the name itself, so just `FormStateInterface $form_state` is needed. See http://php.net/manual/en/language.namespaces.importing.php
Comment: I tried this but its still not required- use Drupal\Core\Form\FormStateInterface;
function demo4__form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['author']['name']['#required'] = TRUE;
}
Comment: Yes I was mainly saying the syntax of your code needed correction. Are you certain that's the form field key? Have you debugged your code to see it add #required?
Answer: What you're looking for is this:
$form['uid']['widget'][0]['target_id']['#required'] = TRUE;
(Devel is your friend!)
You were on the right track as $form['author']['#required'] = TRUE; will make the "Authoring Information" have a red star (*), but won't make your authored by field required.
Complete code:
function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['uid']['widget'][0]['target_id']['#required'] = TRUE;
  }
}

Comment: Incase anyone needs this code here it is, it may be hard to read.
use Drupal\Core\Form\FormStateInterface;
function demo4_form_alter(array &$form, FormStateInterface $form_state,
$form_id) {
if ($form_id == 'node_page_form') {
$form['uid']['widget'][0]['target_id']['#required'] = TRUE;
 }
   return $form;
}
Comment: THanks again CliveCleaves. With dpm I did find all the elements inside the admin box like - uid, author, revision, and inside those I found the widget and title
Comment: Thank you that works. I enabled Devel and Devel Kint. Then in devel settings I checked Kint and display page array. Then placed this inside hook form alter- dpm($form); And then I went to create a basic page and I see the Input array of 41 items but I dont see the elements for the admin settings box, like author by, revision...? Where can I find information on how to use devel and kint to find elements?

How to make author field required?


How to convert date and time only at time?

Question: I get by API such data about time and date 2021-09-05T18:16:47.790601+02:00 how can I get only hours from here?
Comment: you can use the `hour` getter like this: `int hoursOnly = myDateTime.hour;`
Comment: @AdnanAlshami Thanks for the answer. How do i convert this data from String to DateTime?
Comment: you can use `DateTime.parse("2021-09-05T18:16:47.790601+02:00");` to convert string to date.
Answer: From the API you're getting a formatted date and want to get only the hour.
First, it would be better to you get from the API the UNIX date (if available) which has a timestamp format like this: https://www.unixtimestamp.com
Your first question would be more either:
How getting from a fromatted date a Timestamp to obtain the hour
or
How parsing the string to get the hour.
Here the formatted method:
DateTime which should help you: https://api.flutter.dev/flutter/dart-core/DateTime-class.html
Here an example:
final DateTime myDate = DateTime.parse('2021-09-05 18:16:47');
final int hour = myDate.hour;
final int minute = myDate.minute;
final int second = myDate.second;
print('hour: $hour');
print('minute: $minute');
print('second: $second');

Result:
hour: 18
minute: 16
second: 47

Here the parsing method:
Substring which should help you: enter link description here
RegExp which should help you: enter link description here
Here an example:
const String myDate = '2021-09-05T18:16:47.790601+02:00';
final String hour = myDate.substring(11, 13);
final String minute = myDate.substring(14, 16);
final String second = myDate.substring(17, 19);
final String date = RegExp(r"[0-9]{2}:[0-9]{2}:[0-9]{2}").stringMatch(myDate).toString();
final List<String> splitDate = date.split(':');
print('hour: $hour');
print('minute: $minute');
print('second: $second');
print('date: $date');
print('split date: $splitDate');

Result:
hour: 18
minute: 16
second: 47
date: 18:16:47
split date: [18, 16, 47]

Comment: Thank you very much. I figured out what Unix is. And he did everything with the help of him.
Answer: For ISO8601 String you can convert with DateTime
  DateTime dt = DateTime.parse('2020-01-02 03:04:05');

then you can access what you want with dt


In set theory, how are real numbers represented as sets?

Question: In set theory, if natural numbers are represented by nested sets that include the empty set, how are the rest of the real numbers represented as sets?

Thanks for the answers. Several answers basically said for irrational numbers that
A Dedekind cut is a pair of sets of rational numbers $\{L, R\}$. The set of real numbers is defined to be the set of all Dedekind cuts, where a Dedekind cut is a pair of sets of rational numbers $\{L, R\}$ which have no elements in common, and where all the elements of $L$ are less than any element of $R$.  Each Dedekind cut is a real number. This is where I have a problem - surely that can't be correct. The set $L$ is a set of all rationals, and there must be a rational in the set $L$ that is greater than all other rationals in that set, even if we have no method of determining it. And similarly, there must be a rational in the set $R$ that is less than all other rationals in that set, even if we have no method of determining it. If every irrational number has a corresponding set $L$, then each irrational number has some such corresponding largest element of that set $L$, and then each irrational number has some corresponding rational number. And that would mean that the irrational numbers are countable. So, with Dedekind cuts,  the only conclusion is that there must be irrational numbers $x$ which are either greater or lesser than some irrational cut $y$ of the rationals, and between $x$ and $y$ there is no rational number.  But that is impossible, so that the Dedekind cuts cannot be the correct representation of the real numbers.
Surely the problem with Dedekind cuts is in using sets of rationals that include all rationals up to a certain rational. But there is an alternative method of representing irrationals can be defined in terms of infinite sets of rational numbers. For example, in binary notation, the non-integer part of $\pi$ is $.00100100\ 00111111\ 01101010\ 10001$. You define a set by: if the nth digit is a $1$, then  the natural number $n$ is in the set. And then we have that, for the real numbers between $0$ and $1$, that the set of real numbers is simply the set of all subsets of natural numbers. Each subset corresponds to some real number between $0$ and $1$.
And in this way, all real numbers can be considered to be some set based only on nested sets of the empty set.
But I still haven't got a satisfactory answer for how negative numbers can be represented in terms only of sets containing the empty set. Any ideas?
Comment: I thought I should explicitly point out an error in the question. The statement "there must be a rational in the set L that is greater than all other rationals in that set, even if we have no method of determining it" is false, for trivial reasons that have nothing to do with completeness.  The set $L$ of numbers that are strictly less than zero contains no number greater than all other numbers in $L$.  (and this is true regardless of whether "number" means "rational number" or "real number".)
Comment: From the point of view of set-theoretic simplicity, a variant of binary notation is simplest.  However, that is not simplest when we want to verify the basic properties of the reals (complete ordered field), so the set-theoretically more complex standard approaches (Dedekind cuts, or Cauchy sequences) are more convenient.
Comment: Peter, in my answer I did that; so did Zhen. First we start with using the usual definition of $\mathbb N$ as sets, then we continue. Either by defining an equivalence relation (thus a negative number is an equivalence class - a set - of pairs of natural numbers (a set of sets of sets...)) or by defining $-n = n\cup\{\mathbb N\}$ as a set.
Comment: Also about the Dedekind cuts constructions, two comments: (1) Not every pair of sets of rationals define a cut; (2) As I indicated in my answer, we can only consider $L$, and we only consider such $L$ which is closed under $<$ and bounded in the rationals. We do not require an *explicit* supremum, just *some* bound.
Comment: @Peter, I have merged your duplicate account into your current account. If you have trouble logging in, or if you accidentally create duplicate accounts, simply flag one of your own questions for moderator attention, and we will help out.
Answer: There are a few possibilities, but here is the one approach. Even the starting point—the set of natural numbers $\mathbb{N}$—can be defined in several ways, but the standard definition takes $\mathbb{N}$ to be the set of finite von Neumann ordinals. Let us assume that we do have a set $\mathbb{N}$, a constant $0$, a unary operation $s$, and binary operations $+$ and $\cdot$ satisfying the axioms of second-order Peano arithmetic.
First, we need to construct the set of integers $\mathbb{Z}$. This we can do canonically as follows: we define $\mathbb{Z}$ to be the quotient of $\mathbb{N} \times \mathbb{N}$ by the equivalence relation
$$\langle a, b \rangle \sim \langle c, d \rangle \text{ if and only if } a + d = b + c$$
The intended interpretation is that the equivalence class of $\langle a, b \rangle$ represents the integer $a - b$. Arithmetic operations can be defined on $\mathbb{Z}$ in the obvious fashion:
$$\langle a, b \rangle + \langle c, d \rangle = \langle a + c, b + d \rangle$$
$$\langle a, b \rangle \cdot \langle c, d \rangle = \langle a c + b d, a d + b c \rangle$$
(Check that these respect the equivalence relation.)
Again, this is not the only way to construct $\mathbb{Z}$; we can give a second-order axiomatisation of the integers which is categorical (i.e. any two models are isomorphic). For example, we may replace the set $\mathbb{Z}$ by $\mathbb{N}$, since the two sets are in bijection; the only thing we have to be careful about is to distinguish between the arithmetic operations for $\mathbb{Z}$ and for $\mathbb{N}$. (In other words, $\mathbb{Z}$ is more than just the set of its elements; it is also equipped with operations making it into a ring.)
Next, we need to construct the set of rational numbers $\mathbb{Q}$. This we may do using equivalence relations as well: we can define $\mathbb{Q}$ to be the quotient of $\mathbb{Z} \times (\mathbb{Z} \setminus \{ 0 \})$ by the equivalence relation
$$\langle a, b \rangle \sim \langle c, d \rangle \text{ if and only if } a d = b c$$
The intended interpretation is that the equivalence class of $\langle a, b \rangle$ represents the fraction $a / b$. Arithmetic operations are defined by
$$\langle a, b \rangle + \langle c, d \rangle = \langle a d + b c, b d \rangle$$
$$\langle a, b \rangle \cdot \langle c, d \rangle = \langle a c, b d \rangle$$
And as before, we can give an axiomatisation of the rational numbers which is categorical.
Now we can construct the set of real numbers $\mathbb{R}$. I describe the construction of Dedekind cuts, which is probably the simplest. A Dedekind cut is a pair of sets of rational numbers $\langle L, R \rangle$, satisfying the following axioms:

If $x < y$, and $y \in L$, then $x \in L$. ($L$ is a lower set.)
If $x < y$, and $x \in R$, then $y \in R$. ($R$ is an upper set.)
If $x \in L$, then there is a $y$ in $L$ greater than $x$. ($L$ is open above.)
If $y \in R$, then there is an $x$ in $R$ less than $y$. ($R$ is open below.)
If $x < y$, then either $x \in L$ or $y \in R$. (The pair $\langle L, R \rangle$ is located.)
For all $x$, we do not have both $x \in L$ and $x \in R$. ($L$ and $R$ are disjoint.)
Neither $L$ nor $R$ are empty. (So $L$ is bounded above by everything in $R$ and $R$ is bounded below by everything in $L$.)

The intended interpretation is that $\langle L, R \rangle$ is the real number $z$ such that $L = \{ x \in \mathbb{Q} : x < z \}$ and $R = \{ y \in \mathbb{Q} : z < y \}$. The set of real numbers is defined to be the set of all Dedekind cuts. (No quotients by equivalence relations!) Arithmetic operations are defined as follows:

If $\langle L, R \rangle$ and $\langle L', R' \rangle$ are Dedekind cuts, their sum is defined to be $\langle L + L', R + R' \rangle$, where $L + L' = \{ x + x' : x \in L, x' \in L' \}$ and similarly for $R + R'$.
The negative of $\langle L, R \rangle$ is defined to be $\langle -R, -L \rangle$, where $-L = \{ -x : x \in L \}$ and similarly for $-R$.
If $\langle L, R \rangle$ and $\langle L', R' \rangle$ are Dedekind cuts, and $0 \notin R$ and $0 \notin R'$ (i.e. they both represent positive numbers), then their product is $\langle L \cdot L' , R \cdot R' \rangle$, where $L \cdot L' = \{ x \cdot x' : x \in L, x' \in L', x \ge 0, x' \ge 0 \} \cup \{ x \in \mathbb{Q} : x < 0 \}$ and $R \cdot R' = \{ y \cdot y' : y \in R, y \in R' \}$. We extend this to negative numbers by the usual laws: $(-z) \cdot z' = -(z \cdot z') = z \cdot -z'$ and $z \cdot z' = (-z) \cdot -z'$.

John Conway gives an alternative approach generalising the Dedekind cuts described above in his book On Numbers and Games. This eventually yields Conway's surreal numbers.
Comment: You have to exclude at least <0,0> in the construction of Q.  It would be related to all other pairs so transitivity would fail.
Answer: There are two standard constructions, resulting in either equivalence classes of  cauchy sequences of rational numbers, or bounded subsets of rational numbers satisfying some additional properties.
You should actually rather think of "the" real numbers as an ordered field satisfying some additional properties (axiomatic approach), than a specific set.
Comment: The comment that Alexander makes about the axiomatic approach is a subtle point, but entirely worth taking seriously. The importance of the tools we use in mathematics are not their identities, but their properties. While it is **very important** that one can build *models* of the real numbers from sets, choosing a *single* model as canonical is beside the point, and thinking of *what the elements of sqrt(2) are* is not usually a pertinent question.
Comment: @Voyska: to give a (somewhat unfair) caricature of your point, one ***could*** also be interested in the colour of numbers, or their textures. Indeed, synthaethetic people would attest that these sense data can be pertinent of numbers, and allows them in some case to obtain a more reliable memory of those numbers (e.g. as in being able to recall long portions of the decimal expansion of $\pi$). So are these properties in some robust and meaningful sense a part of the identities of those numbers? Or does this say more about human neurology in individual cases, than numbers as such?
Comment: @NieldeBeaudrap Yes, but one could be interested about their identities too.
Answer: First we start with the natural numbers.

$0=\varnothing$,
$n+1=n\cup\{n\}$.

Now we have the natural numbers. From here we can continue creating the integers (the examples here are just out of the blue to show how this can be done, not something purely canonical.)

For $n\in\mathbb N$, define $-n=n\cup\{\mathbb N\}$.

This is unique since $\mathbb N\notin n$ for any $n$. The next step is to define the rational numbers:

$\frac{p}{q} = \big\{\langle m,n\rangle\mid mq=np\big\}$

This is, of course, an equivalence relation over the set $\mathbb Z\times\mathbb Z$.
And finally, we reach the definition of the real numbers:
A real number is a set of rational numbers $r$ such that:

If $q\in r$ and $p<q$ then $p\in r$;
There exists some $q\in\mathbb Q$ such that every $p\in r$ is less than $q$.

This can be formulated as subsets of $\mathbb N$ as followed:
Fix some enumeration of $\mathbb Q$, that is $\{q_n\mid n\in\mathbb N\}$. Now consider the real number $r$ as the set of natural numbers which corresponds to the rationals in the above definition.
This is a usual way of looking at the real numbers as subsets of $\mathbb N$ in modern set theory. It is true that not every set of natural numbers is used, but since "enough" of them is being used we can just map the sets of natural numbers so we use them all.
Comment: I don't follow your logic. At all. Also, note that the natural numbers *embed* into the rational numbers, but they are not a subset of them, under this interpretation.
Comment: So, \begin{align}\varnothing = 0 &= s(-1) \\
&= -1 + 1\\ &= -1 \cup \{-1\} = (1\cup \{\mathbb{N}\}) \cup (\{1\cup \{\mathbb{N}\}\})\\ &= \{\{\varnothing, \mathbb{N}\},\{\{\varnothing, \mathbb{N}\}\}\}\end{align} ???
Comment: @AsafKaragila in the rational number axioms did you re-use $p, q, r$, but with different definitions?  Also, can you expand on how $r$ as the set of natural numbers which corresponds to the rationals?  Do you mean the enumeration for the definition?
Comment: @Nick: Yes, I repurposed the letters. As for the second question, $r$ is a *real* number. We fix a bijection between the rational numbers and the natural numbers, and then we simply translate the Dedekind cuts (initial segments of $\Bbb Q$) to sets of natural numbers. To be honest, this is not a well written question, I wrote this I was still forming an understanding of the set theoretic world around me, and there's a lot I'd improve upon nowadays.
Answer: There are a few ways to do this.

Dedekind cuts are the representation of real numbers which are the most obviously set-like; it is a representation in which each real number x ∈ ℝ is represented by a pair (S, T) of disjoint non-empty open sets S,T ⊂ ℚ, such that
a. If a ∈ S, then every number b < a is also in S;
b. If a ∈ T, then every number b > a is also in T.
(There are alternative, equivalent ways of expressing the idea of a Dedekind cut, e.g. this other example.)
Every rational number q ∈ ℚ can be represented by S = {a∈ℚ | a<q} and T = {a∈ℚ | a>q}; so that q is the supremum of S and the infimum of T. We identify real numbers with sets in the same way: a real number such as $\sqrt 2$ is identified with the sets S = {a∈ℚ | a2<2 or a<0}, and T = {a∈ℚ | a2>2 and a>0}, so that $\sqrt 2$ is the supremum of S and the infimum of T.
To use this construction as a "construction in terms of sets", you must represent rational numbers in terms of sets; this is usually done by representing them as equivalence classes of ordered pairs (p, q), where q ≠ 0, and in which (p, q) ∼ (p', q') if and only if pq' = qp'.
Equivalence classes of Cauchy sequences of rational numbers is another way to construct the real numbers. Cauchy sequences (over the thesmevles are represented as sets by identifying a sequence σ as a function σ : ℕ → ℚ; the function is then a set of ordered pairs. The Cauchy sequences form an algebra over the rational numbers, where addition, negation, and multiplication of Cauchy sequences is done point-wise.
Two Cauchy sequences σ, σ' are considered equivalent if (σ' − σ) converges to 0; real numbers x are then represented by the rational Cauchy sequences converging on x.
For instance, $\sqrt 2$ can be represented by the set of Cauchy sequences equivalent to (1, 1.4, 1.41, 1.414, 1.4142, ...) giving the decimal expansion of $\sqrt 2$.
There is another related representation of real numbers in terms of sequences nested closed intervals; this can be reduced to Cauchy sequences by considering the sequence either of the lower limits or the upper limits of those intervals.

For every construction of the real numbers, there will be a way to describe how to construct a real number from the ground up in terms of sets; it's a good introductory exercise to see how you would do them.
Answer: A long time ago I wrote an exposition on the uniqueness (up to unique order-preserving isomorphism) of the real numbers on this very site. Note: It's filled with exercises and it assumes knowledge of abstract algebra and topology.
It also contains a (very short) series of exercises that lead the reader to proving that the "equivalence classes of Cauchy sequences of rational numbers" are a complete ordered field.
In some sense it is a bit of a failure of mathematics that first year math majors can use the least upper bound property of the real numbers and prove many nice theorems about sequences of real numbers and continuous functions, but actually showing that the real numbers exist and are unique (up to...) pretty much requires half of an undergraduate education. It's not that it's a failure of teaching mathematics, it's just that damn hard.
Answer: While all of the constructions given here describe the construction of the ordered field of real numbers $\mathbb{R}$, you should be aware that more often than not when a set theorist talks about 'the reals' - particularly in the context of cardinality and large-cardinal theory - they don't generally mean the real numbers, but instead the reals as an abstract entity; in that case a 'real' can refer to either a set of natural numbers (that is, a member of $2^{\mathbb {N}} = \mathcal{P}(\mathbb{N})$) or a function from natural numbers to natural numbers (i.e., a member of $\mathbb{N}^{\mathbb{N}}$), and often the two are used interchangeably, depending on context.
Answer: I have written an article where I find the simplest possible representation of real numbers as sets. Namely, real numbers are infinite sets of natural numbers. The order and structure is given explicitly. You can find the details here:
https://www.mdpi.com/2075-1680/8/1/31