Bootstrap 4 - aligning two layers of links to the top and bottom of a navbar

Question: I have a collection of links I'd like to align to both the top and bottom of my navbar.  Specifically, this arrangement:

After playing with Irfandy Jip's code in the answer below, and my own continued research, I've come up withn this code:

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                    <button class="btn btn-link border-dark-blue border-right border-top-0 border-left-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                        Login
                    </button>
                    <button class="btn btn-link border-dark-blue border-left border-top-0 border-right-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                        Sign Up
                    </button>

                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>
                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>
                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>

            Login
            Sign Up

        <form class="form-inline my-2 pt-5 my-lg-0 mx-auto d-inline w-50 order-lg-1" action="{{ path('_store_search_results') }}">

                <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

                    <button class="btn btn-burnt-orange my-2 my-sm-0" type="button"></button>

        </form>

Which results in the following:

Which is really close to what I want, with the exception of how the entire navbar is growing at the bottom, no doubt the result of the margin's I've added (padding does the same thing).  Ideally, the social media icons would be on the same 'line' as the search bar, with the Login and Sign Up links at the top of the bar, as they currently are.
Here's a comparison with the rough draft of the layout:

Is there anything else I can do to make the links on the right look more like the last image?
Comment: The code doesn't match what's shown in the image. Can you post the complete code?
Comment: @Zim I've posted the complete code in this edit
Answer: Remove the  mb-lg-5 class from nav-item

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

          <button class="btn btn-link border-dark-blue border-right border-top-0 border-left-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Login
                </button>
          <button class="btn btn-link border-dark-blue border-left border-top-0 border-right-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Sign Up
                </button>

          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>

      Login
      Sign Up

    <form class="form-inline my-2 pt-5 my-lg-0 mx-auto d-inline w-50 order-lg-1" action="{{ path('_store_search_results') }}">

        <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

          <button class="btn btn-burnt-orange my-2 my-sm-0" type="button"></button>

    </form>

Additionally , I  am also adding an alternative structure of HTML if you are flexible to changing the HTML structure. This structure is more responsive and as per the standards of bootstrap , the icons will be automatically be aligned to the search bar without the use of margins and padding.

