Voronoi cells are off-scale in a force-directed layout

Question: I have a collapsible force-directed layout, which I referenced from here.
I have modified the code where I have added Voronoi cells behind each node in the graph. Currently, it looks like it's working because I can see that the Voronoi cells appear/disappear based on the collapsed state. However, it is off-scaled.
I'm thinking it has to do with this specific line
node.select("path")
    .data(voronoi.polygons(nodes))
    .attr("d", function(d) { return d == null ? null : "M" + d.join("L") + "Z"; });

But I'm a bit confused as to what to do.
Could anyone provide pointers as to why the voronoi-cells are off-scaled? And how I can make sure they're centered with the nodes and scaled properly?

Current code: https://jsfiddle.net/oc8xsm3L/
Answer: The problem lies here:
node.attr('transform', function(d) { return `translate(${d.x}, ${d.y})`; });

As you can see, you're applying a translate to the node groups. That, per se, is not a problem. The problem is that those same groups contain the Voronoi paths. Therefore, when you change the Voronoi coordinates later...
node.select("path")
    .data(voronoi.polygons(nodes))
    .attr("d", function(d) { return d == null ? null : "M" + d.join("L") + "Z";
});

... you're applying the coordinates on a path inside a group that was already translated.
Solution: there are many different solutions, like creating a different group for the Voronoi paths. However, the simplest solution here is applying the translate to the circles, not to the containing groups:
node.select("circle").attr('transform', function(d) {
    return `translate(${d.x}, ${d.y})`;
});

Here is your code with that change only:

const svg = d3.select('#voronoiSvg');
const transform = d3.zoomIdentity;
const width = 600;
const height = 300;
let node, link, simulation, root, voronoi, nodes;
let i = 0;

function loadVoronoi() {
  const data = {
    "name": "flare",
    "children": [{
      "name": "analytics",
      "children": [{
          "name": "cluster",
          "children": [{
              "name": "AgglomerativeCluster",
              "size": 3938
            },
            {
              "name": "CommunityStructure",
              "size": 3812
            },
            {
              "name": "HierarchicalCluster",
              "size": 6714
            },
            {
              "name": "MergeEdge",
              "size": 743
            }
          ]
        },
        {
          "name": "graph",
          "children": [{
              "name": "BetweennessCentrality",
              "size": 3534
            },
            {
              "name": "LinkDistance",
              "size": 5731
            },
            {
              "name": "MaxFlowMinCut",
              "size": 7840
            },
            {
              "name": "ShortestPaths",
              "size": 5914
            },
            {
              "name": "SpanningTree",
              "size": 3416
            }
          ]
        },
        {
          "name": "optimization",
          "children": [{
            "name": "AspectRatioBanker",
            "size": 7074
          }]
        }
      ]
    }]
  }
  root = d3.hierarchy(data);

  svg
    .attr("width", width)
    .attr("height", height)
    .on('dblclick.zoom', null);

  simulation = d3.forceSimulation()
    .force('link', d3.forceLink().id(function(d) {
      return d.id;
    }))
    .force('charge', d3.forceManyBody().strength(-10).distanceMax(300))
    .force('center', d3.forceCenter(width / 2, height / 2))
    .alphaTarget(1)
    .on('tick', ticked);

  voronoi = d3.voronoi()
    .x(function(d) {
      return d.x;
    })
    .y(function(d) {
      return d.y;
    })
    .extent([
      [-1, 1],
      [width + 1, height + 1]
    ]);

  update(root);
}

function update(root) {
  nodes = flatten(root);
  const links = root.links();

  //links
  link = svg.selectAll('.link')
    .data(links, function(d) {
      return d.target.id;
    });
  link.exit().remove();
  const linkEnter = link.enter()
    .append('line')
    .attr('class', 'link')
    .style('stroke', '#132')
    .style('opacity', '1')
    .style('stroke-width', 2);
  link = linkEnter.merge(link);

  //nodes
  node = svg.selectAll('.node')
    .data(nodes, function(d) {
      return d.id;
    });
  node.exit().remove();
  const nodeEnter = node.enter()
    .append('g')
    .attr('class', 'node')
    .attr('stroke', '#666')
    .attr('stroke-width', 2)
    .style('fill', color)
    .style('opacity', 1)
    .on('click', clicked);
  nodeEnter.append('circle')
    .attr("r", 8)
    .style('text-anchor', function(d) {
      return d.children ? 'end' : 'start';
    })
    .text(function(d) {
      return d.data.name;
    });
  nodeEnter.append("path").attr("class", "path");
  nodeEnter.call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));
  node = nodeEnter.merge(node);

  simulation.nodes(nodes);
  simulation.force('link').links(links);
  // simulation.alpha(1).restart();
}

function color(d) {
  return d._children ? "#51A1DC" // collapsed package
    :
    d.children ? "#51A1DC" // expanded package
    :
    "#F94B4C"; // leaf node
}

function radius(d) {
  return d._children ? 8 :
    d.children ? 8 :
    4;
}

function ticked() {
  link
    .attr('x1', function(d) {
      return d.source.x;
    })
    .attr('y1', function(d) {
      return d.source.y;
    })
    .attr('x2', function(d) {
      return d.target.x;
    })
    .attr('y2', function(d) {
      return d.target.y;
    });

  node.select("circle").attr('transform', function(d) {
    return `translate(${d.x}, ${d.y})`;
  });

  node.select("path")
    .data(voronoi.polygons(nodes))
    .attr("d", function(d) {
      return d == null ? null : "M" + d.join("L") + "Z";
    });
}

function clicked(d) {
  if (!d3.event.defaultPrevented) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }

    console.log("clicked");
    update(root);
  }
}

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

function flatten(root) {
  const nodes = [];

  function recurse(node) {
    if (node.children) node.children.forEach(recurse);
    if (!node.id) node.id = ++i;
    else
      ++i;
    nodes.push(node);
  }
  recurse(root);
  return nodes;
}

function zoomed() {
  svg.attr('transform', d3.event.transform);
}

loadVoronoi();
.node circle {
  cursor: pointer;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
  pointer-events: none;
  text-anchor: middle;
}

line.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

path {
  pointer-events: all;
  fill: none;
  stroke: #666;
  stroke-opacity: 0.2;
}

.active path {
  fill: #111;
  opacity: 0.05;
}

svg {
  border: 1px solid #888;
}

  <svg id="voronoiSvg"></svg>

Comment: Thank you! Thank you for providing the insight! :)


putting paragraph tags on content paragraphs

