"Famous" set of correlation plots used for teaching

Question: I am familiar with Anscombe's quartet
I am now looking for a different set of plots. From what I remember, these all had correlations of zero, and there was a question here on CV, and I think it was about dependence in the absence of correlation and it was used as part of an answer.
I have tried a few searches such as this one but so far I've not found it.
Comment: Was it [this](https://cran.r-project.org/web/packages/datasauRus/vignettes/Datasaurus.html), maybe?
Comment: https://stats.stackexchange.com/questions/633316/how-to-check-linearity-of-a-variable-without-plots-graphs-in-r/633437#633437
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Correlation) has one nice plot that I am sure is copied somewhere on this site!
Comment: @COOLSerdash  It isn't that one, though that one may be sufficient for my needs. Thank you !
Answer: Answering my own question after waiting to see if @kjetil b halvorsen convert's their comment. If they subsequently do then I will delete mine.
This is the one I was looking for:

Several sets of (x, y) points, with the Pearson correlation coefficient of x and y for each set. The correlation reflects the noisiness and direction of a linear relationship (top row), but not the slope of that relationship (middle), nor many aspects of nonlinear relationships (bottom). N.B.: the figure in the center has a slope of 0 but in that case, the correlation coefficient is undefined because the variance of Y is zero.

For completeness I will also include some others which also demonstrate the same ideas. First, the "Datasaurus" that @COOLSerdash suggested:

This package wraps the awesome Datasaurus Dozen dataset, which contains 13 sets of x-y data. Each sub-dataset has five statistics that are (almost) the same in each case. (These are the mean of x, mean of y, standard deviation of x, standard deviation of y, and Pearson correlation between x and y). However, scatter plots reveal that each sub-dataset looks very different. The dataset is intended to be used to teach students that it is important to plot their own datasets, rather than relying only on statistics.

The Datasaurus was created by Alberto Cairo. Datasaurus shows us why visualisation is important, not just summary statistics.

And finally, Anscombe's quartet:

All four sets are identical when examined using simple summary statistics, but vary considerably when graphed
Comment: The `R` code I posted at https://stats.stackexchange.com/a/152034/919 will create any of these examples as well as any other example you care to conceive of.
Comment: @whuber that is awesome !


Problema ao adicionar uma data em um índice de array

Question: Estou passando uma data para dentro de um índice de um Array. Conforme vai sendo executado o looping, este Array vai sendo alimentado. O índice também é gerado através deste looping.
Porém, ao printar o índice, exibe apenas 1 caracter (como se estivesse "fragmentado" dentro do Array). Creio que é um erro simples, porém, estou me batendo por não ter passado por isto ainda.
$pcb_data = array();
while($r = $DB->fetchArray($result)){
    $pcb_cmb_id = $r['pcb_cmb_id'];

    $pcb_data[$pcb_cmb_id] = date("d/m/Y",  strtotime($r['pcb_data']));
}

Se eu imprimir $pcb_data[4], por exemplo, ele exibirá "2", ao invés de uma data (ex: 12/12/1988).
Obs: Cortei o código do while pq o restante das informações não possuem relevância, neste caso.
Alguém pode me ajudar, por favor?
Comment: Foi constatado que a variável do array estava sendo sobrescrita por outra informação, provavelmente criada para testes anteriores...foi removida esta informação e funcionou corretamente...Obrigado pelo auxílio.
Comment: De um `print_($pcb_data)`; depois do while, coloca nos comentários depois
Answer: Tentei replicar o mesmo erro mas sem sucesso, veja :
<?php
$pcb_data = array();
$i = 0;

while($i < 2){
  $pcb_data[$i] = date("d/m/Y",  strtotime('2000-10-10'));
  $i++;
}

Saída
Array
(
  [0] => 10/10/2000
  [1] => 10/10/2000
)

obs: Tentei emular em diferentes versões do PHP aqui
Os dados que estão vindo do banco estão corretos ?
Esse índice que você acessou realmente possui essa regra ?
Tem algum log ou algum erro sendo exibido ?
Comment: Foi constatado que a variável do array estava sendo sobrescrita por outra informação, provavelmente criada para testes anteriores...foi removida esta informação e funcionou corretamente...Obrigado pelo auxílio.
Answer: Tente isso, acho que vai descobrir onde está ocorrendo o problema:
function formatDate($data) {
   return implode('-',array_reverse(explode("-", $data)));
}

$pcb_data = array();

while($r = $DB->fetchArray($result)){
    $pcb_cmb_id = $r['pcb_cmb_id'];
    $pcb_data[] = array(
            'id'  => $r['pcb_cmb_id'],
            'data'=>  formatDate($r['pcb_data'])
           );
}

echo '
';
print_r($pcb_data);

Comment: Foi constatado que a variável do array estava sendo sobrescrita por outra informação, provavelmente criada para testes anteriores...foi removida esta informação e funcionou corretamente...Obrigado pelo auxílio.
Answer: $pcb_data = array();
while($r = $DB->fetchArray($result)){
    $pcb_data[$r['pcb_cmb_id']] = date("d/m/Y",  strtotime($r['pcb_data']));
}

echo '
';
print_r($pcb_data);
echo '
';

Não há necessidade de criar variáveis para tudo. Já coloca direto dentro da chave do array e seu valor.


Show that if the gcd of a set of non-negative integers $n_1,n_2,...,n_k$ is 1, then there exists $c_1,...,c_k\in\Bbb Z$ st. $\sum_{i=1}^k c_in_i=1$

Question: Show that if the gcd of a set of non-negative integers $n_1,n_2,...,n_k$ is 1, then there exists $c_1,c_2,...,c_k\in\Bbb Z$ st. $c_1n_1+c_2n_2+...+c_kn_k=1$. Anyone can help give a understandable proof without those advanced number theory stuff? Thank you!
Comment: @DavidKleiman Great! Thank you!
Answer: Let $S$ be the set of integers that can bet written in that form:
$$S=\{c_1n_1+c_2n_2+\cdots+c_kn_k\mid c_1,\dots,c_k\in\mathbb Z\}$$
Then $S$ is non-empty and has a positive integer in it (why?) Let $d$ be the least positive integer in $S$.
Then assume $d$ does not divide $n_i$ for some $i$. Write $n_i=dq+r$ with $0\leq r< d$, by the division algorithm.
Now show that $r=n_i-dq\in S$.  So $0\leq r<d$. Since $d$ does not divide $n_i$, we have $r>0$. So $r$ is a smaller positive integer in $S$, reaching a contradiction.
Therefore, $d\mid n_i$ for all $i$. Since they have no common factor, you are done - $d=1\in S$.
Comment: Thank you for your solution. I have a question. It seems $q>0$, but why? Thank you!
Comment: Ugh, there was a big error in my proof - I had written $d=n_iq+r$ and meant $n_i=dq+r$ with $0\leq r<d$. There is no particular reson to expect $q$ to be positive.


How to find the reason of "Cannot find module" for nrwl modules?

Question: I use nrwl.io in my project.
I created several libs:
ng g lib rest //ok
ng g lib services //ok
ng g lib models //created ok, but "Cannot find module " later on!

All of these libs were successfully created, but when I try to import my models lib I see error "Cannot find module":
import { ModelA, ModelB } from '@myproj/models'; //Cannot find module '@myproj/models'

The question is: How and where I can check if my '@myproj/models' was properly registered?
P.S. I can see "models" module in nx.json, angular.json and tsconfig.json. And I can see no difference with other modules.
P.P.S. I use "@nrwl/nx": "6.1.0" and  "@nrwl/schematics": "6.1.0"
Comment: @SCRATK I don't really remember now, but I guess no. I just re-built project from scratch and it works
Comment: You can try the `--traceResolution` option to `tsc`, though this won't tell you about Angular-specific module resolution behavior if there is any (which I'm not familiar with).
Comment: Have you found any fix to this?
Answer: In my case it was because I was dumb and didn't restart my TypeScript server in VS Code:
CMD / CTRL + SHIFT + P
>TypeScript: Restart TS Server

Comment: Who knows that this also requires lol. Thank you for your answer.
Comment: I think this answer should be the accepted one, this one helped me solve the problem.
Comment: Thanks, got the same issue...
Comment: I had to kill the app and reopen (macOs)
Answer: I also had the same issue. Created a library and tried to use it in multiple projects.
First make sure your library is added in main tsconfig.json -> paths property.
"paths": {
  "@projectName/LibraryName1": ["libs/LibraryName1/src/index.ts"],
  "@projectName/LibraryName2": ["libs/LibraryName2/src/index.ts"],
  ....
}

Then you must have your project added in your main angular.json file.
"projects": {
   "LibraryName1": {
   "root": "libs/LibraryName1",
   "sourceRoot": "libs/LibraryName1/src",
   "projectType": "library",
   "prefix": "projectName",
   "projectType": "library"
   ...
  }
}

Then obviously check tsconfig.json file for that app in which you are going to use lib. The key is to remove paths property. Because you already added in main tsconfig.json (in my case I used nrwl (a technique for managing multiple apps)).
Now you should be able to reference any of your lib projects like so :
import { class1,class2 } from '@projectName/libraryName1';

Don't forget to export your classes (assuming you have models library ) using index.ts like so :
export * from './lib/class1';
export * from './lib/class2';

Or
If you have any UI library that have components. You should create a module add those components in it and then export it using index.ts
The module file should be in lib folder. e.g
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NumberOnlyDirective } from './directives/number-only.directive';

@NgModule({
imports: [CommonModule],
declarations: [NumberOnlyDirective],
exports: [NumberOnlyDirective]
})
export class UiModule {}

index.ts file for UI library
export * from './lib/ui.module';

Add UI module's reference in your project app.module.ts
import { UiModule } from '@projectName/LibraryName1';

in imports also
 imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
NgxPaginationModule,
Ng2OrderModule,
Ng2SearchPipeModule,
AngularEditorModule,
RichTextEditorAllModule,
NgxPrintModule,
DevExpressModule,
UiModule
...
],

