Estimated marginal means and arithmetic means are different

Question: I have the following data set where I am testing how fast people can recognise words in different conditions - pre-test (before learning), immediate (straight after learning) and delayed (a long time after learning).
https://pastebin.com/QM3J8XG2

I first inspect my mean RTs. Subjects are faster during the delayed condition and slowest during immediate
df %>%
  drop_na %>%
  dplyr::group_by(test.time) %>%
  dplyr::summarise(meanRT = mean(RT))

test.time meanRT
  <fct>      <dbl>
1 delayed    1340.
2 immediate  1484.
3 pretest    1386.

I fit a linear mixed effect models to investigate the effect of test time on RTs and conduct post hoc contrasts using the emmeans package
library(lmerTest)
libary(emmeans)

mod.1 <- lmerTest::lmer(RT ~ test.time + (1 | Ppt.No),
              data = df %>%
                drop_na)

emm1 = emmeans(mod.1, specs = pairwise ~ test.time)

emm1

$emmeans
 test.time emmean   SE   df lower.CL upper.CL
 delayed     1343 82.9 43.2     1176     1510
 immediate   1483 83.0 43.5     1315     1650
 pretest     1402 83.0 43.3     1235     1569

Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95

$contrasts
 contrast            estimate   SE   df t.ratio p.value
 delayed - immediate   -140.0 36.2 2454 -3.865  0.0003
 delayed - pretest      -59.0 36.0 2455 -1.639  0.2295
 immediate - pretest     80.9 36.3 2455  2.227  0.0668

Degrees-of-freedom method: kenward-roger
P value adjustment: tukey method for comparing a family of 3 estimates

The contrasts are what I would expect by looking at my arithmetic means - delayed is significantly different from immediate, pretest is significantly different from immediate, and delayed and pretest are not significantly different.
However my estimated marginal means are vastly different from my arithmetic means - why is this? I have read on a few sites that it might be because my design is unbalanced? I investigated this and found that some participants have far fewer observations than others in my sample. Is this a valid reason for my estimated marginal means to be so different? And should I just stick to reporting arithmetic means when describing my post hoc contrasts?
Any help is appreciated, thank you!
Comment: I do not use these "contrasts" but a quick suggestion: maybe you could restrict your analysis to a sample with the same number of observations per person, and see if you get the same issue. ?
Answer: The reason is that estimated marginal means depend on the model, not on the data.
To illustrate, consider this toy example with 5 subjects and two treatments:
foo = data.frame(subj = factor(c(1,1, 2,2,2,   3, 4,4, 5,5,5)),
                 trt = factor( c(1,1, 1,1,1,   2, 2,2, 2,2,2)),
                           y = c(3,2, 4,4,5,   7, 9,9, 10,12,15))

First, here are the raw treatment means:
> with(foo, tapply(y, trt, mean))
       1        2
 3.60000 10.33333

Now, consider fitting a simple one-way fixed-effects model, and obtaining the EMMs:
> foo.lm = lm(y ~ trt, data = foo)
> emmeans(foo.lm, "trt")
 trt emmean    SE df lower.CL upper.CL
 1      3.6 0.995  9     1.35     5.85
 2     10.3 0.908  9     8.28    12.39

Confidence level used: 0.95

These EMMs are in fact the same as the raw treatment means.
Next, do the same but use a mixed model with random subject effects:
> foo.lmer = lmer(y ~ trt + (1|subj), data = foo)
> emmeans(foo.lmer, "trt")
 trt emmean   SE   df lower.CL upper.CL
 1     3.45 1.58 2.70    -1.90     8.81
 2     9.68 1.35 3.06     5.43    13.93

Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95

These results are different from the ones obtained from foo.lm --- again,
because EMMs depend on the model.
Please note that these discrepancies are not a peculiarity of the emmeans package. They are discrepancies in the estimated fixed effects of the two models. For the simple model, we have
> coef(foo.lm)
(Intercept)        trt2
   3.600000    6.733333

Interpreting these coefficients (in terms of the default contrasts "contr.treatment" used for coding the factor), the treatment predictions are 3.6000 for trt = 1 (the reference level), and 3.6000 + 6.7333 = 10.3333 for trt = 2. For the mixed model,
> fixef(foo.lmer)
(Intercept)        trt2
   3.452249    6.227216

implying predictions of 3.4522 for trt = 1 and 3.4522 + 6.2272 = 9.6794 for trt = 2.
If the mixed model is the right model for the data, then the right post hoc means would be the ones based on that model. It would be wrong to report the raw means and use them as the basis of a post hoc analysis.
Comment: Only if there is only one factor, or if the data are balanced with more than one factor. Read the "basics" vignette for an example
Comment: @Lenth, if I use lm(), will the EMMs always be the same as raw treatment means?


Product projections are a universal arrow?

Question: From Mac Lane's Categories for the Working Mathematician:

Let $S: D \rightarrow C$.
A universal arrow arrow from $S$ to $c$ is a pair $\langle r,v \rangle$ consisting of an object $r \in D$ and an arrow $v : Sr \rightarrow c$ with codomain $c$ such that to every pair $\langle d,f \rangle$ with $f : Sd \rightarrow c$ there is a unique $f' : d \rightarrow r$ with $f = v \circ S f'$.

He then says:

For the projections $p : a \times b \rightarrow a$ and $q : a \times b \rightarrow b$, for any other pair of arrows $f : c \rightarrow a$ and $g : c \rightarrow a$ to $a$ and $b$ there is a unique $h: c \rightarrow a \times b$ with $ph = f, qh = g$.  This can be made into a universal arrow by introducing a diagonal functor $\Delta : C \rightarrow C \times C$ with $\Delta c = \langle c, c \rangle$.  Then the pair $\langle f,g \rangle : \Delta c \rightarrow \langle a, b \rangle$ in $C \times C$, and $\langle p, q \rangle$ is a universal arrow from $\Delta$ to the object $\langle a, b \rangle$.

How is $\langle p,q \rangle$ a universal arrow from $\Delta$ to $\langle a, b \rangle$?
By the definition Mac Lane defines if it's a universal arrow from $\Delta$ to $\langle a,b \rangle$ then it's an object $r \in C$ and an arrow $v : \Delta r \rightarrow \langle a, b \rangle$ such that for every pair $\langle d, f \rangle$ with $f : \Delta d \rightarrow \langle a, b \rangle$ there's a unique $f' : d \rightarrow r$ with $f = v \circ \Delta f'$.
But this doesn't seem to match what he wrote in the second paragraph included above about projections.  What is the object $r$ and what is the arrow $v$ and an object $d$ for the universal arrow "$\langle p,q \rangle$"?
Answer: The $r$ is $a\times b$, and $\langle p,q\rangle:\Delta(a\times b)\to \langle a,b\rangle$ is the universal arrow in question. For any other $f=\langle f_1,f_2\rangle:\Delta d\to \langle a, b\rangle$ in $C\times C$, the unique $v:d\to a\times b$ in $C$ is precisely the map usually labeled $\langle f_1,f_2\rangle:d\to a\times b$ (the double duty on the angle brackets is a little unfortunate here).


Command is not defined exception

Question: I created a command with Artisan
$ php artisan command:make NeighborhoodCommand

This created the file app/commands/NeighborhoodCommand.php
Snippet of the code. I modified the name value and filled in the fire() function
<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class NeighborhoodCommand extends Command {

    protected $name = 'neighborhood';

    public function fire()
    {
        // my code
    }
}

But then when I try to run the command with
$ php artisan neighborhood

I get this error:
[InvalidArgumentException]
Command "neighborhood" is not defined.

Answer: Laravel 5.5+
https://laravel.com/docs/5.5/artisan#registering-commands
If you'd like, you can continue manually registering your commands. But L5.5 gives you the option to lazy load them. If you are upgrading from an older version add this method to your Kernel:
/**
 * Register the commands for the application.
 *
 * @return void
 */
protected function commands()
{
    $this->load(__DIR__ . '/Commands');

    require base_path('routes/console.php');
}

Laravel 5
http://laravel.com/docs/5.4/artisan#registering-commands
Edit your app/Console/Kernel.php file and add your command to the $commands array:
protected $commands = [
    Commands\NeighborhoodCommand::class,
];

Laravel 4
http://laravel.com/docs/4.2/commands#registering-commands
Add this line to app/start/artisan.php:
Artisan::add(new NeighborhoodCommand);

Comment: Plus for being humble and a good answer. Happened to me 1000 times!
Comment: Laravel 5.5+ PHP Fatal error:  Cannot redeclare App\Console\Kernel::commands()
Answer: By changing signature in your command class to your commandName.
change
protected $signature = 'command:name';

TO
protected $signature = 'NeighborhoodCommand';

Now try to run
$ php artisan NeighborhoodCommand

It works for me.
Reference
Answer: if none of the above work for you you might want to try to  composer dumpautoload which fixed for me.
Answer: Just in case
I tried all the above and I would still get the "Command is not defined" message (even after a composer dumpautoload). This was before I embarrassingly realised my command file name was not binding the Command Class name.
I had
Filename : CommandThatDoesThis.php
Class: CommandThatDoesThat
Ran a composer dumpautoload just after and all was fine.

note: this would have never happened if I created the command properly, using the php artisan make:command. I ended up in this situation because I duplicated an existing command.
Answer: you should also note, that if you fail to put in the proper value to $signature, you will get the same error

Command is not defined exception


Tableau Public, error message {"error":{"message":"No author found!"}}

