Session_destroy() retorna erro

Question: Estou fazendo uma página, e em partes, uso PHP, mas em uma parte dá um erro no log out.
Segue o erro:

Warning: session_destroy(): Trying to destroy uninitialized session on line 22.

Segue a linha:
if ((!$loginrequired) or ((isset($_SESSION) or !isset($_SESSION) and session_start())
    and (isset($_SESSION['lname']) and isset($_SESSION['lpass']))
    and isValidLogin($_SESSION['lname'], $_SESSION['lpass']))) {

    header("location:/questions/home");
} else {
    unset($_SESSION['lpass']);
    unset($_SESSION['lname']);
    if (isset($_SESSION)) {
        session_destroy();
    }
}

Achei estranho o erro aparecer, se fiz a checagem.
Alguem sabe o que pode ser?
Comment: O `session_start` deve ser a primeira coisa a ser iniciado em seu script, antes de qualquer echo ou saída. O que ele está fazendo dentro do `if` ?
Answer: Usa assim:
session_start();
if (isset($_SESSION)) {
    session_destroy();
}

Comment: Mas isso causaria outro problema, iniciar uma sessão ja iniciada. Editei ali em cima, botei a bloco inteiro.
Comment: o que eu encontrei ate agora você precisa iniciar a session na pagina para depois dar um destroi. Voc~E chegou a testar ao menos ?
Comment: Não testei, você chegou a ver o bloco? em:
if ((!$loginrequired) or ((isset($_SESSION) or !isset($_SESSION) and session_start()) and (isset($_SESSION['lname']) and isset($_SESSION['lpass'])) and isValidLogin($_SESSION['lname'], $_SESSION['lpass'])))

Eu vejo se foi iniciado, se não, inicia a session.
Comment: não cheguei a testar o session_start no if mas pelo que vejo com o pessoal todo aqui usamos da forma inicia e destroi coisas assim direto
Comment: Usei o que você mandou, e como eu disse, deu erro:  A session had already been started - ignoring session_start()
Comment: só que ele precisa estar no topo da pagina senão o session_start da esse erro mesmo
Comment: Não faz sentido, do mesmo modo vai dar o erro
Comment: beleza então muita gente esta tendo problema. pois é a solução que funciona. http://www.portugal-a-programar.pt/topic/58548-session-destroy-nao-destroi/
Comment: ou se quiser usar a propria resposta so stack http://stackoverflow.com/questions/5752858/warning-session-destroy acho que fica mais facil
Comment: Continua a mesma coisa. Ja botei o session_start() e da o erro acima.

Session_destroy() retorna erro


Convergence domain of $\sum_\limits{n=1}^{\infty}(-1)^{n+1}\frac{1}{n^x}$?

Question:
Exercise: Determine the convergence domain if the following series $$\sum_\limits{n=1}^{\infty}(-1)^{n+1}\frac{1}{n^x}$$.
Solution: If $x>1$ the series converge absolutely, if $0<x\leqslant 1$ the series converge but not absolutely, if $x\leqslant 0$ the series diverge.

OP attempted resolution:
I tried to solve it in the following way:
By the comparison(Weierstrass test) test:$\sum_\limits{n=1}^{\infty}|(-1)^{n+1}\frac{1}{n^x}|\leqslant\sum_\limits{n=1}^{\infty}|1\frac{1}{n^x}|=\sum_\limits{n=1}^{\infty}|\frac{1}{n^x}|$.
Now applying the integral test:
$\int_\limits{1}^{\infty}|\frac{1}{n^x}|=\int_\limits{1}^{\infty} \frac{1}{n^x}<\infty$ if $x<1$, which explains the first part of the solution.
However I cannot understand the second part of the solution "$0<x\leqslant 1$ the series converge but not absolutely" either why the series diverge when $x<0$, thought they diverged if $x\leqslant 1$.
Questions:
1) What am I doing wrong? How do I prove "$0<x\leqslant 1$ the series converge but not absolutely"? What does it mean?
2) According to solution "$x\leqslant 0$ the series diverge". Is not when $x\leqslant 1$?
Thanks in advance!
Comment: The Dirichlet eta function (which is essentially the same function presented here), converges absolutely on $Re(x) > 1$. It turns out it still converges on $0 \lt x \le 1$, but only conditionally, meaning that in that small strip its counterpart $\sum_{n=1}^\infty \frac{1}{n^x}$ (the Riemann zeta function) diverges. Under conditional convergence, an expression, after rearranging of terms, can converge to an arbitrarily large number or even diverge.
Answer: For $0< x \le 1$ the series converges by Alternating series test and diverges absolutely by comparison test with $\sum \frac1 n$.
For $x\le 0$ it diverges since $\lim_{n\to \infty} |a_n|\neq 0$.


Extracting audio data every t seconds

Question: I am trying to extract amplitude information from a sound loaded from a URL using the Web Audio API instantaneously (not in real time), which will likely require the OfflineAudioContext. I am expecting to obtain something along the lines of an array containing the amplitude of the sound every t seconds for the duration of the sound (with size depending on the duration of the sound, divided by t). Unfortunately, documentation is sparse at this point, and I'm unsure of how to proceed. How can I load the sound and extract the amplitude every t seconds?
Answer: This was done very quickly, so the math might be messed up. But hopefully it'll get you started...
var ac = new webkitAudioContext(),
  url = 'path/to/audio.mp3';

function fetchAudio( url, callback ) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.onload = function() {
    callback(xhr.response);
  };
  xhr.send();
}

function decode( arrayBuffer, callback ) {
  ac.decodeAudioData(arrayBuffer, function( audioBuffer ) {
    callback(audioBuffer);
  });
}

// return an array of amplitudes for the supplied `audioBuffer`
//
// each item in the array will represent the average amplitude (in dB)
// for a chunk of audio `t` seconds long
function slice( audioBuffer, t ) {
  var channels = audioBuffer.numberOfChannels,
    sampleRate = ac.sampleRate,
    len = audioBuffer.length,
    samples = sampleRate * t,
    output = [],
    amplitude,
    values,
    i = 0,
    j, k;
  // loop by chunks of `t` seconds
  for ( ; i < len; i += samples ) {
    values = [];
    // loop through each sample in the chunk
    for ( j = 0; j < samples && j + i < len; ++j ) {
      amplitude = 0;
      // sum the samples across all channels
      for ( k = 0; k < channels; ++k ) {
        amplitude += audioBuffer.getChannelData(k)[i + j];
      }
      values.push(amplitude);
    }
    output.push(dB(values));
  }
  return output;
}

// calculate the average amplitude (in dB) for an array of samples
function dB( buffer ) {
  var len = buffer.length,
    total = 0,
    i = 0,
    rms,
    db;
  while ( i < len ) {
    total += ( buffer[i] * buffer[i++] );
  }
  rms = Math.sqrt( total / len );
  db = 20 * ( Math.log(rms) / Math.LN10 );
  return db;
}

// fetch the audio, decode it, and log an array of average
// amplitudes for each 5-second chunk
fetchAudio(url, function( arrayBuffer ) {
  decode(arrayBuffer, function( audioBuffer ) {
    console.log(slice(audioBuffer, 5));
  });
});

Basically, if you want to get data for an entire buffer faster than realtime, you really don't even need an OfflineAudioContext. You can just read the samples, do some math, and figure it out.
This is pretty slow, though. Especially for larger audio files. So you might want to put it in a Web Worker.
It's possible that using an OfflineAudioContext would be faster. I'm really not sure. But even if you decide to go down that route, there's still a lot of manual work you'd need to do in order to get the amplitude of these arbitrary chunks of t seconds.
Comment: This is a great approach.  Using an OfflineAudioContext is highly unlikely to be faster - it's not really designed to do this task.
Comment: +1, by the way, to the idea of putting this processing into a web worker.  However, that will be a little bit challenging, as you need to move the AudioBuffer's channel data content across the thread boundary.  Doing that efficiently with transferables takes a bit of work.

Extracting audio data every t seconds


Visual Studio .natvis file, array of class visualization

Question: I have classes that basically look like the following and I would like to make then more readable in Visual Debugger:
template <typename T, precision P = defaultp>
struct tvec4
{
    T x, y, z, w;
};

template <typename T, precision P = defaultp>
struct tmat4x4
{
    typedef tvec4<T, P> col_type;

private:
    col_type value[4];
};

Here is what the natvis file looks like for the vector:
<Type Name="glm::tvec4<*>">
    <DisplayString>{x}, {y}, {z}, {w}</DisplayString>
    <Expand>
        <Item Name="x">x</Item>
        <Item Name="y">y</Item>
        <Item Name="z">z</Item>
        <Item Name="w">w</Item>
    </Expand>
</Type>

Which work fine. However, for the matrix class, I can't manage to get anything to work.
Try1:
<Type Name="glm::tmat4<*>">
    <DisplayString>{{value[0]}, {value[1]}, {value[2]}, {value[3]}}</DisplayString>
    <Expand>
        <Item Name="[0]">value[0]</Item>
        <Item Name="[1]">value[1]</Item>
        <Item Name="[2]">value[2]</Item>
        <Item Name="[3]">value[3]</Item>
    </Expand>
</Type>

Try2:
<Type Name="glm::tmat4<*>">
    <DisplayString>{size = {4 x 4}}</DisplayString>
    <Expand>
        <Item Name="[size]">4</Item>
        <Item Name="[capacity]">4</Item>
        <ArrayItems>
            <Size>4</Size>
            <ValuePointer>value</ValuePointer>
        </ArrayItems>
    </Expand>
</Type>

Any idea what am I doing wrong?
Thanks!
Christophe
Answer: You should try switching the diagnostics on. It is explained here:
https://code.msdn.microsoft.com/Writing-type-visualizers-2eae77a2
Create the registry key below:
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Debugger]
   "EnableNatvisDiagnostics"=dword:00000001

Answer: This is an old question so I'm assuming you have a solution by now but just in case anyone else has a similar problem it is down to your use of curly braces in the description:
<DisplayString>{{value[0]}, {value[1]}, {value[2]}, {value[3]}}</DisplayString>

A single brace {} indicates that the contents should be interpreted by the debugger but if you actually want the brace as part of the description then you need to use double braces:
{{Text here {variable_name_here}}}

So in your case that would make the correct display string:
<DisplayString>{{{value[0]}, {value[1]}, {value[2]}, {value[3]}}}</DisplayString>


Jack bikes to work to shorten the commute

Question:
The time it takes for Jack to go to work distributes by normal distribution with $\mu=25$ minutes and $\sigma=8$. Jack needs to make it to work in time with probability of $97.5\%$. He wants to buy a bike that will shorter the variance of getting to work to $25$ minutes. What is the expected value of getting to work by bike for which the time until arrival will be reduced by half?

So I maybe got a little confused with all the details, but what I understood:
I tried to give a standard score to the original details. I took the $Z$ score of $97.5$% out of the $Z$ table and got $1.96$. Now, with the standard score formula I got: $(x-25)/8 = 1.96$ which game me $x=40.68$. Now I wondering, the right solution is to calculate it again, but this time with $σ=5$ and $x=40.68$? I get $30.88$. I this the right way?
Answer: You might get a bit off-tracked but the grammar of the last sentence sucks. Given that $\mu_{\text{old}} = 25, \sigma_{\text{old}} = 8$ and $\sigma_{\text{new}} = 5$ as you figured out, you need to find the $x_{\text{new}}$ so that $P((x_{\text{new}} - \mu_{new})/\sigma_{\text{new}}) = 0.975$.
Now you found $x_{\text{old}} = 40.68$. I believe the last sentence asked you to half this value to become $x_{\text{new}}$, which is $20.34$ in fact. So now you can calculate the $\mu_{\text{new}}$ the question wants given $(20.34 - \mu_{new})/5 = 1.96$.


