Individual user sessions in vmware esxi

Question: I have a server with vmware esxi 5.5 installed. Basically, I've noticed when I use Vsphere client and logged in as root and another person uses Vsphere client and logged in as root on the same esx host, the person can see what I'm doing.  Is there a way to setup private sessions?  I'd like to be able to work on my vm's and another person working on his vm as well without us looking at each others vm setup.  Highly appreciate any advice.  Thank you.
Comment: I believe that's intended behavior.  The client is intended to be like sitting at the console.
Comment: `I've noticed when I use Vsphere client and logged in as root and another person uses Vsphere client and logged in as root on the same esx host, the person can see what I'm doing` - What do you mean by that? How are they "seeing" what you're doing?
Comment: @joeqwerty - I mean during initial vm setup, since this would have to be performed in vsphere client console.  When another user logs in using root, if the user wants to look into the vm I am using, I can see on top of the screen that there are two active users on the vm. I was hoping there would be some way to have individual private console sessions for each user logging into esx via vsphere client.
Answer:
if the user wants to look into the vm I am using, I can see on top of the screen that there are two active users on the vm. I was hoping there would be some way to have individual private console sessions for each user logging into esx via vsphere client

There's an advanced option that might help you but it's per VM: Prevent Users from Spying on Remote Console Sessions
I don't know any other way.
Btw: You're talking about two persons logged in as root. In that case you don't have two active users, you have one user (root) with two sessions. However, with RemoteDisplay.maxConnections=1 you can limit the number of console sessions to one; another root session can't open one because then there would be two console sessions.
Comment: I knew this setting existed, but just had a hard time finding it!
Comment: @GregL I knew it's in the hardening guide and that's easy to find ;-)
Answer: I think there's a lack of basic understanding here. The console you can view is the VM's frame-buffer, effectively it's video output if you could plug a monitor into it. It's not a virtual desktop, ssh session or similar - if you had a physical server and you plugged two monitors into the VGA port with a splitter you'd see the same output right?
What you need to do is to SSH or RDP into the VM itself, depending on VM OS of course, that way you'll have control but just for you.
Answer: If I understand what you are asking, no I'm not aware of any setting that would mask your connection to a VM's console on a host so that it doesn't show others what you are doing on a VM console if they connect as well.  Nor can you prevent the event window or logs from masking or hiding your real time changes to a VM or a host.
You really shouldn't be accessing your VM's via their console for normal "work".  That's what an RDP or SSH session into the VM is for.  The "console" is no different than a shared KVM.
Comment: Thanks, I am aware of that.  Of course "after" the vm is installed and configured, that is where SSH or RDP would be useful.  I guess once the vm OS is installed, the rest of the configs would be done via RDP or SSH.  In that way, private session can still be established.
Comment: You could restrict which accounts could see which VMs, but not if you are both using root.  Or you can deploy a VM from a template and then continue config over RDP or SSH once the VM is deployed and boots.

Individual user sessions in vmware esxi


Retorno JSON Dando Erro

Question: Estou fazendo um serviço para pegar o retorno JSON em uma aplicação Android, até aí tudo bem, mas não sei aonde estou errando na hora de pegar o valor.
A estrutura do JSON é essa:
"entity": {
    "code": 1,
    "message": "Sucesso",
    "clienteModel": {
        "codigoCliente": 1,
        "nomeCliente": "ederson",
        "rgCliente": "448868",
        "cpfCliente": "11212444488",
        "dataNascimentoCliente": 614833200000,
        "emailCliente": "eder",
        "dataCadastroCliente": 1504666800000,
        "codigoEndereco": {
            "code": 1,
            "message": "Sucesso",
            "codigoEndereco": 1,
            "nomeEndereco": "teste",
            "complementoEndereco": "sxasdf",
            "estadoEndereco": "sdafasd",
            "cidadeEndereco": "sdfasd",
            "bairroEndereco": "sdasds",
            "numeroEndereco": 11211,
            "numeroCEPEndereco": "06851020"
        }
    }
},

Esse é meu método onde leio o JSON, quando tento pegar o codigoCliente ele não encontra, o que estou fazendo de errado? o code e a message eu consigo pegar a partir dos outros campos nenhum consigo pegar.
private ClienteSaidaDTO getClienteSaidaDTOs(String jsonString) {

    ClienteSaidaDTO trends = new ClienteSaidaDTO();

    try {
        JSONObject jsonObjectConvertString = new JSONObject(jsonString);
        JSONObject jsonObjectEntity = jsonObjectConvertString.getJSONObject("entity");
        //JSONObject jsonObjectClienteModel = jsonObjectConvertString.getJSONObject("clienteModel");

        ClienteSaidaDTO clienteSaidaDTO = new ClienteSaidaDTO();
        ClienteModel clienteModel = new ClienteModel();

        clienteSaidaDTO.setCode(jsonObjectEntity.getInt("code"));
        clienteSaidaDTO.setMessage(jsonObjectEntity.getString("message"));

        clienteModel.setCodigoCliente(jsonObjectEntity.getInt("codigoCliente"));

        clienteSaidaDTO.setClienteModel(clienteModel);

        trends = clienteSaidaDTO;
        //}
    } catch (JSONException e) {
        Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
    }

    return trends;
}

Answer: É porque o "codigoCliente" esta dentro do array "clienteModel", então você deve pegar primeiro o array "clienteModel".
String[] clienteModel = jsonObjectEntity.getStringArray("clienteModel");

Retorno JSON Dando Erro


How can I calculate confidence intervals and determine statistical significance for each cell in a contigency table?

Question: I'm creating a large contigency table to summarise the difference between a bunch of (categorical) demographics across groups.  I would like to know what the confidence intervals are for each cell in the proportional cross-tab, and if the proportion of each demographic group in each sample is statistical different from random. Say I have the following data:
<code>> set.seed(1)
> y <- sample(factor(c("Outcome 1", "Outcome 2", "Outcome 3", "Outcome 4")), 1000, replace = T)
> x1 <- sample(c("Male", "Female"), 1000, replace=T)
> x2 <- sample(c("Employed full-time", "Employed part-time", "Not in labour force", NA), 1000, replace=T)
>
> table(x1, y)
        y
x1       Outcome 1 Outcome 2 Outcome 3 Outcome 4
  Female       123       126       124       108
  Male         121       150       108       140
> round(prop.table(table(x1, y), 2) * 100, 1)
        y
x1       Outcome 1 Outcome 2 Outcome 3 Outcome 4
  Female      50.4      45.7      53.4      43.5
  Male        49.6      54.3      46.6      56.5
>
> table(x2, y)
                     y
x2                    Outcome 1 Outcome 2 Outcome 3 Outcome 4
  Employed full-time         57        64        65        77
  Employed part-time         66        80        57        53
  Not in labour force        57        61        51        58
> round(prop.table(table(x2, y), 2) * 100, 1)
                     y
x2                    Outcome 1 Outcome 2 Outcome 3 Outcome 4
  Employed full-time       31.7      31.2      37.6      41.0
  Employed part-time       36.7      39.0      32.9      28.2
  Not in labour force      31.7      29.8      29.5      30.9
