Bootstrap : Fixing navbar at top

Question: Tried everything to make navbar fix to the top in bootstrap, but nothing works. I've already tried position : relative and position : absolute. Any help appreciated!
HTML:

     Search

      About Us

      Education

      Consumer Service

CSS:
.nav.navbar-nav.navbar-right li a {
color: black;
background-color: transparent;
}

EDIT : Implemented this one page scroll in the page : https://github.com/peachananr/onepage-scroll
Comment: In Bootstrap 4 it's just `fixed-top`. Why are you using relative and absolute?
Comment: removing `style="margin-top: 2vw; margin-right: 3vw; position: fixed;"` doesn't work?
Comment: Nope. It didn't
Comment: check https://getbootstrap.com/docs/3.3/examples/navbar-fixed-top/. This demonstrate the same.
Comment: where do you want to fix the navbar? To the top of the window or to the top of the section?.
Don't really understand why you placed it inside a section when you dont need it.
Comment: I've used one page scroll. Hence I had to put it inside a section
Comment: The correct answer is given already. For more details just refer to the documentation and copy-paste the standard solution. Best regards,
Comment: Can you make a jsfiddle? Still don't get it? Is it a one page? you can have a one page and still have a nav outside a section. like here: https://getbootstrap.com/docs/3.3/examples/navbar-fixed-top/
Answer: navbar-fixed-top shall do the job (your additional statement position: fixed; is redundant and should be removed). As an example, refer to the web page which implements the required functionality using Bootstrap CSS: www.alexanderbell.us. Corresponding verbatim HTML :  ( bg-grey-dark is a custom class setting background and could be excluded as it's indifferent to the positioning).
On a separate note: the better practice would be avoiding in-line styling as shown in your case (i.e. style="margin-top: 2vw; margin-right: 3vw; position: fixed;">. Instead, extend the existing class .navbar-fixed-top in your custom CSS file, or CSS included in the  section.
Hope this may help.
Comment: Well, I've provided you with detailed solution/explanation and fully-functional page built on this solution. It's a bit unclear what exactly are you trying to achieve and how it is different from already existing solutions(s). If you can add more clarity to your question, then the solution could be customized per that clarified requirements. Anyway, good luck with your project. Best rgds,
Answer: Don't quite understand your full example and what you are trying to achieve.
Your code is already fixed in the top.
Probably the section you placed the navbar has some css you don't let as see.
here is a working example:
https://jsfiddle.net/L1eczuno/
HTML:

     Search

      About Us

      Education

      Consumer Service

Twitter Bootstrap 3.0

Starter template with CSS and JS included.

Fork this fiddle

CSS:
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
}
#test {
    margin-top: 87px;
    height: 2000px;
}

André
Comment: That's why I've provided the link to the github repo for one page scroll. Its not possible to describe the entire code here. I think, the CSS there might be creating some problem, but don't know where, since I tried tweaking that too
Comment: The example you provided works. So cant help you further

Bootstrap : Fixing navbar at top


Change name to menu link dinamically

Question: I have a menu:
Parent-1
 - Child-1-1
 - Child-1-2
 - Child-1-3
 - another_child
Parent-2
 - Child-2-1
 - Child-2-2
 - another_child

I needed change the name of Parent-2 item (Parent-2 text is unique), I did it with hook_link_alter() hook:
/**
 * Implements hook_link_alter().
 */
function MY_MODULE_link_alter(&$variables) {
  if ($variables['text'] == 'Parent-2') {
     $variables['text'] = t('New name');
  }
}

I need too to change the names of all child of Parent-2 dynamically. I can't do it with hook_link_alter() hook because in my example there is two elements(another_child) with the same name. Those changes must not be saved in database.
How can I do this?
Answer: I can do it implementing hook_preprocess_HOOK hook, specifically hook_preprocess_superfish:
/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_NAME_preprocess_superfish(&$variables) {
  if ($variables['id'] == 'superfish-main-menu') {
    $menu = ($variables['element']['#tree']);
    // ...
  }
}

Comment: Thank you for your -1 vote, no explanation and no solution about the issue.

Change name to menu link dinamically


How can I find webform e-mail submission values keys?

Question: I created a Webform and now I want to send an email on submit to the customer. But I'm not understanding how to take the submission values one by one and use it in the email body.
The submission tokens description says:

%value[key] - A value without additional formatting. Elements may be
  accessed such as %value[fieldset_a][key_b]. Do not include quotes.

What kind of key the %value array have got? How can I find they?
Answer: Here is the answer.
Lets say I've 4 fields in Webform
 Label    -   Field Key
First Name - first_name

Last Name - last_name

Phone Number - phone_number

Message - message

Here is the way to access them in template field
For example if you want to display name as the combination of First Name and Last Name
Name:  %value[first_name] %value[last_name]

Then this appears in mail like
Name: Krishna Mohan

If you want to access a individual field value with Label
For example Phone number
%email[phone_number]

This appears in mail like
Phone Number - 555-555-5225

I've tested this and works great! Hope this helps


geom_bar define border color with different fill colors

Question: I want to draw a bar plot with geom_bar where I want unique fill colors surrounded by a black border. However the instruction color="black" is  not interpreted as "black" as I want it to be and I get red borders.
library(ggplot2)
test=as.data.frame(cbind(a=c(1,1,2,3), b=1:4, c=as.character(1:4)))
ggplot(test) + geom_bar(aes(x=a, y=b, fill=c, colour="black"), stat="identity")

How do I correctly use geom_bar so that it gives me the correct black border?
Answer: You have to put colour outside aes:
ggplot(test) + geom_bar(aes(x=a, y=b, fill=c), colour="black", stat="identity")

Comment: By the way, this is because everything inside `aes` is interpreted as a column in the data. By defining the color aesthetic as `"black"`, it's as if you had a column that read "black" in every row, and then you told ggplot to make group colors conditional on the values in that column. That's why it automatically makes a legend for it, for one. By putting it outside the `aes`, you're telling ggplot to treat it as a single fixed color indicator - as a name, hexadecimal, or whatever.


jquery iterate json variable with $.each gives me a result of [object]

Question: I try to get a json var into HTML, as you see in the snippet the result is [object]
Why do I get this [object] result?
Note: I want to iterate true the json dynamically, because the next json export may be completely different, I might add a extra field or I might remove 'ISO' etc.

var json = [{
    "SourceFile": "/Volumes/Ext 1TB/Google Drive/temp/test1/MapA/2019-10-15 13,46,54 Panasonic-DMC-TZ20.JPG",
    "FileName": "2019-10-15 13,46,54 Panasonic-DMC-TZ20.JPG",
    "FileSize": "5.0 MB",
    "Model": "DMC-TZ20",
    "DateTimeOriginal": "2019:10:15 13:46:54",
    "ImageSize": "4320x2880",
    "FocalLength": "4.3 mm",
    "ShutterSpeed": "1/25",
    "Aperture": 3.3,
    "ISO": 200,
    "WhiteBalance": "Cloudy",
    "Flash": "Off, Did not fire"
  },
  {
    "SourceFile": "/Volumes/Ext 1TB/Google Drive/temp/test1/MapA/2019-10-15 13,51,08 Panasonic-DMC-FZ2000.JPG",
    "FileName": "2019-10-15 13,51,08 Panasonic-DMC-FZ2000.JPG",
    "FileSize": "4.8 MB",
    "Model": "DMC-FZ2000",
    "DateTimeOriginal": "2019:10:15 13:51:08",
    "ImageSize": "3840x2160",
    "FocalLength": "175.7 mm",
    "ShutterSpeed": "1/125",
    "Aperture": 4.5,
    "ISO": 160,
    "WhiteBalance": "Cloudy",
    "Flash": "Off, Did not fire"
  },
  {
    "SourceFile": "/Volumes/Ext 1TB/Google Drive/temp/test1/MapA/2019-10-15 13,52,39 Panasonic-DMC-FZ2000.JPG",
    "FileName": "2019-10-15 13,52,39 Panasonic-DMC-FZ2000.JPG",
    "FileSize": "4.0 MB",
    "Model": "DMC-FZ2000",
    "DateTimeOriginal": "2019:10:15 13:52:39",
    "ImageSize": "3840x2160",
    "FocalLength": "34.7 mm",
    "ShutterSpeed": "1/160",
    "Aperture": 4.1,
    "ISO": 125,
    "WhiteBalance": "Cloudy",
    "Flash": "Off, Did not fire"
  }
];
console.log(json);
$.each(json, function(key, value) {
  console.log(key + ": " + value);
})

Exif test

I want something like this:
 each json entry must show here, all the fields are variable.

  SourceFile: /Volumes/Ext 1TB/Google Drive/temp/test1/MapA/2019-10-15 13,52,39 Panasonic-DMC-FZ2000.JPG
 FileName : 2019-10-15 13,52,39 Panasonic-DMC-FZ2000.JPG
 FileSize : 4.0 MB
 etc. etc.

Comment: Have you seen https://stackoverflow.com/q/4750225?
Comment: the `key` parameter will be the index of the array item. The `value` parameter will be the item that is stored in this index which in your case is always an object.If you want to store it as a JSON string you can use the `stringify()` function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Answer: Update your loop as follow.
$.each(json, function(keyIndex, valueObject) {
 $.each(valueObject, (key, value)=>(console.log(key,":" ,value)));
})


Is there a way to tessellate an area using triangles and minimize/specify the number of unique triangles?

Question: Is it possible to tessellate a planar surface from triangles but with the following constraints:

density (average number of triangles) can be varied.
a finite set of unique triangles are used for the tessellation. Say 5-15 unique triangles.

