What are the chords names for these two-note "chords"?

Question: Live On Forever by The Afters has a "chord" progression that continues throughout the entire song, but each "chord" only has two notes, which are:
C, E♭; (must be Cm, the only chord that works)
E♭, G; (E♭ or Cm, probably Cm because the "C" note from before seems to be sustained into this "chord")
G, B♭; (Gm or E♭)
F, B♭; (must be B♭)
F, A; (Dm or F)
How would you name these?
The chords I would name it is Cm, Cm, E♭, B♭, F
It really tricked me because it's in C "dorian" (so its key signature resembles B♭ but ends on a C note), and there are no accidentals in the entire song, so the possible chords are F, B♭, E♭, Dm, Cm, and Gm.
If you want to listen to it, it's clearest at the very beginning.
Comment: Is there a bass player or keyboard player who is also playing at the same time but might be playing other notes?
Comment: You can only analyse what isn't there by making assumptions.  By pinning the music down to a set of chords YOU feel comfortable with, but which the composer specifically chose NOT to confirm.   There's a pleasing ambiguity about two-note harmony.  Let it alone.  Not everything has to fit into a straijacket of triad-based harmony.
Comment: There'll be multiple hits if you search for "Live on Forever The Afters chords". While not always trustworthy (some may have deduced by individuals, some copied, others from actual sheet music), would any (or most) of these pages agree with your assessment? Or convince you otherwise?
Comment: Be careful. The writers of this song could have used full chords, but they didn't. They preferred the harmonic ambiguity of just two notes. If you decide what the 'implied' chords are and write them in, you'll be encouraging players to play those full chords. Which would be wrong. Sometimes chord symbols aren't the right tool for the job.
Comment: @LaurencePayne, isn't there a difference between using the symbols to analyze the harmony versus using the symbols in lieu of notation? I do agree chord symbols in lieu of notation is a problem if you want to ensure exactly what notes are played.
Answer: I would label it Cm, Eb, Gm, F. With roman numerals it would be i, III, v, IV.
You could say the first three chords are an arpeggiation of a Cm7 chord. Then the pattern is just Cm7 F.
Cm and Eb for the second and third chords seems wrong, because the roots are missing, any why not give them straight forward labels as root position chords instead of calling them rootless chords?
Regarding the Bb above the final F chord. That note is held over from the previous Gm chord and so you can call it a suspension which then resolves by stepping down to the A - the third of the F chord. In other words, the F  Bb isn't a separate chord. It's an F chord embellished with a suspension.
Comment: Chords cannot be implicitly defined using two notes, however they can be implied by the harmony around them. In this case, the previous chords "add together" in the listener's memory to create a Cm7 effect.
Comment: @AricFowler, Cm7 is the interpretation I gave in the second sentence. Either interpretation seems fine to me. I think the more important point is not interpreting Bb over F as a Bb chord in 6/4 inversion, but to regard it as a suspension.
Comment: Oh, like an Fsus4?
Comment: Yes, exactly. So Cm7 Fsus4 F seems ok. FWIW, normally I don't like when songbooks use sus4, add9, etc. to denote notes sung in the melody, but clearly not played in the chords of the rhythm section. But, in this case the suspension is clearly played by the rhythm section so the sus4 label is meaningful and necessary.


How to get AMusTCL for theory by self learning?

Question: Is there any way to get AMusTCL for theory by self study?I can't find any music centre in my area that offers course for Amustcl. Or is there any recommendation for theory classes for AMusTCL in Negeri Sembilan(my area)?Thanks.Maybe I would also consider DipMusLCM?
Comment: Thanks for your posts and advice. I am also planning to self study diploma in theory and was debating on Trinity or LCM. After looking at their sample papers, I think better to go for AMusTCL. I will be sourcing for reading materials.
Comment: Two things here: Number one, you may want to contact the moderators to get your accounts merged. Number two, please don't write "thank you" as an answer.
Comment: How did you go about doing TCL Grade 8 Theory, Elise? (Or anyone who could help answer this)
Answer: I am preparing AMusTCL by self-study. I would advise the following:

Comparing the other existing qualifications at the same level (or lower or higher), such as DipMusLCM, AMusLCM and LMusTCL. There is no prerequisite for DipMusLCM. AMusLCM and AMusTCL. One needs to have Grade 8 Theory in Music in order to pursue for LMusTCL, which is higher than AMusTCL.
Reading through all the syllabus and the sample papers, which are available for free in the respective websites. Once again, understand thoroughly to see which format of exam is more suitable to your ability. AMusTCL is a single paper of 3 hours, where as AMusLCM consists of two 3-hours papers. I personally feel AMusTCL is better in this sense.
AMusTCL requires less essay writing, compared with DipMusLCM or AMusLCM. At least you can choose to answer structural questions in Section B. Good writing skills in English, in the context of music is demanded.
Availability of the exam. Will that be difficult for you to find an exam centre to register for the exam? Any local representative? Trinity College London local representative at my area (Penang) is very helpful in advising me the registration process, exam fees and dates, even I will only take in exam in November 2019!
Fees! Money is a factor in taking this exam. Which qualification can you afford?
How much of time can you allocate to study? Are you a full time student or a busy working adult? Since different syllabus requires certain areas of study, you might roughly calculate the workload that you need in each week and how much of time do you need to spend to study. I am a busy medical personnel working in a hospital with certain days to on-call, and at the same time I am pursuing law degree. Thus, despite I can straight away to sit for LMusTCL with my Grade 8 Theory in Music, but with very limited of time I think AMusTCL suits me better. So, this varies from a person to another.
Study materials. DipMusLCM has most of its study materials available free in the website to be downloaded. As I said, most of it, but not completely everything. Past papers can be purchased online and then downloaded and printed. Anna Butterworth's Harmony in Practice is very helpful in tackling Section A. Of course, you can purchase online the Revised 2017 Study Guide AMusTCL which explains the exam well. And you need to buy some scores for Section B.
Your previous musical knowledge: If you have learned and sat for Grade 5, 6, 7 and 8 Theory of Music (in this manner, progressively), you probably have gained a good foundation in Harmony. Despite there is not prerequisite for AMusTCL, but I still believe that one must have a Grade 8, or at least its corresponding knowledge in order to study AMusTCL. At the end of the day, it is still a Diploma qualification and definitely much demanding than Grade 8.
Comment: But how about the composing and essay parts?As I believe that these parts needed some marking or advice,so how could you overcome this by self studying?
Answer: There's a sample exam paper here.  How close are you to being able to complete it?   The requirements are general musical skills, you don't need a specific AMusTCL course.  I'll have to leave you to research teachers and classes in your area.  But as you've reached the level where you can even consider an advanced diploma, you must have SOME contacts?
http://www.trinitycollege.com/site/?id=1589
Comment: I asked my ABRSM grade 8 theory teacher that she seem even don't know about that there exists some theory diploma.How could I know my answer is correct if there isn't some person to mark my exercise?
Comment: There is a sample answer alongside the sample exam paper.   But, before looking at it, attempt the paper.  Your teacher may not have heard of this diploma.  But she will be able to tell you if your answers are anywhere near the required standard.
Comment: I cannot ask my teacher to help me as I already finished my course with her.
Comment: You're going to have to ask SOME teacher to help you.  Why not the one you already know?    Anyway, talk to her.  If she doesn't want to teach you, she'll be able to recommend someone else.  Teachers LIKE helping ex-students you know!
Comment: Is there any recommendations for anyone who marks papers online?
Comment: Well, is there any recommendations materials for aspects of essay questions? Even though maybe I can do the first section myself(as you said maybe I can ask my teacher for some advice) , the essay question I can't find some materials or any notes in the internet,or is it possible to find out myself by looking the score?
Answer: But how about the composing and essay parts?As I believe that these parts needed some marking or advice,so how could you overcome this by self studying? – lyk Feb 15 at 16:20

Responding to this question, as long as Trinity does not disclose the marking scheme to the public, no one will know how the marks are allocated for essay or composition, unless you have a teacher who is a Trinity examiner. Trinity website provides the sample paper and suggested answers. From the suggested answers, you may know how extensive and intensive a standard answer should be. Composition and essay are something that really depend on one's creativity and the response could be vary from candidate to candidate, since everyone comes from different background. As far as I concern, DipMusLCM has published a very well written study guide, unfortunately it does not really cover the essay part. I could understand the logic here, LCM (or most of the exam boards) believes there is no standard answer for essay or composition. If you read intensely, you should not have any problem with this. If you do really need guide, you may get an A-Level Music (either Edexcel or Cambridge) textbook to help you.


preventDefault() submitting form

Question: I am fairly new to jQuery and JavaScript in general.
I have a form, and what I want to do it have the form run a function to make sure everything is there, and all the variables are correct then submit.
I have used onclick value to the submit button and have it run a function that uses preventDefault(). I am not sure if im using it correctly but it doesn't seem to be working.
This is what I have and when you click submit, it just submits even if the if statement is false.
function checkSubmitStatus() {
    $("#myform").submit(function(event){
        if( whatever==true) {
            event.preventDefault();
        }
    });
}

<input type="submit" name="submit" value="Submit"  onClick="checkSubmitStatus()">

Thanks!
Answer: By putting $("#myform").submit(...) inside the checkSubmitStatus() function, you're attaching the submit handler after the button is clicked and the form is already submitted. Try this:

<form id="myform">
  <input type="submit" name="submit" value="Submit">
</form>

Comment: Thnaks, your detailed answer was what i needed, you not only helped me fix my issue but also realize an issue i didn't notice! Thanks!
Answer: Change
<input type="submit" name="submit" value="Submit"  onClick="checkSubmitStatus()">

to
<input type="submit" name="submit" value="Submit" >

and change your javascript to
$("#myform").submit(function(event){
    if( whatever==true)
    {
        event.preventDefault();
    }
});

Comment: You can't attach `onSubmit` to an input tag, only to a form tag.
Answer: You can just drop the checkSubmitStatus() function.
$("#myform").submit(function(event){
  if(whatever == true) {
    event.preventDefault();
  }
});

Also drop this:
onClick="checkSubmitStatus()"

Answer: In the onclick event handler, if you return false the form will not submit. Try doing this:
function checkSubmitStatus() {
   if(validationSuccess==true)
   {
      return true;
   }
   else
   {
      return false;
   }
}

<input type="submit" name="submit" value="Submit"  onClick="return checkSubmitStatus()">

Comment: Upvoting because this solution is what *I* was looking for; something that does not use jQuery (even though the OP is specific to jQuery!)
Answer: I would refactor this slightly...
function checkSubmitStatus() {
    if( whatever==true) {
          return false;
    }
    return true;
}

<input type="submit" name="submit" value="Submit"  onClick="return checkSubmitStatus()">

Answer: let button = document.getElementById('submit');
button.addEventListener('click', function(event) {
    event.preventDefault();
    this.innerHTML = "Button clicked!";

});

