How to get all parent menu items' titles of the current node?

Question: I know I can load the node's menu item like so:
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

But to use a menu structure in a breadcrumb I need to load all parent menu items. I feel like the menu service provides such a function but I dont get anything out of the documentation. This here seems pretty mighty but it really lacks documentation.
Edit: I've already came this far:
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

if (is_array($menu_link) && count($menu_link)) {
  $menu_link = reset($menu_link);
  if ($menu_link->getParent()) {
    $parents = $menu_link_manager->getParentIds($menu_link->getParent());
    dpm($parents);
  }
}

and it gives me:
Array
(
  [menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e] => menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e
  [menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4] => menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4
)

Is there an easy way to get those titles?
Answer: Even shorter using the MenuActiveTrailInterface.
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    $breadcrumb->addLink(
      new Link(
        $menu_link_manager->createInstance($value)->getTitle(),
        $menu_link_manager->createInstance($value)->getUrlObject()
      )
    );
  }
}

Comment: Where would you initialize the breadcrumb variable to begin with?
Comment: @ref : https://www.drupal.org/node/2240003
Answer: In case it help anyone I used a combination of Alex's solutions to write a function that returns the parent menu item for the current node.
function mymodule_get_parent_menu_title() {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');

  $node_id = \Drupal::routeMatch()->getRawParameter('node');
  if ($node_id) {
    $menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
  }
  else {
    return '';
  }

  if (is_array($menu_link) && count($menu_link)) {
    $menu_link = reset($menu_link);
    if ($menu_link->getParent()) {
      $parents = $menu_link_manager->getParentIds($menu_link->getParent());
      $parent = reset(array_reverse($parents));
      $title = $menu_link_manager->createInstance($parent)->getTitle();

      return $title;
    }
  }

  return '';
}

Answer: So, this code works but I doubt that this is the most performant way of doing it...
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

if (is_array($menu_link) && count($menu_link)) {
  $menu_link = reset($menu_link);
  if ($menu_link->getParent()) {
    $parents = $menu_link_manager->getParentIds($menu_link->getParent());
    if (is_array($parents) && count($parents)) {
      $_parents = array();
      foreach ($parents as $key => $uuid) {
        $uuid_parts = explode(':', $uuid);
        $_parents[] = array_pop($uuid_parts);
      }

      $mlc_ids = \Drupal::database()
        ->select('menu_link_content', 'mlc')
        ->fields('mlc', ['id'])
        ->condition('uuid', $_parents, 'IN')
        ->execute()
        ->fetchCol();

      if (is_array($mlc_ids) && count($mlc_ids)) {
        $titles = \Drupal::database()
          ->select('menu_link_content_data', 'mlcd')
          ->fields('mlcd', ['title', 'link__uri'])
          ->condition('id', $mlc_ids, 'IN')
          ->execute()
          ->fetchAllKeyed();

        foreach ($titles as $title => $entityUri) {
          $breadcrumb->addLink(new Link($title, Url::fromUri($entityUri)));
        }
      }
    }
  }
}

edit: but this does not even add menu items that do not come from nodes (for instance from views). See my other answer!
Answer: Alex, your previous code works well, thanks !
For making it works with views or other routes, you have to use :
  $route_name = \Drupal::service('current_route_match')->getRouteName();

instead of using the node's route
Something like
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');

  $node_id = \Drupal::routeMatch()->getRawParameter('node');

  if ($node_id) {
    $menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
  }
  else {
    $route_name = \Drupal::service('current_route_match')->getRouteName();
    $menu_link = $menu_link_manager->loadLinksByRoute($route_name);
  }


como posso fazer uma div se esconder na lateral e quando clicada aparecer na tela?

Question: Como posso fazer a div se esconder na lateral da tela? repare no menu lateral desse site http://preview.imithemes.com/?theme=Solicitor-WP tentei de um modo mas não foi alguém sabe um meio? o meu coloquei display none e no js coloco block, porém tenho sempre que voltar para none depois se não as telas ficam bloqueadas, para piorar o botão do menu gera um atraso para voltar, ou seja quando a div volta para se esconder no animate o botão não volta colado nela, tem algum modo de deixar isso mais elegante?

function modalOpen(){
            $(document).ready(function(e){
            tamanho = $('.modal-box').css("width");
             $("#box1").animate({right: '0px'});
             $("#botao").animate({right: tamanho});
             $('#modal').css("display","block");

            /*FECHAR O MODAL SE O BOTÃO CANCELAR FOR PRESSIONADO */
            $('.cancel, #modal').click(function(event){
                if(event.target !== this){
                    return;
                }
                 $("#botao").animate({right: '0px'});

                 setTimeout(function() {  $("#box1").animate({right: '-410px'}); }, 30 );
                 setTimeout(function() { $('#modal').css("display","none"); $("#box1").animate({right: '-410px'}); }, 400);
            });

        });

        }
#modal {
    background: rgba(0, 0, 0, 0.1);
    width: 100%;
    height: 100%;
    position: fixed;
    display: none;
    left: 0;
    top: 0;
}
@font-face {
    font-family: "Eurostile";
    src: url('font/Eurostile.ttf');
}
.Eurostile-font {
    font-family: "Eurostile";
}
.btn_modal {
    color: white;
    margin-bottom: 10px;
    background-color: darkgrey;
    border: none;
    font-size: 19px;
}
.btn_modal:hover {
    background-color: honeydew;
    color: black;
}
.modal-box {
    background-color: #FFF;
    width: 20%;
    height: 405px;
    position: absolute;
    right: -410px;
    top: 130px;
    margin-left: -20%;
    z-index: 1000;
    font-family: Eurostile;
}
#modal_form {
    display: block;
    margin: 0 auto;
    z-index: 10000;
}
.itens {
    margin-left: 10%;
    display: block;
    margin-top: 3%;
    z-index: 10000;
    font-family: Eurostile;
}
.itens input {
    line-height: 10px;
    display: block;
    width: 90%;
    z-index: 10000;
}
#bairro {
    display: block;
    margin-right: 10%;
    width: 155px;
    z-index: 10000;
}
#box {
    display: flex;
    margin-top: 0;
    width: 90%;
    height: 60px;
    resize: none;
    z-index: 10000;
}
#form_title {
    text-align: center;
    background-color: grey;
    color: white;
    padding: 0;
    z-index: 10000;
    width: 100%;
    height: 50px;
}
#form_title h3 {
    float: left;
    margin-left: 5%;
    padding-top: 10px;
    margin-bottom: 0;
}
#modal_form {
    width: 80%;
    height: 400px;
    z-index: 10000;
}
.button {
    width: 160px;
    margin-top: 10px;
    height: 30px;
    background-color: grey;
    color: white;
    z-index: 10000;
    display: block;
    font-family: Eurostile;
}
.button:hover {
    background-color: black;
}
#modal_form {
    width: 100%;
    height: 430px;
}
.cancel {
    margin-right: 2%;
}
.send {
    margin-right: 8%;
}
#cbBox {
    line-height: 10px;
    display: block;
    width: 81%;
    z-index: 10000;
    margin-left: 10%;
    margin-top: 10px;
}
#changeText {
    font-size: 20px;
    float: left;
    margin-left: 5%;
    padding-top: 10px;
    margin-bottom: 0;
    font-family: Eurostile;
}
#align-btn {
    width: 180px;
    display: flex;
    margin: 0 auto;
}

                <form name="contactform" id="modal_form" method="post">

Register for valutation

                    Full name<input class="campo" type="text" name="fullname">
                    Adress<input class="campo" type="text" name="adress">
                    Postcode<input class="campo" type="text" name="postcode">
                    E-mail<input class="campo" type="email" name="email">
                    Telephone <input class="campo" type="text" name="telefone">
                    Message <input class="campo" type="text" name="message">

                        <input class="button send" type="submit" value="Send" onclick="return validar();">
                        <input type="button" class="button cancel" value="Cancel">

                </form>

Answer: Olá amigo em vez de usar o modal use a biblioteca JQuery
Nela tem o SlideToggle
Faz esse efeito
Baixe a biblioteca e realize o teste.
No HTML

Titulo

         Seu texto introdução, seu texto introdução, seu texto introdução, seu texto introdução, seu texto introdução, seu texto introdução,

 seu texto completo, seu texto completo, seu texto completo, seu texto completo, seu texto completo, seu texto completo, seu texto completo, seu texto completo.

         Saiba mais.

No CSS
#new {display:none; margin-top:0px;}

No fim do HTML
o JavaScript

Espero ter ajudado.
Answer: Olá você pode conseguir usando esse feito utilizando CSS Transition e um pouco de JS.
Você deve ter uma classe que sera o container em todo o menu lateral.

  <button>Toggle</button>

      0001

      0002

      0003

O Css da classe você deve informar a largura e position relative. No campo left informe a largura do menu multiplicado por -1.
Se seu menu tem 500px left será -500px;
.menu{
  height: 300px;
  width: 100px;
  background:red;
  position: relative;
  transition: all 0.5s;
  left: -100px;
}
Dentro do menu você terá o botão que será responsavel ocultar ou nao.
Este botão será position absolute com uma largura definida e seu right será a largura multiplicada por -1.
Dessa forma ele fica fora do menu e estará visível quando o menu estiver oculto.
button{
  position:absolute;
  width: 50px;
  right: -50px;
}

Uma classe .active para exibir o menu
.active{
  left: 0px
}

Uma função JS que sera responsavel por tratar o click no botão e exibir ou nao o menu.
$('button').click(function(){
    if($('.menu').hasClass('active')){
    $('.menu').removeClass('active');
  }else{
    $('.menu').addClass('active');
  }
})