Optionally also with the ability to increase density for sub areas.
If it is possible, can you point me to some relevant material.
Thanks
Comment: This question needs a lot of work to become comprehensible. To begin with, what's a triangle? I know what a triangle is in the plane, but you want to tessellate a surface, and surfaces are generally curved, and don't have lots of straight lines in them, so - what's a triangle?
Comment: Yes, a planar surface.
Comment: Well, it is possible to tessellate a triangle, but impossible to tessellate a circle, so it would be nice to be more specific about the kind of planar surfaces you wish to allow. Or is that exactly what you want, a characterization of such surfaces? Or perhaps by "planar surface" you mean "polygon"?
Comment: I do not have a requirement for the surface shape. It can be pretty much anything. A square, triangle, rectangle, etc. or even something like: http://www.google.com/imgres?q=penrose+tiling&hl=en&client=safari&sa=X&rls=en&biw=960&bih=1027&tbm=isch&prmd=imvns&tbnid=oFv2VCRg9T2GUM:&imgrefurl=http://en.wikipedia.org/wiki/File:Variable_penrose_tiling.svg&docid=O4b754yHsmD_hM&imgurl=http://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Variable_penrose_tiling.svg/800px-Variable_penrose_tiling.svg.png&w=800&h=447&ei=RDpJT_3XIumM0AX8ysSjBA&zoom=1
Comment: Well, then, it seems that you have your answer. How do you propose to tessellate a disk?
Answer: I'm going to make an interpretation of the question, and then answer it. If my interpretation is wrong, OP can let us know.
We are given triangles $T_1,T_2,\dots,T_n$, and we want to know whether it is possible to tessellate an arbitrary polygonal region $P$ with a finite number of  triangles, each triangle similar to one of those given.
I claim it's not possible. Let $P$ have an angle that is smaller than any of the angles in the triangles. Then there is no way to get to that angle.
Now, what if we are allowed to pick the triangles $T_1,T_2,\dots,T_n$ after we have seen the region $P$? If $n$ is fixed, we're still out of luck. The angles we can get lie in an extension field of transcendence degree at most $2n+1$ over the rationals, so if we are faced with a region with more than $2n+1$ algebraically independent angles, we can't tessellate it.
In short, under the sort of assumptions I've been making, the class of tessellatable polygonal regions is very restricted.
Comment: The Penrose picture shows that one particular polygon can be tessellated with a small number of basic shapes of triangle. Notice that as you go around the perimeter of that polygon, you never come to any really, really sharp angles. If you choose your triangles in advance, and then someone confronts you with a polygon with an angle sharper than any of the ones in your triangles, you are out of luck.
Comment: I appreciate your taking the plunge. I am a layman in math, so I could not have predicted the challenges in interpreting my question. By the statement, "P have an angle", does that mean the sum of all its internal angles?
Comment: Actually, it seems you interpret the question accurately. To clarify, my intent is that "n" is 5-15, and the total number of triangles used for the tessellation is ">n" selecting at least once (preferably at least 4 times) each triangle in the set "T". However, what assumptions (in layman's terms preferably) are being made that do not lead to the following, which I would suspect my description allows for as a successful candidate (assuming one divides the polygons into respective triangles): http://en.wikipedia.org/wiki/File:Variable_penrose_tiling.svg
Comment: $P$ is a polygon. It has a lot of angles, one at each vertex. "Let P have an angle..." means suppose that one of those angles is smaller than the smallest angle in any of the triangles.


How do I know when a group of accidentals lead to a key change or not?

Question: Especially for something like this

(which is originally in D Major), how do I know that it doesn't constitute a key change? A more general question would probably be how do I identify key changes in sheet music in general?
Answer: For your particular example, there is no clear way of telling, because it lacks context. In general, the key has changed when music feels more or less "at home" in a key different than the previous one. For this to happen, the new key has to be properly established, and music has to remain in this new key for some time. Therefore it depends on what there is before and after. In any case, the concept of key change (modulation) is kind of a theoretical simplification; in practise, analysis of a musical score is not always white or black.
This is a complex topic, that involves understanding well the concept of Key, function of different chords, etc… If you want to get it right, study a good harmony text. I strongly recommend you Arnold Schönberg's Harmony book. Chapter 9 talks about modulation, but reading previous chapters might also be usefu/needed.
Answer: Short answer
To detect a modulation based on the presence of accidentals requires recognizing whether those accidentals — plus any unchanged members of the key signature — themselves could constitute a new key (or shift between major and minor).
General answer: considerations upon seeing accidentals
Accidentals show up in three common situations:

The leading tone in a minor key. Recognizing this situation comes down to knowing which pitch is the leading tone and noting that it's the only prominent accidental. Beyond just the leading tone, one would also look to notice how scale degree 6 is or is not altered.
Chromatic alterations. These can look more like a key change, but are generally recognizable either by being very short-lived or by not being joined by other accidentals necessary for a particular key. A piece in C major in which some E#s and F#s appear, is probably not modulating to F# major. If it were, we could reasonably expect to see some G#s and A#s, for example.
Modulation. In this case, we'd expect clusters of accidentals sufficient to suggest a new key (signature). Starting of in C major, but then suddenly seeing a lot of F#s, C#s, and G#s in close proximity (without being immediately cancelled by naturals) would clearly suggest a passage in A major. And an additional E# or two would suggest F# minor.

Excerpt analysis
In the given excerpt, the F naturals (in the 2nd through 7th measures) suggest a shift to D minor, C major, or A minor. In the C major case, though, we'd expect to see some prominent C naturals; and in the A minor case, not only would C natural be expected, but so would some G#s, to reinforce the shift in tonal center. However, the F naturals are consistent enough to at least keep our ears open for D minor. The absence of Bbs argues against a "real" modulation, however.
The introduction of G# (8th measure) might raise an eyebrow, but since it's immediately followed by G natural, it's reasonable to view it as a momentary chromatic pitch.
Seeing both F# and G# at the end of the line is at least suggestive that we could be heading toward A major, but one must keep an open mind, because they're also clearly part of a melodic chromatic scale (E-F-F#-G-G#), and we need to know what's happening beyond the given excerpt to know where we're actually headed. Is it "just" a chromatic scale, or is it leading beyond A major to, say, E major (that is, is there a D# lying just over the horizon)?
And beyond just the accidentals
Taking a step beyond the question of analyzing just the accidentals themselves, the presence of a cadence is a core analytical insight as to whether the accidental is a brief alteration or indicative of a key change.
The excerpt opens with an A major chord followed by the D minor, which suggests at least a temporary focus on D minor, if not a full-on modulation. On the other hand, the later accidentals do not participate in cadential sequences (short of know the next measure after the excerpt), so are more likely of a more ornamental nature.
Comment: @ToddWilcox Absolutely. Added a small section to the post. Thanks for pointing that out.
Comment: I like this answer best, and I also wonder if there's a benefit in looking for cadences to confirm modulation or not. At least in baroque and classical music before Beethoven, I would be reluctant to call anything a key change without an authentic or plagal cadence in the new key, although a half cadence in the right context might do it.
Answer: The composer starts in D major, as you say, but temporarily wants to put some D minor flavour in. As it's only on a temporary basis, and he's returning to D major, it's a modulation rather than a key change. So it's easier for everyone if the key signature stays the same, and accidentals are used to signify changed notes.
A proper key change would involve two naturals, at the beginning of the new key, often with a double bar line, and the new key signature put in place. If the new key is C/Am, it looks a little odd, as there would be the naturals, followed by seemingly no key signature.A look at the next few notes should give sufficient clues, though.
Comment: @ToddWilcox In fact, Tim asked that very question a couple years later: [What's the exact difference between modulation, key change and tonicisation?](https://music.stackexchange.com/q/74379/70803). Good question with good answer(s).
Comment: Is it in some flavor of non-American English that "modulation" doesn't mean a key change?
Answer: There are modulations, and there are key changes.  When a piece includes a "development" section, harmonic excursions will generally use accidentals.  When it's more of a set of variations, each may get its own key signature.  Or a composer may change key signature for purely pragmatic reasons, to make a section easier to read.   The ultimate Key Change is the "up a semitone for the last chorus" device, common in popular music.  This will definitely get a new key signature!
Is the Ring Cycle a series of modulations - it begins in Eb and also ends there, several evenings later - or are there key changes?   Does Bach's 'Minuet in G' modulate to D, or change key?  Would we be dissatisfied if the Ring didn't "come home"?  What about the Bach?    Do you find the unresolved modulation in "Unforgettable" magical, or vaguely unsatisfying?
You wanted an answer and I'm just offering more questions :-)  Questions on how to label something often end up like that.
Comment: Written in, well, the jury seems to be out! I have dots with a G major key sig., but others with a C major key sig. The duet may be like that as it was done post mortem, so there may only have been certain recordings of Nat to use. The original song sounds o.k. to me, with no perceivable modulation. For secong time around, I usually play a bar of the V of the original 1st chord, which makes it sound as if there's a key change there.
Comment: Another question - where exactly does Unforgettable modulate?
Comment: Nat King Cole sings it in F.  The song takes some pleasing harmonic detours but remains firmly rooted in F until the final four bars when it settles on a definite Bb, the subdominant key.
It's odd, and to my ears rather unsatisfactory.   Works best when the refrain's sung just once, as on the YouTube clip of Nat's TV show.  The duet version with Natalie goes back for a second try, and has to jump through some harmonic hoops  - a half-chorus instrumental in Db then a rather contrived slip back into F for the ending.
Great melody, but structural problems that I find hard to spin into virtues.
Comment: All of Nat's contributions to the duo recording are in F.   The inherent modulation in the basic song may not worry you, but I'm surprised you don't perceive it.
Answer: There are four big categories:

Change in key signature: a new key signature is inserted within the score. This is when a whole section is in a new key, you see it a lot, for example, in the middle, or "trio", section of ternary forms.
Modulation: accidentals in the score including a proper cadence of some kind in the new key, of fairly long duration, something like a full phrase or more, basically you want to hear a phrase in a new key.
Tonicization: accidental in the score "hinting" at a different tonic, brief duration, usually only long enough for a two chord change, not proper phrase ending cadence as with a modulation. One place to look for this is sequential passages.
Change of mode: tonic stays the same, but modal degrees change, notable the third and sixth degrees of the scale.

Regarding your example, the harmony is entirely using chord roots A and D, and it mostly uses accidentals for a mode change. The key signature is for D major, but in second bar of the excerpt naturals are used to lower the F# to plain F, F natural being the minor third degree of the key D minor. When the tonic says the same, but it just changes from major to minor, that's a mode change.
Toward the end there is a pedal on A and above it there is an alternation of G natural and G#, this movement can be called "standing on the dominant", something very important in classical music. It's intentionally vacillating back and forth between the G natural which would be diatonic to D minor and the G# which would tonicize A, but it doesn't really set up A as the tonic. Again, that ambiguity is intentional. It's a way to set up tension. We don't see how it continues in the excerpt, but it probably goes to D something, major or minor, which would relieve the tension of playing around with the G natural and G# sharp.


Error 403 forbidden while scraping with python

Question: I need to scrape a website but the thing is i've tried so many times with my python script and didnt work, i tried with differents headers and didnt work, i also tried with Httrack and wget and i keep facing the same problem which is the 403 forbidden error.
Is there any way to bypass this, any header, proxys, browser configuration?
I did manage to get the website html with python script but with no deep levels and images are blurred, if someone know how to improve the python script i will be glad.
EDIT - This is the code of the script:
<code>import urllib.parse
import cfscrape
from bs4 import BeautifulSoup

scraper = cfscrape.create_scraper()
response = scraper.get("website_url")

soup = BeautifulSoup(response.content, 'lxml')
with open('index.html', 'w') as f:
    f.write(str(soup))

for img in soup.findAll('img'):
    if img.get('src') !=None:
        img_url=img.get('src')
        name=img_url.split('/')[-1]
        name = urllib.parse.unquote(name)
        img_response=scraper.get(img_url)
        file=open(name,"wb")
        file.write(img_response.content)
</code>
Comment: It's going to be difficult for anyone to help without seeing your code
Comment: Hi Bruno, please do not paste images of code! Much frownwed upon. But the problem could well be specific to the target website. Can you share one URL that causes you the problem?
Comment: Ok, for example with this URL 'https://www.classcentral.com/' and i tried others and get the same problems or even worst.
Answer: Since I don't have enough info, I can't solve this problem for you. But here are some possible problems you might be having and how to solve them.
For starters, I have some experience from trying to make a kahoot bot using the requests-HTML module (allowing for dynamic javascript rendering).
The way that sending a request works is that it needs the miminum headers, generally just the device headers, and basic auth. I noticed that the site you commented as an example requires a sign in. When you send a request, part of that auth is a cookie generally. As you probaly know, a cookie is pieces of saved data on a website pertaining to your device. When you log into a site, it generally asigns you a validater cookie, which tells it you have authentication to be on it (as the cookie stays with your browser for a set amount of time). Sadly, there are no  other ways to bypass this if that is your issue. You'd have to create a session first, and use it to sign in with your login credentials (though some sites have anti-bot systems in place like captcha). If there is a captcha during log-in, then there is no chance you will be able to scrape data from it without access to the api (though I don't have much experience with web API's). I would also recommend trying an alternave of urllib3 to see what requests work (request, post, head, etc). It's possible that your specific request sent is just invalid entirely (chosen by website creators upon creation). Even if something like the basic request works, you then have to find what data you want to grab, and if the site is dynamically loaded. In terms on dynamically rendered javascript, the most likely scenario for your problem, there are several topics you need to learn basic knowledge about to solve it.

Inspect Element
Element ID/Path
Requests_HTML

Each of these components are crucial for scraping elements off the page, which as everything shown is part of an element, so is whatever you want to grab. Once you render the javascript using requests_HTML, you have to make sure you have the cookie (if needed), and any other validation headers (plently of lists online, just search: headers needed to scrape websites). Though I haven't used it before, you can use Selenium and WebDriver to login, at least that's what I understand from the documentation. To do that, you need to grab the x-path that I mentioned, and then return data to fill out that path (either via an encoded url based on the variable or somehow edit it directly).
I hope that this helps you figure this out!
Comment: Thank you!!! that is pretty helpful i am working on it based on these topics and hopefully will find a solution


Ajax modal form window not loading

Question: I already had success in ajax loading a form into a modal window with Ctools but now it fails and I do not why. Maybe someone can help me?! The problem: I create a link on a page which should open a form in a modal window. With another (Views created) page it did work fine: I click on the link and the form is correctly rendered in a modal window. In the following case it seems to be all the same - the only difference is that another form is used and the ajax links are not created by a Views page but a custom page callback. But when I click on the ajax link the modal window is opened - but the throbber keeps rotating and nothing happens. No form is shown in the window - just the throbber graphic.
As I can see when hacking into functions like ajax_render() that the output is correctly built into an array usable by ajax_render()... there are no error message anywhere, neither in Drupal database logs, reports or server error logs. Additionally the browser gives no JavaScript error or warnings.
This is the menu_hook defining the page callback for the ajax link:
 $items['foodlog/existing/%ctools_js/%foodlogentry/%'] = array(
    'title' => 'Edit your foodlog entry',
    'page callback' => 'foodlog_edit_form_ajax',
    'page arguments' => array(2, 3, 4),
    'access callback' =>  'foodlog_edit_form_access',
    'access arguments' => array(3),
    'type' => MENU_CALLBACK
  );

This is the ajax page callback:
function foodlog_edit_form_ajax($js = NULL, $foodlogentry, $action) {

  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
    );
    $form_state['build_info']['args'][] = $foodlogentry;
    $form_state['build_info']['args'][] = $action;

    $output = ctools_modal_form_wrapper('foodlog_edit_form', $form_state);

    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }

  // go on: if no $js -> render the form
  else {
    return drupal_get_form('foodlog_edit_form', $foodlogentry, $action);
  }
}

