Django Doesn't Serve STATIC_ROOT in DEBUG

Question: I'm using Python 3.5 and Django 1.10 to run a development server:
./manage.py runserver 0.0.0.0:8000

In my settings.py I have:
DEBUG       = True
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL  = '/static/'

And an app directory, with a static subdirectory for its static files:
proj/
    proj/
        ...
    app/
        static/
            a.txt
        ...
    static/
        b.txt

Pretty standard.
However: Django doesn't serve the STATIC_ROOT when DEBUG = True. It returns app/static/a.txt for /static/a.txt alright, but not static/b.txt for /static/b.txt.
Changing settings.py to read:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Works - but then I have to comment out STATIC_ROOT (otherwise Django complains it can't be in STATICFILES_DIRS).
Now, I can't just "use a different external static directory", e.g. static2, because I'm using django-sass-processor, which compiles .sass files into .css files, and puts these .css files in the STATIC_ROOT (which, as I've said, is inaccessible).
Things I've tried:

Settings up NGINX to serve that directory (like in a production environment). Works, but there just has to be another way.
Configuring django-sass-processor to write the .css files into said "different external static directory", e.g. static2, and including it in STATICFILES_DIRS. Again, works, but it just can't be that complicated!
Manually adding static files URLs in urls.py:
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

This one was quite a trip, so I thought I'd share it to save other people the trouble: it turns out that Django does that anyway, and actually overwrites my URLs - but it includes, as I've said, only my apps' static directories and those in STATICFILES_DIRS.
I even changed DEBUG to False and removed the if - but that didn't work as well, because then the django.conf.urls.static.static function actually returns an empty list. So, I implemented it myself using django.views.static.serve, and it finally worked, but again - it doesn't make sense I have to turn off debugging and manually implement serving static file.

Update

If you're working with django-sass-processor and running into similar problems, they've actually provided a solution I just noticed in their documentation: a special static finder you can add in your settings.py like so:
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'sass_processor.finders.CssFinder',
]

(The first two are Django's default finders, so when you override this configuration you should include them manually).
But even now, for anything other than .css files, the STATIC_ROOT is actually the only static directory that is inaccessible via /static/, which I find pretty odd. So, I'd still like to solve (or at least understand...) it.
Comment: I'm pretty sure there is a simple issue of priority. I tried added `static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)` to urlpatterns, and I removed `django.contrib.staticfiles` from INSTALLED_APPS. This way, files in `STATIC_ROOT` are accessible, but not files in `myapp/static`. If I add `django.contrib.staticfiles` to `INSTALLED_APPS`, the opposite happens.
Comment: I've been working with django for almost ten years now. I always have trouble setting up static files.
Answer: At first glance it seems very strange that Django doesn't serve files from STATIC_ROOT, but it makes sense when you consider the workflow Django intends for static files. Django expects that you bundle static files alongside apps and you save project-level static files in a separate directory that is checked into version control. Then, when you run manage.py collectstatic the STATICFILES_FINDERS are used to gather up all the files into a single directory (which should not be in version control) so they can be deployed to AWS S3 or whatever.
So the staticfiles finders have two jobs:

find a file via path, used for DEBUG mode static file serving
list all of the available files, used for collectstatic

If you were able to include STATIC_ROOT in your STATICFILES_DIRS then the collectstatic command would probably get stuck in a loop. Also, the Django developers don't intend for you to save files in STATIC_ROOT since it shouldn't be checked into version control.
However, there's times when you actually do want to serve files from STATIC_ROOT. In my case, I have a Celery task that creates thumbnails of uploaded images and saves them to the static files storage. In production that ends up saving on AWS S3 where it can be served.
So, if you have a valid use case for serving files from STATIC_ROOT just define your own file finder and add it's path to STATICFILES_FINDERS:
from django.contrib.staticfiles.finders import BaseFinder
from django.contrib.staticfiles.storage import staticfiles_storage

class StaticRootFinder(BaseFinder):
    """
    For debug mode only. Serves files from STATIC_ROOT.
    """
    def find(self, path, all=False):
        full_path = staticfiles_storage.path(path)
        if staticfiles_storage.exists(full_path):
            return [full_path] if all else full_path
        return []

    def list(self, ignore_patterns):
        return iter(())

Comment: This exactly the answer I was looking for because it explains the reason for NOT serving the files from STATIC_ROOT when in debug a definite +1 from me. I was coming to same conclusion myself and just needed to see someone else say the same thing!


Help in proving this inequality

Question: $a,b,c \in R^+: abc=1$
Prove that $1+\frac{3}{a+b+c}\ge\frac{6}{ab+bc+ca}$
I tried replacing the RHS using GM-HM
To P.T
$LHS\ge 2GM(ab,bc,ca)=2$
But this means that $3 \ge a+b+c$
which is clealy false by AM-GM
How to proceed I don't know.
I tried assigning $a,b,c$ as the roots of a cubic but this also didn't work
Comment: \ge will give you $\ge$.
Comment: Thanks it works
Answer: By AM-GM $$1+\frac{3}{a+b+c}\geq2\sqrt{\frac{3}{a+b+c}}.$$
Id est, it's enough to prove that
$$2\sqrt{\frac{3}{a+b+c}}\geq\frac{6}{ab+ac+bc}$$ or
$$(ab+ac+bc)^2\geq3(a+b+c)abc$$ or
$$\sum_{cyc}c^2(a-b)^2\geq0.$$
Comment: @Yes it's me Because any symmetric polynomial we can write as sum of squares. I tried to make it and it turned out.
Comment: @Yesit'sme It's also known as [Newton's Inequalities](https://en.wikipedia.org/wiki/Newton%27s_inequalities). Alternatively, with $ x = ab, y = bc , z = ca$, we know that $ ( x+y+z)^2 \geq 3 (xy + yz + xx ) \Rightarrow (ab+bc+ca)^2 \geq  3 (a+b+c)(abc)$.
Comment: Can you please describe how you got the motivation to go to the last line from the previous line?

Help in proving this inequality


Dúvida sobre condicional (if) em função

Question: Tenho um conjunto de 300 e poucas planilhas no qual temos que criar uma função com 3 argumentos: o diretório onde estão as planilhas, a variável que será analisada e a quantidade de arquivos que se deseja analisar.
No caso em questão temos duas variáveis de interesse, a concentração de sulfato e a concentração de nitrato.
Eu consegui equacionar a função para dois parâmetros, no qual me retornará a média de sulfato e separadamente a média de nitrato.
Segue o código:
pollutant_sulfate<-function(directory, ID = 1:332) {
    files_list <- list.files(directory, full.names=TRUE)
    data <- data.frame()
    for (i in ID) {
            data <- rbind(data, read.csv(files_list[i]))
    }
    subset_sulfate<- subset(data$sulfate, data$sulfate > 0)
    mean (subset_sulfate)
}

pollutant_nitrate<-function(directory, ID = 1:332) {
    files_list <- list.files(directory, full.names=TRUE)
    data <- data.frame()
    for (i in ID) {
            data <- rbind(data, read.csv(files_list[i]))
    }
    subset_nitrate<- subset(data$nitrate, data$nitrate > 0)
    mean (subset_nitrate)
}

Agora o 3º argumento da função que seria a determinação de qual variável eu desejo analisar (sulfato ou nitrato) eu estou com dificuldades. Pensei na construção de um condicionante if. Escrevi um código que contem erros e não consigo entender qual o problema. Segue o código em questão:
mean_pollutant1<-function(directory, pollutant, ID=1:332){
    files_list <- list.files(directory, full.names=TRUE)
    data <- data.frame()
    for (i in ID) {
        data <- rbind(data, read.csv(files_list[i]))
    }
    if (pollutant == sulfate){
        subset_sulfate<- subset(data$sulfate, data$sulfate > 0)
        mean (subset_sulfate)
    }
    if (pollutant == nitrate){
        subset_nitrate<- subset(data$nitrate, data$nitrate > 0)
        mean (subset_nitrate)
    }
}

Quando eu tento chamar a função recebo msg de erro:

mean_pollutant1("specdata", sulfate, 1:2)
  Error in mean_pollutant1("specdata", sulfate, 1:2) :
    object 'sulfate' not found

Alguém pode me ajudar a contornar o problema?
Comment: acho que no if vc tem que colocar entre aspas: `if (pollutant == "sulfate")....if (pollutant == "nitrate")`e o mesmo quando for chamar a função: `mean_pollutant1("specdata", "sulfate", 1:2)`
Comment: EU acho que você ainda não criou um as variáveis `sulfate`e `nitrate`, se forem variáveis. ou como o Daniel disse, se são _strings_ coloque aspas.
Comment: Galera, problema parcialmente resolvido! Muito obrigado! Realmente eu tenho que inserir como string. Todavia, quando dou entrada na função em "nitrate" eu consigo a resposta correta. Todavia, na entrada "sulfate" que é o primeiro if a resposta da função é uma linha em branco. Não há nenhuma notificação de erro, apenas a linha de comando limpa. Alguma sugestão?
Comment: isso quer dizer que nas planilhas não tem nenhum `sulfate > 0`. a princípio o código está correto. Ou então teve algum erro de ortografia ao escrever 'sulfate'.. veja que se vc colocar `pollutant = 'x'` vc também receberá uma linha vazia
Comment: Na planilha há valores maiores que 0 para sulfato. E no caso qualquer string diferente de "nitrate" ele resulta em uma linha em branco. o.O
Comment: Isso acontece porque com qualquer string diferente a função não entra em nenhum dos if's e então retorna vazio. será que na planilha não tem um espaço a mais no nome da coluna, ou algo do tipo? Pq aparentemente o problema é que não está entrando em nenhum if quando vc usa a string "sulfate".
Comment: Gente, um amigo me ajudou. Não sei responder o porque do motivo, mas trocamos o segundo if por um else if e deu certo! Sabe Deus porque dois if's seguidos estavam resultando em erro! Obrigado a todos que me ajudaram!
Comment: @DanielFalbel acho que você poderia colocar como resposta seu primeiro comentário. José Ferraz, sempre é interessante colocar um pequeno exemplo da base de dados para reproduzirmos o seu erro. http://meta.pt.stackoverflow.com/questions/824/como-criar-um-exemplo-m%C3%ADnimo-reproduz%C3%ADvel-em-r/825#825
Answer: O problema do seu código é que você está fazendo uma comparação com objetos que não existem.
Em if (pollutant == sulfate), o objeto sulfate não existe. Você pode resolver o problema de duas maneiras:

Antes do ifcriar o obejto, atribuindo o valor de uma string, ou seja, colocar antes do if um sulfate <- 'sulfate'
Comparar direto com a string 'sulfate', if (pollutant == 'sulfate').

Isso você deve fazer para os dois if's.
O outro problema do seu código é que está faltando um return. No R, é possível retornar valores de uma função sem usar o return, mas apenas se o valor retornado for o último comando da função.
No seu caso, o último comando da função é
if (pollutant == 'nitrate'){
    subset_nitrate<- subset(data$nitrate, data$nitrate > 0)
    mean (subset_nitrate)
}

Por isso qualquer string diferente de 'nitrate' retornará NULL. Para resolver isso basta colocar um return() em cada if. Portanto, a função correta seria:
mean_pollutant1<-function(directory, pollutant, ID=1:332){
    files_list <- list.files(directory, full.names=TRUE)
    data <- data.frame()
    for (i in ID) {
        data <- rbind(data, read.csv(files_list[i]))
    }
    if (pollutant == 'sulfate'){
        subset_sulfate<- subset(data$sulfate, data$sulfate > 0)
        return(mean(subset_sulfate))
    }
    if (pollutant == 'nitrate'){
        subset_nitrate<- subset(data$nitrate, data$nitrate > 0)
        return(mean (subset_nitrate))
    }
}

Claro que existem outras saídas para evitar ter que usar o return, mas essa é a que menos modifica o seu código original.

Dúvida sobre condicional (if) em função


Change date on icon click event

Question: I'm trying to create a custom block that display the current date (Only Day of the month, 2 digits with leading zeros and A full textual representation of the day of the week) using the tocken module.
Now my problem is how to change the date when the next, prev icon is cicked?
For example: Today is saturday the 05th. When i click next, i get sunday the 6th. And when i click prev, i get friday the 04th.
Maybe this can be possible using javascript or php.
Answer: There are two ways to go about this.
Pure JS
You can send the date shown to the JavaScript either via drupal_add_js or as a data attribute and let the JavaScript manage the date changes. You would need to change the current date +/- 1 when clicking on a button and figure out the name of the day and the day number of the day and display that. This should be relative simple to do.
AJAX
You can let the use AJAX and send the selected date to a custom menu callback which returns the markup for the new date.
Of the two solutions I would prefer the pure JS version. The Ajax version is more complex to implement and will generate a bigger load on the webserver. It could be a nice solution if you want to do advanced theming and don't want to place that logic in the JS (like weekends / holidays etc are displayed in different styles)

Change date on icon click event


jQuery TABS is not working under new ASP .NET MVC4 project

Question: What I did is

I have create new ASP .NET MVC4 project.
I have used http://jqueryui.com/tabs/ example code

So I have got this:
_Layout.schtml

    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
 @*   @Styles.Render("~/Content/css")
      @Scripts.Render("~/bundles/modernizr")*@

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />

and Index.cshtml

Nunc tincidunt

Proin dolor

Aenean lacinia

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

And it is not working at all.

Any help?
Comment: Is this your entire _Layout.cshtml?  It looks like you are missing the body section with the `@RenderBody()` call.
Comment: @scott-pascoe I have the body there. It is by default.
Answer: If your _Layout.cshtml looks like:

    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)

The problem  is the @Scripts.Render(~/bundles/jquery") since you are already including it at the top of the page.
UPDATE
A cleaner approach using the tools already included in MVC4 is:
_Layout.cshtml
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Scripts.Render("~/bundles/modernizr")

    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @RenderSection("scripts", required: false)

Index.cshtml
... Add at the bottom...
@section scripts
{

}

I found this solution by looking at the App_Start\BundleConfig.cs file.
Also, you will probably want to run the NuGet Update-Package in your Package Manager Console so that you get current versions of the jquery stuff.
Comment: Thanks, been scratching my head all morning on this one after picking up someone elses project to finsih off.


How to avoid Multiple Child forms shown in MDIParent C# Win Forms

Question: I want to avoid my child form from appearing many times when a user tries to open the child form which is already open in MDIParent.  One way to avoid this is by disabling the Controller (in my case BUTTON) but I have given a shortcut key (Ctrl+L) for this function as well. So if the user types Ctrl+L, the same child Form opens and I can see two child forms are in MDI.
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmWebLeads formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

I want to avoid this.  How can I do this?

In the image you can see that a child form Name  Online Leads  is opened twice as the user opened first time using Menu (LEADS) and second time by Shortcut key.  I don't want this to happen. If the form is already opened it should avoid opening another same form ... How to do this?
Answer: the way i usually do it if i am only supposed to have one open is something like:
//class member for the only formWeblead
frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (formWebLead == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
    }

    formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    formWeblead.Show();
}

Answer: Set this in your form main() function
    InitializeComponent();
     this.WindowState = FormWindowState.Maximized;
     this.ShowInTaskbar = true;

 from_login login = new from_login();
                login.MdiParent=this;
                login.Show();
                pmsnrr.pmsmain = this;

and this is the code the goes inside your menu strip slick event
if (this.ActiveMdiChild != null)
            this.ActiveMdiChild.Close();
            frm_companymaster company = new frm_companymaster();
            company.MdiParent = this;
            company.WindowState = FormWindowState.Normal;
            company.Show();

Answer: I personally prefer a generic implementation:
private void ShowOrActivateForm<T>() where T : Form
        {
            var k = MdiChildren.Where(c => c.GetType() == typeof(T)).FirstOrDefault();
            if (k == null)
            {

                k = (Form)Activator.CreateInstance(typeof(T));
                k.MdiParent = this;
                k.Show();
            }
            else
            {
                k.Activate();
            }
        }

Then you can just use it like this:
ShowOrActivateForm<myForm>();

Where myForm is the TYPE of the form you want to create
Comment: I'd imagine any additional overhead would be negligible. It only runs when you try and open a form, so unless you are opening tons of forms at once I can't imagine it would have any impact on your application performance or user experience.
Comment: Nice. Cool solution. Thanks for the feedback. Glad I could share something that someone else could use :)
Comment: I like this approach. It's much more scalable than creating empty fields for each child. +1 for generics. I'd be interested to know if there's any noticable additional overhead for the use of reflection; albeit at a very high level.
Comment: That's good. I suppose in a scalable application, you'd use your IoC Container anyway, instead of relying on the `Activator`. I've used this method with RadDock now, to keep track of MDI Children, and Tool Windows. I've taken the `Show()` and `Activate()` out, and returned the raw form as type `T`, so that it can be docked where needed.
Answer: private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    formWeblead formWeblead = null;
    if ((formWeblead = IsFormAlreadyOpen(typeof(frmWebLeads)) == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }
}

public static Form IsFormAlreadyOpen(Type FormType)
{
   foreach (Form OpenForm in Application.OpenForms)
   {
      if (OpenForm.GetType() == FormType)
         return OpenForm;
   }

   return null;
}

Comment: I'm sorry, but I don't have that same issue. I'm running .NET 3.5 on VS 2008. I can close and open only one form repeatedly.
Comment: i am using .net 3.5   and VS 2010 Ultimate ,Windows Xp ..is this cousing error
Answer:     frmWebLeads formWeblead;

    bool isformWebleadOpen =false;

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if(isformWebleadOpen == false)
      {
       formWeblead = new frmWebLeads();
       isformWebleadOpen =true;
       formWeblead.Closed += formWeblead_Closed;
       formWeblead.Show();
      }
   }

   void formWeblead_Closed(object sender, EventArgs e)
   {
     isformWebleadOpen = false;
   }

