Designing a support reward in reinforcement learning to help the agent reaching the goal when there is an obstacle between them

Question: I have a problem where an agent (a point) evolves in a 2D world and its goal is get sufficiently near to the goal (a circle) to consider is has reached it.
The action space is made of:

the speed of the agent
the direction of the agent

The observation space is made of:

the agent coordinates (x_agent, y_agent)
the goal coordinates (x_goal, y_goal)
where x_agent , y_agent (x_goal, y_goal respectively) are continuous values between 0 and 1.
an image of the map is provided to the learning model.

The agent receives a reward > 1 upon reaching the goal.
If it collides with the obstacle or does not reach the goal within a given number of steps, the episode terminates with a 0 reward.
To fasten the learning process, I have designed a support reward function such that when the agent is getting closer (farther) to the goal, it receives a certain positive (negative) reward such that, at time step t, the support reward is:
$r_{t} = (\frac{dist_{t-1} - dist_{t}}{dist_{0}})$
Where $dist_{t-1}$ is the Euclidean distance between the agent and the goal at step t and $dist_{0}$ is the initial distance between the agent and the goal at the start of the episode.
The issue with this reward function is that the distance does not consider if there is an obstacle between the agent and the goal. In below example, the agent has to receive successive negative support reward to be able to reach the goal, but it seems that such a support reward hinders the learning process as the agent wants to get immediately closer to the goal and then it ends up colliding with the obstacle. This support reward is very helpful to accelerate the learning process when there is no obstacle but it seems it shows its limit in the given situation.
Is there a way to design a better reward function which might helps the agent learning the expected behavior ?

Note: My actual world is made of much more complicated obstacles in terms of shapes and numbers.
Answer: It sounds like you should compute the shortest path between any two points $x, y$ in your environment, and use that as your distance function, rather than euclidean distance.
Even if an exact shortest path is intractable in your actual, more complicated environment, even an approximate shortest path distance would be much better than euclidean distance.
Comment: Thank you for your answer. I saw that skimage library provide a way to compute the shortest path between two pixels, so I'll try this. For example [this module](https://scikit-image.org/docs/dev/api/skimage.graph.html#module-skimage.graph)


toggle element on click

Question:

/**
 * Plugin: RichTile
 *
 * Because I got a little ambitious and decided to include ARIA attributes
 * and stuff, it became easier to manage this as a plugin.
 */

var RichTile = function (element, options) {
  this.element = $(element);
  this.options = $.extend({}, RichTile.DEFAULTS, options);
  this.flyoutElement = this.element.find(this.options.flyout);
  this.toggleElement = this.element.find(this.options.toggle);

  this.toggleElement.on({
    'click.RichTile': $.proxy(this.clickHandler, this),
    'keyup.RichTile': $.proxy(this.keyHandler, this)
  });
};

RichTile.DATA_KEY = 'plugin_richTile';

RichTile.DEFAULTS = {
  flyout: '.js-tile-flyout',
  toggle: '.js-toggle-tile',
  expandedClass: 'is-expanded',
  disabledClass: 'is-disabled',
  toggleKeyCodes: [13, 32] // ENTER, SPACE
};

RichTile.prototype.isExpanded = function() {
  return this.element.hasClass(this.options.expandedClass);
};

RichTile.prototype.isDisabled = function() {
  return this.element.hasClass(this.options.disabledClass);
};

RichTile.prototype.isEnabled = function() {
  return ! this.isDisabled();
};

RichTile.prototype.toggle = function(expand) {
  if (typeof expand === 'undefined') {
    expand = ! this.isExpanded();
  }
  if (this.isEnabled() || !expand) {
    this.flyoutElement.attr('aria-hidden', ! expand);
    this.toggleElement.attr('aria-expanded', expand);
    this.element.toggleClass(this.options.expandedClass, expand);
    this.element.trigger((expand ? 'expanded' : 'collapsed') + '.RichTile', [ this ]);
  }
  return this;
};

RichTile.prototype.expand = function() {
  return this.toggle(true);
};

RichTile.prototype.collapse = function() {
  return this.toggle(false);
};

RichTile.prototype.toggleEnable = function(enable) {
  if (typeof enable === 'undefined') {
    enable = this.isDisabled();
  }
  this.toggleElement.filter('[tabindex]').attr({
    'tabindex': enable ? 0 : -1,
    'aria-disabled': ! enable
  });
  if (! enable) {
    this.toggle(false);
  }
  this.element.toggleClass(this.options.disabledClass, ! enable);
  this.element.trigger((enable ? 'enabled' : 'disabled') + '.RichTile', [ this ]);
  return this;
};

RichTile.prototype.enable = function() {
  return this.toggleEnable(true);
};

RichTile.prototype.disable = function() {
  return this.toggleEnable(false);
};

RichTile.prototype.clickHandler = function(event) {
  event.preventDefault();
  return this.toggle();
};

RichTile.prototype.keyHandler = function(event) {
  if (this.options.toggleKeyCodes.indexOf(event.which) > -1) {
    event.preventDefault();
    return this.toggle();
  }
};

$.fn.richTile = function(option) {
  return this.each(function() {
    var data = $.data(this, RichTile.DATA_KEY);

    if (!data) {
      $.data(this, RichTile.DATA_KEY, (data = new RichTile(this, typeof option === 'object' && option)));
    }

    if (typeof option === 'string') {
      data[option]();
    }
  });
};

/**
 * Apply plugin and account for desired behavior outside of individual toggles.
 */

$('.js-tile').richTile().on({
  'expanded.RichTile': function(event, tile) {
    // disable siblings on expand
    var siblings = tile.element.siblings('.js-tile');
    siblings.richTile('disable');
    // re-enable when this tile is collapsed
    tile.element.one('collapsed.RichTile', function() {
      siblings.richTile('enable');
    });
  }
});
/**
 * Variables
 */
/**
 * Scaffolding
 */
* {
  margin: 0;
}

* + * {
  margin-top: 1rem;
}

html {
  background: #444;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  color: #e1e1e1;
  font: 1em/1.5 "Source Sans Pro", sans-serif;
  margin: 0 auto 1rem;
  max-width: 64em;
}

h1,
a {
  color: #fff;
  font-weight: 600;
}

h1 {
  font-size: 2.25em;
  line-height: 1.1;
  text-rendering: optimizeLegibility;
}

label {
  display: block;
}

pre,
code {
  font-family: "Source Code Pro", monospace;
}

/**
 * Component: Grid
 *
 * https://github.com/suitcss/components-grid/
 */
.Grid {
  display: block;
  font-size: 0;
  margin: 0;
  padding: 0;
  text-align: left;
}

.Grid--withGutter {
  margin: 0 -0.5rem;
}

.Grid--withGutter > .Grid-cell {
  padding: 0 0.5rem;
}

.Grid-cell {
  box-sizing: border-box;
  display: inline-block;
  font-size: 1rem;
  margin: 0;
  padding: 0;
  text-align: left;
  vertical-align: top;
  width: 100%;
}

/**
 * Component: Card
 */
.Card-image {
  display: inline-block;
  position: relative;
  width: 100%;
}