Question: I published something onto Tableau Public and it isn't working for some reason.  This just started happening and I am not sure why.  I tried uploading different workbooks none of them are working.  Here is a sample:
https://public.tableausoftware.com/views/JBCBacktestvs_SP500/JBC-Backtestvs_SP500DB?:embed=y&:display_count=no
This is the error I receive when I log onto it:
<code> {"error":{"message":"No author found!"}}
</code>
Any idea on what I might be doing wrong?  Thank you!
Comment: Are you able to log on to Tableau Public? Did any errors occur when you published the workbook?
Comment: I am able to log on Tableau Public and I did not have any errors.  Thank you
Comment: https://public.tableausoftware.com/profile/yan.wu4001#!/vizhome/JBC-Backtestvs_SP500/JBC-Backtestvs_SP500DB  This is the link that I got to work.  However, this is not the link generated.
Comment: When you say "generated", when and where was that original link generated?
Comment: You already have a link that works.  Is there a reason you don't want to use it?
Comment: My apologies for not being clear.  This link was generated from when I published the workbook and doesn't work https://public.tableausoftware.com/views/JBCBacktestvs_SP500/JBC-Backtestvs_SP500DB?:embed=y&:display_count=no  This is the link i manually created from being familiar with tableau: https://public.tableausoftware.com/profile/yan.wu4001#!/vizhome/JBC-Backtestvs_SP500/JBC-Backtestvs_SP500DB
Comment: In Tableau Public, try the File > Manage workbooks option.  After you sign on and get to the Tableau Public web page, do you see your workbooks?
Comment: I'm getting the same error.

The issue isn't the ability to see the workbook from within public.tableausoftware.com once one signs in. The issue is the ability for non-signed in person to be able to see one's workbook.

The URL in question is the provided by Tableau after the workbook is saved: "Copy and Paste link into your email message"
Comment: Try posting your question on the Tableau forum (http://community.tableausoftware.com/community/forums).  There's a more active group of Tableau users there.
Answer: Follow the methods given in the tableau help section. After the account is made a window with all the story board will come up. Select the story or dashboard (as per the case) and then click on share button .
click on Done and then go to "open in browser window" . It will open in the browser. Copy the address in the address bar of the browser. This is the link to be published


What does a slash mean in an include statement?

Question: There is a following statement in the file:
#include "ssutil/DataBuffer.h"

Please let me know where to search this header file and how to interpret ssutil/?
Comment: That's not a backslash. That's a forward slash.
Comment: @BjörnPollex: Arguably this edit obscures the true level of confusion of the OP...
Comment: This statement is ill-formed. You need a `#` before the include, and the path needs to be surrounded by either `<` and `>` or two `"`. I fixed that for you now.
Answer: It's a path component. ssiutil is a directory and DataBuffer.h is the actual header. The / is a path separation character used on Unix platforms like Mac OS X, Linux, the BSDs and others as well as Windows.
Comment: Ah alright, I'll update my answer. Didn't realize that was legal there. Admittingly don't do much development on those platforms in C or C++.
Comment: Don't forget Windows, DOS, etc. on which it's also used.
Answer: That is a relative path and the preprocessor will look for the file in a directory called ssiutil. Precisely where that directory is depends on your compiler options. For example the MS compiler searches like this:

This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file. The preprocessor then searches along the path specified by the /I compiler option, then along paths specified by the INCLUDE environment variable.

You may need to consult the documentation for your particular tools to learn how the search is done.


which hook is effective for setting custom breadcrumbs?

Question: I have a theme which sets breadcrumbs like this:
function mytheme_process_node(&$variables) {
    (....)
    drupal_set_breadcrumb($my_breadcrumbs_array);
}

This gets overwritten later by something else. I need a specific taxonomy value of the displayed node to set the breadcrumb, that's why I am using this hook. How to do it effectively? Perhaps there is a hook which is performed later and still has access to the node object?
Comment: "a specific taxonomy value" - that is, a specific taxonomy term reference field?
Answer: I normally stick that logic in hook_preprocess_page(), it runs late enough in the page build to not be overwritten by anything else.
You can still get access to the node object by using the menu_get_object() function:
function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    // We're on a node page...
    drupal_set_breadcrumb($my_breadcrumbs_array);
  }
}

Answer: There is also hook_menu_breadcrumb_alter()
Besides, you can use one of the plenty of breadcrumb-customizing modules and might get what you want without custom code.
Comment: It is tempting to use this hook but you may end up with a correct breadcrumb and a wrong menu active trail.


Find the probability of intersection

Question:
Find $P(B \cap E)$ if $3$ digits are chosen in random with replacement from $0, 1, 2..., 9$ and $B = \{\text{All 3 digits are chosen are unique}\}$ and $E = \{ \text{All digits have the same parity (either odd or even)}\}$

I got that $P(B) = 0.72$ and $P(E) = 0.25$
This is a dependent probability, so how can I proceed?
Answer: You calculated $P(E)$ and $P(B)$ correctly. But it's important to understand that you just can not multiply $P(E)$ and $P(B)$ to get the answer!
Suppose you had $N$ experiments. Among those $N$ experiments there are approximately $N * P(B)$ experiments when all chosen digits have same parity. Consider only those experiments now. In some of these experiments all the digits are unique, in others they are not. In what part of these experiments all the digits are unique? Let's denote it X. Then the total expected number of experiments where both "all digits have same parity" and "all digits are unique" hold would be $N * P(B) * X$.
$X \ne P(E)$. They have different meaning! $P(E)$ is the probability that 3 random digits are unique, $X$ is the probability that 3 randomly selected digits of the same parity are unique. They are different.
Now back to original problem. I would suggest the following approach. There are 1000 different possibilities to choose 3 digits: 000, 001, ... 999.
Probability of any of them is the same: 1/1000.
Now manually count all the outcomes satisfying both $B$ and $E$. At least start doing it:
246, 264, ... - 6 combinations of digits (2, 4, 6)
and there are 6 combination for digits (0, 2, 6) and 6 combinations for...
Well we can choose three unique even digits in $\binom{5}{3}$ ways, so there are $3!*\binom{5}{3} = 60$ possible outcomes with unique even digits. And 60 possible outcomes with unique odd digits. Total $120$ outcomes of $1000$. So $0.12$ is the answer.
Answer: For dependent probability it holds:
$P(B∩E) = P(B)*P_B(E)$
or
$P(B∩E) = P(E)*P_E(B)$, where $P_B(E)$ is the probability $E$ is true, under the condition that $B$ is (already) true and vice versa. I am not posting the solution, since you wanted to proceed yourself!
Answer: As you stated this is a dependent probability and can be solved using bayes rule as follows.
Let we define two further events such that $E_o=\text{all digits are odd}$ and $E_e=\text{all digits are even}$. Thus $P(E)=P(E_o\cup E_e)$ Since , $P(E)$ can be written as, $P(E)=P(E_o)+P(E_e)$
So the original question becomes,
$$
P(B \cap E)=P(B \cap (E_o\cup E_e))=P((B \cap E_o)\cup (B \cap E_e))=P(B \cap E_o)+(B \cap E_e)
$$
Since $B \cap E_o$ and $B \cap E_o$ are disjoint events.
$P(B \cap E_o)$ can be computed using the Bayes rule:
$$
P(B \cap E_o)=P(B | E_o)*P(E_o)
$$
Where $P(E_o)=\frac{5*5*5}{10*10*10}=1/8$ (probability that all digits are odd) and $P(B | E_o)=\frac{5*4*3}{5*5*5}=12/25$ (probability that all digits are unique given that all numbers are odd. This decreases our sample space from 0,...,9 to 1,3,5,7,9)). Thus $P(B \cap E_o)=P(B | E_o)*P(E_o)=(1/8)*(12/25)=3/50$.
I believe $P(B \cap E_e)$ is same as $P(B \cap E_o)$ since they are symmetric. Thus the answer should be $3/50+3/50=3/25$

Find the probability of intersection


exception with gsub in R

Question: I am trying to replace all strings with "other", EXCEPT the ones starting with numbers in the following example:
strings <- c("test.5","5.test","6.test","test","test")

I found that the code below replaces only the strings starting with numbers:
gsub("^[0-9].+", "other", strings)
"test.5" "other"  "other"  "test"   "test"

However, I am really confused about how to reverse the statement, so that everything EXCEPT these strings is replaced.
Desired answer would be
 "other" "5.test"  "6.test"  "other"   "other"

Can someone help me out? Thanks in advance!
Comment: It's considered good manners to upvote and checkmark a correct answer.
Answer: Try
 sub('^[^0-9].*', "other", strings)
 #[1] "other"  "5.test" "6.test" "other"  "other"

Comment: You should read the ?regex page's section on character classes.
Comment: @ZMacarozzi  No problem.  The idea is to match the first character that is not a number.  Using  `^[^0-9]`  ensure that we are matching the first character that is not a number.

exception with gsub in R


Migrating D5 users to D6 using MigrateDestinationUser

Question: I'm using the migrate module to migrate users from a Drupal 5 site to a Drupal 6 site.
MigrateDestinationUser assumes that the source passwords will be plaintext which isn't the case in Drupal 5. Is there any way around this assumption?
Answer: As per http://drupal.org/node/1349758, you need to add a complete function:
<code>$this->addFieldMapping('pass', 'source_password');
...
public function complete($account, $row) {
  db_update('users')
    ->fields(array('pass' => $row->source_password))
    ->condition('uid', $account->uid)
    ->execute();
}
</code>


Can't compile GWT project with GWTQuery in Eclipse

Question: I'm trying to start using GWTQuery in a GWT project.

I've created sample GWT project in Eclipse
Added gwtquery-1.3.2.jar
into war/WEB-INF/lib
Edited Myproject.gwt.xml (added <inherits name='com.google.gwt.query.Query'/>)