(NoReverseMatch at / Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['/']). please help me to remove this error

Question: It is a multiple image program in which we can add multiple image at one time to see grouped photos. Error during template rendering
In template C:\Users\a\dev\mysite\templates\base.html, error at line 15
I am able to open my admin panel but i am not able to  my files. thus please help me to find error:
models.py
    from django.db import models
class Post(models.Model):
    title           = models.CharField(max_length=120)
    description     = models.TextField()
    image           = models.ImageField(upload_to='products/', null=True, blank=True)
    def __str__(self):
        return self.title
class PostImage(models.Model):
    post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='images/')
    def __str__(self):
        return self.post.title

views.py
    from django.shortcuts import render, get_object_or_404
from .models import Post, PostImage
def blog_view(request):
    posts = Post.objects.all()
    return render(request, 'blog.html', {'posts':posts})
def detail_view(request, id):
    post = get_object_or_404(Post, id=id)
    photos = PostImage.objects.filter(post=post)
    return render(request, 'detail.html', {
        'post':post,
        'photos':photos,
    })

admin.py
    from django.contrib import admin
from .models import Post, PostImage
class PostImageAdmin(admin.StackedInline):
    model=PostImage
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    inlines = [PostImageAdmin]
    class Meta:
        model=Post
@admin.register(PostImage)
class PostImageAdmin(admin.ModelAdmin):
    pass

base.html
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous">
    <title>Multi Image Tutorial</title>

        {% block content %}
        {% endblock %}

blog.html
    {% extends 'base.html' %}
{% block content %}

    {% for post in posts %}

{{post.title}}

{{post.description}}

                Read More

    {% endfor %}

{% endblock %}

detail.html
    {% extends 'base.html' %}
{% block content %}

    {% for p in photos %}

    {% endfor %}

    {% for p in photos %}

    {% endfor %}

    Previous

    Next

{% endblock %}

urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from posts import views
urlpatterns = [
    url(r'^youadmin/', admin.site.urls),
    url(r'^', views.blog_view, name='blog'),
    url(r'^<int:id>/', views.detail_view, name='detail'),
] + static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Answer: You must include a trailing slash at the beginning of your urls like this:
urlpatterns = [
    url(r'^/youadmin/', admin.site.urls),
    url(r'^/', views.blog_view, name='blog'),
    url(r'^/<int:id>/', views.detail_view, name='detail'),
]

It's also possible that an instance of Post with id=1 just doesn't exist.
Comment: now http://127.0.0.1:8000/ this is showing that page not found but it does not show noreversematch error now what should i do?
Answer: You are using the url function which expects you to use regex to capture arguments, to capture an integer your patterns should be like:
urlpatterns = [
    url(r'^youadmin/', admin.site.urls),
    url(r'^', views.blog_view, name='blog'),
    url(r'^(?P<id>\d+)/', views.detail_view, name='detail'),
]

But i would recommend you to use the path function instead, which doesn't require regex:
from django.urls import path

urlpatterns = [
    path('youadmin/', admin.site.urls),
    path('', views.blog_view, name='blog'),
    path('<int:id>/', views.detail_view, name='detail'),
]

Comment: it is showing ImportError: cannot import name 'path' from 'django.urls'
help me about this
Comment: @AAKASHSINGLA You might be using an older version of Django, use the first option then.
Comment: first option is also not working guide me about first option     help me about the second option what i have to do for install  or any other solution
Comment: @AAKASHSINGLA Whats not working in the first option?
Comment: now 127.0.0.1:8000 this is showing that page not found but it does not show noreversematch error now what should i do?
Comment: @AAKASHSINGLA are you sure you are talking about the first option I have given in my answer? I have not changed anything in this pattern `url(r'^', views.blog_view, name='blog'),`. Please use the **first block of code** in my answer.
Comment: its working but it is not showing the image. help me about this
Comment: @AAKASHSINGLA in your for loop over the images you have set the src attribute to `https://mdbootstrap.com/img/new/slides/041.jpg` set it to `{{ p.image.url }}`
Comment: in detail.html by changing this src="https://mdbootstrap.com/img/new/slides/041.jpg"  to src="{{ post.image.url }}" does not give me any effect.
Comment: @AAKASHSINGLA Your loop is `{% for p in photos %}` and you are writing `{{ post.image.url }}` does that make sense to you?
Comment: This also after changing src="mdbootstrap.com/img/new/slides/041.jpg" to src="{% for p in photos %}" does not give me any effect. Help me about this
Comment: if you can help me regarding this, then please help me. I am not able to show the images or multi-images


Probability of getting 3 3s throwing 3 dice 3 times and saving the 3s

Question: You can throw 3 dice 3 times. Every time a 3 comes, you save it and don't throw it any more. What are the odds you will end up with 3 3 3?
Answer: Here is some hint:
Conditioning on the result of the first throw:
Let $A_0$ = {the first throw doesn't have 3}, $A_1$ = {the first throw has one 3},
$A_2$ = {the first throw has two 3s},
$A_3$ = {the first throw has three 3s} and $A$ = {ends up with 3, 3, 3}.
By law of total probability:
$$P(A) = P(A|A_0)P(A_0) + P(A|A_1)P(A_1) + P(A|A_2)P(A_2) + P(A|A_3)P(A_3)$$
Finding $P(A|A_0)$, $P(A|A_1)$ and $P(A|A_2)$ are just "fractal" problems of the original problem. It is also easy to find $P(A_i), i = 0, 1, 2, 3$.
Comment: This makes sense! I'll try to solve it. But I also should consider $A_0$, right?
Comment: Why? The first throw might be {2,4,6}, then the second throw might be {3,3,3}.
Answer: Here is some R code to check against the theoretical derivation:
<code>perce=0; T=10^7
for (t in 1:T){
  # first throw
  res=sample(1:6,3,rep=TRUE)
  val=sum(res==3)
  # second throw
  if (val<3){ res=sample(1:6,3-val,rep=TRUE)
    val=val+sum(res==3)}
  # third throw
  if (val<3){ res=sample(1:6,3-val,rep=TRUE)
    val=val+sum(res==3)}
  perce=perce+(val==3)}
perce/T
</code>


Finding the value of $\frac{\cos^4\beta}{\cos^2\alpha} + \frac{\sin^4\beta}{\sin^2\alpha}$.

Question: Trigonometry
$\dfrac{\cos^4 \alpha}{\cos^2 \beta}+ \dfrac{\sin^4\alpha}{\sin^2\beta} = 1$
then the value of
$\dfrac{\cos^4\beta}{\cos^2\alpha}+ \dfrac{\sin^4\beta}{\sin^2\alpha}$ is?
NOTE: can somebody help me
$\cos^2\alpha \left(\frac{\cos^2 \alpha}{\cos^2 \beta}\right)+ \sin^2\alpha \left(\frac{\sin^2 \alpha}{\sin^2\beta}\right)$
Comment: Use `$\cos$` (instead of `$cos$`) for $\cos$. Similarly for $\sin$. EX: `$\sin^2(\alpha)+\cos^2(\alpha)=1$` $\to$ $\sin^2(\alpha)+\cos^2(\alpha)=1$
Comment: http://math.stackexchange.com/questions/410304/if-dfrac-cos4-theta-cos2-phi-dfrac-sin4-theta-sin2-phi-1-show and http://math.stackexchange.com/questions/639223/if-frac-sin4-xa-frac-cos4-xb-frac1ab-then-show-that-frac
Answer: Let $t=\sin^2(\alpha)$ and $s=\sin^2(\beta)$. Then, multiplying both sides of the given identity by $s(1-s)$ gives:
$$
(1-t)^2s+t^2(1-s)=s(1-s).
$$
Bringing the RHS over to the LHS simplifies to $(s-t)^2=0$ so $s=t$. Now, the expression you want to evaluate is just
$$
\frac{(1-s)^2}{1-s}+\frac{s^2}{s}=1-s+s=1.
$$
Comment: cant able to follow @kim jong un.It seems hard to me
Comment: $t$ and $s$ are just notational convenience. The rest is just simple manipulations. Keep in mind $\cos^2x+\sin^2x=1$ for any angle $x$.
Answer: $\cos^2 \alpha \left(\frac{\cos^2\alpha}{\cos^2 \beta}\right) + \sin^2 \alpha \left(\frac{\sin^2 \alpha}{\sin^2 \beta}\right)=1$.
It can be noticed that $\frac{\cos^2\alpha}{\cos^2 \beta}$ and $\frac{\sin^2 \alpha}{\sin^2 \beta}$ must be $1$ (Why?).
This tells us that $\cos^2 \alpha = \cos^2 \beta$ and $\sin^2 \alpha = \sin^2\beta$.
Plug those two results in the required expression. It will then become a well-known expression with a well-known value.


using HLSL to invisibly stress a graphics card - How to stress the memory?

Question: I've been developing for a bit an invisible (read: doesn't produce any visual output) stressor to test the capabilities of my graphics card (and as a exploration of DirectCompute in general, with which I'm pretty new). I've got the following code right now that I'm pretty proud of:
RWStructuredBuffer<uint> BufferOut : register(u0);

[numthreads(1, 1, 1)]
void CSMain( uint3 DTid : SV_DispatchThreadID )
{
    uint total = 0;
    float p = 0;
    while(p++ < 40.0){
        float s= 4.0;
        float M= pow(2.0,p) - 1.0;
        for(uint i=0; i <= p - 2; i++)
        {
            s=((s*s) - 2) % M;
        }
        if(s < 1.0) total++;
    }
    BufferOut[DTid.x] = total;
}

This runs the Lucas Lehmer Test for the first 40 powers of two. When I dispatch this code in a timed loop and look at my graphics cards stats using GPU-Z, my GPU load shoots to 99% for the duration. I'm pretty happy with this, but I also notice that the heat generation from a fully loaded out GPU is actually pretty minimal (I'm getting about a 5 to 10 degree Celsius jump, nowhere near the heat jump I get when running, say, Borderlands 2). My thought is that most of my heat comes from memory accesses, so I would need to include consistent memory accesses across the run. My initial code looked like this:
RWStructuredBuffer<uint> BufferOut : register(u0);

groupshared float4 memory_buffer[1024];

[numthreads(1, 1, 1)]
void CSMain( uint3 DTid : SV_DispatchThreadID )
{
    uint total = 0;
    float p = 0;
    while(p++ < 40.0){
            [fastop] // to lower compile times - Code efficiency is strangely not what Im looking for right now.
            for(uint i = 0; i < 1024; ++i)

        float s= 4.0;
        float M= pow(2.0,p) - 1.0;
        for(uint i=0; i <= p - 2; i++)
        {
            s=((s*s) - 2) % M;
        }
        if(s < 1.0) total++;
    }
    BufferOut[DTid.x] = total;
}

