Como colocar dois forms um do lado do outro?

Question: Boa tarde!
Em um arquivo PHP tem um formulário HTML que contém uma tabela e um submit. Tem também um segundo formulário com outra tabela e um 'submit'. Como colocar o segundo formulário ao lado do primeiro sendo que a terceira tabela tem que ficar abaixo das duas primeiras? Segue o código.

<form id="localizacao" name="localizacao" method="post" action="rastreamento.php" onsubmit="return validaCampoLoca(); return false;">

Localizacao de Carga

      CNPJ:
      <input name="CNPJ" type="text" id="CNPJ" size="20" maxlength="14" />
        * somente números
  Selecione o STATUS:
  <select name="status" id="status">
      <option value="0">Recebido</option>
     <option value="1">Em trânsito</option>
     <option value="2">Encerrado</option>
     </select>

        <input name="cadastrar" type="submit" id="cadastrar" value="OK" />

          <input name="limpar" type="reset" id="limpar" value="Limpar!" />

</form>
<form id="alteracoes" name="alteracoes" method="post" action="rastreamento.php" onsubmit="return validaCampoAltera(); return false;">

Alteracoes

      VIAGEM:
      <input name="VIAGEM" type="text" id="VIAGEM" size="20" maxlength="14" />

      NOVO STATUS:
      <input name="NVSTATUS" type="text" id="NVSTATUS" size="1" maxlength="1" />

      EMBARCACAO:
      <input name="EMBARC" type="text" id="EMBARC" size="20" maxlength="10" />

      DATA SAIDA:
      <input name="DATSAI" type="text" id="DATSAI" size="20" maxlength="10" />

      HORA SAIDA:
      <input name="HORSAI" type="text" id="HORSAI" size="20" maxlength="10" />

      DATA CHEGADA:
      <input name="DATCH" type="text" id="DATCH" size="20" maxlength="10" />

      HORA CHEGADA:
      <input name="HORCHE" type="text" id="HORCHE" size="20" maxlength="10" />

        <input name="atualizar" type="submit" id="atualizar" value="ATUALIZAR" />

</form>

 CNPJ
 Data rec
 Tipo Doc
 Nº Doc
 Quant. Vol
 Processo
 Loc. Ent.
 Fornec
 Status

Comment: Cara, cadê o arquivo de folhas de estilo (CSS)?
A aparência da páginas é definida utilizando este recurso.
Comment: Já que faz uso de tabelas, crie uma tabela com duas colunas e em cada coluna coloque um formulário
Comment: Pesquise sobre CSS flexbox, é de longe a forma mais racional.
Answer: Existe o atributo align="left" (
) que faz com que a tabela fique alinhada à esquerda dos elementos seguintes, mas esse atributo se tornou obsoleto no HTML5. Você pode usar float: left que as tabelas ficarão lado-a-lado, exceto se a tela for muito estreita onde a largura mínima das tabelas não permita que uma fique ao lado da outra.
Como a última tabela possui largura total de 100%, esta ficará sempre abaixo das duas primeiras (execute o exemplo abaixo em tela cheia):

table{
   float: left;
}
<form id="localizacao" name="localizacao" method="post" action="rastreamento.php" onsubmit="return validaCampoLoca(); return false;">

Localizacao de Carga

      CNPJ:
      <input name="CNPJ" type="text" id="CNPJ" size="20" maxlength="14" />
        * somente números
  Selecione o STATUS:
  <select name="status" id="status">
      <option value="0">Recebido</option>
     <option value="1">Em trânsito</option>
     <option value="2">Encerrado</option>
     </select>

        <input name="cadastrar" type="submit" id="cadastrar" value="OK" />

          <input name="limpar" type="reset" id="limpar" value="Limpar!" />

</form>
<form id="alteracoes" name="alteracoes" method="post" action="rastreamento.php" onsubmit="return validaCampoAltera(); return false;">

Alteracoes

      VIAGEM:
      <input name="VIAGEM" type="text" id="VIAGEM" size="20" maxlength="14" />

      NOVO STATUS:
      <input name="NVSTATUS" type="text" id="NVSTATUS" size="1" maxlength="1" />

      EMBARCACAO:
      <input name="EMBARC" type="text" id="EMBARC" size="20" maxlength="10" />

      DATA SAIDA:
      <input name="DATSAI" type="text" id="DATSAI" size="20" maxlength="10" />

      HORA SAIDA:
      <input name="HORSAI" type="text" id="HORSAI" size="20" maxlength="10" />

      DATA CHEGADA:
      <input name="DATCH" type="text" id="DATCH" size="20" maxlength="10" />

      HORA CHEGADA:
      <input name="HORCHE" type="text" id="HORCHE" size="20" maxlength="10" />

        <input name="atualizar" type="submit" id="atualizar" value="ATUALIZAR" />

</form>

 CNPJ
 Data rec
 Tipo Doc
 Nº Doc
 Quant. Vol
 Processo
 Loc. Ent.
 Fornec
 Status

Comment: Era isso que o sistema precisava. Só uma dúvida, o flexbox também resolveria essa questão?
Comment: Acho que resolveria, mas acho que para uma coisa simples não seja necessário usar flexbox.


Quasi-isometric Classification of Free Products of Surface Groups

Question: Let $S_g$ denote the compact surface with $g$ holes, and denote its fundamental group as
\begin{equation}
    \Sigma_g=\pi_1(S_g)=\left<a_1,b_1...,a_g,b_g\Big| \prod_{ i \in \{1,...,g\}} [a_i,b_i]\right>.
