What are the main schools of thought on conducting?

Question: Conductor Kevin Purcell writes on his personal website:

There are schools of conducting thought that have evolved over the years.  Some of the more prominent  of these (in no specific order) are the Saito Method (apologies for the lack of diacritic), the Malko and Scherchen inspired techniques and the Russian 'Musin' school.

https://kevinpurcell.com.au/Content/2016/02/is-there-really-a-good-book-on-conducting/
The Saito Method has its own website, but I've found it difficult to find information on the other techniques mentioned here.
What is the distinction between these methods? How do they differ?
Answer: for the Malko technique you should also look for Elizabeth A. H. Green there are videos on Youtube of her demonstrating some of the exercises herself here
as far as I understand the Malko technique tries to develop independent hand technique along with deep musical understanding to make it easier to express what you wish to conduct to players, it consists of standardized exercises and score studies to achieve this goal. You can just watch the video to get an idea I guess, this method is pretty accepted as far as reaching good hand movement goes.
Scherchen has a method book, which I have not read and I am completely unfamiliar with so maybe someone else can explain better.
He only mentioned a few schools of thought on conducting though, currently there is not a unified method for conducting or even a way to evaluate the conductor without a great orchestra to go along with them.


Como permitir acesso à página APENAS por formulário

Question: Tenho uma página no wordpress que existe um formulário, a qual o usuário passa email, nome e estado. Quando a inscrição é completada, eu capturo seus dados numa base (MailChimp, no meu caso) e redireciono para outra página, a qual ele terá acesso a um simulado, por exemplo.
Entretanto, gostaria de que o acesso à essa página redirecionada fosse feito, EXCLUSIVAMENTE, pelo meu formulário descrito.
Pois não quero que haja a possibilidade de digitar na url diretamente o endereço da página redirecionada. Exemplo: dominio.com.br/simulado
Caso o fizesse, ele entraria na home novamente, ou qualquer outra coisa do tipo.
Enfim, como é possível fazer essa restrição?
Comment: Ok, obg! Mas aí volto ao problema inicial (kkkkk). Como, a partir desse cadastro no formulário, posso dar acesso exclusivo à pagina redirecionada?
Comment: Edite a pergunta como eu já disse. PS: talvez sessão somente não resolva teu problema
Comment: Que isso, imagina, agora vou apagar os comentários, já que conseguimos clarear o teu problema e é só aguardar :)
Answer: O WordPress tem uma solução nativa que pode te ajudar: nonces. Na verdade nonces são uma funcionalidade de segurança pra evitar ataques CSRF, mas acho que podem ser uma solução simples pra você.
Na página do seu formulário, inclua dentro do <form> isso:
<?php wp_nonce_field( 'nome_da_acao', '_valida_form' ); ?>

Essa função vai adicionar um input[type=hidden] no seu formulário, contendo um nonce - um valor único e temporário.
Seu formulário vai ser processado em outra página, então no código dessa página, quando receber os dados do formulário, você valida o nonce:
<?php
    $request = wp_unslash( $_REQUEST );

    if ( ! wp_verify_nonce( $request['_valida_form'], 'nome_da_acao' ) ) {
        // o nonce não foi reconhecido, então redireciona para a home
        wp_redirect( home_url('/') ); exit();
    }

    // continua o processamento do formulário e exibe a página

Documentação:
wp_nonce_field()
wp_verify_nonce()


Accessing Variables?

Question: I have an SDI application which creates several modeless dialogs.
Each one of these dialogs can create another modeless dialog called CMyDialog.
All works well except many instances of CMyDialog can be created (from each different original dialog).
I would like to have only one CMyDialog.
The way I have been thinking of approaching this problem is to create a bool flag b_CMyDialog, and then only create a CMyDialog if b_CMyDialog = false.
The problem is I do not know where to put b_CMyDialog variable, and how to access it.
Can someone please help?
Thank you
a.
Answer: Any place in an MFC program can call AfxGetMainWnd() to get a pointer to the main window. So you could put the bool variable there to be able to access it from anywhere.
Better yet, you could put a function there that creates the CMyDialog.
Even better yet, instead of using a bool you can use the pointer to the CMyDialog that you get when you create it. Just make sure you NULL that pointer in the main window constructor and whenever the dialog is destroyed.

Accessing Variables?


Django API "request count" now showing in Azure App Insights > Performance with opencensus

Question: running into an issue where my Django python API application is not logging all metrics to Azure App Insights using opencensus.

But for example, we are getting CPU/memory logging:

I would expect the performance > request count to look similar to this (on a different application framework):

The performance counters section looks pretty straight forward.
My code looks like this:
from opencensus.ext.azure import metrics_exporter

def main():
  INSTRUMENTATION_KEY = os.getenv("INSTRUMENTATION_KEY", "xxx")

  exporter = metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey='+INSTRUMENTATION_KEY)

Answer: I think you need to make sure if your app's requests have been captured and you may refer to this section, Incoming requests, outgoing requests <=> Tracing
Hence, according to the tutorial you provided, I'm new to python, but I assume that you may consider this section?
Comment: @Soccerjoshj07 Thanks for your reply and I'm glad to see it worked for you : )
Comment: this was helpful - thank you for clarifying my misunderstanding! After adding the tracing, we see what we are looking for.


How to send data type map flutter with pusher?

Question: I want to send object data as in the example Pusher 1.0.0, the data to be sent is in the form of a folder and follows my coding :
import 'package:pusher/pusher.dart';

Future<void> mmain(Map data) async {
  Pusher pu = new Pusher('PUSHER_APP_ID', 'PUSHER_APP_KEY',
      'PUSHER_APP_SECRET', PusherOptions(cluster: 'ap1'));
  // Map data = {'message': 'Hello world'};
  Response res = await pu.trigger(['channelTa'], 'tombol', data);
  print(res);
}

and i calling with switch:
child: Switch(
       value: widget.mdata[0]['m' + index.toString()],
       onChanged: (value) {
            setState(() {
               widget.mdata[0]['m' + index.toString()] =value;
               widget.mdata.asMap().forEach((index, value) {
                         String aja = "m$index";
                         tbl.update(aja, (value) => value);
               });
               mmain(tbl);
            });
       }),