Comment: To save anyone the pain I just went through: if everything looks correct, just try restarting VS Code. In my case, that was all that was needed.
Comment: @PatrickMichaelsen after checking all my settings several times and tweaking everything, thanks to your comment I didn't waste anymore time.
Answer: I also encountered this issue.
Assume the project is named "project1" and the library is named "libray1" (so we're trying to reference the module "@project1/library1"). Referencing the NRWL NX generated library modules works fine from non-Angular (in my particular case Ionic/Angular) contexts, but caused the "Cannot find module" error from Angular apps within the monorepo.
The problem occurred because the Angular application was looking for the barrel file (index.ts) in the location "project1/libs/library1", whereas NX puts the barrel one level down in "project1/libs/library1/src".
The (slightly annoying) solution is to create an additional index.ts file at the "project1/libs/library1" location with the following content:
export * from './src';

This ensures that the code works from all contexts, and is a fix-once solution (for each new library you generate) as opposed to having to add an explcit reference to the package.json file of each Angular app in the repo.
Comment: You are an Enlighten Being descended from Mount Olympus.  Thank you!
Answer: In case anyone is experiencing this and mentioned solutions didn't help, here's how I fixed it.

After a while I realized that I could import fine in other places, only the app I was trying had the issue
This lead me to check tsconfig of the app
I found that I had set baseUrl: true in tsconfig, which was the reason why the import couldn't be resolved.

TLDR: Remove baseUrl setting from tsconfig.
Answer: I had the same issue when I was trying to create new lib. I removed the node_modules and reinstall it back. It fixed the issue
Answer: This is the answer for anyone who integrated nx to an existing monorepo and got this error.
You need to add root tsconfig.base.json to your application tsconfig.json using something like
{
...

 "extends": "../../tsconfig.base.json",

....
}

Answer: While you import something using @model/something, editor will automatically add a full path to the module (in my case). so this is what I had to do to get the import '@' working.

delete the editor added full path import. keep only the one you are typing- ie; with @project/models.
turn the server off and ng serve again.
Answer: This is where using --parent-module=apps/myapp/src/app/app.module.ts comes in when creating a lib.
One of the things that flag does is modify the tsconfig.app.json and adds "../../libs/mylib/src/index.ts to the includes which tells TS to use the module.


The $\omega$ function that proves that a function is differentiable at a point $a$

Question: I'll start by listing a definition:
"The function $f$ is differentiable in a $\in$ $D^0$ if there is a number $A_a \in R$ and a function $\omega_a$ continuous and null in $a$ so that, for any $x \in D$ we have:
$$f(x)-f(a)=A_a(x-a)+\omega_a(x)(x-a)$$
where $\lim_{a\to\infty}\omega_a(x)=\omega_a(a)=0$ Immediately we see that $A_a=f'(a)$"
Now, I've found an example but I don't see very well how it's related to the formula above. The problem asks to prove that for a=1 $f$ is not differentiable in $(0,0)$ and for $a>1 \ f$ is differentiable in the origin.
$$f(x,y)=\frac{x^2y}{\sqrt{x^2+y^2}}, \ x^2+y^2\not=0$$
$$f(x,y)=0, \ x^2+y^2=0$$
$$f(x,y)=\frac{\partial f}{\partial x}(0,0)(x-0)+\frac{\partial f}{\partial y}(0,0)(y-0)+\omega(x,y)\sqrt{x^2+y^2}$$
I guess the last row applies the formula listed in the definition (right?). But in the last part in the definition formula says $\omega_a(x)(x-a)$, shouldn't then be?
$$f(x,y)=\frac{\partial f}{\partial x}(0,0)(x-0)+\frac{\partial f}{\partial y}(0,0)(y-0)+\omega(x,y)(x-0)$$
Answer: Exactly what the equations involved look like depends on what dimension the domain and range of $f$ are, but you seem to have picked up on that.
The idea behind the definition is that, if the function $\omega_a$ exists and satisfies the conditions, then we can divide by $(x-a)$ to get that
$$\frac{f(x)-f(a)}{x-a} = A_a + \omega_a(x)$$
When we take the limit as $x \to a$, the left side is the quotient definition of the derivative and the right side approaches $A_a$, since $\lim_{x\to a} \omega_a(x) = 0$.
If we can write $f$ in that form, then $f$ is locally linear (which is the same thing as differentiability), since we can write the difference between $f(x)$ and $f(a)$ as the sum of a linear term (the $A_a(x-a)$) and a term that tends to zero even when you divide it by $(x-a)$ (also referred to as tending to zero faster than $(x-a)$), namely $\omega_a(x)(x-a)$.
In the second problem, things are slightly different in that you have a function $f: \mathbb{R}^2 \to \mathbb{R} $, whereas the first function was just defined on $\mathbb{R}$.  This makes the relevant equation slightly more complicated, but not really that much different.  The analogous equation is that $f$ is differentiable at $(a,b) \in D^0$ if
$$ f(x,y)-f(a,b) = A_{(a,b)}(x-a) + B_{(a,b)}(y-b) + \omega_{(a,b)}(x,y)\|(x-a,y-b)\|$$
for some constants $A_{(a,b)}, B_{(a,b)} \in \mathbb{R}$ and a continuous function $\omega_{(a,b)}(x,y)$ that is zero at $(a,b)$. Since we are working in two dimensions, not just one, the linear part now has one term for $x$ and one for $y$, and $\omega_{(a,b)}$ is a function of two variables, not just one.  You wrote down the correct formula for the case $(a,b) = (0,0)$ as
$$f(x,y) = \frac{\partial f}{\partial x}(0,0)(x-0) + \frac{\partial f}{\partial y}(0,0)(y-0) + \omega(x,y)\sqrt{x^2 + y^2}$$
since the constants $A$ and $B$ have to be equal to the respective partial derivatives, if they exist near $(0,0)$, which they do.  Showing that $f$ is or isn't differentiable at the origin reduces to showing that a continuous $\omega$ that vanishes at $(0,0)$ and satisfies the equation either exists or doesn't exist.  The reason that the equation doesn't look exactly like it does in the definition is that you're working in more dimensions.
I'm not quite sure what you're saying about showing that $f$ is differentiable at the origin for $a>1$, since keeping the notation before would suggest that $a$ is the point $(0,0)$ itself.


Como remover o margin top do ImageView

Question: Olá, estou a criar um app, e tenho uma ImageView com o id ivthumb que fica no topo mas por algum motivo ela não cola no topo e fica um espacinho. Alguém me pode ajudar a resolver este problema? PS: Eu removo a Action Bar com getSupportActionBar().hide(); caso tenha alguma coisa a ver com isso.
Imagem:
https://ibb.co/QJLFFsD
XML:
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#15202b"
        android:padding="0dip"
        tools:context=".ViewMateria">

        <ImageView
            android:id="@+id/ivthumb"
            android:layout_width="match_parent"
            android:layout_height="232dp"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="237dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/back"
                android:layout_width="37dp"
                android:layout_height="44dp"
                android:layout_marginTop="9sp"
                android:onClick="voltar"
                app:srcCompat="@drawable/ic_back" />

        </LinearLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="501dp"
                    android:layout_marginTop="230sp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tvvtitle"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5sp"
                        android:text=""
                        android:textAlignment="center"
                        android:textColor="#fff"
                        android:textSize="23sp" />

                    <TextView
                        android:id="@+id/tvdesc"
                        android:layout_width="399dp"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="5sp"
                        android:layout_marginTop="5sp"
                        android:text=""
                        android:textSize="15sp"
                        android:textColor="#fff" />
                </LinearLayout>
            </LinearLayout>
        </ScrollView>

    </RelativeLayout>

Answer: Verifique alinhamento da sua ImageView. Utilizando a propriedade layout_alignParentTop= true você vai garantir que o topo do componente ficará ligado ao topo do seu layout pai. Caso a margem continue a aparecer, altere o scaleType para centerCrop, de modo a preencher toda a superfície da ImageView com o conteúdo da imagem, mantendo a proporção.
Se isso ainda não resolver, use o LayoutInspector para investigar as propriedades de tamanho e posicionamento da sua ImageView em runtime.
Ao desenvolver interfaces, tome cuidado ao definir tamanhos fixos para componentes, pois isso pode dificultar a composição da tela, especialmente quando há uma variação muito grande no tamanho dos dispositivos que executarão o aplicativo. Dê preferência à utilização do match_parent e wrap_content, ou ainda, use o ConstraintLayout para definir tamanhos e proporções mais dinâmicas.

Como remover o margin top do ImageView


How to update migration field mapping using custom module/form?

Question: I was learning about Drupal migration recently and found out that we can use Migrate Plus module to import migrations as configurations. Hence I started wondering if a migration is imported as a configuration, is it possible to override/update the migration's process plugin field mapping through a custom form using the "config.factory" service.
I tried implementing this and found out that the configuration update through the custom form is not taking effect in the migration end, until and unless I flush the cache in the custom form's submit handler. I feel like this is not the right way.
Is there any other way to implement this without clearing the cache every time the form submits?
The submit handler for my config form looks like this ->
I am trying to change the mapping of the entity:node:body field with a different source plugin field whose id is stored in the selectfield field in the form.
public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $config_factory = \Drupal::configFactory();
    $config = $config_factory->getEditable('migrate_plus.migration.data');
    $process = $config->get('process');
    $process['body'] = $form_state->getValue("selectfield");
    $config->set('process', $process);
    $config->save();
    $this->config("config.migrateform")->set("selectfield", $form_state->getValue("selectfield"))->save();
    drupal_flush_all_caches();
  }

Answer: Your solution changes the migration configuration via form which would then require config export if you have staging, prod etc. environments to import the new config.
Which in the end makes you think what is the point of having a form in the first place when you can edit migration yaml file directly to achieve the same result.
However to answer the question two solutions come to mind:
Both solutions should have the form submit save only the value of the field.
public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->config('config.migrateform')
    ->set('selectfield', $form_state->getValue('selectfield'))
    ->save();
}

1. Using an event subscriber to the migrate.pre_import event
Migration import fires the event at the start of the migration.
$this->getEventDispatcher()->dispatch(new MigrateImportEvent($this->migration, $this->message), MigrateEvents::PRE_IMPORT);

You can subscribe to this event and get the migration object from the event.
Migration object allows you to get and/or set the process plugin definitions.
/**
 * Gets the normalized process plugin configuration.
 *
 * The process configuration is always normalized. All shorthand processing
 * will be expanded into their full representations.
 *
 * @see https://www.drupal.org/node/2129651#get-shorthand
 *
 * @return array
 *   The normalized configuration describing the process plugins.
 */
public function getProcess();

/**
 * Allows you to override the entire process configuration.
 *
 * @param array $process
 *   The entire process pipeline configuration describing the process plugins.
 *
 * @return $this
 */
public function setProcess(array $process);

So in the event subscriber you can load the config.migrateform and the value selectfield then replace the process configuration.
public function onPreImport(MigrateImportEvent $event): void {
  $migration = $event->getMigration();
  // Don't do anything if migration is not the one you want to alter
  if ($migration->getPluginId() !== 'my_migration_id') {
    return;
  }

  $fieldProcess = \Drupal::configFactory()->get('config.migrateform')->get('selectfield');
  $process = $migration->getProcess();
  $process['body'] = $fieldProcess;
  $migration->setProcess($process);
}

This is just a subscriber method snippet, complete solution should use dependency injection.
This will alter the migration on the fly but will not update the yaml configuration which might confuse other developers looking at the migration yaml file but the migration would act differently, so it might be a good idea to add a comment to the yaml file that the event subscriber alters the behaviour. To avoid this confusion the second solution can be used.
Another issue here is that the subscriber applies to the migration id(s) you specify in the if block which would need updating if you want to use it in multiple migrations.
2. Creating a custom plugin
This solution requires creating a custom process plugin that can dynamically load another process plugin from form configuration and delegate the processing to the loaded plugin.
Create a custom process plugin:
/**
 * @MigrateProcessPlugin(
 *   id = "dynamic_process_plugin"
 * )
 */