Question: Im trying to put paragraph text around the paragraphs. This code pulls out the blockquotes from my Wordpress post and outputs everything else
html
        <?php
            $block2 = get_the_content();
            $block2 = preg_replace('~
([\s\S]+?)
~', '', $block2);
            echo '
'.$block2.'
';
        ?>

But it only puts
 tags around the fist paragraph and not the others
Comment: Have your tried $block2=preg_replace('blockquote','p',$block2);
Comment: That throws up an error
Comment: How do you define a paragraph? Can you show some actual examples? @jeff's example I think would use `str_replace`, not `preg_replace`.
Comment: Basically all text in a worpress post I want to put in a pargraph. I want to remove the blockquote in the content (so it can be put somewhere else) and want to put all the text in paragraph tags. The images already post with img tags and the headers with h tags
Comment: I mean paragraphs. The text in the posts in paragraphs (when the ser hits enter creating a new paragraph in the editor)
Answer: If I've understood this correctly, you could try splitting $block2 by newlines, looping through the resulting array and wrapping each element of the array in
 tags as you have done.
Currently, your code wraps the entire content of $block2 in
 tags, where I assume you wanted it to wrap the sections separated by newlines.
Example (I don't remember the exact syntax for PHP - sorry):
$split_block = split($block2, '\n');
for ($i in $split_block) {
    $split_block[$i] = '
'.$split_block[$i].'
';
}
echo $split_block;


Why do EDM musicians often create an intro that is 15/30/45/60/120 seconds long?

Question: Not all tracks have intros, and usually those are extended mixes that have them (sometimes can be original mixes and remixes). However, I notice that often their intros are 15/30/45/60/120 seconds long, or taken in minutes these numbers are 1/4, 1/2, 3/4, 1, 2 minutes.
So, is there some kind of rule? Or is simply their inner OCD and these numbers are some kind of key numbers in music?
A few examples (links to beatport):
D.O.D - Glow (Extended Mix)
Lush & Simon - Callin' (Extended Mix)
Apster - Photobomb (Original Mix)
Swanky Tunes - Fire In Our Hearts feat. C. Todd Nielsen (Arston Remix)
For tracks that I looked their BPM was in 124-128 range, but I guess the actual range is wider than that. As you can note they are of slightly different genres and these were only 4 examples.
Comment: It could be related to the way deejays discover new tracks. Maybe there's an online platform that lets you check out tracks by skipping through them in steps of 15 seconds or something, and people have started to build their intros accordingly?
Comment: Even number of whole measures time even BPM that is divisible by 3 would tend to cause all of the parts of a piece of music to be in lengths like these.
Comment: @ToddWilcox Hm, there are 128 BPM tracks and there are 126 BPM tracks with different measures.
Comment: @YourUncleBob Well, Soundcloud has 5 seconds interval. But this explanation seems to be the most logical.
Comment: I think an in-depth examination might find that these songs are usually not *exactly* 16 seconds long or anything (16.43 seconds is not 16 seconds). But I don't know, I haven't done that study.
Comment: Do know if it's my browser, but the player for the links provided _doesn't have a second counter_ that makes it hard to talk about the exact second count of the intros.
Answer: 8 measures of a song in 4/4 at 128bpm, will take 15 seconds. Longer intros are multiples of this (16 measures => 30 seconds, 24 measure => 45 seconds, etc).
There aren't any rules per se, but there is a greater sense of completion when multiples of 4 or 8 are used for measures (as well as being a part of the genre).
Comment: I added some examples. Can't say that I don't notice 4 seconds margin (64 vs. 60).
Answer: When sequencers first came into use, the default tempo of a new song was generally q=120.   So a whole LOT of music got produced at that speed. I mean, to change the tempo you'd have to look in the manual, and that's, like, heavy stuff man!  (Music producers talked like that in the 80s.)
With 4 beats to the bar (another default setting) that made a bar clock out at 2 seconds, an 8-bar section at 16.
Now, if you'd said EDM sections were typically 16, 32, 48 or 64 seconds long, I'd have to wonder if exactly the same thing was happening!
(Where are these 15s, 30s etc. sections in the examples you posted?
Answer: To understand this question we have to combine what's been said by Laurence and nivlac.
1. The BPM of a typical EDM track
Will be around 120 bpm. This may be for historical reasons, as per Laurence's answer...

When sequencers first came into use, the default tempo of a new song was generally q=120. So a whole LOT of music got produced at that speed.

...but it's also true that 120 is in general a BPM at which is nice and natural to walk, move and dance! Exactly what people want to do when listening to EDM music. From this Quora question about why is 120 BPM such a common time signature:

[120 BMP is] also just a nice speed at which to get people moving quickly and with purpose. 120 bpm is standard American military march tempo [...]

And to back this statement up the Beat Explorer's Dance Music Guide comes to the rescue

Electro House usually sits somewhere between 125-135bpm and tracks are arranged in a way that gives a large focus on the climax or drop. This usually contains a heavy bassline, and frequently includes melodic elements to help establish cohesion within the track.

Which brings us to the second point:
2. The sense of completeness
Not only do multiples of 4 give us a sense of completeness, but having long intros and long tails makes it easy and predictable for DJ's to mix tracks on the fly, knowing when to switch from one track to the other.
Try it yourself: listen to a long EDM mix and count, you'll see that in most cases you'll be able to anticipate the drops, the cuepoints and the changes! Doing rationally so will give you a sense of accomplishment, which is the same amusement and accomplishment that gets people hyped when they dance to it.
Answer:
So, is there some kind of rule? Or is simply their inner OCD and these numbers are some kind of key numbers in music?

You're kind of on the right track. I think it may have been said before, but the thing with EDM music is, repetition is key, but not for repetition's sake.
One of the more conventional things about pop music that carries over to (most, not all) EDM music is common time. Common time is defined as 4 beats in a measure. The number 4 here is then key for this.
Since EDM features the number 4 here a lot, that usually means musical phrases are likely in a multiple of 4. To explain a phrase, it's essentially a group of measures that "speak" completely. So, if a phrase is in multiples of 4, it can take 4, 8, 16, etc. measures for a phrase.
It's hard to think that in EDM music is in phrases, because oftentimes, the space at the intro of the track is filled with mostly a beat loop and sound effects, and maybe some introductory bass line that repeats over and over. However, the feel that pushes the music onward is this division of phrasing. You'll notice in these longer intros, new elements get introduced every new phrase. What might start with just a kick drum and some hi-hats may be joined by a snare or clap a phrase later, and then a bass line a phrase later, etc.
As far as how long it takes to "complete" an intro, it's relative. The length is usually destined by the bpm against the length of the phrase. A phrase consisting of 4 measures of 4 beats each, at a tempo (read, speed) of 120bpm (meaning, 2 beats a second) is 8 seconds. A phrase of 8 measures like this is 16 seconds, etc.
As far as history, there are two things here. One is what tempos were used for EDM. Modern EDM derives from a variety of styles of electronic music, but the general setting in many sequencers was 120bpm. It is always adjustable, and in the case of EDM, it's mostly around 120bpm-130bpm. Other styles closely related, such as Trance, ues higher bpms, as low as 128bpm to about as high as 156bpm. But, intros last as long as they do because they are buffer for a DJ to mix seamlessly from one track to the next. As the bpm of a track can be altered by how fast a vinyl is spinning, it is the necessary time for a DJ to find a suitable revolution speed on the table, adjust the vinyl until one track meshes well into the next, and align the phrasing between the two tracks, before panning the volume from one turntable to the next. This time is meant to link the outro of one track to the intro of another track, essentially making it so that the music doesn't stop and flows well.


Naming notes in non 12-TET tunings?

Question: Note nomenclature is well-defined for 12-tone equal tempered tunings, e.g. English notation vs German notation, etc.
My question is: how is it possible to reliably name notes when using different tunings, e.g. 24-TET or Pythagorean? Does one use the same note names as above, plus some tuning-specific accidental to indicate the difference?
Comment: People who play non-fretted stringed instruments, like violins, will play certain notes in certain keys a little sharp or flat in comparison to 12tet notes - but will still refer to them by the letter names, sharps and flats.
Comment: I think "equal temperament" may be a red herring here - standard note naming is not restricted to equal temperament contexts.
Comment: Just for information as I don't know enough to write a good answer - but I have noticed proposed naming schemes for [quarter tones](https://en.wikipedia.org/wiki/Quarter_tone) etc. (This Wikipedia page has a list.) Names such as "neutral sixth", between a major & minor sixth.
Comment: @Tim i wonder if what's meant is "note naming where we're not using some flavour of the normal 12-tone scale" - not sure how to pin that down better though!
Comment: Is there a specific scale you are trying to notate?
Comment: I'm trying to design a software library with the right relationships between tunings, scales and nomenclatures.
Answer: The western standard terminology of note names has very little to do with 12-edo tuning, in fact the plentitude of enharmonic clashes demonstrates that these naming schemes are actually a lot finer than 12-edo. If you apply it to 12-edo it is, in fact, not well defined anymore!
Those note names, like most of the otherwise body of theory, are all about diatonic scales. Since Pythagorean is on of the two classical diatonic tunings (though the other one is arguably more relevant), it does naturally describe this scale just fine:

 1/1   9/8  81/64 4/3   3/2  27/16 243/128
260.7  293⅓  330  347.7 391.1 440   495
  C     D     E    F     G     A     B

The names can by extension be used in any temperament that approximates diatonic scales. This includes, sure enough, 12-edo – like any other meantone temperament. In particular, it works for more accurate 5-limit equal temperaments like 34-edo, and also 31-edo (though that is rather more interesting as a 7-limit tuning). You will in each case get a slightly different frequency assigned to most notes, but they're still "conceptually the same notes".
You won't necessarily get a name for every note in the temperament this way. 24-edo can also approximate diatonic scales... because it contains 12-edo as a subset. So, the quarter-tones don't get names this way. The "microtonal notes" do get names assigned in e.g. 31-edo though: unlike in 12-edo, enharmonicity doesn't "wrap around" the circle of fifths already after six sharp signs, but only after 16 of them, or 17 in 34-edo. You
https://en.wikipedia.org/w/index.php?title=31_equal_temperament&oldid=740902751#Scale_diagram
Of course, there's a lot of ambiguity if you consider multiple different temperaments and stray through many different diatonic keys. In this case, the western naming scheme just doesn't work very well anymore. I'm afraid there is no single universally accepted convention that adresses this problem. You can of course always just specify the scale and then enumerate the scale degrees, but that's not particularly insightful – essentially you're writing guitar tabs at this point.
More useful are naming schemes like Ben Johnston uses, based on higher-limit just intonation. You can again adapt these to any temperament that approximates the just limit.
Comment: A good read on how varied naming pitches can get is [Dolmetsch's pitch, temperament & timbre lesson](http://www.dolmetsch.com/musictheory27.htm).
Comment: Thanks. My takeaway from your answer is that there isn't a naming system that works across tunings and across cultures, and that the best practice is to use diatonic note names whenever possible (i.e. when the notes of a scale fully or approximately match the diatonic ones).

Naming notes in non 12-TET tunings?


is db_insert secure?

Question: I'm using the Drupal 7 method db_insert, to insert data into a custom table in the Drupal database. I've read that this is the prefered way, however I've walked through the code and doco and I can't see anywhere which parses the values, or tells me that these values are safe.
Some of the values are coming from the user so I need to check against SQL Injection attacks.
This is the example I was reading, where the Drupal 6 parses the values, and the drupal 7 version does not.
<?php
// Drupal 6 version
db_query('INSERT INTO {vchess_games}
   (gid, timestamps, white, black, state, board_white, board_black) ' . "VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
   $gid, $timestamps, $game['white'], $game['black'], $state, $board_white, $board_black);

// Drupal 7 version
db_insert('vchess_games')
  ->fields(array(
    'gid' => $gid,
    'timestamps' => $timestamps,
    'white' => $game['white'],
    'black' => $game['black'],
    'state' => $state,
    'board_white' => $board_white,
    'board_black' => $board_black
  ))
  ->execute();
?>

Answer: The Drupal database layer wraps around PDO and uses prepared statements, so yes, the insert statements are sanitised and protected from SQL injection attacks.
This quote from the Prepared Statements docs says it best:

The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

The same is true for all of the database functions in Drupal 7 (db_select, db_delete, etc.). The only one that is still potentially insecure is db_query() which will execute any arbitrary string you pass to it. Even with db_query(), though, you can pass in parameters so your query is safe.
The Database abstraction layer docs have some more information.

is db_insert secure?


Is there any way to write SQL query to extract data from a postmeta table in wordpress?

Question: I have a directory website running on wordpress. I have a lot the the business listings stored in the postmeta table. I am tasked to retrieve that data to be exported in csv file using either SQL queries or other means.
Is there way to write SQL queries to retrieve the data inside the postmeta table in wordpress database?
Answer: There is rarely a need to directly access the database in WordPress, you can get a post meta with the native get_post_meta() function which retrieves a post meta field for the given post ID
(See here: https://developer.wordpress.org/reference/functions/get_post_meta/)
Example:
Get data for all keys (default):
<?php $meta = get_post_meta($post_id); ?>

Get post meta for a single key:
<?php $key_1 = get_post_meta($post_id, 'key_1'); ?>

You might need to filter out unwanted meta keys starting with an underscore.


Maximize pixels - Android Browserd Address Bar

Question: How big, in pixels is the Android web-browsers addressbar? (not counting the status bar).
I can't seem to find any information on this at all.
UPDATE
I'm mentioning the standard browser that ship with the Nexus. And there should be three sizes (four counting xdpi). Do anyone know the pixel size.
Answer: It will vary by Android version, by screen size/density, and by browser (standard, manufacturer-modified, third-party like Mozilla). Hence, there is no single answer.
Comment: @Joakim Engstrom: Please read http://developer.android.com/guide/webapps/index.html and http://developer.android.com/guide/webapps/targeting.html and http://developer.android.com/guide/webapps/best-practices.html. You will notice that nowhere in there do they discuss the address bar. Please follow their recommendations for designing your Web site. Do not make any assumptions regarding the address bar, which may or may not even be visible at any given point (usually it's not visible, unless the user is attempting to type into it). Also, there are multiple "Nexus" devices.
Comment: @Joakim Engstrom: "both is hdpi screens and should therofore be the same pixel size designwise" -- yes, they are both `hdpi`. That does not mean they will both have the same address bar height. They might, since they are both running Android 2.3 and are largely "Google Experience devices", so device manufacturers may not have messed around with them. I wish that the Android SDK Hierarchy Viewer worked with devices, as that would be the easiest way for you to get your height. As it is, I'd just take a screenshot using DDMS and measure it in your favorite image editor.
Comment: Even though I still would like to know the height of the pixels this is an acceptable answer since I should not be coding a webpage based on pixels when coding a website for mobile devices. But when a designer wants to know how many pixels the adressbar is in I thought it would be an easy answer on the Nexus:es (both is hdpi screens and should therofore be the same pixel size designwise). But thanks anyway for your answer.
Answer: This is device dependent (http://developer.android.com/guide/practices/screens_support.html)- look for information for accommodating different resolutions.
Comment: But I'm not building a native android application. I'm building a website.
Comment: But same answer - if you are trying to emulate the android web browser, it will vary from device to device
Answer: You can calculate this yourself if you use the emulator and set up devices with various densities and no scaling.


How do experienced pianists sight-read chords?

Question: I enjoy sight reading, since it lets me "play" the piano without having to spend hours going over the same passage to get it right.  However, I'm still progressing and have difficulty reading pieces with chords that have 3 or more notes, especially if that piece has a significant number of chord changes to go with it.
At the moment, in order to read a chord I will have to look at all of the individual notes and put them together unlike in lead sheets where the chord symbol is given.  This necessarily takes more time - it essentially becomes an exercise in reading 3 notes, rather than just 1 or 2.  Does an experience pianist see a chord and just think "A7, 2nd inversion", without worrying about the notes, or are they reading the notes, too, just faster?
Comment: The answer's in your question - experience. Recognition of known patterns. Same as reading words.
Answer: Look at the shape of the complete chord, not the individual notes. For example, triads in root position and 1st and 2nd inversion have different patterns of thirds and fourths between the notes.
This also helps when some or all the notes are on leger lines. You only need to "name" the note that is nearest the staff (with the fewest leger lines) and recognise the others from the chord shape.
For example you should be able to see that the example is a "4-note root position C chord" and "an octave of C's" without having to figure out the pitch of the extreme notes that are on 5 leger lines. The C's on two leger lines should be familiar enough to be easy to read.
The same ideas work for reading the intervals between successive notes in the score, of course.

Personally I don't consciously name the chord as "A7 second inversion" or whatever. The objective is to play it, not name it! But of course if you are familiar with the style or genre of the music, you will begin to recognize harmonic progressions of several chords that occur often, rather than each chord in isolation.
Although it's not specifically about "reading chords," your statement

I will have to look at all of the individual notes and put them
  together. This necessarily takes more time

might suggest a more basic problem. You need to read ahead of the notes that actually playing. How far ahead depends on how complex the music is and how good a reader you are, but for simple music it might be several bars ahead, not just one or two notes. That way, if you do hit a "speed bump", your brain has time to get over it before your fingers run out of notes to play.
One way to practice that is to sight-read a passage of music without playing it, close your eyes, and play it "from memory". Don't worry if you can only do this for passages of only one or two notes at first - you will improve with practice.
Comment: This is what I do - not that I sight read well. I look for the lowest note and then the shape, place my hand in the shape, align it to the lowest note, apply the key signature, check for accidentals, and play. Not exactly like that and mostly subconscious, but definitely the shape more than picking apart the exact notes.
Comment: +1 for the reading ahead part, if you aren't a step or two ahead then you are already behind
Comment: For me, the process with that right hand chord is basically: 1. The bottom note (high C). 2.  Black keys? None. 3. Shape? The bottom three notes are a very simple pattern, which my hand can "feel" as soon as I see it under my thumb and first two fingers. 4. A moment later, I can feel the little finger stretching up - I don't even concsciously know that it's C, but I know it's one more note between the G and the note above it than the note below it.
Comment: I like that you point out you are not *naming* the chord mentally, but just playing it. The *relative* relations are the point not the absolute names. For shapes on the staff I also note that 3rds and 5ths will be space & space or line & line, while 4ths and 6ths will mix space & line or line & space. Again, the relative relation of spaces and lines rather than absolute names like pitches F & A or F & D.
Comment: The shape idea works to a point, but when there are accidentals, it isn't quite as easy.
Comment: **You should name the chord** It helps be able to spot a pattern and key.  But, I'll admit, I'm still trying to improve
Answer: Many different ways! Some players who are extremely good readers will simply look at the dots and their fingers will automatically land on the correct keys. Others, like myself, will be expecting a choice of maybe 3 or 4 chords in a sequence, so will second guess what they will be.Then looking at the lowest note, working out rapidly what the inversion is, or might be. Not always good guesses, I might add. With the chord symbols above the staves, life is often easier, except when the name doesn't necessarily reflect the actual chord - more often in hand-written parts.
If it's a piece that's been heard before, I find I have a mental map of the chord sequence, sometimes vague, sometimes not bad, and that helps, as the left hand goes onto a kind of autopilot, and sometimes notes get left out, or an octave copy put in, none of which is too bad for the finished article.
What will eventually happen for you is that in certain keys, you'll recognise clusters of dots, which will immediately make your fingers go to those chords. Rather like we recognise the shapes of long words, and don't have to sound out each phoneme or syllable. Simple example in A (bass clef)- 4 dots, each on one of the spaces = Amaj7. In G - dots on bottom 4 lines = Gmaj7.
Just spoken to my brother-in-law, who's a good sightreader, and the question stumped him. Doesn't have a clue what he does...
Comment: It's much harder to guess chords that are not straightforward. Sorry for not clarifying!
Comment: It's way too early to choose this as the accepted answer! Others will have better ones, I expect!
Comment: Perhaps, although I do like your answer - there are multiple ways, so it seems likely that I'll develop my own style.  Also, it feels rude to unaccept an answer :-P
Comment: Although this technique may work for "simpler" classical music and pop, it won't work for contemporary classical or some 20th-century music (anything with more than simple chords - like dualtonaility, atonality, etc.)
Comment: @AnselChang: why is that?  I typically play through classical through Romantic pieces, but it's still interesting to know
Comment: "Doesn't have a clue what he does..." I have a hard time rationalizing what I do, as well. Sight reading in front of a paying audience where "there is no fail" (which happens more often that you might think, accompanying singers!) the overall process is often something like (1) Read the notes (2) Mentally re-arrange the music into something you can actually get your fingers round (3) Play it. And do that in real time with no mistakes, even when transposing into a different key at sight at the same time!
Comment: @AnselChang for a keyboard player, there are only a few hundred *possible* chord shapes at the most. If you play enough "contemporary classical" music, eventually you won't find any that you haven't seen before.
Answer: Other answers have hinted at what I think is the crucial component, but I'm not sure it has been articulated exactly.
I play piano mostly by ear and from lead sheets (e.g., | Cmin | F7 | Bb maj | and so on). While I can read sheet music, my sight-reading is terrible. I posed this same question once to someone who was a very good sight reader and he didn't know how he did it. If, tomorrow, I decided I wanted to become outstanding at sight-reading chords, I would focus all of my energy on two things: (1) immediately recognizing the bottommost (or topmost) note in the chord, and (2) immediately recognizing the intervals in the chord. Skill (1) speaks for itself, and you can practice this by simply pointing to random staff lines and naming the note. Skill (2) is a bit more complex. The best place to start is by imagining we're in the key of C major.
For instance, when I look at Example 1, I want to instantly know that I'm playing adjacent notes in the C major scale:

And when I look at each chords shown in example 2, I want to instantly know that the notes are not right next to each other in the scale, but rather are separated by one scale tone.
Once I could identify and play any interval in C major, I would practice them all in G major, and D major, and every other key. Then I would start practicing three-note chords. Again, when practicing three-note chords, I'm still trying to cultivate my ability to see the shape of the chord and immediately recognize how many scale tones separate each note. For instance, when I look at Example 3, I'm thinking: (1) bottom note is a C; (2) second note is separated by one scale tone from the bottom note; (3) third note is separated by one scale tone from the middle note.
Ultimately, the goal is to do even less thinking than what I've described. I want to be automatic, such that I can see the shape of a chord on the page and immediately recall a particular finger/hand shape that I've practiced (e.g., for that chord I have 1 scale tone separating each finger). So I practice these until I am automatic and don't have to think at all. But I organize my practice to be systematic so that the work and learning that I do in C major supports my work and learning in G major, F# major, and all of the other keys.
Once I could recognize three-note and four-note chords, I would practice chords with sharps and flats that take me outside the scale I'm working in. Adjusting a finger up/down a half step based on the accidental is probably the third distinct skill for sight-reading chords. I tend to think that this third skill (adjusting for accidentals) would largely come naturally after doing rigorous practice on the first two. But some additional practice is probably needed.
So I think the crucial skills are (1) pairing intervals on the page to shapes of the hand, and (2) knowing where to put these shapes on the piano by recognizing the bottommost (or topmost) note in the chord.
Regarding practicing theory, I know people who are spectacular sight-readers but know nothing of the theory. And even though I might know that a chord is A7/C#, I'm not accessing this knowledge when I look at the notes on the page and try to sight-read them. Thinking about the theory would slow me down. The goal in sight-reading is to become automatic and to require no thought at all, and the only way to achieve this is through practice. Making the practice systematic can make the learning process more efficient, I think.
Regarding "looking ahead," I don't think this is something to focus on, think about, or even attempt in the beginning when at your current stage. You don't have the problem that you're dwelling too long on a chord. In other words, your problem isn't that you're reading a chord and then continuing to look at it after you've figured out what it is. If you try to look ahead to the second chord before you've successfully figured out the first chord, you'll fail and quickly become discouraged (at least, if you're anything like me!). It only makes sense to focus on "looking ahead" in the music if you already have the ability to see a chord and quickly find the correct finger/hand shape. Once you possess that skill, you can then turn to guaranteeing that you're not looking longer than necessary at any one chord.
Answer: It is often a good idea to have a quick look at the keys and the composer of the piece before actually playing it. For example, if Mozart wrote a piece in D minor, you can usually expect G minor and A major (A7 major as well) chords to appear. With this in mind, you will probably find it more easy to sight-read pieces with chords, if you already have some feeling of what notes should be in the chords according to harmony theory. This will of course become more difficult when you want to play Rachmaninoff or something like that, as they use more complicated chords.
A more general answer is probably that you can exercise it just as many other things. Just go ahead and take some pieces you don't know yet and give it a try.
Answer: I have a novel, new angle for you to consider!  Lately, I've been applying a technique that I learned at a speed reading class for reading printed words.  That is, to go pretty fast, and try to get whatever little comprehension you can, as you rapidly move your eye through the text.  Then, go back and read the same text over again at the same quick pace, moving your eyes again quickly, and you will find that you comprehend a little bit more.  After about 6 or 7 passes you will comprehend most of it.  This doesn't take very long, and let me explain how that works with regard to sheet music -  I'll hammer out a piece at the appropriate tempo, trying to get, the rhythmic figures right, even if I'm "slopping" the notes.  The second time, the rhythmic figures are usually even more accurate, and maybe I'll get a few more notes, (including chord clusters) right!  (I pretend, while doing this, that I'm an expert sightreader, like the Broadway rehearsal pianists in New York or something...those guys can play a piece at tempo without ever having seen it before.)  I make a game of it!  If I really want to buckle down and learn the piece thoroughly, I find it much easier after making these rapid fire, attempts.  Of course, the sloppiness sounds awful, so it is best to practice this on a digital with headphones!
Answer: I asked a friend of mine who is a professional pianist and a very good sight reader this question. It's clear to me that she is reading at a much higher level of abstraction than you or I are. She doesn't read individual notes or even individual chords; she reads several bars of music and sees the rhythms, melodies, and harmonies (and even the dynamics!), not the notes.
This isn't as surprising as it might appear. When we're driving, we take in a vast amount of information about the road ahead without even thinking about it. We see a wobbly elderly cyclist, not wheels, pedals, and grey hair. For that matter, how do we know that we're listening to Vivaldi? It's not by building up from individual notes, it's from recognising familiar patterns.
I've no idea whether understanding this will help you or me to become better sight-readers!
I do know that over the years, my vocal sight-reading has slowly improved to a point where I can be fairly comfortable picking out my part in simple hymn tunes and the like. I don't really know how I do it, but I assume it's just practice and repetition. Pattern recognition is all about practice and experience.


Replace element in an unordered map

Question: I have a unordered map with an enum in key and a shared_ptr in content.
When I initialize my map, I use emplace like this :
this->_menu.emplace(BINDINGS, std::shared_ptr<AMenu>(new BindingMenu("Player 1"));

But I would like to know if I can replace (at the same place), with another BindingMenu object :
std::shared_ptr<AMenu>(new BindingMenu("Player 2")

Thanks
Comment: `this->_menu[BINDINGS] = std::make_shared("Player 2");` ?
Comment: Have you tried?
Comment: Don't begin identifiers with underscores. If you want to distinguish members from locals or parameters then use `m_menu` or `mMenu`. Use of `this` is optional except when accessing members of a templated base class. Use `std::make_shared("Player 2");` to create a `std::shared_ptr`
Comment: Why it's better with "m" before ? for "member" ?
Comment: Yes, "m" is for "member". You don't have to prepend "m" but it's a common convention among C++ developers.
Comment: The underscore as prefix is to avoid to break those rules [what-are-the-rules-about-using-an-underscore-in-a-c-identifier](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier).
Comment: You need to delete the old value or you will leak.
Comment: @stark: auto-magically done thanks to smart pointer.
Answer: As @Jarod42 mentioned, you can access an element in a map using the operator[]
this->_menu[BINDINGS] = std::shared_ptr<AMenu>(new BindingMenu("Player 2"));

If the element you are trying to access didn't exist yet, it will be created.
More information here http://www.cplusplus.com/reference/unordered_map/unordered_map/operator[]/

Replace element in an unordered map


Akka Cluster custom serializer:

Question: I am using Akka Cluster to achieve some redundancy and remove single points of failure in my java application. However, I am having some problems with the serialization of the messages when sending them from one machine to another.
I am sending a java object that doesn't implement Serializable. Because of that, I need to use my own serializer and luckily the object provides a serialization method using Kryo. So, following this guide I have created my own akka serializer extending JSerializer:
import akka.serialization.JSerializer;

public class MyObjectClusterSerializer extends JSerializer {

    public int identifier() {
        return 66666;
    }

    public boolean includeManifest() {
        return false;
    }

    public byte[] toBinary(Object obj) {
        MyObject myObject = (MyObject) obj;
        byte[] bytes = null;
        try {
            bytes = MyObjectHelper.serialize(myObject);
        } catch (SerializationException e) {

        }
        return bytes;
    }

    @Override
    public Object fromBinaryJava(byte[] arg0, Class<?> arg1) {
        MyObject myObject = null;
        try {
            myObject = MyObjectHelper.deserialize(arg0);
        } catch (DeserializationException e) {
        }
        return myObject;
    }

}

The code is pretty straightforward and I don't believe that is the problem. Then I add the serializer and the serializer binding to my configuration:
serializers {
  myobject = "com.my.awesome.project.MyObjectClusterSerializer"
}

serialization-bindings {
  "com.my.awesome.project.MyObject" = myobject
}

When I am running a single node I don't have any issues (obviously because I am not serializing anything...). However in cluster mode I keep getting these exceptions:
    2014-08-04 01:45:27,498 ERROR [MyApp-akka.actor.default-dispatcher-16] - Slf4jLogger$$anonfun$receive$1$$anonfun$applyOrElse$1.apply$mcV$sp (Slf4jLogger.scala:66) - Transient association error (association remains live)
    java.io.NotSerializableException: com.my.awesome.project.MyObject
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183) ~[?:1.7.0_60]
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547) ~[?:1.7.0_60]
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508) ~[?:1.7.0_60]
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431) ~[?:1.7.0_60]
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177) ~[?:1.7.0_60]
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347) ~[?:1.7.0_60]
            at akka.serialization.JavaSerializer$$anonfun$toBinary$1.apply$mcV$sp(Serializer.scala:129) ~[akka-actor_2.11-2.3.4.jar:?]
            at akka.serialization.JavaSerializer$$anonfun$toBinary$1.apply(Serializer.scala:129) ~[akka-actor_2.11-2.3.4.jar:?]
            at akka.serialization.JavaSerializer$$anonfun$toBinary$1.apply(Serializer.scala:129) ~[akka-actor_2.11-2.3.4.jar:?]
            at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58) ~[scala-library-2.11.1.jar:?]
            at akka.serialization.JavaSerializer.toBinary(Serializer.scala:129) ~[akka-actor_2.11-2.3.4.jar:?]
            at akka.remote.serialization.MessageContainerSerializer.serializeSelection(MessageContainerSerializer.scala:36) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.serialization.MessageContainerSerializer.toBinary(MessageContainerSerializer.scala:25) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.MessageSerializer$.serialize(MessageSerializer.scala:36) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.EndpointWriter$$anonfun$serializeMessage$1.apply(Endpoint.scala:845) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.EndpointWriter$$anonfun$serializeMessage$1.apply(Endpoint.scala:845) ~[akka-remote_2.11-2.3.4.jar:?]
            at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58) ~[scala-library-2.11.1.jar:?]
            at akka.remote.EndpointWriter.serializeMessage(Endpoint.scala:844) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.EndpointWriter.writeSend(Endpoint.scala:747) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.remote.EndpointWriter$$anonfun$4.applyOrElse(Endpoint.scala:722) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.actor.Actor$class.aroundReceive(Actor.scala:465) ~[akka-actor_2.11-2.3.4.jar:?]
            at akka.remote.EndpointActor.aroundReceive(Endpoint.scala:415) ~[akka-remote_2.11-2.3.4.jar:?]
            at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516) [akka-actor_2.11-2.3.4.jar:?]
            at akka.actor.ActorCell.invoke(ActorCell.scala:487) [akka-actor_2.11-2.3.4.jar:?]
            at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238) [akka-actor_2.11-2.3.4.jar:?]
            at akka.dispatch.Mailbox.run(Mailbox.scala:220) [akka-actor_2.11-2.3.4.jar:?]
            at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:393) [akka-actor_2.11-2.3.4.jar:?]
            at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library-2.11.1.jar:?]
            at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library-2.11.1.jar:?]
            at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library-2.11.1.jar:?]
            at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library-2.11.1.jar:?]