</code>
How would I compute such a table in R?  I have read papers where Fisher's exact test is used for this purpose, but it seems to me only to be useful for 2 x 2 tables.
Comment: Fisher [works on general tables](http://mathworld.wolfram.com/FishersExactTest.html); it's not limited to 2 x 2.
Comment: When you say every possible comparison do you really mean comparing outcome2:male with outcome3:female?  Does it also involve comparisons across the tables?
Comment: Possibly what you want is pairwise.t.test or pairwise.wilcoxon.test?
Comment: @John I want to know if each cell (e.g. outcome 1, male) is of different proportion than the whole the sample (e.g. outcomes 1-4, male).
Comment: @John Doucette I have categorical variables only so a t-test or a wilcoxon test which compares differences between means doesn't make sense does it?
Comment: Why not bootstrap the confidence intervals?
Answer: Indeed Bonferroni needs to be invoked. Many years ago we proved that it provides a tight upper bound and proposed the M-Test. see:
Fuchs, C. and Kenett, R.S. (1980).  A Test for Detecting Outlying Cells in the Multinomial Distribution and Two-Way Contingency Tables, Journal of the American Statistical Association, 75, pp. 395-398.
Kenett R.S. (1991). Two Methods for Comparing Pareto Charts, Journal of Quality Technology, 23, pp. 27-31.
Answer: The best answer I could produce to my question was to calculate binomial confidence intervals, and test 2x2 binomial contigency tables for each cell.  I'd appreciate any improvement on this answer:
The function:
<code>prop.table.with.cis <- function(x, conf.lev = 0.95, do.fisher.2x2.test = TRUE, compare.to.entire.sample = TRUE, digits = 1, p.digits = 3){
  require(PropCIs)
  t <- addmargins(x, 2)
  prop.t <- prop.table(t, 2)
  prop.t.cis <- prop.t
  for(i in 1:dim(t)[2]){
    ms <- margin.table(t, 2)
    ms.col <- margin.table(t, 1)
    for (j in 1:dim(t)[1]){
       ci <- addz2ci(t[j,i], ms[i], conf.lev)
       names(ci) <- NULL
       prop.str <- paste(formatC(prop.t[j, i] * 100, digits = digits, format="f"), " (",
                         formatC(ci[1] * 100, digits = digits, format="f"), ", ",
                         formatC(ci[2] * 100, digits = digits, format="f"), ")", sep = "")
       if (do.fisher.2x2.test){
         if (compare.to.entire.sample){
           fisher.matrix <- matrix(c(t[j, i], sum(t[-j, i]), sum(ms.col[j]) / 2, sum(ms.col[-j]) / 2), nrow=2)
         } else {
            fisher.matrix <- matrix(c(t[j, i], sum(t[-j, i]), sum(ms.col[j]) / 2 - t[j, i], sum(ms.col[-j]) / 2 - sum(t[-j, i])), nrow=2)
         }
         fisher.diff.to.rest.sample <- fisher.test(fisher.matrix)
         prop.str <- paste(prop.str, " p=",
                         formatC(fisher.diff.to.rest.sample$p.value, digits = p.digits, format="f"),
                         sep="")
       }
       prop.t.cis[j,i] <- prop.str

    }
  }
  return(prop.t.cis)
}
</code>
and some sample output:
<code>> set.seed(10)
> y <- sample(factor(c("Group 1", "Group 2", "Group 3")), 1000, replace = T)
> x <- sample(c("Employed full-time", "Employed part-time", "Not in labour force", NA), 1000, replace=T)
> prop.table.with.cis(table(x, y))
                     y
x                     Group 1                   Group 2                   Group 3                   Sum
  Employed full-time  30.7 (25.3, 36.8) p=0.390 33.7 (28.1, 39.9) p=1.000 36.8 (31.3, 42.6) p=0.414 33.9 (30.6, 37.3) p=1.000
  Employed part-time  36.1 (30.3, 42.3) p=0.438 32.5 (26.9, 38.6) p=0.876 31.6 (26.4, 37.4) p=0.652 33.3 (30.1, 36.8) p=1.000
  Not in labour force 33.2 (27.6, 39.3) p=0.938 33.7 (28.1, 39.9) p=0.814 31.6 (26.4, 37.4) p=0.763 32.8 (29.6, 36.2) p=1.000
>
</code>
Comment: What does it tell you, or in other words what are your conclusions about those results? (I'm still having trouble with understanding your original question.)
Answer: I'm thinking you need to consider a Bonferroni type of approach.
You want the probability that there's no error overall
P(error)= 1- P(No Error)
Alpha = 1-(1-Alpha)
Now, we're looking at an overall case.. So I'll call that alphaoverall and alphacell is the chances of making an error in any particular cell..
alphaoverall = 1-(1-alphacell)^n
Now, if you want to get z score in terms of an overall alpha..
alphaoverall = 1-(1-alphacell)^n
alphaoverall -1= -(1-alphacell)^n
1-alphaoverall = (1-alphacell)^n
take the nth root
(1-alphaoverall)^(1/n)= 1- alphacell
(1-alphaoverall)^(1/n)-1= - alphacell
1-(1-alphaoverall)^(1/n)=  alphacell
So, what this means, is say you want a 20% error rate for the whole table, plug in .2 for alpha over all, with your number of cell entries as n.. Say you have a 2*3 table, then that's n= 6.
1-(1-.2)^(1/6) =  0.03650752
 ..
You'll have a 2 sided test, so..
Now, cut that .0365 in 2 ,  0.01825376  now find the score that has that much area in the upper tail, and find the appropriate z is 2.09.
My hunch though, is that the errors in each cell might be correlated. Which I think will matter.. If you don't have an error in one cell, it makes it less likely to have an error in the next cell. Doesn't it?  Come to think of it, if you have a 2x2 table, and one point estimate is very close to the true parameter, the others would have to be very close as well..
Comment: @chl    I edited my response. I'm not sure what to think about it though. Maybe someone can add to it and we can get to the right answer if it's wrong
Comment: You have a point, but detail is needed for this to become a clear and adequate answer.
Comment: Any thought on @whuber's comment?
Comment: Tough but fair. :) At the same time, my answer wasn't rubbish, so I'm not sure what you want me to say.
Comment: @Adam Agreed. Your response was on the point but we generally expect standalone and justified responses rather than a one-line thought. As another response pointing toward Bonferroni correction has been proposed in the meantime, maybe you could expand a little bit on why we must account for inflation in Type I error rate when analyzing two-way tables at the cell level, or if there's another alternative to Bonferroni correction (which is known to be conservative) that might be suited to this particular case, etc.


Transition from pure mathematics to statistics via operational research

Question: I am currently studying an M.Sc. in pure mathematics (my dissertation focuses on category/set theory)). However recently I have decided that I wish to transition to a much more applied field. During my undergrad I studied almost all pure courses, with only one statistics module.
I have enrolled in an M.Sc. in operational research for next year where I will be studying a mix of operational research and statistics courses.
All of this is in the UK.
My question is, should I choose to, will it be possible/realistic for me to apply to do a Ph.D. in some sort of statistics? Not only in terms of actually getting accepted but also getting funding/actually being able to do this?
Thanks for any help
Comment: Economics might be another area to think about. Having a math degree would actually be a feather in your cap.
Comment: In principle your background sounds suitable for a statistics Ph.D. In practice your chances of being accepted depend on the strength of your qualifications and your appeal as a potential student, not just having pertinent degrees. The question isn't really answerable in any but the vaguest of terms, even if we could see a CV (posting one would not be appropriate either).
Comment: Hello. I am currently doing a very similar MSc in the UK and have some relevant info. My email is email@example.com. Feel free to drop me a line.
Answer: Well, I will answer because this is almost exactly what I have done.
My undergraduate degree was in pure mathematics with a thesis on the Lowenheim-Skolem theorem, and now I am in a funded PhD program in environmental science, where most of my work is in statistics (bio&geo).  So clearly, it is possible, and you probably will have the requisite skills.
Whether you will enjoy the switch is a different matter.  I still sometimes find statistics slightly intellectually creepy, but some of it can be fun.
Comment: Thanks, my UG thesis was on Skolem Paradox. Did you find the process  particularly difficult or was it just a lot of work to make up the pre-requisite knowledge? Out of interest are you in America?
Comment: I am still in the middle of learning it all, and I do study pretty hard.  Most days I feel reasonably on top of it.  I am definitely patching it all together, but consider: in any statistically oriented field besides actual Statistics, none of your classmates will have a stunning mastery either, and your ability to push through hard stuff, weird notation, and mental gymnastics will serve you well.

Yes, I am in America.  I also think it helped that I was honest upfront with my advisor about my pure-to-the-point-of-esoteric math background.
Answer: I don't know what the requirements are in the UK, but many good American statistics and biostatistics graduate programs even accept and fund PhD students who only have an undergraduate degree in mathematics.
Answer: Hate to sound all sappy, but you can do anything you want to do! Your background will be very valuable in many situations. In others, you will notice that you are missing other skills that you'll have to develop. But that will be true of everyone. Work hard to fill in any gaps that you feel you have and pursue whatever direction you feel most interests you. The main question to ask yourself is not whether your background is right for some particular career direction but whether you are really passionate about that direction. If you are passionate about your chosen direction you will slowly overtake those who are initially better prepared but lack that passion. I have seen this happen over and over again.


Confused with the DLL. No .lib or .h

Question: I currently have a C# project that uses a 32 bit dll. What I am trying to do is to use the dll in a C++ project , unfortunately the dll referenced in the project does not come with a .h or .lib file so I am confused on how I could access the classes in the dll or use the dll file in my project in C++ (Visual Studio 2010) . I read here that if a dll file contains classes its a good chance it might be a COM component.Any suggestions on what I should be looking at in order to integrate and consume methods and objects in that dll.
Update:
I checked if it was a COM by doing an import statement. However I get a "cannot find .tlb file". Then I decided to use dependency walker to check for any exported methods (objects)it seems there are none. I clicked on the main file (which has been highlighted) and couldn't see any exported functions. Any hints on what I should check for next ?. Here is what I get from dependency walker.
Comment: Just add a reference to it under the "COM" or ".NET" tabs in VS's "Add reference..." dialog.  If that complains, then bug the library's creator for an import library.  :P
Comment: Have a look [here][1]. and [here][2], maybe someone already answered your question.

  [1]: http://stackoverflow.com/questions/4041149/how-to-dllimport-in-c
  [2]: http://stackoverflow.com/questions/1922580/import-a-dll-with-c-win32
Comment: How do you add a reference in VS2010 in C++.?
Comment: Use COM via TLB, try [How to use tlb file in C?](http://stackoverflow.com/questions/4312711/how-to-use-tlb-file-in-c)
Answer: With only a .dll and without a corresponding .h or .exp, one place that you might try looking would be the exports table.  Tools such as Dependency Walker can show you this information.
One caveat with Dependency Walker is that you'll want to use the right version (x86 or x86_64) for the binary (your DLL).  If you're not sure, pick one version and try loading it.  Under the CPU column, middle panel, look to see if it says "x64" or "x86" to determine which one you should be using.
With the provided screenshot of Dependency Walker (indicating a dependency on MSCOREE.DLL), I agree with Eugene - this is most likely a .NET library, not a COM library.  You will want to check one of the other questions about calling .NET managed code from C/C++.
Comment: If it's not obvious, clicking on a module will show you many (but not necessarily all) of the available functions.  The panel to the lower-left of the tree view shows you the exported functions for the selected portable executable ("PE") object.
Answer: The dll is most likely a .Net assembly (seeing that it imports mscoree.dll), so you probably want this: How do I call a .NET assembly from C/C++?
Comment: So does this mean that I cant use it directly in C++ ? From the little that I have read from the link you posted it seems like I'll have to create a C# com wrapper over the methods that I need to use.I'll then have to use that new COM dll in my C++ probably through import ? Am I getting this correct ?
Comment: @Rajeshwar, Yep I think that will work. Assembly -> COM wrapper -> C++.

Confused with the DLL. No .lib or .h


PHPSpreadsheet - Custom Color in Data Series of Chart

Question: Using PHPSpreadsheet to create a custom line graph. I have data loaded into the spreadsheet and it is properly building the graph. However, I am not able to adjust the color of the lines in the graph. When I try to apply a color to my series, the spreadsheet opens but there is some sort of corruption and the graph does not load. Excel tells me that it has removed the graph so that it can open the spreadsheet: 'Removed Part: /xl/drawings/drawing1.xml part.  (Drawing shape)'
I was unable to find any information in the documentation regarding custom chart colors but it was committed and merged into the project earlier this year.
I have checked the source code for my version of PHPSpreadsheet and it does have the updated files/classes that allow for custom chart coloration.
<code><?php

require_once '/opt/sites/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;

$phpsheet = new Spreadsheet();

$phpsheet->setActiveSheetIndex(0);
$phpsheet->getActiveSheet()->setTitle('Worksheet');

$file = "report.xlsx";

header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\"".$file."\"");
header('Cache-Control: max-age=0');

$phpsheet->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);

$r = 1;

$phpsheet->getActiveSheet()->setCellValue('A' . $r, "Date");
$phpsheet->getActiveSheet()->setCellValue('B' . $r, "Val  One");
$phpsheet->getActiveSheet()->setCellValue('C' . $r, "Val Two");

$r++;

while($r<=20)
{
    $randNumOne =  rand(1,100);
    $randNumTwo =  rand(1,100);

    $phpsheet->getActiveSheet()->setCellValue('A' . $r, "2018-04-".$r);
    $phpsheet->getActiveSheet()->setCellValue('B' . $r, $randNumOne);
    $phpsheet->getActiveSheet()->setCellValue('C' . $r, $randNumTwo);

    $r++;
}

/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////
///If I change the two hex codes to NULL, there is no issue but of course then there is no change in color either.
/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////

$dsl=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', NULL, 1, [], NULL, "d914e0"), //Cause of the error
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', NULL, 1, [], NULL, "2ce81b"), //Cause of the error
);

$x = $r - 1;

$xal=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$'.$r, NULL, $x),
);

$dsv = array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$'.$r, NULL, $x),
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$'.$r, NULL, $x),
);

$ds = new DataSeries(
    DataSeries::TYPE_LINECHART,
    DataSeries::GROUPING_STANDARD,
    range(0, count($dsv)-1),
    $dsl,
    $xal,
    $dsv
);

$pa = new PlotArea(NULL, array($ds));

$legend = new Legend(Legend::POSITION_RIGHT, NULL, false);

$title = new Title('Sample Chart');

$chart = new Chart(
    'chart1',
    $title,
    $legend,
    $pa,
    0,
    0,
    NULL,
    NULL
);