Comment: This does not really answer the question within the scope of what the author is asking as it does not use JQuery. However it has great value as an answer if you can add a description as to what your code does and what it is achieving differently.

preventDefault() submitting form


Using a network mount as user home in Mac OS X Server App (v5)

Question: We have an old Mavericks server with a Firewire drive running and about 200 Users (Mac OS Server v3.2.2).
I would like to set up a new server with El Capitan running the latest v5.1.7 Mac OS Server application. For the test phase, I want to use the Firewire drive connected to the old server, so I can test with a few selected users the new server without copying/duplicating the data.
I added the Firewire drive to the shared folders and mounted it on the new El Capitan server, however I could not figure out how to add that to the Storage list 1, so I can select that as a home folder location 2 for the migrated users.
Is this even possible?
Answer: This should only be a matter of changing a simple option first, in Server.app.

Click on the left-hand pane where there is a section called "File Sharing."

You will then see, among the choices there, a checkbox by "Make available for home directories over [your choice of SMB and AFP]."

Check the box "Make available..." and chose SMB (or AFP).
Here's an image of this checkbox:

I suggest using SMB since it is the default file-sharing protocol for OSX in the latest versions, unless users need the afp-added ability to change their passwords while working with the share point.

Now when you return to the "Users" section, like in your first image--make sure you have selected "Network Users" at the top, and authenticated into your Open Directory--you will have the share (in your case, the 1394 aka 'Firewire'-connected-share) as a choice for Home Directories, here now.

*You may need to restart the file-sharing service or other services for this change to take place.
*This may not be the ideal way to test your new server.  I would suggest that you try and simulate the new setup completely, e.g. copy over the exact Users, Groups, etc. that you would like to use, even if it is just one of two Users, rather than using a Firewire drive.


Importing products via Feeds csv import is generating error: "General error: 1366 Incorrect string value:"

Question: I'm trying to import products using the import via csv functionality within feeds and am getting the following errors:
<code>SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'field_description_value' at row 1
Error message SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'message' at row 1
</code>
I also have the commerce-feeds module installed.
There is quite a lot of stuff on this on drupal.org, but it all seems to be contradictory and I am more than a little lost. I am a non-coder and a relatively inexperienced configurator at best.
My csv is definitely encoded UTF-8. I have opened it in Notepad++ and converted it to UTF-8.
I found this post on stack overflow utf-8 database problem The line "It seems your connection is not set to UTF8 but some other 8 bit encoding like ISO Latin" seems to indicate to me that there may be a bug in the Feeds or Commerce Feeds modules in that the database connection cannot cope with csv input files encoded UTF-8. Could that be correct?
I'd really appreciate some sage advice on this. I am completely stuck.
Answer: Maybe the csv is encoded in UTF8, but everything else needs to be UTF8: UTF8 all the way through
I don't know exactly in what step is failing, did you check the databases and tables collation?
Drupal has by default the "SET NAMES="utf8", http://drupal.org/node/310447
Hopefully the Feeds maintainers have a look to your case here. http://drupal.org/node/1140194 , it seems you are not alone.
Comment: Thanks for making the effort to respond. I'm quite embarrassed but I actually started the whole process again starting with the original excel file, save to csv, pull in to notepad++, change the encoding to UTF-8, and then import; and now the import process is working fine.

The bounty is all yours though except the system says I have to wait for 21 hours before I can do that.
Comment: Thanks, I'm sure your question will help other people with same problem.


MySQLi plugin not loaded

Question: I recently upgraded to MySQL 5.7.9 from having previously used 5.5 (by removing the old mysql and installing the new one). Now when I run a PHP script (which used to work), I get this error:

Warning: mysqli::mysqli(): (HY000/1524): Plugin
  '*8CC466EE1F3C4B48CF50D1E337EE808AC922A16E' is not loaded in...

Any idea how to fix this?
Comment: Have you tried reinstalling php5-mysql by using `sudo apt-get remove php5-mysql && sudo apt-get install php5-mysql`?
Comment: Yes I did... now PHP Version 5.5.30-1+deb.sury.org~precise+1
Comment: Does the error show in the mysql error logs, or is this warning php specifically?
Comment: i would suggest removing both MySQL and and PHP. After that reinstall PHP and then MySQL (in that order).
Answer: As it turned out, in my case, the user record in the mysql.users table didn't have the full grant privileges and was causing this error.
Comment: I gave the user full grant privileges.
Answer: I had same situation. I removed that user and added it back with same privileges and the error was gone and all works now.

MySQLi plugin not loaded


Nesting DIV using JavaScript

Question: I am trying to load DIV on button click inside another DIV and on another click it should create a new DIV inside the newly created DIV. Here is my fiddle:http://jsfiddle.net/LzCW5/4/ and my code:
HTML:
Generate

    0

JavaScript:
int level=1;
function nestDiv()
{
    document.getElementById('x'+(level-1)).innerHTML="
"+level+"
";
    level++;
    if(level==5)
        //do somthing
}

I also want to perform some special operation when nesting level reaches 5. I am not so pro at JavaScript. So please tell me how can I achieve this?
Comment: http://jsfiddle.net/adeneo/LzCW5/7/
Comment: There is no `int` in javascript, only `var` and `const`, so using `int` is a syntax error
Comment: awesome @adeneo. Please add the code as your answer.
Comment: Nah, someone will steal it any minute now and post it, or post something better. If not, you can post it and accept the answer yourself.
Comment: Nice one @adeneo I followed different approach though
Comment: @adeneo can you tell me how using `var` instead of `int` effected the output so much?
Comment: @adeneo oh sorry about that. As I am not so pro in JS. Well thanks for this tip. :)
Answer: Here's how to append a div in jQuery:
var newDiv = $("
"+level+"
");
$('#x'+(level-1)).append(newDiv);

This should replace your document.getElementById... line
Comment: Thanks @Nicolas78. +1 to you but I marked answer by NEOLPAR, as the solutions given by adeneo and NEOLPAR are in pure JS. :)
Answer: My understanding as per your question:
When you click a button, add a div to another div.
Now when the user clicks another button, new div must be added in the previously created new div.

so let's break it down:
$("button").click(function() {
    if($("#referenceDivId").children().length == 0) {
        // if there are no children initially
        $("#referenceDivId").append("
New div
");
    } else if($("#referenceDivId").children().length == 5) {
        // do your magic when children divs are 5
    }
    else {
        // if it already had children
        $("#referenceDivId").find("div:last").append("
New div
");
    }
});

DEMO
Comment: Thanks @mohamedrias. +1 to you but I marked the answer by NEOLPAR, as the solutions given by adeneo and NEOLPAR are in pure JS. :)
Answer: In your code you only have to change int to var and call the function as a variable:
var level=1;
nestDiv = function()
{
    document.getElementById('x'+(level-1)).innerHTML="
"+level+"
";
    level++;
}

You can see this working here
Comment: Of course, you can see parseInt function here. http://www.w3schools.com/jsref/jsref_parseint.asp
Comment: Thanks for pure JS solution. But can you tell me how using `var` instead of `int` effected the output so much?

Nesting DIV using JavaScript


Option map() returns a reference to data owned by the current function

Question: I want to do something like this:
struct Foo {
    pub name: String,
}

fn is_empty(s: &str) -> bool {
    s.len() == 0
}

fn main() {
    let entity = Some(Foo { name: "some-name".to_string() });

    let name: &str = entity
        .map(|it| it.name.as_ref())
        .unwrap_or( "onother-name");

    println!("is it empty: {}", is_empty(name));
}

but it compiles with error: "returns a reference to data owned by the current function". How can I fix it elegantly? Make a copy of string and use String instead &str seems to me non optimal. Thanks
Answer: Option::map consumes the Option. You should call .as_ref() on the Option first to get Option<&T> and then call .map on it:
struct Foo {
    name: String,
}

fn is_empty(s: &str) -> bool {
    s.len() == 0
}

fn main() {
    let entity = Some(Foo {
        name: "some-name".to_string(),
    });

    let name: &str = entity
        .as_ref()
        .map(|it| it.name.as_ref())
        .unwrap_or("onother-name");

    println!("is it empty: {}", is_empty(name));
}

Playground


jQuery not detected in Play Framework application

Question: I'm not able to use jQuery/jQuery UI on my Play Framework application. I have included all the necessary stylesheets and js files. The page loads properly but Firebug error console shows Jquery Undefined. I cannot understand what's wrong here. Any ideas?
Comment: Impossible to answer without seeing some specifics
Answer: Actually looks like a syntax error.
Are you using this syntax ?
$(function() {
    // Code
});

Plus if you try to include a file in play that does not exist if there is an error, play will display an error and not launch application. Makes me think, you are using jQuery the wrong way.
Checkout jQuery documentation and make sure, this is not a jQuery related issue.
Comment: Thanks for responding. I got it working. I guess it was some conflict happening while using play.
Comment: That is not possible. As Play is a server side framework there cannot be any conflict with Javascript libraries
Answer: You need to include your jQuery- and jQueryUI-files on your page. How does your


Not able to upload file using HttpClient POST request

Question: I have a JSP page(/Test/faces/pages/admin/csvImport.jsp) which has a form and a input file type File uploader. On clicking on Upload button the form gets submitted to self URL /Test/faces/pages/admin/csvImport.jsp and the files gets uploaded. I want to automate this file upload, and hence I am using HttpClient API to pick up the file and submit the form. I am trying upload a CSV file by POST request using HttpClient APIs but somehow the file is not getting uploaded. Here is the code snippet which does the upload:
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

        HttpPost httpPost = new HttpPost("http://localhost:9088/Test/faces/pages/admin/csvImport.jsp");
        httpPost.setHeader("Cookie", "JSESSIONID="+ sessionId);
        String boundary = "---------------------------" + System.currentTimeMillis();

        httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary);

        File file = new File("C:\\root\\projects\\DataSources1.csv");
        FileBody fileBody = new FileBody(file);
        StringBody importBody = new StringBody("Import", ContentType.TEXT_PLAIN);
        StringBody csvImportFormBody = new StringBody("csvImportForm", ContentType.TEXT_PLAIN);
        StringBody uniqueTokenBody = new StringBody("j911", ContentType.TEXT_PLAIN);
        StringBody uniqueViewBody = new StringBody("j911", ContentType.TEXT_PLAIN);

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.setBoundary(boundary);
        multipartEntity.addPart("uploadFileName", fileBody);
        multipartEntity.addPart("csvimportForm:ImportButton", importBody);
        multipartEntity.addPart("csvImportForm", csvImportFormBody);
        multipartEntity.addPart("uniqueToken", uniqueTokenBody);
        multipartEntity.addPart("uniqueView", uniqueViewBody);

        httpPost.setEntity(multipartEntity.build());
        HttpResponse response = httpClient.execute(httpPost,localContext);