\end{equation}
In particular, we have that $\Sigma_1 = \mathbb{Z}^2$.
There are two tools I use for the proof. First we have that for $g\geq 2$, the group $\Sigma_g$ is quasi-isometric to $\Sigma_2$ (this I already understand, see https://math.stackexchange.com/q/2818142 and my following remark about coverings). Secondly, if we can find that two groups are commensurable, then they are quasi-isometric (this means we can pass by finite index subgroups). An equivalent way to use this is by defining finite-degree covering maps between two surfaces. Here I shall mention the equality:
$$\pi_1 (S)*\pi_1 (S')=\pi_1 (S\vee S').$$
I try to proof that a free product
$$G = \Sigma_{g_1}*\dots \Sigma_{g_n}=\coprod_{i=1}^n \Sigma_{g_i}$$
is quasi-isometric to one of following five groups: $\mathbb{Z}^2 , \Sigma_2,  \mathbb{Z}^2* \mathbb{Z}^2, \mathbb{Z}^2* \Sigma_2, \Sigma_2* \Sigma_2$.
This way we can show that

$\mathbb{Z}^2*...* \mathbb{Z}^2$   is quasi-isometric to $ \mathbb{Z}^2* \mathbb{Z}^2$.
$\Sigma_2*...* \Sigma_2$   is quasi-isometric to $ \Sigma_2* \Sigma_2$.
$\Sigma_2*...* \Sigma_2 * \mathbb{Z}^2*...* \mathbb{Z}^2$   is quasi-isometric to $ \Sigma_2* \mathbb{Z}^2$.

This is where I am stuck. These three equivalences should be proven by showing the two groups are finite index subgroups of each other (note that $\Sigma_2$ can be replaced by $\Sigma_g$ at any time). An indirect way to show these are finite index subgroups of each other, is by defining a finite-degree covering map from one to the other. If I remember well this is due to the Seifert–Van Kampen theorem.
This question and many insights of for a proof are based on the paper "Amenability, bilipschitz equivalence, and the von Neumann conjecture" by Kevin White.
Edit:
I imagine there are many ways to prove this. I wish to thank Lee Mosher for his solution, but I have the impression that Kevin White uses more elementary arguments. Probably, that is why he adds no reference to the proof. In my opinion, he seems to imply easy subgroups can be found. Here is his proof.
Answer: What you need for this question is the paper by Papasoglu and Whyte, "Quasi-isometries between groups with infinitely many ends". The general theorem regarding free products (which is an application of their much more general theorem) says this:

If $G$ and $H$ are each nontrivial free products of one-ended groups, then $G$ is quasi-isometric to $H$ if and only if the set of quasi-isometry types of free factors of $G$ equals the set of quasi-isometry types of free factors of $H$.

In your case, you are considering two quasi-isometry types:

The quasi-isometry class of $\mathbb Z^2$, which equals the quasi-isometry class $[\mathbb R^2]$ of the Euclidean plane $\mathbb R^2$; and
The quasi-isometry class of the $\Sigma_g$'s with $g \ge 2$, which equals the quasi-isometry class $[\mathbb H^2]$ of the hyperbolic plane $\mathbb H^2$.

And your answer is the correct one, as one sees by applying the above theorem: the three quasi-isometry classes of free products in your question correspond to the three nonempty subsets of the set $\{[\mathbb H^2],[\mathbb R^2]\}$, namely
$$\{[\mathbb H^2],[\mathbb R^2]\}, \quad \{[\mathbb H^2]\}, \quad \{[\mathbb R^2]\}
$$


Create a zipped tar archive of a full centos filesystem, and open in Windows

Question: I'm trying to create a zipped tar archive of all files on a centos 7 machine. I'm using this command:
sudo tar -cvzp --exclude=backup --exclude=swapfile -f /backup/archive/full-backup-$today.tar.gz  --one-file-system /

When I do this, I can perfectly untar the file on centos with tar -xvf
However, the file is not readable in Windows (via winrar & winzip). I think it has something to do the way it was tarred.
Since I want to be able to recover some files in Windows, I would like to be able to open it in Windows.
THanks!
Comment: I would also exclude /dev, /sys, /srv, /proc. Though -p may already be disposing of many (all?) of them.
Comment: Duplicate of https://superuser.com/questions/234649/how-to-extract-a-tar-file-tgz-in-windows
Comment: @AlienLifeForm Thanks for the tip!
@GeraldSchneider; I know how to extract a tar file. However, it's not working, so I believe it has something to do how I tar the files.
Comment: @AlienLifeForm `-p, --preserve-permissions` seems to be irrelevant. From `man tar`: extract  information  about  file permissions (default for superuser). You're probably right about excluding these directories though.
Comment: @yahol You are indeed correct - I misread -p as --one-file-system (only root knows why)
Answer: On Windows, you could try 7zip - it works with .tar, .tar.gz files.
You can also zip and unzip files on Linux for better compatibility with Windows' zip.
Comment: Windows 1803 and later will [include `tar` out of the box](https://blogs.msdn.microsoft.com/commandline/2018/01/18/tar-and-curl-come-to-windows/), so 7zip (or starting up WSL) will no longer be a requirement when handling *.tar* files.
Comment: Hi, I've tried to use 7zip, but also there I get a message that the archive is corrupt
Comment: @mitch2k can you extract dirs from top level one by one, to see which one is causing trouble? Can you also try `zip` instead of `tar` on Linux and then extract it on Windows?


Manually installing Sun Java and Debian/Ubuntu virtual java packages

Question: I've installed Sun Java 6 manually since Canonical has removed it from its package repo (I use Ubuntu 12.04). Now I have the following problem: when I want to install a package which depends on Java via a virtual Java packages (java2-runtime or default-jre) the package manager complains that Java is not installed and tries to install the default JRE (OpenJDK on my system). Is there a way to manually mark the virtual package (e.g. java6-runtime) to be installed? This must be a common problem - how is it best addressed?
Answer: use the equivs package to create a dummy package which provides the missing java6-runtime dependency, which will make dpkg/apt think that this dependency is satisfied.  Here are some basic instructions on the debian wiki.
Also note that openjdk-6-jre is the free version of java, which is still available from ubuntu, and generally just works, and might be a much more simple alternative.


Back to the view

Question: I have created a view that creates pages, each page display the terms of taxonomy of a vocabulary and their articles, how can i link the articles to those pages ?
For example :

I have the Vocabulary Food : for which i generated a page /articles/apple
Food has the terms of taxonomy : 'Apple'
The article : 'Learn about appels' has the term of taxonomy 'Apple'

How do i display a link or breadcrumb for the users on the article 'Learn about appels' that redirect them to the list of 'Food' /articles/apple ?
p.s : i have many many articles, terms of taxonomy and vocabulary.
Answer: The default breadcrumb implementation is based on the path.
If you use Pathauto to generate aliases (with a pattern like /articles/[node:field_food_category:entity:name]/[node:title]), so that the resulting alias is /articles/apple/learn-about-apples, then the breadcrumb should just work.
The active menu trail will not, but you can use a module like https://www.drupal.org/project/menu_trail_by_path for that.
A custom link will have to get the term and its URL, you can get that in preprocess_node() and then print it out in the template wherever you want.
I don't now how you handle content in different vocabularies, if it's a separate node type, or using different category fields or even a single one), based on that it will be more or less complicated to define the pathauto pattern(s), but you could always set up a custom token like [node:my_custom_category_path] to deal with that.
I'd suggest you ask more specific questions if some things are not clear yet as this gets too longer otherwise
Comment: I've used pathauto like you suggested and it works fine, thank you
Answer: Using views...

Make a view block
Add a field of your terms
Edit that field's multiple display settings and uncheck "display multiple values in the same row"
Rewrite that field with Learn more about {{Your replacement pattern}}
Include your view block on all content types of article.

Back to the view


How to Properly Import XML Data into Power BI

Question: I'm trying to get data from an online XML file to my power bi report. I don't seem to be getting much of anything. Here's my Query:
<code>let
    Source = Xml.Tables(Web.Contents("https://sharepoint.com/teams/BP/Agile/Shared%20Documents/Power%20BI%20Data/Zachs%20Uninteresting%20Things/zachs%20feed%20query1.xml")),
    Table1 = Source{1}[Table]
in
    Table1
</code>
Answer: I had to expand the table a couple times by clicking on the button in the query editor.


Resolve hostname with Python (via DNS)

Question: I want to resolve a hostname with Python.
But, I don't want that /etc/hosts gets used.
My usecase is checking if DNS is working.
How can I force name resolution via DNS in Python?
Comment: Use the dnspython library, for details see the top rated answer here: https://stackoverflow.com/questions/3898363/set-specific-dns-server-using-dns-resolver-pythondns
Answer: The most commonly used DNS library for Python seems to be dnspython. After that, see this answer: https://stackoverflow.com/a/6947181/4822566
Answer: You do not need a specific Python library to resolve hostnames in general, as this is a core libc feature and hence a core feature of any programming language. This was written at the time your question was not specific to using the DNS, in which case using a DNS library is of course the only solution. The below text remains correct for generic resolution of names from Python.
See socket.getaddrinfo at https://docs.python.org/3.8/library/socket.html#socket.getaddrinfo whose description is:

Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service.

and

The function returns a list of 5-tuples with the following structure:
(family, type, proto, canonname, sockaddr)

and their example:
>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,  6, '',
('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
(<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,  6, '',
('126.96.36.199', 80))]

This may or may not use the DNS as the libc will use /etc/resolv.conf, /etc/gai.conf, /etc/nsswitch.conf and /etc/hosts (typically on an Unix system) to decide how to resolve names and where.
As for

My usecase is checking if DNS is working.

This is too vague. How do you define "DNS is working"? You mean your specifc recursive nameserver replies? Or some distant one? Or is DNSSEC activated? Or are answers spoofed or not? Or are some specific domain name correctly configured and responding to DNS queries? etc.
Comment: Your solution uses /etc/hosts which should not be done in this particular case. The use case is strange, but this is, what the question is about. The file /etc/hosts most not be used in this case. I want to check that the dns server is reachable and returns a sane result for resolving the name of the current host. DNSSEC or recursive resolution does not matter here. Your question is valid, but it is the valid answer to a slightly different question.
Comment: *Your solution uses /etc/hosts* Not necessarily true, it depends how `nsswitch.conf` is configured. For your title "Resolve hostname in Python" the above works.

Resolve hostname with Python (via DNS)


Is it ok to dipose a DbCommand before iterating the DbDataReader

Question: I have a simple application that needs to execute certain queries to get the database schema information. I have written a simple method that executes a query and returns a reader, something like this -
<code>public static DbDataReader ExecuteQuery(DbConnection connection,string sql)
{
   DbCommand command = connection.CreateCommand();
   command.CommandText = sql;

   using(command)
   {
      return command.ExecuteReader();
   }
}
</code>
The calling code does close the connection and dispose the reader and connection appropriately.
My question - Is it ok/right to dipose the command instance (as is done via the using block) before iterating the reader? I do not expect any OUT parameters to be populated after closing the reader. Does the ADO.NET API have any strict guidelines regarding this?
Answer: When you leave the using block in your method command is closed and disposed, if you are able to use the reader from the caller means it still work.
Commands are a mean to execute statements against a connection but do not hold any data this is the reason why this works. As long as the connection is open you can use your reader.
PS. there is also a nice overload of ExecuteReader which instructs the Reader to close the connection directly for you on disposal, useful when connection is created locally like you do with the command and not passed from outside.
Comment: This sounds a bit like a trial and error approach though, can you guarantee that readers from all ADO.NET implementations ignore the command's state? It is technically possible to make it dependent, as the command is the only object able to create the reader.
Comment: @Davide - ya I know the 'using' is disposing the command and hence the question. The problem is that the code seems to work for certain drivers but not all!
Comment: No is not try error approach is the way so many data layers are done. Mostly command object is creared and with using or not disposed in the method anyway and reader is accessible and usable outside. If this did not work there would be so many broken DAL out there!
Comment: actually, the command holds the parameter values; and `out` / `return` parameter values are only updated at the **end** of the TDS stream, i.e. when the reader gets to the end. So *technically*, the reader *does* talk back to state of the command. However, I suspect it'll work fine either way.
Comment: Marc if you want to read an out param you surely are still in the method and command is still there as you wont be able to access it from calling method if you only got back the reader.
Comment: @Davide - As Marc mentioned, the OUT/return parameters are populated with appropriate values only after the reader is closed, which obviously happens somewhere outside in the calling code. So although I can access the command in the method the parameters won't have the right value.
Side note - OUT/return parameters are of no interest in my use case


Spring Data Cassandra ClassNotFoundException

Question: get this error when start spring boot application
my spring boot application
Spring Boot version 2.2.4
and cassandra version
spring-data-cassandra 3.0.1.RELEASE
this is my error
<code>Caused by: java.lang.ClassNotFoundException: org.springframework.data.convert.CustomConversions$ConverterConfiguration
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 113 common frames omitted
</code>
and my config class
<code> public class CassandraConfig {
    @Bean
    public CqlSessionFactoryBean session() {

        CqlSessionFactoryBean session = new CqlSessionFactoryBean();
        session.setContactPoints("localhost");
        session.setKeyspaceName("mykeyspace");
        session.setUsername("cassandra");
        session.setPassword("cassandra");
        session.setLocalDatacenter("dc1");
        return session;
    }

    @Bean
    public SessionFactoryFactoryBean sessionFactory(CqlSession session, CassandraConverter converter) {

        SessionFactoryFactoryBean sessionFactory = new SessionFactoryFactoryBean();
        sessionFactory.setSession(session);
        sessionFactory.setConverter(converter);
        sessionFactory.setSchemaAction(SchemaAction.NONE);

        return sessionFactory;
    }

    @Bean
    public CassandraMappingContext mappingContext(CqlSession cqlSession) {

        CassandraMappingContext mappingContext = new CassandraMappingContext();
        mappingContext.setUserTypeResolver(new SimpleUserTypeResolver(cqlSession));

        return mappingContext;
    }

    @Bean
    public CassandraConverter converter(CassandraMappingContext mappingContext) {
        return new MappingCassandraConverter(mappingContext);
    }

    @Bean
    public CassandraOperations cassandraTemplate(SessionFactory sessionFactory, CassandraConverter converter) {
        return new CassandraTemplate(sessionFactory, converter);
    }

}
</code>
how can in fix this error?
Answer: Those versions are incompatible. spring-data-cassandra had a significant breaking changes from the 2.2.x version to 3.x.x version.
To use the 3.x.x version of Cassandra, you will to upgrade spring to 2.3.x. Either that or you will need to downgrade to 2.2.x version of spring-data-cassandra.
Answer: i'm get a same exception,
when i upgrade the spring boot version, it's work!
<code> <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>


Entity Framework Core - binding SP return value to project Model without re-mapping

Question: In below scenario, The execution of stored procedure is returning the known columns matching with type "LocalModel"
Is there a way in EF Core to query entity and bind that back to anonymous type.
List<LocalModel> ModelList= context.Table.FromSql(Stored_Proc +" @Param", _moduleName).ToList();

Like, In normal EF this can achieved as below.
List<LocalModel> ModelList= context.Database.SqlQuery<LocalModel>("exec Stored_Proc").ToList<LocalModel>();

Comment: I don't see any difference between EF Core and "normal" EF examples - both are returning `LocalModel` instances. So what is the issue/question again?
Comment: First query is to show what I was trying in Core, that do not work in EF Core
Answer: If you use FromSql on the DbSet of the type you want to bind to, then it will create instances of that POCO class. For example:
Assuming:
public DbSet<LocalModel> LocalModels { get; set; }

Then:
context.LocalModels.FromSql(...).ToList();

If you're working generically, or just if you prefer, you can use Set<T>() instead of the actual DbSet property name:
context.Set<LocalModel>().FromSql(...).ToList();


Questions about fulltext-index performance

Question: I searched for a search engine, but the price is expensive or it seems to take a lot of time to build, so I want to save it through 'singer name music name' and use it as a fullText-index.
However, even if I keep searching, it is constantly compared with like, and only the advantages of the function are introduced, and the disadvantages are hard to see even if I look for them.
Currently, there is no big problem except that the index grows when about 30,000 data is created, so I am going to use it, but I wonder what the downsides of fulltext-index are!
If you search additionally, they say that it is better to install a morpheme analyzer, but I plan to use an ngram parser with ngram=1.
Addition) If too large an index can be a problem, I wonder how to increase the ngram size and search like like for 2 letters or less.
Answer: (When it is well suited, FULLTEXT is very fast; meanwhile...)
Downsides of FULLTEXT.  Note that many can be worked around, but it takes deliberate extra code.