When I compile the project it writes a lot of deffered errors but at the end it comes with:
   Scanning for additional dependencies: jar:file:/C:/eclipseBacklog/Backlog/war/WEB-INF/lib/gwtquery-1.3.2.jar!/com/google/gwt/query/client/GQuery.java
      Computing all possible rebind results for 'com.google.gwt.query.client.GQuery'
         Rebinding com.google.gwt.query.client.GQuery
            Checking rule <replace-with class='com.google.gwt.query.client.impl.SelectorEngineNativeIE8'/>
               [ERROR] Errors in 'jar:file:/C:/eclipseBacklog/Backlog/war/WEB-INF/lib/gwtquery-1.3.2.jar!/com/google/gwt/query/client/Properties.java'
                  [ERROR] Line 20: The import com.google.gwt.core.shared cannot be resolved
                  [ERROR] Line 39: GWT cannot be resolved
               [ERROR] Unable to find type 'com.google.gwt.query.client.GQuery'
                  [ERROR] Hint: Previous compiler errors may have made this type unavailable
                  [ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
   [ERROR] Errors in 'jar:file:/C:/eclipseBacklog/Backlog/war/WEB-INF/lib/gwtquery-1.3.2.jar!/com/google/gwt/query/client/GQuery.java'
      [ERROR] Line 1483:  Failed to resolve 'com.google.gwt.query.client.GQuery' via deferred binding

What I'm doing wrong?
Comment: http://stackoverflow.com/questions/14214441/using-gwtquery-with-gwt
Comment: I don't use maven, I just created an Eclipse project, added gwtquery-1.3.2.jar into classpath and added "inherits" into Myproject.gwt.xml. I didn't found build.xml, so skiped this step.
Answer: Check your version of gwt, you have to update to GWT-2.5.x. because this artifact of gquery has a undesired dependency of it. There are two GWT.java classes in 2.5, and gquery is depending of the new com.google.gwt.core.shared by mistake.
Open an issue at the gwtquery site becasuse this release should work with older gwt version as well.
You could also change the gquery version to 1.3.1 or 1.4.0-SNAPSHOT
Update: I've just deprecated version 1.3.2, and released 1.3.3 which compiles with previous gwt versions
Comment: Yes, you're right! I've changed gwtunit version to 1.3.1 and it works! Thank you very much!


Qual é a forma de armazenar e ler configurações?

Question: Imaginando que eu tenho um site pequeno, e esse site armazena e retorna informações do banco de dados. Atualmente vejo muita gente armazenando os dados de login para o MySQL ou paths em variáveis PHP ou define constantes.
<?php
...
$db_host = "localhost";
$db_x = "xxx";
// ou
DEFINE("DB_HOST", "localhost");
...
?>

Na página do PHP li algumas das notas de contribuição dos usuários, e alguns disseram que a melhor forma de armazenar configurações, é em ficheiros de configuração .ini, em outros casos, como por exemplo os frameworks, armazenam paths e outros dados em ficheiros .json.
Se eu salvar configurações num desses ficheiros, qual garantia eu tenho de que será mais seguro, e como posso ler essas configurações de forma segura ?
Comment: [É recomendado o uso de constantes pra configurações de um projeto em PHP?](http://pt.stackoverflow.com/q/98960/91)
Comment: Não vejo uma questão de segurança e sim mais questão de praticidade para eventuais alterações. Sim no meu caso uso mais por praticidade. Acredito que esse tipo de necessidade surgiu para programas compilados, para não ter necessidade para compilar o programa td vez que muda a configuração do banco de dados (senha, usuario, endereço do servidor, etc).
Comment: Obrigado, mas eu gostaria de saber mesmo quais vantagens teria se fosse usar cada um deles, e como seria a melhor forma de armazenar e ler elas.
Comment: @Skywalker obrigado pelo exemplo de uso, eu achei isso [aqui](http://stackoverflow.com/questions/17666728/load-website-configuration-from-json-or-php-file)
Comment: Só um detalhe: não existe segurança inquebrável, então nunca terá garantia de nada. Mas pode se apoiar  em uma análise de risco que terá informações sobre o grau da segurança sob cada forma de armazenar configurações. A forma mais segura ainda é criptografia de dados.
Answer: Não tem nenhuma garantia, pelo contrário, se não souber o que está fazendo é mais fácil acabar fazendo algo menos seguro desta forma. Mudar a extensão ou mesmo o formato do texto interno não dá segurança alguma.
Talvez essa ideia de armazenar em um arquivo .ini fora da área de acesso do site, em um caminho separado que o servidor HTTP não tem acesso. Mas não importa a extensão ou formato do arquivo, o que importa é se ele está fora do acesso público, mas não faz muita diferença. Em um servidor configurado e funcionando corretamente a segurança é a mesma. Em um servidor mal configurado ou comprometido se lascou nos dois casos. "Garantia" de segurança (muito entre aspas) é estudar profundamente o funcionamento dos computadores, sistemas operacionais, servidores, linguagens e outros aspectos da computação, além de manter um comprometimento com a qualidade a todo instante.
A melhor forma de acessar banco de dados de forma anônima ainda é manter a configuração em um arquivo .php, como todo mundo faz, desde que tudo esteja configurado corretamente.
Isto não garante nada se o servidor for comprometido, mas em condições normais, é seguro.
Answer: Como já dito anteriormente pelo @Maniero, é recomendável que as configurações estejam num script PHP, já que o código do mesmo será interpretado apenas pelo PHP, e você não corre o risco de ter seu dados expostos, caso alguém consiga acesso direto ao script.
Uma que é utilizada pelo framework Laravel seria da seguinte forma:
config/database.php
return array(
       'default' => 'mysql_local',
       'mysql_local' => array(
            'host' => 'localhost',
            'database' => 'sopt'
       )
);

Na chamada da configuração, você pode fazer assim:
$config = include 'config/database.php';

$conf_database = $config['mysql_local'];

Como você usou o returnno arquivo de configuração database.php, então foi possível capturar esses dados numa variável, através do include.
Já respondi sobre isso aqui.


How can we prove this inequality involving e?

Question: $$ \frac{1}{1+|x|} \le \frac{e^x - 1}{x} \le1 + |x|(e - 2) $$ where $$x \in [-1,0)\cup(0,1]$$
How can we prove this inequality? My text used it to prove the limit of the middle function when $x→0$ which is $1$ using sandwich theorem.
I have no idea how to begin. I know I can find the limit using L'Hospital but still I cant figure out where did this inequality come from.
Comment: Any answer will depend on particular definition of $e^x$. You might want to include how you've defined it.
Comment: In how many ways can you define e^x ? I think there is only one ?
Comment: Many. Please see [characterizations of exponential function](https://en.wikipedia.org/wiki/Characterizations_of_the_exponential_function).
Comment: The second one it is the value of the infinite series .
Comment: What's wrong with just taking separately into account the part $x >0$ and $x < 0$ and differentiating?
Comment: @ant differentiating what ?
Comment: Take the difference between the two functions and compute the minimum in $(0,1)$ (using the derivatives). If the minimum is bigger than $0$, one of the two functions is bigger than the other
Comment: Isn't there any easier way that way must be the last option to prove something .
Comment: @RaghavSingal Yeah, I agree it's not the smartest way but it usually works and it doesn't require much mental effort, it's just some computations :)
Answer: HINT/Partial Solution
Consider the case where $x\lt0$.
Let's work on the left part inequality $$\frac{1}{1-x}\le\frac{e^x-1}{x}\Rightarrow\\\text{(since $x$ is negative)}\\\frac{x}{1-x}\ge e^x-1\Rightarrow\\e^x(x-1)\le1$$
Let $g(x)=e^x(x-1)$ , $x\in[-1,0)$
We have $$g'(x)=xe^x\lt0, \forall x\in[-1,0)\Rightarrow\\ \text{ g($x$) is increasing in $[-1,0)$ }\Rightarrow\\x\le0\Rightarrow g(x)\le g(0)=1$$
as desired.
For the right part of the inequality, that is $$\frac{e^x-1}{x}\le1-x(e-2)$$
we can work in the same manner, by considering the function $h(x)=e^x-x+x^2(e-2)-1$ (here, you will need to see what happens with $h''(x)$ to find the monotony of $h$).
The same approach can be applied for the $x\gt0$ case.
Answer: Power series algebra is your friend here. We have:
$$\frac{1}{1+|x|}=\sum_{i=0}^\infty (-1)^i|x|^i=1-|x|+|x|^2-|x|^3+\cdots$$
$$\frac{e-1}{x}=\sum_{i=0}^\infty \frac{x^i}{(i+1)!}=1+\frac{1}{2}x+\frac{1}{6}x^2+\cdots$$
$$1+|x|(e-2)=1-|x|+x|x|+\frac{1}{2}x^2|x|+\frac{1}{6}x^3|x|+\cdots$$
To see that the first is less than the second, notice that when $1>x>0$ the first is less than $1$ and the second is greater than $1$. When $-1<x<0$, using the Lagrange Error formula tells you that the second is greater than the first. Thus the second is always greater than the first.
See if you can come up with an argument for why the third is greater than the second.
Comment: What is lagranges error formula ?
Comment: @RaghavSingal Have you ever seen Taylor series before? I had assumed so, since you said that $e$ was defined via infinite series...
Comment: Not exactly though I know the Mclaurin series which is its speacial case I think ?
Comment: It's a way to bound how much the error is when you truncate an infinite series. The calculation is a little messy though, and so I would recommend using the proof given in @jacaboul 's answer to complete my answer rather than Lagrange Error Bounds.
Answer: It sounds awkard to use these inequalities to prove the limit you want.
The limit $\lim_{x\to 0} (e^x-1)/x=1$ follows by L'Hospital's rule as you said, or by using the fact that $(e^x-1)/x=1+\sum_{n\ge 1} x^n/(n+1)!$ and that the power series $\sum_{n\ge 1} x^n/(n+1)!$ is absolutely convergent and hence the sum converges to $0$ as $x\to 0$. If you are not convinced of that at sight you may use  $|\sum_{n\ge 1} x^n/(n+1)!|\le |x|\sum_{n\ge 0} |x|^n/(n+2)!\le |x|e^{|x|}$.
Now to prove the inequality $(e^x-1)/x\le 1+|x|(e-2)$ here are some hints. First note that the case $x\in [-1,0[$ follows from the case $x\in ]0,1]$, since for $x<0$ we have $(e^x-1)/x=(e^{-|x|}-1)/(-|x|)=(1-e^{-|x|})/|x|=(e^{|x|}-1)/(|x|e^{|x|})\le (e^{|x|}-1)/|x|$, since $e^u\ge 1$ if $u\ge 0$. Now let's concentrate on the case $x\in I=]0,1]$. In that case we may write
$(e^x-1)/x=1+x\sum_{n\ge 0} x^n/(n+2)!\le 1+x\sum_{n\ge 0}1/(n+2)!=1+x(e-2)$.
I didn't try, but I guess similar arguments may handle the other inequality. I hope this helps.
Answer: From the series definition it immediately follows that $e^x\geq 1 + x$: by uniqueness of Taylor series, the first derivative at $0$ is $1$, so $1+x$ is tangent - inequality follows by convexity of $e^x$.
1. $\frac{e^x-1}{x}\geq\frac 1{1+|x|}$
If $x>0$, then $e^x\geq 1 + x$ implies
$$\frac{e^x-1}x\geq 1\geq \frac 1{1+|x|}.$$
If $x<0$, then we have
\begin{align}
\frac{e^x-1}{x}\geq\frac 1{1+|x|}&\iff e^x - 1\leq \frac x{1-x}\\
&\iff e^x \leq 1+\frac x{1-x}\\
&\iff e^x \leq \frac 1{1-x}\\
&\iff 1 - x \leq e^{-x}\\
&\iff 1 + t \leq e^{t}
\end{align}
2. $\frac{e^x-1}{x}\leq 1+|x|(e-2)$
For $x > 0$, we have
\begin{align}\frac{e^x-1}{x}\leq 1+|x|(e-2) &\iff e^x-1\leq x+x^2(e-2)\\
&\iff \frac{e^x-1-x}{x^2}\leq e-2\\
&\iff \frac 1{2!}+\frac x{3!}+\ldots\leq \frac 1{2!} + \frac1{3!}+\ldots\\
\end{align}
If $x<0$, then $$e^x\geq 1 + x \implies e^x-1\geq x\implies \frac{e^x-1}{x}\leq 1 \leq 1+|x|(e-2)$$
Comment: Thank you for your answer it helped !! Give you a plus one :)
Comment: Can you elaborate the last step ? How is e^x greater than 1+x if x is negative?
Comment: @Raghav Singal, as I said in the first line, $x + 1$ is tangent line at $0$, while $e^x$ is convex.


Python markdown edge case: /* */

Question: Is there a way to get Python to interpret Markdown the same way as it is interpreted here on stackoverflow:

This is a C comment: /* */ tada!

and on github? https://gist.github.com/jason-s/fc81280dc6108f9ec3a8
Python's markdown module interprets the * * as italics:
>>> import markdown
>>> markdown.markdown('This is a C comment: /* */ tada!')
u'
This is a C comment: / / tada!
'

(Babelmark 2 shows some of the differences. Looks like there are different interpretations of the markdown syntax.)
Comment: (aside from special-casing this and using `/\* \*/`)
Comment: Jakob: Yes, I know. I'm just dealing with someone who put a lot of text in comments in Stash (which also behaves like stackoverflow and github markdown) without doing the escaping with backticks, and I've got a Python script that I wrote which special-formats the results, and it doesn't produce the same HTML output that Stash produces.
Answer: The /* */ syntax is not standard Markdown. In fact, it is not mentioned at all in the syntax rules. Therefore, it is less likely to be handled consistently among different Markdown implementations.
If it is a C comment, then it is "code" and should probably be marked up as such. Either in a code block or using inline code backticks (`/* */`). As mentioned in a comment to the OP, it could also be escaped with backslashes if you really don't want it marked up as code. Personally, I would instruct the author to fix their documents (regardless of parser behavior).
In fact, the Markdown parsers that do ignore it do so by accident. In an effort to avoid matching a few edge cases that should not be interpreted as emphasis, they require a word boundary before the opening asterisk (but not after it) and a word boundary after the closing asterisk (but not before it) to consider is as emphasis. Because the C comment has a slash before the opening asterisk (and a space after it) and a slash after the closing asterisk (and a space before it), some parsers do not see it as emphasis. I suspect you will find that those same parsers fail to identify a few edge cases as emphasis that should be. And as the Syntax Rules are silent on these edge cases, each implementation gets them slightly different. I would even go so far as to say that the implementations that do not see that as emphasis are potentially in the wrong here. But this is not the place to debate that.
That said, you  are using Python-Markdown, which has a comprehensive Extension API. If an existing third party extension does not already exist (see below), you can create your own. You may add your own pattern to match the C comment specifically and handle it however you like. Or you may override the parser's default handling of emphasis and make it match some other implementation who's behavior you desire.
Actually, the BetterEm Extension (which, for some reason is not on the list of third party extensions) might do the later and give you the behavior you want. Unfortunately, it does not ship by itself, but as part of a larger package which includes multiple extensions. Of course, you only need to use the one. To get it working you need to install it. Unfortunately, it does not appear to be hosted on PyPI, so you'll have to download it directly from GitHub. The following command should download and install it all in one go:
pip install https://github.com/facelessuser/pymdown-extensions/archive/master.zip

Once you have successfully installed it just do the following in Python:
>>> import markdown
>>> html = markdown.markdown(yourtext, extensions=['pymdownx.betterem'])

Or from the commandline:
python -m markdown -x 'pymdownx.betterem' yourinputfile.md > output.html

Note: I have not tested the BetterEm Extension. It may or may not give you the behavior you want. According to the docs, "the behavior will be very similar in feel to GFM bold and italic (but not necessarily exact)."
Comment: @Jason S, just curious if the the BetterEm Extension works for you. Haven't used it myself and am wondering if it addresses your issue.
Answer: well, it's ugly, but this post-Markdown-processing patch seems to do what I want.
>>> import markdown
>>> mdtext = 'This is a C comment: /* */ tada!'
>>> mdhtml = markdown.markdown(mdtext)
>>> mdhtml
u'
This is a C comment: / / tada!
'
>>> import re
>>> mdccommentre = re.compile('/( | .* )/')
>>> mdccommentre.sub('/*\\1*/',mdhtml)
u'
This is a C comment: /* */ tada!
'

Python markdown edge case: /* */


Not understanding reason for demeaning covariates in program evaluation regression

Question: I am reading the Imbens et al. 2009 paper on program evaluation methods: http://dash.harvard.edu/bitstream/handle/1/3043416/imbens_recent.pdf?sequence=2
On page 24, discussing simple regression methods for estimating the average treatment effect, they write:
"This estimator is also obtained from the coefficient on the treatment indicator $W_i$ in the regression $Y_i$ on $1, W_i, X_i, W_i·(X_i-\bar{X})$."
Can someone please explain to me why the covariates in the interaction term need to be demeaned here?  I would have thought that if the non-interacted covariates enter the regression unadjusted, then they should be likewise unadjusted in the interaction term.  But apparently my intuition is wrong.
Thanks.
Answer: I believe this is done to avoid having the reader do the arithmetic. In the simple linear model,
$$E[Y_i \vert X] = \alpha + \beta W_i + \gamma X_i + \psi X_i \cdot W_i. $$
The marginal effect of $W$ is $\beta +\psi X_i$, which is a function of $X$, and so the average marginal effect is $\beta +\psi \bar X$. The reader would need to know what $\bar X$ was to figure it out.
In the second version of the model,
$$E[Y_i \vert X_i] = \alpha + \beta W_i + \gamma X_i + \psi (X_i - \bar X) \cdot W_i. $$
The marginal effect of $W$ is $\beta +\psi (X_i - \bar X)$, which is a function of $X$. Here $\beta$ is the average marginal effect, so you don't need to do any arithmetic. Another way to think about it is that in the second model, $\beta$ is the effect of $W$ for someone with the average $X$, and because the model is linear, that is also the average marginal effect.
Here's an example with Stata. First we fit the simple model:
<code>. sysuse auto, clear
(1978 Automobile Data)

. reg price i.foreign##c.weight

      Source |       SS           df       MS      Number of obs   =        74
-------------+----------------------------------   F(3, 70)        =     26.20
       Model |   335885357         3   111961786   Prob > F        =    0.0000
    Residual |   299180039        70  4274000.55   R-squared       =    0.5289
-------------+----------------------------------   Adj R-squared   =    0.5087
       Total |   635065396        73  8699525.97   Root MSE        =    2067.4

----------------------------------------------------------------------------------
           price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-----------------+----------------------------------------------------------------
         foreign |
        Foreign  |  -2171.597   2829.409    -0.77   0.445    -7814.676    3471.482
          weight |   2.994814   .4163132     7.19   0.000     2.164503    3.825124
                 |
foreign#c.weight |
        Foreign  |   2.367227   1.121973     2.11   0.038      .129522    4.604931
                 |
           _cons |  -3861.719   1410.404    -2.74   0.008    -6674.681   -1048.757
----------------------------------------------------------------------------------
</code>
Now we use margins to calculate the AME:
<code>. margins, dydx(foreign) at((mean) weight)

Conditional marginal effects                    Number of obs     =         74
Model VCE    : OLS

Expression   : Linear prediction, predict()
dy/dx w.r.t. : 1.foreign
at           : weight          =    3019.459 (mean)

------------------------------------------------------------------------------
             |            Delta-method
             |      dy/dx   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
     foreign |
    Foreign  |   4976.148   910.5648     5.46   0.000     3160.084    6792.212
------------------------------------------------------------------------------
Note: dy/dx for factor levels is the discrete change from the base level.
</code>
Here we do it the demeaned way:
<code>. qui sum weight

. gen dm_weight = weigh -r(mean)

. reg price i.foreign c.weight i1.foreign#c.dm_weight

      Source |       SS           df       MS      Number of obs   =        74
-------------+----------------------------------   F(3, 70)        =     26.20
       Model |   335885358         3   111961786   Prob > F        =    0.0000
    Residual |   299180039        70  4274000.55   R-squared       =    0.5289
-------------+----------------------------------   Adj R-squared   =    0.5087
       Total |   635065396        73  8699525.97   Root MSE        =    2067.4

-------------------------------------------------------------------------------------
              price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
--------------------+----------------------------------------------------------------
            foreign |
           Foreign  |   4976.148   910.5648     5.46   0.000     3160.084    6792.212
             weight |   2.994814   .4163132     7.19   0.000     2.164503    3.825124
                    |
foreign#c.dm_weight |
           Foreign  |   2.367227   1.121973     2.11   0.038      .129522    4.604931
                    |
              _cons |  -3861.719   1410.404    -2.74   0.008    -6674.681   -1048.757
-------------------------------------------------------------------------------------
</code>
Note that the foreign coefficient matches the output of margins closely, including the standard error.
Comment: Thanks for the explanation and detailed example Dimitriy.  Makes sense.


Delete spaces from items in a list

Question: I have this list:
input_list = ["184.108.40.206", " 126.96.36.199", "  18.104.22.168"]

And I'd like to remove that space in the second e third words... How can I do?
I tried with:
for x in input_list:
    x.strip(" ")

and with:
for x in input_list:
    x.replace(" ","")

Comment: You can't assign to literals. You didn't try these codes, don't you?
Comment: This is _too localised_ to ever be of use to a future reader.
Answer: your_list = [element.strip() for element in your_list]

Comment: you did not test that.
Comment: @ChrisMueller edited.
Comment: You should also specify that the strip method without any arguments will remove all white spaces (including tabs and newlines). If you only want to remove regular spaces you should use `element.strip(' ')`

Delete spaces from items in a list


How to write RegEx to extract strings from an array in PHP

Question: How can I extract the name of the book, and the price of book from this array using Regular expression.
<code>$bookList = array('PHP and MySQL Web Development (4th Edition)' => 49.95,
          'Learning PHP, MySQL, and JavaScript' => 37.33,
          'Beginning PHP and MySQL: From Novice to Professional' => 23.56,
          'Head First PHP & MySQL' => 64.35);
</code>
Is regEx'ing the function the best way to extract it?
<code>function getBookName($bookList)
{
$bookRegEx = '';
$matchResult = array();
if (preg_match($bookRegEx, $bookList, $matchResult))
{
    return intval($matchResult[0]);
}
else
{
    return 0;
}
}
</code>
Comment: regex? wut? [isn't it just key (book) => value (price)?](http://php.net/manual/en/language.types.array.php)
Comment: It's not clear what you want, nor why. Have you tried to `foreach` over the list? Which book entry do you want? Always the same one? And why strip the cents from the prices?
Comment: I want to extract all the names and then output them into tables. Yes basically a foreach statement would work, I just don't know how to separate name and price from each of the books in the array
Comment: @GivePie: You use foreach for exactly that. http://php.net/foreach Read the manual first, there is more in php than regular expressions.
Answer: I wouldn't use regex here. It really depends on how you want to use the array you have structured. I'd read up on how to use PHP arrays.
http://www.php.net/manual/en/book.array.php is probably where you want to start.


Kernel Panic in Debian after converting disk from Hyper-V to VirtualBox

Question: I have a problem after moving the VM from HyperV to VirtualBox running Debian 10. After booting, I have ShellUEFI and then I run grub64 and then the panic kernel appears.
Interestingly, I don't have this problem with Ubuntu ... only Debian is problematic.
Answer: Virtualbox and Hyper-v normally use different disk controllers.
Try this:
Open Virtualbox
Create new VM
Use above VHD as hard drive.
Once VM is created, go to VM settings, storage,
Add new controller PIIX4.
Move VHD from SATA controller to PIIX4 controller.
Press OK, load VM.
Beware though, if you keep hyper-v and virtualbox installed on the same machine, the virtualbox vm will be extremely slow. You need to either completely disable or uninstall hyper-V to make it work properly.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Menus, drush uli link, and some images not working after moving site to localhost

Question: I've just gotten a site I'm supposed to do some work on but I'm having trouble with migrating to a local development environment. I don't have admin access to the site itself, but I do have access to the server. I pulled the database down along with the code base, but I seem to have messed up the file permissions when moving the site because the site loads, but not all the functionality is present.
The site isn't accessible beyond the splash page, and none of the image assets load except the site logo. Accessing any menu links generates a 404. The image that loads has the same ownership and permissions as the image which loads which are myuser:www-data and 640. Initially, no images loaded, but following this post about securing file permissions got the logo loaded.
I am also having issues with accessing the site. Since, I can't access any menus beyond the root, it seems that I can't access the login page either. I've added a user for myself with Drush, and even run drush uli with the the URI provided as a parameter, but the link is inaccessible and returns a 404. I also used the File Permissions module, but it doesn't seem to have helped.
At this point, my next step is going to be setting up a clean install and importing the db through backup and migrate and moving the theme and modules manually, but I'd like to figure out what I did wrong and how to avoid this.
Comment: On a Mac it would go `cd ~/Sites` and then `chwon -R myuser:staff my-project/`. And as you are locally you could also `chmod -R 777 my-project/`. But that shouldn't be necessary. Did you doublecheck the `.htaccess` and uncommented the right `RewriteBase` directive?
Comment: Apart from that this question unfortunately is too broad as it would require lots of back and forth clarification in comments. Debugging always needs to be done by you. As we don't know your project, your setup, your machine or you. Good luck!
Comment: maybe try setting the $base_url in the setting.php file
Answer: I did recently a manual migration and had some problems, similarly to you. After this, I made a script to manually migrate the site and the database. You need to have a zip with the Drupal installation, not the folder of the installation, just the files inside it, the database and know if the database has some prefix. Change all the prefix in the database, you could use notepad++ or similar to change all in one command. Change the url i.e: mydomain.com/drupal to localhost/drupal. Then import the database, and unzip the files in your localhost server. Then go to sites/default/settings.php and at the bottom of the file edit the data of your database, prefix if you have one, pass, user, port if you changed it and, in same file, look for $settings['update_free_access'] = FALSE; and change it to true.
Now, in your browser visit localhost/yourinstallationfoldername/update.php and follow the instructions.
If you don't know the users you can see in the database for the table users and you can see there their ID (uid) and password (uuid) on md5. Just search on google for any md5 generator and copy paste it on uid 1 (admin user generated on installation) for know the name of the user you can go to the table users_field_data and look on name column.
If you have a virtual server working on your server, you must remember to point it to the new folder where is your Drupal installation. This is a good tutorial about how to do it: Installing virtual hosts for Drupal sites and subsites.
Comment: in this case, what tripped me up was not replicating the folder structure and improperly specifying the app entry point with a virtual host. If you update your fairly comprehensive answer to include this I'll accept it, since it's good to have the info out there and not in a comment. Thanks.
Comment: Edited. I think it explains what you did in your installation. If not, please, tell me. My english, as i said, is not the best, so ill try to write it in an understandable way.
Comment: perfectly understandable, cheers.
Comment: Drupal 8 doesn't use MD5 for hashing the password. Also, the uuid field isn't the password field.
Comment: A bit late, but thank you for your corrections @kiamlaluno


Probability Density Function of the Midrange of a Random Sample of Size 3 from a Uniform Distribution (0,1)

Question:
I defined another random variable $W = \frac{Y_3-Y_1}{2}$, then we get $Y_1 = Z-W$ and $Y_3 = Z+W$. I then used the change of variables method and get the joint pdf of $Z$ and $W$ is $h_{W,Z}(w,z) = 24w$, but I do not think this is correct since when I integrate everything out I do not get $1$.
Comment: I think I know how to do the cdf method but in this problem we would require 4 integrals for it because of the support of $X$ so I wanted to know if the transformation method is a bit more tamed.
Comment: What 4 integrals? In the linked post, a transformation is made from $(Y_1,Y_3)\to (Y_3-Y_1,\frac12(Y_1+Y_3))$ and pdf of $\frac12(Y_1+Y_3)$ is derived as a marginal.
Comment: I did it without a transformation, I used the cdf without any transformations and just worked out the integrals and the bounds make it so that we choose a minimum of 2 variables in the lower bound and another 2 in the upper bound.
Answer: Comment: Perhaps find beta distributions of max and min. Then distribution of their difference. This is precisely the approach of @StubbornAtom's useful link. Suggest looking carefully at that--even though your alternative method may work.
Sometimes, it helps to have a clear mental picture of the result. Below, the result is suggested by simulation in R, where range provides min and max (not their difference).
It may be worthwhile to notice that the standard deviation of the midrange of three observations is about $0.158,$ whereas the SD of their sample mean is larger:
$\sqrt{1/36} = 1/6 = 0.167.$ Thus, the midrange is a better estimator of the population mean than is the sample mean.
set.seed(2020)
mr = replicate(10^5, mean(range(runif(3))))
sd(mr)
[1] 0.1580891
hist(mr, prob=T, br=50, col="skyblue2")


Problema com o CORS no Angular 5

Question: Pessoal eu estou com uma aplicação teste em Angular 5 e estou tentando consumir o WebService do cartola. Ao realizar essa tentativa aparece o seguinte erro:

Failed to load https://api.cartolafc.globo.com/mercado/status: The 'Access-Control-Allow-Origin' header has a value 'https://cartolafc.globo.com' that is not equal to the supplied origin. Origin 'https://localhost:4200' is therefore not allowed access.

Eu sei que para questões de teste eu posso simplesmente desativar essa validação seja via plugin ou por outra opção. Mas e no caso de uma aplicação real.
Por exemplo, eu vou criar essa aplicação e a mesma vai consumir o WebService do cartola.
Como corrigir isso ?
Service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Usuario } from '../model/usuario.model';
import { URL_API } from '../util/constantes';
import { Observable } from '../../../node_modules/rxjs';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable()
export class UsuarioService {

  constructor(private http: HttpClient) { }

  public teste2(){
    return this.http.get('https://api.cartolafc.globo.com/mercado/status', httpOptions);
  }
}

Component:
// O botão no meu HTML chama esse método teste()
      public teste(): void{
        this.serviceUsuario.teste2()
          .subscribe(
            (response) => {
              console.log("Sucesso");
              console.log(response);
            },
            err => {
              console.log("Erro");
              console.log(err);
            }
          )
      }

Comment: Aparentemente só está liberado a requisição para o próprio domínio https://cartolafc.globo.com/ Nesse caso sua aplicação deveria estar nesse domínio
Answer: Primeiramente, precisamos entender o que é o CORS.

Cross-origin resource sharing ou compartilhamento de recursos de origem cruzada é uma especificação de segurança de browsers que tem como intenção fazer a segurança de recursos de diferentes origens.

Fonte.
A responsabilidade da configuração desse mecanismo é do backend. Ele que deve dizer quais domínios a API deve barrar/liberar o acesso.
Nesse caso, não temos acesso ao backend para adicionar o milagroso:
Access-Control-Allow-Origin: *.
E agora, como proceder?
Como você mencionou, pode-se utilizar uma extensão no Chrome para desabilitar o CORS, que vai funcionar em um ambiente de desenvolvimento. O problema é quando cai em produção, já que não temos controle sobre o browser do cliente.
Uma opção pra burlar esse controle é utilizar um reverse proxy, que deve monitorar as suas requisições e injetar os headers de CORS a cada requisição.
Existem várias formas de montar esse proxy, uma delas é bem descrita nesse artigo, do qual retirei minha primeira citação.
Um serviço parecido com esse é o cors-anywhere, que já disponibiliza um URL pronta para ser utilizada.
A requisição fica assim:
this.http.get('https://cors-anywhere.herokuapp.com/https://api.cartolafc.globo.com/mercado/status').subscribe(r => {
  console.log(r);
}, err=> {
  console.log(err);
});

que retorna o objeto esperado:

Funciona? Sim!
Deve ser usado?
Bom, na minha opinião, se o desenvolvedor da API negou esses acessos, é por algum motivo. Cabe a você decidir se o uso desse workaround é realmente necessário.

Problema com o CORS no Angular 5


Getting IMCE to accept multiple file uploads at one time

Question: I am currently using the IMCE module for uploading files but it only allows 1 file to be uploaded at one time.  We have tried the plupload and the imce_plupload modules together but those modules sometimes corrupt the files once uploaded.
The only other module called "IMCE Multiple Upload" that claims that it can work with IMCE as an add-on module to IMCE and allows multiple uploads at one time costs $36.
I don't know if the "IMCE Multiple Upload" module will work correctly since the demo site only allows 5 files at once and once over a certain file size it scales it down.
Has anyone used the "IMCE Multiple Upload" module with IMCE and does it restrict how many files can be uploaded at once and does it restrict the file size?
Also does anyone know of an alternative way of getting IMCE to accept multiple file uploads at one time.
Answer: I don't know what version of Drupal you are using, If you are working with Drupal 7 you should take a look at: IMCE plupload that helps you to use IMCE with Plupload .
But in Drupal 7 the best option is Media module.


Cache Performance (concerning loops) in C

Question: I was wondering, why does one set of loops allow for better cache performance than another in spite of logically doing the same thing?

for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        accum = 0.0;
        for (k = 0; k < n; k++) {
            accum += b[j][k] * a[k][i];
        }
        c[j][i] = accum;
    }
}

for (j = 0; j < n; j++) {
    for (k = 0; k < n; k++) {
        val = b[j][k];
        for (i = 0; i < n; i++) {
            c[j][i] += val * a[k][i];
        }
    }
}

I believe the first one above delivers better cache performance, but why?
Also, when we increase block size, but keep cache size and associativity constant, does it influence the miss rate? At a certain point increasing block size can cause a higher miss rate, right?
Comment: Why do you believe the first delivers better cache performance if you have not tested and you have no reason why it might do so?  Might it be that your homework problem asserts so?  We are sometimes willing to help with homework, but I, at least, dislike HW questions in disguise.
Comment: If this is an abstract, academic question, it probably belongs in cs.stackexchange.com, not SO.
Comment: @user3528438 I understand, however the practice problem states "assume associativity and cache size is constant", I guess I forgot to include that in the post.
Comment: When you say "*I believe the first one delivers better cache performance but why??*", have you profiled the code?
Comment: @iharob No i haven't, how would I go about doing that?
Comment: In loop 1, array b is moving slowly through memory, but a is moving in jumps of n * sizeof(a[0][0]).  In loop 2, both arrays are moving in increments of sizeof(array_element).
Comment: @JohnBollinger I completely agree with you, since I too thought that the *concern* was academic only. No testing, kind of proves that.
Comment: I have ran it through a cache simulator, just didn't understand the term 'profile'. I was wondering if this was due to the constant access to the variable accum? This is NOT for Homework its on a practice exam, and I am studying for a final.... I am just trying to understand this a little bit better,but I get crucified for asking others opinion. Sorry to inconvenience you guys.. @iharob
Comment: It depends on the size of data, specifically the shape of `a` array. In the first one, `a[k][i]` causes very strided access pattern. This can cause cache conflicts. The worst case, when `a[k][0]` and `a[k+1][0]` maps to exactly the same cache line, the cache becomes useless.
Comment: @user3528438 Are you saying, generally, the second loop would implement caching better?
Comment: The rule of thumb is, your inner-most loop shall make the most of localized data and avoid strided access. When you do need strided access, make sure to avoid cache conflict so that cached data can be used by the next iteration instead of being evicted.
Comment: @user3528438 OK, makes perfect sense now, thank you a ton! Also, when you increase block size, does this increase the misses because there are less blocks in the cache which could cause conflict misses?
Comment: It doesn't matter how many cache lines of data is cached. If you are preparing for an exam, the key word related to this problem is cache associativity.
Answer: Just generally speaking, the most efficient loops through a matrix are going to cycle through the last dimension, not the first ("last" being c in m[a][b][c]).
For example, given a 2D matrix like an image which has its pixels represented in memory from top-left to bottom-right, the quickest way to sequentially iterate through it is going to be horizontally across each scanline, like so:
for (int y=0; y < h; ++y) {
    for (int x=0; x < w; ++x)
        // access pixel[y][x]
}

... not like this:
for (int x=0; x < w; ++x) {
    for (int y=0; y < h; ++y)
        // access pixel[y][x]
}

... due to spatial locality. It's because the computer grabs memory from slower, bigger regions of the hierarchy and moves it to faster, small regions in large, aligned chunks (ex: 64 byte cache lines, 4 kilobyte pages, and down to a little teeny 64-bit general-purpose register, e.g.). The first example accesses all the data from such a contiguous chunk immediately and prior to eviction.
harold on this site gave me a nice view on how to look at and explain this subject by suggesting not to focus so much on cache misses, but instead focusing on striving to use all the data in a cache prior to eviction. The second example fails to do that for all but the most trivially-small images by iterating through the image vertically with a large, scanline-sized stride rather than horizontally with a small, pixel-sized one.
Also, when we increase block size, but keep cache size and associativity constant, does it influence the miss rate? At a certain point increasing block size can cause a higher miss rate, right?
The answer here would be "yes", as an increase in block size would naturally equate to more compulsory misses (that would be more simply "misses" though rather than "miss rate") but also just more data to process which won't all necessarily fit into the fastest L1 cache. If we're accessing a large amount of data with a large stride, we end up getting a higher non-compulsory miss rate as a result of more data being evicted from the cache before we utilize it, only to then redundantly load it back into a faster cache.
There is also a case where, if the block size is small enough and aligned properly, all the data will just fit into a single cache line and it wouldn't matter so much how we sequentially access it.
Matrix Multiplication
Now your example is quite a bit more complex than this straightforward image example above, but the same concepts tend to apply.
Let's look at the first one:
for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        accum = 0.0;
        for (k = 0; k < n; k++)
            accum += b[j][k] * a[k][i];
        c[j][i] = accum;
    }
}