Veja esse exemplo funcionando
https://jsfiddle.net/g86p79xd/2/
Answer: https://www.w3schools.com/howto/howto_css_sidenav_buttons.asp
Aplique este conceito lógico na sua aplicação, não fique preso ao tamanho das divs ou nada do tipo. Depois que você entender este funcionamento tenho certeza que conseguirá resolver seu problema! Grande Abraço!
Comment: obrigado a todos me ajudaram muito


T4MVC in ASP.NET MVC4 vs2013

Question: I have legacy mvc3 project wich was migrated from mvc2. There is T4MVC in use. First of all i would like to mention that guys who migrated to MVC3 left ProjectTypeGuids for MVC2.
I migrated to mvc4 by following http://www.asp.net/whitepapers/mvc4-release-notes#_Toc303253806 guidelines.
Now i am unable to open this project in vs2010 because its not supported, right?
After i succesfully migrated to mvc4 there was hundreds of errors in t4mvc generated classes and i could not run .tt custom tool again (error in .tt files method GetMvcVersion). I took newer t4mvc version from nugets.

Now, when i run T4MVC.tt custom tool my vs2013 express throw error "An
  unhandled microsoft .net framework exception occurred in
  VWDExpress.exe [6520]" and allows me to choose possible debuggers.
  After i choose vs2010 (not express) it runs succesfully.

http://t4mvc.codeplex.com/documentation
is it posible to use it in vs2013? T4MVC Documentation page says not.
Over all i got few errors in Views like:

..Views\Shared_PaginatePrevious.cshtml(14): error CS0234: The type or
  namespace name 'Assets' does not exist in the namespace 'Links' (are
  you missing an assembly reference?)

<img src="@(Links.Assets.Images.p_left_png)" alt="<" title="@(Shared.PreviousPage)" />

Do i have to add namespace Links to tt template ?
After commenting out all errors, my project is running succesfully.
Overall regarding on documentation wich says:
T4MVC runs in both Visual Studio 2008 SP1 and Visual Studio 2010, and supports both ASP.NET MVC 1.0 and 2.0.
http://t4mvc.codeplex.com/documentation
Does T4MVC is still in use today for MVC4+,  and vs2012+?
What should i do with VS2013 bug?
Answer: I have a .net 4.5 solution in VS2012 which is MVC4. This was upgraded from a .net 4 vs2010 MVC3 and during the upgrade I had to upgrade the version of T4MVC to 3.7.4 to get it to work.
I did have to uninstall T4MVC completely and re-install though through nuget. You will need the latest version however as 3.7.4 wont work with vs2013.
Check your version, do a complete uninstall and reinstall if you havent already done so and have a look  here for further info from T4MVCs creator.
Comment: T4MVC Version is 3.8.0 However i am not getting error in my code. VS2013 just dies during "Run custom tools" command. Perhaps its because of bug in Vs.
Comment: The doc was out of date. I just updated it to reflect that it works with the latest VS & MVC.

T4MVC in ASP.NET MVC4 vs2013


Adding items to dictionary from a dictionary

Question: I want to copy an item from one list to another. For example:
chest = {}

chest["sword":1,3]
chest["gold":5]

inventory = {}

inventory.add(chest["sword"])    #example pseudo code

How would I add 1 item from "chest" to "inventory", keeping the key name, and values?
Thanks for any help!
EDIT TO AVOID CONFUSION:
I want to be able to add a SINGLE item from, say "chest" to "inventory". so:
inventory = {}
chest = {"sword":1, "gold":5, "other item":"other data"}

I want to take 1 item from "chest" (depending on user input) and add it to "inventory":
inventory.add( chest [ item_from_chest ] ) #exampe pseudo code

after this inventory world look like this:
>>>{"sword":1}

Sorry for any confusion, hope this edit helps!
Comment: Your question has some syntax errors. What do you expect do accomplish with `chest["sword":1,3]`?
Comment: @Bonifacio2 sword would have 2 values, say, for damage and weight. This is just example code, it works in real life :)
Answer: Most probably you will need some merging algorithm in order not to overwrite existing items in you inventory. Something like:
#! /usr/bin/python3.2

import random

prefices = ['', 'Shabby', 'Surreal', 'Gleaming', 'Muddy']
infices = ['Sword', 'Banana', 'Leather', 'Gloves', 'Tea Cup']
suffices = ['', 'of the Bat', 'of Destruction', 'of Constipation', 'of thy Mother']

def makeItem ():
    tokens = [random.choice (fix) for fix in (prefices, infices, suffices) ]
    return ' '.join (t for t in tokens if t)

def makeChest ():
    chest = {'Gold': random.randint (5, 20) }
    for _ in range (random.randint (0, 5) ):
        chest [makeItem () ] = 1
    return chest

inventory = {}
while True:
    chest = makeChest ()
    print ('\n\n\nThou hast found a chest containing: {}'.format (', '.join ('{} {}'.format (v, k) for k, v in chest.items () ) ) )
    r = input ('\nWhishest thou to pick up this apparel? [y/*] ')
    if r not in 'Yy': continue

    for k, v in chest.items ():
        try: inventory [k] += v
        except KeyError: inventory [k] = v

    print ('\n\nThy bag now containth:')
    for k, v in inventory.items ():
        print ('    {:6d} {}'.format (v, k) )

Example Session:
Thou hast found a chest containing: 13 Gold