And to me that means it is not able to figure out what serializer to use and it's actually using the generic Java one. Also, I don't know if it's related but I am wrapping my message with a ConsistentHashableEnvelope because I am sending it to a cluster-aware consistent hashing group.
Any help to make this thing work? Am I missing something?
Comment: Just as it is not clear from your pasted config, you do have serializers and serialization-bindings under akka.actor in your config, right?
Comment: Hi pushy, yes it is under akka.actor.
Answer: Akka selects serializer once by message class (see stack trace). In your case akka correctly uses JavaSerializer because base message has ConsistentHashableEnvelope type and applies this serializer to all fields (message and hashKey).
To solve your task just create serlializer for ConsistentHashableEnvelope and use MyObjectClusterSerializer only if message field has MyObject type and JavaSerializer in other cases

Akka Cluster custom serializer:


How to compare two samples without knowledge of the distribution

Question: lets say I have the mean of two different measurements of something, a and b. I also have the standard deviation on a, and b, but I do not have access to all the individual measurements of a and b. Is it possible to compare the two values to see if the means are statistically different (i.e., reject the null hypothesis that they are the same)? Any help would be greatly appreciated
Comment: Actually now that I think of it I do not really know the sample size. Is it possible without this piece of information?
Comment: @user777 You're on a good track. There's a stupid (not clever) procedure but in extreme cases it can be effective: assume the worst and suppose there were only two measurements in each group and conservatively replace the smaller SD by the larger one.  Also assume the measurements are iid Normal. If the resulting t-test identifies a difference, you have made some progress. If it is inconclusive, the results are inconclusive. Without some kind of distributional assumption (like normality), nothing can be done.
Comment: @whuber Thanks! What I like the most about talking to you is that speak with the experience of having conducted statistical consulting for several decades. Due to my age, most of my experience is of the form "well, according to this book I read...". Your replies prompt me to think about problems more creatively.
Comment: Do you know the sample sizes of sets $a$ and $b$?
Comment: yes, sorry i forgot to put that information in. I do know how many samples were used to calculate it.
Comment: Well, my go-to answer was Student's *t*-test, which requires the sample sizes to be known. There may exist a more clever procedure which does not require that information, but I'm afraid I'm not aware of one.
Comment: I believe a t-test also requires that the data come from a normal distribution, does it not?
Answer: If, as you now say, you don't know the sample sizes but you have sample means and sample standard deviations, the best you can guarantee is say that the sample sizes are at least two (since if either were smaller than two you couldn't compute standard deviations).
So you can at least test for that 'worst case' and see if there's a difference on that basis (that would be a two-sample t-test).
[A possible alternative is to figure out which combinations of sample sizes in the two samples would imply a significant difference.]
If you know anything about sample sizes - lower bounds, upper bounds, likely ranges, their ratio, whatever, that information is likely to be at least somewhat useful.