$chart->setTopLeftPosition('E1');
$chart->setBottomRightPosition('V20');

$phpsheet->getActiveSheet()->addChart($chart);

$Excel_writer = new Xlsx($phpsheet);

ob_end_clean();
$Excel_writer->setIncludeCharts(true);

$Excel_writer->save('php://output');
</code>
I have no errors/warnings/issues on the server side of things. Everything executes as expected and I get the excel file without issue other than the 'drawing corruption'.
Comment: I've just been doing something similar. It's a problem with the XLSX writer for charts, it doesn't append the fill colour in the correct place. It causes 2  tags to be appended, when it should add one and apply the fill colour to the  tag. There is no workaround apart from either contributing to PHPSpreadsheet or extending the XLSX writer and making a new chart writer.
Comment: Great, and is it possible to set same color to the corresponding label inside the chart legend?
Answer: Fixed my issue by replacing 0 with 'gap', seems a recent push changed expected int '0' to string 'gap':
<code>$chart = new Chart(
   'chart1',
    $title,
    $legend,
    $pa,
    0,
    'gap', //change here from 0 to gap
    NULL,
    NULL
);
</code>
The push:
https://github.com/PHPOffice/PhpSpreadsheet/commit/144a0cabbc572780d0f49db50243f15b104ce26e#diff-0fa257b790aee274c5c82d3156288e94


Upload multiple files by clicking file upload again

Question: How can I appended files to be uploaded when user clicks on the input upload button again?
I have no problems with selecting multiple files to upload as I have set the multiple attribute. It is just when user wants to add more files to be uploaded.
Here's a scenario to better illustrate.

User clicks on file upload button.
User selects multiple files to upload.
User clicks on file upload button again.
User selects more files to upload.
User clicks on the upload to server button to upload files on the server.

Upon checking the request, it seems that the last batch are the only ones being uploaded. Shouldn't it be appended?
Comment: Have a look at some plugin like: https://github.com/blueimp/jQuery-File-Upload
Comment: I recommend you to use multiple file upload buttons. Like second and third button.
Comment: Natively the upload element only uploads the **latest** selected batch of element
Comment: It is similar to how this works https://blueimp.github.io/jQuery-File-Upload/index.html. User can add files that gets appended and then hit the start upload button to upload all. I already made my own plugin and would like the same functionality.
Answer: I believe you are looking for blueimp/jQuery File Upload

Multiple file upload:
  Allows to select multiple files at once and upload them simultaneously.

You can also upload in serie like you are looking for. See the demo.
Comment: Yeah, similar to how that works. But I made my own plugin and would like the same functionality.
Comment: @basagabi well, if you would like the same functionalities, I would suggest you take something that is already proven, even if you are only interested in 5% of the functionalities.
Comment: I understand where you are coming from but there are some plugins that are not suitable base on the requirements. Aside from that, it will also be a good learning to know how to make such functionality.
Comment: @basagabi Certainly


Programa em C não lê valores em arquivo de txt

Question: Galera, de novo estou de volta. Apliquei algumas mudanças que os membros daqui sugeriram em um outro post, porém os valores continuam sem ser lidos da forma correta. Agora da até uns valores inteiros (antes o DOS imprimia valores negativos com mais de 5 algarismos). Segue parte do código:
void (CPU)
{
setlocale(LC_ALL, "Portuguese");
int matriiz_A[5][5];
char matriz_A[5][5];
int matriz_B[3][2];
int matriz_C[3][2];
int m, n, k, l, i, j, x, aux;

printf("\n Abaixo temos a matriz A \n");

FILE *matrizA;
matrizA = fopen("matriz_A.txt", "r");

if (matrizA == NULL)
{
    printf("\nNão foi possivel abrir o arquivo. \n");
    exit(0);
}

while (fgets(matriz_A, 25, matrizA) != NULL);
{
    for (m = 0; m<5; m++)
    {
        for (n = 0; n<5; n++)
        {
            fscanf(matrizA," %d%*c ", &matriz_A[m][n]);
            printf(" %d ", matriz_A[m][n]);
        }
        printf("\n");
    }
}
fclose(matrizA);
system("pause");
}

int main(int argc, char const *argv[])
{
setlocale(LC_ALL, "Portuguese");
char escolha = '0';

printf("\nEm que modo você deseja executar o programa? \n");
printf("(1) CPU \n");
printf("(2) GPU \n");
printf("Qualquer outra tecla fecha o programa \n");
escolha = getche();

if (escolha == '1')
{
    CPU();
}
else if (escolha == '2')
{

}
else if ((escolha != '1') && (escolha != '2'))
{
    printf("\nEscolha inválida. Programa será encerrado\n");
    exit(1);
}

//system("pause");
return 0;
}

Segue abaixo o arquivo .txt que quero ler:
01 00 02 03 04
00 05 06 00 07
08 09 00 11 12
13 00 14 15 00
00 00 16 17 18

O resultado que obtive foi este:

usando aux eu também obtive o mesmo resultado. Seria algum problema com a função getche()? Isso pq eu percebi que no Linux ela fazia sair lixo na matriz, já no windows não. Pesquisei a fundo na net e nao solucionei ainda. :(
Comment: Se a solução que as pessoas apresentaram a você no seu outro post não resolveu o seu problema, você deveria ter exposto isso a elas nos comentários das respostas.
Answer: Como o programa postado está confuso, é mais fácil reescrever do que apontar os erros.
#include <stdio.h>
#include <stdlib.h>

static void CPU(void)
{
  int m, n, nLido;

  char matriz_A[5][5];

  FILE* matrizA;

  printf("* abrindo arquivo matriz_A.txt\n");

  matrizA = fopen("matriz_A.txt", "r");
  if (matrizA == NULL)
  {
    printf("* nao foi possivel abrir arquivo matriz_A.txt\n");
    exit(1);
  }

  for (m = 0; m < 5; m++)
  {
    for (n = 0; n < 5; n++)
    {
      nLido = fscanf(matrizA,"%d", &matriz_A[m][n]);
      if (nLido != 1)
      {
        printf(" erro na leitura de matriz_A[%d][%d]\n", m, n);
        exit(2);
      }
      printf("%02d ", matriz_A[m][n]);
    }
    printf("\n");
  }

  fclose(matrizA);
}

int main(void)
{
  char escolha = '0';

  printf("*\n");
  printf("* em que modo você deseja executar o programa?\n");
  printf("* (1) CPU \n");
  printf("* (2) GPU \n");
  printf("* qualquer outra tecla fecha o programa\n");
  scanf(" %c%*[^\n]", &escolha);

  if (escolha == '1')
  {
    CPU();
  }
  else if (escolha == '2')
  {

  }
  else
  {
    printf("* escolha invalida, programa encerrado\n");
    exit(3);
  }

}

// 01 00 02 03 04
// 00 05 06 00 07
// 08 09 00 11 12
// 13 00 14 15 00
// 00 00 16 17 18

Teste:
[~/Projects/testes/so]
$cc -o 387091 387091.c

[~/Projects/testes/so]
$./387091
*
* em que modo você deseja executar o programa?
* (1) CPU
* (2) GPU
* qualquer outra tecla fecha o programa
1
* abrindo arquivo matriz_A.txt
01 00 02 03 04
00 05 06 00 07
08 09 00 11 12
13 00 14 15 00
00 00 16 17 18

[~/Projects/testes/so]
$

Comment: obrigado, mano. Solucionou. Alem de me servir, poderei estudar o código e me aperfeiçoar na linguagem
Answer: Faça:
void (CPU)
{
    setlocale(LC_ALL, "Portuguese");
    int matriz_A[5][5];
    int matriz_B[3][2];
    int matriz_C[3][2];
    char linha[300];
    int m, n, k, l, i, j, x, aux;

    printf("\n Abaixo temos a matriz A \n");

    FILE *matrizA;
    matrizA = fopen("matriz_A.txt", "r");

    if (matrizA == NULL)
    {
         printf("\nNão foi possivel abrir o arquivo. \n");
         exit(0);
    }
    m =0;
    while (fgets(linha, 300, matrizA) != NULL);
    {
        for (n = 0; n<5; n++)
        {
            sscanf(linha," %d%*c ", &matriz_A[m][n]);
            printf(" %d ", matriz_A[m][n]);
        }
        printf("\n");
        m++;
    }
    fclose(matrizA);
    system("pause");
}

ou
void (CPU)
{
    setlocale(LC_ALL, "Portuguese");
    int matriz_A[5][5];
    int matriz_B[3][2];
    int matriz_C[3][2];
    int m, n, k, l, i, j, x, aux;

    printf("\n Abaixo temos a matriz A \n");

    FILE *matrizA;
    matrizA = fopen("matriz_A.txt", "r");

    if (matrizA == NULL)
    {
         printf("\nNão foi possivel abrir o arquivo. \n");
         exit(0);
    }

    for (m = 0; m<5; m++)
    {
        for (n = 0; n<5; n++)
        {
            fscanf(matrizA," %d%*c ", &matriz_A[m][n]);
            printf(" %d ", matriz_A[m][n]);
        }
        printf("\n");
    }
    fclose(matrizA);
    system("pause");
}

Como tinha sido orientado em sua outra questão.
Comment: não é necessário colocar assim "%d%*c ", apenas "%d" é suficiente, porque o formato "%d" pula "whitespaces", isto é, espaços, '\n', '\r' e '\t'


Regular singular, Irregular singular & Ordinary points of an equation

Question: I'm currently trying to re pick up physics after a few years off.. but I'm not sure on the current question and I have no idea what it actually means.
My mathematics is not great but it reminds me of poles from complex analysis stuff.
If some one could tell me the answer and more importantly the reason why I would be very grateful. even point me in the direction of further reading if you can.
$$
x y'' -\frac2{x(x-2)}y'+x^2y  = 0
$$
which is true?

$x=0$ is a regular singular point of this equation.
$x=0$ is an irregular singular point of this equation.
$x=0$ is an ordinary point of this equation.
$x=2$ is an irregular singular point of this equation.
Comment: Thanks for that Calvin
Comment: If you have no idea what something means, then a good start would be to put each of the weird words into google. I tried to make your post use Mathjax but it seems that you have reverted the change; please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference and do it yourself so that it is easier to read. Also your post will likely be closed if you don't show some effort
Comment: I am showing effort dude, Ive found the definitions on google, however Its the wording which confufes me ]
Comment: Im currently trying to pick up physics again after several years off so I am very rusty
Comment: Your background is important information that should also go in the post. I don't see any effort that allows someone to begin to help you from. You should make your question about the definitions more specific; as it stands, you're asking someone to write a small section of a textbook. Why not go read a textbook then?
Comment: A quick defintion would suffice
Comment: but you said that you have already seen them by google, so how does that help? For instance http://mathworld.wolfram.com/RegularSingularPoint.html ?
Comment: Thanks ill take a look.. My problem is the wording of a lot of methematical texta I struggle with being dyslex.
Comment: Another thing, at the bottom of that page (and many pages) is a "References" section, that's usually a good place to look for more information. In this case you might want to consult Arfken, G. "Singular Points." §8.4 in Mathematical Methods for Physicists, 3rd ed. Orlando, FL: Academic Press, pp. 451-453 and 461-463, 1985.
Answer: Singular: You can not compute the general highest derivative of the equation at this point due to division-by-zero. Here that is the second derivative. Obviously, $x=0$ and $x=2$ are singular.
Regular singularity: You can, after applying some factor, write the equation as
$$
(x-c)^2y''(x)+(x-c)p(x)y'(x)+q(x)y(x)=0
$$
where $p$ and $q$ are continuous in $x=c$. It does not play any role if these functions have additional roots in $x=c$. What makes this situation "regular" is that the equation is essentially an Euler-Cauchy equation
$$
(x-c)^2y''(x)+(x-c)p(c)y'(x)+q(c)y(x)=0
$$
with some perturbation terms added. And it is known how solve Euler-Cauchy equations, as they are equivalent to linear equations with constant coefficients.