And here is the code where the ajax link is rendered (just the part of the page callback, where it happens):
ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();

$actionlinks = l(t('edit'), 'foodlog/existing/nojs/'. $entry['flid'] .'/edit', array('attributes' => array('class' => array('ctools-use-modal', 'ctools-modal-foodlog-modal-style') ) ) );

The result is the correct link like
Bearbeiten

The JavaScript files are loaded, no caching is enabled, no aggregation. As I mentioned the same is working on another Views page where I create such a link by rewriting a views field. Just the form is another one. The form is rendered when I simply call the URL directly in the browser - there seems to be some trouble somewhere when Drupal sends all the stuff to the browser.
Does anyone has an idea?
Comment: I'm only idea is unfortunately not very helpful to your issue directly. But I see all that (good) custom code and just think this would have been a ton easier: https://www.drupal.org/project/ctools_automodal
Answer: I found the error: on my page I use the jQuery Flot plugin in order to create some charts. For one of the charts there was an error on the page where I wanted to open a form in a modal window. When I solved this error the modal window was working as expected... JavaScript is a weird thing!

Ajax modal form window not loading


Erro ao selecionar dado gravado no BD através de um

Question: Estou com problemas ao carregar os dados de um usuario no formulário.
Meu selectOneMenu é carregado(corretamente) com uma lista de tipos porém o Objeto TIPO inserido no registro do Usuário não está sendo selecionado durante a edição.
Resumo:
Possuo uma classe usuário e cada usuário pode ser de vários tipos. ( AdmGeral/ AdmGerencia / AdmCompras / UserBasico / etc.. )
Consigo cadastrar novos usuários sem problemas mas estou tendo dificuldade ao editar um registro existente devido ao componente "SelectOneMenu" que não está selecionando o valor gravado no banco.
Fiz uma versão reduzida do problema para facilitar e auxiliar os demais.
Classe Usuario.java
<code>@Entity
public class Usuario{
    @Id
    @GeneratedValue(generator="user_id_seq")
    @SequenceGenerator(name="user_id_seq",sequenceName="user_id_seq",allocationSize=1)
    private Integer id;
    private String nome;

    @OneToOne
    private Tipo tipo

    public Integer getId() {
       return this.id;
    }
    public void setId(Integer id) {
       this.id = id;
    }

    public Tipo getTipo() {
       return this.tipo;
    }
    public void setTipo(Tipo tipo) {
       this.tipo = tipo;
    }

    public String getNome(){
       return this.nome;
    }
    public void setNome(String nome) {
       this.nome = nome;
    }
}
</code>
Classe Tipo.java
<code>@Entity
public class Tipo{

 @GeneratedValue(generator="tipo_id_seq")
 @SequenceGenerator(name="tipo_id_seq",sequenceName="tipo_id_seq",allocationSize=1)
    private Integer id;
    private String nome;

    public Integer getId() {
       return this.id;
    }
    public void setId(Integer id) {
       this.id = id;
    }

    public String getNome(){
       return this.nome;
    }
    public void setNome(String nome) {
       this.nome = nome;
    }
}
</code>
View User.xhtml
<code><h:form id="form_user">
    <p:panelGrid columns="2">
        <p:outputLabel value="ID" />
        <p:inputText disabled="true" value="#{usuarioBean.usuario.id}" />

        <p:outputLabel value="Nome" />
        <p:inputText value="#{usuarioBean.usuario.nome}" />

        <p:outputLabel value="ID" />
        <p:selectOneMenu value="#{usuarioBean.usuario.tipo}" required="true">
             <f:selectItem itemLabel="Select" />
             <f:selectItems value="#{tipoBean.lista}" var="c" itemValue="#{c}" itemLabel="#{c.nome}" />
             <f:converter converterId="entityConverter"/>
        </p:selectOneMenu>
        <p:commandButton value="New" icon="fa fa-plus" update="form_user" action="#{usuarioBean.newRecord}" />
        <p:commandButton value="Save" icon="fa fa-save" update="form_user" action="#{usuarioBean.save}"/>
    </p:panelGrid>

    <p:dataTable var="user" value="#{usuarioBean.lista}">
        <h:outputText value="#{user.id}"/>
        <p:commandButton title="Edit" update="form_user" icon="fa fa-fw fa-edit" process="@this">
        <f:setPropertyActionListener target="#{usuarioBean.usuario}" value="#{user}" />
        </p:commandButton>

        <p:commandButton action="#{usuarioBean.removeRecord}" update="form_user" icon="fa fa-fw fa-trash" immediate="true">
            <f:setPropertyActionListener target="#{usuarioBean.usuario}" value="#{user}" />
        </p:commandButton>
    </p:dataTable>
</h:form>
</code>
Converter EntityConverter
<code>@FacesConverter(value="entityConverter")
public class EntityConverter implements Converter {