The original HTML form which I want to simulate in java code is:
<form id="csvImportForm" method="post" action="/Test/faces/pages/admin/csvImport.jsp" enctype="multipart/form-data">

             File Name:

             <input type="file" name="uploadFileName" style="width: 90%">

             <input type="submit" value="Import" name="csvImportForm:importButton" id="csvImportForm:importButton" onclick="javascript:hideForm();" class="commandExButton" />

    <input type="hidden" name="csvImportForm" value="csvImportForm" /><input type="hidden" name="csvImportForm:_idcl" /><input type="hidden" name="clickedLogoutLink" />
</form>

Can anyone give any hints why the file is not getting uploaded? When I execute the code, it just fetches the jsp page and does not upload the file.
UPDATE after comparing the HEADERS and POST PARAMETERS:
Compared both the headers and parameters.
With the FORM it is:
Request               POST /Test/faces/pages/admin/csvImport.jsp HTTP/1.1
Accept  */*
Referer                https://host1:30862/Test/faces/pages/admin/csvImport.jsp
Accept-Language             en-GB
User-Agent         Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Content-Type    multipart/form-data; boundary=---------------------------7e0212b90428
Accept-Encoding              gzip, deflate
Host       host1:30862
Content-Length                2398
DNT       1
Connection        Keep-Alive
Cache-Control   no-cache
Cookie  ssoLang=en; dbihybrid_preferredLanguage=en; dbihybrid_locationDepartment=in.false; wt_eid=2143773288100110717; JSESSIONID=W9vmLJRZkf7u2Pevmd4QdSC2hUvliVepaVm-tFuz9m7O4lkWYPUw!1008091679; PA.MinLogLevel=30

AND with HTTPClient it is:
Cookie: JSESSIONID=9C_m5OE8QUquA9sdj4T5eOyVS1yXC6yb0jdiVCuaZ_X-MjPQqEMw!1008091679
Content-Type: multipart/form-data; boundary=---------------------------1459867674444
Accept-Language: en-US,en;q=0.5
Accept: */*
Cache-Control: no-cache
Referrer: https://host1:30862/Test/faces/pages/admin/csvImport.jsp
Content-Length: 2423
Host: host1:30862
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.1 (java 1.5)
Accept-Encoding: gzip,deflate

The POST parameters with FORM:
Content-Disposition: form-data; name="csvImportForm" value="csvImportForm"
Content-Disposition: form-data; name="uniqueToken" value=""
Content-Disposition: form-data; name="uniqueView" value="j1154"
Content-Disposition: form-data; name="csvImportForm:importStatus" value=""
Content-Disposition: form-data; name="clipboard_l" value=""
Content-Disposition: form-data; name="clipboard_t" value=""
Content-Disposition: form-data; name="uploadFileName"; filename="C:\Users\Public\Documents\eclipse luna\workspace\WebScraper\properties\DataSources.csv" Content-Type: application/vnd.ms-excel
Content-Disposition: form-data; name="csvImportForm:importButton" value="Import"
Content-Disposition: form-data; name="javax.faces.ViewState" value="3514046226787645214:-6068281828613739341"

The POST parameters with HttpClient:
Content-Disposition: form-data; name="uploadFileName"; filename="C:\Users\Public\Documents\eclipse luna\workspace\WebScraper\properties\DataSources.csv" Content-Type: application/vnd.ms-excel; charset=UTF-8
Content-Disposition: form-data; name="csvImportForm:importButton" value="Import"
Content-Disposition: form-data; name="csvImportForm" value="csvImportForm"
Content-Disposition: form-data; name="uniqueToken" value="j1228"
Content-Disposition: form-data; name="uniqueView" value="j1228"
Content-Disposition: form-data; name="javax.faces.ViewState" value="8959970480121731339:-7418251671370896640"
Content-Disposition: form-data; name="clipboard_l" value=""
Content-Disposition: form-data; name="clipboard_t" value=""
Content-Disposition: form-data; name="csvImportForm:importStatus" value=""

Comment: In browser while submitting use the developer tools to see the http post. In your application use a proxy (e.g.TCP/IP monitor in views in eclipse) to see the message being sent. Compare both and you will have your answer.
Comment: I did the comparison, and I have added the results as an update above. No clue whatsoever, why its not working.
Comment: Why is the content length different? Please try to compare post data also. Is this page secured?
Comment: I referred http://stackoverflow.com/questions/8623870/how-can-i-programmatically-upload-a-file-to-a-website/8625286#8625286 and found that one POST parameter was wrongly named. After correcting the error, it started working in HTTP. But when I put the same code on HTTPS, it is still not submitting the form. I have added an additional hidden parameter javax.faces.ViewState. Is there something special we need to do when dealing with HTTPS?
Comment: I have added headers for POST parameters for Secure call in the post. @sashwat, do you have any hints. The difference in length was because I was trying to upload different files. For HTTPS, the length is almost same.
Answer: Not sure it is the problem in your case, but MultipartEntityBuilder handles the Content-Type header and boundary internally so you do not have to set them explicitly. That is, you can safely remove the following lines
    String boundary = "---------------------------" + System.currentTimeMillis();

    httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary);

otherwise they might conflict each other.
Since you are just setting boundary to something random, you can just let MultipartEntityBuilder do it for you. This is the default behavior if you to not provide a boundary. And you can therefor also remove
    multipartEntity.setBoundary(boundary);

Comment: I removed it but that did not help. thanks for the response.


Every positive integer $n$ has at least as many divisors of the form $4k + 1$ as divisors of the form $4k + 3$

Question: Provided that $n$ is a positive integer, how do we prove it has at least as many divisors of the form $4k+1$ as divisors of the form $4k+3$, where $k\in\mathbb{N}$? What I've tried is assuming that the statement holds for some $m$ and then proving it holds for all $mp$, where $p$ is prime. This doesn't seem to get us far, since it's hard to relate divisors of $m$ with $mp$. Also, note that if we take the product of two numbers of the form $4k + 1$ or two numbers of the form $4k+3$, we get a number of the form $4k + 1$, and if we take the product of a number of the form $4k+1$ and a number of the form $4k+3$, we get a number of the form $4k+3$. I think this fact may be useful.
Comment: Let $\chi(d)$ be the function that takes the value $0$ if $d$ is even, takes the value $1$ if $d$ is of the form $4k+1$, and takes the value $-1$ if $d$ is of the form $4k+3$. Then $\sum_{d\mid n} \chi(d)$ is directly relevant to your question. Can you show that $\chi$ is multiplicative and hence this sum is a multiplicative function of $n$? That should reduce the problem to showing it for prime powers.
Comment: Hint:  Suppose $n=m\times k$ with $1<m,k$ and $\gcd(m,k)=1$.  If the claim is true for $m,k$, can you deduce it for $n$?
Comment: Another strategy can be considering the "extreme case" n=p^k where p is a prime of the form 4k+3 and showing that the claim is true
Comment: Or, do it directly: suppose it has $A$ primes of the form $4k+1$ and $B$ primes of the form $4k+3$, and $C$ primes of the form $2$. How many divisors are of the form $4k+1$? $4k+3$?
Comment: Just shooting here.  Lets suppos $n = 2^w\prod q_i^{n_i}\prod p_j^{m_j}$ is the prime factorization were $q$ are primes of the form $4k+1$ and $p$ are primes of the form $4k+3$. The factors of the form $4k+3$ are $\{\prod q_i^{a_i}\prod p_j^{s_j}|a_i\le n_i; s_ji\le m_j\sum s_i$ is odd$\}$ and the factors of the form $4k+1$ are $\{\prod q_i^{a_i}\prod p_j^{s_j}|a_i\le n_i; s_ji\le m_j\sum s_i$ is even$\}$.  You can put this in counting order.  As every odd sum is preceded immediately by an even sum the result should follow.
Comment: @fleablood It's a bit trickier than just a simple comparison (which is my interpretation of "put this in counting order"). It eventually boils down to $ \sum { M \choose 2s } \geq \sum { M \choose 2s+1 } $, where $ M = \sum m_j$. $\quad$ Note that the exact values of $p_j$ do not matter, which is why I phrased my comment as just $A / B / C$.
Comment: I am having trouble finding that $253=11*23$ has as many divisors of the two forms.
Comment: @CalvinLin essentially for every $Qp_m^{2a_m+1}$ of the form $4k+3$ then $Qp_m^{2a_m}$ is of form $4k+1$.  The trouble of course could be that $Qp_n^{2a_n+}p_m^{2a_m}\ne Qp_n^{2a_n}p_m^{2a_m+1}$ would be two factors of the form $4k+3$ and my reducing algorithm would result in the same $Qp_n^{2a_n}p_m^{2a_m}$.  I figure we can somehow put these divisors in order of there primes and only reserve the higher primes to odd powers for when we need them.  That's what I meant by "counting order".  .....
Comment: ... "counting order" cont. If we consider the divisor $p_1^{a_1}p_2^{a_2}.....p_m^{a_m}p_{m+1}^{a_{m+1}}....$ where $a_m$ is the *last* odd power then we map it to the divisor $p_1^{a_1}p_2^{a_2}.....p_m^{a_m-1}$. Hmm... but then we have ambiguity if $a_m=1$ *and* $a_{m-1}$ is even *and* $p_m$ is of form $4k+3$. So I'll some cleverer counting algorithm. I'm sure of two things.  1) it can be done and ii) I'm too lazy to do it.
Answer: Let's prove the following statement: if a positive integer $n$ has a prime of the form $4k+3$ in the odd power in its prime factorization then $n$ has as many divisors of the form $4k+1$ as of the form $4k+3$, otherwise $n$ has more divisors of the form $4k+1$ than of the form $4k+3$.
Consider prime decomposition of the number $n$. The primes fall into three categories: of the from $4k+1$, of the form $4k+3$, number $2$ (not all of them can be present for a given $n$, of course). The third category is completely irrelevant for our problem since if a divisor contains a factor $2^i$ it is not of the form $4k+1$ or $4k+3$. So we assume that $n$ is odd.
Let $n$ have a factor $q^b$ in its prime factorization where $q$ is a prime of the form $4k+3$ and $b$ is odd. Then let us build a bijection between all the divisors of $n$ of the form $4k+1$ and of the form $4k+3$. Any divisor of $n$ that contains $q^i$ where $i$ is even will be corresponded to a divisor containing $q^{i+1}$. (Note that $i+1\leq b$ since $b$ is odd.) All the divisors are split into pairs where one divisor is of the form $4k+1$ and another is of the form $4k+3$. Hence their quantities are equal.
If all the divisors of $n$ of the form $4k+3$ are raised to even powers then the following procedure can be applied. Let $q_1, q_2, …, q_m$ be all the prime divisors of the form $4k+3$. We can split almost all divisors of $n$ the same way as in the previous paragraph with respect to $q_1$ except the divisors containing $q_1$ raised to the maximum power. We will try to split these divisors with respect to $q_2$ the same way. We will get that all the divisors split in pairs except a group of divisors containing all $q_i$ raised to their maximum powers. These powers are all even. So these numbers are all of the form $4k+1$. And there is at least one of them. This finishes the proof.
——————————————————————
Note $1.$ "a positive integer $n$ has a prime of the form $4k+3$ in the odd power in its prime factorization" is the same condition as "$n$ can't be presented as a sum of two squares of integer numbers".
Note $2.$ Another way of proof also comes to mind. I will sketch it here. Let $n$ be odd. If $n$ is of the form $4k+3$ then all its divisors are split into pairs $(a,b)$ where $ab=n$ ($a\neq b$ since $4k+3$ is never a square). In each pair one of the divisors is of the form $4k+1$ and another is of the form $4k+3$.
If $n$ is of the form $4k+1$ and it has $q^b$ in its prime factorization where $q$ is of the form $4k+3$ and $b$ is odd then $n/q^b$ is of the form $4k+3$ and previous method of splitting into pairs works. Multiplying by $q^i, i\leq b$ doesn't change anything.
Finally, if $n$ is of the form $4k+1$ and all the primes of the form $4k+3$ in its factorization are raised to an even power then one can show that quantity of the divisors of the form $4k+1$ is greater.


