how to take file as input and ignore the new line character

Question: The following is the content of fasta fileA:
>1
PLAARRPRRGKSLAGFESLACSFPVVSRGFLASRSARSLSSEGGTMPDNRQ
PRNRQPRIRSGNEPRSAPAMEPDGRGAWAHSRAALDRLEKLLRCSRCTNIL
REPVCLGGCEHIFCSNCVSDCIGTGCPVCYTPAWIQDLKINRQLDSMIQL

>2
PLWRPAVPDAGRARPVWSRWSAASLWFLKASLLPALRGAFHPKAGRCRIIGS
RGTGSRGSAPGTSLVPRPPWNRMVAVPGPTVAPRSTAWRSCCAARVVLTF*E
SLCV*EDVSTSSVVIV*VTALELDVQCVTPRPGYKT*R*ID

>3
TPPLWRPAVPDAGRAWPVSSRWPAASRWFPEASLLPALRGAFHPKAGRCRII
GSRGTGSRGSAPGTSLVPRPPWNRMVAVPGPTVAPRSTAWRSCCAARVVLTF

now i need to take the fileA as input and find out the mismatches present between 1 and 2 and then 1-3 and also find out the nucleotide change between them. I have written a program so far but it doesn't take fileA as input. kindly help
my problem is i need the fileA to be given as input, and the sequences contains new line character after every 51 nucleotides and my program considers the new line character also for finding out the mismatches.
Program:
$a=<>;$b=<>;
@mul=("$a","$b");

for($i=0;$i<scalar(@mul)-1;$i++) {
    $source=$mul[$i];
    print "\n\nComparision of source:  $mul[$i]\n";
    print "------------------------------------";
    for($j=$i+1;$j<scalar(@mul);$j++) {
        $sample=$mul[$j];
        print "\n$sample ";
        print "\n------\n";
        $t=mutate($source,$sample);
        print $t;
    }
}

sub mutate {
    my ($s1,$s2)=@_;
    $temp="";
    for($k=0;$k<length($s1);$k++) {
        $seq1=substr($s1,$k,1);
        $seq2=substr($s2,$k,1);
        if($seq1 ne $seq2) {
            $temp.="[$seq1($k)/$seq2($k)]";
        }
    }
    return $temp;
}

Comment: What is your question exactly?
Comment: To remove a new line character you can use chomp or use the regular expression s/\n//g
Comment: @aki i tried using chomp too... but its not givin the output.. unable to figure out the problem.
Comment: is this your actual file(I am assuming your file looks like as you pasted above). is it in linux or windows.
Comment: Can you please explain the problem clearly. Is this something like, Your file has three groups of lines, and between the groups you want to print the ratio of number of charactes matching to the total number of characters in the file.
Answer: You probably want to read paragraphs, which are marked by two newlines in a row.  Hence:
use strict;
use warnings;
my(@a);

{
    # Limit the scope in which you reset the $/ variable
    local($/) = "\n\n";
    while (<>)
    {
         s/\n+//gm;  # Remove all newlines
         push @a, $_;
    }
}

# Now your array contains three items with no newlines - process away...

Comment: Caveat: newlines in the input may be marked by "\r\n" rather than "\n".
Comment: @reinierpost: of course; they could also be marked by '\r' only (MacOS 9 or earlier).  Adapt if necessary.
Answer: If I understood your problem correctly, then here is what you can do to read the file from command line so that you can get results for different files.
Here we read each line and get the source number, then after chomp, append each line to corresponding source. then you can compare any line with any source content.
my $file = $ARGV[0];
open (FILE, $file);
my $file_content;
my $src_indx = 0;
while (my $line = <FILE>){
    chomp $line;
    $line =~ s/^\s+//;

    if ($line =~ /^\>(\d+)/){
        $file_content->{$1} = '';
        $src_indx = $1;

    }else{
        $file_content->{$src_indx} .= $line;
    }
}

print "\n\nComparision of source:  1 and 2\n";
print "------------------------------------\n";
$t = mutate($file_content->{1},$file_content->{2});
print $t;

sub mutate {
    my ($s1,$s2)=@_;
    $temp="";
    for($k=0;$k<length($s1);$k++) {
        $seq1=substr($s1,$k,1);
        $seq2=substr($s2,$k,1);
        if($seq1 ne $seq2) {
            $temp.="[$seq1($k)/$seq2($k)]";
        }
    }
    return $temp;
}

I have not modified your mutate function. If you use regular expression or split instead of substr, you can get better control in mutate too.
Let me know if this is not what you want.


Ask if user really want to close bootstrap modal

Question: I have a bootstrap modal. When it is closed some instructions are executed. But now I want to ask if user really want to close it (with a confirm window) What can i do?
Here is my code at the moment.
<code>$('#modal').on("hide.bs.modal", function (e) {
    //Instructions to execute when the modal is closed
});
</code>
Answer: Like this?
<code>$('#modal').on("hide.bs.modal", function (e) {
   if(confirm("Are you sure, you want to close?")) return true;
   else return false;
});
</code>
Or, just like this:
<code>$('#modal').on("hide.bs.modal", function (e) {
   if(!confirm("Are you sure, you want to close?")) return false;
});
</code>
Comment: Yes, it was exactly what I need. Thanks. It is easier than I thougt :)
Comment: Glad, I could help you.
Answer: <code>$('#modal').on("hide.bs.modal", function (e) {
  //Instructions to execute when the modal is closed
 if(!confirm("Are you sure, you want to close?")) return false;
});
</code>


How to see on Linux what network interface and source IP address is used for a route to a specific destination host?

Question: If I have multiple network interfaces (here: 2) on a Linux machine (here: Debian Lenny).
How do I see, over what network interface (NIC) a route to a specific destination host is going and what source IP address is used by default?
I have though of using
ping -I nic1 desthost.example.com
ping -I nic2 desthost.example.com

too see if both ways are possible. (Here: Both ways are possible)
I looked up the routing table
ip route show

But it's quite complex, so I thought, there must by a small simple tool, to just tell me:
"To destination host desthost.example.com it takes interface nicX and source IP address 10.0.0.1"
What is the simplest way of getting this information?
(And I'd rather not use tcpdump and set the interfaces in promiscous mode.)
Thanks.
Answer: Use ip route get <ip>.
Comment: or `ip -o route get $ipaddress | awk '{ print $5 }'`
Comment: And to get only the interface: `ip -o route get $ipaddress | perl -nle 'if(/dev\s+(\S+)/) {print $1}'`
Comment: ip -6 route get 240b:c020:104:5422:bb27:2:1d:134 for example doest print anything. But its pingable
Answer: what about route -C
Comment: route is deprecated. use iproute2.
Comment: Please make the answer somewhat more complete (e.g. *explain*). If I try the command I just get a header.
Answer: I use netstat -Wcatnp . You should try this command.
Comment: Recent Linuxes dropped `netstat` in favor of `ss`.
Answer: Even easier, I'd say nm-tool and if you only want the relevant line nm-tool | grep Device. That should output:
- Device: wlan0  [My router name] -----------------------------------------------

Comment: What is `nm-tool` and in what package is it provided? Something related to NetworkManager?
Comment: Yes, it required NetworkManager (which is not installed universally).


Positive definite matrix implies the **infimum** of eigenvalues are positive (second version)?

Question: I asked a similar question in here, but actually what I want to ask is more difficult as described below:
Suppose $P(x): \mathbb{R} \to \mathbb{R}^{n \times n}$ is always a positive semi-definite matrix. Now if there is a set $\Omega \subset \mathbb{R}$ such that we know the infimum of the determinant of $P(x)$ over $\Omega$ is always positive, then does it imply that the infimum (over $\Omega$) of the minimum eigenvalue of $P(x)$ is always positive? In a mathematical way:
Is the following conclusion correct?
\begin{equation}
    \inf_{x \in \Omega}\{\det(P(x))\}>0 \implies  \inf_{x \in \Omega} \{\lambda_{{\rm min}}(P(x)) \} > 0
\end{equation}.
Comment: No. Just take the $1x1$ matrices $P(x) = 1/sqrt(1+x^2)$ over $\Omega=\mathbb R$.
Comment: Or for $n=2$, $P(x) =diag( sqrt(1+x^2),1/sqrt(1+x^2))$.
Answer: No. Consider e.g. $P(x)=\operatorname{diag}(x,\frac1x)$ over $\Omega=[1,+\infty)$.
It is true, however, that if $\Omega$ is compact, $P$ is continuous and $P(x)$ is positive definite over $\Omega$, then $\inf_{x\in\Omega}\lambda_\min(P(x))>0$. This is because the eigenvalues of a matrix vary continuously with the matrix's entries and every continuous function attains its minimum on a compact set.
Answer: Originally, the text-part of the question asked whether we knew that, over $\Omega$, the determinant of $P$ is always positive.  This is different from the case that the infimum of the determinant is positive (the infimum condition implies that the determinant is always bounded away from zero).
For the edited question:
It is enough for $\Omega$ to be compact and $P$ to be continuous.  Suppose that $\Omega$ has the desired property and the infimum of the smallest eigenvalue goes to zero.  In this case, there exists a sequence $\{x_i\}$ so that $P(x_i)\in\Omega$ for all $i$ and $\lambda_{\min}(P(x_i))\rightarrow 0$.
Since the determinant is bounded from below and the determinant is the product of the eigenvalues, it must be that the largest eigenvalue of $P(x_i)$ is growing (without bound).  Since the magnitudes of the eigenvalues are bounded in terms of the maximum of the entries of the matrix, for an eigenvalue to grow without bound, the maximum of the entries of the matrix must also be growing.
We can find a subsequence $\{x_{i_j}\}$ so that in one particular entry of the matrix, the magnitude of that entry is growing without bound.  By sequential compactness, there is some subsequence that converges in $\Omega$.  However, since the magnitude of the entry is growing without bound, it follows that the corresponding entry of the limit must be $\pm\infty$, which is absurd.
Comment: You also need compactness.
Comment: Thanks. My question has been edited now.
Comment: Can you re-edit your answer? I do not quite understand what you are talking about, because your conclusion is not clear, though the description is easier to understand.
Comment: I've edited the answer with more details.


Minimum Requirements for ImageUnattend.xml Porition of WDS For Windows Server 2008 R2

Question: What are the minimum required fields for an unattended Windows Server 2008 R2 installation via Windows Deployment Service for the ImageUnattend.xml portion?
Answer: The absolute minimum settings are documented here Settings to Use for an Unattended Installation Note that these would be in WDSUnattend.xml.  Technically speaking you don't need any settings in the imageunattend.xml file.  It just means that you get to go through setup after system install.  To automate the OOBE portion you need at least the following sections listed here ( Settings to Use for Automating Windows Welcome ) and tagged with server 2008.
I've never tried just the minimum as I've always tried to do as much as possible at deployment.


Why do Drupal core functions get node object instead of nid as argument?

Question: Most (if not all) of Drupal functions accept $node object instead of $nid as argument, like node_type_get_name($node), so we should first write node_load($nid) and send its long output to the functions, whereas they can call the node_load() function themselves and reduce number of developers' codes. What's the reason?
Comment: Why would you want to load the node again for every single API function? What an incredible slowdown that would be. Loading the object once and passing it around is definitely a better approach.
Answer: I think it's to avoid the repetition of node_load that could occur.
I searched a little in the source and you can see node_type_get_name($node) is called from others functions which also take a $node object argument, node_promote_action for exemple
function node_promote_action($node, $context = array()) {
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
}

It seems DRY to me. Imagine you gave a nid as argument in node_promote_action :
function node_promote_action($nid, $context = array()) {
  $node = node_load($nid);
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($nid), '%title' => $node->title));
}