The definition of a "letter".  That is, certain punctuation marks are treated as word breaks.  You might be able to live with it, or you might sanitize the input (see below).
Min word length -- The default is 3.  You can lower that to 2 or even 1, but there is a price to pay.  Avoiding short words in the "sanitization" is one solution.
Short words and stop words cannot be forced to be present.  (I think this is a bug.)  AGAINST ("+john +q +smith" IN BOOLEAN MODE) will always fail.  This, on the other hand, will succeed, though it may deliver too many rows: AGAINST ("+john q +smith" IN BOOLEAN MODE).  That is, "John W Smith" will succeed.  See "fine tuning", below.
When the order of words is important (you want "foo bar", but not "bar foo" nor "foo blah blah bar"), there are some quoting you can do to force that in FT.  (Watch out for short words.)
"stop words" -- There is a list of words not to index (eg, "the").  You can point to a different list.  (I don't have the details off the top of my head.)
All or none -- Many of the tunable things I mention here apply to all FT indexes in the system.  You may need to find a workaround to get the effect of different settings in different tables.

Sanitizing the input.  Part numbers and model numbers are a nuisance to deal with because of the liberties that manufacturers take.  Example: "Model 3" -- "Model" is a nice fulltext 'word', but '3' is not.  You could [perhaps] tweak the input (when INSERTing) to say "Model3".  Another example "xyz-123".  Another:  "John Q. Smith"
Combining columns.  It may be beneficial to put together likely FT strings (from many columns) and throw them into a single column that is purely for searching.  Do the sanitizing as you insert the data.
Fine-tuning.  Here's one way to solve some of the hiccups:
WHERE MATCH(texts) AGAINST ("+john q +smith" IN BOOLEAN MODE)
  AND texts LIKE "%John Q. Smith%"

Explanation...  The FT test will come first and be fast.  Then comes the LIKE (or REGEXP) which is much slower, but is not a problem because it is being applied only to those rows that passed the FT test.  Example:  "John Jones and Phil Smith" will pass the MATCH, but then be filtered out by the LIKE.
Some more notes:  http://mysql.rjweb.org/doc.php/myisam2innodb#fulltext
Your question starts out implying "words", then digresses into cases where "ngram" may be better.  If it is "names" (singers, music titles, etc), then ngram is probably not worth considering.
Comment: Hmmm -- I should probably copy some of this into my blog.
Comment: I think this will be a very good post. All right :)


Choosing a discrete distribution

Question: Initially modelled as a normal distribution, I'm now trying to capture the probability that human judgments take on a scale of -100 to 100 (arbitrary discrete judgements) using some kind of discrete distribution that's bounded. The distribution has to be centred around a specified mean and SD, but I'm not sure what kind of distribution I could use. Categorical? Multinomial?
I'm not well versed in statistics so any help would be much appreciated.
Comment: Could you tell us more about your data? What is it? Why can't you just use Gaussian? You probably are not assuming that those "judgments" are discrete by nature?
Comment: Started with Gaussian, but say participants can choose on an integer scale of -100 to 100 (not 99.3453), and it must be bounded, then a Gaussian doesn't capture this. As for the data, participants are asked to make confidence judgments on cause-effect trials.
Comment: And you assume that people in their heads have a scale consisting of exactly 201 points, so they can like something at exactly 50 points or 51 points, but anything in between is impossible..?
Comment: You can use a beta distribution latent variable Y ( for rating in ppls head - @Tim suggestion), but then you observe only the integer version of it , X=[Y].  Now do maximum likelihood on beta parameters but observing only rounded Y.
Answer: If you have a ruler and read from it that something measures 8cm and 2mm, you don't assume that the measurement is exact. You assume it's approximate, with some measurement error. The same with measuring things in social sciences. When using the Likert scale, we don't assume that people can have only 5, 7, 201, etc possible states that are measured, but we use it to approximately measure the underlying phenomenon. So in most cases, you don't need a discrete distribution for such cases, the same as we don't use discrete distributions for things like size, weight, time, etc while neither of them is measured with infinite permission. Discrete distributions are needed for inherently discrete things, like counts.

Choosing a discrete distribution


How is (male) falsetto taught?