Answer: Fists time when you open the form from menu, the variable frmRep is null
frmReportes frmRep = null

...so I add another "if" inside the first "if" to validate my form is visible, because I have another forms, then if its not visible I make an instance and show the form, but if is visible I just use Activate()
    private void rToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (frmRep != null)
        {
            if (frmRep.Visible == false)
            {
                frmRep = new frmReportes();
                frmRep.MdiParent = this; frmRep.Show();
            }
            else
            {
                frmRep.Activate();
                return;
            }
        }
        else
        {
            frmRep = new frmReportes();
            frmRep.MdiParent = this;
            frmRep.Show();
        }
    }

Answer: // Implementation of the below class in your MDI Parent
private void openToolStripMenuItem_Click(object sender, EventArgs e) {
            if (SingletonForm.Exists) {
                return;
            } else {
                m_openToolStripMenuItem.Enabled = false;

                SingletonForm form = new SingletonForm();
                form.FormClosed += new FormClosedEventHandler(
                    delegate(object _sender, FormClosedEventArgs _e) {
                        m_openToolStripMenuItem.Enabled = true;
                    });
                form.MdiParent = this;
                form.Show();
            }
        }

// SingletonForm Class
    using ...
    using System.Threading;

    namespace SingletonForm {

        public partial class SingletonForm : Form, IDisposable {
            static private readonly string m_mutexName = "SingletonForm.SingletonForm";
            private Mutex m_mutex;
            private bool m_disposed;

            public SingletonForm() {
                m_disposed = false;

                // Check to see if there is already a running instance...
                bool owned;
                m_mutex = new Mutex(true, m_mutexName, out owned);
                if (!owned) {
                    // Already running, get out...
                    Close();
                    return;
                }

                InitializeComponent();
            }

            ~SingletonForm() {
                Dispose(false);
            }

            static public bool Exists {
                get {
                    bool owned;
                    using (new Mutex(false, m_mutexName, out owned)) {
                        return !owned;
                    }
                }
            }

            // IDisposable Members
            // --------------------------------------------------------------------------
            #region IDisposable Members
            new public void Dispose() {
                Dispose(true);

                // Use SupressFinalize in case a subclass of this type implements a finalizer.
                GC.SuppressFinalize(this);
            }
            #endregion  // IDisposable Members

            ///
            /// Note: Comment out the Dispose(bool disposing) implementation in your
            /// SingletonForm.Designer.cs
            ///
            /// <param name="disposing">true if we are disposing.</param>
            protected override void Dispose(bool disposing) {
                if (disposing && (components != null)) {
                    components.Dispose();
                }

                base.Dispose(disposing);

                // If you need thread safety, use a lock around these
                // operations, as well as in your methods that use the resource.
                if (!m_disposed) {
                    if (disposing) {
                        // Code to dispose the managed resources held by the class here...
                        if (m_mutex != null) {
                            m_mutex.Dispose();
                            m_mutex = null;
                        }
                    }

                    // Indicate that the instance has been disposed.
                    m_disposed = true;
                }
            }
        };
    };