And then node_load again in node_type_get_name :
function node_type_get_name($nid) {
  $node = node_load($nid); // repetition
  $type = _node_extract_type($node);
  $types = _node_types_build()->names;
  return isset($types[$type]) ? $types[$type] : FALSE;
}

With nid as argument, each time a node related function (A) need to process some node's properties (often if not always), they would call node_load. This would lead to unnecessary repetition when another node processing function (B) is called inside the first (A), just like in the above example.


(= 1/5 0.2) is false?

Question: This is in both common lisp (clisp and sbcl) and scheme (guile). While these are true:
<code>(= 1/2 0.5)
(= 1/4 0.25)
</code>
This turns out to be false:
<code>(= 1/5 0.2)
</code>
I checked the hyperspec, it says that "=" should check for mathematical equivalency despite the types of the arguments. What the heck is going on?
Comment: [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768)
Comment: @Darthtater Well yeah, but given the spec for "=", the binary representation or the data type shouldn't matter, as "=" is specified to check for mathematical equivalency despite differences in binary representations / data types. Its the job of the implementators to check that "=" works as the spec says, isn't it? though i do understand that it might be difficult if the floating point format does not provide the precision to check. the implementations should find a workaround, no?
Comment: It is possible that the binary representations are not equal, in which case you would want to check if they are approximately equal.
Comment: That's pretty common in most computer languages.  Unless you are using a data type with the right precision, the actual result of a calculation may not be what you think.
Comment: What you're perhaps meaning to propose is to ban flonums outright, and exclusively use decimal floating-point numbers. That'd work but be much slower since no common processor natively supports them, so it all has to be implemented in software.
Answer: The problem is that 0.2 really is not equal to 1/5. Floating point numbers cannot represent 0.2 correctly, so the literal 0.2 is actually rounded to the nearest representable floating point number (0.200000001 or something like that). After this rounding occurs, the computer has no way of knowing that your number was originally 0.2 and not another nearby non-representable number (such as 0.20000000002).
As for the reason why 1/2 and 1/4 work its because floating point is a base 2 encoding and can accurately represent powers of two.
Comment: My point was, it evaluates to `13421773/67108864`.  So it is not equal to 1/5.  Which is not surprising, since `0.2` really stands for a floating point representation of `0.2`, which is not 0.2.
Comment: What is interesting, in Maxima: `:lisp (= 1/5 0.2)` evaluates to `T`, but `:lisp (rational 0.2)` is `3602879701896397/18014398509481984`.
Comment: but isn't that going against the spec for "="? why not do a workaround? like, when encountering a "=", evaluate all floating point calculations in the arguments with BCD or right in their ascii representation. or even better, if encountering floating point arguments, evaluate all other arguements with floating point.
Comment: never mind, i don't think the second option would work. and i know what's wrong with the first. i just feel perplexed that while the standard says one thing, the implementations do something different. and i always though that lisps strove for mathematical correctness, given their use of rationals instead of floating point to represent fractions. this is kind of a downer.
Comment: @JanHlavacek you didn't try it did you? it doesn't work, it's still false. would be neat if it did though. oh god, it evaluates to 13421773/67108864. i can't believe this is right for lisp.
Comment: You must write your own approximately equal test with a certain tolerance.
Answer: please read What every Computer Scientist should know about Floating Point Numbers
Answer: This actually depends on what is coerced to what. If you think about it, then rational is more precise, so it makes sense to coerce to rational for comparison, rather then to float, however, if you consciously want to compare numbers as being floats you can force it by doing something like below:
<code>(declaim (inline float=))
(defun float= (a b)
  (= (coerce a 'float) (coerce b 'float)))
(float= 0.2 1/5) ; T
</code>
Actually... there's more to it, since floats provide you with things like not-a-number, positive-infinity and negative-infinity. Infinities, for example, for the 64-bit floats are 10e200 iirc, so, there's nothing stopping you from creating a rational larger then infinity (or smaller then negative infinity!), so, perhaps, if you want to be super precise, you'd need to consider those cases too. Likewise a comparison to not-a-number must always give you nil...
Answer: However, in scheme you have exact numbers, so you may ask (note the #e prefix, which means the number which follows is to be treated exactly):
<code>> (= 1/5 #e0.2)
#t
</code>
Comment: That is implementation-dependent, BTW.  Some implementations implement `#e0.2` as the read-time equivalent of `(inexact->exact 0.2)`.

(= 1/5 0.2) is false?


At Vis.js, timeline, refresh display on change data

Question: i have set a html-form in this text box i change the title, content, start- and end-time. By a click on 'okay'-button change the dataitem.
How can i refresh the timline?
Code from onlclick-Button
<code>    var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData._data[selItemNr].start = start;
        timeline.itemsData._data[selItemNr].end = end;
        timeline.itemsData._data[selItemNr].title = tbTitle.value;
        timeline.itemsData._data[selItemNr].content = tbContent.value;
        timeline.redraw();
    }
};
</code>
The values of item is correct set also the start and end, but the timline shows nothing change.
regards Mario
Answer: i have found the solution:
The javascrtipt class store the _data.id into cuItemId
and in the OnClick function i call timeline.itemdData.update().
<code>var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData.update({id: cuItemId, start: start,end: end, title: tbTitle.value, content: tbContent.value});
    }
};
</code>
That works fine.
regards Mario


Não acha o HttpContext.Current

Question: Estou tentando criar um UrlHelper da seguinte forma:
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

Já fiz a referencia a System.Web, como vi como solução em vários lugares.
using System.Web;

O estranho que é esse using está cinza (Visual Studio 2015) o que mostra que ele nem está usando essa referencia.
O erro é:

Error CS1061  'HttpContextBase' does not contain a definition for
  'Current' and no extension method 'Current' accepting a first argument
  of type 'HttpContextBase' could be found (are you missing a using
  directive or an assembly
  reference?)
Comment: você pode user o HttpContext  do controller, é só chamar HttpContext.Request.RequestContext (sem o current), que funciona da mesma forma.
Comment: você está utilizando qual mvc no vs2015? vnext? se for vnext, pode esquecer o system.web.
Comment: o projeto é mvc 5, asp.net aplication. vs2015, vnext? não sei dizer...
Comment: Tenta assim UrlHelper urlHelper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
Comment: vnext é o mvc6.
Comment: Funcionou! Estranho, pq não funciona com using?
Comment: O Using está certo, o problema é que HttpContext que voce tava puxando era do Controller e nao do SYSTEM.WEB
Answer: Do SOen:
Para ter uma referência ao HttpContext.Current você precisa trocar o termo
HttpContext.Current

por
System.Web.HttpContext.Current

Isso é porque a classe Controller define uma propriedade com o nome HttpContext, definida como
public HttpContextBase HttpContext { get; }

HttpContext na classe Controller retorna um HttpContextBase que não tem a propriedade Current.
Por isso você precisa usar o namespace qualificado

Não acha o HttpContext.Current


Cobrança de taxa de entrega: às vezes funciona e as vezes não

Question: Tenho um formulário de entrega que utiliza um arquivo (form.js) onde contem os dados de cobrança por CEP, até ai tudo bem, minha dúvida é, porque as vezes ele cobra e depois não cobra, sendo o mesmo CEP?
Exemplo: Tem dia que o CEP 20240-200 ele reconhece e cobra R$ 4,30 e no outro não! Pior, as vezes tem mais de um pedido para o mesmo CEP e ele NO MESMO DIA cobra para um e não cobra para outro pedido, como isso pode acontecer????
Segue o CODIGO completo desse arquivo:
 //aqui eu pego o cep
var cep = document.getElementById("cep").value;

//verifica se deve incrementar ou não
if(cep == "20040-010" || cep == "20071-002" || cep == "20090-910" || cep == "20210-010" || cep == "20080-102" || cep == "20230-130" || cep == "20081-250" || cep == "20090-030" || cep == "20090-030" || cep == "20211-340" || cep == "20211-351" || cep == "20221-240" || cep == "20221-250" || cep == "20230-010" || cep == "20230-011" || cep == "20230-025" || cep == "20230-150" || cep == "20230-160" || cep == "20230-240" || cep == "20231-016" || cep == "20231-030" || cep == "20231-031" || cep == "20231-050" || cep == "20211-005" || cep == "20231-085" || cep == "20230-014" || cep == "20231-004" || cep == "20021-180" || cep == "20240-180" || cep == "20240-051" || cep == "20211-010" || cep == "20230-170" || cep == "20230-024" || cep == "20240-050" || cep == "20230-050" || cep == "20231-006" || cep == "20090-010" || cep == "20230-901" || cep == "20040-051" || cep == "20241-080" || cep == "20221-901" || cep == "20051-011" || cep == "20021-190" || cep == "20240-200" || cep == "20230-170" || cep == "20231-015" || cep == "20211-350" || cep == "20231-020" || cep == "20061-030"){

        //se for um dos ceps acima, incrementa 4 no valor final
    taxa = 4.30;

    //verifica se deve incrementar ou não
}if(cep == "20241-220" || cep == "22210-015" || cep == "22220-000" || cep == "20241-160" || cep == "20021-040" || cep == "20241-150" || cep == "22210-010" || cep == "22211-230" || cep == "22220-000" || cep == "22220-070" || cep == "22221-060" || cep == "22211-200" || cep == "22221-020" || cep == "20241-180" || cep == "20240-200"){

        //se for um dos ceps acima, incrementa 5.5 no valor final
    taxa = 6.0;

}if(cep == "20050-091" || cep == "20060-050" || cep == "20071-000" || cep == "20080-003" || cep == "20081-000" || cep == "20081-050" || cep == "20090-000" || cep == "20090-003" || cep == "20231-092" || cep == "24938-600" || cep == "20051-002" || cep == "20090-050" || cep == "20231-046" || cep == "20231-047" || cep == "20231-048" || cep == "20090-001" || cep == "20231-093" || cep == "20051-011" || cep == "20060-010" || cep == "20050-002"){

    //se for um dos ceps acima, incrementa 3.5 no valor final
    taxa = 3.8;

}if(cep == "20031-170" || cep == "20040-004" || cep == "20040-902" | cep == "20021-360" || cep == "20040-020" || cep == "20040-908" || cep == "20071-000" || cep == "20230-070" || cep == "20071-004" || cep == "20040-009" || cep == "20230-060"){

    //se for um dos ceps acima, incrementa 3 no valor final
    taxa = 3.30;

}if(cep == "20010-010" || cep == "20020-906" || cep == "20031-908" || cep == "20031-917" || cep == "20040-001" || cep == "20040-006" || cep == "20050-090" || cep == "20070-022" || cep == "20031-909" || cep == "20031-904" || cep == "20021-390" || cep == "20031-919" || cep == "20031-912" || cep == "20031-905" || cep == "20050-060" || cep == "20031-901" || cep == "20031-924" || cep == "20051-040" || cep == "20031-901" || cep == "20003-191" || cep == "20241-110" || cep == "20050-030"){

    //se for um dos ceps acima, incrementa 2.5 no valor final
    taxa = 2.80;

}if(cep == "20010-020" || cep == "20011-020" || cep == "20011-030" || cep == "20011-040" || cep == "20011-901" || cep == "20020-000" || cep == "20010-170" || cep == "20011-000" || cep == "20021-260" || cep == "20021-350" || cep == "20031-040" || cep == "20031-050" || cep == "20031-130" || cep == "20031-204" || cep == "20021-245" || cep == "20040-002" || cep == "21335-253" || cep == "20040-031" || cep == "20030-041" || cep == "20040-000" || cep == "20004-002" || cep == "20040-003" || cep == "20040-007" || cep == "20011-010"){

    //se for um dos ceps acima, incrementa 1.7 no valor final
    taxa = 2.00;

}if(cep == "20010-090" || cep == "20020-100" || cep == "20021-130" || cep == "20021-315" || cep == "20030-001" || cep == "20031-000" || cep == "20031-003" || cep == "20031-010" || cep == "20031-050" || cep == "20031-141" || cep == "20031-143" || cep == "20031-005" || cep == "20031-001" || cep == "20020-903" || cep == "20031-144" || cep == "20030-080" || cep == "20031-142" || cep == "20031-120" || cep == "20031-007" || cep == "20010-009" || cep == "20031-913" || cep == "20021-370" || cep == "24220-280"){

    //se for um dos ceps acima, incrementa 1.2 no valor final
    taxa = 1.50;

}if(cep == "20020-010" || cep == "20020-040" || cep == "20020-080" || cep == "20021-060" || cep == "20021-120" || cep == "20021-900" || cep == "20021-903" || cep == "20030-002" || cep == "20030-015" || cep == "20030-013" || cep == "20030-020" || cep == "20030-021" || cep == "20030-060" || cep == "20030-070" || cep == "20030-120" || cep == "20002-080" || cep == "20003-021" || cep == "20030-905" || cep == "20030-015"){

    //se for um dos ceps acima, incrementa 0.7 no valor final
    taxa = 1.00;

}

