Harmony and roman numeral analysis: how to deal with chromaticism?

Question: I recently started playing piano.
While learning and performing new pieces, I found that it helps me a lot to have some certainty of what's going on with the notes, the chords, and the harmony.
I decided to learn these as my first 3 pieces: Beethoven's Bagatelle No. 25 in A minor and Piano Sonata No. 14 in C-sharp minor Op. 27 No. 2, and Chopin's Prelude Op. 28 No. 4.
I have no issues with the first two. I understand what's going on in the harmony, and roman numeral analysis was straight-forward. Chopin's prelude Op.28 No. 4, in the other hand, confuses me. I don't even know where to start in order to understand the function of each chord.
Here are the first measures:

It starts with i - V: Em to B7sus4 (i think?), and from there it goes through a series of subtle chromatic movements, involving only one note of each chord, slowly moving semitone by semitone. That's where I get lost. The functions of the chords stop being obvious to me.
How do you perform harmony and roman numeral analysis on works like this, with so much chromaticism going on? Where do you start? How is the function of the chords deduced/derived?
Comment: Hi JC, I'm part way through preparing an answer for you - it is proving a little harder than expected. In the meantime, I found this online, which is pretty interesting! http://mathemusicality.wordpress.com/2007/08/05/how-to-make-a-chopin-prelude/
Answer: The term for chord connections like this, where each note of the chords changes (usually chromatically, almost always step-wise) one-by-one, is linear harmony. It's quite common in Liszt, Scubert, Schumann, etc. Roman numeral analysis is mostly pointless during linear harmony passages, most analysts will either just label it as linear harmony until the next functional chord is found, or will use Neo-Riemannian analysis to describe the harmonic movement. Neo-Riemannian analysis is complicated if you haven't already heard studied it, and it mostly only works for the portions of the linear harmony passage that has triads, but you might find it interesting enough to look up.
Comment: Well, he practically invented it, so I would hope he could make a relatively compelling case! :)
Comment: The article "Introduction to Neo-Riemannian Theory" from the *Journal of Music Theory* by Richard Cohn is an excellent starting point. I'll try a link that I found to a PDF, but you might need to access it via a library or other scholarly institution. http://recherche.ircam.fr/equipes/repmus/mamux/Cohn%20Intro%20Neo-R.pdf
Comment: +1 Pat, this is really helpful. As these chords are predominately triadic, I started writing an answer to show JC how he *could* analyse them, but yes, I found this approach to be pretty meaningless. Glad you posted this answer; it made me decide to rethink… I don't know anything about Neo-Riemannian analysis - I'll definitely check it out...
Comment: Thanks, Pat. I'll check out that link. As it happens, I realised I know a *little* about this, having stumbled across info while reading about Tonnetz, but I could definitely do with learning about this analytical approach in detail.
Comment: Thanks again, Pat. I was able to open the whole PDF, despite it being a JSTOR article. I've only read the first few pages, and the rest will have to wait until I have a little more time, but it is already very enlightening, and has already explained the need for this analytical approach in a more convincing manner than other sources I've seen.
Answer: Although much of the harmony here is triadic, few of the chords function in a conventional way. It is possible to give each chord a "name"; for instance, the first 13 bars could be notated as these chords (with a little enharmonic licence):
Em / / / | B7sus4 / B7 / | B7b5 / Bm7b5 Dm7b5 | E7 / Em7 Edim7 |
Am7 / F#m7b5 ?? | F#m7b5 / D#dim7 ?? | D7 / / / | Dm7 / Bm7b5 Bdim7 |
Cmaj7+ Am / / | B7sus4 B7 F#m7b5 (Am) | B7 / F#m7b5 (Am) | B7 / / / (implied) | Em …
At this point, we could try to analyse these chords in terms of key, however this quickly becomes problematic, for two main reasons:

few of these chords feel strongly associated with the tonic, E Minor; it makes little sense to analyse them in terms of this key.
although there are a number of dominant 7th chords, we never cadence in any key (except the final return to E Minor in bars 12-13), so no modulations are effected, making it unhelpful to analyse chords in terms of any other key, either.

So, although we may be able to describe each of the chords in this harmonic progression, and even relate them to one or more keys (using roman-numeral notation, for instance), this would neither describe how we perceive this progression, or how it is constructed. Instead, we need to view this chord sequence as the result of a series of simultaneous (mostly) chromatic descending "voices". (@Pat Muchmore gives a good explanation of this in his answer.)
However, we do feel some "harmonic-signposts" along the way. Essentially the first 13 bars function as a single i-iv-V-i cadence, embellished by many chromatic passing notes. Bar 1 is clearly chord i; with some decoration, bars 9-10 are basically chord iv and bars 11-12 are chord V; we cadence strongly back to i in E Minor at bar 13. (Possibly the D7, bVII7, chord in bars 7-8 could be considered pre-cadential too…)
This article, which I already mentioned in comments above, clearly shows the chromatic and step-wise movement of the "voices" in this harmonic progression. Although it is a rather "tongue-in-cheek" article, suggesting an approach to "create-your-own-Chopin-Prelude", it does show that the harmonic movement in this Prelude can be viewed at a variety of different background "rates", which progressively become closer to the actual Prelude, as further embellishments are made.
Comment: Could this be thought of as polyphonic rather than harmonic? Would it make more sense to analyze each voice?
Comment: @KevinJohnsrude, I see what you mean about the movement of "lines" within these chords, but no this is not polyphonic music; these "lines" are certainly not independent, being mostly part of block-chords. They are only "lines" or "voices" in the sense of *voice-leading*.
Comment: @KevinJohnsrude, but you could, I suppose, analyse the movement of the "voices" within the chord progression, as though they were independent lines - this is effectively what the article I link to does.
Answer: Theory powerhouse Dieter de la Motte mentions explicitly that throughout the romantic period "chromatic downward motion can negate any harmonic tendency" (my own translation from the German & paraphrased).
Comment: @Aaron Diether de la Motte: Harmonielehre, Bärenreiter 1985, page 86 "Auch noch im 19. Jahrhunderd gilt: Jede Leittontendenz kann durch chromatische Führung in entgegengesetzter Richtung neutralisiert werden".
Comment: There is an English translation by Jeffrey L. Prater, *The Study of Harmony* (W.C. Brown Publishers, 1991).


To put text on table border as a header