what is wrong with my coding so it displays the following error:
Reload already in progress, ignoring request
Restarted application in 4.457ms.
D/PusherPlugin(15412): onCancel args: null
I/flutter (15412): CONNECTING
I/flutter (15412): CONNECTED
E/flutter (15412): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter (15412): {m0: false, m1: false, m2: false, m3: false, m4: false, m5: false}
E/flutter (15412):  ^
E/flutter (15412):
[38;5;244mE/flutter (15412): #0      _ChunkedJsonParser.fail  (dart:convert-patch/convert_patch.dart:1394:5)[39;49m
[38;5;244mE/flutter (15412): #1      _ChunkedJsonParser.parse  (dart:convert-patch/convert_patch.dart:924:48)[39;49m
[38;5;244mE/flutter (15412): #2      _parseJson  (dart:convert-patch/convert_patch.dart:31:10)[39;49m
[38;5;244mE/flutter (15412): #3      JsonDecoder.convert  (dart:convert/json.dart:505:36)[39;49m
[38;5;244mE/flutter (15412): #4      JsonCodec.decode  (dart:convert/json.dart:153:41)[39;49m
[38;5;248mE/flutter (15412): #5      _MyHomePageState._konekpusher.<anonymous closure>[39;49m
[38;5;248mE/flutter (15412): #6      Pusher._handleEvent[39;49m
[38;5;244mE/flutter (15412): #7      _rootRunUnary  (dart:async/zone.dart:1192:38)[39;49m
[38;5;244mE/flutter (15412): #8      _CustomZone.runUnary  (dart:async/zone.dart:1085:19)[39;49m
[38;5;244mE/flutter (15412): #9      _CustomZone.runUnaryGuarded  (dart:async/zone.dart:987:7)[39;49m
[38;5;244mE/flutter (15412): #10     _BufferingStreamSubscription._sendData  (dart:async/stream_impl.dart:339:11)[39;49m
[38;5;244mE/flutter (15412): #11     _DelayedData.perform  (dart:async/stream_impl.dart:594:14)[39;49m
[38;5;244mE/flutter (15412): #12     _StreamImplEvents.handleNext  (dart:async/stream_impl.dart:710:11)[39;49m
[38;5;244mE/flutter (15412): #13     _PendingEvents.schedule.<anonymous closure>  (dart:async/stream_impl.dart:670:7)[39;49m
[38;5;244mE/flutter (15412): #14     _rootRun  (dart:async/zone.dart:1180:38)[39;49m
[38;5;244mE/flutter (15412): #15     _CustomZone.run  (dart:async/zone.dart:1077:19)[39;49m
[38;5;244mE/flutter (15412): #16     _CustomZone.runGuarded  (dart:async/zone.dart:979:7)[39;49m
[38;5;244mE/flutter (15412): #17     _CustomZone.bindCallbackGuarded.<anonymous closure>  (dart:async/zone.dart:1019:23)[39;49m
[38;5;244mE/flutter (15412): #18     _rootRun  (dart:async/zone.dart:1184:13)[39;49m
[38;5;244mE/flutter (15412): #19     _CustomZone.run  (dart:async/zone.dart:1077:19)[39;49m
[38;5;244mE/flutter (15412): #20     _CustomZone.runGuarded  (dart:async/zone.dart:979:7)[39;49m
[38;5;244mE/flutter (15412): #21     _CustomZone.bindCallbackGuarded.<anonymous closure>  (dart:async/zone.dart:1019:23)[39;49m
[38;5;244mE/flutter (15412): #22     _microtaskLoop  (dart:async/schedule_microtask.dart:43:21)[39;49m
[38;5;244mE/flutter (15412): #23     _startMicrotaskLoop  (dart:async/schedule_microtask.dart:52:5)[39;49m
E/flutter (15412):
I/flutter (15412): {}

pusher only returns empty json
Answer: The issue is that your "data" value is not valid JSON. From the stacktrace I can see that you are passing in:
{m0: false, m1: false, m2: false, m3: false, m4: false, m5: false}

This isn't being parsed as JSON.
The mN (m0 etc) keys need to be in double quotes e.g.
{"m0": false, "m1": false, "m2": false, "m3": false, "m4": false, "m5": false}

You can check this here - https://jsonformatter.curiousconcept.com/
In your code add the quotes as follows:
String aja = '"m$index"';

or
String aja = "\"m$index\"";

Comment: thank you @Chris C, it doesn't work well, I've followed your instructions until I have to repeat it several times.


Proximity Search

Question: So i'm trying to set up an online store kinda thing. The user uploads items and others see it in their news feed. I want items listed based on the location proximity of the user.
Say there are 3 people accessing the news feed. The item closest to that person should come up first in the news feed.
I'm getting the location of the user during registration and i want this location to get attached with the item.
Answer: I once put together a similar system for users physically near each other to find and contact each other, but the best way I ever came up with was to store every distance in the database.
Essentially, I saved the lat/lon location (via the Google Maps API) of each user when they registered. Then (via cron) I calculated that user's distance from every other user and saved that distance in a custom table. That allowed me to simply query the database sorting by shortest distance.
This requires a substantial amount of overhead, depending on the number of users (and items, in your case), but it worked reasonably well.
I know that some databases have custom geo data types now, that allow this kind of query automatically, but that's somewhat outside the realm of Drupal.

Proximity Search


If score is higher than 5 then

Question: So if my score is higher than 5 then gotoSceneA elseif gotoSceneB.
But I am getting this error:
game.lua:439: unexpected symbol near '..'*

If i remove the .. I get:
game.lua:443: 'then' expected near 'end'

My code:
if .. score > 5 then
    storyboard.gotoScene("bonus", "fade", 400)
elseif
    storyboard.gotoScene("gameover", "fade", 400)
end
end

Comment: Please change `elseif` to `else`. Also, you should remove the `..`.
Comment: Also, You should remove last line with an `end`.
You don't need multiple ends for one `if then/else` statement.
Answer: if score > 1000 then
    storyboard.gotoScene("bonus", "fade", 400)
else
    storyboard.gotoScene("gameover", "fade", 400)
end

If score is higher than 5 then


Centos 6 to Centos 7 cgroups

Question: I'm trying to set up resource limits per user in Centos 7, but I can't find the right commands for the new implementation of cgroups (I did read the documentation but it talks about restricting services not users).
This are the steps in Centos 6

Add to /etc/cgconfig.conf
group mygroup{
    cpu {
            cpu.shares = 200;
    }
    memory {
            memory.limit_in_bytes = 128m;
    }
}
Restart service cgconfig restart
Start in system boot: chkconfig cgconfig on
Verify groups added correctly: lscgroup
Add the processes for which we wish to limit resources to the cgroups we created: add to /etc/cgrules.conf
myuser       cpu,memory      mygroup/
start the cgred service for the cgrules configuration changes to take effect: service cgred start
make sure the cgred service is enabled to start on system boot so that our rules persist across reboots: chkconfig cgred on

What is the equivalent in Centos 7?
Comment: @MichaelHampton I did read that documentation but it talks about restricting services, not users.
Comment: [Read the documentation, of course.](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Resource_Management_Guide/index.html)
Comment: you can use the cgroup with systemd
Comment: @c4f4t0r I have no idea how to use the cgroup with systemd to replicate the steps above
Answer: Please try for example
systemctl set-property user-1000.slice CPUShares=100

Assuming you wish to limit the resource for UID 1000 and limit the CPUShares.
Answer: After install : yum install libcgroup-tools
commands lscgroup and cg*, files /etc/cg* are available.
Comment: that method is considered deprecated and I'd like to know the new recommended way to do it in Centos 7

Centos 6 to Centos 7 cgroups


Connecting to MSSQL on EC2 from local

Question: Has anyone ever managed to connect to Microsoft SQL Server (preferably 2008) hosted on Amazon EC2 from Management Studio on your development machine?
I have set up the security group to allow port 1433, opened port 1433 outbound from Windows Firewall to no avail.
Error from Management Studio is '26 - Error Locating Server/Instance Specified'. I am using the associated Elastic IP address as the server name.
Tried searching 'sql-server ec2', but no similar problem found.
The server is accessible from local EC2 Management Studio.
Answer: Is the server configured to listen on the public IP of the EC2 instance? A local EC2 SSMS would connect using Shared Memory protocol.
Needles to say, opening a SQL Server for internet is a really bad idea. Your TDs port will be subject to constant bot scans and your ERRORLOG will fill with failed 'sa' attempts. You do have a very strong sa password, don't you? At the very leats, use a non-default port.
Comment: Instance has Shared Memory and TCP/IP protocols enabled.

I'm trying to use default values here first and make sure it's working. Afterwards, secure them. If it doesn't even work, I don't think anything is worth securing.
Comment: Did you open the port 1433 from EC2 firewall (in the group security settings)?
Answer: Check list to enable connection:

First of all, determine the port number that you want to access to (default is 1433 but you may want to change this. For this example, I picked 5555.)
Allow connection to this port on EC2 Security Group. Add TCP/5555-5555/all.
Allow inbound connection to this port on Windows Firewall. Add a new rule on that port (and you may want to specify sqlservr.exe as the program).
Enable TCP/IP protocol on SQL Server Configuration Manager and set static port. To do this, go to the IP Addresses tab on the protocol property, scroll down to IPAll, blank the TCP Dynamic Ports and set the port that you want in the TCP Port property.

You're all set.
Comment: We should not recommend opening 1433 to all IPs.  It should be restricted to the corporate IP range and/or AWS hosted VPN or some sort of Bastion solution.

Connecting to MSSQL on EC2 from local


Continuity+differentiability imply weak sequential continuity?

Question: Let $E$ and $F$ be two Banach spaces. We know that, if $f:E\rightarrow F$ is a nonlinear continuous operator, then $f$ may fail to send weakly convergent sequences to weakly convergent sequences, i.e., $u_n \rightharpoonup u$ weakly in $E$  does not necessarily imply $f(u_n)\rightharpoonup f(u)$ weakly in $F$. Even through $f$ has very mild non-linearity,  this weak sequential continuity may fail. For example, let $u_n(x)=\sin(nx), x\in (0,2\pi)$. Then Riemann-Lebesgue lemma shows that $u_n\rightharpoonup u= 0$ in $L^p(0,2\pi)$ for any $p\geq 1$.
Now, for $f(u)=\max(0,u)=u^+$, one has
$$f(u_n)\rightharpoonup \frac{1}{\pi}\neq f(u)=0  \text{ in } L^1(0,2\pi).
$$
Also,
$$
\int_0^{2\pi}f(u_n(x))dx=\int_0^{2\pi}\sin^+(nx)dx=\frac{1}{n}\sum_{k=0}^{n-1}\int_{2k\pi}^{(2k+1)\pi}\sin (y)dy=2,
$$
which implies $f(u_n)$ can not converge weakly to  $0=f(u)$ in $L^2(0,2\pi)$.
If $g(u)=|u|$, then
$$g(u_n)\rightharpoonup \frac{2}{\pi}\neq g(u)=0  \text{ in } L^1(0,2\pi).
$$
From these two examples, we see there is no general hope that a continuous map  preserves weak sequential continuity. We are wondering what kind of conditions imposed on $f$ so that it preserves weak sequential continuity.  For the two examples above, we note that both $f$ and $g$ are sub-linear ($|f(u)|\leq c|u|$ for some  constant $c>0$),  continuous but not differentiable. Now, a natural question arises: whether a sub-linear ($|f(u)|\leq a|u|+b$ for some positive constant $a$ and non-negative constant $b$), continuous and differentiable map $f:E\rightarrow F$ preserves weak sequential continuity? Here, we emphasize the non-linearity of $f$, since, for linear map $f$, it is known from functional analysis this question holds. For this question, one can choose $E$ and $F$ to be Hilbert spaces, for convenience. As concrete examples, one may test: 1. $u_n\rightharpoonup u$ with $u_n\geq 0$ in $L^2(\Omega)$ and $f(u)=\frac{u}{1+u}$, do we have $f(u_n)\rightharpoonup f(u)$ in $L^2(\Omega)$? 2. $u_n\rightharpoonup u$ in $L^2(\Omega)$ and $g(u)=\frac{u}{1+u^2}$, do we have $g(u_n)\rightharpoonup g(u)$ in $L^2(\Omega)$? Thank you for your effort!
Answer: Thank user 37238 first. Actually, the example listed in the last sentence  has already illustrated that the question is not true. Here, I make it more clear. Consider the sequence $u_n(x)=\sin(nx)$. Then $u_n\rightharpoonup 0:=u$ in $L^2(0,2\pi)$. Now, by a known result about weak limits of rapidly oscillating periodic functions, we have
$$
f(u_n(x)):=\frac{u_n(x)}{2+u_n(x)}=\frac{\sin(nx)}{2+\sin(nx)}\rightharpoonup \frac{1}{2\pi}\int_0^{2\pi}\frac{\sin(x)}{2+\sin(x)}dx\neq 0=f(u) \text{ in } L^2(0,2\pi).
$$
Of course,, $f$ is sub-linear, continuous and differentiable. As answered by User37238, it seems that, if $u_n\rightharpoonup u$ implies $f(u_n)\rightharpoonup f(u)$, then we must necessarily have $f$ is affine?
Answer: Here is an example (from Brézis' book Functional Analysis, Sobolev Spaces and Partial Differential Equations exercise 4.20) that shows that it is much more restrictive than you think :
Take $\Omega = (0,1)$ and $a : \mathbb{R}\to \mathbb{R}$ a continous function such that
$$ |a(t)|\le a|t|+b$$
and define $A : L^2(\Omega)\to L^2(\Omega)$ by $(Au)(x) = a(u(x))$ for almost every $x\in \Omega$. Then you can show that $A$ is strongly continuous.
Suppose now that for every sequence $(u_n)$ such that $u_n \to u$ weakly in $L^2(\Omega)$, we have $Au_n \to Au$ weakly in $L^2(\Omega)$.
Then you can show that $a$ is necessarily an affine function.
Sketch of the proof :
First define $f$ a function $1$ periodic such that
$$f = \left\{\begin{array}{rcl}
\alpha &\text{on}& (0,1/2) \\
\beta &\text{on}& (1/,2) \\
\end{array} \right. $$
where $(\alpha,\beta)\in\mathbb{R}^2$. Then define $u_n : x\in (0,1) \mapsto f(nx)$ and show that $u_n$ converges weakly in $L^2$ towards $\frac{\alpha+\beta}{2}$.
Using this $u_n$, you can show that
$$\forall(\alpha,\beta)\in \mathbb{R}^2,\ \frac{a(\alpha)+a(\beta)}{2} = a\left( \frac{\alpha+\beta}{2}\right) $$
Finally, you get $a$ affine from the previous equation.
Comment: I do not think your $A$ is weakly sequentially continuous. Modify the example above. Let $a(t)=\max(0,t)$ and $u_n(x)=\sin(2n\pi x)$. Then $u_n\rightharpoonup 0$ weakly in $L^2(0,1)$, but $A(u_n)$ can not converge weakly to $0=A(u)$ in $L^2(0,1)$.
Comment: @teh What I say is if you want $A$ to be weakly sequentially continuous then $a$ has to be an affine function. That's why your example does not work.
Comment: So, you meant for a sublinear function $a$, in order $(Au)(x)=a(u(x))$ to be weakly sequentially continuous, we must have $a$ is affine? If this is the case, the question above may not be true.  Then how to show $a$ is an affine function? Could you show this?
Comment: Yes it is what I meant.


Preorder on real-valued random variables

Question: We say that $X$ is smaller than $Y$ in distribution (which we denote by $X \stackrel{D}{<} Y$) if $\mathbb{E}[h(X)] \leq \mathbb{E}[h(Y)]$ for all positive, increasing and bounded functions $h$.
We say that $X$ and $Y$ are equal in distribution (which we denote by $X \stackrel{D}{\sim} Y$) if $X \stackrel{D}{<} Y$ and $Y \stackrel{D}{<} X$
I've already answered the following question :

Prove that $X \stackrel{D}{<} Y$ if and only if the cumulative
  distribution functions $F$ and $G$ of $X$ and $Y$ respectively
  satisfy $F \geq G$

Indeed, it suffices to take $h(x) = 1\!\!1_{x \geq c}$ for different values of $c$.
But I don't know how to answer the following two questions :

Prove that $X \stackrel{D}{<} Y$  if and only if we can find two random variables $X'$ and $Y'$ such that $X \stackrel{D}{\sim} X'$, $Y \stackrel{D}{\sim} Y'$ and $X' \leq Y'$ a.s.
Suppose that $X \leq Y$ a.s. and $X \stackrel{D}{\sim} Y$. Prove that $X = Y$ a.s.

Can I have some help on these two questions ?
Answer: For 3 we are assuming $X,Y$ lie on the same space, say $\Omega$. Since these variables are real-valued, $Y(\omega)>X(\omega)$ implies there is some $q\in\mathbb{Q},n_0\in\mathbb{N}$ s.t. $Y>q+1/n,X<q-1/n$ when $n>n_0$. So
$$
P\{X<Y\}\le P(\cup_{q,n_0}\cap_{n>n_0}\{Y>q+1/n,X<q-1/n\})\le \sum_{q,n_0}P(\cap_{n>n_0}\{Y>q+1/n\text{ and }X<q-1/n\})=\sum_{q,n_0}P(Y>q\text{ and }X<q)=\sum_{q,n_0}(P(Y>q)-P(X>q))=0.
$$
In the first equality I used that $\cap_{n>n_0}\{Y>q+1/n,X<q-1/n\})\uparrow\{Y>q,X<q\}$ as $n_0\to\infty$, for the second equality I used that $X<Y$ a.s., and for the last equality I used $Y\sim X$.
For 2 the skorokhod representation might do the trick. Speaking loosely, given a cdf $F$, flip the $x$ and $y$ axes, giving you a variable $Z$ defined on the unit interval with lesbesgue measure such that the cdf of $Z$ is $F$ (you need to handle details like where $F$ is constant). So let $X',Y'$ be the skorokhod representations of $X,Y$, then $X',Y'$ have the same distributions as $X,Y$, then by 1 they are equivalent under the pre-ordering to $X,Y$ (respectively). Also by 1, $F_{X}\ge F_{Y}$, so when you "flip" the axes to get the skorokhod representations, $Y'>X'$ a.s.
Comment: Thanks for 2 and 3. For 3, I think that you have to change some "<" to "$\leq$" (and ">" to "$\geq$") but I got the idea. For 2, it seems OK but I'm waiting for a more elementary solution.


What is the connection between the two ways in which functions get represented as vectors when discussing inner product?

Question: When I interpret the inner product and orthogonality of two functions, I consider it the following way. Say you have a basis for a function space
$\{\sin(x), \cos(x)\}$ and you have two vectors $u = (2,2)$ and $v = (-1,1)$ representing the functions $2\sin(x)+2\cos(x)$ and $-\sin(x)+\cos(x)$ respectively.
These vectors $u$ and $v$ are orthogonal on the function space defined by the basis. Hence the functions they represent are orthogonal on some interval, in this case $[-\pi,\pi]$, why? I dont really know.
But that was just a side question, my main is that is in other texts I have seen when defining the inner product, the functions are being sampled at different points. A function $f(x)$ is sampled at points $t_0, t_1, ... t_n$ and it is represented by a vector $(f(t_0), f(t_1), ... f(t_n))$. And then you can represent another function  as the vector $(g(t_0), g(t_1), ... g(t_n))$. And define the inner product of the functions $f$ and $g$ as the dot product between these vectors as
$f(t_o)\cdot g(t_o) + f(t_1)\cdot g(t_1) + ... + f(t_n)\cdot g(t_n)$.
My question is what is the connection between the vectors $u,v$ and the sampled vectors? Both of these pairs of vectors represent the same thing. If the functions are orthogonal then dot product between these pairs are 0. But I still cant see the link between them.
I'll give an example of how the text I have read defines the inner product by sampling....
Consider $p(t) = 2t^2 - t + 1,   q(t) = 2t-1$. These functions can be defined on a function space by the basis {$1, t, t^2$}. And this is how my text defines the inner product between these functions, I quote:
"Step 1: You should first sample the polynomials at the values -1, 0, and 1. The
samples of each polynomial will give you a vector in $R^3$."
"Step 2: You take the dot product of the two vectors created by sampling. (As a
variation, this step could be a weighted inner product)"
Comment: Edited post, it was meant to be a multiplication
Answer: You  can define the inner product between vectors (functions, in this case) in many ways, as long as the axioms are satisfied (see inner product space). One way is by considering the integral of the product over a finite range, others multiply a third fixed function in, ... All those are different inner product spaces (as the inner product is different), even if the vector spaces (functions in your example) are the same; it makes little sense to try to use the inner product of one in the other.
Answer: I think you are getting bogged down in switching back and forth between different spaces. Orthogonality is all defined in a single space. Looking at an example like yours, if you have a space with two orthonormal vectors $v_1,v_2$, and $(a_1,a_2)$ and $(b_1,b_2)$ are two orthogonal vectors in $\mathbb{R}^2$, then $a_1v_1+a_2v_2$ is orthogonal to $b_1v_1+b_2v_2$. That comes about by expanding the inner product using bilinearity, and canceling out any terms which involve $v_1$ and $v_2$ using their orthogonality. Thus $(a_1v1+a_2v_2,b_1 v_1+b_2v_2)=a_1 b_1 + a_2 b_2 = 0$ by the orthogonality in the plane. But this only works if $v_1,v_2$ are orthogonal and have the same norm.
I don't think I understand your question about sampled functions.
Comment: With sampling I was just refering to representing the function as a vector with the functions values at different points
Comment: @ArnoldDoveman But that's not a representation of the whole function, it's just a vector constructed from the function.
Answer: Your $u$ and $v$ are finite linear combinations of some base functions.
The sample vector with components $f_i = f(t_i)$ is in general an approximation for $f$ and the one with components $g_i = g(t_i)$  in general an approximation for $g$.
It depends on the properties of $f$ and $g$ and the used number of samples, if the original functions can be reconstructed fully.
E.g. see Whittaker-Shannon interpolation formula.
So it could be the case (or not) that some function $f$ has an exact representation as $u$ and thus the two coordinates you mention, and some set of samples, which can be seen as $N$ coordinates.


Graphing Polar equation

Question: I was plotting graphs on Desmos, I plotted $r=a+sin(\theta)$ and it rightfully spit out a cardiod at $a=-1$ and $a=1$
Then when I was sliding the values of $a$,  it spits out a limacon for $-1<a<1$($a\neq0$)
Then I notice a weird thing that is when I was sliding the value between $1<|a|<3$ it was spitting out something between cardiod and a circle. What is it called?
For values $|a|>3$ it was mapping circles. Why does this back and forth happen between circles, limacons, cardiodes and the unknown shape?
Comment: @ViktorGlombik I had to ask for the term because I can't keep referring to it as unknown shape. So, term is a cheeky question there. The profound one is the base of the post
Comment: A circle is $r=a$, hence your curve is not one.
Comment: @YvesDaoust yes, the two answers have cleared my doubts. However, $r=asin(\theta)+bcos(\theta)$ can also be a circle.
Comment: @Rifat: that's right, but through the origin rather than centered on the origin.
Answer: The figure is called a limaçon for all $a \neq 0$, in particular it's called a cardioid for $|a|=1$. In general, the polar equation $r = a + b\sin\theta$ produces a limaçon when $a,b \neq 0$, and a cardioid when $|a/b|=1$.
What it doesn't produce is circles. Remembering $r^2 = x^2 + y^2$ and $r\sin\theta = y$, we find
$$x^2 + y^2 = r^2 = r(a + \sin \theta) = a \sqrt{x^2 + y^2} + y $$
and thus
$$(x^2 + y^2-y)^2 = a^2(x^2 + y^2) $$
which is the Cartesian equation of a quartic curve for all $a \neq 0$ (for $a=0$ it does simplify to a degree 2 equation, specifically that of a circle, but you're excluding that case). It would however describe a proper circle for all $a \neq 0$ if the $-y$ term on the LHS weren't there.
Comment: Thank you so much, it was looking so close to a circle, so I kind of thought it would be, but now I checked, the chords aren't always the same length from the same distance from the center
Answer: In fact, all of these graphs are limaçons. The generic equation for a limaçon in polar coordinates is $r = a + b \cos (\theta)$ for a limaçon oriented horizontally, along the $x$-axis, or $r = a + b \sin(\theta)$ for a limaçon oriented vertically, along the $y$-axis. There are different types of limaçons, depending on the relationship between $a$ and $b$ in the polar equation.

If $a < b$ then you will have a looped limaçon
If $a = b$ then you will have a cardioid. A cardioid is actually a type of limaçon, i.e. the only limaçon that has a cusp.
If $b < a < 2b$ then you will have a dimpled limaçon. This is the "weird thing" you noticed when you had the slider in the range roughly between $1$ and $3$.
If $a \ge 2b$ then you will actually have a convex limaçon. At exactly $a=2b$, the dimple will flatten out, and if $a > 2b$, then it will even start to bow outwards again... however, it is still not a circle! As $a \gg 2b$, the difference between the limaçon and a circle is hardly discernible, but it is there.

You can tell that your limaçon is not a circle, by plotting an actual circle with similar parameters (Desmos link), and (1) noticing the difference between the two equations, and (2) noticing the visual difference on a graph. Move the sliders for $a$ and $b$ to scale the limaçon. See how, for $a \ge 2b$, it looks quite circleish, but remains very slightly "fatter" along the horizontal direction than a true circle.
Comparing the polar-form equations gives more insight into why exactly this happens.
Before we get into that, however, I'll just take a brief detour and show the derivation for the circle equation in the first place. I simply started with the Cartesian equation for a circle of radius $a$ centered at $(0, b)$, and converted to polar coordinates. (EDIT: this derivation is only for the inscribed circle; I have added also the circle circumscribed about the limaçon to the Desmos graph, but I will not show the derivation of that circle here.)
\begin{align}
  x^2 + (y-b)^2 &= a^2 \\
  x^2 + y^2 - 2by + b^2 &= a^2 \\
  r^2 - 2br\sin(\theta) &= a^2 - b^2 \\
  r^2 - 2br\sin(\theta) + b^2\sin^2(\theta) &= a^2 - b^2 + b^2\sin^2(\theta) \\
 (r - b\sin(\theta))^2 &= a^2 - b^2(1 - \sin^2(\theta)) \\
  r &= b\sin(\theta) + \sqrt{a^2 - b^2\cos^2(\theta)}
\end{align}
OK, now that that's out of the way - let $r(\theta)$ be the limaçon, and let $\hat{r}(\theta)$ be the circle (the equation we just found a moment ago), as polar functions of $\theta$. To make the difference between them crystal clear, we can do a little convenient rearranging, and write both equations in terms of the ratio $a/b$, so that as $a/b\to\infty$, the limaçon gets closer to the circle.
First, the limaçon:
\begin{align}
  r(\theta) &= a + b\sin(\theta)  \\
      &= b\left( \sin(\theta) + \frac{a}{b} \right)  \\
\end{align}
And second, the circle:
\begin{align}
  \hat{r}(\theta) &= b\sin(\theta) + \sqrt{a^2 - b^2\cos^2(\theta)}  \\
      &= b\left( \sin(\theta) + \sqrt{\left(\frac{a}{b}\right)^2 - \cos^2(\theta)} \right)  \\
      &\approx b\left( \sin(\theta) + \sqrt{\left(\frac{a}{b}\right)^2} \right)  \text{ if }a\gg b \\
      &\approx b\left( \sin(\theta) + \frac{a}{b} \right) = r(\theta)
\end{align}
As $a$ becomes very much larger than $b$, the ratio $a/b\to\infty$. On the other hand $-\cos^2(\theta)$ will never be less than $-1$ or greater than $0$. So for $a\gg b$, this term becomes essentially insignificant; it is "dwarfed" by the enormous $a/b$ term under the square root. This term, which is tiny for $a\gg b$, is where the difference between your almost-circle limaçon & a true circle enters in.
Comment: Wow! I couldn't thank enough. This clears each and every doubt I had. So structured and beautifully classified and written. And the desmos link is just amazing.
Comment: @Rifat Thank you kindly sir :) I am glad to have been of help! If you are interested, I have made one small tweak to the Desmos graph. The old version only had the inscribed circle - the one that just touches the inside of the limaçon. This was because the equation of the inscribed circle was the easiest to think of and explain in my answer. Now I added the circumscribed circle as well - the one that just touches the *outside* of the limaçon. If $b=1$ and $a\ge 3$, then the difference in their radii will be less than $5\%$.

Graphing Polar equation


Changing the properties of the active control automatically

Question: Please consider that im a newcomer to c#. After scanning about 700 posts i decided to post one more question:
On my windows form (c#) I have some controls including textboxes, checkboxes and so on.
I want to change the backcolor whenever the controls become active.
I know i could raise 'enter' and 'leave' events for each control to change the corresponding properties but there should be another way.
Answer: Simply hook Enter and Leave events - toggling the color in each.  Save the last color saved in OnEnter to use in OnLeave
public Form1()
{
    InitializeComponent();

    var lastColorSaved = Color.Empty;

    foreach(Control child in this.Controls)
    {
        child.Enter += (s, e) =>
                            {
                                var control = (Control)s;
                                lastColorSaved = control.BackColor;
                                control.BackColor = Color.Red;
                            };
        child.Leave += (s, e) =>
                            {
                                ((Control)s).BackColor = lastColorSaved;
                            };
    }
}

Comment: I appreciate your reply and tried out the code, but get an error message: The name parent doesnt exist in the current context. I'm learning from each example posted so it would be very helpful if you could revise your code.
Comment: Many thanks for your effort. Now I'm going to check why the code didn't accept 'Form1' instead of 'this'.
Answer: You customize control classes just like you customize any class, you derive your own class and override the virtual methods.  Arbitrarily:
using System;
using System.Drawing;
using System.Windows.Forms;

class MyTextBox : TextBox {
    protected override void OnEnter(EventArgs e) {
        prevColor = this.BackColor;
        this.BackColor = Color.Cornsilk;
        base.OnEnter(e);
    }
    protected override void OnLeave(EventArgs e) {
        this.BackColor = prevColor;
        base.OnLeave(e);
    }
    private Color prevColor;
}

Now any MyTextBox you drop on the form will have this behavior without having to implement events.  Although there's certainly nothing wrong with using events.
Answer: Create a class (eg. ControlColorizer) and in its constructor pass:
1) The backcolor for the 'active control' and save to a internal Color variable
2) a variable length Control array
In the contructor add the same event handler for OnEnter and OnLeave  on each control
In the OnEnter event set the backcolor
In the OnLeave event set the standard background color
The advantage is all in the use of the class:
1) Declare a global instance in your form class
2) Initialize in the form contructor after the InitializeComponent.
3) Forget everything else. No other code required
So let me explain everything with code:
This will go in a file called ControlColorizer.cs
public class ControlColorizer
{
    private Color _setBColor = SystemColors.Window;

    public ControlColor(Color bkg, params Control[] ctls)
    {
        _setBColor = bkg;
        foreach (Control o in ctls)
        {
            o.Enter += new EventHandler(o_Enter);
            o.Leave += new EventHandler(o_Leave);
        }
    }

    private void o_Enter(object sender, EventArgs e)
    {
        if (sender is Control)
        {
            Control c = (Control)sender;
            c.BackColor = _setBColor;
        }

    }
    private void o_Leave(object sender, EventArgs e)
    {
        Control c = sender as Control;
        c.BackColor = SystemColors.Window;
    }

Now, in every form contructor where you need the functionality you have this
ControlColirizer _ccz;
public Form1()
{
    InitializeComponent();
    // Create an instance of ControlColorizer, pass the background color
    // the list of Controls and that's all
    _ccz = new ControlColorizer(Color.LightYellow, this.TextBox1,
               this.TextBox2, this.TextBox3, this.TextBox4);
}


Como pegar texto de uma Span com Class [VB.NET]

Question: 0

Esse é o código.
Preciso pegar o resultado "0" e colocar em uma Label.
Porém as vezes pode ter ex: 10 (2 números) e o código vai ser:
1
0

Ou seja 2 span class separadas.
Tem como pegar todas as Span Class "odemeter-value" e jogar tudo pra uma Label?
Obrigado pela atenção.
Comment: Você vai ler esse código a partir de um WebBrowser?
Comment: O webbrowser precisa estar presente sim, mas está em enable=off
Comment: No caso um botão teria que usar o WebBrowser1.GetElementById pegar todas as span/class iguais e me dar o resultado em um textbox ou label.
Answer: Se entendi bem, isso resolve seu problema

function teste(){

    var textSpan = document.getElementsByClassName('odometer-value')
    var textLabel = document.getElementById('mylabel').textContent;

    for (let index = 0; index < textSpan.length; index++) {
        const element = textSpan[index];
        textLabel = textLabel + element.textContent;
    }
    document.getElementById('mylabel').innerHTML = textLabel;

}
window.onload = teste();
3
    1
    0

    minha label:


Prob. 7, Chap. 5 in Baby Rudin: If $f^\prime(x)$, $g^\prime(x)$ exist, $g^\prime(x)\neq 0$ and $f(x)=g(x)=0$, ...

Question: Here is Prob. 7, Chap. 5 in the book Principles of Mathematical Analysis by Walter Rudin, 3rd edition:

Suppose $f^\prime(x)$, $g^\prime(x)$ exist, $g^\prime(x) \neq 0$, and $f(x) = g(x) = 0$. Prove that $$ \lim_{t \to x} \frac{ f(t) }{g(t)} = \frac{f^\prime(x)}{g^\prime(x)}.$$ (This holds also for complex functions.)

My Attempt:

As $f(x) = g(x) = 0$ ans as $f^\prime(x)$ and $g^\prime(x)$ exist, with $g^\prime(x) \neq 0$, so we have
  $$
\begin{align}
\lim_{t\to x} \frac{f(t)}{g(t)} &= \lim_{t\to x} \frac{f(t) - 0 }{g(t) - 0 } \\
&= \lim_{t \to x} \frac{ f(t) - f(x) }{ g(t) - g(x) } \\
&= \lim_{t \to x} \frac{ \frac{f(t) - f(x)}{t-x}}{ \frac{g(t)-g(x)}{t-x}} \\
&= \frac{\lim_{t \to x} \left(  \frac{f(t) - f(x)}{t-x} \right) }{ \lim_{t \to x} \left( \frac{g(t)-g(x)}{t-x} \right) } \\
&= \frac{f^\prime(x)}{g^\prime(x)}.
\end{align}
$$

Is this reasoning correct? If so, I reckon the above calculation is valid for complex as well as real functions $f$ and $g$. Am I right?
I'm afraid we cannot resort to the Generalized Mean Value Theorem here even for real functions $f$ and $g$ because we have no information about the continuity of $f$ and $g$ in any interval containing $x$ or about the differentiability of these functions in a segment around $x$.
Please refer to a questions of mine at Math SE at the following link.
Any example of a function which is discontinuous at each point in a deleted neighborhood of a point at which that function is differentiable?
Am I right?
Comment: Yes, it's correct. You don't need the mean value theorem, just the fact that the limit of a quotient is the quotient of the limits, when the denominator has limit $\ne0$.
Comment: @JaideepKhare thank you for your edit, but I'd prefer to keep the problem and chapter reference alongwith that of the text.
Comment: That Information isn't needed in the title, someone interested can easily get that information from the main body of the question... But ultimately it's your question and you can edit the title as you wish!
Comment: @JaideepKhare so nice of you!
Answer: You surely can't invoke the mean value theorem.
The right tool is: suppose $\alpha$ and $\beta$ are functions defined in a punctured neighborhood of $x$ and that
$$
\lim_{t\to x}\alpha(t)=l,\qquad \lim_{t\to x}\beta(t)=m\ne0
$$
Then $\alpha(t)/\beta(t)$ is defined in a punctured neighborhood of $x$ and
$$
\lim_{t\to x}\frac{\alpha(t)}{\beta(t)}=\frac{l}{m}
$$
(which is what you essentially used).


MVC Net Core with Docker Containers Problems

Question: I am creating a simple MVC Net Core app with C# backend, and ASP CSS/html/Razor front end. It is a simple start project where customers can create orders, buy books, and place into a shopping cart. Previous question discussed the benefits. However, what problems or limitations would have if introducing Docker in the workplace? Anything I need to tell manager before incorporating into a corporate setting for simple application? I read Docker contains may have issues with security settings or talking with other micro service apps.
Prior Question:
MVC Net Core with Docker Containers Benefits
Answer: I'd suggest googling for success stories. For example https://apiumhub.com/tech-blog-barcelona/top-benefits-using-docker/
Security is not such a big issue. Your software needs to be as secure as it needs to be when running on the host directly plus you get some level of resource isolation (memory, filesystem, etc.). This doesn't free you from writing secure code in the first place, but is an additional advantage.
Container to container networking on the same host is quite easy as docker provides the addresses of other containers as environment variables. On a larger scale with multiple servers you need to think about service discovery and maybe load balancing.
But start small and try it on your local machine, start dockerizing your app and use docker images to test your software. When that is established, you can try to move it into production. Also here you can start with a smaller microservice and get some experience in production before trying to migrate a huge mission-critical software in a big bang scenario.


Spivak Calculus 5-23

Question: Consider a function $f$ with the following property: if $g$ is any function for which $\lim_{x\to 0}g(x)$ does not exist, then $\lim_{x\to 0} f(x)g(x)$ does not exist.  Prove that this happens iff either $\lim_{x\to 0} f(x)$ exists and is $\neq 0$ (condition 1) or $\lim_{x \to 0} |f(x)| = \infty$ (condition 2).
My attempt:
I did not have any trouble proving the converse (proving condition 1 implies $f$ has the property and proving condition 2 implies $f$ has the property).  I am not sure how to proceed to prove the other direction (want to know how to prove that if $f$ has the property, then it must either satisfy condition 1 or condition 2).
The textbook states to consider the contrapositive (if neither of these two conditions holds, then there is a function $g$ such that $\lim_{x \to 0} g(x)$ does not exist but $\lim_{x\to 0} f(x)g(x)$ does exist.)
It further hints to consider separate cases: (case 1) for some $\epsilon>0$ we have $|f(x)|>\epsilon$ for all sufficiently small x. (case 2) for every $\epsilon>0$ there are arbitrary small x with $|f(x)|<\epsilon$.  In the second case, begin by choosing points $x_n$ with $|x_n| < 1/n$ and $|f(x_n)|<1/n$.
I have two main questions:

how do I formally negate the two conditions in an attempt to prove the contrapositive (is it just [$\lim_{x \to 0} f(x)$ does not exist or $\lim_{x \to 0} f(x) = 0$] and [$\lim_{x \to 0} f(x) \neq \infty$] ?)
I have no clue why we would consider those 2 cases
Comment: If a limit is $\infty$, do we say the limit exists or not? What's the convention in the book?
Comment: It states that the limit does not exist if it's $\infty$
Answer: Assume that for every $g$ such that $\lim_{x\to 0}g(x)$ does not exist, we also have that $\lim_{x\to 0}f(x)g(x)$ does not exist. Towards a contradiction, suppose that both condition 1 and condition 2 fail. This means:

Either $\lim_{x\to 0}f(x)$ does not exist, or $\lim_{x\to 0} f(x)=0$.
It is not true that $\lim_{x\to 0}|f(x)|=\infty$.

We now proceed by cases as in the hint:
Case 1: For some $\varepsilon>0$ and some $\delta>0$, we have that $|f(x)|>\varepsilon$ for all $x$ with $|x|<\delta$. Consider the function $g=\frac{1}{f}$, defined in $(-\delta,\delta)$.
Claim: $\lim_{x\to 0}g(x)$ does not exist.
Proof: There are two possibilities. If the limit exists and is non-zero, then the same is true of $\lim_{x\to 0}\frac{1}{g(x)}$, which contradicts 1. The other option is that $\lim_{x\to 0}g(x)=0$, which then gives $\lim_{x\to 0}|f(x)|=\infty$, contradicting 2. $\square$
Note however that $\lim_{x\to 0}f(x)g(x)=1$. As a side remark, the assumption of Case 1 was useful because it implies that $f$ never vanishes in some neighbourhood of $0$, which allows us to define $g$ (try define $g$ by cases without this assumption, you'll run into trouble).
Case 2: Suppose for every $\varepsilon>0$ and every $\delta>0$ there is some $x$ with $|x|<\delta$ and $|f(x)|<\varepsilon$. Pick $x_n$ such that $|x_n|<\frac{1}{n}$ and $|f(x_n)|<\frac{1}{n}$. Note that this implies $x_n\to 0$ as $n\to\infty$. Define
$$
g(x):=\begin{cases}
\sqrt{n} & \text{if $x=x_n$}\\
0 & \text{otherwise}
\end{cases}
$$
Obviously, $\lim_{x\to 0} g(x)$ does not exist. However, $|f(x)g(x)|\le \frac{1}{\sqrt{n}}$ for every $x$, which gives $\lim_{x\to 0}f(x)g(x)=0$, contrary to the hypothesis.
Comment: @SaranWrap Well, there are two parts to that question. First, some things become more natural with practice. I'm sure there are problems you now find trivial which used to be completely vexing. The same thing happens, to varying degrees, across mathematics. Second, from the more mathematical point of view, if you try to think about how $f$ might behave. Does it vanish near $0$? Does it do so infinitely often? Is it bounded above? Below? Asking this kind of questions can uncover something useful.
Comment: @SaranWrap You can also view this problem as a harder variation of the following: "If $\lim_{x\to 0} f(x)g(x)$ exists, is it true that $\lim_{x\to 0} f(x)$ and $\lim{x\to 0}g(x)$ exist (one or both)?" The natural counterexample to consider is $f\frac{1}{f}$ for this to make sense, $f$ should be non-zero in a neighbourhood of $0$. So, that could be one of our cases. The other option is that there is a sequence $x_n\to 0$ such that $f(x_n)=0$ for every $n$. Then you can define $g(x_n)=n$ and $g(x)=0$ for $x\neq x_n$. Actually, now that I think about it, this might be an easier way!
Comment: How would I go about finding these cases - like if we weren't given the hint, how is one suppose to find the cases by himself? Thank you for your detailed response as well

Spivak Calculus 5-23


How to graphically show how "normal" a collection of dice rolls are in a game

Question: I was trying to think of a way to show how "normal" a set of dice rolls are in a game like catan. In Catan, each turn you roll 2d6 and the sum of those 2d6 dictate game outcomes. A game can last anywhere from 20 - 50+ turns.
For examples sake, let's say we roll 36 times in a game. For a perfectly "normal" game the dice sum 2 would roll exactly once, as would 12. The dice sum 7 would roll 6 times. This forms a triangular distribution. In the distribution of all possible sets of dice results, this would be exactly in the middle of the distribution.
One way to do this might be to look at the total sum of all the dice sums (2d6) throughout the game. At the lower extrema someone could roll 2 36 times (so 72) and at the highest extrema someone could roll 12 36 times (432). The average then would be 7 * 36 = 252.  So you'd have a distribution of sum results with around 252 with a min of 72 and max of 252. Is the distribution also triangular? I think so.
However, this isn't a very good score of how "normal" a game might be, because there is a big difference between rolling specific numbers. For example if no 7s were rolled the entire game this would be very abnormal and greatly affect gameplay.
So looking at the sum isn't a very good score.
I then thought about trying to compute the Z score for each result and somehow combine them. We know the expected frequencies of each 2d6 result in the totals number of rolls. We can then take the actual frequency and divide by the standard deviation for each roll to get this.
So (E(2d6r) - O(2d6r)) / Std(2d6r) where 2d6r is a specific result on 2d6 (like 12) and E is expected, O is observed and Std is standard deviation.
At this point we could sum up the absolute values of these z scores and get a total score. If the distribution matched exactly this score would be 0. In the most extreme case of rolling only 2s or 12s this number would be the largest it could be. How is this result distributed? Obviously it's going to be right skewed but it is normally distributed where I can say x% of results are less than some positive X value?
Is this z score calculation the most statistically appropriate for determining the "normal"-ness of a specific set of results given that we care about the frequencies of each results and not just the sum?
Comment: You are asking how to test the goodness of fit of a distribution.  A standard and (IMHO) very effective method for discrete distributions with small support, like yours, is the chi-squared test: see https://stats.stackexchange.com/search?q=chi+squared+fit+distribution.   Z-score calculations won't accomplish anything for you.
Answer: With games using dice it's important to pay attention to how the game mechanics relate to what matters in the game play. For example (speaking outside specifics of Catan) in a game where you're just trying to roll a total that was at least some fixed target, only the proportion of times you do that matters; any biases that don't affect the outcome -- like more 2's and fewer 3's than expected when the target is 8 -- would be irrelevant. On the other hand if the target varied you might consider displaying the whole cdf. Which is to say, you may well get a different answer about a suitable choice for different games.
In Catan, each individual outcome is typically important. I concur with whuber's comment that the chi-squared test would be a suitable test for this case, but it's not a display. A warning -- at these sample sizes, the dice would have to be pretty far from fair to show up anything on a chi-squared test with at most 50 rolls.
I will discuss a potential display I'd be inclined to look at. [I may come back and add another but I want to think about advice relating to some consequences of discreteness for that one.]
You could plot the proportion of times each outcome was
rolled, with the expected proportions for a fair die (so far, it is straightforward). Here's an example for a game with 36 rolls.

Of course this doesn't show how unusual what we see is; we could add an interval around the expected proportions to indicate a range of observed probabilities consistent with a fair pair of dice. Alternatively to that interval you could put a confidence interval around each observed proportion. The coverage of such a set of individual intervals would need to consider the fact that you're looking at many such comparisons simultaneously -- the chance at least one would be outside such an interval is much higher than the individual ones. You might well want to look at a high individual coverage, or consider two different intervals.
At the same time, you could not use the asymptotic distribution of the counts to get the interval here, because $n$ is quite small (e.g. a game of 25 turns may very easily see no 2's or 3's, and the probability you don't see a "2" say is quite high, around $50\%$), so choice of what interval to display is not trivial. See the discussion at https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval for example. Keep in mind that when choosing a higher coverage, the discreteness problem is worse.
Even in the middle of the distribution, counts that are too low are only likely to "show up" at relatively low coverage probabilities (e.g. at n=25, even a 95% interval for each might not include "$0$" for just the middle three values), which means high probability of at least some values being outside overall.
Consequently, with so few rolls, this sort of thing would tend to only have much hope of finding individual errors "on the high side". It would tend to find the problem with my Catan dice easily; they roll "7" roughly 1/3 of the time, across many dozens of games (and games tend to be on the longer side as a result, helping show the bias more clearly).
Even with that caveat in mind, a similar warning to the one for the chi-squared test - about not seeing anything with such a small sample - applies here. Your power to see anything not explainable as just random variation is quite low.
If the number of rolls was higher -- across ten games, say -- it would be a more useful display, and you would begin to detect differences that matter.
Comment: The standard errors would certainly be straightforward but I feared they might tend to be used to implicitly construct the asymptotic intervals I sought to avoid given the small samples combined with small probabilities. When combined with some additional information, they might work better.
Comment: +1. But for a really effective display I would consider a rootogram or at least some indication of the standard errors of the proportions.


Growling in heavy music

Question: I have enjoyed the vocals of the singer Angela Gossow for a fair number of years now and I'm very interested to learn more about the Growl style of vocals in heavy music.
Is this style of singing in response to the heavy distorted guitar tones of heavy metal or is it more a reflection of the macabre imagery that are part and parcel of heavy music?
I would love to learn more about this style of singing, how it developed and who some of its more prominent champions were.
Comment: Wki  https://en.wikipedia.org/wiki/Death_growl#History_and_variations has some interesting information
Answer: I personally would say growling/screaming tends to fit the heavier style of the music, but then remember that Angela Gossow (and by extension, Arch Enemy) are a very extreme and "brutal" style of metal that usually has constant growling vocals, as it's all part of the genre and sound.
If you look back across plenty of other genres of metal and rock, you'll see that a lot of bands only use heavy vocals in certain sections of songs, or sometimes not at all in certain songs, because it doesn't fit the theme or feel of the song. Take Trivium for example, a lot of their earlier music was very fast paced and heavy. Their later efforts (In Waves and Vengeance Falls specifically) have a much broader range of styles, which means that perhaps growling isn't the most appropriate way to approach singing.
I can't tell you how the style developed, but if you listen across several genres of rock and metal you'll hear the whole spectrum from the original gritty rock vocal to all out pure screaming.
Some prominent figures currently are along the lines of...

Matt Heafy
Corey Taylor
Robb Flynn
Phil Anselmo
Spencer Sotelo
Daniel Tompkins

... but then also there's the likes of Dave Grohl who still use that very gritty original style of rock vocals.
Answer: As far as for how it developed there will be differing opinions, but to me there's a line from Howlin' Wolf to Lemmy of Motörhead, via Chronos of Venom and Tom G. Warrior of Celtic Frost through Tom Araya of Slayer, ending up with the originators of the growl style in the late '80s/early '90s death metal/grindcore scene, like Chuck Schuldiner of Death, Glen Benton of Deicide, LG Petrov of Entombed, Bill Steer and Jeff Walker of Carcass, David Vincent of Morbid Angel, Lee Dorrian and Barney Greenway of Napalm Death. That's a pretty complete one sentence answer with what I would consider the highest impact names, but throw in Repulsion, Possessed and Massacre for good measure, and you've got a reasonable list of the origins.

Growling in heavy music


Somatório total dos valores de todas as datas

Question: Como que eu faço para somar X valores de uma data especifica e comparar se o valor somado é maior que 100?
/*
Data das consultas, e para cada data o somatório total dos valores, desde que este total seja maior do que 100.00.
*/

SELECT
    c.data AS 'Data Consul.', SUM(c.valor) AS 'Total dia'
FROM
    consulta c
WHERE
    c.valor > 100
GROUP BY c.data;

Answer: Você pode usar o operador HAVING
SELECT
    c.data AS 'DataConsul.', SUM(c.valor) AS TotalDia
FROM
    consulta c
GROUP BY
    c.data
HAVING
    TotalDia > 100;

Estou sem ambiente MySQL para testar, qualquer erro me fale que eu edito aqui
Comment: valeu, brother funcionou certinho...
Comment: valeu, amigo feito :)


Twitter api for iPhone OS4

Question: It looks like the twitter api refused to work for iPhone OS4 :(
(Twitter+OAuth http://github.com/bengottlieb/Twitter-OAuth-iPhone).
When I building the project to which I just add the Twitter+OAuth I see the following:
alt text http://www.freeimagehosting.net/uploads/3ce52c447b.png
It's really really important for me! Any help will be greatly appreciated!
Many thanks in advance!!!!!!!
Answer: It seems that there is a binary mismatch between the various object files.
Don't forget that iPhone 4.0 is a new major version, thus it may break ABI (Application Binary Interface). This means that you cannot take a binary object from iPhone 3.0 and link it with a iPhone 4.0 binary object without problems (Note that it may works, but unlikely).
I suggest you to re-build everything from the sources.
Comment: Yes that's right. You need to rebuild from sources all the libraries involved in Twitter+OAuth project.
Comment: You're absolutely right as for the ABI. it's really sooo many problems with OS4!! so I need just rebuild the OAuthConsumer library (the only library in the Twitter+OAuth project) for Mac OS 10.6, right? (sources of library - http://oauth.googlecode.com/svn/code/obj-c). Thanks for help!
Comment: Yeeeh! It's working. I rebuilt the OAuthConsumer library from the Twitter+OAuth project (http://github.com/bengottlieb/Twitter-OAuth-iPhone) and errors disappears. Now I know that all the lib's should be rebuild-ed if you want to use it in OS4. Thank you Laurent!!!

Twitter api for iPhone OS4


Insert a floating button on a textarea using jQuery

Question: I have a textarea that I can control over a jquery function to become a full screen one. I would like to add a button to close the fullscreen
my function that manage the fullscreen is :
function setFullScreen(cm, full) {
         var wrap = cm.getWrapperElement();
         if (full) {
           wrap.className += " CodeMirror-fullscreen";
           wrap.style.height = winHeight() + "px";
           document.documentElement.style.overflow = "hidden";
         } else {
           wrap.className = wrap.className.replace(" CodeMirror-fullscreen", "");
           wrap.style.height = "";
           document.documentElement.style.overflow = "";
         };

        cm.refresh();
       }

The way I call it is like this :
Turn on fullscreen : setFullScreen(cm, !isFullScreen(cm));
Turn off fullscreen : if (isFullScreen(cm)) setFullScreen(cm, false);
I would like to add a button when my textarea is on fullscreen, I would like that button to be  inside the textarea on the top right corner and independant from scrolling (floating)
Is there a way of doing this using jquery ?
Thanks
Answer: You can use the position: fixed; attribute in CSS.  Let's say this is your HTML button mark-up

Your CSS would look like this:
#textarea_close_button{
     position: fixed;
     display: none; //it won't be visible until your textarea becomes fullscreen
     top: 5px;
     right: 5px;
     height: 5px;
     width: 5px;
}

Then run the following line of code when you fullscreen your textarea
$("#textarea_close_button").css({"display": "block"});

And vice-versa when the button is clicked


Nodes that point to panel pages

Question: I'm having an issue with deciding how to display nodes that in turn point to panel pages.
My site currently has a lot of panel pages that have static content. I have a view on my front page that displays nodes which in turn point to these panel pages. However, when a user clicks on a node link, they'll of course see the node in isolation.
In order for me to point users to the correct page, I've been using redirects. So if a user clicks on featured article on the home page,  a redirect pushes them to the panel page I've set up instead of just the node view.
Have I made this overly complicated? Is there a way to making this workflow a lot simpler?
Comment: Is there a reason you aren't using the node override panel page?
Answer: @MPD was correct. I had neglected to use the node override panel page correctly. Thank you!

Nodes that point to panel pages


Cache-Control: no-cache despite allowing cache for anonymous users

Question: We have a D7 site I'm trying to cache with Varnish. The assets are caching fine but for some reason every page is served with this header:
Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0

The pages are quite heavy to render and end users aren't authenticated, so I'd really like to find a solution. How can I find out if a module is preventing caching? What else could cause this? We have a similar site that plays completely nice with Varnish but I haven't been able to spot the difference yet.
Edit: I checked the site with http://www.isvarnishworking.com/ and it says Varnish is working - "sort of". That is, the age is smaller than one, meaning something is preventing the page from being cached. Below are the full response headers as reported by the service.
Server: Apache
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Mon, 27 Apr 2015 17:11:55 GMT
Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0
ETag:   "1430154715"
Content-Language:   en
X-Generator:    Drupal 7 (http://drupal.org)
Content-Type:   text/html; charset=utf-8
Content-Length: 45567
Accept-Ranges:  bytes
Date:   Mon, 27 Apr 2015 17:11:56 GMT
X-Varnish:  1868715414
Age:    0
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    MISS

Answer: Inspect your HTTP headers and see if session or other cookies are being set. This is the most common cause of Varnish "not working." Also make sure you are not logged in, and you can test using http://www.isvarnishworking.com/ to see what headers are outputted. If you could paste the headers would be helpful.
Comment: Thanks, that seems like a pretty useful link! I added the headers to my question.
Comment: What about sessions? Its easy in Firefox, go to page, then right click "View Page Info" then click on Security tab and click View Cookies. From there click Remove All and then reload your home page. There should not be any SESSxxxxx cookies, if you could screen shot or list all cookies.
Comment: It sends cookies `has_js`, `_ga`, `_gat`, `__atuvc` and `__atuvs`. Our other site also sends the same cookies and it works fine. All the cookies are JavaScript originated, so they shouldn't affect caching or headers.
Comment: Yeah I just wanted to see if there was a session cookie set as that would break cache. You can force varnish to cache by adding something like: sub vcl_fetch {
  remove beresp.http.Cache-Control;
  set beresp.http.Cache-Control = "public";
}
Comment: Also another thing that helps is disabling Varnish and seeing if Drupal will cache the page. If no then you should focus on reviewing the modules and if any of them set FALSE for cache. I am assuming you have cache configured with varnish in settings.php


Django Managers

Question: I have the following models code :
from django.db import models
from categories.models import Category

class MusicManager(models.Manager):
    def get_query_set(self):
        return super(MusicManager, self).get_query_set().filter(category='Music')
    def count_music(self):
        return self.all().count()

class SportManager(models.Manager):
    def get_query_set(self):
        return super(MusicManager, self).get_query_set().filter(category='Sport')

class Event(models.Model):
    title = models.CharField(max_length=120)
    category = models.ForeignKey(Category)
    objects = models.Manager()
    music = MusicManager()
    sport = SportManager()

Now by registering MusicManager() and SportManager() I am able to call Event.music.all() and Event.sport.all() queries. But how can I create Event.music.count() ? Should I call self.all() in count_music() function of MusicManager to query only on elements with 'Music' category or do I still need to filter through them in search for category first ?
Answer: You can think of a manager as a 'starting point' for a query - you can continue to chain filters just as if you'd started out with the default manager.
For example, Event.objects.filter(category='Music').filter(title='Beatles Concert') is functionally equivalent to Event.music.filter(title='Beatles Concert')
So, as Daniel says, you don't really need to do anything special, just choose one of your custom managers instead of objects and go from there.
Comment: It is the start point and end point. To get anything 'in between' you will want something like this snippet: http://djangosnippets.org/snippets/734/ Be sure to check out the comments...
Answer: You don't need to do anything (and your count_music method is unnecessary). The count() method will use the existing query as defined by get_query_set.
Comment: cont() is just an example. Let's say filter_city('City') or anything else. I'm just wondering if in this custom manager if i want to create function for even more specific query, can I use .all() or nothing at all or do I need to filter category once again ?

Django Managers


Rabbitmq no Node.js com ampqlib não fazendo broadcast das mensagens

Question: Esse script deveria ser um tipo de chat em linha de comando somente para o estudo do rabbitmq.
Seriam abertos execuções do programa em paralelo. Cada execução cria um consumer da mesma fila e todo texto enviado por uma execução do programa deveria ser enviado para todas consummers através de um exchange do tipo fanout.
Acontece que embora eu tenha configurado o exchange como fanout ele não está fazendo broadcast das mensagens. Ele está se comportando como um load balancer enviando a mensagem para cada consumer por vez.
<code>const amqplib = require('amqplib');
const readline = require("readline");

class Chat {

    async init() {
        await this.configureChannel();
        await this.configureConsumer();
        await this.configureCommandLine();
    }

    async configureChannel() {
        const conn = await amqplib.connect('amqp://guest:guest@localhost:5672');
        const ch = await conn.createChannel();
        await ch.assertExchange("chat", "fanout", {});
        const { queue } = ch.assertQueue('messages');
        await ch.bindQueue(queue, 'chat', '');
        this.ch = ch;
    }

    async configureConsumer() {
        await this.ch.consume("messages", logMessage);
        function logMessage(msg) {
            if (msg.content)
                console.log("\n[*] Recieved message: '%s'", msg.content.toString())
        }
    }

    async configureCommandLine() {
        const commandLine = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
        this.commandLine = commandLine;
    }

    async run() {
        const prompt = () => {
            this.commandLine.question("Message: ", async (mensagem) => {
                debugger;
                if (mensagem === "sair") {
                    return this.commandLine.close();
                }
                await this.ch.publish("chat", 'messages', Buffer.from(mensagem), {});
                prompt();
            });
        }
        await this.init();
        console.log("\nChat\n");
        prompt();
    }

}

const chat = new Chat();
chat.run();
</code>
Answer: Baseado na resposta dada no StackOverflow em inglês:
https://stackoverflow.com/questions/68324760/rabbitmq-innode-js-with-amqplib-not-broadcasting-fanout-messages/68329407#68329407
Supondo que você execute várias instâncias desse script como está, o problema aqui é que você está usando uma fila para todos os consumidores. Um exchange do tipo fanout envia cada mensagem recebida para todas as filas que estão vinculadas ao exchange. Mas cada fila (se tiver vários consumidores) funcionará no estilo de rodízio (round-robin) - supondo que haja algum limite na contagem do prefetch. Para obter o comportamento fanout, você precisa executar cada instância do script com uma fila diferente.
As solução estaria na alterações destas linhas:
<code>...
async configureChannel() {
    const conn = await amqplib.connect('amqp://guest:guest@localhost:5672');
    const ch = await conn.createChannel();
    await ch.assertExchange("chat", "fanout", {});
    this.ch = ch;
}

async configureConsumer() {
    const { ch } = this;
    const { queue } = await ch.assertQueue('', { exclusive: true });
    await ch.bindQueue(queue, 'chat', '');
    ch.consume(queue, logMessage);
    function logMessage(msg) {
        if (msg.content)
            console.log("\n[*] Recieved message: '%s'", msg.content.toString())
    }
}
...
</code>


eudev was skipped: conflicting distro feature 'systemd' (in DISTRO_FEATURES)

Question: My recipe needs eudev.
RDEPENDS_${PN} += "eudev"

but when bitbake it:
it got:
ERROR: Nothing RPROVIDES 'eudev' (but foo_126.96.36.199.bb RDEPENDS on or otherwise requires it)
eudev was skipped: conflicting distro feature 'systemd' (in DISTRO_FEATURES)

Comment: Do you really need to depend on eudev specifically (and not udev which could be provided by systemd as well)?
Comment: actually, I need libudev.so.0, this is a test.
Comment: Please add your machine info in systemd* files (bb | bbappend)
Answer: If you want libudev, then DEPEND on udev.  This is provided by either systemd or eudev.


Independent variable has a known non-causal relationship with the dependent variable; is it still okay to regress?

Question: To further elaborate on my question, assume that I have a time series dataset of Tax X and Tax Y, where in Tax X is paid by 100% of the sample while Tax Y is paid by 75%. Both taxes differ with regards to how they are implemented and collected, but are ultimately based on business revenues. Now if I am trying to figure out the relationship between Tax Y and Tax X to estimate Tax Y for the 25% of the sample for which there is no Tax Y data, is it kosher to regress Tax Y on Tax X? It is clear to see that Tax X is not causing Tax Y and that both taxes are being determined by individual business revenues, which is not known.
Answer: There can be a linear relationship between variables with no causal relation directly involved. It's fair to check if the linear model is a good fit in order to make estimations.
I personally don't know any single model which needs something like "direct causality assumption".
Comment: Interesting. I don't have too much experience with time series data, but I was under the impression that since you have a greater degree of ability to identify and establish things like Granger causality, regression specifications with spurious relationships like the one I laid out were not considered useful.
Comment: +1 In the absence of a causal idnetification strategy, linear regression is just a handy descriptive or predictive tool. Apply as necessary, where necessary.


Does anyone know of a module like "Artsy Editor" for Drupal?

Question: I'm looking for a writing interface similar to Artsy Editor which is built for Wordpress.
It's a "distraction-free" wysiwyg that I need for a client's site and thus far I've not been able to find one.
Does anyone have suggestions on an existing editor that I can use, or a way to use existing modules to achieve the same effect?
I'm really looking for a way to have a wysiwyg style interface similar to the new "notes" in the new version of basecamp.
The site in question is a Drupal 7 site.
Answer: There's no module for Artsy Editor.
But if you mean inline editor, you can use Edit for Drupal 7 and 8 - In-place editing for fields on any entity. Including WYSIWYG editing powered by CKEditor or Aloha.
"Edit" is part of Spark - Drupal distribution which aims to be "the Pressflow of Drupal authoring experience


Dplyr: Filter a pairwise grouped dataset keeping only one row from each pair by condition

Question: I have a dataset like the one below:
game                  teams              score
Liverpool - Leeds     Liverpool          2
Liverpool - Leeds     Leeds              1
Sheffield - Norwich   Sheffield          0
Sheffield - Norwich   Norwich            1
Arsenal - Newcastle   Arsenal            3
Arsenal - Newcastle   Newcastle          2

My purpose is to keep only the rows corresponding to the winning team. My desired outpout would look like this:
game                  teams              score
Liverpool - Leeds     Liverpool          2
Sheffield - Norwich   Norwich            1
Arsenal - Newcastle   Arsenal            3

I guess I would need to group the rows by game firstly, but once done I'm not being able to move forward successfully.
Answer: One possible dplyr solution would be
df %>%
  group_by(game) %>%
  filter(score == max(score))

# A tibble: 6 x 3
# Groups:   game [5]
#   game                teams     score
#   <chr>               <chr>     <int>
# 1 Liverpool - Leeds   Liverpool     2
# 2 Sheffield - Norwich Norwich       1
# 3 Arsenal - Newcastle Arsenal       3

With this solution, you will get both teams in case of a draw.
Answer: We can use slice_max
library(dplyr)
df %>%
     group_by(game) %>%
     slice_max(score)
# A tibble: 6 x 3
# Groups:   game [5]
#  game              teams     score
#  <chr>             <chr>     <int>
#1 Arsenal-Newcastle Arsenal       3
#2 Bayer-Real        Bayern        3
#3 Bayer-Real        real          3
#4 Liverpool-Leeds   Liverpool     2
#5 Sheffield-Norwich Norwich       1
#6 Tottnham-Bvb      BvB           6

data
df1 <- structure(list(game = c("Liverpool-Leeds", "Liverpool-Leeds",
"Sheffield-Norwich", "Sheffield-Norwich", "Arsenal-Newcastle",
"Arsenal-Newcastle", "Tottnham-Bvb", "Tottnham-Bvb", "Bayer-Real",
"Bayer-Real"), teams = c("Liverpool", "Leeds", "Sheffield", "Norwich",
"Arsenal", "Newcastle", "Tottenham", "BvB", "Bayern", "real"),
    score = c(2L, 1L, 0L, 1L, 3L, 2L, 5L, 6L, 3L, 3L)),
    class = "data.frame", row.names = c(NA,
-10L))

Answer: You can try:
df %>%
  group_by(game) %>%
   summarize(teams = teams[which.max(score)], score = score[which.max(score)])
#> # A tibble: 3 x 3
#>   game                teams     score
#>   <chr>               <chr>     <int>
#> 1 Arsenal - Newcastle Arsenal       3
#> 2 Liverpool - Leeds   Liverpool     2
#> 3 Sheffield - Norwich Norwich       1

I'm not sure how you plan to handle draws though...
Answer: I have added 2 further hypothetical plays, from which one is a tie. In this case both are named with my solution
library(tidyverse)

df <- read.table(text =
"
game                  teams           score
Liverpool-Leeds     Liverpool          2
Liverpool-Leeds     Leeds              1
Sheffield-Norwich   Sheffield          0
Sheffield-Norwich   Norwich            1
Arsenal-Newcastle   Arsenal            3
Arsenal-Newcastle   Newcastle          2
Tottnham-Bvb        Tottenham         5
Tottnham-Bvb        BvB               6
Bayer-Real          Bayern            3
Bayer-Real          real              3
", header =T)

df
#>                 game     teams score
#> 1    Liverpool-Leeds Liverpool     2
#> 2    Liverpool-Leeds     Leeds     1
#> 3  Sheffield-Norwich Sheffield     0
#> 4  Sheffield-Norwich   Norwich     1
#> 5  Arsenal-Newcastle   Arsenal     3
#> 6  Arsenal-Newcastle Newcastle     2
#> 7       Tottnham-Bvb Tottenham     5
#> 8       Tottnham-Bvb       BvB     6
#> 9         Bayer-Real    Bayern     3
#> 10        Bayer-Real      real     3

df %>%
  group_by(game) %>%
  top_n(1)
#> Selecting by score
#> # A tibble: 6 x 3
#> # Groups:   game [5]
#>   game              teams     score
#>   <fct>             <fct>     <int>
#> 1 Liverpool-Leeds   Liverpool     2
#> 2 Sheffield-Norwich Norwich       1
#> 3 Arsenal-Newcastle Arsenal       3
#> 4 Tottnham-Bvb      BvB           6
#> 5 Bayer-Real        Bayern        3
#> 6 Bayer-Real        real          3


Camera view blocked detection using opencv in python3 windows platform

Question: I am developing a camera state monitoring service using opencv in Python3, am facing a problem in detecting if a camera view is blocked by an obstruction (obstacle) ,like a tree or any object blocking the view, how can i detect such case using opencv in Windows platform
Comment: You need to reformat your question. What have you tried so far? Is there any code we can look at? What kind of scene is your camera looking at, or should it be general? etc
Comment: My scene will be a road with cars crossing, it is a camera monitoring the streets. I have a baseline image to compare to , which was generated from a video after removing moving objects, and each day will take a snapshot at the same time of the baseline image by the same logic.
There is no code to work with, am trying to find some logic to work with , how to say that there is a blocking object in the view, or even if lot of dust on the lens that is blocking the view.
Comment: I thought in comparing the features of both images, but if am still getting more cars in the frame due to huge traffic then this wont work, because I need to limit the time of the video taken to generate the video, considering the no of cameras am dealing with
Comment: You should look into block-matching, sometimes reffered to as template-matching. It essentially breaks the image up into smaller blocks and compares the individual elements, perhaps this can be utilised for your problem. Goodluck.
Answer: if something got stuck on the camera, then optical flow in that area will be very less and you can say that it is blocked.


Adding basic click animation to dynamic buttons

Question: I have a simple button that looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:tag="general"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#343535"
    android:orientation="vertical"
    tools:context=".fragments.GeneralFragment">

    <Button
        android:id="@+id/hello"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center_vertical"
        android:onClick="onClick"
        android:text="@string/hello" />

Instead of static, these buttons should now be dynamic
Button button = (Button) layout.getChildAt(0);
for(String text : readFromSharedPreferences) {
        // Set the layout
        Button btn = new Button(this.getContext());
        btn.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        btn.setText(text);
        btn.setTag(text);
        btn.setLayoutParams(button.getLayoutParams());
        btn.setBackground(button.getBackground());
        layout.addView(btn);

The static button has an animation when I click on it. That looks like this:

But the dynamic button has no animation. So when I click on it, nothing happens. That looks like this:

How can I add this animation to my dynamic buttons?
Update
I have figured out that my loop contains an on-touch listener. That looks like this:
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
    // No code in here
});

If I remove that listener (even if it contains no code), the animation works great but I would like to keep it, because of my swipe function that is placed into it.
That is my whole code:
// Swiping to link
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
    @Override
    public void onSwipeLeft() {
        super.onSwipeLeft();

        // Alert to ask
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Delete");
        builder.setMessage("Do you want to delete?");
        // Delete
        builder.setPositiveButton("Yes", (dialog, which) -> {
            // Set the SharedPreferences as String
            ArrayList<String> currentSharedPreferences = readFromSharedPreferences(getContext());
            currentSharedPreferences.remove(btn.getTag().toString());
            Gson gson = new Gson();
            String currentSharedPreferencesAsText = gson.toJson(currentSharedPreferences);

            // Update the SharedPreference k-text
            SharedPreferences mPrefs = getContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = mPrefs.edit();
            prefsEditor.putString("k-text", currentSharedPreferencesAsText);
            prefsEditor.apply();

            // Start the animation
            btn.animate()
                    .translationX(-btn.getWidth())
                    .alpha(0.0f)
                    .setDuration(300)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            btn.clearAnimation();
                            btn.setVisibility(View.GONE);
                            Snackbar.make(view, "Entry deleted.", Snackbar.LENGTH_LONG).setAction("Delete", null).show();
                        }
                    });
        });
        // Cancel
        builder.setNegativeButton("No", (dialog, which) -> {
            // Silence is golden
        });

        builder.show();
    }

    @Override
    public void onClick() {
        MainActivity mainActivity = new MainActivity();
        Tts tts = new Tts(getContext(), _mediaPlayer, mainActivity.barTop, mainActivity.barBottom);
        try {
            tts.say(btn.getTag().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

});

Well I could use
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    return false;
}

Then the animation will work but onClick() wouldn't work anymore.
Another update
I had a similar problem on another view. There my static button was not having a click effect. Then I have just simply added android:foreground="?attr/selectableItemBackground" and it worked! The same way I have just tried with my dynamic button. So I have added btn.setForeground(button.getForeground()); but that doesn't do anything.
Answer: Use MaterialButton instead of Button. MaterialButton is a subtype of Button that supports additional features. The Button that is in your XML layout is actually a MaterialButton if you're using a Material Components theme. The theme automatically swaps out Buttons for MaterialButtons when your XML is inflated. So, when dynamically creating buttons in your Java code, you must use MaterialButton if you want it to match the original.
Also, when using MaterialButton, never call setBackground() because this causes undefined behavior. It likely will prevent the ripple effect from occurring as well.
Alternatively, you can define your Button in its own XML file, even with the layout params it needs for LinearLayout. Then inflate the XML each time you need another button.
for(String text : readFromSharedPreferences) {
    Button btn = requireContext().getLayoutInflater()
        .inflate(R.layout.my_button, layout, true); // true adds it to layout
    btn.setText(text);
    btn.setTag(text);
}

Comment: Thanks for your answer! I have tried it with MaterialButton but I see no changes. Also, I have removed `setBackground()`.
Since your code gives me some errors, I have tried it with `Button btn = (Button) inflater.inflate(R.layout.fragment_general, layout, true);`. But also there I get the error: _android.widget.LinearLayout cannot be cast to android.widget.Button_. Also please tell me what `my_button` should be. `fragment_general` is just a fragment.
Comment: To inflate the XML button, the button needs to be by itself in its own XML file.
Comment: I have updated my question. Please check it again.


(How) can I recover lost whistle register? [Male]

Question: Disclaimer: I have never taken proper singing classes so my vocabulary may be incorrect, I hope you understand what I mean.
Thanks to my quite late voice change (when I was ~15) I have have developed a taste for high-pitched singing.
Before the voice change, my range was about A3-F6~A6 depending on training.
Later I kind of grew into a baritone voice (not exactly sure about that) which went from G2-G4, and a falsetto/whistle that was quite airy and could still reach A3-F#6.
At first I wasn't able to get a mixed voice, so I could either sing ~soprano or baritone (not very practical for most classical rock). With some practice I was able to get to this mixed voice to have a stronger upper range from G4 to B5 (sounds more Rob Halford than Axl Rose unfortunately, but working on it).
After screaming a bit too much during a party and getting sick two years ago (was 20 at the time), I lost my voice for a few days. When I recovered, I could not use the whistle/falsetto register with the same technique I had always used, it either 'fell back' to mixed chest up to B5, or simply made no sound as if the voice were broken. With time, I was able to use the falsetto voice again if I sung softly around the 4th octave, but to this day I'm unable to use this voice for singing very high notes.
Is there anything I can do to recover whistle register?
I'd be elated if I could sing the end of Aerosmith's Crazy again, would that be possible?
Comment: Probably not.  Once your vocal cords go thru puberty,  they won't go back.   You should work with a trained voice coach to make sure you don't attempt something that will cause permanent damage to your existing range.
Comment: Well, hormones continue to change body parts thru at least age 25.  Or it may be that there was minor damage from screaming and illness that's limited your vocal cords' flexibility.
Comment: Its seems weird since two years ago I had long gone through puberty, and could still do this falsetto!
Comment: If it were the latter that caused my loss, would there be anything to recover?
Answer: First,  high range isn't necessarily whistle register.  Whistle register literally sounds like you're whistling (Minnie Ripperton uses it in "Loving you",  Mariah Carey used it, albeit a harsher sounding R&B style version of it).   That and although males CAN sing in whistle register, it's REALLY RARE -  Brett Manning sings in it and can teach it too )
I think you're referring to headvoice which is how most people sing high.  That said, it sounds like you may have temporarily damaged (?) your vocal chords by screaming.
(The question mark is there because I'm not an ENT so I can't  say this for fact, but the fact you didn't mention any nagging hoarsness or loss of speaking voice hints at it.)
That said,  all voices change with age (especially puberty), the good news is  you can recover some of it, maybe even all of your range.  I'm a second bass and can sing from "F#" one octave over middle "C" down to the lowest "C" on the piano, but I've had years of training and have had to rebuild my voice from scratch due to exploratory surgery that cut my diaphragm muscle.   I don't go as high as I  used to, but I'm slowly building back up to it.  Look into voice lessons with a good coach !


Music Sheet Notes Interpretation

Question: I am learning guitar on my own no i found something written on music sheet which is below

My Understanding : From E string strum 8 fret then hammer on 10 (not sure if we need to do pull off please clarify the same) then slide to 7 fret
strum it and then hammer on 8 fret and so on
Now i see another notes as below :
So why these line (2 and 3 are bind together using long lines) can't understand it please need the explanation for the same
Comment: Has anyone else noticed that first triplet - three *dotted* 16th notes beamed as a triplet. Three dotted 16ths in the time of two dotted 16ths, i.e in the time of three 16ths. I think it would have been much clearer to notate that as just three 16th notes?  In fact, when I saw the question title, I was expecting it to be about that triplet, not about the TAB notation…
Comment: @BrianTHOMAS My first thought too when I saw the image. This is terrible notation, and beginning with three straight sixteenth notes is the *only* acceptable solution, it seems to me.
Comment: I love how bonkers (but obviously redundant and ridiculous) that notation is! It reminds of a composition pupil I once taught, suggesting that a melody could simply be written all in crotchets, with new metronome markings used for all changes of note length. I just stared at him open mouthed...
Answer: The TAB is telling you what fret and string to play the notes corresponding to the standard music notation on the staff above.  The arc under groups of notes is a slur and indicates that the notes should be played without right hand attack.  So yes you need to hammer on and pull off in the first example.  It looks like groups of three notes, triplets, played as a single unit.  You can and should attack (pick) at the start of each new group.  The small numbers in the staff under each note indicate the finger to use.  So the first two groups of triplets are played in the same position with fingers (2 and 4) followed by fingers (1 and 2).  Then they want you to shift down and use fingers (1 and 3) for the next two groups, shifting for each group.  I'm not sure why they stopped there and didn't put fingering under the last group but it would have to be (1 and 3) again if there are no accidentals.
In the second example is a trill.  Same idea, the slur indicates that you keep the energy going by pull off and hammer on of the left hand fingers (fretting hand for those who play the opposite way).  You have to keep this trill going without picking for 2 measures.  Not sure how you would even play the small chord up at the 30th fret.  They do make 36 fret guitars (I played one in the late 80s) but that's rare and I'd have see the entire score to make a judgement as to whether that's a harmonic of a fretted note, and how it would be played.
Answer: First part, yes play 8th fret, hammer-on 10th, pull off to 8 again (keep a finger on fret 8 ready for the pull off).
The G/F♯ semiquavers are played alternating, as written, on the bottom string. The other numbers are strange though - frets 30 and 31. Maybe it's harmonics on the top 4 strings, but the actual music notes are off screen high on ledger lines above the stave. An equivalent of the harmonics around the 5th fret?, or around the middle of the soundhole on an acoustic, roughly. A screenshot slightly higher will give better clues.
Answer: In TAB notation, whenever there are legato sections of tied notes, you should pick / strum the first note of the set and then use hammer-ons and/or pull-offs to sound the other notes. In your first example, if you follow the notation exactly, you should fret the note on the eighth fret on the low E string (using your middle finger), pick it, then hammer-on to the tenth fret (using your fourth finger for this) and then pull-off back to the eighth (your second finger should remain on the eighth fret throughout). Then, do the same starting on the seventh fret, hammering-on to the eighth and then pulling-off back to the seventh.
In the second example, you should continuously hammer-on and pull-off on the second and third frets. When doing these longer runs, your "pull-off" needs to slightly "twang" the string in order to sustain the note long enough for it not to die out before the end of the legato section.

Music Sheet Notes Interpretation


Como empacotar e distribuir um sistema web?

Question: Preciso que determinado sistema Web - incluindo o próprio servidor PHP, bem como o MySQL - sejam "empacotados" em um arquivo executável, permitindo dessa forma, que o usuário leigo utilize-o numa espécie de browser próprio. Quais etapas precisaria seguir para tornar este sistema distribuível?
Edit: O PHP e o MySQL posso instalar manualmente, mas ainda não sei como fazer para ter um browser para o sistema.
Comment: é realmente necessário utilizar um navegador que não esteja presente no sistema? Para o lado do servidor, até usaria algo como [Vagrant (em inglês)](http://www.vagrantup.com/) para virtualizar o ambiente, mas não consigo conceber opções para embarcar o navegador no pacote.
Comment: Sim, o browser próprio seria fundamental.
Answer: Considerando que você pode instalar o PHP e o MySQL no computador do seu cliente, então é só criar um domínio fake usando o arquivo hosts do Windows (C:\Windows\System32\drivers\etc\hosts).
# Localhost
127.0.0.1 localhost
127.0.0.1 meusite.dev

Mas precisa criar um virtual host pelo httpd.conf:
NameVirtualHost *:80

<VirtualHost *:80>
    ServerName meusite.dev
    DocumentRoot "C:\Users\Nome\Documents\.....\pasta_do_site"
</VirtualHost>

E pedir para ele visitar http://meusite.dev no browser.
A única outra alternativa que eu imagino, é hospedar o site em algum servidor de testes.
=============
Edição: transformei meu comentário em resposta:
Você pode fazer o seguinte:

Instale o Google Chrome;
Abra o endereço de desenvolvimento;
Clique no ícone de três barrinhas no canto superior direito;
Escolha "Ferramentas > Criar atalho de aplicativos" e marque "Área de trabalho".

E pronto você tem um browser dedicado para o site em questão, sem botão voltar, barra de endereços, etc com ícone no desktop. Ver também http://en.wikipedia.org/wiki/Site-specific_browser
O resultado fica assim:
Comment: Mas o usuário não tem um navegador (browser) instalado?
Comment: Já pensei na possibilidade, mas falta-me o browser.
Comment: Não. O navegador seria personalizado, para só abrir aquela página, sem barra de ferramentas, botão de voltar, ou algo assim, para o cliente não se distrair e abrir o facebook "sem querer".
Answer: Uma solução alternativa seria criar um instalador próprio e incluir as sub-instalações dos programas necessários. O NSIS é uma boa ferramenta para fazer isso.
WAMP
O primeiro passo da instalação principal seria instalar um pacote WAMP, por exemplo, do Bitnami. Para fazer isso sem intervenção do usuário executa-se o pacote com o parâmetro --mode unnatended (fonte). A instalação principal poderia verificar se o pacote WAMP já está instalado e pular esta etapa em caso afirmativo.
Nesse primeiro passo, seria possível ainda instalar os aplicativos necessários separadamente. Apache, PHP e MySQL (até a versão em que eu usava, pelo menos) funcionam se executarmos os binários diretamente da pasta de instalação. Então na verdade, se houver tempo e necessidade, poderia-se criar um WAMP customizado, cuja vantagem é o tamanho menor do pacote e a menor quantidade de elementos desnecessários instalados no cliente.
Navegador
Para a navegação, existem tópicos em alguns fóruns sobre como deixar um Firefox Portable sem barras de ferramentas. Não cheguei a testar essa ideia, mas já usei a versão portável desse navegador e sei que funciona.
Outra opção seria criar um pequeno executável (em outra linguagem, é claro) com um navegador embutido. Há muitos anos eu costumava fazer isso em Delphi ou VB incluindo algumas DLL's que permitiam colocar um componente com o Internet Explorer dentro de uma janela. O programa somente precisa de uma janela simples que abra sempre o sistema na página inicial, embora seja possível incluir algumas funcionalidades interessantes, como uma janela especial para dados de login que então faz uma requisição para o servidor local antes de abrir o sistema em si ou um listener que faz o logout do usuário quando ele fecha a janela.
Aplicação
Depois disso, é necessário extrair os arquivos da aplicação no diretório do WAMP, além dos arquivos de configuração necessários, que podem ser obtidos de uma instalação de teste.
Um último passo seria fazer criar a estrutura do banco de dados, o que pode ser feito ainda na instalação através de um script PHP de linha de comando ou no primeiro acesso da aplicação através de um wizard a là Wordpress.
Atualização
E um epílogo nessa história seria fazer a atualização do sistema via PHP mesmo usando uma extensão de SVN ou GIT, ou mesmo baixando um zip da web.
Alternativa: Máquina Virtual
Uma última alternativa que eu consideraria seria uma Máquina Virtual (VM) com o ambiente do sistema pré-configurado. No caso do Windows poderia ser criado um serviço associado a essa VM que a liga/desliga ou salva/restaura o seu estado quando o SO é iniciado ou desligado.
Existem sites que disponibilizam VMs enxutas baseadas em linux que podem ser usadas para tais propósitos. Por exemplo, o TurnKey Linux.
Answer: Eu já fiz uns testes e gostei do TideSDK. Você cria o sistema com html, javascript, php etc, empacota e distribui para mac, linux e windows. Já vai com um navegador do SDK, não precisa mais nada. Estão migrando em breve para tideKit
Comment: Tive alguns problemas com o TideSDK há algum tempo, por isso engavetei o projeto. Vamos ver como o TideKit se sai.
Answer: Encontrei um site que trás mais algumas alternativas além das já citadas aqui, bem como os prós e contras de cada uma, trazendo também seus principais recursos.

AppJS, baseado no nodejs;
Node-webkit, combina o Node.js e o webkit;
Sencha Desktop (não é gratuito), baseado no webkit;
Brackets Shell, utiliza o Chromium.