If we look at the innermost k loop, we access b[j][k]. That's a fairly optimal access pattern: "horizontal" if we imagine a row-order memory layout. However, we also access a[k][i]. That's not so optimal, especially for a very large matrix, as it's accessing memory in a vertical pattern with a large stride and will tend to suffer from data being evicted from the fastest but smallest forms of memory before it is used, only to load that chunk of data again redundantly.
If we look at the second j loop, that's accessing c[j][i], again in a vertical fashion which is not so optimal.
Now let's have a glance at the second example:
for (j = 0; j < n; j++) {
    for (k = 0; k < n; k++) {
        val = b[j][k];
        for (i = 0; i < n; i++)
            c[j][i] += val * a[k][i];
    }
}

If we look at the second k loop in this case, it's starting off accessing b[j][k] which is optimal (horizontal). Furthermore, it's explicitly memoizing the value to val, which might improve the odds of the compiler moving that to a register and keeping it there for the following loop (this relates to compiler concepts related to aliasing, however, rather than CPU cache).
In the innermost i loop, we're accessing c[j][i] which is also optimal (horizontal) along with a[k][i] which is also optimal (horizontal).
So this second version is likely to be more efficient in practice. Note that we can't absolutely say that, as aggressive optimizing compilers can do all sorts of magical things like rearranging and unrolling loops for you. Yet short of that, we should be able to say the second one has higher odds of being more efficient.
"What's a profiler?"
I just noticed this question in the comments. A profiler is a measuring tool that can give you a precise breakdown of where time is spent in your code, along with possibly further statistics like cache misses and branch mispredictions.
It's not only good for optimizing real-world production code and helping you more effectively prioritize your efforts to places that really matter, but it can also accelerate the learning process of understanding why inefficiencies exist through the process of chasing one hotspot after another.
Loop Tiling/Blocking
It's worth mentioning an advanced optimization technique which can be useful for large matrices -- loop tiling/blocking. It's beyond the scope of this subject but that one plays to temporal locality.
Deep C Optimization
Hopefully later you will be able to C these things clearly as a deep C explorer. While most optimization is best saved for hindsight with a profiler in hand, it's useful to know the basics of how the memory hierarchy works as you go deeper and deeper exploring the C.