Question: I have one difficulty.
I have to put text on table border as a header.
For example:
--------------This Is header-----------------------
Is it possible, if anybody can provide solution on this?
Comment: Possible duplicate of [Text in Border CSS HTML](https://stackoverflow.com/questions/7731310/text-in-border-css-html)
Answer: There are multiple ways.
You could create a table header, and set the text position: relative and move it up a bit. Though, this is not classy.
I would use a fieldset instead, which is 100% valid. You need to give the fieldset a border instead of the table though.
<fieldset>
    <legend>Your text</legend>

</fieldset>

Comment: I tried this but failed in some way. Meanwhile I want  rounded corner for this table. How can I achieve this
Comment: hi, Is there is any solution to achieve this with rounded corner? If any other way then provide me?
Comment: Just apply your CSS rules for your border to your fieldset instead of your table... http://www.border-radius.com
Comment: Thanks for your valuable reply.Its working perfectly now. great Man
Comment: You can mark an answer correct by clicking the "V" left of an answer. It will allow people to find this answer more easily, and people will answer your future questions faster.

To put text on table border as a header


Vue.JS - invoking event listener

Question: I'm trying to make links inside  in the second column. When clicked, I want MonitoringTable function to be invoked with the value I supplied.
Vue.Js:
 const app = new Vue({
    el: '#page-wrapper',
    data: {
        loading: false,
        resultsTable: [],
        defaultTable: '*some name*',
        columnsFilter: ['*some name*','*some name*','*some name*']
    },
    methods: {
          /** Get Chosen Table Results From DB **/
          MonitoringTable: function(table) {
            var self = this;
            self.loading = true;

            /** Erase Previous Data From Table **/
            if ($.fn.DataTable.isDataTable('#monitoringTable')) {
                $('#monitoringTable').DataTable().destroy();
            }

            /** Get Data From DB **/
            Services.getMonitoringTable(table).then(function(response) {
                self.resultsTable = response.data;

                $('#monitoringTable thead tr').empty();
                $('#monitoringTable tbody').empty();

                if (self.resultsTable.length) {
                    /** Build Array of Table Heads **/
                    var columns = [];
                    $.each(self.resultsTable[0], function (index, value) {
                        columns.push({ data: index });
                        /** Append Filters to Table Heades **/
                        $('#monitoringTable thead tr').append(
                            '' +
                            index +
                            ((self.columnsFilter.includes(index) )? '<select class="hidden"></select>' : '') +
                            '	');
                    });

                    /** Construct Table **/
                    setTimeout(function() {
                        Global.CustomTable('#monitoringTable', [ 0, 'asc' ], 25, false, response.data, columns, self);
                        $('#monitoringTable').find('[data-toggle="tooltip"]').tooltip('fixTitle');
                        if(table == self.defaultTable){
                            $.each(self.resultsTable, function (index, value) {
                                $('#monitoringTable tbody tr td.sorting_1').eq(index).next().html(
                                    `<a @click="MonitoringTable(` + *table's name* + `)" style="cursor: pointer;">` + *table's name* + '');
                            });
                        }
                    }, 0);
                } else {
                    $('#monitoringTable thead tr').append('Table results	');

                    /** Construct Table **/
                    setTimeout(function() {
                        Global.CustomTable('#monitoringTable');
                        $('#monitoringTable').find('[data-toggle="tooltip"]').tooltip('fixTitle');
                        self.loading = false;
                    }, 0);
                }
            }).catch(function(error) {
                var error = Object.assign({}, error);
                Global.ErrorMessages(error.response.data);
            });
        }
    },
    mounted: function() {
        var self = this;

        self.MonitoringTable(self.defaultTable);
        Global.ShowMounted();
    }
});

Element before mount:
@extends('*some name*')

@section('*some name*', '*some name*')
@section('*some name*', '*some name*')

@section('content')

            <loading v-if="loading"></loading>

@stop

I added the HTML after table is constructed (with setTimeout). The view is as expected... what am I missing? How can I invoke MonitoringTable with a click?
Comment: Just tried it with a `console.log` instead of your code inside `MonitoringTable`, it worked. What isn't working for you?
Comment: I tried console.log at the first line of `MonitoringTable` but saw nothing in console.@Daniel_Knights
Comment: Must be somewhere else in your code then. Could you post the full file?
Comment: @Daniel_Knights that is the entire JS and HTML code
Comment: Something else must be wrong somewhere, there's no reason you'd see nothing in the console
Answer: You are mixing 2 paradigms - the Vue reactivity and the jQuery imperativity.
You can not use anything Vue-related in your jQuery-based code. You seem to think that @click will work in a string literal like <a @click which you are injecting into the DOM through jQuery - but it simply won't work because it is not part of any Vue-based template. You will have to either use an inline event handler (<a onclick="....") or use addEventListener to attach your handler after the A tag is already present in the DOM tree.
I highly recommend you to get rid of jQuery (and anything based on it) and switch completely to Vue.JS
Comment: Thanks. so how can I access the vue instance from Js (because obviously just `onclick="MonitoringTable('*tebleName*')"` wouldn't work)
Comment: Well, you can assign the root Vue instance to a global variable, e.g. `var myVue = new Vue({.....}).$mount('#app');`

Vue.JS - invoking event listener


Batch node operations in Drupal 5

Question: What is the most efficient way to go through and update every single node in a drupal site, to, for instance mechanically add tags? Drupal 6 has a shiny new batch API, but what to do in Drupal 5?
I started writing a script that keeps a pointer and then goes around all nodes on a cron, loads them and then saves them, but I wonder what else could be done.
Answer: I don't suggest working directly on the database level since some modules might want to update some other related tables. The most reliable and flexible way is to write a script to load, change and save nodes in a loop. You can also try using additional special modules for Drupal 5:

Taxonomy Node Operations
Taxonomy Multi Editor (similar functionality)
and more general module Views Bulk Operations
Answer: Consider the Job queue module. Here is a quote about it (from the module's project page):

... used by modules to queue function calls for execution on cron. The job_queue_add() function is used by modules to add a job to the queue
This module is end of life for Drupal 7, there is a queue in core.
Answer: hmm i'm not familiar with drupal 5's database structure, but if it's similar enough to drupal 6, you could just modify this all pretty easily by just working off the term_node table. it's a mapper of node id's to term id's:
term_node
- nid
- vid
- tid

nid is the node id of course, vid is the revision id, if you use revisions, and tid is the term id. terms are all stored in term_data
term_data
- tid
- name

are the more interesting columns. so if you already have existing terms, you can create a quick map of existing tid's, then add to whatever nodes you want in term_node. anyhow, being careless in this regard could possibly cause weird data issues, so i wouldn't suggest this approach unless you feel pretty comfortable with the raw database.
Comment: doing things on the db level is not something that I want to do - there is a lot more risk to mess everything up in a subtle way and then not notice until it's too late.

Batch node operations in Drupal 5


How can I display lots of rows of information from a database in my drupal module?

Question: In the example_page I believe it shows something like this:
function foo() {
    return array('#markup' => t('bar'));
}

And the function foo would be used for a page callback in the menu hook to create a page. However, In my module I plan on using a db_query to access a database table and with it display many rows of data.
Is there a better way to do this than stuffing all of my output into #markup? It could be done with lots of concatenation, but it would be rather messy and it seems like there should be a better way.
Answer: If you're looking to build an HTML table then the theme_table() function will help a lot. See the docs page for full details but this is a basic example:
function MYMODULE_page_callback() {
  // Header for the table
  $header = array('id', 'name');

  // Get your data
  $data = db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();

  // Loop through the data and add rows to the table
  $rows = array();
  foreach ($data as $id => $name) {
    $rows[] = array(
      $id,
      $name
    );
  }

  // Return the themed table
  return theme('table', array('header' => $header, 'rows' => $rows));

  // You could also use:
  return array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows
  );
}

Comment: Don't mention it :) Drupal is notorious for having a steep learning curve but trust me it's worth it if you persevere!
Comment: Thank you very much again. Sorry for the simple questions, I really know PHP,SQL, & HTML, but learning how to program for drupal almost feels like another language lol.


How to show activity only to the user whom the post belongs to in Public activity gem

Question: what am trying to do is to use public activity gem to build a notification system i followed this railscast and everything worked just fine. I have a article and a comment model where users can comment on each others article and the user whom the article belongs to will get notified in their activity feed, but the problem here is that the activity page shows activity of all users, but now i want to show activity only to the specific person whom the article belongs to. Means if a user clicks on the activity button they will only see the activities that happened on there article. Is there any way to accomplish that ? Thanks in advance.
what i had tried till now, but it doesn't seems to work
activities_controller.rb
<code>class ActivitiesController < ApplicationController
 def index
   @activities = PublicActivity::Activity.all.order("created_at desc")
                  .where(trackable_type: "Comment", owner_id: current_user.id, owner_type: "User")
 end
end
</code>
Comment: Read [this section](https://github.com/chaps-io/public_activity#use-custom-fields-on-activity) . Use `recipient`..
Answer: <code>@activities = PublicActivity::Activity.order("created_at desc")
          .where(trackable_type: "Comment", owner_id: current_user.id, owner_type: "User")
</code>
Should work
Comment: no it works but in opposite manner  the user which commented can see the activities but the user who created the the post on which comment have been done cant't see the activities that this user had commented on your post... actually sir @artyom Kalmykov  am newe to rails...but i think there will be something different instead of current_user.id


Restored database taking massive amount of space

Question: I restored a database with a 1.5gb .bak file. Everything works fine except the restored database now takes 64gb of space.
I've heard about shrinking databases and log files but how should I find out what is it that takes so much space and what I can "shrink" so that the data itself won't change. I need this production backup data in my development environment as it is.
I don't need full logs in the development environment where I'm doing the restoring. How to find out is it the data or the logs that take more space?
I'm using SQL Server Management Studio 2017
Comment: backup files are usually compressed so this is expected behaviour, try shrinking the files, it won't delete data, it will free up space that has been allocated but not used. you need to specify some more details too, as you've not said if it's the log or data file that are taking up the bulk of the space and whether you need the full logs in the restoring environment.
Comment: Check if this helps you: https://stackoverflow.com/questions/48617895/sql-server-c-drive-memory-issue/48620616#48620616 It deals with similar issue; shrinking log file will not harm the data in any way.
Comment: Sounds like you haven't taken any transaction log backups, if you don't backup and truncate the log it will just grow and grow - especially if you are doing large operations like deleting all records from a table and re-filling it etc.
Comment: Can you delete tables from the restored database? Try figuring out which tables consume the most space and either delete rows from them, or delete the whole table... If you do end up deleting rows, perform a shrink operation after to reduce the space used...
Comment: @bastos.sergio -- you are advising him to delete underlying data in order to gain disk space before shrinking the db?  That does not seem like very good advice.  Why would you assume that he can just delete data?  Also, deleting data won't help if he is running in the full recovery model and the problem is a large log file.
Comment: I'll add these details to the question
Answer: Your question: "How to find out if it is the data or the logs that take more space?"
Answer:  Here is one way.  Right click your database in Sql Mgt. Studio, click Reports=>Standard Reports and then disk usage.
If you don't understand the differences between the full and simple recovery models, I encourage you to do some reading.  Also understand the consequences of shrinking files and auto-grow.  Shrinking files won't cause you to lose committed data, but will cause a performance hit later on if and when Sql needs to auto-grow files.
If you don't need the full recovery model and aren't concerned about auto-grow, then change it to simple or bulk-logged and then shrink the log file(s).
If you are not concerned about auto-grow, then you can also shrink data file(s).
Answer: Maybe logs?
I suggest you to analyze if that fits you. Make the backups much shorter: See More
BACKUP DATABASE XXXXX TO DISK 'C:\XXX.bak' WITH COPY_ONLY

You can also change the Recovery Model from Full (Default) to Simple, after the restore.

Then SHRINK it

I'm honestly not sure if all of those are necessary, but that works for me to reduce space. Maybe shrinking before changing recovery model is better, or maybe one of those are not the best pratices.
Answer: You could see what is the file size of a database in your backup using
restore filelistonly from disk = 'here_the_full_pass_to_your_backup_including_file_name'

So you could plan how much space it will need.

How to find out is it the data or the logs that take more space?

Please update your question with the results of
use MyDB;
exec sp_spaceused;


Carregamento lento com plugin JQuery DataTables

Question: Estou usando o JQuery DataTables em um pequeno sistema e estava tudo muito bem até que me deparei com uma listagem de quase 2500 registros...
A questão é que demora um certo tempo até que as informações sejam carregadas e ajustadas no DataTable, o que faz com que fique carregando e exibindo todos os 2500 registros na página até que carregue tudo e a paginação entre em ação.
Teria alguma forma de evitar/mascarar isso? Atualmente não uso ajax, faço assim:
No meu Controller:
public function index()
{
    $funcoes = Funcao::orderBy('id')->get();
    return view('cadastros/funcao/index', compact('funcoes'));
}

Na minha View:

...

    @foreach($funcoes as $funcao)

        {{ $funcao->cbo }}
        {{ $funcao->nome }}
        ...

    @endforeach

Meu script:

Comment: Um opção seria você carregar pelos eventos/interações do usuario com a tabela. https://datatables.net/examples/data_sources/server_side.html
Comment: Carregar 2500 registros de uma só vez não é sensato, por que não usar Server-side processing? https://datatables.net/examples/data_sources/server_side.html
Comment: Eu n uso por que eu não sei mesmo rs, vou dar uma olhada nesse link e ver se consigo fazer aqui
Comment: No caso estou usando Laravel5, na parte que chama o ajax eu ponho uma rota que devolva os elementos todos em JSON e ele faz esse lance de carregar só o que precisa?
Comment: A chamada ajax está dentro do método .DataTable? ou você preenche a  primeiro e depois usa $('#tabela').DataTable()?
Comment: isso, eu preencho e depois chamo
Comment: edita a pergunta e coloca o javascript da chamada ajax e do .DataTable()
Comment: coloquei o que faço atualmente @EduardoMoreira
Comment: olha, essa lerdeza provavelmente é na escrita da tabela, e não em você transformar ela em DataTable (na minha experiência isso é bem rápido). sugiro que você teste sem transformar ela em DataTable para confirmar onde está o problema.
Comment: Sim, pelo visto está lento por seu muita coisa mesmo, também demorou bastante sem o DataTable, vou tentar fazer o que disseram com o server side.
Answer: Eu já passei por esse problema. Percebi que a lerdeza era causada por eu preencher manualmente a tabela e, depois, usar $('#tabela').DataTable(). Vejo duas alternativas para resolver isso, mas ambas precisam de ajax.
A primeira opção, mais fácil, é fazer uma chamada ajax e entregar o json ao DataTables
Portanto:
function preencherTabela(jsonData) {
    $('#tabela').DataTable({
        destroy: true, //retirar essa linha caso você nunca recarregar a tabela
        sPaginationType: "simple_numbers",
        data: jsonData,
        columns: [
            { "data": "Cbo" },
            { "data": "Nome" }
        ]
    });
}

$.ajax({
    url: '/suaUrl',
    type: 'GET',
    success: function (jsonData) {
        preencherTabela (jsonData);
    }
});

A segunda opção, mais elegante, seria usar o suporte a "server-side processing" e fazer uma paginação real. Particularmente nunca precisei fazer isso e portanto não posso te ajudar muito. Mais sobre o assunto aqui
Comment: tentei fazer dessa forma mas ta dando erro "Uncaught ReferenceError: data is not defined" na linha " success: preencherTabela (jsonData)". Esse jsonData eu tenho que substituir por algo?
Comment: tinha um probleminha no success. Editei. jsonData é só um nome qualquer que eu dei para a variável. São os dados que você vai receber via ajax para a popular a tabela (se o ajax for bem sucedido, claro).
Comment: Ah agora funcionou, já da pra quebrar um galho enquanto eu vejo como implementar esse lance do server side com mais calma, vlw.


Ruby/GSL online documentation for wrong version?

Question: After successfuly installing Ruby/GSL library on my Debian (via *deb), with Ruby 1.9.3, I am having troubles running most of the GSL methods. Specifically, this webpage shows several code samples, but (in Arrays), right from the top line, require "GSL" is obsolete, it is require "gsl" today. The remaining methods also do not work.
For another example of my problem, consider another online reference to Ruby/GSL.
GSL::VERSION
#=> 1.15
GSL::pow_2( 4 )
#=> 16

But when I flip the page,
GSL::Complex.new( 0.9, 1.1 )
#=> ArgumentError: wrong number of arguments(2 for 0)

The simplest explanation to me would be that Ruby/GSL has more than one version hanging online, and the documentation I found is for the old one. For example, there is this abandoned version (https://github.com/codahale/ruby-gsl), so perhaps the version history is a bit complicated? Which is the authoritative version, and where can I finde the up-to-date documentation?
Answer: Following methods do work for the Complex module:
> c = GSL::Complex[0.9, 1.1]
=> GSL::Complex
[ 9.000e-01 1.100e+00 ]

> c.real
=> 0.9
> c.imag
=> 1.1

> c.pow 2
=> GSL::Complex
[ -4.000e-01 1.980e+00 ]

Comment: Great. So all that obsolete documentation was misleading me. Do you know where can I find the up-to-date documentation?
Comment: @BorisStitnicky It seems you have to build upto-date docs with rdoc or yard from ruby-gsl sources by yourself. There is documentation from 2010 at http://rb-gsl.rubyforge.org/files/rdoc/ref_rdoc.html and at least it does contain updated info for Complex class. If my answer did helped you, feel free to mark is as accepted.
Comment: It did help, thanks. I was looking everywhere online and I completely forgot about good old rdoc :-)


Binomial random variable expectation bound

Question: Let $X,Y \sim \text{Bin}(n,0.5)$ for some positive $n$.
What is a lower bound for $\mathbb{E}(XY)$? When is it achieved?
My try:
I got confused by the following two results and couldn't proceed!
By Jensen's, $\mathbb{E}(XY) \geq \mathbb{E}(X)\mathbb{E}(Y)$. But we also know that $\text{cov}(X,Y)=\mathbb{E}(XY) - \mathbb{E}(X)\mathbb{E}(Y)$, and this quantity can be negative!
Please help me to proceed. Thanks in advance!
Answer: Hint: If $\rho_{X,Y}:=\frac{\text{cov}(X,Y)}{\sigma_X\sigma_Y}$ denotes the correlation coefficient of $X,Y$, then you know that $$-1\le \rho\le 1$$
Now $\sigma_X=\sigma_Y=0.5\sqrt{n}$ and $\mathbb E[X]=\mathbb E[Y]=0.5n$. Hence, $$-1\le \rho=\frac{\mathbb E[XY]-(0.5n)^2}{\left(0.5\sqrt{n}\right)^2} \implies 0.25n(n-1)\le \mathbb E[XY]$$ The equality is attained when $\rho=-1$, for instance when $Y=n-X$ (negative linear relationship with "slope" -1).
Comment: This I know, but still, my conundrum exists (the last two statements which I have mentioned in the details)! Could you give more hints?
Comment: Thanks, but the equality attainment condition says $Y$ is negative when it is not, remember $Y\sim  \text{Bin}(n,0.5)$. Can you comment on the equality attainment again?
Comment: Also, there's a typo in the final inequality. It should be $0.25$
Comment: Hey. For the equality attainment, $Y=n-X$ suffices. :) Please check the same, and update your answer. I'll accept it.
Comment: Sorry, I was offline. You are right in both your comments, so I corrected accordingly. Thanks


Convergence rate of log likelihood ratio

Question: I have come across the following statement in the textbook A course on Large Sample Theory by Ferguson - Chapter 17. Strong Consistency of the Maximum Likelihood Estimates.

The likelihood ratio, $L_n(\theta)/ L_n(\theta_0)$  converges to zero
exponentially fast, at a rate $\text{exp}\{-nK(\theta_0,\theta)\}$

Here, $L_n$ is the likelihood function, $\theta_0$ is the true parameter of the distribution from which data was sampled, $\theta$ is an estimate of the true parameter and $K$ is the KL-divergence between the true distribution and fitted distribution.
The reasoning for the statement was given as follows:
From Weak Law of Large Numbers, we have
\begin{aligned}
\frac{1}{n} \log \frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)} &=\frac{1}{n} \sum_{i} \log \frac{L_{i}(\boldsymbol{\theta})}{L_{i}\left(\boldsymbol{\theta}_0\right)} \\
& \stackrel{\mathrm{P}}{\longrightarrow}-\mathrm{K}\left(\boldsymbol{\theta}_0 ,\boldsymbol{\theta}\right), \\
\text{i.e.}\qquad  \frac{1}{n} \log \frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)} + \mathrm{K}\left(\boldsymbol{\theta}_0 ,\boldsymbol{\theta}\right) &= o_p(1)
\end{aligned}
I am trying to understand how the above statement on this exponential convergence follows from this convergence in probability.
Here is my attempt where I proceed from the reverse direction:
I need to prove that
\begin{align}
& \frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)}  = o_p(-\text{exp}\{-nK (\theta_0,\theta)\}) \\
\implies  & \frac{\frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)}}{\text{exp}\{-nK (\theta_0,\theta)\}} = o_p(1)  \\ & \text{and because log is a continuous function}, \qquad
   \log \frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)} + nK (\theta_0,\theta) = o_p(1) \\