Executar uma Paginação PHP com JQuery

Question: Fiz um script que importa imagens de um CMS próprio para o Wordpress e para não sobrecarregar o servidor e a maquina de importação esse sistema tem uma paginação que exibe 20 elementos por página:
http://localhost/sistema_importa/base_importat.php?pagina=160
Gostaria de saber se teria uma maneira de o jquery executar essa página e ao fim do carregamento dela o jquery mudar para a próxima página evitando que eu tenha que ta clicando em próximo direto e tornar o processo pouco mais rápido:
http://localhost/sistema_importa/base_importat.php?pagina=161
Answer: Você pode usar o evento .scroll() no seu window, mais ou menos assim:
$(window).scroll(function() {
   if( $(window).scrollTop() + $(window).height() == $(document).height() ) {
       var url = document.URL;
       var pageNumber = url.split('=')[1];
       var newUrl = "http://localhost/sistema_importa/base_importat.php?pagina=" + pageNumber;

       $(location).attr('href', newUrl);
   }
});

Se você quer que a página seja recarregada quando o usuário chegar perto do final, use isso aqui:
$(window).scroll(function() {
   if( $(window).scrollTop() + $(window).height() > $(document).height() - 100 ) {
       var url = document.URL;
       var pageNumber = url.split('=')[1] + 1;
       var newUrl = "http://localhost/sistema_importa/base_importat.php?pagina=" + pageNumber;

       $(location).attr('href', newUrl);
   }
});

* Onde o 100 da condição representa o tamanho em pixels em relação ao final da página, você pode mudar pro número que desejar.
Mas eu não recomendo essa solução, aconselho você a utilizar algum plugin de Infinite Scroll/Lazy Loading.
Comment: Muito obrigado @eduardo-silva Modifiquei sua ideia

``

Executar uma Paginação PHP com JQuery


Horizontally centering two stacked divs, when one has a vertical scrollbar

Question: Centering elements horizontally is easy using margin: 0 auto;
However, it doesn't work if there are two elements stacked in a column and one has a scrollbar and the other does not. In that case, the two horizontal centered elements aren't aligned anymore.
Question: Is there any way to align the two elements without using Javascript to adjust the margin of the first one?
JSFIDDLE DEMO

Comment: Why not just do it like this? https://jsfiddle.net/904umrhy/2/
Comment: Scrollbar widths are OS / browser dependent, so your solution works for your browser, but [doesn't correctly align for me](http://i.imgur.com/wvuKxSc.png). It's even more an issue for OS X users, because scrollbars are overlays there.
Comment: So why not use Javascript then? You don't need full JQuery libraries, just simple javascript.
Comment: Javascript is just a workaround, no solution. It's the last thing I want to use, before I'd switch to a fixed header probably. As pointed out by Wes in chat, it's entirely possible with CSS only. I posted it as answer, because he's too lazy.
Comment: Considering your answer is not centered, I feel that your answer is also no a solution, see fiddle https://jsfiddle.net/904umrhy/5/
Answer: The main problem is obviously the centering. So why not circumvent it and use margin-left?
Try this CSS:
.inner { margin-left: calc(50vw - 150px); }  /* half viewport width less half element width
                                                (for precise centering) */

body {
  margin: 0;
  height: 100vh;
}

.header {
  height: 50px;
  background: red;
}

.content {
  background: blue;
  overflow-y: scroll;
}

.inner {
  background: rgba(255,255,255,.5);
  max-width: 300px;
  /* margin: 0 auto;                   <-- remove */
  margin-left: calc(50vw - 150px);     /* new */
  min-height: 50px;
}

.content > .inner {
  min-height: 300px;
}

Revised Fiddle
Answer: Answer from Wes in chat:
This can be solved by adding a scrollbar to the first one, but hiding it from the user.
.header {
  height: 50px;
  background: red;
  overflow-y: scroll;
  width: 120%;
  margin-left: -10%;
}

JSFIDDLE DEMO
If you're concerned a user could have a scrollbar wider than 10%, increase it width: 300% and margin-left: -100%. If somebody has a scrollbar as wide as the page, he / she can't use the page anyway.
Comment: This is not centered see example. https://jsfiddle.net/904umrhy/5/ its aligned but not centered.
Comment: @AdamBuchananSmith It's not centered to the viewport, but the lower white box is centered in its parent and the other upper white box is correctly aligned.


WPF: Kill Windows GUI (explorer.exe) and then restore it

Question: What I want to do is to kill the explorer.exe main process (which will result in killing the Windows gui programatically and then open the gui again. I can achieve that by manually killing and then starting the process through taskmanager, but I can't figure out how to do kill the main explorer process from a wpf visual C# program. Also, I tried killing it from taskmanager and then starting the windows gui again by:
var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "explorer.exe",
                    Arguments = "",
                    UseShellExecute = true,
                    CreateNoWindow = true
                }
            };
            proc.Start();

but it only starts a new explorer window, not the windows gui. Can someone help me to kill the win gui and start it again with some code, please?
Comment: Why do you want to do this? It's somewhat user-hostile, and I wouldn't be happy using an app that did this. BTW what do you mean by "windows gui" - open explorer windows? The taskbar?
Comment: Users of Windows from time to time could have reason to programatically "kill windows gui", was happening all the time with bug-rich games. I never thought to automatize it for myself, pitty.
Comment: @stuartd this app's main aim is to do that
Answer: You can get processes by name using:
var explorerProcesses = Process.GetProcessesByName("explorer");

Then you can loop through and kill them all:
foreach(var process in explorerProcesses)
{
    process.Kill()
}

Your program may need to be running as Administrator to kill explorer, I'm not certain.
Comment: You were right the first time, you use the process friendly name which is `explorer`, not `explorer.exe`: `var explorerProcesses = Process.GetProcessesByName("explorer");`
Comment: woops, my bad, sorry!
Comment: Thanks! But how about restoring the GUI? Starting explorer.exe with the code I gave in the first post only opens Windows explorer and the GUI (taskbar) still doesn't show up...
Comment: But now I see that it only restarts the gui. But I've found a solution to this already... thanks anyway
Answer: I finally managed to find out the solution: killing the explorer.exe by getting the process and using Kill() only restarted the gui. To completely shut it down, use
        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "taskkill.exe",
                Arguments = "/F /IM explorer.exe",
                UseShellExecute = true,
                CreateNoWindow = true
            }
        };
        proc.Start();


Oblique projection matrix - proof definition is correct.

Question: The oblique projection matrix on $\text{range}(X)$ orthogonal to $\text{range}(Y)$ is given by $P = X (Y^\top X)^\dagger Y^\top$.
Prove that the above definition is right, i.e. it holds that
$Xw^\star = Py$ where $w^\star = \text{argmin}_{w: (Xw - y)^\top Y = 0} \|Xw - y\|_2$.
Edit: originally, the formula above erroneously had a min instead of an argmin.
I do recognize this has the feel of very standard material, but for some reason I can't find it. It's OK if you could just name a reference. I don't know if this makes a huge difference, but I need the case where the matrix $Y^\top X$ need not be invertible (hence the pseudo-inverse).

Ok, I do accept that calling the matrix $P$ an oblique projection requires that $\text{range}(X)$ and $\text{range}(Y)^\perp$ are complementary subspaces. Even given this, $Y^\top X$ may still not be invertible (consider $X=Y$ and $X$ has linearly dependent columns).
Also, if we forget the geometry, it is still a legitimate question to ask, in terms of pure algebra, if $Xw^\star = Py$ for the given definition of $w^\star$, for any matrices $X$, $Y$.
I am interested in this case because the question comes from an application where the matrices involved are estimated from samples and the task is to show that even when the inverse doesn't exist, the formula $X (Y^\top X)^\dagger Y^\top$ still solves the optimization as mentioned above.

I have realized that the optimization given above may not be the obvious way to ask the question - the solution $X w^\star$ is already defined by just the fact that $(Xw^\star - y)^\top Y$ has to vanish, even without any optimization.
Now, I'm trying to prove the following things suggested by Marc van Leeuwen below.

$Pw = w$ for $w \in \text{range}(X)$. This is equivalent to saying $\forall b. PXb = Xb$, or $X(Y^\top X)^\dagger (X^\top Y) = X$. But where do I go from here? I can't just cancel the terms because $(Y^\top X)^\dagger (X^\top Y)$ isn't necessarily the identity.
$Pw=0$ for $w \perp \text{range}(Y)$. This is obvious since $Y^\top w = 0$.

Also, I don't see how 1 and 2 should imply the result.
Answer: The oblique projection only exists if $\operatorname{range}(X)$ and $\operatorname{range}(Y)^\perp$ are complementary subspaces, so that must be part of the assumptions. Now it suffices to show that $Pw=w$ for $w\in\operatorname{range}(X)$ and $Pw=0$ for $w\perp\operatorname{range}(Y)$; both of these should be doable.


Como o PDO lida de maneira mais performática

Question: Finalidade:
Selecionar uma única linha com LIMIT 1
Uso Interno:
Os selects recebem só parâmetros internos
Não precisa de PREPARE pois não há dados externos de usuários
$pdo = new PDO("mysql:host=A.com;dbname=B; charset=utf8", "C", "PW");

exemplo 1:
$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1");
foreach($con as $row) {
echo $row['id'].' - '.$row['titulo'];
}

Exemplo 2:
$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1");
$con->execute();
$sel=$con->fetch();
echo $sel['id'].' - '.$sel['titulo'];

Exemplo 3:
$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1")->fetch();
echo $con['id'].' - '.$con['titulo'];