$x=0$:
$$ x^2y''(x)-\frac{2}{x-2}y'(x)+x^3y(x)=0 $$
fails this test in the middle term, thus a irregular singularity.
$x=2$:
$$ (x-2)^2y''(x)-(x-2)\frac2xy'(x)+x^2(x-2)^2y(x)=0$$ fits the pattern, thus a regular singularity.


How to statistically determine if something appears in the beginning of a vector

Question: I have multiple vectors of letters, in which an entry can appear multiple times. The vectors are of variable length.
ACBDEABAEE
ACDE
ACBDBBDDE

I want to determine statistically if A or C occurs mostly at the beginning of the list, whereas E occurs towards the end and D occurs in the middle.
Is there a way to do this?
Comment: Against what null hypothesis? That - conditionally on the number of each value, they're just randomly placed - or something else?
Answer: Several methods occur to me:
1) Define what you mean by "toward the beginning", "middle" and "toward the end", then do a chi-square analysis:
           B       M     E
A
B
C
D
E

This only tells you if the order is associated with the letter, but you can see from the results which comes first most.
2) For each letter in each list, compute a measure of place in the list. The most obvious is proportion of the list that comes before the letter. Then use that as a dependent variable and letter as an independent variable.
3) If you are just interested in which comes before which, compute a set of duples or triples and see which are most frequent.
Comment: One way would be to find the average proportion of letters that come after your letter; e.g. ABABC  - 4/5 come after first A and 2/5 come after 2nd A, average is 3/5. Then that could be the DV in a logistic regression.


How to know that a specfic incoming sms is a reply to a previous outgoing sms?

Question: I am integrating Twilio SMS service where my users are able to send SMS messages to their clients. I would like to be able to link each reply with the sent SMS. In another word, is there any field in the Message Resource that could lead me to conclude whether the incoming message received is related to the outgoing message my user sent previously ? I need same behavior as Email send/reply functionalities.
Answer: Twilio developer evangelist here.
There is no way to do this I'm afraid, the SMS protocol has no information about users replying to a specific message. SMS is chronological, you can test this by opening your phone's SMS app and trying to reply to the second to last message you received from someone. In SMS there's no way to do that.
The best thing you can do is consider the messages chronologically, and assume that the reply is in response to the last message you sent to that number from the number you sent it from.
I suspect your are interested in this because you need to send notifications and get responses to those notifications and you realised you might need to send more than one notification to a user at a time but still get their responses. The best way to get around this is to use different numbers to send the different notification messages from, then when they reply you can tell which notification they were replying to by the number they sent the message to.


Akka actor instance and class

Question: When the Akka manual refers to an actor, does it mean an instance of an Actor subclass? Or is it Props that allow creation of multiple actor instances?
So when it says an Actor has a mailbox, does it mean one mailbox per Actor instance, or a single mailbox per multiple instances of the same-Props actors?
Answer: When documentation refers to actor instance, it's an instance of Actor, Props is just a configuration object. See scaladocs
Think of Props as a recipe - meaning that each baked actor instance will be separate and have separate mailbox. For instance, you can configure deployment configuration in both config file (application.conf) or in Props. See docs in addition to example from scaladocs (e.g. props.withRouter(...))
There are two entities that can be referred as an actor:

Actor instance, or object of Actor class is usually referred as an actor. So, when you read 'actor is created' it means that this instance is created
ActoRef is a pointer to the Actor (or its mailbox) that is used to interact. As you shouldn't (and will not) interact with Actor instance itself, you will send messages to the ActorRef. So, if you read 'send message X to the actor Y' it means that you invoke ! method on ActorRef pointing to actor Y's mailbox.
Comment: But when it refers to just an Actor? Without saying it's an instance. Does it actually mean an instance? As with the mailbox example.
Comment: Updated answer regarding instances and refs

Akka actor instance and class


Are Exponential and Trigonometric Functions the Only Non-Trivial Solutions to $F'(x)=F(x+a)$?

Question:
Are exponential & trigonometric functions the only non-trivial solutions to $F'(x)=F(x+a)$?