Question: I've encountered men and boys who are seemingly unable to sing in falsetto. They sing as high as their chest voice will allow, straining at the top, but are unable to slip into falsetto.
Presuming this isn't a physiological impossibility for them, how would a voice teacher approach teaching falsetto to them?
I've framed the question around male voices, because I'm allowing that men and women are trained differently, and my particular encounters with this limitation has only involved male voices. However, there's no reason answers can't address both.
Comment: idk… though for 30 years of my life I had just that… 3 ½ octaves of 'full voice' but am incapable of singing any higher by switching to falsetto. I *can* sing falsetto, just with the same limits. [I've now lost a lot of the top end, but the limitation remains]
Comment: Were they trained in any kind of singing before?  Do they have a cultural/psychological aversion to singing in that register?
Comment: @user1079505 I'm specifically asking about falsetto. My understanding of the difference is that it has to do with how strong the vocal cord vibrations are. But if teaching one teachers the other, then a discussion of teaching head voice would work for my purposes.
Comment: @Theodore good questions. No and no.
Comment: Very interesting, but IMO phrased a bit broadly. What would you like to know specifically about how male falsetto is taught?
Comment: @user45266 I don't know how to answer that. I'm wondering how a voice teacher would approach a student who is seemingly unable to produce a falsetto tone and can sing only in chest voice.
Comment: Oh, you mean "how would a voice teacher teach it to *those* men and boys", right?
Comment: @user45266 Yes. That's what I was trying to get at.
Comment: Why specifically male? Do you think women all magically know how to switch and never need to learn it?
Comment: @Divizna - The general vibe I've read is that women's voice ranges tend to go high enough that falsetto isn't necessary (and sounds terrible in some soprano roles like *The Phantom of the Opera*'s Christine).
Comment: @Divizna It's because I'm allowing that men and women are taught differently. I've updated the question to reflect that.
Comment: I teach kids from age 3-4 through to age 12, or early childhood up until/into voice change at puberty.  I've noticed anecdotally that ... (1) those boys who can be encouraged to sing in their head voice before puberty have a much easier time singing in head voice or falsetto once their voce changes, and (2) many boys in America naturally avoid singing in their upper registers to avoid sounding "like a girl."  So while I don't have an answer for how to teach a post-pubescent boy or adult to access these registers, I do think that good training before puberty can make a difference.
Comment: But... if you listen to pop music, both present and older, both male and female singers use head voice _a lot_! Anyway, question to OP, are you asking about falsetto specifically, or about head voice too? I know (some people claim that) there is a difference between the two, but I fail to understand it.
Comment: "presuming this isn't a physical impossibility..."   I rather doubt it's even mildly difficult for those able to hit falsetto to start doing so.
Comment: @CarlWitthoft Then why haven't they?
Comment: @Dekkadeci Well I sure do have to switch if I want to sing along to [No More Lonely Nights](https://www.youtube.com/watch?v=-T_ZkacL9A0). Granted, I've never been trained (and I'm far from a soprano)... But, I've read that (male, of course) theoreticists long thought that female falsetto doesn't exist because they couldn't hear a difference in timber and so they claimed that women are incapable of it but have much larger normal voice range instead. Which is a load of bwahaha what.
Comment: @Divizna - I've also read that females sing in head voice significantly more easily than males because the head voice transition is at around the E to F above Middle C. (If head voice truly means "no more chest vibrations", this seems about right for my voice.)
Answer: Trying to describe any vocal 'process' can be very difficult, and often ends up by using nebulous instructions like "sing through the top of your head".
Teaching by example is often more beneficial than descriptions. Show them how you do it. Try to find some exercise that enables falsetto.
Falsetto can require more diaphragm pressure and breath control -- novices often complain that they can't sing as long phrases as with their chest voice; so it can indeed be more difficult, physically.
A first approach is to ask them to mimic yodelling: sing a low note and try to 'flip it' to a high one, without sliding.
Many people find their falsetto as a more relaxed method of singing higher notes, so encouragement to relax into it may help. Short repeated percussive 'ahs' at a high pitch may be a way to feel different ways of making the sound.

How is (male) falsetto taught?


How to transform the following dataframe using R

Question: I am using R for generating statistical reports for past 6 months. I got a requirement as mentioned below:
Input DataFrame:
 FY_Qtr       region     Lic_type    revenue
 2009 Q1         AP       NCV       126.67
 2010 Q1         NA       NCV       395.80
 2011 Q1         LA       NCV       469.10
 2012 Q1         EMEA     MR        173.85
 2013 Q1         JAPAN    MR        140.24

Expected Data:
  FY_Qtr       AP.NCV   NA.NCV   LA.NCV   EMEA.MR JAPAN.MR
 2009 Q1       126.67   -           -       -       -
 2010 Q1        -       395.80      -       -       -
 2011 Q1        -       -           469.10  -       -
 2012 Q1        -       -           -       173.85  -
 2013 Q1        -       -           -       -       140.24

Can any one help me on this to get the Expected Data?
Answer: This is exactly the type of task that the 'reshape2' package was built for.
Setup: Let's load in the sample data.
data <- read.table(text="
     FY_Qtr       region     Lic_type    revenue
     '2009 Q1'         'AP'       NCV       126.67
     '2010 Q1'         'NA'       NCV       395.80
     '2011 Q1'         'LA'       NCV       469.10
     '2012 Q1'         'EMEA'     MR        173.85
     '2013 Q1'         'JAPAN'    MR        140.24
    ", header=TRUE)

Cast the data: Essentially what you have right now is considered "melted" data.  You have ID columns with a separate row for every set of variable combinations and an assigned value.  This means you can skip the usual 'reshape2' step of melting the data first and skip straight to casting, like so:
library(reshape2)

dcast(data, FY_Qtr ~ region + Lic_type, value.var='revenue')

#    FY_Qtr AP_NCV EMEA_MR JAPAN_MR LA_NCV NA_NCV
# 1 2009 Q1 126.67      NA       NA     NA     NA
# 2 2010 Q1     NA      NA       NA     NA  395.8
# 3 2011 Q1     NA      NA       NA  469.1     NA
# 4 2012 Q1     NA  173.85       NA     NA     NA
# 5 2013 Q1     NA      NA   140.24     NA     NA

We're using the 'dcast' function, because we're wanting to output a data frame.  Then, we are specifying your melted data as the input.  The next part explains how to relate the data, with the left-hand side of the '~' equation specifying the ID (FY_Qtr) and the right-hand side of the '~' specifying the column variable combinations to use.  The 'value.var' argument then specifies (as a string) the variable to be used as the value.
Comment: @user2661475 Glad you're happy!  Please click the checkmark next to the answer to indicate that the solution worked for you to close out the question.
Answer: +1 to @Dinre; that's a good solution, and it's worth learning reshape2.  In case you want to see how this can be done in base R, it's not too difficult:
data <- read.table(text="FY_Qtr       region     Lic_type    revenue
                      '2009 Q1'         'AP'       NCV       126.67
                      '2010 Q1'         'NA'       NCV       395.80
                      '2011 Q1'         'LA'       NCV       469.10
                      '2012 Q1'         'EMEA'     MR        173.85
                      '2013 Q1'         'JAPAN'    MR        140.24",
                   header=TRUE)

expected_data           <- matrix(NA, nrow=5, ncol=5)
rownames(expected_data) <- data$FY_Qtr
colnames(expected_data) <- with(data, paste(region, Lic_type, sep="."))
diag(expected_data)     <- data$revenue
expected_data
        AP.NCV NA.NCV LA.NCV EMEA.MR JAPAN.MR
2009 Q1 126.67     NA     NA      NA       NA
2010 Q1     NA  395.8     NA      NA       NA
2011 Q1     NA     NA  469.1      NA       NA
2012 Q1     NA     NA     NA  173.85       NA
2013 Q1     NA     NA     NA      NA   140.24


Enforce URL rules when posting content types

Question: so I created a content type "Regions" - This includes the 13 provinces in Canada listed as individual terms.
When creating a new post with the content type "Regions", you have to choose which term to post into. Let's say I would like to post a page "TEST POST ONTARIO", I post it in the term "Ontario"
I would like the URL from this post to be automatically changed to
www.website.com/region/on/testpost
by default, it posts to www.website.com/testpost
Is there a way to automate the url for when this content type is created? or would you have to manually change the url alias every post?
Answer: You want to use the PathAuto module.  This lets you create default patterns on a per content type basis that can use information from fields on the node to create a URL.


Show that $f_n(x)$ converges uniformly to a continuous function on $[0,1 ]$

Question: Let $f_0(x): [0,1 ] \rightarrow \mathbb{R}$, where $f_0(x)=x$.
Define $f_n(x)=-1 +\frac{1}{3} \int_0 ^1 \cos (3x^2+y^2+1) f_{n-1}(y) dy$
Show that $f_n(x)$ converges uniformly to a continuous function on $[0,1 ]$.
I thought of ways of solving this questions.

First we want to find a function $f(x)$ that $f_n(x)$ converges to, then use the $\epsilon-\delta$ definition. But the integral part just makes it difficult to proceed this way.

We can try the Weierestrass M-test, by first proving $f_n$ is continuous. Then use the Weierestrass M-test to prove uniform convergence. Then conclude that $f$ is continuous. But I had trouble finding a bound for the M-test. I think it's the recursive part that is making it difficult. But I'm sort of guessing $|f_n|\leq 1$. But $\sum 1$ does not converge.

Any help will be appreciated!
Comment: The $M$-test tells you about series of functions, not sequences - so you should be trying to bound $|f_{n + 1} - f_n|$. You can show $\lVert f_{n + 1} - f_n \rVert_\infty \le \tfrac 13 \lVert f_n - f_{n - 1} \rVert_\infty$ using the calculation from the answer below, and then the $M$-test actually applies, as you can bound the differences by a geometric series. This is essentially re-proving part of the contraction mapping theorem.
Answer: Use the contraction mapping theorem applied to the space $C[0,1]$ and the mapping $T:C[0,1]\to C[0,1]$ with
$$Tf(x)=-1+\frac{1}{3}\int_0^1\cos\left(3x^2+y^2+1\right)f(y)\,dy.$$
To see that this is a contraction, note that
$$\begin{align*}
\left|Tf(x)-Tg(x)\right|&=\frac{1}{3}\left|\int_0^1\cos\left(3x^2+y^2+1\right)\big(f(y)-g(y)\big)dy\right| \\
&\leq\frac{1}{3}\int_0^1\left|\cos\left(3x^2+y^2+1\right)\right|\left|f(y)-g(y)\right|\,dy \\
&\leq\frac{1}{3}\sup_{x\in[0,1]}\left|f(x)-g(x)\right|,
\end{align*}$$
and thus
$$\left\Vert Tf-Tg\right\Vert=\sup_{x\in[0,1]}\left|Tf(x)-Tg(x)\right|\leq\frac{1}{3}\sup_{x\in[0,1]}\left|f(x)-g(x)\right|=\frac{1}{3}\left\Vert f-g\right\Vert.$$


Can thread creation within OS internals run concurrently?

Question: Suppose we have a dual-core machine with a mainstream, modern OS capable to utilize both the cores.
If I have two threads, P1 and Q1 within the same process, and they happen to commence creating child threads, say, P2 and Q2, at approximately the same machine cycle, will OS perform the thread creation concurrently?
I heard thread creation is expensive, so the question came forth...
Thanks in advance.
Comment: Are the two threads spawned within the same process or separate processes? It matters. Threads have a parent process they must initiate from. With that in mind, are you considering the parent process the first thread? Processes and threads are not the same.
Answer: Any reasonably well designed OS can have multiple processors executing kernel code at the same time. Therefore some of the tasks involved in a thread creation can be happening concurrently. But there will be some necessary serialization to manipulate some shared data structures (e.g. allocating memory, inserting a newly created threat structure into a global list). The processors could contend for the same lock thereby reducing concurrency.
Systems/applications which make new threads so often that the overhead of thread creation actually matters are probably designed wrong (doing too little useful work in a thread relative to the startup time, and not taking advantage of the obvious optimization of reusing short-lived threads from a pool).
Answer: It will be sorta-concurrently.  There are aspects of thread-creation that cannot proceed in parallel - it would be unfortunate if the kernel memory-manager allocated both threads the same stack!
Thread creation is sufficiently expensive that it's worth while avoiding doing it at all during an app. run, hence the popularity of thread pools. Long-running tasks that block can be threaded off and left for the life of the app - often this means that explicit thread termination, (awkward at best, almost impossible at worst, from user code), is not necessary.
I think developers continually start and stop threads because they like to think of them as 'functions',  where you 'pass parameters' in at the start and 'return' results when the thread ends.  Ths is not the best way of conceptualizing threads.


Is there a function to return all the multisite names?

Question: Is there a Drupal function to return all the multisite names?
I have searched a bit but have not come up with anything.
Comment: There would (should?) not be an easy method in the Drupal API to do this, because multi-site instances are not supposed to be aware of each other. That said... I don't know what you're trying to achieve, but perhaps you could make it a requirement that the developer adds a sites.php file (see [example.sites.php](https://api.drupal.org/api/drupal/sites!example.sites.php/7)) and parse that file.
Comment: Are you talking about domain access? What is a multisite name for you?
Comment: I mean if I have sites/foo.com and sites/example.com, it would return array('foo.com', 'example.com').
Comment: ok, I'm not sure there's something built for this
Comment: each instance of drupal isn't necessarily aware of other instances. You could write a custom module that does a simple directory search under sites to return the values you want.
Comment: Thanks guys, I came up with a not so elegant solution that I will post as an answer for now.
Comment: In my testing so far sites.php gets loaded after drushrc.php. But yeah, I am trying to get drush to look in a sites/{sitename}/drush/ folder to load drushrc.php, aliases and commands per multisite.
Answer: Okay, this is what I am using for now in a drushrc.php file. If you can improve upon this please post a new answer. Thanks
<code>// Gets a list of all directories in /sites.
$sites = glob(drush_locate_root() . '/sites/*', GLOB_ONLYDIR);
// Strips the absolute path except for the last name.
$sites = array_map('basename', $sites);
// Removes the 'all' folder.
$sites = array_diff($sites, array('all'));
</code>
Comment: I like this solution but have replaced `drush_locate_root()` with `DRUPAL_ROOT`. It is set in index.php as the current working directory.
Answer: Another solution inspired by some team members and @marcvangend.
<code>if (is_file(__DIR__ . '/../../sites.php')) {
  include __DIR__ . '/../../sites.php';
  $sites = array_keys($multisites);
  $sites[] = 'default';
}
</code>
Comment: Can I ask why do you need to do that? Why do you need the list of sites inside Drupal?
Comment: To make Drush look in a sites/{sitename}/drush/ folder for ../drush/commands, ../drush/aliases and ../drush/drushrc.php files.
Comment: This supposes that the project makes use of the sites.php file for multisite aliasing. As a side note, the default variable name in sites.php is `$sites`.


Log4j 2.x com vários arquivos dependendo do nivel

Question: Sou iniciante no log4j. Quero criar um arquivo diferente para cada nivel de log (warn, error e etc).
Tenho o seguinte arquivo de configuração xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true" name="XMLConfigTest" packages="org.apache.logging.log4j">
  <Properties>
    <Property name="ErrorFileName">c:/ripper/ripper_error.log</Property>
     <Property name="WarningFileName">c:/ripper/ripper_warning.log</Property>
  </Properties>

  <Appenders>
    <Appender type="Console" name="STDOUT">
      <Layout type="PatternLayout" pattern="%m MDC%X%n"/>
      <Filters>
        <Filter type="MarkerFilter" marker="FLOW" onMatch="DENY" onMismatch="NEUTRAL"/>
        <Filter type="MarkerFilter" marker="EXCEPTION" onMatch="DENY" onMismatch="ACCEPT"/>
      </Filters>
    </Appender>

    <Appender type="File" name="File" fileName="${ErrorFileName}">
      <Layout type="PatternLayout">
        <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
      </Layout>
    </Appender>

    <Appender type="File" name="FileWarning" fileName="${WarningFileName}">
      <Layout type="PatternLayout">
        <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
      </Layout>
    </Appender>

  </Appenders>

  <Loggers>
    <Logger name="warn" level="warn">
        <AppenderRef ref="FileWarning" />
    </Logger>
    <Root>
      <AppenderRef ref="File"/>
    </Root>
  </Loggers>
</Configuration>

Na minha classe está assim:

public class HashMapFactory {
final static Logger logger = LogManager.getLogger(HashMapFactory.class);

//...

logger.error("Erro! A chaveEL "+chaveEL+" está duplicada ou não há terminal cadastrado na TotalGirosLinhaEstacao.");
logger.warn("teste");
}

Ele só grava o do nivel error no arquivo ripper_erro.log. O warn ele não grava em arquivo algum.
Como eu tenho que fazer pra gravar no ripper_warning.log os eventos do nivel warn?
Answer: Cheguei nessa solução:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true" name="XMLConfigTest" packages="org.apache.logging.log4j">
  <Properties>
    <Property name="Dir">/log/ripper</Property>
    <Property name="ErrorFileName">${Dir}/log/ripper_error.log</Property>
    <Property name="WarnFileName">${Dir}/log/ripper_warn.log</Property>
    <Property name="InfoFileName">${Dir}/log/ripper_info.log</Property>

    <Property name="pattern">%d %p %C{1.} [%t] %m%n</Property>
    <Property name="name">ripper</Property>
  </Properties>

  <Appenders>
    <Appender type="File" name="FileError" fileName="${ErrorFileName}">
      <Layout type="PatternLayout">
        <Pattern>${pattern}</Pattern>
      </Layout>
      <Filters>
            <ThresholdFilter level="ERROR" onMatch="ACCEPT" />
        </Filters>
    </Appender>

    <Appender type="File" name="FileWarn" fileName="${WarnFileName}">
      <Layout type="PatternLayout">
        <Pattern>${pattern}</Pattern>
      </Layout>
      <Filters>
            <ThresholdFilter level="WARN" onMatch="ACCEPT" />
        </Filters>
    </Appender>
    <Appender type="File" name="FileInfo" fileName="${InfoFileName}">
      <Layout type="PatternLayout">
        <Pattern>${pattern}</Pattern>
      </Layout>
      <Filters>
            <ThresholdFilter level="INFO" onMatch="ACCEPT" />
        </Filters>
    </Appender>
  </Appenders>

  <Loggers>

    <Logger name="warnLog" level="WARN">
      <AppenderRef ref="FileWarn" level="WARN"/>
    </Logger>

    <Logger name="errorLog" level="ERROR">
      <AppenderRef ref="FileWarn" level="ERROR"/>
    </Logger>

    <Logger name="infoLog" level="INFO">
      <AppenderRef ref="FileInfo" level="INFO"/>
    </Logger>

    <Root>
      <AppenderRef ref="FileError" level="ERROR"/>
    </Root>

  </Loggers>
</Configuration>

E na minha classe:
final static Logger logger = LogManager.getLogger(HashMapFactory.class);
final static Logger loggerWarn = LogManager.getLogger("warnLog");

...
loggerWarn.warn("Estação não encontrada para a linha "+linha+" operada pela empresa "+empresa+" na ConsolidacaoLinhasPorEstacao.");
logger.error("Erro! Não existe movimento para a ERN neste dia no rateio exclusivo.");


Problem from Sidney Resnick A Probability Path.

Question: $X_{i}\sim bern(\frac{1}{i})$
$S_{n}=\sum_{i=1}^{n}X_{i}$.
Then $\frac{S_{n}}{\ln(n)}\xrightarrow{a.s} 1$
I think I somewhere have to use that $\frac{H_{n}}{\ln(n)}\to 1$. Where $H_{n}$ is the nth harmonic number. As $\sum_{i=1}^{n}\frac{1}{i}$ and $\ln(n)$ just screams out Euler-Mascheroni constant to me.
So I try to bring in expectation somewhere to make that $H_{n}$ appear.
$$P\left(\left|\frac{S_{n}}{\ln(n)}-1\right|\geq \epsilon\right)\leq \frac{E\left[\frac{S_{n}}{\ln(n)}-1\right]}{\epsilon}$$ by Markov's inequality.
This gives me that as $n\to\infty$. $P(|\frac{S_{n}}{\ln(n)}-1|\geq \epsilon)\to 0$ .
But this does not give me almost sure convergence.
also I cannot apply Strong Law of Large numbers as the rv's are not iid. Can anyone tell me how I should proceed. I am lost for ideas .
Comment: You can try with [Chernoff bound](https://en.wikipedia.org/wiki/Chernoff_bound) and other concentration inequalities. In particular you can compute $$\ln\mathbb E\Bigl[\mathrm e^{\theta S_n}\Bigr]=\sum_{i=1}^n\ln\Bigl(1+\frac1i\bigl(\mathrm e^\theta-1\bigr)\Bigr)\sim\bigl(\mathrm e^\theta-1\bigr)\ln n.$$
Comment: Do you know martingale theory?
Comment: No man . I am in a introduction to probability course . Well what I mean to say is this is my first time doing probability
Comment: Try to prove that  $\sum P(|\frac{S_{n}}{\ln(n)}-1| <\infty$. That would be enough, by Borel -Cantelli Lemma.
Comment: @KaviRamaMurthy Yeah I tried that also. But how do I do that ?. $P(|\frac{S_{n}}{\ln(n)}-1|>\epsilon)=P(S_{n}>\ln(n)+\epsilon\cdot\ln(n))+P(S_{n}<\ln(n)-\epsilon\ln(n))$ . Now how do I proceed ?.  I was stuck at this part as I do not understand how to find this probability let alone finding a way to upper bound it by a convergent series.
Comment: @nejimban . I managed to use what you said to prove convergence of $\sum_{n=1}^{\infty}P(S_{n}>\ln(n)(1+\epsilon))$. What should I use for the sum $\sum_{n=1}^{\infty}P(S_{n}<\ln(n)(1-\epsilon))$. ?
Comment: @Hundred-eyes Doesn't it work in this direction as well? As in [this paragraph](https://en.wikipedia.org/wiki/Chernoff_bound#The_generic_bound).
Comment: @nejimban . It holds but I could not make any use of it Mainly because when we use it we get $e^{\theta(1-\epsilon)\ln(n)}$ in the numerator.
Comment: (I haven't checked details) It can help centering the variables (replace $X_i$ by $X'_i=X_i-\mathbb E[X_i]$). At least [Bernstein's inequality](https://en.wikipedia.org/wiki/Bernstein_inequalities_(probability_theory)) seems to work (use it with $t:=H_n$, $M:=1$, once for the family $(X'_i)_{i\ge1}$ and once for $(-X'_i)_{i\ge1}$ to get the two bounds). You should have bounds approximately equal to $$\exp\!\left(-\frac{\frac12t^2}{\frac13Mt}\right)\approx\exp\!\left(-\frac32\ln n\right)\!.$$
Bernstein's inequality is proved from Chernoff bound. I can try to write a full answer later.
Answer: I think you can use the following result to answer this:

Suppose $\{X_n\}_{n\in \mathbb N}$ is a sequence of independent random variables with $\operatorname{Var}(X_n)<\infty$ for every $n\in \mathbb N$. If $S_n=\sum\limits_{i=1}^n X_i$, then
$$\sum_{n=1}^\infty \frac{\operatorname{Var}(X_n)}{b_n^2}<\infty\,,\, b_n \uparrow \infty \implies \frac{S_n-E(S_n)}{b_n}\stackrel{\text{a.s.}}\longrightarrow 0$$

The above can be shown by combining Kronecker's lemma and Kolmogorov's convergence criterion. See, e.g., A Probability Path by Sidney Resnick.
If you take $b_n= \ln n$, then
$$\sum_{n=1}^\infty \frac{\operatorname{Var}(X_n)}{b_n^2}=\sum_{n=2}^\infty \frac{n-1}{n^2 (\ln n)^2}<\sum_{n=2}^\infty \frac{1}{n (\ln n)^2}<\infty\,,$$
where the convergence of the last series is discussed here.
Therefore,
$$\frac{S_n-E(S_n)}{b_n}=\frac{S_n}{\ln n}-\frac{H_n}{\ln n} \stackrel{\text{a.s.}}\longrightarrow 0$$
and $$\frac{H_n}{\ln n}\to 1$$
together imply
$$\frac{S_n}{\ln n}\stackrel{\text{a.s.}}\longrightarrow 1$$
Comment: Forgot to mention that $b_n$ is a monotone sequence in the quoted result.


MobX autorun doesn't get dependency it should

Question: This code I took from https://mobx.js.org/understanding-reactivity.html
import { makeAutoObservable, autorun, getDependencyTree  } from "mobx";

class Message {
  title;
  author;
  likes;
  constructor(title, author, likes) {
    makeAutoObservable(this);
    this.title = title;
    this.author = author;
    this.likes = likes;
  }

  updateTitle(title) {
    this.title = title;
  }
}

let message = new Message("Foo", { name: "Michel" }, ["Joe", "Sara"]);

const disposer = autorun(() => {
  console.log(message.title);
});

console.log(getDependencyTree(disposer));
message.updateTitle("Bar");
message.updateTitle("gasdg");

But in consolse I get this:
Foo
index.js:114 {name: 'Autorun@2'}

It doesn't pick up message.title as dependency, please help me understand why!
Comment: Class properties seem to be very dependent on environment. The code in your question doesn't work in e.g. a Stack Overflow code snippet, but [it works in a CodeSandbox](https://codesandbox.io/s/serene-cannon-11wxpk?file=/src/index.js).
Answer: By default make(Auto)Observable only supports properties that are already defined, so you need to define every property inside constructor or make it nullable like that: author = null, or add default value likes = 0:
class Message {
  // Or add default values here
  title = '';
  author = null;
  likes = 0;
  constructor(title, author, likes) {
    // Initialise properties as first thing
    this.title = title;
    this.author = author;
    this.likes = likes;

    makeAutoObservable(this);
  }

  updateTitle(title) {
    this.title = title;
  }
}

Alternatively you might want to try to reconfigure how class properties initialisation works, using useDefineForClassFields TS compiler flag:
"compilerOptions": {
  "useDefineForClassFields": true
},

Comment: as a Tholle said it works like that in different environment,
But thanks to you know I'm better understanding how make(Auto)Observable works, default values helped!)


Number of roots of equation $3^{|x|}-|2-|x||=1$

Question: Number of roots of equation $3^{|x|}-|2-|x||=1$
My approach:-
If $x>0$
$$3^x-2+x=1$$
$$3^x+x=3$$
$$x=3-3^x$$
After this I can't solve this problem
Comment: How did you get from the second line into the third line? The log is not a liner function
Comment: I just take log both sides
Comment: Observe that if $y$ is a solution, so is $-y$
Comment: @AbhishekKumar $log(3^x+x)\ne lon(3^x)+log(x)$
Comment: Desmos shows two roots but I'm pretty sure there are more. This is odd.
Answer: So we can think of this problem in separate cases:

$x<-2$
$-2\leq x \leq 0$
$0\leq x \leq 2$
$x>2$

These cases should allow the problem to be enumerated enough to where you can solve for the solution and see if it fits within the assumed domain (otherwise, no solution exists for that case)
Answer: Using only what you wrote in the last line $$x=3-3^x$$ consider that you look for the zero of function
$$f(x)=3^x+x-3$$ The derivatives
$$f'(x)=3^x \log (3)+1 \qquad \qquad  f''(x)=3^x \log ^2(3) > 0 \,\, \forall x$$
Then, the first derivative does not cancel in the real domain and it is always positive. So, ???
In the other hand, by inspection $f(0)=-3$ and $f(1)=+1$; then ???.
Just for your curiosity, there is an analytical expression of the root in terms of Lambert function. If you follow the steps given in the linked page, you would get
$$x=3-\frac{W(27 \log (3))}{\log (3)}$$
For the remaining, take into account what is given in comments and answer.
Answer: Let $|x|=t$. Two cases for $3^t-|2-t|=1$:
$$1) \begin{cases}0\le t<2 \\ 3^t+t-3=0\end{cases} \lor \ 2) \begin{cases} t\ge 2\\ 3^t-t+1=0\end{cases}$$
Case 1: the function $f(t)=3^t+t-3$ is increasing:
$$f'(t)=3^t\ln 3+1>0,0\le t<2$$
and $f(0)=-2<f(1)=1$. Hence, there is a solution at $0<t<1$ and $x=\pm t$.
Case 2: the function $f(t)=3^t-t+1$ is increasing:
$$f'(t)=3^t\ln 3-1>0,t\ge 2$$
and $f(2)>0$. Hence, there is no solution at $t\ge 2$.
Thus, there are two roots of the original equation:
$$-1<x_1<0 \ \text{and} \ 0<x_2<1$$
Answer: How the question is the number of roots. You  can draw two functions
If $x\geq0$ then $$3^x-1=|2-x|$$

If $x<0$ then $$3^{-x}-1=|2+x|$$

There is two roots.
Comment: It's $3^{|x|}$, not $3^x$... Also, I don't think a graph can serve as an answer.
Comment: YuiTo How $3^{|x|}-1=|2-|x||$ then $x\geq0$.
Comment: But what you plot (the orange one) is $|2-x|$, not $|2-|x||...$
Comment: Moreover, notice $3^{|x|}-|2-|x||-1$ is an even function, the number of roots must be even
Comment: YuiTo if $x\geq0$ then $|x|=x$, therefor $3^{|x|}=3^x$, and $|2-|x||=|2-x|$.
Comment: [This](https://www.desmos.com/calculator/tkbzh2gj2g) should be the correct graph. There are actually two solutions, i.e. $-0.742$ and $0.742$.
Comment: Yes, the other case is wend $x<0$, there is other root.


Responsive way of placing shapes behind an image CSS?

Question: I drew the following:

I cloned this in HTML/CSS, but it's not responsive.

HTML
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./cat.css" />
    <link rel="stylesheet" href="./reset.css" />

CSS
@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap");
* {
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
}

.person {
    position: relative;
    max-width: 25em;
    margin-left: 400px;
    margin-top: 100px;
}

img {
    object-fit: contain;
    width: 100%;
}

.r1 {
    position: absolute;
    height: 50%;
    max-width: 250px;
    width: 250px;
    background-color: #EFD2B4;
    border-radius: 15px;
    top: 0;
    left: 60px;
    opacity: .2;
    transform: rotate(-17.9deg);
    z-index: 1;
}

.r2 {
    position: absolute;
    height: 50%;
    max-width: 230px;
    width: 230px;
    background-color: #E69868;
    border-radius: 15px;
    bottom: 100px;
    opacity: .2;
    left: 20px;
    transform: rotate(15deg);
    z-index: 3;
}

.r3 {
    position: absolute;
    height: 50%;
    max-width: 230px;
    width: 230px;
    background-color: #A6BB9E;
    border-radius: 15px;
    bottom: 130px;
    opacity: .2;
    left: 200px;
    transform: rotate(8.12deg);
    z-index: 2;
}

What principles should I follow to ensure that everything resizes together? I am thinking I definitely shouldn't have hardcoded pixel values for dimensions, but not quite sure how to properly size this to ensure it's as responsive as possible.
Answer: You are probably better off giving the container (.person) a fixed/scaling size and then using percentage or viewport units to scale everything inside.

.container{
  position: relative;
  border: 1px solid black;
  width: min(300px, 25vmin);
  height: min(300px, 25vmin);
}

.child{
  position: absolute;
  width: 50%;
  height: 50%;
}

.--1{
  top: 25%;
  left: 25%;
  background-color: red;
}

.--2{
  top: 10%;
  left: 10%;
  background-color: blue;
  transform: rotate(25deg);
  opacity: .5;
}

.--3{
  top: 50%;
  left: 50%;
  background-color: green;
  transform: rotate(-25deg);
  opacity: .5;
}

The major benefit of doing so is that, once you've found the placement and scale you want, everything will stay proportionate to their container, and you won't need to consider max/min sizes for the children.
Applying this principle to your code might look something like this:

@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap");
* {
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
}

.person {
    position: relative;
    max-width: 25em;
    margin-left: 400px;
    margin-top: 100px;
}

img {
    object-fit: contain;
    width: 100%;
}

.r1 {
    position: absolute;
    height: 70%;
    width: 60%;
    background-color: #EFD2B4;
    border-radius: 15px;
    top: 5%;
    left: 5%;
    opacity: .2;
    transform: rotate(-17.9deg);
    z-index: 1;
}

.r2 {
    position: absolute;
    height: 60%;
    width: 40%;
    background-color: #E69868;
    border-radius: 15px;
    bottom: 5%;
    opacity: .2;
    left: 20px;
    transform: rotate(15deg);
    z-index: 3;
}

.r3 {
    position: absolute;
    height: 70%;
    width: 60%;
    background-color: #A6BB9E;
    border-radius: 15px;
    bottom: 130px;
    opacity: .2;
    right: 10%;
    bottom: 5%;
    transform: rotate(8.12deg);
    z-index: 2;
}

Note that they now all scale in proportion to one another, and to your parent element.
Comment: Ah, great suggestion! So the absolutely positioned div dimensions are % relative to the person div as well as their margins?


What is the correct V7 family for the harmonic progression?

Question: The key I am in is B flat Major, and the progression I have is A2, G3, E4, C5, which is the vii7 chord progression. Keeping the sharing notes, what would be the correct V chord? Would it be V6/5, V2, V3/4, or V7?
Comment: Are A2, G3, E4, and C5 the notes making up a single chord? (And do you mean Eb5?)
Answer: The V chord in Bb major is F-A-C-Eb. Since the given vii7 chord has A as its lowest pitch, the corresponding V chord would be A-C-Eb-F, which is V6/5.
In general, viio7 and V7 correspond as follows:

viio7   ~ V6/5
viio6/5 ~ V4/3
viio4/3 ~ V4/2

viio4/2 does not correspond to a V7 chord as it has scale degree 6 as the lowest pitch, and the V7 chord does not contain that pitch.
For a vii7 chord in major (i.e., a half-diminished chord), the correspondence is similar, except that vii7 does not typically serve a dominant function. Nevertheless, the correspondence would be according to the lowest note of the chord.
Answer: You've spelled an a minor 7th chord, which doesn't live in B♭ due to the E♮.  However, it DOES live in the key of F, so I think the simplest progression would be something like:
ACEG (amin7)
-> ACE♭F (F7 / A)
-> B♭B♭DF. (B♭)


Congruency of Triangles, To prove BE = CF

Question: I am preparing for my maths exam on saturday, I could not find a satisfactory answer to a question I am stuck on.
http://i66.tinypic.com/nqxwn7.jpg
Given an isosceles triangle ABC in which AB = AC. If E and F be midpoints of AC and AB respectively, prove BE = CF.
I know the constructed line EF is parallel to BC but I could not prove the same satisfactorily. Thanks.
Comment: yes but I'm looking for a proof with triangle congruence conditions like SSS or SAS (side angle side), ASA which is how I need to answer
Comment: Everything is symmetric with respect to the perpendicular bisector of $BC$.
Comment: Or you may invoke the full power of Stewart's theorem, then write an article for the future edition of *Mathematics made difficult*.
Answer: The base angles of an isosceles triangle are equal. SAS proves triangles are equal. Then corresponding parts of congruent triangles are equal finishes the proof.
Answer: The proof is like this (by congruency):
In $\triangle BEC$ and $ \triangle CFB$
$$BC \cong CB $$
$$\angle ABC \cong\angle ECB$$
$$AB\cong AC \Leftrightarrow BF \cong EC$$
By $SAS$ congruence criterion
$$\triangle BEC \cong \triangle CFB$$
So $BE \cong CF $ (Corresponding parts of Congruent Triangles)
Answer: In the $\Delta$s ABE, ACF
$AB=AC$ given
$AE=AF$ half of AC, AB resp.
$\angle BAE=\angle CAF$ common
Therefore $\Delta ABE\cong \Delta ACF$ two sides and included angle
In particular, $BE=CF$
$QED$
You don't need to prove $FE\|BC$, nor to quote the base angles of an isoceles triangle theorem.
In fact the same proof applies whenever points $E$ and $F$ are equidistant from $A$ on the sides $AC$,$AB$ (not necessarily the mid points). This is used in Euclid's proof of Proposition 5 (the base angles of an isoceles triangle theorem), though he could, more elegantly, have used the fact that $\Delta ABC\cong \Delta ACB$ (two sides and the included angle).


How to determine the accuracy of regression? Which measure should be used?

Question: I have problem with defining the unit of accuracy in a regression task.
In classification tasks is easy to calculate sensitivity or specificity of classifier because output is always binary {correct classification, incorrect classification}. So I can count good/bad answers and based on the confusion matrix calculate some measurements.
But in regression tasks the output is a number. So I can't just say is it correct/incorrect -- instead I should measure "how far from true solution am I".
So what be the unit of accuracy in regression task?
Comment: Have you heard of coefficient of determination, a.k.a. $R^2$? That's a popular measure.
Comment: Have you looked here: http://en.wikipedia.org/wiki/Forecasting#Forecasting_accuracy ?
Comment: If you're looking at the relative "goodness" of two or more models, you could also look into [AIC](http://en.wikipedia.org/wiki/Akaike_information_criterion) or [BIC](http://en.wikipedia.org/wiki/Bayesian_information_criterion)
Comment: @RichardHardy the $R^2$ can be useful but should definitely not be blindly suggested. I think the answer to the question depends on what is important in the regression. A often used approach in regression is to minimize the MSE. A downside of the $R^2$ is that when we add another factor into our regression the $R^2$ cannot go down even if the variable essentially adds no information.
Comment: @Jan, good points. I suggested to the OP looking at $R^2$ simply because it is the standard even though it is neither always relevant nor flawless. Good that you added some points of warning. It is also true that not all criticism of $R^2$ hits the point. For example, you may or may not worry about the fact that $R^2$ can only grow by adding more variables. It depends on what you are looking for.
Comment: check this for normalized eucledian similarity as a candidate measure: https://stats.stackexchange.com/questions/136232/definition-of-normalized-euclidean-distance
Comment: Check this for normalized euclidean similarity NES/1-NED as a candidate measure: https://stats.stackexchange.com/questions/136232/definition-of-normalized-euclidean-distance the question and answers already contain great details.
Comment: I think you are looking for Mean Absolute Percentage Error (MAPE). Or maybe. Here is the formula: [MAPE](https://en.wikipedia.org/wiki/Mean_absolute_percentage_error). If looking for some kind of accuracy measure, then use 1-MAPE.
Answer: You should ask yourself what were you trying to achieve with your modeling approach.
As you correctly said "how far from true solution am I" is a good starting point (notice this is also true for classification, we only get into specifics when we run into dichotomization, usually in more CS oriented machine learning, such as trees or SVMs).
So, let's measure it, shall we? If $x_i$ is the truth and $\hat x_i$ your model output, for sample $i$, here's the error:
$$\epsilon_i = x_i - \hat x_i$$
You could measure the mean error $\sum_i \epsilon_i$, but it turns out that, doing that, positive and negative errors cancel, giving you no way to know how good your model actually performs!
So, what people do in general, is to use these measures:

Squared error:

$$\text{SE}=\sum_i^n \epsilon_i^2$$

Mean squared error:

$$\text{MSE}=1/n \times \text{SE}$$

Root mean squared error:

$$\text{RMSE}=\sqrt{\text{MSE}}$$

Relative mean squared error (do not confuse this for the RMSE, root mean squared error):

$$\text{rMSE}={n-1\over n}{{\sum_i^n \epsilon_i^2}\over {\sum_i^n (x_i - \mathbb E(x))^2}}= {\text{MSE} \over Var(x)}$$

$\text{R}^2$:

$$\text{R}^2=1 - \text{rMSE}$$

Absolute error:

$$\text{AE}=\sum_i^n \sqrt{\epsilon_i^2}=\sum_i^n |{\epsilon_i}|$$

Mean absolute error:

$$\text{MAE}=1/n \times \text{AE}$$

And many, many others. You can find them around on the site (see for example How to interpret error measures?).
Comment: (+1), but there is a typo in the MSE equation


Is there an easier way to notate this excerpt in LilyPond?

Question:
<< <des f aes c g' bes>1 \arpeggio { <<c''1 {f4. (c8 c2)} >> }  >>
It seems too difficult to do this in LilyPond. How do I do it?
Answer: I'm not exactly sure what your question is, but I would personally do it this way:
\version "2.19.81"
\language "english"

global = {
  \key c \minor
  \numericTimeSignature \time 4/4
}

right = \relative c'' {
  \global

  <<
    {
      f'4.\(\arpeggio c8 c2\)~ |
      c1 |
      ef4.\arpeggio bf8 bf2~ |
      bf1 |
      s |
      s |
    }
    \\
    {
      <df,,~ f~ af~ c~ g'~ bf~ c>1\arpeggio |
      <df f af c g' bf> |
      <c~ ef~ g~ bf~ f'~ af~ bf>\arpeggio |
      <c ef g bf f' af> |
      <c~ f~ bf~ ef~ af~ df>\arpeggio |
      <c f bf ef af ef'>
    }
  >>
}

left = \relative c, {
  \global

  s1 |
  s |
  s |
  s |
  s |
  s |
}

\score {
  \new PianoStaff <<
    \set PianoStaff.connectArpeggios = ##t
    \new Staff = "right" \right
    \new Staff = "left" { \clef bass \left }
  >>
  \layout { }
}

A few notes:

I've separated the treble staff into two voices: the whole notes and the uppermost line. It looks like you were doing something like this, but in a slightly different way.
In order to connect both of these with an \arpeggio, I inserted \set PianoStaff.connectArpeggios = ##t in the \score block.
My ties in the last two measures look different than yours do. This is for a couple of reasons, one of which being that I tied the two bf1s together. (You didn't, but you may not want this, so feel free to change it.)

Sometimes dealing with multiple voices can be a tricky thing in LilyPond. But the more you do it, the easier it becomes. Keep working at it!


How to override remote state in Terratest Terraform setup

Question: I'm trying to understand how to override the Terraform backend ( in my case remote state ) and use local state when setting up Terratest Terraform test.
I am using Terratest to test some Terraform code, and we manage the state remotely in s3. During Terratest i want to use local state but during the "terraform init" state it can'nt find a way to override it.
any help will be appreciated
Answer: Terraform allows for command line options to control backend configuration. Since you're using Terratest, you'll have to pass these backend options to Init.
<code>package terraform

import (
    "fmt"
    "testing"
)

// InitE calls terraform init and return stdout/stderr.
func InitE(t *testing.T, options *Options) (string, error) {
    args := []string{"init", fmt.Sprintf("-upgrade=%t", options.Upgrade)}
    args = append(args, FormatTerraformBackendConfigAsArgs(options.BackendConfig)...)
    return RunTerraformCommandE(t, options, args...)
}
</code>
Comment: Thank you, totally missed the init method!
Comment: @kbry Did you end up being able to do this? From what I can see, it doesn't support backend-config files (only KV pairs). Were you able to override the backend from "remote" to "local" using `FormatTerraformBackendConfigAsArgs`?


Asymptotic distribution of zero-drift Geometric Brownian Motion as $t \to \infty$

Question: If we fix the drift at $\mu = 0$, then my geometric brownian motion will have stationary mean, but it seems that the variance will grow without bound. What does the limiting distribution look like for different volatilities? Is there a "tipping" point where its limiting distribution behavior changes?
Comment: the limit is not measurable so it doesn't look like anything I am afraid. If you put a non zero trend the story is different  as it converges almost surely to $0$ or $+\infty$. You can also notice that the result changes when you move to another probability measure by the means of Girsanov theorem for example. Best regards
Comment: @TheBridge Thanks...the case where $\mid \mu \mid > 0$ was pretty clear. Are we in a situation where a driftless GBM process is a lot like the Cauchy sample mean...never settling down? Surely, if we simulated enough GBMs over a very long time horizon, we'd get results all over the map, I'm guessing.
Comment: This comes from the fact that BM is recurrent (so $liminf_{t\to \infty} B_t=-\infty$ and $limsup_{t\to \infty} B_t=+\infty$ almost surely so this doesn't give much hope regarding measurabillity. Best regards.
Comment: @TheBridge OK, so its not a measurable function...but does it even converge to $a$ function?
Comment: Obviously it is not does the function f(x)=sin(x) converges when x goes to infinity it is the same here Best regards
Answer: Just to be clear, I'm assuming that you mean the process $dX = \sigma X dW$ where $W$ is Brownian motion.  According to the theorem 12 from these lecture notes at Brown University, driftless geometric Brownian motion converges to zero with probability 1.  They sketch a proof in terms of the law of the iterated logarithm.
You can also specialize the results from the answers to this question at Quant Stack Exchange.
Loosely related is this answer to a different question, which makes an interesting big-picture point.  At any finite time, $E_0(X_t) = X_0$, so its surprising that the long-run limit is zero.  The answer locates this weird result in a failure of a probabilistic property known as "uniform integrability".
Comment: Cool. Thanks for the references!


Quintic diophantine equation $x^5+y^5=7z^5$

Question: Are there any non-zero integer solutions to the equation $x^5+y^5=7z^5$? I am unsure how to approach this.
Comment: it is homogeneous, you may demand $\gcd(x,y,z) = 1.$ Then try $\pmod {11},$ that may be enough.
Comment: @WillJagy, how did you know that $11$ would work?
Comment: @lhf, the thing is restrictive because 5 divides 11-1; the fifth power map is five to one in geeral, values $0,1,-1.$ The bad news is that this does not suffice to finish the question. I would like to know the source of the question. ...We could have $$  x^5 \equiv 1, \; \; y^5 \equiv -1, \; \; z^5 \equiv 0 \pmod {11} $$
Comment: Yes I had already observed that small congruences don't rule out much. (There are also many candidates mod 31 and 41 it appears.) On the other hand, a computer search rules out solutions with $\max(|x|,|y|,|z|)<10^4$
Answer: This question has been solved on Mathoverflow.
Solution by Michael Stoll
The integer points are given by $(x,-x,0)$ for $x\in \mathbb Z$.
The trick is to reduce the equation to a form that has been studied more extensively. For any solution $(x,y,z)$ to the equation with $z\not=0$, let $X=-xy/z^2$ and $Y=\frac{x^5}{z^5}-\frac{7}{2}$. Then $Y^2-\frac{49}{4}=X^5$, which is a hyperelliptic curve, and there are techniques for finding all rational solutions to such an equation.


Redirecionamento de domínio em arquivo .htaccess

Question: Eu tenho um domínio assim: https://www.dominio.com, que sempre tem que acessar dessa forma.
Então preciso fazer uns redirecionamentos. São esses:
De:
(http) www.dominio.com.br
(http) www.dominio.com
https://www.dominio.com.br

Para:
https://www.dominio.com
O que eu fiz até agora:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?dominio\.com$ [NC]
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^(www\.)?dominio\.com\.br$ [NC]
    RewriteRule ^(.*)$ https://dominio\.com/%{REQUEST_URI} [L,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

O único problema é esse:
Mas não redireciona quando digito https://www.dominio.com.br.
Comment: Não seria só fixar o dominio.com? `RewriteRule ^(.*)$ https://www.dominio.com/$1 [L,R=301]`
Comment: Não funcionou. O problema é quando eu digito `https://www.dominio.com.br.`, ele não redireciona e dá aquela página de erro de segurança. Porquê não tem certificado nesse domínio.
Comment: os dois domínios são seus? caso não seja dono do `.com` ele não vai apontar para o seu serviço.
Comment: Os dois são meus, o `.com` e o `.com.br`. Eles são redirecionados para o IP do meu servidor.
Answer: Vamos por partes :
<IfModule mod_rewrite.c>

    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^www\.(.*)$ # REMOVE O www DA FRENTE DO DOMINIO
    RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,L]

    RewriteCond %{HTTP_HOST} (.*)\.br$ # REMOVE O br DO FINAL DO DOMINIO
    RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,L]

    RewriteCond %{HTTPS} off # CASO NAO ESTEJA EM https ALTERA PARA POR https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-d # SE O CAMINHO NÃO FOR UM DIETORIO
    RewriteCond %{REQUEST_FILENAME} !-f # SE O CAMINHO NÃO APONTA PARA UM ARQUIVO
    RewriteRule ^(.*)$ index.php [L] # QUALQUER REQUISIÇÃO VAI PARA index.php

</IfModule>

Comment: Guilherme, não fui eu que negativei. Veja só, editei minha pergunta e coloquei meu .htaccess inteiro. É do Laravel. Fiz o que você falou, mas deu erro no site.
Comment: @DiegoSouza veja a edição, pode ser pelo segundo motivo, tlz invertendo a ordem resolva
Comment: Sua resposta resolveu, mas não foi por causa da ordem. O certificado está instalado no `.com`. O que eu fiz foi retirar as outras condições que o Laravel coloca, igual você fez. Obrigado!
Comment: @DiegoSouza que bom que resolveu :D
Comment: Guilherme, aconteceu um problema que eu descobri. O meu site em uma página /pasta. Quando vai para essa página dá erro de não encontrada. É porquê eu comentei a linha `RewriteCond %{REQUEST_FILENAME} !-d`. Tive que descomentar porquê ela é muito importante, daí voltei a estaca 0.
Comment: Alterar em qual linha ?
Comment: Mas já tem essa linha embaixo.
Comment: @DiegoSouza estou fazendo os testes localmente, e esta ok, me mande no pastebin como esta seu htaccess atual
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/59987/discussion-between-diego-souza-and-guilherme-lautert).
Comment: @DiegoSouza Alterei novamente, agora testei todas as possibilidades aqui no local e esta ok como conversamos, altera seu `.htaccess` para este e lembre de limpar o cache do navegador ou abrir como privado.
Comment: Sinto muito, mas não foi. Dá erro 500.


What is this statement mean "It is connected but not path-connected."

Question: What is this statement mean "It is connected but not path-connected."
For example. topologist's sine curve is one of the example.
Answer: Let $X$ be a topological space.  To say that $X$ is connected is to say that there are no (non-empty) open sets $U,V\subset X$ such that $U\cap V=\emptyset$ and $U\cup V=X$.
To say that $X$ is path-connected is to say that for every pair of points $x,y\in X$, there exists a continuous map $\varphi: [0,1]\rightarrow X$ such that $\varphi(0)=x$ and $\varphi(1)=y$.
As you point out, the topologists' sine curve is one of the typical examples to exhibit that being connected need not imply path-connectedness, though the converse does hold: path-connectedness always implies connectedness.


How to convert dates to numbers in Matlab

Question: I have some variables like these:
a(1)=00:26:00
a(2)=744:32:00
a(3)=8040:33:00

I want to convert them to numbers, so I use the datenum command.
The biggest number should be 8040:33:00, but look what happens.
datenum(a([1 2 3]))

ans =

1.0e+005 *

7.3487
7.3485
7.3486

But if I don´t calculate a(1):
datenum(a([2 3]))

ans =

1.0e+005 *

7.3490
7.3520

That´s the results that I want to get. I think that the problem is that a(2) and a(3) have more than 24hours but I haven´t found any way to solve this problem.
Thanks.
Comment: You mean, `a{1} = '00:26:00'`?
Answer: You did not give us your actual input. Having
a(1)=00:26:00
a(2)=744:32:00
a(3)=8040:33:00

means a holds three zeroes. (doc colon explains why.)
If my guess as to what you're actually doing is right, you should be able to use
cellfun(@datenum, a)

I haven't checked deeply, but the behavior looks a bit surprising, indeed. You might want to contact MathWorks Support and file a bug report.
Comment: SOLVED. Christopher Creutzig was right. With the function cellfun it works perfectly. Thank you very much.


Can Spring Web Flow be used in non-UI contexts?

Question: I have a need for a generic workflow builder. Something that builds workflows that automated processes (not end users) would then use like a BPM.

Can Spring Web Flow be used for non-UI purposes (in other words, just the workflow aspect)?
If so, is it possible to configure Spring Web Flow outside of Spring XML, and just as raw Java? If so, how? If not, why not?
Answer: I have recently done some research on a similar requirement to handle workflow processing without implementing a heavy service like BPM.  The most likely candidate I found for processing was using Spring AOP and AspectJ to create the states of a workflow engine, define your transitions based on conditions in your pointcuts.
Take a look at this tutorial


Can I create a collection of arbitrary types in F#?

Question: Very simple
let x = dict [(1, "Foo"); (2, 4)]

doesn't work. So I hoped that this will work.
let x:System.Collections.Generic.IDictionary<int,System.Object> = dict [(1, "foo"); (2, 4)]

Also doesn't. I sort of understand ...
But then how do I process a collection (of arbitrary types) that was handed over to me from an external library?
let x = SomeCallToAExternalLibraryReturningArbitraryTypes()

Answer: F# is strongly typed. You need to cast your objects to the correct type. If you want to have tuples of int * obj then:
[(1, "Foo" :> obj); (2, 4 :> obj)] |> dict

Comment: `box` is idiomatic here.


Unique solutions ODEs

Question: $$ x \frac{dx}{dt} -4t =0 $$
i) Show there are two distinct solutions to the above at $x(0)=0$
ii) Does it have a unique solution that satisfies $x(t_0)=0 $
So the first part I think I've solved, I solved the ODE as an IVP found the two solutions to the problem namely $x(t)=2\sqrt{t^2} $ and $x(t)=-2\sqrt{t^2}$ and we're good.
But could somebody shed some light on the second?
Comment: What about $x\left(t\right)=\pm2\sqrt{t^{2}-t_{0}^{2}}$ ?
Comment: Yes I did, sorry.
Answer: the answer to part (ii) of your question is, no.  here $$ x = 2\sqrt{t^2-t_0^2} \text{ and  } x = -2\sqrt{t^2-t_0^2}, t_0 \neq 0  $$  are solutions of  $$x\frac{dx}{dt}  = 4t, \, x(t_0) = 0.$$
Comment: Clearly, thanks for your input.
Answer: In part i), your solutions are not quite correct.
Your solutions to the equation can be simplified to
$$x=2|t|, \quad x=-2|t|$$
However, note that in either solution $x$ is not differentiable at $t=0$, since the left-hand and the right-hand derivatives are not equal. (In other words, there is a corner at $t=0$.) Therefore we cannot say that either formula for $x$ is a solution at $x(0)=0$. The best we can say is that those functions are solutions to the equation at everywhere except $t=0$, those functions are continuous everywhere, and $x(0)=0$.
You can remove those problems by adjusting your solutions to
$$x=2t, \quad x=-2t$$
These then solve the problem as worded. A slightly different wording of the problem would allow your given solutions to also be valid.
Comment: you don't want the absolute value signs.
Comment: @abel: You are correct, thanks for the catch. I'll edit my answer appropriately.

Unique solutions ODEs


Taxonomy term name alias in taxonomy term autocomplete

Question: I'd like to have two or more names for one Term-ID in my custom taxonomy dictionary. As for now I've added a custom field and named it "Synonyms". The field can have multiple values.
How can I display values of the "Synonyms" field in the autocomplete taxonomy widget (or even a list control) together with original names of the terms (is there any way to do this?).
Real life example:
<code>tid  |name              |synonyms
_____|__________________|___________________________
1    |sneakers          |gym shoes, tennis shoes
</code>
The main name would be: sneakers but while tagging a user may also type: "tennis shoes" into autocomplete and it will link the node field (for example: "Shoes type") with sneakers (tid 1).
Comment: You should wrap fixed-width text with the code wrapper so it displays properly.
Answer: Two options to maybe investigate (neither are easy...):

You could create a custom module using hook_field_widget_form() to define a custom widget. There are several good tutorials on hook_field_widget_form out there, here's one I found quite useful, and the Form API Reference will help too. You might also want to look at Autocomplete Deluxe as a possible base.
You could create a Views table with autocomplete exposed filters, and some custom javascipt that binds a click event to each row controlling the form element, and you could use the 'Node edit' override in Ctools page manager to customise the form page and add it in. If you want one autocomplete box to filter both 'Name' and 'Synonyms', you might need some custom javascript again: maybe hide one input box and control its input with a jquery keyup event on the other box, and set the contextual filters to 'Or' in Views

Of these I'd recommend the first way - much cleaner and probably less work!


Responsive Views-Slideshow Json Cycle working good in Chrome not in IE or mozilla

Question: In drupal I AT themes, views with slideshow of json2 and cycle plugin. I set the options for the plugin like this :
Make views slideshow responsive - remove inline styles

height auto  ,  width auto   , containerResize 0  ,  slideResize 0    ,  fit 0

Result:
- In chrome works perfect
- IE and firefox not responsive
Probably something to do with the html but how to find out where en how. Can it be sold with some CSS?
Any suggestions?
Answer: I use this code
<code>     $(window).resize(function () {
          $('.views_slideshow_cycle_main').each(function(){
                var cycleMain = $(this);
                var img_width = 0,
                    img_height = 0;
                var clearCSS = {width: "auto", height: "auto"};
                var cycle = cycleMain.children('.views-slideshow-cycle-main-frame');
                cycleElements = cycle.data("cycle.opts");
                cycle.css(clearCSS);
                cycleMain.find('.views-slideshow-cycle-main-frame-row').each(function(i){
                  $(this).css(clearCSS);
                  var tmp_img_width = $(this).width();
                  var tmp_img_height = $(this).height();
                  if(tmp_img_width > img_width)
                    img_width = tmp_img_width;
                  if(tmp_img_height > img_height)
                    img_height = tmp_img_height;
                  cycleElements.elements[i].cycleW = tmp_img_width;
                  cycleElements.elements[i].cycleH = tmp_img_height;
                  $(this).css({width: tmp_img_width, height: tmp_img_height});
                });
                cycleMain.height(img_height);
                cycle.css({width: img_width, height: img_height});
                cycle.data("cycle.opts.elements", cycleElements);
              });

        });
</code>
and it works perfectly. you can also add some css to avoid too much high height like:
<code>@media screen and (min-width: 980px){
 .al-slideshow img{
       height: 650px !important;
   }
}
</code>
The following css code is also needed
<code>.views_slideshow_cycle_main { width: 100% !important; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }
</code>
Comment: nice code. I never add code like this to drupal. How can I apply it?
Comment: Add this to your javascript file. you first need to define the js file in `theme.info` then create the js file in there.
Comment: don't forget to add the css code
Comment: Only the css was already enough. thxs


Different number of observations after including control variables

Question: I have two regression models. I am using paneled data on individuals from 2010 up to 2019. For some individuals, I have several years of observations, whereas for others, there are only 2 or so.
The thing is, I have created two different models: One including the control variables, and one without. Below, the first image shows the results without the control variables.

Then, I figured I would add the control variables. However, after doing so, I discovered that the number of observations in the regression models with the control variables is way lower... I am not sure if this is common, because for some individuals, there is no data on their personality traits (for example). I have tried to discover whether this is common in research, but I cannot really find anything about it... Could someone help me or give me advice? The number of observations still seems sufficient, but I'm not sure if this is even 'allowed' in statistics.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Update: @FrankHarrell advises this situation requires multiple imputation. See hbiostat.org/rmsc/missing for how to do multiple imputation. The rest is my original answer.

Before getting to the question of missing covariate values, here are a few points to consider. Some of them might not be relevant in your area of study.

You have four regression models: a regression for graduate hourly earnings and for non-graduate hourly earnings, with and without covariates. Why do you model graduates and non-graduates separately? One model for hourly earnings doesn't necessarily mean that graduates and non-graduates share effects. (For example, we can add a graduate_status term to give each group its own intercept.) However, with two different models the two groups definitely share no effects.
You have multiple observations for most individuals, so how does your model handle that? It's incorrect to assume that observations for the same individual are independent. For example, it's reasonable to expect that the earnings of the same person in 2010 and 2011 are more similar than the earnings of two different persons in 2010. This can be represented with individual random effects.
You model the time effect with one dummy variable per year even though clearly the time effect increases with time (at least in the regressions without covariates). Have you considered modeling the functional relationship between time and hourly earnings, eg. as a line? See plot below.
Some of the covariates likely vary with time, eg., number of family members and number of children in the household. For many people these numbers would have changed over the course of 10 years. Have you thought about when these numbers are recorded and how you interpret their effects?
Time (as either categorical or continuous variable) might be confounding two effects: with each year, people gain more experience and they start getting paid more. Concurrently, average salaries might be increasing with inflation and cost of living. Maybe you already take this into account with Experience?

As you note yourself, you don't have data on at least one covariate for 83% of graduates (observations drop from 7476 to 1269) and 82% of non-graduates (10940 → 1948). There are methods to deal with missing values; otherwise the regression is fitted on the subset of observations without missing values.
Yes, this is allowed but as it's often the case in statistics, it means making (strong) assumptions. In this case the required assumption is that the patterns of missingness are not associated with the outcome, hourly earnings: either values are missing completely at random (think about flipping a coin that determine whether a value is observed or not) or values are missing at random (the other observed variables explain the missingness).
So broadly you have (at least) three options:

Proceed with regression without covariates. However, you cannot unsee that covariates seem to be associated with the outcome. So it might be hard to justify the conclusions you draw from this analysis. [Regression analysis assumes validity, ie. the model includes all relevant predictors and the sample is representative of the population of interest.]
Make strong assumptions about missingness and proceed with regression with covariates. You can also use your domain knowledge to decide that it's reasonable to ignore some covariates altogether.
Impute missing values.

Finally, I'd like to show what I mean by functional relationship between time and outcome. Since I don't have the raw data, I plot estimated yearly effects from the regressions without covariates. You can see that the relationship seems to be linear with a different intercept. A straight line is the simplest function; it's possible to allow for a smooth relationship as well.
Comment: Multiple imputation is needed here, besides addressing all of the super important design questions above.  For one source on multiple imputation see https://hbiostat.org/rmsc/missing
Comment: Thank you so so much for these comments. I must say, I am slightly confused about everything (in case you didn't notice) and your comment is very helpful. It's true that I have a separate regression model for graduates and non-graduates. I'm basing my analysis on a paper who split it between malegrad/malenongrad/femalegrad/femalenongrad. By creating a distinct model for grads and non-grads, I thought the effect of potential work experience would be clear splitted (this effect may be different across the two groups). I thought  that by creating this subset, the different effects may be clear
Comment: About the second point: My supervisor said I should do a pooled OLS regression with fixed time effects (time dummies). But now that I think about it, I'm confused about whether I should also include individual fixed effects...
Comment: Third point: Im afraid I dont really get what you mean by 'modeling the functional relationship between time and hourly earnings'. As compared to 2010, it is clear that in general the hourly earnings have increased (regardless of whether this is due to inflation etc.), so there are time effects present, but to be completely honest, I have no clue what to do with it other than mentioning that they are present...
Comment: Fouth point: I've not looked into that at all! Thank you so much, definitely gonna look into it


Problema em identificar triângulo em Java

Question: Bom, ainda sou muito novo no mundo da programação e estou tentando fazer um simples código onde ele diz se o triângulo é isósceles, escaleno ou equilátero dependendo da medida dos lados digitada. Porém, se eu digitar todas as medidas iguais, ao invés dele apenas dizer que o triângulo é equilátero (todos os lados são iguais), ele tambem diz que é isósceles (apenas dois lados são iguais).
Exemplo:
Digite o valor do primeiro lado:
10
Digite o valor do segundo lado:
10
Digite o valor do terceiro lado:
10
O triângulo é equilátero.
O triângulo é isósceles.
BUILD SUCCESSFUL (total time: 7 seconds)

Esse é o código:
int lado1, lado2, lado3;
    Scanner leia = new Scanner(System.in);
    System.out.println("Digite o valor do primeiro lado:");
    lado1 = leia.nextInt();
    System.out.println("Digite o valor do segundo lado:");
    lado2 = leia.nextInt();
    System.out.println("Digite o valor do terceiro lado:");
    lado3 = leia.nextInt();

    if ((lado1 == lado2) && (lado2 == lado3) && (lado3 == lado1)) {
        System.out.println("O triângulo é equilátero.");
    }

    if ((lado1 != lado2) && (lado2 != lado3) && (lado3 != lado1)) { //O != significa diferente
        System.out.println("O triângulo é escaleno.");
    }

    if ((lado1 == lado2) || (lado2 == lado3) || (lado3 == lado1)) {
        System.out.println("O triângulo é isósceles.");
    }

Alguém sabe me dizer o problema?
Answer: Você pode fazer desse jeito:
if (x == y && x == z){
    System.out.println("Três lados iguais . Trata-se de um Triangulo Equilatero");
}else if(x == y || x == z || y==z ){
    System.out.println("Dois lados iguais . Trata-se de um Triangulo Isosceles");
    }else
    System.out.println("Três lados diferentes.");

mais simples e atinge o objetivo.