A linha selecionada contém 80 colunas (com ou sem dados)
Os 3 funcionam OK, mas tenho dúvidas de qual usar.
Se houver uma outra forma, mais reduzida ou mais rápida.
Comment: Se retorna apenas um registro, não vejo motivos para usar o `foreach`, descartando o exemplo 1. Entre os exemplos 2 e 3, a única diferença que vi foi o `execute`, porém como funciona sem no exemplo 3, ele realmente é necessário no exemplo 2? Se não for, os exemplos serão iguais.
Comment: Eu diria para você medir a performance de cada uma das 3 maneiras. Não tenho base sobre PHP/PDO para falar com propriedade, mas você poderia testar em uma massa significativa de dados para ver o quão performático é cada uma. Repete algumas centenas de vezes, tira a média e o desvio padrão e usa o que você achar melhor (normalmente menor média e com menor desvio)
Comment: Não tem mudanças a nível de MySQL, apenas de PHP. Note inclusive que o SQL passado para o SGBD é o mesmo. A pergunta então se torna "como o PDO lida de maneira mais performática".
Comment: Vc recomenda alterar o texto da pergunta? A sua é mais objetiva? estou aprendendo a usar o Stack, agradeço a atenção
Comment: Falei mais para você mesmo perceber qual o foco da questão. Nem tanto sobre o uso do site, mas sim para que você tenha a ideia correta do que esteja acontecendo. O mundo fica muito mais fácil e direto quanto se sabe com o quê estamos lidando. Sobre o uso do StackOverflow, já vi textos melhores. Eu recomendo editar o título, já que não há real diferença entre `select`s, mas em recuperar os dados no PHP, mas também não tenho uma sugestão de título melhor. O que mais me incomodava que era a tag eu já substituí
Comment: @Geo A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Se a performance é relevante para sua aplicação use uma linguagem compilada de tipagem estática e de preferência que utilize a filosofia de abstração de custo zero. Tipo C, C++, Rust, eventualmente C#, Kotlin, Java, D, Go, Swift. Não utilize uma linguagem de script. Para PHP a performance é irrelevante.
O maior custo aí, e com larga margem de diferença, provavelmente algumas ordens de magnitude, é a consulta ao banco de dados, então se precisa de melhor performance pense em estratégia de cache ou rearquitetar a aplicação, os ganhos costumam vir mais do design do que detalhes no código.
Se ainda quer algum ganho de execução saia do PDO. Quase ninguém precisa dele e ele custa bem mais caro que o acesso direto ao cliente do banco de dados.
Dito tudo isso, o terceiro é mais simples, direto e até por executar diretamente menos coisas provavelmente é o mais rápido (não será fácil medir a diferença de performance). Digo provavelmente porque só conhecendo a implementação do PDO para saber, mas só usei a palavra para não parecer que o simples fato de ter um comando a menos já faz tudo ser mais rápido, pode ser que a falta dele gere outras consequências que torne mais lento, mas nesse caso é altamente improvável, e se acontecer fuja do PDO.
Então algo assim seria melhor:
$dados = $mysql->query("SELECT id, titulo FROM cursos WHERE cod = 1")->fetch();
echo $dados['id'] . ' - ' . $dados['titulo'];

Coloquei no GitHub para referência futura.
Mas dependendo de onde for usar pode haver ganhos fazendo de outra forma. Não se pode analisar performance sem contexto.
Tem como melhorar mais fazendo algo totalmente diferente disto, mas só no caso concreto com muita informação disponível dá para saber o que.
E funcionar é diferente de estar certo. Não que isto esteja errado, não tenho como afirmar sem contexto, mas fica o alerta.
Comment: Vou mudar meu apelido para "Esponja", porque qualquer tempinho sempre fico absorvendo conteúdo ! Merece ênfase: "Se ainda quer algum ganho de execução saia do PDO. Quase ninguém precisa dele e ele custa bem mais caro que o acesso direto ao cliente do banco de dados."
Comment: Gostei da sua sugestão e testei. Mas o resultado não parece. A conexão está OK. Será que cometi algum erro? $mysql = new mysqli('h','A','pw','B') or die ("Falha");
if (!$mysql){echo'Erro'.mysqli_error();exit;}else{echo'Conectado';}
$dados = $mysql->query("SELECT id,titulo FROM cursos where cod=1")->fetch();echo $dados['id'] . ' - ' . $dados['titulo'];
Comment: Aí já é outro problema, faça outra pergunta com bastante detalhes sobre ele.
Comment: Ok, (não há mais o que detalhar, está tudo no comentário acima) Agradeço a explanação e analogia com carros. Para mim: Ferrari = Performance com qualidade. Obrigado.
Comment: @Geo Sem execute não vai funcionar.
Comment: [Fazendo par com o 147](https://www.youtube.com/watch?v=8ZwkbD2IHKQ) :D


How can the F statistic of my anova test be greater than 1?

Question: I've been digging into the formula for one way ANOVA test and I understand the we obtain the results from the ANOVA analysis with:
Group Sum of Squares/Total Sum of Squares

To see how much variance is explained. However, I also read that:
Total Sum of Squares = Error Sum of Squares + Group Sum of Squares
In that case, how could an F statistic be greater than 1? Shouldn't it always be a fraction of 1?
Answer: The F is not GroupSS/TotalSS.
If it were you'd be right that it shouldn't exceed 1 ... but it isn't. You should re-read your sources (and preferably find several different sources).
In ordinary one-way ANOVA the overall F is the group mean square over the error mean square. Each mean square is the relevant sum of squares divided by the corresponding degrees of freedom.
If there's no group effects (they're all one population) then the F should be typically close to 1 (the numerator and denominator mean squares should both be unbiased estimates of $\sigma^2_\text{error}$). When there are group effects the expected group mean square includes a term related to the variation in group-means.
As a result (since there's usually at least some group effect), the F is typically greater than 1.
Comment: +1 A while back I went through the manual process of getting F [here](http://rinterested.github.io/statistics/anova_interpretation.html). It could possibly be of help provided R is not a barrier.


AspNetMx Emaild Validation with c# asp.net

Question: I am trying the aspNetMx API. I would like to know the following figures.
Checking the email is valid or invalid.

If email is valid (means domain is valid and user also exists) => flag as valid (eg. X)
If email is invalid, => flag as invalid (eg. Y)
2.1. which is due to bad email syntax (eg. Y1)
2.2. which is due to bad email domain (eg. Y2)
2.3 which is due to bad mailbox (eg. Y3)

The following are different levels that aspNetMX validates the email addresses.
MXValidateLevel.NotValid

MXValidateLevel.Syntax

MXValidateLevel.MXRecords

MXValidateLevel.GreyListed

MXValidateLevel.SMTP

MXValidateLevel.Mailbox

Regards,
Answer: You should check the docs online : Taken from http://www.aspnetmx.com/help/index.htm
MXValidate mx = new MXValidate();

string email = "email@example.com";
MXValidateLevel level = mx.Validate( email, MXValidateLevel.Mailbox );

switch( level )
{
case MXValidateLevel.NotValid:
//bad email address, remove from email address list
break;

case MXValidateLevel.Syntax:
//the email address is syntactically correct
break;

case MXValidateLevel.MXRecords:
//mx records were found, but for some reason
//the SMTP server couldn't be found
//save email for checking later, and see if SMTP servers fail again
break;

case MXValidateLevel.SMTP:
//able to connect to the mail server
//but mail server said email address was bad
//remove from list
break;

case MXValidateLevel.Greylisted:
//able to connect to the mail server
//but mail server said email address was greylisted
//for a later time.
//try back later
break;

case MXValidateLevel.Mailbox:
//the email address validated to the mail box `enter code here`level
//and the mail server will accept email for that address
break;
}

Comment: From Docs - "When Validate() is executed, it attempts to validate an email address UP TO the level that was specified. If the validation was successful, it returns that level. If the validation was NOT successful, it returns the last highest level of validation that was found. This allows you to vary actions, based upon the level of validation returned."
Comment: Thanks. I found the docs but I don't know how to flag as valid or invalid.


Window title bar disappears - how to find culprit?

Question: I am having a problem on some PCs where the window title bar disappears, then network drive connections get broken and various error messages concerning inadequate resources appear.
Yet Proc Explorer shows nothing untoward and plenty available memory and cpu.
How do I go about finding which app might be causing this?
Comment: Is this on XP? You may need to increase your desktop heap allocation.
Answer: This sounds like an application is leaking resources. Even good old task manager can help you see if that's the case:
Go to the Processes tab. View menu -> Select Columns.
Some columns to watch for abnormal values are Handle Cound, Thread Count (not very common) and GDI Objects.
An application leaking handles or GDI Objects could very well cause what's happening.
A combination could also empty the nonpaged pool of kernel memory, causing inadequate resources.
Comment: What would abnormal values be?  I have some apps using 800+ GDI objects, some using 1800 handles and some with 50 threads.
I thought I had found something - there were 67,000 files all named sxp????.tmp in my local settings\temp directory, all of zero bytes size. I deleted them all but still have the problem.
Comment: None of those seem exceptionally high I'm afraid.
What do the event logs say, if anything?
Comment: Turns out an issue with our Visual Source Safe database was causing the problem. Everytime someone opened Visual Studio things would start to go weird.  But we found this through trial and error....
Answer: I haven't seen a PC experience this since Windows 98!  Using Process Explorer, try to find an application that is causing a large number of virtual memory page faults (having to read memory from disk).
Is the machine running out of phyiscal memory? (Start->Run->Taskmgr, at the bottom of the process window, is the first number of 'commit charge' larger than how much memory the machine has?
alt text http://imagebin.ca/img/lJIi09Ch.jpg
Answer: How many PC's does this happen on verses how many do you have? have you had updates recently that only went on these pc's? could be a virus, do you have up to date anti virus? have you done a full scan?
To be honest I would just re-image the affected machines as you can't trust windows when things like this happen and who has the time these days.
Stuart


How to find exact substring inside a string using javascript

Question: var str = "Hello World +1 new test Good Morning";
var subStr = "+1 new test";

I want the code snippet to return true only when entire phrase i.e. "+1 new test" is found in the string str. I have tried regEx and match,search,test options. But, none are working for me. It shows error for the '+'.
Below is what I am using -
    var HVal = "Hello World +1 Good"
    var HValNew = HVal.toString().toUpperCase();
    var probStr = "Hello World";
    var test = probStr.toUpperCase();
    var re = new RegExp('\\b'+test+'\\b');
    re.test(HValNew);

This works when probStr is a string containing alphanumeric characters but fails when it has special characters e.g. "+", "?"
I found my answer to match exact phrase
        var str = "Hello World +1 new test Good Morning".toString().toUpperCase();
        var subStr = "+1 new test".toString().toUpperCase();
        escapeSpecialChars = function(string) {return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, 'x')};
        var probStr = escapeSpecialChars(subStr);
        var strNew = escapeSpecialChars(str);
        var re = new RegExp("\\b"+probStr+"\\b");
        re.test(strNew);

This return true when subStr = "+1 new test" and false when subStr = ""+1 new te" (i.e. in case of partial phrase).
Comment: `str.indexOf(subStr) > -1`
Comment: `+` has a special meaning in regexp you need to escape that using `\+`
Comment: I'd suggest just taking a glance at the documentation for [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), and learning those methods, which will help you solve this problem and many more that you will encounter in the future.
Comment: IndexOf is giving result as true for partial substring too
Answer: Use includes() function in ES6, and indexOf() in ES5
includes - will return true if the subStr is in the str.
indexOf - will return -1 if no match found, and a if the subStr was found, will return the index, from where the subStr starts.
Examples

var str = "Hello World +1 new test Good Morning";
var subStr = "+1 new test";

console.log(str.includes(subStr)); // ES6

console.log(str.indexOf(subStr) !== -1); // ES5
Comment: @Rajesh yes of course
Comment: This is not a duplicate question @Rajesh. My question is to match exact phrase. indexOf, contains, search etc. were not answering my questions
Comment: @aks **exact substring inside a string** what do you mean by this then? Also code shared is also pointing to it. If you think its not duplicate, please share both correct case and incorrect case. That would clarify your requirement.
Answer: You can use includes

var str = "Hello World +1 new test Good Morning";
var subStr = "+1 new test";

console.log(str.includes(subStr));     // ECMAScript 6

console.log(str.includes("anything")); // ECMAScript 6
Comment: This seems to be a very basic question. Should you not mark it as duplicate instead?
Comment: @Rajesh sure :)
Answer: + is a RegEx token, meaning to match one or more of the preceding token.
You need to escape it to make the RegEx engine treat it literally:
\+1 new test

Although as others have mentioned, you should look at string manipulation rather than RegEx in this case.
Comment: This seems to be a very basic question. Should you not mark it as duplicate instead?
Answer: You don't have to use regex here.
str.indexOf(subStr) >=0

This will return true if substring found
Comment: This seems to be a very basic question. Should you not mark it as duplicate instead?
Comment: @Rajesh, yes you are right
Comment: var str = "Hello World";
var subStr = "Hell";
then, str.indexOf(subStr) returns 0;
if var subStr = "Hello"; then too str.indexOf(subStr) returns 0.
Comment: I was looking for a solution that matches entire Substring. IndexOf is not serving that purpose.
Answer: Since '+' sign is valid regex we will need to escape it using a \ like "\+ ". Here is the working example.

var str = "Hello World +1 new test Good Morning";
var subStr = "\+1 new test"
var bol = str.indexOf(subStr) > -1;
console.log(bol);
Comment: Please add explanation. Just putting working code is not enough.
Answer: The includes() method determines whether a string contains the characters of a specified string.
This method returns true if the string contains the characters, and false if not.
Note: The includes() method is case sensitive.
Example :
var str = "Hello +1 world, welcome to the universe.";
var subStr = str.includes("+1 world");

Where subStr  is equal to true


Proving Green's Theorem for Computing Area

Question: I'm having a hard time understanding where exactly the formula for computing area using Green's theorem comes from. It is typically:
\begin{equation}
  \int_C x\,dy = \int_C -y\,dx = Area
\end{equation}
Or the equation with:
\begin{equation}
  \frac{1}{2}\int_C x\,dy  -ydx= Area
\end{equation}
But I don't understand and can't seem to find anywhere where this is proven or from where it is derived. I do know that when you do a little algebraic manipulation on the first equation, you can get:
\begin{equation}
  \int_C x\,dy + y\,dx = Area
\end{equation}
And then using Green's theorem, I seem to get the partial derivative of x with respect to x and the partial derivative of y with respect to y to subtract each other, which gives me Area = 0. This is where I'm stuck. Any and all help is appreciated.
Thanks.
Comment: I don't think your third equation is consistent. If $\int_C xdy = \int_C -ydx$, then by adding $\int_C ydx$ to both sides, we get $\int_C xdy + ydx = 0$.
Answer: First, Green's theorem states that
$$
\int_C P dx+Q dy=\iint_D\left(\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}\right)dA
$$
where $C$ is positively oriented a simple closed curve in the plane, $D$ the region bounded by $C$, and $P$ and $Q$ having continuous partial derivatives in an open region containing $D$. Since the area of $D$ is simply $\iint_D 1dA$, you want to choose $P$ and $Q$ such that $\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}=1$ and then apply Green's Theorem to derive a formula for the area of $D$.
A possible choice is $P=0$, $Q=x$, which gives the formula
$$
A=\int_C x\,dy.
$$
Or you could take $P=-y$, $Q=0$, giving
$$
A=\int_C -y\,dx
$$
or finally take $P=-y/2$, $Q=x/2$, to yield
$$
A=\frac{1}{2}\int_C x\,dy  -ydx.
$$
You could derive this third one by adding the first two and dividing as well.
These are the three formulas which you provided in your question.
Comment: Thanks so much. I can't believe I didn't see that. It seems so obvious now...
Answer: As yunone' noted completely: $$\oint_C Pdx+Qdy=\iint_D\left(\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}\right)dA$$ This can be proved that the left hand side closed integral is independent of the path $C$ joining any two given points in the riegi $\mathcal{R}$ iff $$\frac{\partial Q}{\partial x}=\frac{\partial P}{\partial y}$$. It is also supposed that the partial differential above are continues on $\mathcal{R}$. In this case; $Pdx+Qdy$ is an exact differential, i.e. $\exists \phi(x,y); Pdx+Qdy=d\phi$. Now if the end points of the curve $C$ are $(x_1,y_1),(x_2,y_2)$ we have: $$\int_{(x_1,y_1)}^{(x_2,y_2)} Pdx+Qdy=\int_{(x_1,y_1)}^{(x_2,y_2)} d\phi=\phi(x_1,y_1)-\phi(x_2,y_2)=0$$ since $C$ is closed and two end points are coincided.