Would have been nice to use semaphores instead in order to allow 1-n instances to exist.
Answer: The easiest way is to keep a reference to the child form, and only spawn a new one if it doesn't already exist. Something like this:
class ParentForm : Form {
    frmWebLeads formWeblead = null;

    //...

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if(formWeblead != null) return;
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

}

You also need code to set formWeblead to null when you close it, but I'm sure you can figure that part out :)
Comment: I don't think I would use the Leaving event, as that's a focus thing. Instead, using the child form's Closing event, which triggers when you close it.
Comment: @ Mike Caron thanks for your Code. The Last Part you left for me creating some confusion, have doubt in that the declared formWeblead i n MDIParent  and i thinking to set formWeblead =null using  frmWebLoad  leaving Event using Child to parent access ,is it fine !! ??? or is there any best method available
Comment: @Mike This leaves some TODO regarding the menu item that calls the click event; I like to disable the menu item that created the form to avoid confusion to the user e.g. "I am clicking 'open' and nothing happens".
Comment: @Gangelo: Well, sure. But that's outside the scope of the question. It's not hard to figure out where to insert the `.Enabled = false` and `.Enabled = true` code. Or, even better, the `formWeblead.Focus()` code.
Answer: Here is the "Method" that I created for Calling open only one form when u click on Menu in MDIParent. Hope this "Method" can help you!
Usage: On Even ToolStripMenuItems.
Form1 frm1 = new Form1();
CheckActiveChildForm(frm1,"myForm");

//myForm is the Text of Form1
private void CheckActiveChildForm(Form FormControl, string FormExists)
{
    int h = 0;
    if (MdiChildren.Count() == 0)
    {
        //Form2 childF = new Form2();
        FormControl.MdiParent = this;
        FormControl.Show();
    }

    if (MdiChildren.Count() > 0)
    {
        for (int i = 0; i < MdiChildren.Count(); i++)
        {
            if (MdiChildren.ElementAt(i).Text == FormExists)
            {
                h = 1;
            }
        }
    }

    if (h == 0)
    {
        FormControl.MdiParent = this;
        FormControl.Show();
    }
}

Answer: You could check current open forms to achieve that:
if (Application.OpenForms.Count == 1) {
    ReportProductDetails Report9 = new ReportProductDetails();
    Report9.MdiParent = this;
    Report9.Show();
    Report9.Activate();
}
else {
    MessageBox.Show("Sorry!Close the All the Exist Form,Before open this Form", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Answer: I use this solution, with a little trick
frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (formWebLead == null || formWebLead.isAccessible == false)
        {
            formWeblead = new frmWebLeads();
            formWeblead.MdiParent = this;
        }

        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }

Answer: The code which prevents the same child form in an MDI form
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
  frmMaterial newMDIChild = new frmMaterial();
  bool opened = false;
  foreach (Form OpenForm in Application.OpenForms)
  {
    if (OpenForm.GetType() == typeof(frmMaterial))
    {
      OpenForm.Activate();//to bring the activated form to the front
      opened = true;
    }
  }
  if (opened==false)
  {
    // Set the Parent Form of the Child window.
    newMDIChild.MdiParent = this;
    //newMDIChild.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    // Display the new form.
    newMDIChild.Show();
  }
}

Answer:     private void mnuMyForm_Click(object sender, EventArgs e) // click to open MyForm
    {
        foreach (Form item in this.MdiChildren) // check all opened forms
        {
            if (item.Name == "MyFormName") // check by form name if it's opened
            {
                item.BringToFront(); // bring it front
                return; //exit
            }
        }

        // if MyForm is not opened
        // you know what it is
        MyForm frm = new MyForm();
        frm.MdiParent = this;
        frm.Show();
    }

Answer: the simpleist ways of preventing multiple instance of child
private void Showforms(Form frm)
{
    if (this.ActiveMdiChild==null)
    {
        frm.MdiParent = this;
        frm.Show();
    }
}

Answer: The simplest ways of preventing multiple instance of child:
 private void Showforms(Form frm)
 {
   if (this.ActiveMdiChild==null)
   {
      frm.MdiParent = this;
      frm.Show();
   }
 }

Then call it like  this:
Form1 frm = new Form1();
Showforms(frm);


Dúvidas sobre como usar mapas dinâmicos

Question: Minha irmã vende Avon e eu resolvi fazer uma coisa bem simples que são os cadastros dos clientes dela. Até aí tudo bem, mas eu gostaria de adicionar o mapa do Google Maps no site dela. Achei a API da Google mas com um monte de coisas, o que eu quero é coisa simples, ao abrir o cadastro de clientes tem 3 tabs
PRINCIPAL | ENDEREÇO | MAPA
Ao clicar na tab "mapa" gostaria que dentro da DIV ou IFRAME ou outro elemento, me mostrasse o mapa do endereço do cliente dela. É coisa simples, algo do tipo assim:
https://www.google.com.br/maps/preview/place/AQUI-VAI-O-CEP
Se eu mudar o CEP e colocar o da minha rua e copiar o link e colar no browser ele abre o link direitinho, agora se eu colocar ele dentro de uma DIV ou de um IFRAME ele não carrega.
Como resolver?
Comment: Você pegou o código do iframe da própria página do maps? Clique no ícone do elo da corrente e pegue de lá.
Answer: Tente fazer a URL neste formato:
https://www.google.com.br/maps?q=<CEP_COM_TRACO>,%20Brasil&output=embed

Um exemplo de como ficaria:
https://www.google.com.br/maps?q=49100-000,%20Brasil&output=embed

Isso porque o Google Maps Preview (novo Google Maps) que você está usando precisa ser usado por alguém que está logado no Google e aceitou testar essa nova versão!
Espero que ajude!
Comment: Não deu certo Rodolfo. Veja o exemplo:
http://www.zenasloc.com.br/mapa.htm
Continua sem aparecer
Comment: Tente agora, editei a resposta para tentar outra alternativa. não esqueca do `&output=embed` no final da URL
Comment: Certo, com isto eu vou usar a versão antiga do Google né e não terei problemas em saber se o cara está ou não logado. Seria isto? Deu certinho. Confere aí pra você ver:

http://www.zenasloc.com.br/mapa.htm

Funcionou tanto no Chrome quanto no IE.
Comment: Protinho, consegui ajustar até um mapa para pegar uma rota, com isto vou poder saber qual a rota dela de um ponto para outro. Valeu.
Comment: Fico feliz que conseguiu! Exatamente, desta maneira não é necessário que o usuário esteja logado no Google.

Dúvidas sobre como usar mapas dinâmicos


php DOMDocument()->loadXML() not working

Question: I have this XML automatically produced by GPAC MP4Box.
<?xml version="1.0"?>

<MPD
    xmlns="urn:mpeg:dash:schema:mpd:2011" minBufferTime="PT1.500000S" type="dynamic" availabilityStartTime="2014-05-07T22:02:08Z"
    timeShiftBufferDepth="PT0H0M0.00S" profiles="urn:mpeg:dash:profile:isoff-live:2011">
    <ProgramInformation
        moreInformationURL="http://gpac.sourceforge.net">
        <Title>session.mpd generated by GPAC</Title>

    </ProgramInformation>

    <Period id="GENID_DEF" start="PT0H0M0.00S">
        <AdaptationSet segmentAlignment="true" maxWidth="352"
                       maxHeight="288" maxFrameRate="5" par="352:288">
            <SegmentTemplate timescale="10240" media="stream$Number$.m4s"
                             startNumber="1" duration="20480" initialization="streaminit.mp4"/>
            <Representation id="1" mimeType="video/mp4"
                            codecs="avc1.42e014" width="352" height="288" frameRate="5" sar="1:1" startWithSAP="1" bandwidth="192548">
            </Representation>

        </AdaptationSet>
    </Period>
</MPD>

And
$x = new DOMDocument();
$x->loadXML('session.mpd');

Results in:
Warning: DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 1

Does any one see what is wrong?
Comment: It's either one of these options: one. Your XML has errors in it, somehow, somewhere. Try running a few online parsers, see if it validates. If it does, then it's possible it might be two. You're using an older version of PHP where a bug was present where valid XML could not be parsed. What version are you running?
Comment: If I recall correctly, XML must start with `<?xml`, not `<? xml`. Also no spaces for `version="1.0"`.
Comment: sorry it actually does, my editor put the spaces in
Comment: @Mave PHP Version 5.3.10-1ubuntu3.11
Comment: Okay, when I try to run this code myself, by referencing a file it's a no-go. But by pasting the xml directly into the `loadXML()` function, it works. I can't test more as I've run out of time, but I do hope this points you at least somewhat in the right direction.
Comment: oh that's interesting, ok I'll give it a try. Thanks
Answer: DOMDocument::loadXML expects XML source as an argument, if you are going to use file path, use DOMDocument::load