@media(min-width:992px) {
  .login-btn {
    border-right: 1px solid #aaa;
  }
  form.search-form {
    width: 50% !important;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

          Login

          Sign Up

        <form class="search-form form-inline my-2 my-lg-0 mx-lg-auto d-inline w-100" action="{{ path('_store_search_results') }}">

            <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

              <button class="btn btn-burnt-orange my-2 my-sm-0" type="button"></button>

        </form>

          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

      </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

      </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

      </button>

Answer: UPDATED NOV 27, 2018, Since question has been updated my old answer is no longer sufficient. Actually your answer is already answered a little by @Nandita, but since you liked my JSFiddle, I revised it again so it looks better.
You just have to set the "Search Bar" width yourself.

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

      <form class="w-100 m-auto" action="{{ path('_store_search_results') }}">

          <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

            <button class="btn btn-burnt-orange" type="button"></button>

      </form>

          <button class="btn btn-link border-right p-0 m-0 d-none d-lg-inline">
              Login
            </button>
          <button class="btn btn-link border-left p-0 m-0 d-none d-lg-inline">
              Sign Up
            </button>

          <button class="btn btn-link p-0 m-0">

            </button>
          <button class="btn btn-link p-0 m-0">

            </button>
          <button class="btn btn-link p-0 m-0">

            </button>

        Login
        Sign Up

Link to JSFiddle to play around https://jsfiddle.net/irfandyjip89/y9fksubx/4/
Comment: That works really well for the top two buttons, so thanks for that :)  Please look at the edit I made to my original question... how would I put an additional series of links/buttons at the bottom of my navbar on the same side as login and sign up?  Is it even possible?
Answer: To achieve use css flextbox and align-items: flex-end;
Here is the updated snippet:

form.form-inline {
  display: flex!important;
  width: 100%!important;
  align-items: flex-end;
}

.form-inline .input-group,
.form-inline .nav-item {
  width: 33.33%!important;
}

.navbar-nav {
  position: absolute;
  right: 20px;
  top: 0;
}

.nav-item .btn-group {
  float: right;
}

.nav-link {
  padding: 0 1rem!important;
}

@media only screen and (max-width: 991px) {
  .navbar-nav {
    position: inherit;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

          <button class="btn btn-link border-dark-blue border-right border-top-0 border-left-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Login
                </button>
          <button class="btn btn-link border-dark-blue border-left border-top-0 border-right-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Sign Up
                </button>

      Login
      Sign Up

    <form class="form-inline my-2 pt-5 my-lg-0 mx-auto d-inline w-50 order-lg-1" action="{{ path('_store_search_results') }}">

        <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

          <button class="btn btn-burnt-orange my-2 my-sm-0" type="button"></button>

          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
          <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>

    </form>

Answer: to achieve more like the example, i think you should just remove the padding in nav-item..and add padding in the nav class

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

                <button class="btn btn-link border-dark-blue border-right border-top-0 border-left-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Login
                </button>
                <button class="btn btn-link border-dark-blue border-left border-top-0 border-right-0 border-bottom-0 p-0 m-0 d-none d-lg-inline">
                    Sign Up
                </button>

                <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
                <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>
                <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                </button>

        Login
        Sign Up

    <form class="form-inline my-2 pt-5 my-lg-0 mx-auto d-inline w-50 order-lg-1" action="{{ path('_store_search_results') }}">

            <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

                <button class="btn btn-burnt-orange my-2 my-sm-0" type="button"></button>

    </form>

and for your second question, just add another div with nav-item class
Answer: here is what you want , check output in fullscreen :

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                    <button class="btn btn-link  border-dark-blue border-right border-top-0 border-left-0 border-bottom-0 p-0 m-0 d-none d-lg-inline" style="line-height:2px;">
                        Login
                    </button>
                    <button class="btn btn-link  border-dark-blue border-left border-top-0 border-right-0 border-bottom-0 p-0 m-0 d-none d-lg-inline" style="line-height:2px;">
                        Sign Up
                    </button>

                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>
                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>
                    <button class="btn btn-link p-0 m-0 d-none d-lg-inline">

                    </button>

            Login
            Sign Up

        <form class="form-inline my-2 pt-5 my-lg-0 mx-auto d-inline w-50 order-lg-1" action="">

                <input name="search" class="form-control" type="search" placeholder="Search" aria-label="Search">

                    <button class="btn btn-warning my-2 my-sm-0" type="button"></button>

        </form>


Infinite metric space has open set $U$ which is infinite and its complement is infinite

Question:
Let $(X,d)$ be a metric space where $X$ is an infinite set. Prove that the space has an open set $U$ such that both $U$ and its complement are infinite sets.

I have considered if $d$ is the discrete metric, then one such $U$ exists. But if $d$ is not discrete, how do we find such $U$?
Answer: If $p\in X$ and $p$ is not an isolated point of $X$ (that is,if $p\in \overline {X\backslash \{p\}}$) then every nbhd of $p$ is infinite.(Because we may take $p_1\in X\backslash \{p\}$, and take $p_{n+1}\in  B_d(p,(1/2)d(p,p_n))\backslash \{p\}$ for each $n\in N.$ Any nbhd of $p$ contains $p_n$ for all but finitely many $n.$) So if $X$ has two unequal non-isolated points $p, q$, then $U=B_d(p,(1/2)d(p,q))$ is open and infinite,and $U$ is disjoint from the infinite set $B_d(q,(1/2)d(p,q))$.On the other hand if $X$ has at most one non-isolated point, let $\{x_n :n\in N\}$  be a set of isolated points of $X$, with  $(n\ne m\to x_n\ne x_m).$ Then $U=\{x_{2n}:n\in N\}$ is open and infinite and $U$ is disjoint from the infinite set $\{x_{2n-1}:n\in N\}.$
Comment: @Tom Collinge, No it doesn't. If X has at most one, I construct a different kind of infinite,co-infinite open set  than in the case where X has at least two.
Comment: OK, I see that and removed my question.
Comment: Nice! It seems like your proof even works for arbitrary Hausdorff spaces, even for non-metric ones. In this case, every neighborhood of $p$ must still be infinite.
Answer: The statement is correct, and I am trying to prove it by contradiction. Suppose that there exists an infinite metric space $(X,d)$ such that every infinite open set has finite complement.
Recall that a limit point of a metric space is a point whose open neighbourhoods are infinite.
Then it is quite easy to understand that:

$X$ is not discrete, hence it has at most one limit point $p$
$p$ is the unique limit point of $X$: otherwise, denoting by $p,p'$ two limit points, find $U, U'$ two disjoint open sets separating $p$ and $p'$, these are both infinite, against our assumptions on $X$.
$X$ is compact: if $U_i$ is an open cover, one of these open sets is a neighbourhood of $p$ and its complement is finite.

An easy example of a metric space satisfying these three properties is
$$K= \{ 1/n \}_{n \ge 1} \cup \{ 0 \} \subset \Bbb{R}$$
Anyway, $K$ has an infinite open set with infinite complement, namely:
$$U= \{ 1/2n\}_{n \ge 1}$$
Following this behaviour of $K$, take any infinite set $A \subset X$ with infinite complement. Clearly the closure of $A$ is
$$\overline{A}=A \cup \{ p \}$$
 since $p$ is the unique limit point of $X$. This shows that the infinite open set $X \setminus \overline{A}$ has infinite complement: we reached a contradiction. Hence such a metric space does not exist.
Comment: Why is $X$ compact ?
Comment: @TomCollinge If $\{ U_i \}_i$ is any open cover, then pick one of these open sets containing $p$. This is infinite, hence its complement is finite: so you can cover its complement with finitely many open sets, constructing a finite subcover.


Session in spring MVC

Question: Can anyone know at which point the user session is getting created in spring MVC?
Whether once the user request reaches the controller layer or Service layer or DAO layer.
Whether the DispatcherServlet is responsible for creating the JSessionID for each user and at what point it will get created?
Answer: A session is created when an http request is received by the servlet container - tomcat, glassfish etc.
It is independent of spring. However you can associate @SessionAttributes with sessions, although I try and avoid this and keep everything stateless.

Session in spring MVC


Chopin's Nocturne 2 : D natural or E natural?

Question: I'm sight-reading the second (2a : "Version with later authentic variant") Chopin's nocturne in Eb for piano, Op. 9 No. 2, and I am unsure about how to read the left hand in the second bar :
music score photo
Does the last "natural" sign in this second bar apply to the D or the E in this case?
I'd say the E but it also would be redundant with the first one in that case so I wonder if it wasn't meant for the D.
Comment: [Trouble understanding two accidentals in Chopin's Nocturne Op 9 No 2](https://music.stackexchange.com/q/51272/21766)
Answer: It's an E natural. The chord is an E diminished seventh chord over an F pedal tone, which leads back to F minor in the next chord.
The marking would seem to be Chopin's own, as it appears in the Henle urtext edition (image below), and it is placed consistently at each parallel measure (see mm. 6, 14, and 22).

It also appears in the (French) first edition, presumably proofread and approved by Chopin. (Source: IMSLP)
Answer: Based solely on the natural's position and alignment, I'd also say it's for the E and not the D. It's redundant, but that wouldn't be the first time I've seen redundant non-courtesy accidentals in sheet music from books (I typically see those at the starts of measures, though).
Musically, making the natural for the D and not the E destroys the inner descending line in the left hand from E natural to D flat to C by inserting a D natural between the D flat and the C.
Comment: In addition, both notes are on the same pedal, that would make it quite crowded with D natural. Also Eb would produce quartal harmony which I think is unusual for Chopin, while with Db-E makes it more probable Bbmadd.#4
Comment: It's a courtesy accidental, not a non-courtesy one.
Comment: @Tim - I'm of the firm belief that only accidentals in parentheses are courtesy accidentals.
Comment: Sounds fair to me, but some embalmers, sorry, engravers...
Comment: @Dekkadeci I do not believe the Henle accidentals in parentheses are courtesy accidentals. They are the editor's way of suggesting which lower and upper notes should be played in the turn, since the sources used to prepare the edition have no indication. The second natural sign on the left-hand E is done as a courtesy, but also serves to avoid an E with no sign, which could be taken for a misprint for a forgotten flat sign.


Storage account access for 3rd party Azure

Question: we are trying to set up a storage account where a third party company can come and programmatically collect updated files, we upload a new file, then the company gets an email notification but we are stuck where the company needs a sas token, that's fine but it's per blob, does anyone know how we can set up access to storage account for third party for them to programmatically collect the latest files in a secure mannner?
Thanks in advance :)
Answer: If you want to give access at the container level, specify "container" as the allowed resource type.
Comment: Hi Guy :) Welcome to SF. It's always nice to see another Canadian MVP around :)
Comment: does that give them access to the container and then the 3rd party company can query the account for latest file, what happens when someone generates a new SAS, will the previous stay active until the end date specified in the token?
Comment: Q1: Yes.  Q2: the previous ones stay active as you can't revoke them.  If you want to be able to revoke a SAS, first create a Stored Access Policy then a SAS based on that SAP as you can revoke a SAP.
Comment: thanks that's a great help, one last question if i may, they use the url and the sas token to access the container and extract the latest file added, would they use powershell or internet explorer for this, for individual blobs it's IE not sure about container files
Comment: When using the container URL combined with the SAS with the List permission, they will be able to list the files with any tool/language.


Integrating MS CRM 2011 with Outlook 2016

Question: Please can you let me know it is possible to integrate MSCRM 2011 with Outlook 2016? There are couple of links where some says they do support while other says they do not support.
Answer: The answer is yes for CRM 2011 >= UR18.
According to Technet, CRM for Outlook 2011 requires one of the following:

Microsoft Office 2016
Microsoft Office 2013
Microsoft Office 2010
2007 Microsoft Office system SP2
Microsoft Office 2003 SP3

Additionally the following limitations are listed for Office 2016:

Office 2016 compatibility requires Microsoft Dynamics CRM 2011 Update
  Rollup 18 or later update rollup.
Click-to-Run installed versions of
  Office 2016 are not compatible with Microsoft Dynamics CRM 2011.
Comment: "Click-to-Run installed versions of Office 2016 are not compatible with Microsoft Dynamics CRM 2011." ...didnt got this point?
Comment: The system which I am working on uses Update rollup 13.What it takes to upgrade to update rollup 18+
Comment: I have couple of Querys here:
1. How do we upgrade from the rollup 13 to 18, will it  be direct deployment of UR 18 or we need to install 14,15 etc.. 2. Is it safe to upgrade?
3. Any other requirement for UR18 that you didnt mention


What do you call a play when the offensive line is on the side?

Question: I saw recently in some video a play where only two guys, namely one who snaps and other one who catches a snap, were between the hash marks, but the offensive line was on the side of the line of scrimmage. It looked a bit weird, so I'm curious what kind of play it is, and what are its advantages and so on.
Does anyone know the name of this play?
Comment: See also: https://en.wikipedia.org/wiki/A-11_offense
Answer: The swinging gate formation, as you described, has the entire offensive line on one side of the center and quarterback, with perhaps only one wide receiver on the other side of the center.  It is pretty rare, and the advantages are surprise and the fact that you have a lot of blockers on one side for a running play if you don't need many yards.  The biggest disadvantage is that your quarterback is completely unprotected on one side, so the quarterback needs to get rid of the ball in a hurry.
Comment: The reason to have a wide receiver on the other side of the center is that otherwise the center must be an eligible receiver, as he would be the outermost line player on that side. I'm not actually certain whether or not that's legal.
Comment: It's legal as long as the "center" reports as an eligible receiver for that play.
Answer: Got it! It is called swinging gate.
Comment: Welcome to Sports SE. Feel free to [accept](http://sports.stackexchange.com/help/accepted-answer) your (or another) answer.


High Load With Call Trace

Question: My server is running Debian 6 64bit with kernel 2.6.32-5-amd64, a few times a day the load on my server goes very high I have this call trace below can anyone explain to me what the problem is?
    [521565.551017] Call Trace:
[521565.551019]  <IRQ>  [<ffffffff810ba7b3>] ? __alloc_pages_nodemask+0x59b/0x5fc
[521565.551029]  [<ffffffff81248c08>] ? skb_gro_receive+0x17e/0x3cf
[521565.551034]  [<ffffffff810e6b26>] ? new_slab+0x5b/0x1ca
[521565.551037]  [<ffffffff810e6e85>] ? __slab_alloc+0x1f0/0x39b
[521565.551039]  [<ffffffff8124896e>] ? __alloc_skb+0x3e/0x15a
[521565.551041]  [<ffffffff8124896e>] ? __alloc_skb+0x3e/0x15a
[521565.551044]  [<ffffffff810e7261>] ? kmem_cache_alloc_node+0x8b/0x10b
[521565.551046]  [<ffffffff8124896e>] ? __alloc_skb+0x3e/0x15a
[521565.551051]  [<ffffffff8119bf48>] ? swiotlb_map_page+0x0/0xc4
[521565.551053]  [<ffffffff8124996c>] ? __netdev_alloc_skb+0x29/0x45
[521565.551063]  [<ffffffffa0058b00>] ? tg3_alloc_rx_skb+0x96/0x11e [tg3]
[521565.551067]  [<ffffffffa006291e>] ? tg3_poll_work+0x45a/0xb49 [tg3]
[521565.551072]  [<ffffffff8127362c>] ? ip_local_deliver_finish+0x146/0x1e9
[521565.551076]  [<ffffffff8124fc8a>] ? napi_gro_flush+0x1e/0x39
[521565.551080]  [<ffffffffa0063139>] ? tg3_poll+0x8f/0x1a8 [tg3]
[521565.551084]  [<ffffffff811f6f71>] ? mix_pool_bytes_extract+0x57/0x14a
[521565.551087]  [<ffffffff8124fd8e>] ? net_rx_action+0xae/0x1c9
[521565.551091]  [<ffffffff81053d2b>] ? __do_softirq+0xdd/0x1a6
[521565.551095]  [<ffffffff81011cac>] ? call_softirq+0x1c/0x30
[521565.551097]  [<ffffffff8101322b>] ? do_softirq+0x3f/0x7c
[521565.551100]  [<ffffffff81053b9b>] ? irq_exit+0x36/0x76
[521565.551102]  [<ffffffff81012922>] ? do_IRQ+0xa0/0xb6
[521565.551104]  [<ffffffff810114d3>] ? ret_from_intr+0x0/0x11
[521565.551106]  <EOI>  [<ffffffff81017318>] ? mwait_idle+0x72/0x7d
[521565.551110]  [<ffffffff810172c8>] ? mwait_idle+0x22/0x7d
[521565.551113]  [<ffffffff8100fe97>] ? cpu_idle+0xa2/0xda
[521565.551115] Mem-Info:
[521565.551116] Node 0 DMA per-cpu:
[521565.551118] CPU    0: hi:    0, btch:   1 usd:   0
[521565.551120] CPU    1: hi:    0, btch:   1 usd:   0
[521565.551121] CPU    2: hi:    0, btch:   1 usd:   0
[521565.551123] CPU    3: hi:    0, btch:   1 usd:   0
[521565.551124] CPU    4: hi:    0, btch:   1 usd:   0
[521565.551126] CPU    5: hi:    0, btch:   1 usd:   0
[521565.551127] CPU    6: hi:    0, btch:   1 usd:   0
[521565.551129] CPU    7: hi:    0, btch:   1 usd:   0
[521565.551130] Node 0 DMA32 per-cpu:
[521565.551132] CPU    0: hi:  186, btch:  31 usd:   0
[521565.551133] CPU    1: hi:  186, btch:  31 usd:   0
[521565.551135] CPU    2: hi:  186, btch:  31 usd:   0
[521565.551136] CPU    3: hi:  186, btch:  31 usd:   0
[521565.551138] CPU    4: hi:  186, btch:  31 usd:   0
[521565.551139] CPU    5: hi:  186, btch:  31 usd:   0
[521565.551141] CPU    6: hi:  186, btch:  31 usd:   0
[521565.551142] CPU    7: hi:  186, btch:  31 usd:   0
[521565.551143] Node 0 Normal per-cpu:
[521565.551145] CPU    0: hi:  186, btch:  31 usd:   0
[521565.551147] CPU    1: hi:  186, btch:  31 usd:   0
[521565.551148] CPU    2: hi:  186, btch:  31 usd:  30
[521565.551150] CPU    3: hi:  186, btch:  31 usd:   0
[521565.551151] CPU    4: hi:  186, btch:  31 usd:   0
[521565.551153] CPU    5: hi:  186, btch:  31 usd:   1
[521565.551154] CPU    6: hi:  186, btch:  31 usd:   0
[521565.551155] CPU    7: hi:  186, btch:  31 usd:   0
[521565.551159] active_anon:50248 inactive_anon:44179 isolated_anon:0
[521565.551160]  active_file:1929286 inactive_file:1929366 isolated_file:0
[521565.551161]  unevictable:0 dirty:307090 writeback:56879 unstable:0
[521565.551162]  free:18514 slab_reclaimable:68418 slab_unreclaimable:51386
[521565.551163]  mapped:260756 shmem:95 pagetables:4659 bounce:0
[521565.551165] Node 0 DMA free:15852kB min:12kB low:12kB high:16kB active_anon:0kB inactive_anon:0kB active_file:0kB inactive_file:0kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:15296kB mlocked:0kB dirty:0kB writeback:0kB mapped:0kB shmem:0kB slab_reclaimable:0kB slab_unreclaimable:0kB kernel_stack:0kB pagetables:0kB unstable:0kB bounce:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no
[521565.551173] lowmem_reserve[]: 0 2991 16121 16121
[521565.551175] Node 0 DMA32 free:53496kB min:3012kB low:3764kB high:4516kB active_anon:13668kB inactive_anon:24464kB active_file:1297884kB inactive_file:1298024kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:3063648kB mlocked:0kB dirty:290652kB writeback:41076kB mapped:221156kB shmem:16kB slab_reclaimable:71508kB slab_unreclaimable:55600kB kernel_stack:360kB pagetables:1048kB unstable:0kB bounce:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no
[521565.551184] lowmem_reserve[]: 0 0 13130 13130
[521565.551187] Node 0 Normal free:4708kB min:13224kB low:16528kB high:19836kB active_anon:187324kB inactive_anon:152252kB active_file:6419260kB inactive_file:6419440kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:13445120kB mlocked:0kB dirty:937708kB writeback:186440kB mapped:821868kB shmem:364kB slab_reclaimable:202164kB slab_unreclaimable:149944kB kernel_stack:1480kB pagetables:17588kB unstable:0kB bounce:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no
[521565.551196] lowmem_reserve[]: 0 0 0 0
[521565.551198] Node 0 DMA: 1*4kB 1*8kB 2*16kB 2*32kB 2*64kB 0*128kB 1*256kB 0*512kB 1*1024kB 1*2048kB 3*4096kB = 15852kB
[521565.551204] Node 0 DMA32: 121*4kB 276*8kB 539*16kB 1197*32kB 4*64kB 4*128kB 0*256kB 2*512kB 0*1024kB 1*2048kB 0*4096kB = 53460kB
[521565.551211] Node 0 Normal: 612*4kB 80*8kB 43*16kB 16*32kB 0*64kB 0*128kB 0*256kB 1*512kB 0*1024kB 0*2048kB 0*4096kB = 4800kB
[521565.551217] 3883344 total pagecache pages
[521565.551218] 24509 pages in swap cache
[521565.551220] Swap cache stats: add 96013, delete 71504, find 812823/817958
[521565.551221] Free swap  = 4737200kB
[521565.551222] Total swap = 4878304kB
[521565.594382] 4194304 pages RAM
[521565.594383] 77961 pages reserved
[521565.594384] 2084547 pages shared
[521565.594385] 2278383 pages non-shared
[521565.594387] SLUB: Unable to allocate memory on node -1 (gfp=0x20)
[521565.594390]   cache: kmalloc-256, object size: 256, buffer size: 256, default order: 1, min order: 0
[521565.594393]   node 0: slabs: 500, objs: 15104, free: 8
[521598.698442] swapper: page allocation failure. order:4, mode:0x4020
[521598.698451] Pid: 0, comm: swapper Not tainted 2.6.32-5-amd64 #1

Answer: I obviously don't know for certain, but judging from that trace, I'd say it's

network related
indicates your kernel can't allocate memory to handle whatever is coming in
specifically inbound traffic related

I would start by running a traffic trace, to correlate inbound network traffic to the periods of slowness.  That might give you some insight as to what is going on.
It could also be entirely unrelated to network traffic and just be a memory issue.  Check the output of free -m.

High Load With Call Trace


Ubuntu LXC 14.04 Error

Question: I had installed LXC in ubuntu 14.04. I had used an existing template and created a VM by executing the below command.
/usr/share/lxc-templates/lxc-ubuntu -p /lxc/vm0
After the installation getting the below error.
lxc-unshare: symbol lookup error: /usr/lib/x86_64-linux-gnu/liblxc.so.1: undefined symbol: cgmanager_get_pid_cgroup_abs_sync
The same error get repeated whever i execute any command with lxc-*.

What can be the problem?
How can i get this fixed?

Thanks
Sandeep Krishnan
Comment: Hi Guys,
apt-get upgrade fixed the issue.
Answer: Take a look here:
https://github.com/lxc/lxc/issues/247
You basically just need to update your ubuntu
sudo apt-get update
sudo apt-get upgrade

and it should work.
Answer: It is probably because you are running an old libcgmanager. To fix this problem, you need to update libcgmanager.
$ sudo apt-get install libcgmanager0 --upgrade
Comment: This solution is better than the best answer. That one upgrades all the packages which it is not desired all the time.

Ubuntu LXC 14.04 Error


What if Cochran-Armitage test ("linear by linear association" for trend in SPSS) is significant but associated chi-square test is not signficant?

Question: I administered a customer service satisfaction survey, and one of the questions is a check-all-that-apply asking respondents to check the boxes for the services that they liked most (medication assistance, linkage to medical doctor, housing assistance, therapy, and additional funds). I wanted to determine not only if there were significant differences in the proportions of "yes" to "no" response counts as a function of age group (55-60, 61-65, 66-70, 71+) for each of the above services, but also to see if there were any significant decreasing or increasing trends in proportion of "yes" to "no" responses as a function of increasing age for each category.  I received insight into this at this post.  Here is the link to my post to get clarity on tests to run for these research questions.
I conducted chi Square tests to investigate if any significant differences in popularity of the above services, and separately Cochran-Armitage tests (linear-by-linear association test for trends) to answer the question about whether there are any trends for each of the categories.
Now I wonder if anyone can offer insight into the following finding for the "medication assistance" choice.  I'm using an alpha of .05 as the threshold for rejecting the null hypothesis, and the linear-by-linear association finding shows that the result is significant (p=.035) while the associated Pearson Chi-Square is not (p=.213).  How can there be both a significant trend of decreasing proportion of popularity of medication assistance, but at the same time a non-significant difference in proportions of "yes" to "no" responses as a function of age group?  Isn't the finding of a significant trend dependent on the significant differences between the proportions of "Yes" to "no" responses of each level of age group?
tables of yes and no responses and findings for medication assistance choice
Answer: One thing to understand about p-values is that they are dependent on sample size.  As a simple experiment, multiply each of your counts by 2, and then re-run the tests.  The p-values will decrease, despite the fact that the distribution of the counts is exactly the same as your original data.  This is one reason why experimenters are cautioned about putting too much meaning into p-values.
Another thing to keep in mind is that if you fail to reject the null hypothesis, that is, if p >= 0.05, the conclusion is not that you accept the null hypothesis, but that you don't have good evidence to reject the null hypothesis.  This may simply be because you don't have sufficient power to reach a small enough p-value.  If you had the same distribution of values, but just twice the observations, you may have had sufficient power to come to a different conclusion.
Considering these tests and your results, basically the fact is that the Cochran-Armitage test has greater power than a chi-square test of association if there is a trend in the ordinal categories.  That's the advantage of this test in these situations.


Disable mod_cache to fix website

Question: I am working on a website that runs on WordPress. The an error occurs when accessing the blog page that it displays the RSS feed (in XML) rather than the posts. After some research I found out the when enabling mod_cache this error sometimes occurs. I see when looking at the apache2 modules enabled apache2ctl -M it shows that mod_cache, mod_mem_cache and mod_disc_cache are enabled. What should I disable in order to resolve this problem?
Answer: Make sure you do not have a CacheIgnoreQueryString On directive, or that it's set to off. Also that you do not have a CacheIgnoreHeaders Accept directive. I'm not terribly familiar with WordPress RSS generation, but disabling caching altogether is going to be really bad for performance.
Comment: Thanks for your comment. I actually fixed this quite some months ago, I simply disabled the mod completely and that fixed it.

Disable mod_cache to fix website


is canvas html5 be readonly?

Question: I want my html5 canvas as readonly. Is that possible?
Answer: No, the canvas is compiled and rendered on the client-side.

is canvas html5 be readonly?


How do I access the profile picture of a facebook user in PHP?

Question: I am developing an app that will use the profile picture of user. I am trying to save the profile picture of the user on my server for manipulation.
When I use https://graph.facebook.com/[uid]/picture?type=large it will not work because there is some sort of redirection that facebook does before serving the pic.
Can anyone help me with this issue? I am using PHP.
Comment: What are you using to download the image? Try to modify it to follow redirects.
Comment: Show the PHP, that you use to call that URL. Are you using a facebook API framework?
Answer: If I understand your issue correctly, you are probably using file_get_contents to fetch the image but you are just getting a text response back, because file_get_contents does not automatically follow the redirect the text response contains?
A quick-and-dirty solution is to parse the text response yourself to find the url of the actual image:
@file_get_contents('https://graph.facebook.com/'.$userid.'/picture?type=large');
foreach ($http_response_header as $rh) if (substr($rh, 0, 10)=='Location: ') $imgurl=substr($rh, 10);

Then you should have the actual image url that you can process as needed.
Answer: You can use the graph API to retrieve the direct URL for the user's profile picture.
https://graph.facebook.com/{user_id}/picture
Answer: <?php
# You can do:

$userid = SOMEID;

$piclink = 'https://graph.facebook.com/'.$userid.'/picture?type=';

#then a option to choose the type,
#there is the small, normal, square and large type.
#So lets say you choose the large size:

$pictype = 'large';

$userpicture = $piclink . pictype;

# ----------------------------------
# Now that we have a picture link you can do various stuff like:

echo '';

?>

Now, if what you want is to save the image to the database then see this
http://www.phpriot.com/articles/images-in-mysql
Then when storing the image use that $userpicture to get it.


One user with multiple profiles

Question: I'm setting up a webshop were clients can have multiple profiles. For example a customer and supplier profile.
Whenever the user logges in, he gets a choice which profile he wants to sign in. Depending on which profile the user has selected, he gets to see different views.
Above this, the user should be able to change from profile within the site... Much like the Masquerade-module, but in this case, it should be for all users.
I hope I make myself clear on this one...
Some advise on how to tackle this issue would be most welcome!
Answer: Discussion about one user - multiple personas started and ended at drupal.org in 2007. I think your best bet is to use masquerade as a code example and implement it yourself.
Answer: You can achieve this with help of user roles
and profile module

The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module by
  default.
      Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated
  permissions for those.

there is also a useful module which you can use
Profile2 Registration Path

This module enables administrators to set unique registration paths
  per Profile2 profile type
Comment: This doesn't allow users to switch accounts without logging out and back in though.
Comment: Answer is not relevant to question..

One user with multiple profiles


Does AMF support caching?

Question: In other words: Can I respond with a 304 and have it "just work"?
Comment: Yes, AMF is a binary format, but it is transported via HTTP - which means I should be able to use built-in browser caching using HTTP headers to control expiration. I'm just not sure if this works with any of the AMF libraries.
Comment: Isn't AMF a binary data format?  How can a format support caching?  I believe if you want to cache data, you'll have to implement such caching mechanisms yourself.
Answer: By default Flex's RemoteObject and BlazeDS handle AMF requests as POSTs so they won't cache in the browser.  You could change that by implementing your own servlet that serializes GET responses as AMF.  Then on the Flex side use URLLoader to make the request.  That might cause the browser to cache the response.

Does AMF support caching?


Are there any size limits on the squad size for international cricket match series?

Question: I often see the cricket team squads for a tournament/series contain 15 players. From those 15, playing eleven would be sorted for each match.
But, for the India's tour of South Africa 2013, Indian team has 16 players in ODI squad and 17 players for test matches.
I would like to know if there are any limitations on the squad size for international cricket match series? (i.e. a maximum and minimum count).
Comment: Good question. I think the squad size is decided by mutual agreement between the two boards. I vaguely recall during India's tour to WI in 1997, when Sachin was the captain, they initially had 16 players, but then he requested the BCCI to send an additional player when someone was sick, and then the BCCI took WICB's approval and then sent the 17th player. Didn't find any official source though. For ICC events like World Cup, this is obviously decided by the ICC.
Comment: @Happy, after fixing a squad, if a team needs an another player(as in your pointed example), then there is a need of mutual agreement between two cricket board. Is there any fixed squad size for a team while selecting the players for the series?
Comment: I am guessing that's also by mutual agreement. Another possibility is if the squad consists of upto 16 members, they don't bother on an explicit agreement, but if they need more than 16, then an agreement is required. For instance, if a visiting team comes with only 14 players, the home board wouldn't probably be bothered.
Answer: According to the official ICC Squad Registration Form, there can be a maximum of 18 players in an squad in both Men's and Women's Cricket.
ICC Squad Registration Form - Men's Cricket
ICC Squad Registration Form - Women's Cricket
Comment: @BenMiller Yes, you are correct but that's the only official information available in this regard.
Comment: Just because the registration form has 18 spots on it doesn't necessarily mean that the rules forbid more than 18 players, does it?
Answer: For an ICC tournament, the squad size, as well as the date it must be submitted by, are fixed. Look at the rules for the specific tournament for the allowed squad size.
For a bilateral tour, squads can be as small or large as the teams like. For the first ever Eng/Aus tour, England sailed over with only 12 men, one of whom caught a STD early in the tour leaving the squad with only the bare eleven. Modern touring squads are much larger and often have the 'A'-team touring nearby to provide even more cricketers in case of injury.
Home squads are effectivly unlimited in size. While home teams often name a 12-man squad a day or two before the game, there is nothing stopping the home coach from naming a 12 man squad but, 30 minutes before the match starts, going down the nearby pub and grabbing eleven locals to play.
Comment: Welcome to SE.Sport. The answer is interesting when you are able to add any official references


Instanciar uma função global padrão para chamar funções

Question: Gostaria de saber como posso criar uma variável global (ou elemento global, não sei como chama) como em vários plugins que vejo. Exemplo no Jquery onde para chamar qualquer função referente a ele só tenho que instanciar o símbolo # ou chamar pela função Jquery antes de qualquer função interna do plugin.
Quero que em minha aplicação eu consiga chamar algo do tipo:
MeuElemento.Cria(args);
MeuElemento.Salvar(args);
MeuElemento.Outrafunção(args);

Como faço isso? Alguém por favor me consegue um exemplo?
Answer: Basta criar um objeto global e adicionar funções a ele.
Quando você faz um objeto global, como abaixo, ele fica visível... Bem, globalmente.
var foo = {}; // foo só será global se essa linha rodar no escopo global, ok?

Agora é só adicionar funções ou o que mais você quiser. Você pode fazer isso a qualquer momento, pois os objetos em Javascript podem receber novas propriedades e métodos dinamicamente.
foo.monstraUmPopup = function (args) {
    alert(args);
}

E você pode chamar globalmente também:
foo.mostraUmPopup("tio");

Experimente no console do seu navegador.
Comment: Eu não recomendaria omitir o `var`. Melhor usá-lo, certificando-se de que a variável está sendo declarada no escopo global. Acho menos confuso.
Comment: muito obrigado, vai ficar bem mais organizado meu código rs
Comment: @bfavaretto Não usar `var` força a variável a ficar no escopo global, mas tens razão quanto a ser menos confuso com `var`. Vou editar.
Comment: Eu sei que força, mas sempre acho bom recomendar nunca omitir :) Já falei disso aqui: http://pt.stackoverflow.com/a/2517/74. PS: obrigado pelo edit


Definir css com php de acordo com o navegador

Question: Hoje cedo fiz esta pergunta.
O que preciso saber, é como posso fazer algo parecido com isso:

Verificar se o navegador é ou não o Safari.
Se for, section#internal.services aside ul li a deve receber este css:

CSS aplicado:
color:#666666;
display:block;
font:normal normal bold 15px/normal Questrial, Arial;
height:70px;
line-height:4em;

Qual seria a melhor forma de fazer isso, com php?
Comment: A página html é gerada a partir de uma template engine como dwoo ou smarty?
Comment: @ricardo Não...
Comment: Como é gerada? poste aqui
Comment: @ricardo Perdão, sou novo em programação, não entendi ao que você se refere...
Comment: Postei pra ti a resposta, verifique. Testei aqui e está funcionando corretamente.
Comment: Editei minha resposta, como não tinha seus Css dois links para dar o mesmo efeito.
Answer: É possivel verificar o user agent desta forma:
  <?php
    $useragent = $_SERVER['HTTP_USER_AGENT'];

  if (preg_match('|MSIE ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = 'IE';
  } elseif (preg_match( '|Opera/([0-9].[0-9]{1,2})|',$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = 'Opera';
  } elseif(preg_match('|Firefox/([0-9\.]+)|',$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = 'Firefox';
  } elseif(preg_match('|Chrome/([0-9\.]+)|',$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = 'Chrome';
  } elseif(preg_match('|Safari/([0-9\.]+)|',$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = 'Safari';
  } else {
    $browser_version = 0;
    $browser= 'other';
  }
?>

        <title></title>
        /*<?php
            if($browser == 'Safari')
                echo '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">';
            else
                echo '';
         ?>*/

         <?php
              if($browser == 'Safari'){
                  echo '';
              }else{
                  echo '';
              }
         ?>

Como desejo do AP foi aplicado o id especifico ao elemento caso o browser seja o safari. É necessário que o estilho que será aplicado ao elemento quando no safari esteja no css.
Adendo: Ainda é possível com esta Super Global $_SERVER['HTTP_USER_AGENT'] identificar qual o SO
Comment: ricardo obrigado pela resposta, pode me mostrar como posso fazer usando o css no html? digo sem chamar um arquivo externo.
Comment: Por exemplo, se for safari `section#internal.services aside ul li`vai receber aquele css que passei na pergunta
Comment: Adicionei o meu html a pergunta, gostaria de adicionar o css utilizando a tag `
Comment: Perdão ricardo, acho que não me expliquei bem. Eu preciso que o elemento `section#internal.services aside ul li a ` receba um css caso esteja no safari, caso em outro, receba outro css. Mas quero fazer isso no mesmo arquivo. Usando ``.
Comment: Mas no meu exemplo você pode definir ele. Porém, não é possivel se ele estiver externo... Ele precisa estar no mesmo arquivo que está recebendo a página do CSS, porque não dá para interagir o CSS dentro de um arquivo .css, só se ele estiver dentro do
Comment: @Skyirn Para o que deseja julgo que haja duas soluções uma seria a primeira que havia feito onde há uma seleção entre arquivos css (esta na minha resposta marcada com comentários) a outra opção seria a do AndreBaill
Answer: Você pode buscar o userAgent, e verificar o navegador, e com base nisso, pode então definir seu css.
Segue o exemplo:
 if (preg_match('|MSIE ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
    $css = "border: solid 5px blue;";
    $browser = 'IE';
  } elseif (preg_match( '|Opera/([0-9].[0-9]{1,2})|',$useragent,$matched)) {
    $css = "border: solid 5px blue;";
    $browser = 'Opera';
  } elseif(preg_match('|Firefox/([0-9\.]+)|',$useragent,$matched)) {
    $css = "border: solid 5px red;";
    $browser = 'Firefox';
  } elseif(preg_match('|Chrome/([0-9\.]+)|',$useragent,$matched)) {
    $css = "border: solid 5px blue;";
    $browser = 'Chrome';
  } elseif(preg_match('|Safari/([0-9\.]+)|',$useragent,$matched)) {
    $css = "border: solid 5px red;";
    $browser = 'Safari';
  } else {
    $css = "border: solid 5px red;";
    $browser= 'other';
  }

Use da seguinte forma:
No $css eu inclui o CSS, e então você pode colocar:

Com isto, importará o css corretamente.
Comment: André, como definiria o css assim fazendo?
Comment: A verificação funciona corretamente, mas não entendi como posso definir o css! Pode me ajudar?
Comment: Você pode colocar o CSS dentro do $css ou então, você pode definir o css dele separado...  se caso for Firefox, ou se for os demais, você pode definir o outro css.
Comment: Mas como digo que meu elemento deve receber o estilo dentro de $css?
Comment: Coloquei um exemplo pra ti
Comment: Se quiser add no skype @Skyirn - srandrebaill - Sempre fico mais lá do que no site.. Precisando, só chamar. Respondo aqui sempre que vejo.
Comment: Muito obrigado!
Comment: Deu certo minha resposta?
Comment: Estou testando, se funcionar irei marcar como aceita!
Comment: Ok, sem problemas! :)
Comment: @Skyirn Alterei minha resposta, verifique se atende sua necessidade.
Comment: André, fiz dessa forma, mas não funcionou ):
Comment: está dando em todos os navegadores que é safari
Comment: Consegui, obrigado!
Comment: Por via das dúvidas, alterei também o código com todos os navegadores, sugestão do @ricardo, para que faça a iteração correta. Caso tenha dúvidas, estamos todos por aqui!
Comment: Muito obrigado pela ajuda!


Can I access data in Nx3 Matrix for other column with specific value

Question: Say I have
data=np.array([[30,0.109,1],
               [25,0.517,2],
               [22,0.174,1],
               [35,0.812,3],
               [45,0.215,4],
               [40,0.111,4],
               [50,0.095,4]])

Doing
A = data1[:,2]
print(A)

Will give me
[1. 2. 1. 3. 4. 4. 4.]

Is there a command so I can get the values from other columns (1 or 2) if column 3 has a value of 4
In my mind it would look like this
B=data[:,1,[2]=4]
So B should print out
[0.812, 0.215, 0.111]
Is this possible?
The reason I need it is for graphical display. The number in column 3 corresponds to a type of bacteria (I.e. all 4's are the same bacteria), from which I need to plot the other values "bound" to that type of bacteria.
Hope its possible, and all the best
Comment: Unfortunately not for me, it prints out exactly the same as print(data[[:, [0,1]])
Comment: the output should be `array([0.215, 0.111, 0.095])`
Comment: Does this answer your question? [Numpy select rows based on condition](https://stackoverflow.com/questions/58079075/numpy-select-rows-based-on-condition)
Comment: what is `data1` in the question ?
Answer: You need to use boolean indexing:
out = data[data[:, 2]==4, 1]

Output:
array([0.215, 0.111, 0.095])


Silverlight 4 chart created at runtime won't show data

Question: Using the Silverlight 4 toolkit chart control, I am trying to create a chart 100% at runtime with no evidence of it anywhere in the XAML. To do so, I create the blank chart when the page loads:
<code>        Chart TrendChart = new Chart();
        TrendChart.Name = "TrendChart";
        TrendChart.Title = "Call History";
        TrendChart.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
        TrendChart.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
        TrendChart.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
        TrendChart.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch;

        GridPanel.Children.Add(TrendChart);
</code>
After the user clicks on a button to retrieve data, a List is created of this custom class:
<code>    private class PhoneTrendDataPoint
    {
        public string XValue { get; set; }
        public double YValue { get; set; }
    }
</code>
I use that List, called CurrentCallTrends, as an ItemsSource for my chart.
<code>        // Update the chart with the received data
        Chart TrendChart = (Chart)this.FindName("TrendChart");

        // Wipe out previous chart data
        TrendChart.Series.Clear();

        // set the data
        ColumnSeries columnSeries = new ColumnSeries();
        columnSeries.Name = "Current Call Volume";
        columnSeries.ItemsSource = CurrentCallTrends;
        //columnSeries.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding("CurrentCallTrends"));
        columnSeries.DependentValueBinding = new Binding("XValue");
        columnSeries.IndependentValueBinding = new Binding("YValue");
        TrendChart.Series.Add(columnSeries);
</code>
The problem is that I get a runtime error where it prompts me to open a debugger regarding an object reference not set to an instance of an object. If I comment the line to .SetBinding then the ItemsSource vanishes and no data shows up, but at least there is no runtime error.
What am I missing?
Comment: I declared this at the top of the class. It is:        private List CurrentCallTrends = new List();
Answer: After additional Googling, I made some modifications that seem to work but don't strike me as the best way to go about doing this. Data now shows up, but I will not accept this as the answer unless there is no better method:
<code>        // Update the chart with the received data
        Chart TrendChart = (Chart)this.FindName("TrendChart");

        // Wipe out previous chart data
        TrendChart.Series.Clear();

        // test data
        KeyValuePair<string, double>[] CurrentCallData = new KeyValuePair<string, double>[CurrentCallTrends.Count];
        for (int i = 0; i < CurrentCallTrends.Count; i++)
        {
            CurrentCallData[i] = new KeyValuePair<string, double>(CurrentCallTrends[i].XValue, CurrentCallTrends[i].YValue);
        }

        // set the data
        ColumnSeries columnSeries = new ColumnSeries();
        columnSeries.Name = "CurrentCallVolume";
        columnSeries.Title = "Current Call Volume";
        columnSeries.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding());
        //columnSeries.ItemsSource = CurrentCallTrends;
        columnSeries.ItemsSource = CurrentCallData;
        columnSeries.DependentValueBinding = new Binding("Value");
        columnSeries.IndependentValueBinding = new Binding("Key");
        TrendChart.Series.Add(columnSeries);

        //this.DataContext = CurrentCallTrends;
</code>


Sampling from under/over-dispersed count data in R

Question: I am currently working a some datasets with count data in R, in which the response is the number of activities of a given type that were performed in one day by a population.
For each type, I build a Poisson model and test for over/underdispersion using the function dispersiontest() from package AER. Depending on the result, I switch to quasi-Poisson model when there is evidence of over- or underdispersion.
In a next step, I would like to sample and generate simulated data using the results of my models. If I have a Poisson model, I can use rpois() with lambda being the fitted value of the model. However, I have no idea how to do it in the cases of over/underdispersion. Any ideas?
Comment: Have you thought of swapping to a negative binomial model and then sampling using that distribution?
Comment: @mdewey this works fine indeed in the cases of overdispersion. However, sometimes I have underdispersion as well, and then the negative binomial isn`t appropriate since it assumes that the variance is necessarily larger than the mean
Comment: It sounds like this problem could be approached fully non-parametrically. This way you wouldn't have to make any assumptions about the superpopulation distribution, and you'd get error bars aroud the simulated data.
Comment: Quasilikelihood is not a probability model, only a weighting scheme to get proper parameter estimates. There exist alternatives to the Negative Binomial which allow underdispersion like the Gamma-count model (https://arxiv.org/pdf/1312.2423.pdf)
Answer: Simulating on the continuum from not overdispersed to over-dispersed is easy: you fix a rate $\lambda$ (no overdispersion) or you draw your rates from a gamma distribution (=overdispersion). This is one way of getting the negative binomial distribution. For example, if you want the negative binomial distribution with the parameterization that has a mean rate per time unit of $\mu$, a dispersion parameter $\kappa \in [0, \infty)$ ($\kappa=0$ = Poisson) and an observation time $t>0$, you can use functions like these:
# Simulate from NegBin(mu*t, kappa); mu>0, t>0, kappa>0
rnegbin = function(n, mu, kappa, t=1){ # Note: no protection against kappa <= 0
  rpois(n=n, mu*t*rgamma(n=n, shape=1/kappa, rate=1/kappa))
}

# Density function for NegBin(mu, kappa); mu>0, kappa>=0
dnegbin = function(x, mu, kappa, log=FALSE){
  if (kappa>0) {
    tmp = lgamma(x+1/kappa) - lgamma(x+1) - lgamma(1/kappa) + x*log(kappa*mu) - (x+1/kappa)*log1p(kappa*mu)
  } else { # no protection against kappa <0
    tmp = x*log(mu)-mu-lgamma(x+1)
  }
  if (log==F) return(exp(tmp)) else return(tmp)
}

If you do not really mind whether your overdispersed counts are from a negative binomial, you can of course also draw your rates from a log-normal distribution (or log-rates from a normal distribution).
I don't have much experience with simulating underdispersed counts, but one I idea would be to simulate Poisson random variables and to draw a new set with increasing probability the further away from the mean you are. It's a bit tricky to keep the expected value constant though (if that matters to you).
Answer: I would use the predict() function with the newdata parameter.
For simulation, we would need to create a random data set of predictors. Let's say that your model has 2 explanatory variables: a factor and a continuous variable. Some pseudo code could be:
set.seed(1) # Reproducibility
simfac <- sample(c("level1","level2"),100,replace=T) # Simulate 100 factor observations with 2 levels
simcont <- runif(100,0,1) # Simulate 100 continuous uniforms between 0 and 1
dat <- data.frame(simfac, simcont)
pred <- predict(model, newdata=dat, type="response") # Predict using the new data

Comment: @GabrielLM: The issue might be that in the predict function, you need to use type="response" (I've updated my answer). This applies the link function to the predictor.
Comment: Thanks for the reply! The prediction does work for the model, no matter what strategy I use it. However, the problem is that the result is a continuous variable, which will be equal to E[Y|covariates]. However, since  I have count data, I would to draw only discrete values so it would make sense.

An analogy: if I draw from a Poisson distribution with a non-integer Lambda, I will still get integer values
Comment: the type="response" will apply the link function indeed, but the result will be the expected response given the value for the covariates in the new data. However, it still does not solve the problem of drawing from the discrete distribution, as the outcome will be a continuous.

Let me give an example: My mean is 1.1 and variance is 0.1, thus most responses are 1. Using the predict function, all resulting values will be close to 1.1. What I would like is to be able to draw plausible data from it, i.e., most individuals would have a response of 1, but a few would have 0 or 2, etc.


Autosave with TinyMCE

Question: I have tried outputting code simliar to the custom_format example thats included with TinyMCE. I enabled the Autosave module, however I never see a "restore drafts" button. The only setting that doesn't wipe out all the buttons in the editor is using "theme_advanced_buttons3". Which also doesn't show a button with the 'restoredraft' value.
Edit: context
Answer: I have made some progress on this. I downloaded the TinyAutoSave module from https://code.google.com/p/tinyautosave/ which I believe is more recent than the 'autosave' plugin included with TinyMCE 3.4.4. There may be updates in the latest version of tinymce, but I haven't checked. It seems the codebases have forked, however.
Anyways, I ended up removing autosave from the tinymce.inc file located in sites/all/libraries/wysiwyg/editors. I put tinyautosave/ into sites/all/libraries/tinymce/jscripts/tiny_mce/plugins.
The solution involved was to not use the 'restoredraft' setting, and use the 'tinyautosave' one instead. I have some strange way that builds the wysiwyg settings table but it basically does:
<code>$settings['tinyautosave'] = array('tinyautosave' => 1);
</code>
Answer: After searching a bit I found a fixed issue at drupal.org. A dev describes how it is possible to integrate thirdparty plugins with tinyautosave as an example.
I just did what was described and everything works fine for me now.

Autosave with TinyMCE


linux/centos crashing periodically

Question: Excuse me if I'm not doing something right on the site it's my first time here (have used stackoverflow before).
I have a centos 5.2 server running Plesk and the tech support guys are refusing to look into this as they keep saying that I should just reboot, however that's not really a solution as it's happening a lot (perhaps once a week).
I have to admit I'm not hugely into Linux but I know my way around and here's what the syslem messages say for just before the server went down, can someone perhaps confirm my suspicion that this is a lack of RAM thing?
Dec  7 20:56:24 ns2435 kernel:  [<c10d67f7>] ? handle_mm_fault+0xf7/0x190
Dec  7 20:57:08 ns2435 kernel:  [<c10598e4>] ? do_page_fault+0x164/0x3f0
Dec  7 20:57:26 ns2435 kernel:  [<c10f2757>] ? filp_close+0x47/0x70
Dec  7 20:57:38 ns2435 kernel:  [<c1037df0>] ? do_device_not_available+0x0/0x20
Dec  7 20:57:44 ns2435 xinetd[4186]: START: smtp pid=10839 from=220.127.116.11
Dec  7 20:57:56 ns2435 kernel:  [<c1037dc4>] ? math_state_restore+0x24/0x50
Dec  7 21:02:31 ns2435 kernel:  [<c1059780>] ? do_page_fault+0x0/0x3f0
Dec  7 21:02:41 ns2435 kernel:  [<c19b42ba>] ? error_code+0x5a/0x60
Dec  7 21:02:42 ns2435 kernel:  [<c1059780>] ? do_page_fault+0x0/0x3f0
Dec  7 21:02:45 ns2435 kernel: Mem-Info:
Dec  7 21:02:45 ns2435 kernel: DMA per-cpu:
Dec  7 21:02:45 ns2435 kernel: CPU    0: hi:    0, btch:   1 usd:   0
Dec  7 21:02:49 ns2435 kernel: CPU    1: hi:    0, btch:   1 usd:   0
Dec  7 21:02:59 ns2435 kernel: Normal per-cpu:
Dec  7 21:03:08 ns2435 kernel: CPU    0: hi:  186, btch:  31 usd: 102
Dec  7 21:03:10 ns2435 kernel: CPU    1: hi:  186, btch:  31 usd:  84
Dec  7 21:02:58 ns2435 xinetd[4186]: START: smtp pid=10862 from=184.108.40.206
Dec  7 21:27:21 ns2435 kernel: active_anon:55616 inactive_anon:55680 isolated_anon:192
Dec  7 21:27:26 ns2435 xinetd[4186]: START: smtps pid=10924 from=220.127.116.11
Dec  7 21:27:29 ns2435 kernel:  active_file:216 inactive_file:399 isolated_file:0
Dec  7 21:27:31 ns2435 xinetd[10862]: warning: can't get client address: Connection reset by peer
Dec  7 21:27:32 ns2435 xinetd[4186]: START: submission pid=10928 from=22.214.171.124
Dec  7 21:27:32 ns2435 kernel:  unevictable:0 dirty:0 writeback:155 unstable:0
Dec  7 21:27:35 ns2435 xinetd[4186]: START: smtp pid=10931 from=18.104.22.168
Dec  7 21:27:35 ns2435 kernel:  free:1349 slab_reclaimable:965 slab_unreclaimable:4086
Dec  7 21:27:38 ns2435 xinetd[4186]: START: smtps pid=10932 from=18.104.22.168
Dec  7 21:27:38 ns2435 kernel:  mapped:221 shmem:25 pagetables:2663 bounce:0
Dec  7 21:27:40 ns2435 kernel: DMA free:2052kB min:88kB low:108kB high:132kB active_anon:6076kB inactive_anon:6308kB active_file:20kB inactive_file:252kB un$
Dec  7 21:27:43 ns2435 kernel: lowmem_reserve[]: 0 484 484 484
Dec  7 21:27:43 ns2435 kernel: Normal free:3344kB min:2768kB low:3460kB high:4152kB active_anon:216388kB inactive_anon:216412kB active_file:844kB inactive_f$
Dec  7 21:27:40 ns2435 xinetd[4186]: START: submission pid=10933 from=22.214.171.124
Dec  7 21:27:56 ns2435 kernel: lowmem_reserve[]: 0 0 0 0

Comment: Any reason you can't update to latest CentOS 5.x release?
Answer: You should try updating to CentOS 5.7 if at all possible, but here are some pointers to help you diagnose the problem:
Look at your memory usage with 'top', see how much memory is available, and how much is used by caches and buffers (can be considered as 'unused' for the sake of simplicity).
You could try monitoring your memory usage over time with something like cacti. Then when you system crashes again, you can see what the situation was before the crash.
If you are running low on available memory, this could be a cause of crashes. If this isn't the case, it could be a problem with bad memory or other hardware issues.
Try installing memtest86 and running that.
Comment: A big +1 for the upgrade suggestion, since it's not really an upgrade - all versions of CentOS 5 will be running the same versions of core tools, but later versions will have more fixes backported.  This is especially true of the kernel.  I'd +1 again for memtest86 to check the memory hardware if I could.
Comment: Hi there, theres about 10%-20% free memory right now and there's not really a lot going on on the server (this info gained by top). I know this is low, but would this cause regular total freezes of the system?
Comment: No, when you would have out-of-memory situations, you should be able to see those in the logs. It could be that you have some hardware issues, though these could be difficult to diagnose.
Answer: You need to issue following commands to analysis what happened on December 07
sar -f /var/logs/sa/sa07

will provide you information about all day report of cpu usage on december 07
sar -n -f /var/logs/sa/sa07

will provide you information about all day report of network  usage on december 07
sar -r -f /var/logs/sa/sa07

will provide you information about all day report of memory  usage on december 07
and if you like check other day of month like  17 the day of month , you need to issue following commands:
sar --f /var/logs/sa/sa17
sar -n -f /var/logs/sa/sa17
sar -b -f /var/logs/sa/sa17
sar -r -f /var/logs/sa/sa17

Answer: This kernel log does seem to point towards memory exhaustion.  If the server doesn't have the amount of ram that Plesk suggests for recommended operation, then you might be running into ram contention issues with the rest of the system.  This could be exacerbated if the server runs multiple logical services.
Answer: Do not rule out hardware failure.  Take the machine offline for a few hours and run Memtest86.  I had a machine once that exhibited consistent failures when I would run a particular application, without fail crash, but it was just one app.  On a whim I decided to run Memtest86 and within seconds I had thousands of errors.  Pulled the offending memory and I've never had issues since.
Also take note of when the failures occur.  For instance how long after reboot do they happen, was the system under heavy load?  What was the thermal characteristics like where your server was?
Answer: Don't rule in hardware failure before upgrading the kernel.
far more likely to be the known bug with MM and that version of the kernel than your ram chips/cosmic rays.
Google "handle_mm_fault" and your kernel version.
Read up on memory handling - the output of free is misleading if you don't understand that linux tends to use all the memory .
Google "linux ate my ram"
Comment: In fact ignore all answers above before you have upgraded _the_ _kernel_ only.

linux/centos crashing periodically


How to take limits of 'almost Riemann' sums like $\lim_{n \to \infty} \sum_{k=0}^n \frac{1}{n} \cos (a \pi k \log(n)/n)$

Question: How can I solve limits of sums that are 'almost' Riemann, but can't be written in the typical form (i.e, $\lim_{n \to \infty} \sum_{k=0}^n \frac{1}{n} f(k/n)$ which we can rewrite as an integral $\int_0^1 f(x) dx$)?
For example, I'd like to turn $\lim_{n \to \infty} \sum_{k=0}^n \frac{1}{n} \cos (a \pi k \log(n)/n)$ into an integral.
More generally, is there a closed-form way to convert sums like $\lim_{n \to \infty} \sum_{k=0}^n \frac{1}{n} f(k h(n)/n)$ into integrals, when $h(n) = o(n)$? Clearly such sums don't always converge - if $h(n) = \log(n)$, and $f(kh(n)/n) = k\log(n)/n$, the limit is unbounded. What conditions on $f, h$ might we require for convergence?
Comment: What is $N$?$\!\,$
Comment: Fixed, meant $n$ instead of $N$
Answer: This is not a comprehensive solution to the general question posed in the OP, however it does give a solution to the first (and more specific) question in the OP and gives some sufficient conditions for the more general question.

Suppose $h\geq0$, $h(n)\xrightarrow{n\rightarrow\infty}\infty$, and $h(n)=o(n)$.

Divide $[0,h(n)]$ in $n$ subintervals of same size. The size of each subinterval is $\frac{h(n)}{n}$ and the Riemann sum of the integral $\int^{h(n)}_0 f\,dx$ for the uniform partition is
$$\frac{h(n)}{n}\sum^n_{k=1}f\big(\frac{k}{n}h(n)\big)$$
Then
$$A_n:=\int^{h(n)}_0f(x)\,dx-\frac{h(n)}{n}\sum^n_{k=1}f\big(\frac{k}{n}h(n)\big)=\sum^{n}_{k=1}\int^{\tfrac{k}{n}h(n)}_{\tfrac{k-1}{n}h(n)}\Big(f(x)-f\big(\tfrac{k}{n}h(n)\big)\Big)\,dx$$

Suppose  $f$ is uniformly continuous in $[0,\infty)$.

Then for any $\varepsilon>0$, there is $N\in\mathbb{N}$ for which
$$\begin{align}
\frac{1}{h(n)}|A_n|\leq \frac{1}{h(n)}\sum^{n}_{k=1}\int^{\tfrac{k}{n}h(n)}_{\tfrac{k-1}{n}h(n)}\Big|f(x)-f\big(\tfrac{k}{n}h(n)\big)\Big|\,dx\leq \varepsilon
\end{align}$$
for $n\geq N$. That is
$$\begin{align}
\frac{1}{h(n)}|A_n|\xrightarrow{n\rightarrow\infty}0\tag{0}\label{zero}
\end{align}$$
Notice that
$$\begin{align}
C_n:=\frac{1}{n}\sum^n_{k=1}f\big(\frac{k}{n}h(n)\big)
=\frac{1}{h(n)}\Big(\int^{h(n)}_0 f(x)\,dx -A_n\Big)\tag{1}\label{one}\end{align}$$
3. Let $F:x\mapsto \int^x_0 f(t)\,dt$, $x\geq0$. If  $F$ is bounded, then from \eqref{zero} and \eqref{one}
$$C_n\xrightarrow{n\rightarrow\infty}0$$
4. If $f(x)\xrightarrow{x\rightarrow\infty}b$, then from \eqref{zero} and \eqref{one}
$$C_n\xrightarrow{n\rightarrow\infty}b$$

Conditions 1-3 are satisfied for the function $f(x)=\cos(a\pi x)$ and sequence $h(n)=\log n$. Thus,
$$\frac1n\sum^n_{k=1}\cos(a\pi\tfrac{k}{n}\log n)\xrightarrow{n\rightarrow\infty}0$$
Comment: In 1, you like to write "Riemann sum of the integral $\int_0^{h(n)}f dx$".


f in L^1 implies lim f(x+n) = 0 for a.e. x

Question: Let $f \in L^1(\mathbb{R})$. Prove that for almost every $x \in [0,1]$, the sequence $\{f(x+n)\}_{n=1}^{\infty}$ converges to $0$.
I am trying to use the fact that $f(x+n)= \frac{d}{dx}\int_{a}^{x+n} f(y) \ dy$. But how do I justify the exchange of limit and derivative on the RHS ?
Can anyone provide a useful hint ?
Answer: Hint:
$$ \int_{[0,1)} (\sum_{n=0}^{\infty}|f(x+n)|)\ dx =  \sum_{n=0}^{\infty} \int_{[0,1)} |f(x+n)|\ dx = \sum_{n=0}^{\infty} \int_{[n,n+1)} |f(x)|\ dx = \int_0^\infty |f| <\infty.$$
Comment: I am able to prove that for almost all $z \in [x,x+1]$ the above result that $f(z+n) \rightarrow 0$ is true where $x$ can be arbitrarily small. Is that correct ?


How can I acquire a better sense of rhythm?

Question: I dance and my main problem is timing and what is called by dancers musicality, which means matching the steps to the music, essentially the praxis of rhythm.
I was never musical as child and I do not ordinarily listen to music, so I have a lot of difficulty detecting the beat in music, especially if it is melodic or there are changes in phrasing.
I have watched a lot of YouTube videos that purport to teach how to recognize the beat in a piece of music, but I have not found them to be useful. Half of them are by music teachers who have obviously had a musical life and been doing it since they were little children and there they are advising me to just "feel" it. Well, easy for them to say, when they have been playing and listening to music since they were in diapers. Other videos recommend gimmicks like "just listen to the snare drum" or things like that, which really don't have general application, and even if I hear a snare drum, that doesn't mean my feet are hitting the ground when the snare drum plays. Just because I hear the beat, doesn't mean I automatically step on it.
One thing I have done is use a metronome, so when I practice I know if I am late or early because when the metronome rings the end of the measure, if I am not on the end of the step, then I know how far I am off. That is useful, but only goes so far and a metronome is not music. I am hoping to know in a more thoroughgoing way what exercise, drill or other thing I can do to improve my musicality in a concrete and reliable way without gimmicks.
Note that correct timing is not just stepping on the beat, but specifically making the first step of a figure on the first beat of the phrase which is generally 8 beats of 2 measures. So, the problem is not just keeping time (which is hard enough) but also recognizing the one and PREDICTING it, because you have to know ahead of time when the one is coming in order to hit it.
Comment: Please clarify: do you find it equally difficult to just clap to the beat?
Comment: Does this answer your question? [Problems with Natural sense of rhythm. Ways to improve it](https://music.stackexchange.com/questions/51116/problems-with-natural-sense-of-rhythm-ways-to-improve-it). And numerous others.
Comment: I have this strong feeling that "musicality" is a lot more than "being on the beat". I am not a specialist in any sense of the word, but not from another planet either.
Comment: This hasn't yet acquired any close-votes, but to head them off at the pass, you might want to remove the mention of dance from the title. Your goal is to acquire a kinesthetic sense of musical pulse, which is on-topic here; the fact that you want to use it for dancing is secondary. You might want to look into the tradition of "[eurhythmics](https://en.wikipedia.org/wiki/Dalcroze_eurhythmics)."
Comment: @Theodore The subject here is competitive ballroom dance also called "dancesport". You lose if your timing is off, it's the #1 criteria that the judges look for.
Comment: Not sure we can answer questions about dancing here. To me musicality in music is putting expression into every note, as opposed to just playing the right note at the right time at the right volume. In fact, I might say musicality in music is also knowing how and when to play a note differently from how it's written. The intention of the written score and the literal written score are almost always different. You have to understand the intention and not just follow the score like a computer.
Comment: @ToddWilcox: very interesting POV. Extending your explanation, does it also include the choice of the instrument? I am not talking about replacing the violin with a (e.g.) saxophone, but choosing between different essences of wood, for example (if we refer to wooden instruments). A violin might sound different if made from poplar or if made from oak. (trees chosen randomly) Some people prefer lamps-based amplifiers to silicone amplifiers simply because of the specific distortion.
Comment: @virolino No, I don't think of "musicality" in the performance sense being related to choice of instrument because by the time one is actually performing, the instrument is fixed. I'm talking about shaping long notes, playing non-slurred notes in fast passages very crisply like staccato, adding dynamics to the phrasing, etc. Also I think instead of "lamps" you meant to say "tubes" or "valves" and instead of "silicone" you meant "solid state". As in "tube amps versus solid state amps". Also, *silicone* is a polymer used to make gels and lubricants; *silicon* is a metal used to make electronics.
Comment: I don't mean to be unkind, but if you aren't really interested in music, why dance to music?  Let your movements happen at their own natural pace.  Some people may say it's not dance, or that it's gymnastics, but why not?
Comment: The *Rhythm Heaven* games [purportedly](https://www.youtube.com/watch?v=c7lyjfI7WGg) teach rhythm, but I have no idea if anyone has studied them for effectiveness. At the very least, they do provide feedback and an objective measurement of progress.
Answer: Good news: This is a learned skill, not just some kind of "talent" that one is supposed to have from birth (even if it's often learned at an early age), so it's something you can work on. The short answer is you should "scaffold" it by starting easy and working up.
The fundamental issue here is about feeling the musical phenomenon that is best called "pulse"; a more common term might be "the beat," but that gets confusing in music-theory ways. The idea is that a certain point in the music is emphasized, or carries a sense of weight, and that such points recur regularly and predictably. This is "the beat" that we subdivide into rhythms. We should note that not all music is "pulsed". Most is, and has been across history and many music-cultures, but some music can be unpulsed. And some music can prefer a "weak" pulse, that is not strongly emphasized, or to be flexible with it (aka "rubato"), stretching or compressing the period between pulses expressively. Other music might change the pulse often (changes in tempo), or have a complex meter that combines pulses of different lengths.
My advice is to avoid these at first: start with something "strongly pulsed," with a straightforward meter. There's a reason that the notion of "danceability" is correlated with "strongly pulsed." A lot of funk or disco can work well here: tracks with strong, thumpy, straightforward four-on-the-floor bass lines.
When I work on this with students, I often play this track in which RJD2 remixes Astrud Gilberto:

The opening 14 seconds or so are unpulsed, but then a bass-range piano part comes stomping in, and starts strongly marking every downbeat. This is maybe not the simplest track to choose, because the snare drum also provides a strong "backbeat"; that is, if the low piano notes are beat 1, then the snare plays on the so-called weak beats 2 and 4. The bass drum also complicates things a bit. But overall, with the help of those left-hand piano downbeats, the pulse is marked so strongly that it's easy to move in time with it. I encourage students simply to bend their knees with the pulse.
Continue with this kind of exercise, simply locating "the beat" in strongly pulsed music. "Stay alive" with the Bee Gees, maybe. Dance with the "Dancing Queen." Walk through the "Gangsta's Paradise." March along with John Philip Sousa. Just keep bobbing in place, bending your knees. Try replaying a small handful of tracks often; the ability to predict the familiar is easier than the ability to pick up and react to something new.
Once this ability becomes so secure that it's boring, you can move on to examples that are more subtle about their pulse, not thumping it out on every beat. You can try another meter, like a waltz, so that the pulses come in sets of 3 instead of 4:

Then you might try tracks that change tempo, and try to follow along. Grieg's "In the Hall of the Mountain King" speeds up as it goes:

For the ultimate challenge, try the sort of pieces that manipulate the pulse so much that it approaches being unpulsed; try some Chopin piano pieces (famous for extreme "rubato," or pushing/pulling the pulse) or Impressionists like Debussy or Ravel. A piece like the Debussy violin sonata might present the ultimate challenge, with the tempo constantly in flux; I've told students before that no two consecutive beats should be the same length.

That piece not only manipulates, but also de-emphasizes the pulse, "smoothing it over" with ties and blurring its impact. A choreography of it might be equally fluid and expressive.

Edit after question was edited: Looks like the issue is not just finding beats, but finding phrase lengths. It gets a little confusing, since dancers often count the total number of beats in a phrase, while musicians describe it as a number of measures (there's a reason dancers often count off "five, six, seven, eight" while musicians say "an' a one an' a two an' a one two three four"). For being aware of phrase lengths, it might actually help to do some study of music theory, enough to know a "cadence" when you hear it, and especially the part that deals with deciding just how long phrases are. This is no small undertaking; we're talking about a semester or two of an average theory course, but it would be well worthwhile.
Meanwhile, the advice is the same: start simple. Stick to songs that do have simple phrases, in sets of four bars, and avoid things that throw in an extra bar or two now and then (like Simon and Garfunkel's "Scarborough Fair"). And work with the same tracks over and over so you get to know their ins and outs.
Comment: Wilcox does not understand the term. In dancing musicality refers specifically to stepping correctly on the beat and keeping time. At high levels of dance there are issues like arm styling in its relation to the music and things like that, but they are irrelevant to my questions.
Comment: @ToddWilcox Heh, I'm trying to answer this question here rather than [that one](https://music.stackexchange.com/q/129068/78419). Tyler seems clearly to be looking for help strengthening a sense of pulse, the ability to track and predict it. Questions of how to be sensitive to expressive "musicality" when choreographing would have to come second to that skill!
Comment: @ToddWilcox Although this question is narrowly focused on the timing aspect, I think you're correct that in *dancesport* (which OP indicated in a comment this question concerns) [musicality is about more than timing](https://www.dancecompreview.com/4-key-points-musicality-dancesport/).
Answer: To me it sounds like mastering these two skills would help you:

developing a/improving the sense of time
after that extend this sense to feet, limbs, body.

Please let me know via a comment, if this would help you, and I'll add more practical things.


The ends of the longest open path in a simple connected graph can be edges of the graph

Question: I am struggling with how to approach this problem, specifically part a. What is the relationship between the length l of the longest open path and the sum of the degrees of any two non-adjacent vertices, and how does that help solve the problem?
$G$ is a simple connected graph with 20 vertices. Assume that for any two non-adjacent vertices $x$ and $y$ we have $deg(x) + deg(y)\geq 12.$
a) Let $x_1-x_2-...-x_l$ be the longest open path in $G$ (recall    that in a path we have distinct vertices and distinct edges). If $l < 20$ then could ${x_1, x_l}$ be an edge of $G$? Prove your assertion.
b) Prove that $G$ has a cycle of length at least 7.
Answer: For part a) you can present a case where the longest open path is less than $20$ and does not make a circuit and make an argument that such a longest path not containing all vertices cannot be connected into a circuit.
The first case is relatively easy; have a $K_{12}$ component and then have one of the vertices connect individual edges to the other $8$ vertices not in the $K_{12}$. The longest path is $13$ and cannot be connected.

Now consider for the sake of contradiction a longest path $<20$ length which can be formed into a circuit. Then there are vertices not on the circuit, and because the graph is connected, there must be some such vertex $v$ adjacent to some point on the circuit. Then a longer path can be made by starting at $v$ and then following the circuit - contradiction. Therefore if the longest path does not include all nodes, it cannot be connected into a circuit.
Comment: That makes sense! Thank you. For part b, isn't it essentially asking whether $x_1, x_7$ could be an edge of G? It seems like it's asking for a proof of the same thing that was just disproven for part a.
Comment: No, there's no sense in which the cycle of 7 must be the longest path so not the same. For that one I would expect the condition on vertex degree sum to be important.
Comment: Certainly it is possible, for part (b), to construct a graph meeting the conditions where the maximum cycle is $7$ by connecting a $K_7, K_6, K_6$ suitably through a cut vertex.


Increasing the size of a PersistentVolumeClaim on GKE

Question: I've heard that in later versions of Kubernetes (1.9 onwards if I'm not mistaken; I have 1.10), it's possible to expand a PersistentVolume as long as allowVolumeExpansion: true is set in the StorageClass configuration.
In my case, on GCP, the StorageClass my PVC uses does not have that line, and I cannot add it either.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    storageclass.beta.kubernetes.io/is-default-class: "true"
  creationTimestamp: 2018-05-30T17:07:33Z
  labels:
    addonmanager.kubernetes.io/mode: EnsureExists
    kubernetes.io/cluster-service: "true"
  name: standard
  resourceVersion: "8741704"
  selfLink: /apis/storage.k8s.io/v1/storageclasses/standard
  uid: f1bd0421-642b-11e8-bb11-42010a9a00b5
parameters:
  type: pd-standard
provisioner: kubernetes.io/gce-pd
reclaimPolicy: Delete
volumeBindingMode: Immediate

So, I want to increase a PV, and its corresponding PVC from 8Gi to 100Gi. What's the best way of doing this? Is there a way to do it while preserving data, or must the current PV be deleted before making a new one?
Here's the PV YAML:
apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    kubernetes.io/createdby: gce-pd-dynamic-provisioner
    pv.kubernetes.io/bound-by-controller: "yes"
    pv.kubernetes.io/provisioned-by: kubernetes.io/gce-pd
  creationTimestamp: 2018-05-31T10:30:39Z
  finalizers:
  - kubernetes.io/pv-protection
  labels:
    failure-domain.beta.kubernetes.io/region: europe-west2
    failure-domain.beta.kubernetes.io/zone: europe-west2-c
  name: pvc-a70ca000-64bd-11e8-bb11-42010a9a00b5
  resourceVersion: "8728415"
  selfLink: /api/v1/persistentvolumes/pvc-a70ca000-64bd-11e8-bb11-42010a9a00b5
  uid: a9e8c071-64bd-11e8-bb11-42010a9a00b5
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 8Gi
  claimRef:
    apiVersion: v1
    kind: PersistentVolumeClaim
    name: production-postgres
    namespace: neserver-6540663
    resourceVersion: "85487"
    uid: a70ca000-64bd-11e8-bb11-42010a9a00b5
  gcePersistentDisk:
    fsType: ext4
    pdName: gke-cluster-1-320626e3-pvc-a70ca000-64bd-11e8-bb11-42010a9a00b5
  persistentVolumeReclaimPolicy: Delete
  storageClassName: standard
status:
  phase: Bound

Answer: Unfortunately, this feature is not yet supported in GKE. You can open a Feature Request to have this feature enabled in future versions of GKE using the Public Issue Tracker
Comment: Ironically, it seems I cannot create an issue on the issue tracker (button is greyed out). Does this mean I'm stuck with an 8Gi database until they fix this? Might just move to a regular monolithic server where I can actually control things.
Comment: You should be able to create a new feature request as per [this doc](https://developers.google.com/issue-tracker/guides/access-ui)
Comment: Otherwise, yes, the disk size can't be changed. But you can create a new PVC with a new disk and transfer your data from the old one to the new one and delete the old one. This is more work but it will provide you a larger disk without losing data or paying for additional disks
Comment: Yeah, this is the only other option I can conceive, but it brings another question: how do I copy the data to the new disk?
Comment: the PVC creates a persistent disk. You can attach that PD to another instance to copy data over. You can do the same thing with the new PVC, the disk can be created before you actually mount it to a pod


Combine 2 fields in one div with Twig

Question: I have three templates

field--field-custom.html.twig
field--field-custom1.html.twig
field--field-image.html.twig

I also have a teaser template containing all three fields like that:

    {{ content }}

I want to have the first two templates in a bootstrap div, for example
col-sm-6

and the third template in the other div
col-sm-6

If I include the second template in the first template file it just repeats the field instead of rendering the intended field (both templates are name suggestions of the same file).
What can I do in order to have both fields in the same template file?
Answer: Just chunk the output by using the field names:

{{ content.field_custom }} {{ content.field_custom1 }}

Then do the same for the remaining field.
Comment: Awesome! Thank you Kevin. I did it in the node--teaser-*  template and just realized, I don't need the field---field-* templates anymore. The first time I tried with the template names, but it refers to the field machine name.
Answer:

    {{ content.field_imagen }}

    {{ content.field_resumen }}
    {{ content.field_leer_mas }}

Thanks to Kevin!

Combine 2 fields in one div with Twig


calculate R² as a function of μ,σ

Question: Suppose I fit the sum of $t$ iid random variables
$$y_t=\sum_{i=1}^t{x_i} \space \space \space\space\space x_i \text{ i.i.d} \sim N[\mu,\sigma]$$
to a linear regression model
$$f_t=a\space t +b$$
then I calculate the coefficient of determination $R^2$
$$R^2=RSQ([y_1..y_n],\space [f_1..f_n])$$
I expect that on average $R^2$ will depend on $\mu$ and $\sigma$:
$$E[R^2]=f(μ,σ)$$
does such a relationship exist? What is the function $f()$?
Comment: Hi: There's no analytic relationship between your model for $y_{t}$ and your model for $f_{t}$ because $y_{t}$ is difference stationary and $f_t$ is trend stationary. These are two different types of non-stationarity in time series and I think that you're mistake is that you're comparing them.
Comment: $R^2$ is not a useful statistic in this context for many reasons, not least of which is because the regression is invalid: it relies on assuming the responses $y_i$ are independent but they are (by construction) very strongly correlated.
Comment: Dispersion is going to depend on the timescale you look at. The longer the interval, the bigger the possible random walks from the straight line. If you do a PCA of random walk in one dimension it decomposes into a series of eigenvectors whose features differ in freqency of features.
Comment: Renet and Whuber sound like they know more about this but the "true" $R^2$ between your random walk and the straight line is probably zero. One way to test this is  to run thousands of simulatons so that you get thousands of realizations between the straight line and the random walk. Then calculate the average $R^2$ of all of them. I'm pretty sure it will be close to zero. There is a possibility of spurious correlation ( see Granger and Newbold for that ) but, if you simulate enough times, I would think you'd wash that effect away.
Comment: @mlofton thank you. I appreciate it might be inappropriate, but I thought I could use $R^2$ to measure the "average dispersion" of the random walk of $y_t$ compared the "ideal trajectory", that is a straight line from $y_0=0$ to $y_t=\mu t$. So I supposed there is a relationship between $R^2$ and $\mu$, $\sigma$.
Comment: @ReneBt: Could you explain what you mean by a series of eigenvectors whose features differ in frequency of features. Or, maybe an example if possible ? Thanks.
Comment: THere is a discussion here with external links that show what I refer to https://stats.stackexchange.com/questions/330857/principal-components-of-random-walk/367685#367685
Comment: @everyone thanks for your feedbacks. The concept of $R^2$ does not make sense in the context of a random walk, but for the records... I simulated it and there is a numerical relationship $E[R^2] = f(\frac{\mu}{\sigma})$ which looks like this: https://i.imgur.com/0fLVYEW.png  - intuitively when $\mu \gg \sigma$ the random walks look more like a straight line so $E[R^2] \approx 1$ and viceversa.
Answer: What defines $R^2$ in a random walk
As indicated in the comments the process you describe is not appropriate for $R^2$. I have done a simulation (code at bottom) of a random walk using a normal distribution in a linear model - you can tweak the various settings to see what impact they have. We will examine the behaviour now.
Here's what 1000 random walks over 5000 intervals for normally distributed changes with a mean interval change of 1 and a standard deviation of 1. To tweak these simply adjust 'mu' and 'sd' in the code.

This looks intuitively like you suggestion would work - the lines show upward trends that could be fitted with a linear model. The variation between samples (dispersion) for each interval varies against interval as follows:

You can see that the variance between interval rises with the number of intervals, which is the central concern underpinning the initial comments to the question. The actual variance is dependent on the interval you look at, so you can get what every answer you want by adjusting your interval range. What about $R^2$ itself? We look at the individual samples and the mean across the samples:
$R^2$ for individual trends">
The variation in $R^2$ is dependent on time interval range
$R^2$ across samples">
The mean $R^2$ is very dependent on time interval range
So all in all $R^2$ is very dependent on the time range used, so is hugely biased by the interval you choose. This means it cannot be recommended.
For completeness, I show the PCA eigenvectors from the series since I alluded to this in my comment. It shows that the variance in the dataset is composed of changes of different frequency.

So why does this happen?
The key is that the underlying data generating process consistently averages adding the mean step, so over long runs the variance due to accumulated mean steps will eventually overpower the variance in the individual steps and tend towards 1 (except for 0 mean). The rate at which this happens will depend on the relative size of the mean and the standard deviation of the underlying process.
Simulation Code
Here's python code should you wish to play around
from sklearn.decomposition import PCA
    import numpy as np
    import matplotlib.pyplot as plt
    import scipy
<code># SETUP simulation parameters
N_intervals =  5000 # can restrict range to see how interval sample range affects behaviour
N_samples = 1000
N_PCs = 5
fig_num = 0
mu = 1
sd = 1
np.random.seed(8736)

sim_data = np.empty((N_samples,N_intervals))
# starts the samples at zero, to start at random positions
sim_data[:,0] = np.zeros((N_samples))

# simulate time dependent random walk - you can replace the step change with
# any distribution or stochastic process you want. The -0.5 gives a mean change of 0
for i in range(1,N_intervals):
    sim_data[:,i] = sim_data[:,i-1] + np.random.normal( mu , sd , (N_samples) )

# plot how the data varies against time for each run
fig_num =+ 1
plt.figure(fig_num)
plt.plot(sim_data.T)
plt.xlabel('Time Increment')
plt.ylabel('Value')
title = str( N_samples ) + ' simulated random time walks'
plt.title(title)
plt.figure(fig_num).savefig( title + '.png')

# plot dispersion against interval
sim_data_sd = np.std(sim_data,axis=0)
fig_num += 1
plt.figure(fig_num)
plt.plot(sim_data_sd)
plt.xlabel('Time Increment')
plt.ylabel('SD')
title = ( 'Standard Devation between ' + str( N_samples ) +
         ' simulated random time walks vs time interval' )
plt.title(title)
plt.figure(fig_num).savefig( title + '.png')

# plot R2 against interval
ranges = (10**np.arange(np.log10(50),np.log10(5001),0.25)).astype('int')
r = np.empty((N_samples,np.shape(ranges)[0]))
for iSam in range(N_samples):
    for iInt in range(ranges.shape[0]):
        a , b , r[iSam,iInt], p , se = (
            scipy.stats.linregress(np.arange(ranges[iInt]), sim_data[iSam,:ranges[iInt]]) )
        #currently not storing slope a or intercept b as only looking at R
fig_num += 1
plt.figure(fig_num)
plt.plot(ranges, r.T**2,'.') # this is one version of R2
plt.xlabel('Time Increment')
plt.ylabel('$R^2$')
title = ( 'Individal R2 for ' + str( N_samples ) +
         ' simulated random time walks vs interval' )
plt.title(title)
plt.figure(fig_num).savefig( title + '.png')

fig_num += 1
plt.figure(fig_num)
plt.plot(ranges, np.mean(r.T**2,axis=1),'.') # this is one version of R2
plt.xlabel('Time Increment')
plt.ylabel('$R^2$')
title = ( 'mean R2 for ' + str( N_samples ) +
         ' simulated random time walks vs interval' )
plt.title(title)
plt.figure(fig_num).savefig( title + '.png')

# Here's the PCA eigenvectors
random_walk_PCA = PCA( n_components=N_PCs )  # fit a PCA to the simulated data
random_walk_PCA.fit(sim_data)
fig_num = fig_num+1
plt.figure(fig_num)
plt.plot(random_walk_PCA.components_.T + np.arange(0,-0.05*N_PCs,-0.05))
plt.xlabel('Time Increment')
plt.ylabel('Weighting')
title = 'PCA eigenvectors  from ' + str( N_samples ) + ' random walks'
plt.title(title)
plt.figure(fig_num).savefig( title + '.png' )
</code>

calculate R² as a function of μ,σ


Typescript Class or Interface to represent a json HttpClient.get response

Question: In Angular2 when I call httpClient.get() on some api, it always returns the same json object structure, which may have some nested attributes, i.e.:
<code>{
   attr1: 123,
   attr2: "xyz",
   attr3: [{v1: 1, v2: 2}, {v1: 3, v2: 4}]
}
</code>
I would like to create a class or an interface in typescript to enforce this representation, like httpClient.get< MyObject >()
This "MyObject" should have two characteristics:
1) it should be easily defined directly using something like:
<code>{attr1: number, attr2: string, attr3: Array<{v1: number, v2: number}>}
</code>
meaning without using constructors, declaring class properties, and verbose code
2) it should be able to contain some methods, like:
<code>is_greater_than_onehunded() {
  return this.attr1 > 100;
}
</code>
Is there a straightforward way to "model" a json structure in ts?
Answer: <code>    export class YourType{
    {
    attr1: number;
    attr2: string;
    attr3: Array<{v1: number, v2: number}>
    is_greater_than_onehunded() {
           return this.attr1 > 100;
        }
    }
</code>
And there you go