Whishest thou to pick up this apparel? [y/*] y

Thy bag now containth:
        13 Gold

Thou hast found a chest containing: 1 Shabby Gloves of Destruction, 1 Surreal Sword, 1 Gleaming Gloves of Constipation, 7 Gold

Whishest thou to pick up this apparel? [y/*] y

Thy bag now containth:
         1 Shabby Gloves of Destruction
         1 Surreal Sword
         1 Gleaming Gloves of Constipation
        20 Gold

As you see the gold got added. Also if you find another Surreal Sword, you will have 2 in your inventory.
Answer: You can use dictionary update():

Update the dictionary with the key/value pairs from other, overwriting
  existing keys.

>>> chest = {}
>>> chest = {"sword": 1, "gold": 5}
>>> inventory = {}
>>> inventory.update(chest)
>>> inventory
{'sword': 1, 'gold': 5}

Or, if you need just one sword item, simply:
>>> inventory['sword'] = chest['sword']
>>> inventory
{'sword': 1}

Or, if there are several keys you need to copy (but not all of them):
>>> keys_to_copy = ['sword']
>>> inventory.update(((key, chest[key]) for key in keys_to_copy))
>>> inventory
{'sword': 1}

Comment: This answers the question, but I fear that OP will need some merge algorithm for cases like "You have 5 gold pieces in your inventory and find a chest containing a sword, a banana and 3 gold pieces".
Comment: Thanks! But is it possible to just add 1 item from "chest"?
Comment: @Inazuma then, I'm not sure I'm getting the real issue you have. Could you edit the question and provide what the `inventory` should look like after? (simple example: input/output) Thanks.
Comment: @Hyperboreus yeah, probably, smells like World of Warcraft :)
Comment: @alecxe I tried to take this into consideration in my answer.


Is there anyway to get the $form_state inside a hook_block_configure?

Question: Is there any way to get the $form_state inside a hook_block_configure()? I'm trying to do that to make #ajax work on hook_block_configure().
Comment: I am facing the same situation (need to implement ajax at block configure page). Why is this too localized?
Answer: You don't have this information, but you can access to it with hook_form_alter. But to access to this form (that call block_configure) you have two form_id block_admin_configure and block_add_block_form.
Comment: Please post your solution as an answer to accept it and help other to figure this out.
Comment: I made a workaround using ajax_get_form function and it worked


Problem with PDO MySQL

Question: For the last couple of days I've been getting the following error:

Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /home/mydomain/public_html/drupal/includes/database/mysql/database.inc on line 46

This comes after my Hosting did an upgrade and PHP is now version 5.2.17.  From what they have told me, I think I have to enable a PDO MySQL extension in php.ini.  The problem is I'm on a shared hosting and I don't have access to the file; also, my Hosting said they can't change it either.  My info.php shows:

PDO
PDO support enabled
     PDO drivers sqlite, sqlite2
pdo_sqlite
     PDO Driver for SQLite 3.x enabled
     PECL Module version (bundled) 1.0.1 $Id: pdo_sqlite.c 293036 2010-01-03 09:23:27Z   sebastian $
     SQLite Library 3.3.7

I tried modifying the .htaccess file and/or adding my own php.ini file to the root directory per some suggestions I found, but nothing I've tried has worked yet.
Can anyone please suggest what else I could do?
EDIT:
Once again I asked the Hosting to enable PDO_MySQL extension and their answer was that they could not, that cPanel (to which they migrated from Plesk, causing this whole problem) had this extension disabled by default and changing it would affect their servers.  Their solution?  That I would change my programming to adjust to these new features, which I wouldn't even know how to go about.  Are they right requesting that I do this? Is there any other way?
Answer: Your hoster needs to enable that extension. I don't think you can do that in a local php.ini file.
I don't believe that they can't do it, they just need to add an extension=pdo_mysql.so to the php.ini, install the package, depending on whatever setup they are using. It's their job to do that, pdo_mysql is a hard requirement for Drupal 7.
Comment: I already asked them, but their reply was that due to restrictions on shared hosting accounts they can not alter the configuration, and that I only have whatever variables that are already enabled under info.php.
Comment: Then you need to look for another hosting provider. I wouldn't want to rely on a hosting provider that is incapable of enabling a PHP extension :)
Comment: After escalating this with the hosting they finally enabled the extension.  But I already talked my client into changing to another provider :)  Thank you.
Answer: In my case when I swap PHP version in WAMP this error stopped me.
I checked my phpinfo() then i observed PDO is enable but it's value is Blank
Solution :
Go to in your php.ini file and find "extension_dir" and changed it's path to current working php's ext directory.
ex/: extension_dir = "c:/wamp/bin/php/php5.2.9/ext/"
Restart you wamp, it will start working again ....

Problem with PDO MySQL


Setting Viewport width in Sencha Touch 2

Question: My Sencha Touch 2 app works perfectly on my desktop browser but when I test it on the iPhone the viewport is not set correctly.
My app has a fixed layout with a width of 640 Pixel. On iPhone 3G, only half of the app is seen. Inspecting the generated html I can see multiple "viewport" declarations in the  section, e.g.
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">

I figured I have to set the viewport width to 640 and inserted this code at the end of the  section:
<meta name="viewport" content = "width=640,initial-scale=1.0,user-scalable=no" />

but to no avail. Why does Sencha Touch insert multiple viewport declarations? How can I override it? Or what do I have to do to display the app in full width?
Any help will be very much appreciated.
Answer: Regarding meta tag, the width property controls the size of the viewport. It can be set to a specific number of pixels like width=600 or to the special value device-width value which is the width of the screen in CSS pixels at a scale of 100%.
Regarding your problem, there may be some content which might crossing the width of device, Either you need to add the scroll bars or need to take inbuilt controls of sencha.


Does UDP includes of source address?

Question: Both UDP and TCP does not include source address, but how does it say UDP IP spoofing is easier than TCP? For example, the following webpage also says about UDP vulnerability.
"Unlike TCP, UDP does not have a mechanism for verifying a packet source, which makes it very vulnerable to source-packet spoofing and inception attacks."
http://www.onlamp.com/pub/a/onlamp/2004/10/14/dnssec.html
Please help me to understand.
Answer:
Both UDP and TCP does not include source address

Your question is based on a misunderstanding. It's true that neither UDP or TCP headers include a source address, but that's because they don't have to: source address is already included in the header of the encapsulating transport protocol, which in this case would be the IP header.
As for why UDP spoofing is of particular note:

TCP sessions are initiated with a three way handshake before payload is delivered. (SYN, ACK, SYN ACK) The device holding an IP address that another is spoofing will refuse an unexpected ACK or SYN ACK packet, preventing the session from being established. This still wastes the resources of the victim, but is not very bandwidth efficient.
There is no handshake required to begin transmitting a payload via UDP. Any authentication of packets must be implemented within the payload itself and is not built into the protocol. Services which commonly do not implement such checks (DNS, NTP) are therefore vulnerable to source address spoofing, since the software will assume that any incoming data with a spoofed source address is valid and reply with the requested information.
Since many UDP based applications can be fooled into replying to a small UDP query with a much larger UDP reply, it's more bandwidth efficient for malicious parties to leverage these in their attacks. This phenomenon is referred to as an amplification effect.
Answer: Assume you want to spoof a DNS request, because a DNS server will answer to both UDP and TCP.
How many packets do you have to send for a DNS request by UDP -- and how many packets do you need for the same request by TCP? Which attack is easier?
Comment: what................?
Comment: To answer a question, with a riddle.  Maybe there should be a different site for that...

Does UDP includes of source address?


createMaterialTopTabNavigator can't modify tabStyle paddingVertical

Question: Two lines up and down are createMaterialTopTabNavigator,I wont to customize the next line, but I can't remove paddingVertical part like the picture
tabBarOptions={{
          scrollEnabled: true,
          style: {
            backgroundColor: 'transparent',
          },
          tabStyle: {
            width: 'auto',
            margin: theme.sizes.radius,
            padding: 0, //only horizontal works,how to modify vertical padding ?
            backgroundColor: 'yellow',
          },
          labelStyle: {
            margin: 0,
            backgroundColor: 'red',
          },
          activeTintColor: theme.colors.default,
          renderIndicator: () => null,
        }}

Comment: tabStyle: {minHeight: null} works
Answer: Try just style under tabBarOptions
tabBarOptions={{
    labelStyle: { fontSize: 12 },
    tabStyle: { width: 100, height: 100 },
    style: { backgroundColor: 'powderblue' },
}}

Detail here tabnavigator-extra-padding
Comment: Thank you, but I found the solution, source code has minHeight:48,so only set tabStyle: {minHeight: null} works.


What is the probability that a person will die on their birthday?

Question: I am curious about what the probability is that a person will die on their birthday?
I am sure there are a number of ways to approach this, plus I have heard that actual numbers point to a higher rate on birthdays, hence why I am asking it here.
Comment: Probability that when they die, it will be their birthday? Or probability that on their (n-th) birthday, they will die? In other words, determine the probability field, the outcome, and the condition.
Comment: @ttnphns the former, but I like the distinction.
Comment: Depends if they like their presents
Answer: Sorry, a bit new here so please excuse me if this doesn't help too much.
The US Social Security Administration keeps records of births and deaths and has their information available for purchase (apparently for a hefty price): Here
However I found a source that claims to have bought it and is offering it for free (as well as offering the data sorted by date on the site): Here
I'm assuming you can just use that as your sample and go through all the data with a script and find how many people actually die on their birthday. I would do that myself but I have 20 min left to download (they're about 1.5GB) so I'll try to get back to you on the statistics myself if I find the time to write up a script.
Of course the United States can't represent the entire world's population but it is a good start. I'm assuming you will see a higher rate in deaths on birthdays because of "first world problems" because we're using the United States and I think the effect would be less visible across the world...
Update - Numbers :D
I've ran through the Social Security Death Master File from the free source, so there's no way knowing if the information is valid. However, given the size that they're ~3 Gigabytes each and that there's no reason for anyone to spoof these kind of files... I'll assume they are valid.
You can see the code that I used to run through it here: http://pastebin.com/9wUFuvpN
It's written in C#, it reads through the lines of the death index one by one and then parses the date using regex. I assumed that the file was basically this format:
`(Social Security Number)(First Name)   (LastName)   (Middle Name)    (Some Letter)(MM-DD-YYYY of Death)(MM-DD-YYYY Of Birth)`

I had regex just pick out the last part for the dates of birth/death, check if any of the fields are just 0 (which I'm assuming it means that Social Security couldn't get a valid month/date for the record), and discard the 0's. Then it'll check if the day of birth and month of birth match the day of death/month of death and add that to the died on birthday count. It'll add all records that aren't 0's to the death count.
It outputs the results in this format:
Deaths On Birthday/Total Deaths   Lines Looked Through - People With a 0 in any of their record
It's be great if someone could double check that code, as I've found quite a few errors I've made before and could only tell because my results made no statistical sense.
Here is the console output:
Doing some math...

File 1 had 44665 Deaths on a Birthday out of 14879058 Deaths in Total
File 2 had 47060 Deaths on a Birthday out of 15278724 Deaths in Total
File 3 had 49289 Deaths on a Birthday out of 15374049 Deaths in Total
Total we have 141014 Deaths on a Birthday out of 45531831.

So we have ~0.3097% chance of dying on a birthday while statistically (1/365) would lead us to believe there is only ~0.27397% chance of dying on a birthday. That is indeed a 13% increase in chance of death on a birthday from 1/365. Of course this sample is only for Americans and only has 45 million records, I'm sure organizations who originally published their paper had access to much more reliable and larger death indexes. However, I think that it is indeed valid that deaths on a birthday is more likely than death on any other day.
Here's a Time article citing jumps in reasons for death on birthdays: Article
Edit 2: @cbeleites pointed out that I forgot to account for same day deaths, which would be a huge factor in increasing deaths on birthdays. Strictly speaking my data is still valid but I did not throw out if a person died on the same day they were born. It's interesting that my results were not affected too heavily by this error so it seems that these records don't include death on first day. I'll look into it later. I'm thinking there would be very interesting statistics I can look for such as death on days of the month and make a heatmap of some sort. I'll probably try to do that sometime...
Comment: No, this is interesting too. I was hoping to think about this question beyond simply `1/365`.
Comment: You need to take in account errors due to counting statistics. Roughly speaking the relative uncertainty in these calculation is going to be about 1/sqrt(47000) = 0.5%. So these differences are not statistically significant.
Comment: Can you post a link to the free data?
Comment: Sorry, I messed up pasting the second link. I fixed it on my post but here you go: http://ssdmf.info/download.html I currently can't do the script because I have some college apps to finish and the files are 2GB each... :(
Comment: @Dave31415: Isn't the denominator $\sqrt{45531831}$? That makes it very statistically significant.
Answer: We can be even more precise than @Mike Shi's data: the most dangerous of all birthdays is the very first one.
The 1st day mortality rates reported there are around 0.2 % for industrialized countries and 0.8 % average for all countries. Which means that the risk of dying on the day of birth is at least as high as the risk of dying at any of the following birth days*.
* I think it is a safe assumption that 1st day deaths do not appear in @Mark Shi's file, as the US 1st day mortality rates are reported to be 0.3 % (other source: 0.26 %). Which is almost the total birth day death rate in the social security file. So either babies who die at the day of birth do not get a social security number, or dying on a birth day > 1 year is extremely improbable.

side note:
There are other days, such as Chirstmas and New Years Eve which are known to have higher-than-average mortality rates as well.
Comment: Ah yes, I forgot to account for deaths that occur on the same day as the birth. I'm assuming this was excluded from the data as the hospital would have to submit this data to the state for a birth certificate and they wouldn't submit data on babies who die I'm assuming. This has lead me to a series of awkward Google searches... "do dead babies get a social security number"... oh search history.
Answer: Here's an argument why the probability of death on the birthday may be higher than on other days: Birthdays are emotionally charged days. More over, people tend to celebrate it somehow.. So there is an excess of factors (relative to the person's usual life style) that increase biological stress (excess emotions, excess drinking, excess eating, excess dancing, excess banjee jumping etc). Statistically speaking, this situation increases the chances of dying on a birthday, since it intensifies any health issues a person may have, or because it exposes the person to situations and risks for which the person is inexperienced.
Comment: sure. but rather than speculate, let's measure :)
Comment: I would think that it should in fact be lower. In the US more births occur near August, and most deaths occur in the winter due to the cold. But maybe the effect of too much cake and drinking overshadows seasonality :)
Answer: The probability that a newborn dies within a year can be found in the life tables. For example, you can check out the periodic life tables and look at the column $q_x$ for $x=0$ in the human mortality database. This is not exactly want you want, but will give you an idea.
Answer: In addition to the other excellent answers, but there is a point none of them discussed: Birthdays are not uniformly distributed over the year, and neither are deathdays. That conspires such that the "statistical" probability is not 1/365.  To get an idea of this effect, lets first assume they are both almost uniform, only 29 february has a probability 1/4   of the others. That gives
$$
    365 p + \frac14 p=1
$$
so $p= 0.002737851$. That leads to probability of birth and death on the same day equal $356\cdot p^2 + (p/4)^2=  0.002736445  > 0.00273224=\frac1{366}$ which is the minimum possible value (with 366 days).
With a bit more generality, let $p_i, i=1, \dotsc, n$ be the birthday probabilities, and $q_i, i=1,\dotsc,n$ the deathday probabilities, for a year with $n$ days. Then, if birthday and deathday for a person are statistically independent, we will find that
$$ \DeclareMathOperator{\P}{\mathbb{P}}
\P(\text{Birth and death on same day}) = \sum_{i=1}^n p_i q_i
$$
so if $p_i=q_i$ then that is $\sum_i p_i^2$. That is a quantity known (in biology) as Simpsons index of (bio)diversity. Its inverse  could then be taken as "effective number of days (in a year)"! The minimum value of $\sum_i p_i^2$ is $1/n$. To see that use convexity.
But assuming $p_i=q_i$ is quite a stretch, lets first look at some data, birthday probabilities for Norway calculated from data from ssb.no:

Clearly not uniform, the high outlier is 1. july. That is not real, it is caused by immigrants without documented birthday registered that date. One max in spring, around beginning of april, another maximum in autumn, in september. The simpson index calculated from this is $ 0.002750224$, and the inverse is $363.6067$, so the "effective number of birthdays" is about 363 and a half, rather close to 366. So the nonuniformity maybe is not to important. It is more difficult to find data for deathday, but I found the paper  (in norwegian) (this is the official journal of the Norwegian medical association) they report around 12% higher rate of death in winter than in summer. They also  report a slightly increased risk of death at Mondays! In fact, international comparisons reported by that paper shows that winter overmortality is lowest in scandinavia, in countries like Irland or England it is about double. That might be surprising, might have to do with us Scandinavians having warmer and better isolated houses?
From that we can reconstruct a deathday distribution. I take winter halfyear  as november-april. Then we can calculate
$$
p_w =1.12 p_s \\
(182 \cdot 1.12 + 184) p_s = 1
$$
leading to $p_s=0.002578383, p_w= 0.002887789$ and finally $\sum_i p_i q_i = 0.00273151$, its inverse, the "effective number of days" being 366.1, pretty close to 366! The anticorrelation ($\rho(p_i,q_i)=-0.06$) seems to offset the nonuniformity in such a way that we could as well assume uniformity (and equal distribution for birthday and deathday). That is quite interesting.
EDIT:  Here is a published paper on nonuniformity in the birthday problem.
Answer: 1 out of 365 would be the correct odds, because you are guaranteed to die on one day out of a 365 day year... Therefore odds are 1 out of 365.
Comment: On a unrelated point, we should clarify the terms used here. You are describing a *probability*, not an *odds*. It might help to read my answer here: [Interpretation of simple predictions to odds ratios in logistic regression](http://stats.stackexchange.com/a/34638/7290).
Comment: How do you account for the purported observation (in the question, supported by Mike Shi's answer) that more people die on their birthdays? Could it be that your assumption that death is equally likely on every day might be flawed? Might it be, for example, that Alecos' suggested reason (in his answer) applies? You should justify your assumption or otherwise address the information in the question and other answers to explain why it doesn't cause a problem for your assumption. There may be such an argument but you'd need to offer it, not just hope it's true.


Pandas : How to drop #DIV/0! and NA values in 'new' column in pandas dataframe?

Question: I did some calculation and have  #DIV/0! in my dataframe. How to drop these values and count further ? I followed df.dropna but dataframe still counting #DIV/0!. Please suggest.
df.insert(loc=df.columns.get_loc('A')+1 ,
          column = 'new',
         value=(abs(df['A'] - df['B'])/df['B'] * 100))
df = df.dropna()
df.reset_index(drop=True)
print(len(df.index))

Comment: What is the issue, exactly? Have you tried anything, done any research? Please share some of your data, or a [mcve].
Answer: You can tell your script to treat '#DIV/0!' as NaN values when you read your excel/csv file:
More here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
df = pd.read_csv('my_file.csv', na_values=['#DIV/0!'])

Comment: its not the problem in reading CSV. I created new column in dataframe after reading csv.
Comment: @Akash - the `#DIV/0!` error is made by excel, not pandas. So the csv must have been used in excel at some point. This answer should convert the `#DIV/0!` to `np.nan` when you read the document. Then, you can remove the nan values with `df.dropna()`.


Cost of cable problem

Question: So I have this math project that I cannot understand and I would really appreciate it if someone could help me out and explain how I'm supposed to figure it out.
I work for a cable TV company and have been asked to come up with a formula to determine the cost of running cable from a connection box to a new cable household. This home has a 2 mile long driveway extending to the house from a nearby highway. The nearest connection box is along the highway, but 5 miles from the driveway. It costs the company \$100 per mile to install cable along the highway and \$140 per mile to install cable off the highway. It IS possible to to run the cable overland to the house directly from the connection box or from any point between the connection box to the driveway.
A) Draw a sketch of this problem situation, assuming that the highway is a straight road and the driveway is also a straight road perpendicular to the highway. Include two or more possible routes for the cable. (I got this part)
B) Let $x$ represent the distance in miles that the cable runs along the highway from the connection box before turning off toward the house. Express the total cost of installation as a function of $x$. *You may choose to answer part C before part B if you would like to examine concrete instances before creating the equation. (This is where the trouble starts for me!)
C) Make a table of the possible integral values of $x$ and the corresponding cost in each instance. Does one choice appear to cost the least?
D) If you charge the household \$800 for installation, would you be willing to let them choose which way the cable would go? Explain.
(e) Using a graphing calculator, graph the function from
part (b) and determine the value of x that would make
the installation cost minimum.
(f) Before proceeding further with the installation, you
check the local regulations for cable companies and
find that there is pending state legislation that says
that the cable cannot turn off the highway more than
0.5 mile from the Steven's driveway. If this legislation
passes, what will be the ultimate cost of installing the
Steven's cable?
(g) If the cable company wishes to install cable in 5000
homes in this area, and assuming that the figures for
the Steven's installation are typical, how much will
the new legislation cost the company overall if they
cannot use the cheapest installation cost, but instead
have to follow the new state regulations?
If you could answer any of these parts that would be amazing! Thank you so much for the help!!
Comment: Can you upload a sketch somehow?
Comment: Is it a kind of homework you ask us to answer parts of ?
Answer: B) For $0\le x\le 5$, the cost incurred from the highway part of the cable is $100\cdot x$ dollars. The length of line on customer premises can be obtained via Pythagoras as $\sqrt{2^2+(5-x)^2}=\sqrt{29-10x+x^2}$, so the corresponding cost is $140\cdot \sqrt{29-10x+x^2}$ dollars and the total cost is
$$ 100\cdot x+140\cdot \sqrt{29-10x+x^2}\text{ dollars.} $$
You can plug in $x=0,1,2,3,4,5$ to build the table in part C.

Cost of cable problem


Does learning multiple instruments synergize musical skill?

Question: Recently I've been learning a lot of different instruments; it now is more than I can count on one hand. They range all different types (strings, keys, brass, percussion etc.)
It is becoming difficult to practice all of them consistently; not out of laziness, but simply trying to do it while working all the time.
Does practicing many different instruments provide an overall benefit to musical skill? In other words, will my skills synergize from instrument to instrument?
Eventually I would like to become an advanced player of at least a few of them...
But I fear I may not be able to by spreading my practice time between so many.
Are there any multi-instrumentalists who can speak their experience?
Comment: I learned to play harmonica so I could play Bob Dylan and Neil Young songs on guitar and harmonica at the same time.  "Heart of Gold" is just not the same song without the harmonica solo's between verses and at the intro.  But most instruments are played one at a time.
Comment: If you want to become an "advanced player" on one instrument, you have to put in the practice time. If you have "average" talent, 5 to 10 hours a week would be a reasonable *minimum*. (If you hope "advanced" means "professional level", you might need to increase that to 4 or 5 hours per *day*, not per week.)  If you want play three different instruments with little in common, like strings, keys, and brass, multiply the time by three. If you don't have that much time to spend, either rethink your ambitions, or prepare to be disappointed.
Comment: @alephzero That doesn't take into account the skills that transfer from instrument to instrument. For example: say that an experienced pianist would like to pick up the trumpet. The pianist would pick up trumpet *much* faster than someone who has never played or read music. Do you agree?
Comment: @KolobCanyon While I agree that there are *musical* skills that would transfer, the *technical* skills not so much. I play piano and sing quite well, but my skills on clarinet and cornet run to being pretty good at creating a sound similar to that of a goose in mortal agony. I could leverage my understanding of how to practice to get past the beginner stage considerably faster, but to get to an advanced level would probably take about as much work. And that assumes that I have the same level of talent for winds and brass that I have for piano, which I'm sure I don't.
Comment: @BobRodes I would agree with that
Comment: That said, I don't mean to suggest that you shouldn't work on all of the instruments that interest you. Rather than fearing that you don't have enough time, just let your interest flow naturally. At some point, you'll probably find yourself focusing on one or two of them, just as you have said you did with guitar and harmonica. Some level of keyboard proficiency will help you with music theory, by the way.
Comment: @BobRodes I've gone the other direction. I have previously focused on one instrument for many years and have started branching out due to inspiration from a fellow multi-instrumentalist.
Comment: Ah. Me too. I got a degree in piano, and more recently started singing karaoke. Singing has helped me pay more attention to phrasing in my piano playing.
Answer: Yes, to a small extent. I play piano and sax. To steal a quote, I'm not just untalented, I'm multi-untalented!
From my experience, the different instruments have taught me different aspects of music, which then transition back to the other instrument. For example, learning sax has given me a greater appreciation of tone, articulation, and melodic phrasing. It's taught me about transposition, and arranging for single-note instruments. Piano gives me a much better understanding of how music fits together, among many other things. You get the picture.
There are other skills that will transfer to a smaller group of other instruments; an awareness of intonation is useful for all brass, woodwinds and string instruments, but less useful for piano. However, knowledge of how to fix the intonation (i.e. technique) is going to be more specific. Even then, some technique does transfer, but the target list is much smaller. Some clarinet technique will transfer to sax, but not to trumpet. The more specific the skill, the less it will transfer.
If you want to master an instrument, you're not going to do it by being average at lots of instruments. Keep playing around, find the one you really want to master, and then make it the focus of your practice. That doesn't mean you have to stop playing the others; you'll just have to prioritise your time to reach your goal.
Answer: Certainly! When I was learning piano and guitar (a long, long time ago) if there was something that didn't make sense musically on one, the other was consulted, often making sense of the problem. Admittedly, usually solved by piano, with its graphical layout of notes. Harmonies, intervals, chords, voicings et al all made more sense having two instruments there. Harmonica was also played, but I can't remember consulting that.
The technical side of playing - producing notes - won't particularly transfer instrument to instrument - unless you're considering, say, the brass family: playing a trumpet will give a head start to trombone, or woodwind: playing clarinet helps to get going on sax.
The main boost comes from knowledge gained through each instrument. Understanding harmonics comes through brass instruments. Understanding chords comes from playing guitar or keyboards (it's not easy playing triads on flute...) tone production is different, but just as important on all, but how it's produced shows difference also. Differences between just intonation and 12edo are revealed on violin, etc.
Musical skills will benefit from playing multi instruments - trying to play the same thing on several different ones will help develop execution, or sometimes underline that, actually, this instrument is better that that.That may spawn another question - who knows?
I expect the largest criterion will be time for the OP, and most of us. The old adage of 'Jack of all trades' springs to mind, but it's certainly worth persevering along the multi route for the purposes cited above, and many more I've omitted.
And another thing! When I play with others, it's so much nicer to be able to empathise, or explain something relating to another instrument/player when I can use the correct words for techniques on whatever instrument, and sometimes be able to offer help specifically. (It's not always accepted, but that's another story!)
Comment: The other day I heard the term "Jack of all trades, master of none" which brought me to this question... kind of worried me to be honest.
Comment: And also, I've found playing drums helps with piano rhythm... a lot. I heard someone mention playing drum rudiments on the piano recently
Answer: I would just add to the above answers that there are some purely physical skills that do transfer- to some extent.  For instance, dexterity of fingers and precise timing of their motions to the music is necessary for just about all instruments, and getting your fingers in shape will help for all.  Learning fingerings for wind instruments, although they differ between them, is helped by the general knowledge of patterns they fall into.
That said, there are of course some conflicts too.  If you go, say, from sax to recorder, you will have to use much less force closing the holes/keys.  Timing of motion with sound must be learned separately for some different instruments- you have to start a drumstick moving further ahead of the beat than your finger for a wind instrument.  And some embouchures are very difficult to change back and forth, especially at short notice- from oboe to flute, for instance.  So you need to take time to work on these differences too.
But as the others have said, the main limitation is probably practice time.
Answer: To add to other answers: Yes. Here's why:
Learning multiple instruments multiplies synaptic connections.
The more resources your brain has for learning stuff, the more comprehensively it will understand that thing. After learning 3-4 woodwind instruments, you realize that the process by which they produce and execute sound is basically all the same. The same is true for brass, string, and percussion instruments (hence the "families"). So, your capacity for being able to learn new instruments dramatically increases, as it becomes easier to learn successive instruments. It is similarly true for learning languages. Even though I don't speak Italian or Spanish, I can use my knowledge of French and English to guess at many Italian or Spanish texts or shows.
You're fine-motor coordination increases for reasons similar to those listed above.
You're musical-literacy increases for reasons similar to those listed above.
In short, learning many instruments won't necessarily make you a better musician, but it will make you better at learning musical things.
The more instruments you learn, the more terrible you will be at each of them. If you want to be truly proficient (in a professional sense), then the less instruments you focus on, the better you will become.
Comment: I'm curious to see if there are examples of professional musicians that have played more than one instrument. Coltrane played two saxes right?
Comment: @KolobCanyon - I'd guess that most sax players are more than capable of playing any of the sax family - it's just that some have a preference for one in particular.
Comment: @KolobCanyon Prince was fairly notorious for playing all the instruments on many of his tracks, as well as doing his own recording. Many videos of Prince playing guitar, piano, and bass on youtube. There's a wonderful multi-instrument concerto performed by a woman (whose name unfortunately escapes me) in which she plays trumpet, clarinet, and bagpipes among many others. A young kid, Jacob Collier, is an accomplished multi-instrumentalist, now tours and has worked with Chick Corea and is managed by Quincy Jones: https://www.youtube.com/watch?v=K28H04Y2IdE
Comment: @Tim Almost all sax players can play all instruments of the sax family; it really doesn't count. All saxophones read the same range / clef and have the same fingerings. The only difference is embouchure and transposition (the latter not affecting playing, but just the instrument's sound). A better comparison is to say that most sax players also play flute because of fingering and ensemble needs (very commonly in jazz and in Broadway pits).
Comment: @KolobCanyon Many musicians who play in musicals (Broadway or otherwise) are very accomplished multi-instrumentalists. I have friends who do this type of work for a living, and in a given show, they are often called to play flute, clarinet, saxophone, and bassoon, for example.


Why $L_X \circ d = d \circ L_X$?

Question: How to understand that the Lie derivative $L_X$ commutes with exterior differentiation $d$?
I can follow the proof step by step, but I do not think I understand it.
A similar question concerns $F^* \circ d = d \circ F^*$, namely, the pull-back commutes with exterior differentiation.
There should be some simple reason for two things to commute, right?
Comment: If you believe the latter, you get the former for free: $L_X Y$ is (maybe I am off by a sign) the derivative at $t=0$ of $\phi^t_*(Y)$ where $\phi^t$ is the flow generated by $X$. Here we assume the vector field is complete, but you are asking about a local property, so we may as well cut off the vector field outside of a compact neighborhood, so this is fine. Then differentiating your second formula at $t=0$ gives you the first formula.
Comment: Thanks a lot for pointing this out! It is so smart.
Answer: Let $M$ be a smooth manifold, let $F:M\to N$ be a smooth map, and let $\omega \in \Omega^k(N)$ be a smooth $k$ form on $N$.
Then for each $p\in M$ and $v_1,\dots,v_k \in T_pM$ we have $(F^*\omega)_p(v_1,\dots,v_k):=w_{F(p)}(dF_p(v_1),\dots,dF_p(v_k))$.
If $(V,\psi=(y^j))$ is a chart on $N$, then $\omega_{|V}=\sum'_Jw_J \;dy^{j1}\wedge\dots\wedge dy^{j_k}$.
Then $(F^*\omega)_{|F^{-1}(V)}=\sum'_J (w_J\circ F) \;d(y^{j1}\circ F)\wedge\dots\wedge d(y^{j_k}\circ F)$
While $(dw)_{|V}=\sum'_J dw_J \wedge dy^{j1}\wedge\dots\wedge dy^{j_k}$
And $[d(F^*\omega)]_{|F^{-1}(V)}=\sum'_J d(w_J\circ F) \wedge d(y^{j1}\circ F)\wedge\dots\wedge d(y^{j_k}\circ F)$
And $[F^*(dw)]_{|F^{-1}(V)}=\sum'_J d(w_J\circ F) \wedge d(y^{j1}\circ F)\wedge\dots\wedge d(y^{j_k}\circ F)$
Answer: If $f(t)^\ast \alpha = b_I(x,t)dx_I$, then
\begin{align*} dL_X\alpha &=d\frac{d}{dt} f^\ast\alpha\\
&= d (b_I)_tdx_I = (b_I)_{tx_i}dx_i\wedge dx_I
\\&=
\frac{d}{dt} d(b_Idx_I) = \frac{d}{dt} d f^\ast\alpha
=\frac{d}{dt} f^\ast d\alpha
\\&= L_Xd\alpha\end{align*}

Why $L_X \circ d = d \circ L_X$?


growing python process memory over time

Question: My python code process memory increases dynamically as it stores dynamic data in list, dictionary and tuples wherever necessary. Though all those dynamic data is cleared physically in their variables after then, the memory is not shooting down.
Hence i felt like there is a memory leak and i used gc.collect() method to collect all the unfreed memory. But i could not make the memory to minimum when there is no data in the variables.
Comment: Why would you expect it to go down?  What OS are you using?  In many OS's, once a process has acquired memory, the process stays that big.
Comment: i m using mac osx 10.5, i beleive in later it would eat more space.
currently it had grown around 15MB more from 24MB at initial stage.
i beleive that the process memory should grow in terms of MB which might affect the available memory size.
Answer: It's very hard, in general, for a process to "give memory back to the OS" (until the process terminates and the OS gets back all the memory, of course) because (in most implementation) what malloc returns is carved out of big blocks for efficiency, but the whole block can't be given back if any part of it is still in use -- so, most C standard libraries don't even try.
For a decent discussion in a Python context, see e.g. here.  Evan Jones fixed some Python-specific issues as described here and here, but his patch is in the trunk since Python 2.5, so the problems you're observing are definitely with the system malloc package, not with Python per se.  A 2.6-specific explanation is here and here.
A SO thread is here, where Hugh Allen in his answer quotes Firefox programmers to the extend that Mac OS X is a system where it's basically impossible for a process to give memory back to the OS.
So, only by terminating a process can you be sure to release its memory.  For example, a long-running server, once in a while, could snapshot its state to disk and shut down (with a tiny watchdog process, system or custom, watching over it and restarting it).  If you know that the next operation will take a lot of memory for a short time, often you can os.fork, do the memory-hungry work in the child process, and have results (if any) returned to the parent process via a pipe as the child process terminates.  And so on, and so forth.
Answer: How big are we talking?  Python itself takes up some amount of memory.. up to maybe 30 or 40 MB I believe.  If it is bigger than that and not getting collected, you have a memory leak. Only garbage with no references can be collected, somehow your extra stuff is still referenced. Do a memory profile and see what is going on.
Comment: currently it had grown around 15MB more from 24MB at initial stage for minimal scenario. However i tried the below link tool from which i found the referred data are not more than 3MB. I could not get the remaining amount of memory details.
Comment: That isn't that big. If you are looking for a super low memory program, you normally don't code in Python. Most PCs have 2-4GB of ram, 15MB is not worth worrying about.

growing python process memory over time


camera inside app force close data null when i try in different device

Question: i have an apk app which can take photo and take video with a button.
This is my activity
package com.example.testcamera;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

public class AndroidCameraTestsActivity extends Activity
{
    private static final String TAG = AndroidCameraTestsActivity.class.getSimpleName();

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Uri fileUri;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    /**
     * https://developer.android.com/guide/topics/media/camera.html
     * **/
    public void onCaptureImage(View v)
    {
        // give the image a name so we can store it in the phone's default location
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "IMG_" + timeStamp + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image (this doesn't work at all for images)
        fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); // store content values
        intent.putExtra( MediaStore.EXTRA_OUTPUT,  fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    /**
     * https://developer.android.com/guide/topics/media/camera.html
     * **/
    public void onCaptureVideo(View v)
    {
         //create new Intent
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        //fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video in specific folder (this works for video only)
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name

        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

        // start the Video Capture Intent
        startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Originally I was going to iterate through the list of images and grab last added to the MediaStore.
                // But this is not necessary if we store the Uri in the image
                /*
                String[] projection = {MediaStore.Images.ImageColumns._ID};
                String sort = MediaStore.Images.ImageColumns._ID + " DESC";

                Cursor cursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, sort);

                try{
                    cursor.moveToFirst();
                    Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns._ID));
                    fileUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
                } finally{
                    cursor.close();
                }
                */

                if(fileUri != null) {
                    Log.d(TAG, "Image saved to:\n" + fileUri);
                    Log.d(TAG, "Image path:\n" + fileUri.getPath());
                    Log.d(TAG, "Image name:\n" + getName(fileUri)); // use uri.getLastPathSegment() if store in folder
                }

            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the image capture
            } else {
                // Image capture failed, advise user
            }
        }

        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Video captured and saved to fileUri specified in the Intent
                fileUri = (Uri) data.getData();

                if(fileUri != null) {
                    Log.d(TAG, "Video saved to:\n" + fileUri);
                    Log.d(TAG, "Video path:\n" + fileUri.getPath());
                    Log.d(TAG, "Video name:\n" + getName(fileUri)); // use uri.getLastPathSegment() if store in folder
                }

            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the video capture
            } else {
                // Video capture failed, advise user
            }
        }
    }

    /** Create a file Uri for saving an image or video to specific folder
     * https://developer.android.com/guide/topics/media/camera.html#saving-media
     * */
    private static Uri getOutputMediaFileUri(int type)
    {
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type)
    {
        // To be safe, you should check that the SDCard is mounted

        if(Environment.getExternalStorageState() != null) {
            // this works for Android 2.2 and above
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AndroidCameraTestsFolder");

            // This location works best if you want the created images to be shared
            // between applications and persist after your app has been uninstalled.

            // Create the storage directory if it does not exist
            if (! mediaStorageDir.exists()) {
                if (! mediaStorageDir.mkdirs()) {
                    Log.d(TAG, "failed to create directory");
                    return null;
                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File mediaFile;
            if (type == MEDIA_TYPE_IMAGE){
                mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_"+ timeStamp + ".jpg");
            } else if(type == MEDIA_TYPE_VIDEO) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_"+ timeStamp + ".mp4");
            } else {
                return null;
            }

            return mediaFile;
        }

        return null;
    }

    // grab the name of the media from the Uri
    protected String getName(Uri uri)
    {
        String filename = null;

        try {
            String[] projection = { MediaStore.Images.Media.DISPLAY_NAME };
            Cursor cursor = managedQuery(uri, projection, null, null, null);

            if(cursor != null && cursor.moveToFirst()){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
                filename = cursor.getString(column_index);
            } else {
                filename = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting file name: " + e.getMessage());
        }

        return filename;
    }
}

I have first device running the app and I have 2 button, take photo and take video.
When I click take video in this app and it works well but when i click take picture from the button, the app always "force closes".
this is my  error logcat
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): FATAL EXCEPTION: main
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): java.lang.NullPointerException
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera.initializeFirstTime(Came ra.java:328)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera.access$1100(Camera.java: 95)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera$MainHandler.handleMessag e(Camera.java:282)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.os.Handler.dispatchMessage(Handler.java:99 )
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.os.Looper.loop(Looper.java:130)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.app.ActivityThread.main(ActivityThread.jav a:3683)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at java.lang.reflect.Method.invoke(Method.java:507)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:839)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:597)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at dalvik.system.NativeStart.main(Native Method)
11-19 14:43:27.093: WARN/ActivityManager(1308): Force finishing activity com.android.camera/.Camera
11-19 14:43:27.109: WARN/ActivityManager(1308): Force finishing activity makemachine.android.examples/.PhotoCaptureExample