Terminology for point in dent in surface?

Question: This is a simple terminology question.  Let $S$ be a (let's say smooth)
surface in $\mathbb{R}^3$, and $p$ a point
on $S$.  Suppose the principle curvatures $\kappa_1$ and $\kappa_2$ at $p$ are both negative.
I am imagining $p$ sitting at the bottom of a dent in the surface.
Is there an accepted term to describe such a point?
The difficulty is that the Gaussian curvature $\kappa_1 \kappa_2$ is positive, so intrinsically
$p$ is no different than if it were on a bump rather than a dent.
I could make up my own term of course, e.g., valley point or cup point, but I'd rather follow convention.
Thanks!
Comment: I've never come across specific terminology for this situation.  I think if $p$ is really at a "dent" in the surface, not only should the Gauss curvature be positive there, but it should decrease (roughly with the distance to $p$) and become negative near $p$.
Comment: The only term I could find is "elliptical" point (the signs of $\kappa_1$ and $\kappa_2$ are the same), so maybe you can just invent a new adjective to add to "elliptical".
Comment: @Ryan: Yes, I see there are constraints nearby. @JM: Ah, _elliptical_! I didn't know that term.  Your suggestion of modifying that term is perhaps my solution.  Thanks!
Answer: This question (does established terminology for a certain situation exist) has been answered in the comments (no).  But for posterity--- ie, for students who may meet "principal curvature" terminology before they learn a lot of differential geometry, and who may run across this question on web searches for related topics--- I can't resist emphasizing a point hinted at in the question itself: having both principal curvatures negative at a point is not a well defined property of a point on a surface; the signs of the principal curvatures depend on the coordinate system you calculate them in.
For example, if you pick a point $p$ on a sphere in $\mathbb{R}^3$ and a coordinate patch around $p$ in which to compute principal curvatures, you find that both principal curvatures are positive at $p$ if the normal vector field associated to the coordinate patch points inward (ie, toward the center of the sphere), and both negative if the normal vector field associated to the patch points outward.  The choice of normal is yours to make; it doesn't come with the sphere.  (I suppose this point might be better made with a complicated surface that does not correspond to a well-known shape--- e.g. the surface formed by a tangle of ribbon after you have unwrapped a gift.  If you punch a hole in this ribbon and replace the missing disc with a hemisphere, whether this is a "valley" or a "cup" is entirely up to you.  In choosing the normal direction, you are deciding whether or not curves in the hemisphere are "curving" "toward" the normal or "away from" it.)
Now, this indeterminancy up to sign is the worst thing that can happen: if $S \subseteq \mathbb{R}^3$ is a smooth surface, and the principal curvatures at a point $p$ in $S$ are found in some coordinate system to be $\kappa_1$ and $\kappa_2$, then in any other coordinate system they will be either found to be exactly the same (that is, $\kappa_1$ and $\kappa_2$) or the same, but with opposite sign (that is, $-\kappa_1$ and $-\kappa_2$).  How you prove this depends on how you define the principal curvatures, but arises e.g. from the fact that they are the maximum and minimum normal components of accelerations of unit-speed curves in the surface at $p$, and there are only two possible choices of unit normal at $p$, differing only by sign.  So "both principal curvatures are negative" is a well-defined property of an oriented smooth surface in $\mathbb{R}^3$ (a property which, we learned in the comments, apparently does not have a well-established name; for what it's worth, I like "bump point").
This same discussion shows that the slightly weaker condition that "both principal curvatures at $p$ have the same sign" is well-defined independent of a choice of normal.  (As pointed out in the comments, it does have a well-established name: such a $p$ is said to be an elliptic point.)  What the above discussion does not show, but is nevertheless true, is that this weaker condition is even independent of how one "embeds" $S$ in any "ambient space" (what the asker meant when he referred to the Gaussian curvature at $p$ as being "intrinsic").  For more, open up any book on the differential geometry of surfaces and look for the sections around Gauss's Theorema Egregium.


What is the safest way to allow a developer to edit 3 Puppet modules?

Question: We have a developer that has to make 3 Puppet modules for an environment. I want him to be able to write his 3 modules.
We currently write our own modules and he is the first person from another department that has to write modules. We use root-access to write/edit our modules, but we do not want to give him root access.
What is the best way to grant him rights to make/edit his 3 modules?
We use the Puppet 3.2.4 and Red Hat Linux 6.4.
Comment: Do your developers make changes to code using root access too?
Answer: Commit your modules and puppet scripts to a shared Git repository.
Your developers and this new dev can then fork the repository, and make changes, then you can merge the changes back in.
Using root access to edit files without versioning or change control is a recipe for disaster.
Answer: The official doc for writing modules is a good place to start.
Publishing Modules on the Puppet Forge — Documentation — Puppet Labs :
puppet generate username-module
$EDITOR Modulefile
puppet module build <MODULE DIRECTORY>

Installing Modules — Documentation — Puppet Labs :
puppet module install --module_repository http://dev-forge.example.com username-module
puppet module upgrade --module_repository http://dev-forge.example.com username-module

Comment: This is surely good general advice, but how does it answer the question?
Comment: Create, Test, Share/Publish (Git Push, Pull), Install, Upgrade.


How to change AWS Support Plan on a member account?

Question: When I log in with root credentials, I have the option to change the support plan in Support Center.
However, that only changes the Support Plan in the root account.
How do I do this for a member account in the organization?
Answer: To change support for a member account you log into that account using root credentials and enable support.


php: mysqli_num_rows is returning 0

Question: I know this might be a duplicate on:
php - MYSQLI_NUM_ROWS ALWAYS RETURNING 0
php - mysqli_num_rows() is always returning 0

The thing is none of them is giving me an answer for my problem.

This is an example code of my code with the same syntaxes as I used.

index.html

    <title>GAS - Give Away System - Create User</title>

        <input type="text" placeholder="Username" id="uname" />

php/errorchecking.php
<?php
    $con = mysqli_connect('localhost', 'root', '', 'gas');
    if(isset($_GET['c']) && isset($_GET['v'])){
        echo 'Current value: ', $_GET['v'], '
This value is set for: ', $_GET['c'], '

';

        if($_GET['c']==="username"){
            if($_GET['v']===null){
                echo "Sorry, this username is empty! Please write a username!";
            }else{
                // I know this is open for SQL Injection, it's not in my worries.
                $query = "SELECT `username` FROM `users` WHERE `username` ='{$_GET['v']}'";
                $sql = $con->query($query);

                if(mysqli_num_rows($sql) > 0){
                    echo "Sorry, this username is already in use! Please choose something else";
                }else{
                    echo "Username avaible!"; //This is line 17
                }
            }
        }
    }else{
        echo 'This is an invalid form!';
    }
?>

Now lets say I have a username in my table called User15, and someone's input is the exact same it will display the message "Username available!" from php/errorchecking.php Line:17
Why does it do that? Since it already is a user there called User15, so what it should display is "Sorry, this username is already in use! Please choose something else"
Thanks for taking time helping me! Cecilie.
Comment: I will accept it in 8 minutes, I have to wait before i can put it to the answer @PraveenKumar
Comment: $query = "SELECT username FROM `users` WHERE username='".$_GET['v']."'";
Comment: Hahaha, thank you very much @Anant . That was very helpfull! If you post this as an answer I will use it :)
Comment: @Anant Partial solution. `:)` I gave a full explanation. That counts. `:)` You didn't explain why it happens, and we both have a difference of `12 seconds`, which I used to explain it well. An answer should not be just do this and you'll get it, will be like you don't teach the person.
Comment: A partial solution is that which solves only some part of the problem not the complete problem. explanation only add information about the logic, it didn't make a solution partial or full.
Answer: That's a wrong way of query syntax. You need to use back-ticks and not 's:
$query = "SELECT username FROM `users` WHERE 'username'='".$_GET['v']."'";
//-------------------------------------------^--------^

Change it to:
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";

Note:

`` - For columns.
'' - For values.
Answer: You have to remove '(single quotes) around your column-name from your query like below:-
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";

Note:- Instead of '(single quotes) use back-ticks. because single-quotes(') used for values and back-ticks used for column-name as well as table-name too.Thanks