Servlet Faces - Erro in context with path

Question: Bom dia,
Como já havia dito em outro tópico não é minha área web mais estou tentando kkkk...
Após adicionar um template responsive com nome de Prologue estou com o seguinte erro.
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/ibmo] threw exception [javax/servlet/jsp/jstl/core/Config] with root cause

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config
pom.xml

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.3</version>
    </dependency>

    <dependency>
         <groupId>com.sun.faces</groupId>
         <artifactId>jsf-api</artifactId>
         <version>2.1.13</version>
    </dependency>

    <dependency>
          <groupId>com.sun.faces</groupId>
          <artifactId>jsf-impl</artifactId>
          <version>2.1.13</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.2.8</version>
        <scope>compile</scope>
    </dependency>

Answer: Adicione no seu pom.xml:
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

E veja se funciona, esse erro ClassNotFoundException geralmente ocorre quando alguma biblioteca está ausente de seu projeto
Comment: você tem a pagina index.jsp no projeto?
Comment: Então você já começou errado rs, pelo que vi você quer usar JSF. Se for mesmo usar JSF esses templates não irão funcionar.
Comment: Agora, se você quiser podes usar JSP, Spring, Struts. Mas pra isso você precisará fazer outras configurações.
Comment: Ah, tá. Muito obrigado ! Vou vê o que eu faço. Abraço!
Comment: Bom, resolveu. Só que agora está dizendo na execução da página:"HTTP Status 404 - /ibmo/index.jsp" minha página é html...
Comment: Pior que não. Como disse estou usando template do prologue ele é "index.html"


Percentage Off a Sale Price

Question: How can I find the percentage off of a sale price? For example, the sale price of an item is $\$13$. The original price was $\$85$. What percentage was discounted from the original price?
For example, the sale price of an item is $\$19$. The original price was $\$150$, which means the sale is $87\%$ off the original price.
Answer: Use the formula:
$\text{percent discount}=\frac{\text{difference}}{\text{original}}\times 100$
Thus: $\frac{150-19}{150}\times 100 = \frac{131}{150}\times 100 = 87\frac13$, so you get $87\frac13\%$
The same formula works for percent increases. It's always "difference over original".
Comment: Great, thanks!!

Percentage Off a Sale Price


Scala: do something if get the value in getOrElse

Question: If a variable is an Option[Account], and there is a string field called accountName in the class Account.
e.g:
val allAccounts: Set[Option[Account]] = Set(Some(Account1), Some(Account2), None)

How do I get the accountName from Some(Account) if I get something from getOrElse?
I tried allAccounts.map(_.getOrElse("").accountName) but it doesn't work. It cannot apply to the "get" part but the "OrElse" part
Thanks for your help!
PS: wonder why allAccounts.map(_.map(_.accountName).getOrElse("")) works fine with None value but if I create another variable: val sampleAccount2 = None and sampleAccount2.map(_.accountName).getOrElse("") will failed? Basically I just goes from Set(None) to None ?
Comment: `allAccounts.map(_.map(_.accountName).getOrElse(""))`
Comment: @XavierGuihot I would use `fold` in this case: `allAccounts.map(_.fold("")(_.accountName))`
Comment: Possibly, I just didn't want to add too much complexity, just the bare minimum to give an understanding of the issue
Comment: @Tim Why ? It is more opaque for beginners... and seems kind of unnacessary complication. It involves a totally unnacessary string creation as well. Is there a specific reason for your preference, or is it just personal taste ?
Comment: @sarveshseri I don't agree that it is more complicated, it is just different. It is also clearer and more efficient.
Comment: Ok. So... it is just personal taste. And less efficient due to extra string creation (and unncessary more complicated to me as a third party).
Comment: The Scala library is full of methods that can be implemented using combinations of other methods. I would argue that it makes them simpler rather than more complicated. Is `groupMapReduce` more complicated than `groupBy`/`map`/`reduce`? And, yes, `fold` is more efficient than `map`/`getOrElse` because it only tests the `Option` once (the `String` is only created if needed).
Answer: Is this what you ultimately wanted to achieve?
final case class Account(accountName: String)

val allAccounts: Set[Option[Account]] =
  Set(Some(Account("Account1")), Some(Account("Account2")), None)

def getAccountNames(maybeAccounts: Set[Option[Account]]): Set[String] =
  maybeAccounts.map(_.fold("")(_.accountName))

assert(getAccountNames(allAccounts) == Set("Account1", "Account2", ""))

You can play around with this code here on Scastie.
Another way to write getAccountNames is by using a combination of map and getOrElse instead of fold, like so:
def getAccountNames(maybeAccounts: Set[Option[Account]]): Set[String] =
  maybeAccounts.map(_.map(_.accountName).getOrElse(""))

This is probably closer to what you initially wanted to write. In this case fold and map with getOrElse are basically equivalent, choose whichever makes more sense given your knowledge of the code base you're working on at the moment.
This version is also available here on Scastie.
The problem with your attempt if that you were applying getOrElse to the Option[Account] type, meaning that you were trying to return something that was either an Account (within the Option) or a String and from that thing you were then asking the accountName, which only makes sense on Account but not on String. The key difference is that in this case you first map on Option[Account] to get the accountName on Somes, getting an Option[String], and then you either get what's in there or the default value if the Option is empty.

As further input, please note that since you are using a Set, if you have multiple empty values in your input, they will be effectively collapsed into one, as in the following example:
assert(getAccountNames(Set(None, None)) == Set(""))

If by any chance you would rather remove any empty value entirely from the output, you can do so by rewriting the function above so that it's defined like so (Scastie):
def getAccountNames(maybeAccounts: Set[Option[Account]]): Set[String] =
  maybeAccounts.flatMap(_.map(_.accountName))

In this case getAccountNames can be redefined in terms of a for-comprehension (more on the topic here on the Scala documentation):
def getAccountNames(maybeAccounts: Set[Option[Account]]): Set[String] =
  for {
    maybeAccount <- maybeAccounts
    account <- maybeAccount
  } yield account.accountName

This last example is also available here on Scastie for you to play around with it.
In both cases, the assertion that holds now changes to the following:
assert(getAccountNames(allAccounts) == Set("Account1", "Account2"))

Comment: Thanks! Wonder what if I want to iterate the set and have a map like this: Account (an instance) -> accountName
Comment: Another question is why if I create two examples below:

val sampleAccount1 = Some(Account("Account11"))
val sampleAccount2 = None

sampleAccount1.map(_.accountName) -> will return Some(Account11) instead of a string Acccount111? I thought when "map", it goes inside the Some()?
And sampleAccount1.map(_.accountName) will throw an error?  I think it is because the None has no map function, but why it works when in an iterable collection and with flatMap? (i.e. maybeAccounts.flatMap(_.map(_.accountName))), it will filter the None


What's the point with the Gelfand–Naimark theorem?

Question: Does anybody can explain me in plain english what's the real point with the Gelfand–Naimark Theorem. I know it's crucial, but I think I'm missing how much it's crucial.
Answer: The Gelfand-Naimark theorem is a "Cayley's theorem" for C*-algebras.
One way to think about Cayley's theorem is the following. You can define a "concrete group" to be a subgroup of the group of permutations of some set (this is how mathematicians implicitly used to work with groups, back in the day), and define an "abstract group" in the usual way. Cayley's theorem guarantees that every abstract group arises as a concrete group, so the abstract definition really captures the concrete phenomenon it was intended to.
Similarly, you can define a "concrete C*-algebra" to be a closed and star-closed subalgebra of $B(H)$ for some Hilbert space $H$, and an "abstract C*-algebra" in the usual way. Gelfand-Naimark guarantees that every abstract C*-algebra arises as a concrete C*-algebra, so the abstract definition again captures the concrete phenomenon it was intended to. (This is much less obvious than Cayley's theorem for groups, and in particular the C*-identity, which isn't obvious to write down, plays a crucial role.)
Various other theorems in mathematics also play this role; for example Whitney embedding is a Cayley's theorem for manifolds, and the PBW theorem implies a Cayley's theorem for Lie algebras.


jvectormap uncaught typeerror

Question: I have been trying to get this plugin working for hours and can't seem to do so. I am fairly new to jquery so i do apologize if i say something stupid :) I tried following the tutorial provided on the site but have had no luck. Anyways my code so far is:
<!doctype html>

  <meta charset="utf-8">
    <title> vectormap </title>
  <link rel="stylesheet" media="all" href="css/jquery-jvectormap-1.2.2.css">

The errors im getting are:
1. Uncaught TypeError: Cannot read property 'maps' of undefined
2. Uncaught TypeError: undefined is not a function
Appreciate any help as this is doing my head in !!
cheers
ps sorry for not indenting properly
Answer: You have to include jquery library before including any of your plugins library. so put below line as first library include -

like below

 <meta charset="utf-8">
<title> vectormap </title>

<link rel="stylesheet" media="all" href="css/jquery-jvectormap-1.2.2.css" />

 -->

Comment: your solution has fixed the initial problem and i have updated my code but now i get two different errors
1.Uncaught TypeError: Cannot read property 'maps' of undefined
2.Uncaught TypeError: undefined is not a function
my only guess is that i am missing a .js file
Comment: for first problem, you need to see API documents for the plugins you are using and for second error comes when you find some element using `id` or `class` or any other jquery selector but it is not getting.

jvectormap uncaught typeerror


install WIX installer application in C: partition instead of Program Files folder

Question: I have created a installer using WIX in VS2010.Currently when i install the application,it is installing the application and application related dependency files under C:\Program Files\Wixdemoapplication. I need to customize this.I need to install the application directly under Wixdemoapplication under C:\Wixdemoapplication and not C:\Program Files\Wixdemoapplication.
Need help.
Comment: You need to set the INSTALLFOLDER property to wherever you want to install.
Answer: Try this (untested; but probably enough for what you need to do):
<Directory Id="TARGETDIR" Name="SourceDir">
    <Directory Id="INSTALLFOLDER" Name="Wixdemoapplication" />