As you suggest, the t-test relies on the normality assumption. But without the individual observations you will pretty much have to make some kind of assumption, and it's at least somewhat robust to the assumption, more so if the true sample sizes are not actually very small.
Comment: I now see whuber posted the same suggestion in comments as I was typing that answer.
Comment: The subtlety in this suggestion concerns estimating the variance of the difference of the means. That's why I suggested replacing the smaller SD by the larger in order to proceed. With some additional calculation, that could be improved upon using the "possible alternative" you describe: for all possible combinations of sample sizes, retain the one yielding the largest (most conservative) p-value. This is not an infinite search, because the p-value will eventually decrease for very large sample sizes.
Comment: @whuber I don't think there's any issue with an equal variance assumption (which we can at least compare the sample values for rough proximity as a reasonableness check). If we take a Welch-Satterthwaite approach instead, there's an issue, as you suggest.
Comment: Yes, there's definitely an issue with highly unequal SDs. But even when you use an equal-variance test, it is possible to do better with a search--but the difference will be inconsequential unless you are using very high thresholds (around $.3$ or greater) for significance. *E.g.*, take $s_1=300$ and $s_2=30$ (which are not significantly different for samples of size 2): with $n_1=2$, the p-value is slightly higher for $n_2=3$ than for $n_2=2$.
Comment: I think I finally see what you're trying to convey. I'll try to write something on it tomorrow. Have to sleep now.
Comment: @whuber I see in your example (which I didn't read as far as last night because I got the point by then) you're using a *significance test* to decide whether or not to use an equal sample assumptions. I recommend against doing that every time I see it.
Comment: I guess I wasn't clear: I'm not trying to say anything about how you should decide which t-test to use. I was only pointing out in passing that *if* you wished to conduct (say) an F-test to see whether the SDs differ, you wouldn't reject the null, so I have some justification in using these SDs--even though they differ by an order of magnitude--in an example that applies an equal-variance t-test. With the value $0.3$ I was referring to the threshold of significance for the t-test itself.


Understanding the almost complex structure of a complex manifold

Question: I start learning complex manifold by myself and hard to lift my previous intuition of differential geometry over the complex structure.

Let $M$ be a real $2m$-dimensional manifold. We define an almost complex structure $J$ on $M$ to be a smooth tensor field $J \in \Gamma(TM \otimes T^*M)$ on $M$ satisfying $J_a^bJ_b^c=-\delta_a^c$. Where given any vector bundle $E$, we will always denote its space of sections by $\Gamma(E)$.

Here I understand that $J$ is a generalization of the usual multiplication by $\pm i$ in complex analysis, But I couldn't grasp what they mean by an almost complex structure $J$ on $M$ to be a smooth tensor field $J \in \Gamma(TM \otimes T^*M)$ on $M$ satisfying $J_a^bJ_b^c=-\delta_a^c$. Like how the role of $J$ integrated in the manifold? In fact, I haven't any clear idea about what it mean a tensor field over a manifold except the bookish definition, a tensor field on a manifold is a section of a tensor bundle over the manifold where tensor bundle is a fiber bundle whose fibers are vector spaces of tensors of a fixed type and rank.
From this M.SE I got,

Notice that a complex structure determines a unique (linear) complex structure on each tangent space $T_p M$, this time by declaring $J X := i X$ (or, more precisely, $J X := T \phi_\alpha^{-1} \cdot (i T\phi_\alpha \cdot X)$). The hypothesis that the transition maps are holomorphic ensures that $J$ so defined does not depend of the choice of chart $(U_\alpha, \phi_\alpha)$ in which one works.

I understand what it mean a complex structure on a real vector space like it give a notion to multiplication of complex number $i$, $$(a+ib).v=a.v+b.J(v),\text{where }a,b\in\mathbb R,v\in V_{\mathbb R}$$But I couldn't understand what does it mean "a complex structure determines a unique (linear) complex structure on each tangent space", like what kind of structure in the tangent space? I understand the atlas definition version of complex manifold but couldn't visualize or interpret what benefit/role actually it brings here.
Let the basis for $T_pM\cong\mathbb R^{2m}$ is $\left\{\frac{d}{dx^1}|_p,\frac{d}{dx^2}|_p,\cdots,\frac{d}{dx^m}|_p,\frac{d}{dy^1}|_p\cdots,\frac{d}{dy^m}|_p\right\}$, then how $J_p:T_pM\rightarrow T_pM$ will act on this basis? In Geometry, topology and physics- M. Nakahara write it as, $$J_p\left(\frac{d}{dx^{\mu}} \right)=\frac{d}{dy^\mu},\quad J_p\left(\frac{d}{dy^{\mu}} \right)=-\frac{d}{dx^\mu}$$
Where $z^\mu=x^\mu+iy^\mu$ are the coordinates of $p$ in a chart $(U,\phi)$, but I didn't see why is should be define like this?
Answer: An almost complex structure on a manifold $M$ is a bundle endomorphism $J : TM \to TM$ such that $J\circ J = -\operatorname{id}_{TM}$. Note, this is just a different way of expressing the definition you gave. So for each $p \in M$, we have a linear map $J_p : T_pM \to T_pM$ which satisfies $J_p\circ J_p = -\operatorname{id}_{T_pM}$. The map $J_p$ is what is being referred to as a linear complex structure (on $T_pM$).
As the comment you quoted indicates, given a complex structure on $M$, there is a natural almost complex structure. The tangent bundle of a complex manifold has a complex vector bundle structure, so $J$ is nothing more than multiplication by $i$.
Comment: Thanks for your response @MichaelAlbanese. Let the basis for $T_pM\cong\mathbb R^{2m}$ is $\left\{\frac{d}{dx^1}|_p,\frac{d}{dx^2}|_p,\cdots,\frac{d}{dx^m}|_p,\frac{d}{dy^1}|_p\cdots,\frac{d}{dy^m}|_p\right\}$, then how $J_p$ will act on this basis? I guess this will be the last line of confusion now.
Comment: If $J$ is an arbitrary almost complex structure, then $J_p$ can be any linear map which squares to $-\operatorname{id}_{T_pM}$. However, if $J$ is integrable and $z^k = x^k + iy^k$ are holomorphic coordinates on $M$, then $J\left(\frac{d}{dx^k}\Big|_p\right) = \frac{d}{dy^k}\Big|_p$ and $J\left(\frac{d}{dy^k}\Big|_p\right) = -\frac{d}{dx^k}\Big|_p$. That is, in this basis, $J_p$ is given by the matrix $\begin{bmatrix} 0 & -I_n\\ I_n & 0\end{bmatrix}$.


View displays no results for roles without Bypass Content Access

Question: For some reason one of my Views displays no results when I use my moderator role, but it does when I use the administrator role. The role permissions are exactly the same, except for the "Bypass Content Access" permission.
When I display content of type A everything is displayed like it should. But as soon as I add a "referenced entity" relationship from A to type B, nothing is displayed and the view uses the "No results behaviour".
When I create a view displaying only type B, both roles can see everything just fine.
I'm using Content Access and Organic Groups. I granted the roles the same permissions. I also set the View permissions to None.
Does anyone have a clue why this could be?
Answer: Based on my experience user1 (admin) bypasses everything , no matter what permissions the role administrator has granted (check to believe) , so just because you can see something in a view as admin and having same permissions for administrator and another role does not permits users in that role to access what admin can.
so check to see what what permissions may lead to accessing this view , this permission might be unchecked for admin but still bypassing it.


Why do I get a square wave when iterating $\cos\left(\tan\left(\cos\left(\tan\left(\cos(x)\right)\right)\right)\right)$?

Question:
Why do I get a square wave when iterating
  $$\cos\left(\tan\left(\cos\left(\tan\left(\cos(x)\right)\right)\right)\right)?$$
  And why does the square wave happen where it does? It is clearly an even function, and it seems to have period $1.634$
Answer: First of all, notice that it depends on how you "iterate". If you repeatedly apply
$x \mapsto \cos(\tan(x))$
to $\cos(x)$, you will eventually get graphs that look like square waves,
but the wave will "flip" every time you iterate: the peaks will become troughs
and the troughs will become peaks. This is not a convergent sequence of functions.
If you repeatedly apply $x \mapsto \cos(\tan(\cos(\tan(x))))$ to $\cos(x),$ however,
you do get a converging sequence of functions.
I think this is a little easier to make sense of by considering the function
$f(x) = \tan(\cos(\tan(\cos(x)))).$
The figure below is a graph of $y=f(x)$ with the graph of $y=x$ for comparison.

There are exactly three values of $x$ for which $f(x) = x.$
Let's call them $x_1,$ $x_2,$ and $x_3.$
These numbers are approximately
\begin{align}
x_1 &\approx 0.0137109619668026, \\
x_2 &\approx 0.816541226172734, \\
x_3 &\approx 1.55708579436399.
\end{align}
Because $f(x) < x$ when $x_1 < x < x_2,$ if we apply $f$ repeatedly to a value of $x$ in that range, the outcomes of $f(x),$ $f(f(x)),$ $f(f(f(x))),$ $f(f(f(f(x)))),$
and so forth will be progressively smaller, eventually approaching $x_1.$
Because $f(x) > x$ when $x_2 < x < x_3,$ if we apply $f$ repeatedly to a value of $x$ in that range, the outcomes of $f(x),$ $f(f(x)),$ $f(f(f(x))),$ $f(f(f(f(x)))),$
and so forth will be progressively larger, eventually approaching $x_3.$
For similar reasons, if $0 \leq x < x_1$ then the successive applications of $f$ produce larger and larger values approaching $x_1,$ whereas if
$x_3 < x \leq \frac\pi2$ then the successive applications of $f$ produce smaller and smaller values approaching $x_3.$
On the other hand, $f(x_1) = x_1$ exactly, and therefore
$f(x_1) = f(f(x_1)) = f(f(f(x_1))) = f(f(f(f(x_1))))$ and so forth.
Likewise $x_2 = f(x_2) = f(f(x_2)) = f(f(f(x_2))) = f(f(f(f(x_2))))$
and $x_3 = f(x_3) = f(f(x_3)) = f(f(f(x_3))) = f(f(f(f(x_3)))).$
So for every possible value of $x$ in the range from $0$ to $\frac\pi2$ inclusive,
whenever $x < x_2$ the repeated application of $f$ produces a sequence of outputs converting to $x_1,$ and whenever $x > x_2$ the repeated application of $f$ produces a sequence of outputs converting to $x_3.$
The result is a sequence of functions, which if restricted to
the domain $\left[0,\frac\pi2\right]$ converge on the step function
$$
f^*(x) = \begin{cases}
x_1 & 0 \leq x < x_2, \\
x_2 & x = x_2, \\
x_3 & x_2 < x \leq \frac\pi2.\end{cases}
$$
Outside of the interval $\left[0,\frac\pi2\right],$ we can use the fact that
$\cos(-x) = \cos(x)$, the fact that
$\cos(\pi - x) = -\cos(x)$,
and the fact that $\tan(-x) = -\tan(x)$ to conclude that
$$
\cos(\tan(\cos(\pi - x)))
= \cos(\tan(-\cos(x)))
= \cos(-\tan(\cos(x)))
= \cos(\tan(\cos(x)))
$$
and therefore $f(\pi - x) = f(x)$
and $f(f(\cdots f(\pi - x))) = f(f(\cdots f(x)))$
for any number of iterations of the application of $f$;
that is, each of these functions is symmetric around the line $y = \frac\pi2,$
and each function on the interval $\left[\frac\pi2,\pi\right],$
is just a mirror image of the same function over $\left[0,\frac\pi2\right].$
This gives us
$$
f^*(x) = \begin{cases}
x_1 & 0 \leq x < x_2, \\
x_2 & x = x_2, \\
x_3 & x_2 < x < \pi - x_2,\\
x_2 & x = \pi - x_2, \\
x_1 & \pi - x_2 < x \leq \pi.\end{cases}
$$
This is already starting to look like a square wave.
The fact that $\cos(-x) = \cos(x)$ also tells us that any of these functions on the interval $[-\pi,0]$ is a mirror image of the function on the interval $[0,\pi].$
This gives us something that looks like two cycles of a square wave.
Then the fact that $\cos(x+2\pi) = \cos(x-2\pi) = \cos(x)$ means the function
over $[-\pi,\pi]$ repeats forever to the left and right,
so $f^*$ actually is a square wave with period $\pi$
(not $1.634$).
You are interested in functions of the form $\cos(f(\cdots f(x)))$, which converge on the limit function $\cos(f^*(x)).$
This again is a square wave, except that all the $x_1$ values are replaced by $\cos(x_1)$ (which is close to $1$),
all the $x_3$ values are replaced by $\cos(x_3)$ (which is close to $0$),
and all the $x_2$ values are replaced by $\cos(x_2)$.
That is, the wave has a smaller amplitude, it has peaks where $f^*(x)$ has troughs,
and it has troughs where $f^*(x)$ has peaks.
Unlike what you might have expected, the peaks and troughs are not of equal width.
One peak of $\cos(f^*(x))$ runs from $-x_2$ to $x_2,$
so its width is $2x_2 \approx 1.63308.$
That is greater than $\frac\pi2,$ so the trough has a width less than $\frac\pi2$
in order to make the length of one complete cycle be $\pi.$


A question about Mertens function $M(n)=\sum_{k=1}^n\mu(n)$

Question: The Mertens function is defined as:
$$M(n)=\sum_{k=1}^n\mu(n)$$ where $\mu(n)$ is the Möbius function.
The Mertens conjecture states: $|M(n)|\lt\sqrt n$. In 1985 A. M. Odlyzko e H. J. J. te Riele proved the conjecture to be false. There exists a number $m$ with $10^{12}\lt m\lt 10^{65}$ for which the previous inequality doesn't occur.
My question is: the number $m$ is the only number for which this happens or is there an infinite (or finite) set of numbers for which the Mertens conjecture is false?
Answer: There are infinitely many counter-examples. This was proved by Tadej Kotnik and Herman te Riele in 2006, in their article The Mertens Conjecture Revisited In: Hess, F., Pauli, S., Pohst, M. (eds) Algorithmic Number Theory. ANTS 2006. Lecture Notes in Computer Science, vol 4076. Springer, Berlin
Comment: This appears to be a "link-only" answer.  Please include in your answer sufficient information to answer the question without requiring the link to answer for you.
Comment: The question was not a reference request, but given that link is all you provided, please include a full citation, including the journal and/or publisher, and relevant pages.
Comment: @amWhy It is done.


Crontab run MongoDB script in javascript file

Question: I tried this :
0 0 */15 * * /usr/bin/mongo stories  /usr/share/cronjobs/15days.js
* * * * * touch /usr/share/neargood/testing.txt

The testing.txt file is  effectively created each minute, but the mongo script doesn't have any effect.
15days.js :
d=new Date();
mdate15 = new Date(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()-15);
db.story.update({ date: {$lte:mdate15} , active:1},{ $set: {active:0}},{ multi: true })

What could the problem be ?
Comment: Manually it works. When I run Cron the Email I get is :
MongoDB shell version: 2.4.8
connecting to: stories
Comment: I changed the js file to executable , IT worked :) thanks!
Answer: What happens when you run the command by hand? Does it work? If so, it could be a permissions issue. Check all files involved to make sure that the cron user has privilege to read and/or execute where applicable.
If it runs manually, then I'd guess it's got something to do with how things are chmod'd and/or chown'd. Find out what user cron runs as, and check to see if the mongo binary can be run by it. Also, check the permissions and ownership of 15days.js