$F(x)=0$ would be the trivial solution. Then, for $a=0$ (or  $a=2\pi i$), we have $F(x)=e^x$, and for $a=\dfrac\pi2$ there are $F(x)=\sin x$ and $F(x)=\cos x$. But the three are connected by Euler's formula $e^{ix}=\cos x$ $+i\sin x$. Indeed, on a more general note, letting $F(x)=e^{\lambda x}$, we have $\lambda=\dfrac{W(-a)}{-a}$ where W is the Lambert W function. My question would be if these are the only ones, due to the special properties of the number e and the exponential function, or if there aren't by any chance more, which do not belong in the same family or category as these, i.e., which are not exponential or trigonometric in nature ? Thank you.
Comment: That seems like an unrealistic expectation.  Delay differential equations have an entire interval of definition as input.  So you could easily ensure that's not an exponential or trig function.
Comment: Questions on this kind of equation are a recurrent theme on this site. It is an example of a linear retarded differential equation (up to a change of sign). There is a survey "A shifted view of fundamental physics" by Atiyah and Moore, available on arXiv 1009 2176.
Comment: For example, if $a<0$ is real, look at the solutions with $F(x)=0$ on $[0,-a)$.  That's not trig or exponential, unless its the zero function.
Comment: Possibly the question becomes more interesting (or tractable) if $F$ is assumed analytic? If $F$ is merely $C^\infty$, then taking for example $a = 1$ and any $C^\infty$ function $F$ such that $F^{(n)}(0) = 0 = F^{(n)}(1)$ for all $n \geq 0$, the extension of $F$ to any interval $[n-1, n]$, for $n \in \mathbb{Z}$, can be defined recursively by appealing to the functional equation.
Comment: From a more purely mathematical perspective, I was also able to find [this](http://www.emis.de/journals/EJDE/conf-proc/13/i2/iakovleva.pdf).
Comment: related: http://math.stackexchange.com/q/199691/
Answer: Look at these MO entries:
https://mathoverflow.net/questions/114875/on-equation-fz1-fz-fz/114878#114878 ,
and
https://mathoverflow.net/questions/156312/solve-fx-int-x-1x1-ft-mathrmdt/156315#156315 .
They contain the answer to your question.
EDIT. To put it shortly, the answer is: "yes" and "no".
In exactly the same sense as the answer to a simpler question:
"Is every periodic function an
exponential/trigonometric sum"? "Yes" for a physicist, and "no" for a mathematician.
But every periodic function is a limit of exp/trig sums.
Comment: So you're saying that exponential and trigonometric functions are indeed the *only* type of solutions to this problem, or am I misunderstanding something ?
Comment: It depends on the exact definition of "trig and exp functions". You can take limits of their linear combinations.  With a proper definition of limits all solutions are such limits. The references are given in MO entries that I cited.
Comment: I guess it's a good thing that I nagged my father into teaching me the [Cyrillic alphabet](http://en.knigoteka.net/math/file5915.html) when I was a kid. :-) I found the *Gelfond* reference on page $379-380$.
Comment: Also in [RAND](http://www.rand.org/content/dam/rand/pubs/reports/2006/R374.pdf), on page $45$.
Comment: Gelfond is available in English MR0342890. But in Russian it is available FREE. As most Russian math books are. A good justification to learn Cyrillic alphabet:-)
Comment: However I emphasize that Hormander's book covers all of this subject and much more. It is difficult to read, but rewarding.


Conditions that a complex matrix has real and identical eigenvalues

Question: Given a matrix $H \in \mathbb{C}^{N \times N}$, is there some condition on its elements such that all the $N$ eigenvalues are real and have the same value? Obviously, the trivial case of the identity matrix is not acceptable.
Thanks in advance.
Comment: If you have $N$ linearly independent eigenvectors with eigenvalue $\lambda$, then $H=\lambda I$
Comment: @HagenvonEitzen: is it the only possible condition?
Comment: This is not the answer but some suggestion to look for --  For having real eigenvalues, one needs to have symmetric matrices(this is subset of all the matrices with real eigenvalues). As eigenvalues of the upper triangular matrices are its diagonal values, upper diagonal matrices with same diagonal values will have same eigenvalues.
Answer: If we know that $H$ is diagonalizable (i.e. that $H$ has $N$ linearly independent eigenvectors), then the eigenvalues of $H$ are all equal to $\lambda \in \Bbb C$ if and only if $H = \lambda I$.
If $H$ is not necessarily diagonzalizable, we can say that $H$ will have $\lambda$ as its only eigenvalue if and only if $(H - \lambda I)^N = 0$, or equivalently, $(H - \lambda I)^k = 0$ for some $k \leq N$.
Answer: @Riccardo.Alestra , you give to Omnomnomnom the green chevron and, yet, he does not answer your question. Of course, Omnomnomnom is a very good mathematician; perhaps you are impressed because he has $10^5$ points. Would you give him the chevron if he wrote that $2 + 2 = 5$ ?
In fact, a solution to your question is about that follows:
Let $H=[h_{i,j}]$ and $\chi_H(x)=\det(xI_n-H)$.
The NS condition is $trace(H)\in\mathbb{R}$ and $\chi_H(x)=(x-\dfrac{trace(H)}{n})^n$.
Clearly, this condition links the $(h_{i,j})$.
EDIT. Answer to  @Omnomnomnom . I hope that you are not upset. In fact, we often tell students they do not answer the question. If we do the same, then we are not credible. Here, the OP's question is clear. The required eigenvalue is explicitly $trace(A)/n$; moreover, it is real; moreover the fact that $A$ is diagonalizable or not, is interesting but has nothing to do here; in particular, the calculation of eigenvectors of $A$ can only be done if one knows the eigenvalues!
Comment: Oh, I see now.  To make my answer complete, the candidate eigenvalue $\lambda$ should be expressed "in terms of $H$".  Well done.  To be fair, it wasn't clear from the question whether the eigenvalue was a "prespecfied" $\lambda \in \Bbb R$.
Comment: I appreciate the somewhat backhanded compliment.  In what way does my answer not answer the question?  The condition I present is that $H$ has $\lambda$ as its only eigenvalue if and only if $(H - \lambda I)^N = 0$.
Answer: Elaborating on Hagen von Eitzen's comment:
If an $N\times N$ matrix has $N$ eigenvalues equal to $\lambda$, we usually speak of a single eigenvalue $\lambda$ with geometric multiplicity $N$. The latter means that there exist $N$ linearly independent eigenvectors with eigenvalue $\lambda$. Since the space if $N$-dimensional, these eigenvectors already span the whole space. Now, vectors with eigenvalue $\lambda$ always form a subspace. All this means that the the whole space is the eigenspace corresponding to $\lambda$.
By definition, the matrix $A$ acts as $Ax = \lambda x$ on an eigenvector $x$. In our case, any vector is an eigenvector, hence $\forall x : Ax = \lambda x$, which is the same as $A = \lambda I$.


"Only open voicing below middle C!" Really?

Question: Every resource I've seen and person I've talked to has said that putting low voices, usually trombones, in close spacing anywhere below C4 is to be avoided at all costs, due to muddiness. As I arrange, though, this rule is causing me some grief, as it forces me to treat the 2nd trombone as a chord-root machine, or to put the 1st trombone up into the higher part of its practical range, crossing higher than the alto voices. Not only that, but in band arrangements, making the baritone double the tuba at the octave would result in very close spacing anyway, and often between the two trombones!
Furthermore, I've recently seen band arrangements of considerable age and popularity (as in, played week in and week out every school year for no less than 80 years) that do use close voicing below C4. It's never long chords or extended passages, but they're there: Bb3 and G3, C4 and Ab4, and even (I think I saw it) Bb3 and G3!
This leads me to question: Is close voicing really so bad? If not, where's the limit? I'd never make a chord at F2 and A2, for example, and that for any instrument. If it is to be avoided like the plague, how am I supposed to handle voice leading?
Comment: https://music.stackexchange.com/questions/77173/lower-interval-limits/77176#77176
Comment: I think C4 really is a silly limit; going below that is seldom a problem at all, even for pretty juicy dissonances. It's true, trombones can be particularly problematic, both because of their piercing midrange SPL and the often less-than-ideal intonation, but still. And, even F2-A2-C3 is a perfectly usable chord in the right setting. What's more important than absolute limits is to make the harmonic structure clear, and keep in mind what just-intonation ratio each interval corresponds to.
Comment: Not completely relevant but I play the piano and I find that closed voicings below C3 (the C below middle C) sound muddy. I haven't done enough arrangement work to comment on how this compares with other instruments or groups of multiple instruments. Also, I'm sure if I played on a finely-crafted and well-tuned grand I would the lower registers more flexible.
Answer: There are acoustical reasons for not wanting close voicing in the lower register; in short, the upper harmonics muddy each other up and fog up the sound.
But in my experience, C4 is a really high limit; I can think of tons of scores with thirds below C4.
Every musical environment is different, and sometimes you might want that slightly muddy sound. But if I had to come up with a hard rule, I would be inclined to use C3 as your upper limit instead of C4.
Below C3, composers often just stick with octaves, but occasionally you'll find some perfect fifths between tuba and bass trombone, or split between two tuba parts, etc.
Edit: As I mention in a comment to mkingsbu's answer, Mahler 3 has consecutive thirds of D2–F2–A2 at m. 209 of the first movement. These tight spacings do happen, but typically they're written to create a very specific effect.
Comment: So I'm NOT crazy!
Comment: Also, much depends on what's going on in the high register at the same time.  Close-spaced low register chords with nothing above them are not so unusual (cf. various low brass chorales).  What really gets muddy is having close spacing in low register, plus a large overall range in the chord — the upper harmonics of the lower voices will muddy with the main pitches of the higher voices, giving an effect that's very rarely desirable.
Answer: Closed vocings aren't bad, but you need to be aware of the register you are in no matter what you compose. In lower registers, having notes close together isn't always what you want. Specifically intervals that are supposed to have color like 3rds and 6ths both will sound "muddied" to most. Perfect internals typically don't observe this problem. This is also the reason in most counterpoint people are taught to keep the tenor high. It's not necessarily a bad sound, but expected harmonies may not turn out the way you want to due to this property.
Like with anything else in music listen to what you are writing. You should be able to hear a difference in clarity from the low register closed chords to a higher register open. The muddiness may even be something you desire for your piece.
Answer: Human pitch discrimination is frequency dependent.  There is a concept of critical bands.  You can read about it in a text on Physics and music by Rigden.  I keep promoting that text because I've taught out of it as several universities.  There are probably many good texts on the subject.  In short, there is a critical minimum frequency difference at which people will not likely be able to hear the difference between two tones.  This also has an impact on the perception of consonance and dissonance in an interval.  It is a fact that small intervals will be "muddy", more dissonant, and perhaps indistinguishable at low frequencies (in the low registers).  That doesn't mean you can't do it.  At the end of the day you need to be happy with your arrangement.  If you're just looking to arrange a piece of music and trying to find work for each section I'd adhere to the rule (guide line) but it you're composing you have freedom to break the rules.  It will produce an effect and as long as that effect is what you want it works.  But I'd be careful and try it out during a rehearsal in an auditorium and see if it sounds the way you think it does.  The "muddiness" has nothing to do with acoustics and acoustic scattering and interference will make the effect worse.  If you find yourself with limited options for notes in lower registers you can always rearrange a piece to have different harmony, chord inversion etc.
Comment: _Physics and the Sound of Music_ by John Rigden? I will have to check that one out. When I need to I dip into James Jeans _Science and Music_, or go back to Helmholtz.
Comment: I have both, and Helmholtz's book is outstanding.  I especially love the reference to aether when discussing light propagation.  It's a little old fashioned but interesting.  Rigden is not as rigorous so don't have that expectation.  If you need rigor stay with Helmholtz or Fletcher and Rossing.
Answer: As a trombonist, I've used D3 as the cutoff though I make context dependent exceptions.
When you say:

or to put the 1st trombone up into the higher part of its practical range, crossing higher than the alto voices

That this isn't as big of a deal as you might think for trombonists, depending upon the difficulty level you are writing for. If it is a professional ensemble, C5 is absolutely expected range for a tenor player.  Alto parts slightly higher, up to the Eb above it, really.    So having each member of the trombone section belonging to a different 'voice' in an overall voicing in an orchestration is perfectly okay.
If you would like a snapshot of some writing that is largely considered idiomatic to the trombone, you can check out a resource such as http://www.tromboneexcerpts.org.  That is a collection of resources that are used in auditioning, which is why I suggest everything can be considered 'idiomatic'... because if it isn't, people are still treating it as if it is!  Perhaps a better way of putting it would be that it's in the 'standard repertoire' that a trombonist would be expected to play.
Each excerpt has a recording from several orchestras that demonstrate the written passage, so you can hear how it might sound on the trombone, in the context of the full orchestra.  In most cases it has all of the trombone parts so you can see the voicings for that part of the passage. The exception would be solos within a larger work, such as Mahler 3. Incidentally, that is a good example of a 2nd inversion, at least in the trombone part with a fairly tight D minor chord starting that particular excerpt, which would violate closed intervals or other voicings in the trombone part below C4.
Answer: Muddiness depends on other considerations as well, such as volume and tuning.  Just thirds (i.e., in a harmonic ratio of 6/5 or 5/4) will sound clearer than equal-temperament thirds.  Check out some renaissance counterpoint, which generally works very well with trombones playing the lower voices.  I'm thinking of Schütz Die mit Tränen säen, SWV 42, and Selig sind die Toten, SWV 391.  There are also some great pieces by Thomas Tallis usually sung by men's voices that have close spacing in the lower register in certain sections.
You may also be interested in a page I have found from the Ohio State University School of Music (by means of a web search employing heavy use of the <code>-</code> operator), called Spacing of Chords.  To summarize, the page notes that Walter Piston called into question the historical rule about chord spacing matching the harmonic series, since actual practice showed that acceptable spacing depended among other things on register.  The page then goes on to describe psychoacoustic work on chord spacing that has been done since the 1960s.
Comment: @JAF and thanks for your comment calling my attention to the fact that I wrote the name of the school incorrectly in the answer.  As an alumnus of Indiana University, I am normally more sensitive to these matters.
Comment: As an Ohioan, I love seeing The Ohio State University's name on such a useful and interesting article! Thank you for the link!


How much higher accuracy of train than test is enough to consider the model overfitted?

Question: Considering a dataset of 920 samples with 40 features in a binary classification problem. The dataset is the heart disease dataset publicly available here.
I preprocessed the dataset discarding those features which contains >50% missing data. Those which contains < 50% I imputed it using MICE ncbi.nlm.nih.gov/pmc/articles/PMC3074241. Then I bagged numerical data into categorical data by gathering the values in equal ranges and then encoding features by OHE. The info about the dataset is the following:

The models considered are:
Linear SVM, RBF SVM, Logistic Regression, KNN , Decision Tree , Random Forest
I tuned the parameters using RandomSearchCV:
> Model: SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma=0.1, kernel='linear',
  max_iter=-1, probability=True, random_state=None, shrinking=True,
  tol=0.001, verbose=False)

> Model: SVC(C=10000.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma=0.0001, kernel='rbf',
  max_iter=-1, probability=True, random_state=None, shrinking=True,
  tol=0.001, verbose=False)

> Model: LogisticRegression(C=0.01, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False)

> Model: KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=65, p=2,
           weights='uniform')

> Model: DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=10,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='random')

> Model: RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=30, max_features='sqrt', max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=4, min_samples_split=2,
            min_weight_fraction_leaf=0.0, n_estimators=400, n_jobs=1,
            oob_score=False, random_state=None, verbose=0,
            warm_start=False)

I got the following scores (mean +/- std) in a 10-CV:

It surprises me that the training accuracy and F-score is higher (specially in random forest) than the test one.
Besides I computed bagging algorithms by the same methodology (tuning the number of estimators with RandomSearchCV and having the base_estimator the previous models considered):
Model: BaggingClassifier(base_estimator=SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma=0.1, kernel='linear',
  max_iter=-1, probability=True, random_state=None, shrinking=True,
  tol=0.001, verbose=False),
         bootstrap=True, bootstrap_features=False, max_features=1.0,
         max_samples=1.0, n_estimators=200, n_jobs=1, oob_score=False,
         random_state=36, verbose=0, warm_start=False)