</Directory>

Otherwise, can do some other fun stuff, like:
Add this custom action to Product.wxs:
<CustomAction Id="SpawnBrowseFolderDialog" BinaryKey="CustomActions" DllEntry="SpawnBrowseFolderDialog" Return="check" />

Add this into button in some dialog in Product.wxs:
<Control Id="BrowseButton" Type="PushButton" X="276" Y="126" Width="90" Height="18" Text="{\VSI_MS_Sans_Serif13.0_0_0}B&rowse..." TabSkip="no">
    <Publish Event="DoAction" Value="SpawnBrowseFolderDialog"><![CDATA[1]]></Publish>
    <Publish Property="INSTALLFOLDER" Value="[INSTALLFOLDER]"><![CDATA[1]]></Publish>
</Control>

Add this custom action in (right click solution, add, new project, C# Custom Action project):
[CustomAction]
public static ActionResult SpawnBrowseFolderDialog(Session session)
{
    session.Log("Started the SpawnBrowseFolderDialog custom action.");
    try
    {
        Thread worker = new Thread(() =>
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "Please select an installation directory to house core files and components.";
            dialog.SelectedPath = session["INSTALLFOLDER"];
            DialogResult result = dialog.ShowDialog();
            session["INSTALLFOLDER"] = dialog.SelectedPath;
        });
        worker.SetApartmentState(ApartmentState.STA);
        worker.Start();
        worker.Join();
    }
    catch (Exception exception)
    {
        session.Log("Exception while trying to spawn the browse folder dialog. {0}", exception.ToString());
    }
    session.Log("Finished the SpawnBrowseFolderDialog custom action.");
    return ActionResult.Success;
}

Comment: TARGETDIR should be avoided because it's variable. And there's no need for a custom action when directory selection is built in to MSI.
Answer: Put the <Directory> element for your program nested under a <Directory Id="WindowsVolume">.


git pre-commit: modify files in pre-commit script

Question: Is it possible to modify changed files(I want to tidy up xmls) in git pre-commit hook script? If yes, how to do it? Now I have such script:
files=`git diff --name-only --cached`

was_xml=false
for file in $files
do
    extension="${file##*.}"
    xml="xml"
    if [ "$extension" = "$xml" ]
    then
        tmp_file=$file"_xmlint"
        echo $tmp_file >> fuck
        xmllint --format --encode utf8 $file > $tmp_file
        rm $file
        mv $tmp_file $file
        git add $file
        was_xml=true
    fi
done

if $was_xml ; then
    git commit -m 'Xml cleanup'
fi

But it doesn't work...
Answer: You probably want to look up clean and smudge ( see http://git-scm.com/book/ch7-2.html ).  You could do XML reformatting during the clean phase of staging a file.
Comment: Oh, thanks! But how can I get git filename from clean filter script? I've tried to use %1(I'm writing on bash), but it doesn't work.
Comment: The clean filter gets called with the file contents on stdin, and it puts the filtered result on stdout.  It doesn't get the filename of the file it happens to be working on _but_ using .gitattributes, you control exactly which files for which it will be run.  For instance, if you named your reformatting filter ``indent-xml``, you could add the following line to the appropriate .gitattributes file: ``*.xml filter=indent-xml``.  Then it would get run for all and only your xml files.


How effective are acoustic panels to deaden a room?

Question: I need to deaden an echoing drum practice room and am considering acoustic panels, probably DIY ones 3.5" deep filled with rock wool.  I'm look at these vs. heavy blankets for aesthetic reasons.  I'd like to know they are effective before I spend the labor to assemble them.  Also interested in how many (or how much area of wall) I need.  My space is small, about 10' x 10'.
Comment: Good panels can be _very_ effective, but it depends on rather too many factors to discuss it on StackExchange. Room acoustics is a really tricky science.
Comment: I'm voting to close this question mostly because it's not on a [topic covered here](https://music.stackexchange.com/help/on-topic). Treating room acoustics is certainly tangentially important to musical practice, but it's a separate topic (and installation tips are definitely off-topic). Also partly because "does it work well" is too vague/subjective for good answers.
Comment: I might be able to give a better answer if I knew whether you wish to remove room reverberation or eliminate sound transfer to surrounding rooms.
Comment: I'm just trying to dead the room, i.e. remove the echo and reverberation.  I understand that soundproofing is a whole different animal.
Answer: You can compare the sound absorption coefficients for the materials you are considering to see how dead different amounts of materials will make your room.
Here is a chart: http://www.acoustic.ua/st/web_absorption_data_eng.pdf
What you could do is approximate the room response by simplifying the math by assuming the non-damped surface area reflects 100% of the sound equally (i.e. treat the walls as if they are a sphere with the drum kit in the center). Then multiply the absorption coefficient by the percent of surface area you intend to cover with the material and estimate that the intensity of the reflections will be that much less. For example, if you cover 50% of the surfaces with materials having absorption coefficients of 0.50, then you could estimate that reflections and reverb will be reduced by about 25%.
Two important reminders: the ceiling and floor count as reflective surfaces for your estimates, and absorbing reflections only affects the reverberant sound level in the room. It does not affect the direct sound level (from the drums to anyone's ears), nor does it necessarily reduce the amount of sound transmitted to other rooms through the walls of the room. In other words, you can't really make the drums quieter this way, only deader. And you don't want it too dead because that would sound weird.
Really a good way to go is to plan to build perhaps four panels and put them up and see if you're happy. If not, build four more. Keep going until it sounds good. It's not often effective to do math to predict how something will sound.
Comment: It should be stated clearly that there is a balance point between to much reverberation and not enough reverberation and the goal is to find that balance point. Ask a lot of questions and be ready to experiment.
Comment: Yeah, I guess I've never experienced "too dead".  The room was just fine when it doubled as a storage room full of shelves of junk.  Now that I've cleaned it out, I can hardly stand to play due to the echo.
Answer: It's not easy to tame a 10' x 10' box which you intend to be LOUD in.
You might be well advised to forget the aesthetics and put most of the junk back, leaving JUST room for the drum kit!  Then you get free sound treatment AND free storage!  I've too often seen people ruin a perfectly useable room with 'design'.
Answer: Although, it's an old thread but I want to share that acoustic panels really works very well in deaden the room. My apartment was very close to the main city road and it was a quite annoying situation for me almost all day because of traffic sounds. I will say that after installing these acoustic felt panels in my apartment, I was like that staying in pin drop silent room. :-
Comment: I'm confused by the down-vote. If people feel the original question should be off-topic, maybe it should be closed. Meanwhile, although this answer mentions a different material than the OP proposed, it seems like a reasonable answer to the question.
Comment: @AndyBonner - this answer addresses the *external* noise problem, which is different from the echo OP is asking about. It's a good solution, maybe, but to a different problem!


techniques for sampling graphs? (possibly implemented in r packages)

Question: Let's say I have a very large graph that proves impractical for visualization ends and I wanted to sample a random subgraph.
(I know that I can filter out a subgraph via measures like degree, components, weights... but this is not my point)
Is there any procedure that I can use to get a random sample from the graph?
I see that the igraph package has two sampling functions that  seem however to be generic and not specifically designed for  sampling graphs. But if they are in that package there must be a reason!
(Is it as easy as random sampling edges i.e. rows?)
Comment: This is exactly the point of my question: I wondered if the idea of sampling from a graph has been defined by anyone. The aim would be to preserve "the most" of the original graph - this could be defined as keeping some measures invariant, as in a geometric transformation. (A graph is a topological object if I am not wrong.)
Comment: As far as I'm aware there's no one way to sample a graph because the idea of sampling a graph isn't well-defined. Do you sample nodes and let edges "fall off"? Do you sample edges and leave isolated nodes? What are you trying to accomplish?
Answer: There is a large number of research on graph sampling (easily discoverable by simple Internet search, by the way). The following is just a small representative sample of this research stream:

http://arxiv.org/abs/1308.5865 (nice overview, I would read this first)
http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0010012
http://dl.acm.org/citation.cfm?id=1150479
http://cs.stanford.edu/people/jure/pubs/sampling-kdd06.pdf
http://www.deutsche-telekom-laboratories.de/~panhui/publications/graph_sampling_simplex11.pdf
http://charuaggarwal.net/selectives.pdf
http://vserver1.cscs.lsa.umich.edu/~crshalizi/notabene/graph-sampling.html
http://www2.warwick.ac.uk/fac/cross_fac/complexity/people/staff/delgenio/gsampler
http://systemg.research.ibm.com/analytics-sampling.html (seems to be commercial)
http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=5961350
http://link.springer.com/article/10.1007%2Fs10651-011-0170-3
Comment: Thank you Aleksandr. I do not see any method that has been implemented in a r package, isn't it?
Comment: @DarioLacan: You're welcome. Yes, to the best of my knowledge and based on extensive search, currently there are no R packages, implementing graph sampling of any type. Thank you for accepting, feel free to upvote as well, if you like my answer. I will update it and let you know, if I will run across new or relevant information.
Comment: @AleksandrBlekh: Have you since found any R packages for graph sampling?
Comment: @histelheim: No, as I simply haven't searched since (deviated to other matters). However, I'm still curious about the topic. So, please feel free to comment or update the answer, should you find relevant R packages.


Fitting a distribution to match known points on the CDF

Question: I've recently run into a situation where I know a few probability points in the tail of a distribution and I want to "fit" a distribution that goes through these points in the tail. I realize this is messy and not overly accurate, and plagued with conceptual issues. However, trust me that I really want to do this.
So effectively I know some points in the tail of the CDF with x being the values and y being the probability of that value or smaller. Here's R code to illustrate my data:
x <- c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85)
y <- c(0.0666666666666667, 0.0625, 0.0659340659340659, 0.0563106796116505,
       0.0305676855895196, 0.0436953807740325, 0.0267459138187221)

Then I create a function to minimize error between my data and a beta distribution CDF using pbeta. I use SSE as a fit metric then minimize that with -sum. I throw in an initial guess as the first param to optim of (9, .8) although I've tried this with different guesses and I always get the same result. The starting point guess I use comes from manually cooking up parameters by hand that seem close.
# function to optomize with optim
beta_func <- function(par, x) -sum( (pbeta( x, par[1], par[2]) - y)**2 )
out <- optim(c(9,.8), beta_func, lower=c(1,.5), upper=c(200,200), method="L-BFGS-B", x=x)

out <- out$par
print(out)
#> [1]  0.90000 23.40294

Below I graph the 'optimized' beta distribution in red, my actual data in blue, and a hand tweaked starting guess of the beta parameters in black.
plot(function(x) pbeta(x, shape1=out[1], shape2=out[2] ), 0, 1.5, col='red')
plot(function(x) pbeta(x, 9,.8), 0, 1.5, col='black', add=TRUE)
lines(x,y, col='blue')

I can't grok what's going on with optim to give a solution that's worse than my starting guess. I calculated the SSE for my starting guess vs the optim solution and it looks like my guess has a much larger -SSE:
# my guess
-sum( (pbeta( x, 9, .8) - y)**2)
#> [1] -0.03493344

# optim's output
-sum( (pbeta( x, .9, 23) - y)**2)
#> [1] -6.314587

Using past history as my Bayesian prior, my guess is that I'm misunderstanding optim or feeding it improper inputs. However, I can't grok what's going on. Any tips would be greatly appreciated.
I've tried using the CG optimization method, but the results are not meaningfully different and still don't seem near as good as my starting guess.
out <- optim(c(9,.8), beta_func, method="CG", x=x)
out <- out$par
print(out)
#> [1]  2.287611 11.124736

Comment: How can these points be "known" for a CDF and yet tend to decrease with increasing values of $x$ ?
Comment: I think these are problems which would disappear if you were to estimate these quantities using standard statistical tools instead of re-inventing the wheel.
Comment: @JimB the source of the downward slope is two fold. Estimates of each point come from a different sampling process so two things happen: 1) sample noise 2) violation of the iid assumption about each underlying. I'm not concerned as much with the stats issues here as much as trying to make `optim` do my bidding.
Comment: @Sycorax your suggestion presumes that standard statistical tools would work in my situation. That's an incorrect assumption.
Answer: I think you are accidentally trying to maximize the squared errors.  The default for optim() is to minimize the function, so the negative sign in your beta_func() results in searching for a max.
If you modify your function like so you get values closer to your guess:
beta_func2 <- function(par, x) sum( (pbeta( x, par[1], par[2]) - y)**2 )
out2 <- optim(c(9,.8), beta_func2, lower=c(1,.5), upper=c(200,200), method="L-BFGS-B", x=x)
out2 <- out2$par
print(out2)
[1] 11.04296  0.50000