& \text{in other words, I need to establish}  \qquad \frac{1}{n} \log \frac{L_n(\boldsymbol{\theta})}{L_n\left(\boldsymbol{\theta}_0 \right)} + K (\theta_0,\theta) = o_p(1/n)
\end{align}
As you can see, I need a convergence order of $o_p(1/n)$, however, from WLLN, I have only $o_p(1)$. How do I proceed from here? Also, in general, is this approach correct? Are there any other ways to prove the same?
Comment: @kjetilbhalvorsen: Appreciate your suggestion to add the self-study tag; added it now. Also, I did provide my attempt and indicated where I am stuck in my original post. Let me know if something was not clear. Thanks.
Answer: By the Law of Large Numbers
$$\frac{1}{n}\log\frac{L_n(\theta)}{L_n(\theta_0)} = -K_n(\theta_0,\theta)+o_p(1)$$
so
$$\log\frac{L_n(\theta)}{L_n(\theta_0)} = -nK_n(\theta_0,\theta)+o_p(n)$$
And that's all we need: the term that's proportional to $n$ dominates the $o_p(n)$ term.
If you want the epsilontics: write $r_n$ for the $o_p(n)$ term.  For every finite $M$ and $\epsilon>0$ there is $N$ such that for $n>N$
$$P(r_n<Mn)>1-\epsilon.$$
Choose $M=K_n(\theta_0,\theta)/2$, then for every $\epsilon>0$ there is $N$ such that for $n>N$
$$P\left(-nK_n(\theta_0,\theta)+r_n< -nK_n(\theta_0,\theta)/2\right)>1-\epsilon$$
so
$$P\left( \frac{L_n(\theta)}{L_n(\theta_0)}<\exp\left(-nK_n(\theta_0,\theta)/2 \right) \right)>1-\epsilon$$


How to create a view block only visible to the Referenced Content Type's Author?

Question: I have 2 custom content types: Item for sale, and Bid (offer). The latter has a node reference URL to a node of the first content type.
I created a view (block) which shows the people with their offers.

I need to edit this view in such a way that is will be only visible to the person who created the Item for sale (author of the first content type may only see this block).
How can I achieve this? I cant seem to find a way with contextual filters.
Answer: Easiest way to do this:

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add another relationship for the Content Author and select the node reference field relationship from the dropdown list at the top of the window.
Filter the view for the current logged in user by selecting the author relationship that was just created in step 2.

OR

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add a contextual filter for the Content: Author uid, select the node reference field relationship from the dropdown list (top of window), select: provide default argument of type: user id from logged in user

Either way the result is the same and it's what you need.
Answer: You can restrain block visibility only to node's author in the block's visibility settings. For example select "Pages on which this PHP code returns TRUE (experts only)" and use the following code as a visibility criteria:
<code><?php

    global $user;
    $node = menu_get_object('node');
    if($node) {
       if ($user->uid == $node->uid) {
           return TRUE;
       }
    }
    return FALSE;
</code>
Comment: I'll try this as soon as I get home. I let you know if it solves my problem
Answer: I presume you are extracting the ID node on display from the current URL for use in a contextual filter? You should also be able to add a relationship to that node and then a filter for the author of that content type = current user. That way there'll be no results when anyone else views the page.


Conditionally update argument to function in Rust

Question: I am trying to conditionally update an argument to a function:
struct A {
    foo: i32,
    bar: i32,
}

impl A {
    fn foobar<'a>(&'a self) {
        let a;
        if true { // something more complex obviously
            let x = A {
                foo: self.foo,
                bar: self.bar,
            };
            a = &x;
        } else {
            a = self;
        }

        println!("{} {}", a.foo, a.bar);
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=27fcba42d135da6282bd000fd8e3db5d
Here, the function foobar receives an argument of type &A. Depending on some condition I want to replace this argument with another value of type &A.
I do understand why the above code results in the error 'x' does not live long enough. My question is whether there is a pattern to conditionally update the value of the argument a without requiring it to be mutable? Is there maybe a way to forcefully extend the lifetime of x?
Comment: really just call your function in both branch.
Answer: Inside your if condition, you give to a a reference to x, which will be destroyed just after. Then a will hold a reference to a destroyed object.
You can fix it by declaring the x variable before the condition:
struct A {
    foo: i32,
    bar: i32,
}

impl A {
    fn foobar<'a>(&'a self) {
        let a;
        let x;
        if true { // something more complex obviously
            x = A {
                foo: self.foo,
                bar: self.bar,
            };
            a = &x;
        } else {
            a = self;
        }

        println!("{} {}", a.foo, a.bar);
    }
}

You can also simplify your code, by removing the lifetimes and using the pattern let a = if ... {} else {}; :
    fn foobar(&self) {
        let x;
        let a = if true { // something more complex obviously
            x = A {
                foo: self.foo,
                bar: self.bar,
            };
            &x
        } else {
            self
        };

        println!("{} {}", a.foo, a.bar);
    }