    public Object getAsObject(FacesContext ctx, UIComponent component,
            String value) {
        if (value != null) {
            return component.getAttributes().get(value);
        }
        return null;
    }

    public String getAsString(FacesContext ctx, UIComponent component,
            Object obj) {
        if (obj != null && !"".equals(obj)) {
            String id;
            try {
                id = this.getId(getClazz(ctx, component), obj);
                if (id == null){
                    id = "";
                }
                id = id.trim();
                component.getAttributes().put(id, getClazz(ctx, component).cast(obj));
                return id;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private Class<?> getClazz(FacesContext facesContext, UIComponent component) {
        return component.getValueExpression("value").getType(
                facesContext.getELContext());
    }

    public String getId(Class<?> clazz, Object obj) throws SecurityException,
            NoSuchFieldException, IllegalArgumentException,
            IllegalAccessException {
        for (Field field : clazz.getDeclaredFields()) {
            if ((field.getAnnotation(Id.class)) != null) {
                Field privateField = clazz.getDeclaredField(field.getName());
                privateField.setAccessible(true);
                if (privateField.get(clazz.cast(obj)) != null) {
                    return (String)field.getType()
                            .cast(privateField.get(clazz.cast(obj))).toString();
                } else {
                    return null;
                }
            }
        }
        return null;
    }
}
</code>
Conclusão:
1 - Meu SelectOneMenu está sendo populado com os dados do banco corretamente
2 - Depois que comecei a utilizar o converter genérico(EntityConverter) consigo salvar o registro do usuário no banco.
3 - Quando abro o registro para edição ele não carrega o tipo gravado no banco no SelectOneMenu.
O que estou fazendo errado?
Answer: Após analisar um projeto pronto que utilizava JPA/Hibernate notei que as classes possuiam o método equals e hash code. Era exatamente isso que eu não havia implementado e que não deixava o SelectOneMenu selecionar o meu objeto.
Segue abaixo o método inserido na classe Tipo.java
<code>@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Tipo other = (Tipo) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
</code>


UIActivityViewController : Possible to implement flow with a configuration step?

Question: An app I am building needs functionality to share video.
I have successfully implemented a UIActivityViewController for this, with a custom UIActivityItemProvider to dynamically generate the video output.
However, I would like the user to be able to select an output quality for the video as well. I would like the flow to be:

User taps share button UIActivityViewController appears
User taps desired activity
Options for video quality are presented
User taps desired quality
UIActivityItemProvider generates video at desired quality
Video is shared to selected service

However I don't see any options to hook items 3 and 4 into the flow.
Any suggestions would be much appreciated.
Answer: I have been struggling with trying to implement a similar flow, and I couldn't get anything that was close enough to work for my case. So I ended up going about it in a different way, that accomplished my same goal (for the end users experience). Here's what I did:

User taps share button, and I present a UIActionSheet with the share options (in your case, the quality options).
User taps desired option, and then UIActivityViewController is presented.
Item is shared, with appropriate options, to the selected share service.

It actually turned out to be a really nice flow in the end. However, it doesn't solve the problem of allow option configuration after the UIActivityController is displayed, it just shuffles the flow around so that the end result is the same - but working within the confines of the UIActivityViewController.
I hope this alternative is helpful to anyone that finds this older post and is curious about how to do this. Also, if there is a way to do this in the primary flow as the OP asks, I'd love to know that as well.


how to test a class and her subclass

Question: If I have class A and a subclass B, is there a way to write a test case which will be able to check a function in both classes without code duplication in two separate classes ATest and BTest?
Answer: You can do the generic tests in TestA using an instance of class A, which is created in the setup
Then extends TestA within TestB and use the instance of class B for the B-specific tests, making sure that you override the setup so this instance is passed to the tests in class TestA
All the unit test cases will be reused without duplication
Comment: Is there a way to do it with one class using parameter annotation or something like this?

how to test a class and her subclass


Matplotlib won't work in python even though i pip installed it

Question: I'm trying to use matplotlib to do some plotting.
i wrote:
import matplotlib as mpl
import matplotlib.pyplot as plt

When I try to run the program I get:
    import matplotlib as mpl
ModuleNotFoundError: No module named 'matplotlib'

This shouldn't be happening as I've pip installed matplotlib to the latest version (3.5.1) and matplotlib shows up correctly when i write "pip list" in the terminal.
Why doesn't matplotlib work?
Comment: Can you please share the output of the command `pip freeze` in your working directory ? Btw, are you using a *virtual environment* ?
Comment: when i write ```pip freeze``` i get:

```matplotlib==3.5.1```
along with my other packages. I am not using a virtual enviornment.
Comment: Check if you have multiple versions of Python installed, and also check that the name of the Python script being run is not called "matplotlib.py"
Comment: @DavidG i checked with ```py -0``` and it looks like I have two older versions (3.9-64 and 3.8-64). The Python script is not named "mathplotlib.py"
Comment: I also want to add that the same is for BeautifulSoup/bs4. I have installed it but i get No module named "bs4"
Comment: Try `python -m pip freeze`  Almost certainly your default python is different than your default `pip`.
Comment: @JodyKlymak I mean when I do that i still see the correct version of matplotlib there. Is there anything spesific I should look out for?
Comment: Hold on - it says that i'm using python 3.9.9 which is outdated. I have installed the latest version. Why hasn't it changed?
Comment: Which OS are you working with and how did you install the newest version of python?
Comment: @FlyingTeller I am using Windows 10. I installed the newest python version through downloading the latest version from the Python website.
Comment: It seems like the problem is that pip is using an older python version (it is using 3.9 while I use 3.10.1). How do I change that? When I run ```py -V``` I get ```pip 21.3.1 from C:\Users\johan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pip (python 3.9)```
Comment: Easiest fix would probably be to simply uninstall the other python. You can also use `python -m pip` to use that pip that is associated with `python`. Other options can be to edit your PATH environment variable so that the newer python has preference.
Comment: @FlyingTeller I just did uninstall the older python version, but pip is still using 3.9. Should I try to uninstall and reinstall pip?
Comment: You should use Anaconda and not try to hand install
Answer: Looks like you messed up your Python installations. Maybe pip installs something in one Python, but python calls another version, which doesn't have the libraries you want.
To get sure you're installing and running with the same Python, replace python -m pip with python[version] -m pip, and python my_file.py with python[version] my_file.py. For example, to use Python 3.9, use python3.9 instead of python. And so on.
With this, you get sure to install and run things with the same Python. Also, it's good to try virtual environments, instead of fighting with global installations.


a problem using the Cauchy-Schwarz inequality

Question: I watched videos on the Cauchy-Schwarz inequality, but don't know how to work this problem due to the $\mathbf{a}^\top \mathbf{x}$ part.
Let $\mathbf{a}\in \Bbb R^n$ be given. Define $f: \Bbb R^n\to\Bbb R$ by $f(\mathbf{x}) =
\mathbf{a}^\top \mathbf{x}$. Show
that $f$ is continuous. Hint: Use the Cauchy-Schwarz inequality
If someone can show steps/explain that would be great. Thank you!
Answer: The dot product of two vectors $u,v \in \Bbb R^n$ may be written in matrix notation as $u^\top v$, where $u$ and $v$ are now seen as column vectors. Then Cauchy-Schwarz reads $|u^\top v| \leq |u||v|$. That said, if $a = 0$ then $f = 0$ is continuous. If $f \neq 0$, let $\epsilon > 0$ and take $\delta = \epsilon/|a|>0$. If $|x-y|<\delta$, then we have that $$|f(x)-f(y)| = |a^\top x - a^\top y| = |a^\top(x-y)| \stackrel{(\ast)}{\leq} |a||x-y| < |a|\delta = \epsilon,$$where in $(\ast)$ we have used Cauchy-Schwarz. So $f$ is, in fact, uniformly continuous.


Create project folder Buildengine

Question: When I am creating one project file by code using the BuidEngine, Does anybody know..

how to add project folders?
how to add one builditem to the created folder?

.
var project = new Project();
project.Load(ProjectFile.FullName, ProjectLoadSettings.IgnoreMissingImports);
//Create project folder
var buildItem = project.AddNewItem(itemName, fileName);
//add file to folder

Thanks in advance
Answer: What do you mean by project folder? Won't specifying filename like Folder\File1 do the trick?

Create project folder Buildengine


What does p value 2.5e-0.5 mean?

Question: What does p value 2.5e-0.5 mean? If it is 2.5 × 10 ^0.5 then it is way above the statistically significant p<0.005.. learning this to interpret the results of one study..
Comment: Are you sure it's `e-0.5`? That would presumably mean $2.5 \times 10^{-0.5} = 2.5 / \sqrt{10} \approx 0.79$, but that's very unusual use of notation. Maybe it's a typo/mistake in the study.
Comment: Something more like `2.5e-5` would be much more standard, which would should be read as a computer version of scientific notation, i.e. $2.5 \times 10^{-5}$, which is a pretty small $p$-value.
Comment: Please paste in your actual output so we can determine what the situation is.
Comment: @amoeba, I believe that's supposed to happen when more than 1 dup was suggested.
Comment: Notice the $-$ sign... $e^{-0,5} = 1/\sqrt{10}$, multiplied with 2.5... Thats about $0.8$...
Comment: Could you please tell which software you are using?
Comment: I'm voting to close this question as off-topic because it is a trivial matter that should have no interest to the OP and others here.
Comment: @amoeba, you could, I suppose, although that Q has extra aspects that aren't relevant to this one. I'm not sure why the thread I linked was closed, TBH, it seems on topic enough to me. Either way, tomayto tomahto.
Comment: @gung Yeah, this should be consolidated somehow. I voted to reopen, edited both Qs, and raised a mod flag...
Comment: @gung Oh wow, now it's closed as a dup of both!
Answer: Taking 2.5e-0.5 at face value, that's $2.5 \times 10^{-1/2} \approx 0.79$ (as pointed out by @Dougal and @Repmat in the comments). The p-value is defined as "the probability of seeing a result as strong as observed or greater, under the null hypothesis."
Combining these two, we have the following: under the null hypothesis, the probability of seeing a result as strong as observed or greater is about 79%. So, given the null hypothesis, the result you have found is not particularly "unusual."
Comment: I don't think I have ever seen a computing system in which "2.5e-0.5" would even be considered syntactically correct.
Comment: @whuber, I haven't either. I use STATA, and if p were equal to 0.79, it would just report 0.79. That said, hopefully OP knows what how to define a p-value now.

What does p value 2.5e-0.5 mean?


C++ 3D perfect collision detection

Question: I'm having hard time learning collision detection by experience. I'm making a box game, à la Minecraft, and am at the stage of implementing collision detection.
I've done x and y axis', since everything consists of cubes I would like to make my own collision detector and make it as light as possible.
Is there a way to make "pixel perfect" collisions, that is when the player's bounding box (or circle) touches a box it registers as a collision? Right now this is what I did:
if(-TOUCH_DISTANCE-1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE-1)
{
    collisionNorth = true;
}
if(-TOUCH_DISTANCE+1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE+1)
{
    collisionSouth = true;
}

It basically detects the collision within a certain margin and that means errors, which I don't like :(. Notice the +/-1 which offsets the "collision wall" to the respective side of the box.
This works, on lower speeds, but once there's some action (when I crack up the speed variable) the collision can't be detected anymore since I go too fast and pass right through the cube... Is there a way to make it wallhax0r proof?
This is especially annoying on z axis, when the player falls at high speed and even when defining a respectable collision margin it will ultimately look nasty (player half buried).
Answer: You've identified one of the problems of using discrete mathematics to model the path of an object. At time t the object is "here" and at time t + delta it's "there" - without actually having passed through the points in between.
You can get more accuracy by decreasing delta, but ultimately you are going to hit the limit of what you can calculate in that time interval.
If you can detect a collision approaching by using a relatively large time delta and loose bounding box you could then crank up the accuracy, but again you are going to hit limits.
Converting to a continuous model might help - but may take more computational power. You could switch to this when your objects are close so you're not doing it all the time.
Sorry I've not got a definite answer, only pointers.
Comment: Well, there goes 2 days worth of code. Not only a continuous model is exact, but it's cheaper too (in this case).
Answer: Usually what you need to do is keep track of the previous position of the objects as well as the current position. Then when you update, you can check if the objects intersected during the time period, rather than if they intersect 'at the moment'.

C++ 3D perfect collision detection


Classification trees: the best Predictor and the ability to predict

Question: The topmost decision node, the root node in a classification tree is said to be the best predictor of the model. Does this mean the root node variable is also the best in predicting the target variable?
Comment: Yes, it is the strongest predictor, by default. But you may force any (not the strongest) predictor to define the root 1. Most implementations allow it.
Answer: In theory, yes, but you should avoid drawing conclusions from a single tree. Trees have low bias, but high variance, meaning that the addition or removal of a few observations only from your training set can change the first split, and modify the entire tree structure in a cascading fashion. On the other hand, ensemble methods such as Random Forests and Stochastic Gradient Boosting allow more variables to play an important role in determining tree structure (by considering only a random subset of predictors as candidates at each split), and by combining the output from many trees, they generate way more reliable variable importance measures. I would advise reading the Hastie for more details.


identifying possible machine learning approaches

Question: I am working on a Biology study and myself and a fellow colleague have looked at various patient medical images and we have computed a clinical score based on the pathology noted on the images. This score is in the range 0-9 (where lower values indicate remission and higher values indicate severe disease).
On top of this we have worked with some image analysis people to compute some automated image metrics. These are typically based on image texture, some measured displacement of certain anatomical landmarks over time and a few others. In total we have 6 of these image derived metrics.
Now, we want to know if there is a mapping between these image metrics and the clinical scores that we have computed. In the beginning, I tried a simple multivariate linear regression and there does not seem to be any link between them. I am now wondering what other methods I could try to see perhaps if there is a non-linear relationship.
My question is that given this kind of data, which machine learning methods do you think would be appropriate to try next? We have about 300 datasets that we have analyzed i.e. 300 patients where we have the clinical scores and the image based metrics that I described before.
Answer: Keeping the assumption that human-derived severity score is the "truth" label about the severity of the disease, then your approach is correct, and the only question left is "is there a possibility that a relationship exist even after my multivariate linear regression fails to spot any significant relation?"
I would say that you should in order

post the result of the regression so we can judge whether your conclusions are correct, or at least say what metrics you use to conclude there is no relationship
mention whether you tried adding interaction terms and or quadratic/cubic/higher order terms
if all that fails, you could try a non-parametric regression method such as k-nearest neighbor (KNN).


angularjs view not updating on data change

Question: I have this code on my controller:
angular.module('chatApp').
controller('MainUserList', ['$scope', '$state', '$http', 'AppData', '$localStorage', function ($scope, $state, $http, AppData, $localStorage) {
    var socket = AppData.getSocket();
    $http.get('http://localhost:3000/api/users').success(function(data){
        $scope.users = data;
    });
    socket.on('X_USER_LOGIN', function(data){
        for(var x=0;x<$scope.users.length;x++){
            if($scope.users[x].id === data.id){
                console.log('doufn!');
                delete $scope.users[x];
                break;
            }
        }
    });
    socket.on('X_USER_LOGOUT',function(data){
        console.log(data.id+' has logged out!');
    });

    $scope.excludeUser = function(object){
        return object.id !== $localStorage.clientProfile.id;
    };
}]);

However when the event X_USER_LOGIN is fired, the console is displaying the string I want but the list on the view isnt updating.
From my code above, array member should be deleted right?
Here is my partial view:

             {{usr.firstname + ' ' + usr.lastname}} ({{usr.username}})

 Sample last message

Am I doing something wrong?
Answer: Okay I have the answer.
Since I am using socket.IO's function, I have to wrap the data deletion on $scope.apply function
Working code:
angular.module('chatApp').
controller('MainUserList', ['$scope', '$state', '$http', 'AppData', '$localStorage', function ($scope, $state, $http, AppData, $localStorage) {
    var socket = AppData.getSocket();
    $http.get('http://localhost:3000/api/users').success(function(data){
        $scope.users = data;
    });
    socket.on('X_USER_LOGIN', function(data){
        for(var x=0;x<$scope.users.length;x++){
            if($scope.users[x].id === data.id){
                console.log('doufn!');
                /*change is here*/
                $scope.$apply(function(){
                   delete $scope.users[x];
                });
                break;
            }
        }
    });
    socket.on('X_USER_LOGOUT',function(data){
        console.log(data.id+' has logged out!');
    });

    $scope.excludeUser = function(object){
        return object.id !== $localStorage.clientProfile.id;
    };
}]);


Streaming Live Video From Webcam Android

Question: I need to stream live video from web-cam to my android phone. On PC side I am planning to use OpenCV and grab each frame using Mat class. I am familiar with OpenCV, but no idea about how to stream this video to Android. I need to do this through wifi.  Can any one suggest how can I do this ?. Or is there any other method for doing this ?.
Thanks in advance....
Comment: Via file transfer is easy.. But I've totally no idea on live stream
Comment: Hi thanks for replay...Can you give some link which help me for doing these.
Answer: Via file transfer, it is easy to read video files.
Here's the answer from another post on SO, and one more
The code in that post is as follows.
<code>public static Bitmap getVideoFrame(FileDescriptor FD) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(FD);
        return retriever.getFrameAtTime();
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }
    return null;
}
</code>
Note that this is off-line process. For online realtime transfer, I have no idea.


Crash while using Mac save dialog

Question: Our users are experiencing an exception with the following scenario:

Save a file under some arbitrary name, e.g. "test1".
Open the save dialog to save again (the dialog now suggests "test1" by default).
Click "Save", and then "Replace" to overwrite the existing file.

Result: exception.
If, just before step 3 the user clicks on the file in the dialog finder window (the name "test1" remains) - there is no exception.
I found a mention of this issue here, and tried to use the given advice - however it didn't help.
Here's a reduction of my code:
<code>#define kMaxPathLength 1023
[self setDialogResult:[dialog runModal]];

if ([self dialogResult] == NSOKButton)
{
    char pathBuffer[kMaxPathLength];
    @try{
        NSString* pathcopy = [[dialog URL] path];  // <== Causes the exception
        [pathcopy getCString:pathBuffer maxLength:kMaxPathLength encoding: NSUTF8StringEncoding];
    }
    @catch(NSException* e){
        <breakpoint>
    }
}
</code>
The line with the remark causes the exception:
<code>ROSP: sandbox extension failure: nil result or wrong class type ((null)) for finalURL
</code>
Note: the said remarked line and the line below are a breakdown of the original statement used:
<code>[[[dialog URL] path] getCString:pathBuffer maxLength:kMaxPathLength encoding:NSUTF8StringEncoding];
</code>
In which the exception also happens.
Using Xcode 12, Catalina.
Any advice to avoid the exception?
Comment: Is it possible to reproduce the issue in a small test project?
Answer: This bug was eventually solved (actually worked around) by explicitly specifying the file extension in the suggested name for the Save As dialog.
The bug happens when specifying only the base name (no extension).

Crash while using Mac save dialog


How would you explain covariance to someone who understands only the mean?

Question: ...assuming that I'm able to augment their knowledge about variance in an intuitive fashion ( Understanding "variance" intuitively ) or by saying: It's the average distance of the data values from the 'mean' - and since variance is in square units, we take the square root to keep the units same and that is called standard deviation.
Let's assume this much is articulated and (hopefully) understood by the 'receiver'. Now what is covariance and how would one explain it in simple English without the use of any mathematical terms/formulae? (I.e., intuitive explanation. ;)
Please note: I do know the formulae and the math behind the concept. I want to be able to 'explain' the same in an easy to understand fashion, without including the math; i.e., what does 'covariance' even mean?
Comment: Assuming you already have a scatterplot of your two variables, x *vs.* y, with origin at (0,0), simply draw two lines at x=mean(x) (vertical) and y=mean(x) (horizontal): using this new system of coordinates (origin is at (mean(x),mean(y)), put a "+" sign in the top-right and bottom-left quadrants, a "-" sign in the two other quadrants; you got the sign of the covariance, which is basically [what @Peter said](http://bit.ly/v1WX5s). Scaling the x- and y-units (by SD) lead to a more interpretable summary, as discussed in the [ensuing thread](http://bit.ly/vjOfeG).
Comment: @Xi'an - 'how' exactly would you define it *via simple linear regression*? I'd really like to know...
Comment: @chl - could you please post that as an answer and maybe use graphics to depict it!
Comment: I found the video on this website to help me as I prefer images over abstract explanations. [Website with video](http://www.investopedia.com/terms/c/covariance.asp) Specifically this image: [![enter image description here](http://i.stack.imgur.com/xGZFv.png)](http://i.stack.imgur.com/xGZFv.png)
Answer: Sometimes we can "augment knowledge" with an unusual or different approach.  I would like this reply to be accessible to kindergartners and also have some fun, so everybody get out your crayons!
Given paired $(x,y)$ data, draw their scatterplot.  (The younger students may need a teacher to produce this for them. :-)  Each pair of points $(x_i,y_i)$, $(x_j,y_j)$ in that plot determines a rectangle: it's the smallest rectangle, whose sides are parallel to the axes, containing those points.  Thus the points are either at the upper right and lower left corners (a "positive" relationship) or they are at the upper left and lower right corners (a "negative" relationship).
Draw all possible such rectangles. Color them transparently, making the positive rectangles red (say) and the negative rectangles "anti-red" (blue).  In this fashion, wherever rectangles overlap, their colors are either enhanced when they are the same (blue and blue or red and red) or cancel out when they are different.

(In this illustration of a positive (red) and negative (blue) rectangle, the overlap ought to be white; unfortunately, this software does not have a true "anti-red" color.   The overlap is gray, so it will darken the plot, but on the whole the net amount of red is correct.)
Now we're ready for the explanation of covariance.
The covariance is the net amount of red in the plot (treating blue as negative values).
Here are some examples with 32 binormal points drawn from distributions with the given covariances, ordered from most negative (bluest) to most positive (reddest).

They are drawn on common axes to make them comparable.  The rectangles are lightly outlined to help you see them.  This is an updated (2019) version of the original: it uses software that properly cancels the red and cyan colors in overlapping rectangles.
Let's deduce some properties of covariance.  Understanding of these properties will be accessible to anyone who has actually drawn a few of the rectangles. :-)

Bilinearity. Because the amount of red depends on the size of the plot, covariance is directly proportional to the scale on the x-axis and to the scale on the y-axis.

Correlation. Covariance increases as the points approximate an upward sloping line and decreases as the points approximate a downward sloping line.  This is because in the former case most of the rectangles are positive and in the latter case, most are negative.

Relationship to linear associations. Because non-linear associations can create mixtures of positive and negative rectangles, they lead to unpredictable (and not very useful) covariances.  Linear associations can be fully interpreted by means of the preceding two characterizations.

Sensitivity to outliers. A geometric outlier (one point standing away from the mass) will create many large rectangles in association with all the other points.  It alone can create a net positive or negative amount of red in the overall picture.

Incidentally, this definition of covariance differs from the usual one only by a constant of proportionality.  The mathematically inclined will have no trouble performing the algebraic demonstration that the formula given here is always twice the usual covariance.  For a full explanation, see the follow-up thread at https://stats.stackexchange.com/a/222091/919.
Comment: Now if only all introductory statistical concepts could be presented to students in this lucid manner …
Comment: @fcoppens Indeed, there is a traditional explanation that proceeds as you suggest.  I thought of this one because I did not want to introduce an idea that is unnecessary--namely, constructing the centroid $(\bar x, \bar y)$.  That would make the explanation inaccessible to the five-year-old with a box of crayons. Some of the conclusions I drew at the end would not be immediate, either. For example, it would no longer be quite so obvious that the covariance is sensitive to certain kinds of outliers.
Comment: Thanks, this as I suspected. I realised that an extra factor of 2 comes out if the sum is taken over all $i, j$ rather than $i<j$. I think the only other ambiguity is whether the "pair" $(i,i)$ counts - the area of the rectangle is zero, but if averaging rather than summating it clearly makes a difference! Incidentally when I teach covariance I also use the "positive and negative rectangles" approach, but pairing each data points with the _mean point_. I find this makes some of the standard formulae more accessible, but on the whole I prefer your method.
Comment: This is beautiful. And very very clear.
Comment: Having done the algebra, I wonder if "universal constant of proportionality (independent of the data set size)" may be misleading, so I want to check if I understood the procedure correctly. For {(0,0),(1,1),(2,2)} there are $3\choose{2}$ = 3 possible rectangles of areas 1, 1 and 4. They're all red so the "covariance" is 6. And {(0,0),(1,1),(1,1),(2,2)} has $4\choose{2}$ = 6 rectangles, all red or zero, of areas 0, 1, 1, 1, 1 and 4 so "covariance" is 8. Is this right? If so it's $\sum_{i<j}(x_i-x_j)(y_i-y_j)$.
Comment: It seems many people find this a simple explanation, unfortunately I failed to understand covariance by reading this at first. After reading about covariance in other places, such as [this Quora's question](https://www.quora.com/What-is-the-difference-between-correlation-and-covariance), then I was able to read this again and understand better the rectangles example. I personally think explaining *covariance properties* such as **Bilinearity** and **Relationship to linear associations** is not intuitive (as OP asked), at least to me (maybe I'm way too mediocre). Still appreciatte the effort +1
Comment: @whuber: You should stop editing posts and start posting answers ;) Simply stunning!
Comment: I will do something similar if/when I next teach an introductory statistics class. I wish somebody had done so for me when I was first learning statistics!
Comment: @Silverfish Yes, I should have indicated that the constant was universal after *averaging* the values rather than *summing* them.
Comment: Coming from a programming background, I still have no idea :S
Comment: I think a reason as to ***what*** the co-variance is used for in applications would not hurt the mind of many.
Comment: @whuber: this is a genious explanation for covariance ! I must give (+1) (I would like to give more).  One question, why do you draw rectangles based on the points $(x_i, y_i)$ and $(x_j, y_j)$ and not on $(x_i, y_i)$ and $(\bar{x}, \bar{y})$ ?
Comment: Hi @whuber, I was looking at your graph a year ago, looking to decipher something highly complex , or at least presumably very complex because I wanted to , and now going back to your reading, it is absolutely simple. Many many thanks for such a pedagogical explanation. One thing though however and this something I've noted a lot in a lot of math/stats explanation: Tons of teachers are not mentionning that sometimes it is up to the do-er to choose in a arbitral manner the points and to be honest with you, I had to fight a bit to get that. But once done, 1/2
Comment: I'm with @Alisson and Karl Morrison, I'm lost. Super thanks for all the time you put into making the answer but I didn't follow at all. It's full of math jargon like *bilinearity* and *Relationship to linear associations*. I still have no idea what covariance is. Is it related to points or lines? Are we pulling pairs of points or all possible pairs? If the points are A,B,C,D are we doing (A,B) and (C,D) or are we doing (A,B),(A,C),(A,D),(B,C),(B,D),(C,D)? I guess I first need to be a math wiz, then I'll understand this.
Comment: @FreezingFire A reasonable request.  I have included a demonstration in another answer at https://stats.stackexchange.com/a/222091/919.
Comment: I've tried several examples by hand and there is an error with this answer. The sum of the areas need to be divided by 2 times the number of rectangles drawn (N*(N-1)). In a way, covariance is taking the average area (considering the positive/negative signs) of each rectangle drawn, and then dividing by 2. The author may have actually done this for their calculations but this is not mentioned in the answer.
Comment: my professor used that very diagram :)
Comment: Do we know if people that invented the concept of covariance and correlation (Pearson i think) had this view in mind ?
Comment: Yeah, I do not know anything about stats. I don't understand how the points on the corners are assigned: `it's the smallest rectangle, whose sides are parallel to the axes, containing those points.` Aren't all sides parallel?
Comment: @Tjorriemorrie This isn't about statistics, it's about geometry: You can construct plenty of rectangles whose sides are *not* parallel to the coordinate axes.
Comment: @Karl Its relationship to linear associations and correlation coefficients (see the bullet points at the end) ought to be enough!
Comment: @whuber your explanation and the implicit deductions just made perfect sense. Thanks again 2/2
Comment: I couldn't get the sciguides link to load. That may just be a problem with me but you might like to double-check it at some convenient time.
Comment: @Glen_b Thanks--it doesn't work for me, either.  I'll delete the reference.  For the record, here's the deleted text:
*(The original version of this post has led to the creation of a simplified graphical rendition of the underlying idea. It is accompanied by an admirably clear, step-by-step explanation.  Please check it out at http://sciguides.com/guides/covariance/. For additional explanation also see the answer posted here by [arthur.00](http://stats.stackexchange.com/a/111296).)*
Comment: Thanks for the explanation, i still need one clarification. If the x,y pairs are (-1,-1), (0,0), and (1,1) - there will be in total 3 rectangles. 1 red and 1 non-red. And the 3rd rectangles between connecting (-1,-1) and (1,1) - is it positive or negative ? Or will it be partly positive and partly negative  ?
Comment: @Praveen Yes, those three points determine three (nondegenerate) rectangles--and *all* are red.
Comment: Thanks. Are both the x_i, y_i random (binormal) distributed or is x_i a given , a mathematical ( non-random) variable?
Comment: I am unable to prove the equivalence mentioned in the last statement... Could you please perhaps give a hint or a sketch of the proof?
Comment: @Kenny Thank you for your comment.  This is no error: it is by design and it is mentioned.  I explain the distinction in the last paragraph.  I did not want to distract anyone with this detail, which is discussed in several other threads here on CV.
Comment: is @Kenny's remark mentioned in your answer? in the last paragraph, you say that the constant of proportionality is "independent of the data set size" -- that seems different than the remark, which says that the constant of proportionality depends on the data set size
Comment: @Richard Good point: I could have stated this more clearly, especially because Kenny's characterization of the constant is wrong (it's off by a factor of 2).  I'll think about how to clarify that in the text.  Since this post has been around so long, I want to proceed carefully and change it as little as possible.
Comment: Thanks. I think saying that the constant of proportionality depends on the dataset size (rather than being independent of it) might be correct? If it is correct, that would be sufficient. I think that is intuitive, since the net sum of the areas is not taking an average, and covariance is an average.
Comment: @Richard The underlying idea is there is a denominator that obviously *ought* to depend on dataset size: namely, the number of pairs of diagonally opposite vertices that can be formed, $\binom{n}{2}.$  Upon dividing by that, there is a *universal* constant, independent of $n,$ that will produce the covariance.  (And that constant therefore is readily computable by doing the calculation with a tiny dataset :-).
Comment: Maybe then my confusion is in the sentence you write "The covariance is the net amount of red in the plot," which seems false, and I think the correct statement is "The covariance is the net amount of red in the plot, divided by twice the number of rectangles you drew." Which isn't that much more complicated of a statement.
Comment: I am calculating the covariance of 2 stock price movements. So covariance is 1 dimensional to me. Why is @whuber's answer is 2 dimensional? How can I change it to 1 dimensional covariance problem of mine?
Comment: how are the 2 dots comprising a square decided?
Comment: @Eiffel (1) Two stocks, two dimensions.  (2) Take two dots in the plane: there's only one rectangle that has them as diagonally opposite endpoints.  Its top and bottom span the range of the first coordinates of the dots while its left and right sides span the range of the second coordinates.
Answer: To elaborate on my comment, I used to teach the covariance as a measure of the (average) co-variation between two variables, say $x$ and $y$.
It is useful to recall the basic formula (simple to explain, no need to talk about mathematical expectancies for an introductory course):
$$
\text{cov}(x,y)=\frac{1}{n}\sum_{i=1}^n(x_i-\bar x)(y_i-\bar y)
$$
so that we clearly see that each observation, $(x_i,y_i)$, might contribute positively or negatively to the covariance, depending on the product of their deviation from the mean of the two variables, $\bar x$ and $\bar y$. Note that I do not speak of magnitude here, but simply of the sign of the contribution of the ith observation.
This is what I've depicted in the following diagrams. Artificial data were generated using a linear model (left, $y = 1.2x + \varepsilon$; right, $y = 0.1x + \varepsilon$, where $\varepsilon$ were drawn from a gaussian distribution with zero mean and $\text{SD}=2$, and $x$ from an uniform distribution on the interval $[0,20]$).

The vertical and horizontal bars represent the mean of $x$ and $y$, respectively. That mean that instead of "looking at individual observations" from the origin $(0,0)$, we can do it from $(\bar x, \bar y)$. This just amounts to a translation on the x- and y-axis. In this new coordinate system, every observation that is located in the upper-right or lower-left quadrant contributes positively to the covariance, whereas observations located in the two other quadrants contribute negatively to it. In the first case (left), the covariance equals 30.11 and the distribution in the four quadrants is given below:
<code>   +  -
+ 30  2
-  0 28
</code>
Clearly, when the $x_i$'s are above their mean, so do the corresponding $y_i$'s (wrt. $\bar y$). Eye-balling the shape of the 2D cloud of points, when $x$ values increase $y$ values tend to increase too. (But remember we could also use the fact that there is a clear relationship between the covariance and the slope of the regression line, i.e. $b=\text{Cov}(x,y)/\text{Var}(x)$.)
In the second case (right, same $x_i$), the covariance equals 3.54 and the distribution across quadrants is more "homogeneous" as shown below:
<code>   +  -
+ 18 14
- 12 16
</code>
In other words, there is an increased number of case where the $x_i$'s and $y_i$'s do not covary in the same direction wrt. their means.
Note that we could reduce the covariance by scaling either $x$ or $y$. In the left panel, the covariance of $(x/10,y)$ (or $(x,y/10)$) is reduced by a ten fold amount (3.01). Since the units of measurement and the spread of $x$ and $y$ (relative to their means) make it difficult to interpret the value of the covariance in absolute terms, we generally scale both variables by their standard deviations and get the correlation coefficient. This means that in addition to re-centering our $(x,y)$ scatterplot to $(\bar x, \bar y)$ we also scale the x- and y-unit in terms of standard deviation, which leads to a more interpretable measure of the linear covariation between $x$ and $y$.
Answer: I loved @whuber 's answer - before I only had a vague idea in my mind of how covariance could be visualised, but those rectangle plots are genius.
However since the formula for covariance involves the mean, and the OP's original question did state that the 'receiver' does understand the concept of the mean, I thought I would have a crack at adapting @whuber's rectangle plots to compare each data point to the means of x and y, as this more represents what's going on in the covariance formula. I thought it actually ended up looking fairly intuitive:

The blue dot in the middle of each plot is the mean of x (x_mean) and mean of y (y_mean).
The rectangles are comparing the value of x - x_mean and y - y_mean for each data point.
The rectangle is green when either:

both x and y are greater than their respective means
both x and y are less than their respective means

The rectangle is red when either:

x is greater than x_mean but y is less than y_mean
x is less than x_mean but y is greater than y_mean

Covariance (and correlation) can be both strongly negative and strongly positive. When the graph is dominated by one colour more than the other, it means that the data mostly follows a consistent pattern.

If the graph has lots more green than red, it means that y generally increases
when x increases.
If the graph has lots more red than green, it means that y generally decreases when x increases.
If the graph isn't dominated by one colour or the other, it means that there isn't much of a pattern to how x and y relate to each other.

The actual value of the covariance for two different variables x and y, is basically the sum of all the green area minus all the red area, then divided by the total number of data points - effectively the average greenness-vs-redness of the graph.
How does that sound/look?
Comment: @Kirsten it's likely just a cultural background thing, but I found the idea of `blue=negative` / `red=positive` deeply unintuitive and jarring.
I am much more used to `red=negative` in the context of displaying the sign of numbers, while blue & green are natural positive colours (e.g. traffic lights).
I'm a native english speaker from Australia. I'm guessing people from different backgrounds would have different colour/number associations.
Comment: Just to make sure, the blue dot in the middle is the average of ALL the points?
Comment: Yes that's correct. It's different in each of the 4 graphs as they are of different sets of data.
Comment: Thanks for this! One confusing thing about this is that you have sort of flipped (although not exactly) the color scheme from @whuber's answer. In trying to wrap my head around the concept, that gave some cognitive whiplash.
Comment: +1 I prefer your explanation, especially the second-to-last sentence, thank you so much
Comment: @Eiffelbear You can draw rectangles using [`matplotlib.patches.Rectangle`](https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Rectangle.html) and the multiple panels with [`subplots`](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html). Making a plot like this with `matplotlib` is pretty straightforward. Look up the necessary documentation.
Comment: How do you draw the plot? Did you use Python to draw it? If you did, can you kindly share your code, please? @capohugo
Comment: Was there a reason you switched the meaning of red from whuber's?
Answer: Covariance is a measure of how much one variable goes up when the other goes up.
Comment: @nupul Well, the opposite of "up" is "down" and the opposite of "positive" is "negative".  I tried to give a one sentence answer. Yours is much more complete.  Even your "how two variables change together" is more complete, but, I think, a little harder to understand.
Comment: That's right, Peter, which is why @naught101 made that comment: you description sounds like a rate of change, whose units will therefore be [units of one variable] / [units of the other variable] (if we interpret it like a derivative) or will just be [units of one variable] (if we interpret as a pure difference). Those are neither covariance (whose unit of measure is the product of the units for the two variables) nor correlation (which is unitless).
Comment: Is it always in the 'same' direction? Also, does it apply for inverse relations too (i.e., as one goes up the other goes down)?
Comment: @nbro Covariance is the second central moment of a bivariate random variable.  And *that* returns us to the beginning: how would one convey this precise definition to the proverbial five-year-old?  As always, there's a trade-off between economy of expression and accuracy: when the audience doesn't have the concepts or language needed to understand something immediately, somehow you have to weave in an explanation of that background along with your description.  Doing it *right* requires some elaboration.  Usually there's no shortcut.
Comment: @nbro Consider any concrete example: suppose you know the covariance of variables $X$ and $Y$ is $1,$ for instance.  Even with the most generous understanding of "variable" and "go up," could you tell from that information alone how much $Y$ goes up when $X$ goes up by a given amount?  The answer is no: the *only* information it gives you is that $Y$ would tend to increase.  In this post Peter has confused the covariance with a regression coefficient (of which there are two, by the way, and they usually are different).
Comment: +1 for fitting it in a single, simple sentence, but isn't that correlation? I mean, I know greater cov=> greater corr, but with that sentence, I'd expect something like "80%" as an answer, which corresponds to corr=0.8. Doesn't cov also describe the variance within the data? ie. "Covariance is proportional to how much one variable goes up when the other goes up, and also proportional to the spread of the data in both variables", or something?
Comment: @nbro The only problem is that it's wrong.  (And not just a little bit: this is not a nit-pick.)
Comment: I think that that's what determines the sign of covariance...as per my posted 'answer'
Comment: @naught101 Covariance is in the original units, isn't it?
Answer: I am answering my own question, but I thought It'd be great for the people coming across this post to check out some of the explanations on this page.
I'm paraphrasing one of the very well articulated answers (by a user'Zhop'). I'm doing so in case if that site shuts down or the page gets taken down when someone eons from now accesses this post ;)

Covariance is a measure of how much two variables change together.
  Compare this to Variance, which is just the range over which one
  measure (or variable) varies.
In studying social patterns, you might hypothesize that wealthier
  people are likely to be more educated, so you'd try to see how closely
  measures of wealth and education stay together.  You would use a
  measure of covariance to determine this.
...
I'm not sure what you mean when you ask how does it apply to
  statistics. It is one measure taught in many stats classes.  Did you
  mean, when should you use it?
You use it when you want to see how much two or more variables change
  in relation to each other.
Think of people on a team.  Look at how they vary in geographic
  location compared to each other.  When the team is playing or
  practicing, the distance between individual members is very small and
  we would say they are in the same location.  And when their location
  changes, it changes for all individuals together (say, travelling on a
  bus to a game). In this situation, we would say they have a high level
  of covariance.  But when they aren't playing, then the covariance rate
  is likely to be pretty low, because they are all going to different
  places at different rates of speed.
So you can predict one team member's location, based on another team
  member's location when they are practicing or playing a game with a
  high degree of accuracy.  The covariance measurement would be close to
  1, I believe.  But when they are not practicing or playing, you would
  have a much smaller chance of predicting one person's location, based
  on a team member's location.   It would be close to zero, probably,
  although not zero, since sometimes team members will be friends, and
  might go places together on their own time.
However, if you randomly selected individuals in the United States,
  and tried to use one of them to predict the other's locations, you'd
  probably find the covariance was zero.  In other words, there is
  absolutely no relation between one randomly selected person's location
  in the US, and another's.

Adding another one (by 'CatofGrey') that helps augment the intuition:

In probability theory and statistics, covariance is the measure of how
  much two random variables vary together (as distinct from variance,
  which measures how much a single variable varies).
If two variables tend to vary together (that is, when one of them is
  above its expected value, then the other variable tends to be above
  its expected value too), then the covariance between the two variables
  will be positive. On the other hand, if one of them is above its
  expected value and the other variable tends to be below its expected
  value, then the covariance between the two variables will be negative.

These two together have made me understand covariance as I've never understood it before! Simply amazing!!
Comment: Although these descriptions are qualitatively suggestive, sadly they are incomplete: they neither distinguish covariance from correlation (the first description appears to confuse the two, in fact), nor do they bring out the fundamental assumption of *linear* co-variation.  Also, neither addresses the important aspect that covariance depends (linearly) on the scale of each variable.
Comment: @whuber - agreed! And hence haven't marked mine as the answer :) (not as yet ;)
Answer: I really like Whuber's answer, so I gathered some more resources. Covariance describes both how far the variables are spread out, and the nature of their relationship.
Covariance uses rectangles to describe how far away an observation is from the mean on a scatter graph:

If a rectangle has long sides and a high width or short sides and a short width, it provides evidence that the two variables move together.

If a rectangle has two sides that are relatively long for that variables, and two sides that are relatively short for the other variable, this observation provides evidence the variables do not move together very well.

If the rectangle is in the 2nd or 4th quadrant, then when one variable is greater than the mean, the other is less than the mean. An increase in one variable is associated with a decrease in the other.

I found a cool visualization of this at http://sciguides.com/guides/covariance/, It explains what covariance is if you just know the mean. link via the wayback machine
Comment: +1 Nice explanation (especially that introductory one-sentence summary). The link is interesting. Since it has no archive on the [Wayback machine](https://web.archive.org/web/http://creatorguides.com) it likely is new. Because it so closely parallels my (three-year-old) answer, right down to the choice of red for positive and blue for negative relationships, I suspect it is an (unattributed) derivative of the material on this site.
Comment: The "cool visualization" link has died... .
Comment: @MSIS That's not possible to figure out, because there are a very great number of possible distributions on the circle.  But if you are referring to the *uniform* distribution, there's nothing to calculate, because (as I recall remarking in your thread at https://stats.stackexchange.com/q/414365/919) the correlation coefficient must equal its own negative, *QED.*
Comment: @MSIS If "method" means "an appeal to symmetry," the answer is that it will work but the result depends on how $X$ is distributed.  As an example, if $X$ is  a random variable with a distribution symmetric about $0$ with finite fourth moment, then $X$ and $X^2$ must be uncorrelated. As a non-example, if $X$ has a distribution symmetric about $1,$ then nothing general can be said about the correlation of $X$ and $X^2:$ indeed, it could be any value between $-1$ and $1$ inclusive.
Comment: @MSIS Usually, in the absence of an explicit distribution, and almost always in a purely mathematical context, one assumes that a uniform distribution is meant.  In the case of a geometrical circle parameterized by an angle $\alpha,$ the basic events are of the form $a\lt\alpha\le b$ and their probabilities equal $((b-a) \operatorname{mod} 2\pi)/(2\pi).$
Comment: @whuber: Thanks again. I am trying to prove analytically that points on the circle, i.e., y = \pm (1-x^2)  are uncorrelated. For  that, I need the joint distribution (X,Y). Can you help me figure it out?
Comment: @whuber: Would this method work for other pairs such as (X,X^2)?
Comment: @whuber :  EDITThanks for your patience, a last one , please:  Do you know what joint distribution is assumed when the claim is made of the variables being uncorrelated? You were right, I was careless in not  scoping this assumption. It seems hard to figure out what the joint should be so that  \int xy f_{XY}(x,y) - \int x* \mu_X *\int y*\mu_Y =0.
Answer: Here's another attempt to explain covariance with a picture.  Every panel in the picture below contains 50 points simulated from a bivariate distribution with correlation between x & y of 0.8 and variances as shown in the row and column labels.  The covariance is shown in the lower-right corner of each panel.

Anyone interested in improving this...here's the R code:
<code>library(mvtnorm)

rowvars <- colvars <- c(10,20,30,40,50)

all <- NULL
for(i in 1:length(colvars)){
  colvar <- colvars[i]
  for(j in 1:length(rowvars)){
    set.seed(303)  # Put seed here to show same data in each panel
    rowvar <- rowvars[j]
    # Simulate 50 points, corr=0.8
    sig <- matrix(c(rowvar, .8*sqrt(rowvar)*sqrt(colvar), .8*sqrt(rowvar)*sqrt(colvar), colvar), nrow=2)
    yy <- rmvnorm(50, mean=c(0,0), sig)
    dati <- data.frame(i=i, j=j, colvar=colvar, rowvar=rowvar, covar=.8*sqrt(rowvar)*sqrt(colvar), yy)
    all <- rbind(all, dati)
  }
}
names(all) <- c('i','j','colvar','rowvar','covar','x','y')
all <- transform(all, colvar=factor(colvar), rowvar=factor(rowvar))
library(latticeExtra)
useOuterStrips(xyplot(y~x|colvar*rowvar, all, cov=all$covar,
                      panel=function(x,y,subscripts, cov,...){
                        panel.xyplot(x,y,...)
                        print(cor(x,y))
                        ltext(14,-12, round(cov[subscripts][1],0))
                      }))
</code>
Answer: I would simply explain correlation which is pretty intuitive.  I would say "Correlation measures the strength of relationship between two variables X and Y.  Correlation is between -1 and 1 and will be close to 1 in absolute value when the relationship is strong.  Covariance is just the correlation multiplied by the standard deviations of the two variables.  So while correlation is dimensionless, covariance is in the product of the units for variable X and variable Y.
Comment: This seems inadequate because there is no mention of linearity. X and Y could have a strong quadratic relationship but have a correlation of zero.
Answer: Variance is the degree by which a random vairable changes with respect to its expected value Owing to the stochastic nature of be underlying process the random variable represents.
Covariance is the degree by which two different random variables change with respect to each other. This could happen when random variables are driven by the same underlying process, or derivatives thereof. Either processes represented by these random variables are affecting each other, or it's the same process but one of the random variables is derived from the other.
Answer: Two variables that would have a high positive covariance (correlation) would be the number of people in a room, and the number of fingers that are in the room.  (As the number of people increases, we expect the number of fingers to increase as well.)
Something that might have a negative covariance (correlation) would be a person's age, and the number of hair follicles on their head. Or, the number of zits on a person's face (in a certain age group), and how many dates they have in a week.  We expect people with more years to have less hair, and people with more acne to have less dates.. These are negatively correlated.
Comment: Covariance is not necessarily interchangeable with correlation - the former is very unit dependent. Correlation is a number between -1 and 1 a unit-less scalar representing the 'strength' of the covariance IMO and that's not clear from your answer
Comment: Downvoted as the answer implies that covariance and correlation can be used interchangeably.
Answer: Covariance is a statistical measure that describes the relationship between two variables. If two variables have a positive covariance, it means that they tend to increase or decrease together. If they have a negative covariance, it means that they tend to move in opposite directions. If they have a covariance of zero, it means that they are independent and do not affect each other.
To explain covariance to someone who understands only the mean, you could start by explaining that the mean is a measure of the central tendency of a distribution. The mean tells you the average value of a set of numbers.
Covariance, on the other hand, measures how two variables vary together. It tells you whether they tend to increase or decrease together, or whether they move in opposite directions.
For example, suppose you have two sets of numbers, X and Y. The mean of X tells you the average value of X, and the mean of Y tells you the average value of Y. If the covariance between X and Y is positive, it means that when X is above its mean, Y tends to be above its mean as well. And when X is below its mean, Y tends to be below its mean as well. If the covariance is negative, it means that when X is above its mean, Y tends to be below its mean, and vice versa. If the covariance is zero, it means that there is no relationship between X and Y.
So, in summary, covariance measures the tendency of two variables to vary together, and can be positive, negative, or zero.


VLAN security compared to DMZ

Question: I found this question very illuminating about DMZs and when to place a server in one.
We're re-organizing our internal company network (keeping the same external IPs and domains), our mainly Windows servers (we use WinAD heavily) will be kept on the LAN with firewalls and port forwarding to direct external traffic.
What are the security (dis)advantages setting a server (example: email) up on a different VLAN  to the rest of the internal network rather than inside a DMZ?
Answer: That's a bit of an apples and oranges comparison.  A DMZ is a separate network segment for systems with a greater risk of compromise; a vlan is a mechanism for achieving logical separation between different logical networks on the same physical network.
The comparison you probably want to make instead is this one:  Should I implement my DMZ through physical separation by using separate network infrastructure, or through logical separation on the same network infrastructure?

With physical separation, the main barrier is cost; you'll be investing in dedicated network equipment for what sounds like a small number of DMZ systems.  There's also extra management time involved in setting up and maintaining that infrastructure.
With vlan separation, you'll be essentially building the same logical infrastructure as with the physical separation; a dedicated vlan with its own subnet, the device doing the routing between the subnets will apply access controls, etc.
However, the concern is security; sharing the same physical infrastructure increases the number of potential attack surfaces for an attacker who has compromised a DMZ device to try to access the non-DMZ network.
When using just the logical separation, vlan hopping attacks, as well as direct remote exploits against the network devices accessible to the DMZ (but serving both networks) are potential risks, as well as a greater risk of a misconfiguration in a single device compromising the barrier between the networks.

VLAN security compared to DMZ