Let $U, V \sim U(0,1)$ be independent. What is $P(U \leq V)$?

Question: Let $U, V \sim U(0,1)$ be independent. What is $P(U \leq V)$?
My attempt:
We are looking for $P(U-V \leq 0)$. For a given $t \in [0,1]$ this is equivalent to $$P(U \leq t, V \gt t)= P(U \leq t)P(V \gt t)=P(U \leq t)(1-P(V\leq t))=t(1-t)=t-t^2$$
Then summing over $t$ on $[0,1]$, I get:
$$\int_0^1 t-t^2 \, dt = \frac{1}{6}$$
Which seems like a reasonable value, but I'm not exactly sure whether my approach with doing this in terms of t was correct, can anybody please validate my solution?
Comment: By symmetry, $$\mathbb{P}[U\leq V]=\mathbb{P}[V\leq U]=\frac{1}{2}.$$
Comment: Indeed, $$\int P(U\leqslant t,V\gt t)\,\mathrm dt=E(W),\qquad W=\max\{V-U,0\},$$ and $E(W)\ne P(V\geqslant U)$ in general.
Comment: Both probabilities are the measure of the set of points above/below the diagonal in the unit square.
Comment: Thanks a lot for your answer, which makes perfect sense. But I still don't really see which step is wrong in my solution, can you tell me?
Comment: "This is equivalent to..." is a big leap. The probability you've given for any particular $t$ is certainly a subset of the set of values $(U,V)$, but it seems to be a counting problem to suggest that you can sum those all up against $t$. In particular, for particular values $u<v$, your integral only counting those incidences with weight $v-u$, rather than weight $1$.
Answer: Your attempt:

We are looking for $P(U-V \leq 0)$. For a given $t \in [0,1]$ this is equivalent to $$P(U \leq t, V \gt t)= P(U \leq t)P(V \gt t)=P(U \leq t)(1-P(V\leq t))=t(1-t)=t-t^2$$

Your error is in not considering cases where $V$ is less than a given $t$ but still greater than $U$.
What you should have attempted was to integrate the product of the probability density function of $U$ and the conditional cumulative probability distribution of $V$ greater than that value.
$$\begin{align}
\mathsf P(U\leq V) & = \int_0^1 { f_U(t) }\cdot{ \mathsf P(t\leq V\mid U=t) } \;\operatorname d t
\\ & = \int_0^1 f_U(t)\cdot\mathsf P(V\geq t)\,\operatorname d t & \text{by independence of }U,V
\\ & = \int_0^1 1\cdot(1-t)\,\operatorname d t & \text{since uniformly distributed}
\\ & =\frac 1 2
\end{align}$$
Which is in agreement with the symmetry argument's result.
Answer: The distribution of $(U,V)$ is the same as the distribution of $(V,U)$.  Therefore any statement about $U$ and $V$ that follows from a specification of that joint distribution is true if $U$ and $V$ are interchanged.  That means if we can say $P(U\le V)=c$ then it is also true that $P(V\le U)=c$.  If you know that $P(U=V)=0$, then that tells us that $P(U<V)=P(V<U)=c$ and $P(U<V)+P(V<U)=1$.  So $c+c=1$.
That's probably the simplest way to do it, but you can also notice that the pair $(U,V)$ is uniformly distributed in the unit square.  Draw the square, and look at the graph of the part of it where $U\le V$, and that should tell you the answer.


Is linking to autocomplete results possible?