Comment: notice that this will add runtime overhead and in my opinion is ugly code.


Integration over a combination of sphere and cone

Question:
If $P$ is the part of the sphere $x^2+y^2+z^2=4$ that is above the cone $z=\sqrt{x^2+y^2}$, them what is $$\int_P yz \,dS?$$

I can't really visualize this problem and I'm not sure how to integration works here.
Comment: Two notes: (i) The region has a simple description in spherical coordinates. (ii) The integral can be evaluated immediately by inspection (the integrand is "odd in $y$" and the region of integration is symmetric across the $(x, z)$-plane).
Comment: How do I describe it in spherical coordinates?
Comment: The specifics depend on your definition of spherical coordinates $(\rho, \theta, \phi)$, but the region inside the sphere is described by an inequality $\rho \leq \text{constant}$, and the region above the cone has a description (similar to) $\phi \leq \text{constant}$.
Comment: But what are those constants? And are there more definitions of spherical coordinates?
Comment: To some people $\phi$ is latitude; to others, it's co-latitude; to others, it's longitude. The key point here is: If you look at the cone $z = \sqrt{x^{2} + y^{2}}$, what is the angle (in radians) between the $z$-axis and a generator? (Hint: The cone intersects the $(x, z)$-plane in the graph $z = \sqrt{x^{2}} = |x|$.) Also, what's the radius of the sphere?
Comment: The radius is 2, but how do I use that?
Comment: One set of defining conditions for your region is $0 \leq \rho \leq 2$. (Again, this _particular_ integral can be evaluated immediately by inspection, as Travis's and my comments outline. The comments here are solely for purposes of setting up integrals over this type of region.)
Answer: Hint The region of integration is symmetric across the $xz$-plane.
Comment: Let $P_-$ and $P_+$ denote the parts of $P$ on which the $y$-coordinate is respectively negative and positive. What is the relationship between $\int_{P_-} yz \,dS$ and $\int_{P_+} yz \,dS$?
Comment: Yes, it's the union of $P_-$ and $P_+$. Actually, as we defined it, $P_+ \cup P_-$ misses the intersection of $P$ and the $xz$-plane, but this is just a curve and so does not contribute to the value of the integral, so this omission doesn't harm us. So, this means $$\int_P yz \,dS = \int_{P_+ \cup P_-} yz \,dS.$$ Then...
Comment: How can I use this?
Comment: Isnt $\int_{P_-}=-\int_{P_+}$?
Comment: Yes, that's the idea. Now, what is the relationship between the integrals over $P, P_+, P_-$?
Comment: I don't know what the relation is between those
Comment: Okay, what is the relationship between $P, P_+, P_-$ themselves, rather than the integrals over them?
Comment: P is the sum of $P_-$ and $P_+$
Comment: I'm not sure what happens then. Can i calculate $\int_{P_+\cup P_-}yzdS$?
Comment: I think you should reread the introductory section on multivariable integration in your textbook.


How do I add/remove form fields dynamically?

Question: i have form build in standard like:
public function getFormId() { }
public function buildForm(array $form, FormStateInterface $form_state) { }
public function validateForm(array &$form, FormStateInterface $form_state) { }
public function submitForm(array &$form, FormStateInterface $form_state) { }

in my build form it return $form array with button add and remove.
if i press add, i would like to add new textfield above the add button (or anywhere else)
and next to the new text field i like to have a minus button ( - ) to remove the text field.
how do i achieve this in drupal 8 with ajax? how do i position the newly added textfield? how do i generate the field id ($form['composition']['DynamicallyAddedAndRemove'])?
i know how to build ajax callback but im not sure how to add new field and/or remove it dynamically through ajax
this is what i did and it didn't work, any idea why
class MyForm extends FormBase {
  /**
   * Class constructor.
   */
  public function __construct($coreService) { }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) { }

  /**
   * {@inheritdoc}
   */
  public function getFormId() { return 'id_form'; }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::form().
   *
   * Builds the entity add/edit form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param FormStateInterface $form_state
   *   An associative array containing the current state of the form.
   *
   * @return array
   *   An associative array containing the settings add/edit form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

  /*
   * to make it short... $form build here
   * then continue...
   */

    // Initialize the counter if it hasn't been set.
    if (null !== ($form_state->get('fields'))) {
      // Nested this deep to avoid conflicts with other modules
      $form_state->set('fields', array(
        'module' => array(
          'fieldset' => array(
            'items_count' => 0
          )
        )
      ));
    }

    $max = $max = $form_state->get(['fields','module','fieldset','items_count']);

    $form['fields']['module']['fieldset'] = array(
      '#type' => 'details',
      '#title' => t('title here'),
      '#description' => t('description here'),
      '#open' => TRUE,
    );

    // Add elements that don't already exist
    for ($delta = 0; $delta <= $max; $delta++) {
      if (!isset($form['fieldset'][$delta])) {
        $element = array('#type' => 'textfield','#title' => t('tittle 00'),'#required' => FALSE);
        $form['fieldset'][$delta]['t00'] = $element;
        $element = array('#type' => 'textfield','#title' => t('title 01'),'#required' => FALSE);
        $form['fieldset'][$delta]['t01'] = $element;
        $element = array('#type' => 'textfield','#title' => t('title 02'),'#required' => FALSE);
        $form['fieldset'][$delta]['t02'] = $element;
      }
    }

    $form['fieldset']['add'] = array(
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => t('Add field'),
      '#submit' => array(array($this, 'addSubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addfield'),
        'wrapper' => 'foo-replace',
        'effect' => 'fade',
      ),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );

    return $form;
  }

  /**
    * Ajax submit to add new ingredient.
  */
  public function addSubmit(array &$form, FormStateInterface $form_state) {
    $max = $form_state->get(['fields','module','fieldset','items_count']);
    $form_state->set(['fields','module','fieldset','items_count'],$max++);
    $form_state->set('rebuild', TRUE);
  }

  /**
    * Ajax callback to add new ingredient.
  */
  public function addfield(array &$form, FormStateInterface $form_state) {
    return $form['fieldset'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) { }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
  }

}