php: mysqli_num_rows is returning 0


Busca em grafos para resolver o teorema de euler

Question: Olá, gostaria de uma ajuda para fazer uma busca em um grafo e verificar se ele satisfaz o teorema de euler.
O teorema diz: "Um grafo conexo conterá um ciclo de Euler se, e somente se, cada um dos vértices tiver um número par de arestas incidindo sobre ele."
Então o problema se resume em descobrir o grau de cada um dos vértices do meu grafo, e se ele é conexo.
Pensei em representar meu grafo através de uma lista de adjacência, pois como cada vetor vai ter a lista de vizinhos, basta pedir seu tamanho menos um e obtenho o grau do vértice. Para descobrir se é conexo pensei em utilizar uma DFS, pois assim posso verificar tanto quanto possível cada um dos meus vizinhos no grafo.
De quais outras formas posso otimizar essa minha sugestão de solução?
Comment: Qual é o tamanho do grafo no caso médio? E no pior caso que você está disposto a tratar? Quais linguagens de programação te interessam ou não?
Comment: Victor, não tenho um tamanho definido. Mas se fosse para grafos pequenos, até mil vértices por exemplo, minha sugestão é boa? Em que situação minha sugestão vai ser ruim? Eu interessado em fazer isso em C++.
Comment: Pra mim descobrir se minha sugestão é boa ou não, teria de fazer uma análise de complexidade de algoritmo, correto?
Answer: Para determinar se o grafo é conexo, a melhor abordagem provavelmente é a busca em largura ou em profundidade. (Referência)
Para contar o grau de cada vértice, você pode usar lista de adjacências ou matriz de adjacências. Ambas as abordagens consomem memória  no pior caso.
Para determinar se dois vértices são vizinhos, você tem que percorrer a lista de adjacências de um deles e procurar sequencialmente o outro vértice desejado lá, o que é razoavelmente lento. Com matriz de adjacências, isso pode ser feito em tempo constante.
Para computar o grau de um vértice, ou você percorre a lista de adjacências inteira, ou conta o número de elementos na linha. Ambas as abordagens têm tempo proporcional a  para cada vértice, de forma que será  se aplicado ao grafo inteiro.
Para grafos esparsos onde o número de arestas é proporcional ao número de vértices (ou seja, , para algum  constante e pequeno), que significa que há um limite fixo de arestas incidentes em um vértice, a melhor abordagem é a lista de adjacências, pois neste caso, essas listas serão curtas. Para grafos densos, as listas ocuparão mais memória do que a matriz de adjacência correspondente, e para descobrir se dois vértices  e  são vizinhos, você terá que percorrer a lista de adjacências de um deles, elemento por elemento, fazendo uma busca sequencial, o que é bem lento.
Como você quer grafos com até 1000 vértices, a matriz de adjacência terá 1.000.000 de entradas no pior caso. Considerando que você use um char[] no C++ e que sizeof char é 1, isso dará pouco menos de 1 Mb de memória, o que não é lá muita coisa. Assim sendo, matriz de adjacências parece ser uma abordagem bem melhor do que lista de adjacências.
Há ainda uma otimização importante, que depende de como o grafo é construído. Supondo que você tenha em algum lugar uma lista de arestas ou um gerador de arestas, convém manter em algum lugar, um array contendo o grau de cada vértice, de forma que sempre que uma aresta é declarada, você incrementa 1 em ambas as posições correspondentes do array. Ao terminar, você verifica se o array contém algum elemento ímpar ou o número zero. Se conter ímpar, então ele não é euleriano. Se houver zero, então ele não é conexo (a menos que o grafo consista de um único vértice isolado). Se todos os elementos forem pares e nenhum for zero, faça a DFS ou BFS. Com esta abordagem, é possível computar o grau de todos os vértices em tempo .


