Intuition for the Cauchy Quantile

Question: I've got these two plots, the first is a plot of the cauchy quantile function evaluated at 500 random standard uniforms. The next plot is the cumulative sum of the qunatiles. For example, if elements of the first plot are $x(1), x(2), \cdots,x(500)$. Elements of the second plot are: $y(1) = x(1), y(2)=x(1) + x(2), \cdots ,y(n) = x(1)+\cdots+x(n)$.
I am trying to see whether my code is correct and whether my results are intuitive. Here are the plots:

If they are correct, are these jumps due to the fact that we have a tan function (in the qunatile function of the cauchy) ? Almost like the tan is a bit unstable in the values it produces? (intuitively not mathematically)?
Answer: No, this is about the heavy tails of the Cauchy distribution. As you can see in the upper plot, when you draw very small or very large uniform r.v.s you get extreme quantiles. Compare
qcauchy(.01)
[1] -31.82052
> qcauchy(.001)
[1] -318.3088
> qnorm(.01)
[1] -2.326348
> qnorm(.001)
[1] -3.090232

These extreme quantiles then obviously will also have a strong effect on the sum.
Ploting the realizations against the uniform random numbers instead of against the index maybe makes this more transparent:
x=runif(500)
plot(x,qcauchy(x))

Comment: A related (and perhaps more penetrating) question is whether the O.P.'s experiment will ever stabilize if it is modified to track the *mean* of the quantiles.  *It will not*--but to see that you would need to provide a more detailed analysis of just how "heavy" the Cauchy tails are. Another way to make this point is to reconsider your argument for a Student $t(1.01)$ distribution (the Cauchy is a Student $t(1)$). Your plot will look almost identical and you will get qualitatively similar behavior in your simulation--*but this time the mean will converge to zero.*

Intuition for the Cauchy Quantile


Spring batch exit message on workflow failure

Question: I have a Spring batch step executing a tasklet that polls for files on a remote server:
public class MyConfiguration extends AbstractConfiguration {

    @Bean
    @Qualifier("pollStep")
    public Step pollStep() {
        return stepBuilderFactory.get("pollStep")
                                 .tasklet(filePollingTasklet())
                                 .listener(promoteContextListener())
                                 .build();
    }

    @Bean
    @StepScope
    private Tasklet filePollingTasklet() {
        return ((stepContribution, chunkContext) -> getStatus(stepContribution, chunkContext));
    }

    private RepeatStatus getStatus(StepContribution stepContribution, ChunkContext chunkContext) {
        //some code
        Map<String, Boolean> result = poller.pollForFile(myContext, sourceInfo);
        return RepeatStatus.FINISHED;
    }

}

It polls for up to 100 minutes, retrying every so often...
When it is out of while loop polling for file in pollForFile() method, it throws a RuntimeException if it cannot find the file.
the spring batch STEP EXECUTION table records the EXIT MESSAGE for this step with exception as follows when the batch fails in this instance:
org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connectionat org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:565)at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:835)at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:809)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)at com.sun.proxy.$Proxy177.rollback(Unknown Source)at org.springframework.transaction.support.TransactionTemplate.rollbackOnException(TransactionTemplate.java:168)at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:144)at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273)at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82)at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375)at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:258)at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:208)at org.spring

I would like to understand why the exit message is a jpa rollback error and not the runtime exception? How can I ensure that in this case the runtime exception message is what gets stored in Exit Message in spring batch table when the step fails.
Answer:
I would like to understand why the exit message is a jpa rollback error and not the runtime exception?

Because this is what actually makes your step fails. The stack trace you shared is truncated, but the runtime exception should be the cause of org.springframework.transaction.TransactionSystemException, which in turn is the cause of your step failure.
Comment: This is another question and not related to the initial one. I see you have asked it here: https://stackoverflow.com/questions/67491044/spring-batch-long-running-tasklet-database-timeout. Please accept this answer here as I believe it answers your initial question and I will try to help on the other one.
Comment: Thanks, how to avoid this error? Have I misconfigured my step somewhere ?
Comment: You can't avoid this error (if the transaction fails then the step will fail as well), unless you catch runtime exceptions around your code and decide what to do with them.
Comment: it seems the connection to my sqlserver database is being reset or times out due to long running tasklet. in this case if I increase the timeout interval for sql server reset, will this suffice or is there a setting to keep the connections alive ?
Comment: appreciate if you can help to resolve the other one which I've been stuck with for some time


Do unit test programs in C# based on unit test library provided by Visual Studio need entry point?

Question: I saw that for some code with some methods, its unit tests based on the unit test library provided by Visual Studio don't have entry point like main method in them.
So are the test programs compiled into executables?
Where are their entry points?
Thanks.
Comment: The tests themselves aren't an application host, the test runner application is.  It would use the compiled test libraries to execute tests.
Answer: They're compiled as libraries (dlls). They do not have an entry point.
A test runner will load the library, inspect the public methods (and optionally filter based on attributes, depending on the runner), and then invoke each method.
Answer: The Test Runner, in most cases Visual Studio, inspect assemblies to find classes marked with [TestClass] and methods marked with [TestMethod] attribute. Effectively what would go in a "Main" method is handled transparently to the developer.


Problemas com a minha tabela

Question: Boa tarde galera, estou pegando um problema aqui na minha table
Se eu defino td's para "GCOI,GCTA E GOAG", a linha da GCTA fica com um background color diferente das demais, caso eu defina th's pra "GCOI,GCTA E GOA", eu perco as linhas que dividem as célula. Como posso resolver isso?
Segue abaixo os códigos:

.datagrid table {    /* definição da tabela dentro da div que tem a class datagrid */
    border-collapse: collapse;
    text-align: left;
    width: 100%;
}