Question: When users search a member profile using Views autocomplete exposed filter text field, is it possible to link the result values? Suppose we are searching some 'XY' user. The results appear as autocomplete drop-down. When we click on them, we are redirected to the member's description page.
Is linking to autocomplete results possible?
Comment: If I understood you correctly, not it is not possible. The drop-down list is created dynamically basing on the user input; there isn't a page that shows you that drop-down list content in a different way.
Answer: Yes it is possible.
You can try Search Autocomplete moodule.
Module page says:
<code> This module allows you to add autocomplete functionality to virtually any fields of a Drupal site. During the input, the field will be expanded and offer a list of suggestions before you start the search.
    By default, the module integrates with search forms from the Drupal core Search and Search Block.

Uses either static data, external or internal URL callback or an embeded view style to easily create your suggestions set.
</code>
For more information go through the module documentation.
Comment: Thank you for the info. Is there any video tutorial how to use this search autocomplete module.


ufw configuration for smtp connections

Question: I have a PHP application running on a Debian server with UFW as firewall. The application needs to connect to a SMTP to send mails.
It works when I disable UFW. When it's enabled, the PHP application just keeps waiting. These are my rules:

The SMTP port is 465. I think it's because it can't send packages back from the smtp host. But which ports to I need to open for that? When I connect to the SMTP from the server, the port is just random.
Comment: SMTP is TCP port 25  (other ports can be used but will only be used when explicitly configured in the client connecting to that server, in all other cases  e-mail traffic from one smtp server to another will use port 25)
Answer: As Bob mentioned the port for smtp is 25.
Port 25 is the original standard email SMTP port and the oldest, since it first debuted in 1982. Today, the Internet Assigned Numbers Authority (IANA), the group responsible for maintaining the internet addressing scheme, still recognizes port 25 as the standard, default SMTP port.
On the modern web, there's not a single SMTP port. Instead, there are four common SMTP ports:
25
587
465
2525
If you're configuring your WordPress site or email client to send emails via SMTP (submission), you'll almost always want to use port 587. Again, this is the default SMTP port for submission and it supports secure transmission via TLS.
If port 587 is blocked for some reason, port 2525 is a common alternative. Again, this is not an officially recognized SMTP port, but it is commonly used and supported by most providers.
While many providers still do support port 465 for SMTP, it's no longer an accepted standard and you should always try to use ports 587 and 2525 before using port 465.
Finally, while port 25 is commonly used for SMTP relay, you should not use it when setting up an email client or WordPress website because most ISPs and cloud hosting providers block port 25.
I left you this reference How to Choose the Right SMTP Port (Port 25, 587, 465, or 2525)
Comment: The email provider use port 465 with SSL authentication.

ufw configuration for smtp connections


Can't find proper image path

Question: I just googled and searched this site, found a lot of stuff, but either did I not understand the principle or am doing it wrong.
Actually the Class and the Image are not in the same directory, but to ease things for testing, I put the image into the same folder as my class.
These are the two lines:
ImageIcon img = new ImageIcon("gimmick_facepalm.png");

System.out.println(img.getIconWidth() + " " + img.getIconHeight());

Output is always -1 -1, so I suspect that Java does not read in the image.
Hint or solution would be appreciated :)
Thanks!
Comment: use absolute path instead of just image name.
Comment: Look into Java's [URI](http://docs.oracle.com/javase/7/docs/api/java/net/URI.html) and [URL](http://docs.oracle.com/javase/7/docs/api/java/net/URL.html) classes.
Answer: If you do not specify an absolute path (ie. C:/... under windows), the current directory will be the directory where the program was executed, not the class folder (your project root in eclipse for instance, or where your were when you invoked the "java" command).
Furthermore, you can access files in a package of the classpath like so:
File file = new File(ClassLoader.getSystemResource("name/of/package/"+fileName).toURI());

Or directly with ImageIcon:
new ImageIcon(ClassLoader.getSystemResource("name/of/package/"+fileName));

Comment: okay, but since we are working as a group using git, an absolute path will bring problems to every other member since they do not use the same folder to download to project to
Comment: Thanks for answer, but not even `ImageIcon imageFacepalm = new ImageIcon(ClassLoader.getSystemResource(filename));` where filename is a String with the images name in the same directory works. Why is that?
Comment: @N30 look more closely: you need to put the package in path form in front of your file, ie. "com/myapp/gimmick_facepalm.png"
Comment: Thank you all, but all the help doesnt work when the real issue is PEBKAC. I remembered saving the image as .png, but it was actually .jpg. DOH! Nonetheless, Thanks for effort ! (Besides that, I had to add src/ to any relative path I had used)
Answer: Try
URL url = ClassLoader.getSystemResource("gimmick_facepalm.png");
ImageIcon img = new ImageIcon(url);

System.out.println(img.getIconWidth() + " " + img.getIconHeight());

Can't find proper image path


Dividir linha par por linha ímpar ao longo das colunas

Question: Preciso dividir as linhas pares pelas linhas impares ao longo das colunas em um dataframe do R
Segue um MVP

# Nomes das colunas
colunas <- c("RMSE","MAE","MAPE","MASE")

# Dados
mz <- matrix(runif(40), nrow = 10, ncol = 4)
colnames(mz) <- colunas

# Para uma coluna o código roda bem
treino_teste <- numeric(10)
for (i in 1:10) {
  treino_teste[i] <- mz[2*i, "RMSE"]/mz[i, "RMSE"]
}

# Resultado para uma coluna
res <- treino_teste %>% cbind(colunas)

# Código com problema:
for (j in 1:4) {
  for (i in 1:10) {
    treino_teste[i,j] <- mz[2*i,j]/mz[i,j]
  }
}

Ao tentar fazer as iteraçoes para todas as colunas e gravar em uma matriz recebo um erro:
Error in treino_teste[i, j] <- mz[2 * i, j]/mz[i, j] :
incorrect number of subscripts on matrix
Algúem teria alguma solução com o looping ou talvez mais elegante com a família apply?
Answer: Defina uma função que resolva o problema para uma coluna genérica e aplique essa função a cada coluna da matriz.
# resultados reprodutíveis
set.seed(2023)
# Nomes das colunas
colunas <- c("RMSE","MAE","MAPE","MASE")

# Dados
mz <- matrix(runif(40), nrow = 10, ncol = 4)
colnames(mz) <- colunas

faux <- function(x) {
  sapply(seq.int(length(x)/2L), \(i) x[2*i]/x[2*i - 1])
}

apply(mz, 2, faux)
#>           RMSE       MAE      MAPE      MASE
#> [1,] 0.7183475 0.1726491 0.6975585 0.8759951
#> [2,] 2.4329072 5.5382856 2.7452295 0.6335880
#> [3,] 3.9775579 0.1694690 0.8848418 1.0387234
#> [4,] 1.4498068 2.5797582 0.1493072 0.8480003
#> [5,] 1.8096844 2.2167254 0.3604911 1.2431108

Created on 2023-08-12 with reprex v2.0.2
Numa só linha, com uma função anónima:
apply(mz, 2, \(x) sapply(seq.int(length(x)/2L), \(i) x[2*i]/x[2*i - 1]))
#>           RMSE       MAE      MAPE      MASE
#> [1,] 0.7183475 0.1726491 0.6975585 0.8759951
#> [2,] 2.4329072 5.5382856 2.7452295 0.6335880
#> [3,] 3.9775579 0.1694690 0.8848418 1.0387234
#> [4,] 1.4498068 2.5797582 0.1493072 0.8480003
#> [5,] 1.8096844 2.2167254 0.3604911 1.2431108

Created on 2023-08-12 with reprex v2.0.2
Answer: Pode simplesmente usar indexação, usando um vetor lógico de comprimento 2 para selecionar linhas alternadas. Por exemplo:
# Dados
set.seed(2023)
mz <- as.data.frame(matrix(runif(40), 10, 4, dimnames = list(NULL, c("RMSE","MAE","MAPE","MASE"))))

# Linhas pares
mz[c(FALSE, TRUE), ]
#>         RMSE       MAE       MAPE      MASE
#> 2  0.3351910 0.1488786 0.43817257 0.6635921
#> 4  0.3961200 0.9992733 0.93309259 0.4589465
#> 6  0.1208849 0.1426491 0.63085187 0.7005136
#> 8  0.6178579 0.8896255 0.11145029 0.6911815
#> 10 0.4763239 0.7090158 0.09851809 0.8905799

Assim, para dividir todas as linhas pares pelas ímpares:
mz[c(FALSE, TRUE), ]/mz[c(TRUE, FALSE), ]
#>         RMSE       MAE      MAPE      MASE
#> 2  0.7183475 0.1726491 0.6975585 0.8759951
#> 4  2.4329072 5.5382856 2.7452295 0.6335880
#> 6  3.9775579 0.1694690 0.8848418 1.0387234
#> 8  1.4498068 2.5797582 0.1493072 0.8480003
#> 10 1.8096844 2.2167254 0.3604911 1.2431108


Does anyone knows how to average function in three dimensions

Question: $$
\begin{split}
\frac{dr}{dt}       &= -\epsilon \sin^2(\theta)z \\
\frac{d \theta}{dt} &= -1-\epsilon \cos\theta \sin\theta z\\
\frac{dz}{dt}       &= \epsilon(r^2-T)
\end{split}
$$
Does anyone know how to do function averaging by using Fourier analysis in cylindrical coordinates or have some helpful reference?
Answer: I would refer to F. Verhulst, Nonlinear Differential Equations and Dynamical Systems (Springer, 1996), chapter 11, section 11.6. Quoting equation (11.37) therein, you have
\begin{align}
\dot{x} &= \epsilon\, X(\phi,x) + \mathcal{O}(\epsilon^2),\quad x\in D\subset \mathbb{R}^n, \tag{1a}\\
\dot{\phi} &= \Omega(x) + \mathcal{O}(\epsilon),\quad \phi \in S^1,\tag{1b}
\end{align}
with $X(\phi,x)$ periodic in $\phi$; in your case, $\phi = \theta$, $\Omega(x) = -1$, $x = (r,z)$ and $X(\phi,x) = (-\sin(\theta)^2 z, r^2 - T)$. Then, Theorem 11.4 (Verhulst, p.151) says that

Consider system $(1)$ with initial values $x(0) = x_0$, $\phi(0) = \phi_0$ and suppose that
a. the righthand sides are $C^1$ in $D \times S^1$;
b.) the solution of
  $$
