Erro em WebService no Laravel 5.7

Question: Estou tentando criar um WebService pelo Laravel usando o symfony/process, se eu rodar ele no command do windows ele preenche o log com sucesso (php artisan gerar:arquivo 12 param1 1000), mas quando tento rodar pela minha rota ele não preenche o log, ele me retorna o seguinte erro:
Symfony\Component\Process\Exception\ProcessFailedException: The command "php artisan gerar:arquivo 12 param1 1000" failed.

Exit Code: ()

Working directory: C:\xampp\htdocs\pw

Output:
================

Error Output:
================
 in file C:\xampp\htdocs\pw\app\Http\Controllers\PwController.php on line 339
Stack trace:
  1. Symfony\Component\Process\Exception\ProcessFailedException->() C:\xampp\htdocs\pw\app\Http\Controllers\PwController.php:339
  2. App\Http\Controllers\PwController->pw() C:\xampp\htdocs\pw\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
  3. call_user_func_array() C:\xampp\htdocs\pw\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
  4. Illuminate\Routing\Controller->callAction() C:\xampp\htdocs\pw\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45
  5. Illuminate\Routing\ControllerDispatcher->dispatch() C:\xampp\htdocs\pw\vendor\laravel\framework\src\Illuminate\Routing\Route.php:212

Segue meu código:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class Gerar extends Command
{

    protected $signature = 'gerar:arquivo {id} {param} {page_size}';
    protected $description = 'Aplicação para Gerar PDF';

    public function handle()
    {
        $page_size = $this->argument('page_size');
        $id = $this->argument('id');
        $param = $this->argument('param');

        Log::info($page_size);
        Log::info($id);
        Log::info($filtro);

    }

}

Note que eu estou gerando um Log com dados para teste mas não chega a preencher o log, parece que ele para no controller.
E o controller:
public function gerar(Request $request)
{
        $process = new Process(sprintf("php artisan gerar:arquivo %d %s %d", 1299, "param1", 1000), base_path());
        $process->start();
        //$process->wait();
}

Note tambem que se eu descomentar a linha //$process->wait(); ele funciona, mas tenho que esperar o fim do processamento do WebService e não quero isso.
Comment: O $process->wait() fica em loop?
Comment: Da uma olhada nesses artigos

https://laracasts.com/discuss/channels/general-discussion/running-artisan-command-through-symfony-process

https://stackoverflow.com/questions/27022516/controlling-an-interactive-process-with-php-using-symfony-process
Answer: De acordo com a documentação, aqui está a maneira correta de chamar um comando em uma rota/controller, ex:
$exitCode = Artisan::call('email:send', [
    'user' => 1, '--queue' => 'default'
]);

Comment: Ele não quer isso, ele quer gerar logs com laravel

Erro em WebService no Laravel 5.7


Como "startar" um servidor Node?

Question: Instalei o Node, criei a variável de ambiente (NODE_ENV) valor development.
Quando instalei e configurei, imprimi um arquivo.js com hellow world e funcionou.
Hoje, quero iniciar o servidor, mas não consigo. Já fiz set node_env e a variável de ambiente está ok.
Já digitei no terminal node -v, mas não mostra a versão, o Windows não reconhece este comando.
Como faço para iniciar e manter o servidor Node em execução?
Comment: Não uso muito a formatação de textos, pois sou deficiente visual e não é possível acompanhar visualmente cada formatação, estilo, etc. O que poço fazer é escolher fonte, cor, coisas mínimas.
Answer: Provavelmente, apesar de você criar a variável NODE_ENV, ela não está no PATH do Windows, isso é necessário para que o Windows reconheça o comando que vc está executando, no caso o node -v.
Faça isso nas propriedades avançadas do sistema, na aba Avançado, variáveis de ambiente.
Outra opção, é setar isso via linha de comando, faço isso com um BAT, para simplificar o processo, assim só seto as variáveis quando realmente preciso. Abaixo um exemplo de como ficaria o BAT:
SET NODE_ENV=<caminho_node>
SET PATH=%PATH%;%NODE_ENV%

Note que neste caso as variaveis de ambiente serão validas apenas para a sessão atual. Então faça o BAT, salve no diretório de trabalho do node, e antes de começar a rodar o node, execute o bat.
Answer: No windows o node disponibiliza o arquivo nodevars.bat que atribui ao PATH o caminho para funcionamento do NodeJs e NPM.
C:\Program Files (x86)\nodejs ou C:\Program Files\nodejs
Para manter a aplicação rodando você pode utilizar o Forever ou PM2.
https://github.com/Unitech/pm2
https://github.com/foreverjs/forever
Answer: Uma opção para criar um servidor sem muita dificuldade é usar os módulos: express-generator no node.
O express-generator pode ser instalado ao digitar o comando:
$ npm install express-generator -g

Criando a estrutura do projeto:
$ express exemplo-express -e ejs

Uma estrutura semelhante a essa será criada no seu diretório raiz.
exemplo-express/
├── bin/
├── public/
│   ├── images/
│   ├── javascripts/
│   ├── stylesheets/
├── routes/
│   ├── index.js
│   ├── users.js
├── views/
│   ├── error.ejs
│   ├── index.ejs
├── app.js
├── package.json

Depois disso, será preciso instalar todas as dependências que se encontram em  package.json.
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Papa instalar as dependências basta digitar no console o seguinte comando:
$ npm install

Feito isso, seu servidor já estará criado e pronto para ser usado e o server pode ser iniciado com o comando:
$ npm start

Como "startar" um servidor Node?


Compact-open topology for the space of continuous paths

Question: My question is probably silly... There is a cryptic claim in Hatcher's book page 530 that I do not understand about the compact-open topology on the set of continuous maps from the segment $[0,1]$ to a topological space $X$. I guess that it is a misunderstanding with the English words.
It is claimed that a basis of open subsets in this particular case consists of the open sets $\bigcap_i M(K_i,U_i)$ where the $K_i$'s are a partition of $[0,1]$ into nonoverlapping closed intervals. Consider the open subset $M(\mathbb{K},U)$ where $\mathbb{K}$ is the Cantor set. I do not see how to find an open of the form $\bigcap_i M(K_i,U_i)$ contained in $M(\mathbb{K},U)$, unless the partition is not necessarily finite: in that case, $M(\mathbb{K},U)=\bigcap_{b\in \mathbb{K}} M(\{b\},U) \cap \bigcap_{n\geq 0} M([a_n,b_n],X)$ where the $[a_n,b_n]$ are the closure of all connected components of the complement of $\mathbb{K}$.

What does Hatcher mean exactly ?
Answer: It seems like Hatcher is claiming something different (emphasis mine):

In [the case of the compact open topology on $X^I$] one can check that a system of basic neighborhoods of a path $f: I \to X$ consists of the open sets $\bigcap_i M(K_i, U_i)$ where the $K_i$'s are a partition of $I$ into nonoverlapping closed intervals and...

On the other hand, the subbasis of the topology definitionally consists of the sets $M(K, U)$. A basis of the topology then consists of finite intersections of such sets. (Note that this means there is no "overlapping" condition on the basic open sets.) This means that your open subset $M(\mathbb K, U)$ is already a basic open set.


What causes the imbalance where back points towards the side after serving?

Question: I am analysing the serving here where the player gets angular momentum not towards the field but to the side.

where you see back pointing towards the side, bad. In comparison Federer 1m12s gets the momentum towards the field.