Model: BaggingClassifier(base_estimator=SVC(C=10000.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma=0.0001, kernel='rbf',
  max_iter=-1, probability=True, random_state=None, shrinking=True,
  tol=0.001, verbose=False),
         bootstrap=True, bootstrap_features=False, max_features=1.0,
         max_samples=1.0, n_estimators=100, n_jobs=1, oob_score=False,
         random_state=37, verbose=0, warm_start=False)

Model: BaggingClassifier(base_estimator=LogisticRegression(C=0.01, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False),
         bootstrap=True, bootstrap_features=False, max_features=1.0,
         max_samples=1.0, n_estimators=100, n_jobs=1, oob_score=False,
         random_state=38, verbose=0, warm_start=False)

Model: BaggingClassifier(base_estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=65, p=2,
           weights='uniform'),
         bootstrap=True, bootstrap_features=False, max_features=1.0,
         max_samples=1.0, n_estimators=100, n_jobs=1, oob_score=False,
         random_state=38, verbose=0, warm_start=False)

Model: BaggingClassifier(base_estimator=DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=10,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='random'),
         bootstrap=True, bootstrap_features=False, max_features=1.0,
         max_samples=1.0, n_estimators=500, n_jobs=1, oob_score=False,
         random_state=34, verbose=0, warm_start=False)

Model: RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=30, max_features='sqrt', max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=4, min_samples_split=2,
            min_weight_fraction_leaf=0.0, n_estimators=400, n_jobs=1,
            oob_score=False, random_state=None, verbose=0,
            warm_start=False)

I got the following scores (mean +/- std) in a 10-CV:

It also surprises me that there is no so much improvement from single algorithms to bagged algorithms.
On the other hand I also tried AdaBoost with Decision Tree and Logistic Regression (same tuning of n_estimators and learning rate with Random SearchCV:
Model: AdaBoostClassifier(algorithm='SAMME.R',
          base_estimator=LogisticRegression(C=0.01, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False),
          learning_rate=10, n_estimators=600, random_state=38)

Model: AdaBoostClassifier(algorithm='SAMME.R',
          base_estimator=DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=10,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='random'),
          learning_rate=0.01, n_estimators=200, random_state=34)

I also got the following scores:

Reading about ensembles methods one may believe that its accuracy improves from single models, however for logistic regression even worsen (just a bit) but still, for Decision Trees it does not really improved that much < 1%.
What could have happened? Am I overfitting?
Comment: You can do an empirical analisys or you can use cross validation train and test to minimize the changes of overfit. Another technique is to bootstrap the data, if it were possible.
Comment: Already made it. I will try to perform some kind of feature selection.
Answer: The gap between train and validation isn't what overfitting is. If you work under that incorrect definition you'll almost always choose underfitted models.
An overfit model is one where another would yield equal or greater generalization (which validation loss proxies) with less memorization of training data (higher training loss).
Comment: A model can be overfitted & still generalize better than a simpler model.
Comment: You need to provide a citation that it is the formal definition. I haven't seen that formulation before in various papers & books. Eg, your definition doesn't match descriptions in ESL ($\widehat{\rm Err}-\overline{\rm Err}$), or elsewhere. Steyerberg, *Clinical Prediction Models* (which I happen to have open for other reasons), states "A key threat to validity is overfitting, i.e. that the data under study are well described, but that predictions are not valid for new subjects".
Comment: You're taking that too literally.  That's just a definition he used for his class.  It isn't *the* definition.  I also put up definitions that I think will 'click' for students in my classes.  He also talks about "simpler" & "complex" models, and "rigid" & "flexible" models, but these aren't synonymous--that's fine, I do the same thing, but they're all just attempts to break through the conceptual logjam, they aren't meant to be taken as the final, perfect definition.
Comment: If it generalizes better, it is not overfit, at least relative to that simpler model.
Comment: You have an idiosyncratic & nonstandard definition of overfitting.
Comment: No, this is the formal definition of overfitting. I suggest you research what it means and see if your opinion changes.
Comment: Victor Lavrenko. Overfittings vs underftting https://www.youtube.com/watch?v=j9_yzC-x-js&t=2s
Comment: It seems like you're just arguing about semantics instead of the crux of my argument.
Comment: The point is, there is the kernel of a good answer, but the answer, as written, isn't really correct, & that's likely to be a disservice to people who come to this page in the future.
Comment: I agree that the model doesn't necessarily need to be simpler, so I removed it that word. But, I believe what I've stated now is what overfitting means.


Validando Data de nascimento

Question: Olá,
Estou tentando validar data de nascimento menor a 15 anos utilizando a seguinte regra:
1- Se o usuário entrar com a data de nascimento, verificar se o dia, mês e ano q o usuário digitou, corresponde a menor  que 15 anos, se sim, o botão será ocultado.
Inserir a seguinte função abaixo:
function calculaIdade(dobString) {

var data_nasc = document.getElementById('data_cri').value.split("/");
var verifica = data_nasc[2]+data_nasc[1]+data_nasc[0];

var dob = new Date(dobString);
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
var verifica = currentYear - dob.getFullYear();

alert(verifica); //mostra a idade
alert(currentYear); // mostra o ano

alert(birthdayThisYear);

if (verifica >= 15 && currentYear < birthdayThisYear ){
    //alert('pode');
    document.getElementById('mostravid').style.display = "block";
} else {
    //alert('nao pode');
    document.getElementById('mostravid').style.display = "none";

}

if (verifica == ''){
    document.getElementById('mostravid').style.display = "none";

  }
}

<input type='text' name='data_cri' id='data_cri' value='<?=$data_cri?>' size='12' maxlength='10' onkeyup='formataData(this,this.value);' onblur='return calculaIdade(this.value)'>

Por enquanto está funcionando validando apenas por ano, gostaria que validasse da seguinte maneira:
o usuário nasceu 21/09/2000 porém, a idade dele é de 14 anos utilizando essa função acima, amanha é dia 22/09, o usuário entrara com os dados 22/09, a função vai calcular 15 anos, ok .
Gostaria ajuda de vocês para calcular dessa forma.
Obrigado
Comment: Caso,queira agilizar seu trabalho :http://bit.ly/1efORk3 ou http://bit.ly/1KqRCR8 esta framework.
Comment: Temos um problema no cálculo quando consideramos o ano bissexto... se fizer a diferença pelo tempo exato passado o dia antes do aniversário pode ser considerado como ok..
Comment: tem algum exemplo ai ?
Comment: Obrigado pelo link e pelas dicas ...
Answer: uma solução contando os milisegundos

//define as duas datas base...
var actualDate = new Date();
//validando 25/09/2000 que ainda nao completou 15 anos
var birthDate = new Date("2000", "8", "25", "0", "0", "0");

// pega o milisegundo de cada uma
var actualMili = actualDate.getTime();
var selectMili = birthDate.getTime();

// 15 anos em milisegundos
var timeToTest= 1000 * 60 * 60 * 24 * 365 * 15; //15 anos em mili segundos...