EDIT : this is my different activity with single app button
package com.example.maincamera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class OpenCameraDemo extends Activity {

    private static final int CAMERA_PIC_REQUEST = 2500;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                 startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_PIC_REQUEST) {
              Bitmap image = (Bitmap) data.getExtras().get("data");
              ImageView imageview = (ImageView) findViewById(R.id.ImageView01);
              imageview.setImageBitmap(image);
        }
    }
}

this app still error too, i have tried many app. searching in google.the error still same like my logcat error
When i try to run it on other device, this app works perfectly.
How to fix this, So that i can run and take photos in my first device?
BR.
Alex
Comment: wha's the different between two device ?
Comment: first device is MT35A from china and other device is axioo vigo. when i use axioo the app works but when i move to MT35A the capture video works but take photo is force close
Comment: do you have any other android phone so we can fix main problem .?
Comment: i think that is not supportable for that hardware it may be .what is the minimum api version ?
Comment: axioo 2.3.4 and MT35A 2.3.7. and just now  i try to install this app to LG ics 4.0.3 and capture camera works. but im curious with samsung [this link](http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/)
Comment: weird hardware in this handheld. this camera original is work but when calling with button is force close. so help me
Comment: what is minimum api for your app ?
Comment: my minimum api version is api 8
Comment: man i fell your problem but we can't change hardware. its may be possible some other mobile will not support for the same . this type of hardware problem we are useless. still i am not a big developer some other member can also help you. i think you should keep bounty for question some one will answer you.
Comment: yes, thank you so much friend. i'll be wait and i'll try to found the answer.
Comment: i believe in help to people. so no thanks
Comment: ah i still can't found the answer. :'(
Comment: Alex belek as you see i have set a bounty for you. so now wait for 7 days more.hope you will get you will get success.
Comment: ok. this device can't auto rotate too. maybe this is the problem?
Comment: Does the Camera application on this device work normally?  In other words, can you go directly into the Camera application (not using your app) and take a picture successfully?
Comment: @devunwired the camera in this device is work normally. when i try without my application, camera can take picture successfully. but the problem is when i take photo in my app, the camera always force close. i try to change other device and my app works.
Comment: If you remove `intent.putExtra( MediaStore.EXTRA_OUTPUT,  fileUri);` from the code in `onCaptureImage()`, does it successfully take a picture then?
Comment: @Alexbelek just do simple task. make a demo app in that add single button by click on that photo should be capture. so we can find out easily.
Comment: @Devunwired still error. and same logcat. i think some thing wrong with `MediaStore.ACTION_IMAGE_CAPTURE`
Comment: we need to add permission
Answer: The crash is happening inside the device's Camera application, not your own.  Unfortunately, because the Camera application on this device could be a heavily customized variation of what is actually in AOSP, it's not entirely clear what the failure is, but here is a link to the source file in the AOSP 2.3.7 source tree where your exception is occurring.  The line numbers don't match up exactly to anything of interest, which is what tells me the application on your particular device has been customized at least some.
Any object in the initializeFirstTime() method, where the exception occurs, where a method is called could be the source of the issue, but none of this is related to the Intent parameters your request passes in, so it is doubtful there is much you can do to make this operate appropriately.
As a result, you may have better luck implementing the capture functionality yourself in your own application.  It is likely that the Android APIs on this device are more stable than the system applications it's bundled with.  Here is an example of how you can create your own camera preview and capture Activity.
Comment: thanks. @Devunwired. i tried use Camera API and it works. but i have 2 problem. 1. camera cant full image resolution, when i take capture camera . the camera is rotation 90. but thanks for your answer.
Comment: can i ask you something. its about this costum camera. how to connect custom camera with onActivityResult?
Comment: Have a look at the Android developer training for Activity results.  Any Activity can pass a result to its parent, and your app can make the result data look the same as it would have from the Camera app: http://developer.android.com/training/basics/intents/result.html
Answer: Friend Do one thing.
Make Simple app which have only one button. onClick event photo should be capture no add other task.
Is it working Properly ?
Comment: still doesnt work. ok i'll edit my question and add activity with one single button.
Answer: try to catch the exception and post the message here:
try{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
catch(ActivityNotFoundException e){
e.printStackTrace();
}

Answer: I'm curious about your phone. what the different of them
because of your onCaptureImage(View v) does describe about external storage.
but onCaptureVideo(View v) doesn't

the phone that didn't work. is it support external sd card? if it not, all your code is about ext.sd
Is it your phone that didn't work it remove sd card occasionally? try connect it as camera or mtp
Answer: Thanks @Devunwired, thanks @chintan and thanks all for helping me. i use camera api and it works.
this is my activity
package com.exercise.AndroidCamera;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

public class AndroidCamera extends Activity implements SurfaceHolder.Callback{

    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;
    LayoutInflater controlInflater = null;

    final int RESULT_SAVEIMAGE = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

    }
        public void onCaptureImage(View v)
        {

        setContentView(R.layout.main);

        Toast.makeText(AndroidCamera.this,
                "Image dimulai : ",
                Toast.LENGTH_LONG).show();
        getWindow().setFormat(PixelFormat.UNKNOWN);

        surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.control, null);
        LayoutParams layoutParamsControl
            = new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT);
        this.addContentView(viewControl, layoutParamsControl);

        Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
        buttonTakePicture.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                camera.takePicture(myShutterCallback,
                        myPictureCallback_RAW, myPictureCallback_JPG);

            }});
    }

    ShutterCallback myShutterCallback = new ShutterCallback(){

        @Override
        public void onShutter() {
            // TODO Auto-generated method stub

        }};

    PictureCallback myPictureCallback_RAW = new PictureCallback(){

        @Override
        public void onPictureTaken(byte[] arg0, Camera arg1) {
            // TODO Auto-generated method stub

        }};

    PictureCallback myPictureCallback_JPG = new PictureCallback(){

        @Override
        public void onPictureTaken(byte[] arg0, Camera arg1) {
            // TODO Auto-generated method stub
            /*Bitmap bitmapPicture
                = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);  */

            Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

            OutputStream imageFileOS;
            try {
                imageFileOS = getContentResolver().openOutputStream(uriTarget);
                imageFileOS.write(arg0);
                imageFileOS.flush();
                imageFileOS.close();

                Toast.makeText(AndroidCamera.this,
                        "Image Tersimpan: " + uriTarget.toString(),
                        Toast.LENGTH_LONG).show();

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*controlInflater = LayoutInflater.from(getBaseContext());
            View viewControl = controlInflater.inflate(R.layout.confirm, null);
            LayoutParams layoutParamsControl
                = new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
            this.addContentView(viewControl, layoutParamsControl);*/

        }};

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
        if(previewing){
            camera.stopPreview();
            previewing = false;
        }

        if (camera != null){
            try {

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
                previewing = true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        camera = Camera.open();
        //m_camera = Camera.open();
        /*Camera.Parameters p = camera.getParameters();

        //camera.setDisplayOrientation(90);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation",90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }*/

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        camera.stopPreview();
        camera.release();
        camera = null;
        previewing = false;
    }
}

i create home.xml to show button image like my question
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:text="Capture Image" android:onClick="onCaptureImage"
        android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

main.xml this is a camera preview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<SurfaceView
    android:id="@+id/camerapreview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

and create control.xml take picture button inside camera preview.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="bottom"
    >
<Button
    android:id="@+id/takepicture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" * Ambil Foto "
    android:layout_gravity="right"
    android:layout_margin="10px"
    />

</LinearLayout>

but i have 2 problem in this app.

the camera resolution not full size . -+20kb
when take camera preview is rotate 90 degrees


How to get a permission from a relationship using CanCanCan?

Question: In my app I have a model called User that has_one Talent.
In CanCanCan I have this ability:
class Ability
  include CanCan::Ability
  def initialize(user)

  if user.nil?
    can :read, User
    can :read, Talent, is_public?: true
  else
    can :read, Talent, is_public?: true
  end

My page is being rendered by the ProfilesController#show. Like this:
class ProfilesController < ApplicationController
  before_action :check_ability, except: [:show]
  def show

    @user = User.find(params[:id])
    authorize! :read, @user
    authorize! :read, @user.talent

    if current_user
      sent_connections = current_user.sent_connections
      connections  = sent_connections + current_user.all_connections
      @is_connected = !(connections.select { |c| c.user.id == @user.id }.empty?)
    end
    @top_5_photos = @user.top_5_photos
  end

Well. Im trying to render a profile that the method: is_public returns false. But the page is being rendered correctly, while I expected was that the user cant see the page because of the rule:
   can :read, Talent, is_public?: true

What Im missing here?
Comment: What is the value of `@user.talent.is_public?`. Is it `false`?
Comment: Yes. Even I putting a cannot :read, Talent. It doesnt work. Looks like something is overriding the permissions, but I triple-checked and nothing is setting the permissions on Talents.
Answer: If I remember it correctly,
can :read, Talent, is_public?: true

^ is_public? above is expected to be an attribute by Cancancan.
But because is_public? is a custom method, then can you try the following instead?
can :read, Talent do |talent|
  talent.is_public?
end

Comment: Hmm. Can you try adding `cannot :manage, :all` at the very end of your ability.rb's `initialize` method? Because this will override everything to be "not-authorised!". Then try again and you should hopefully not be able to see the page
Comment: @FernandoMaymone, I just looked at it right now from the official docs, that you are supposed to just only use attributes there, and you should not use custom methods (but will still probably work, from my what I could remember, and is why yours still work; however I remember having some problems before with this, and was why I had to use the "block" form). See [here](https://github.com/CanCanCommunity/cancancan/wiki/defining-abilities#hash-of-conditions): I quote: "It is important to only use database columns for these conditions so it can be used for Fetching Records."
Comment: If `cannot :manage, :all` still allowed the rendering of the page, then maybe your "initialize" method was not actually being called, or that your `show` action is not getting called, or that for some reason you have a different `ability` object defined/overidding `current_ability` method somewhere, maybe in your application_controller
Comment: hmm i see. I want to check something, can you try `can :read, Talent do |talent|; puts 'XXXXXXX'; puts talent.is_public?; end`. And then look at the running `rails server`, it should print out the value. Can you let me know the value being displayed? If it's false or true?
Comment: @FernandoMaymone hmm it is looking to me like the `show` method is not being called. So, can you try adding `puts 'MMMMMMMM'` just above `authorize! :read, @user.talent` in your `show` method? and let me know if "MMMMM" gets printed out
Comment: Hmm ok, I want to filter out if the `current_ability` got overriden, so can you try instead of `authorize! :read, @user.talent`, replace that with `Ability.new(current_user).authorize! :read, @user.talent`?
Comment: Yes Jay. I was giving maintanence in a very old code, and it was very well hidden btw a lot of comments. Sorry for missing our time. Thanks for the help!!!!
Comment: It works with methods too Jay. I know because on my other side of the IF, the declaration is working perfectly :/

Anyway, I tried with this setting too and didnt works
Comment: even putting a cannot :read, Talent , on the "else", the page is shown :/
Comment: I did a desperate test here. And still is showing the page:

    if user.nil?
      can :read, User
      can :read, Talent, is_public?: true
    else
      can :read, Talent do |talent|
        false
      end
    end
Comment: If I add a simple  cannot :read, Talent , it works. But if I try to do a can :read, Talent do |talent|
  talent.is_public?
end

It doesnt. Even If instead of talent.is_public? I put a false.
Comment: I putted too a byebug inside. And it didnt print the puts 'XXXXX'. But before and after the Talent do |talent|, it prints any puts. ?????
Comment: puts "*** Out"
      can :read, Talent do |talent|
        puts "*** In"
        puts talent.is_public?
        puts "*** In"
      end
      puts "*** Out"

Only the OUTS are printed
Comment: weirdest thing. If I put a cannot :Talent do |talent|, the "INS" are printed correctly :/
Comment: Another question, can you also check if `@user.talent` in fact is not `nil`? like maybe: `puts '>>>>>> @user.talent = ', @user.talent`
Comment: I found this in the code:

 can :read, :all

Probably this option overrides all right?
Comment: ^ depends on where you put that. Because the `Ability` class implements linearly, meaning, if you put `can :read, :all` at the very end of `def initialize`, then yes that will override everything to be "authorised" on `:read`
Comment: Did you have `can :read, :all` there??? Then if so, then that was the cause of your problem!! XD
Comment: @FernandoMaymone No prob at all! :)) Glad I helped you in some way!