total += taxa;

if(taxa != 0){
    //caso a taxa seja diferente de 0, mostra ao usuário
    document.getElementById("idTaxa").innerHTML = "Custo adicional: R$ " + taxa;
}

Desde já agredeço e MUITO a atenção de todos!!
Comment: Alessandro será muito dificil que alguém possa olhar para todo esse código. Podes tentar isolar o pedaço que pode estar a dar-te problemas e descrever melhor o problema em si?
Comment: Oi Sergio, a parte do CEP é essa:
Answer: Sugiro algumas melhorias nesse código:

Você possui vários CEPs para aplicar uma mesma taxa, agrupe esses CEPs em uma estrutura de dados, de forma que fique mais simples de compreender o código e mais simples de manipulá-los, sugiro um array ou um map nesse caso.
Você possui vários IFs seguidos sem o uso do ELSE. Nesse caso você está perdendo performance, ou até mesmo pode ter um erro de lógica aí, dado que por mais que seja aplicada a taxa de 4.30 que está no primeiro IF, o fluxo do seu algoritmo ainda passará verificando em TODOS os outros IFs.
No seu quarto if tem o seguinte trecho de código: cep == "20040-902" | cep == "20021-360". Nesse caso você está utilizando um operador bit a bit, onde esse trata seus operandos como um conjunto de 32 bits e não o dado como um todo, embora não faça muita diferença no seu caso dado que serão retornados apenas 1 ou 0 e Javascript traduz esses números para true ou false, acredito que ele não era para estar ai, mais detalhes aqui.

Espero ter ajudado =)
Código com as minhas sugestões:
    var cep = document.getElementById("cep").value;
    var taxa = 0;

    var cepRateMap = (function() {
        var map = new Map();

        map.set(4.30, [
            "20040-010", "20071-002", "20090-910", "20210-010", "20080-102",
            "20230-130", "20081-250", "20090-030", "20090-030", "20211-340",
            "20211-351", "20221-240", "20221-250", "20230-010", "20230-011",
            "20230-025", "20230-150", "20230-160", "20230-240", "20231-016",
            "20231-030", "20231-031", "20231-050", "20211-005", "20231-085",
            "20230-014", "20231-004", "20021-180", "20240-180", "20240-051",
            "20211-010", "20230-170", "20230-024", "20240-050", "20230-050",
            "20231-006", "20090-010", "20230-901", "20040-051", "20241-080",
            "20221-901", "20051-011", "20021-190", "20240-200", "20230-170",
            "20231-015", "20211-350", "20231-020", "20061-030"
        ]);
        map.set(6.0, [
            "20241-220", "22210-015", "22220-000", "20241-160", "20021-040",
            "20241-150", "22210-010", "22211-230", "22220-000", "22220-070",
            "22221-060", "22211-200", "22221-020", "20241-180", "20240-200"
        ]);
        map.set(3.8, [
            "20050-091", "20060-050", "20071-000", "20080-003", "20081-000",
            "20081-050", "20090-000", "20090-003", "20231-092", "24938-600",
            "20051-002", "20090-050", "20231-046", "20231-047", "20231-048",
            "20090-001", "20231-093", "20051-011", "20060-010", "20050-002"
        ]);
        map.set(3.3, [
            "20031-170", "20040-004", "20040-902", "20021-360", "20040-020",
            "20040-908", "20071-000", "20230-070", "20071-004", "20040-009",
            "20230-060"
        ]);
        map.set(2.8, [
            "20010-010", "20020-906", "20031-908", "20031-917", "20040-001",
            "20040-006", "20050-090", "20070-022", "20031-909", "20031-904",
            "20021-390", "20031-919", "20031-912", "20031-905", "20050-060",
            "20031-901", "20031-924", "20051-040", "20031-901", "20003-191",
            "20241-110", "20050-030"
        ]);
        map.set(2.0, [
            "20010-020", "20011-020", "20011-030", "20011-040", "20011-901",
            "20020-000", "20010-170", "20011-000", "20021-260", "20021-350",
            "20031-040", "20031-050", "20031-130", "20031-204", "20021-245",
            "20040-002", "21335-253", "20040-031", "20030-041", "20040-000",
            "20004-002", "20040-003", "20040-007", "20011-010"
        ]);
        map.set(1.5, [
            "20010-090", "20020-100", "20021-130", "20021-315", "20030-001",
            "20031-000", "20031-003", "20031-010", "20031-050", "20031-141",
            "20031-143", "20031-005", "20031-001", "20020-903", "20031-144",
            "20030-080", "20031-142", "20031-120", "20031-007", "20010-009",
            "20031-913", "20021-370", "24220-280"
        ]);
        map.set(1.0, [
            "20020-010", "20020-040", "20020-080", "20021-060", "20021-120",
            "20021-900", "20021-903", "20030-002", "20030-015", "20030-013",
            "20030-020", "20030-021", "20030-060", "20030-070", "20030-120",
            "20002-080", "20003-021", "20030-905", "20030-015"
        ]);

        return map;
    }());

    cepRateMap.forEach(function(values, key) {
        if (values.indexOf(cep) !== -1) {
            taxa = key;
        }
    });

    total += taxa;

    if (taxa != 0) {
        var elementRate = document.getElementById("idTaxa");
        elementRate.innerHTML = "Custo adicional: R$ " + taxa;
    }