//faz a diferença entre as datas e o tempo calculado
if( ( actualMili -  selectMili) >= timeToTest){
  document.body.textContent = "Pessoa com mais de 15 anos";
}
else{
  document.body.textContent = "Pessoa com menos de 15 anos";
}
Comment: Não funcionou h3nr1ke, qualquer data que eu insiro mostra que a  Pessoa com mais de 15 anos ...
Comment: Opa... como vc está inserindo as datas, lembrando que o mês deve ser colocado como número de 0 a 11, se vc rodar o código como está e colocar o ano de 2001 por exemplo, tem de mostrar com menos de 15 anos... lembrando o lance do ano bissexto que ainda permanece neste exemplo...
Comment: @hulckb coloquei o teste [aqui](https://jsfiddle.net/g33eo044/2/) dá uma olhada
Comment: @h3nr1ke, movi o seu exemplo para o corpo da sua pergunta.
Comment: show @TobyMosque, realmente só compliquei separando, obrigado.
Answer: Galera, deu certo ...
tive que utilizar ajax e php por questões de segurança, segue o script para quem quiser reaproveitar.
 //Data de nascimento
$data_cri = date('Y-m-d',strtotime(str_replace('/','-',$_POST['data_cri'])));

// data atual
$dt_fim = date('Y-m-d');

if (date('Y') - substr($data_cri,0,4) < 15){
        $date = str_replace('-', '/', $data_cri);
        echo "

Data ".date('d/m/Y', strtotime($date))." fora do intervalo.
 Menor que 15 anos não pode ser cadastrado!

";

}

// diferenca entre duas datas
if( isset($data_cri) && $data_cri!="" && isset($dt_fim) && $dt_fim!="") {
    $data_cri = DateTime::createFromFormat('Y-m-d', $data_cri);
    $dt_fim = DateTime::createFromFormat('Y-m-d', $dt_fim);

    if ((int)$dt_fim->diff($data_cri)->format('%y') >=15){
        echo "
<input type='submit' value='Prosseguir'>
";
        echo "

Idade: ".(int)$dt_fim->diff($data_cri)->format('%y').' anos

';
    }
}

Comment: Ajax pra calcular data com valores que já estão na tela? Quais questões de segurança?
Comment: Estava ocultando uma div quando a idade era menor que 15 anos, sendo assim, se o usuário malicioso inspecionava o elemento, ele mesmo poderia alterar a propriedade para display='block' nesse caso o botão seria habilitado e ele conseguiria prosseguir, por isso que criei a chamada ajax, abs
Comment: Cara, nunca delegue as validações apenas à interface com o usuário. Suponho que uma validação na ação do botão seria menos complexa e menos custosa à navegação e ao sistema do que fazer requisições adicionais ao servidor. Você também pode remover o elemento via JavaScript, evitando a possibilidade de se exibir o botão em casos inválidos. E o que acontece se o usuário tentar submeter os dados com o JavaScript desativado ou através de um batch?
Answer: você pode simplesmente adicionar 15 anos a data atual.

var formulario = document.getElementById("formulario");
var nascimento = document.getElementById("nascimento");
var enviar = document.getElementById("enviar");

var mensagemErro = function (event, input, mensagem) {
  //input.setCustomValidity(mensagem);
  alert(mensagem);
  event.preventDefault();
}

formulario.addEventListener("submit", function (event) {
  var data = nascimento.value;
  //nenhuma data informada
  if (!data) {
    return mensagemErro(event, nascimento, "Campo nascimento não informado");
  }

  //O browser não realizou a conversão de forma nativa
  if (!(data instanceof Date)) {
    data = data.split('/').reverse().join('-');
    data = Date.parse(data);
    if (!isNaN(data)) {
      data = new Date(data);
    }
  }

  //a data informada não é valida
  if (!data) {
    return mensagemErro(event, nascimento, "Campo nascimento não é valido");
  }

  var atual = new Date();
  data.setFullYear(data.getFullYear() + 15);

  //menor de 15 anos.
  if (data > atual) {
    return mensagemErro(event, nascimento, "Nascimento posterior a 15 anos atrás");
  }
})
<form id="formulario">
  <input id="nascimento" type="date" />
  <input id="enviar" type="submit" value="Enviar" />
</form>

No caso acima, estou usando um input do tipo date, então só preciso converter a data manualmente se a propriedade value não me retornar uma data.
Comment: @hulckb, estava se perdendo na exibição das mensagens, coloquei um alerta.
Comment: o script já trata este comportamento, por exemplo, se você abrir em um exemplo em um navegador que não tenha o `input:date` implementado (eg: Firefox), você vai poder digitar uma data no formato `dd/MM/yyyy`, neste caso ele vai entrar na condição `!(data instanceof Date)` e o algotimo `data.split('/').reverse().join('-')` irá converter `dd/MM/yyyy` em `yyyy-MM-dd` que é uma data valida no formato `ISO 8601`
Comment: esse script nao rodou TobyMosque ...,
Comment: como seria no caso da entrada do ano dd/mm/yyyy ?
Answer: Crie um objeto data com a data de nascimento do usuário e uma outra data com a data corrente menos 15 anos. Se a data de nascimento do usuário for inferior a data corrente menos 15 anos o usuário tem menos de 15 anos.
function idadeMaiorQue(dataNascimento, idadeMinima) {
    var userDob = new Date(dataNascimento);
    var maxDob = new Date();

    maxDob.setFullYear(maxDob.getFullYear() - idadeMinima);

    return !(userDob < maxDob);
}

Validando Data de nascimento


Non-static private variables in javascript

Question: I'm setting up my javascript objects like the following
Object1 = function() {
  var privateMember = "private value"

  return {
    publicMember: "public value"
    setPrivateMember: function(value) {
       privateMember = value;
    }
  }
}();

Now if I use prototypal inheritance to create new objects
Object2.prototype = Object1

And then set the private member
Object2.setPrivateMember("new value");

Then the value of private member in Object 1 changes too, so it behaves more like a static variable. Is there a way I can get private variables to not be static?
PS - I'm a self-taught programmer so my use of terminology might be a bit sketchy. Let me know if it needs clarifying
Comment: Should be using `Object2.prototype = Object1()`, or is that just a typo in the pasted code?
Comment: possible duplicate of [Private variables in inherited prototypes](http://stackoverflow.com/questions/3617139/private-variables-in-inherited-prototypes)
Answer: Righto, knew I awnsered something like this before:
Private variables in inherited prototypes
;oP
Comment: I knew it had to have been asked before, but just couldn't find the right phrase to search for.

Cheers for the answer
Answer: You're creating a global variable. Put var before it.
var privateMember = "private value";
Comment: This was a typo in my question. Problem still happens even when I use var
Answer: Edited my answer, can you check if this works?
Try this -
Object1 = function() {
  var privateMember = "private value";

  var returnVal =  {
                publicMember: "public value",
                setPrivateMember: function(value) {
                privateMember = value;
                }

           };
  return returnVal;
}();


Watching a file and sending an email when it changes

Question: I have a log file that occasionally has critical errors.  Each time a critical error occurs, I'd like to have an email sent to myself notifying me of the change.  Is there a unix tool / set of unix tools I can adapt for this purpose?
What I thought of doing was
tail -f logfile | grep CRITICAL > critical.errors
watch tail critical.errors   # And somehow, email on changes.

However, the watch command doesn't take an action.  So ... is there something like 'watch' that does.  Or perhaps a good existing script that will do this?  I can homebrew a bash/python solution, but I'd rather reuse existing tools for cleaner error handling, etc.
Answer: Try IWatch - it's a perl script based on inotify that does just what you need:
http://sourceforge.net/projects/iwatch/
You can also roll your own with inotify-tools, in particular inotifywait. Modifying example #2 from that page (untested):
#!/bin/sh
file=logfile
cp $file $file.last
while true; do
  EVENT=$(inotifywait --format '%e' $file)
  [ $? != 0 ] && exit
  [ "$EVENT" = "MODIFY" ] && ( diff $file $file.last | mail ... ) && cp $file $file.last
done

You could also keep a byte/line counter and only mail the new bytes/lines, but using diff is simpler. It could cause performance issues if the file gets big and changes constantly though.
Comment: Is there something like this for Windows?


Calculate weighted mean of different sized groups with different interests

Question: In a conference format you often try to find "the best talk" by letting the attendees vote. Of course the primary factor is the quality of the talk itself. The problem I see is that you have differently sized interest groups per talk skewing the results.
Example: Assume you have one talk with 100 attendees. You get an average of 7.5/10 out of the 100 answers of all attendees. Pretty good talk. Then there is this other talk only relevant for a very small special interest group with 5 attendees running in parallel to the other talk. As they're all friends they all vote with 10/10. Just using a mean would let the small talk win "the best talk".
Is this fair? Using a minimum number of responses as a cut-off point doesn't seem fair. Shouldn't a weighted average be used, using the sample size as weight?
What is the best / most fair way to figure out "the best" talk?
Answer: I think your hypothesis that group size affects the average score should be formally tested first. If you have data from previous conferences, you could regress average score of the talk on group size to see if it is a significant predictor.
If it turns out to be significant, you can use its regression parameter to "penalize" the average score of future talks.


How to select items in a custom control

Question: I wrote a custom control to displays items from an ItemsSource at calculated positions.
Generic.xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Control="clr-namespace:MyControls.Control">

</ResourceDictionary>

MyControl.cs
public class MyControl : MultiSelector, INotifyPropertyChanged
{
    private bool _layoutHandlingDone = false;
    private Border _drawingArea;
    private Border DrawingArea
    {
        get { return _drawingArea ?? (_drawingArea = (Border) Template.FindName("DrawingArea", this)); }
    }

    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    protected override Size MeasureOverride(Size aviableSize) { ... }
    protected override Size ArrangeOverride(Size finalSize) { ... }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if (Template != null && _layoutHandlingDone == false)
        {
            _layoutHandlingDone = true;
            ItemContainerGenerator.StatusChanged += (sender, args) =>
                                                        {
                                                            if(ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
                                                                InvalidateMeasure();
                                                        };
            DrawingArea.SizeChanged += (sender, args) => UpdateLayout();
        }
    }
}

Layouting and drawing the items works very well. Now I want the items to be selectable. For this I derived my control form MultiSelector, but it seems that this isn't enough.
What functionality does the MultiSelector provide and how should I use it in my control?
Answer: I strongly suggest to separate things here. Managing a collection of items and arranging them in a container control are two distinct concerns, and ItemsControl provides support for both.
Instead of overriding MeasureOverride and ArrangeOverride, you should write your specialized Panel class (and override MeasureOverride and ArrangeOverride there) and use that class in the ItemsPanel template of your ItemsControl.
You could then easily derive from ListBox instead of MultiSelector and would get all the selection functionality for free.
Comment: Deriving form ListBox did it. Thanks. But did I get you right: I can derive from Panel instead of ListBox. Put MyPanel into the ItemsPanel property of ItmesControl, a ListBox or what ever is selectable. And would get the same functionality?
Comment: Exactly. That's what the `ItemsPanel` property was designed for. Use a ListBox with a specialized Panel. I do this for example to arrange items on a map control at geographic locations. The map items are managed by a standard ListBox, but the ItemsPanel template defines a specialized "MapPanel" that does all the necessary calculations for actually arranging the items.

How to select items in a custom control


$X \in L_1$, $X_n \xrightarrow{P} X$ and $EX_n \to EX$. Prove that $X_n \xrightarrow{L_1} X$

Question: Let $X,X_1,X_2,\ldots$ positive r.v. such that $X \in L_1$, $X_n \xrightarrow{P} X$ and $EX_n \to EX$. Prove that $X_n \xrightarrow{L_1} X$.
My attemp:
We have to prove that $\lim_{n \to \infty}E|X_n-X|=0$, then we can observe that
$$E|X_n-X| \leq E((X_n-X)1_{[X_n \geq X]})+E((X-X_n)1_{[X \geq X_n]}).$$
First we take this part: $E((X-X_n)1_{[X \geq X_n]})$. Then we have for hypothesis that
$$(X-X_n)1_{[X \geq X_n]} \leq X \in L_1,$$
and
$$P[(X-X_n)1_{[X \geq X_n]} > \epsilon] \leq P[X-X_n > \epsilon] \to 0.$$
Then when we take limit
\begin{align*}
        \lim_{n \to \infty} E((X-X_n)1_{[X \geq X_n]}) &= E(\lim_{n \to \infty}(X-X_n)1_{[X \geq X_n]})\\
        &= \int_{\Omega} \lim_{n \to \infty}(X-X_n)1_{[X \geq X_n]} dP\\
        &= \int_{[X \geq X_n]} \lim_{n \to \infty}(X-X_n) dP\\
        &= 0.
    \end{align*}
For the second expected value I do not know how to proceed. Is there other way or this way is correct?
Thanks in advance.
Answer: Since $L_1$ is a normed space, it is enough to prove that from every subsequence $(X_{n_k})_k$ we can extract yet again a sub-subsequence $(X_{n_{k_m}})_m$ such that $X_{n_{k_m}} \to X$ in $L_1$. Since any subsequence of sequence converging in probability converges in probability, and from sequence converging in probability we can extract a.s convergent subsequence, we can WLOG assume that $X_n \to X$ almost surely. Let us denote $Y_+ = \max\{Y,0\}$ and $Y_- = \max\{-Y,0\}$ (so that $Y = Y_+ - Y_-$). Note that from $\mathbb E[X_n] \to \mathbb E[X]$ and $\mathbb E[X-X_n] = \mathbb E[(X-X_n)_+] - \mathbb E[(X-X_n)_-]$ we get $\mathbb E[(X-X_n)_-] = \mathbb E[(X-X_n)_+] + r_n$, where $r_n$ converges to $0$. Hence $$ \mathbb E|X-X_n| = \mathbb E[(X-X_n)_+] + \mathbb E[(X-X_n)_-]= 2\mathbb E[(X-X_n)_+] + r_n.$$
Finally, due to non-negativeness, $(X-X_n)_+ \le X$ which is integrable, and since $X_n \to X$ a.s, we get $(X-X_n)_+ \to 0$ a.s, hence by dominated convergence theorem, $\mathbb E[(X-X_n)_+] \to 0$, so by above, $\mathbb E|X-X_n| \to 0$.
Comment: This is another way to prove it... I see. I used a variant of Pratt Lemma to the second expression, but this is a nice way to prove it. Thanks!


What are the assumptions to path analysis and how to test them?

Question: There are some structural assumptions to path analysis that are not difficult ascertain. They are (a) no loops (b) no going forward and backward (c) a maximum of one curved arrow per path.
I am aware that path analysis assumes multivariate normality if the dependent variable is continuous. How do we check for this? What is the path model includes categorical variable as one of the dependent variables or independent variables? What are the additional assumptions?
Comment: Where exactly did you encounter assumptions a-c?
Comment: @AdamO Got it from Latent Variable Models by John C. Loehlin
Answer: It's important to distinguish causal or conceptual assumptions from statistical assumptions here. Reverse causality, for instance, has no test, since statistically $A \rightarrow B$ leads to a probability model for $P(A, B)$ that is identical to $B \rightarrow A$ without control for additional causal moderators.
Unlike most regression techniques, SEM requires normality of the residuals. There is one reason for this: only for multivariate normal RVs does no correlation imply independence.
Path models run sequences of regression models, and each regression leads to a corresponding error term (when specified in the model). You can graphically inspect the distribution of error terms and latent variables using their predicted values and a QQplot, which plots the quantiles of the observed distribution against the quantiles of an expected distribution (in this case normal). A good distributional fit will produce a straight calibration line. S shaped curves, or bathtub shaped curves indicate poor fit.
SEM in MPlus allows estimation of some models using robust standard errors, where the error terms are allowed to have non-normal, and non-heteroscedastic fit. This is the MLR... which I find a little disingenuous because the theory of robust standard errors does not jive with maximum likelihood. Differences in these fits and their inference would indicate problems with the path model and normality. See the Mplus discussion here. Lastly, even with MLR, any latent variables would still need to be checked for distributional assumptions, because they are obtained from a maximum likelihood estimate as plug-in estimates for other regression models. It's not as strictly robust as the Muthens' description would lead one to think. Use the QQPlot to assess.
I never in analyses or reporting use distributional tests, statistical testing is a poor framework for verifying assumptions. Graphical inspection is much cleaner, clearer and can actually give you some insight into exactly how small departures from assumptions may affect subsequent analyses.
Comment: The path model that I am analysing does not contain any latent variable. It contains 1 continous dependent variable and 1 binary dependent variable. All independent variable are continous. So does the normality of residuals still required? How about multivariate normal assumption for the covariance matrix?
Comment: @tatami why on earth wouldn't you fit a regression model then?
Comment: because there is a flow from the linear regression to the logisitc regression
Comment: What is the difference between a structural equation model, which appears to encode paths, and a path model?
Answer: We have four assumptions:
1 : linearity of model
2: The exogenous variables not correlated with disturbances.
3 : The disturbance are not correlated.
4 :  Recursive model
See Bollen 1989 for more details and linear causal modeling book.


How to handle free and paid orders with post processing?

Question: I'm going around in circles trying to use Drupal Commerce to make an ecommerce site where some orders cost money and some don't (because some users have coupons that make products free).
I've set up the Checkout process as seen in the screenshot below and have created a rule as such

Rules Event: Process checkout pane
Rules Conditions: Price comparison (commerce
order = $0)
Rules Actions:

Change pane properties (disable billing
information, off-site payment redirect, Payment)
Update the order state to (pending/complete)

With this setup when the user goes through without a coupon it all works fine. When the user uses a coupon to get the price to zero on the Checkout page the user presses the Continue to next step button and goes to an empty Review page (the panes have been set to disabled so there is nothing to see) and they can't progress any further.
Pressing the Continue button on that page just bounces them back to the same page. If they press Cancel and go back to the shopping cart, then on through checkout and press "Continue to next step" again (the coupon has been remembered and the total is still $0) then get sent to the Checkout Complete page and hook_commerce_checkout_complete($order) is called.
I've tried adding extra actions to the rule, to complete the checkout or change the order status, but they have strange side effects like going to the Review page anyway, or calling that hook twice.
Can anyone help me set up the checkout and rules so that a free order goes straight to complete from the checkout page, whilst still maintaining the normal path for orders that require payments?
Comment: I believe this is a known bug in commerce discount (the integrating part of commerce coupons). Try running the latest development version
Answer: You would be better to implement a custom payment method that can be active when the order has a 0 balance.
If the order has payment required, use the standard payment method.
If the order has no payment required, complete checkout.
e.g: https://drupal.org/project/commerce_no_payment
Comment: I'm already using that module (actually the Payment module that replaces no_payment) but I don't want the user to have to choose the "No payment" option from a radio button list as that setup directs so I want to skip right over those panes.
Comment: Just make the other payment method not available (in payment method rules configuration) then only one payment method will be active.
Comment: I have two rules to turn on credit card payments and turn off no_payment according to the order total. But when only one payment method is active the user still has to pick it from the list.


User contributed image gallery, per node

Question: Working on a new Drupal 7 based site.  Put together a few sites back in the 5 days, but lots has changed.
I'm looking to allow users to upload images to a particular content type, and to show those images as a gallery.  Restated - I'd like user X to be able to create a node, and then users X, Y, Z, P, D, and Q to each be able to upload images to that node.  (Looking to the future, I want people to vote on images, but let's keep it simple, for the moment.)
My sense at this point is that I have to create an entity type for image, use entity reference to point from the images to their parent node, and use views and probably eva to show the galleries on the parent node.
Question 1: Am on the right track here?
Question 2: How should I handle the 'allow anyone to upload images' piece?  I'd like there to be a rather simple opportunity, when a user is viewing a parent node, to upload an image or provide an image url, and for the image node to be created and appropriately associated.
Thanks for any help.
Answer: You could just use the modules:
http://drupal.org/project/references
and
http://drupal.org/project/nodereference_url
This would work if users create new images as nodes. With the help of the second module you achieve that the relation between image node and parent node is automatically created and it also allows to set a link directly on the parent node (a la: create image for this content).
I don't think that you would need EVA in this case. The view to show all images per parent content is straightforward with one argument based on the relation.
What I describe above is pretty much the way you would have done it in Drupal 6 as well. You might get additional features (and maybe complexity) using the module entity reference and EVA.
Hth.
Answer: Another solution would be to have users create a node for each image and then select the "gallery" the photo is assigned to. You can use the built-in taxonomy term reference for that.
To automatically prefill a term reference field (to upload a photo for a given gallery) you can use the prepopulate module.
Answer: To answer your questions,

Question 1: Am on the right track here?

Yes!

Question 2: How should I handle the 'allow anyone to upload images' piece? I'd like there to be a rather simple opportunity, when a user is viewing a parent node,

When displaying the gallery, display the form for users to add a new image.

to upload an image or provide an image url,

You can add 2 fields,

Field image (image field)
Field image url (link?)

You will need to add logic, determine precedence.
Another option, add a third field that allows someone to check if it's an image or a file and then based on that, present the right field.
For your display,
If it's an image url, you'll need to decide if you'll either download the image or just use the URL provided.  (You mentioned in the future voting, so people could down vote problematic/broken links.)

and for the image node to be created and appropriately associated.

https://www.drupal.org/project/entityreference_prepopulate
:)


Confusion about the rhythm I use

Question: This might be a odd question but on guitar I have this lick where I would play 3 notes with the same distance to each other between the strokes and then I would play 4 notes slightly faster (with the first note of this set of 4 having the same distance to the last note of the set of 3 but then all notes in the set of 4 have a shorter distance). I'm relatively new to theory and notation but can I assume what I play could be notated as a triplet of 2 quarter notes + 4 eight notes ? If so what rhythm is best suited underneath it ?
EDIT:
Since I have no possibility of recording myself right now I tried to visualize what I mean:

The time passed by the blue bar and the red bar is equal.
If I would play 8 notes with the same distance between each stroke I
would get the pattern of line 2.
The way I play it the first 3
notes take up as much time as the 4 notes do and I have 7 strokes
total.
Comment: This may be really hard to answer by this description. Do you have a link to video or recording of you playing this?
Comment: Edited my question to provide a better understanding.
Comment: If it is in 4/4 I'd say it's triplet crotchets followed by four quavers.
Answer: Possibly you mean:
Dotted eighth note, dotted eighth note, eighth note, eighth note, eighth note, eighth note, eighth note?

If this is the case, note that the first 3 aren't played with the exact same timing (the gap between the 3rd and the 1st note of the second group of 4 notes is too small to be a triplet)
Comment: Alternatively, those opening three pitches could be a quarter-note triplet.
Comment: It feels like the first 3 notes belong together and the last 4 notes belong together, so I'm guessing that its triplet + 4 eightn notes. I edited my question with a visualization of what I mean.
Answer: If the entire graph you have there is one measure, or in 4/4 time, 4 beats (which equals one measure) then red and blue are half notes. And in 4/4 half notes get two beats each.
The second row has 8 notes in the measure. Easiest way to think about that is that you are playing eight notes. Anything divided by 8 would get you eights. But you can also think there are two for each beat. One beat 4/4 would be quarter notes and a quarter note divided in half is eight notes.
The third row has three notes for each half note. Anytime you have 3 to a unit you are most likely dealing with triplets. In this case you have what is called quarter note triplets.
Hope that makes sense.

Confusion about the rhythm I use


'django-admin help' Fatal error in launcher: Unable to create process

Question: When I try to run "django-admin help" or any other django-admin command in the vscode terminal (within the virtualenv) it gives me the following error :
Fatal error in launcher: Unable to create process using '"F:\DevOps\Django\btre_project\venv\Scripts\python.exe"  "F:\Django\btre_project\venv\Scripts\django-admin.exe" help': The system cannot find the file specified.
The whole Django project was located in F:\DevOps first but then I moved the Django folder outside the F:\DevOps so it's now at this location currently "F:\Django".
Virtual environment can be activated and deactivated perfectly and also if I start the server with "python manage.py runserver" The server is up and running. But whenever I try to run the django command it gives me the above error.
Also, in the virtual environment of project django is installed and I also tried reinstalling the django in the virtualenv with pip but nothing worked out and I get the same error.
Any help would be appreciated, thanks.
Comment: Does this answer your question? [Can I move a virtualenv?](https://stackoverflow.com/questions/32407365/can-i-move-a-virtualenv)
Comment: No it doesn't . my virtual environment is working fine. like it can be activated and deactivated but the django commands give the error.
Comment: If you read the above linked question carefully the virtual environment's `activate` scripts etc. have the path of the virtual environment hardcoded, they set that as an env var for the current session. That is how `django-admin.exe` knows which python to use and also the reason you get the error.
Answer: The easiest way to handle this is to create a new virtual environment, pip install django in that environment and it will resolve this specific issue.
PS: Then run your manage.py server on this new virtual environment instead of the old one!


Android Restricting file to applications

Question: Android Application Development ::
Is there any way to restrict/moderate the access of file created by one application to other applications/file explorers?
Ex: App ABC created file file.txt
Now, file.txt could only be accessed (access mode 700 in Linux Structure) by ABC app. This file should also be hidden/secured from file explorer apps.
Context: This could be a settings file such as JSON/XML which should be made private only to this application but stored in ext. mem card (I can use assets folder but this file keeps adding new settings to the existing settings eventually).
Any Ideas??
Answer: Anything on the external storage is world readable.
If you need to store data private to your app, your options are Shared Preferences, or Internal storage.
See the Storage Options page at the Android Developer site for samples of using each type of storage.