Green's Function for a Semi-Circle

Question: Find Green's function for $\Omega = \{(x,y) \in \mathbb{R}^2\mid x^2+y^2 < r^2, y>0 \} $.
I tried to find it and I know that $G(x,y)=\frac{1}{2}\pi\cdot \ln\left(\frac{1}{|y-x|}\right) + h^x(y)$. But I don't know how to find the $h^x(y)$ function. Could someone help please?
Answer: This is usually done by reflection (aka the method of images). Reflect the half-disk across the diameter, extending it to the disk $D$. For the disk, Green's function is known (and easy to obtain from a Möbuis map):
$$G_D(x,y)=\frac{1}{\pi}\ln\frac{|1-\bar y x|}{|y-x|}$$
(It's somewhat unusual to use $x,y$ for complex numbers, by the way.)
The idea is to subtract $G(x,\bar y)$, because $\bar y$ is the reflection of $y$ in the diameter. The symmetry makes sure that the difference vanishes on the diameter, and so
$$G_D(x,y)-G_D(x,\bar y)$$
is Green's function for half-disk $\Omega$. (The extra pole at $\bar y$ is outside of $\Omega$, so it does not concern us.)
Comment: What is the function $F$ in your answer?

Green's Function for a Semi-Circle


Hiding menu items dynamically

Question: I am developing an application based on Drupal 7 and web services. Some application pages have a menu which should be customized (menu items should be removed) based on the response from the web service, but am not sure on how should implement it.
In general the logic is the following: I will get a parameter from the request and call the web service with PHP (I know how to do this). Then, based on the response, I should show or hide some menu items.
The problem is that the menu should be customized in every request, so hook_menu_alter does not help me, because it is only called once when the menu is created. Is there another hook that I should be looking into, or any other method I should be using?
Comment: Is there any logic for the request? May you do an example?
Comment: Hi Syd, I added some extra info
Comment: I'm not sure but... maybe you can create a content type with links a related it with a view instead of menu items. Or you you can try Menu Block, but It's still not quite clear, can you provide a detailed example?
Comment: Thanks for your suggestion, I'll try to replace the menu with a custom view. Sorry if I didn't give enough details, but I'm not that experienced in Drupal
Comment: If you give us a detailed example on what's your menu items and what kind of link you want to show depending on the content.
Answer: use theme_menu_link() to modify your menu links on the fly:

style="display:none"
class="invisible"

e.g.
function mytheme_menu_link(array $variables)
{
   if ($variables['element']['#href']=='temp-menu-link') {
       $variables['element']['#attributes']['class'][] = 'invisible';
   }
   return theme_menu_link($variables);
}

Security note: It'll still be possible to access the URL, thus a "state check" must be implemented on the receiving end if temporarily invisible also means 'not permitted to call'.
Comment: Thanks, I too believe that this would be the best way to go, but I ended up reimplementing the menu as a custom PHP page. So I'm accepting this as the correct answer even though I have not tried it.
Comment: Could I just `unset($variables['element'])`? I.e. is this array completely mutable?
Comment: how to do same thing for drupal 9, hook_menu_link is not available for drupal 9
Answer: You can use hook_menu_alter if it's solve your problem. You can call this hook as many as you like with module_invoke_all('menu').
Note that you need to clear the menu cache after altering a menu.
Comment: Could you add an example? I'm having trouble understanding where to put which part of the code. Where should I be calling `module_invoke_all('menu')`, for example?
Answer: I was able to accomplish this by loading the menu with the link in question.  I then acted upon this menu item using its link path.  I set the links hidden attribute to 1 to hide it.  I then saved the menu link. Then I cleared the menu cache.  For the use case for this question, you would just do this when the web service call happens that is requesting to hide the menu.  Here is what the code looks like.
$links = menu_load_links('secondary-navigation');
foreach($links as $item) {
    if ($item['link_path'] == 'blog') {
        $item['hidden'] = 1;
        menu_link_save($item);
        menu_cache_clear('secondary-navigation');
        break;
    }
}

Hiding menu items dynamically


Estimating true average from sampled average with Inspection Paradox

Question: I'm facing the following problem (situation simplified). I'm sampling a group of students and I need to find out the number of families having 2 kids (or a probability). Assume

Siblings are all part of the group I'm sampling from
Siblings can be either 0 or 1 for simplicity

I run the survey and get back results in the following way

0 sibling, frequency = 4
1 sibling, frequency = 9

I arrive at a biased estimate of the probability that a given family has 2 kids as (0*4 + 1*9)/13 = 0.69. This is biased because I'm more likely to sample someone who has 1 sibling given all siblings are in the same group. If my overall population is about a 100, what is a way to estimate the true probability given this data? Is it even possible? Do I need more information?
To see the bias, assume a simple case where there are 3 kids. 2 siblings and 1 single which gives 2 families one of them with 2 kids.
The survey method above would yield $\frac{2}{3}$ probability when in reality it should be $\frac{1}{2}$.
Answer: Your sampling is fine as is your estimate of the mean.  You might have a population of $32$ only children and $72$ pairs of siblings.  The average number of siblings is exactly as you calculated it.  That doesn't mean that only one third of the families have only one child.  Your population would then represent $32$ families with one child and $36$ families with two children, so (a little over) half the families have two children.  Of course, your sample is quite small, so the variance on your estimate is quite high, but that doesn't change the point of the question.
Comment: I think I phrased the question incorrectly. Rephrased it now.
Comment: I think I indicated the answer already.  In your simple case of three kids, it is true that $2/3$ of them have one sibling.  It is also true that half the families have two kids.  The fallacy comes when you assume that the fraction of families that have two kids matches the fraction of kids that have siblings.  Your sampling is fine and will measure the number of kids that have siblings accurately.


Isomorphism as an R-module not algebraically

Question: Prove that the $k$-algebras $k\times k$ and $k[x]/(x^2)$ are isomorphic as $R$-modules, but not as rings, with $k$ is a field.
Suppose for the contrary that $k\times k \cong k[x]/(x^2)$. Then there is $\phi : k \times k \rightarrow k[x]/(x^2)$ isomorphism, so $\phi(s)\phi(s^{-1})=1_{k[x]/(x^2)}$ which means $\phi(s)$ is a unit in $k[x]/(x^2)$. So $\phi(s)=m+(x^2)$ for some $0 \neq m \in k$ and it is a unit since generally we have $k$ is a field. I want to conclude somehow that $kerf$ is not trivial to get a contradiction but I am getting stuck with my assumption. Also, I want to ask about the construction of the isomorphism function for $R-$ module.
I appreciate any help or hints.
Comment: You mean as $k$-modules ($k$-vector spaces), not as $R$-modules. There is no $R$ anywhere. Think about the multiplicative structure in $k \times k$ and in $k[x]/(x^2)$. Do you know what nilpotent elements are?
Answer: Well for the $k$-module part, you can convince yourself that $k[x]/(x^2) = \{\alpha + \beta x + (x^2) \mid \alpha,\beta \in k\}$, and then the map $k \times k \to k[x]/(x^2)$ given by $(\alpha,\beta) \mapsto \alpha + \beta x + (x^2)$ will work.
As for not being isomorphic as rings, suppose that they are, say $\phi: k \times k \to k[x]/(x^2)$ is an isomorphism. Notice that in $k \times k$, any non-zero element does not square to zero. Indeed, if $(a,b)^2 = (a^2,b^2) = 0$, then $a = b = 0$. With this in mind, let $y \in k \times k$ be such that $\phi(y) = x + (x^2)$ in $k[x]/(x^2)$ (surjectivity). But then $x^2 + (x^2) = (x^2)$ implies that $(x^2) = \phi(y^2) = \phi(y)^2$, which implies that $y^2 = 0$ (injectivity). But as we just mentioned, this would imply that $y = 0$ which clearly is a clear contradiction as $x + (x^2)$ is not zero.
As mentioned in the comments, this boils down to the quotient ring having nilpotents, while the product ring does not.
Comment: Is true in general that field must not have a nilpotent?
Comment: I can see that since field is an integral domain..
Comment: @Ahmed keep in mind that $k \times k$ is not a field, nor an integral domain ($(1,0)(0,1) = (0,0)$). But yes, in general integral domains won't have niltpotents since (non-zero) nilpotents are necessarily zero divisors.


Best way to monitor for SSL / Connection failures on a server that's still up

Question: We had an outage issue today (NGinx not successfully restarted by our Let's Encrypt renewal CRON job, so not serving the renewed cert) leading to the server being up according to Pingdom but not serving the web service it should have been. Is there a way of monitoring for unsuccessful connection / page serving rather than whatever Pingdom is currently measuring (server response?)? We've been looking at Rollbar for exception monitoring too - can either of these services track / monitor for this kind of problem?
Comment: Check for the HTTP Status code, probably `200`. Or some content you expect.
Comment: @gf_ thanks - which service were you recommending that check to originate from?
Answer: You can use check_http which is a plugin for Nagios or Icinga.
When run from cron you should append something like <code>| grep -v OK</code> to only get output/mail when it is not Ok.
https://www.monitoring-plugins.org/doc/man/check_http.html
It even supports checking the remaining days of validity for the certificate.
Comment: this sounds like it's worth looking into - thanks