class DynamicProcessPlugin extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  protected $configFactory;

  protected $pluginManager;

  public function __construct(array $configuration, $plugin_id, array $plugin_definition, ConfigFactoryInterface $factory, MigratePluginManagerInterface $pluginManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->configFactory = $factory;
    $this->pluginManager = $pluginManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('config.factory'),
      $container->get('plugin.manager.migrate.process')
    );
  }

  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $fieldProcess = $this->configFactory->get('config.migrateform')->get('selectfield');
    $processPlugin = $this->pluginManager->getInstance($fieldProcess);

    return $processPlugin->transform($value, $migrate_executable, $row, $destination_property);
  }

}

And use this custom plugin in the migration yaml for whatever field you want - in your case for body:
process:
  body:
    plugin: dynamic_process_plugin
    source: body

This solution is more flexible as you can add use the plugin in any migration on any field you want and there is no confusion for other developers.
Note that I have not tested this code and it is not complete - missing namespaces, incomplete coding standards etc.


Website Conversion: how to calculate confidence interval for tomorrow's conversion rate

Question: Let's say I have a website with certain number of visits per day and conversion events:
<code>Date    Visits   Conversion_Events  Conversion_%
12/1/14  3,369   179                 5.3%
12/2/14  3,297   199                 6.0%
12/3/14  3,355   405                 12.1%
12/4/14  2,035   220                 10.8%
12/5/14  4,834   207                 4.3%

Total    16,890  1,210               7.2%
</code>
These numbers fluctuate for multitude of reasons that are unknown to us (we can't control for geo location, demographics, etc., and assuming day-of-week, day-of-month, etc. don't make sense to control for). But we do know day-by-day data fluctuates around some mean. I'm interested in coming up with a plausible 95% confidence interval for tomorrow's (or any other day's) conversion based on historical data.
I can think of a few ways to achieve this:
(1) Look at totals only and use "standard error of proportion" formula: Sp = sqrt(p*(1-p)/n) = sqrt(7.2%*(1-7.2%)/16890). This means in this example 6.8%-7.6%. Intuitively, this seems to me to hide the fact that the day-by-day conversions fluctuate, so I'm concerned this loses some valuable information.
(2) Look at every date as a sample of the population, and calculate mean and stdev across samples. I.e. average() and stdev() on the array [5.3%,6.0%,12.1%,10.8%,4.3%]. Now, I get it that mathematically averaging proportions with varying sample sizes is not great, but intuitively assuming that sample sizes are very large it seems to me that this effect should be mitigated by the fact we are looking at the proportion summary statistic. Note that I gave an example of 5 days, but in reality, I can get a high number of "samples", so I can have a pretty good understanding of the distribution function of day-by-day proportions. This means the 95% confidence interval in this example is 0.8%-14.6%, which is quite big (but probably due to the fact that the numbers in this example are just made up).
(3) Calculate 95% confidence interval of Visits and of Conversion_Events, then take the low/high and high/low. I.e. Visits 95% confidence is 1435-5674, Conversion_Events is 61-361, so 61/5674=1.1% and 361/1435=25.2%. This makes some intuitive sense to me, though I suspect that simply dividing in such manner no longer means the outcome confidence is at 95%.
So, my questions:
a. Is my concern that method (1) is "hiding" some information justified?
b. Does method (2), which intuitively makes the most sense to me, make statistical sense?
c. What's the preferred approach (which I suspect is neither of the 3)?
Comment: In your search for solutions it will help to know that limits for tomorrow's conversion rate are *prediction limits,* not confidence limits.  This means your efforts to use confidence limit formulas are doomed.
Comment: What is @Conversion"?
Comment: Conversion is frequency of occurrence of some desired event. For example, if 100 visitors visited the website, and 5 of them clicked on the "Buy" button, the conversion rate for this action is 5%.
Answer: You say you do not want to consider covariables like weekdays and so on, so we omit mention of covariables.  You should concentrate on modelling the counts directly, not he percentages/proportions. Number of daily visits is then a time series of counts, so the simplest model to consider is the Poisson distribution.  Then we know the variance is equal to the mean, so my first question to you is: Compare your sample mean, and the sample variance. Are they close enough to warrant using a Poisson model?  If not, we could try some other counting distribution, like the negative binomial.
Next, you should investigate if there is time dependence. Calculate the autocorrelation function, maybe after applying the square-root transformation (which is approximately a variance-stabilizing transformation for the Poisson).  Is there time-correlation structure which needs to be modeled?
After deciding on a model for the daily visit counts, then the conversions.  Focus on the probability  $p$ that the visit result in conversion.  If the visits process is Poisson with expected number of daily visits $\lambda$, then the conversion process is poisson with expectation (per day) $p\lambda$.  But, this assumes $p$ is a constant and does not vary, which must be investigated. So make a plot of  conversion percentage versus daily visits. Is there some relationship?
This way you can gradually build up a model, which you finally  use to get your confidence (better prediction) interval. Hope this helps!
If you would include in your past some reasonable part (say, 100 days) of your data, we could test out some possible models. Also,if this answer is not understandable for you, tel us what is the problem.


MATCH() AGAINST() & Fulltext index: Possible to have "keywords" field?

Question: I'm using MATCH() AGAINST() with a fulltext index and I was wondering how I could setup a "keywords" data field.
So let's say I have a a fulltext index on the "title" column, which for example might have a row with the value of "AC/DC".. I want to have a field to enter additional keywords like "ACDC" "AC DC" and "AC-DC"
Ideally I'd like to specify these keywords in comma-delimited text form, like this:
Title: "AC/DC"
Keywords: "ACDC, AC DC, AC-DC"

Any idea how I might accomplish this from a database perspective?
Let me know if you need any clarification!
Dave
Answer: Please - no comma separated values.  Store the keyword info in a separate table:
DROP TABLE IF EXISTS `example`.`keywords`;
CREATE TABLE  `example`.`keywords` (
  `title` varchar(45) NOT NULL,
  `keyword` varchar(100) NOT NULL,
  UNIQUE KEY `uk_idx` (`title`,`keyword`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


Ajax HTTP Error Occured in Theming Tables

Question: I have two elements in my form: a select element and a div with an id of #myid_table_wrapper.
function myid_print_user_page_form()
{
    $form = array();

    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's")
        ),
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_table_wrapper',
        ),
    );
    $form['myid_table_wrapper'] = array(
        '#type' => 'item',
        '#markup' => '

',
    );
    return $form;
}

Everytime the select element fires an onchange event it calls a callback function named myid_print_all_submitted_id_callback.
function myid_print_all_submitted_id_callback($form, $form_state)
{
    // Build the sortable table header.
    $header = array(
        'id_number' => array('data' => t('ID Number'), 'field' => 'id_number','sort' => 'asc'),
        'student' => array('data' => t('Student'), 'field' => 'student', 'sort' => 'asc')
   );

   //Get the node data.
   $query = db_select('student', 't1',array('target' => 'import'));
   $result = $query
       ->fields('t1', array('studid','lastname', 'firstname', 'middlename', 'extname'))
       ->condition('t1.id_status',2,'=')
       ->distinct()
       ->execute();
   //Build the rows.
   $rows = array();
   foreach($result as $record){
       $rows[$record->studid] = array(
           'id_number' => $record->studid,
           'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
       );
   }
   return theme('table', array('header' => $header, 'rows'=> $rows));
}

The code results to an error:

Whats wrong with my code? How will I debug this?
Answer: The correct way to do this is to populate the id table inside the form generation function (checking $form_state['values']). Then the callback should only return the form element.
This is an example of how I would do it:
function myid_print_user_page_form($form, $form_state)
{
    $form = array();

    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's")
        ),
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_table_wrapper_div',
        ),
    );
    $table_html = '';

    // Check if option has been selected.
    if(!empty($form_state['values']['options'])){
      // Build the sortable table header.
      $header = array(
          'id_number' => array('data' => t('ID Number'), 'field' =>   'id_number','sort' => 'asc'),
          'student' => array('data' => t('Student'), 'field' => 'student', 'sort' => 'asc')
       );
       //Get the node data.
       $query = db_select('student', 't1',array('target' => 'import'));
       $result = $query
           ->fields('t1', array('studid','lastname', 'firstname', 'middlename', 'extname'))
           ->condition('t1.id_status',2,'=')
           ->distinct()
           ->execute();
       //Build the rows.
       $rows = array();
       foreach($result as $record){
           $rows[$record->studid] = array(
               'id_number' => $record->studid,
               'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
           );
       }
       $table_html = theme('table', array('header' => $header, 'rows'=> $rows));

    }

    $form['myid_table_wrapper'] = array(
        '#type' => 'item',
        '#markup' => $table_html,
        '#prefix' => '
',
        '#suffix' => '
',
    );
    return $form;
}

function myid_print_all_submitted_id_callback($form, $form_state)
{
    return $form['myid_table_wrapper'];
}

This is untested, but you get the idea.
Comment: also, might be a good idea to send it through the check_plain function `'student' => check_plain($record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname)`
Comment: Thanks for giving me  an idea, I tried what you said, but my table only rebuilds when the last option is selected. When the first two options are selected, the same error occurs. Where am I missing?
Comment: Something's wrong with the line below:
Comment: 'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
Comment: I edited the code to:

'student' => 'Constant String'. Then, it perfectly runs. Why?
Comment: Are you sure all the properties you are expecting are set on the record object?
Comment: Thank you for your answer 2pha. The symbol ñ is causing my ajax to break. Thanks again.


Increasing (or changing) the eccentricity of a vertex in a given graph.

Question: I considered a graph, path $P_8$ and added two more vertices such that eccentricity of two vertices is three and rest of the vertices have eccentricity four, and $P_8$ is induced in the new graph. I got the following figure, where exactly two vertices (numbered 2 and 7) are central vertices (eccentricity two) and rest are non-central vertices i.e., diametral vertices (eccentricity four) and $P_8$ is induced in this graph.

Is there any way to get the same result for the graph path $P_9$, or other path graphs, by adding exactly two vertices. Any kind of help or suggestion will be highly useful for me. I am thankful in advance for the help.
Comment: What exactly is the result that you are looking for? Are you looking to add two vertices to $P_9$ to achieve diameter $4$ and radius $3$?
Comment: Yeah, You are right, but the condition is that only two vertices should have eccentricity 3 and rest should have eccentricity four.
Answer: I want to note that there is one other graph (and only one up to isomorphism) that meets your conditions on $P_8$:

Here, vertices $7$ and $9$ have eccentricity $3$ and the rest have eccentricity $4$.
I have found $76$ such graphs on $P_9$ though many of these are not unique up to isomorphism. Also, some of the graphs are subgraphs of other such graphs. A couple are listed below.

Above, vertices $1$ and $2$ have eccentricity $3$ and the rest have eccentricity $4$.