You can check the new function against your observations (where out, x, and y are defined as in your example):
plot(x,(pbeta(x,out[1],out[2])), ylim=c(-.1,1), col="red", type="l")
points(x, (pbeta(x,9,0.8)), col="black", type="l")
points(x,(pbeta(x,out2[1],out2[2])), col="orange", type="l")
lines(x,y, col='blue')
title(main="Blue observed CDF, black guesstimate, gold optimized")

Comment: yep, that was clearly my mistake. I *thought* I had tried changing the sign, on a whim, but clearly I had not. I was pretty anchored to the idea the the default behavior of `optim` was to maximize. Thanks!


Add rows based on column index

Question: I have a dataframe that has the following columns:
<code> id     index1    index2    value
 DivA     1         4        3
 DivA     3         6        4
 DivB     1         3        5
 DivB     5         7        3
</code>
On another dataframe I have the following:
<code> id      index
DivA       1
DivA       2
      ...
DivA       10
DivB       1
      ...
</code>
final result:
df2:
<code> id      index    value
DivA       1        3
DivA       2       nan (because no value in df1)
DivA       3        4
DivA       4        3
      ...
DivA       10       nan (because no value in df1)
DivB       1        5
      ...
</code>
I'm wondering if I can add a new column 'value' to the second df in a way that 'index1' and 'index2'
are combined and that 'value' in the second df can have 'nan' if there is no values in the first dataframe 'value' ?
Thank you for help !
Comment: check with df.melt('id')
Comment: it puts the three columns into one, what I'm looking for is that I transform the 'index1' and 'index2' into 'index' where the missing values in the two columns have a nan, any thoughts ?
Answer: <code>  #pd.melt first dataframe
    df3=pd.melt(df, id_vars=['id','value'], value_vars=['index1', 'index2'], value_name='index').drop(columns=['variable'])

#pd.concat second dataframe to the pd.met result, sort-values and drop duplicates in index
(pd.concat([df3, df1], ignore_index=True).sort_values(by=['id','index'])).drop_duplicates(subset=['index'],keep='first')

     id  value  index
0   DivA    3.0      1
9   DivA    NaN      2
1   DivA    4.0      3
4   DivA    3.0      4
5   DivA    4.0      6
10  DivA    NaN     10
3   DivB    3.0      5
7   DivB    3.0      7
</code>
Comment: It works, I found out that pd.melt can very usefull in a lot of tasks but need a bit of time to understand the concept, thank you !

Add rows based on column index


how to check if a word is in a phrase in python (simple search engine)

Question: Okay I've been having some problems with my code, it's a simple python search engine whereby the user inputs a sentence and a word. If the word is in the sentence then the code is to output "word found" and if the word is not found then it is supposed to print "word not found".
Here is my code:
text = input()
word = input()

def wrong(text, word):
    print("Word not found")
wrong(text, word)

def right(text, word):
    print("Word found")
right(text, word)

def check(right, wrong):
    if text.index == word:
        return right
    elif text.index != word:
        return wrong
check(right, wrong)