\dot{y} = \epsilon\, X^0(y),\quad y(0) = x_0
$$
  with
  $$
X^0(y) = \int_{S^1} X(\phi,x)\,\text{d}\phi
$$
  is contained in an interior subset of $D$ in which $\Omega(x)$ is bounded away from zero by a constant independent of $\epsilon$;
then $x(t) - y(t) = \mathcal{O}(\epsilon)$ on the time-scale $1/\epsilon$.

In your case, this yields the system
\begin{align}
\dot{r}_\text{av} &= -\frac{1}{2} z_\text{av},\\
\dot{z}_\text{av} &= r_\text{av}^2 - T,
\end{align}
for the averaged values of $r$ and $z$, which is Hamiltonian and hence integrable.
Comment: You're welcome! Feel free to accept the answer
Comment: Thanks!I would take a look on the reference book first.
Comment: So we don't need to average $\theta$ dot function?
Comment: No, you don't need to do that. The idea is, as explained in the book, that you effectively change the time variable from $t$ to $\theta$.
Comment: There is no $\epsilon$ in the system,I guess that's because you use the new time scale $\tau = \epsilon \theta$ ?


JavaFX remove Node from ToolBar ContextMenu

Question: I'm having an issue with my usage of Toolbar. I've provided a small program that demonstrates what I'm trying to do and the issue. Basically I add a 'custom' Button to a Toolbar. The 'custom' Buttons have a X image on them and they have an action which allows them to remove themselves from the Toolbar. This works fine. The issue is when more Buttons are added to the Toolbar than there is width to show them Toolbar performs it's nice behaviour of showing the option to view a ContextMenu/popup to display the other Buttons. This also works well. The problem comes when removing the Buttons from the Toolbar. Removing Buttons that are visible on the Toolbar works well but if you try to remove Buttons from the ContextMenu, when it's made visible, it doesn't redraw itself and so the Button looks like it hasn't been removed. If the ContextMenu is hidden and then reshown the Button has been removed so it's just a redrawing issue.
Is there anyway I can force this to redraw from the Parent Node (the Toolbar) down?
    package ToolbarTest;

import java.net.URL;
import java.util.LinkedHashMap;
import java.util.ResourceBundle;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;

public class ToolbarHolderController implements Initializable {

    @FXML
    ToolBar toolBar;
    @FXML
    BorderPane borderPane;
    @FXML
    Button addButton;
    @FXML
    Button removeButton;
    @FXML
    private LinkedHashMap<String, ToggleButton> toggleButtonHash = new LinkedHashMap<>();

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        IntegerProperty i = new SimpleIntegerProperty(0);

        addButton.setOnAction(e -> {
            ImageView closeImageView = new ImageView(new Image(getClass().getResource("tabclose2.png").toString()));
            String text="B:" + i.get();
            RemoveableToggleButton tButton = new RemoveableToggleButton(text, closeImageView, new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    if (toggleButtonHash.containsKey(text)) {
                        toolBar.getItems().remove(toggleButtonHash.get(text));
                        toggleButtonHash.remove(text);
                    }
                    e.consume();
                }
            });
            toolBar.getItems().add(tButton);
            toggleButtonHash.put(text, tButton);
            i.set(i.get() + 1);
        });

        removeButton.setOnAction(e->{
                toolBar.getItems().remove(toolBar.getItems().size()-1);
            }
        );
    }

    class RemoveableToggleButton extends ToggleButton {

        private Button close = new Button();

        public RemoveableToggleButton(String text, Node graphic, EventHandler<ActionEvent> closeEvent) {
            this.close.setGraphic(graphic);
            this.close.setOnAction(closeEvent);
            this.close.setMouseTransparent(false);
            this.textProperty().set(text);
            this.setGraphic(close);
        }

    }
}

ToolBarHolder.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane fx:id="borderPane" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ToolbarTest.ToolbarHolderController">
   <top>
      <ToolBar fx:id="toolBar" prefHeight="40.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
   </top>

      <HBox spacing="5.0" BorderPane.alignment="CENTER_LEFT">
         <children>
            <Button fx:id="addButton" mnemonicParsing="false" text="add" />
             <Button fx:id="removeButton" mnemonicParsing="false" text="remove" />
         </children>
         <padding>
            <Insets bottom="5.0" left="5.0" top="5.0" />
         </padding>
      </HBox>

</BorderPane>

Answer: We have this very same problem. Through a bunch of trial and error, I was able to figure out that you not only need to remove the button from the toolbar.getItems(), but also from the Context Menu that the "overflow" button generates.
Try this:
// if the button is inside of a context menu, remove it from there as well
if (buttonToClose.getParent() != null &&
    buttonToClose.getParent().getParent() != null &&
    buttonToClose.getParent().getParent().getParent() != null &&
    buttonToClose.getParent().getParent().getParent() instanceof ContextMenuContent) {

    ContextMenuContent contextMenuContent = buttonToClose.getParent().getParent().getParent();
    contextMenuContent.getItemsContainer().getChildren().remove(buttonToClose.getParent());
}

I know it looks really hacky and has insider knowledge about the makeup of that context menu, but it works.
Comment: The only thing I needed to do was cast to ContextMenuContent, thanks very much for posting this :)


facing error while uploading file in mvc5 on server

Question: I have MVC5 application , where I need to upload file excel and then then create data table of this excel. I use devexpress control to upload file. I use following code to store uploded file and then read in datatable and then store in database.
<code> if (e.UploadedFile.IsValid)
        {
            e.UploadedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
            var Filepath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
            DataTable  dtReport = new DataTable();
            try
            {
                dtReport = CreateDataTableFromExcelFile(Filepath, "A1:U", true, "Sheet1").Tables[0];
            }
            catch
            {
            }
              SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            con.Open();
            System.Data.SqlClient.SqlBulkCopy sqlcopy = new System.Data.SqlClient.SqlBulkCopy(con);
            sqlcopy.DestinationTableName = "table_Name";
            sqlcopy.WriteToServer(dtReport);
            con.Close();
</code>
If I host this application on IIS on my machine then it works fine. But If I host it on another server then it shows error

Access to the path 'C:\inetpub\wwwroot\MVC_Project_v3\App_Data\UploadTemp\dxupload_19aafa62643d42418b2fe5eaadede3cfcugxrc4e.nrt.tmp' is denied.

Please suggest right solution
Answer: The credential you are using to host the WebSite (the credential you enter in the application pool identity) does not have the privilege to access that directory.

Add a valid credential here.


How to access a keyboard via Bluetooth in Android?

Question: I want to access a keyboard via Bluetooth.
For example :
Two devices connect each other via Bluetooth if I open keyboard in the first device, and I want access that keyboard in another device in any edittext.
So how can I access that keyboard in another device via bluetooth in android?
Answer: To detect a EditText keyboard popping up :
Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
    final int actualHeight = getHeight();

    if (actualHeight > proposedheight){
        // Keyboard is shown
    } else {
        // Keyboard is hidden
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

To capture a key event
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if (event.getAction() == KeyEvent.ACTION_DOWN)

         // keycode should be sent over bluetooth.

          return true;
        }
        return false;
    }
});

To inject keypresses in your Activity simply call onKeyDown() with the appropriate KeyEvent

To open up a keyboard
EditText editText = (EditText) findViewById(R.id.myEdit);
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

and close it :
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

If you are not interested in popping up the keyboard on the other phone, simply ignore this section. Use the good old : setText()

Now how you form the chatting protocol by which Bluetooth sends these key events is up to you.Hint:  RemoteDroid used OscMessages
Comment: @Reno..but i am not using edittext...i want to access 1st device keyboard to any editor (Edittext) of another device...So how i can get that keys in edittext for example : if i want enter username and password in another device then i can access 1st device keyboard ?
Comment: What you you talking about ... you're not using EditText's yet you want to use EditText? I can't understand what you mean.
Answer: If what you want is to have someone on Phone A press a key and the key be entered into the currently highlighted field on Phone B then this is what you need:
The app on both phones (One in "Send Mode" and one in "Receive Mode").
You need to capture the key press as coded in @Reno 's answer. You then need to use the transport mechanism (in this case Bluetooth) to transfer it to the other device. You should be able to search for more than enough tutorials on transferring strings via bluetooth.
You need the app on phone B to receive the string/character and then output it to the currently selected field. This means finding the focused field (Again, answers out there on SO) and then writing to that field (Which will likely be setText("A");).


Limit of $\{a_n ^r\}$ when $\{a_n\} →\alpha$?

Question: Say, $a_n → \alpha$. ($\alpha \in \mathbb{R}$)
How do I prove that the sequence $\{a_n ^r\}$ converges to $\alpha ^r$ when $r\in \mathbb{R}$?
(Only if $\alpha ^r$ can be defined)
Comment: Is this true? What if $\alpha = 0$ and $r = -1$?
Comment: How do you define $\alpha^r$ when $\alpha\in\mathbb C$ and $r\in\mathbb R$?
Comment: Edited! My mistake
Comment: This follows from the fact the $f(x)=x^r$ is continuous, (except at $x=0$ when $r<0$).
Comment: @Teddy Is there any direct proof for at least when $r\in \mathbb{Q}$?
Comment: A complete answer requires the basic definition of $x^r$. You need to construct powers as suprema and infima.
Comment: @Siminore I have constructed it using exponentiation to the power $q\in \mathbb{Q}$. Still, I have trouble with this problem.
Answer: For $r\in\mathbb Q$, you should consider 3 cases:

$r\in\mathbb N$: use $(\alpha_n)^r-\alpha^r = (\alpha_n - \alpha)\cdot\displaystyle\sum_{k=0}^{r-1}{\alpha_n}^k\alpha^{r-1-k}$
$r=\displaystyle\frac 1b,\ b\in\mathbb N$: use the same backwards for $\sqrt[b]{\alpha_n}-\sqrt[b]{\alpha}$
$r=-1$: use $\displaystyle\frac1{\alpha_n}-\frac1\alpha = \frac{\alpha-\alpha_n}{\alpha_n\alpha}$. Here $\alpha\ne 0$ (hence for almost all $n$, $|\alpha_n|$ is above a positive limit) is needed.

For arbitrary $r\in\mathbb R$, in a sense you have to use continuity, anyway exactly continuity defines $\alpha^r$ for all $r\in\mathbb R$..