Above, vertices $7$ and $10$ have eccentricity $3$ and the rest have eccentricity $4$.
I would be happy to provide more information about the graphs if you want more. Just comment.
Comment: Amazing. That is really helpful to me. I am glad that you helped me. Really thanks a lot.
Comment: How did you manage to get such a large family of graphs?
Comment: @monalisa I used SageMath to look for graphs that had the required property. My code produced $14$ such non-isomorphic graphs on $P_9$ and $2$ on $P_8$. I would be happy to post a second answer here to classify the $14$ graphs. Just let me know.
Comment: That would be so helpful to me if you can share them. Once again thanks a lot for your efforts.
Comment: @monalisa Added another answer. Hope you find it helpful.
Answer: These are the $15$ graphs (up to isomorphism) with this property on $P_9$.
Comment: A million thanks for this answer. I am grateful to you. Thank you.


When the kernel says "Out of memory: Killed proces..." does it mean real memory or virtual memory?

Question: Looking at journal -xe for the reason(s) a process is killed, the message comes up in red "Out of memory: Killed process..." but it doesn't say whether the limiting resource is virtual memory or is real memory.
Which does it mean and why doesn't it simply say so?
Comment: A nice slightly above entry level write up on the causes of an out of memory error and the OoM killer triggering is this: https://linux-mm.org/OOM  - in short you only get one error because for the kernel the problem is always the same root issue: it can't free up enough real memory to run all requested tasks. That can coincide with full swap but doesn't have to be.
Comment: That's a reasonable answer to my two 'and' conjoined questions.
Answer: The simply answer is, at the moment your memory usage (RAM) is high and make other proccess cant run.
If your server run on VMs virtualization like KVM etc then it mean virtual memory.
Comment: Virtual memory in this context does not mean a hypervisor and virtual hardware. It means abstracted address spaces that do not necessarily directly map to the contents of DRAM chips.  https://en.wikipedia.org/wiki/Virtual_memory


My admin panel view fancy box not working

Question: I am new to drupal. I searched this problem in google but could not get the solution that could solve my problem. My problem is,
I used a fancybox for one of my news post page. It uses latest version of Jquery. When, I use this, my fancybox works well. But, when I come to view page, My light box does not work there. Like,
When I click on add button [Add button to add fileds or filters ], the sceen goes black and nothing happens. When I remove the fancybox, it works well. It is important for me to use fancybox. Please suggest how to solve this problem.
Answer: I also faced the same problem. This is due to jquery problem. Let me tell you that jquery contains default support to jquery. It uses older version of jquery in its core. So, if u want to use that module, then, what u can do is:

Download jquery update module and enable the moudle,
Then you open the project code, moudles folder and find the jquery update moulde, there you will find replace folder. You, will find various version of jquery there. You can include or replace the latest version of jquery.
However the drupal core works in older version, so what you can do is open the jquery_update.module file and find the line that says.
// Replace files for jQuery 1.7 and up
      if (version_compare($version, '1.7', '>=')) {
        $javascript['drupal.states']['js']['misc/states.js']['data'] = $path . '/replace/misc/1.7/states.js';
  }
Now what you need to do is. You need to check, if the user is logged in then replace the jquery with core old jquery and if user is not logged in then, use the latest your fancybox jquery.
Answer: I found the same thing and patched fancy box. There was a missing permission for the settings page.
You might like to grab the dev release. http://drupal.org/node/1888814


Why is $\left(\frac{\partial}{\partial x_i}\right)f = \left(\frac{\partial f}{\partial x_i}\right)$

Question: i'm currently reading An Introduction to Morse Theory by Yukio Matsumoto and on p.62 it says

A vector field itself is sort of a differential operator, since it
  assigns to each point a "tangent vector" which is a differential
  operation. Let us differentiate $f$ with respect to the gradient
  vector field $X_f$:
$$X_f \cdot f = \left(\sum_{i=1}^m \frac{\partial f}{\partial x_i}
 \frac{\partial}{\partial x_i}\right)\cdot f = \sum_{i=1}^m \left(
 \frac{\partial f}{\partial x_i}\right)^2 \ge 0$$

I would love to understand why $$ \left(\frac{\partial}{\partial x_i}\right)\cdot f =  \left(
 \frac{\partial f}{\partial x_i}\right)$$
Could anyone help me on this? Thank you very much.
Answer: It is just notation. See here for a short description.
Comment: @Zest I'm not completely at home with this, but I think that you can interpret it sort of like the [gradient](https://en.wikipedia.org/wiki/Gradient) (even though the gradient and the gradient vector field is not the same). Maybe you can see some similarities in the way that they are used. Especially notice that $\nabla \cdot f = \nabla f$ where $\nabla$ is the gradient, i.e. the gradient works sort of like an action on the function.
Comment: Thank you very much @soer9606. Can you also help me understanding what "differentiating $f$ with respect to the gradient vector field" means? Because all i see is just a product of $f$ with $X_f$.
Comment: that helped! thank you very much :-)


Getting libraries to load with newer jQuery using jqmulti

Question: I'm kind of a newbie to this so I could be missing something really obvious, but I'm having trouble getting specific libraries to load with jQuery 1.7 in noconflict mode using jqmulti. I'm working on a theme based off twitter_bootstrap, and the bootstrap.js library is dependent on more recent jQuery. I've got jqmulti recognizing and loading 1.7 if I check "load even if no libraries are assigned" but when I have that unchecked and attempt to use hook_jqmulti_files() to assign particular libraries, nothing happens.
This is what I have in my template.php:
function regent_jqmulti_files() {
    return array(
        'sites/all/themes/regent/bootstrap/js/bootstrap.js',
        'sites/all/themes/regent/bootstrap/js/bootstrap.min.js'
    );
}

but when I look at my rendered html, the library is loaded, but nothing about noconflict mode,  and jQ 1.7 is nowhere to be found. I'm sure I'm missing something basic and stupid, this being the first time I've tried to set something like this up.
Answer: If you have checked "load even if no libraries are assigned", jQuery 1.7 should load regardless of anything else you do. So in your HTML you should see Drupal's jQuery loading, and you should also see jQuery1.7 loading, and also a script called switch.js, which takes care of the noConflict() mode. If you don't see those loading, there is a problem that's not related to your hook. Check the jQuery Multi settings page, does it list the jQuery version it's using?
Answer: As you are talking of a template.php file, I get you are talking of theme code. The only hooks a theme can implement are alter hooks (the ones called with drupal_alter() and with a name ending in _alter), in Drupal 7. (Theme functions are not hooks.)
If you look at the code of drupal_alter(), you will notice it contains the following lines.
// Allow the theme to alter variables after the theme system has been
// initialized.
global $theme, $base_theme_info;
if (isset($theme)) {
  $theme_keys = array();
  foreach ($base_theme_info as $base) {
    $theme_keys[] = $base->name;
  }
  $theme_keys[] = $theme;
  foreach ($theme_keys as $theme_key) {
    $function = $theme_key . '_' . $hook;
    if (function_exists($function)) {
      $functions[$cid][] = $function;
    }
    if (isset($extra_types)) {
      foreach ($extra_types as $extra_type) {
        $function = $theme_key . '_' . $extra_type . '_alter';
        if (function_exists($function)) {
          $functions[$cid][] = $function;
        }
      }
    }
  }
}

Differently, module_implements() (used from any function that invokes hooks) doesn't check hooks implemented by themes.


Google Script adding multiple lines based on cell value or date ranges