So instead what I've been getting as output is both the responses instead of just one. Please help me.
Comment: `if word in text: ... else: ...`
Comment: You're calling `wrong` and `right` right after you defined them, unconditionally… So yes, both will always print.
Comment: [`str.index`](https://docs.python.org/3/library/stdtypes.html#str.index) is a function that you must call, not something that you compare a string to.
Answer: Are you searching for something like? :
a = 'some word'
b = 'some'

if b in a:
  print('yes')
else:
  print('no')

Comment: yes it is fully functional. Thank you
Comment: I am yes, I didn't try that yet let me see
Comment: Please do not forget to mark this as the correct answer if it is the correct one
Answer: text = input('input text: ')
word = input('input a word: ')

if word in text:
    print('Word found!')
else:
    print('Word not found')


How to avoid underflow of the probability of sentence in calculating the perplexity of corpus

Question: I am looking at this post How to find the perplexity of a corpus. I understand the whole post, but

the probability of a sentence appear in a corpus, in a unigram model,
is given by p(s)=∏ni=1p(wi), where p(wi) is the probability of the
word wi occurs.

For a large corpus, even if I only calculate the probability of a sentence by using ∏ for each word in the sentence, I still get a 0 proabibilty which causes error in the following log2 calculation. Can someone help me?
Answer: We deal with underflow in probability calculations by working in log-space (i.e., dealing with log-probabilities instead of probabilities for all intermediate calculations).  This often requires us to add or subtract probabilities in log-space or conduct other computations in log-space.  In the present case, the equation of interest:
$$p(s) = \prod_{i=1}^n p(w_i),$$
can be written easily in log-space as:
$$\ell(s) = \sum_{i=1}^n \ell(w_i),$$
where $\ell(s) \equiv \log p(s)$ and $\ell(w_i) \equiv \log p(w_i)$ are the log-probabilities.
When undertaking probability calculations in log-space, you should do all intermediate calculations in log-space and then convert back to regular probability space only at the end of your calculations.  This will avoid underflow by ensuring that small probabilities are represented in intermediate calculations only through their log-probabilities.


IIS host header name resolution across my network

Question: I have a Windows Server 2012 R2 machine, named [mine-1234].
I have IIS 8.5 installed and a hole in my firewall for ports 80 and 443.
I have created 2 test sites

one with a default binding to :80
one with two bindings to :80  with host headers. [foo.mine-1234]and[foo.mine.local]

I configured my hosts file to resolve mine.local and foo.mine.local to 127.0.0.1 and local reference to the sites resolve fine. The issue I'm having is when I attempt to use the external bindings on my LAN.
Requests from Localhost

http://mine.local/index.html loads in the browser
http://foo.mine.local/index.html loads in the browser.

Requests from LAN Clients

http://mine-1234/index.html loads in the browser.
http://foo.mine-1234/index.html does not load in the browser.

However, the host headers do not resolve for other callers on my LAN that are outside my machine.
3 Questions (2 and 3 depend on the answer to 1)

Can foobe made available to my LAN without modifying DNS?
[if: 1=yes] What is the proper binding for foo on mine-1234 to make it accessible to my LAN without modifying DNS?
[if: 1=no] What is the most straightforward way to modify DNS to make foo  available to my LAN?
Answer: Alan Bates,
Generally speaking yes you need to modify your DNS for other LAN clients in your network to know how to reach the website.
An easy way to think about it is the setting you create in IIS tell the web server what IP address and host name your website to answer to. It does NOT tell other LAN clients how to reach your website.
LAN clients send the hostname to the DNS server and the DNS server resolves the hostname to an IP address (for this to work you need an A record) the LAN client then sends the request to that IP address (your web server) which checks the hostname requested and if it matches the settings in IIS displays the website.
So you have two parts.

What do I respond to (IIS settings)
How do I reach the website (DNS records)

Best practice is to set one static IP address per website and set the IIS binding for each site to its corresponding static IP address. Then add the DNS A and PTR records on your DNS server so your LAN clients know how to reach your website.
Please let me know if you have any other questions.
Comment: I was expecting that the existing A record for `[mine-1234]` could be matched with a CNAME record for `dev.mine.domain.local` to allow LAN connected users to find my machine, but my curiosity was whether or not `foo` would need its own DNS entry or if registering it with a host header in the site binding would suffice. Are you saying it will not? (This is my first time being responsible for onprem hosting in about 12 years. I'm rusty)
Comment: "I was expecting that the existing A record for [mine-1234] could be matched with a CNAME record for dev.mine.domain.local." Usually your DNS server would be authoritative for domain.local. Your hostname would be mine and your FQDN for that server is mine.domain.local. So if you want to create a website hosted on mine.domain.local with a DNS name of dev.domain.local you would bind the hostname dev.domain.local to the website in IIS and create a DNS CNAME record that says dev.domain.local is actually mine.domain.local.
Comment: ok. So let me see if I understand you: if my FQMN is `//mine-1234.domain.local`, I need to configure the binding in IIS to `foo.mine-1234.domain.local:80` and in order to make it accessible to LAN Clients, I need a CNAME pointing `foo.mine.local` to `foo.mine-1234.domain.local`. Is this correct?
Comment: For reference it is FQDN not FQMN and in Windows the slashes for a computer name are "\\" not "//". ;)

You can have your hostname be whatever you want (mine-1234.domain.local is fine).

Configure your website in IIS to bind to dev, foo, whatever .domain.local (e.g. dev.domain.local) and in your DNS server create a CNAME record for dev.domain.local to mine-1234.domain.local.
Comment: ok. ...that's consistent with something that I had already tried but couldn't make work and why I asked the question the way I did.  With a default binding to port 80, I can access `http://mine-1234` on my LAN. I can also access `http://mine-1234.mydomain.local` on my LAN as well as to localhost.  Whenever I add a host header to the binding, `http://foo.mine-1234.mydomain.local` doesn't even resolve on localhost.
Comment: Like I said, you may want to add a secondary IP address on your host network interface card, bind the IP to your website and add a DNS A record resolving the dev.mydomain.local to the secondary IP address that you bound to the website in the IIS role. That works very well.
Comment: " Whenever I add a host header to the binding, http://foo.mine-1234.mydomain.local doesn't even resolve on localhost." Yes, because you have provided no way for the client to resolve the hostname. You must add the DNS A and PTR records for that to work.
Comment: If this fixed your problem, please feel free to mark the answer as accepted.


Clean URLs caused site to break?

Question: I'm installing a new Drupal site using Red Hat... Getting Clean URLs to work was a pain in the you-know-what. I followed all the steps in the official drupal.org helpguide, but ended up needing extra help for a guide specific to RHEL users here: https://www.tecmint.com/install-drupal-in-centos-rhel-fedora/
I went into my httpd.conf file and made AllowOveride All as shown here: https://www.tecmint.com/wp-content/uploads/2013/07/Enable-Clean-URL-in-Drupal.png
I then fixed all of my directory issues in .htaccess (because my .htaccess file is in sites/web), and then all my admin links work perfectly. So Clean URLs is definitely enabled, but the issue now is the site is broken.

This was probably caused by enabling Clean URLs through the httpd.conf issue, but I'm not sure. I ran drush cr and it did nothing. Help?
Comment: Hey thanks for the suggestions... It turned out, actually, that I had to uncheck aggregate css. Duh!
Comment: That sounds more like a misconfigured tmp/files directory to me.
Comment: Welcome to Drupal Answers! :-) The site isn't broken. It's just the stylesheets are missing. Maybe uncomment `RewriteBase /` in your site's .htaccess. Maybe make make your files and temp dirs writeable recursively. But definitely check your site's status page for more info.
Answer: As leymannx and Kevin mention it is probably a misconfigured tmp/files directory
Uncheck aggregate css is something that you would not want on your live site as the performance will suffer.
Check in Reports > status report (/admin/reports/status) and try to fix or report on the errors that you see.
Also go into configuration > media > file system (/admin/config/media/file-system) and correct any file system problems reported when saving the settings.
The most probable cause of what you are seeing is wrong permissions.
There is a lot of guides on the net about setting those permissions.
You can start from the official guide on the subject or on one support thread that started as a drupal 7 thread but has Drupal 8 answers.

Clean URLs caused site to break?


Não consigo dar push no git

Question:
Galera estou com esse probleminha no git quando dou o push apresenta esse erro. Criei o repositório online acessei a pasta do projeto local pela cli do git Executei os comandos: (git, init, status. add ., commit...) fiz tudo no padrão mas mesmo assim o erro permanece
Comment: Fez o gitpull? A mensagem diz que o repositório que você está tentando fazer commit está mais a frente do seu local..
Comment: Provavelmente um readme, algo que vc não criou local...
Comment: Quando vc fizer o gitpull ele vai atualizar o local com o remoto, se houver conflito vai ter o famoso merge, se tudo der certo é um merge automático, senão vc vai ter que resolver. Depois disso vc vai poder fazer seu push.
Comment: Vc já rodou o comando e o git está informando  "remote origin already exist" ou seja origem remota já existe... já executou uma vez....  olhe e vê se ja tem o comando aplicado .....   git remote -v
Answer: O que aconteceu foi que vc trocou a ordem dos comandos do git, você colocou "git branch - M main" antes do "git remote add origin ..." e isso desatualizou seu repositório local.
Faz esse comando pra forçar a substituição da branch remota pelo código que vc tem no repositório local:
<code>git push -f origin main
</code>

Não consigo dar push no git


Scope e IIFE em JS

Question: O pessoal tudo bem? Estou aqui com uma dúvida num pequeno código, basicamente tenho um for loop que adicionar um evento click a cada numero onde será apresentado o numero que foi clicado no alert, e é claro que o número apresentado é sempre o último, até ai percebi, mas estou com uma dificuldade em entender o scope que foi acrescentado ao codigo, entendo que no inner-scope temos acesso a variaveis do outer-scope mas não o inverso, mas mesmo assim não entendo a técnica que é aplicada aqui, espero que me possam ajudar a entender:
var nums = [1,2,3];

for (var i = 0; i < nums.length; i++) {
var num = nums[i];
elem.addEventListener('click', (function(numCopy) {
    return function() {
        alert(numCopy)
    };
})(num));

}

Answer: Tentarei explicar o que acontece no código.
O primeiro ponto que vale notar é o "Declaration Hoisting":
https://developer.mozilla.org/pt-BR/docs/Glossary/Hoisting
Que significa a elevação das declarações de variáveis para o topo do escopo, que pode ser global ou de função. Ou seja:
for(var i=0; i < nums.length; i++)

É como fazer:
var i;
for(i = 0; i < nums.length; i++)

Desta forma a variável i estará disponível para uso por todos dentro do escopo.
E por este motivo que ao adicionar um clique desta forma:
elem.addEventListener('click', function() {
        alert(nums[i])
});

Resultará sempre no último número sendo exibido. Pois a função anônima que você criou tem acesso às variáveis i e nums  que foram no mesmo escopo da função anônima. Significando que, no momento em que a função é executada a variável i contém o índice do último elemento do Array.
IIFE
Para mitigar este problema, usamos uma IIFE (Immediately Invoked Function Expression), uma função que se executa imediatamente ao ser criada. Geralmente expressa desta forma:
(function(){

}())

Ou
(function(){

})()

Embora eu, pessoalmente, prefira a primeira opção. Ao fazer o que você demonstra no código, o seguinte acontece:

A IFFE é executada durante o loop e recebe como parâmetro o valor contido no índice atual do Array;
elem.addEventListener('click', (function(num) {

})(nums[i]));

Como uma nova função foi declarada, um novo escopo é criado. Este escopo tem uma variável chamada num que contém o valor contido no índice do array com que a função foi chamada.
Você retorna uma nova função que ao ser executada chamará a função alert, passando num como parâmetro;
return function() {
  alert(num);
};

Esta nova função, que foi criada na cláusula return é então adicionada como listener do evento;
elem.addEventListener('click', (function(num) {
   return function() {
     alert(num)
   };
})(nums[i]));

No seu caso, ao clicar é exibido sempre o último número do Array porquê, pelo que eu entendi, você chama o addEventListener várias vezes no mesmo elemento. Sendo assim, ao adicionar um novo listener, o antigo é sobrescrito.

Scope e IIFE em JS


Correct way to use multiple filters in an elasticsearch query

Question: I've managed to put together some fairly complex queries (for instance, for generating a heatmap from data), and thought I understood the query syntax, but it appears that I don't.
I'm trying to return the data which matches the following criteria:

Event is MyEvent
Has a field called "MyField"
Has a timestamp from less than one minute ago.

This is what I've tired, it doesn't return an error, but also doesn't return the correct results:
<code>{
"query" :
{
    "filtered":
    {
        "query":
        {
            bool:
            {
                must:
                    [
                        { match: { "event": "UpdateTitle" } }
                    ]
            }
        },
        "filter" :
        {
            "range" :
            {
                "@timestamp" :
                {
                    "gt" : "now-1m"
                }
            }
        }
        ,
        "filter" :
        {
            "exists" :
            {
                "field" : "Lobby"
            }
        }
    }
}
</code>
}
Obviously I've tried reading the documentation, but it's examples are generally only snippets rather than full queries, and the use of identically named queries and filters makes them incredibly confusing.
Answer: This appears to produce the effect I desired, hopefully it's using filters over queries:
<code>{
"query" :
{
    "filtered":
    {
       "filter" :
       {
            bool:
            {
                must:
                    [
                        { "term": { "event.raw": "MyEvent" } },
                        { "range" : { "@timestamp" : { "gt" : "now-1m" } } },
                        { "exists" : { "field" : "MyField" } }
                    ]
            }
        }
    }
}
</code>
}