Answer: Read a lot of non-coherent samples in large textures. Try both DXT1 compressed and non-compressed values. And use render to texture. And MRT. All will beat on the GPU memory systems.


Why there is dependencies when i copy a List in a List>?

Question: I'm creating a little C# apps using List of an object and i have a very noob question :
First i'm filling my object 'A' , then i add in my list named 'lstA' :
List<List> Lst_LstA = new List<List>();  // List of List
List lstA = new List(); // List of my object

A myA = new A();
A.xxx = xx;
A.yyy = yy;

lstA.Add(A);
Lst_LstA.Add(lstA);
lstA.Clear();

What is my problem ? Very simple : When i call  lstA.Clear(), it clear my lstA list, perfect, but...it clear too the element in my lst_LstA<> list.
I need to clear the lstA List, but only these list.
Why the Clear() modify too the other list ? How solve this simply ?
Thanks a lot,
best regards,
Comment: It's because `List<>` is a reference type... If you want to add it as new List, use `.Add(new List<>(a)`. Or use `.ToList()`
Comment: Thanks @TripleEEE it's ok :)
Answer: The issue is that when you add lstA to lst_lstA, you're adding by reference - i.e. you're just adding a pointer to the list.
The only way for this to work would be to add a copy of lstA to lst_lstA
Comment: Perfect ! I did .Add(new List<>(a) and it's ok ! Thanks a lot !
Comment: @WalterFabioSimoni no problem :) don't forget to mark it as the answer in a couple of hours' time, when it lets you


Putting socks and shoes on a spider

Question:
A spider needs a sock and a shoe for each of its eight legs. In how many ways can it put on the shoes and socks, if socks must be put on before the shoe?

My attempt:
If I consider its legs to be indistinguishable, then it's exactly the $8^{\text{th}}$ term of the Catalan sequence. However the legs are distinguishable. So the total number of ways equals $\frac1{8+1} \binom{16}{8} (8!)^2$.
Is this correct? Is there another way of doing it?
Edit: All socks and shoes are distinguishable.
Comment: Wow!  Ambiguous questions are to be expected in beginning combinatorics questions but this one takes it to a whole new level!  What is a "way of putting on shoes".  Is it about which shoe and sock goes on which foot?  Is it about what order you put things on on which foot?  Are shoes and sock distinguishable.  Are legs?
Comment: I think your factor of $(8!)^2$ is overcounting because it doesn't account for the constratint that the sock on leg $n$ has to go on before the shoe on leg $n$. Your count would allow sequences starting sock on leg $1$, shoe on leg $2$, ... for example. But I can't see a simple expression for the distinguishable legs case.
Comment: Are those 4 left shoes and 4 right shoes and 8 symmetrical socks?
Comment: @fleablood i want to ask something , if  All socks and shoes are distinguishable , after we found wearing order , why did we not multiply by $(8!)^2$ ? For example , for $345322815....$ , i think that we should have determined which socks is for the first $3$ , and which shoe is for the second $3$ ? am i wrong?
Comment: @Bulbasaur  I have no idea what you are asking.  I don't know what "wearing order" means, I have no idea *what* you are proposing multiply by $(8!)^2$, I don't know what the numbers $345322815....$ means.  And I have no idea why you are asking *me* this of all people..... This question is *still* ambiguous but if we assume that it means the spider has 8 distinct shoes and 8 distinct socks how many outcomes can it have if it has a shoe under a sock for each leg.... The the answer to that is $(8!)^2$. $8!$ positions for 8 socks on 8 legs and $8!$ positions for 8 shoes on 8 legs.
Comment: https://oeis.org/A000680
Answer: You can imagine doing this as writing a sequence, say $$3453228156467781$$
What does it mean?
It means first put sock on leg $\color{red}{3}$ and on 4-th move put shoe on leg $\color{red}{3}$
then put sock on leg $\color{blue}{4}$ and on 11-th move put shoe on leg $\color{blue}{4}$ and so on...
So for each leg you must choose a pair in this sequence. On smaller number in this pair put a sock and the other shoe.
So we have $${16\choose 2}{14\choose 2}....{4\choose 2}{2\choose 2} = {16!\over 2!^8}$$
Comment: Oh, I figured it out: you have $1,1,2,2, ..., 8,8$ and you just permute them to form that sequence above.
Comment: I gave the tick to this answer because it's the easiest to understand.
Comment: Am I the only one amazed by the fact that there are over 81 billion possibilities?
Comment: You gave $34;53;22;81;56;46;77;81$. Why does $81$ appear twice, at positions 4 and 8, or have I misunderstood the way the sequence is written?
Comment: i see that you deleted my comment , it is unrespectful behavior , you chould have added an explanation .Was my comment wrong? if not why did you delete
Comment: I didn't delete it, any way you could look around at other solutions to see what is wrong with yours. I'm not obliged to search and explain others mistakes. @Bulbasaur
Answer: No, it's not correct. Multiplying the Catalan number by $8!$ twice means we're choosing legs arbitrarily for each instance of a socking or a shoeing - with no regard to whether that leg has a sock on it, in the latter case. It's a substantial overcount.
Multiplying by $8!$ once would correspond to a "last in, first out" restriction; each time we put a shoe on, it's the most recently socked leg. That's an undercount, of course.
There are two actions per leg - the sock and then the shoe. All we need to know to determine a sequence is when each leg was worked on. That's $\binom{16}{2}$ for the first leg, $\binom{14}{2}$ for the second, and so on - or, equivalently, the multinomial coefficient $\binom{16}{2,2,\dots,2} = \frac{16!}{(2!)^8}$.
Comment: I wrote an comment in @aqua's answer , can you look at it ? i think that there is something deficit in your answers , it is said that socks and shoes are distinguishable , so $(8!)^2$ must be added to your answers
Answer: The answers given are correct, but I have a different (and possibly easier) way to think of it:
If you relax the condition for the sock/shoe event to be in order then there are $2n$ ($=16$) events hence $16!$ orderings.
This is of course an over-count: many (most) of these are of an invalid ordering, with at least one sock over the top of a shoe.
The question is by how many?
To answer this, suppose we divide them into groups. Specifically one group for each of the orderings of shoe/sock on each foot.
For example:

a group where: the sock on leg 1 is before on leg 1, the sock on leg 2 is before the shoe on leg 2 ..., the sock on leg 8 is before the shoe on leg 8 (the one we want)
a group where: the sock on leg 1 is after on leg 1, the sock on leg 2 is before the shoe on leg 2 etc (not valid for us)

These groups are of the same size (none of them are special).
There are $2^n$ ($2^8$) of these groups so each of them, including the one we want, is of size: $\frac{16!}{2^8}$ or $81,729,648,000$.
Notes on generalisation:
Suppose $n$ legs and $k$ objects to put on in a given order.
There are $(k n)!$ events, $k!$ orderings of any one of the leg's objects. Hence $(k!)^n$ orderings of the objects on each leg, only one of which is desired and so:
$\frac{(k n)!}{(k!)^n}$ possible valid orderings of placing an object on a leg.
Answer: Another approach:
Let $f(n)$ denote the number of ways for an $n$-legged animal to put socks and shoes on all of their legs.
With one leg, there's only one way: Put the sock on, then the shoe.
With two legs (like the vast majority of humans), there are 6 possibilities.  In greedoid's notation, these are:

1122 = Sock on leg #1, shoe on leg #1, sock on leg #2, shoe on leg #2
1212 = Sock on leg #1, sock on leg #2, shoe on leg #1, shoe on leg #2
1221 = Sock on leg #1, sock on leg #2, shoe on leg #2, shoe on leg #1
2112 = Sock on leg #2, sock on leg #1, shoe on leg #1, shoe on leg #2
2121 = Sock on leg #2, sock on leg #1, shoe on leg #2, shoe on leg #1
2211 = Sock on leg #2, shoe on leg #2, sock on leg #1, shoe on leg #1

Now, suppose that we've calculated $f(k)$ for some $k$.  How does introducing a $(k + 1)$th leg affect the problem?
If you take any possible sequence of the $2k$ sock+shoe events for $k$ legs, then there are $2k + 1$ possible positions in the sequence to put the sock for the new leg (the $2k - 1$ positions between existing events, at the beginning, or at the end).  Assume that we decide to put this new event after $j$ of the original events.
Now, let's decide when to put on the shoe for the new leg.  This is trickier, because it depends on when we put on the sock.  This new event can be inserted at index $j + 1$, $j + 2$, $j + 3$, ..., up to $2k + 1$, for $2k + 1 - j$ possibilies.
So, that gives us $\sum\limits_{j=0}^{2k+1} (2k + 1 - j)$ possibilities for when to add the sock and shoe for the new leg, which works out to the $(2k + 1)$th triangular number = $\frac{(2k + 1)(2k + 2)}{2}$.  With $k + 1 = n$, this can be rewritten as $\frac{(2n - 1)(2n)}{2} = n(2n - 1)$.
We now have the recurrence relation $f(n) = n(2n - 1)f(n-1)$ with base case $f(n) = 1$.  Or, in Python syntax.
<code>>>> def f(n):
...     if n == 1:
...         return 1
...     else:
...         return n * (2 * n - 1) * f(n - 1)
...
>>> f(8)
81729648000
</code>
Proof that this is equivalent to the non-recursive formulation $f(n) = \frac{(2n)!}{2^n}$ is left as an exercise for the reader.

Putting socks and shoes on a spider


HortonWorks HDP 2.6:DRPC Server Install issue via Ambari

Question: I install HDP 2.6 via Ambari 18.104.22.168 on SUSE11sp3,the last step one of my nodes meet failure ,it seems happen in "DRPC Server Install" task,here is log:

stderr:   /var/lib/ambari-agent/data/errors-603.txt

Traceback (most recent call last):
  File "/var/lib/ambari-agent/cache/common-services/STORM/0.9.1/package/scripts/drpc_server.py", line 139, in <module>
    DrpcServer().execute()
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 314, in execute
    method(env)
  File "/var/lib/ambari-agent/cache/common-services/STORM/0.9.1/package/scripts/drpc_server.py", line 44, in install
    self.configure(env)
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 117, in locking_configure
    original_configure(obj, *args, **kw)
  File "/var/lib/ambari-agent/cache/common-services/STORM/0.9.1/package/scripts/drpc_server.py", line 50, in configure
    storm()
  File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk
    return fn(*args, **kwargs)
  File "/var/lib/ambari-agent/cache/common-services/STORM/0.9.1/package/scripts/storm.py", line 86, in storm
    content=Template("storm.conf.j2")
  File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 155, in __init__
    self.env.run()
  File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 160, in run
    self.run_action(resource, action)
  File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 124, in run_action
    provider_action()
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 120, in action_create
    raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname))
resource_management.core.exceptions.Fail: Applying File['/etc/security/limits.d/storm.conf'] failed, parent directory /etc/security/limits.d doesn't exist

stdout:   /var/lib/ambari-agent/data/output-603.txt