Question: pretty new at this stuff, but trying hard to keep learning. I'm looking for a possible script or solution to essentially take a row of data and duplicate it based on the value of a cell within the row.
As an example, see this sheet.
Any help would be greatly appreciated.
Comment: Welcome. _take a row of date and duplicate it based on the value of a cell within the row._ This description is hard to follow. Would you please edit your question to describe your problem and reference the sheets (and relevant ranges) in your spreadsheet, and make it clear which sheet contains the data, which cell is the one to be evaluated, what is the evaluation, where is the duplication to be made, and what data is to be  duplicated. Would you also please indicate whether the spreadsheet contains an example of a successful outcome and if not, please add a sheet showing the desired outcome.
Comment: When you want to achieve your goal using Javascript which is not Google Apps Script, I think that you are required to use Sheets API. You can read the official document at [here](https://developers.google.com/sheets/api/reference/rest/). And also you can see the Quickstart at [here](https://developers.google.com/sheets/api/quickstart/js).
Comment: Echoing off @Tedinoz, you might be able to achieve your goal with native sheet functions. Advanced solutions with js might also be an option, depending on the scope.
Answer: <code>=ArrayFormula(vlookup(transpose(split(query(rept(row(A2:A)&" ",F2:F),,9^9)," ")),ArrayFormula({row(A2:A),A2:G}),{2,3,4,5,6,7,8},0))</code>
In this sample, the formula is in cell I2. The headers in Row 1 are added manually.

Credit: infoinspired.com
Comment: Is this answer was helpful, then you might consider accepting it.


Overdispersed Poisson Distribribution

Question: I'm interested in finding the probability distribution of the following process:
Let $X \sim Poisson(\lambda_1)$, and $Y \sim Poisson(\lambda_2)$.
If $X$ is observed, the system 'waits' for time $t_x$ before being able to observe $X$ or $Y$ again. That is, time continues to advance, but during the waiting time $t_x$, neither $X$ nor $Y$ can be observed. Similarly for $Y$ with time $t_y$.
What is the probability of observing $X$ in the following t seconds, starting in an un-waiting state?
What is the probability that the next observation is $X$, and what is the expected time to observe it?
I'm finding this problem difficult to solve from an analytical perspective. I've already simulated it but I'd like to solve it analytically.
Any help is greatly appreciated. I really don't know where to start with incorporating the waiting times :(
Comment: I don't think the problem is described clearly enough.  What exactly is meant by "observing" a stochastic process?  For what duration of time are the processes observed?  What is the rule about choosing between observing process $X$ or process $Y$ next?  Do we choose probabilistically? Or,  can we observe both processes at the same time over some interval of time?  How do the individual arrivals from the $X$ and $Y$ processes affect our decisions about what to observe, and for how long we make the observations?
Comment: Say the result of the observation (a realization of $X$) is $5$. What is the relationship between $5$ and $t_x$?
Comment: Observing a poisson process X here means a single count observation. So in the same way that you can find the expected time for the first poisson event to occur, that first event will trigger the wait time, and then once that wait time is over, the system is reset

The Poisson observations themselves are instantaneous, but observing them triggers the wait time.
Comment: So in infinitessimal time bins, you have counts of 0,0,0,0,0,0,0...,1...wait for time $t_x$ ... 0,0,0,0,1....wait for time $t_x$.... etc.
Comment: I think you mean that you have two classes of Poisson processes, and you observe individual arrivals from these processes.  Depending on the type that arrives next, you "timeout" for a certain time (and we ignore all arrivals, of both types, that occur during the timeout). After each timeout, we go back to "observing mode" which is really just waiting for the next arrival to occur (which could be from either type).  Is this correct?
Comment: That's right! Thanks
Comment: Still no progress on my end btw. This is a hard problem
Answer: I think the system may work like this:  We have two independent Poisson arrival processes $X_1(t)$ and $X_2(t)$, with rates $\lambda_1, \lambda_2$, respectively (in units of arrivals/sec).  The timeline is segmented into renewal frames $i \in \{1, 2, 3, ...\}$ that work like this:

We start each renewal frame $i$ in observation mode, which lasts until the next arrival.
If the next arrival is type 1, we go to sleep for time $T_1$ seconds. On the other hand, if the next arrival is type $2$, we go to sleep for time $T_2$ seconds. Here, $T_1$ and $T_2$ are fixed nonnegative constants.
We ignore all arrivals that occur while we are asleep.
The next renewal frame $i+1$ occurs when we wake up from sleep.

The basic theory is that if $X_1(t)$ and $X_2(t)$ are independent Poisson processes of rates $\lambda_1, \lambda_2$, then the combined process is also a Poisson process, has rate $\lambda_1 + \lambda_2$, and each new arrival of the combined process is independently type 1 with prob $\lambda_1/(\lambda_1+\lambda_2)$ (independent of the history of interarrival times and types before this new arrival).
So if we start a new renewal frame $i \in \{1, 2, 3, ...\}$, the time $Y_i$ to the next arrival is exponentially distributed with rate $\lambda_1+\lambda_2$, so it has average time $1/(\lambda_1+\lambda_2)$.  Regardless of the value of $Y_i$, the new arrival is type 1 with prob $\lambda_1/(\lambda_1+\lambda_2)$, and it is  type 2 with prob $\lambda_2/(\lambda_1+ \lambda_2)$.
Renewal theory allows us to compute the steady state fraction of time we are in the observation mode, the sleep-type-1 mode, and the sleep-type-2 mode: Let $H(t)$ be the total time we are in the observation mode during $[0,t]$, and let $S_1(t), S_2(t)$ be the total time we are in the sleep-type-1 mode and sleep-type-2 mode, respectively, during $[0,t]$.  Then:
\begin{align}
\lim_{t\rightarrow\infty} \frac{H(t)}{t} &= \frac{\frac{1}{\lambda_1+\lambda_2}}{\frac{1}{\lambda_1+\lambda_2}+ \frac{\lambda_1T_1}{\lambda_1+\lambda_2} + \frac{\lambda_2T_2}{\lambda_1+\lambda_2}} \quad \mbox{ with prob 1} \\
\lim_{t\rightarrow\infty} \frac{S_1(t)}{t} &= \frac{\frac{\lambda_1T_1}{\lambda_1+\lambda_2}}{\frac{1}{\lambda_1+\lambda_2}+ \frac{\lambda_1T_1}{\lambda_1+\lambda_2} + \frac{\lambda_2T_2}{\lambda_1+\lambda_2}} \quad \mbox{ with prob 1} \\
\lim_{t\rightarrow\infty} \frac{S_2(t)}{t} &= \frac{\frac{\lambda_2T_2}{\lambda_1+\lambda_2}}{\frac{1}{\lambda_1+\lambda_2}+ \frac{\lambda_1T_1}{\lambda_1+\lambda_2} + \frac{\lambda_2T_2}{\lambda_1+\lambda_2}} \quad \mbox{ with prob 1}
\end{align}
Notice that these fractions of time sum to 1.
Comment: This is absolutely fantastic! It looks like renewal theory deals only with the limit as time goes to infinity. Do you know what the distribution looks like for $t < \infty$ ? If not, do you perhaps know how quickly the convergence takes place?
Comment: Finite time analysis is usually much harder.  In this case, we can get upper and lower bounds on, say, the expected time spent in the observation phase during $[0,t]$. The Wald equality may help. I think those bounds, when divided by $t$, converge to the limiting fraction of time (given above) with error $O(1/t)$.  You can also compute the probability that there are at least $k$ renewal frames during $[0,t]$, and there may be an interesting recursive calculation for the probability that we go into sleep-type-1 mode at least once during $[0,t]$.  What is the context? What is this analysis for?

Overdispersed Poisson Distribribution


modifying data variable in vue.js using axios

Question: Here is my script :

        {{ textFromApi }}

I'm trying to modify this.textFromApi from the call of this api: https://jsonplaceholder.typicode.com/posts/1
but my this.textFromApi doesn't seems to update, any ideas why?
Here is a fiddle code:
https://jsfiddle.net/bussiere/5t3v013o/
Edited from remark just below
Regards and thanks
Answer: created() is a lifecycle hook, it should be at the same level as data, methods, computed etc. Not a child of methods (so if you nest created() in methods() it will never get executed unless you call the method).
You also don't do anything with the axios promise, you should process it using then ().

        {{ textFromApi }}

Comment: if i'am not wrong still not working  : https://jsfiddle.net/bussiere/5t3v013o/ and edited but htanks
Comment: Axios needs a promise like this: https://jsfiddle.net/5t3v013o/1/ I also updated my answer to include the promise.


Attempted import error: 'yup' does not contain a default export (imported as 'yup'). NPM

Question: Estou criando um site com serviço de autenticação e nele pretendo usar o yup, um modulo do NPM.
Instalei tudo certo mas quando vou dar start na aplicação ele aparece:
Attempted import error: 'yup' does not contain a default export (imported as 'yup').

Já tentei diversas coisas mas sempre o mesmo erro no npm.
Comment: insira no final do código o "export default yup"
Answer: Como você está importando o yup no seu projeto ? Ele não possui um export padrão, sendo assim, não dá para importar desta forma: import yup from 'yup', você precisa importá-lo assim import * as yup from 'yup' para ter acesso a todos os recursos, ou desestruturar para um recurso específico. Veja aqui.


Order by entry in separate table in Webmatrix

Question: I'm trying to do something in my new Webmatrix site, and I'm not sure it is possible.
I have the following 2 tables in my database.
Property
PropertyID,
PropertyName,
Primary_Image
Images
PropertyID,
ImageURL,
ImageID
I have set up a page for each property, which shows ALL images that belong to that property. The problem is, I want to order those images, so that the primary image shows at the top? How can I make that happen?
Here's  my current SQL query:
var images = db.query("SELECT * FROM Images JOIN Property ON Images.ImageID=Property.Primary_Image WHERE PropertyID = @0"), PropertyID;

Answer: Try with:
var images = db.query(@"SELECT t1.* FROM Images t1 LEFT JOIN Property t2 ON
    t1.ImageID = t2.Primary_Image WHERE t1.PropertyID = @0 ORDER BY
    t2.Primary_Image DESC", PropertyID);

With this query you filter the records from Images that have a given PropertyID joining with the matching rows of Property.
Since only the primary image has a matching row in Property, this record is the only that has a value in Primary_Image: ordering in descending order puts this record at the first place.
Comment: sorry for the delay, but managed to try this, and it's worked perfectly. Thanks for your help.


Query for exact word search

Question: hope that you are doing fine
I am having very hard time writing a query
Here is my question explained
i have a database table say "jreviews_content" which has a field named "jr_produits"
In "jr_produits" the data is is the format *ryan-decosta*tom-gosling* so i want a search query that is exact word based i.e if the user type "rya" the mysql should not return anything
but if the user type ryan then it should return the row likewise if the user type "gos" the mysql should not return anything
but if the user type gosling then it should return the row where ryan and gosling are the exact words
the query that i am writing are
SELECT *
FROM `jreviews_content`
WHERE jr_produits LIKE '%*ryan-%' or jr_produits LIKE '%-ryan*%'
or jr_produits LIKE '%*ryan*%' or jr_produits LIKE '%-ryan-%';

I want that to be done in some other way that is more efficient(either by regular expression or any other method)
SELECT * FROM `jreviews_content` WHERE jr_produits REGEXP '^[*-]ryan[*-]$'

It doen't fetch anything
neither does
SELECT * FROM `jreviews_content` WHERE jr_produits like '%[*-]ryan[*-]%'

Please suggest something
Comment: Change your database schema, and do not try to make custom tables within each record!!!
Answer: Try the MySQL regex word boundary markers. They're documented about halfway down this page:
SELECT *
FROM jreviews_content
WHERE jr_produits REGEXP '[[:<:]]ryan[[:>:]]'

Note that I don't have MySQL access today, so this is untested.
Also heed what @user1032531 said. Records with values like *ryan-decosta*tom-gosling* almost always mean "bad design".
Comment: Fair enough on the table structure, and no worries. As for the regex, the `[[:<:]]` means "beginning of a word". It doesn't match to a character; it says "whatever follows (in this case `ryan`) must be at the beginning of a word". Likewise, the `[[:>:]]` means "end of a word". The link in my answer gives a little more detail. Hope this helps; it's kinda hard for me to explain :)
Comment: can you please explain the regular expression you wrote
Comment: this is not my table structure i am using JReviews component of joomla that has this structure to store the products
Comment: hello its me again i have another query
my site is in french language and hence there are lot of accent on my site for example frènch french i want the search to be acccent insensitive is there any way to do that
Comment: Hi Ryan - I Googled this and it may not be possible. See [here](http://stackoverflow.com/a/14137335/2091410). Still, I'd suggest posting this as a separate question because lots of people will see it and someone may know a workaround. Good luck :)

Query for exact word search


PHP & Smarty - Submit form to self within Ajax Tab

Question: I have an ajax tab with a form inside it, with url http://example.com/tabs.php#pg=3, and I'm trying to submit the form to this tab using <code>{$smarty.server.REQUEST_URI}</code>, and although this does in fact submit the form to the correct .php file (used by the ajax tab), it is no longer contained within an ajax tab (I end up at http://example.com/formhandle.php).
Does anyone have an idea of how to submit the form to itself contained within the ajax tab? I've tried submitting to the URL of the specific tab (http://example.com/tabs.php#pg=3), however if I do this, the form post isn't actually handled. I'm stuck on this one.
Comment: What does it mean `form post isn't actually handled`? You should put some code otherwise we can only guess what you are doing
Answer: Your code within formhandle.php would need to be moved to or included in tabs.php


order by weight ASC - D7

Question: This piece of code:
<code>->orderBy('weight', 'ASC');
</code>
orders the column by the weight ascending. However, the rows are sorted like: 15 - 2 - 20
of course this should be: 2 - 15 - 20
How can I achieve this, specifically for drupal(7)?
Answer: It seems that the database is using lexicographic ordering, while your intention is to use numeric ordering. Numeric ordering is only used when the type of the field is a numeric type. Check whether the field is of a numeric type.

order by weight ASC - D7


2 domains configured on digital ocean, only 1 works with direct browser access using Apache2

Question: I have a droplet on digital ocean which was initially configured with only one domain (andrey.dev.br), it worked right out of the box after installing either Apache or Nginx without any extra configuration.
after some time I configured a second domain (raphaelvieira.dev) on the same droplet via digital ocean admin panel, the first weird behavior was that every time I tried to access the domain raphaelvieira.dev on the browser (chrome, firefox, etc), the browser automatically redirected it to https://raphaelvieira.dev, which is odd because I don't have a HTTPS configured on apache, but it works if I access it via terminal with curl, example:
<code>curl htttp://raphaelvieira.dev
</code>
after some unsuccessful tries, I decided to add virtual hosts for the two domains, following this tutorial, the first one (andrey.dev.br) continued to work fine via browser access or curl, but the raphaelvieira.dev, when accessed from browser, started to return "www.raphaelvieira.dev took too long to respond.", but kept working via curl on terminal.
the raphaelviera.dev domain is registered on google domains.
why is this happening?
Comment: i installed https on apache and now the raphaelvieira.dev is working, seems like .dev domains must have https enabled, at least for direct browser access
Comment: "why is this happening?" When you bought your `.dev` domains the registrar had the obligation to show you a message (this is required by the registry, Google) explaining that `.dev` domains requires HTTPS as the whole TLD has been added to the HSTS preloading list.
Answer: This is a known issue.
TLD .dev is forced to use HSTS, which means without SSL is not possible
Regarding https://get.dev/#get-started as Reference:

Your security is our priority. The .dev top-level domain is included
on the HSTS preload list, making HTTPS required on all connections to
.dev websites and pages without needing individual HSTS registration
or configuration. Security is built in.

So Enable and force SSL and also forgot any http on this as it will be useless on this kind of TLD.


Why frequency difference between notes is not constant?

Question: I found that the difference is sometimes ~3, sometimes ~2 or ~4 Hz. Why isn't it constant? Would it be better if it was constant?
Comment: What do the 3, 2, and 4 stand for? Do you mean 3:1, 2:1, and 4:1 frequency ratios? If so, the 3:1 ratio does not represent an octave: it represents an octave plus a perfect fifth. (4:1 represents two octaves.)
Comment: Hi Abhishek - I can't tell what you're talking about here. Are you talking about a particular scale? What do the numbers 2, 3, and 4 mean - are they ratios? Hz? intervals in semitones?
Comment: This is a poorly worded question.  Can you be more explicit?  FOr example he difference between 440Hz and 220Hz is 220Hz, not 2 or 3.  And what are you using ~ to represent?  Approximately?
Comment: However, the Western musical system of notes isn't designed to have the maximum number of discernible notes. If you google *pitch difference limen*, you will see that human sensitivity to pitch differences is much greater than the difference between notes in the chromatic scale apart from at the extremes of Human hearing.
Comment: Compromise - science and maths don't always align with art and music!
Comment: Thosr numbers are in hertz
Comment: Secondly, why would you expect them to ever be constant?
Comment: "Those numbers are in hertz" - So you are talking about a situation where some "notes" might have a frequency difference between them of 2, 3, or 4 Hz. But as @ggcg says,  I'm afraid it's still not clear to me what situation you're talking about in which you'd expect some difference in tuning, and you'd expect it to be constant. We're not mind readers - please explain fully what you are asking about!
Comment: Yes, since there are all sorts of notes you can have delta(f) as small as 0.01Hz, and as large as ~19,000Hz.  It just does not make sense what you are asking @AbhishekDaberao
Comment: @Tim, wadr, in this case I do think math aligns with music but I cannot figure out what the OP is trying to ask.
Comment: Sorry for the problem. Let me clarify. I have Just started learning music theory. The question came like this... Human audible range is 20hz to 20kHz. So I thought like, the maximum number of notes in that range depends on the least possible frequency interval that humans can notice. To find what that smallest interval is and if it is followed in our music system. I tried to simply subtract adjacent note frequencies. But turns out that the difference isn't arithmetic, it's geometric. So I am even more confused.
Comment: Aha. So it's the logarithmic behaviour of perceived pitch differences that confuses you? You and many others. There are twice as many frequencies between C2 and C3 than between C1 and C2, Counting frequencies is not the way to go for your experiment since we will be able to perceive frequency differences in more detail the lower the pitches that are being compared. This is about energy changes and relative differences, not absolute values. Perhaps this is what is confusing you.
Comment: "I tried to simply subtract adjacent note frequencies" - if you take a look at http://pages.mtu.edu/~suits/notefreqs.html, you will see that the difference in Hz is not 'sometimes 3' - it's only around 3 at one particular point near G#1. As @PeterJ says, Human perception of musical intervals is approximately *logarithmic* with respect to fundamental frequency - have a look at https://en.wikipedia.org/wiki/Pitch_(music)#Labeling_pitches and especially the graph https://en.wikipedia.org/wiki/Pitch_(music)#/media/File:Music_frequency_diatonic_scale-3.svg
Answer: It seems to me that this is a rather difficult question and maybe the only real answer is "cause it happens to be this way".
It breaks down to: If you want to partition the frequency range into octaves and each of this intervals into a constant number (12) of pitches (halftones) then constant ratio instead of constant difference is simply a necessity.
As the comments already pointed out musical pitch happens to be geometric rather than arithmetic. That is e.g. if one A has a frequency of 440 Hz the A one octave higher has a pitch of 880 Hz = 440 Hz * 2. The A one more octave higher has a frequency of 880 Hz * 2 = 1760 Hz. If the frequency/pitch relation would be linear you could expect it to have a frequency of 880 Hz + 440 Hz = 1320 Hz which is not the way how it is organised.
If you accept this relation for octaves than the idea of "equal frequency differences" is obviously not compatible with the idea to have the same number of halftone steps in each octave.
Why octaves then? And why do they double the frequency?
One line of reasoning is the anatomy of the ear. The cochlea is constructed in a way that octaves lead to a similar neural stimulus.
Another line of reasoning is that tones an octave away have the highest degree of similarity:
Because they have of all possible frequency combinations the best alignment. That is the time after which the pattern formed by the tone at f1 and the tone at 2*f1 has the lowest period. It repeats after 1 wavelength of the tone with lower frequency.
f1 and 1.5 times f1 e.g. repeat after 2 wavelengths of the tone with the lower frequency.
Which happens the be the reason why the cochlea will give a neural stimulus of maximum similarity for two tones an octave away :-)
Answer: For a "perfect unison" it is always better if there is no difference between the two frequencies. If the two frequencies are different by 2 Hz, you will hear two "beats" per second due to the interference between the wave frequencies. A difference of 4 Hz will sound like four beats per second. These sound "out of tune".  A musician who is playing out of tune is trained to quickly adjust (fingering, embouchure, slide position) in order to eliminate the interference beat.
Being able to reproduce absolutely stable frequencies is the purview of electronic music synthesis. One common musical device requires the musician to modulate the frequency of a note like a wave.  It is called "vibrato" and results in a more beautiful music tone— even though the frequency is very unstable!
In music, it is very common to express the tuning of a pitch in "cents", where one cent is a hundredth part of the distance between semitones in 12-tone equal temperament.  In university we learned a difference of only 3¢ is audible to most people.  If someone says you are playing 2¢ sharp, a good reaction would be "oh really?", whereas if you were 8¢ off an adjustment would absolutely be required.
There are other scales with more or less than 12 equal semitones per octave.  Some scales are logarithmic, like equal temperament is, some are rational (based on frequency ratios) for example scales based on just intonation; Harry Partch's 43-tone per octave scale https://en.m.wikipedia.org/wiki/Harry_Partch's_43-tone_scale or Dean Drummond's 31-tone subset.
Example Harry Partch's frequency ratio-based notation:
Example 31-tone just intonation scale in standard hybrid notation practice (concert C pitches with Bb fingerings):


jQuery not properly reading CSS "left" property when Chrome is zoomed in?

Question: Discovered a strange problem that went undetected because I do 99% of my web dev in Windows.
I've got a neat jQuery-based slider for feature stories on a website. You can see it at http://www.vancitybuzz.com/
I can't seem to figure out why the slider fails on OSX even when using the same version of Chrome. When jQuery reads $("#slidebox .container").css("left").replace("px","") it returns -533 on the first "slide" even though the DOM inspector is actually -640.
Is this a jQuery 1.7.1 bug or a Chrome bug? Workaround? Thanks.
EDIT
I have found what causes this problem. When Chrome v17 is zoomed in (turns out it wasn't OS-specific, only defaults caused by OS) it screws up the real reading of CSS left property. What could be a workaround for this?
You can find the code that controls SlideBox at the bottom here: http://www.vancitybuzz.com/wp-content/themes/meganfox/js/meganfox.js
Comment: same version of chrome + 2 different OSs = inconsistency? sounds like a chrome bug...
Comment: that was my thought, too. i'll see if i can post a workaround
Comment: I'm on OSX / chrome, and it I think it looks correct.
Comment: yeah i don't think i've ever seen "OS sniffing" inside of any library, the only OS-to-OS inconsistency that i've seen occasionally arise is one that is font related, eg. using a specific font that exists by default on one OS and not at all on a different, but even that's kind of an odd case and not at all applicable here... good luck
Comment: @joakimdahlstrom which version of Chrome? using v17.0.963 thx
Comment: @DeLonge, I'm using the exact same one. with .79 at the end as well.
Comment: @joakimdahlstrom that's very strange. macbook, mac desktop, or air? looks like it's only occuring on newer macbook pros but still investigating
Comment: @DeLonge It's supposed to be a few pixels to the left of the white space, right? I'm on a 13" macbook, late 2009 model.
Comment: @joakimdahlstrom check out the edit to my question, i found the cause
Comment: @DeLonge, Oh yeah, I see it. It wanders away out to the left.
Comment: Is this perhaps a CSS pixels vs. Device pixels thing? http://www.quirksmode.org/mobile/viewports.html
Comment: I dont want to disappoint you my friend, but the slider is dead in my Firefox 10..
Comment: it's quite possible jQuery is using different methods of pixels, bug report might be needed. @joakimdahlstrom OMG FF10 has been a pain since release!
Answer: I'm rather late to the party here, but I had the exact same problem when I created a slider about a year ago. The workaround I found was to do all of my offsets in percentages instead of pixels. It behaved well in Chrome at all zoom levels after that.
Flixster uses a slider that works in a similar manner, You get stuck, you can learn a lot by dissecting what they do.


Containment of sets in arbitrary metric spaces

Question: This is the full question:

$(X,d)$ be any arbitrary metric space. Let $S,T \subseteq X$. Prove or disprove the following:(if it's incorrect, what will be the correct statement?)
$1)S^o\cap T^o = (S\cap T)^o\,\,$ $\,\,2)S^o \cup T^o = (S\cup T)^o $
$3)$ $\overline{S\cap T}$ $\subseteq$ $\overline{S}\cap\overline{T}\,\,$ $\,\,4) \overline{S\cup T}$ = $\overline{S}\cup\overline{T}\,\,$ $\,\,5)$ $(S^o)^c = \overline{(S^c)}$
$6)$ $(S)^o = \left(\overline{S}\right)^o\,\,$ $\,\,7)$ $\overline{S} = \overline{\left(S^o\right)}\,\,$ $\,\,8)$ $\overline{S-
 T}$ = $\overline{S}-\overline{T}$