where you see the back pointing towards the back of the field after serving, good.
Is the back direction after serving due to bad center of mass? How to fix it? And what is causing it with the red player?
Answer: It's the follow-through , the only way to fix it is to practice your serving motion and form
Comment: Quick tip: in-order for you to improve your shoulder swing , try practicing serve by being parallel to baseline , i've done it in my younger days , it can help you control and add more serving power and also improve your service motion
Comment: regarding with that , when i was starting tennis in my younger days, i am having a hard time serving hard and according to my coaches that i had unnecessary movements and i needed whip motion for me to serve effectively, that's why they introduce me to that training and also squat training for the spring effect.
Comment: Glad i could help, cheers for the discussion , i've learned alot. Keep Playing!
Comment: It is the follow-through, spot-on +1. **I suspect the reason for the swing is too tight rotator/shoulder cuff**: the massive rotational force spins the torso to the side in the point where the flexible shoulder cuff should make room for the motion...I think I better improve the rotator cuff flexibility before any further changes...
Comment: You mean legs parallel to the baseline and direction of the body after serving perpendicular to the baseline? My upper body analysis [here](http://fitness.stackexchange.com/a/19404/6066) which I suspect causing the stiffness and so the extra unnecessary swing. I must get the flexibility better...trying to find solutions to rotator cuff flexibility...
Comment: Excellent point about squats! And squats must be done with that kind of explosive power to use glycogen energy reserves (not long switch). I am building rotator cuff training to me -- and now I also need to do more explosive squats training -- that is so sure! The explosive jump/turn requires squats/explosiveness from all muscles (not just from upper body). I think I better start booty training -- **perhaps the swing is also due to imbalances due to muscles --> next more booty/squats/shoulder-cuff training**. Training [rotator cuff](http://www.pinterest.com/henrilosoi/rotator-cuff/).
Comment: Also I have S-shaped back, hunched back in the video -- which results into poor form. It can be improved by keeping the position better (middle part of body forward so breasts less hunced and back more straight).
Comment: I collected points so far emerging [here](http://sports.stackexchange.com/a/7360/630), there is many little points to which I need to concentrate on my training -- amazing brainstorming. Big thanks for your contributions, I am starting to feel so motivated to my training again :D
Comment: I created a video showing how I understand explosive [squats](https://www.youtube.com/watch?v=8dckzhtPCJI&t=1m16s) for improving the tennis serving :)
Answer: I am trying to summarise points emerging in the other answer and its comments. Video shows possible weaknesses in Technique

legs parallel the baseline and direction of the motion perpendicular the baseline

which can be improved by

stiff shoulder cuff that requires shoulder cuff trainings like here
hunched S-shaped back requires booty training like here
explosive serving requires explosive squats like here where you use as many leg muscles as possible: use hypothrophy/power training using the glycogen energy reserves for the first serving while the second serving can be done with different technique with less power


B - F - A chord in the key of C major

Question:
It was published in 1891 so I guess the harmony is based on common practice era music.
There is one exercise (in C major) that I can play but I just don't really know how to understand it theoretically.
1 bar: I, V6, IV6, I6/4,
2 bar: IV6, then a chord with B-F-A, then ending on I
These are two of the 4 bars (and the left hand plays only a C octave).
I do not understand the B-F-A. All I know is that if you move B and F one half step you will end on C and E.
How should one view the B-F-A chord? Cause we are thinking in chord, right? And what I learn in school was that when taling about inversions you must look at both the left hand and the rght hand. So if there is a C octave in the left hand then all I (or C) chords will be said to be in first inversion?
Comment: No, Schytte probably wouldn't have considered (or really used) a B-F-A agglomeration as a chord: he would have considered one or more of the notes as non-harmonic (i.e., an auxiliary or appoggiatura or accented passing tone). Can you print-screen the passage, or give us more info as to where it can be found (which publication, which page)?
Answer: There are two ways of viewing this passage, both, I think, equally valid.

On a small-scale level, where every note is harmonized against some type chord, this would technically be a B half-diminished (without the D), as Victor points out (over a pedal C).
If you take a step back to a higher level, and look at the functions throughout the measure, you have what Patrx2 describes: an F/C resolving to C (a plagal cadence). In this view, the B is just a passing tone to get from A to C. You can test this by playing the passage twice: as written, and then replacing the B with a C (making it fully a plagal cadence). The second sounds sufficiently similar to the written version that there is no critical loss of function.

I would tend to favor the second view, but the main difference between them is whether you consider the B as harmonic or non-harmonic, which is largely a semantic issue that raises the question of how granular harmony is. You could even combine the two views, and see a B half-diminished chord that is a non-fuctional "passing chord" on the way from F to C. At this point, you can start to see harmonies as existing in a hierarchy of importance, and you've taken your first step on the road to all sorts of cool harmonic analysis.
Answer: In the key of C major (B - F - A) could be used to imply a B half-diminished 7 chord (B - D - F - A). Although not the most common, it isn't unusual to see a missing 3rd in a half-dim; omitted notes help avoid voice leading problems.
Bar1: I-C; V6-G/B; IV6-F/A; I6/4-C/G;
Bar2: IV6-F/A; vii©7-B©7
Specific to this example:
You could argue two basic things:
1) The (B-F-A) notes are neighbor tones, being used to decorate the end of the exercise.
2) The (B-F-A) notes are a chord, being used harmonically.
*) It's both!
Given that there are only chords in the exercise, and that the harmonic rhythm is a quarter note (e.g. one chord per quarter note), there's a stronger argument for it being a chord rather than a stack of non-chord tones. This argument is further supported by the tempo of the exercise, lento. That leaves the C bass note acting as a non-chord tone.
Comment: @BobRodes, sure. It's a rootless dominant ninth. It was, however, not gapped all that often (the sound of the interlocking diminished and perfect fifth is characteristic), and, in this case, we would have the 7th in the bass, possibly with the root in the descant. If F/A remains fixed throughout the bar, and there's a C-B-C movement in the descant with B on a weak beat, then it may well make more sense to describe B as an auxiliary note. That's why I want to see the passage.
Comment: I'm not sure about a typo here, though, @jjmusicnotes. The function here looks deliberately ambiguous and inconclusive, as perhaps it should be - this isn't really a full phrase at this point. The 2 bars in their entirety are really just establishing and elaborating the tonic. Notice the importance of the melodic motion: the descant descends to E, then uses a fairly standard centering motion around G (F-A-G), while the tenor steps from C to G and back up to C, and the alto drops from E to C, holds C, then articulates 4-3 over the bass. (_more_)
Comment: I'm thus inclined to see this as a somewhat ambiguous mixed function chord, where various voices are suggesting different functions. The top two voices are articulating a fairly common shift of the IV chord so as to centre on C/E, whereas the tenor B both acts as a passing note _and_ suggests dominant function. The "gapped chord" thus suggests both plagal and (imperfect) authentic motion, while the earlier chords are articulating I, V and IV in the most melodic way possible. (_more_)
Comment: However, given two bars that start and end at the tonic, and state the tonic in the middle at the lowest point, all over a strong tonic pedal, I'm also inclined to see this as two bar of straight tonic harmony with melodic elaboration in all the upper voices.
Comment: Ah. I overlooked the first inversion on F. Sight unseen, the passage probably holds IV for the entire measure, and the B is the lower auxiliary of the C that is common to both IV6 and I. 19th century voice leading practices weren't _purely_ chordal: they did include the notion of non-harmonic notes. I think we need to see the passage.
Comment: If I remember my Music Theory 101 classes all these years later at all well, the vii half-diminished chord resolving to tonic was fairly common in the 19th century.  I can't think of any examples off the top of my head though.
Comment: I actually think it's a typo. If the "A" were replaced with a "G" would make the chord a V6/5 with an omitted fifth, a very common move.  We know from the first two chords that smooth voice-leading is acceptable in this piece of music, so it's possible. Half-diminished chords were mostly used as pre-dominants, not as agents of cadences themselves, like the leading-tone chord. Because of this fact, I think it's unlikely that the composer would have used a half-diminished chord to resolve to tonic; unless the function is to prolong a plagal cadence as Patrx22 describes.
Comment: @Patrx2 I can see that as well; I just thought I'd offer a different viewpoint for the sake of variety. It would be interesting to see where this music comes from.
Comment: @jjmusicnotes, I agree. I couldn't find it on IMSLP, although it's a bit difficult to search there with just a music sample to go on. It's an interesting example. One of the things that tends to drive me a bit batty is that so many here tend to look at chords, chords and more chords, but tonal function has always been as much a resultant of lines as harmonies, and the often ambiguous interplay between the two, which this simple chordal example illustrates nicely.

B - F - A chord in the key of C major


How to get the GPRS Mobile data usage for 1 month?

Question: I have searched a lot about this. Found the same code everywhere which solves the purpose partially. As API documentation says, it reset the counter once the device restarts. Sometimes the counter just resets even without the restart. Below is the code
<code>float totalRxBytes = (float)TrafficStats.getTotalRxBytes()/(float)1048576;  // Received
float totalTxBytes = (float)TrafficStats.getTotalTxBytes()/(float)1048576;  // Sent
float mobRxBytes = (float)TrafficStats.getMobileRxBytes()/(float)1048576;
float mobTxBytes = (float)TrafficStats.getMobileTxBytes()/(float)1048576;
float wifiRxBytes = totalRxBytes - mobRxBytes;
float wifiTxBytes = totalTxBytes - mobTxBytes;
</code>
But I could not figure out any way to have this data from a specific date OR for a month? Please help. Any pointer will be appreciated.
Thanks.
Comment: any pointers please ?
Comment: you might find an answer here http://stackoverflow.com/a/7640565/6689101
Answer: First of all, TrafficStats.getTotalRxPackets():

Return number of packets received since device boot.

The same is with TrafficStats.getTotalTxPackets()
This class is not helpful for getting month statistics.
I would advise solution working from API 23:
NetworkStatsManager
This class has the possibility to obtain statistics per device or per package. Especially helpful for you would be function:
NetworkStatsManager.querySummaryForDevice()
which expect measuring start time as third parameter and end time as fourth paramter.
The sample project can be found here. It shows how to obtain access to NetworkStatsManager asking for appropriate runtime permissions.
This solution is only API 23+.
If you really want to use TrafficStats then create a Service that would get the result of TrafficStats.getTotalRxPackets() every hour, count the difference, save it in database in different row per day.
Comment: Hello Zag,
Thanks for the information. I answer is useful and I am trying to implement the same.
Comment: I am facing 1 issue and could not solve it yet.    ERROR : "java.lang.RuntimeException: java.lang.SecurityException: NetworkStats: Neither user 10053 nor current process has android.permission.READ_NETWORK_USAGE_HISTORY".      I am implementing this in API 23 which is having a runtime security implementation for permission, I hope you understand what I am trying to say. I was able to add android.permission.READ_NETWORK_USAGE_HISTORY in Manifest but I am not able to add the same permission in Java file because its giving the compilation error. Could you please help ?
Comment: Look into the [sample project](https://github.com/RobertZagorski/NetworkStats). Especially into the `AndroidManifest.xml` and into `MainActivity` on how to ask for it and use it.
Answer: I agree with R. Zagorski, but I have a different approach in mind.
Use TrafficStats to get amount of packets received/sent, subtract the last amount from it and then save it using SharedPreferences along with the last amount. Now, to handle a device restart, always check if the last count is greater than current amount. If yes, reset the last amount to 0. Also, keep track of when the month started. As soon the month has ended, don't forget to reset the counts to 0!
If you wish to keep track of the previous month counts as well, use a List. When the month gets over, add the total amount to the array at the index of the month number. Also, keep in mind that the first index is 0, not 1. So, you'll have to offset the array by 1 value to be able to directly use the month number to query your list.
This has an advantage over R. Zagorski's idea (which is also quite good) that it can be used from api level 8 as that's the minimum for TrafficStats.
Hope I Helped :D


Brightcove Connects breaks site after core upgrade to 8.5.x in Acquia Cloud

Question: After upgrading core to 8.5.2, and eploying to Acqui Cloud, Brightcove causes a fatal error. Note, the code works as expected in my local DevDesktop environment, and I am unable to recreate the error locally.
Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveCmsEntity' not found in /mnt/www/html/xxx/docroot/modules/contrib/brightcove/src/Entity/BrightcovePlayer.php on line 30
The error is thrown via http and drush commands
Answer: I discovered the issue. Case-sensitivity of the class names. Class "brightcove/src/Entity/BrightcovePlayer.php" extends "BrightcoveCmsEntity", while class "brightcove/src/Entity/BrightcoveCMSEntity.php" is named as "BrightcoveCMSEntity".
I replaced all instances of "BrightcoveCmsEntity" with "BrightcoveCMSEntity", and the issue was resolved, it exposed the same issue with "BrightcoveVideoPlaylistCmsEntity".
Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveVideoPlaylistCmsEntity' not found in /mnt/www/html/nhradev/docroot/modules/contrib/brightcove/src/Entity/BrightcoveVideo.php on line 75
Replacing all instances of "BrightcoveVideoPlaylistCmsEntity" with "BrightcoveVideoPlaylistCMSEntity" resolved all issues.
The plugin now works as expected in Acquia Cloud.
NOTE, the code worked locally because I am developing on Windows.
Files touched:
brightcove/src/Entity/BrightcoveCMSEntity.php
brightcove/src/Entity/BrightcoveCustomField.php
brightcove/src/Entity/BrightcovePlayer.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php
brightcove/src/Entity/BrightcovePlaylist.php
brightcove/src/Entity/BrightcoveVideo.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php
brightcove/src/Form/BrightcoveVideoPlaylistForm.php
Reference: https://www.drupal.org/project/brightcove/issues/2969674


How to show if $\Gamma\models\bot$, then $\Gamma$ is not satisfiable?

Question: I am struggling to show that for any set of sentences $\Gamma$, if $\Gamma\models\bot$, i.e. $\Gamma$ entails $\bot$, then $\Gamma$ is not satisfiable, i.e. for any structure $M$, $M\not\models\Gamma$.
My idea is to prove by contradiction:
Assume to the contrary that $\Gamma\models\bot$ and $\Gamma$ is satisfiable. Then there is some structure $M$ s.t. $M\models\Gamma$. Since $\Gamma\models\bot$, $M\models\bot$...
I am not sure what to do next.
Comment: Looks fine so far. What to do next: observe that by definition of satisfaction for $\bot$, $M\not\models \bot$, so we have a contradiction.
Answer: First, suppose that $\Gamma \models \bot$, then for any $p, \Gamma \models p \land \neg p$ (why?).
Now let M be any model of $\Gamma$. Then apply the definition of satisfaction to obtain a contradiction.


Xcode interface builder: Static table view cell font is not being set

Question: I am trying to set the font of static table view cells, using Interface Builder. I added all the cells visually using interface builder. Now I want to change the font of the table view cells.
First, I tried selecting the label of each cell and changing it to attributed text, and I set the font. Even the preview is showing the correct font, but the simulator still shows the normal font.
Then I kept it as a plain label, but changed the font from there. Still, the Interface Builder shows the correct font. But the results show otherwise.
So what do I do? It'll be a hassle to create an array, create a bunch of segues, and use the cellForRowAtIndexPath function. Maybe there's a better way? Thank you.
Answer: You should use following method willDisplayCell to set custom fonts of the table cell:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

cell.textLabel.textColor=[UIColor whiteColor];
cell.detailTextLabel.font=[UIFont fontWithName:@"Helvetica" size:16.0];
cell.detailTextLabel.textColor=[UIColor blueColor];
}

because your changes will be lost when the cell is actually displayed using xib file or using cellForRowAtIndexPath method.
follow this LINK and LINK


Mail getting blocked as abuse, error 500

Question: we just moved our domain ( daytonaparts.com ) to a new service provider ( ait.net ) and since we went live we have had our emails rejected by AT&T and Microsoft ( Hotmail, MSN, Live.com ) with an Error 500 based on our IP. We are not sending spam or newsletters, these are just responses to customer emails. We have tried to contact the 2 behemoths but have gotten nowhere.
Does anyone have any Ideas how to get removed from these lists
Answer: The best thing to do is use a service like mailgun or sendgrid. They provide a way to relay your email through their email servers like its coming from you. Both offer free tiers that allow you to send like 10k emails a month.
Once setup, you never have to worry about keeping your ip range off a blacklist.


Correlated categorical predictors

Question: I am using an automated variable selection technique to find covariates in a regression model. Notwithstanding the issues with automated variable selection, the procedure has returned two categorical covariates, RACE and LOCATION. RACE has five categories (1,2,3,4,5), and LOCATION has two (A and B). Part of the issue is that in location A, most of the RACE observations fall into a specific category, so it seems including both covariates is redundant...?
What is a typical procedure to deal with this? Would I want to combine categories somehow?
Answer: A simple solution is to dichotomize all your categorical features before running the automated variable selection process. For instance, you can create five dummy (binary) features for RACE:

RACE_1 = 1 when RACE = 1, else 0
RACE_2 = 1 when RACE = 2, else 0
...

The automated variable selection process should have a subroutine that removes heavily redundant (correlated) features. This is relatively easy to do once you have all numeric features (continuous, and binary) instead of a mix of numeric and character fields.
One approach to remove such redundancy is to study pairwise correlations between all of your input features and identify heavily correlated pairs. From each such pair, discard the field that has a lower correlation with the dependent variable.
In addition (or alternatively, if you prefer), you can perform multicollinearity diagnostics to remove fields that are heavily correlated with other fields.
Comment: But is it necessary to re-do automated variable selection? In other words, is it also plausible to just create a new categorical variable that combines RACE and LOCATION i.e. If RACE= 1 and LOCATION =A, RACELOC = 1, etc?
Comment: You could create those new variables by combining RACE and LOCATION. However, the new variables should be scrutinized by the automated variable selection process, otherwise they would be getting a free pass.

Correlated categorical predictors


How to pass non-object arguments in launch.json for debugging in VS Code

Question: I have been able to use args from the launch.json file as described in this question post
In Visual Studio Code, how to pass arguments in launch.json
But I want to pass in an argument without a value. When I call the executable in the shell, I call it with a single argument like so:
a.exe -fw

*where the fw arg prints out the firmware version. This works well, but I cannot simulate this in debug since I get an error that my arg needs to be an object.
"configurations": [
    {
        "environment": ["-fw"]
    }

This gives me an error
Incorrect type. expected "object"

But I dont want to pass in a value, it is basically just a read argument.
How do I incorporate this in my launch.json file?
Thanks!
Comment: You can delete the question if it is due to a typo
Answer: Nevermind... I realized I copy pasted my args in the "environment" pair and not the the "args"... everything works as expected
        "args": [
            "-fw"
        ],


Rails - Joining multiple tables

Question: I have the following models:
class Company < ActiveRecord::Base
  has_many :price_movements
  has_many :goods_movements
end

class PriceMovement < ActiveRecord::Base
  belongs_to :company
end

class GoodsMovement < ActiveRecord::Base
   belongs_to :company
end

I am trying to join everything together into an sql in the form of activerecord, but I'm not sure how to go about doing it because I'm relatively new to ROR.
select * from companies c

inner join price_movements p
on c.id = p.company_id

inner join goods_movements g
on c.id = g.company_id
and g.date = p.date

The key problem for me is the second link where goods_movement date == price_movement date.
Can someone advice on whether there's any way to do it?
Answer: Company.joins(:price_movements,:goods_movements).where("goods_movement.date = price_movement.date")

Go through this link it has detailed explanation of how to use ActiveRecord
Comment: Just an additional question: In terms of efficiency, because the two tables are huge to begin with, this ActiveRecord query takes 8000ms compared to the sql that completes in 3000ms. Is there any ways to speed things up a little in ActiveRecord? I am using ActiveRecord::Base.connection.execute() in the latter.
Comment: What would be the way to go about getting the records from PriceMovement and GoodsMovement where Company id is 1?

Rails - Joining multiple tables


Updated to InnoDb - MySQL Unstable

Question: I have updated several MySQL tables to InnoDb. After doing so, MySQL has become sluggish and the hard drive I have the database on is constantly writing, even though my changes have been completed. Peridoically the CPU will get heavy use, 100% on two cores, but whatever is using them is not registering that us in System Monitor (Debian). Reading the database is possible, but slow. I have not tried writing, as it is obviously busy doing something - but I do not know what.
Digging deeper, I have found that I have a very large ibdata1 file, almost 62GB - I have some large tables in InnoDB, including 16, 10, 9, 1.5 and 1.1 GB; and many smaller.
Does anyone have any idea what may be happening here? Or logs I can look at that might shed some light? I have restarted, but when MySQL comes online, the same thing happens, and has been going on for over an hour. Also, would it be a good idea for me to change some InnoDB tables to MyISSAM? Of the large ones, none require InnoDb for transactions, but some of my smaller ones do (under 50MB).
Comment: Can you share more details. How big is the database, what kind of issues are you faces. "Sluggish" and "Doing something" is too generic
Comment: I think you should try to optimize innoDB first. Just an opinion
Comment: What would that entail? At the moment I can't really do anything. access to the database is very sluggish, and the hard drive is constantly doing something.
Comment: Added more notes above.
Answer: Two most important options to start are innodb_buffer_size and innodb_logfile_size. Set former to be as big as your database, but leave at least 4-6G for the OS.
Optimal logfile size depends on how much you have writes, but something around 256M works for most workloads.

Updated to InnoDb - MySQL Unstable


Trigger whenever a user uploads an image

Question: I would like to enable certain actions to occur whenever a user uploads an image, namely movement to s3 and adding an entry in the db for site and metadata purposes. What would be my first steps in accomplishing this?
Answer: If you're using a field field in Drupal 7, you could accomplish this with the use of stream wrappers, core-supplied file API hooks, and a file field.
See the file examples in the Examples for Developers module. Also read through the 'Stream Wrappers and You' post from Advomatic for some background.
For more advanced triggered actions, you could also consider using the Rules module to react to a file being uploaded to the site via a new node or other entity type.


Finding argument of a complex number

Question: How do you evaluate the following
$$\text{Arg}\{\sin\frac{8\pi}{5} + i(1 + \cos\frac{8\pi}{5})\}$$
Comment: what formula for argument are you familiar with?
Comment: Plot in argand plane.
Comment: I am getting it of the form arg(a+b) which I am not able to evaluate
Comment: Since a complex number can be plotted on the plane, you can draw a line from the origin to the point and use $\tan$ to obtain the angle the line makes with the positive real axis.
Comment: It is equal to $\dfrac{7\pi}{10}$.
Answer: $\displaystyle1+\cos\frac{8\pi}5=1-\cos\frac{3\pi}5>0$
and $\displaystyle\sin\frac{8\pi}5=\sin\left(\pi+\frac{3\pi}5\right)=-\sin\frac{3\pi}5<0$
So using the definition of atan2, $$\text{Arg}\left[\sin\frac{8\pi}{5} + i(1 + \cos\frac{8\pi}{5})\right]=\pi+\arctan\left(\frac{1-\cos\frac{3\pi}5}{-\sin\frac{3\pi}5}\right)$$
Now, $\displaystyle\frac{1-\cos2A}{-\sin2 A}=\frac{2\sin^2A}{-2\sin A\cos A}=-\tan A=\tan(-A)$
Here $\displaystyle2A=\frac{3\pi}5$
$$\implies \text{Arg}\{\sin\frac{8\pi}{5} + i(1 + \cos\frac{8\pi}{5})\}=\pi+\left(-\frac{3\pi}{10}\right)=\frac{7\pi}{10}$$

Finding argument of a complex number


How to validate a value against an existing field

Question: I'm doing some custom stuff with programmatically saving fields with EMW:
<code>$wrapper->my_field->set('my_value');
</code>
Problem is, this doesn't validate before trying to save the field. How can I validate the value against the field before trying to save it?
Comment: Are you trying to validate the value against the field of the entity you saved before? Is it an edit action?
Comment: Yes it's editing, but whether it's editing or a new entity I don't see the difference.
Comment: Yes, i just misunderstood the question. zhilevan is right, you have to add your custom validations using for example some regular expressions etc depending on what you need for your field.
Answer: install entity_validator module .

Unlike Drupal 8, Drupal 7 has not validation for entity objects what
  so ever. One of your modules can create a node object without any
  title or a language and you don't want that.

for drupal 8 Use Entity Validation before save your fields.
as a example
<code> $violations = $typed_data->validate();
    $definition = DataDefinition::create('integer')
      ->addConstraint('Range', ['min' => 5]);
    $typed_data = \Drupal::typedDataManager()->create($definition, 10);
  if ($violations->count() == 0) { // this means there is not any validation error
     // save Entity
  }
</code>
Comment: @Smalution Oops, so there is no convenient way, you can write your own custom validator and check items before saving or wait for entity wrapper exceptions :D
Comment: Whaaat? How does Drupal itself do it? There must be a function somewhere!
Comment: @Chris Unlike Drupal 8, Drupal 7 has not validation for entity objects what so ever.
Comment: @Smalution Check the Answer again, I update it.


Wireshark Data view

Question: I would like to view the data from the capture in plain text, but when I do the "Follow UDP Stream" all I see is:
..........x..7..L....7....
..7..Ver 6.41 Dec 21 2011...d..7..~PIN2Width...a..7..~PIN2Width=5......7..~ExtendFmt...
..7..~ExtendFmt=1......7..WorkCode......7..WorkCode=0...Z..7....s..7..
Does anyone know how to fully decode the data section of the capture so that I can read it?
Thanks
Answer:
I would like to view the data from the capture in plain text,

Not all data from a capture is plain text.

Does anyone know how to fully decode the data section of the capture so that I can read it?

I've heard there's a program called "Wireshark" that does a pretty good job of it.  The middle pane of its display shows packet data as fully as it can.
Comment: The Details pane needn't be in the middle, see Edit / Preferences / Layout. Note Wireshark guesses the protocol/format of the data by looking at the port numbers; if you have a known protocol over an unusual port, rightclick the List-pane entry (or select it and click Analyze), choose DecodeAs..., identify the source/dest port that matters, and choose the protocol.

Wireshark Data view


Proving the Extreme Value Theorem

Question: Lately I have been trying to prove the extreme value theorem using the concept of Cauchy sequences but I can't figure out how to start or where to go after I have started, and I was if anyone could lead me to proving it.
Theorem:
In calculus, the extreme value theorem states that if a real-valued function f is continuous in the closed and bounded interval [a,b], then f must attain a maximum and a minimum, each at least once.
Comment: What do you have?
Comment: @Demosthene Pretty much nothing, I've been wondering how to start and I amn't certain. However, I know how to prove that a function attains a maximum value, http://math.duke.edu/~cbray/Stanford/2000-2001/math41/EVTProof.pdf, but do not know know whether the same method can be extended to prove a function attains a minimum value or whether I even need to do that.
Answer: f is continuous and bounded on $[a,b]$ such that $c,d\in[a,b]\subset \mathbb{R}$.
Let $\alpha :=inf\left\{f(x):x\in [a,b]\right\}$. This exists because f is continuous on the bounded interval $[a,b]$. (What is it's infimum?)
$\alpha$ denoted as the infimum of the function $f$ on $[a,b]\Rightarrow \alpha+\frac 1n $ isn't the greatest lower bound of $f$. Thus $\exists$ some mapping $x_n \rightarrow f(x_n) \ s.t. f(x_n)$ lies in between its infimum $\alpha$ and $\alpha+\frac 1n$.
Mathematically this can be notated as the inequality $\alpha \leq f(x_n) \leq \alpha+\frac 1n$.
$f$ is bounded on $[a,b]\Rightarrow$ its equivalent sequence, let's call it $a_n =\left\{x_n\right\}_{n=1}^{n= \infty } \ \forall n\in\mathbb{N}$, is also bounded on $[a,b]$. Thus by Bolzano-Weierstrass theorem, $a_n$ contains at least one convergent subsequence in the interval $[a,b]$, let's call it $a_{n_i}$ for $i\in$ of $n$, such that $\lim_{i\to\infty}{ \ (a_{n_i})}=c$
Because f is continuous, the limit of the function, or in this case, sequence, is the function of the limit. So the following results:
$$\lim_{i\to\infty}{ \ (a_{n_i})}=c\Rightarrow f(\lim_{i\to\infty}{ \ (x_{n_i}))}=f(c) \ for \ c\in [a,b]$$
Going back to our definition for $\alpha$, and applying the squeeze theorem for functions, we note:
$$\alpha \leq f(x_n) \leq \alpha+\frac 1n \Rightarrow \lim_{n\to\infty}{ (\alpha)} = \lim_{n\to\infty}{f(x_n)}=\lim_{n\to\infty}{(\alpha+\frac 1n})=\alpha$$
Noting that if a sequence or function is convergent, that all of its subsequences/subfunctions are convergent to that same limit value, we thus finally have:
$$\lim_{i\to\infty}{f(x_{n_i})=\lim_{n\to\infty}f(x_n)=\alpha}$$
This implies $\alpha :=inf\left\{f(x):x\in [a,b]\right\}=f(c)$
Thus the function f achieves a minimum value $f(c)$ for $c\in [a,b]$.
To prove the maximum version, consider some number $\beta \ s.t. \ \beta :=sup\left\{f(x):x\in [a,b]\right\}=f(d)$ for $d\in [a,b]$.
Comment: A system flag has been raised. You have posted the exact same answer twice. The system doesn't like it. Is there a particular reason for you to do this?

Proving the Extreme Value Theorem


programmatically add a UIButton to rootview, what am I doing wrong?

Question: I have freshly setup app, just with a window an a root view (from the iOS single view application template, provided by XCode).
Now I try to add a button to it.
The according code looks like this:
<code>- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UIButton* button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button0.frame = CGRectMake(140, 230, 40, 20);
    [button0 setTitle:@"Exit" forState:UIControlStateNormal];
    [button0 addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [self.viewController.view addSubview:button0];

    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
    else
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}
</code>
When I start the app, I can only see the empty view.
However, when comment out the line, which adds the view as root to the window and instead directly add the button to the window, then I can see the button just fine.
So why isn't this working with the view?
Answer: The problem is that, you are adding button0 as subview of self.viewController.view even before allocating the viewController.
By the time you call addSubview: method, self.viewController is nil. So, the button is not added to the viewController. You should add the button after you allocate the viewController.
<code>self.viewController = [[ViewController alloc]...
[self.viewController.view addSubview:button0];
</code>
Comment: Wow, looks, like I have been blind.
Answer: At first, create the root viewcontroller, later add subviews to it. You did it the other way round.


Is there a special etiquette in mixed doubles tennis?

Question: Though mixed doubles are rarely broadcasted on Television, they are a part of official Tennis tournaments, including the Grand Slams. I am wondering, whether on that professional level, there is any unwritten Rules between the players.
Female players at average and at top-level have slower hitting speeds, which is especially important regarding serves. So even if they do not have slower reaction times, a women will simply not be used to returning a 220 kph serve (unless she is specializing on mixed doubles). So would a male server "restrain" himself when serving? Likewise, would a male player "attack" the female opponent standing at the net like he would with a male counterpart?
Comment: Tennis maintains the traditional binary-sex-assignment grouping of players into male and female groups. Mixed doubles means exactly having one male and one female player together. The words have no meaning beyond their standard English definitions.
Comment: What do you mean by male and female?
Answer: No, there is no special etiquette in mixed doubles tennis matches at the professional level. Professional players are expected to adhere to the rules of the game, that is all. As professionals, they are aware of their own strenghts and weaknesses and also of their opponents. If the opposing mixed double team has a female player who has difficulty returning a hard service, that is simply a bonus. No restaint is required or expected, as this would only harm the chances of the restraining team. Similarly if the male of the opposing team has a poor backhand, it is perfectly okay to direct as many balls as possible to his backhand. If a team loses matches as a result of these weaknesses, the two players should address this problem and train harder. That is what professionals do.
Comment: This answers has the implicit assumption that there are "mixed doubles teams" which train together and actually care a lot about winning - but that's not really the case: mixed doubles is played only at the Grand Slams, with pairs often formed in the couple of days before the tournament for a bit of fun. As such, it _is_ treated a lot differently from the "regular" competitions.


Application of Schwarz lemma and Liouville's theorem

Question: I recently came across the following problem

Let $h : \Bbb C → \Bbb C$ be an analytic function such that $h(0) = 0, h(1/2) = 5$, and $|h(z)| < 10$ for $|z| < 1$. Then pick out the correct statement(s):

the set $\{z : |h(z)| = 5\}$ is unbounded by the Maximum Principle
the set $\{z : |h'(z)| = 5\}$ is a circle of strictly positive radius
$h(1) = 10$
regardless of what $h'$ is, $h'' \equiv 0$.

My try
Consider $f(z)=\frac{h(z)}{10}$ and $f$ satisfies the hypothesis of Schwarz lemma, so $$\vert f(z) \vert \leq \vert z \vert$$ and so $$\vert h(z) \vert \leq 10 \vert z \vert ^1$$ so by extended Lioville's theorem, $h$ is a polynomial of degree atmost $1$. So $h$ is either constant or linear. But given hypothesis implies $h$ is not constant and $h$ is exactly $10z$. That is, $$(\forall z \in \Bbb C): h(z)\equiv 10z$$
So the set in the first bullet is a circle $\vert z \vert =1/2$ ,which is bounded and so it is false
The second set is $\varnothing$ and so the second  one is false
Third and fourth are true. Since $h$ is linear , its second derivative vanishes!
Is my reasoning correct ? Any thoughts?
Edit:  I agree that my reasoning in wrong as Mr. Kavi Rama Murthy says in the comment. So this $h(z)=10z$ helps to eliminate the first two options. But how to conclude the last two. Any help ?
Comment: By Schwarz Lemma you only get $|h(z)| \leq 10|z|$ for $|z| <1$ . This does not tell you that $h$ is a ploynomial.
Comment: @KaviRamaMurthy: So how to proceed further ? kindly explain !
Comment: Consider the function defined on the disk $f(z)=h(z)/(10z)$. By Schwarz lemma, $|f|$ is $1$ at $1/2$ and $1$ is the supremum of $|f|$ on the unit disk. So the right argument is not Liouville but something else.
Answer: Since $h$ is entire with $h(0)=0$, the function $f(z):=h(z)/10z$ is entire. Since $|h(z)|<10$ on the open unit disk, by continuity, $|h(z)|\le 10$ and thus $|f(z)|\le 1$ on the unit circle. By maximum modulus principle, unless $f$ is a constant, the maximum of $|f(z)|$ over closed unit disk can be only achieved on the boundary, that is, the unit circle.
Suppose to a contrary that $f$ is not a constant. Then $|f|\le1$ in the closed unit disk. But we have that $|f(\frac12)|=1$, which asserts that the maximum of $|f|$ over closed unit disk is achieved by an interior point. This gives us a contradiction.
Therefore $f$ must be a constant. Since $f(\frac12)=1$, $f(z)=1$ for all $z$. So $h(z)=10z$.
Comment: Thanks!.........
Answer: Let $g(z)= h(z)/10.$ Then $g$ restricted to $\mathbb D,$ let's call it $\tilde g,$ maps $\mathbb D$ into $\mathbb D,$ sends $0$ to $0,$ and takes $1/2$ to $1/2.$ By the Schwarz Lemma, $\tilde g(z)= z.$ That is the same as saying $g(z)=z$ in $\mathbb D.$ By the identity principle, $g(z) = z$ on all of $\mathbb C.$ Therefore $h(z) = 10z$ on $\mathbb C.$ In order then, we see the given statements are false, false, true, and true.
Comment: This helps too! Thanks!
Answer: A partial solution : Schwartz Lemma does not work completely( on boundary ) . To discard some options take counterexample as $f(z)=10z$.


Joint Probability Distribution of the marginal gaussianization of a multivariate distribution

Question: I have a set of random variables $Y = Y_1, \dots, Y_k$, where each $Y_i$ follows a gamma distribution. I would like to transform the variables into normally distributed variables.
Suppose I use a function  $\phi$ to marginally transform all $Y_i$ so that they follow a normal distribution, i.e. $$\phi: (Y_1, \dots, Y_k) \rightarrow (\phi_1(Y_1), \dots, \phi_k(Y_k)),$$
so that each $\phi_i \sim N(\mu_i, \sigma_i)$. Call $Z =(\phi_1(Y_1), \dots, \phi_k(Y_k))$.
Now I wonder about the relationship between the joint probability distribution of $Y$ and the joint probability distribution of $Z$. Is there any way to recover  the joint probability distribution of $Y$ from the joint probability distribution of $Z$? Maybe making some assumptions over $\phi$?
Comment: why are you doing this?
Comment: @Aksakal I am studying Latent Variable Models and I wonder about the relationship of the latent variable and the modeled variable in global terms, so I thought in the JPD.
Answer: One way to transform is as follows.
Suppose gaussian CDF is $F$ and Gamma CDF is $\Gamma$.
$$Z_i=F^{-1}_i(\Gamma_i(Y_i))$$
If you do it this way the converting back to Gamma is straightforward, and the correlation structure will be preserved in the following sense:
$$C=cov[\Gamma(Y)]=cov[F(Z)]$$
Comment: Why does this *nonlinear* transformation preserve correlations?  (I doubt it does.)
Comment: @whuber, correlation in certain way, i.e. uniforms formed by CDF
Comment: I see now.  It's hard to decide whether that's a clever or trivial observation, but maybe it's both ;-).  (+1)
Comment: @Aksakal I think you meant "converting back to Gaussian" -> " converting back to Gamma"?
Comment: @Aksakal Also, I think the first formula should be $Z_i=F^{-1}_i(\Gamma_i(Y_i))$
Comment: @D1X, yeah, I mixed them up


Why does sem (GNU parallel) behave differently with single quotes and double quotes?

Question: I can't understand the following behavior of sem from GNU Parallel.
When I use single quotes, it seems to work well:
sem -j1 'echo $(date);sleep 5;echo $(date)'
sem --wait

gives
Sat Apr 23 15:46:50 EDT 2016
Sat Apr 23 15:46:55 EDT 2016

However, when I use double quotes.
sem -j1 "echo $(date);sleep 5;echo $(date)"
sem --wait

the result is
Sat Apr 23 15:46:08 EDT 2016
Sat Apr 23 15:46:08 EDT 2016

where it seems that the sleep 5 is totally ignored.
Could anyone explain why this happens? Is it caused by GNU parallel or bash?
Comment: See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858)
Answer: It has nothing to do with sem or GNU parallel, but everything to do with the shell.
When you use double-quotes for strings, the shell expands all environment variable references at once. If you use single-quoted strings the shell doesn't do that variable expansion.


Power and exponential of the following Jordan form

Question: Let
$$J=
        \left(\begin{matrix}
        4 & 1 & 0 \\
        0 & 4 & 1 \\
        0 & 0 & 4 \\
        \end{matrix}\right)$$
What $e^{Jt}$ and $J^t$ look like? Can you help me, please?
Answer: Hint: Note that $J = 4I + N$, where
$$
N = \pmatrix{0&1&0\\0&0&1\\0&0&0}.
$$
We have $\exp(Jt) = \exp((4I + N)t) = \exp(4It)\exp(Nt)$.
Similarly, we can expand $(4I + N)^t$ using the binomial theorem for any integer $t$.
Both of these are made easier to compute by the fact that $N^3 = 0$.


How do you use and activate Node.js on a Chromebook?

Question: I've been looking all over the internet to figure this out, but it always comes up with results for "How to Install Node.JS". What I'm looking for isn't how to install it, but how to actually use it once it's installed on my Chromebook. Any help would be much appreciated.
(Chromebook is a Lenovo S33 with a 32-bit)
Comment: https://support.google.com/chromebook/thread/1370187/how-do-you-reach-the-chromebook-terminal?hl=en ?
Comment: I think you cant. Perhaps you are lucky with compiling it from source. (or this: https://github.com/nodejs/help/wiki/Installation)
Answer: To use node.js in the terminal:
Once you've installed node and npm, you can run the node command in your terminal and type any node.js code in the following prompt. Press ctrl D when you are ready to exit. For example:
node
Welcome to Node.js vX.X.X
Type ".help" for more information.
> var x = 0;
undefined
> console.log(x)
0

To run a node.js file:
You can run the node command followed by whatever file you want to run. For example: node myfile.js


Object initialized via resolve is not "watched"?

Question: I need help to understand the concept of "watching" the changes of an object and updating it in the view.
In my particular case, the object is initialized via the view's resolve then assign to scope's parameter withing the controller.
My expectation is that somehow if I update the original object again then it should change the value printed out in the view
var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        template: 'hello {{ user.name }}',
        controller: 'userController',
        resolve: {
          user: function () {
            return {name: 'john'}
          }
        }
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

myApp.controller('userController', function($scope, user) {

    $scope.user = user;

    // I thought the object is supposed to be watched by reference but it is not
    user = {name: 'doe'}

});

plunker: http://plnkr.co/edit/w7woYVYB6GwCiJpWGWB4?p=preview
Please tell me what I'm doing wrong and how to fix it
Edit for more clarification:
It's my fault to skip the reason behind all this. My resolve actually looks like this:
resolve: {
              user: function () {
                return userService.get();
              }
            }

As you can see, I'm returning an object to resolve (which is a property defined inside the userService). Now, my hope is that if I can simply call userService.update();  in my controller then somehow the $scope.user still pointing to the same object will update automatically. I guess not....
userService.update();

Comment: I updated my answer to show you how to implement the $watch functionality.
Answer: The issue is simple. $scope.user points to a different object than what user points to after the call user = {name: 'doe'}
The fix is either one of them
$scope.user={name:'doe';}

or
$scope.user.name='doe';

Update: If the service updates the data and controllers want to get notify the approach to take would be to raise events on $rootSscope.
In the service you can do
$rootScope.$emit('event.userUpdate',{user:user});

In the controller you can catch this event with
$rootScope.$on('event.userUpdate',function(evt, args) {
   //args should have he update user data, to rebind.
});

Comment: Actually, the problem is that this user is supposed to be updated via a service, so I would prefer to somehow simply update user and the scope will reflect that, any solution at all?
Comment: As long as the service updates the same user object, everything would work fine.
Comment: Thanks Chandermani, I updated my question for some more info, please let me know if I'm not being clear enough.
Comment: An angularjs service is a factory function and as such is fired only once (when the controller is instantiated). You can implement a $watch function to monitor when a change happens and then call the service function again.
Comment: Chandermani is completely correct. His approach is probably what you want. You fire a $emit or $broadcast event when a user has changed and in all interested controllers watch with $on for changes and respond accordingly.
Comment: thank you, I chose to use the solution you suggested :)
Answer: If I understand correctly what you want to achieve, then this should work:
myApp.controller('userController', function($scope, user) {

    $scope.user = user;

    $scope.user = {name: 'doe'}

});

Note the line: $scope.user = {name: 'doe'} instead of user = {name: 'doe'}
Here is your modified plunker.
As you edited your question, I also updated my answer to show you how to implement the $watch functionality. In this case we are watching for a change on a variable willChange and changing the user accordingly. Here the plunker.
Comment: thank you zszep, I updated my question with more info


Enable translation for theme settings

Question: Theme settings are not translatable in core. Is there a way to make them translatable? I have some additional theme settings which needs to have different values per language.
I'm trying to achieve something like this - How do I translate theme settings?
What I have so far -
mytheme/config/schema/mytheme.schema.yml
mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text_format
      label: 'Additional settings'

mytheme/config/install/mytheme.settings.yml
custom_textarea:
  value: "
*this is an additional settings.
\r\n"
  format: full_html
langcode: en

mytheme/mytheme.config_translation.yml
mytheme.settings:
  title: 'my theme settings'
  base_route_name: system.theme_settings
  names:
    - mytheme.settings

theme-settings.php
/**
 * Implements hook_form_system_theme_settings_alter().
 *
 * Form override for theme settings.
 */
function mytheme_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {

  $custom_textarea = theme_get_setting('custom_textarea');
  $form['custom_textarea'] = [
    '#type'          => 'text_format',
    '#title'         => t('custom textarea'),
    '#format'        => 'full_html',
    '#default_value' => $custom_textarea['value'],
  ];

}

When I navigate to admin/config/regional/config-translation it shows the 'my theme settings' but when I click on Translate it navigates to admin/appearance/settings/translate and returns Access Denied.
I also tried updating the base_route_name in mytheme.config_translation.yml to system.theme_settings_theme but when I navigage to admin/appearance/settings/mytheme/translate it throws a fatal error.
Looking forward for any suggestions.
Comment: Do you use different domains per language? Are you being redirected to a different domain where you haven't logged in yet?
Comment: All the languages are in a single domain. It's not multi site or multi domain.
Answer: in schema change field type to text and add translatable: true
mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text
      label: 'Additional settings'
      translatable: true

You may also face this problem later https://www.drupal.org/project/drupal/issues/2719553 (my reply there is the last from current date)
Comment: Doesn't seem to work even after reinstalling the theme, are there any additional steps? Where should the translation interface appear?
Comment: Can't remember where it should appear, was too long ago. Take a look into link above, may be it brings you ideas. As I remember all was fine in the end of those my project

Enable translation for theme settings


How to keep a dict sorted as new items are pushed in?

Question: So I have a high score file like this:
Markus:5000
Mike:3000
John:2400

And I read it to an OrderdDict:
high_scores = OrderedDict()
with open('highscores.txt') as file:
    for line in file:
        name, score = line.strip().split(':')
        high_scores[name] = int(score)

Now as I add new scores to the dictionary, how can I keep it sorted? The only way I thought of is to recreate the dictionary every time with something like this:
high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)

But this seems rather awful behaviour, I would much prefer if the elements were put into the correct position as I add them to the dictionary, i.e. I'd like to keep the dictionary sorted at all times.
Comment: If you want to preserve sorted order, you might want to consider an alternative data structure like a priority queue.
Comment: @Chris_Rands or maybe make use of the `bisect` lib...
Comment: `sort`ing it each time probably isn't as bad as it sounds because of the way  the algorithm timsort works, also it's done in C, but `sort` a list like John suggests instead
Comment: @JonClements Yes, that's actually better I think
Answer: OrderedDict is not the best structure for a highscores list.  Try a regular list of 2-tuples, and simply sort() it every time you add an element.
If you really dislike the explicit sorting, you could use https://pypi.python.org/pypi/sortedcontainers to do it for you.


Exponential supremum proof

Question: Suppose $S\neq\emptyset$ is a bounded subset of $\mathbb{R}$. Define $T=\{e^x:x\in\ S\}$. Show that $sup(T)=e^{sup(S)}$.
To do this I said suppose $x=sup(S)$. Then for any $a\in S$ we have $x\ge a$. Hence $e^x\ge e^a$, so $e^x$ is an upper bound for $T$. Now we need to show it is the least upper bound. This part I struggled with - suppose there is some $y$ for which $e^y$ is an upper bound of $T$. Then we have $e^y\ge e^a$ for any $a\in S$ and so $y\ge a$ for any $a\in S$, proving that $y=x$. Is this an ok proof or have I made a mistake?
I think the first part I did correctly (proving $e^x$ is an upper bound for $T$ where $x=sup(S)$), but I worry I made a mistake for proving that it is the least upper bound.
Comment: How did you conclude that $y = x$?
Comment: Well since $x=sup(S), x\ge a$ for any a in S. Since $y$ has a similar inequality it must be the case that $y=x$(Since we could have a=x)
Comment: @Alidixon244 that's not true $8\ge 6$ and $7\ge 6$  but $8$ does not equal to $7$
Answer: Just because $y\ge a$ and $x\ge a$ does not mean $x=y$, $y$ could be for example $x+1$. To prove that $e^x$ is the least upper bound of $T$ you have to show that for any upper bound of $T$ , $M$, $M\ge e^x$, To prove this assume that there exists a $M$ such that $e^x>M$ then $e^x>e^k$ for some $k$ so $x>k$ but $x$ is the leats upper bound and $k$ is also an upper bound(since $e^k=M$ implies that $e^k > e^a$ for all $a$ in $S$) contradiction.

Exponential supremum proof


How to change "John Doe's Test Store" business name in the PayPal sandbox?

Question: I am integrating PayPal with my platform in sandbox mode.
I want to rename "John Doe's Test Store" (pictured below) with the name of my platform.
I would also like to rename "John Doe's Test Store" in the second image below, with the name of my platform.
How can this be done?
Answer: To change the account's business name, log into that receiving sandbox Business account via https://www.sandbox.paypal.com/businessmanage/account/aboutBusiness
(If you need to change the sandbox account's password, do so from PayPal Developer)

To change the displayed business name for a particular transaction, set the v2/orders REST API application_context object's brand_name parameter, or the old classic API's BRANDNAME parameter.  This is mainly useful if you have multiple websites/storefronts going to one PayPal account.
Comment: ,Can you please explain with easy word and every step how to do it, for people with not experience?
Answer: I found this, (but I am not able to edit more than two characters of the name, its asking me to upload proof. Please leave a comment, if you found a work around for this)

Login to sandbox business Account
Click username on top right and chose account settings
Open Business information(Screenshot below)

Here you can edit the details by clicking the update button
reference : https://github.com/paypal/PayPal-PHP-SDK/issues/1313


Weird definition for convergent sequences

Question: if exists $N\in\mathbb N$ that for all $\varepsilon>0$ so that for all $n>N \,\,$ $|a_n-L|<\varepsilon \Longrightarrow \underset{n\rightarrow\infty}{\lim}a_{n}=L$
Any ideas on how to prove this definition is equal to the conventional definition of a the limit of sequence?
Comment: The way you write down the above definition, it is certainly not equal to the conventional definition of a limit of a sequence, it is a lot stronger. It reads as "there is an $N\in \mathbb{N}$ such that the distance between any later element of the sequence and $L$ is smaller than any $\epsilon >0$". The only number smaller than every $\epsilon >0$ is $0$ itself.

Think about what that means heuristically, then it should dawn on you that this is indeed a much stronger condition than just convergence.
Comment: Why do you think its weird?
Answer: The implication is certainly true, but the given condition is not equivalent to the definition of limit. For that condition to hold, the terms of $a_n$ are all equal to $L$ from a certain order on.
Answer: Hint
Notice that $$\exists N\in\mathbb N: \forall \varepsilon >0, \forall n\in\mathbb N, n\geq N\implies |a_n-L|<\varepsilon $$
means that $a_n=L$ for all $n\geq N$.


Comparing linear mixed effects models using ANOVA - underlying assumptions

Question: I am trying to analyze some CPUE (Catch Per Unit Effort) data for a fisheries related analysis with lme models in R. So I have total of six models that are tested in groups of two to determine the effects of both fixed variables and their interaction separately. The models are:
M1 : CPUE = area + year + area*year + (1|location)
M2 : CPUE = area + year + (1|location)
M3 : CPUE = area + (1|location)
M4 : CPUE = ~1 +(1|location)
M5 : CPUE = year + (1|location)
M6 : CPUE = ~1 +(1|location)
The testing is done so that model 1 is tested against model 2 to test for interaction between the fixed variables, and models 3 vs 4 and models 5 vs 6 against each other for the effect of both fixed variables year and area.
The models are fitted with lme (from nlme -package) using 'ML' as method and the testing is done with anova.
So my questions are:
1) The CPUE data is not normally distributed. As I fit the models I see that the residuals also deviate from normal distribution, as do the plotted random effects. Do I need to transform my data to produce models with normally distributed residuals and random effects to use ANOVA for model comparison?
2) If I should transform my data can I be done simply by using for example log or sqrt if this seems to produce models with residuals and random effects that are approximately normally distributed? Does using a boxcox transformation fitted on a linear model without random effects produce erroneous results if used for lme models in this context? What I mean is using the estimate for lambda with the maximum log-likelihood obtained from the models without random effects to transform the data.
I am not the person who designed this analysis and have no resources or competence to change it. Therefore I am only interested in producing the results without making errors. Any help is appreciated!
Comment: Look into the literature. A quick look shows that GLMs with log-link and normal distribution have been used to model CPUE but I'm not sure if that is the best distribution since CPUE is an abundance measure, i.e., something similar to a count variable.
Comment: Thanks for the input. You have some literature recommendations on GLM for an ecologist with very basic understanding in statistics?
Answer:
The assumption is that the residuals, not the actual data, are normally distributed. If the departure from normality is severe then a transformation may indeed make sense.

You can use Box-Cox transformations - the main disadvantage is that the model is harder to interpret than if you use a "simple" transformation such as the positive square root or a logarithm.

Your model selection procedure is a kind of backwards stepwise procedure. this is not a good idea. For example see here, here and here.
You may also wish to investigate generalised linear mixed models, depending on the nature of the outcome variable.
Comment: @mihy You asked for a reference for ecologists above. Try [this](https://www.amazon.co.uk/Effects-Extensions-Ecology-Statistics-Biology/dp/0387874577) , [this](http://www.highstat.com/index.php/beginner-s-guide-to-regression-models-with-spatial-and-temporal-correlation) and [this](https://ms.mcmaster.ca/~bolker/emdbook/book.pdf)
Comment: Thank you for your response! Yes, the residuals being non-normally distributed led me to this question, not the actual data. The only thing this model testing is used for is to see if models with or without fit the data significantly better f.ex. does a model with area as fixed fit the data significantly better than a model without it and so on. I am sure to pass the critique to my superiors to hire an actual statistician for a new analysis design (:


GIT keep asking for merging even though it's nothing to merge

Question: I use git to store my wordpress
then I update something via "wordpress admin editor"
then update something in local and wants to push it
and I got this
I have stash and merge it and got this

why is it?
Comment: Please list your commands on doing this.
Answer: When you updated something in admin editor, you changed you local files (files in working directory). To push changes to server, you need to commit them to your local repo, then fetch changes from server, merge them, and push.
When you stashed your changes, you basically canceled them in your working directory. (to get them back, you can run git stash apply). This is why when you merge origin/master, there is nothing to merge.
So, you should:

change something in admin editor
git add -A

(adds changes to index)
git commit -m "Commit message"

(commit to local repo)
git fetch origin

(fetch changes from origin)
git merge origin/master

(merge)
git push origin master

(push)


create book navigation menu tree

Question: I have a book with few children article nodes. I would like to create a navigation block tree, that can be placed anywhere on page.
Problem: Normally if I place book navigation block using context (on book and article content type) - the menu shows all links with the link to main book.
However, if I try to print inside tpl.php like this
<code>$block = module_invoke('book', 'block_view', 'navigation');
print render($block['content']);
</code>
The menu shows only child items. How to show the parent book as well?
Answer: This code worked for me:
<code>$blockObject = block_load('book', 'navigation');
    $block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
    $output = drupal_render($block);
    print $output;
</code>

create book navigation menu tree


How to return a View's content in search results?

Question: We have a page display of a view that contains two or more nodes, but when searching for a keyword that would pertain to those nodes, only links to the individual nodes are returned.  What we really want is just the link to the page display of the view to be returned, but it doesn't show up in the results list.
I'm looking into caching the View and index the cached content through a custom module, but i was wondering if anyone has come across this situation and can share their solution?
edited: made some clarifications.
Answer: There is the Search by Page module that allows this (and much more). Some details from its project page:

This module is an enhancement to the core Drupal search module, which adds a new tab to the core Search page or can also be used in stand-alone mode. The differences between Search by Page and the existing tabs in the core Search module lie in what is indexed for searching and how it is indexed:

Search by Page indexes the content of your pages as rendered by your theme (Search indexes the default rendering you would have from an unmodified theme)
Search by Page allows you to omit content from indexing (such as "database table" node types that should never be viewed as stand-alone content)
Search by Page allows you to index non-Node pages, including user profiles, file attachments, and Views
Search by Page is language-aware, so it only shows you results in the current language.
Search by Page has multiple search "environments", so you can have different search pages/blocks to search different things.

Maybe you can use that or look how they index the views pages.
Answer: Search in drupal is entirely themeable - meaning you can alter the markup.
@see

http://api.drupal.org/api/drupal/modules--search--search-result.tpl.php/6
http://api.drupal.org/api/drupal/modules--search--search-results.tpl.php/6

You could invoke your view programmatically in search-result.tpl.php using an argument of nid
Comment: I might not have explained the situation properly, not sure if your answer applies.  The view containing the nodes is what i want to return when searching for a keyword that is part of its content, and not the nodes themselves.  I think your solution is for returning a view of results...unless i didn't understand your solution correctly.
Answer: From your question, it is very hard to determine if you are talking about an actual view, or search. But I'm going to assume you are talking about a view that has an exposed filter.
When you create a view with an exposed filter, the results upon submission usually stay formatted the same unless another display is involved. In the case that another display is taking care of results, then you would simply modify that display to format the results in the desired way, by either changing the style or the fields being displayed and their options.
It would help if you could explain your question a bit more, providing details on the actual view's setup/structure. This is actually the reason Earl first created the ability to 'export' a view. If you can provide an export of your view, it will be easier for others to help you.
Answer:
"The view containing the nodes is what i want to return when searching for a keyword that is part of its content, and not the nodes themselves"

You can either let views handle all your searching on your site, or embed the view into your search-results.tpl.php, but the latter is counter productive.
Answer: i have been struggling for customizing "D8 Search Index". Though there are many solutions and discussion, it's really not possibly to get it configured the way you want, unless you really get your hands dirty with twig templates.
i believe in less coding. This allows end-user to customize things without actually entering the code. So i was looking to avoid coding as much possible.
"search pages" in "search & meta" config gives you path of /search/node.
Create your own view and give it path "search/node"
Then add contextual filter "search keyword" and select "provide default value" as "query parameter"... there specify parameter as "keys" ..
customize other things like title, grouping as you may want. dont forget cache!
views gives you lot of power!
Check output by searching.
see my search page with grouping "https://shabdakosh.marathi.gov.in/search/node?keys=knowledge"


Interaction not significant, but one simple effect significant: linear mixed model with lmer() in R

Question: Currently cross-posted at https://stackoverflow.com/questions/63492814/interaction-not-significant-but-one-simple-effect-significant-linear-mixed-mod because I wasn't sure which site was more appropriate, but StackOverflow tends to get more traffic and responses. I will take suggestions on where to best post, with the hope of getting useful feedback.

Background: I have fit a linear mixed model using lmer() (lme4 package) in R with two binary categorical predictors as dummy variables. One (Intervention) is within-subjects, while the other (Sex) is between-. The model accounts for two levels of correlation with random effects (data structure and model code described below). The outcome is proportions, but they're very well-behaved - the mean is around 0.5, with a range of about 0.2 to 0.9, and they're very normally distributed. Subsequently, the residuals show assumptions (normality, equal variance) are met. Thus, I don't think what I'm observing is due to violating assumptions of a linear (mixed) model.
Issue: The following is true no matter what random effects structure I use (which I list below): In every case, the test statistic for the interaction term between the two binary categorical predictors is about 1.7 in magnitude, while that for one of the binary predictors is always about 2.8 (the test stat for the other is ~1.3). Although there is question about how to accurately calculate p-values for these types of models (and whether or not we even should - I'm aware of this discussion point), it is clear that no matter the degrees of freedom used, the interaction term would be not considered statistically significant (with, say, $\alpha$ = 0.05), while the one predictor would. Note here the estimate for the individual predictor is a simple effect, since it is binary and dummy-coded. I used emmeans() to look at all four possible simple effects, and there is only one that is statistically significant (that with the test statistic of about 2.8).
I cannot figure out how the interaction could lack significance, but one of four possible simple effects is significant. I could see if the test statistics/p-values were "borderline," making it a potential issue of power. However, here the ballpark p-value for the interaction term (test stat ~1.7) is about 0.09, while a rough p-value for the simple effect (test stat ~2.8) is about 0.007. It seems problematic to me that they could differ by a magnitude, and makes me concerned that I am inherently modeling the data incorrectly, although if so, I can't see where I am in error.
Data structure: Each subject has an observed proportion across six different images (out of 12 possible they could have been randomly assigned): Three images were viewed pre-intervention, and three were viewed post-intervention. Thus, there is potential correlation due to subject and image, so these are considered as random effects. Lastly, Intervention is within-subjects, while Sex is between-.
Here is a small dummy dataset (not actual data, where number of unique subjects is 59 (29 of one sex, 30 of the other)):
structure(list(Subject = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L), Image = c("B", "A",
"G", "E", "C", "I", "C", "G", "L", "A", "D", "F", "E", "A", "K",
"B", "C", "I", "D", "F", "H", "J", "L", "B", "D", "F", "A", "L",
"C", "E", "J", "K", "F", "B", "A", "D"), Intervention = c("Pre", "Pre", "Pre", "Post",
"Post", "Post", "Pre", "Pre", "Pre", "Post", "Post", "Post", "Pre",
"Pre", "Pre", "Post", "Post", "Post", "Pre", "Pre", "Pre",
"Post", "Post", "Post", "Pre", "Pre", "Pre", "Post", "Post", "Post",
"Pre", "Pre", "Pre", "Post", "Post", "Post"), Sex = c("Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male"), Prop = c(0.488277,
0.236734, 0.41036, 0.745403, 0.464705, 0.625076, 0.5602122, 0.590909, 0.333266, 0.365954, 0.374941, 0.662141, 0.64877, 0.434947, 0.721343, 0.5288113, 0.782714,
0.603777, 0.4480342, 0.629813, 0.347684, 0.41906, 0.553854, 0.639324, 0.389804, 0.49155, 0.355763, 0.695487, 0.537433, 0.650022, 0.54022, 0.58907, 0.666208,
0.713883, 0.625882, 0.434924)), class = "data.frame", row.names = c(NA, -36L))

Candidate models considered, each with varying random effects:
Model 1 (gave convergence warning): Note the output is that from my actual data (not the dummy dataset given above):
largest_lmer <- lmer(Prop ~ factor(Sex)*factor(Intervention) +
                            (1 | Image) +
                            (1 + Intervention | Subject),
                     data = data01)

coef(summary(largest_lmer))
#                                            Estimate Std. Error   t value
# (Intercept)                              0.51415277 0.03503742 14.674389
# factor(Sex)Male                          0.04019813 0.03006458  1.337059
# factor(Intervention)Pre                  0.05123982 0.01830275  2.799569
# factor(Sex)Male:factor(Intervention)Pre -0.04238911 0.02509809 -1.688938

install.packages("emmeans")
library(emmeans)

largest_lmer_emm_Int <- emmeans(largest_lmer, ~ factor(Sex) | factor(Intervention))
pairs(largest_lmer_emm_Int)
# Intervention = Post:
#  contrast      estimate     SE   df t.ratio p.value
#  Female - Male -0.04020 0.0301 57.3 -1.336  0.1867
#
# Intervention = Pre:
#  contrast      estimate     SE   df t.ratio p.value
#  Female - Male  0.00219 0.0307 57.2  0.071  0.9434
#
# Degrees-of-freedom method: kenward-roger

largest_lmer_emm_Sex <- emmeans(largest_lmer, ~ factor(Intervention) | factor(Sex))
pairs(largest_lmer_emm_Sex)
# Sex = Female:
#  contrast   estimate     SE   df t.ratio p.value
#  Post - Pre -0.05124 0.0184 56.5 -2.789  0.0072 **This is the significant simple effect**
#
# Sex = Male:
#  contrast   estimate     SE   df t.ratio p.value
#  Post - Pre -0.00885 0.0172 55.0 -0.515  0.6084
#
# Degrees-of-freedom method: kenward-roger

Model 2: All output similar to that from Model 1 (not repeated here):
medium_lmer <- lmer(Prop ~ factor(Sex)*factor(Intervention) +
                           (1 | Image) +
                           (1 | Subject) +
                           (1 | Intervention:Subject),
                    data = data01)

Model 3: All output similar to that from Model 1 (not repeated here):
smallest_lmer <- lmer(Prop ~ factor(Sex)*factor(Intervention) +
                             (1 | Image) +
                             (1 | Subject),
                      data = data01)

As I mentioned, all of these candidate models gave roughly the test statistics noted above - they did not vary depending on the random effects included. Assumptions of the model (normality, equal variance) were met. Is there something else I'm missing? Or is it mathematically possible to have an insignificant interaction, but a significant simple effect that differ as much as these two do with regard to their test statistic/p-value?
Comment: As for where to post... I would say it is like looking for lost keys: look near where they should be, not where there is more light or foot traffic. Here you have lots of statisticians albeit less traffic. I suspect statisticians will know better how to handle your question.
Comment: Thanks, @kurtosis. I see a lot of statisticians on StackOverflow too, as the intersection between stats and coding is very blurred.
Comment: "the intersection between stats and coding is very blurred" Will have to agree to disagree. Guess it depends on how we define "statistician." :-)
Comment: Since even theoretical statistical papers generally require a simulation and/or application to a dataset, they are indeed blurred in my eyes. And in my job, I do plenty of theory *and* application, each requiring the other, so I cannot separate the two.
Answer: I think there are a few potential issues here.
Your results tend to be the same using different random effects setups. That is not so surprising: Liang and Zeger talk about how approximate random effects models are often sufficient to get close to the truth and produce useful standard errors. The fixed effects should not change much if at all between the three models since they are the same in all three. This is the good part.
The troubling part is that you seem to insist that the interaction should be significant. Do you have some theoretical reason for that belief, or is it just a prior not based on theory? You don't want to be the analyst who tortures the data until it falsely confesses, so it really sounds like you need to be willing to accept that the interaction is insignificant. That should not be surprising: interactions are often less significant than the main effects.
Another possible issue is you may have a problem with heteroskedasticity. Proportions tend to be more variable when they are near 0.5 than when they are near 0 or 1. A typical correction for this is to transform the response to $\tilde{Y} = \sin^{-1}(\sqrt{Y})$ to stabilize the variance. That is a little bit of a pain because you need to transform back your predictions and the model coefficients are less intuitive, but the results will likely be cleaner. Weisberg's Applied Linear Regression, 2nd Ed. discusses this in Chapter 8.
Finally, you ask "is it mathematically possible to have an insignificant interaction, but a significant simple effect that differ as much as these two do with regard to their test statistic/$p$-value?" Absolutely. Suppose we gather school children from Smallville and Littletown, show some of them videos on word roots and guessing at spelling, and then give them all spelling tests. We might see that town is almost significant (say Smallville has better schools), the treatment is very significant, but that the interaction of town and treatment is not at all significant (i.e. both town's kids learn equally well from the video, so the interaction is immaterial). That would not even be unusual: I probably saw a hundred datasets like that in graduate school.
To summarize: I would be glad for your random effects modeling, transform your response, and be open to your interaction term not being significant. Don't torture the data; those confessions are rarely true. Good luck; hope it goes well!
Comment: Oh, yes, I know that not all simple effects will be *output*, but they can subsequently be *calculated* (with algebra using 0s and 1s, or using something like `emmeans`). *p*-values can be obtained by refitting the model with different baselines, or, again, using `emmeans`. I thought by aliasing you meant some things may *never* be estimable, but all simple effects in this 2x2 situation should be estimable, just by using algebra/changing baseline/using `emmeans`. It is unclear to me if/how this is related to the lack of a significant interaction despite a significant simple effect.
Comment: Ah, no. Everything you have is identifiable. It's just what gets reported. That is how the significance gets affected: how something is coded often implies a basis for comparison. So coding as $\pm$1 would be comparing to 0 while the usual treatment contract compares to the baseline. I suspect your significant simple effect is (most of but not all of) what is driving the significant InterventionPre effect.
Comment: 1/4 Thanks, @kurtosis. Although *in theory* the random effects hopefully don't change our results much, this is not always true. In a logistic mixed model of these data, the results are sensitive to which random effects are/are not included. There could be other issues with the model leading to this, but one cannot assume that any old random effects will do. As a matter of fact, there are many conflicting opinions in the literature on how to best choose random effects so as to balance the type I error rate and power.
Comment: 2/4 I am not insisting the interaction be significant. I originally stumbled upon the significant simple effect in light of the insignificant interaction because I have also considered a similar logistic model (using 0/1 data instead of the proportions), and wanted estimates of the odds ratios between all groups as measures of effect size to report anyway, *despite lack of statistical significance*. That is, until I saw one of the simple effects *was* significant. That's what led to me questioning if/how/when this could happen.
Comment: 3/4 As I mentioned in my post, I had no evidence of heteroskedasticity in the residuals after I fit the model. For completeness, however, I had already also tried an empirical logit transformation on the proportions, and the results are equivalent. But, as I said, I don't think a transformation is necessary here because the proportions are already so well-behaved (as in my post).
Comment: 4/4 I also think you're misunderstanding *main* vs. *simple* effects. I understand that you can readily have a significant *main* effect without a significant interaction (and, indeed, the *Sex* *main* effect *is* significant here). What I'm asking about are the *simple* effects: All four *combinations* of *Sex* and *Intervention* (change from male to female when holding intervention at "pre," e.g.). It makes less (no?) sense to me how one of these *simple* effects can be significant if the interaction is not.
Comment: Good to hear that a logit transform performed similarly; and, yes, the random effects sometimes make a difference. One of your simple effects can be significant if the others are incredibly noisy. Also, presumably one of those simple effects is aliased with your baseline, so that is likely an issue with looking at the simple effects.
Comment: Would I expect aliasing in a 2x2 ANOVA (fit as a linear mixed model, so random effects could be incorporated)?
Comment: * Typo two comments above: "and, indeed, the *Sex* *main* effect *is* significant here" should be, "and, indeed, the **Intervention** *main* effect *is* significant here".
Comment: Aliasing is a direct result of identifiability. It happens but how it happens depends on how your factors are coded, not on the size of groups and treatments. So yes, you should expect this in a 2x2 setup. Most discussions of contrasts in $R$ discuss how this happens.
Comment: My data are coded as dummy variables (0/1), which is the natural way to then estimate simple effects, and I have not seen an example where aliasing has caused an issue with doing so. Indeed, I have seen the 2x2 ANOVA case as a straightforward example for the sake of illustrating simple effects, so it's unclear why it would be an issue here. (Note I have only seen aliasing discussed with effects coding (say, -1/1).) I have spent some time now searching various terms, and have not found an indication that aliasing would be at play here. Do you have a source for the 2x2, dummy-coded case?
Comment: See here: https://bbolker.github.io/stat4c03/notes/contrasts.pdf Note that aliasing happens in your case; that is why you do not see an effect estimated for each of the simple effects. So Sex0:Intervention0, Sex1:Intervention0, and Sex0:Intervention1 would all not be reported and the model summary would instead report the intercept, Sex effect, and Intervention effect. Only Sex1:Intervention1 would *not* be aliased and reported as Sex1:Intervention1.
Comment: Thanks for clarifying everything is identifiable. And yes, I want to compare back to baseline so I can get simple effects here. And I agree - the one significant simple effect is probably driving the significant *Intervention* main effect. What I can't get over is this: *I would have missed this simple effect altogether had I never "stumbled upon" it* (again, when estimating ORs when treating the outcome as binary), because an *insignificant* interaction should generally indicate *no need* to go on to look for significant simple effects. So this goes back to my question: How is this happening?
Comment: I'm not sure why you think an insignificant interaction means no significant simple effects. It just means one of your simple effects (Sex1:Intervention1) is insignificant. Does that help?
Comment: 1/2 In theory, no significant interaction tells you that there is no need to differentiate between the four groupings - the main effect for *Sex* and/or *Intervention* (here, just *Intervention*) is "enough." So, now you collapse (get rid of the interaction), and conclude that pre- and post-interventions differ, but not that – *specifically* - *females post-intervention* differ from *females pre-intervention*.
Comment: 2/2 You've lost this level of detail (i.e., the simple effect). The only way to get this detail is with the interaction in the model. However, when an interaction is not significant, it is generally argued there is no need to leave it in the model, and now your chance to capture that simple effect is gone. Is there something I'm missing?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112039/discussion-between-kurtosis-and-meg).
Answer: My sense is that you are putting too much importance on the binary significant/not-significant distinction. As this answer from Jeromy Anglim put it:

This binary thinking is generally not what we are most interested in. Once you think about your research question, you will almost always find that you are actually interested in estimating parameters. You are interested in the actual difference between group means, or the size of the correlation, or the size of the regression coefficient, or the amount of variance explained.

What you are seeing is what you would expect if there is a true interaction but your data set is simply too small to document it at the standard p < 0.05 level. Your test statistic for a coefficient is the ratio of its point estimate to the standard error of its estimate. The standard error of its estimate will go approximately with the square root of the number of cases. With about 50% more cases the point estimate you found for the interaction coefficient, -0.04239, might well have been deemed "significant" by that standard.
You can't really read much into p-values that "differ by a magnitude." A significance test is based on a null hypothesis; if that holds the p-values among multiple experiments are uniformly distributed and p < 0.05 is taken to be "significant." The distance of the p-value below 0.05 is hard to interpret further; you need to know the true alternate hypothesis for which you just provided evidence. See this page and play with the Pvalue.norm.sim or Pvalue.binom.sim functions in the TeachingDemos package for R to see how variable p-values can be among experiments under alternate hypotheses.
Comment: @Meg the "simple effect" of Post-Pre for women is still reliable even if the interaction term isn't significant, as that "simple effect" properly takes into account the covariances among the coefficient estimates. I'd say to focus on that. (The fixed-effect coefficient covariance matrix might be informative in this context.) Someone who just throws away a p = 0.09 isn't thinking; that might be something worthy of further study even if you can't publish it as "significant." Inform your data analysis with your knowledge of the subject matter and an open mind.
Comment: 1/5 Thanks, @EdM. I agree *p*-values shouldn't be the be-all and end-all, but we're still a ways from convincing the scientific community. Also, note I stumbled upon this finding when estimating ORs (treating the outcome as binary instead of as proportions) as measures of *effect size* to report *despite a lack of significance* (this same "phenomenon" occurred in logistic models). I would have not *found* this simple effect had I not gone on to estimate ORs (I got the *p*-values for the four comparisons while estimating the ORs), and it remains that I want to know when/why this happens.
Comment: 2/5 As your quote says: I *am* interested in estimating parameters – the ORs (logistic regression), the estimated probabilities of the four groupings here. I *am* also interested in the magnitude of the OR and the difference in these probabilities. It's actually *all* of this (i.e., looking at my results to see if they made sense, the direction and magnitudes of the differences, etc.) that *led* me to this – what I would consider – anomaly. But the reality is the journal also wants *p*-values, not just estimates, etc.
Comment: 3/5 I was wondering if power was the issue, but *n* = 354 isn't "that" small (although there is correlation (each subject contributes six probabilities, one for each image)). I appreciate your comment about the magnitudes of the *p*-values not necessarily being comparable: Maybe there is a *general* lack of power, and *p* for the simple effect *and* interaction would *both* be smaller with more data?
Comment: 4/5 What I can't understand is how a simple effect with *p* = 0.007 wouldn't "drive down" the *p*-value for the interaction to a "similar" level. It seems they should be more well-aligned. But maybe this is a logical fallacy, or my definition of what might be considered "well-aligned" is inappropriate/unreasonable.
Comment: 5/5 Also, humor me: From a practical standpoint (since this is the world in which we still live): How do you reconcile that most would see *p* = 0.09 for the interaction, deem it unimportant, remove it, and never see a potentially significant simple effect (which existed here)? Is the argument to always look at the simple effects if they're of interest (which they are here), *despite* the *p*-value for the interaction? Should we not still be able to explain *why* this happens "sometimes"? Is "lack of power" enough of an explanation? I just can't shake that something isn't right.
Comment: @Meg the way you have this coded with Female as the reference category, the significant "simple effect" is identical (except for change of sign) to the fixed-effect coefficient for "Pre". What you have is a significant "main effect" with a near-significant interaction. That's a tough but frequent situation. There was a [very similar question yesterday](https://stats.stackexchange.com/q/483669/28500): the "best" model by AIC included an interaction that didn't pass the "significance" threshold. Which result was correct? Both were, by their respective criteria.
Comment: In my current model with female as baseline, the *simple* effect for female/pre is only equivalent to the "main" effect when the interaction is in the model. In this way, it's not really a "main" effect (which I would define as being the effect of *Intervention* *overall*, not parsed out by males or females). If the interaction were *removed*, *then* you have a true *main effect* for *Intervention* (and another for *Sex*). Right now, with two binary predictors and an interaction, all "main effects" are actually simple effects.
Comment: I think I can make a case for looking at the simple effects given the journal to which we plan to submit, as I think it will be open to the "borderline" significance of the interaction term, but time will tell. I think this discipline/journal is probably more open to this than some. I know in some fields in which I help colleagues analyze their data, this wouldn't fly. I think this disconnect between *p*-values and the "bigger picture" is something we will probably continue to fight, maybe indefinitely (at least in some disciplines). Thanks.