Comment: Pedro Muitoooooooo obrigado!!
Comment: Pedro, pintou um problema, não sei pq agora no e-mail não aparece mais a informação da taxa! `$entrega = $_POST["taxadeentrega"];` no formulário do site aparece a taxa (`
Taxa de Entrega:

`, mas no e-mail que é processado pelo arquivo mail.php ele não está mais lendo, não envia a informação. Será que é algo nesse parte do código do java? `var taxa = 0;
var taxadeentrega = total - taxa;
var total = 0.00;
`


won't display in Ruby on Rails

Question: First and third div are displayed, but the second won't display at any cost, even with CSS disabled.
<%= provide(:title, 'Ask a question')%>

Ask a Question

  <% if logged_in? %>
    <%= render 'question_form' %>
  <% else %>

Please login to ask/or answer questions

  <% end %>

test test

Comment: `` close the comment properly, to ``
Answer:

If you check the syntax highlighting of your question, it should become apparent.
Comment: well vim did not show me anything wrong. Now I just deleted them both, and it worked. But when I've put them back including the same spacing they worked as well. So why is that???

won't display in Ruby on Rails


Placement of earlier features in more complex features in CNN

Question: I'm trying to understand convolutional neural networks better. I've been doing different tutorials, but there are some basics concerning how the hidden units represents features that I really would like to have clarified.
Look at the following picture (from slide 31 from www.cs.stanford.edu/people/ang//slides/DeepLearning-Mar2013.pptx by Andrew Ng):

When combining features from layer 3 (object parts) to layer 4 (object models), how does the specific hidden unit know where to place the different features? I would guess it would know that the hidden unit should represent 0.3 x "mouth feature" and 0.6 x "eyebrow feature", but how does it know to place the eyebrow above the mouth?
Thanks. Any links to books or websites with easy-to-understand material on this would also be greatly appreciated!
Answer: A neural network does not actually know/understand like humans do.
A neural network is nothing but a fancy name for application of Non-linearities to a signal.
That being said, this knowing simply comes from training the Neural Network over thousands/millions of examples. This training gradually keeps optimizing the weights and biases to minimize the loss function, which in this case leads to combination of the right parts of the images.
This must sound dull, but this is what neural networks do.


Changing conjunction and disjunction in equivalent boolean functions.

Question: I have some difficulties to prove that if two equivalent boolean functions contain only ∧, ∨ and $\neg$ than we can change ∧ to ∨ and vice versa and the result functions will remain equivalent.
There's a hint to solve it with the induction and de Morgan's laws, but I've no idea how to use it.
Thanks in advance!
Comment: I was wondering if you would perhaps consider changing the symbols $\lor$ and $\land$ in the title of the question to the words 'disjunction' and 'conjunction'. I'm just thinking it might make it easier to match on searches.
Answer: HINT
First, get some precise definitions going, so you can refer to those in your proof.
So, relative to any expression or function $\phi$ built up from $\neg$, $\lor$, and $\land$, define the expression $\phi^D$ to be the result of changing all $\land$'s into $\lor$'s and vice versa. Formally and recursively:

$A^D = A$ if $A$ is an atomic sentence
$(\neg \phi)^D = \neg \phi^D$
$(\phi \land \psi)^D = \phi^D \lor \psi^D$
$(\phi \lor \psi)^D = \phi^D \land \psi^D$

OK, so what you are asked to prove is that for any $\phi$ and $\psi$ built up from $\neg$, $\lor$, and $\land$: If $\phi \Leftrightarrow \psi$ then $\phi^D \Leftrightarrow \psi^D$
Now, how do you prove this?  Here is one strategy:
Relative to any expression or function $\phi$ built up from $\neg$, $\lor$, and $\land$, define the expression $\phi'$ to be the sentence that one obtains by putting a negation in front of every atomic sentence occurring in $\phi$. Formally and recursively:

$A' = \neg A$ if $A$ is an atomic sentence
$(\neg \phi)' = \neg \phi'$
$(\phi \land \psi)' = \phi' \land \psi'$
$(\phi \lor \psi)' = \phi' \lor \psi'$

Use this to prove (using induction) the following Lemma's:

For any $\phi$ built up from $\neg$, $\lor$, and $\land$: $\phi^D \Leftrightarrow \neg \phi'$

For any $\phi$ and $\psi$ built up from $\neg$, $\lor$, and $\land$: If $\phi \Leftrightarrow \psi$ then $\phi' \Leftrightarrow \psi'$

The result you have to prove follows quickly from these two Lemma's.
Comment: @VladislavSemenov Glad I could help! :)


SSRS- Account and Contact

Question: I have a requirement such that there is one parameter XXX field(in CRM) which we have for both contact and account(which should be a dropdown parameter). If the user is entering some value in XXX and selecting contact or account from that drop down parameter. The results have details(which is few other fields like address etc.) depending upon the contact or account the user selects. Firstly, Is it possible to get contact and account in dropdown(since contact and account both are datasets). Please let me know. Thanks
Comment: You might want to mention that this is an SSRS report parameter, and state your version of CRM.
Comment: Dynamics 365(on premise) and SSRS 2012
Answer: You can do it. Whatever you want, write the query from filteredviews & prepare the dataset for parameter. Bind it to combobox using the steps below. (Though you can have combined account+contact in one combobox using union query & addl. parameter of account/contact identifier dropdown, I won't recommend it)

Right click the parameter
Select "Available Values" section
Click the "Get values from a query" option
Select the appropriate dataset and fields

How many records we are talking here? 10s, 100s, 1000s. You can have a search box to filter the bulk data. Read this article
Refer this with detailed steps for full understanding of cascading filters/multi-select params in SSRS reporting.

SSRS- Account and Contact


Unable to use a hyphen in a Drupal 7 text field

Question: I've got a simple field of type "text", widget = "text field" (Drupal 7).
I am able to use special characters like &(%, but when I try to type a hyphen, there is no result. I can use a rich text field, but I only want plain text.
I am able to use the ASCII code like S-26 where I really just want S-26.
This was not an issue in Drupal 6.
Thanks very much!
Comment: are you using text field with custom form?
Comment: Do you mean you cannot type it, like, literally, keypress on keyboard does nothing? If so, then you have javascript or browser problem. On what browser it happened? What are your results from other browsers?

Or you can type it, and it's just not rendered?
Comment: I have the same problem, I can copy-paste it but can't type it. Weird problem. Could googlemaps (openlayers) maybe cause this javascript problem?
Comment: @Aboodred1, no I am not.
Comment: @Mołot That's a great suggestion. Unfortunately (?), the error seems to have "gone away on its own". I can't test it or reproduce it.
Comment: @Mr.B I am also using OpenLayers, but I can't say now whether that's an issue.
Comment: I can confirm that it had something to do with Openlayers. I removed the map on that page and hyphen and underscores where available again. Did not need/find a good solution for it yet.
Comment: @Mr.B, I wonder if it has something to do with Keyboard Controls on your Map (preset). I just noticed that the hyphen is also the zoom out. It's possible that we were both pressing the zoom out, but if the map was not visible on the screen we wouldn't have noticed it. I'm 99% sure this is the issue. Under "behaviors" in your map settings, disable keyboard controls.
Answer: The zoom behavior of the map is responsible for this unwanted behavior.
You need to disable keyboard controls on the map in your node edit form.
This could be the default map or the default map installed by geofield.
Comment: That was also my finding in the last comment above. Thanks!
Answer: I finally found the solution after spending a lot of time in OpenLayers library.
Basically the solution is to create a new behavior which will override the function OpenLayers.Control.KeyboardDefaults, after that you will have to comment the lines which use the - and + code keys, and in the end force to render the behavior.
This Solution works for Drupal 7
Create a new module and don't forget to add these 2 lines in the info file:
dependencies[] = openlayers
dependencies[] = geofield

The new behavior
function mymodule_openlayers_behaviors(){
  return array(
    'openlayers_behavior_OKC' => array(
      'title' => t('Override key control'),
      'description' => t('Remove the - and + zoom key'),
      'type' => 'behaviors',
      'behavior' => array(
        'class' => 'openlayers_behavior_OKC',
        'parent' => 'openlayers_behavior',
        'path' => drupal_get_path('module', 'mymodule') . '/includes',
        'file' => 'openlayers_behavior_OKC.inc',

      ),
    ),
  );
}

the file includes/openlayers_behavior_OKC.inc will call the js to override the function.
class openlayers_behavior_OKC extends openlayers_behavior {
  /**
   * Provide initial values for options.
   */
  function options_init() {
    return array(
      'keyboarddefaults' => '',
    );
  }

  // /**
  //  * Render.
  //  */

  function render(&$map) {
      drupal_add_js(drupal_get_path('module', 'mymodule').'/js/openlayers_behavior_OKC.js');
      return $this->options;
    }

}

after that you just need to rewrite the function OpenLayers.Control.KeyboardDefaults (I've comment the lines related to the + and - but you can choose or add new keys if you want to)
Here is the file js/openlayers_behavior_OKC.js
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Keyboard Defaults Behavior.  Implements the KeyboardDefaults OpenLayers
 * Control.
 */
OpenLayers.Control.KeyboardDefaults = OpenLayers.Class(OpenLayers.Control, {

    /**
     * APIProperty: autoActivate
     * {Boolean} Activate the control when it is added to a map.  Default is
     *     true.
     */
    autoActivate: true,

    /**
     * APIProperty: slideFactor
     * Pixels to slide by.
     */
    slideFactor: 75,

    /**
     * APIProperty: observeElement
     * {DOMelement|String} The DOM element to handle keys for. You
     *     can use the map div here, to have the navigation keys
     *     work when the map div has the focus. If undefined the
     *     document is used.
     */
    observeElement: null,

    /**
     * Constructor: OpenLayers.Control.KeyboardDefaults
     */

    /**
     * Method: draw
     * Create handler.
     */
    draw: function() {
        var observeElement = this.observeElement || document;
        this.handler = new OpenLayers.Handler.Keyboard( this,
                {"keydown": this.defaultKeyPress},
                {observeElement: observeElement}
        );
    },

    /**
     * Method: defaultKeyPress
     * When handling the key event, we only use evt.keyCode. This holds
     * some drawbacks, though we get around them below. When interpretting
     * the keycodes below (including the comments associated with them),
     * consult the URL below. For instance, the Safari browser returns
     * "IE keycodes", and so is supported by any keycode labeled "IE".
     *
     * Very informative URL:
     *    http://unixpapa.com/js/key.html
     *
     * Parameters:
     * evt - {Event}
     */
    defaultKeyPress: function (evt) {
        var size, handled = true;
        switch(evt.keyCode) {
            case OpenLayers.Event.KEY_LEFT:
                this.map.pan(-this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_RIGHT:
                this.map.pan(this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_UP:
                this.map.pan(0, -this.slideFactor);
                break;
            case OpenLayers.Event.KEY_DOWN:
                this.map.pan(0, this.slideFactor);
                break;

            case 33: // Page Up. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, -0.75*size.h);
                break;
            case 34: // Page Down. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, 0.75*size.h);
                break;
            case 35: // End. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0.75*size.w, 0);
                break;
            case 36: // Home. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(-0.75*size.w, 0);
                break;

/*            case 43:  // +/= (ASCII), keypad + (ASCII, Opera)
            case 61:  // +/= (Mozilla, Opera, some ASCII)
            case 187: // +/= (IE)
            case 107: // keypad + (IE, Mozilla)
                this.map.zoomIn();
                break;
            case 45:  // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
            case 109: // -/_ (Mozilla), keypad - (Mozilla, IE)
            case 189: // -/_ (IE)
            case 95:  // -/_ (some ASCII)
                this.map.zoomOut();
                break; */
            default:
                handled = false;
        }
        if (handled) {
            // prevent browser default not to move the page
            // when moving the page with the keyboard
            OpenLayers.Event.stop(evt);
        }
    },

    CLASS_NAME: "OpenLayers.Control.KeyboardDefaults"
});


Is this progression considered to be in A mixolydian?

Question: I have a chord progression that goes:
A Bm D A G
Other areas of the song also have an A, G, D, A progression.
Would this song considered to be in A mixolydian vs A major or D major since the root seems to A, and the 7th is a flat 7th?
Comment: Does the progression stay on each chord the same amount of time or are there parts where maybe two chords are played in the same measure.  A sound file might also help clarify.  Or some notation.  What about the melody?  More information might be needed to make a definitive declaration here.
Comment: This can only be answered properly if you let us know the harmonic rhythm.
Comment: It's a song in 4/4. The A Bm D A G progression is completely even except the last G, which is used as a quick turnaround to get back to the first A. In the A G D A progression each chord takes one measure. I'd love to be able to link to or specify the exact song, however, I'm afraid this will get closed because analysis of specific works are not allowed. Perhaps it's time we finally amend that rule, or is this question out of scope as well?
Comment: The rule has been amended - check the help desk.  Adding a specific work as an example here will not get your question closed.  But the information you recently provided is very helpful. You could amend the question with the new information.  Add it at bottom preceded by "EDIT:" (bold and all caps).
Answer: The scale that fits over all the chords given is:
A B C# D E F# G A
Those notes are in the D Major Scale but the intended root is A as repeated at beginning and end of chord progression in other areas of song and starts the song. Therefore it is A Mixolydian.
Answer: The song definitely has the more an A Mixolydian feel then a D major feel. Both contain similar chord progressions, but there are a few signs showing A Mixolydian is the better way to look at it.
First of all, the progression itself centers around A as the tonic. Also note that the dominant chord (E major) is not present in this progression which would very strongly suggest an A major tonally. The VII chord (G major) is very present and used in a very Mixolydian way.
Let's examine the Roman Numeral Analysis that would be associated with each mode choice.
In D major the results would be

V  vi  I  V  IV

and

V  IV  I  V

Not unheard progressions, but if we instead analyze it in A Mixolydian we get:

I  ii  IV  I  VII

and

I  VII  IV I

This analysis shows how the progression centers more around A then D thus makes more sense to call it A Mixolydian.
Comment: My only problem with this, @Dom, is that G isn't a usual cadential point for the Mixolydian mode; it tends to have a "pre-dominant" function in Mixolydian. The Mixolydian tenor (quasi-dominant) is D, which _might_ apply to the second phrase. G and A, however, are fairly normal cadential points for D Major, and the second progression is in fact a fairly standard half-cadence. It isn't _that_ unusual to start with a dominant and avoid authentic cadences in a piece - it makes for a fairly restless character normally.
Comment: If E major was present, wouldn't it suggest G major instead? Even though no E chord is present, the G major chord is, and it shares chord tones (G and B) with E minor, the dorian chord of D major. The same applies to the Bm chord, where D and F# - major 3rd of D - are present. Because of the common tones, the vi chord acts like a tonic and the IV chord acts like a subdominant. Are you sure there is no D major feel here?
Comment: @Costagero the progression obviously centers around A as tonic. While the A major chord occurs 4 time the D major occurs 2 times and the chord progressions start and end with it. E major being present would suggest A major not G major as E major is the dominant chord of A. It not being present, but A still being the center shows it's most appropriate to think modally.
Comment: In the first section, there is harmonic motion from A major to B minor. The stress and resolution movement is there and D major follows. Particularly if this is the beggining of the piece, I don't think it is obvious that A is such a center.
Comment: @Costagero look at the two analysises. It's `I  ii  IV  I  VII` in A mixoldyian and  `V  vi  I  V  IV ` in D major. I think the analysis clearly show's what the progressions revolve around.
Comment: Yes, but what about the common chord tones? If you consider reharmonization, the vi and IV can be substitutions for I and ii, respectively. The progression would become V I V ii.
Comment: @Costagero IV is not a tonic chord it is a predominant. While vi is a substituent for a tonic in some cases, looking at it as ii going to IV (which has the same property) makes much more sense in context of the progression.
Comment: I didn't say it was a tonic. It is, indeed, a predominant, like the ii chord. Please read carefully.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/21692/discussion-between-costagero-and-dom).
Answer: All the notes involved are present in A mixolydian, which is the 5th mode of D major = D ionian. The two scales are relative to each other: they share the same notes. If it was a modal progression, staying in A7 for most of the time, you could say it was in A mixolydian. But that's not the case.
There is a G# in A major, not a G, so that's wrong too.
It would be more appropriate to say this chord progression is in D major. It is not that common to consider a mode as the key to a piece, unless it clearly has a modal flavor. We use the parent major scale for that.
Let's take a closer look:

Bm chord -  B, D, F#
D chord  -  D, F#, A

As you can see, there is little difference between the two chords. In fact, Bm can be a voicing for a D6 chord! The vi chord can be a substitute for the I chord.
This also happens with the G:

G chord  -  G, B, D
Em chord -  E, G, B

The happens here. The IV chord can be a substitute for the ii chord.
Because of the notes they share, the chords can be used to reharmonize progressions. Take a look at this Berklee course.
If you consider reharmonization, your original progression could be:
<code>V I V ii
</code>
This has a clear D major feel, and it can be what your musical ear is actually perceiving.
Comment: Since A Mixolydian contains exactly the notes in D major, the main factor will be about where the song gravitates to. D and Bm, and G and Em are NOT the same. D6 is a revoicing of Bm7 - not mentioned. To have a clear Dmaj feel it would gravitate to D, rather than the A used.
Comment: Reharminization is not appropriate for an analysis as you are literally changing the harmony. It is done in playing to spice up a line and keep **most** of the function.
Comment: I disagree. We are talking about simple reharmonization - reharminization by areas - in which you preserve the harmonic features of the chords. Dominants for dominant (V and vii); Predominants for predominant (ii and IV); Tonics for tonic (I, iii and vi). That's because the substitutions keep the important chord tones, the ones that define harmonic motion. Things like tritone substitutions and secondary dominants do alter the harmony, but that's not the case here.
Comment: If that was the case we would only ever use 3 chords in analysis.
Comment: We do not use 3 chords in analysis, but we do think of harmonic motion when we want to find the key to a song :) Your analysis was correct. What I did was not an analysis, it was an explanation.
Answer: It's very common to use chords 'borrowed' from the parallel. As in A maj - with A, Bm, C#m, D, E, F#m and ...Am, C, Dm, E (Em), F, G. Yes I left out the 'dim'.
Doing this in a song doesn't put it into a mode, but it still retains its original letter name as its key.
There is no mention about a G# NOTE in the song, at a different place. If that exists, then it can't be A Mixolydian, which is exactly the same note make up as D major.If every G is G natural, and the song gravitates to A, it could well be construed as A Mix.
Answer: both progressions you mentioned can definitely be attributed to the Mixolydian mode:
A–Bm–D–A–G or I–ii–IV–I–VII
A–G–D–A or I–VII–IV–I
the second progression is quite typical of the Mixolydian mode and can be found in  Grateful Dead's Scarlet Begonias, Led Zeppelin's Thank You, The Doors' The End, and Steve Young's Seven Bridges Road.


IP vs domain name when setting custom name servers

Question: Is it better (for efficiency) to use an IP address when setting a custom name server for my domain name rather than a domain like ns1.myserver.com?
Comment: I can't figure out how this question could make sense. In what case do you have to choose between using a domain name or using an IP address?
Comment: This question is very vague; use IP address where? In general, using an IP address is best for daemons and servers in general.
Comment: Apologies for the vagueness--my understanding of how this works is limited. I have a domain registered with a company other than where my web site is being hosted, and thus need to point the domain to my web host.
Answer: When you specify a name server, you need to provide an NS record. NS records always point to a name. See Can the value for a NS record be an IP address?
$ host -t NS serverfault.com
serverfault.com name server ns3.serverfault.com.
serverfault.com name server ns4.serverfault.com.
serverfault.com name server ns1.serverfault.com.
serverfault.com name server ns2.serverfault.com.

Whatever hosts you list as your name servers must also resolve to an IP.
$ host ns3.serverfault.com
ns3.serverfault.com has address 126.96.36.199

Thus, if you're using an interface that is asking you to enter a name server's address, enter a DNS name.
Also, don't sweat the round-trip-time to find that A record -- the referring server also keeps the A record as "glue". That's why you usually also have to enter the IP address. When looking up the NS record, we get that additional data as well. With my registrar, I must first define a nameserver's name and IP combination before I can register the nameserver to the domain.
$ dig serverfault.com. @b.gtld-servers.net

; <<>> DiG 9.7.3-P3 <<>> serverfault.com. @b.gtld-servers.net.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 30818
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 3, ADDITIONAL: 3
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;serverfault.com.           IN      A

;; AUTHORITY SECTION:
serverfault.com.    172800  IN      NS      ns1.serverfault.com.
serverfault.com.    172800  IN      NS      ns2.serverfault.com.
serverfault.com.    172800  IN      NS      ns3.serverfault.com.

;; ADDITIONAL SECTION:
ns1.serverfault.com.        172800  IN      A       184.108.40.206
ns2.serverfault.com.        172800  IN      A       126.96.36.199
ns3.serverfault.com.        172800  IN      A       220.127.116.11

;; Query time: 151 msec
;; SERVER: 126.96.36.199#53(126.96.36.199)
;; WHEN: Mon Mar 12 22:37:41 2012
;; MSG SIZE  rcvd: 135

Comment: I could have sworn I've been able to add IP addresses into the name server settings for a domain before. Oddly enough my registrar has two apparent ways to set this: one under "name servers" and the other under NS record of DNS. How are these different?
Comment: @chaiguy Gave you some updates on glue records... it is very likely that you did have to add addresses when specifying name servers.
Comment: I think I get it, cheers :)


How to initialize @DateTimeFormat Parameter on Get?

Question: The problem is that the DateTime passed as a parameter on my Spring Rest Controller Request is not initialized correctly.
Controller:
<code>@RequestMapping(value = "/events/{dateTimeStart}/{dateTimeEnd}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Event>> getEventsWithinTime(@DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME) DateTime dateTimeStart, @DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME) DateTime dateTimeEnd)
{
  log.debug("Rest Request: Getting Timestamp Events from " + dateTimeStart + " and " + dateTimeEnd);
}
</code>
Test:
<code>    @Test
@Transactional
public void checkEventWithingDateTime() throws Exception {
    eventRepository.saveAndFlush(event);

    LocalDate nowDateTime = new LocalDate();

    DateTime midnightDateTime = new DateTime(nowDateTime.getYear(), nowDateTime.getMonthOfYear(),
        nowDateTime.getDayOfMonth(), 0,0);

    DateTime lastSecondDateTime = new DateTime(nowDateTime.getYear(), nowDateTime.getMonthOfYear(),
        nowDateTime.getDayOfMonth(), 23,59,59);

    System.out.println("Event Start Date: " + event.getStartDate());
    System.out.println("Looking between : " + midnightDateTime.toDateTimeISO() + " and " + lastSecondDateTime.toDateTimeISO());

    restEventMockMvc.perform(get("/api/events/{timestampStart}/{timestampEnd}", midnightDateTime.toDateTimeISO(), lastSecondDateTime.toDateTimeISO()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$").isArray())
        .andExpect(jsonPath("$", hasSize(1)))
        ;

}
</code>
The Issue:
<code>Event Start Date: 2015-06-09T15:19:01.935+02:00
Looking between : 2015-06-09T00:00:00.000+02:00 and 2015-06-09T23:59:59.000+02:00
[DEBUG] com.ent.event.web.rest.EventResource - Rest Request: Getting Timestamp Events from 2015-06-09T15:19:02.681+02:00 and 2015-06-09T15:19:02.681+02:00
</code>
The datetime passed is not initialized correctly, the date is ok, but the time is set to current and not the one given.
Thanks.
Answer: As I remember I faced with some problem of adding DateTimeFormat. Eventually I resolved situation through binder:
<code>@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");;
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
</code>


Help Understanding Etale Space of Sheaf (Local Homeomorphism)

Question: I am new to algebraic geometry. I can't understand why an etale space is considered locally homeomorphic to its base space. The analogy I have heard is that etale space can be visualized as "stacked over" the base space, or that it is like a "puff pastry". I understand that we can (locally) map this stacked/pastry space to the base space, but I don't understand how an inverse map could exist. It seems to me like the inverse map would be multi-valued as it takes a point in the base space to several points in the etale space.
As an example, consider the base space to be a circle and an etale space to be a circle winding around itself twice. The map from the etale space takes two points to one point of the circle. Doesn't this mean that the inverse map is multi-valued?
Michael
Answer: You're misinterpreting this. The claim is that for all points in the etale space, there exists an open neighborhood so that the projection restricted to that neighborhood is a homeomorphism. For instance, if you take a small interval on the circle winding twice, it's image is again a small interval of the target circle, and the projection map restricted to this small interval is a homeomorphism.
Comment: Thanks Mr. Scorpio. That makes sense to me. However, in the book that I am reading it says the following: "Let E be an etale space and p a local homeomorphism. The fiber over x is the set E_x which is equal to p^-1(x)."  I still don't understand what is meant by p^-1(x) though. What is the image of p^-1(x)?
Comment: That's the inverse image of $x$ under the map $p$; they're not defining an inverse map to $p$. (By the way, [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) works in the comments.)
Comment: Thank you! I think I get it now. The -1 exponent is just meant to indicate the preimage of the map. It's not exactly an inverse of the local homeomorphism. Perhaps one would call it an abuse of notation or something.
Comment: I would not call it an abuse of notation, it's the standard way to refer to the inverse image of a point under a map. If this answers your question, please consider "accepting" the answer by clicking the check mark next to it. This scores points for you and for the person who answered your question. You can find out more here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).


I want to convert Array to stdobject

Question: i have this code
$array = (car => 'yes', 'bike' => 'no', 'cycle' => 'yes');

print_r($array);

My output is
Array
(
    [car] => yes
    [bike] => no
    [cycle] => yes
)

I want output like this
stdClass Object
(
    [car] => yes
    [bike] => no
    [cycle] => yes
)

i am using php version 5.3
Comment: Does this answer your question? [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php)
Comment: Is there any way you could upgrade your PHP (although it doesn't affect this question).
Comment: https://stackoverflow.com/questions/19272011/how-to-convert-an-array-into-an-object-using-stdclass
Comment: ArrayObject https://3v4l.org/3qLWn is a nice way if you want both
Answer: Try this
$array  = array('car' => 'yes', 'bike' => 'no', 'cycle' => 'yes');
$array=json_decode(json_encode($array), false);
print_r($array);

your output is like this
stdClass Object
(
    [car] => yes
    [bike] => no
    [cycle] => yes
)

Comment: `$array  = (object) array(...)` would suffice

I want to convert Array to stdobject


confusion about root mean squared distance in 1 dimensional random walk

Question: I was just introduced to the concept of a random walk while reading the Feynman lectures on physics, Volume 1. There was something in the explanation there that confused me, so I tried looking online for other explanations, and encountered the same difficulty.
I'm trying to understand how on earth the expected distance traveled could ever be the square root of the number of steps.
Here's my thinking process. I'm curious where I'm going wrong.
Suppose you start at 0, and at each step, either go forward (+1), or backward (-1), with equal probability. Suppose that you do 100 steps. Let us call X the number where you end up.
I can see how if you were to repeat this experiment many many times, the mean value of X would be 0.
But this is not interesting. What is interesting is the total distance moved, not the final displacement.
Well, it's as obvious as pie that that total distance moved is simply 100!
This is because the distance moved with each step is the absolute value of the incremental displacement at each step, which, in our example, is 1. So the total distance moved is 1 multipled by the number of steps, which is 100.
Now all the guides I've read say that using the absolute value is computationally tricky/impossible/inefficient, so it's better to first square the individual displacements, and then square root them at the end. But the problem with this is that you end up with something completely different. In our example, you'd end up with a value of 10, which is clearly incorrect if what you are interested in is the total distance traveled.
So, if we define the root mean squared distance as "the square root of the expected total distance traveled", that is fine and consistent. But to say that the root mean squared value is the expected total distance traveled seems nonsensical to me.
Yet we have statements that appear to say just that.
For example:

Since sqrt(d2) is something like the average positive distance away from 0 after N steps (technically, it's called the "root-mean-squared" distance), we expect that after N steps, the black dot will be roughly sqrt(N) steps away from where it started. So for 25 steps, we expect the black dot to have moved roughly 5 total spaces from 0 in either direction. Of course sometimes it will move more and sometimes fewer total spaces, but 5 is roughly what we might expect.

taken from http://www.mit.edu/~kardar/teaching/projects/chemotaxis(AndreaSchmidt)/random.htm
The second thing that confuses me is that this is portrayed as some sort of probabilistic function. According to my thinking descibed above (which may be woefully misguided!) both the total distance and the square root of the total distance will be exactly N and square root of N, each and every time, in the case where the magnitude of each incremental displacement is always the same (i.e. "1" in this example). So why even frame this as an expected value. How on earth could the total distance traveled be anything but N x |stepsize|?
Comment: Your argument should make it obvious that the "distance" in "expected distance" must refer to the *net* distance: that is, the distance between the position at time $N$ and the initial position, regardless of what path was taken to arrive there.
Comment: Unless I'm missing something, net distance is total displacement, which, in my example, has an expected value of 0, not root N.
Comment: It's going to be extremely difficult for a nonnegative random variable to have zero expectation!
Comment: But net displacement can be either positive or negative. Why would it be non negative?
Comment: The strongest reason perhaps is that when you do not adopt the interpretation I am suggesting, then none of the results makes sense, whereas when you interpret the net distance as an actual *distance* (which axiomatically is nonnegative) then all the stated results are true.
Comment: but isn't actual distance traveled simply N mutliplied by magnitude of step size, which would be 100 x 1 = 100, in my example?

I'm not trying to be daft or difficult!
Comment: If I travel from New York to London, the distance between my origin and destination is still 5700 km regardless of whether I went directly or stopped at Hong Kong and Santiago along the way. That's the entire (and rather trivial) point: we are talking about *distance between the start and the stop* (which is what is of physical interest), not about the distance along the path (which is the same for all paths after $N$ steps and therefore is uninteresting).
Comment: How is the distance between the start and stop different than the final net displacement? This is the key idea that I'm not grasping (and I do appreciate your patience here).
Comment: I definitely know there's something wrong with my thinking, since when I simulate the random walk, the expected value of the absolute value of the net displacement is certainly not 0. Interestingly, neither is it root N. For example, when N is 25, the expected value seems to be around 3.87.

Here's the Matlab code : [link](http://pastie.org/10659835)

Now that I have a sandbox to work with, I'll see if I can resolve this paradox that exists inside my addled brain.
Comment: Think I've figured it out. Also, Matlab code was faulty as it was taking modulus, rather than square.
Comment: See discussions [here](http://stats.stackexchange.com/questions/159650/why-does-the-variance-of-the-random-walk-increase) and also [this post](http://stats.stackexchange.com/a/136879/805)
Answer: The average "distance" is sqrt(n) in the topological sense, independent of direction. You drive a distance of 10 miles no matter what direction you drive (North, South, East or West). You correctly point out that given 100 steps the average distance from the origin will be 10 (above OR below the point of orgin)
Rest assured that the average displacement (which may be either positive OR negative) is zero.
Comment: Thanks @Gregg B, yes, it's been a while since I tackled this issue, but I think that I was confusing the concept of distance and displacement in my discussion with Whuber.
Answer: I think I've figured it out.
The key thing that was bugging me was this:
In the example I gave, consider tossing a fair coin to decide which direction to step for each of the 100 steps. The expected value of the number of heads would be 50.
But if there are 50 heads and 50 tails, that means that the net distance traveled would be 0.
However, it is a thinking error to assume that each of the experiments (a single experiment being a 100 coin toss random walk) will yield 50 heads. Rather, there will be a distribution, with 50 heads at the center of this distribution.
While the expected value of this distribution is 50, it is highly unlikely that all samples are going to be exactly 50. Rather, many of them will be merely in the vicinity of 50. The average deviation from 50, for any given sample, is determined by the spread of this distribution.
As we are squaring the the value of each experiment, these deviations do not cancel out.


Django M2M Relationship Issue with Admin Using Intermediate Table with Multiselect

Question: I'm working with m2m relationships using through to set intermediate table. Issue is I need to show multiselection instead of a normal dorpdown but when I select multiple items and save I get an error.
ValueError: Cannot assign "<QuerySet [<Facility: facility1>, <Facility: facility2>]>": "Property.facility" must be a "Facility" instance.
Also I am showing this model in admin.TabularInline which allows me select only one item per row as tabular inline gives capability to insert multiple forms.
I have tried multiple solutions like custom save and many other things and some how I get able to save that but then issue appears on view. I need to show only one form with multiselect widget to perform this selection.
models.py

class Facility(models.Model):
    name = models.CharField(max_length=200)

class Property(models.Model):
    name = models.CharField(max_length=200)
    area = models.CharField(max_length=200)
    facility = models.ManyToManyField(Facility, through="PropertyFacility")

class PropertyFacility(models.Model):
    prop = models.ForeignKey(
        Property, related_name="facilities", on_delete=models.CASCADE
    )
    facility = models.ForeignKey(
        Facility, related_name="properties", on_delete=models.CASCADE
    )

admin.py

from django.contrib.admin.widgets import FilteredSelectMultiple
from django.utils.translation import ugettext_lazy as _

class PropertyFacilityForm(forms.ModelForm):
    facility = forms.ModelMultipleChoiceField(Facility.objects.all(), required=True, widget=FilteredSelectMultiple(_('ss'), False, attrs={'rows':'10'})

class PropertyFacilityInline(admin.TabularInline):
    model = Property.facility.through
    form = PropertyFacilityForm

class PropertyAdmin(TabbedModelAdmin):
    model = Property
    tab_facilities = (PropertyFacilityInline,)
    tab_property = (
        (
            "Property Details",
            {
                "fields": (
                    "name",
                    "area",
                )
            },
        ),
    )

    tabs = [
        ("Property", tab_property),
        ("Facilities", tab_facilities),
    ]

It let me show on admin like this
Here you can see I am able to select multiple select but the form should be one here instead of multiple.
I want to show only one single form with multiselection widget which allows me multi select and save it and then on change_view it shows the selected one and the left unselected ones.
Answer: I had fixed the issue by adding some custom logic for saving m2m field.
admin.py

class PropertyForm(forms.ModelForm):
    facility = forms.ModelMultipleChoiceField(Facility.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Property
        fields = ["id", "name", "area", "city"]

    def save(self, commit=True):
        prop_facilities = self.cleaned_data.pop('facility')
        instance = forms.ModelForm.save(self, commit=False)
        instance.facility.clear()
        for facility in prop_facilities:
            PropertyFacility.objects.create(facility=facility, prop=instance)
        return instance

class PropertyAdmin(TabbedModelAdmin):
    model = Property
    tab_facilities = (("Facilities", {"fields": ("facility", )},),)
    tab_property = (
        (
            "Property Details",
            {
                "fields": (
                    "name",
                    "area",
                )
            },
        ),
    )

    tabs = [
        ("Property", tab_property),
        ("Facilities", tab_facilities),
    ]


How to derive the variance of this MLE estimator

Question: Let $(x_i, Y_i)\in\mathbb{R}^2$ be independent observations on $n$ subjects, such that $$Y_i|x_i\sim N(x_i\beta, \sigma^2)$$ where $(\beta, \sigma^2)\in\mathbb{R}^2$ are unknown coefficients.
I computed the maximum likelihood estimate $\hat\beta$ of $\beta$, which is $\hat\beta = \frac{\sum_{i=1}^n y_{i}x_i}{\sum_{i=1}^n x_i^2}$, and we want to compute the variance of this estimator $\hat\beta$.
Using that $Var(\hat\beta)= E[\hat\beta^2]-E[\hat\beta]^2$, I would only need $E[\hat\beta^2]$ to get the variance, as I already showed $E[\hat\beta]=\beta$, but I'm struggling with it.
$$E[\hat\beta^2]=E[(\frac{\sum_{i=1}^n y_{i}x_i}{\sum_{i=1}^n x_i^2})^2]=\frac{1}{(\sum_{i=1}^n x_i^2)^2}E[(\sum_{i=1}^n y_{i}x_i)^2]$$
I do not really know how to compute this expectation. Any help would be appreaciated.
Answer: $y_{i}|x_{i} \sim \mathcal{N}(x_{i}\beta | \sigma^2) \Leftrightarrow y_{i} = \beta x_{i} + \epsilon_{i}, \ \epsilon_{i} \sim \mathcal{N}(0, \sigma^2)$
It's easier to find $\mathbb{D}(\hat \beta)$ directly - not by finding $\mathbb{E}(\hat{\beta}^2)$.
$\mathbb{D}(\hat \beta) = \mathbb{D}\left( \frac{\sum\limits_{i=1}^n y_{i}x_{i}}{\sum\limits_{i=1}^n x_{i}^2}  \right) = \frac{1}{\left( \sum\limits_{i=1}^n x_{i}^2  \right)^2} \mathbb{D}\left( \sum\limits_{i=1}^n (x_{i}\beta + \epsilon_{i})\cdot x_{i}  \right) = \frac{1}{\left( \sum\limits_{i=1}^n x_{i}^2  \right)^2} \mathbb{D}\left( \sum\limits_{i=1}^n \epsilon_{i}\cdot x_{i} + \beta \cdot \underbrace{\sum\limits_{i=1}^n x_{i}^2 }_{\text{nonrandom}}  \right) = \frac{1}{\left( \sum\limits_{i=1}^n x_{i}^2  \right)^2} \mathbb{D}\left( \sum\limits_{i=1}^n \epsilon_{i}\cdot x_{i} \right) = \frac{1}{\left( \sum\limits_{i=1}^n x_{i}^2  \right)^2}  \sum\limits_{i=1}^n \mathbb{D}(\epsilon_{i})\cdot x_{i}^2 =  \frac{\sigma^2 \cdot \sum\limits_{i=1}^n x_{i}^2 }{\left(\sum\limits_{i=1}^n x_{i}^2  \right)^2} = \boxed{\frac{\sigma^2}{\sum\limits_{i=1}^n x_{i}^2}}$
Comment: Shouldn't the fraction you take out from the variance be sum of $x_i^2$, instead of sum of $x_i$?
Comment: @eseou Hope you noticed that this answer finds $\operatorname{Var}(\hat\beta\mid x)$ as opposed to $\operatorname{Var}(\hat\beta)$.
Answer: Let $\epsilon_i=Y_i-x_i\beta$. Then $\epsilon_i\mid x_i\sim N(0,\sigma^2)$ and
$$
\operatorname{Var}(\hat{\beta})=\mathsf{E}[\hat{\beta}-\beta]^2=\mathsf{E}\left[\left(\sum x_i^2\right)^{-2}\left(\sum \epsilon_i x_i\right)^2\right].
$$
Conditionally on $X\equiv (x_1,\ldots,x_n)$,
\begin{align}
\mathsf{E}[(\hat{\beta}-\beta)^2\mid X]&=\left(\sum x_i^2\right)^{-2}\sum \operatorname{Var}(\epsilon_ix_i)\\
&=\left(\sum x_i^2\right)^{-2}\sum x_i^2 \sigma^2=\sigma^2\left(\sum x_i^2\right)^{-1}.
\end{align}
Therefore,
$$
\operatorname{Var}(\hat{\beta})=\sigma^2\mathsf{E}\left[\sum x_i^2\right]^{-1}.
$$


Feeds: solution with most frequent/real time/push notification update of feeds (e.g. for twitter tweets)?

Question: Which module (or solution) provides the quickest update of feeds after their source is updated? E.g. with Twitter if a new tweet is posted, which Drupal feed or twitter solution updates the quickest following that tweet? (I'd also be looking for general feed solutions for youtube etc).
I currently use feed aggregator which has minimum refresh interval of 15 minutes.
Do solutions require/work better if linked to a cron task?
Are there any real time genuine (i.e. not pseudo*) push notification solutions out there? Please give examples for particular feeds (e.g. twitter, youtube etc.) *by pseudo I mean a high frequency polling solution that appears to be near real time but is actually a pull on the feed from the drupal site rather than a push from the feed source.
Can feed sources like twitter be configured to know about subscribed external sites such that they can push updates to them?
By the way, currently evaluating the following as part of a solution for e.g. twitter (any specific advice on these welcome as is general advice on other solutions including for other feed sources such as youtube).

http://drupal.org/project/twitter
http://drupal.org/project/oauth
http://drupal.org/project/twitter_pull
Answer: It looks like Twitter's "Streaming API" is your solution. However, I would look closely at their Pre-Launch Checklist before going down that route. They have 10+ things that you should comply with before becoming a stream or push consumer of their API.
Maybe a solution that would fit you is to develop a twitter stream client (that would be your server), and then to have your application users connect to your server via node.js, since node.js provides a "persistent" connection suitable for chat rooms and push-like notifications.
This is an interesting (and probably doable) suggestion, but not something that you would find pre-packaged in a Drupal module.
Comment: +1 Thanks @amateur barista. I will explore your options before accepting an answer. Good to see an application of node.js as a means to maintaining persistent connections. Distilled from the all the hype around it when all I could see was yet another server-side scripting language.
Comment: Accepted answer - the suggestions comes closest to a real time solution I was looking for. Alternatively, if I don't need that instantaneous requirement then my own original suggestions would suffice.


How to set admin theme for a route?

Question: According to Drupal handbook route definition accepts parameter called _theme. Unfortunately this parameter is documented as "TODO".
Can this be used to force admin theme for the route? Is it possible to inject config parameter with admin theme name here?
It appears that other solution is to use Theme negotiator however the _theme parameter looks very tempting and way simpler to use.
Answer: You're looking for the _admin_route option:
aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE

Comment: Documentation might not be so great yet for D8 but change records are: https://www.drupal.org/node/2224207. Always search there if you know how something worked in D7 (found by seaching for "admin path"). https://www.drupal.org/developing/api/8/routing seems like a good place (subpage or so) to document this, looking forward to the documentation you'll write about this :)
Comment: Yet another undocumented D8 feature.
Comment: so does _admin_route just change it so it uses the default theme instead of the admin one?
Comment: I get a InvalidArgumentException: Routing requirement for "options" must be a string. when attempting to use this solution
Answer: module.myroute:
  path: '/path/path2'
  defaults:
    _controller: 'Drupal\module\Controller\MyController::add'
    _title: 'Add element'
  options:
    _admin_route: 'TRUE'

You need to use ' ' around TRUE, if not,  you will get 'InvalidArgumentException: Routing requirement for "options" must be a string'
Comment: Example here shows it without quotes: https://www.drupal.org/docs/8/api/routing-system/structure-of-routes so I don't think it's necessary anymore.

How to set admin theme for a route?


What is the distribution of a Poisson-Binomial variable where the probabilities of success are from another distribution?

Question: If I have a Poisson-Binomial random variable $X$ built from $n$ trials where I draw each $p_i$ as either $a \in \left[0, 1 \right]$ or $b \in \left[0, 1 \right]$ with equal probability. How can I find the mean and variance of $X$ in terms of $a$ and $b$? Are there any general techniques I could use?
This question seems relevant, though it's almost going in the other direction.
Edit: Just to clarify, imagine I'm performing $n = 6$ trials and I have $5$ samples. For each trial, I'll first flip a coin to decide if I should use $p_i = a$ or $p_i = b$, then I'll do the trial itself. So if I have $n = 6$ trials, my success probabilities for the first sample I take of this Poisson-Binomial random variable could be $\vec{p}_1 = \left[a, a, a, b, b, a \right]$.
The second might be $\vec{p}_2 = \left[b, a, b, b, a, a \right]$, and so on. Each time I sample the random variable $X$, I'm using different success probabilities $p_i$ that are themselves drawn from a distribution.
Comment: I cannot understand your setup, because you don't tell us how $p_i$ might be related to $a$ or $b.$  Could you describe it differently or perhaps give an example?
Comment: I am not sure what you mean by "$5$ samples".  Each of the $6$ components of $X$ seems to have probability $\frac12a+\frac12b$ of being $1$ and is otherwise $0$.  So the sum of $6$ iid copies of this is binomial with mean $3(a+b)$ and variance $\frac32(a+b)(1-a-b)$
Comment: @whuber I expanded on the question to give a concrete example of what I'm imagining. Essentially, $p_i$ is either $a$ or $b$ with equal probability in this setup.
Comment: @Henry, I was thinking of "$5$ samples" in terms of trying to estimate the mean and variance of this random variable using only the outcomes.
Answer: You describe a two stage experiment: first draw the $n$ success probabilities $p_1,\dots, p_n$ from $\{a,b\}$ with equal probability, then draw $X$ as a Poisson binomial given the probabilities. To get mean and variance for this doubly stochastic variable, you can condition on the outcome of the first part of your experiment and then average, use the law of total expectation and law of total variance.
Let $N_a$ be the number of probabilities $p_i=a$ in the first stage. Then $N_a\sim \mathrm{Bin}(n, \frac{1}{2})$. This gives
\begin{aligned}
\mathrm{E}X &= \mathrm{E}[\mathrm{E}(X|N_a)]
\\&=\mathrm{E}[N_a a + (n-N_a)b]
\\&=\frac{n}{2}(a+b),
\end{aligned}
and
\begin{aligned}
\mathrm{Var}X &= \mathrm{E}[\mathrm{Var}(X|N_a)] + \mathrm{Var}[\mathrm{E}(X|N_a)]
\\&=\mathrm{E}[N_a a(1-a) + (n-N_a)b(1-b)] +  \mathrm{Var}[a\cdot N_a  + b(n-N_a)]
\\&=\frac{n}{2}[a(1-a)+b(1-b)] + \frac{n}{4}(a-b)^2
\\& = n\cdot \frac{a+b}{2}\cdot \left(1-\frac{a+b}{2}\right).
\end{aligned}
This result could have been derived in a much more simple way, by looking at the probability that you get a success for the $i$-th outcome after sampling the probability and then the actual Bernoulli trial, as suggested in the comment by @Henry. Then you have a probability $(a+b)/2$ for success on each of the $n$ trials :-).
Comment: Yes, you are right, but it would still simplify to binomial if you use the same distribution for all $i=1,\dots,n$ and sample the $p_i$ independently. But these laws of total mean / total variance often come in handy - I probably use them too routinely and did a bit of overkill in the start. Good tools, anyway.
Comment: Thanks for the explanation! I like this technique because it seems somewhat general. I could modify the initial stage of the experiment to follow some other distribution, and I could do the same kind of calculation as here (with different results). Do I have this right?


Threading in WCF and Dependency Property (The calling thread cannot access this object because a different thread owns it exception)

Question: Any help will be very appreciated.
We have a WCF service (hosted in IIS) that is calling a method, and inside this method there is a call to a getter of a dependency property (this getter is part of of several dependency properties gathered in a single object and used for all kind of conversions).
We see sometimes, and not consistent, a crash on the WCF service side, with the following exception message:
"The calling thread cannot access this object because a different thread owns it".
I did some searching and found out a similar problem.
From the reading I understand that there is a scenario in which the getter is called on a different thread, and this is why we don't see this exception all the time.
However, I'm still puzzled about the solution. Does the WCF service has a dispatcher on which I can activate CheckAccess() and then call the Dispatcher.Invoke() method (like in WPF application)?
Can someone please advise?
Thanks,
Elad
Comment: Why are you using a `DependencyObject` from within IIS?  That's the root problem here - `DependencyObject` classes, in general, are never intended to be used outside of a system with a proper `Dispatcher`.
Comment: I thought that dependency properties were WPF specific? Is this also an WPF app?
Comment: This is not a WPF application. This is a WCF service using some kind of an infrastructure contains set of objects, and several of them are exposing dependency properties. We have inherited this infrastructure and needs to use it.
Comment: You're referencing a WPF assembly in a WCF service hosted in IIS?
Comment: @EladGutman well then, as  Reed Copsey says, looks like the solution is fundamentally flawed, the best bet is to redesign your app not to use technologies in the way they are not supposed to be used, and if this fails write you own thread synchronization code (which is complicated and error prone). WCF does not have a Dispatcher.
Comment: Thank you all for the comments and the advises. We'll see how we can continue from here.
Answer: ALL DependencyObjects have thread-affinity. They can only be accessed by the thread that instantiated it. Call DependencyObject.CheckAccess() to determine if on correct thread.
Here's an example. Even though the code uses a Button, a Button is still a DependencyObject.
<code>private void TryToUpdateButtonCheckAccess(object uiObject)
{
    Button theButton = uiObject as Button;

    if (theButton != null)
    {
        // Checking if this thread has access to the object
        if(theButton.CheckAccess())
        {
            // This thread has access so it can update the UI thread
            UpdateButtonUI(theButton);
        }
        else
        {
            // This thread does not have access to the UI thread
            // Pushing update method on the Dispatcher of the UI thread
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new UpdateUIDelegate(UpdateButtonUI), theButton);
        }
    }
}
</code>
Comment: Steven, thanks a lot for the example. I'm familiar with this pattern in WPF and I thought there is something similar in WCF in case we "combine" dependency properties.
Answer: What you can do is create a class in your "primary" thread which inherits from DispatcherObject.  That will give you access to the Dispatcher property in WCF.
Answer: Since your problem is to do with accessing dependency properties across multiple threads, you could use an STA threading model in your WCF service.
This article describes the approach
http://www.netfxharmonics.com/2009/07/Accessing-WPF-Generated-Images-Via-WCF
The relevant section is near the end of the article. It sounds like he is describing your exact problem.


Find the average score obtained

Question: Given a regular dice game in which each side has an equal probability of $1/6$, you roll the dice. If you get an even number, you roll two dice now and if the sum of the new values is again even, you roll three dice now and this continues until you get an odd sum. This odd sum is your score. What's your average score per turn?
This problem really confuses me as I've been learning probability. What if you continuously get even sums?
Comment: The probability that at some point, you get an odd score, is $1$, but the number of throws until this happens is unbounded. It could well be that the expected score is infinite , although my guess in this case is a finite expected score. It seems to be difficult to determine the expected score however.
Comment: What might help : The probability to get an odd score is $\frac{1}{2}$ in every throw.
Comment: I had thought of that but couldn't proceed
Comment: Is your main question about how to find the answer to the original problem, or about the issue of "what if you continuously get even sums?"? If the latter, just say so. If the former, then please provide more context of what you tried, where the problem comes from (a textbook? a course?), what recent facts or similar problems you've studied, etc.
Answer: These type of questions can usually be tackled using recursion.  In this case consider the following:
As Peter well pointed out, the probability of rolling an odd sum is always $\frac{1}{2}$, and you have probability 1 of the game ending at some point. So let's say that $E$ is the expected value of the game, while $E_{n}$ is the expected value of the game given that your starting turn is throwing $n$ dice.
First time rolling, game will finish if you roll an odd number. This happens with probability $\frac{1}{2}$ and $\mathbb{E}(\text{result}|\text{roll was odd})=3$, while with probability $\frac{1}{2}$ we will roll an even number and now the expected result will be the expected result of a game with two dice (what we called $E_{2}$).
So we write down the following:
$$E = \frac{1}{2}.3+\frac{1}{2}.E_{2}$$
Next step is to work out $E_{2}$, which following our reasoning (you can run the cases), renders:
$$E_{2} = \frac{1}{2}.7+\frac{1}{2}.E_{3}$$
which we can replace in our previous expression for $E$ resulting in:
$$E = \frac{1}{2}.3+\frac{1}{2}.\frac{1}{2}.7+\frac{1}{2}.\frac{1}{2}.E_{3}$$
It's easy to see from here that:
$$E = \frac{1}{2}.3+\sum_{n=2}^{\infty}\frac{\mathbb{E}\left( \text{sum of n dice}|\text{sum is odd}\right)}{2^{n}}$$
Now I haven't found an analytical solution for this, but upon running the cases it looks as if for $n\geq2$, $\mathbb{E}\left( \text{sum of n dice}|\text{sum is odd}\right)=3.5n$
Now, if this is true then the answer would be:
$$E = \frac{1}{2}.3+3.5\sum_{n=2}^{\infty}\frac{n}{2^{n}}$$
$$E = \frac{27}{4}$$
Answer: I am pretty sure the answer is 6 2/3 instead of 6,75
I took off where the previous posts started and wrote everything down and discovered a pattern. I used excel to do the math and will include the image.
Solution:
Half the time you hit an odd number...
So there is 50% chance you hit an odd number throwing 1 die (1+3+5) which is an average of 3. So half the time you can throw again with 2 dice and 1/4 of the time you can throw 3 dice and so forward.
With 2 dice you can throw: odd-even, odd-odd, even-even. Only odd-even ends up in an odd number. the average for an odd die is 3 and the average for an even die is (2+4+6) is 4. So you have 25% of an average of 7 (3+4)
With 3 dice only odd-odd-odd and odd-even-even end up in an odd number for 3+3+3=9 and 3+4+4=11. So you have 12.5% of hitting an average of 10 (9+11/2)
4 dice gives 6,25% of an average of 14 -
5 dice gives 3,125% of an average of 17 -
6 dice gives .... average of 21
The pattern is 3-7-10-14-17-21 (3+4+3+4+3+4+3+4) etc..
Now take a look at the image
I simple added 50% x 3, 25% x 7, 12.5% x 10 .. etc and devided by total %% used which is close to 1.
Diesheet excel

Find the average score obtained


VSTest 2013 Agent Stopped Working After First Test

Question: We have been running into an issue where we are running our interactive Coded UI tests, and when our second test starts, the QTAgent32.exe stops working. Our setup is through TFS where we queue a new build that tells a controller to run our tests on VMs. These tests are directly sent to the VMs designated by a .testsettings file. Once the tests are distributed on the VMs, the tests start to work on the WPF application under test. A test can mainly take an hour to run due to the complexity of what needs to be tested. After the test completes and the agent shows '1/10 Completed' we get a windows message that QTAgent32.exe has stopped working.

Problem Event Name: BEX
Application Name: QTAgent32_40.exe
Application Version: 12.0.21005.1
Fault Module Name: StackHash_83e2
Fault Model Version: 0.0.0.0

If we close out the Windows message, another will pop up with different details.

Problem Event Name: APPCRASH
Application Name: QTAgent32_40.exe
Application Version: 12.0.21005.1
Fault Module Name: msxml6.dll
Fault Model Version: 6.30.7601.18431

If we close the second message, the test will be claimed as complete with a failure in the test results. We also see that the Agent will continue running the next test until it fails on the fourth test!
We have looked at event viewer on both the controller and agents. The controller shows nothing. The agent shows failures with the same details as the errors above. We have repaired the agent and looked into .Net. We know that we can run these tests in any order and that they do all pass without this issue when ran locally. The errors described above are only when ran on our VMs/Agents.
Anyone have ideas on how to either get more details during the test runs? Has anyone else ran into an issue like this before?
Thank you all in advance for taking a look and helping out!
Comment: It looks like [BEX indicates a buffer overflow exception](http://answers.microsoft.com/en-us/windows/forum/windows_other-windows_programs/problem-event-name-bex-error-message/cf5baf73-0877-4070-abfb-a2c3a17a9e10#ThreadAnswers). Try checking your DEP settings on your VM vs your dev box (Control Panel > System Properties > Advanced > Performance Settings > Data Execution Prevention.
Comment: A variation in OSes or running as administrator vs not in those different environments might make a difference too. And if you're running web browser based tests, check on your internet explorer security settings (even Chrome uses some of those).
Comment: Thanks NextInLine! Will look more into the BEX settings. The OSes are the same, we run everything with administrative privileges and UAC off. Also, No web based tests, all WPF/C#.
Comment: To get more details on a test run, try [Enabling Coded UI Test Logs](http://www.dotnetcurry.com/showarticle.aspx?ID=880) if you haven't already.
Comment: Looks like DEP is required for the Agent executable and sub programs. When trying to add it to the exclusion list it requests throws an error saying it is required. Turned on logs and got no errors or warnings.
Comment: NextInLine, thank you so much for all of your help. After much investigation on our tests and what the VMs were doing, we learned that they were failing on the msxml6.dll. We were able to repair the installation for msxml6.dll and everything went back to working condition! Thanks for your help!
Comment: Glad to hear. Debugging that kind of issue can be quite frustrating.
Answer: After much investigation and NextInLine's help, we found that the issue was with how our test was accessing and using the msxml6.dll. We repaired the installation of this dll and others, and resolved the issue.


How to update all libraries in Spring Boot project?

Question: I'm updating a spring boot project from spring boot 2 to spring boot 3.
the parent maven pom has a lot of the dependencies locked down to a specific version in the dependencyManagement section, like this, for example:
<code>     <dependency>
            <groupId>com.netflix.feign</groupId>
            <artifactId>feign-jackson</artifactId>
            <version>${netflix.feign.jackson.version}</version>
     </dependency>
</code>
Is this supposed to be the normal procedure, to lock down all versions once you get it working?
And in my case, when updating to spring boot 3, What is the best procedure to update all libraries? do I need to comment out everything in the dependencyManagement section to re-establish compatibility with Spring Boot 3?
Comment: Welcome to SO. Please show us what you have tried and ask one specific question at a time. The answer largely depends on you project, to keep it short you it will probably work to simply update spring boot and nothing else but ideally you should update and keep all your dependencies to the latest versions whenever possible.
Comment: Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: Locking down versions in the dependencyManagement section is generally considered good practice for stability and conflict resolution. Upgrading a Spring Boot project can be a challenging task.
For custom dependencies locked down in dependencyManagement, consult the documentation for each dependency to see if they're compatible with Spring Boot 3. Update their versions as needed. Update the version one by one, testing each time to ensure nothing breaks. Also, make sure all your unit tests and integration tests pass.
Also read these articles carefully: https://spring.io/blog/2022/05/24/preparing-for-spring-boot-3-0
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide
As I said this task could be challenging and tedious, it depends how many dependencies in general you have in your project.