.Card-image:after {
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.Card-image img {
  display: block;
  height: 100%;
  width: 100%;
}

.Card-expiry {
  color: #aaa;
  font-size: 0.6666666667em;
}

/**
 * Component: Input
 */
.Input {
  background: #fff;
  border: 3px solid #e1e1e1;
  border-radius: 0.375rem;
  color: #444;
  display: block;
  font: inherit;
  padding: 0.5rem 1rem;
  width: 100%;
  -webkit-appearance: none;
}
.Input:hover {
  border-color: #aaa;
}
.Input:focus {
  border-color: #08c;
  outline: 0;
}
.Input.is-visa, .Input.is-mastercard, .Input.is-amex {
  background-position: 0.75rem center;
  background-repeat: no-repeat;
  padding-left: 3.375rem;
}
.Input.is-visa {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-visa.svg");
}
.Input.is-mastercard {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-mastercard.svg");
}
.Input.is-amex {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-amex.svg");
}

/**
 * Component: Button
 */
.Button {
  background: #fff;
  border: 3px solid transparent;
  border-radius: 0.375rem;
  color: #08c;
  cursor: pointer;
  display: inline-block;
  font: inherit;
  font-weight: 600;
  line-height: normal;
  margin: 0;
  padding: 0.5rem 1rem;
}
.Button:focus, .Button:hover {
  color: #00aaff;
}

.Button--primary {
  background: #08c;
  color: #fff !important;
}
.Button--primary:focus, .Button--primary:hover {
  background: #00aaff;
}

/**
 * Component: Tiles
 */
.Tiles {
  font-size: 0;
  margin-left: 0.5rem;
  margin-right: 0.5rem;
}

.Tile {
  display: inline-block;
  font-size: 1rem;
  margin: 0;
  vertical-align: top;
  width: 100%;
}

.Tile-content {
  background: #fff;
  border-radius: 0.375rem;
  color: #444;
  margin: 1rem 0.5rem 0;
  min-height: 10em;
  padding: 1rem;
  position: relative;
}

.Tile-content--toggle {
  cursor: pointer;
}
.Tile-content--toggle:focus, .Tile-content--toggle:hover {
  box-shadow: 0 0 0 3px #75d1ff;
  outline: 0;
}

.Tile.is-disabled .Tile-content--toggle {
  cursor: default;
  opacity: 0.5;
}
.Tile.is-disabled .Tile-content--toggle:focus, .Tile.is-disabled .Tile-content--toggle:hover {
  box-shadow: none;
}

.Tile-flyout {
  display: none;
  position: relative;
}

.Tile.is-expanded .Tile-flyout {
  display: block;
}

.Tile-flyout:before {
  background: #fff;
  content: "";
  left: 50%;
  margin-left: -0.5rem;
  position: absolute;
  height: 1rem;
  top: -0.5rem;
  transform: rotate(45deg);
  width: 1rem;
}

/**
 * Breakpoint layout changes
 */
@media (min-width: 30em) {
  .Tile {
    width: 50%;
  }

  .Tile-flyout {
    width: 200%;
  }

  .Tile:nth-child(2n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(2n+1) .Tile-flyout:before {
    left: 25%;
  }

  .Tile:nth-child(2n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(2n+2) .Tile-flyout:before {
    left: 75%;
  }
}
@media (min-width: 48em) {
  .Tile {
    width: 33.3333333333%;
  }

  .Tile-flyout {
    width: 300%;
  }

  .Tile:nth-child(3n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(3n+1) .Tile-flyout:before {
    left: 16.6666666667%;
  }

  .Tile:nth-child(3n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(3n+2) .Tile-flyout:before {
    left: 50%;
  }

  .Tile:nth-child(3n+3) .Tile-flyout {
    margin-left: -200%;
  }
  .Tile:nth-child(3n+3) .Tile-flyout:before {
    left: 83.3333333333%;
  }
}
@media (min-width: 64em) {
  .Tile {
    width: 25%;
  }

  .Tile-flyout {
    width: 400%;
  }

  .Tile:nth-child(4n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(4n+1) .Tile-flyout:before {
    left: 12.5%;
  }

  .Tile:nth-child(4n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(4n+2) .Tile-flyout:before {
    left: 37.5%;
  }

  .Tile:nth-child(4n+3) .Tile-flyout {
    margin-left: -200%;
  }
  .Tile:nth-child(4n+3) .Tile-flyout:before {
    left: 62.5%;
  }

  .Tile:nth-child(4n+4) .Tile-flyout {
    margin-left: -300%;
  }
  .Tile:nth-child(4n+4) .Tile-flyout:before {
    left: 87.5%;
  }
}
/**
 * Utilities: Space
 */
.u-marginTop {
  margin-top: 1rem;
}

@media (min-width: 48em) {
  .u-md-no-marginTop {
    margin-top: 0;
  }
}
/**
 * Utilities: Size
 *
 * https://github.com/suitcss/utils-size/
 */
.u-size1of2 {
  width: 50% !important;
}

@media (min-width: 48em) {
  .u-md-size1of2 {
    width: 50% !important;
  }
}
/**
 * Utilities: Text
 *
 * https://github.com/suitcss/utils-text/
 */
.u-textCenter {
  text-align: center !important;
}

.u-textRight {
  text-align: right !important;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>CodePen - Responsive tiles with column-spanning flyouts</title>
  <meta name="viewport" content="width=device-width, initial-scale=1"><link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Source+Code+Pro'><link rel="stylesheet" href="./style.css">

●●●● ●●●● ●●●● 1234

Expires May 2017

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-0"
      aria-hidden="true">

              Card Number
              <input class="Input is-visa" type="text" value="XXXX XXXX XXXX 1234">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="05 / 17" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 0000

Expires July 2018

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-1"
      aria-hidden="true">

              Card Number
              <input class="Input is-mastercard" type="text" value="XXXX XXXX XXXX 0000">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="07 / 18" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●●●● ●1001

Expires February 2019

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-2"
      aria-hidden="true">

              Card Number
              <input class="Input is-amex" type="text" value="XXXX XXXXXX X1001">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="02 / 19" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 1234

Expires May 2017

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-3"
      aria-hidden="true">

              Card Number
              <input class="Input is-visa" type="text" value="XXXX XXXX XXXX 1234">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="05 / 17" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 0000

Expires July 2018

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-4"
      aria-hidden="true">

              Card Number
              <input class="Input is-mastercard" type="text" value="XXXX XXXX XXXX 0000">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="07 / 18" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●●●● ●1001

Expires February 2019

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-5"
      aria-hidden="true">

              Card Number
              <input class="Input is-amex" type="text" value="XXXX XXXXXX X1001">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="02 / 19" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

I am really new with html / javascript.
I am playing around with this code i found in google.
I wanted to know how would i make the flyout hide when i click anywhere on the window part from the flyout itself.
Currently to hide the flyout you have to click back on the main picture, or click a button.
Thanks.
Answer: I added this to determine if a click made anywhere in the document has been done inside a .Tile-flyout or inside a .js-tile that is not "disabled".
// A click outside something active
$(document).on("click", function(e){
  // the click did not occur inside a tile "flyout" or inside an "not disabled" tile
  if(!($(e.target).closest(".Tile-flyout").length == 1 || $(e.target).closest(".js-tile:not(.is-disabled)").length == 1)){
    console.log("CLOSE!")

    // Then simply simulate a click in the active one
    $(".is-expanded>div").trigger("click")
  }
})

/**
 * Plugin: RichTile
 *
 * Because I got a little ambitious and decided to include ARIA attributes
 * and stuff, it became easier to manage this as a plugin.
 */

var RichTile = function (element, options) {
  this.element = $(element);
  this.options = $.extend({}, RichTile.DEFAULTS, options);
  this.flyoutElement = this.element.find(this.options.flyout);
  this.toggleElement = this.element.find(this.options.toggle);

  this.toggleElement.on({
    'click.RichTile': $.proxy(this.clickHandler, this),
    'keyup.RichTile': $.proxy(this.keyHandler, this)
  });
};

RichTile.DATA_KEY = 'plugin_richTile';

RichTile.DEFAULTS = {
  flyout: '.js-tile-flyout',
  toggle: '.js-toggle-tile',
  expandedClass: 'is-expanded',
  disabledClass: 'is-disabled',
  toggleKeyCodes: [13, 32] // ENTER, SPACE
};

RichTile.prototype.isExpanded = function() {
  return this.element.hasClass(this.options.expandedClass);
};

RichTile.prototype.isDisabled = function() {
  return this.element.hasClass(this.options.disabledClass);
};

RichTile.prototype.isEnabled = function() {
  return ! this.isDisabled();
};

RichTile.prototype.toggle = function(expand) {
  if (typeof expand === 'undefined') {
    expand = ! this.isExpanded();
  }
  if (this.isEnabled() || !expand) {
    this.flyoutElement.attr('aria-hidden', ! expand);
    this.toggleElement.attr('aria-expanded', expand);
    this.element.toggleClass(this.options.expandedClass, expand);
    this.element.trigger((expand ? 'expanded' : 'collapsed') + '.RichTile', [ this ]);
  }
  return this;
};

RichTile.prototype.expand = function() {
  return this.toggle(true);
};

RichTile.prototype.collapse = function() {
  return this.toggle(false);
};

RichTile.prototype.toggleEnable = function(enable) {
  if (typeof enable === 'undefined') {
    enable = this.isDisabled();
  }
  this.toggleElement.filter('[tabindex]').attr({
    'tabindex': enable ? 0 : -1,
    'aria-disabled': ! enable
  });
  if (! enable) {
    this.toggle(false);
  }
  this.element.toggleClass(this.options.disabledClass, ! enable);
  this.element.trigger((enable ? 'enabled' : 'disabled') + '.RichTile', [ this ]);
  return this;
};

RichTile.prototype.enable = function() {
  return this.toggleEnable(true);
};

RichTile.prototype.disable = function() {
  return this.toggleEnable(false);
};

RichTile.prototype.clickHandler = function(event) {
  event.preventDefault();
  return this.toggle();
};

RichTile.prototype.keyHandler = function(event) {
  if (this.options.toggleKeyCodes.indexOf(event.which) > -1) {
    event.preventDefault();
    return this.toggle();
  }
};

$.fn.richTile = function(option) {
  return this.each(function() {
    var data = $.data(this, RichTile.DATA_KEY);

    if (!data) {
      $.data(this, RichTile.DATA_KEY, (data = new RichTile(this, typeof option === 'object' && option)));
    }

    if (typeof option === 'string') {
      data[option]();
    }
  });
};

/**
 * Apply plugin and account for desired behavior outside of individual toggles.
 */

$('.js-tile').richTile().on({
  'expanded.RichTile': function(event, tile) {
    // disable siblings on expand
    var siblings = tile.element.siblings('.js-tile');
    siblings.richTile('disable');
    // re-enable when this tile is collapsed
    tile.element.one('collapsed.RichTile', function() {
      siblings.richTile('enable');
    });
  }
});

// A click outside something active
$(document).on("click", function(e){
  // the click did not occur inside a tile "flyout" or inside an "not disabled" tile
  if(!($(e.target).closest(".Tile-flyout").length == 1 || $(e.target).closest(".js-tile:not(.is-disabled)").length == 1)){
    console.log("CLOSE!")

    // Then simply simulate a click in the active one
    $(".is-expanded>div").trigger("click")
  }
})
/**
 * Variables
 */
/**
 * Scaffolding
 */
* {
  margin: 0;
}

* + * {
  margin-top: 1rem;
}

html {
  background: #444;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  color: #e1e1e1;
  font: 1em/1.5 "Source Sans Pro", sans-serif;
  margin: 0 auto 1rem;
  max-width: 64em;
}

h1,
a {
  color: #fff;
  font-weight: 600;
}

h1 {
  font-size: 2.25em;
  line-height: 1.1;
  text-rendering: optimizeLegibility;
}

label {
  display: block;
}

pre,
code {
  font-family: "Source Code Pro", monospace;
}

/**
 * Component: Grid
 *
 * https://github.com/suitcss/components-grid/
 */
.Grid {
  display: block;
  font-size: 0;
  margin: 0;
  padding: 0;
  text-align: left;
}

.Grid--withGutter {
  margin: 0 -0.5rem;
}

.Grid--withGutter > .Grid-cell {
  padding: 0 0.5rem;
}

.Grid-cell {
  box-sizing: border-box;
  display: inline-block;
  font-size: 1rem;
  margin: 0;
  padding: 0;
  text-align: left;
  vertical-align: top;
  width: 100%;
}

/**
 * Component: Card
 */
.Card-image {
  display: inline-block;
  position: relative;
  width: 100%;
}

.Card-image:after {
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.Card-image img {
  display: block;
  height: 100%;
  width: 100%;
}

.Card-expiry {
  color: #aaa;
  font-size: 0.6666666667em;
}

/**
 * Component: Input
 */
.Input {
  background: #fff;
  border: 3px solid #e1e1e1;
  border-radius: 0.375rem;
  color: #444;
  display: block;
  font: inherit;
  padding: 0.5rem 1rem;
  width: 100%;
  -webkit-appearance: none;
}
.Input:hover {
  border-color: #aaa;
}
.Input:focus {
  border-color: #08c;
  outline: 0;
}
.Input.is-visa, .Input.is-mastercard, .Input.is-amex {
  background-position: 0.75rem center;
  background-repeat: no-repeat;
  padding-left: 3.375rem;
}
.Input.is-visa {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-visa.svg");
}
.Input.is-mastercard {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-mastercard.svg");
}
.Input.is-amex {
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/62127/creditcard-amex.svg");
}

/**
 * Component: Button
 */
.Button {
  background: #fff;
  border: 3px solid transparent;
  border-radius: 0.375rem;
  color: #08c;
  cursor: pointer;
  display: inline-block;
  font: inherit;
  font-weight: 600;
  line-height: normal;
  margin: 0;
  padding: 0.5rem 1rem;
}
.Button:focus, .Button:hover {
  color: #00aaff;
}

.Button--primary {
  background: #08c;
  color: #fff !important;
}
.Button--primary:focus, .Button--primary:hover {
  background: #00aaff;
}

/**
 * Component: Tiles
 */
.Tiles {
  font-size: 0;
  margin-left: 0.5rem;
  margin-right: 0.5rem;
}

.Tile {
  display: inline-block;
  font-size: 1rem;
  margin: 0;
  vertical-align: top;
  width: 100%;
}

.Tile-content {
  background: #fff;
  border-radius: 0.375rem;
  color: #444;
  margin: 1rem 0.5rem 0;
  min-height: 10em;
  padding: 1rem;
  position: relative;
}

.Tile-content--toggle {
  cursor: pointer;
}
.Tile-content--toggle:focus, .Tile-content--toggle:hover {
  box-shadow: 0 0 0 3px #75d1ff;
  outline: 0;
}

.Tile.is-disabled .Tile-content--toggle {
  cursor: default;
  opacity: 0.5;
}
.Tile.is-disabled .Tile-content--toggle:focus, .Tile.is-disabled .Tile-content--toggle:hover {
  box-shadow: none;
}

.Tile-flyout {
  display: none;
  position: relative;
}

.Tile.is-expanded .Tile-flyout {
  display: block;
}

.Tile-flyout:before {
  background: #fff;
  content: "";
  left: 50%;
  margin-left: -0.5rem;
  position: absolute;
  height: 1rem;
  top: -0.5rem;
  transform: rotate(45deg);
  width: 1rem;
}

/**
 * Breakpoint layout changes
 */
@media (min-width: 30em) {
  .Tile {
    width: 50%;
  }

  .Tile-flyout {
    width: 200%;
  }

  .Tile:nth-child(2n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(2n+1) .Tile-flyout:before {
    left: 25%;
  }

  .Tile:nth-child(2n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(2n+2) .Tile-flyout:before {
    left: 75%;
  }
}
@media (min-width: 48em) {
  .Tile {
    width: 33.3333333333%;
  }

  .Tile-flyout {
    width: 300%;
  }

  .Tile:nth-child(3n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(3n+1) .Tile-flyout:before {
    left: 16.6666666667%;
  }

  .Tile:nth-child(3n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(3n+2) .Tile-flyout:before {
    left: 50%;
  }

  .Tile:nth-child(3n+3) .Tile-flyout {
    margin-left: -200%;
  }
  .Tile:nth-child(3n+3) .Tile-flyout:before {
    left: 83.3333333333%;
  }
}
@media (min-width: 64em) {
  .Tile {
    width: 25%;
  }

  .Tile-flyout {
    width: 400%;
  }

  .Tile:nth-child(4n+1) .Tile-flyout {
    margin-left: 0%;
  }
  .Tile:nth-child(4n+1) .Tile-flyout:before {
    left: 12.5%;
  }

  .Tile:nth-child(4n+2) .Tile-flyout {
    margin-left: -100%;
  }
  .Tile:nth-child(4n+2) .Tile-flyout:before {
    left: 37.5%;
  }

  .Tile:nth-child(4n+3) .Tile-flyout {
    margin-left: -200%;
  }
  .Tile:nth-child(4n+3) .Tile-flyout:before {
    left: 62.5%;
  }

  .Tile:nth-child(4n+4) .Tile-flyout {
    margin-left: -300%;
  }
  .Tile:nth-child(4n+4) .Tile-flyout:before {
    left: 87.5%;
  }
}
/**
 * Utilities: Space
 */
.u-marginTop {
  margin-top: 1rem;
}

@media (min-width: 48em) {
  .u-md-no-marginTop {
    margin-top: 0;
  }
}
/**
 * Utilities: Size
 *
 * https://github.com/suitcss/utils-size/
 */
.u-size1of2 {
  width: 50% !important;
}

@media (min-width: 48em) {
  .u-md-size1of2 {
    width: 50% !important;
  }
}
/**
 * Utilities: Text
 *
 * https://github.com/suitcss/utils-text/
 */
.u-textCenter {
  text-align: center !important;
}

.u-textRight {
  text-align: right !important;
}

/* ADDED to restore the SO console's style */
.as-console{
  color: black !important;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>CodePen - Responsive tiles with column-spanning flyouts</title>
  <meta name="viewport" content="width=device-width, initial-scale=1"><link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Source+Code+Pro'><link rel="stylesheet" href="./style.css">

●●●● ●●●● ●●●● 1234

Expires May 2017

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-0"
      aria-hidden="true">

              Card Number
              <input class="Input is-visa" type="text" value="XXXX XXXX XXXX 1234">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="05 / 17" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 0000

Expires July 2018

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-1"
      aria-hidden="true">

              Card Number
              <input class="Input is-mastercard" type="text" value="XXXX XXXX XXXX 0000">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="07 / 18" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●●●● ●1001

Expires February 2019

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-2"
      aria-hidden="true">

              Card Number
              <input class="Input is-amex" type="text" value="XXXX XXXXXX X1001">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="02 / 19" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 1234

Expires May 2017

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-3"
      aria-hidden="true">

              Card Number
              <input class="Input is-visa" type="text" value="XXXX XXXX XXXX 1234">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="05 / 17" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●● ●●●● 0000

Expires July 2018

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-4"
      aria-hidden="true">

              Card Number
              <input class="Input is-mastercard" type="text" value="XXXX XXXX XXXX 0000">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="07 / 18" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

●●●● ●●●●●● ●1001

Expires February 2019

    <form class="Tile-flyout js-tile-flyout"
      id="edit-flyout-5"
      aria-hidden="true">

              Card Number
              <input class="Input is-amex" type="text" value="XXXX XXXXXX X1001">

              Full Name on Card
              <input class="Input" type="text" value="John Smith">

                  Expiration Date
                  <input class="Input" type="text" value="02 / 19" placeholder="MM / YY">

                  Security Code
                  <input class="Input" type="text" value="XXX">

              Address Line 1
              <input class="Input" type="text" value="208 SW 1st Ave">

              Address Line 2
              <input class="Input" type="text" value="Ste. 240">

              Zip/Postal Code
              <input class="Input" type="text" value="97204">

          <button class="Button js-toggle-tile" type="button">Never Mind</button>
          <button class="Button Button--primary js-toggle-tile" type="submit">Save</button>

    </form>

Comment: Thanks that seems to work, how would i make it so that if i dont click save it restores the values to default?
Comment: The question was about clicking outside an active thing.... For the rest, it is up to you.

toggle element on click


What means dbconfig-common?

Question: I have a simple question.
During installation of PHPMyAdmin it ask you if you want to configure the database with dbconfig-common (Debian).
Can someone please explain to me what dbconfig-common exactly does? What is the difference?
Many thanks!
Answer: dbconfig-common is a tool which simplifies database configuration. Instead of editing the config-files directly, it provides an UI where you can set up your setting to avoid misconfiguration. You can find more information here: http://docs.openstack.org/havana/install-guide/install/apt-debian/content/debconf-dbconfig-common.html
Answer: dbconfig-common is a simple way to generating database configuration
From documentation:
"dbconfig-common is an implementation of the "best practices for database applications" draft, which provides debian packagers with an easy, reliable, and consistent method for managing databases used by debian packages."
In case of installation phpmyadmin - you will need to setup your MySQL password and set the password you'll use to log into phpmyadmin
More information about dbconfig-common here: https://people.debian.org/~seanius/policy/dbconfig-common.html/

What means dbconfig-common?


OpenCV: Ordering a contours by area (Python)

Question: The OpenCV library provides a function that returns a set of contours for a binary (thresholded) image. The contourArea() can be applied to find associated areas.
Is the list of contours out outputted by findContours() ordered in terms of area by default? If not, does anyone know of a cv2 function that orders a list of contours by area?
Please provide responses in Python, not C.
Comment: [This](http://stackoverflow.com/a/27156873/5008845) can be helful. You just need to change the `greater` function to compare areas.
Comment: To partially address my question, the findContours() apparently outputs a list topologically ordered in terms of (x,y) coordinates (source: http://stackoverflow.com/questions/28693312/opencv-findcontours-how-contours-are-ordered). The second, bold part of the question still stands.
Comment: I was addressing the _bold_ part. You just need to sort your contours using a custom sorting function. I can't give you Python code, but it's pretty straightforward to modify `greater` comparing `contourArea()` of the two contours.
Comment: The last part of the post was meant for clarification, not to knock your answer. Hoping for an answer that allows for a comparison of the entire array, rather than a pair of contours, although I suppose the leap from comparison to a sorting function that uses the comparison isn't terribly difficult. My apologies if I'm missing something here.
Comment: my response was for clarification, too :D
Comment: Just saw the sort method being applied on the bottom of that linked post. Looks like I have what I need.
Comment: If you make it work, post the solution as an answer
Answer: Use sorted and sort by the area key:
cnts = cv2.findContours(boolImage.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
cntsSorted = sorted(cnts, key=lambda x: cv2.contourArea(x))

Answer: image, cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = sorted(cnts, key=cv2.contourArea)

cnt gives you an ordered list of contours in increasing order w.r.t area.
You can find the area of contour by index:
area = cv2.contourArea(cnt[index])

index can be 1,2,3.....,len(cnts)
For accessing the largest area contour:
cnt[reverse_index]

give reverse_index as -1
For second largest give reverse_index as -2 and so on.
The above can also be achieved with:
cnt = sorted(cnts, key=cv2.contourArea, reverse=True)

so cnt[1]  gives the largest contour cnt[2] second largest and so on.
Comment: Shouldn't that be cnt[0] for the largest and cnt[1] for the second largest since we start indexing at 0? If not, what's at index 0?
Comment: area = sum([cv2.contourArea(cnt)  for cnt in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]])
Comment: if I have two contours or more and I need to sum them. please, help me how?? for example: cnts = sorted(contours, key=cv2.contourArea, reverse=True)[:5]  # get largest five contour area
Comment: I tried to work {{{x, y, w, h = [cv2.boundingRect(n) for n in cnts ]}}} similar yours but give me error: ValueError: too many values to unpack
Comment: [cv2.boundingRect(n) for n in cnts] => it would give a list of [(x,y,w,h), (x,y,w,h).....]. Thats why its showing the error.
Comment: "index can be 1,2,3.....,len(cnts)" thats why cnt[1] else it would have been cnt[0]


Formula for length of a measure in minutes?

Question: This question is probably a crossover with mathematics.
I'm charting a song into a music game. The song has numerous #/12 time signatures, but the game can only handle power-of-2 signatures (#/4, #/8, etc).
As a workaround, I'm trying to use #/16 and increase the BPM so it takes the same time as if it was in #/12. However I can't figure out how much faster.
What is the formula for how much time a measure takes, given the BPM & time signature?
Comment: May I ask what song is in a #/12 time signature? I wasn't aware that such a thing existed.
Comment: @LemmyX that would actually be 12/8. There can't be a 12 in the bottom of a time signature because there is no native 1/12th note. dan9er do your numbers refer to the top note of the time signature?
Comment: @JohnBelzaguy I agree with your opinion about anyone who uses an x/12 time signature.  I would say though that "triplet" here doesn't necessarily imply anything about grouping; it just means "the note whose duration is 1/3 that of a quarter note."
Comment: @meganoob I think that 12/12 is the same as 4/4 played with triplets. I've never heard of any other such time signature.
Comment: @JohnBelzaguy while standard music notation does not support time signatures with a denominator that isn't a power of two, it's fairly trivial to extend the system.  (In fact, numeric time signatures were originally nothing more than fractions; they had nothing to do with measure length because measures did not exist when they came into use.)  As LemmyX suggests, the note that has 1/12 the duration of a whole note is the eighth note triplet.  It's confusing, but possible.
Comment: @phoog I understand what you're saying and I won't dispute it. I will say that with the infinite options available with standard music denominators, in my opinion anyone that chooses to write an x/12  is just attempting to be contrary and/or unique as opposed to writing something that is clear to understand. Plus you and LemmyX are actually making assumptions when you say 12/12 is 8th note triplets, maybe it's 3 groups of 8th note quadruplets or something else.
Comment: @phoog point taken, I was just suggesting that someone who would write a x/12 might have some other odd idea besides the logical triplet.
Answer: It is: BPM divided by top number of time signature = number of bars per minute. As long as the BPM corresponds to the bottom number of the time signature you don't need it. If the BPM corresponds to a group of notes, say 3 notes in 9/8 then divide by the number of groups per measure, in the case of 9/8 it's 3.
60 seconds divided by number of bars per minute = seconds per measure.
Example 1: 120 BPM 4/4 time
120/4 = 30 measures per minute; 60/30 = 2 seconds per measure
Example 2: 200 BPM 6/8 time
200/6 = 33.33 measures per minute; 60/33.33 = 1.8 seconds per measure
Example 3: 140 BPM 9/8 time, dotted 1/4 = 140 BPM
140/3 = 46.67 measures per minute; 60/46.67 = 1.28 seconds per measure
Please correct me if I'm wrong, I USED to be decent at math years ago.
Comment: You nailed it John. I used to manually calculate times back in the Cakewalk 6 days to be able to have loops to sync properly and completely forgot about it.
Comment: @SaccoBelmonte Thanks, to this day I still like figuring some things out with pencil and paper even if there IS an app that can do it in a split second.
Answer: You can figure something like this out.  By definition the lower number indicates the type of note that gets ONE beat.  I prefer to keep it as a fraction.  So common time, 4/4 is the same as 4 quarter notes, 4*(1/4).  We have 8th and 16th but we do not have 1/12 notes in standard music notation, unless it's something new.  So I am not even sure I can directly answer your question.  But I will provide a formula for the other time signatures that make sense to me.  If you have the BPM (beats/min) and you know the time signature as N/M then each 1/M note gets ONE beat.  In 3/2 time, with a tempo of 120 bpm, each 1/2 note gets 1 beat and a measure in 3/4 would be 3 of these.  If one note is one beat then the time for a single beat is 1/120 minutes, or a 1/2 second and a single measure of 3/2 is 3/2 seconds long.
So all you really need is N/BPM.  The value of the note does not come into play.  You would read this as there are N M-th notes in a measure, each M-th note gets a beat at tempo BPM, hence the measure is N/BPM units of time long.


How can you tell if the singer is in pitch?

Question: Just found this site. I'm an adult piano beginner. I just started studying music for the first time in my life about a year ago and am loving it. It's fascinating.   I've been taking piano lessons.
So my question revolves around voice and ear training. I've been watching "The Voice" this season. After some performances one of the judges will say something like "You hit all the notes correctly", or "Your pitch was perfect", or "You were sharp in places" etc. I understand what all that means. But my question is HOW? How does the judge know whether they sing each note perfectly the entire song?  And sometimes the judge doesn't even know the song! So how would they know what the notes are supposed to be?  This is just mind boggling to me. I've looked at sheet music before with the vocal line. It seems to be different pitches than the actual accompanying music. So how can one know that the singer is hitting the notes or not? Is that possible?  And is this something I can train myself to do?  I think I have good ear, but have no idea how to know how to listen to determine if a singer is hitting the notes correctly. I listen to their performances but have no idea if they are hitting the notes perfectly. How does one do that? Thanks!
Comment: You may want to check out some of these existing questions on ear-training: [How can I train my ear for music?](http://music.stackexchange.com/questions/98/how-can-i-train-my-ear-for-music), [What are the most effective ear training methods?](http://music.stackexchange.com/questions/178/what-are-the-most-effective-ear-training-methods), and [Are there any games useful for ear training?](http://music.stackexchange.com/questions/209/are-there-any-games-useful-for-ear-training)
Comment: There's a concept called "relative pitch" where a person hearing one pitch will be able to precisely sing pitches that are a specific interval from that pitch.  "Absolute pitch" means that a person can, for example, sing a G# when asked.  I have always had relative pitch, meaning that if someone plays a C, I can sing a G#.  But that C doesn't make it to long-term memory for me.  It's not uncommon for musicians to have relative pitch; absolute pitch is pretty uncommon even among professionals.
Comment: Don't have to use the "exact" notes in the sheet music, can use different ones (Artistic license). Judges are not hearing the difference from the "exact" note. They are listening for every note in the 12 semitones (using the band as a reference) and can hear if they are flat or sharp of any of those 12 notes. And yes, you can get better at it. (a game for matching notes: http://trainer.thetamusic.com/en/content/vocal-match)
Comment: Does it sound good?
Comment: I'm sure you can hear if someone is singing horribly out of key. The people judging are likely quite sensitive to pitch deviations from the start, and working with music has in any case sharpened this skill. This means they can hear deviations some of us do not perceive.
Answer: In Western music, based a 12 note chromatic scale, there are fixed frequencies that are named notes.
Picking an octave at random, and using A4 = 440 Hz as a reference, here are some frequencies in Hz (that is, oscillations per second)

C4  261.63
C#4 277.18
D4  293.66
D#4 311.13
E4  329.63
F4  349.23
F#4 369.99
G4  392.00
G#4 415.30
A4  440.00
A#4 466.16
B4  493.88
C5  523.25

It's important to realise that all of this is relative to A4=440Hz. You could tune a whole orchestra up or down to a different 'A', and all of those frequencies would change too.
Most people process pitches relatively. That is, they process the interval between notes, not the absolute pitch. So if you played me an out-of-tune A on its own, I wouldn't know. But if you played me an in-tune C followed by an out-of-tune A, I would know that one of them was off.
So, alongside an in-tune accompaniment, if a singer is aiming for a G4, they want to sing at 392.00 Hz. The ear is fairly forgiving, so the singer might hit 390.00 Hz or 394Hz and it could sound OK -- indeed a little variance can be pleasant, to make the singing sound human and not too perfect. Slight differences in pitch are part of what makes unison choirs sound good.
If the singer sings at 381Hz, however, they're pretty much halfway between F# and G. We know it can't be the note the singer was aiming for. It doesn't harmonise with the accompaniment. It doesn't sound pleasant.
In some musical traditions, it's a bit more complicated than that. In Blues music for example, some notes are deliberately flattened -- but others are not, and a listener with experience of the Blues would still spot badly pitched notes.
Answer: Well, there are only 12 correct pitches per octave.  If you are not on pitch, you are more likely than not somewhere else.
Imagine a target range with 30 equally-spaced popup rods you have to hit as they go up randomly.  Afterwards the judge, not knowing which rods went up and when, gets to tell you how good your aim is.  He'll be able to tell you if you are going all over the place, or if your aim tends to be slightly to the left, or if you are really hitting well, all this without having to know which targets went up as long as they are going up in fixed places.
But the judge actually get to hear the accompaniment as well, and that gives a frame of reference in addition since the actual target is related to the accompaniment as well as to itself.  The usual singer's problem is being semi-consistently about a quartertone or less flat, sometimes sometimes particularly as pitches go higher.  Then there are high exposed tones particularly prone to problems: those are usually in a very simple relation to the underlying harmony so you'll have to be off by at least a third or so before the judge would have to know the score in order to figure out you're wrong.
Then there are tonedeaf people going all over the place without any recognizable connection to the grid of valid tones.
Answer: It is possible that some few people in this world are tone deaf and can not achieve this for various reasons either ear and or brain related. For the rest of us it is achieved through one of two skills, tone comparison and perfect pitch.
Imagine the music in a horror movie (a great example is the shower scene from psycho). Hearing even the slightest similarity to harmonies depicted in a tense moment of the horror movie suggests that notes being sung are out of tune. If, on the other hand, the notes sound like a Disney movie or the beach boys then the note is likely to be on pitch. Many years of practice and experience practicing an instrument (voice being a possible instrument) can give you a refined sense of pitch, some come by it naturally (perhaps simply by listening to music in their youth, though this is speculation on my part).
Some people find themselves developing varying degrees of perfect pitch, which means that they remember something akin to the exact frequency of a note and need no reference to hear this as in or out of tune. This would mean that they can hear if the accompaniment is out of tune as well. This is a rarer achievement, and accounts of people actually learning this skill (rather then simply knowing it) are rare.
So then, how do you know if it is too high or too low? Years of teaching students to tune the guitar has taught me that most do not have a natural sense of this. Naturally I feel that practicing tuning an instrument is a way to improve this skill, but remember the voice is an instrument too. Try practicing sliding in and out of pitch while listening to a reference note (such as one on a reasonably tuned piano). Listening to unprocessed sounds (such as a acoustic instrument) will be easer to discern, all the better if you are familiar with the reference instrument. I have also spent allot of time listening to others tune their instruments.
Beyond this, People seriously interested in hitting or hearing their notes precisely study ear training as @caleb Hines suggested. This study usually involves listening to music and intervals (distances between pitches) and writing down both the rhythm, intervals and pitches they hear (sometimes separately, sometimes together). It also involves training yourself to read and sing the correct notes, intervals and rhythms without accompaniment. The interval training is both harmonic (two or more pitches at the same time) and melodic (two or more notes played one at a time). There are many good books on this, but having a good teacher can accelerate your learning of these skills (It is difficult to be your own judge of your success).
To summarize, some come by it quite naturally and others have to struggle a great deal to achieve this skill.
I find that I am better at this skill on some days than others depending on my mood, my health, allergy season, and the weather. I also find my ears get tired after extended use (concentrated ear training/ listening) and become less accurate.
Answer: hitting the written notes is different than singing in pitch. In pitch means you are not slightly flat or slightly sharp. This is pretty easy to hear when you have a decent musical ear (ie you are not tone-deaf.) Most of the public can tell when someone is singing on pitch or not, cuz if they aren't, it sounds "off-key" (sour).
As for the other thing, whether or not they are singing the correct "written" notes, you have to take the judges with a grain of salt. Of course they don't know.
Answer: I am a firm believer that ability to sing in tune is innate. I don't believe the judges on america's got talent or the voice is professionally trained, but any person who can sing in tune decently can hear if a person is singing in tune whether they know the song or not and if they don't have the music notes in front of them. You can be trained to hear it if you play an instrument religiously.. its not hard to tell if someone is out of tune especially when there is background accompaniment.. I am a novice violin player and a classical soprano. I just started fudging with the strings. I can be searching for that elusive note up and down the string, but when I hit it right, it just shines at me... ah.. that sounds so much better!
Answer: The easiest way to check if someone is in pitch is to play on a keyboard the vocal line from the sheet music along with the vocalist and record both you and the vocalist.  You may need to adjust what you play to fit the notes that the singer is attempting to hit.
Then listen to the recording. Any place where the played note and the sung note sound ugly is where the singer sang off-pitch, either deliberately or intentionally.  The human ear is very good at comparing tones.


Determine current / own iframe

Question: What is the best way to determine the iframe DOM element a page is being displayed in ?
I need to notify the parent window when the iframe's contents have really finished loading (iframe onload looks like a scam with WebKit).
Consider the following scenario:

Parent window loads a new iframe
The loaded iframe invokes a function from the parent window and sends along a reference to its iframe DOM element (sort of a "sender" parameter).
The parent's invoked function destroys the iframe.

Suggestions on alternative solutions to this inter-frame communication are also welcome.
One problem I faced was that Safari / Chrome / WebKit browsers apparently fire the iframe's onload event too early – I tried sending form data (with file upload) to an iframe and had the onload handler clear the <input type="file" /> element's value and destroy the iframe, causing the form submission to be aborted, so I cannot use onload in that case (btw, is that a feature or a bug ?).
Another use case is where the iframe does something and wants interact with the parent.
Comment: what onload handler are you talking about? the iframes or the documents that you load in the iframe?
Comment: The iframe's `onload` handler.
Comment: if you can, try to set the onload function in the documents body tag and call from there up to the parent, that should work. I remmebr having seen the iffy webkit onlaod on iframes before and also rememebr a solution i built around it, but it's well oevr a year ago and i can't find the source code right now in our repository - if you truely need it, i can look for it :)
Comment: Thanks Martin, I don't really need it but I'm sure interested to hear about the workaround you've come up with, so let me know if you find it some day - no need to hurry though.
Answer: Like Stefaan id say window.parent but you should check window.frameElement too.
Comment: Isn't this the parent of the iframe, rather than the current iframe?
Comment: Looks like this is what I was looking for... seems to be supported by all major browsers although it is not part of any standard.
Answer: With window.parent you can get the parent window. You can also call methods on it. So with the following code you can notifiy the iframe parent that you have finished loading (you need to have a notifyLoaded function in the parent window.
window.parent.notifyLoaded(window);

Because we gave our own window the parent can loop all known iframes and check which one is loaded (using iframe.contentWindow to get the window of a certain iframe)
Comment: Yeah, the solution with `contentWindow` scanning was the best I could think of... I was wondering if there was a better one, but it currently seems to be the only way to go.
Answer: There are several ways to communicate between a frame and it's parent.
The easiest is if both have same document.domain set, in which case they can communicate directly.
if not there are several different ways of doing cross domain communication, for instance by setting/reading the hash-component of the iframe url
Look here for more information
Comment: This is good to know, but in my case, I do not need cross-domain communication - everything stays on one domain.
Answer: You can walk all iframe-elements inside the parent document and compare the contentWindow-property of the iframe-elements with the window-object inside the iframe(should be equal, but I didn't test it yet)
P.S.: tested it now, works fine http://www.jsfiddle.net/doktormolle/CMdLZ/
Comment: I'm afraid there is no other way than some kind of searching, as long as a window has no property to determine a parent DOM-element . Another solution may be to give the iframe-element an ID and submit the ID together with the form, so you can directly access the DOM-element using `parent.document.getElementById('submitted_ID')`
Comment: I thought about the same solution but it is quite inefficient as it has to search for the iframe.

Determine current / own iframe


Hypothesis Testing under Uniform Distribution Question

Question: The question reads:
Let $\theta > 0$ and $X \sim \mathcal{U}[0, \theta]$, i.e. $X$ is uniformly distributed on the interval $[0, \theta]$.
Assume that $\theta$ is unknown, but we can observe $X$. For given $\theta_1$, we want to test the
hypothesis H0: $\theta \geq \theta_1$ against the alternative H1 : $\theta < \theta_1$. Consider the test which rejects H0, if and only if $X < c$. How should we choose $c$, as a function of $\theta_1$ and $\alpha$, to get a test with confidence level $\alpha$? Carefully justify your answer.
I struggle to understand how to approach this question/ how to carry it out? Any help would be much appreciated as this question is due in today. Thanks!!
Comment: What is uniformly distributed?
Comment: @the_candyman Sorry, completely blanked out the first bit of the question, have edited the post to make it correct now. Should make sense.
Answer: The significance level $\alpha$ corresponds to the maximum Type I error you are willing to accept for the test; that is to say, the erroneous conclusion to reject the null hypothesis when it is true:  $$\Pr[\text{reject } H_0 \mid H_0 \text{ true}] \le \alpha.$$  Since you are already told that the criterion to reject $H_0$ is if $X < c$, and you are also told that the null hypothesis is $H_0 : \theta \ge \theta_1$, this becomes $$\Pr[X < c \mid \theta \ge \theta_1] \le \alpha.$$
Questions you should ask yourself:

For a fixed $\theta$, what is the conditional probability $\Pr[X < c \mid \theta]$?
As $\theta$ increases, does $\Pr[X < c \mid \theta]$ increase, or decrease, for a fixed $c$?
How does this inform the choice of $\theta$ under $H_0$, and $c$ as a function of $\theta_1$ and $\alpha$, to ensure a level $\alpha$ test?


Como otimizar esse código (Time Limit Exceeded)?

Question: Esse código é uma possível solução do problema 1211 no URI Online Judge. No meu pc roda normal para os casos de teste, mas na plataforma eu recebo a mensagem de Time Limit Exceeded. Alguma idéia de otimização?
#include <iostream>
#include <string.h>
using namespace std;

struct telefone{
    char digito[200];
};

int main(void){

    long int i = 0, N = 0;
    int soma = 0, j = 0;

        cin >> N;

    while(N!= EOF){
    struct telefone tel[N];

    for(i=0; i<N; i++){
        cin >> tel[i].digito;
    }
    int tamanho = strlen(tel[0].digito);

    for(i = 0; i < N - 1 ; i++){
        for(j=0; j<tamanho; j++){
                if (tel[i].digito[j] == tel[i+1].digito[j])
                    soma++;
                else break;
            }
    }
    cout << soma << endl;
    soma = 0;
    cin >> N;

    }
}

Comment: C não é C++, seu código é C++ e não C, editei as tags.
Comment: Eu não sei que problema é esse, o 1211 do URI judge. Se você puder sumarizá-lo para que nós possamos ter uma ideia melhor do que se trata, fica melhor tentar ajudar. Mas, se te ajudar, por esse vetor de escopo automático de tamanho `N` para ser alocado no começo do bloco a cada repetição, isso é um erro em programação competitiva. Melhor deixar esse vetor já alocado com seu valor máximo ou então nem usá-lo, se não for necessário guardar mais do que duas sequências de dígitos por vez
Comment: Exemplo de questão de programação competitiva que se encaixa bem melhor no formato do SOpt: https://pt.stackoverflow.com/q/306086/64969
Answer: Use while (!cin.eof()) no lugar de while(N!= EOF).
Veja aqui funcionando no ideone.


Limit of quotient of products $\lim_{n\to \infty}\left|\frac{\prod_{z^n=1}f(z)^n}{\prod_{z^n=-1}f(z)^n}\right|$

Question: I have a following problem: Let $f$ be a holomorphic function such that $|f(z)|>1$ for $|z|=1$. So what can we say about the limit $$\lim_{n\to \infty}\left|\frac{\prod_{z^n=1}f(z)^n}{\prod_{z^n=-1}f(z)^n}\right|?$$
Thanks in advance for any help!
Comment: What does $|f(z)|>1$ mean? Does this only serve to rule out zeroes?
Answer: This was fun. Where did you get this problem?
[edit] I was a little too rash in my first estimates, but I think the following is correct: The original sequence can converge or not, but I don't think the limit will be very interesting in any case. To see this, we first prove the next claim (which is the original answer, minus the exponent $n$):
Claim.
Let $f$ be holomorphic on an open set that contains the unit circle $S^1$. Then
$$
\lim_{n \to \infty}
\biggl\lvert
\frac{\prod_{z^n = 1} f(z)}{\prod_{w^n = -1} f(w)}
\biggr\rvert
= \exp \int_{S^1} \operatorname{Re}\biggl(\frac{f'(z)}{f(z)} \biggr) d\lambda.
$$
Proof:
For $n$ fixed write the $n$-th roots of $1$ and $-1$ as
$$
z_j = e^{2\pi j/n}, \quad
w_j = e^{2\pi j/n+ i\pi/2n}.
$$
For future use, note that $z_j - w_j = z_j(1 - e^{i\pi /2n})$, so $z_j - w_j \to 0$ as $n \to \infty$.
We now take logarithms and calculate that
$$
\log
\biggl\lvert
\frac{\prod_{z^n = 1} f(z)}{\prod_{w^n = -1} f(w)}
\biggr\rvert
=
\sum_{j=1}^n \frac{\log|f(z_j)| - \log|f(w_j)|}{z_j - w_j}(z_j-w_j).
$$
The right-hand side reminds us of the derivative. If $\epsilon > 0$ is given then, since $z_j - w_j \to 0$ as $n \to \infty$, there exists an $n_\epsilon$ such that
$$
\biggl\lvert
\frac{\log|f(z_j)| - \log|f(w_j)|}{z_j - w_j}
- (\log |f(z_j)|)'
\biggr\rvert
\leq \epsilon
$$
for all $n \geq n_\epsilon$. If this is the case, then
$$
\biggl\lvert
\sum_{j=1}^n \frac{\log|f(z_j)| - \log|f(w_j)|}{z_j - w_j}(z_j-w_j)
- \sum_{j=1}^n (\log |f(z_j)|)'(z_j - w_j)
\biggr\rvert
\leq n \epsilon |z_j - w_j|.
$$
for $n \geq n_\epsilon$.
Recall now that $|z_j - w_j| = |z_j(1 - e^{i \pi/2n})| = |e^{i\pi/2n} - 1|$.
Expanding $e^{i\pi/2n}-1$ as a series we find that
$$
n|z_j - w_j| =
n \Bigl\lvert \frac{i\pi}{2n}
+ O\Bigl(\frac{1}{n^2}\Bigr)
\Bigr\rvert
\leq \frac{\pi}{2} + O\Bigl( \frac{1}{n} \Bigr).
$$
This is good enough for our purposes, which are to show that the difference of the two sums above becomes smaller than any given $\epsilon$ as $n \to \infty$: Given $\epsilon$ we make an $\epsilon'$ such that $\epsilon' \frac{\pi}2 < \epsilon$, use that one to estimate the derivative and fudge everything so that in the end $\epsilon' \frac{\pi}{2} + O(1/n) \leq \epsilon$, which can be done by taking $n$ ludicrously big.
We have thus shown that the two big sums converge to the same limit as $n \to \infty$. But the sum involving the derivative is a Riemann sum, so
$$
\lim_{n \to \infty}
\biggl\lvert
\frac{\prod_{z^n = 1} f(z)}{\prod_{w^n = -1} f(w)}
\biggr\rvert
=
\exp \int_{S^1} (\log|f(z)|)' d\lambda,
$$
where we write $S^1$ for the unit circle and the $\exp$ appears because we calculated the $\log$ of the original sequence. A little manipulation shows that since $f$ is holomorphic we have
$$
(\log|f(z)|)' = \operatorname{Re} \biggl(\frac{f'(z)}{f(z)} \biggr),
$$
which gives the result.
Remark that this simplification is the only part that requires $f$ to be holomorphic, until now the argument carries through with $f$ only complex valued and once-differentiable.
Now back to the original question. Let's write $A_n = |\prod_{z^n = 1} f(z) / \prod_{w^n = -1} f(w)|$. This is a sequence of nonnegative real numbers that converges to $A = \exp\int_{S^1} \operatorname{Re}(f'(z)/f(z)) d\lambda$ by the claim. I see three cases:
Case 1: $A > 1$. Then all $A_n > 1 + \delta$ for all $n$ big enough and for some fixed $\delta  >0$, so $A_n^n$ goes to infinity.
Case 2: $A < 1$. Then $A_n^n \to 0$ by a similar argument.
Case 3: $A = 1$. I don't know. Maybe $A_n^n \to 1$ also, maybe it oscillates weirdly around $1$, maybe this is somehow trivial?
Comment: Thank you. For your original work, you can see at http://math.stackexchange.com/questions/417541/existence-of-lim-n-to-infty-frac-prod-zn-1fz-prod-zn-1fz?rq=1
Comment: I am just confused about the result, I think $A=1$ (following the above link). Also because $(A_n)$ is a sequence of nonnegative numbers, the limit (if exists) must be nonnegative. But I don't see that in your answer. May be there is a mistake?
Comment: @mapping: "May be there is a mistake?" Quite possibly, at least if the other answer you linked to is correct. I don't see where I went wrong, but I'll have a closer look later.
Comment: Ah ok, in fact $\int_{S^1} \operatorname{Re} f'/f d\lambda  =0$ for a holomorphic function $f$; the integral w/o the real part counts $2 \pi i$ the number of zeros of $f$ and writing it as the integral of real + imaginary parts of $f'/f$ shows that only the imaginary part contributes anything. So my $A = 1$ (forgot exponential too in the answer, edited) and is of no help to you.
Answer: There are the same number of $n^{th}$ roots of 1,  $\omega_1 , ~..., \omega_n $, as there are roots of -1, $\eta_1 , ~..., \eta_n $. With this in mind we can consider the expression as $ lim|\frac{f(\omega _1)}{f(\eta _1)}||\frac{f(\omega _2)}{f(\eta _2)}| \ ... \ |\frac{f(\omega _n)}{f(\eta _n)}|$ Then you can estimate how close $f(\omega _i)$ is to $f(\eta _i)$ using the maximum of $f'(z)$ on the unit circle. As $n$ becomes large they will get very close, but there will be more things to multiply.
The $n^{th}$ roots of unity are defined as
$\omega_j = \exp(\frac{2 \pi i}{n} j ) $ for $j = 0,1,...,n-1$ These are located along a circle of radius 1, evenly spaced.
The $n^{th}$ roots of -1 are defined as
$\eta_j = \exp(\frac{\pi i}{n}+ \frac{2 \pi i}{n} j ) $ for $j = 0,1,...,n-1$ These are also located along a circle of radius 1, evenly spaced.
So we have two sets of $n$ points evenly spaced along the unit circle. We can then "pair" up these points with each other, pairing each $\omega$ with its closest $\eta$. Since the $\eta$ are evenly spaces there will always be one within an $\frac{2 \pi i}{n}$ arc along the circle. So as $n$ becomes large each $\omega$ will become closer to its paired $\eta$. We relable the roots so that $\omega _l$ is paired with $\eta _l$ then write out the product as above.
As $n$ gets big ethe distance between each pair shrinks, so $f(\omega _l)$ and $f(\eta_l)$ approach each other. How quickly does this happen? Since $f$ is holomorphic on the (compact) unit circle it has bounded derivative there, so $|f'(z)| < L$ for $|z|=1$. It follows that $|f(\omega_l) - f(\eta_l)| < L|\omega_l - \eta_l|$. Then calculate $|\omega_l - \eta_l|$ and use this to put an upper bound on the product. Through further manipulation and using the fact that $|f(z)| > 1$ I think you get the limit is less than $1$. It is probably equal to $1$ as well.
Comment: Dear Daron, your approach doesn't quite work. It runs into the same problem as my original approach did, that we end up majorizing the (log of the) $n$-th power of the product by $L n^2 |1 - e^{i\pi/2n}|$, and this doesn't converge as $n \to \infty$.
Comment: I don't understand the relation between the closeness of $f(w_i)$ and $f(\eta_i)$ and $f'(z)$. Can you explain more? Thanks.


Print on new tab 'about:blank' and close after printed like datatable lib

Question: I like the way datatable does the printing, by clicking the PRINT button, new window opens (not in popup window), than the print prompt appears, after you click PRINT or CANCEL the opened tab closes!
I want to modify, or to be honest, I want to create my own customized script code!
So all i did till now is that i found out how to open a new about:blank page:
PRINT

So how to populate it inside of blank page with a table with data, and how to close that page automatically after finishing printing? What is the JavaScript behind it?
Like this example: https://jsfiddle.net/ms85e7zo/
Notice! I don't want to use datatable library for this, I want just a clear concept how it is possible to do that!
Answer: If you check the source of the DataTables print button you can see the logic which achieves the effect you're after. Note that win is a reference to the popup which was created and had the content injected in to.
var autoPrint = function() {
  if (config.autoPrint) {
    win.print(); // blocking - so close will not
    win.close(); // execute until this is done
  }
};

if (navigator.userAgent.match(/Trident\/\d.\d/)) { // IE needs to call this without a setTimeout
  autoPrint();
} else {
  win.setTimeout(autoPrint, 1000);
}

In short, all they do is call print(), which blocks the main browser thread, and then immediately afterwards call close(). As a result, no matter if the user decided to go ahead with the print or cancel it, as soon as execution resumes after the modal is dismissed the new window is closed. The setTimeout() is only to ensure that all styles and data has been loaded in IE before printing.
It's a simple and effective solution.
Comment: config.autoPrint undefined, I set it always true, then it's work~


What is the probability each team wins the tournament?

Question:
$A, B, C, D$ are four teams in a tournament where $A$ faces $B$ and $C$ faces $D$ in the first round and the winners of those rounds face each other.  $A$ has a $0.7$ probability of beating any other team, while $B, C, D$ have a $0.5$ probability of beating each other.  If the games are independent, what is the probability that each team wins the tournament?

My idea is $P(\text{$A$ wins})=P[A \text{ beats } B $ and  ($A \text{ beats } C$ or $A \text{ beats D}$)$]$  $=P[(A \text{ beats B and A beats C) or (A beats B and A beats D)}]$ $=0.7*0.7 + 0.7*0.7 =98$%, and repeating this process for each $B,C,D$ but this seems incorrect.
Is there an easier way to go about this?
Comment: $A$ wins with probability $0.7\cdot 0.5=0.35$.  How you got $0.98$ I have no idea.  Similarly, $B$ will win by first beating $A$ and then beating whichever of the remaining opponents are left, which occurs with probability...   Finally, we can get the probability for $C$ and $D$ by appealing to symmetry and that it must be half of the remaining available probability.
Comment: @JMoravitz He said $A$ wins with probability $0.7$ against _all_ teams. Should it not be $0.49$?
Comment: @JMoravitz I edited my question to show specifically how I got $0.98$, what have I incorrectly assumed to get that number?
Comment: @bames sure would, good catch.  And now that he has edited, we can see where his mistake lies.  When $A$ beats $B$, he moves on to play against the other remaining player, but *this is conditioned on that player having won his own game*!.  If you insist on keeping track of who the second opponent is for $A$, then you need a factor of $\frac{1}{2}$ in front of each.  Note, it doesn't make sense for the probability that $A$ wins the tournament as a whole to be higher than the probability that $A$ wins his first game.
Comment: So assuming $P(A \text{ wins })=0.7 * 0.7 = 0.49$, $P(B) = 0.3 * 0.5 = 0.15$, $P(C) = 0.5 * 0.5=0.25$ and $P(D)= 0.5 * 0.5 = 0.25$ then we have the probability of the sample space is greater than $1$.  What mistake did I make here?
Comment: @OliverG See my answer.
Comment: $P(C)\neq 0.5\cdot 0.5$.  $C$'s chances of winning the first game are indeed $0.5$, but the chance that $C$ wins the second game depends on whether he is playing against $A$ or playing against $B$.  In the case he is playing against $A$ he has a worse chance of winning than usual.
Answer: Since $A$ has probability $0.7$ of beating all teams, it doesn't matter who wins in the $C$ vs. $D$ match. We have
$$P(A\text{ wins})= P(A\text{ wins twice})=0.7\cdot0.7=0.49$$
Similarly, since $B$ has probability $0.5$ of beating both $C$ and $D$, we can write:
$$P(B\text{ wins}) = P(B\text{ beats }A)P(B\text{ wins next game}) = 0.3 \cdot 0.5 = 0.15$$
By symmetry, the probability that $C$ wins is the same as the probability that $D$ wins. We have:
\begin{align}
P(C\text{ wins}) &= P(C\text{ beats }D)\left[P(A\text{ beats }B)P(C\text{ beats }A) + P(B\text{ beats }A)P(C\text{ beats }B)\right]\\
&=0.5(0.7\cdot0.3+0.3\cdot0.5) \\
&=0.5\cdot 0.36 \\
&= 0.18\\
&=P(D\text{ wins})
\end{align}
An easier way to get $P(C\text{ wins})$ is to divide the remaining probability $1 - (0.49 + 0.15) = 0.36$ by $2$, since $C$ and $D$ have the same chance of winning the tournament.
Comment: @OliverG nothing is wrong with the samplespace either person chose, but you are ignoring the chance that $A$ gets the chance to play against $C$ in the first place in your calculations.  If you want, you could write it like barnes did, but it gets tedious to parse: $A$ wins tournament $=$($A$ beats $B$ in rd1) and ((($A$ beats $C$ in rd2) and ($C$ beats $D$ in rd1)) or (($A$ beats $D$ in rd2) and ($D$ beats $C$ in rd1))), yielding the calculation $0.7\cdot((0.7\cdot 0.5)+(0.7\cdot 0.5))=0.49$
Comment: What is the sample space you're using here?  I don't understand what you mean by "$A$ wins twice".  I was assuming the sample space had two ways to win for each team as in $A$ wins by beating $B$ and $C$ or $A$ wins by beating $B$ and $D$.
Comment: @OliverG $A$ wins the first game with probability $0.7$, and $A$ wins the second game with probability $0.7$ as well, regardless of whether $C$ won or $D$ won in the $C$ vs $D$ game because $A$ wins with probability $0.7$ against everyone. "$A$ wins twice" means that $A$ wins in both the first and second round of the tournament.
Comment: Can you explain what sample space you chose?  What's incorrect about using the sample space I chose?
Comment: @OliverG It is the same sample space as yours. You simply calculated the probabilities incorrectly, as JMoravitz pointed out. The probability that $C$ wins the second game is not $0.5$, since the probability of $C$ winning against $A$ ($0.3$) is different from the probability that $C$ wins against $B$ ($0.5$)...
Comment: I think I understand now, the sample space I was using was incorrect.  Does it make sense to say the sample space elements are like $(A,C,A)$ where this means $A$ wins first round, $C$ wins first round, then $A$ wins the last round?  Then $P(A \text{ wins }) = P((A,C,A) \cup (A, D, A)) = P(A)P(C)P(A) + P(A)P(D)P(A)$?
Comment: @OliverG Yes, that seems to work!


How to change the background color to perticular word inside a h:inputTextarea

Question: I made a from with input text area, and the value will come from database.
value is some thing like : A 2 year notice has bean applied by mycompany with effect from 12 December 2012.
I want to hilight 12 December 2012 with some different background color.
Note: value will come dinamycally from database.
<h:inputTextarea cols="60" rows="5" id="messageId" style="margin-top:3px;"
    value="#{messageBean.textMessage}" />

How can i do this? Thanks !!
Answer: Since <h:inputTextarea generates <textarea
Its impossible
Take a look at this similar questions:
Change the Color Of Certain Words In Textarea using Jquery?
And
color codes in textarea using jquery
You can use some WYSIWYG text editor
Like this one used in Primefaes Editor
Or just integrate some third party js WYSIWYG text editor , like CKEditor or TinyMCE

You also can strip all the toolbars/buttons from the editor , so it will eventually look like almost like a textarea
Answer: No it is impossible.
But you can do a trick. You can make your <h:inputTextarea component transparent by using the css property background:transparent;. Then use another colored div and place it behind the word you want to highlight. Sometimes you may need to add display:inline-block;  to your highlighter div if JSF doesn't render the div with the width you give. A negative z-index may also be needed.


WebApi 2.0 OData, obtain list of SQL tables used in the query

Question: I have a fairly standard WebApi 2.0 OData 4.0 webservice using EF5, and code first approach. This service works and I can query entities and related entities through foreign keys.
The service is read-only and the controllers only have a Get and Get-by-key implemented.
public class MyTableController : MyDbController
{
    [EnableQuery]
    public IQueryable<MyTable> Get()
    {
        return db.MyTable;
    }

    [EnableQuery]
    public SingleResult<MyTable> Get([FromODataUri] int key)
    {
        IQueryable<MyTable> result = db.MyTable.Where(p => p.pk == key);
        return SingleResult.Create(result);
    }
}

In both Get() implementations, I would like to have access to the list of tables that are being used in the OData and resulting SQL query. MyTable is obviously one of them, but how do I obtain the others (among others, the ones used in (nested) $expand)? I can try to parse the URL myself, but that's doesn't seem like a very good way to go about it.
Answer:
Create a class CustomizeAttribute inherit from EnableQueryAttribute
Override this method : public virtual IQueryable ApplyQuery
then you get the queryOptions in this method, you can go to the SelectExpandQueryOption and find the ExpandItem, then you get all the table.
public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
{
    if (queryOptions.SelectExpand != null)
    {
        foreach (var selectItem in queryOptions.SelectExpand.SelectExpandClause.SelectedItems)
        {
            var expandedItem = selectItem as ExpandedNavigationSelectItem;
            if (expandedItem != null)
            {
                // get the entitySetName, tableName
                string entitySetName = expandedItem.NavigationSource.Name;
               // can go recursive with expandItem.SelectExpandClause in case we have $epxand=A($expand=B)
            }
        }
    }
    return base.ApplyQuery(queryable, queryOptions);
}

Use this attribute on Controller method
[CustomizeAttribute]
public IQueryable<MyTable> Get()
{
    return db.MyTable;
}


Como retornar o ultimo Registro de uma coluna SQL em uma textBox?

Question: Estou desenvolvendo uma aplicação para meu curso técnico que irá cadastrar clientes, no caso gostaria que antes de cadastrar o cliente o campo código retornasse o ultimo código da tabela sql + 1 para mostrar automaticamente o código que será registrado no cliente que esta sendo cadastrado. se alguém puder me ajudar ficaria muito grato. tentei esse código no form para retornar o valor:
private void cad_cliente_Load(object sender, EventArgs e)
        {
            comando.Connection = conn;
            {
                conn.Open();
                const int i = 1;
                comando.CommandText = "SELECT MAX(cod_cli) FROM cad_cli";
                dr = comando.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        textBoxCod.Text = "SELECT MAX(cod_cli) FROM cad_cli" + i;
                    }
                }

            }

        }

Answer: Quando precisas apenas de um valor podes e deves usar o ExecuteScalar
O codigo ficaria algo assim:
string sql = "SELECT MAX(cod_cli) FROM cad_cli";
using (var conn = new SqlConnection(sua_connection_string))
{
    var comando = new SqlCommand(sql, conn);
    try
    {
        conn.Open();
        int maxId = (int)comando.ExecuteScalar();
        textBoxCod.Text = (maxId + 1).ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Comment: no campo "using (var conn = new SqlConnection(sua_connection_string))" neste "sua_connection_string" eu usei conn no inicio do código, assim : SqlConnection conn = new SqlConnection("Data Source=luanpc\\SQLEXPRESS; Initial Catalog=cliente; Integrated Security=True"); seria "conn" mesmo ?


Give a counterexample disproving: $Boundary(Closure(A)) = Boundary(A)$

Question: I know that for set $A$, Closure($A$) = $A \cup L$ where $L$ is the set of limit points.
So $Boundary(A \cup L) = Boundary(A) $
It doesn't seem like it's true necessarily I just cannot give a concrete example.
Could anyone give an example showing A and it's closure, and its set of limit points please.
Comment: You would need for the interior of $\overline{A}$ to be bigger than the interior of $A$. You can obtain this if you have holes that are filled in the closure.
Comment: What is your definition of the boundary of a set?
Comment: @SantanaAfton -- My definition of the boundary of $A$ is the set of all points $P$ for which any open set $S\ni P$ contains some point in $A$ and some point not in $A$. An interior point has some open set $S\ni P$ containing only points in $A$. An exterior point has some open set $S\ni P$ containing only points not in $A$.
Answer: $A = \mathbb{Q}$ in the reals, usual topology.
its closure is $\mathbb{R}$ which has empty boundary.
its boundary is $\mathbb{R}$ which is non-empty.
Answer: How about a punctured disk?
Its closure is the whole disk, which has boundary a circle.
But the punctured disk's boundary is the circle along with the point in the middle.
Comment: I'm actually taking an intro to real analysis course, not a topological class. How could we represent a punctured disk in terms of a set?
Comment: $A = \{(x,y)\in\mathbb R^2\mid0<x^2+y^2<1\}$
Comment: $\overline A=\{(x,y)\in\mathbb R^2\mid x^2+y^2\leq1\}$ , $\text{bd}(\overline A)=\{(x,y)\in\mathbb R^2\mid x^2+y^2=1\}$ , $\text{bd}(A)=\text{bd}(\overline A)\cup\{(0,0)\}$


How to make a specific region use a specific template?

Question: I'm currently working on Drupal 7 project in a Zen sub-theme. Each of my region uses "region.tpl.php" as HTML/PHP template. I just created a new region called "foo". This region needs a different HTML/PHP than the other regions.
How do I make Drupal use my custom template "region--foo.tpl.php" instead of the default "region.tpl.php"?
Answer: I thought Drupal already added the theme hook suggestion for region--name.tpl.php, but if not you can add it yourself with a preprocess function in your theme's template.php file:
<code>function MYTHEME_preprocess_region(&$vars) {
  $vars['theme_hook_suggestions'][] = 'region__' . $vars['region'];
}
</code>
Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.
Comment: I'm not succeeding. I added the region "foo". I populated it with blocks. I copied "region--tpl.php", added extra code and renamed that file to region--foo.tpl.php. Then in template.php I added "function aura_preprocess_region(&$vars) {
  $vars['theme_hook_suggestions'][] = 'region__foo' . $vars['foo'];
}" and no modules are shown... What did I forget?
Comment: @Apex I think you've added rather than forgotten :) The `$vars['region']` variable will already have `foo` in it so that line should literally be: `$vars['theme_hook_suggestions'][] = 'region__' . $vars['region'];`
Comment: Ok succes! I forgot to add "" in page.tpl.php. So if I get this right, if region--foo.tpl.php exists it will overwrite region.tpl.php? If region--foo.tpl.php does not exists it simply uses region.tpl.php?
Comment: Yep, spot on :)
Comment: Awesome. Works like a charm. Also by removing the Zen theme's default region--footer.tpl.php the footer region finally gets the standard region template (region.tpl.php). Have been looking for that for quiet a while. Thanks a lot Clive, appreciate your help.


Percentage properties in MVC 3

Question: My application has many models, many of which contain percentage data. These are represented as decimal or decimal? structs in the model. However, not all properties with decimal structs are percentages. Some should be treated like regular decimals.
The percentages need special attention:

For display, they should use {0:P2} format. (I have this part working.)
For editing, they should allow the same format as the display, i.e. "95" or "95%" or "95.00 %" all bind to a value of 0.95.

I started down the road of creating a PercentModelBinder that implements IModelBinder, but then realized that you can only apply the ModelBinderAttribute to a class, not a property.
What's the best way to handle this case where some (but not all) uses of a type need special handling both for display and binding?
Every solution I think of smells badly of overkill, fighting the MVC framework. Surely there is a better way than:

Creating a custom Percentage struct and using it as the basis for the IModelBinder and EditorTemplates, or
Reimplementing the default binding behavior of decimal and decimal? and changing the parsing logic based on intimate knowledge of my model, or
Implementing a custom model binder for each class that contains a percentage property, or
Using fake proxy properties in the model (i.e. breaking MVC)
Comment: I think I'd consider writing a custom Data Annotation attribute if I were you. If that's something you're at all familiar with, take it and run with it. If not, comment back and I'll put some info together for you.
Comment: @Rick, I'd be very interested in seeing your implementation.
Comment: I'll get some links and sample code together tomorrow at the office and get them posted here.
Comment: I didn't get back to this until late today, and @Darin has already posted the gist of what I was going to outline, so I'll leave it in his hands. :-)
Answer: One possibility is to write a custom metadata aware attribute:
public class PercentageAttribute : Attribute, IMetadataAware
{
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["percentage"] = metadata.EditFormatString;
    }
}

then decorate your view model properties that represent percentages with it:
public class MyViewModel
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
    [Percentage]
    public decimal? Percentage { get; set; }
}

and inside the custom model binder test for the presence of this value:
public class PercentageModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelMetadata.AdditionalValues.ContainsKey("percentage"))
        {
            var format = (string)bindingContext.ModelMetadata.AdditionalValues["percentage"];
            // TODO: do the custom parsing here
            throw new NotImplementedException();
        }
        else
        {
            // Let the default parsing occur
            return base.BindModel(controllerContext, bindingContext);
        }
    }
}

Now you can register this model binder to all decimals.
Comment: Thank you, this worked very well, and was exactly the type of solution I was looking for.
Answer: Instead of representing your percentage properties using decimal primitives (see Primitive Obsession), why don't you create a Percentage type to wrap your desired functionality? You should have much more flexibility doing it that way...
Comment: Well, if you look at it from the perspective that it represents a concrete business requirement, it seems much more appropriate to me.
Comment: Yes, that was the first potential solution I mentioned in the original question. I'm not opposed to it, but it seems rather draconian to have to create another entire domain class just to get around the formatting and binding behaviour of a framework.
Answer: Bind to a string in your view model. Then when do the conversion back to the real model.
Comment: Yeah, I thought about that. (I added that as a solution I'd rather not consider in my question.) But then I have to do this with *every single percentage property*, plus it pretty much breaks the MVC paradigm.

Percentage properties in MVC 3


Theme preprocess for module's template variables using dynamic path

Question: I am doing templating for a module that adds a block in the module's folder so that the template can be there, and it may be overridden in the theme if desired. I want the module to support different "sources" (but only one will be active/used at a time), which may each have a separate template and variable preprocessing. I have hook_theme() working, and the template works. But the .vars.php file I have contains the preprocess function, and it doesn't get called.
Here is a basic example of what I have:
/MODULE.module
function MODULE_theme($existing, $type, $theme, $path) {
  $source = '';
  switch ($source) {
    case 'SRC_A':
      $path .= '/sources/SRC_A/theme';
    default:
      $source = 'default';
      $path .= '/theme';
  }

  return array(
    'MODULE_block' => array(
      'path' => $path,
      'variables' => array('data' => array(), 'source' => $source),
      'template' => 'MODULE-block',
    )
  );
}

/MODULE/sources/SRC_A/theme/MODULE-block.tpl.php
(contains template HTML with references to PHP variables)

/MODULE/sources/SRC_A/theme/MODULE-block.vars.php
/**
 * Implements template_preprocess_HOOK() for theme_MODULE_block().
 */
function template_preprocess_MODULE_block(&$vars) {
  // Add variables before they get to the template file.
  $vars['some_key'] = 'some_value';
}

I originally was trying to modify the $template value in hook_theme() to MODULE-block--SRC-A, but I decided that didn't matter, and if only one template is active at once I should just call them all MODULE-block.tpl.php regardless of the source, since they are all in different folders.
The template works, and adding a template in my theme will correctly override it. But the .vars.php file with the preprocess function does not seem to do anything unless it is in my actual theme and is THEME_preprocess_MODULE_block instead.
I'm still pretty new to this, but I looked at a lot of pages online, and there aren't any similar examples in my code base that have a module-specific .vars.php file that is located in the module's folder rather than in the theme.
I do not know what I am doing wrong. Any ideas?
Comment: I'm not sure I understand - if the template is defined in the theme layer, that will always override the original. That said, why not preprocess the template as you seem to do above with the variables you want to pass into the block?
Comment: @Kevin The template is not going to be defined in the theme layer right now. I'm leaving it open so that it can be, but it probably won't be. As I said above, I'm trying to preprocess the template to pass in the variables using `template_preprocess_MODULE_block`, but the function is never called for some reason. I don't know why. I looked using dpm() and `MODULE_block` is in the theme registry.
Answer: I figured it out. There was already a preprocess function with the name template_preprocess_MODULE_block in the module file. Declaring the same function a second time has no effect.


Adobe PDF reader com component C# open on specific pagenumber

Question: I am using the Adobe FDF reader from the com components in C#. It opens the PDF file I want in my form but it opens on page number 1. Does anyone know if I can open it for example on page number 5?
Here is the code that I user:
pdfWiki.src = pdfWiki.src = "F:\\STAGE\\test.pdf";

Hope u could help me..
Thanks!
Comment: After looking at the properties of the element I found the solution:

            pdfWiki.src = pdfWiki.src = "F:\\STAGE\\test.pdf";
            pdfWiki.setCurrentPage(NUMBER);

Replace NUMBER for the pagenumber you want to visit!
Answer: Try this:
pdfWiki.src = @"F:\\STAGE\\test.pdf";
pdfWiki.setCurrentPage(5);


Python Frequency table

Question: I want to make frequency table by below table.
number       1         2         4         6       Sum
frequency   0.4      0.25    0.15    0.2    1
And I wrote the below code.
import random
from collections import Counter

number = [1, 2, 4, 6]
probability = [0.4, 0.25, 0.15, 0.2]

def Cdf(p):
  y_cdf = []
  s = 0
  n = len(p)
  for i in range(0, n):
    s = s + p[i]
    y_cdf.append(s)
  return y_cdf

def rand_G(p):
  q = random.uniform(0, 1)
  n = len(p)
  c = Cdf(p)
  for i in range(0, n):
    if q <= c[i]:
      return i

def rand2_G(p, n):
  a = []
  for i in range(n):
    a.append(rand_G(p))
  return a

def Table(a):
  c = Counter(a)
  pair = c.most_common()
  pair.sort()
  print('Number\tFrequency')
  for x in pair:
    print('{0}\t{1}'.format(x[0], x[1]))

data = rand2_G(probability, 10000)
Table(data)

But result is
Number  Frequency
0   3990
1   2495
2   1521
3   1994
Above Table, Number is not 1,2,4,6.
How can I make frequency table with number 1,2,4,6(above number list)?
Comment: What is the relationship of `Cdf`, `rand_G`, `rand2_G` to your question?
Answer: Starting with python 3.6, there is random.choices:

random.choices(population, weights=None, *, cum_weights=None, k=1)
  Return a k sized list of elements chosen from the population with
  replacement. If the population is empty, raises IndexError.
If a weights sequence is specified, selections are made according to
  the relative weights. Alternatively, if a cum_weights sequence is
  given, the selections are made according to the cumulative weights
  (perhaps computed using itertools.accumulate()). For example, the
  relative weights [10, 5, 30, 5] are equivalent to the cumulative
  weights [10, 15, 45, 50]. Internally, the relative weights are
  converted to cumulative weights before making selections, so supplying
  the cumulative weights saves work.
If neither weights nor cum_weights are specified, selections are made
  with equal probability. If a weights sequence is supplied, it must be
  the same length as the population sequence. It is a TypeError to
  specify both weights and cum_weights.
The weights or cum_weights can use any numeric type that interoperates
  with the float values returned by random() (that includes integers,
  floats, and fractions but excludes decimals).

Python Frequency table


angular2 table with dynamic rows and columns

Question: How do I create a table with dynamic columns and rows in angular2
I have the data coming from a rest service and captured in this observable
this._physicalDataService.getPhysicalData().subscribe(res=> this.data = res)

I can display the rows dynamically through this code. How do I make the columns and the column headers dynamic too ie how can i extract all the JSON keys in an array to put another loop on top.
To clarify my backend service may return different datasets with different columns and row and I want to show them dynamically on a page.

                          Id
                          Number
                          Employee Name
                          Manager Name

                          {{tablerows.row_id}}

                          {{tablerows.number}}
                          {{tablerows.employee_name}}
                          {{tablerows.manager_name}}

Answer: You can use same *ngFor on your 	 too.
But For that you will need to calculate length of Object.It Will give you no of elements in each Array.
var custObject = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
this.objLength = Object.keys(myArray).length;  // Calc length of Object i.e. 3

After You Have length of Object , You can render your  block that many times using below pipe:

Column{{i}}

Pipe:
import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
  transform(value, args:string[]) : any {
    let res = [];
     for (let i = 0; i < value; i++) {
        res.push(i);
     }
    return res;
  }
}

This will calculate no of Object fields & then ngFor will render Coulmn+index for each field.
Hope this helps.
Comment: Thank You. These hints helped a lot. I got it working
Comment: @SaurabhVerma glad to hear. close the question by accepting the answer if your query is resolved


Artisan Laravel não instalado

Question: Instalei o laravel com composer tudo funcionando ... Utilizo comandos como laravel new projeto, porém se uso um comando como php artisan list ele informa que o comando artisan não é reconhecido... Como posso "instalar o artisan"?
Obs :

Uso Mac
Uso MAMP
Comment: Quando tento chamar esse comando, você estava na pasta do projeto no terminal?
Comment: @rray era isto mesmo... não sabia... por favor escreva isso em uma resposta para oder dar como aceita.
Answer: Para utiliza os comandos do artisan é necessário estar na pasta do projeto no terminal.
Comment: @augustoFurlan, pode editar se tiver mais alguma coisa para complementar.
Answer: dentro da pasta do projeto você deve dar composer install para instalar as dependências do projeto

Artisan Laravel não instalado