2017-05-16 02:07:02,497 - Stack Feature Version Info: stack_version=2.6, version=None, current_cluster_version=None -> 2.6
2017-05-16 02:07:02,499 - Using hadoop conf dir: /usr/hdp/current/hadoop-client/conf
User Group mapping (user_group) is missing in the hostLevelParams
2017-05-16 02:07:02,500 - Group['livy'] {}
2017-05-16 02:07:02,503 - Group['spark'] {}
2017-05-16 02:07:02,504 - Group['zeppelin'] {}
2017-05-16 02:07:02,505 - Group['hadoop'] {}
2017-05-16 02:07:02,506 - Group['users'] {}
2017-05-16 02:07:02,507 - Group['knox'] {}
2017-05-16 02:07:02,509 - User['hive'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,512 - User['storm'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,514 - User['infra-solr'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,516 - User['zookeeper'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,517 - User['atlas'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,519 - User['oozie'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['users']}
2017-05-16 02:07:02,521 - User['ams'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,523 - User['falcon'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['users']}
2017-05-16 02:07:02,525 - User['tez'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['users']}
2017-05-16 02:07:02,527 - User['zeppelin'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['zeppelin', 'hadoop']}
2017-05-16 02:07:02,529 - User['accumulo'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,531 - User['livy'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,533 - User['mahout'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,535 - User['spark'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,537 - User['ambari-qa'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['users']}
2017-05-16 02:07:02,538 - User['flume'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,540 - User['kafka'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,542 - User['hdfs'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:02,543 - Modifying user hdfs
2017-05-16 02:07:03,568 - User['sqoop'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,571 - User['yarn'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,573 - User['hbase'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,574 - User['hcat'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,576 - User['mapred'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,578 - User['knox'] {'gid': 'hadoop', 'fetch_nonlocal_groups': True, 'groups': ['hadoop']}
2017-05-16 02:07:03,581 - File['/var/lib/ambari-agent/tmp/changeUid.sh'] {'content': StaticFile('changeToSecureUid.sh'), 'mode': 0555}
2017-05-16 02:07:03,584 - Execute['/var/lib/ambari-agent/tmp/changeUid.sh ambari-qa /tmp/hadoop-ambari-qa,/tmp/hsperfdata_ambari-qa,/home/ambari-qa,/tmp/ambari-qa,/tmp/sqoop-ambari-qa'] {'not_if': '(test $(id -u ambari-qa) -gt 1000) || (false)'}
2017-05-16 02:07:03,595 - Skipping Execute['/var/lib/ambari-agent/tmp/changeUid.sh ambari-qa /tmp/hadoop-ambari-qa,/tmp/hsperfdata_ambari-qa,/home/ambari-qa,/tmp/ambari-qa,/tmp/sqoop-ambari-qa'] due to not_if
2017-05-16 02:07:03,595 - Directory['/tmp/hbase-hbase'] {'owner': 'hbase', 'create_parents': True, 'mode': 0775, 'cd_access': 'a'}
2017-05-16 02:07:03,597 - File['/var/lib/ambari-agent/tmp/changeUid.sh'] {'content': StaticFile('changeToSecureUid.sh'), 'mode': 0555}
2017-05-16 02:07:03,599 - Execute['/var/lib/ambari-agent/tmp/changeUid.sh hbase /home/hbase,/tmp/hbase,/usr/bin/hbase,/var/log/hbase,/tmp/hbase-hbase'] {'not_if': '(test $(id -u hbase) -gt 1000) || (false)'}
2017-05-16 02:07:03,609 - Skipping Execute['/var/lib/ambari-agent/tmp/changeUid.sh hbase /home/hbase,/tmp/hbase,/usr/bin/hbase,/var/log/hbase,/tmp/hbase-hbase'] due to not_if
2017-05-16 02:07:03,610 - Group['hdfs'] {}
2017-05-16 02:07:03,611 - User['hdfs'] {'fetch_nonlocal_groups': True, 'groups': ['hadoop', 'hdfs', 'hdfs']}
2017-05-16 02:07:03,613 - Modifying user hdfs
2017-05-16 02:07:03,664 - FS Type:
2017-05-16 02:07:03,664 - Directory['/etc/hadoop'] {'mode': 0755}
2017-05-16 02:07:03,689 - File['/usr/hdp/current/hadoop-client/conf/hadoop-env.sh'] {'content': InlineTemplate(...), 'owner': 'hdfs', 'group': 'hadoop'}
2017-05-16 02:07:03,690 - Writing File['/usr/hdp/current/hadoop-client/conf/hadoop-env.sh'] because contents don't match
2017-05-16 02:07:03,690 - Changing owner for /usr/hdp/current/hadoop-client/conf/hadoop-env.sh from 0 to hdfs
2017-05-16 02:07:03,691 - Changing group for /usr/hdp/current/hadoop-client/conf/hadoop-env.sh from 0 to hadoop
2017-05-16 02:07:03,692 - Directory['/var/lib/ambari-agent/tmp/hadoop_java_io_tmpdir'] {'owner': 'hdfs', 'group': 'hadoop', 'mode': 01777}
2017-05-16 02:07:03,718 - Initializing 2 repositories
2017-05-16 02:07:03,719 - Repository['HDP-2.6'] {'base_url': 'http://192.168.156.25/hdp/HDP/suse11sp3/2.x/updates/188.8.131.52', 'action': ['create'], 'components': ['HDP', 'main'], 'repo_template': '[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0', 'repo_file_name': 'HDP', 'mirror_list': None}
2017-05-16 02:07:03,734 - Flushing package manager cache since repo file content is about to change
2017-05-16 02:07:03,734 - checked_call[['zypper', 'clean', '--all']] {'sudo': True}
2017-05-16 02:07:03,837 - checked_call returned (0, 'All repositories have been cleaned up.')
2017-05-16 02:07:03,837 - File['/etc/zypp/repos.d/HDP.repo'] {'content': '[HDP-2.6]\nname=HDP-2.6\nbaseurl=http://192.168.156.25/hdp/HDP/suse11sp3/2.x/updates/18.104.22.168\n\npath=/\nenabled=1\ngpgcheck=0'}
2017-05-16 02:07:03,839 - Writing File['/etc/zypp/repos.d/HDP.repo'] because contents don't match
2017-05-16 02:07:03,840 - Repository['HDP-UTILS-126.96.36.199'] {'base_url': 'http://192.168.156.25/hdp/HDP-UTILS-126.96.36.199/repos/suse11sp3', 'action': ['create'], 'components': ['HDP-UTILS', 'main'], 'repo_template': '[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0', 'repo_file_name': 'HDP-UTILS', 'mirror_list': None}
2017-05-16 02:07:03,846 - Flushing package manager cache since repo file content is about to change
2017-05-16 02:07:03,846 - checked_call[['zypper', 'clean', '--all']] {'sudo': True}
2017-05-16 02:07:04,410 - checked_call returned (0, 'All repositories have been cleaned up.')
2017-05-16 02:07:04,411 - File['/etc/zypp/repos.d/HDP-UTILS.repo'] {'content': '[HDP-UTILS-184.108.40.206]\nname=HDP-UTILS-220.127.116.11\nbaseurl=http://192.168.156.25/hdp/HDP-UTILS-126.96.36.199/repos/suse11sp3\n\npath=/\nenabled=1\ngpgcheck=0'}
2017-05-16 02:07:04,411 - Writing File['/etc/zypp/repos.d/HDP-UTILS.repo'] because contents don't match
2017-05-16 02:07:04,412 - Package['unzip'] {'retry_on_repo_unavailability': False, 'retry_count': 5}
2017-05-16 02:07:04,884 - Skipping installation of existing package unzip
2017-05-16 02:07:04,884 - Package['curl'] {'retry_on_repo_unavailability': False, 'retry_count': 5}
2017-05-16 02:07:05,170 - Skipping installation of existing package curl
2017-05-16 02:07:05,171 - Package['hdp-select'] {'retry_on_repo_unavailability': False, 'retry_count': 5}
2017-05-16 02:07:05,391 - Skipping installation of existing package hdp-select
2017-05-16 02:07:05,594 - Package['storm_2_6_0_3_8'] {'retry_on_repo_unavailability': False, 'retry_count': 5}
2017-05-16 02:07:06,118 - Installing package storm_2_6_0_3_8 ('/usr/bin/zypper --quiet install --auto-agree-with-licenses --no-confirm storm_2_6_0_3_8')
2017-05-16 02:07:36,817 - Stack Feature Version Info: stack_version=2.6, version=None, current_cluster_version=None -> 2.6
2017-05-16 02:07:36,820 - Using hadoop conf dir: /usr/hdp/current/hadoop-client/conf
2017-05-16 02:07:36,822 - Directory['/var/log/storm'] {'owner': 'storm', 'group': 'hadoop', 'create_parents': True, 'mode': 0777, 'cd_access': 'a'}
2017-05-16 02:07:36,823 - Changing group for /var/log/storm from 117 to hadoop
2017-05-16 02:07:36,824 - Changing permission for /var/log/storm from 755 to 777
2017-05-16 02:07:36,825 - Directory['/var/run/storm'] {'owner': 'storm', 'create_parents': True, 'group': 'hadoop', 'mode': 0755, 'cd_access': 'a'}
2017-05-16 02:07:36,826 - Changing group for /var/run/storm from 117 to hadoop
2017-05-16 02:07:36,827 - Directory['/hadoop/storm'] {'owner': 'storm', 'group': 'hadoop', 'create_parents': True, 'mode': 0755, 'cd_access': 'a'}
2017-05-16 02:07:36,827 - Creating directory Directory['/hadoop/storm'] since it doesn't exist.
2017-05-16 02:07:36,827 - Changing owner for /hadoop/storm from 0 to storm
2017-05-16 02:07:36,828 - Changing group for /hadoop/storm from 0 to hadoop
2017-05-16 02:07:36,828 - Directory['/usr/hdp/current/storm-client/conf'] {'group': 'hadoop', 'create_parents': True, 'cd_access': 'a'}
2017-05-16 02:07:36,828 - Changing group for /usr/hdp/current/storm-client/conf from 0 to hadoop
2017-05-16 02:07:36,834 - File['/etc/security/limits.d/storm.conf'] {'content': Template('storm.conf.j2'), 'owner': 'root', 'group': 'root', 'mode': 0644}

Command failed after 1 tries

I found similar issue in https://issues.apache.org/jira/browse/AMBARI-7792
,but it has been solved in Ambari 1.7 .
Answer: I hit this same error with Storm Nimbus on Suse 12 while deploying HDF 3.0 with Ambari 2.5.1.
I've raised it as a new apache jira https://issues.apache.org/jira/browse/AMBARI-21489 as AMBARI-7792 was supposed to be fixed back in Ambari 1.7.
The obvious quick workaround it just to mkdir /etc/security/limits.d
Comment: I just solved this problem by choosing components as few as I can.


How does the Unit of Work pattern accommodate references to new aggregates?

Question: Background
As I understand it, the Unit of Work (UoW) pattern essentially provides transaction semantics. In other words, given a domain of aggregates persisted by repositories, a UoW class allows consumers of the domain to register invocations of repository methods into an atomic operation. Say we have:
interface IAggregate<TKey> {
    TKey Id { get; }
}

interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
    TEntity Get(TKey id);
    void Save(TEntity entity);
    void Remove(TEntity entity);
}

interface IUnitOfWork {
    void RegisterSave<TEntity>(TEntity entity);
    void RegisterRemove<TEntity>(TEntity entity);
    void RegisterUnitOfWork(IUnitOfWork uow);
    void Commit();
    void Rollback();
}

Assume the implementations of IRepository use a relational database, and the implementation of IUnitOfWork.Commit merely sets up a transaction with the database and proceeds to invoke Save or Remove on the appropriate IRepository instances for all the operations that had been registered.  I'd say what I outlined above is a standard, direct interpretation of the Aggregate Root, Repository, and UoW patterns (NHibernate/EF and all their bloated glory notwithstanding).
In the past, I have interpreted the concept of aggregate root boundaries as meaning that references from one aggregate to another should be objectified by an Id property of the target aggregate on the source aggregate. For example:
class User : IAggregate<int> {
  int Id { get; private set; }
}

class Blog : IAggregate<int> {
  int Id { get; private set; }
  int AuthorUserId { get; set; }
}

Question
Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?
I have come up with some answers (marked community wiki), but am posting my question here anyway to solicit feedback and more answers.
Comment: Nothing wrong with answering your own questions - see [the faq - What kind of questions can I ask here?](http://stackoverflow.com/faq). As long as you pretend you're on [Jeopardy!](http://en.wikipedia.org/wiki/Jeopardy!)
Comment: If you don't want rep for your answers, you can tag your _answers_ as community wiki. See the details in the first answer to [this question on meta](http://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts). It's also explained how a question gets community wiki status.
Comment: With all due respect...this question with your own answers is like you're having a conversation with yourself.  Why put a question up and then answer it?  Why not just create a wiki?
Comment: Good point. Just looked it up. Apparently community wiki is no longer available: http://meta.stackexchange.com/questions/67039/what-can-we-do-to-make-community-wiki-better/67192#67192 . What's the correct etiquette for this? I put up the question even though I have answers because I want to know what other answers exist. Should I put my answers in the question? I'd rather people be able to vote on them, not so I get reputation, but simply so I can see how they are measured by the "crowd".
Comment: Moved my own answers into the question.
Comment: Thanks for the information guys! Restored my answers in the answer section, and removed them from the question text.
Answer:
Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?

Thing is - aggregate is responsible to draw transactional boundaries too. That means - there should be no need to simultaneously create User with Blog and rollback User creation if Blog creation somehow fails.
If there is such a need - You are modeling aggregates wrong.

Just posting some quick comments that might be useful...
interface IAggregate<TKey> {
    TKey Id { get; }
}

Interfaces should be used to define behavior (roles) and not what implementing class will hold (knowledge about key type in this case).
Can't google quickly enough to find proper explanation why exactly it's so though...
Will try later.
interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
  TEntity Get(TKey id);
  void Save(TEntity entity);
  void Remove(TEntity entity);
}

Avoid usage of generic repositories.
interface IUnitOfWork {
  void RegisterSave<TEntity>(TEntity entity);
  void RegisterRemove<TEntity>(TEntity entity);
  void RegisterUnitOfWork(IUnitOfWork uow);
  void Commit();
  void Rollback();
}

Avoid usage of unit of work (this one solves Your problem).
interface IAggregate<TSelf> where TSelf : IAggregate<TSelf>
{
    IKey<TSelf> Id { get; }
}

Keep learning. Soon enough You will stop abusing interfaces & generics. :)
Comment: @gWiz Genericness blurs intent. Strength of generic repository is at the same time its weakness.
Comment: Yes, I had the feeling that aggregate boundaries should accomodate transactional state changes. I had broken this before to improve performance when aggregate roots had hundreds of entities, although it would have been better to implement a lazy-loading proxy instead. Regardless, when using UoW without DDD, the general problem I posed still arises.
Comment: I disagree that generic repositories should necessarily be avoided. Although you wouldn't ever do anything polymorphically with them (nonsense: `foreach (var r in repositories) { var e = r.Get(5); e.Id = rnd.GetNext(); r.Save(e); }`) they do serve the supporting role of illucidating code intent, especially when XML documentation is added to the interface.
Comment: The unit of work link you provided does not conclusively argue to avoid UoW. In CQRS, can the execution of a command not cause multiple events to occur, all of which should be persisted atomically?
Comment: Just one comment though. The main reason not to violate ARs transactionnal boundaries is to mitigate the risk of concurrency exceptions (assuming optimistic concurrency). However, the rule can be loosened when you create new ARs, since there's usually no contention when creating ARs: 2 transactions creating a `User` at the same time wouldn't usually collide. Therefore, it might be convenient at times to create multiple ARs in a single transaction and that shouldn't impact the system's ability to scale. However, **modifying** multiple ARs in a single transaction shall be avoided.
Answer: Should the ID type be smarter as a reference type? That way when the repository updates the ID, it can be accessed via reference by another aggregate. For example:
interface IKey<TAggregate> : IEquatable<IKey<TAggregate>>
{
    /* should provide a ctor that accepts a string */

    TAggregate GetAggregateType();
    string ToString();
    bool IsAssigned { get; }
}

interface IAggregate<TSelf> where TSelf : IAggregate<TSelf>
{
    IKey<TSelf> Id { get; }
}

interface IRepository<TAggregate> where TAggregate : IAggregate<TAggregate>
{
    TAggregate Get(IKey<TAggregate> id);
    void Save(TAggregate entity);
    void Remove(TAggregate entity);
}

class User : IAggregate<User>
{
    public IKey<User> Id { get; private set; }
}

class Blog : IAggregate<Blog>
{
    public IKey<Blog> Id { get; private set; }
    public IKey<User> Author { get; private set; }
}

The implementation of IKey<TAggregate> is provided in the same package as the implementations of IRepository<TAggregate>.
Answer: It seems that one of the following pattern constraints must be loosened:

Repository is responsible for generating aggregate IDs. Instead, a natural key must be used.
UoW can't register arbitrary Action delegates. Instead, allow UoW to register arbitrary Actions.
Inter-aggregate relationships are objectified as ID properties. Instead, use aggregate-typed properties, such as:

partial class Blog : IAggregate<int> {
  User Author { get; set; }
}

So had I interpreted the patterns incorrectly? Or are they actually limited in this regard?


JDBCTemplate RowMapper para Nested POJOs

Question: Vamos dizer que eu tenho os seguintes Pojos
public class Pedidos{
 private Strig codigo;
 private String nomePedido;
 private List<Dados> dadosPedido;
 //getters e setters}
}

E
  public class Dados {
    private String nome;
    private int codigo;
 }

Eu sei que poderia usar um BeanPropertyRowMapper para popular uma lista de objetos de Pedidos, agora existe alguma forma de popular também o objeto Dados através da mesma query? Depois disso eu precisaria montar um XML onde cada Pedido teria a sua lista de Dados correspondente, eu achei uma pergunta similar: https://stackoverflow.com/questions/16718163/jdbctemplate-set-nested-pojo-with-beanpropertyrowmapper
Porém no meu caso eu tenho também uma Lista de Users.
Answer: O RowMapper não é uma boa solução para isso.
Eu estava aqui pensando em uma gambiarra para armazenar um mapa interno ou algo parecido, mas pesquisando por uma alternativa, encontrei esse código praticamente pronto usando o ResultSetExtractor:
jdbcTemplate.query("SELECT * FROM INVOICE inv JOIN INVOICE_LINE line " +
   + " on inv.id = line.invoice_id", new ResultSetExtractor<List<Invoice>>() {

    List<Invoice> extractData(ResultSet rs) {
        Map<Integer,Invoice> invoices = new HashMap<Integer,Invoice>();
        while(rs.hasNext()) {
            rs.next();
            Integer invoiceId = rs.getInd("inv.id");
            Invoice invoice = invoces.get(invoiceId);
            if (invoice == null) {
               invoice = invoiceRowMapper.mapRow(rs);
               invoices.put(invoiceId,invoice);
            }
            InvoiceItem item = invLineMapper.mapRow(rs);
            invoice.addItem(item);
        }
        return invoices.values();
    }

});

Fonte
Com o ResultSetExtractor você faz a iteração manual sobre os resultados da query. Para cada registro:

Recupere o id do objeto da sua tabela principal (Pedidos)
Verifique se o Pedido já existe no mapa
2.1 Se não existir, crie o produto e coloque no mapa
Recupere as informações da tabela Dados
Adicione os dados na lista do produto atual

O resultado final é um mapa de produtos, cada um com os respectivos dados preenchidos. Para retornar uma lista de produtos, use o método keySet() do mapa.


Eigenvalue and space for orthogonal projection

Question:
Let $V$ be an inner product space over a field $\mathbb{K}$, and let $W \neq V$ be a subspace in $V$ of finite dimension $> 0$.
Let
  $P_W : V \to W$
  be the orthogonal projection on $W$.
(1) Show that $1$ is an eigenvalue for $P_W$, and the corresponding eigenspace equals $W$ .
(2) Show that $0$ is an eigenvalue for $P_W$, and the corresponding eigenspace is $W^{\perp}$.

I'm really stuck here.
 I know that $P_W(v)=\lambda v$.
and the eigen space: $E_{P_W}(\lambda)=\{v \in V | P_W(v)=\lambda \cdot v\}=\operatorname{ker}\left(P_W-\lambda \cdot \operatorname{Id}_{V}\right)$
But how do I relate this to the orthogonal projection. I mean I hardly have any information about the two vector spaces, their basis, the inner product, any matrix representations, etc.
Answer: I'll answer the part regarding finding the eigenvalues, as it looks like the other part regarding the eigenspaces has been answered:
If $P_W$ is an orthogonal projection, then in particular, $P_W^2=P_W.$ So, if $P_Wv=\lambda v,$ then $P_W^2v=\lambda v.$ and $P_W^2v=\lambda^2 v.$ That is, $\lambda =\lambda ^2,$ so $\lambda=0$ or $\lambda=1.$
Comment: It's just one of the main properties (sometimes a definition) on a projection. Here's a link that might help: https://math.stackexchange.com/questions/1574758/prove-that-the-orthogonal-projection-operator-is-idempotent
Comment: That makes sense. But why is $P_W^2=P_W$? Does that go for $P_W^n=P_W$ - I can't find anything about that in my text book.
Comment: I see it now. I think it makes perfectly intuitive sense, when thinking on vectors. If you project v down on W, you get p. If you try to project p on W again, of course you will get the same vector.
Comment: And the reason it also gives $\lambda^2v$ is because of: $\left(P_{W} \circ P_{W}\right) v=P_{\mathbf{w}}\left(P_{\mathbf{w}}(v)\right)=P_{\mathbf{W}}(\lambda v)==\lambda P_{W}(v)=\lambda \lambda V=\lambda^{2} v$
Comment: That is correct!
Answer: Orthogonal projection means that for $v\in V$, we can write $v=v_1+v_2$ with $v_1\in W$ and $v_2\in W^\perp$ and that then $P_W(v)=v_1$.
The eigenspace for eigenvalue $1$ consists of those vectors $v\in V$ for which $P_W(v)=v$. According to the above decomposition, this is equivalent to  $v=v_1+v_2=v_1$, i.e., $v\in W$.
The eigenspace for eigenvalue $0$ consists of those vectors $v\in V$ for which $P_W(v)=0$, in other words,  $v_1=0$, i.e., $v=v_2\in W^\perp$.


How to speed up if statements with for loop

Question: I am trying to create an on-edit function in Google Apps Script that automatically checks/changes formatting for certain checkboxes on Sheet 2 ("interventionSheet") based on which checkboxes are selected on Sheet 1 ("sessionFocus"). Each checkbox on Sheet 1 is associated with its own unique group of checkboxes on Sheet 2. I have figured out how to do this by using repeated if statements, but this is slowing down the processing speed significantly. I am looking for help with how to use batch processing (arrays, for statements, etc.) to make the code more efficient. See current (inefficient) code below.
function populateInterventions(e)
{
  var sessionFocus = SpreadsheetApp.getActive().getSheetByName('Session Focus');
  var interventionSheet = SpreadsheetApp.getActive().getSheetByName('Therapeutic Intervention');

  if(e.range.getA1Notation()=='B23')
  {
  var range3a = interventionSheet.getRangeList(['J78','Q69','Q71','Q72']);
  var range3b = interventionSheet.getRangeList(['J78','K78','Q69','R69','Q71','R71','Q72','R72']);

  if(sessionFocus.getRange('B23').isChecked()==true)
      {
        range3a.check();
        range3b.setBackground('#cfe2f3');
        range3a.setBorder(null,null,null,true,null,null,'#cfe2f3',null);
      }
  else
      {
        range3a.uncheck();
        range3b.setBackground('#ffffff');
        range3a.setBorder(null,null,null,true,null,null,'#ffffff',null);
      }
  }

  if(e.range.getA1Notation()=='B24')
  {
  var range4a = interventionSheet.getRangeList(['J18','J20','J32','J84','J85']);
  var range4b = interventionSheet.getRangeList(['J18','K18','J20','K20','J32','K32','J84','K84','J85','K85']);

  if(sessionFocus.getRange('B24').isChecked()==true)
      {
        range4a.check();
        range4b.setBackground('#cfe2f3');
        range4a.setBorder(null,null,null,true,null,null,'#cfe2f3',null);
      }
  else
      {
        range4a.uncheck();
        range4b.setBackground('#ffffff');
        range4a.setBorder(null,null,null,true,null,null,'#ffffff',null);
      }
  }

  if(e.range.getA1Notation()=='B26')
  {
  var range5a = interventionSheet.getRangeList(['J86','J87','N61','Q79','Q80']);
  var range5b = interventionSheet.getRangeList(['J86','K86','J87','K87','N61','O61','Q79','R79','Q80','R80']);

  if(sessionFocus.getRange('B26').isChecked()==true)
      {
        range5a.check();
        range5b.setBackground('#cfe2f3');
        range5a.setBorder(null,null,null,true,null,null,'#cfe2f3',null);
      }
  else
      {
        range5a.uncheck();
        range5b.setBackground('#ffffff');
        range5a.setBorder(null,null,null,true,null,null,'#ffffff',null);
      }
  }

Answer: In this specific case it doesn't look to make sense using a loop because the script has code sections that only executes when an specific cell is edited.

In order to make your scripts more efficients in terms of their execution time whenever is possible you have to minimize the calls to the Google Apps Script services.

Avoid having calls to the Google Apps Script services in loops
Take advantage of variables

i.e. instead of
if(e.range.getA1Notation()=='B23')
if(e.range.getA1Notation()=='B24')
if(e.range.getA1Notation()=='B26')

before do a variable declaration
const cellAddress = e.range.getA1Notation()

then use the variable instead of doing multiple Google Apps Script service calls
if(cellAddress=='B23')
if(cellAddress=='B24')
if(cellAddress=='B26')

Regarding using arrays, for loops etc., that might help to write better scripts, making them more readable, maintainable, extensible, etc. but you might find that they will not have a really relevant impact on the script performance when using only the "basic" services (i.e. SpreadsheetApp).
On more complex scripts it might be worthy to use Advanced Sheets Service in order to be able do multiple changes "at once" by using batchUpdate.
Resources

https://developers.google.com/apps-script/guides/support/best-practices


Loop through an same object in js

Question: {
    "uri": "https://www.fsa.go.jp/en/newsletter/index.html",
    "path": "D:\\SSN_INS\\JP--FSA--INS--NEWSLETTER\\",
    "pattern": "/.+/",
    "scope": "#main",
    "selector": "void",
    "extractors": [
        {
            "name": "TitleHtml",
            "query": {
                "scope": "title"
            }
        },
        {
            "name": "Title",
            "query": {
                "scope": "title"
            }
        }
    ],
    "tree": [
        {
            "type": "pseudo",
            "scope": ":scope .col-two_fp > div h2",
            "extractors": [
                {
                    "name": "Title",
                    "query": {
                        "scope": ":scope"
                    }
                },
                {
                    "name": "TitleHtml",
                    "query": {
                        "scope": ":scope"
                    }
                }
            ],
            "tree": [
                {
                    "type": "pseudo",
                    "scope": ":scope ~ h3",
                    "extractors": [
                        {
                            "name": "Title",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        },
                        {
                            "name": "TitleHtml",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        }
                    ],
                    "tree": [
                        {
                            "type": "pseudo",
                            "scope": ":scope ~ h4",
                            "extractors": [
                                {
                                    "name": "Title",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                },
                                {
                                    "name": "TitleHtml",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                }
                            ]

                        }
                    ]

                }
            ]
        }
    ]
}

This is an object has 'tree' for each and I need to get the length and loop through it
Comment: Your question is bit confusing. Could you please elaborate more?
Comment: This might help https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects
Comment: I need to add nested for loops dynamically to tree level views
Answer: Assuming your object is stored in a variable $a, then $a['tree'] will give you the 'tree' array. You can use forEach to loop through it: $a['tree'].forEach() (no need to determine the length).
If you need the length, use $a['tree'].length.
Answer: May use recursion if expected tree length is not very large.

var data = {
    "uri": "https://www.fsa.go.jp/en/newsletter/index.html",
    "path": "D:\\SSN_INS\\JP--FSA--INS--NEWSLETTER\\",
    "pattern": "/.+/",
    "scope": "#main",
    "selector": "void",
    "extractors": [
        {
            "name": "TitleHtml",
            "query": {
                "scope": "title"
            }
        },
        {
            "name": "Title",
            "query": {
                "scope": "title"
            }
        }
    ],
    "tree": [
        {
            "type": "pseudo",
            "scope": ":scope .col-two_fp > div h2",
            "extractors": [
                {
                    "name": "Title",
                    "query": {
                        "scope": ":scope"
                    }
                },
                {
                    "name": "TitleHtml",
                    "query": {
                        "scope": ":scope"
                    }
                }
            ],
            "tree": [
                {
                    "type": "pseudo",
                    "scope": ":scope ~ h3",
                    "extractors": [
                        {
                            "name": "Title",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        },
                        {
                            "name": "TitleHtml",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        }
                    ],
                    "tree": [
                        {
                            "type": "pseudo",
                            "scope": ":scope ~ h4",
                            "extractors": [
                                {
                                    "name": "Title",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                },
                                {
                                    "name": "TitleHtml",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                }
                            ]

                        }
                    ]

                }
            ]
        }
    ]
}

function findObjectByLabel(node, key, childList) {
    if(!childList)
        childList = [];

    if(node.hasOwnProperty(key)) {
        node = node[key][0];
        childList.push(node);
        return findObjectByLabel(node, key, childList);
    }
    return childList;
}

var childList = findObjectByLabel(data, "tree");
for(var i=0; i < childList.length; ++i)
    console.log(childList[i]);
Answer: You need a recursive dig function?

function dig(obj, func){
  let v;
  if(obj instanceof Array){
    for(let i=0,l=obj.length; i<l; i++){
      v = obj[i];
      if(typeof v === 'object'){
        dig(v, func);
      }
      else{
        func(v, i);
      }
    }
  }
  else{
    for(let i in obj){
      v = obj[i];
      if(typeof v === 'object'){
        dig(v, func);
      }
      else{
        func(v, i);
      }
    }
  }
}
const data = {
    "uri": "https://www.fsa.go.jp/en/newsletter/index.html",
    "path": "D:\\SSN_INS\\JP--FSA--INS--NEWSLETTER\\",
    "pattern": "/.+/",
    "scope": "#main",
    "selector": "void",
    "extractors": [
        {
            "name": "TitleHtml",
            "query": {
                "scope": "title"
            }
        },
        {
            "name": "Title",
            "query": {
                "scope": "title"
            }
        }
    ],
    "tree": [
        {
            "type": "pseudo",
            "scope": ":scope .col-two_fp > div h2",
            "extractors": [
                {
                    "name": "Title",
                    "query": {
                        "scope": ":scope"
                    }
                },
                {
                    "name": "TitleHtml",
                    "query": {
                        "scope": ":scope"
                    }
                }
            ],
            "tree": [
                {
                    "type": "pseudo",
                    "scope": ":scope ~ h3",
                    "extractors": [
                        {
                            "name": "Title",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        },
                        {
                            "name": "TitleHtml",
                            "query": {
                                "scope": ":scope",
                                "exclude": "span:has(a)"
                            }
                        }
                    ],
                    "tree": [
                        {
                            "type": "pseudo",
                            "scope": ":scope ~ h4",
                            "extractors": [
                                {
                                    "name": "Title",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                },
                                {
                                    "name": "TitleHtml",
                                    "query": {
                                        "scope": ":scope",
                                        "exclude": "span:has(a)"
                                    }
                                }
                            ]

                        }
                    ]

                }
            ]
        }
    ]
}
dig(data, (v, i)=>{
  console.log({key:i, value:v});
});

It's similar to array_walk_recursive in PHP, if you're familiar. Of course, this function takes Objects whether they are instanceof Array or not.

Loop through an same object in js


What is Tanam in Music?

Question: What is Tanam in Indian music ?
Is tanam used in Cinema music ?
i.e After Pallavi of a song a piece of music playing it might be 8 bar or 16 bar etc. Is it Tannam ?
Comment: Looks like a type of improvisation, also spelled *tanam*: https://en.m.wikipedia.org/wiki/Ragam_Thanam_Pallavi
Answer: Tanam is one of the methods of improvising a raga(which is called manodharma) in carnatic music. There are various tanams like vadhya tanam, aja tanam, gaja tanam etc. Tanam comes after the raga but before the pallavi of a song. To sing a tanam one should have good hold on singing and experience. It is rarely being sung by any musician.
Answer: Thanam is a specific kind of improvisation in Carnatic music. It is rhythmic, but not bound by meter (Thalam). Tempo varies within the performance. Unmeasured pauses are allowed between phrases/sections.

After Pallavi of a song a piece of music playing it might be 8 bar or 16 bar etc. Is it Tannam ?

No, that would be an interlude.
Here's an example of Thanam:

What is Tanam in Music?


Sending HTTP request in JavaScript to get results from MongoDB

Question: I am running MongoDB in the REST mode and trying to get query results from the MongoDB server through HTTP request. The following is the simple code that I have written:

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

    <title>Connection</title>

    <button onclick="httpGet('http://127.0.0.1:28017/test/first/?limit=-1')" >
        Click
    </button>

But I am unable to get the response. Whereas when I copy and paste the URL in the address bar of the browser I get following as the response:
{
  "offset" : 0,
  "rows": [
       { "_id" : { "$oid" : "4d510086ce29000000007d5a" }, "date" : { "$date":60968917800000 } }
    ],

 "total_rows" : 1 ,
 "query" : {} ,
 "millis" : 0
}

Can someone help and tell me what could be the problem.
Answer: Is the page on which your code is running also loaded from 127.0.0.1 port 28017? If not, that's your problem, you're running into the Same Origin Policy.
If it is (both server and port are the same), I'd recommend using a relative URL, so your
httpGet('http://127.0.0.1:28017/test/first/?limit=-1')

becomes
httpGet('/test/first/?limit=-1')

Fundamentally, the code works: http://jsbin.com/awose3

Off-topic: I'd strongly recommend not using synchronous XHR calls (ajax requests). They lock up the UI of the browser while they're in process, and of course they can take a second or two (or ten) to run, during which the user experience is unpleasant to say the least. Instead, use an asynchronous call and a callback on onreadystatechange, like this (obviously, error handling and other complexities have been left out):
function httpGet(theUrl){
    //document.write(theUrl);
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.onreadystatechange = handleReadyStateChange;
    xmlHttp.send(null);

    function handleReadyStateChange() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          document.getElementById("response").innerHTML=xmlHttp.responseText;
        }
      }
    }
}

Live example

Off-topic 2: I'd suggest looking at a library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser quirks, simplify various things, and add a number of useful features so that you can concentrate on solving the actual problem you're trying to solve, rather than worrying about things like (random example) Safari mis-reporting the default selected value of an option, and Internet Explorer's habit of leaking memory on event handlers unless you chant, burn incense, and periodically get up and twirl three times as you write your code.
Comment: @aditya: No worries, glad that helped. Re the SOP: JavaScript code isn't allowed to load content via XHR from anywhere it likes, only from the same "origin" as the document in which the code is running. See the link for details. "Origin" is fairly strictly defined (the protocol [http / https], server, and port must all match). There are ways around it: [JSON-P](http://en.wikipedia.org/wiki/JSONP#JSONP) is a popular one, or if you can control both the server and the browser that the client will use, [CORS](http://www.w3.org/TR/access-control/).
Comment: Thank you for such a wonderful response.I did not completely get the first part of your message. I am a bit confused but I'll look into it and yes I am looking into jQuery and YUI for past couple of days. If you could please suggest me a source (apart from the Yahoo Developer Network) from where I could read about VUI it be great.
Comment: @aditya: (continuing) Re libraries: I don't have any other info on YUI, but as it's a Yahoo! project, the YDN is going to be your best source of info anyway. I would look closely at jQuery and the associated jQuery UI. It's free and open source, has good corporate sponsorship (and so there are people *paid* to work on the library), has incredible penetration in the community (read: lots and lots of people to help you), and works well. I am/was also a fan of Prototype, but the lack of a corporate sponsor has really hurt the project (in my view).
Comment: @Crowder: You replies had been really helpful. At the moment I am facing a situation which is something like this: the mongoDB interface is listening at port: 28017. So how will I been able to run the script on same port. Sorry for bothering you, I am new to all this.
Comment: @Crowder: I have read that JSON-P has some security concerns, is it true?
Comment: @aditya: I've never used MongoDB, but for this sort of thing you usually have two options: Have server-side code that queries MongoDB and returns the results to your client-side code (preferred), or have your web server proxy the MongoDB process on certain request URIs. So (for instance) requests starting with `/mongo` get passed on by the web server to the MongoDB process. The former is considerably more secure though; I mean, with the latter, if you just allowed requests and responses from the outside world to go to your and from your MongoDB process, you're opening up your DB to the world.
Comment: @aditya: Re JSON-P security concerns: If you're doing JSON-P from your *own* server (because of port issues or something), you're probably fine. When integrating JSON-P services from *other sites* into your site, it's definitely a security issue. JSON-P works by you loading JavaScript code from the other site and executing it, so if the other site sends you malicious script, you're in trouble, since the script runs with all the permissions your script does.
Comment: @Crowder [here](http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-an-introduction-to-yui/) is a basic tutorial on YUI which I found, this might prove to be useful.


Conteúdo da página fuindo fora do elemento pai

Question: Estou fazendo um site simples com a seguinte estrutura:

Título da página

Conteúdo da página...

Sobre mim

Conteúdo do painel sobre mim...

O objetivo é o seguinte: Eu quero que a área da div id=hello ocupe 100% do viewport quando o site carrega. A div vazia id=front-bg serve só pra colocar uma imagem de background que também expanda para o viewport inteiro. E o restante do conteúdo devia ser mostrado ao rolar a página. SÓ QUE pra colocar a altura da div id=hello como 100% eu precisei colocar height: 100%; em TODOS os elementos pais até o html.
O CSS é o seguinte:
.front-page {
    height: 100%;
}

.front-page main {
    margin-top: 0;
    padding-top: 40px;
    height: 100%;
}

#front-bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -2;
    width: 100%;
    height: 100%;
    background: url(img/landscape.png) center center no-repeat fixed;
    background-size: cover;
}

.front-page #hello {
    height: 100%;
}

.front-page .panel {
    position: static;
}

O que acontece é que, quando eu coloquei height: 100% no seletor .front-page, o painel com id=about fluiu bem pra fora da div class=front-page. Se eu tiro essa linha, o id=about flui abaixo do id=hello, dentro do viewport, que eu queria que aparecesse só ao rolar a página. E se eu deixo essa linha, o id=about flui fora da class=front-page sobreponto o footer que tem no fim da página.
Não sei o que faço pra resolver. Qualquer luz é muito apreciada!
Answer: Com o CSS vh fica bem tranquilo de resolver:

.front-page {
    height: 100%;
}

.front-page main {
    margin-top: 0;
    padding-top: 40px;
    height: 100%;
}

#front-bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -2;
    width: 100%;
    height: 100%;
    background: url(img/landscape.png) center center no-repeat fixed;
    background-size: cover;
}

.front-page #hello {
    height: 100vh;
}

.front-page .panel {
    position: static;
}

Título da página

Conteúdo da página...

Sobre mim

Conteúdo do painel sobre mim...

Para saber mais dá uma olhadinha AQUI.
Comment: Muitíssimo obrigada, Thiago. Pela solução e pelo artigo também. Só tive que tirar o `height: 100%;` do `.front-page` que deu certo, e também eliminou a necessidade de colocar `height: 100%;` em todos os elementos pais.


Getting a "bad system call (core dumped)" when using a message queue in C

Question: I'm trying to do a homework involving message queues and I'm getting "bad system call(core dumped)" when I try to do anything and I'm not sure why. Also when I use get_queue_ds() function it wouldn't compile for me but I assume that is because I'm using cygwin on windows. Any help would be appreciated or a link to similar code(searching for something like this didn't yield any results). Thank you.
<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MAX_SEND_SIZE 1024//Make sure I have comments

typedef struct mymsgbuf
{
    long mtype;                 /* type of message */
    long sender_id;             /* sender identifier */
    char msg[MAX_SEND_SIZE];    /* content of message */
}MSGBUFFER;

/* Function prototypes */
void send_message(int qid, MSGBUFFER *qbuf, long type, char *text);
void read_message(int qid, MSGBUFFER *qbuf, long type);
void remove_queue(int qid);
void change_queue_mode(int qid, char *mode);
void usage(void);

int main(int argc, char *argv[])
{
    key_t myKey;
    int   msgqueue_id;
    int qid;
    MSGBUFFER* qbuf;

    if(argc == 1)
        usage();
    else
        myKey = ftok("/cis370/lab5", 1);//Creates a unique key

    //Opens message queue
    qid = msgget(myKey, IPC_CREAT | 0660);
    if(qid == -1)
    {
        printf("Creating message queue failed");
        exit(1);
    }

    switch(tolower(argv[1][0]))
    {
        case 's': send_message(qid, qbuf, MAX_SEND_SIZE, argv[2]);
                  break;
        case 'r': read_message(qid, qbuf, MAX_SEND_SIZE);
                  break;
        case 'd': remove_queue(qid);
                  break;
        case 'm': change_queue_mode(qid, argv[2]);
                  break;
        default: usage();
    }
    return(0);
}

void send_message(int qid, MSGBUFFER *qbuf, long type, char *text)
{
    int length, result;
    length = sizeof (MSGBUFFER) - sizeof (long);
    result = msgsnd(qid, (MSGBUFFER *)qbuf, length, 0);
    if (result == -1)
    {
        printf("Send message failed\n");
    }

}

void read_message(int qid, MSGBUFFER *qbuf, long type)
{
    int result, length;
    length = sizeof (MSGBUFFER) - sizeof (long);
    result = msgrcv(qid, (MSGBUFFER*)qbuf, length, type, 0);
    if (result == -1)
    {
        printf("Messege read failed\n");
    }
}

void remove_queue(int qid)
{
    int result;
    result = msgctl(qid, IPC_STAT, 0);
    if (result == -1)
    {
        printf("Queue removal failed");
    }

}

void change_queue_mode(int qid, char *mode)
{
    /*struct msqid_ds tmpbuf;
    int result;
    //isn't working on cygwin
    //get_queue_ds(qid, &tmpbuf);

    sscanf(mode, "%ho", &tmpbuf.msg_perm.mode);

    result = msgctl(qid, IPC_SET, &tmpbuf);
    if (result == -1)
    {
        printf("Queue mode change failed");
    }*/

}

void usage(void)
{
    printf("USAGE:\tmsgqueue\t(s)end  <type>  <message>\n");
    printf("\t\t\t(r)ecv  <type> \n");
    printf("\t\t\t(d)elete\n");
    printf("\t\t\t(m)ode  <mode>\n");

    exit(0);
}
</code>
Comment: You need to learn how to [use a debugger](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/).
Comment: @DourHighArch My class mostly just uses gedit then tries to compile/run with terminal. What would be a good debugger for c?
Comment: gedit is an editor. If you use gcc for compiling you could use gdb for debugging.
Answer: Cygwin uses a special background service in order to implement the persistent XSI IPC. Check the documentation of Cygserver on how to configure and start it.
Comment: Would this most likely be the reason it is failing or just the get_queue_ds()? If it's the cause of it all not working I can use my schools computers to make sure it runs.
Comment: The source code of `get_queue_ds()` is [here](http://www.tldp.org/LDP/lpg/node36.html). It uses `msgctl` which will fail under Cygwin if Cygserver is not running.


Usar PHP WebSocket Ratchet online

Question: Estou tentando usar o Ratchet para criar WebSockets em PHP em um site que possuo. Quando fiz os testes (localhost) tudo funcionou perfeitamente, mas quando tento colocar online, ele não executa a conexão. Lendo mais a respeito do assunto, vi que seria necessário mudar o ip para ser o do servidor - ou usar a referência correta. O que me levou a este código final:
var socket = new WebSocket('ws://meusite.com.br:8000');

Porém quando acesso o site, após um certo tempo, recebo essa mensagem:

failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT

O arquivo de servidor ficou com este código:
require __DIR__ .'/../vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\http\HttpServer;
use Ratchet\WebSocket\WsServer;

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ), 2000, '0.0.0.0'
);
$server->run();

Estou utilizando composer também para o gerenciamento do pacote Ratchet.
Não sei o que pode estar acontecendo para não haver a conexão ou o que deixei passar, mas este processo não está funcionando online, somente em localhost.

Editando a pergunta, e já adicionando a resposta ao comentário, eu possuo acesso SSH sim, inclusive quando tento iniciar o script conforme feito em localhost
php bin/server.php

O SSH apresenta o seguinte erro:

Fatal error: Class 'Ratchet\http\HttpServer' not found in /bin/server.php on line 10

Nota: A aplicação final não vai ser um chat, estou fazendo assim apenas por estar seguindo um tutorial. O objetivo é que apenas haja a troca de mensagens para informar que um novo pedido foi feito, ou que chegou uma nova ordem de serviço, etc...
Comment: Mas você tem acesso SSH ao teu servidor pra disparar a aplicação, ou tem algum sistema de webapp pra configurar um PHP como aplicação? O websocket não roda diretamente no Apache ou Ngnix, ele é independente, não irá funcionar se acessar via `http://site/script.php`, a não ser que use o `exec();`, no entanto tenho quase certeza que será necessário privilégio pra iniciar o WebSocket.
Comment: @GuilhermeNascimento havia esquecido desta etapa, editei a pergunta. Mas sim, eu possuo acesso e tentei a inicialização conforme feito em localhost, mas ainda assim ele apresenta um erro.
Comment: Rodou o `composer update`? Me diz uma coisa o correto não seria isto `require __DIR__ .'/vendor/autoload.php';`? Coloca a estrutura das pastas
Comment: @GuilhermeNascimento Acredito que o require seja como está, pois partindo da raiz possuo 2 pastas `bin/server.php` e `vendor/autoload.php`. Dentro do vendor também existem outras pastas como a do proprio Ratchet, composer, etc.. Mas eu não rodei o composer update não, e quando tentei isso agora, apresentou erro informando que não havia permissão ou não estava em diretório que possuo permissão (algo assim)
Answer: Troque:
use Ratchet\http\HttpServer;

Por:
use Ratchet\Http\HttpServer;

Porque isto ocorre:
No Windows os arquivos são case-insentive, quando você roda:
use Ratchet\http\HttpServer;

Ele encontra no Windows normalmente isto (veja que Http começa com a letra H em maiúsculo):
./src/Ratchet/Http/HttpServer.php

Já sistemas Like-unix, como linux usam o sistema de arquivos como case-sensitive, então no momento que você usa use Ratchet\http\HttpServer; ele procura isto:
./src/Ratchet/http/HttpServer.php

Mas no servidor o arquivo esta assim:
./src/Ratchet/Http/HttpServer.php

São diferentes.
Comment: Show. Uma parte resolveu. Consegui rodar o SSH e não apresentou erro algum.. Porém a conexão ainda não é estabelecida. Após um certo tempo ele volta a apresentar o erro de time out que comentei na questão.
Comment: @CelsomTrindade liberou a porta 8000? Talvez não tenha que rodar via SSH e sim configurar no dashboard, que tipo de servidor usa? Seria o AWS?
Comment: É, não lembro de ter feito nada para liberação da porta não... Você quis dizer qual serviço de hospedagem eu uso? é isso?
Comment: @CelsomTrindade isso, qual serviço de hospedagem, porque dependendo não tem como liberar. Agora se você tiver controle "total", como é no AWS.
Comment: No momento uso www.weblink.com.br
Comment: @CelsomTrindade Nossa :D ... esse servidor é bom? Ele cai muito? O Mysql é estavel? Cara fiquei surpreso contas de email ilimitados... Sobre o seu problema, então aparentemente não tem como rodar um WebSocket, terá que conversas com o suporte pra ter certeza, mas parece que ali não tem esta opção.
Comment: Cara, eu gerencio uma agência de site e hospedo meus clientes ali. Nunca tive nenhuma reclamação, nunca tive problema com suporte, nada do tipo.. Sempre que acessei meus serviços, sempre estiveram online. hahahaha Sobre a questão, já estou em contato com eles para verificar o que pode estar acontecendo, pois ao tentar conexão em 80 ou 443 me da acesso negado e qualquer outra porta da erro de time out.
Comment: @CelsomTrindade Porta 80 e 443 é do Apache, não tem como rodar um socket nelas, elas já estão em uso. Fora que mesmo que inativasse o Apache e roda-se o script ainda sim poderia não funcionar.
Comment: Pois é, são as únicas que retornam algum erro. Todas as demais rodam o script, mas não efetua conexão, sempre aponta o erro. Alguma dica ou sugestão de alternativas?
Comment: Então é como eu disse, Websocket é uma coisa, sites Http é outra, não tem como misturar ambos. Agora existem duas saidas, a primeira é trocar de serviço, mas se ler a doc do Ratchet talvez seja possivel usar sem ser por websocket, veja esse exemplo: http://socketo.me/docs/wamp
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/42030/discussion-between-celsomtrindade-and-guilherme-nascimento).

Usar PHP WebSocket Ratchet online


Java - Using multiple threads to read/write to memory mapped buffers (MappedByteBuffer)

Question: I have an application where a lot of File I/O (both reads and writes) takes place. I know that using multiple threads to do File I/O is not a good solution as it can degrade the performance (I have no control over the kind of disk which is used). So I ended up dedicating one thread for all File I/O.
Can MappedByteBuffer be of any use in my case? I know that MappedByteBuffer is a memory area which is mapped to a file by the OS, can I leverage multiple threads to do I/O operations on different memory mapped buffers efficiently? Does disk head seek times still matter when multiple threads are mapping different files to different memory buffers? Is consistency guaranteed in such cases? Are there any benchmark results available for such cases?Thank you all in advance.
Comment: @skytreader thanks for pointing that out, I should have used 'MappedByteBuffer' in the description.
Comment: I can probably find as many that say it is better, such as this http://stackoverflow.com/a/1239987/360211 The key is to take no ones word for it and profile. Personal experience has been that it improves overall throughput, it's not all about head seek times, there are other delays involved which are minimised when done in parallel.
Comment: The only thing one can say for sure is "it depends". Memory mapped files do have some advantages in some cases - they will cost you time in others. Also to some degree relevant: http://www.ibm.com/developerworks/java/library/j-zerocopy/ the part about less context switching should apply to memory mapped files as well. If you want a proper answer for your usecase, implement all the methods, profile  & optimize until you have the best.
Comment: "I know that using multiple threads to do File I/O is not a good solution as it can degrade the performance" What's that based on?
Comment: The disk's head needs to keep seeking the next position to read and when multiple threads do that the head will be bouncing between different disk areas inefficiently.
Comment: http://stackoverflow.com/a/10397184/1878313 http://stackoverflow.com/a/1034860/1878313 are some relevant posts to support that multiple threads to do File I/O is not a good solution when one has no control over the type of disk used.
Comment: Out of curiosity, the way you mentioned MemoryMappedBuffer makes it look like a specific class. However, searching the default JDK docs does not yield anything for MemoryMappedBuffer. What class/library are you planning to use in particular?
Comment: @zapl thanks for the reply, the only option I see now is to profile and benchmark results myself and put them in public domain for the interested.
Answer:
Can MappedByteBuffer be of any use in my case?

Refering to the JavaDoc a MappedByteBuffer should give you no performance advantages in contrast to a ByteBuffer. You could even end up with some unexpected changes during your runtime

The content of a mapped byte buffer can change at any time, for
  example if the content of the corresponding region of the mapped file
  is changed by this program or another.

I know that MappedByteBuffer is a memory area which is mapped to a file by the OS, can I leverage multiple threads to do I/O operations on different memory mapped buffers efficiently?

Except you know better than your OS or the VM how to read and write your data efficiently this is not the case.

Does disk head seek times still matter when multiple threads are
  mapping different files to different memory buffers?

The head still has to seek its position. Unless you have different disks and you do only disk IO it is useless to have more than one thread. In case you have some redundancy reading your data multithreading should be useful, because your OS will cache "hot" data.

Is consistency guaranteed in such cases?

Not really sure, what you mean, but you have to make sure accessing your ByteBuffer is somehow synchronized, because it is no threadsafe data structure.

Are there any benchmark results available for such cases?

Last year I did some sort of benchmarking, working with multiple buffers. Long story short, it really depends on the use case, the operating system and your hardware. Depending on how important this is I would recommend you do your own benchmarks. The only constant I remember is that you get the best performance writing data blocks of your disk segment size... which is somehow obvious ;-)
Comment: thanks for the answer, there is still lot of confusion on the topic of file system accessed from multiple threads, some conflicting answers here didn't help me either. As far as Memory mapped buffers are concerned , I would do some bench marking myself, it would be helpful if you can share your results as well.
Answer: So long as you're not attempting to have more than one thread write to the same file at a given time, there's no problem with doing file I/O from different threads. Using NIO, the FileSystem implementation is way better than you could ever hope to be at managing disk writes and resources. Disk writes are buffered and asynchronous by default in Java, so there's no need to do something as convoluted as making a single thread do all your I/O and writing into memory buffers - this is almost exactly what OutputStreams writing to disk do already, but the native JVM will do it more efficiently than you could.
In fact, file I/O operations can benefit substantially from multithreading. Different threads can be processing read information while other threads are reading, and it can even sometimes be faster to read or write a few files in parallel than sequentially.
Comment: "Different threads can be processing read information while other threads are reading" I was concerned about "different threads reading/writing to disk" performing badly than a single thread doing this. It would be helpful if you can share any bench marked results to support this.
Answer: If you're suggesting that you want to map separate regions of the same file to different MappedByteBuffers, and want to compare writing the file that way to single-threaded, blocking, unbuffered writes to the same file, I'm pretty sure that you'll be very happy with the results from a performance perspective.
You should remember that when writing to MemoryMappedBuffers, you are not necessarily writing to the disk when you request to perform a write. The OS is responsible for deciding which MemoryMappedBuffers correspond to RAM and when that RAM is written back to disk; typically that means that while writing, that file or portion of a file is kept in RAM, and the file is written back to disk at the discretion of the OS, which may mean it's kept in memory until it looks like you're done writing it, and then moved to disk, or that it's kept in RAM until the RAM it's taking up is needed for something else, unless you force() it to be written out to disk.
I think, from a performance perspective, it depends a lot on what your goal is: do you want your algorithm that does the writing to finish faster, in which case the memory mapped regions may well be a good option, as the algorithm can finish before the file finishes writing to disk, or do you want the file copied to the disk faster, in which case it's hard to say: if you are able to break up the file into nice large chunks that can be efficiently written to disk, and if the OS is able to recognize when you're done with a region and only writes each region back to disk once during the process, it may be more efficient.
On the other hand, if your current implementation is writing to disk very efficiently, i.e. if you are successfully arranging the writes to the file efficiently, such that there is little seeking necessary (if using hard disks), and the writes are buffered appropriately, so that you aren't forcing the OS to write small bits of the file all the way to disk before permitting it to have the next bit of the file, or writing bytes at random (which even solid state drives do not like, since they must write a certain sized region, and cannot write single bytes individually), then it's entirely possible that your current strategy would finish writing the file to disk faster -- assuming that getting the file onto the physical disk as fast as possible is the goal.
If you want to know how much room for improvement there is, you could compare your speed with the speed of a hard-drive performance test on your system, that should be able to benchmark the limit on your throughput to the disk; if that's significantly faster than your current implementation, either there's room for improvement in your writing strategy, or it's generating the data, rather than writing it, that's taking the time.
To test the latter, you could try having your algorithm write to ByteBuffers that are not memory mapped; with no file I/O, you can benchmark the speed of your algorithms independently of the disk.