$9)$ If $(X,||.||)$ is a Norm Linear space then is it true that $\overline{S+
 T}$ = $\overline{S}+\overline{T}$ ?

$1)$ is true. $S^o \subseteq S $ and $T^o \subseteq T $. This implies $S^o \cap T^o \subseteq S \cap T$, and since the interior of a set is the largest open set contained in it, we have $S^o \cap T^o \subseteq \left( S \cap T \right)^o$ $\subseteq S \cap T$. Also $S \cap T \subseteq S$ and  $S \cap T \subseteq T$. This implies $\left(S \cap T\right)^o \subseteq S^o$ and  $\left(S \cap T\right)^o \subseteq T^o$. Hence $\left(S \cap T\right)^o \subseteq S^o \cap T^o$. This finishes the proof of $1)$.
$2)$ is false, a counterexample will be $S=\mathbb{Q}$ and $T=\mathbb{Q^c}$ in $X=\mathbb{R}$. $\,S^o=\emptyset$, $T^o=\emptyset$ and $S \cup T =$ $\mathbb{R}$. It should be $S^o \cup T^o \subseteq (S\cup T)^o$. $S^o \subseteq S $ and $T^o \subseteq T $, so $S^o \cup T^o$ $\subseteq$ $S \cup T$. Which implies $\left( S^o \cup T^o \right)^o$ $=$ $ S^o \cup T^o$ $\subseteq$ $\left( S \cup T\right)^o$.
$3)$ is true. $S\cap T$ $\subseteq S$ and $S\cap T$ $\subseteq$ $T$. Which implies $\overline{S\cap T}$ $\subseteq$ $\overline{S}$ and $\overline{S\cap T}$ $\subseteq$ $\overline{T}$. Hence $\overline{S\cap T}$ $\subseteq$ $\overline{S}\cap\overline{T}$. This finishes proof of $3)$. It is not necessary that $\overline{S\cap T}$ $=$ $\overline{S}\cap\overline{T}$, counter example of $2)$ will work.
$4)$ I am not sure. $S$ $\subseteq S\cup T$ and $T$ $\subseteq S\cup T$. which implies $\overline{S}$ $\subseteq \overline{S\cup T}$ and $\overline{T}$ $\subseteq  \overline{S\cup T}$, and hence $\overline{S}\cup\overline{T}$ $\subseteq$ $\overline{S\cup T}$. It seems to be false, but i am not able to find a counter example.
$6)$ and $7)$ are false. A counterexample would be $S =\mathbb{Q}$ in $X=\mathbb{R}$. I think the correct containments are $(S)^o$ $\subseteq$ $\left(\overline{S}\right)^o$ and $\overline{S}$ $\supseteq$ $\overline{\left(S^o\right)}$. Proof: $S \subset \overline{S}$ , which implies $S^o \subseteq \left(\overline{S}\right)^o$ $\subseteq$ $\overline{S}$. Also, $S^o \subseteq S$ hence $\overline{\left(S^o\right)}$ $\subseteq$ $\overline{S}$.
$8)$ is false. A counterexample will be $S=[0,1]$ and $T=[0,1)$ in $X=\mathbb{R}$. Will the correct containment be $\overline{S-
 T}$ $\supseteq$ $\overline{S}-\overline{T}$ ?