Thank you,
Answer: public function buildForm(array $form, FormStateInterface $form_state) {
  $form['fields']['modules'] = array(
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => t('sample field'),
      '#description' => t('Explaination about sample field is here, Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here. Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.thank you.'),
      '#prefix' => '
',
      '#suffix' => '
',
    );

    $max = $form_state->get('fields_count');
    if(is_null($max)) {
      $max = 0;
      $form_state->set('fields_count', $max);
    }

    // Add elements that don't already exist
    for($delta=0; $delta<=$max; $delta++) {
      if (!isset($form['fields']['modules'][$delta])) {
        $element = array(
            '#type' => 'textfield',
            '#title' => t('field Name'),
            '#autocomplete_route_name' => 'route here',
        );
        $form['fields']['modules'][$delta]['iqqq'] = $element;
        $element = array('#type' => 'textfield','#title' => t('aaa'),'#required' => FALSE);
        $form['fields']['modules'][$delta]['iaaa'] = $element;
        $element = array('#type' => 'textfield','#title' => t('sss'),'#required' => FALSE, '#suffix' => '
');
        $form['fields']['modules'][$delta]['isss'] = $element;
      }
    }

    $form['fields']['modules']['add'] = array(
      '#type' => 'submit',
      '#name' => 'addfield',
      '#value' => t('Add more field'),
      '#submit' => array(array($this, 'addfieldsubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addfieldCallback'),
        'wrapper' => 'modules-wrapper',
        'effect' => 'fade',
      ),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit sample'),
    );

    return $form;
  }

  /**
    * Ajax submit to add new field.
    */
  public function addfieldsubmit(array &$form, FormStateInterface &$form_state) {
    $max = $form_state->get('fields_count') + 1;
    $form_state->set('fields_count',$max);
    $form_state->setRebuild(TRUE);
  }

  /**
    * Ajax callback to add new field.
    */
  public function addfieldCallback(array &$form, FormStateInterface &$form_state) {
    return $form['fields']['modules'];
  }

Comment: I get an Uncaught AjaxError when using this code.
Comment: Hi , how it can apply to a content type form ? will it be applicable ?
Comment: You should add a description of why this works and what fixed it. Don't just post a block of code as an answer.


Linear Fit Issue

Question: Consider a quantity $Q$ that changes as a function of time.
The function $Q(t)$ is not explicitly known. We know
that $Q(t_{0})=Q_{0}$. Assume for $t-t_{0}\le\epsilon$,
we have a method to estimate one additional point on the $Q(t)$ curve. This estimation gets better
for small $\epsilon$. Given the inital point and
another point, for a fixed epsilon, it seems that
one can approximate $Q(t)$
by  a linear function. However the nature of the linear
function seems to change based on $\epsilon$ that one picks.
What is the best way to estimate $Q(t)$ in this case?
Thanks -abiyo
Answer: Here is what you are missing: because you have chosen a linear model, $T = at + c$, so $\frac{t_1 - t_0}{T_1 - T_0} = \frac{1}{a}$. By the nature of the linear model that you have chosen, $T(t) \in O(t)$, so the limit of their ratio must be real-valued.
Comment: Thanks Orangutango for the reply, I want to have an explicit expression for $t_{r}$. In my case, $T_{1}$ is more precise when $t_{0}-t_{1}<\epsilon$. Now where I am stuck is writing an explicit expression for $t_{r}$ that doesn't depend on epsilon
Comment: You realize that by shrinking $\epsilon$ to zero, you are losing the linear information, don't you? You can't describe a line with only one point, which seems to be what you are trying to do. Honestly I find your model very unrealistic, both in that temperature does not decay linearly and that you would never take measurements at a sample rate where this became a problem.
Comment: Orangutango, thanks once again. I agree the example I gave is rather poor. For my actual case, I am trying to give some estimate for the decay of pressure at a fixed point in space behind a shock wave. One of the quasi-analytical forms known in the literature for this case is the exponential decay. It is just that in the way I derive my solution, I have an initial point. The additional point will be known precisely if I am arbitrarily closer to the initial point. I have edited the question to reflect your comments.

Linear Fit Issue


Mean of squared "sum of squared errors"

Question: Let $X_i, i=1,\dots,n$ are independent with mean $\mu$ and variance $\sigma^2$.
For example they are iid normal distributed.
I wonder how to calculuate
$
\mathrm{E} \{[\sum_i (X_i - \bar{X})^2]^2\}
$
?
My first try:
$$
\mathrm{E} \{[\sum_i (X_i - \bar{X})^2]^2\}
= \mathrm{Var} \{[\sum_i (X_i - \bar{X})^2]^2\} + [\mathrm{E} \sum_i (X_i - \bar{X})^2]^2
$$
I know  $
\mathrm{E} [\sum_i (X_i - \bar{X})^2] = (n-1) \sigma^2.
$
So I am tempted to find $\mathrm{Var} \{[\sum_i (X_i - \bar{X})^2]^2\}$, which seems to me harder than the original problem.
My second try:
$$
\mathrm{E} [\sum_i (X_i - \bar{X})^2]^2\
= \mathrm{E} \{\sum_i [X_i^2 - 2 X_i \bar{X} + \bar{X}^2]\}^2
= \mathrm{E} [\sum_i (X_i^2) - n \bar{X}^2]^2
$$
Unsure how to proceed.
Thanks.
Comment: If you write down the exact definition of $\bar{X}$ it's not so bad after expanding out the product carefully. Also you probably meant to write covariance, not variance (and adjust the product accordingly).
Comment: Thanks, I was also stuck at the expanded expression before I tried the covariance.
Comment: I'd have mentioned independence if that was intended, and if it wasn't, then that's also a huge omission.
Comment: @MichaelHardy: yes, they are independent.
Answer: This is known as a moment of moment problem ... it is often convenient to express such problems in power sum notation namely:   $s_r = \sum_{i=1}^n X_i^r$. For your problem, express:
$$p = \sum_{i=1}^n (X_i - \bar{X})^2  = s_2 - \frac{s_1^2}{n}$$
Then, you seek $E[p^2]$, which is simply the $1^{st}$ RawMoment of $p^2$:

where:

RawMomentToCentral is a function from the mathStatica package for Mathematica, and
$\mu_i$ denotes the $i^{th}$ central moment of the population of $X$.

Note that the solution obtained is completely general and valid for any distribution whose moments exist ... not just for the Normal case.
For the Normal case:
For you specific case, i.e. with a $N(\mu, \sigma^2)$ parent, $\mu_2 = \sigma^2$ and $\mu_4 = 3 \sigma^4$, so the general solution simplifies to:
$$\sigma^4 (n^2 - 1)$$
Notes

As disclosure, I should add that I am one of the authors of the software used above.
Jonas asks (comments below):  "What is the theorem that the software is based on?"

The theorem is known as the fundamental expectation result, which expresses the expectation of an augmented symmetric function in terms of moments of the parent population. For more detail, see Stuart and Ord (1994, Section (12.5)), or see Chapter 7 of our Springer book: Rose and Smith (2002, section 7.4) ... a free download of which is available here:
http://www.mathstatica.com/book/bookcontents.html
It is possible to do such calculations by hand ... but it rapidly gets extremely tedious, and such problems are far more easily solved with computer. In fact, we found a number of errors in the tables in Stuart and Ord using the software, as well as errors in solutions derived by Fisher (the famous one).
Comment: Jonas, the very first comment to your question indicates how such derivations can be done. Your example, when fully expanded, is a quartic form in the data and therefore the expectation (because it's a linear operator) becomes a homogeneous polynomial (in a suitable sense) of the first four moments of $X_1$. *Mathematica* merely is doing that routine algebra under the hood. An algebraic theory has been developed; it is explained in great detail in Kendall & Stuart (5th Ed.).
Comment: @MichaelHardy: In your original post, why is the dof $n-1$ not $n$?
Comment: Thanks. What is the theorem that the software is based on? Is the derivation of the theorem simple?
Comment: References are also appreciated.
Comment: Nice question:  in reply, please see note added above (in body)
Comment: This answer seems to ignore the simple geometry involved.
Comment: It's a general approach to any such question:  not just the simple case considered here, nor the special assumption of Normality.
Comment: @MichaelHardy: as wolfies says, it seems the problem is distriubtion free.
Comment: wolfies: I am still looking for an analytical derivation for my problem. Thanks.
Comment: @whuber: I can't find that book. Can you post a solution for that? Thanks.
Comment: See [*Advanced Theory of Statistics*](http://books.google.com/books/about/Kendall_s_Advanced_Theory_of_Statistics.html?id=tW18thQWJQIC), Volume I, chapters 3 ("Moments and Cumulants") and 12 ("Cumulants of Sampling Distributions--(2)").
Comment: If the answer doesn't depend on the distribution other than through the first two moments, then it should be the same as the answer with a normal distribution wih those moments, and then you can use geometry including orthogonal projections.  However, I've deleted my answer for now.  I may do some further edits and then reinstate it.
Comment: @whuber: I only find a book of the second edition 1945 by Kendall himself. It has Ch3 for Moments and Cumulants, and there is no chapter for "Cumulants of Sampling Distributions--(2)". I quickly look through ch3, and didn't find where estimating moments of sample moments is mentioned, but I often miss things. Where in the book do you find it?
Comment: @Jonas : Could you post a separate question on that with a comment below it calling it to my attention?
Comment: @Jonas: The results are $(1/\sigma^2)\sum_{i=1}^n(X_i-\mu)^2\sim\chi^2_n$ and $(1/\sigma^2)\sum_{i=1}^n(X_i-\bar X)^2\sim\chi^2_{n-1}$.  Can you see why you would expect the latter sum of squares to be smaller than the former (except when $\bar X=\mu)\text{ ?}$ ${}\qquad{}$
Comment: @Michael Do you mean the latter sum of squares is bigger than the former instead, because the latter is "variance + squared bias", while the former is just variance?
Comment: No. The former is bigger.
Comment: @Jonas: I wrote this earlier answer about this: http://math.stackexchange.com/questions/61251/intuitive-explanation-of-bessels-correction/61409#61409
Comment: @Jonas : I am somewhat baffled as to what would make you think the latter sum is a variance plus the square of a bias.  Normally such things would be functions of $\mu$ and $\sigma$, i.e. of the parameters that index this family of probability distributions, and not functions of the random variables.

Mean of squared "sum of squared errors"


Has an NHL or NBA champion ever won all playoffs series with the same record?

Question: After losing game 3 of the 2019-20 NBA finals, the Los Angeles Lakers lead the Miami Heat 2-1 in the series. The Lakers got to the finals after beating the Portland Blazers, the Houston Rockets, and the Denver Nuggets in the first three rounds of the playoffs with a score of 4-1 in each of those series. The Lakers are now 2 wins away from winning the championship and winning all series 4-1.
(Note that the Lakers ended up winning the series 4-2 and didn't achieve this feat).
Since the NHL and the NBA playoffs have been played a best of 7 series on all rounds, has there ever been a team winning all rounds with the exact same score?
Answer: The NHL has been hosting best of 7 playoff rounds since the 1986-87 season. Looking at Hockey Reference there has been no Stanley Cup champion winning all rounds with the same score.
The NBA has been hosting best of 7 playoff rounds 2002-03 season where the San Antonio Spurs on that year became the first and only NBA team to to this date
winning all series with the same record.
Answer: Absolutely.  One example is the 2002-03 San Antonio Spurs, who won all four series they played 4 games to 2.


Is pizzicato louder than finger picking?

Question: Is pizzicato on a violin family instrument louder than finger picking an acoustic guitar?
It seems that way, since those instruments are played in large concert halls that a guitar would probably need an amplifier for.
And if it's true, what is the reason?
Comment: Bear in mind that, often, there are multiple violinists performing the same pizzicato note, which obviously makes it more audible in large concert halls.
Answer: "Pizzicato" may be performed on guitars as well as the other string members. The technique on both instruments exists in a dynamic curve and can be played any volume from "ppp" to snap pizz.
Violins might project more clearly due to a couple reasons: modern strings are typically steel or nickel-wound, holding more tension and producing a brighter, louder sound. Classical guitars  on the other hand use nylon strings which are lower tension.
The other reason violin pizz might be more easily heard is due to register. The two instruments in question only overlap for a portion of their respective ranges. Pizz at lower and extreme upper frequencies aren't as successful. More to say here but it falls outside the question so I'll omit.
So, it's difficult to say definitively as there are so many factors involved for sound production, but above are two reasons why a violin might have a "louder" pizzicato.


Searching for module filtering to Core compatibility 8.x, turned out it is only for 7.x

Question: Searching for module "Serial field" filtering to Core compatibility 8.x, it is listed, but going into the details turned out it is only for 7.x.
How should I avoid listing in 8.x if it is not really available?
Is there anywhere information  when it will be available?
Is it possible to get a notification when it is released for 8.x?
Answer: Select both "Core compatibility: 8.x" and "Stability: Has a supported stable release".
The combination will filter out modules like Serial Field, which has a stable version for D7 but only a -dev version for D8.
Unfortunately, this will also hide modules with only pre-releases (even -rc) for D8, some of which are in fact quite stable in practice.
There is no way to determine how far along a "non-stable" module is without actually going to the project page and looking at the releases/issue queue. There will usually be a message like this (this is the one for Serial):

This module has a pre-release version for Drupal 8. To find out more, follow this issue or download below.

You can subscribe to these issues to get email updates when someone comments on it, and thus get alerted about development progress.
Comment: Thanks Christoph, yes it is a good hint to subscribe to the issue to get any updates, however the perfect solution would be the possibility to get alert only if the module is ready to use "stable". It would be especially important in case of 7.x -> 8.x  module upgrades, since the e-mail traffic from Drupal could be decreased.


Convert pdf to text with colors

Question: I am trying to convert a pdf to text, and als extract the color information of the text.
I am trying to do this in golang, but using a command line tool I call from golang is absolutely acceptable.
I found pdftotext from poppler-utils, and its almost perfect. Only, it does not give me the color information.
I tried github.com/ledongthuc/pdf, which also does not give me color information.
Is there some other tool? Am I missing a way to do this with pdftotext?
Comment: Do you want to do PDF to Text or Text to PDF? Question title and content don't match.
Comment: @VikramKumar wow, I am sorry. Thanks for pointing that out. I want pdf to text
Answer: There is a C++ library called poppler (https://poppler.freedesktop.org), which allows extracting text from PDF Files including color.
There a go bindings here: https://github.com/cheggaaa/go-poppler

Convert pdf to text with colors


Alesis SamplePad resets itself / possible ground loop?

Question: I have an Alesis DM Lite e-drum kit , an Alesis SamplePad , a Roland UM-ONE mk2 MIDI-to-USB convertor , a Montarbo Eve 5 mixer and a MacBook Pro.
Sometimes I use the audio output from both drums (and Songsterr from an iPhone) into an external mixer and noticed that the SamplePad randomly resets itself every 15 minutes or so.
Sometimes I do not use the audio out from drums into the mixer but plug in the USB MIDI outputs into a MacBook Pro and use the oudio out from there. Noticed that the SamplePad does not reset itself.
I stopped using the audio output into the mixer configuration because I'd like to not destroy the equipment.Attached a rough schematics of the complete setup.
Any clues why the SamplePad resets itself ?
Is it a possible "ground loop" ? The power supplies of both Alesis drums are "wall wart" style, without ground on the plug. Both are mounted using plastic pads, so there is no common ground.
Comment: latest drivers?, faulty cable, grounding issues (you can get a little tingle from macbook pro cases), audio problem with mac osx (Can it handle 3 soundcards), is it trying to draw power from USB (try a powered hub), do you have your master clock set and everything else as slave
Answer: I added ground cables between the Alesis drum brains and the mixer. So far, no more resets.


How can I print the file size and other file info in a Views field template?

Question: I have created a content type with a number of fields including file fields. In the node template for that CT (node--unit.html.twig) I am able to get the details with the following code:
{% if content.field_files.0 %}
   {% for key, value in content.field_files if key|first != '#' %}
      {{ content.field_files[key]['#description']}}
   {% endfor %}
{% endif %}

Now I'm trying to get those same details for the field inside a view that lists nodes of that CT but the above code doesn't work. In fact all I can get from the field is the 'content' using the following code inside the views-view-field template (views-view-fields--units-e-resource-sheets.html.twig):
{{ fields.field_e_resources.content}}

All I can find using kint and other tools is the target_id attribute. Do I have to use this to retrieve those other details in the view?
Answer: Well with some pointers from colleagues I have found out what I was doing wrong!
In the node you have all that info already there but views and their displays are more stripped back to keep them 'lean' so you have to be explicit that you need that info...
Step 1 - add a 'relationship' to the field
In the settings for the display of the view, I added a relationship to the file from the field under the 'advanced' settings using the 'add' button and it shows like this:

Step 2 - add fields for the stuff from the relationship
Under the fields for the view display I can now add fields for the relationship I just created. I added one for the URI and one for the filesize using the 'add' button and they show like this:

Step 3 - build the template
Now you can use those just like any regular field in the template. Here is the code I'm using to build a link with the file extension, filesize and a link to download the file:
Download
  (.{{ fields.field_e_resources.content|striptags|split('.')[1] }})({{ fields.filesize.content }})

Conclusion
I couldn't access the details for the uploaded file because they aren't included by default so by building the relationships as required you can add to the available fields and get the job done!
Comment: Instead of displaying fields and templating your way through this (which  both can become a hell to maintain in the long run) use a view mode and field formatters for the node type and then let the view display the nodes with this view mode.
Comment: Do you think that is less complex when you have a very specific layout to build? I agree that templating is a bit hellish... But I like that everything is in one or a small number of places. If I understand your suggestion, each field would need to have mark-up added through the admin for each situation so the amount of mark-up would be the same but just in different places no?


Ask agent to join an agentset if attributes of agents in the agentset isn't match

Question: I'm having trouble to make "members" join "households" correctly. Each member has pre-defined variables, 'mbzone' 'abshid' 'abspid' and 'absfid', and some members could have exactly the same set of values of those pre-defined variables. In the same sense, household agents can have the same set of values for their pre-defined 'hhzone' and 'abshid'.
I would like to make member agents join household agents through the given conditions in the code below. But it turned out that some [memberlist] of households didn't contain only member agents with unique 'abspid' and 'absfid'. Meaning in the memberlist of a household agent there could be members with the same abspid and absfid. My question is how can I prevent this from occuring?
Thank you in advance. Sorry if what I wrote isn't clear to you, I'm more than happy to explain in a greater detail if necessary.
    breed [members member]
    breed [households household]

    members-own [mbzone abshid abspid absfid]
    households-own [hhzone abshid]

    to members-join-households
          ask members [
            set hhid one-of households with [hhzone = [mbzone] of myself and abshid = [abshid] of myself and [abspid] of hhmemberlist != [abspid] of myself and [absfid] of hhmemberlist != [absfid] of myself]
            ask hhid [
              let newmember myself
              set hhmemberlist (turtle-set hhmemberlist newmember)
            ]
          ]
          output-print "member-join-households is done"
        end

Comment: First problem is that you need to actually record that a member joins a household. You add the member to the agentset named hhmemberlist, but this is not a variable owned by households. Since your description of the problem suggests that you can access [memberlist] later, there must be some missing relevant code. The other problem is the bit that I think you intend to exclude duplicates (`hhmemberlist != [abspid] of myself`). This won't exclude for the same reason that the set {1,2,3} != {1}. You need membership not equality. See `member?` in NetLogo dictionary.
Answer: What @JenB said.  Additional consideration: test that you found such a household.
breed [members member]
breed [households household]

members-own [mbzone abshid abspid absfid hhid]
households-own [hhzone abshid hhmemberlist]

to members-join-households
  ask members [
    let _pid abspid
    let _fid absfid
    set hhid one-of households with [
      hhzone = [mbzone] of myself
      and abshid = [abshid] of myself
      and not member? _pid ([abspid] of hhmemberlist)
      and not member? _fid ([absfid] of hhmemberlist)
    ]
    if (hhid != nobody) [ ;did such a household exist?
      ask hhid [
        set hhmemberlist (turtle-set hhmemberlist myself)
      ]
    ]
  ]
  output-print "member-join-households is done"
end

But keeping member lists this way is very clumsy compared to using directed links, so I recommend that you switch to that. If you have members form directed links to a households, then a household's members are just its in-link-neighbors, and a member's hhid is just the household it links to.
Comment: Recommendation to use links: seconded.


Portability and reproducibility of RNG techniques

Question: I can use one of two methods to create a pseudo random number sequence that has two important characteristics - (1) it is reproducible on different machines, and (2) the sequence never repeats a number within range until all have been emitted.
My question is - do either of these methods have potential issues with regards to portability (OS, Python versions, etc)? For example, does anyone know if I would get one set of results on one system but a different one on another when XXX is true?
I'm not really asking for advice on which method to use per se, only if I should watch out for X on Y system when Z is true.
I have tried on a few versions of Linux, all 64bit, and they seem consistent, but I don't have easy access to Windows or 32 bit versions.
Note that they don't produce the same ranges as each other, but that's OK for my purposes. The numbers just have to appear random to the human eye.
Method 1generates a random sample from a range using native Python library functions. It's slow if I use large ranges (10m or more) but OK for relatively small ones, and is much easier to understand for people without a degree in maths :
import random
random.seed(5)
x = random.sample(range(10000,99999),89999)
for i in range(10):
   print(x[i])

Method 2uses an algorithm not from a Python library : (https://en.wikipedia.org/wiki/Linear_congruential_generator)
It's super fast even for massive ranges, but harder to understand and therefore spot potential issues with :
def lcg(modulus, a, c, seed):
  while True:
    seed = (a * seed + c) % modulus
    yield seed

m = 10000019
c = int(m/2)
a = 5653
s = a

g = lcg(m,a,c,s)
for _ in range(10):
  print(next(g))

Note I am more than open to alternatives; the original question was asked here : https://math.stackexchange.com/questions/3289084/generate-a-pseudo-random-predictable-non-repeating-integer-sequence-purely-math
Comment: @Dukeling - the RNG only has to be human-good (ie look like it's random) just so long as it doesn't repeat and can be reproduced from machine to machine. I suppose the question is nebulous, I guess portability issues might include how things are worked out under the hood that might make a seed on one machine behave differently to another. I tend to find other more experienced people just sort of "know" these things, so I thought it was worth asking. I will of course test as much as I can.
Comment: Just use a specific RNG. If your LCG meets your needs then use it, no reason to fret over it. python and almost every other programming language are all about portability, they wouldn't be of much use if their behavior changed from machine to machine.
Answer: Most portable version, IMO, would be LCG with period equal to natural word size of the machine. It uses register overflow for module which makes it even faster. You have to use NumPy datatypes to do that, here is simple code, constants a, c are taken from Table 4 here
import numpy as np

def LCG(seed: np.uint64, a: np.uint64, c: np.uint64) -> np.uint64:
    with np.errstate(over='ignore'):
        while True:
            seed = (a * seed + c)
            yield seed

a = np.uint64(2862933555777941757)
c = np.uint64(1)

rng64 = LCG(np.uint64(17), a, c)

print(next(rng64))
print(next(rng64))
print(next(rng64))

Both Linux x64 and Windows x64 as well as OS X VM works exactly the same.
Concerning reproducibility, the only good is to store first couple numbers and compare them with LCG output during app initialization stage - if they are ok, you proceed further.
Another feature of the LCG I like is it's ability to jump ahead in log2(N) time, where N is number of skips. I could provide you with code to do that. Using jump ahead you could ensure non-overlapping sequences for parallel independent random streams
UPDATE
Here is translation of my C code into Python/NumPy, seems to work. It could skip forward as well as backward in logarithmic time.
import numpy as np

class LCG(object):

    UZERO: np.uint64 = np.uint64(0)
    UONE : np.uint64 = np.uint64(1)

    def __init__(self, seed: np.uint64, a: np.uint64, c: np.uint64) -> None:
        self._seed: np.uint64 = np.uint64(seed)
        self._a   : np.uint64 = np.uint64(a)
        self._c   : np.uint64 = np.uint64(c)

    def next(self) -> np.uint64:
        self._seed = self._a * self._seed + self._c
        return self._seed

    def seed(self) -> np.uint64:
        return self._seed

    def set_seed(self, seed: np.uint64) -> np.uint64:
        self._seed = seed

    def skip(self, ns: np.int64) -> None:
        """
        Signed argument - skip forward as well as backward

        The algorithm here to determine the parameters used to skip ahead is
        described in the paper F. Brown, "Random Number Generation with Arbitrary Stride,"
        Trans. Am. Nucl. Soc. (Nov. 1994). This algorithm is able to skip ahead in
        O(log2(N)) operations instead of O(N). It computes parameters
        A and C which can then be used to find x_N = A*x_0 + C mod 2^M.
        """

        nskip: np.uint64 = np.uint64(ns)

        a: np.uint64 = self._a
        c: np.uint64 = self._c

        a_next: np.uint64 = LCG.UONE
        c_next: np.uint64 = LCG.UZERO

        while nskip > LCG.UZERO:
            if (nskip & LCG.UONE) != LCG.UZERO:
                a_next = a_next * a
                c_next = c_next * a + c

            c = (a + LCG.UONE) * c
            a = a * a

            nskip = nskip >> LCG.UONE

        self._seed = a_next * self._seed + c_next

np.seterr(over='ignore')

a = np.uint64(2862933555777941757)
c = np.uint64(1)
seed = np.uint64(1)

rng64 = LCG(seed, a, c) # initialization

print(rng64.next())
print(rng64.next())
print(rng64.next())

rng64.skip(-3) # back by 3
print(rng64.next())
print(rng64.next())
print(rng64.next())

rng64.skip(-3) # back by 3
rng64.skip(2) # forward by 2
print(rng64.next())

Anyway, summary of the LCG RNG:

With good constants (see reference to L'Ecuyer paper) it will cover whole [0...264) range without repeating itself. Basically perfect [0...264) -> [0...264) mapping, you could set
0,1,2,3,... as input and get whole range output
It is reversible, you could get previous seed back so mapping is actually
bijection, [0...264) <-> [0...264). See Reversible pseudo-random sequence generator for details
It has logarithmic skip forward and backward, so there is no problem to find
suitable intervals for parallel computation - start with single seed, and then next thread would be skip(seed, 264/N), next thread skip(seed, 264/N * 2) and so on and so forth. Guaranteed to not overlap
It is simple and fast, though not a very high quality RNG
Comment: @DavidWylie Please check update. Not sure about `way to restrict the max. digit length`. If you're talking about multiplier in LCG, it is taken from the paper and known to have good FoM. You could take the code and make it into 32bit LCG, just replace np.uint64 with np.uint32 and it should work, and then pick good values for `a` and `c` from prof.L'Ecuyer paper, and LCG constant(s) would be smaller
Comment: "I could provide you with code to do that" - yes please! I'm finding this whole subject fascinating. Is there a way to restrict the max. digit length in your example? I'm trying where possible to keep it to 7 digits.
Answer: LCGs are nice. If you want to make LCGs more understandable, you may implement it recursively instead of iteratively to highlight the recursive formula it's based upon. Do it only if you don't worry too much about complexity.
Otherwise, I think method 2 is clear enough for a PRNG.
Comment: But are they both portable? I'll edit the question to define that better, but I mean python versions, OS types & versions, etc.
Comment: I don't know how the random lib works (is it based on OS primitives ? What PRNG is it based on? ). Solution 2 works on any current python version 2.7 and 3, and any OS that has python.
Answer: There are many ways an algorithm (particularly a pseudorandom number generator) can have inconsistent results across computers. The most notable way is if the algorithm relies on floating-point numbers (which almost always are limited precision) and floating-point rounding.
Some programming languages are more prone to portability issues than others. For example, unlike in Python, inconsistent results can arise in C or C++ due to—

Undefined behavior of signed integer overflows, or
how the lengths of certain data types, notably int and long, are defined differently across compilers.

I am not aware of any way the Python code in method 2 can deliver inconsistent results across computers. On the other hand, whether method 1 can do so depends on whether random.sample is implemented the same way across all Python versions you care about and across all computers.


Forward Windows Events Logs to Rsyslog

Question: I would like to forward Windows Events Logs from all my desktop clients to a Linux box with rsyslog on.
Rsyslog provide a Windows agent to do just that but its 40 euros per license and when you have x amount of machines that cost adds up.
I was wondering if there is a FOSS alternative available I have tried searching the Google but haven't managed to find anything.
Hopefully someone might already faced this same problem and are using an alternative that they could recommend.
Answer: You might be also interested in nxlog as it provides a wealth of features such as rfc5424 syslog format, TLS/SSL, filtering, rewrite, etc. (note: I'm affiliated with the project).
Answer:
Snare Agent for
Windows
Datagram
SyslogAgent
eventlog-to-syslog

Forward Windows Events Logs to Rsyslog


Circle question involving area?

Question: Suppose you are given a square with an inscribed circle if the area of the square is 100 meters squared what is the area of the circle?
Answer: Hint
Diameter of the circle is also the length of a side of the square, $10$ units.
Comment: Would I do pir^2 with radious of five?
Comment: Exactly. BTW, this site allows you to use TeX mark up for the Math. So, you'd write the area of the circle $\pi r^2$ as `$\pi r^2$`. Regards,
Answer: Note that area of a square is given by $s^2$ where $s$ is the length of one of its sides (whichever side it may be, it doesn't matter for they are all equal.
So if $s^2=100 \implies s=\sqrt{100}=10 \text{ meters}$. The side of your square is $ 10$ meters. A circle inscribed in it would look something like this

Now Note that in the diagram, Since $\bar{DC}=10\text{ meters} \implies \bar{XY}=
\bar{DC}=10 \text{m}$.
So we now have that the diameter $XY$ of the circle at $O$ is $10\text{ meters}$.(I made a mistake while making the diagram, it should have been $10 \text{m}$ not $10 \text{cm}$, I hope this won't be much of a problem)
 Figuring out the area of a circle with a given diameter is an elementary geometry problem. The area of the circle hence is $\pi\cdot\big(\frac12\cdot10\text{m}\big)^2=(25\pi)\;\text m^2$
Comment: I gave this answer a +1 for filling in what my post lacked.
Comment: @KannappanSampath ahaha, thanks mate :)

Circle question involving area?


Schwarz's Lemma and functions with positive real part

Question: Problem:

Let $D = \{ z \in \mathbb C : |z| < 1 \}$. Suppose $f : D \to \mathbb C$ is a non-constant analytic function such that $\mathrm{Re} f(z) \geq 0$ for all $z \in D$.
(a) Show that $\mathrm{Re} f(z) \neq 0$ for all $z \in D$.
(b) Using a Möbius transformation and Schwarz's lemma, prove that if
  $f(0) = 1$, then $$ |f(z)| \leq {1+|z| \over 1-|z|}. $$
  What can be said if $f(0) \neq 1$?
(c) Show that if $f(0) = 1$, then $f$ also satisfies $$ |f(z)| \geq {1-|z| \over 1+|z|}. $$

Progress:
(a) We can use the open mapping theorem.
(b) We can compose a Möbius transformation $m$ that sends the right-half plane to $D$ with $f$. Then $h = m \circ f$ satisfies the hypotheses of Schwarz's lemma by construction. Simple manipulations of the inequality from Schwarz's lemma give the result.
(c) Looking at part (a), we know that $\mathrm{Re} f(z) \neq 0$, and so $f(z) \neq 0$. Thus, we can use the function $g = 1/f$ in the statement of part (b).
Question:
What about when $f(0) \neq 1$? I don't think you can get anything from $f(z)-f(0)+1$ unless $\mathrm{Re} f(0) < 1$. And you can't in general rearrange the inputs of $f$ because $1$ isn't necessarily in the image of $f$. Also, I don't think you can get anything from $f(z)/f(0)$ unless $f(0)$ is real, because otherwise the range of $f(z)/f(0)$ could extend into the left-half plane.
Answer: If $f(0)\ne 1$, you can consider $\phi\circ f$ where $\phi$ is an automorphism of the right half plane such that $\phi(f(0))=1$. Namely,
$$\phi(w) = \frac{w-i\operatorname{Im}f(0)}{\operatorname{Re}f(0)}$$
Comment: Should the numerator be $w- i \operatorname{Im} f(0)$? And is it important that $\phi$ be an automorphism? I don't see why it wouldn't work if $\phi$ was just any function that sends $f(0)$ to $1$, whose image is contained in the right-half plane when restricted to inputs in the right-half plane. I guess it needs to be analytic for Schwarz's lemma to apply.
Comment: @DanielHirsbrunner Thanks for pointing out the missing $i$. If $\phi$ is not  an automorphism, we can still get **an** inequality for $f$. But we won't get **the sharp** inequality for $f$.
Answer: $$\bigg|\dfrac{f-f(0)}{f+f(0)}\bigg|\leqslant 1$$ (think why? hint: Re $f(z)>0$)
Schwarz's lemma dictates that if we consider $\dfrac{f-f(0)}{f+f(0)}$ as a single function, we have:
$$\Bigg|\dfrac{|f|-|f(0)|}{|f|+|f(0)|}\Bigg|\leqslant\bigg|\dfrac{f-f(0)}{f+f(0)}\bigg|\leqslant|z|$$
Solve it: $$\dfrac{1-|z|}{1+|z|}|f(0)|\leqslant|f(z)|\leqslant\dfrac{1+|z|}{1-|z|}|f(0)|$$ (now consider
$|f|,|f(0)|,|z|$ as $x,y,z$ and solve it using the most elementary way)


How can an electric bass/guitar without pick ups work?

Question: I have seen electric guitars and basses that don't have any pick ups. For instance, here is an image of two Line 6 electric basses that have no pick ups:

How do these instruments work if they have no pickups?
Comment: Are you interested in Line6 Variax instruments particularly, or instruments without visible magnetic pickups generally?
Comment: @jonrsharpe nstruments without visible magnetic pickups generally
Answer: Piezo-electric transducers lurking under the saddles on the bridge! just like acoustic guitars have possessed for ages. Now bassists have the opportunity to use this technology. It's not new, but quite new on basses. Next may be a 'hybrid' with standard pups and p-e ts.
Comment: It might be worth mentioning that the Line6 Variax range (this is a [Bass 700](http://uk.line6.com/legacy/variaxbass700/)) are modelling guitars; they don't just have an acoustic sound like other instruments with piezos. The newer JTV and Standard Variax models (no longer available in bass or acoustic versions) *do* have traditional pickups as well.
Answer: As well as the in-bridge piezo pickups (either for acoustic tones or MIDI, which is what the Variax guitars use to feed the modelling system), there is a relatively rare second option: hidden pickups. The "Type I" Fender Marauder, for example, had magnetic pickups concealed under the pick guard:

On the same theme, as of a few days ago, Seymour Duncan are selling a Brad Paisley signature Secret Agent pickup, designed to be concealed under a Fender Esquire pickguard, expanding it from one pickup to two.
Comment: Interesting. Apparently, this idea never really caught on... wonder whether that's more due to practicality (hidden PUs can't be height-adjusted as easily as normal ones, and you can't get them as close to the strings) or because the look wasn't well-received.
Comment: @leftaroundabout a bit of Googling found a couple of Fender Esquires modded with one or two hidden pickups (e.g. [a Custom Shop Stealth](http://www.musiciansfriend.com/guitars/fender-custom-shop-masterbuilt-50sstealth-esquire-by-john-english)) to keep the original looks but add tonal options, but it certainly doesn't seem very popular. I'd guess a combination of the two reasons you mention - I quite like the look, but it does reduce adjustment and mean you'd need hot pickups and/or very low action (e.g. routed neck pocket).
Comment: AFAIK, it also was really, really expensive for that era to have 4 ( yes, four) hidden pickups on the guitar...


Consume web service using VB6

Question:
Possible Duplicate:
What is the best way to consume a web service from VB6?
Communicate with WCF Windows Service in VB6?

I have a simple web service (asp.net 2010) that will just return the inputted string.
the problem is i want to display it on vb6 (maybe on a msgbox) but i don't know how.
Answer: You might be interested in this other question which talks about hitting a RESTful web service from VB6. It uses the MSXML library which seems at first glance to wrap the actual act of sending an HTTP request.

Consume web service using VB6


Replacing a loud fan in a 1RU server

Question: I just bought a firewall that is very loud. The biggest problem is the two fans in the back (2 x Sunon 40mm fans) running at full speed.
The firewall is 1RU with pfSense installed on it.The CPU is a Pentium 4 2.8 GHZ with a heat sink on top.
The air is lead through a plastic tunnel across the unit with the fans in the back and the CPU in the front.
Do i really need two fans running at full speed? Can I reduce it to something like 5v? Will that affect the performance or do I even risk burning the CPU?
Are there any quiet fans I can replace them with?
Comment: Why does it matter? Servers should be in an isolated room with proper cooling and humidity. No one should really be able to hear them.
Comment: 2013. And you buy a firewall with a P4 CPU? SERIOUSLY? THat is end of life. Not as in "out of support" but so old it is likely to fail every day now. Man, where did you find some archeological artifact like that? Why did you buy that in the light of special ahrdware firewalls jus acouple of hundred USD for a LOT more performance?
Comment: It sounds like you made the mistake of buying 1U equipment for a small office where no proper server room is available. (I've been there.) These things are loud, and the only viable solutions would cost more than buying a tower server chassis.
Answer: I don't recommend this. These old Pentium 4's were hot. Very hot. Especially the old 400Mhz FSB processors.
By disabling or lowering those fans, you're probably going to overheat your server.
Swapping them for low-noise fans won't help much either. Low-noise fans work mostly by being huge and turning at a slow RPM. A 1RU server doesn't have much room, so the fans have to be tiny. Because they have to be tiny, they have to spin at a very high RPM in order to move the air required to keep the server cool.
These servers are designed to run in a rack a long way away from people, so they're not designed with noise in mind. Just be glad you don't have one of the newer 1RU servers that often have two rows of 8 fans back-to-back for a total of 16x 40mm fans.

Replacing a loud fan in a 1RU server


Issue with the definition of differential privacy

Question: The definition of differential privacy states that if $\mathcal{M}$ is  $(\epsilon,\delta)$-differentially private, then $\forall x,y$ such that $||x-y||_1\leq1$ and for all $S \subseteq \mathrm{Range}(\mathcal{M})$:
$$\mathrm{Pr}(M(x)\in S) \leq e^\epsilon \mathrm{Pr}(M(y)\in S) + \delta. $$
Now, suppose you were able to show that for any outcome $s_i$ (single element) that $\mathcal{M}$ was $(\epsilon,\delta)$-differentially private, i.e., $\mathrm{Pr}(M(x)= s_i) \leq e^\epsilon \mathrm{Pr}(M(y)= s_i) + \delta $. Then for a set $S=\cup_i s_i$, since $\mathrm{Pr}(M(x)\in S) = \sum_i \mathrm{Pr}(M(x)=s_i)$, we have that:
$$\sum_i \mathrm{Pr}(M(x)=s_i) \leq  e^\epsilon \sum_i \mathrm{Pr}(M(y)=s_i) + |S| \delta \implies$$
$$\mathrm{Pr}(M(x)\in S) \leq  e^\epsilon \mathrm{Pr}(M(y) \in S) + |S| \delta$$
The above is fine if we have $(\epsilon,0)$ with $\delta=0$, but non-zero delta causes a problem. There is a one to one corresponds between proving differential privacy over a single element and a set in the case when $\delta=0$. But the definition doesn't make sense to me for $\delta \neq 0$.
What am I missing?
Answer: To show that a mechanism/algorithm is $(\epsilon,\delta)$-differentially private you would have to show that the inequality holds for all subsets (technically all measurable subsets, which matters if the output is continuous).
So if you are in a situation where all you can show is that for single outputs $s$ that the inequality holds for some $\delta > 0$ then you might, as you see, have a hard time stitching together the same guarantee for all subsets. In most cases, however, you won't need to build up the result like that.
An intuition behind the parameter $\delta$ is that it is the probability that the stronger $(\epsilon,0)$ guarantee fails to hold. That is, the probability of producing an $s$ such that for some neighboring $y$ the bound fails to hold.
A related concept are composition bounds, which are used to analyze the aggregate privacy risk of releases from a collection of $(\epsilon,\delta)$-differentially private mechanisms. Composition bounds give an upper bound on the total privacy risk. However each individual risk has to satisfy the bound for all measurable subsets in the range of the mechanism.


Threading wxPython app with background process for multitouch detection

Question: So basically I have some code for multitouch detection and I would like to run it as a separate thread which sends custom events to a wxPython GUI upon a multitouch event.
Now I could post the code for the multitouch tracking but to use it you would require a trackpad, the server app and the detection code, so I think it's better to consider a simple example for the sake of the question.
So for example lets assume an event simulator sending an event every 10 seconds:
import wx
import wx.lib.newevent
import time

MultiTouchEvent, EVT_MULTITOUCH = wx.lib.newevent.NewEvent()

class EventSimulator:

    def __init__(self):
        self.eventdata = 0

    def Start(self):
        self.RunTUIO()

    def RunTUIO(self):
        while True:
            time.sleep(10)
            wx.PostEvent(GUI, MultiTouchEvent(self.eventdata))
            self.eventdata += 1

if __name__ == '__main__':

    MultiTouchTracker = EventSimulator()
    MultiTouchTracker.Start()

Now I would like to receive these events whenever they occur within a wxPython GUI (something like this):
import wx

class Frame(wx.Frame):
     def __init__(self, title):
         wx.Frame.__init__(self, None, title=title, size=(350,200))
         self.Bind(EVT_MULTITOUCH, self.handler)

     def handler(self, event):
         data = event.data,
         print data

if __name__ == '__main__':

    app = wx.App(redirect=False)
    window = Frame("My Basic GUI")
    window.Show()
    app.MainLoop()

The problem is I cannot workout how to combine these two pieces of code into a working example. As I understand it I need to run the event simulator as a separate thread from within the GUI code. Please can someone explain how to do this, thanks!
Answer: For details on multi-threading in Python see the docs for the threading module in the stock Python library.  There is an example of using it in a GUI in the Threads module in the wxPython demo, although there are other viable approaches as well.  (Deriving from the Thread class instead of just using one, etc.)  That demo module also shows a convenient way to make a new event class and binder using the wx.lib.newevent module.
Comment: Thanks, I have looked at several of the docs and also loads of examples but I struggled to get it working. I found they were usually about discussing some operation performed in a second thread when a button is pressed, not a second process running in parallel with the GUI for the complete execution time. But I will have another look!


Simplification of $a_0+\sum_{n=1}^{\infty} a_n\cdot \left[\sum_{k=0}^{\infty}b_k\cdot x^k\right]^n$ where I know the expressions for all the $a_n$

Question: I have this equation: $a_0+\sum_{n=1}^{\infty} a_n\cdot \left[\sum_{k=0}^{\infty}b_k\cdot x^k\right]^n$ where I know the expressions for all the $a_n$.
How can I simplify the multiplication of the two power series knowing that one series has an exponential $n$?
Thank you in advance for your answers.
Comment: Hi! I tried expressing the second sum raised to the power n by a sum with no power n, but I can't seem to find the coefficients of this new sum.
Comment: Hi, Sabrina, and welcome to Stack Exchange. What approaches have you tried so far?
Answer: Hint: Consider the multinomial coefficient as in
\begin{align*}
\left(\sum_{k=0}^\infty b_kx^k\right)^n=\sum_{j=0}^\infty\left(\sum_{{k_1+\cdots+k_n=j}\atop{k_1,\ldots,k_n\geq 0}}\binom{j}{k_1,\ldots,k_n}\prod_{l=1}^n b_{k_l}\right)x^j
\end{align*}


make UIView in UIScrollView stick to the top when scrolled up

Question: So in a UITableView when you have sections the section view sticks to the top until the next section overlaps it and then it replaces it on top. I want to have a similar effect, where basically I have a UIView in my UIScrollView, representing the sections UIView and when it hits the top.. I want it to stay in there and not get carried up. How do I do this? I think this needs to be done in either layoutSubviews or scrollViewDidScroll and do a manipulation on the UIVIew..
Answer: To create UIView in UIScrollView stick to the top when scrolled up do:
func createHeaderView(_ headerView: UIView?) {
    self.headerView = headerView
    headerViewInitialY = self.headerView.frame.origin.y
    scrollView.addSubview(self.headerView)
    scrollView.delegate = self
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let headerFrame = headerView.frame
    headerFrame.origin.y = CGFloat(max(headerViewInitialY, scrollView.contentOffset.y))
    headerView.frame = headerFrame
}

Comment: Make sure that the view you're intending to catch scrolls for has a delegate set, and that delegate is where scrollViewDidScroll will live. If you let your controller implement the protocol , you can assign the delegate as 'self' in the controller like [this](http://stackoverflow.com/a/14096093)
Comment: I tried this and it works fine but my view get translucent and i tried everything but not succeeded, so please can you help me the way or reason why it is happening. Its only get translucent for a time till it sticks to top
Answer: Swift Solution based on EVYA's response:
var navigationBarOriginalOffset : CGFloat?

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    navigationBarOriginalOffset = navigationBar.frame.origin.y
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    navigationBar.frame.origin.y = max(navigationBarOriginalOffset!, scrollView.contentOffset.y)
}

Answer: If I recall correctly, the 2010 WWDC ScrollView presentation discusses precisely how to keep a view in a fixed position while other elements scroll around it. Watch the video and you should have a clear-cut approach to implement.
It's essentially updating frames based on scrollViewDidScroll callbacks (although memory is a bit hazy on the finer points).
Comment: hmm.. basically you have to check if that sectioned UIView is on top and then keep it there right? My issue is how to determine if that sectioned UIView is on "top"
Comment: To determine which view is on top, you can ask the superview for it's array of subviews, e.g. NSArray *subviews = [superview subviews]. Then, ask your array for the indexes of the subviews you want to compare, e.g., NSUInteger oneIndex = [subviews indexOfObject:viewOne], twoIndex = [subviews indexOfObject:viewTwo]. Once you've go the indexes for both of the subviews, simply evaluate which is greater to determine which is on top of the other.
Comment: when I say on top, not meaning one on top of each other.. but I mean which is at contentOffSet.y
Comment: Knowing nothing else about your design, it's hard to say precisely how you should "know" which is on top. My thinking would be that the view controller has a sense of which is the "current" section, based on section info coming for your model, or some other basis. Trying to determine which section/header should be at the top sheerly in the scope of views (i.e., you could do it be comparing yOffsets, or rectContainsRect or similar), does not seem like an ideal strategy imo.
Answer: Evya's solution works really well, however if you use Auto Layout, you should do something like this (The Auto Layout syntax is written in Masonry, but you get the idea.):
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    //Make the header view sticky to the top.
    [self.headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_top).with.offset(scrollView.contentOffset.y);
        make.left.equalTo(self.scrollView.mas_left);
        make.right.equalTo(self.scrollView.mas_right);

        make.height.equalTo(@(headerViewHeight));
    }];

    [self.scrollView bringSubviewToFront:self.headerView];
}

Comment: Unfortunately this forces you to recreate the layout constraints with each frame of scroll movement. Instead, what you should do is have a container contain the `UIScrollView` and make the header's top equal to the *container's* top, not the scrollview's top plus content offset. Doing it this way allows you to set up the constraints once.
Comment: @AnthonyMills thanks for the comment! Helped me understand a lot.