.datagrid { /* definição da div */
    font: normal 12px/150% Arial, Helvetica, sans-serif;
    background: #fff;
    overflow: hidden;
    border: 1px solid #3D0F99;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

.datagrid table td, .datagrid table th { /* definição das td's e th's dentro da div da class dategrid */
    padding: 8px 20px;
}

.datagrid table thead th { /* definição das thdead's e das th's dentros das thead's da div class dategrid */
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #0700fc), color-stop(1, #362B7F) );
    background:-moz-linear-gradient( center top, #0700fc 5%, #362B7F 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#0700fc', endColorstr='#362B7F');
    background-color:#0C0299;
    color:#FFFFFF;
    font-size: 16px;
    font-weight: bold;
}

.datagrid table thead th:first-child { /* definição do filho(primeiro elemento) de thead da tabela que está na div class dategrid */
    border: none;
}

.datagrid table tbody td { /* definição das tag's td que estão dentro da tag tbody da div class dategrid */
    color: #6B6B6B;
    border-left: 4px solid #EBF9FF;
    font-size: 14px;
    border-bottom: 4px solid #E1EEF4;
    font-weight: normal;
}

.datagrid table tbody .alt td { /* definição da tag tbody e td da class alt da div class dategrid */
    background: #FFE3E3;
    color: #0A0808;
}

.datagrid table tbody th:first-child { /* definição do filho(primeiro elemento) da tag tbody que contém a tag td da div class dategrid*/
    border-left: none;
}

.datagrid table tbody tr:last-child th { /* definição do filho(ultimo elemento) da tag tbody que contém a tag tr para td da div */
    border-bottom: none;
}

        Setor
        Entrada M.M
        Entrada Atual
        Saída M.M
        Saída Atual
        Saldo M.M
        Saldo Atual
        Estoque M.M
        Estoque Atual
        Idade em Estoque M.M
        Idade em Estoque Atual
        Lead Time M.M
        Lead Time Atual

        GCOI

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

        GCTA

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

        GOAG

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

Answer: A cerca do background do GCTA, ele faz referência a uma classe no css (class="alt"), alterando a cor para vermelho. Segue o código com a cor igual a todas.

.datagrid table {    /* definição da tabela dentro da div que tem a class datagrid */
    border-collapse: collapse;
    text-align: left;
    width: 100%;
}

.datagrid { /* definição da div */
    font: normal 12px/150% Arial, Helvetica, sans-serif;
    background: #fff;
    overflow: hidden;
    border: 1px solid #3D0F99;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

.datagrid table td, .datagrid table th { /* definição das td's e th's dentro da div da class dategrid */
    padding: 8px 20px;
}

.datagrid table thead th { /* definição das thdead's e das th's dentros das thead's da div class dategrid */
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #0700fc), color-stop(1, #362B7F) );
    background:-moz-linear-gradient( center top, #0700fc 5%, #362B7F 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#0700fc', endColorstr='#362B7F');
    background-color:#0C0299;
    color:#FFFFFF;
    font-size: 16px;
    font-weight: bold;
}

.datagrid table thead th:first-child { /* definição do filho(primeiro elemento) de thead da tabela que está na div class dategrid */
    border: none;
}

.datagrid table tbody td { /* definição das tag's td que estão dentro da tag tbody da div class dategrid */
    color: #6B6B6B;
    border-left: 4px solid #EBF9FF;
    font-size: 14px;
    border-bottom: 4px solid #E1EEF4;
    font-weight: normal;
}

.datagrid table tbody .alt td { /* definição da tag tbody e td da class alt da div class dategrid */
    background: #FFE3E3;
    color: #0A0808;
}

.datagrid table tbody th:first-child { /* definição do filho(primeiro elemento) da tag tbody que contém a tag td da div class dategrid*/
    border-left: none;
}

.datagrid table tbody tr:last-child th { /* definição do filho(ultimo elemento) da tag tbody que contém a tag tr para td da div */
    border-bottom: none;
}

        Setor
        Entrada M.M
        Entrada Atual
        Saída M.M
        Saída Atual
        Saldo M.M
        Saldo Atual
        Estoque M.M
        Estoque Atual
        Idade em Estoque M.M
        Idade em Estoque Atual
        Lead Time M.M
        Lead Time Atual

        GCOI

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

        GCTA

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

        GOAG

        NAN

        NAN

        NAN

        NAN

        NAN

        NAN

Answer: Boa tarde!
Remova a class alt em:

Ela que está gerando este conflito.
Abraços.

Problemas com a minha tabela


How to pass date arg to my cloudbuild yaml

Question: My cloudbuild.yaml exists of the following:
- name: 'gcr.io/cloud-builders/gsutil'
  args: ['-m', 'cp', '-r', '/workspace/api-testing/target/cucumber-html-reports', 'gs://testing-reports/$BUILD_ID']

- name: 'gcr.io/cloud-builders/gsutil'
   args: ['-m', 'rm', '-r', 'gs://studio360-testing-reports/latest']

- name: 'gcr.io/cloud-builders/gsutil'
  args: ['-m', 'cp', '-r', '/workspace/api-testing/target/cucumber-html-reports', 'gs://testing-reports/latest']

This way I always have my latest report seperated from the older ones. But can I pass a {date} arg or something into my first line so I can have a visual order of all the older reports?
(Because there is no way to rank the files by last modified in the gcp storage/bucket)
Thanks
Comment: You could try using variables values defined by you. [Here](https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values#using_user-defined_substitutions) you will find more information about it. Keep in mind you will need to follow a set of rules when defining user-defined variables. Let me know if this is what you are asking for! I hope it helps.
Comment: I am looking in to it, I tried a substitution _FOO = bar and it started building but just stopped at the beginning of the step with the substitution. I don't see no clear errors only at the end of my log it says

``` CommandException: 1 file/object could not be transferred. ```

You got any clue? Also: I'm not sure how to put a var date can I just use something like var date = new Date();?
Comment: Can I just use something like var date = new Date();? It's not possible to add variables like that in the cloudbuild.yaml. Your best bet is to use [user-defined substitution](https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values#using_user-defined_substitutions). The problem might be related with unmatched keys. Please make sure to follow the rules presented in the documentation to avoid mismatched keys when building your cloudbuild.yaml. I hope it helps.
Answer: Change the first block to this:
- name: 'gcr.io/cloud-builders/gsutil'
  args: ['-m', 'cp', '-r', '/workspace/api-testing/target/cucumber-html-reports', 'gs://testing-reports/${_DATE}_$BUILD_ID']

Then run this:
gcloud builds submit . --substitutions _DATE=$(date +%F_%H:%M:%S)
Then you would have something like this in the bucket:
gs://testing-reports/2020-02-13_14:01:40_8a6a7ed0-62e0-43ed-8f97-aa6eca9c2834
Explanation here and here.

EDIT:

For automatic builds started by Cloud Build triggers, use this cloudbuild.yaml:
steps:
- name: 'gcr.io/cloud-builders/gsutil'
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    gsutil -m cp -r $FILENAME gs://$BUCKET/$FILENAME-$(date +%F_%H:%M:%S)-$BUILD_ID

This allows the builder to use bash to execute gsutil, so the bash command "date" can be used inside the command.
Good explanation of the syntax by Googler here, and info about entrypoint here.
Comment: Thats the answer I was looking for @asbovelw, it works fine. Thank you!
Comment: You save my life haha thanks!
Answer: Pretty sure you should be able to bash out and do something like this:
- name: 'gcr.io/cloud-builders/gsutil'
  entrypoint: 'bash'
  args:
  - -c
  - |
    gsutil -m cp -r /workspace/api-testing/target/cucumber-html-reports gs://testing-reports/$BUILD_ID-$(date +%m-%d-%Y)

To my knowledge, you can't run system commands in sub. variables or env. variables. (or at least I haven't been able to figure out how)
Comment: sadly this doesn't work either, it just append the literal string
Comment: How are you running the build? via the CLI? Or a github trigger?
I run via Git trigger and it works just fine for me... could try this? (seems redunant though)

`- name: 'gcr.io/cloud-builders/gsutil'
  entrypoint: 'bash'
  args:
  - -c
  - |
        echo $(date +%m-%d-%Y) > /workspace/my_date &&
    gsutil -m cp -r /workspace/api-testing/target/cucumber-html-reports gs://testing-reports/$BUILD_ID-$(cat /workspace/my_date)`
Comment: I made a step to echo the date, touch the file with the date, then show and here are the results:

`Status: Downloaded newer image for gcr.io/cloud-builders/metadata:latest
gcr.io/cloud-builders/metadata:latest
2020/02/13 14:54:09 Started spoofed metadata server
2020/02/13 14:54:09 Build id = localbuild_f943b41f-5fd2-4237-9b6a-b6e362e4b2dc
2020/02/13 14:54:09 status changed to "BUILD"
BUILD
: Already have image (with digest): gcr.io/cloud-builders/gsutil
: 02-13-2020
: -rw-r--r-- 1 root root 0 Feb 13 20:54 myfile-02-13-2020.txt`

(ps - I ran this locally)
Comment: I forgot to add, you might have to escape the command and add two "$" (so - `$$(date)`)
Comment: Thanks for the help @Lance Sandino I used the solution above (automatic cloud build) but thanks for the effort!


OSX automatic login disabled, cannot re-enable

Question: I'm a sysadmin for a school that has a iMac that is setup as the security computer, the security software needs to be running in order to record from the cameras, so the computer needs to be able to automatically log in after a reboot.  Right now it does not automatically login.  If I goto System Preferences > Accounts > Login Options.  The drop down for Automatic Login is greyed out (disabled) and says "Disabled" in the drop down (The lock icon is un-locked, its not that simple).  If I go to System Preferences > Security the checkbox "For all accounts to this computer > Disable Automatic Login" is ticked.  If I try to un-tick, I get the message "Turning off disable automatic login has no effect.  To enable automatic login you must use the Accounts preferences pane."  It gives me the option to "Open Accounts", "Cancel", or "OK".
This has put me into a loop, I can't seem to get the automatic login drop down to be enabled so I can select the user to automatically login.
I have repaired permissions on the drive, and that didn't fix it.
Also, in the Login Options pane, there are more options greyed out (disabled):

Display login window as: "List of Users" or "Name and password"
Show the Restart, Sleep and Shutdown buttons
Show password hints

Any thoughts?
Comment: Did you enabled firevault? If you did you wont be able to turn auto-login on
Answer: Sounds like you're using MCX policy to disable those options. Are you running Open Directory?
Comment: Yes, the system is joined to Open Directory, but in the login options I've disabled the option for remote users to login to the computer.
Comment: That was it, all I needed to point me in the right direction.  I opened up work group manager and saw the computer sitting in a group that was applying this restriction.  Thanks!
Answer: I had the same problem.  Under system preferences go to security and privacy. Under the general tab the disable automatic login box is checked by default. To uncheck it you have to click the lock in the lower left hand corner.  Hope this helps.


Script to alert when Root Password Expiry in AIX

Question: I am trying to build a script in AIX which I am planing to run as cron job.
I want the script to check if the root password will expire with in 10 days and trigger an email. I have written a script to trigger mail but I am not sure how to write a script for password expiry for root.
This is script for sending mail .
#!/bin/sh
sendmail -t -F 'ABC ' -f 'firstname.lastname@example.com' << test.mail
From: ABC <email@example.com>
To:  email@example.com
Subject:
Password expired in 10 days

This script works fine .
But i want a script for AIX that will check root password expiry within 10 days of expiry date .
Comment: Great, it works for you too.
Comment: https://www.ibm.com/developerworks/community/blogs/brian/entry/don_t_let_your_aix_passwords_expire5?lang=en
Comment: Above script works very nicely for me on my AIX 5.2 box.
Comment: `root         -160      Thu Jun 13 13:41:47 2013  Thu Jun 13 13:41:47 2013  0` - This is what it says for root .
Answer: you can do it like,
lastupdate=lssec -f /etc/security/passwd -a lastupdate -s <username> | cut -d " " -f2 |cut -d "=" -f2
maxage=lsuser -a maxage itimadm | cut -d " " -f2 |cut -d "=" -f2
maxage=$(($maxage*7))
expires=$(($lastupdate+(60*60*24*$maxage)))
expire_date=perl -le 'print scalar localtime $expires
daysremaining=ceil((($expires - $now) / (60*60*24)) - 1)
echo $username,$maxage,$expire_date,$daysremaining
Though this is not full fledged script but logic is present (improvement is possible :) ) and you can add if clause for checking condition (daysremaining<10) then call your mailing script which will send mail to respective users.


Finding out the total number of email accounts in a cPanel server

Question: I need to find the total number of email accounts in a cPanel Linux server.
This must include only the active accounts. i.e. only those accounts whose MX is pointing to this server.
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: You can do it using following one liner.
for i in `cat /etc/localdomains`; do grep -E ^$i: /etc/userdomains ; done | sed 's/://g' | awk '{ system("cat /home/"$2"/etc/"$1"/passwd") }' 2>/dev/null | wc -l

Answer: I have tried this script which checks the users in '/etc/userdomains' and displays the count of total mail accounts in the server.
sed "s|:||g" /etc/userdomains | awk '!/^\* nobody/{print $1, $2 | "sort | uniq" }' | awk '{print "cat /home/"$2"/etc/"$1"/passwd"}' | sh 2>/dev/null | wc -l
but I am looking for a script which could search the /etc/localdomains.
Regards,
Ajo
Answer: You can try this too:
find /home*/*/etc -name passwd -exec cat {} \; | wc -l


Backbone click event being fired multiple times

Question: I have seen many questions about this, but no one is solving my problem.
I have a page with a main div which has one div one-image by default. There is also a button so you can add other divs. So I have an event click which appends this other div template with a "remove" button. Like this:
Image stack

     ...
     Add another image
     ...

Image template

View
events: {
          'click #addImage' : 'addAnotherImage',
          'click #removeImage' : 'removeThisImage'
},

addAnotherImage: function(e) {
  var another = $('#another-image-template').html();
  $('.images-stack').append(another);
},

removeThisImage: function(e) {
  $(e.currentTarget).closest('.one-image').remove();
}

This works fine. When I click the "Add" button, it adds a new one-image div under the last one; and when I click the "Remove" button, it removes the div I clicked. If I change the view and come back to the same view (always created with new in Backbone), the image-stack has one div one-image only, which is fine. But when I click the "Add" button, it appends two one-image divs. And if I repeat the previous steps, it appends three.
I have checked and the function is being called twice (and thrice and so...). I don't understand why this is happening since remove() is removing the object from the DOM and I always initialize the view with new. Any ideas?
Comment: When the handlers are called several times there are 2 possible reasons: Either you, after appending elements, have several nested elements  that all of them match with the handler selector, as the `click` event _propagates_ the handler is called once for each element. Or the elements have several direct event handlers attached to them, this happens when one binds handler in the context of another handler.
Comment: IDs must be unique, you are generating invalid markup. Can you provide a [fiddle](http://jsfiddle.net) that can reproduce the problem?
Comment: Oh man! Totally my bad! But bad news are that I still have the same issue. And even worst, it works fine on http://jsfiddle.net/oy1t38ho/
Comment: Could it be something related to the way I use Backbone? Maybe it *saves* somehow the DOM?
Comment: Sounds good! I'll take a look at that and come back to you ;)
Comment: Technically,  tags without href properties are also invalid....not that that's your problem....
Answer: You problem is probably related to not closing and unbinding your views. It is called zombie views. By calling this.remove() and this.off() should cleanup all references to the view.
Have a look at the following:

this.remove() - http://backbonejs.org/#View-remove
this.off() - http://backbonejs.org/#Events-off

and

https://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
Backbone zombie views & good practice
Preventing backbone zombie views
Comment: It was a bit hard for me to solve this, because my Backbone app was not using Backbone "workflow" correctly. But this showed me the way!


On a representation of the Moebius strip

Question: Let $f:\, (x,y,z)\in C\mapsto ((x^2-y^2)(2+xz),2xy(2+xz),yz)\in\mathbb{R}^3$. I have to prove that the image of this function is homeomorphic to the Moebius strip. I would like to use the universal property of quotient spacea, but I need to show that $f(x,y,z)=f(x',y',z',)$ if and only if $(x,y,z)=\pm(x',y',z')$. Is there any simple way to prove this? (I got lost in too many calculations).
EDIT
The domain of the map is the cylinder $C=\{(x,y,z):x^2+y^2=1,|z|\leq1\}$.
Definition of Moebius strip: the quotient space $C/\sim$ where $P\sim Q\iff P=\pm Q$.
Comment: Which definition of the Möbius strip do you use? The image of $f$ is certainly unbounded, are you sure that $f$ is correctly specified?
Comment: yes, you are right the domain is the cylinder!
Comment: And what **exactly** is the definition of the Möbius strip as a quotient space?
Comment: Well, for instance one can see it as the quotient space $C/\sim$ where $P\sim Q$ if and only if $P=\pm Q$. This is actually the definition I'm using. That's why I thought I needed to show that the same happens for $f(C)$.
Comment: Okay, that is one of many possible definitions. You should add that to your question. People do not wamt to read comments to get all necessary information.
Answer: Write $C = S^1 \times [-1,1]$ with $S^1 = \{ w \in \mathbb C \mid \lvert w \rvert = 1\}$ . Then
$$f(w,z) = ((2+\text{Re}(w)z) w^2,\text{Im}(w)z) \in \mathbb C \times \mathbb R .$$
Therefore it is obvious that $(w,z) = - (w',z')$ implies $f(w,z) = f(w',z')$.
We have $\lvert \text{Re}(w) \lvert \le 1, \lvert z \rvert \le 1$, thus $\lvert \text{Re}(w)z \rvert \le 1$ and therefore $2+\text{Re}(w)z \ge 1 > 0$.
If $f(w,z) = f(w',z')$, then

$(2+\text{Re}(w)z) w^2 = (2+\text{Re}(w')z') (w')^2$
$\text{Im}(w)z = \text{Im}(w')z'$.

Taking the absolute value on both sides of the first equation, we get $2+\text{Re}(w)z = 2+\text{Re}(w')z'$, i.e. $\text{Re}(w)z = \text{Re}(w')z'$. Add this and $i$ times the second equation and get

$wz = w'z'$.

Taking the absolute value on both sides of this equation gives $\lvert z \rvert =  \lvert z' \rvert$. Thus $z  = \pm z'$. If $z \ne 0$, we immediately see from 3. that  $(w,z) = \pm (w',z')$. If $z = 0$, the first equation shows that $w^2 = (w')^2$, i.e. $w =  \pm w'$. Thus again $(w,z) = \pm (w',z')$.


How to notate 3 quarters framed by eighths?

Question: Context: I recently transcribed a Piano solo piece in MuseScore 4. It was based on a different person's transcription that used ♩ = 70 as tempo marking. My transcription initially used the same tempo. However now I think the tempo should actually be ♩ = 140, so I used MuseScore's feature "Paste with double duration" to 'convert' the notes.
But there are some parts that look "weird" to me, but I'm unsure if its actually weird or really the best representation there is.
Here's the part in original:

As you can see the durations of the bass line are split up and tied such that the quarters are visually groupable.
This is what that part looks like after pasting with double duration:

What looks "weird" to me is that now obviously not quarters but just the half notes are properly visually split. I am not experienced in writing sheet music or playing by sheet, so I have no idea how people playing by sheet would feel about that.
If I wanted quarters to be visible, I'd end up with a lot of ties:

If I combine as many split notes as possible, I end up with essentially four quarters for the right hand and three quarters framed by eighths for the left hand, making most notes misalign:

Or I could make sure that every time a note is played by the right hand there's a corresponding aligned note for the left hand:

What would be the way people reading sheet music are expecting the durations to be?
Comment: By the way: This isn't really about *tempo*. I assume the other person's transcription and yours "sound the same," they just look different. One big difference is how long each measure is: their one-bar excerpt is a two-bar phrase for you.
Comment: Yes, they sound the same. But counting to the other transcription felt like I had to hold back a lot, it felt more natural to count double the tempo.
Answer: Let's discuss the pros and cons of each version, albeit slightly out of order:
Version 3

This one is mainly non-ideal because of the half note that crosses the midpoint of the first measure. A sight reader could easily glance at this and think that the left-hand C occurs simultaneously with the right-hand F, which obviously isn't true. This is the least successful version.
Version 2

The rhythm in this one is very clear, but the notation is very cluttered, and cluttered to the point that I could easily envision a performer getting lost in all of the eighth notes, misconstruing which notes are articulated and which are tied, etc. This one is passable, but not ideal.
Version 4

This one is better than Version 3 because it de-clutters some of the eighth notes. I would argue that just about any musician would read this without problem, although they would probably find the left hand at the end of m. 2, with the four Cs in a row, to be a bit strange. This is fine, but it could be better.
Version 1

Notation to me is about clarity and efficiency, and I think this version handles both perfectly. The eighth-quarter-eighth rhythm in the left hand is standard fare for any musician worth their salt, so that syncopation won't present any problems. Furthermore, the left-hand ties into beat 3 show clearly how the right-hand melody aligns with the left-hand syncopations. This, in my opinion, is the optimal version.
Comment: May be worth mentioning that in 4/4/ time it's quite usual to span beats 1–2 or 3–4, but not to span beats 2–3. So notation in the style of Version 1 is very common. (This answer explains why it makes sense — but familiarity is also important.)
Answer: No, your score is fine. There is no actual need to have a note on each beat, because you have something like a "beat grouping". A 4/4 measure will have strong parts (1,3) and weak parts (2,4). This means the meter actually can be felt as divided by 2. You ties make clear where in this subdivision you are. Mean while the figure 8th - 4th - 8th is a very common syncopation. So this is a rhythm any somewhat experienced musician should be able to feel within on  macrobeat of this binary subdivision. If this was a more complex rhythm such as dotted 8th - 4th - 16th you should definitely split this in a way to make the 4ths visible. But in this case you do not need to do so, in fact it most liekly would become harder to understand the rhythm if you did.


Existence of open set in a continuous mapping

Question: Give $f: A\rightarrow B$ is a closed , onto and continuous mapping. For $b\in B$, let $C$ be an open set in $A$ s.t $\ f^{-1}(b)\subset C$. Show that there exists open set $D$ in $B$ with $b\in D$ s.t $f^{-1}(D)\subset C$.
My attempt Since $f$ is an onto and continuous mapping, for every open set $C$ in $A$,  $f(C)$ is an open set in $B$. Since $\ f^{-1}(b)\subset C$, $f(C)$ contains $b$ and is open. Since $f$ is closed, there must exists an open set $D\subset B$ such that $f(C)$ contains $D$. Thus $f^{-1}(D)\subset C$ (Q.E.D).
I'm not quite sure if this proof is correct, especially where I used the hypothesis $f$ is closed. Can someone please help with this problem?
Comment: Why exactly does $f$ map open sets onto open sets? (Continuity says that the preimage of open sets is open, not the other way round. Consider $x\mapsto x^2$, which maps $(-1, 1)$ onto $[0, 1)$).
Comment: Just notice, that $f(A\setminus C)$ is closed, because $A\setminus C$ and also $f$ are closed.
Comment: @Thomas: That's a mistake indeed...:( (I need $f$ to be bijective for that to be true, but I can't show that:P). Can you please help with the proof?
Answer: $f$ is a closed mapping, and so if $U \subset A$ is closed in $A$, $f(U)$ is closed in $B$.
For $b \in B$, there is an open $C \subset A$ s.t. $f^{-1}(b) \subset C$ since $f$ is onto ($A$ is such a set). Consider any such $C$.
$A\backslash C$ is closed, so $f(A\backslash C)$ is closed (as $f$ is a closed mapping).
That is to say, $B\backslash f(A\backslash C)$ is open in $B$, also $ b \in B\backslash f(A\backslash C)$.
Further, $$\begin{align*}
f^{-1}(B\backslash f(A\backslash C)) &= A \backslash f^{-1}(f(A\backslash C))\\ &\subset A \backslash (A \backslash C) \\&= C
\end{align*}$$
Where the first line follows as $f$ is onto, and the second is from the fact that $A \backslash C \subset f^{-1}(f(A\backslash C))$
Thus take $D = B\backslash f(A\backslash C)$ and we get $b \in D$, $f^{-1}(D) \subset C$
Comment: Many thanks for your great help!
Comment: You're very welcome. It was an interesting question to try.
Comment: can you give this problem a try as well? http://math.stackexchange.com/questions/1260993/zero-dimensional-space-in-rn


How many positive integers less than 1,000,000 have the sum of their digits equal to 19?

Question: How many positive integers less than $1,000,000$ have the sum of their digits equal to $19$ ?

I tried to answer it by using stars and bars combinatorics method.
The question says that sum of $6$ digit numbers { considering the number as $abcdef$ } is 19.
Hence, I can write it as $a + b + c + d + e + f = 19$ ,but this assumes that $a,b,c,d,e,f >= 0$ .

But, here each digit lies between 0 and 9. So, how stars and bars method will be modified according to this domain ?
Comment: You'll need for three or more of the digits $a, b, c, d, e, f$ to be nonzero (since no two of the digits in $\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9\})$ sum to $19$.  Stars and Bars (two forms) does not take into account
Answer: If we treat each positive integer with fewer than six digits as a six-digit string with leading zeros, we seek the number of solutions of the equation
$$a + b + c + d + e + f = 19 \tag{1}$$
in the non-negative integers subject to the restrictions that $a, b, c, d, e, f \leq 9$.  A particular solution of equation 1 corresponds to the placement of five addition signs in a row of $19$ ones.  For instance,
$$1 1 1 + 1 1 + 1 1 1 1 + 1 1 1 1 1 1 + + 1 1 1 1$$
corresponds to the solution $a = 3$, $b = 2$, $c = 4$, $d = 6$, $e = 0$, and $f = 4$. Hence, if there were no such restrictions, the number of solutions would be equal to the number of ways we can insert five addition signs into a row of $19$ ones, which is
$$\binom{19 + 5}{5} = \binom{24}{5}$$
since we must choose which five of the $24$ symbols (five addition signs and nineteen ones) are addition signs.
However, we have counted solutions in which one or more of the variables exceeds $9$.  There can only be one such variable since $2 \cdot 10 = 20 > 19$. We must exclude solutions in which one of the variables exceeds $9$.
We count the number of solutions in which $a > 9$.  Since $a$ is an integer, then $a \geq 10$.  Hence, $a' = a - 10$ is a non-negative integer. Substituting $a' + 10$ for $a$ in equation 1 yields
\begin{align*}
a + b + c + d + e + f & = 19\\
a' + 10 + b + c + d + e + f & = 19\\
a' + b + c + d + e + f & = 9 \tag{2}
\end{align*}
Equation 2 is an equation in the non-negative integers.  Consequently, the number of solutions of equation 1 in which $a > 9$ is
$$\binom{9 + 5}{5} = \binom{14}{5}$$
By symmetry, there are
$$\binom{14}{5}$$
solutions for each of the six variables that could exceed $9$.  Hence, the number of positive integers less than $1,000,000$ with digit sum $19$ is
$$\binom{24}{5} - \binom{6}{1}\binom{14}{5}$$
Answer: Note - 1,000,000 has sum of digit = 1.
Then we are concerned with numbers between 1 - 999,999.
Let us assign an alphabet for every digit.
u+v+w+x+y+z=19 has 24C5= 42504
if u=10 then v+w+x+y+z =9 has 13C4 = 715
if u=11 then v+w+x+y+z =8 has 12C4 =495
if u=12 then v+w+x+y+z =7 has 11C4=330
if u=13 then v+w+x+y+z =6 has 10C4=210
if u=14 then v+w+x+y+z =5 has 9C4=126
if u=15 then v+w+x+y+z =4 has 8C4=70
if u=16 then v+w+x+y+z =3 has 7C4=35
if u=17 then v+w+x+y+z =2 has 6C4=15
if u=18 then v+w+x+y+z=1 has 5C4=5
if u=19 then v+w+x+y+z=0 has 4C4=1
The total is = 2002 for u>10
Now, any one u, v, w, x, y, z can be more than 10.
Hence, 2002 x 6 = 12012
So, answer = 42504 - 12012 = 30492
The answer will be 30492.
Comment: The answer is correct numerically and methodically; only the writeup leaves something to be desired.
Comment: This answer is seriously unclear and looks false to me.
Comment: @chris where i was wrong?
Answer: The number is $<$ $1000000$ ,
$\Rightarrow$ it contains 6 digits.
Each of these digits can be one of $0,1,2,3....9$
$\Rightarrow$ problem reduces to no of integral solution to the following equation
$d_1+d_2+d_3+d_4+d_5+d_6 = 19$ where $0\leq d_i \leq 9$
Using generating function :
$$\begin{align*} & \ \ \ \left [ x^{19} \right ]\left ( 1+x+x^2+x^3+....+x^9 \right )^{6} \\ &=\left [ x^{19} \right ]\left [ \frac{1-x^{10}}{1-x} \right ]^{6}\\ &=\left [ x^{19} \right ]\left ( 1-x^{10} \right )^{6}. \sum_{r=0}^{\infty}\binom{5+r}{r}.x^{r} \\ &=\left [ x^{19} \right ]\left [ \sum_{r=0}^{6}.\binom{6}{r}.\left ( -x^{10} \right )^{r} \right ]. \left [ \sum_{r=0}^{\infty}\binom{5+r}{r}.x^{r} \right ] \\ &=\left ( -1 \right )^{0}*\binom{24}{19} + \left ( -1 \right )^{1}*6*\binom{14}{9} \\ &=30492\\ \end{align*}$$
NOTE:
1. $1+x+x^2+x^3+.....x^n = \frac{1-x^{n+1}}{1-x}$
2. $\frac{1}{(1-x)^n} = \sum_{r=0}^{\infty}\binom{n+r-1}{r}.x^r$
3. $\left [ x^{19} \right ]$ means coefficient of $x^{19}$ of the whole expression.
Answer: Add one to each of $a,b,c,d,e,f$ and make the sum $25$.  All the new variables have to be positive.  You still have to worry about the fact that none of the new variables can exceed $10$
Comment: Define new variables $a'=a+1$ etc.  Then $a'$ can range from $1$ to $10$, so none of the new variables can be zero.  That makes stars and bars work.  The sum has to be increased to account for the $+1$s.  Unfortunately basic stars and bars will count cases where some of the variables are greater than $10$, so you need to subtract those off.
Comment: Sorry !! Didn't get exactly . Can u please be more elaborative ?


Simple proof on set difference

Question:
Prove if $A$ is a subset of $B$, then $A\backslash B= \emptyset$.

I used a proof by contrapostive.
The assumption ($A\backslash B$ not being equal to the empty set) means there exists an $x$ such that $x\in A\backslash B$ implies $x\in A$ and $x\not\in B$. This implies that $A$ is not a subset of $B$.
How is this proof, thanks.
Comment: Your proof is fine in terms of content, but in terms of presentation you have mixed notations.  You wrote both $A/B$ and $A\setminus B$ to denote the set difference.  Only the second should be used.  Writing by hand I'd expect you would have access to whatever symbols you want, but if typing here you can find several symbols [here in this MathJax and $\LaTeX$ primer](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).  In particular `\not\subset` and `\not\in`
Comment: Thanks ill learn to format
Comment: "How is this proof"  I'm not sure what this means.  Are you asking if that is a valid proof?  Yes, it is valid.  Or are you asking how does that prove $A \not \subset B$?  Or are you asking how does that prove $A\setminus B = \emptyset$?
Comment: i was just asking if it was valid
Answer: Your proof is correct. You could have avoided using the contrapositive and just proved it directly:

Suppose that $A \subseteq B$. If there is some $x \in A \setminus B$, then $x \in A$ and $x \not\in B$, which contradicts the assumption that $A \subseteq B$; hence $A \setminus B$ has no elements, so is empty.

It doesn't really make much of a difference to the structure of the proof, though—the original statement is of the form $p \Rightarrow \neg q$, so its contrapositive is also of the form $q \Rightarrow \neg p$ (where $p$ means '$A \subseteq B$' and $q$ means '$A \setminus B$ is inhabited').
But as a general rule, it's nice not to use indirect proof techniques if you don't have to.

Simple proof on set difference


Finding the conditions of (x,y,z,t) for them to belong to the span of a set of vectors

Question: So I got this math exercise, and I don't know how to go about it:
In $\mathbb{R}^4$, $S$ is the subspace spanned by the following set of vectors:  $(1, 1, 1, 0) , (1, 2, 1, 1) , (2, 0, 1, 1) , (3, 0, 4, 2)$
Find the condition (or a series of conditions) that $(x, y, z, t)$ must meet to so they belong to $S$.
Answer: If a vector is in the subspace spanned by those four vectors, then we have:
$$\begin{pmatrix} x\\ y\\ z\\ t\\
\end{pmatrix} =\alpha \begin{pmatrix}1\\1\\1\\0\\ \end{pmatrix}+\beta \begin{pmatrix}1\\2\\1\\1\\ \end{pmatrix} + \gamma \begin{pmatrix}2\\0\\1\\1\\\end{pmatrix} + \delta \begin{pmatrix}3\\0\\4\\2\\\end{pmatrix}$$
For some coefficients $\alpha, \beta, \gamma, \delta$. This is just saying that it can be expressed as a linear combination of these vectors.
In the context of linear algebra, this can be expressed as
$$ \begin{pmatrix}1&1&2&3\\1&2&0&0\\1&1&1&4\\0&1&1&2\\ \end{pmatrix} \begin{pmatrix} \alpha\\ \beta\\ \gamma\\ \delta\\
\end{pmatrix}=\begin{pmatrix} x\\ y\\ z\\ t\\
\end{pmatrix} $$
This should allow you to find your answer.


Does a power of endomorphism factor through a projective?

Question: Let $A$ be a ring (e.g. an $R$-algebra over a noetherian local ring $R$), $M$ an indecomposable $A$-module, and $f$ an endomorphism, which is not an isomorphism.
Now, we assume that the endomorphism ring of $M$ is a local ring.
Then, does a power of $f$ factor through a projective $A$-module?
If $A$ is a finite-dimensional algebra over a field, then this is true by the Harada-Sai lemma.
Thank you.
Answer: In full generality, the answer is no.  Take $A = K[[x,y]]$, the ring of power series in variables $x$ and $y$ with coefficient in a field $K$.  Take $M = K[[x,y]]/\langle y \rangle$.  Then the endomorphism ring of $M$ is isomorphic to a ring of formal power series $K[[\phi]]$, where an endomorphism $p(\phi) = \sum_{i=0}^{\infty} a_i \phi^i$ applied to a $z\in M$ is defined by
$$
 p(\phi)(z) := \sum_{i=0}^{\infty} a_i xz.
$$
Finally, take $f=\phi$.  Then $f$ is not an isomorphism, and no power of $f$ vanishes.  However, there are no non-zero morphisms from $M$ to $A$ (and thus to any projective module).  So $f$ does not factor through a projective module.

If, moreover, the endormosphism ring of $M$ is Artinian (which happens if $A$ is an algebra over a field and $M$ is of finite length over $A$, for instance), then any non-invertible endomorphism of $M$ is nilpotent.  Thus a power of $f$ vanishes, and trivially factors through a projective module.


AuthorizedKeysCommand in OpenSSH without user

Question: Is it possible to configure OpenSSH to invoke the AuthorizedKeysCommand without a matching user being registered locally on the host machine?
Comment: What would you expect `sshd` to do upon successful authentication? The user name would still not be valid, so who would it run as after successful authentication?
Comment: what do you exactly mean by "a user not being registered in the host machine"? A user can be available from a remote source. Or do you mean a user not available _at all_?
Answer: If you mean a non-local user, yes, it is perfectly possible, freeIPA, for example, can store users' public keys in its LDAP backend:
ipa user-mod user –sshpubkey='ssh-rsa AAAA…'

and uses:
AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys
AuthorizedKeysCommandRunAs nobody

in /etc/ssh/sshd_config effectively delegating the validation of authorized keys to `sssd', which in turn is configured to contact the freeIPA server.
References from the freeIPA site here.
Comment: It depends on how users are looked up in your system, are you using `sssd`, plain LDAP, any other? what's in the `passwd` line in your `/etc/nsswitch.conf`?
Comment: Thanks @dawud, the Name Service Switch configuration was the piece I was missing.
Comment: I can only get the AuthorizedKeysCommand to fire if a local user exists.  Is there perhaps a conflicting setting somewhere else that I haven't been able to pin down?
Comment: @dawud @chadmaughan I am having the same issue and am not clear on what changes were necessary in nsswitch.conf.  I currently have `passwd:    compat systemd`.  Thanks in advance.
Answer: No.
sshd cannot authenticate users that do not exist according to the system it is running on. The user must exist, though they need not be defined locally.


Amplification of guitars

Question: Does using more than one amplifier help increase volume to a greater extent or a little bit? I am currently using a 60 watt and 75 watt amp. I don't think the power just adds up.
What do you think about this guys? Also, using a ABC/Y switcher pedal gives three outputs and all can be activated together. Hence, we can connect to three amps. Is it feasible in relation to sound?
Comment: @Qweevs: even an unbuffered splitter does not make the part signals any quieter, it only puts the three amp inputs in parallel, thereby reducing the _impedance_ to be fed. If you then directly plug in a passive guitar, this may indeed effect a volume reduction, though the loss of treble you mention is more likely a problem (the lower impedance drains away the pickups' resonance peak). None of this should happen if you have an active guitar or there are any other effect pedals before the splitter.
Comment: It will make your overall sound louder. I have 17watt and 40watt valve amps that crank when I run stereo. Overall, it'll just make your sound bigger. Depending on what style of music you play it may actually be too big and sound muddy and gross.
Comment: Also, you should watch out for those ABC/Y switchers as many of them do not include a buffer. They will split your guitar signal into 3 other guitar signals, however without a buffer, it will make each of those 3 outputs 3 times as less volume since it's splitting into 3 outputs. A ABC/Y switcher can also make your tone sound darker and have less clarity. It may also increase feedback and you may experience more buzzing from your amplifiers.
Comment: Thankyou guys for yur answers, i use a buffer pedal in front of signal chain..helps me for soundng good :)
Answer: The number attached to watts is not actually a very good guide to how loud it is. Other factors come into play, such as speaker efficiecy, sort of cabinet. Others may explain that better. However, when I use two of the same amps (for kbds, but it's the same idea) the sound seems to be more than twice. Say they're 50 watts each, for example, two makes 100 watts. Like for like, a 100 watt amp is theoretically only half as loud again as the 50 watt. So it appears that the two amps will be louder. But there again, like I said earier, there's the difference of twice as many speakers, too (two against one).
Comment: Er, I don't think it's clear what you're saying here.
Answer: No, the power ratings cannot simply be added up, in order to estimate the resulting loudness.
The power rating of the amplifier - assuming we're dealing with a consistent measure of power (more on that at the end) - is only part of the story when it comes to volume.
Sound pressure levels
Sound is essentially a wave that propagates through air. Therefore, what interests us in terms of loudness is how much the air is moving.
Sound pressure - saith Wikipedia:

is the local pressure deviation from the ambient (average, or equilibrium) atmospheric pressure, caused by a sound wave.

Sound pressure level (SPL) is:

a logarithmic measure of the effective pressure of a sound relative to a reference value.

(Source: the Wikipedia article linked to above.)
Like for like, a sound source that generates a higher SPL will be perceived as louder than one that produces a lower SPL.
It's important to note that distance is a factor. We know that something closer to us is going to be louder than something further away, but it's easy to forget to include distance in SPL comparisons.
Amplifiers and speakers
It should be clear, but bears reminding of, that whatever the amplifier may be doing, it is the speaker that creates the actual sound pressure that allows us to hear the sound.
The speaker converts the amplifier's electrical power output into motive force that creates a soundwave. The sound pressure will depend on the speaker's power rating, its efficiency and the volume of air it is able to physically shift (which, in turn, depends on its diameter). It is possible for the power ratings of the amplifier and speaker to be mismatched (albeit, this is not common these days), plus there are physical limits to what SPL an individual speaker is capable of generating. We should be aware that at no point is the entire power provided by the amplifier converted into sound - some will always be lost.
Given that the volume of air capable of being moved by a single speaker is a limiting factor in the SPL it can produce, one option is to increase the number of speakers - provided the amplifier has sufficient power to drive all of them.
More than one (combo) amplifier being driven with the same signal will be louder than a single amp, simply because more air is being moved.
Hearing sensitivity
The sensitivity of the human ear to sound varies with frequency (the linked Wikipedia article includes a chart that shows equal loudness contours by frequency). Our hearing is most sensitive around 3 kHz and - generally speaking - less sensitive to low frequencies than higher ones. This means a lower SPL will be needed for sounds at around 3 kHz to be perceived to be as loud as sounds at 100 Hz, say.
What this means, in practice, is the tone you set up will have an effect on perceived loudness. Accentuating the higher mid-range (from around 1 kHz to around 5 kHz) will make your amplifier sound louder than if the same frequency range is "scooped" out.
Phase cancellation
Whenever you have more than one speaker generating soundwaves, the waves from both sources will interact. This can have an effect on the resulting sound.
When two waves are perfectly in sync (in phase) - their peaks and troughs coincide - the amplitude of the resulting wave is increased, giving a louder sound. When they are reversed (180 degrees out of phase) - peaks from one wave meet troughs from the other - they cancel one another out (in an ideal scenario, the result would be silence; incidentally, this is how the "karaoke" function in a stereo works).
In a practical setting, the sound waves from separate speakers will not be ideal copies of one another and they will be interacting with reflected waves from the floor, ceiling and walls. This results in complex phase relationships that may lead to damping of certain frequencies (comb filtering), overall volume reduction and other sonic unpleasantness.
When using more than one amplifier, it's a good idea to position the amplifiers so that the direct signals from all speakers are in phase as much as possible.
Bottom line
Higher-rated amplifiers produce more electrical power that can be used to drive speakers, which - other things being equal - will result in greater volume than a lower-rated amplifier. However, power rating is not a measure of volume, in itself.
Using a greater number of speakers and amplifiers will give a louder sound, but there isn't a simple relationship in play, such as double the number of speakers (amplifier) means twice as loud.
The perceived volume of any combination of speakers and amplifiers might be increased by altering their position (a simple trick is to position the speaker closer to ear level, by lifting it from the floor) and equalization.
A word on power ratings
When it comes to amplifiers, marketing operates under the assumptions that more power means louder means better. For this reason, we should be wary of stated power, unless we are told how it was measured.
Maximum power measured during brief peaks ("peak power") tells us exactly nothing, other than that the seller is trying to pull a fast one. A meaningful measure of power should track the power level over many cycles, examples of such methods include average and root mean square (RMS) power output (I shall leave an investigation of the exact methodologies as an exercise for the Reader).
What is important, from a practical perspective, is that when the power ratings of different amplifiers are being compared, we should ensure that they were all measured using the same method (subject to the caveats above). The numbers given by different methods will vary greatly.
Answer: Guitar amps are not a PA: they are part of your instrument's sound.  Using more than one will result in inconsistent sound.  This is exacerbated since we are talking about two different amps of comparable volume here.  They will have different frequency response and most particularly different but correlated phase response.  As a result, you will get some weird directional characteristics for various frequencies, and different timbre in different directions.  You are usually quite better off with one larger instrument amp, or with miking your amp and using a common band or venue PA.
Comment: There are disadvantages to using two amps, but they are not acoustic in nature.
Comment: @ToddWilcox - when using two amps, is it at all possible that the speakers of each may be out of phase with each other? Not something I've noticed, but...
Comment: You're quite right that different amps may interact in strange ways, though especially with electric guitar you should never equate _strange&unpredictable_ with _undesirable_... by signal processing standards, electric guitar transmission is essentially just _broken_, yet we say it sounds good.
Comment: Quite often different amps and cabs are used in parallel deliberately **because** of the tonal qualities that to introduces.

Amplification of guitars


Java SoftReference: Soft references were not collected before the occurrence of OOM

Question: it's my test code
public class Test {

    public static SoftReference<byte[]> cache = new SoftReference<>(new byte[0]);

    public static List<byte[]> list = new ArrayList<>();

    public static void main(String[] args) {
        try {
            func();
        } catch (OutOfMemoryError e) {
            sniff();
            e.printStackTrace();
        }
    }

    public static void func() {
        byte[] bytes = new byte[1024 * 1024];
        cache = new SoftReference<>(bytes);
        for(;;) {
            byte[] tmp = new byte[1024 * 1024];
            list.add(tmp);
        }
    }

    public static void sniff() {
        byte[] bytes = cache.get();
        if (bytes == null) {
            System.out.println("recycling data.");
        } else {
            System.out.println("object still live");
        }
    }
}

The program output is as follows

object still live

I don't understand? why?
This is a sentence I found in the official documentation of Oracle:

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.

Even more strangely, if I put byte[] bytes = new byte[1024 * 1024]; cache = new SoftReference<>(bytes); into the for loop; like this
public class Test {

    public static SoftReference<byte[]> cache = new SoftReference<>(new byte[0]);

    public static List<byte[]> list = new ArrayList<>();

    public static void main(String[] args) {
        try {
            func();
        } catch (OutOfMemoryError e) {
            sniff();
            e.printStackTrace();
        }
    }

    public static void func() {
        for(;;) {
            byte[] tmp = new byte[1024 * 1024];
            list.add(tmp);
            byte[] bytes = new byte[1024 * 1024];
            cache = new SoftReference<>(bytes);
        }
    }

    public static void sniff() {
        byte[] bytes = cache.get();
        if (bytes == null) {
            System.out.println("recycling data.");
        } else {
            System.out.println("object still live");
        }
    }
}

the program output is as follows:

recycling data.

I have two question:

The first writing method,Why did the garbage collector not collect SoftReferences
Why do these two writing methods produce such a difference

I analyzed the dump file and the first way of writing really doesn't collect it
Answer: The important thing to note in the quote from the official documentation is in bold below:

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.

Softly-reachable objects are those that can be reached by the "root" context only through soft references or weaker (reference).
In your first example you are putting your byte[] in a List; this creates a path of strong references to the object - that is why it is not garbage collected in the end.
In your second example, the array referenced by the tmp variable is added to the list and lives at least as long as the list lives. The array referenced by the bytes variable however is created and is strongly referenced in the scope of func() only. The only reference that escapes is the soft reference. So, before the OutOfMemoryError it is guaranteed that this softly reachable array, the last you created in the loop, will be garbage collected. The ones you created in the loop iterations before the last are already unreachable, because even the soft reference to them that survived the loop is overwritten in the next iteration.
You could try changing the list to be List<SoftReference<byte[]>>; you will find out that all of the soft references will have been cleared before the OOME.
Comment: I think I understood the first example. Garbage collector not collect the "Softly-reachable" object because it not really Softly-reachable object. Variable `bytes` have a strong references to object when occur `OutOfMemoryError`.
I changed my code to `cache = new SoftReference<>(new byte[1024 * 1024])` and not use variable to reference the byte array.The program print ` recycling data` prove that it has been collected.
Is my understanding correct?
Comment: But I can't understand the sencond example. Variable `bytes` also have a strong reference to byte array when occur `OutOfMemroyError`.Why can it be collected
Comment: Oh! I understand in the second example. Becauser of the variable's scope!In a loop, the pointer to a variable is constantly changing. Therefore, on the surface, the array is strongly referenced and associated with the variable 'bytes'. In fact, in the next loop, the object it references will be overwritten, and the previous old object can be collected.Is this correct?


Prove that for all real numbers $a$ and $b$, if $0 < a < b$ then $0 < a^2 < b^2$

Question: I'm trying to prove:

For all real numbers a and b, if $0 < a < b$ then $0 < a^2 < b^2$

This is my first class in formal proofs, and I'm not sure where to begin. I'd appreciate any help
Comment: Just use the fact that if $c \in \mathbb{R}_{>0}$, then $0 < a < b$ implies $0 < ca < cb$.
Comment: See [Axioms for total ordered fields](https://en.wikipedia.org/wiki/Real_number#Axiomatic_approach): if x ≥ 0 and y ≥ 0 then xy ≥ 0. Thus, from $0 < a < b$ we get $0 < a^2<ab$ and also $0 < ab < b^2$.
Comment: You can write $b^2-a^2=(b-a)(b+a)$.
Answer: Look at your list of axioms regarding $\lt$.  You should have one that says something like if $c,d,e \gt 0, d \lt c,$ then $ed \lt ec$  You should also one that says $\lt$ is transitive, that if $c \lt d$ and $d \lt e$ then $c \lt e$.  You want to use these by finding something between $a^2$ and $b^2$ that you can relate to both.


If $f$ is a function differentiable at $a$ find: $\underset{h\rightarrow 0}{\lim} \frac{f(a+7h)-f(a-9h^2)}{h}$

Question: If $f$ is a function differentiable at $a$ find:
$\underset{h\rightarrow 0}{\lim} \frac{f(a+7h)-f(a-9h^2)}{h}$
I am struggling to understand what to do. I tried brute forcing this question and I get $\frac{f(a)-f(a)}{0}$ which makes no sense to me. Any clarification would be appreciated.
Answer: Hint: $\dfrac{f(a+7h)-f(a-9h^2)}{h} = \dfrac{(f(a+7h) -f(a)) + (f(a) - f(a - 9h^2))}{h} = 7\cdot\dfrac{f(a+7h) - f(a)}{7h} + 9h\cdot \dfrac{f(a) - f(a - 9h^2)}{9h^2}$
Comment: Those steps make sense to me. However, I am struggling with 2 things. 1, I don't have a grasp with what exactly I am trying to solve and how an answer would even remotely look like. 2. I sense I am missing some definition or rule. By any change does $\dfrac{f(a+7h) - f(a)}{7h}$ equal $7f^{'}(x)$ or something?
Answer: Why not to try with Taylor series ?
$$f(a+7h)=f(a)+7 h f'(a)+\frac{49}{2} h^2 f''(a)+O\left(h^3\right)$$
$$f(a-9h^2)=f(a)-9 h^2 f'(a)+O\left(h^3\right)$$
$$f(a+7h)-f(a-9h^2)=7 h f'(a)+h^2 \left(\frac{49 f''(a)}{2}+9 f'(a)\right)+O\left(h^3\right)$$
$$\frac{f(a+7h)-f(a-9h^2)}h=7  f'(a)+h \left(\frac{49 f''(a)}{2}+9 f'(a)\right)+O\left(h^3\right)$$ and $h \to 0$.


Text box with line wrapping

Question: Is it possible to display text in a box through Matplotlib, with automatic line breaks?  By using pyplot.text(), I was only able to print multi-line text that flows beyond the boundaries of the window, which is annoying.  The size of the lines is not known in advance…  Any idea would be much appreciated!
Answer: The contents of this answer were merged into mpl master in https://github.com/matplotlib/matplotlib/pull/4342 and will be in the next feature release.

Wow... This is a thorny problem... (And it exposes a lot of limitations in matplotlib's text rendering...)
This should (i.m.o.) be something that matplotlib has built-in, but it doesn't.  There have been a few threads about it on the mailing list, but no solution that I could find to automatic text wrapping.
So, first off, there's no way to determine the size (in pixels) of the rendered text string before it's drawn in matplotlib.  This isn't too large of a problem, as we can just draw it, get the size, and then redraw the wrapped text.  (It's expensive, but not too excessively bad)
The next problem is that characters don't have a fixed width in pixels, so wrapping a text string to a given number of characters won't necessarily reflect a given width when rendered.  This isn't a huge problem, though.
Beyond that, we can't just do this once... Otherwise, it will be wrapped correctly when drawn the first time (on the screen, for example), but not if drawn again (when the figure is resized or saved as an image with a different DPI than the screen).  This isn't a huge problem, as we can just connect a callback function to the matplotlib draw event.
At any rate this solution is imperfect, but it should work in most situations. I don't try to account for tex-rendered strings, any stretched fonts, or fonts with an unusual aspect ratio. However, it should now properly handle rotated text.
However, It should attempt automatically wrap any text objects in multiple subplots in whichever figures you connect the on_draw callback to...  It will be imperfect in many cases, but it does a decent job.
import matplotlib.pyplot as plt

def main():
    fig = plt.figure()
    plt.axis([0, 10, 0, 10])

    t = "This is a really long string that I'd rather have wrapped so that it"\
    " doesn't go outside of the figure, but if it's long enough it will go"\
    " off the top or bottom!"
    plt.text(4, 1, t, ha='left', rotation=15)
    plt.text(5, 3.5, t, ha='right', rotation=-15)
    plt.text(5, 10, t, fontsize=18, ha='center', va='top')
    plt.text(3, 0, t, family='serif', style='italic', ha='right')
    plt.title("This is a really long title that I want to have wrapped so it"\
             " does not go outside the figure boundaries", ha='center')

    # Now make the text auto-wrap...
    fig.canvas.mpl_connect('draw_event', on_draw)
    plt.show()

def on_draw(event):
    """Auto-wraps all text objects in a figure at draw-time"""
    import matplotlib as mpl
    fig = event.canvas.figure

    # Cycle through all artists in all the axes in the figure
    for ax in fig.axes:
        for artist in ax.get_children():
            # If it's a text artist, wrap it...
            if isinstance(artist, mpl.text.Text):
                autowrap_text(artist, event.renderer)

    # Temporarily disconnect any callbacks to the draw event...
    # (To avoid recursion)
    func_handles = fig.canvas.callbacks.callbacks[event.name]
    fig.canvas.callbacks.callbacks[event.name] = {}
    # Re-draw the figure..
    fig.canvas.draw()
    # Reset the draw event callbacks
    fig.canvas.callbacks.callbacks[event.name] = func_handles

def autowrap_text(textobj, renderer):
    """Wraps the given matplotlib text object so that it exceed the boundaries
    of the axis it is plotted in."""
    import textwrap
    # Get the starting position of the text in pixels...
    x0, y0 = textobj.get_transform().transform(textobj.get_position())
    # Get the extents of the current axis in pixels...
    clip = textobj.get_axes().get_window_extent()
    # Set the text to rotate about the left edge (doesn't make sense otherwise)
    textobj.set_rotation_mode('anchor')

    # Get the amount of space in the direction of rotation to the left and
    # right of x0, y0 (left and right are relative to the rotation, as well)
    rotation = textobj.get_rotation()
    right_space = min_dist_inside((x0, y0), rotation, clip)
    left_space = min_dist_inside((x0, y0), rotation - 180, clip)

    # Use either the left or right distance depending on the horiz alignment.
    alignment = textobj.get_horizontalalignment()
    if alignment is 'left':
        new_width = right_space
    elif alignment is 'right':
        new_width = left_space
    else:
        new_width = 2 * min(left_space, right_space)

    # Estimate the width of the new size in characters...
    aspect_ratio = 0.5 # This varies with the font!!
    fontsize = textobj.get_size()
    pixels_per_char = aspect_ratio * renderer.points_to_pixels(fontsize)

    # If wrap_width is < 1, just make it 1 character
    wrap_width = max(1, new_width // pixels_per_char)
    try:
        wrapped_text = textwrap.fill(textobj.get_text(), wrap_width)
    except TypeError:
        # This appears to be a single word
        wrapped_text = textobj.get_text()
    textobj.set_text(wrapped_text)

def min_dist_inside(point, rotation, box):
    """Gets the space in a given direction from "point" to the boundaries of
    "box" (where box is an object with x0, y0, x1, & y1 attributes, point is a
    tuple of x,y, and rotation is the angle in degrees)"""
    from math import sin, cos, radians
    x0, y0 = point
    rotation = radians(rotation)
    distances = []
    threshold = 0.0001
    if cos(rotation) > threshold:
        # Intersects the right axis
        distances.append((box.x1 - x0) / cos(rotation))
    if cos(rotation) < -threshold:
        # Intersects the left axis
        distances.append((box.x0 - x0) / cos(rotation))
    if sin(rotation) > threshold:
        # Intersects the top axis
        distances.append((box.y1 - y0) / sin(rotation))
    if sin(rotation) < -threshold:
        # Intersects the bottom axis
        distances.append((box.y0 - y0) / sin(rotation))
    return min(distances)

if __name__ == '__main__':
    main()

Comment: Hi, I appreciate this post! Is still the way to go today or is there novel built-in matplotlib goodness?
Also: Why does this not work when I replace `plt.show()` with `plt.savefig('test.png')`?
Comment: +1.  Wow!  Impressing mastering of Matplotlib. :)  With the code you provide, when I change the window size, widths get smaller and smaller, but seem to never get bigger again (including reaching their original size when the window is put back to its original size)…
Comment: @Joe: The thread you point to is interesting too: LaTeX wrapping could be a useful option.
Comment: @EOL - Thanks!  I added a new version that fixes the resizing problems (and also handles center-aligned text properly).  The text should now reflow both when the figure is made larger and smaller.  LaTeX wrapping is a good option (and definitely simpler!), but I can't seem to find a way to make it automatically fit the size of the axes... Maybe I'm missing something obvious?
Comment: @Joe: Thank you.  This is impressive.  Maybe this is a bug in my Matplotlib implementation, but when I zoom in, and then go back to the original size, spaces disappear in some of the texts.  Strange…
Comment: @EOL - That's odd... I can't seem to reproduce the disappearing spaces.  It might be a textwrap issue instead of a matplotlib issue.  Try slapping a debug `print wrapped_text` at the end of the `autowrap_text` function and see if the actual string is missing the spaces... At any rate, I added an updated version that (mostly) handles rotated text. It still has tons of limitations (and lots of vertical alignment problems), but hopefully it's useful, anyway.
Comment: @Joe: It works perfectly, now!  I'm not sure what was the problem, before.  Thank you so much.  You example is inspiring: it makes me want to learn more about Matplotlib.
Comment: @tacaswell can you provide instructions on using this feature now that it's been merged?
Comment: nvm - found this: https://matplotlib.org/gallery/text_labels_and_annotations/autowrap.html#sphx-glr-gallery-text-labels-and-annotations-autowrap-py
Comment: The built-in wrap seems not to support Chinese character. A string of Chinese character cannot be wrapped.
Comment: This is great, I'm so glad they implemented it.  But is there a way to wrap text within a specified bounding box, or does it only wrap when it meets the axis boundary?
Answer: Its been roughly five years but there still doesn't seem to be a great way to do this.  Here is my version of the accepted solution.  My goal was to allow pixel-perfect wrapping to be selectively applied to individual text instances.  I have also created a simple textBox() function which will convert any axes into a text box with custom margins and alignment.
Instead of assuming a particular font aspect ratio or average width, I actually draw the string one word at a time and insert newlines once the threshold is hit.  This is horrendously slow compared to the approximations, but still feels quite snappy for strings of <200 words.
# Text Wrapping
# Defines wrapText which will attach an event to a given mpl.text object,
# wrapping it within the parent axes object.  Also defines a the convenience
# function textBox() which effectively converts an axes to a text box.
def wrapText(text, margin=4):
    """ Attaches an on-draw event to a given mpl.text object which will
        automatically wrap its string wthin the parent axes object.

        The margin argument controls the gap between the text and axes frame
        in points.
    """
    ax = text.get_axes()
    margin = margin / 72 * ax.figure.get_dpi()

    def _wrap(event):
        """Wraps text within its parent axes."""
        def _width(s):
            """Gets the length of a string in pixels."""
            text.set_text(s)
            return text.get_window_extent().width

        # Find available space
        clip = ax.get_window_extent()
        x0, y0 = text.get_transform().transform(text.get_position())
        if text.get_horizontalalignment() == 'left':
            width = clip.x1 - x0 - margin
        elif text.get_horizontalalignment() == 'right':
            width = x0 - clip.x0 - margin
        else:
            width = (min(clip.x1 - x0, x0 - clip.x0) - margin) * 2

        # Wrap the text string
        words = [''] + _splitText(text.get_text())[::-1]
        wrapped = []

        line = words.pop()
        while words:
            line = line if line else words.pop()
            lastLine = line

            while _width(line) <= width:
                if words:
                    lastLine = line
                    line += words.pop()
                    # Add in any whitespace since it will not affect redraw width
                    while words and (words[-1].strip() == ''):
                        line += words.pop()
                else:
                    lastLine = line
                    break

            wrapped.append(lastLine)
            line = line[len(lastLine):]
            if not words and line:
                wrapped.append(line)

        text.set_text('\n'.join(wrapped))

        # Draw wrapped string after disabling events to prevent recursion
        handles = ax.figure.canvas.callbacks.callbacks[event.name]
        ax.figure.canvas.callbacks.callbacks[event.name] = {}
        ax.figure.canvas.draw()
        ax.figure.canvas.callbacks.callbacks[event.name] = handles

    ax.figure.canvas.mpl_connect('draw_event', _wrap)

def _splitText(text):
    """ Splits a string into its underlying chucks for wordwrapping.  This
        mostly relies on the textwrap library but has some additional logic to
        avoid splitting latex/mathtext segments.
    """
    import textwrap
    import re
    math_re = re.compile(r'(?<!\\)\$')
    textWrapper = textwrap.TextWrapper()

    if len(math_re.findall(text)) <= 1:
        return textWrapper._split(text)
    else:
        chunks = []
        for n, segment in enumerate(math_re.split(text)):
            if segment and (n % 2):
                # Mathtext
                chunks.append('${}$'.format(segment))
            else:
                chunks += textWrapper._split(segment)
        return chunks

def textBox(text, axes, ha='left', fontsize=12, margin=None, frame=True, **kwargs):
    """ Converts an axes to a text box by removing its ticks and creating a
        wrapped annotation.
    """
    if margin is None:
        margin = 6 if frame else 0
    axes.set_xticks([])
    axes.set_yticks([])
    axes.set_frame_on(frame)

    an = axes.annotate(text, fontsize=fontsize, xy=({'left':0, 'right':1, 'center':0.5}[ha], 1), ha=ha, va='top',
                       xytext=(margin, -margin), xycoords='axes fraction', textcoords='offset points', **kwargs)
    wrapText(an, margin=margin)
    return an

Usage:

ax = plot.plt.figure(figsize=(6, 6)).add_subplot(111)
an = ax.annotate(t, fontsize=12, xy=(0.5, 1), ha='center', va='top', xytext=(0, -6),
                 xycoords='axes fraction', textcoords='offset points')
wrapText(an)

I dropped a few features which weren't as important to me.  Resizing will fail as each call to _wrap() inserts additional newlines into the string but has no way of removing them.  This can be solved by either stripping out all \n characters in the _wrap function, or storing the original string somewhere and "resetting" the text instance between wraps.
Answer: By setting wrap = True when creating the text box, as in the below example. This may have the desired effect.
plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)

Comment: Just note that this solution (`wrap=True`) is essentially the same than the accepted answer, as that answer is what happens behind the scenes when using `wrap`.
Comment: Text flowing outside of the bounding box is a deal breaker for me.  I wonder why they included such a broken implementation?
Comment: more info here https://matplotlib.org/gallery/text_labels_and_annotations/autowrap.html
Comment: That's a good approximate solution (the text flows outside of the bounding box but not by too much).

Text box with line wrapping


How do you open and transfer a file on the filesystem in mod_python?

Question: I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request.  I've got a very simple setup right now, and was hoping to simply open the file and write it to the response:
from mod_python import apache

def handler(req):
    req.content_type = 'application/octet-stream'
    fIn = open('response.bin', 'rb')
    req.write(fIn.read())
    fIn.close()
    return apache.OK

However, I'm getting errors when I use open(), saying that the file doesn't exist (even though I've checked a dozen times that it does).  This happens when using relative and absolute filepaths.
I've got two questions:

Why isn't open() finding the right
files?
What is the best way to return a file
from the filesystem?  (I ask to make
sure I'm not missing some better way
to use mod_python to return a file.)

Thanks
Edit:  After finding this thread: http://www.programmingforums.org/thread12384.html  I discovered that open() works for me if I move the file to another directory outside of home (I was aliasing out of /home/myname/httpdocs, but it works if I use /data).  Any ideas why that works?
Edit 2: Part of my debug error, as requested:
MOD_PYTHON ERROR

ProcessId:      13642
Interpreter:    '127.0.1.1'

ServerName:     '127.0.1.1'
DocumentRoot:   '/var/www'

URI:            '/test/mptest.py'
Location:       None
Directory:      '/home/myname/httpdocs/'
Filename:       '/home/myname/httpdocs/mptest.py'
PathInfo:       ''

Phase:          'PythonHandler'
Handler:        'mptest'

Traceback (most recent call last):

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch
    default=default_handler, arg=req, silent=hlist.silent)

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target
    result = _execute_target(config, req, object, arg)

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target
    result = object(arg)

  File "/home/myname/httpdocs/mptest.py", line 13, in handler
    fIn = open('/home/myname/httpdocs/files/response.bin', 'rb')

IOError: [Errno 2] No such file or directory: '/home/myname/httpdocs/files/response.bin'

Answer: To debug this kind of thing, you need to gather all information from the running mod_python instance.
Stop messing with "checking a dozen times that it [exists]".  Some assumption isn't correct.
Do something like this to get some debugging information.
def handler(req):
    req.content_type = 'text/plain'
    req.write(os.environ)
    req.write(os.getcwd())
    # etc.
    return apache.OK

Edit
Now you have a glimpse of the Important Stuff.  In this case it might be permissions -- you'll need to use os.filestat to be sure.  Apache runs mod_python as a user who has almost no usable permissions.  Apache does not like links, either, but this shouldn't affect mod_python.  If your file doesn't have  read-by-everybody and isn't in the right directory you'll have problems.
You might want to switch to mod_wsgi.
Comment: I've updated my question after finding a clue on what's going on.  Also I tried your advice and found out some interesting factoids: mod_python runs as "www-data", and runs out of "/".
Answer: Could you paste the error(s) you get?
It's likely to be a permission error (if you tried using the full path to the file). Remember the script runs as the user running the web-server process - so you will be accessing the file as "www-data", or "nobody" usually.
Check the permissions of the folder /home/myname/httpdocs/files/ also. The folder should be +x for the www-data user:
$ mkdir blah
$ echo works > blah/response.bin
$ chmod 000 blah/
$ cat blah/response.bin
cat: blah/response.bin: Permission denied
$ chmod +x blah/
$ cat blah/response.bin
works

You could eliminate Apache/your-script from the equation by doing the following:
you:~$ sudo su - www-data
www-data:~$ file /home/myname/httpdocs/files/response.bin

(the su may not work, depending on what OS/distribution you are using, for example OS X prevents you logging in as it's www user)
File permissions aside, why is the script dependant on a file in your home folder anyway? Can response.bin be moved to the same folder as your Python script? Or possibly even moved into a database? (perhaps SQLite? Might be unnecessary/excessive, depending on what is in response.bin and how much it changes)
Comment: I've pasted most of an error to my question.  However, I have tried chowning the files to www-data without success.  (Maybe I'm misunderstanding Unix OS permissions, though)


Erro ao rodar o programa em python via terminal com python 2: "IOError: [Errno 2] No such file or directory:"

Question: O programa deveria criar um arquivo mes/dia.dat, porém nada é criado e este erro me é retornado, onde podemos ver que o arquivo não está sendo criado com o comando file.open(). Segue o código do programa. Achei no stack algo sobre o programa não reconhecer o diretório em que estou rodando o programa, porém, mesmo depois de acrescentar "import os", não há resultados.
import os

ch=1
while ch != 0:
    print("###  Script rodando. Bem-vindo a inserção de dados.  ####\n\n")
    m = int(input('Insira o mes:'))
    d = int(input('Insira o dia:'))

    name = '{}/{}'.format(m,d)
    curpath = os.path.abspath(os.curdir)

    #abrir o mes/dia.dat aqui
    file = open("%s.txt" %name, "w+")

    qt = int(input('Insira a quantidade de alunos presentes.'))
    for i in range(0,qt):
            nome = raw_input('Insira o nome do aluno:')
            course = raw_input('Insira o curso:')
            data = '{} {}'.format(nome,course)
            file.write(data)

    file.close()
    ch = int(input('Fim das opções.\nInsira 0 para fechar ou 1 para inserir dados em outro arquivo:'))

Comment: Antes de tudo no arquivo, coloque `print "programa iniciado com sucesso"` e poste o retorno.
Comment: Você ta usando python2 ou 3?
Comment: estou usando python2
Comment: Ele pode estar buscando no diretório raiz como a resposta abaixo diz, ou na verdade entendendo a "/" que separa o mes e o dia como sendo um diretório dentro de outro
Answer: O erro esta na linha você define o nome do arquivo, quando você passa a / entre os mês e dia desse jeito name = '{}/{}'.format(m,d) ele entende que deve buscar uma pasta  no diretório raiz com o número do mês para gravar um arquivo com o nome do dia, que ficaria desse jeito c:/seu/diretorio/raiz/mes/dia.txt. Com isso ele explode esse erro, por não encontrar o diretório ou arquivo.
Minha sugestão seria definir o nome do arquivo sem a /, pode ser um _ ou - ou qualquer outro caractere
por exemplo:
name = '{}-{}'.format(m,d)


What does representer theorem in machine learning tell us?

Question: In reference to the Representer Theorem in machine learning, Why this is so important? Somehow, this theorem justifies the importance of Kernels in machine learning, i.e. the Kernel trick - a more computationally effective way to "shuttle" data between different dimensions. What does representer theorem in machine learning tell us?
Answer: The reason the representer theorem is important is that it tells us that the primal model parameters (the weights of the linear model constructed in the kernel induced feature space) can also be written in terms of the dual parameters, where there is one parameter for each training pattern.  This means that the output of the linear model can be written as a kernel expansion
$$f(x) = \vec{w}\cdot\phi\{\vec{x}\} + b = \sum_{i=1}^\ell\alpha_i\mathcal{K}(\vec{x},\vec{x}_i) + b$$
Where $\vec{x}_i$ is a training example, $\phi\{\cdot\}$ is the non-linear transformation for which the kernel function $\mathcal{K}:\mathcal{X}\times\mathcal{X}\rightarrow\mathbb{R}$ gives us the inner product, i.e. $\mathcal{K}(\vec{x},\vec{x}') = \left<\phi\{\vec{x}\}\cdot\phi\{\vec{x}'\}\right>$.  Now the reason this is important is that we know that we can never get a better model by adding any more terms to this expansion, so if we have one term for each training pattern, then we know can obtain the optimal solution given by the primal parameters.
The nice thing about this is that we can construct a model in a potentially infinite dimensional space (such as that induced by the Radial Basis Function kernel) without needing an infinite number of parameters (which we would if we used the primal representation rather than the dual).  The representer theorem tells us that this finite optimal representation always exists.
Comment: $\mathcal K(\vec x, {\vec{x}}') =  \langle\phi(\vec x) \cdot \phi({\vec{x}}') \rangle$
Comment: @Kuo, well spotted!  I have corrected my answer.
Comment: oops...are the angle brackets$\langle\;\rangle$ redundant? or replace the dot  $\cdot$ with a comma $,$ or use Bra-Ket $\langle | \rangle$ .


Resolve domain to another domain's IP on Linux via local DNS

Question: I have a local domain name "SomeName" and an Internet domain "AnotherName.dyndns.org" whose IP can change at any time (it uses a dynamic DNS). I want to resolve "SomeName" to "AnotherName.dyndns.org"'s IP. In other words, if "AnotherName.dyndns.org" points to 126.96.36.199, I want "SomeName" to point to that same IP, namely 188.8.131.52.
Is there any easy and straightforward way to achieve this? I couldn't find such an option for DNSMasq or BIND. I suppose one could write a script that gets the domain's IP and rewrites the config file, then reloads the DNS server, but that would be so ugly.
Why do I want this? To put it simply, I want to setup a Bacula server and client. The server has to resolve "SomeName" to a local IP (static, no problem here) and the client has to resolve it to a public IP (dynamic, namely "AnotherName.dyndns.org").
Answer: If I understand correctly, what you want is a CNAME DNS record:
http://en.wikipedia.org/wiki/CNAME_record
Comment: Thank you for your answer. Unfortunately, I tried for several hours to use something like `SomeName IN CNAME AnotherName.dyndns.org` in DNSMasq, BIND and Unbound but to no avail. Either I'm doing something terribly wrong or it isn't possible. I'm guessing the former, but right now I think I'm better off just writing a bash script that updates `/etc/hosts`.
Comment: In bind, a major trip up is the use of a "." at the end of a record.  On the left hand side if you put domain.com this will be pre-pended to the zone's main domain.  if you put domain.com.  then there is no pre-pending.  This is not the case for all setups but many default bind config files work this way.  When in doubt fully specify the domain names and end them with a ".".
Answer: The CNAME DNS record looks like this:
<an alias> CNAME

in example:
somename CNAME domain.dyndns.org

If domain.dyndns.org is resolved to the IP address dynamically, you have what you want.
Answer: What i understand is you are looking for Split DNS configuration. It also called views in BIND language. So you will create two view Private (local) and Public (Internet) and create ACL list to match your source IP address from where query coming base on that it will give you whatever IP address you want to give to client. for example if your request coming from private ip address 192.168.100.x then DNS will give you "SomeName" 188.8.131.52 and if query coming from public domain it will give you "SomeName" 202.67.29.x
Take a look here. Hope this answer will fulfill your need.
http://www.shorewall.net/SplitDNS.html
Answer: How about adding "AnotherName.dyndns.org" as domain-suffix for DNS-resolving on the client?
Comment: I don't know what you mean by that and Google didn't help me much. Can you explain a bit further, please?
Comment: If your client is a linux box you could add "AnotherName.dyndns.org" to the searchlist in /etc/resolv.conf. Now if that client looks up "foo" via DNS it will try "foo.AnotherName.dyndns.org" first. On a Windows-system you can accomplish the same in the TCP/IP-DNS-settings of the network card of the client. Most propably you can distribute that as group policy as well.