I am stuck with $5)$ and $9)$. Kindly check whether the above proofs and counterexamples are correct or not. Any alternate easy proofs will be great :).

Definition 1: A point $x \in X$ is called a limit point of $E\subseteq X$ if $B(x,r)\cap E \ne \emptyset $ $\,\forall\, r>0$.
Definition 2:(Closure of a set) Let $(X, d)$ be a metric space and $A\subset X$. Let $\overline{A}$ denote the set of all limit points of $A$. Thus
$\overline{A}$ $= \{y \in X : $ For every $r > 0$, the set $B(y, r) \cap A \ne\emptyset \}$.
Definition 3(Interior of a set): Let $S\subset X$ be a subset of a metric space. We say that $x \in S$ is an interior point of $S$ if $\,\exists\,$ $r > 0$ such that $B(x, r) \subset S$ . The set of interior points of $S$ is denoted by $S^o$ and is called the interior of the set $S$
Comment: What you have so far is correct. Except for your hunch in 4); 4) is equivalent to 1), by taking complements [that is 5), which you don not yet have].
Comment: Thank you @Daniel
Comment: 4,5 are true, the proofs are not hard. $\overline{S} + \overline{T} \subseteq \overline{S+T}$ follows from continuity of addition. The other inclusion can fail in general, IIRC.
Comment: For the failure of 9. see [this](https://math.stackexchange.com/a/60471/4280)
Answer: Number 5 is an important equation for all topological spaces.
Proof.
x in X - S$^o$ iff x not in S$^o$ iff
not exists open U nhood x with U subset S iff
for all open U nhood x, not-(U subset S) iff
for all open U nhood x, exists y in U with y not in S iff
for all open U nhood x, exists y in U $\cap$ (X - S) iff
for all open U nhood x, U $\cap$ (X - S) is not empty iff
x in $\overline {X - S}$.
For metric spaces instead of open neighborhoods
of x, one may use open balls centered at x.
The usual definition of a limit points is:
x is a limit point of A when
for all open U nhood A, exists y in U $\cap$ A with y /= x.
What you called a limit point is usually called an adherence point.
Answer: Suppose $x \notin \overline{S}$ and $x \notin \overline{T}$. There then exist $r,s>0$ such that $B(x,r) \cap S= \emptyset$ and $B(x,s) \cap T = \emptyset$, but then $B(x, \min(r,s)) \cap (S \cup T) = \emptyset$ too and so $x \notin \overline{S \cup T}$. This shows $\overline{S \cup T} \subseteq \overline{S} \cup \overline{T}$ by contradiction.
nr 5. follows from the observation that if no ball around $x$ stays inside $S$ (so $x \notin S^\circ$) then every ball around $x$ intersects $S^c$, so $x \in \overline{S^c}$ and vice versa.


Google translate service not available on Translation Management module(Drupal 6)

Question: When I using the translation management to translate my node, I got "Google translation failed to Chinese, Simplified: Google returned error #403: Quota Exceeded. Please see http://code.google.com/apis/language/translate/overview.html", anyone know what happen and how to fix it?
Thanks
Answer: Like is said on that page http://code.google.com/apis/language/translate/overview.html access to Google Translate API is now limited.
If you still want continue to use the module you should have a look into this discussion http://drupal.org/node/1215426 where they are looking for another solution.


Left handed piano?

Question: Is there such a thing as a piano that goes from high notes to low notes where the left hand plays the melody and right hand plays the harmony? Lol what is going on here:
Answer: Bah, this video has been filmed in a mirror:
The pianist is sitting at the left side in front of a piano!
Comment: Or it was flipped digitally.
Comment: I verified this by playing in front of the mirror. I wasn't aware that mirrors do that with playing.
Answer: Best guess would be it was shot using the selfie-cam on a smartphone.
They are often mirrored.
Answer: There was a very rich left-handed player, who had a grand made for him (one off, no surprise there!) I mentioned it in an answer a couple of years ago. Strangely enough, not many of his musical colleagues could play it well...
Could be referenced to a question about genuine ambidextrous instruments I asked.
Comment: Wouldn't it be cheaper and easier to play with your hands under a shroud if you want to hide your secret techniques from prying eyes?
Comment: @DavidBowling - I find that a sharp stick is quite effective...
Comment: I don't have good aim when I am playing, but perhaps a pepperspray pedal?
Comment: @DavidBowling - the practice pedal found on some pianos can be adapted to drop a blanket over the keys instead of the strings. That'd work.
Answer: It would be easy to map an electronic keyboard to play 'backwards'.   But this is just a reversed video.
Here's a whole band of reversed marimbas.  Watch the bass player at 1'14"

Left handed piano?


Custom Transition gives "Unbalanced calls to begin/end appearance transitions" Error

Question: I used the code shown below to present a new view controller in a seamless sliding motion. The actual animation works perfectly but when the animation has finished, all of the views disappear and i am left with a blank screen. There is an error posted in the console saying
"Unbalanced calls to begin/end appearance transitions for < Rocket_Game18GameViewController: 0x155e288f0 >"
<code>class SlideRightToLeft: UIStoryboardSegue {
override func perform() {
    var sourceVC:UIViewController = self.sourceViewController as UIViewController
    var destVC:UIViewController  = self.destinationViewController as UIViewController

    let sourceVCFrame = sourceVC.view.frame
    let width = destVC.view.frame.size.width
    sourceVC.view.addSubview(destVC.view)
    destVC.view.frame = CGRectOffset(sourceVCFrame, width, 0)

    UIView.animateWithDuration(1.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
        sourceVC.view.frame = CGRectOffset(sourceVCFrame, -width, 0)
        }, completion: {
            finished in
            destVC.view.removeFromSuperview()
            sourceVC.presentViewController(destVC, animated: false, completion: nil)
        })
    }
}
</code>
Please ask if you need any more information, Thanks!
Comment: You're not calling any of the child view controller methods (`willMoveToParentViewController:`, etc).
Comment: That'd be bad. You say that you are very new to this. If that's the case, I suggest staying away from view controller containment, it's an intermediate level topic. Start with something simpler. That said, Apple's documentation is a good place to find relevant sample code.
Comment: Sorry, im very new to this and have adapted this code from a tutoiral online which has nothing like what you said, could you give me an example?
Comment: I meant to say new to transitions not xcode and swift, but thanks for your help anyway. Ill go check out the documentation
Comment: This was the only documentation i could find and it is out of date as "presentModalViewController" is now deprecated. Any ideas? https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomSegues/CreatingCustomSegues.html
Comment: https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html
Answer: I have now figured out what i was doing wrong by converting someone else's objective-c code into swift. It turns out that my whole custom animation idea was wrong and when iOS7 was released, they changed how it was done. Here is the link to the blog where i found the solution incase anyone else would like to see it
https://github.com/jbradforddillon/TransitioningExample


Having trouble installing Curl on Solaris 10

Question: Here is what I am doing, this is purely through PuTTy on my windows system onto a Solaris VM.
<code># ls
curl-7.27.0          curl-7.27.0.tar.bz2  hostName.pl          starthere.desktop
# cd curl-7.27.0
# ls
Android.mk           README               configure.ac         m4
CHANGES              RELEASE-NOTES        curl-config.in       maketgz
CMake                acinclude.m4         curl-style.el        missing
CMakeLists.txt       aclocal.m4           depcomp              mkinstalldirs
COPYING              buildconf            docs                 packages
MacOSX-Framework     compile              include              sample.emacs
Makefile             config.guess         install-sh           src
Makefile.am          config.log           lib                  tests
Makefile.in          config.sub           libcurl.pc.in        vc6curl.dsw
Makefile.msvc.names  configure            ltmain.sh            winbuild
# ./configure
checking whether to enable maintainer-specific portions of Makefiles... no
checking whether to enable debug build options... no
checking whether to enable compiler optimizer... (assumed) yes
checking whether to enable strict compiler warnings... no
checking whether to enable compiler warnings as errors... no
checking whether to enable curl debug memory tracking... no
checking whether to enable hiding of library internal symbols... yes
checking whether to enable c-ares for DNS lookups... no
checking for sed... /usr/bin/sed
checking for grep... /usr/bin/grep
checking for egrep... /usr/bin/egrep
checking for ar... no
configure: error: ar not found in PATH. Cannot continue without ar.
#
</code>
It is located on my desktop. Any suggestions? I googled and nothing came up =/
Let me know if this belongs somewhere else...
Answer: For Solaris 10, ar is contained in SUNWbtool package.
For Solaris 11, ar is contained in system/linker package.
Comment: On Solaris 10, you'll also need to add /usr/ccs/bin to your $PATH for the SUNWbtools version.  Solaris 11 moved it to /usr/bin so it's in the default $PATH.
Answer: ar is the GNU archiver
You will need to make sure binutils, which supplies ar, is available on your system.
I'm not familiar with Solaris, but it seems like installing the 'binutils' package should help you out: http://www.opencsw.org/packages/binutils/ .