Updating matplotlib plot in tkinter gui via another process

Question: I have an interface that I am writing using tkinter. Inside that interface, I have a matplotlib plot. In the background, I have zmq connecting to a server to get data. I am using python's multiprocessing module with a Queue sharing data and a Process running for all of the zmq communication.
In the GUI, I can set up a button to update the plot with the following function:
def addData(self):
    if not self.data.empty():
        print "Have Data!"
        self.hist.addQueue(self.data)
        self.hist.updatePlot()
    else:
        print "No Data"

However, if I try to create another process that basically puts this inside of a while True, I get the following error:
X Error of failed request:  RenderBadPicture (invalid Picture parameter)
  Major opcode of failed request:  139 (RENDER)
  Minor opcode of failed request:  7 (RenderFreePicture)
  Picture id in failed request: 0x160000a
  Serial number of failed request:  2686
  Current serial number in output stream:  2690
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
fish: Job 1, "python clientGUI.py " terminated by signal SIGABRT (Abort)

I can't find anything about this error that seems to be related to anything that I'm doing.
I can provide other parts of my code if needed, but there's a good bit of code that I didn't want to floood the question with.
Comment: I'm not at all familiar with any of this, but there seems to be some relevant information in [this](http://stackoverflow.com/questions/22626989/multithreaded-gstreamer-w-pygtk-crashing-xcb-xlib-threads-sequence-lost) SO question, it's the same `xcb` error and may be a similar cause.
Answer:
Excuse me for not following your post-mortem trails

STEP 0: (re)-align the concept of components
motto: while debugging a mis-directed architecture is possible, the resulting efficiency is rather low compared to a better and a more straightforward design

Component Inventory:

Tkinter is a very smart framework that works around .mainloop() ( a central scheduler ) and allows for a soft-real-time scheduling of additional tasks / incl. a planned/scheduled querying of a pool of messaging agents.
Queue is a mediator-service that on one endpoint receives any message(s) and delivers (all of such messages ) to the opposite endpoint. Due to the unmanaged context-less delivery of all messages to the receiving point, the Queue-based automation is not feasible for the GUI-refresh functionality agent in a distributed system with soft-scheduling. ( ref. remarks below on a state-full-GraphModelAGENT, that is better equipped for the task of co-integration with Tkinter.mainloop()
Process allow to run separate sub-processes and distribute roles not only via Tkinter tasks ( called in pre-scribed time slots via time-triggered .mainloop() and/or event-triggered callback(s) ) but also to run a fully self-contained <<_aStateFullGraphAGENT_>>, that will have two responsibilities:
[a] communicate with Tkinter to update in-sync with Tkinter's SIGRTU_aRequestToUpdate
+
[b] communicate with "server" to update AGENT's internal GUI-ModelPART ( without any push thereof to any third-party, the less to (over)load the GUI-VisualPART via a FIFO-Queue ( GUI-VisualPART does not have to suffer from having to handle and repaint all the "past" states of the GUI-Model, but becomes a lightweight Repaint-On-Demand process, dealing with just the most recent state of the graph ( already assembled and continuously ( async from Tkinter ... ) maintained in aStateFullGraphAGENT )

STEP 1: Solution approach

-- avoid FIFO-Queue that has to deliver all "GUI-states", that 've become obsolete
++ add aStateFullGraphAGENT to maintain the "recent" GUI-state
++ use ZeroMQ intelligent process-to-process messaging layer without any inter-thread blocking

ZeroMQ-associated messaging overhead is in the order of microseconds, which does not adversely impact any Repaint-On-Demand GUI-related operations, so there is a lot of freedom to arrange the Tkinter refresh-rate, be it the .mainloop()-scheduled or event-driven.
Ref.: >>> https://stackoverflow.com/a/25769600/3666197

STEP 2: Validate / adjust feasibility of GUI-repaint latency / overheads
Ref.: Processing times in Item 2 >>> https://stackoverflow.com/a/25530099/3666197


Can I conditionally render partial views in _Layout.cshtml?

Question: Suppose I have a _Layout.cshtml where I render a left sidebar, which is common to every page of my website.
Something along these lines - a menu, for example

    @Html.Action("_MenuView", "LeftSideMenu")

A feature I would like to have would be to add another partial view, but only display it in certain sections of the website.
For example, in the blog section I may want to display a list of post categories or a treeview of the posts.

    @Html.Action("_MenuView", "LeftSideMenu")

    @if ("???")
    {
        @Html.Action("_BlogTreeView", "BlogEntries")
    }

How could I do that? I know that I want to display "_BlogTreeView" if the view I'm rendering is returned by BlogController ... where do I go from there?
Comment: Why not to use sections? Create a section in the _layout and implement it in the relevant views
Answer: In your layout, add this section
@RenderSection("blogEntries", false)

Then in every view where you want to show the partial view add this:
@section blogEntries {
    @Html.Action("_BlogTreeView", "BlogEntries")
}


How to convert a point on a tilted 3D plane to a point on a 2D plane?

Question: I have an infinite plane in 3D that I only know the normal vector of. I also have a point, somewhere on this plane. Based on the normal of the plane, its center point and the coordinates of the point, how do I convert this to a point on a 2D plane?
Example:
The normal vector of the plane is (0, 0.5, 0.5), its center is at (0, 0, 0) and the point is (0, 0.7, -0.7). On a 2D plane, this would mean the point's coordinate is (0, 1) in 2D space. Does anyone know a formula/method for this?
Any help is greatly appreciated!
Comment: Your question is missing detail and your example is not a good one. The obvious solution from what you have written is simply to take (x, y) from (x, y, z) and just ignore the plane.
Comment: Choose two basis vectors in the plane, i.e. two unit vectors that are perpendicular to each other and to the normal vector. For example $v_x=(1,0,0)$ and $v_y=(0,\sqrt{2}/2,-\sqrt{2}/2)$. This imposes a coordinate system in the tilted plane (which has $(0,0,0)$ as the origin) and you can then decompose any point vector into plane coordinates by taking the dot product with these basis vectors.
Comment: plane has no center.
Answer: Let $N$ be the unit normal to the plane, and $P_0$ be a point on that plane.  To find the $2D$ coordinates you need two mutually orthogonal unit vectors $u_1, u_2$ that also orthogonal to $N$, i.e.
$u_1 \cdot u_2 = 0 , u_1 \cdot N = 0 , u_2 \cdot N = 0 $
With this, we can write any $3D$ point as
$ P = (x, y, z) = P_0 + x_1 u_1 + x_2 u_2 $
Then the coordinates $x_1$ and $x_2$ for the $2D$ representation can found as follows
$ x_1 = (P - P_0) \cdot u_1 $
$ x_2 = (P - P_0) \cdot u_2 $
For example, if $N = \dfrac{1}{\sqrt{2}}(0, 1, 1) $, then you can take,
$u_1 =  (1, 0, 0) $
and $ u_2 = N \times u_1 = \dfrac{1}{\sqrt{2} } (0, 1, -1 ) $
If $P_0 = (1, 2, 5) $ and $P = (3, 1, 1) $ then
$ x_1 = (P - P_0) \cdot u_1 = (2, -1, -4) \cdot u_1 = 2 $
$ x_2 = (P - P_0) \cdot u_2 = (2, -1, -4) \cdot u_2 = \dfrac{3}{\sqrt{2}} $
Comment: Thanks, I'm no expert thought, so can I have some clarification on what mutually orthogonal unit vectors are, and how to find them?
Thanks!
Comment: If $N = (n_1, n_2, n_3) $ , then choose $u_1 = (n_2, -n_1, 0) / \sqrt{n_1 ^ 2+ n_2^ 2} $ provided $n_1 $ and $n_2$ are not both zero.  If they are, then choose $u_1 = (1, 0, 0) $.  Then find $u_2$ as the cross product between $N$ and $u_1$, i.e. $u_2 = N \times u_1$.  The cross product of two vectors is guaranteed to be perpendicular (orthogonal) to both.


Flutter: Determining the speed of a vehicle using GPS

Question: I want to monitor the speed the of device(mobile,tablet,..) like google maps where they shows the speed of vehicle moving with almost exact speed with the delay of fractions of second. if it is possible please let me know.
Answer: Yes, you can measure the speed by using geolocator plugin. It provides you Position object and you can call speed on it. Example:
Geolocator.getPositionStream().listen((position) {
  double speedMps = position.speed; // This is your speed
});

(Optional) You can also provide location settings to it. For example:
var androidSettings = AndroidSettings(
  // Change parameters to your liking.
);
var iosSettings = AppleSettings(
  // Change parameters to your liking.
);
var settings = Platform.isIOS ? iosSettings : androidSettings;
Geolocator.getPositionStream(locationSettings: settings).listen((position) {
  double speedMps = position.speed;
});

Comment: it didnt work, can you give me more context or an example to follow? I would highly appreciate it, Thanks in advance
Comment: does this work for mobile websites also? As per docs "The speed at which the devices is traveling in meters per second over ground.
The speed is not available on all devices. In these cases the value is 0.0." but I didn't find any doc mentioning the devices and platforms supported.
Answer: This is the currently working implementation...
 Geolocator.getPositionStream(
        forceAndroidLocationManager: true,
        intervalDuration: Duration(seconds: 3),
        distanceFilter: 2,
        desiredAccuracy: LocationAccuracy.bestForNavigation)
    .listen((position) {
  var speedInMps =
      position.speed.toStringAsPrecision(2); // this is your speed
  print(speedInMps);

Comment: Why is it giving non zero speed even at rest ?
Comment: @abdullah may be due to accuracy limitation which makes it look like the device is moving.
Comment: Force the Android Location Manager it's not recommended. The Fused Location Provider is a better approach in most cases.
Answer: If you want speed in km:
speedInKm = speedInMps * 3.6;

How to convert m/s to km/h ?
Method 1 (deduction method):
Looking at the whole thing logically, to convert m/s to km/h, divide meters by 1000 and then multiply the result by 3600.
For example, to convert 40 m/s to km/h:

Step 1: 40 m/1000 = 0.04 km
Step 2: 0.04 km * 3600 = 144
Result: 40 m/s = 144 km/h

Why do we do these actions and not others? Because first we need to convert meters to kilometers. To do this, we have to divide them by 1,000, because 1 m = 0.001 km. At this stage, we will get the result in kilometers per second. To get the result in kilometers per hour, we must additionally multiply the whole number by 3600, because 1 hour = 3600 seconds.
Method 2 (faster):
A shorter way is to multiply m/s times 3.6 because 1 m/s = 3.6 km/h.
Example: 12 m/s * 3.6 = 43.2 km/h.
Convert km/h to m/s
To quickly convert km/h to m/s, just divide it by 3.6.
Example: 90 km/h / 3.6 = 25 m/s
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Multiplicity constraint violated when trying to clone Entity Framework object

Question: I am trying to duplicate an object in Entity Framework using the method in this answer, but when I call Add(clone) I get an InvalidOperationException saying that a multiplicity constraint has been violated. My code looks like this
var dbSet = context.Set<MyObject>()
var clone = dbSet.Include(e => e.Property1)
                 .Include(e => e.Property2)
                 .Include(e => e.Property3)
                 .AsNoTracking()
                 .First(e => e.Id == OriginalPrimaryKey)
dbSet.Add(clone); // Throws InvalidOperationException
context.SaveChanges();

The stack trace looks like

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079   Message=Multiplicity constraint violated. The
  role 'MyObject_Property1_Target' of the relationship
  'DataModels.MyObject_Property1' has
  multiplicity 1 or 0..1.   Source=EntityFramework   StackTrace:
         at System.Data.Entity.Core.Objects.EntityEntry.WillNotRefSteal(EntityReference
  refToPrincipal, IEntityWrapper wrappedPrincipal)
         at System.Data.Entity.Core.Objects.EntityEntry.FixupEntityReferenceToPrincipal(EntityReference
  relatedEnd, EntityKey foreignKey, Boolean setIsLoaded, Boolean
  replaceExistingRef)
         at System.Data.Entity.Core.Objects.EntityEntry.FixupReferencesByForeignKeys(Boolean
  replaceAddedRefs, EntitySetBase restrictTo)
         at

Note that Property1 is a full object with a foreign key back to MyObject. From what I can tell, the multiplicity error is coming from the fact that the Property1 objects between an existing entity and my clone are "the same" according to EF (they are not reference equal, I checked).
From the looks of the above answer, I thought when using AsNoTracking EF would handle this and generate a new version of the Property1 entity to save to the database. Is this not the case? If not, what is the best way to clone my entire entity with all referenced properties?
Answer: I fixed this by setting the primary keys of all referenced properties to 0. So my code now looks like
var dbSet = context.Set<MyObject>();
var clone = dbSet.Include(e => e.Property1)
                 .Include(e => e.Property2)
                 .Include(e => e.Property3)
                 .AsNoTracking()
                 .First(e => e.Id == OriginalPrimaryKey);
clone.Property1.Id = 0;
clone.Property2.Id = 0;
clone.Property3.Id = 0;
dbSet.Add(clone);
context.SaveChanges();

I'm not sure if this is the right way to do this—it certainly doesn't feel right—but I haven't been able to find anything else that works.
Comment: I don't know if it is right either, but it fixed my problem so thanks.
Comment: I had a piece of code that worked for years but suddenly threw this error. Also feels wrong but I did this method and it solved my issue (only needed to nil a special 1  0..1 relation.


random colors for circles in d3.js graph

Question: Here is a link to the jsfiddle
http://jsfiddle.net/jaimem/RPGPL/2/

Now the graph shows red color for all the circles.Is dere a way to show random colors on the circles.
Here is the d3.js code
 var data = [{ "count": "202", "year": "1590"},
                  { "count": "215", "year": "1592"},
                  { "count": "179", "year": "1593"},
                  { "count": "199", "year": "1594"},
                  { "count": "134", "year": "1595"},
                  { "count": "176", "year": "1596"},
                  { "count": "172", "year": "1597"},
                  { "count": "161", "year": "1598"},
                  { "count": "199", "year": "1599"},
                  { "count": "181", "year": "1600"},
                  { "count": "157", "year": "1602"},
                  { "count": "179", "year": "1603"},
                  { "count": "150", "year": "1606"},
                  { "count": "187", "year": "1607"},
                  { "count": "133", "year": "1608"},
                  { "count": "190", "year": "1609"},
                  { "count": "175", "year": "1610"},
                  { "count": "91", "year": "1611"},
                  { "count": "150", "year": "1612"} ];

function ShowGraph(data) {
d3.selectAll('.axis').remove();
var vis = d3.select("#visualisation").append('svg'),
    WIDTH = 500,
    HEIGHT = 500,
    MARGINS = {
        top: 20,
        right: 20,
        bottom: 20,
        left: 30
    },
                xRange = d3.scale
                       .linear()
                       .domain([
                          d3.min(data, function(d){ return parseInt(d.year, 10);}),
                          d3.max(data, function(d){ return parseInt(d.year, 10);})
                        ])
                       .range([MARGINS.left, WIDTH - MARGINS.right]),
            yRange = d3.scale
                       .linear()
                       .domain([
                          d3.min(data, function(d){ return parseInt(d.count, 10);}),
                          d3.max(data, function(d){ return parseInt(d.count, 10);})
                        ])
                       .range([HEIGHT - MARGINS.top, MARGINS.bottom]),

    xAxis = d3.svg.axis() // generate an axis
    .scale(xRange) // set the range of the axis
    .tickSize(5) // height of the ticks
    .tickSubdivide(true), // display ticks between text labels
    yAxis = d3.svg.axis() // generate an axis
    .scale(yRange) // set the range of the axis
    .tickSize(5) // width of the ticks
    .orient("left") // have the text labels on the left hand side
    .tickSubdivide(true); // display ticks between text labels
var transition = vis.transition().duration(1000).ease("exp-in-out");

transition.select(".x.axis").call(xAxis);
transition.select(".y.axis").call(yAxis);

vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add some classes so we can style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // finally, add the axis to the visualisation

vis.append("svg:g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(yAxis);

var circles = vis.selectAll("circle").data(data)
circles.enter()
    .append("svg:circle")
    .attr("cx", function (d) {
    return xRange(d.year);
})
    .attr("cy", function (d) {
    return yRange(d.count);
})
    .style("fill", "red")

circles.transition().duration(1000)
    .attr("cx", function (d) {
    return xRange(d.year);
})
    .attr("cy", function (d) {
    return yRange(d.count);
})
    .attr("r", 10)

circles.exit()
    .transition().duration(1000)
    .attr("r", 10)
    .remove();
}

Answer: you can also use d3.scale.category20(); to get some predefined random colors
Just define color scale as
 var color = d3.scale.category20();

Add add fill attribute to the circles as
 .attr("fill",function(d,i){return color(i);});

Comment: d3.scale.category20(); contain only 20 colors.
Comment: this doesn't work with `var color = d3.scaleOrdinal(d3.schemeCategory20);` `attr("fill",function(d,i){return color(i);});`
Answer: replace .style("fill","red") with
.style("fill",function() {
    return "hsl(" + Math.random() * 360 + ",100%,50%)";
    })

doc for dynamic properties
Comment: Why function? Isn't this simpler: `.style("fill", "hsl(" + Math.random() * 360 + ",100%,50%)")`?
Answer: For a quick-and-dirty approach to random colors:

 const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

d3.select("body").selectAll("div")
      .data(dataset)
      .enter()
      .append("div")
      .attr("class", "bar")
      .style('height',(data) => { return data+'px' })
      .style('background-color',() => {
        let color = '#'+Math.floor(Math.random() * Math.pow(2,32) ^ 0xffffff).toString(16).substr(-6);
        console.log(color);
       return color;
      })
 .bar {
    width: 25px;
    height: 100px;
    display: inline-block;
 }

Answer: May be the Chumliu answer is the first approach, but it has one fault: it will repeat colors and make a confusion for the when read the graphics.
Like this way you have different colors:
var colors = [];
var arr    = [];
var j;

products.forEach(function(d)
{
    do
    {
        j = Math.random();
    }
    while($.inArray(j,arr) != -1);
    arr.push(j);

    //this gives us different values
    var value = parseFloat(d.category_id) + parseFloat(d.total);
    eval('colors.cat'+d.category_id+' = "hsl('+ parseFloat('0.'+ value ) * 360 + ',100%,50%)"');
}

later you can use it in D3 like this:
g.append("path").style("fill", function(d)
{
    var indexcolor = 'cat'+d.data.category_id; return colors[indexcolor];
});


É possível criar um arquivo virtual no Python?

Question: Estou tentando usar um arquivo m3u modificado, porem não quero gerar um arquivo físico pra isso
Gerando o arquvio fisico:
url = "#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:8
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:6.006400...."

arquivo = open("movies.m3u8", "w+")
arquivo.write(url)
arquivo.close()

Gostaria de fazer o mesmo processo só que como um arquivo virtual sem precisar criar um arquivo físico na maquina, é possível?
Comment: Não seria apenas não gravar o campo `url`? A variável não seria o tal do "arquivo virtual"?
Comment: No caso para reprodução ele precisa executar o arquivo alocado como .m3u8, modo direto pela url não funciona
Comment: Você já pensou em redirecionamento de entrada e saída? Se o seu problema é manter um arquivo gravado em seu disco.
Comment: Como seria isso? pode dar um exemplo
Comment: https://pt.wikipedia.org/wiki/Redirecionamento_(computa%C3%A7%C3%A3o)
Comment: Vou dar uma lida, obrigado
Comment: Pessoal - só reiterando uma consideração: se você não consegue entender uma pergunta, pode ser só por que você ainda não tem o conhecimento necessário para responde-la - evitem negativar uma pergunta só por isso. Nesse caso, por exemplo, a resposta é simples e única na forma de uma funcionalidade na própria linguagem.
Answer: Sim - em Python 3, há o módulo io - e dentro dele, as classes BytesIO para criar o que você chama de "arquivo virtual"(*) binário, e StringIO para fazer o mesmo com um arquivo de texto.
Os objetos dessa classe tem os métodos write, read, seek e outros para "fingirem" que são um arquivo, e podem ter todo o conteúdo que for escrito neles como um objeto tipo "bytes" (ou tipo "str") a qualquer momento:
In [68]: from io import StringIO

In [70]: arq = StringIO()

In [71]: arq.write("um monte de texto\n")
Out[71]: 18

In [72]: texto = arq.getvalue()

In [73]: print(texto)
um monte de texto

As classes são feitas para você passar uma instância delas para código
que espere um arquivo como um parâmetro - como por exemplo, as funções de salvar imagens da biblioteca "Pillow" - e quando a função retorna, você tem acesso aos bytes que teriam sido escritos em um arquivo ".jpg" no disco.
Atenção que o código que usa o arquivo não pode chamar o método .close() nele, senão não é possível recuperar o conteúdo. Mas se isso for acontecer, é fácil contornar criando uma subclasse muito simples, que "desligue" o método close() colocando um que não faz nada no lugar:
In [82]: a = io.BytesIO

In [83]: a = io.BytesIO()

In [84]: a.write(b"teste")
Out[84]: 5

In [85]: a.close()

In [86]: a.getvalue()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-86-a51238acd863> in <module>
----> 1 a.getvalue()

In [89]: class CloseProofIO(io.BytesIO):
    ...:     def close(self):
    ...:         pass
    ...:
    ...:

In [90]: b = CloseProofIO()

In [91]: b.write(b"outro teste\n")
Out[91]: 12

In [92]: b.close()

In [93]: b.getvalue()
Out[93]: b'outro teste\n'

(*) Nunca vi oficialmente a terminologia "arquivo virtual" - mas acho que ela pode ser bem correta. Pelo menos eu entendi de primeira o conceito.
Comment: Exatamente isso, esse modulo resolveu o problema, o termo "arquivo virtual" é a forma leiga de tentar explicar, muito obrigado :D


Any explanation why obtained sum gives "Near Integer" result?

Question: Here is "almost an integer" result:
$$\sum^{\infty}_{k=0}\left(\frac{1}{\exp(\pi\sqrt{163})}\right)^{k}\left(\frac{120}{8k+1}-\frac{60}{8k+4}-\frac{30}{8k+5}-\frac{30}{8k+6}\right)
= 94.000000000000000014789449792044364408558923807659819...$$
?
Comment: I hope I did not err in changing your expression "(1/(exp(Pi*sqrt(163))^k))" to $e^{-k\pi\sqrt{163}}$.
Comment: @Jyrki I would vote for these comments as an answer.
Answer: There is nothing magical about this sum. Remember that $e^{-\pi\sqrt{163}}\approx 4\cdot10^{-18}$ is a small positive number. When you substitute $k=0$, you get the main term $=94$. The other terms are all tiny.
If you don't believe this, try the following. Compute the same sums with $164, 165,\ldots$ instead of $163$.
Comment: Well, there is, of course, a chance that the series is very interesting for some other reason, but do you know of one?


How to calculate Associated Legendre Functions as a function of theta?

Question: I'm trying to solve Problem 4.4 in Griffiths Quantum Mechanics, and I need to calculate the associated legendre functions $P^{m}_{\ell}(x)$ to do this. $P^{m}_{\ell}(x)$ are functions of $x$, yet in Griffiths, it is said that $P^{1}_{1} = -\sin(\theta)$ (clearly not a function of $x$). I then thought that maybe I should be plugging in $\cos(\theta)$ for $x$, but when I do that I don't get the answer for $P^{1}_{1}$. Are we doing a change of variables technique here? Why isn't $P^{1}_{1}$ a function of $x$?
Answer: The associated Legendre polynomial $P^{1}_1$ is $-(1-x^2)^{1/2}$. Substituting $\cos\,x$ and using the trigonometric identity $1-\mathrm{cos}^2x=\mathrm{sin}^2x$ should give you the result.
Comment: thanks a lot mate!


Should I use Chi-squared or exact binomial test?

Question: I am testing for the difference in 30-day mortality between an exposure group and a non-exposure group. The contingency table:

Taking drug A
Dead at 30 days post-op
Alive at 30 days post-op

Yes
3
25

No
9
218

Having read other answers on this site I'm not clear whether a Chi-squared or Exact binomial test is appropriate to test the null hypothesis that there is no association between taking drug A and 30 day mortality. Some sources seem to say the small group numbers mean the Exact binomial is more appropriate but I'm not clear.
Thank you for your help.
Comment: Do the tests give you the same (opposite) results?
Comment: Both tests are non-significant at 0.05 level. Chi-square, p = 0.11. Exact binomial test, p = 0.10.
Comment: So it does not matter whether you use one of them. However, exact test might be preferable as it does not receive "critics" for small cells.
Answer: I tried several standard tests: A test of two binomial proportions,
an equivalent chi-squared test in R with a simulated
P-value (on account of the small sample taking the drug), and Fisher's exact test. No P-values below 5%. The drug gives a
higher survival rate, but not enough larger to be statistically
significant at the 5% level.
Looking toward the future: If a similarly higher survival
rate persists when more subjects taking the drug can be included, the P-value
might be small enough for a significant difference. For example, with 9 survivors in 84, the P-value would be about 0.024. (Whether the
trial should be continued might depend on whether the drug
has risks or undesirable side effects.)
Here are results from a recent release of Minitab:
    Test and CI for Two Proportions

Sample  X    N  Sample p
1       3   28  0.107143
2       9  227  0.039648

Difference = p (1) - p (2)
Estimate for difference:  0.0674953
95% CI for difference:  (-0.0498455, 0.184836)
Test for difference = 0 (vs ≠ 0):  Z = 1.13  P-Value = 0.260

* NOTE * The normal approximation may be inaccurate for small samples.

Fisher's exact test: P-Value = 0.133

The smaller sample is too small for an accurate normal approximation.
Fisher's exact test is based on a hypergeometric distribution and so
can give an accurate P-value for small samples. However, Fisher's test
shows no significant difference.
Fisher's Exact Test in R, for verification: Same P-value as in Minitab
MAT = rbind(c(3,25),c(9,218))
MAT
     [,1] [,2]
[1,]    3   25
[2,]    9  218
fisher.test(MAT)

        Fisher's Exact Test for Count Data

data:  MAT
p-value = 0.1326
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.4726708 12.6193587
sample estimates:
 odds ratio
   2.889384

Chi-squared test in R using simulation to get an accurate P-value.
This test gives the same P-value as Minitab's test of two
proportions (when sample sizes are large enough to avoid
the error message).
chisq.test(MAT, cor=F, sim=T, B = 10000)

        Pearson's Chi-squared test with simulated p-value
        (based on 10000 replicates)

data:  MAT
X-squared = 2.5321, df = NA, p-value = 0.1325

Comment: Thank you for your answer! It is clear there is no statistically significant difference in these samples. I take it from your answer that these tests (Binomial, Chi-squared, Fisher's etc.) are statistically valid to use in this scenario however.
Comment: Various tests comparing two binomial proportions are very similar to chi-sq test on a $2\times 2$ table, Some versions use continuity corrections for small sample sizes, but that usually makes little difference in P-value. Fisher's exact test traditionally used when counts are too small for good normal or chi-squared approximations, but modern software makes it feasible to use Fisher for larger counts. I think all are valid. Different authors have various favorites.