Question on normal subgroup and sum of characters.

Question: Let $G$ be a finite group and let $N$ be a normal subgroup of $G$. Prove that $$\mid G:N \mid = \sum \chi(1)^2$$ where the sum ranges over all irreducible characters of $G$ such that $N \subseteq \ker \chi$.
From previous results, I have proven that $N= \cap \ker \chi$, where the intersection goes over the same irreducible characters as above. I am trying to use this, but I don't manage. I am looking for hints.
Answer: The characters in the sum on the right hand side have a special relationship to $G/N$.


Exporting settings in a code with Features / Strongarm - how to detect right variables - config ones

Question: Many modules does not support Features, so I need Strongarm module to export config in the code. But in situation where i have many contrib modules, it seems tedious work. not all variables are named after module.
More important, how can I know which variables are used for settings, as I noticed some vars are not used for settings but may be user/module specific, and I need to aviod them.
I want to Strongarm only variables that have to do something with the config.
Is it done by researching modules one by one ? What are your experiences (It would be nice if I could filter variables that are used only in config :) )
Answer: Unfortunately, the Drupal variables table doesn't provide any distinction between variables used for configuration (e.g., whether anonymous pages should be cached) and variables used to store transient values (e.g., date cron was last run, which tabs are currently active in the UI), so there's no automatic way to do this.  (Fortunately, it looks like Drupal 8's configuration management system will handle this better.)
I typically export and update Features modules from the command line using Drush.  I've been using the following Unix shell script to list Features Components which haven't yet been exported to any feature — the script filters out Features Components I know I don't want in my Features modules:
<code>drush fc % --not-exported \
    | grep -v '^ dependencies:' \
    | grep -v '^ user_permission:access devel information' \
    | grep -v '^ user_permission:execute php code' \
    | grep -v '^ user_permission:switch users' \
    | grep -v '^ uuid_node:' \
    | grep -v '^ variable:additional_settings__active_tab_' \
    | grep -v '^ variable:cron_key' \
    | grep -v '^ variable:cron_last' \
    | grep -v '^ variable:ctools_last_cron' \
    | grep -v '^ variable:date_api_version' \
    | grep -v '^ variable:dev_mem' \
    | grep -v '^ variable:dev_timer' \
    | grep -v '^ variable:devel_api_url' \
    | grep -v '^ variable:devel_error_handlers' \
    | grep -v '^ variable:devel_execution' \
    | grep -v '^ variable:devel_krumo_skin' \
    | grep -v '^ variable:devel_page_alter' \
    | grep -v '^ variable:devel_query_display' \
    | grep -v '^ variable:devel_query_sort' \
    | grep -v '^ variable:devel_raw_names' \
    | grep -v '^ variable:devel_rebuild_theme_registry' \
    | grep -v '^ variable:devel_redirect_page' \
    | grep -v '^ variable:devel_use_uncompressed_jquery' \
    | grep -v '^ variable:devel_xhprof_directory' \
    | grep -v '^ variable:devel_xhprof_enabled' \
    | grep -v '^ variable:devel_xhprof_url' \
    | grep -v '^ variable:drupal_css_cache_files' \
    | grep -v '^ variable:drupal_http_request_fails' \
    | grep -v '^ variable:drupal_js_cache_files' \
    | grep -v '^ variable:drupal_private_key' \
    | grep -v '^ variable:entityreference:base-tables' \
    | grep -v '^ variable:features_codecache' \
    | grep -v '^ variable:features_ignored_orphans' \
    | grep -v '^ variable:features_semaphore' \
    | grep -v '^ variable:install_profile' \
    | grep -v '^ variable:install_task' \
    | grep -v '^ variable:install_time' \
    | grep -v '^ variable:mimemail_key' \
    | grep -v '^ variable:prod_check_module_list_lastrun' \
    | grep -v '^ variable:simplenews_last_cron' \
    | grep -v '^ variable:simplenews_last_sent' \
    | grep -v '^ variable:simplenews_private_key' \
    | grep -v '^ variable:simplenews_source_cache' \
    | grep -v '^ variable:update_last_check' \
    | grep -v '^ variable:xmlsitemap_generated_last' \
    | grep -v '^ variable:xmlsitemap_rebuild_needed' \
    | grep -v '^ variable:xmlsitemap_regenerate_needed'
</code>
Comment: There is some effort to do this better way also for Drupal7: http://drupal.org/project/configuration . It looks promising. As for your answer, you suggest that I must manually discover what variables are transient and exclude them this way ? This could be tedious with many contributed modules installed, but probably unavoidable :( . Thanks!
Comment: There has been some effort to simplify this, but I do not see it is maintainted/developed recently http://drupal.org/project/selector
Comment: Yeah, I haven't found a better way than to manually examine each variable individually, then add it to my blacklist.
Comment: Oh my. I think then it is best approach, when I need to change config of unsupported contrib modules on dev, to research which vars are right, and add them to feature. Doing all this for +50 contrib modules would take me days, and probably most of them wont be changed (in settings)
Comment: https://www.drupal.org/node/2400531 gives a list of features components that should never be exported, and mentions the Features Banish module as a way to prevent accidentally exporting them.


Como interromper a execução do each do jQuery?

Question: Estou com um problema ao percorrer rows (de uma DIV que está dentro de outra DIV) com o método each.
Quando uma condição é verdadeira, eu preciso interromper o loop e exibir uma mensagem para o usuário, mas não estou conseguindo interrompê-lo.
Pesquisei na net, e descobri que o each tem esse problema, mas só encontrei soluções usando o for e eu não sei como transformar minha estrutura atual de each para for. Alguém sabe me ajudar com isso ou oferecer alguma solução para interromper o laço each?
var rowPessoaAnaliseCredito = $(this).closest('.row-pessoa-analise-credito');

$(rowPessoaAnaliseCredito).find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
    if ($(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val() === '')
        return;
});