Can the melody have more than one note sounding at once?

Question: When more than one note is playing, it probably is a chord. But can the melody section have two or more notes, being played simultaneously?
EDIT: I mean for a single instrument whose focus is either melody or chords, could the melody part have simultaneous notes at any point? (Eg right-hand piano notes).
Comment: So you are only talking about monophonic instruments?
Comment: @Keiwan No, this is in context of a piano. Basically, is melody a succession of single notes or it can have (at times) multiple nodes being played simultaneously?
Comment: I hope the edit to my answer provides a good example for what you are asking. Let me know if not :)
Answer: Yes, it's called Polyphony (if I understood you correctly this is what you mean). This is when multiple lines of melody are played simultaneously.  You can pretty much pick anything by Bach and get a good example of polyphony. Or Rachmaninoff's second sonata... there are numerous more examples. It's actually not that rare.
As an example (not for polyphony) but for a harmonic progression which contains the melody take a look at this excerpt from Rachmaninoffs sonata 2 (the right hand):
Comment: I am trying to analyse MIDI files, that show notes (like a piano roll). If I am able to interpret the image correctly, the upper bars mean melody (the treble clef) ?
If yes, so looking at the bars of melody, it seems that, yes, some notes do occur simultaneously in melody as well. Am I right?
Comment: Essentially, yes.
Answer: If I'm understanding the question correctly... generally no, sometimes yes.
Generally No
Take Debussy's Claire de Lune...

The melody is primarily in the right hand, doubled by the same line a third below.
If you were asked to analyze this piece and identify the melody, you would single out the top line only (not the doubled thirds). This is because:

In terms of acoustics, the top notes are going to be more prominently heard than any of the inner lines. You wouldn't listen to this piece and identify the 3rd below, for instance, as being the main melody line. It just doesn't stick out like the top line does. And it's generally important to clearly hear the melody as a listener because it is often the basis for later musical development.
The linear nature of melody. Melody is considered a linear element, and once you start to include simultaneous doublings of various intervals as part of that melody, you're introducing horizontal/harmonic elements which directly goes against this linear nature. Melody has a flow (even choppy, aggressive melodies) which contributes to the ongoing continuation of a piece of music. Vertical elements tend to be there to support this flow like little aural scaffolds.

Which leads to:

Using melody for compositional development. In vast amounts of music, melody is the key to the development of a composition. A brief melody line can later be transformed via inversion, or retrograde, or to new keys, or in many other ways. This both moves the music along and helps to keep it from descending into total chaos. If, in the Debussy example, the melody always had to appear in 3rds (because it was introduced that way in the beginning and identified as the "official" melody), then you're going to be limiting what the composer can do later on with that melody. It also would enforce an entire piece to be played with those thirds repeating ad nauseum. Repetition is great, but nothing but repetition doesn't make for a well-developed piece of music (unless you're taking about minimalism).

Now yes, those 3rds are noticeable and prominent in the beginning, but depending on how they're used later on (I haven't personally analyzed this far), they could easily be considered a motif or a harmonic motif. Something which can be referenced now and then, and will be pleasantly recognizable to the listener, but doesn't define every single note of the melody.
Sometimes Yes
Is it impossible for a melody to contain more than one line? No. As one of the other answers mentioned, there is polyphony, which is multiple simultaneous lines at one time. This is most obvious in music of the Renaissance, however; not all polyphonic works have equally important melodies within the hierarchy of the composition. Contrapuntal works can have an established melody stated at the beginning of the composition, while a secondary counter-melody is later introduced underneath. Analyzing these types of compositions require taking into account the specific techniques used, the time period... and a little bit of personal interpretation.
20th/21st century works also are varied enough that it would be difficult to claim there are no examples - outside of pure, rhythmically independent polyphonic works - that can't claim to have more than a single line melody. Once you get into music that might only have rhythms and a couple intervals as a "melody", you're into completely different territory.
So, when else would this be a yes?
Identifying a specific melody in an academic analysis is often different than using the term "melody" in practice. Let's say you were in an orchestra rehearsal. You're playing a piece that has very delineated melody lines and accompaniment. Something's gone wrong, the conductor stops everyone, and tells only those with the melody line to play. The conductor is probably not literally asking for only the top line to play (and you might not necessarily know what notes some other part/section is playing anyway), just for everyone who has a similar melody that plays together at the same time to rehearse a section.
Answer: You could be talking about HARMONY. Where two or more voices or instruments are often playing the same timing, but different notes.It doesn't even have to be simultaneous notes, listen to some fugues. Yes, often these notes are contained within the chord at that moment, usually a third or a fifth apart. They will blend with each other. African unaccompanied music, pop music and certainly most 'classical' music contains loads of examples. You can't fail to have heard lots in most kinds of music.
Comment: @goelakash - still not crystal clear. On instruments which can play more than one note, such as piano, guitar, harp, certainly a melody could be, and often is, played with two or more notes. What point am I missing?
Comment: But it is only possible with multiple instruments, right? I mean would a single instrument's tune, playing two or more notes simultaneously at some point, get classified as part of the melody?
Comment: Yeah, thats what I am asking. Basically, is melody a succession of single notes or it can have (at times) multiple nodes being played simultaneously?
Comment: @goelakash - you mean notes rather than nodes?
Comment: yeah, notes. Sorry for the typo.


Plotting text annotation in R

Question: I'm trying to add text annotations to a network when plotting an igraph graph object. I provided a toy example - I can't get any of the text to show up in the (x,y) locations. Can someone modify this so that it works properly?
TestAnnoDir <- getwd()

myText <- data.frame(x=seq(2,20,2), y=seq(2,20,2), text= sample(state.name, 10))
fn <- paste(TestAnnoDir, "Test", ".tif",sep="")
tiff(filename = fn, width = 1000, height = 1000)

# toy network example
erdos.renyi = erdos.renyi.game(10, 1/2, directed=FALSE)
plot( erdos.renyi ,
     vertex.size = 3,
     vertex.label = "",
     vertex.label.color = "black"
)

#plot.new()
for(i in 1: nrow(myText)){
  text(x=myText[i,"x"],y=myText[i,"y"], labels=myText[i,"text"])
}
dev.off()

p.s. I'm doing this in RStudio
Comment: Can you ditch the `tiff` stuff here and just show it on the screen?
Comment: The network is plotted freely, so the coordinates are nothing to do with the x and y coordinates in the data frame. Do you want the 10 nodes plotted at the coordinates in the data frame? igraph is trying to lay it out nicely.
Comment: If you want to plot the text at the nodes then `vertex.label=as.character(myText$text)` as an option to plot will do it.
Comment: Hi, sorry @Spacedman but nothing to do with the node text. It doesn't work either if I ditch the tiff stuff (i.e. doesn't work if I write it to file or display in RStudio)
Comment: Yes but there's no point having the TIFF code in there. I can see it's not working on R's graphics window easier than writing a TIFF file and opening an image viewer!
Answer: Ah... Looks like the canvas is scaled on -1,1 in both x,y
so this will work:
text(0, 0,"0,0")
text(0, 1,"0,1")
text(0, -1,"0,-1")
text(-1, -1,"-1,-1")
text(1, -1,"1,-1")
text(1, 1,"1,1")
text(-1, 1,"-1,1")

And looks like

Plotting text annotation in R


Using angulars ngResource get method

Question: I have a basic controller defined in C#, its only purpose is to return whoever the current user is.
    namespace ProjectName.Controllers
{
    public class UserController : ApiController
    {

        // GET api/user/
        public string Get()
        {
            return User.Identity.Name;
        }

    }
}

I then have an ngResource defined to look at that controller
cript.factory('User', function ($resource) {
return $resource('/api/User')
});

finally I try to get that user in my Angular Controller
    $scope.checkIfAuth = function () {
    $scope.user = User.get();

    console.log($scope.user);

    if ($scope.user === '"DS//:lemieszr"') {
        console.log("success");
    }
};

The problem is $scope.user is a resource object that looks like this
    Resource {$get: function, $save: function, $query: function, $remove: function, $delete: function}
    0: """
    1: "D"
    2: "S"
    3: "\"
    4: "\"
    5: "l"
    6: "e"
    7: "m"
    8: "i"
    9: "e"
    10: "s"
    11: "z"
    12: "r"
    13: """
    __proto__: Resource

Is there anyway to just get the string containing my Username. User.query() only returns an empty array.
Comment: Take a look at http://stackoverflow.com/questions/16553363/angular-nsresource-creates-an-array-of-char-arrays-for-rest-string-arrays
Comment: try returning a model instead of plain string
Answer: I would advise looking into Angular's implementation of Kris Kowal's Q promise library ($q). I'm working with mvc 4.0 right now as well and I have found it to be much more flexible than ngResource.
However with respect to your question specifically, your issue here is you are making an async request to your server while synchronously invoking its response. Well, the data hasn't gotten there yet (why you are seeing an empty array []). That empty array is basically the server saying "Hey, good work following protocol on your http request, we are getting your data, to prove it to you here is an empty array where we will put the data there when it gets to you."
In other words, your problem is that you are asking setting checking the value of $scope.user before it even has one (roughly speaking).
You two options for simple fixes (at least to my knowledge):
You can set $scope.user to the response from the server in a SEPARATE function, or some other service, and then use the response once it gets there. OR (the better 'simple' fix) use the $timeout service, which essentially tells your system to "chill until my async request gets done and I have my data."
Comment: Thank you other answers were good to, but you were the only one that mentioned the $timeout.

Ive seen some example of the $q library and but I stuck with ngResource for simplicity
Answer: User.query() returns an empty array because it needs an array of json objects [{...},{...}] as a response from your back-end. User.get assumes that your server returns an object like {"name":"Andi"} for example, so if your server response is correct there is no problem with get method.
$scope.user = User.get();

Than you have access to you name property as $scope.user.name
This plumk may help you link

Using angulars ngResource get method