Relaxing the subgroup requirement for cosets

Question: The definition I have for left cosets is as follows:

Let $G$ be a group and let $H$ be a subgroup of $G$. A left coset of $H$ in $G$ is a set of the form $gH=\{gh:h\in H\}$ for some $g\in G$.

Right cosets are defined similarly.
Is there any purpose in relaxing the requirement that $H$ be a subgroup so that $H$ only needs to be a subset of $G$? If so, what properties of cosets will still hold when this requirement is relaxed?
The only result I have found so far that still holds is $1H=H=H1$. This doesn't seem like a very useful result on its own.
It also seems that the following results won't hold when the requirement is relaxed:

The cardinality of the set of left cosets is equal to the that of the set of right cosets.
The set of left cosets forms a partition of the group $G$.
Lagrange's Theorem (the proof I have seen uses the the fact that the left cosets form a partition of $G$).
Comment: Since different cosets won't be disjoint, I'd say that pretty much everything that's true about cosets of a subgroup can be expected to fail. For example, everything that's based on the idea of choosing a representative element of a coset will fall apart.
Answer: The cosets are defined by the equivalence relation: $g\sim g'\Leftrightarrow g^{-1}g'\in H$. If you consider only subsets of the group $G$, you will not get an equivalence relation, as you can check. As you surmised, you then lose your partition of $G$. So, you really need to use subgroups. Incidently, if you require $H$ to be normal in $G$ the cosets will actually be a group.
Comment: @Anson Hungerford uses the above equivalence relation to define cosets in his algebra textbook.
Comment: Herstein's Modern Algebra  might be another good choice
Comment: You might want to read this: http://math.stackexchange.com/questions/1252108/intuition-behind-quotient-groups/1253636#1253636
Comment: That makes sense. Can I ask if there are any textbook(s) you know of that use the equivalence relation definition? I'm using Abstract Algebra by Dummit and Foote, and occasionally Algebra by Sigler.
Comment: Thanks to both of you. I've already heard good things about both books!


Httpd and selinux - change root dir

Question: I have problem with my centos 7 server and httpd. I have already install http, but i need change home dir from /var/www/html to /home/pawel/domains. I added vhost:
<VirtualHost *:80>
    ServerName local.nauka
    ServerAlias www.local.nauka
    DocumentRoot /home/pawel/domains/nauka
    <Directory "/home/pawel/domains/nauka">
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog /home/pawel/domains/nauka/error.log
    CustomLog /home/pawel/domains/nauka/requests.log combined
</VirtualHost>

I execute this command:
 systemctl enable httpd && systemctl start httpd
 firewall-cmd --permanent --add-service={http,https}
 firewall-cmd --reload
 sudo setsebool -P httpd_enable_homedirs on
 sudo chcon -R -t httpd_sys_content_t ~/domains/
 sudo semanage fcontext -a -t httpd_sys_content_t "/home/pawel/domains(/.*)?"
 sudo restorecon -R ~/domains/
 setsebool -P httpd_can_network_connect 1

When i execute
ls -lZ ~/domains/

i got
drwxr-xr-x. apache apache unconfined_u:object_r:httpd_sys_content_t:s0 nauka

But when i open webrowser with url local.nauka i have
Forbidden

You don't have permission to access / on this server.

What i do wrong?
Answer: By default, SELinux will prevent web server access to user home directories. If you really need the web server to access files in a user home directory, you can set the boolean httpd_read_user_content.
# setsebool -P httpd_read_user_content 1

You apparently set the boolean httpd_enable_homedirs, which does something else entirely.
It's not a good idea to host websites in user home directories though. For example, an exploit of the web server could allow other files than the web site files to be read if you used the above boolean. Also, while you can use that boolean to allow read access, SELinux will never allow the web server to write files to a user home directory. Better to place them elsewhere in the filesystem, such as a subdirectory of /srv/www, where SELinux already permits access with the type httpd_sys_content_t, and directories which will contain uploaded files can be given the type httpd_sys_rw_content_t. This can't be done with user home directories without potentially breaking things.
For example, you can create the directory /srv/www/local.nauka, set its ownership to the user you want, and make any upload directories writable by the web server user with the SELinux context to allow uploads shown above.
Comment: @PawelC I would not use `/var/www` because this directory is used by the default documents shipped with the httpd RPM, and updating that RPM might affect that directory. You can use `/srv/www` which is reserved for that purpose and will have the correct SELinux default context.
Comment: Hi, thanks for reply :) I understand, better solution is stay root directory to /var/www/html?
Comment: Ok :) Thanks for reply, because your answer solved my issue. And in addition I learned a new thing.

Httpd and selinux - change root dir


Execute bazel-buildfarm in a production-ready way without "bazel run"

Question: The readme of Bazel-buildfarm says:
In general do not execute server binaries with bazel run, since bazel does not support running multiple targets.

This sounds like bazel run is designed for local testing-purpose, not for productive servers where multiple jobs could run.
But I couldn't find a documentation showing how to run the bazel server instead. Older Dockerfiles run bazel build and then execute the generated jar-file with java. I tried this on my test machine and got the following error:
[vagrant@localhost bazel-buildfarm]$ java -Djava.util.logging.config.file=/config/logging.properties -jar bazel-bin/src/main/java/build/buildfarm/buildfarm-server.jar
no main manifest attribute, in bazel-bin/src/main/java/build/buildfarm/buildfarm-server.jar

The build before seems working:
[vagrant@localhost bazel-buildfarm]$ bazel build //src/main/java/build/buildfarm:buildfarm-server
Starting local Bazel server and connecting to it...
[...]
INFO: Analyzed target //src/main/java/build/buildfarm:buildfarm-server (94 packages loaded, 1623 targets configured).
INFO: Found 1 target...
INFO: Deleting stale sandbox base /home/vagrant/.cache/bazel/_bazel_vagrant/277990f61896f4bac21fb997fb976b70/sandbox
Target //src/main/java/build/buildfarm:buildfarm-server up-to-date:
  bazel-bin/src/main/java/build/buildfarm/buildfarm-server.jar
  bazel-bin/src/main/java/build/buildfarm/buildfarm-server
INFO: Elapsed time: 11.180s, Critical Path: 0.61s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action

And the jar file exists:
[vagrant@localhost bazel-buildfarm]$ l bazel-bin/src/main/java/build/buildfarm/buildfarm-server
-r-xr-xr-x. 1 vagrant vagrant 17K Nov 11 11:27 bazel-bin/src/main/java/build/buildfarm/buildfarm-server

I just installed bazel using CentOS repo with all dependencies (gcc gcc-c++) and cloned the git repo of bazel-buildfarm. With
bazel run //src/main/java/build/buildfarm:buildfarm-server $(pwd)/examples/server.config.example

the server could at least start successfull:
INFO: Analyzed target //src/main/java/build/buildfarm:buildfarm-server (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //src/main/java/build/buildfarm:buildfarm-server up-to-date:
  bazel-bin/src/main/java/build/buildfarm/buildfarm-server.jar
  bazel-bin/src/main/java/build/buildfarm/buildfarm-server
INFO: Elapsed time: 0.325s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Nov 12, 2019 3:08:13 PM build.buildfarm.server.BuildFarmServer <init>
INFO: buildfarm-server-c6735a2a-2c1b-473e-9d3e-14fe5d01c27d initialized

What am I doing wrong? Or is there another way how to run bazel in a production-ready way?
Platform: CentOS 7.7.1908 with Bazel 1.1.0 on Vagrant
Answer: While I don't know anything specific about buildfarm, you're probably missing a double dash (--) between the target you're running with Bazel and its arguments. Your command line should probably be this:
bazel run //src/main/java/build/buildfarm:buildfarm-server -- $(pwd)/examples/server.config.example


Reinstalled windows, apache will not start

Question: Had to reinstall most of the stuff on my machine, but I had xampp on a separate drive. I started up the control panel and hit start on the apache service, but it will not start.
Here is the error I am receiving. I'm a little confused as to what is happening since I never touched anything on in the xampp folder.
<code>[Tue Nov 29 21:45:33 2011] [error] VirtualHost _default_:443 -- mixing * ports and
non-* ports with a NameVirtualHost address is not supported, proceeding with
undefined results

(OS 10048)Only one usage of each socket address (protocol/network address/port) is
normally permitted.  : make_sock: could not bind to address 0.0.0.0:443
no listening sockets available, shutting down
</code>
Answer: That error indicates that something else is listening on port 443 on your system. Is it possible that an instance is already running? Either way, to see what is going on have a look at netstat -ano, and see which pid is bound to port 443.


I need a Spring AOP pointcut explanation

Question: I have seen two variations of pointcut patterns:
This
execution(* some.package.*.*(..))

and this
execution(* some.package.* *(..))

What is the meaning of the dot (or of it absence) between the last two *'s?
Answer: This appendix defines grammar of the pointcut expression langauge. For the execution expression the rule is the following:
execution(MethodPattern)

where
MethodPattern =
  [ModifiersPattern] TypePattern
        [TypePattern . ] IdPattern (TypePattern | ".." , ... )
        [ throws ThrowsPattern ]

That means that if you have 3 expressions (separated by space) before "(", then the first is modifier, second is class and third is method name. But if you have 2 expressions before "(", then first will be class and second will be method name.
Comment: Now I'm starting to understand it myself :). First TypePattern is actually a return type of the method, second TypePattern is location class of the method.
Comment: Ok, it's getting a little clearer now. But in the production rule I have two places to put a TypePattern, what is the difference between using one or the other? Does it make sense to use both?
Comment: I think there is no difference, but it is a bit confusing to use both type patterns at once. But probably in some situations it may be useful to refer to inner types.
Comment: I actually do think there is a difference, it behaved very differently in a use case I had, but I don't understand the principle behind the difference


How to append values in an array of unknown size in C++?

Question: Just as I do in Python,
arr = []
data = input()
arr.append(data)

I know how to append data in C++ with for loop. But how to initialize an array of unknown size? It's size will depend on number of data points appended in loop section.
Comment: Are you limited to an array? Or can you use `std::vector`?
Answer: Your code actually uses a Python list, not a Python array.
In C++, the closest match to your code would use an std::vector:
// In a header:
#include <string>
#include <vector>

// In your code
auto arr = std::vector<std::string>();
std::string data = "Hello world!";
arr.push_back( data );