Answer: Segundo a documentação:

You can stop the loop from within the callback function by returning false.

Ou seja, basta que a função de callback retorne false.
Segue abaixo uma comparação do seu código (adaptado porque não foi fornecido o HTML), e a diferença quando o retorno é false:

// imprime "abc" e "def"
console.log('each percorre todos');
$('#analise-credito').find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
    var valor = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
    if (valor === '') {
        return; // <-- esse return não interrompe o each
    } else {
        console.log(`achei: ${valor}`);
    }
});

// imprime somente "abc"
console.log('--------\neach para no primeiro vazio que encontrar');
$('#analise-credito').find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
    var valor = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
    if (valor === '') {
        return false; // <-- retorna false para interromper o each
    } else {
        console.log(`achei: ${valor}`);
    }
});

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="abc">

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="">

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="def">

Ou seja, no primeiro caso ele percorre todos os elementos (imprimindo todos os não-vazios - no caso, "abc" e "def"). E no segundo caso, ele interrompe quando o primeiro vazio for encontrado, então só imprime o "abc".

A opção com for é sem jQuery, bastando usar querySelectorAll e querySelector para buscar os elementos que você precisa:

for (const elemento of document.querySelectorAll('.row-pessoa-analise-credito-consulta')) {
    var valor = elemento.querySelector('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').value;
    if (valor === '') {
        break; // interrompe o for
    } else {
        console.log(`achei: ${valor}`);
    }
}

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="abc">

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="">

    <input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="def">

Comment: Obrigado @hkotsubo!!!! O problema estava em eu retornar com "return". Ao retornar com "return false", deu certo. :)


Prove that a covariant functor which satisfies 2 conditions is a cosheaf

Question: Suppose that $\mathfrak{U}$ is a covariant functor on the open sets of $X$ to $\mathbb{Z}$-modules with satisfies the following two conditions :
(a) If $U$ and $V$ are open then the sequence $$\mathfrak{U}(U\cap V)\stackrel{\alpha}{\rightarrow}\mathfrak{U}(U)\oplus\mathfrak{U}(V)\stackrel{\beta}{\rightarrow}\mathfrak{U}(U\cup V)\rightarrow 0$$ is exact, where $\alpha=i_{U,U\cap V}-i_{V,U\cap V}$ and $\beta=i_{U\cup V,U}+i_{U\cup V,V}$.
(b) If $\{U_{\alpha}\}$ is an upward-directed family of open sets with $U=\bigcup U_{\alpha}$, then $\mathfrak{U}(U)=\varinjlim \mathfrak{U}(U_{\alpha})$
How to show that $\mathfrak{U}$ is a cosheaf ?
(Exercise 3 in BREDON G. E., $\textit{Sheaf Theory}$, McGraw-Hill Book Company, New York-Toronto, Ont.-London, 1967, p. 248)
Answer: The full proof is given by Bredon in this paper page 3.
The general idea is that your assuption (a) will give you the cosheaf property for finite coverings. (You can proceed by induction, the case $n=2$ being your assumption.) Then, thanks to an inductive limit and assumption (b) you can get the cosheaf property for any covering.