Kurzweil-Hensotck integral, an unclear point in a book for undergraduates by Fonda

Question: I would like to understand how from $$d\omega_2(x)=(\frac{\partial g_{2,3}}{\partial x_1}-\frac{\partial g_{1,3}}{\partial x_2}+\frac{\partial g_{1,2}}{\partial x_3})dx_{1,2,3}$$
follows $$\operatorname{div}F=\frac{\partial F_1}{\partial x_1}+\frac{\partial F_2}{\partial x_2}+\frac{\partial F_3}{\partial x_3} $$ as claimed in the book by Fonda in the snippet below:
Comment: This has absolutely nothing to do with Kurzweil-Henstock. This just plain old differential forms.
Comment: @TedShifrin Right, I have just taken that name from the title of a book I was reading.
Answer: The divergence already has a classical definition (which you typed in your second equation). He's just arriving at the formula through the machinery of differential forms. To the vector field $F$ we associate the $2$-form $\omega = F_1dx_{23} + F_2dx_{31}+F_3dx_{12}$. Then $d\omega = (\text{div}\,F)dx_{123}$. He says this in the text if you read the lower half of the page. So in his earlier notation, he's taking $F_1=g_{23}$, $F_2=-g_{13}$, and $F_3=g_{12}$.
(You might find the latter half of my YouTube lecture helpful. Perhaps others of my lectures will be useful, as well.)


Send NGINX logs to Graylog

Question: I'm trying to collect nginx error and access logs with graylog, I think everything is correctly configured, but Graylog receive nothing from NGINX
(Graylog & NGINX are in docker containers and both are in the same network)
I use nginx/1.13.5 & Graylog 2.4.0 and I use this content pack on graylog
Here is my nginx.conf
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    log_format graylog2_json escape=json '{ "timestamp": "$time_iso8601", '
                 '"remote_addr": "$remote_addr", '
                 '"remote_user": "$remote_user", '
                 '"body_bytes_sent": $body_bytes_sent, '
                 '"request_time": $request_time, '
                 '"status": $status, '
                 '"request": "$request", '
                 '"request_method": "$request_method", '
                 '"host": "$host",'
                 '"upstream_cache_status": "$upstream_cache_status",'
                 '"upstream_addr": "$upstream_addr",'
                 '"http_x_forwarded_for": "$http_x_forwarded_for",'
                 '"http_referrer": "$http_referer", '
                 '"http_user_agent": "$http_user_agent" }';

    access_log syslog:server=graylog:12301,facility=local0,tag=nginx,severity=info graylog2_json;
    error_log  syslog:server=graylog:12302,facility=local0,tag=nginx,severity=error warn;
    #error_log stderr;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
daemon off;

If I try with nc, my graylog receive the message
echo -n "test message" | nc -u -w1 graylog 12301

Thanks!
Comment: `/var/log/graylog/server/current` houses debug information, along with parse error information (which is what I think this is). If your Graylog server is expecting JSON (which if it's using the nginx collector it will be), I think your JSON is invalid and causing parse errors. Specifically, missing double-quotes around `$request_time` which is a string.
Answer: I suggest you collect some debug info:
As you said your network work

TCP Dump packets on the Graylog host:

if Nginx on the same host as Graylog: sudo tcpdump udp -n -vv port 12301 -i lo -X
if Nginx on a different host as Graylog: sudo tcpdump udp -n -vv port 12301 -X

If the network level works and you can see packets like on the picture go to Graylog Inputs and check which kind of input you have
[a] It needs to be Raw/Plaintext UDP (if you have GELF UDP Graylog will filter your messages as Nginx sends logs in Syslog format and not in Json
[b] You will have Network IO different from 0
[c] Port (12301 in your case) and IP needs to be the same as in Nginx configuration

If you have all this you will find a RAW message from Nginx in your Graylog:

<190>Jul.26.16:12:07.graylog.nginx:.{."timestamp":."2018-07-26T16:12:07+03:00",."remote_addr":."xx.x.x.xxx",."body_bytes_sent":.4277,."request_time":.0.005,."response_status":.200,."request":."POST./api/cluster/metrics/multiple.HTTP/1.1",."request_method":."POST",."host":."xx.x.x.xxx",."upstream_cache_status":."-",."upstream_addr":."xx.x.x.xxx",."http_x_forwarded_for":."xx.x.x.xxx",."http_referrer":."https://xx.x.x.xxx/system/inputs",."http_user_agent":."xx.x.x.xxxxx.x.x.xxxxx.x.x.xxxxx.x.x.xxx",."http_version":."HTTP/1.1",."nginx_access":.true.}

Extract form pseudo-Syslog RAW message a JSON using Graylog Input Extractor:

Extractor Example:
{
  "extractors": [
    {
      "title": "Extract from Pseudo-Syslog a JSON",
      "extractor_type": "regex_replace",
      "converters": [],
      "order": 0,
      "cursor_strategy": "cut",
      "source_field": "message",
      "target_field": "message",
      "extractor_config": {
        "replacement": "$1",
        "regex": "^.*?(\\{.*?\\})$"
      },
      "condition_type": "none",
      "condition_value": ""
    }
  ],
  "version": "2.4.6"
}

As you use "content pack" you need to add the rule before all others that cames from "content pack" (order: 0) if you do import export
After adding the rule, you will have clear JSON log from Nginx, all other work will do "content pack"

Check your Nginx config

ngnix.conf example:
log_format graylog_json '{ "timestamp": "$time_iso8601", "remote_addr": "$remote_addr", "body_bytes_sent": $body_bytes_sent, "request_time": $request_time, "response_status": $status, "request": "$request", "request_method    ": "$request_method", "host": "$host", "upstream_cache_status": "$upstream_cache_status", "upstream_addr": "$upstream_addr", "http_x_forwarded_for": "$http_x_forwarded_for", "http_referrer": "$http_referer", "http_user_agent": "$h    ttp_user_agent", "http_version": "$server_protocol", "nginx_access": true }';
access_log syslog:server=graylog:5555 graylog_json;

Hope, following all this steps you will find useful

Send NGINX logs to Graylog


Zipping sub directories is zipping only content of sub directories but not the sub directories

Question: Below is the code I tried. it is zipping only content of the sub folder but not the folder
I need to zip all sub folders along with the contents. what i am doing wrong here.
Example: I have a folder 'demo' inside demo folder  i have a, b, c folders. I want to zip a, b, c along with contents and zip should not include parent that is demo.
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
        File[] files = dirObj.listFiles();
        byte[] tmpBuf = new byte[1024];

        for (int i = 0; i < files.length; i++) {
          if (files[i].isDirectory()) {
            addDir(files[i], out);
            continue;
          }
          FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
          System.out.println(" Adding: " + files[i].getName());
          out.putNextEntry(new ZipEntry(files[i].getName()));
          int len;
          while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
          }
          out.closeEntry();
          in.close();
        }
      }

    public static void zipFiles(File[] subd) {

        String zipFile = "test.zip";

        try {

            FileOutputStream fos = new FileOutputStream(zipFile);

            ZipOutputStream zos = new ZipOutputStream(fos);

            for (File dir : subd) {

                addDir(dir, zos);

            }

            // close the ZipOutputStream
            zos.close();

        } catch (IOException ioe) {
            System.out.println("Error creating zip file: " + ioe);
        }

Comment: Maybe something like [this](https://stackoverflow.com/questions/51833423/how-to-zip-the-content-of-a-directory-in-java/51833575#51833575) as a starting point (`out.putNextEntry(new ZipEntry(files[i].getName()));` needs to contain a path element, which is described in the linked example)
Comment: if I add path, it adds complete obsolute path,  i just need all  sub folders  and its contents inside the zip. I have explained with example
Comment: Read the linked example - it only adds relative paths (based on the source path)
Comment: Are you talking about this line   String name = srcFile.getPath();
                name = name.replace(rootPath.getPath(), "");
Comment: That's the start of the basic idea (and just one approach)
Comment: Also why he has passed srcFolder two times in the argument, i am bit unclear
Comment: It's a recursive method, meaning that `addFolderToZip(srcFolder, srcFolder, zip);` is just seeding the initial pass
Answer: Here is a code I did for zip files and directories with hierarchy and without hierarchy.
zip.getHierarchy().equals("F") part does the work you want to do.
In this code, you have to pass source file, destination, hierarchy (T/F) as arguments.
Additionally you may need a DTO class.
public static void Start() throws IOException{

    FileOutputStream fos = new FileOutputStream(zip.getDestination());
    ZipOutputStream zipOut = new ZipOutputStream(fos);
    File fileToZip = new File(zip.getSourcePath());

        zipDirectory(fileToZip, fileToZip.getName(), zipOut);

    zipOut.close();
    fos.close();
}

public static void zipDirectory(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {

    if (fileToZip.isDirectory()) {

        File[] children = fileToZip.listFiles();

        for (File childFile : children) {
            if(zip.getHierarchy().equals("T")) {
                zipDirectory(childFile, childFile.getPath(), zipOut);
            }else if(zip.getHierarchy().equals("F")){
                zipDirectory(childFile, childFile.getName(), zipOut);
            }
        }
        return;
    }
    doZip(fileToZip,fileName,zipOut);
}

public static void doZip(File fileToZip,String fileName,ZipOutputStream zipOut) throws IOException {
    FileInputStream fis = new FileInputStream(fileToZip);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipOut.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
}


Nested IF Statement (price bands)

Question: I am trying to create a formula using the following parameters:
=IF(E20<=500,E20*.90,IF(E20<=1000,E20*.80,IF(E20<5000,E20*.70,IF(E20<=10000,E20*.60,IF(E20<999999,E20*.50
I want the formula to calculate the price if the quantity falls within the range but am missing something with the formula above.
Could someone please point out the mistake and offer a suggestion or correction?
Comment: Missing the closing brackets? )))))
Comment: Please provide proper formula. I think you are missing something.
Comment: Also missing the condition when E20 > 999999
Answer: Since struggling with nested IFs (understandably!) you might be better off with a lookup table. Say name an array as below LT;

1       0.9
500     0.8
1000    0.7
5000    0.6
10000   0.5
and apply =VLOOKUP(E20,LT,2)*E20
Comment: They should be `501`, `1001`, `5001` and `10000` since there's less than or equal to :) But this is also a good alternate approach!
Comment: Hmm, right that they could be wrong as well. I didn't notice the inconsistency between the inequalities until now.
Answer: With this, you check if cell A1 value falls between 100 and 200
=IF(A1 < 200; IF(A1 > 100; "ok"; "no"); "no")

Instead of "ok", you can insert your price calculation.
With this, you check if A1 < 100, if it is not then it checks if A1 < 200, and again if not it checks if A1 < 1000. If none of these conditions are true, it says "A1 > 1000"
=IF(A1 < 100; "A1<100"; IF(A1 < 200; "A1 < 200"; IF(A1 < 1000; "A1 < 1000"; "A1 > 1000")))

Again, instead of the optut string, you can insert your price calculation
Hope it helps, regards

Nested IF Statement (price bands)


It is sufficient to find the inverse of an element in a subgroup?

Question: I have a simple proposition about groups, but it is not obvious for me. (This question is motivated by the last answer in Show identity of subgroup is same as identity of group by TheRealFakeNews)

Let $(G, \circ)$ and $(H, +)$ be groups with the identity elements $1_G$ and  $1_H$, respectively. (The operation $+$ is defined to be the operation $\circ$ restricted on the elements in $H$. In other words, for all $h_1, h_2 \in H$ we have $h_1 + h_2 = h_1 \circ h_2.$)
Suppose that $(H, +)$ is a subgroup of $(G, \circ)$. Show that if $h_1, h_2 \in H$ and $h_1 + h_2 = 1_H$, then $h_1 \circ h_2 = 1_G$.

The proposition says that if $h_2$ is the inverse of $h_1$ in $(H, +)$, then also $h_2$ is the inverse of $h_1$ in $(G, \circ)$.
I know how to show that $1_H = 1_G$, from which the proposition is an easy consequence. But I want to prove the proposition, and use this to show that $1_H = 1_G$.
Since $(H, +)$ is a subgroup of $(G, \circ)$, we have $h_1, h_2, 1_H \in G$ and $h_1 \circ h_2 = 1_H$. Moreover, $1_G \circ 1_H = 1_H \circ 1_G = 1_H$ because $1_G$ is the identity in $(G, \circ)$. But I do now know to continue. Any suggestion please?
Comment: *NB:* "proof" and "prove" are different words.
Answer: Let us denote the inverse of $h$ in $H$ by $h^{(-)}$, to possibly contrast with the inverse of $h$ in $G$, which is $h^{-1}$.
Let $h\in H$, and let $h^{(-)}$ be its inverse in $H$. Then you have that
$$h(hh^{(-)}) = h$$
in $H$, but also in $G$. That means that $hh^{(-)}$ is an element of $G$ that satisfies the equation $hx=h$ in $G$. The only element that satisfies that equation in $G$ is $1_G$, so $1_H = hh^{(-)} = 1_G$ and $h^{(-)} = h^{-1}$.
Comment: Fantastic, thank you.


How to create node and reference it in Drupal 7?

Question:
Possible Duplicate:
Options for "create and reference"

How can I put a link "Add another item" on a node edit page that would create a new node and reference it at the same parent node ?
Also, I need to put Edit link beside the new created & referenced node.
I found modules like the Popups API and Popups: Add and Reference, but, sadly they are not ported to D7
Thanks for any hints!
Comment: This should be migrated to Drupal Answers
Answer: http://drupal.org/project/noderefcreate
This one is available for D7, and allows you to create & reference nodes within the create / edit form for another node type. Unlike the popups_reference module, it will only allow you to create the extra nodes with titles (no other fields). You could, however, use this and then write a small custom module that uses hook_form_alter() to redirect the user to the edit forms for newly-created nodes to enter the rest of the information.
Not as nice as popups_reference, but it should work.
Comment: I need to create & reference a new child node type without leaving the parent node edit page, please read my comments to M.Reda below.
Comment: I think that the noderefcreate module referenced above will do most of what you need. If you just go into Views, you can display the newly-created Chapters with edit links somewhere on the course page (probably using a block). I think that should do it.
Answer: I'm not sure what are you trying to do, Samir.
Have you tried Node Reference URL Widget (http://drupal.org/project/nodereference_url)
If it's not the right one, explain a bit more what are you trying to do.
Comment: Thanks M.Reda,

What I am trying to do is to create a course building website,
I have created three content types, Course, Chapter& Page

In the Course edit page, I need to add a link "Add new chapter", pressing this link will create and reference a new Chapter content type without leaving the Course edit page, then a new link to the newly created chapter get visible at the bottom of page, which if pressed will navigate to the chapter edit page.

I will need to apply the same thing for adding pages to a chapter.

Please advice, I really appreciate your response.


Keystroke to Duplicate Current Line in Toad

Question: How does one duplicate the current line in Toad's query editor? Such as to create a cloned line above or below the current line?
Answer: Good, old copy/paste is what I use.
But you, you may open TOAD's Options, navigate to key shortcuts and set the (within the "Editor" category) Line duplicate action's shortcut to any key combination you want (and which doesn't conflict with some other key combination).
Comment: Ya I Cut/paste too; and go way back. But I am having to Port a database and while learning what differences there are between 20+ reference similar textual *columns*, I am doing a process where I put the column name in the paste buffer, then need to copy the last  `Select ... union` line and replace the prevous requested column, Once the union line is duplicated, I execute the multi union query to see if it grows. Uggg... :-)


Qual o risco de um erro em uma página já carregada?

Question: Possuo uma aplicação onde dados grandes em requisições AJAX são feitas, isso gera um certo delay ate posicionar os dados na página.
Preciso renderizar uma imagem onde seu path está um array. Ao meu perceber o browser tenta carregar a imagem uma vez mas o array não foi processado ainda, gerando um erro no console. O browser tenta encontrar a imagem de novo e nessa tentativa consegue pois o array já foi processado.
Para um usuário ele não veria problema nenhum, mas no console eu recebo um erro de

Undefined

Com base nisso segue algumas dúvidas:

Devemos sempre eliminar os erros por mais que visualmente está tudo "certo"?
A melhor forma de resolver a situação seria com um Catch?
Existe alguma técnica ou tendencia a fazer um carregamento tardio?
Comment: você precisa então carregar as imagens depois do array, se há esse dependência, isso é o mais correto a fazer
Comment: _"Ao meu perceber o browser tenta carregar a imagem uma vez mas o array não foi processado ainda"_ - seria o caso de corrigir para que não aconteça desta forma, já que você conseguiu diagnosticar o problema.
Answer:
Devemos sempre eliminar os erros por mais que visualmente está tudo "certo"?

Não está tudo certo, está tudo funcionando, são coisas diferentes, então tem que fazer certo, porque o que está errado um dia te traz problemas.

A melhor forma de resolver a situação seria com um Catch?

Não, é a pior coisa a fazer em quase todas situações. Quando existe um erro você o conserta em vez de fazer de conta que ele não está lá. Pesquise aqui no site sobre o assunto. Exceção é o recurso de linguagem mais mal usado na programação hoje em dia. Poucas exceções devem ser tratadas em código. Não posso garantir poque não vi isso acontecendo e o código que faz desta forma, mas parece um erro de programação e não uma falha momentânea de ambiente, faça o código corretamente e não precisará disso. Use o catch para o caso de uma falha que foge do seu controle.

Existe alguma técnica ou tendencia a fazer um carregamento tardio?

Sim, tem aqui no site e outros lugares e pelo jeito já sabe que chama-se lazy loading, não tem como responder em específico porque a pergunta é geral.
Comment: Heh, ótima imagem para ilustrar!


Add invoice, payments, expenses, etc. into Quickbooks via ASP.NET

Question: I have an ASP.NET application that I would like to connect to my Quickbooks Online account to programmatically enter new invoices, make payments against those invoices and even enter new expenses.  It seems that there are all sorts of APIs and processes for this that have undergone many changes over the years so I am confused as to where to start.  I'm not looking to create a app that I'd release to some sort of App Store or anything, this is just for personal use (automation, etc.)  I'm looking for a simple, straight forward, approach.
Answer:
It seems that there are all sorts of APIs and processes for this that
  have undergone many changes over the years

That's an understatement. Intuit is the king of confusing and poorly implemented APIs. :-)

I'm not looking to create a app that I'd release to some sort of App
  Store or anything

Since this is just for your internal use, your only option at this point is the QuickBooks SDK/qbXML gateway for QuickBooks Online.
(IPP/Intuit Anywhere are the newest APIs, but as the FAQs state, right now Intuit Anywhere is only for SaaS apps that you're re-selling to others.)
The easiest way to get started with qbXML and QuickBooks Online is by HTTP POSTing data directly to the gateway. Some example code looks like this:
<code>string requestUrl = null;
requestUrl = "https://apps.quickbooks.com/j/AppGateway";

HttpWebRequest WebRequestObject = null;
StreamReader sr = null;
HttpWebResponse WebResponseObject = null;
StreamWriter swr = null;

try
{
    WebRequestObject = (HttpWebRequest)WebRequest.Create(requestUrl);
    WebRequestObject.Method = "POST";
    WebRequestObject.ContentType = "application/x-qbxml";
    WebRequestObject.AllowAutoRedirect = false;

string post = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<?qbxml version=""6.0""?>
<QBXML>
<SignonMsgsRq>
<SignonDesktopRq>
<ClientDateTime>%%CLIENT_DATE_TIME%%</ClientDateTime>
<ApplicationLogin>APPLICATION_LOGIN</ApplicationLogin>
<ConnectionTicket>CONNECTION_TICKET</ConnectionTicket>
<Language>English</Language>
<AppID>APP_ID</AppID>
<AppVer>1</AppVer>
</SignonDesktopRq>
</SignonMsgsRq>
<QBXMLMsgsRq onError=""continueOnError"">
<CustomerQueryRq requestID=""2"" />
</QBXMLMsgsRq>
</QBXML>";

post = post.Replace("%%CLIENT_DATE_TIME%%", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"));
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(post);
    post = xmlDoc.InnerXml;
    WebRequestObject.ContentLength = post.Length;
    swr = new StreamWriter(WebRequestObject.GetRequestStream());
    swr.Write(post);
    swr.Close();
    WebResponseObject = (HttpWebResponse)WebRequestObject.GetResponse();
    sr = new StreamReader(WebResponseObject.GetResponseStream());
    string Results = sr.ReadToEnd();
    }
finally
    {
        try
        {
            sr.Close();
        }
        catch
        {
        }

    try
    {
        WebResponseObject.Close();
        WebRequestObject.Abort();
    }
    catch
    {
    }
</code>
Notice that to use that sample code, you'll need a application login and connection ticket. You can get those by following the DESKTOP REGISTRATION walk-through on our QuickBooks integration wiki.
If you need more abstraction than that, you can also use the QBFC libraries included with the SDK. Be aware that the "QBOEConnector" .NET components have been problematic for people in the past (they require some weird registry edits and stuff for some strange reason...).
You can use the QuickBooks OSR (check the "OE" checkbox, uncheck the "US" checkbox, use the "Select Message" drop-down at the top of the screen, and choose the "XML Ops" tab) to view available requests to send to QuickBooks Online. If you don't see it in the list, it's not supported by the QuickBooks Online API.


Mapping a UID on custom module content

Question: Dear Drupal Enthusiasts,
I was hoping that one of you may be able to solve a problem I'm having with the Feeds module and its unique identifiers.
Basically, I would like to be able to target a field with a unique identifier like you can do with any ordinarily created content-type. However, I want to do this on a custom module (which has its own form of unique identification).
In other words, I have a field in my custom module that is unique, but Drupal does not know that this field is unique. How do I both tell Drupal that this custom module contains a unique field and identify that field as unique so that I can update content rather than delete it and replace it every time I wish to import data?
Any guidance would be most helpful!
Thanks!
Answer: So I was able to resolve this problem with a simple fix - though it took a good deal of time to find it, so I figured I'd post it here to inform others in the event they have a similar difficulty.
I simply used the Field validation module which gives the user the capability of selecting his/her own UID for any field instance...quite straightforward.
Hope that helps!

Mapping a UID on custom module content


Embedding $\operatorname{GL}(K^2)$ into $\operatorname{GL}(K^n)$

Question: Suppose $V$ is a two-dimensional $K$-vector space.
Does an embedding $\varphi\colon\operatorname{GL}(V) \hookrightarrow \operatorname{GL}(K^n)$ exist?
I tried multiplying $A \in\operatorname{GL}(V)$ with the basis vectors of $K^n \cong \operatorname{Sym}^n(V)$ via $A(v\cdot w) = Av\cdot Aw$ and take the resulting coordinates as colums for $\varphi (A)$, but I don't see how this is well-defined (i.e. yields linearly independent colums and thus an invertible matrix) let alone a group homomorphism.
Edit: I forgot to mention that this embedding is in particular required to preserve the set of power tensors $v^n \in\operatorname{Sym}^n(V)$ in a way that $A(v)^n = \varphi (A)(v^n)$ - So it is better to think of it as an embedding $\varphi\colon\operatorname{GL}(V) \hookrightarrow \operatorname{GL}(\operatorname{Sym}^n(V))$.
I computed the above construction for $n = 3$ and it seemed to work, but I don't know why $\varphi$ needs to be a well-defined homomorphism in the general case.. Any hints would be greatly appreciated
Comment: I believe you are on the right track with symmetric powers (maybe with some assumptions on $K$). For each $n\ge 2$, there is an $n$-dimensional representation of $GL(2)$, given by it's natural action on $Sym^{n-1}(K^2)\simeq K^{n}$. Unfortunately, I don't have a good source for this, though the Lie algebra version of this result is easy to find.
Comment: Sadly, I know absolutely nothing about representation theory or lie algebras, but this might be a good opportunity to start learning something. I'll look representations of GL(2) up.
Comment: Fulton-Harris, "Representation Theory", has this stuff for $K=\mathbb C$. See Sections 11.1 and 15.5. (Technically, this will give representations of $PGL_2(\mathbb C)$, which can be lifted to $GL_2(\mathbb C)$ by having the center act trivially.)
Comment: Thank you, I'll look into it (funny coincidence by the way, the reason I asked this question is a certain passage in "Algebraic Geometry - A First Course" by Harris).
Answer: What about a map like $g\mapsto\begin{pmatrix}g&0\\0&\mathbf{1}\end{pmatrix}$?$\qquad$ (assuming that $V$ sits inside $K^n$ as $K^2\times 0^{n-2}$)
Comment: You are absolutely right. I forgot to add my additional condition, this is edited now - Thanks though, this was a silly mistake of me.
Answer: Yes, your formula gives a homomorphism in general.  The point is that the formation of $Sym^n V$ is functorial in $V$.  Since $GL(V)$ acts on $V$, it thus acts on each $Sym^n V$ as well.
Comment: Functorial - This seems to be the keyword I was looking for.. Am I right about the fact that I don't need to be as explicit about $\varphi$ as I was in the question? If $GL(V)$ acts on $Sym^n(V)$ via $A \cdot (v_1 \cdot v_2 ..) = (A \cdot v_1) \cdot (A \cdot v_1) ..$, can't I just take - for A fixed - this induced automorphism of $Sym^n(V)$ as $\varphi (A)$? The fact that this is a homomorphism would essentially be the functoriality of Sym(V)..
Comment: whoops, $A \cdot (v_1 \cdot v_2 ..) = (A \cdot v_1) \cdot (A \cdot v_1) ..$ is of course supposed to be $A \cdot (v_1 \cdot v_2 ..) = (A \cdot v_1) \cdot (A \cdot v_2) ..$


Jquery-Mobile: validation

Question: I am new to jquery mobile concept. The validation in the jquery mobile is similar to jquery or not. Please give me the easy tutorials links to understand the validations.
thanks
Comment: Why this post is closed? This post is based on real practical problem and very useful to many developers!
Answer: You can use a normal JQuery validation plugin - here's an example of JQM validation done using such a plugin.
Hope this helps!
Comment: if this answers your question, please mark as Answer for the other members! 10x

Jquery-Mobile: validation


when can one find a $G$-connection that makes a particular section constant

Question: Let $M$ be a smooth manifold and let $E=\mathcal{O}_M^n$ be a trivial
vector bundle. Assume that a linear group $G \subset \mathrm{GL}_n$
acts on $E$ naturally. Let $s$ be a section $s \in H^0(M, E)$. What is
the necessary and sufficient condition for existence of a section $a
\in H^0(M, LG \otimes \Omega_M^1)$ such that $a \cdot s =
-ds$, where $ds$ is understood as section of $E \otimes \Omega^1_M$, and $LG \subset \mathrm{End}(\mathbb{R}^n)$ is the Lie algebra of $G$?
Answer: Formulating the question precisely helped me to understand what is happening: I will post an answer myself.
Substititing vector fields in the 1-forms that are part of the question, one finds that it is really equivalent to the following one. Let $G$ be a liner group acting naturally on $\mathbb{R}^n$, and let $x(t)$ be a curve in $\mathbb{R}^n$. What is the necessary and sufficient condition that for any $t$ there exists an endomorphism $a$ from the Lie algebra $LG$ (acting on the tangent space to $\mathbb{R}^n$ which we identify with $\mathbb{R}^n$ itself) such that $a(x(t)) = -\dot{x}(t)$, where $\dot{x}(t)$ is the tangent vector? This is clearly true if the linear subspace $LG \cdot x(t) \subset \mathbb{R}^n$ is constant for all $t$, then clearly $-\dot{x}(t)$ lies in the same space, and, tautologically, the required endomorphism from $LG$ can be found.


Is there a formula to multiply two column only if both of them not null?

Question: beginner here.
So I have to find a value with calculation like this: Sum of Column C * Sum of Column B / Sum of Column B. But the problem is both of Column B and C have to be not null. I use excel 2007 fyi.
I'm trying SUMIF but confused in how to corporate it. I used SUMPRODUCT but it calculate every cell, basically I want it to calculate only if there is a pair of data. For now I'm doing it manually =((B3*C3)+(B4*C4)+(B6*C6)+(B11*C11))/(B3+B4+B6+B11). But is there a formula I can use because there are so many rows and doing it manually will waste so much time. Sorry if it's a little bit confusing but I attached the image of data dummy that I use. This calculation and requirement is only for Cell C14. Thank you in advance
Data dummy:
Answer: You may try below for Excel-2007.
=SUMPRODUCT(B3:B13*C3:C13*(B3:B13<>"")*(C3:C13<>""))/SUMPRODUCT(B3:B13*(B3:B13<>"")*(C3:C13<>""))

Comment: Thank you so much! It didn't work at first and I was so confused but then I realized some of my cells have '0' value haha. I'll try it to my actual data
Comment: In that case you can try number comparing like `=SUMPRODUCT(B3:B13*C3:C13*(B3:B13>0)*(C3:C13>0))/SUMPRODUCT(B3:B13*(B3:B13>0)*(C3:C13>0))
`


Why isnt my function called in a list? (Angular Dropdown)

Question:

  <button class="btn btn-primary" dropdown-open>My Heroes</button>

Den haag

Amsterdam

Utrecht

Gouda

Eindhoven

Rotterdam

Why is my console saying function is not defined when I select that option? The functions stated in the onclick params do exist in my component as follows:
public goToRotterdam = () => {

let position = {lat:  51.9244201, lng:  4.4777325};
this.gmapWrapper.panTo(position);
}

Uncaught ReferenceError: goToRotterdam is not defined
Any help is appreciated
Edit:
import {Component, OnInit, ViewChild} from "@angular/core";
import { MapsAPILoader } from '@agm/core';
import { Observable, Observer } from 'rxjs';
import {GMapsService} from "./map.service";
import * as data from './inkomen.json';
import * as inbraakdata from '../../assets/output.json';
import * as data_latlon from './inkomen_latlon.json';
import * as inbraak_latlon from './output.json';
import {Http} from "@angular/http";
import 'rxjs/add/operator/map';
import {last} from "@angular/router/src/utils/collection";
import {DropdownModule} from "ngx-dropdown";
import { AgmCoreModule, GoogleMapsAPIWrapper, AgmInfoWindow, AgmDataLayer, CircleManager, AgmCircle } from '@agm/core';
import {$} from "protractor";

@Component({
  selector : 'googlemap',
  templateUrl: 'maps.html',
  styleUrls: ['map.component.css']
})
export class GoogleMapsComponent implements OnInit{
  @ViewChild(GoogleMapsAPIWrapper) private gmapWrapper: GoogleMapsAPIWrapper;
  arr = [];
  arr2 = [];

  jsonLatlon;
map : any;
jsonData;
  result;
  inkomen
  count = 0;
  results: any;
  pages =['abc','bca','pqr'];

  constructor(private http: Http, private mapservice: GMapsService, map: MapsAPILoader) {
  this.jsonData = data;
    this.jsonLatlon = data_latlon
    this.results = inbraak_latlon;
    this.result = inbraak_latlon;

  }

  ngOnInit(){
    console.log(this.jsonData)
    console.log(this.jsonLatlon.data)
    console.log(this.results)
    this.convert()
    let pos1 = {lat: 52.0704978, lng: 4.3006999};
    this.gmapWrapper.setCenter(pos1)
    this.gmapWrapper.setZoom(12);

    }

  title: string = 'My first AGM project';
  //lat: number = 52.1941679;
 // lng: number = 4.6820146;

  public ewa = () => {

    var li = document.getElementById("Denhaag")
    console.log("ewa" +li.innerText);

    alert("ewa");
    let position = {lat: 52.0704978, lng: 4.3006999};
    this.gmapWrapper.panTo(position);
    this.gmapWrapper.setZoom(12);

  };

  public goToDenHaag = () => {
    let position = {lat: 52.0704978, lng: 4.3006999};
    this.gmapWrapper.panTo(position);
  };

  public goToAmsterdam = () => {

    let position = {lat: 52.379189, lng: 4.899431};
    this.gmapWrapper.panTo(position);
  };

  public goToUtrecht = () => {

    let position = {lat: 52.0928768, lng: 5.104480};
    this.gmapWrapper.panTo(position);
  };

  public goToGouda = () => {

    let position = {lat: 52.0115205, lng: 4.7104633};
    this.gmapWrapper.panTo(position);
  };

  public goToEindhoven = () => {

    let position = {lat: 51.441642, lng: 5.4697225};
    this.gmapWrapper.panTo(position);
  };

 goToRotterdam() {
 console.log("We gaan naar Roffa");
    let position = {lat:  51.9244201, lng:  4.4777325};
    this.gmapWrapper.panTo(position);
  };

  public goToAlmere = () => {

    let position = {lat: 52.3507849, lng: 5.2647016};
    this.gmapWrapper.panTo(position);
  };

  public goToGroningen = () => {

    let position = {lat: 53.2193835, lng: 6.5665018};
    this.gmapWrapper.panTo(position);
  };

  public goToNijmegen = () => {

    let position = {lat: 51.8125626, lng: 5.8372264};
    this.gmapWrapper.panTo(position);
  };

}

Added the component class for the map.
Some text. Some more text*
Comment: Did you try with the Angular event syntax: `(click)="goToRotterdam()"`? `onclick` is a DOM element property, it doesn't know where to find your method.
Comment: I tried it that way, but the method is still not firing somehow..
Comment: You can compare your code with [this plunker](https://plnkr.co/edit/cdcx0S0sSqPvFYn7Y1sk?p=preview). The click event works for Rotterdam (you can see it in the console).
Comment: @ConnorsFan where do I see the console? And why are the list items below the button?
Comment: The console is seen with the F12 key (on Windows at least). One important difference in my plunker: it does not implement the dropdown; it only shows the list. In your case, if the dropdown closes when you select an item, you can try to handle `(mousedown)` instead of `(click)`.
Comment: I see that it works there indeed. But dont know why it is not working here locally.. I get a strange error though which I do not understand. Please check my comment below the answer
Answer: Try to define your methods like this in your component,
goToRotterdam() {
  const position = {lat:  51.9244201, lng:  4.4777325};
  this.gmapWrapper.panTo(position);
}

And also use the (click) event as ConnorsFan mentioned.
Comment: I get this strange error message: stats.js:4 Uncaught TypeError: _.vf is not a function
    at new D1 (stats.js:4)
Comment: please post your component code, it's hard to debug otherwise
Comment: That error is likely due to the way you include the google maps api.
Comment: @user3660293 - You can try to just send a string to the console in `goToRotterdam`, to see if everything is OK with the `click` handling.
Comment: No even the string doesnt get logged to the console. @ConnorsFan


Can two logic models with different domains be isomorphic?

Question: I'm trying to find out how logic model isomorphism works.
I have a question.
If I have models:
<code>A: L (language) = {P (predicate)}, M (domain) = {1,2} where P=(1)
B: L = {P}, M = {2,3} where P=(2)
C: L = {P}, M = {1,2,3} where P=(1)
</code>
I suppose that A and B models are isomorphic because it's the same thing (1=2 and 2=3)
But I can't figure out whether A and C are isomorphic. They has the same predicate but they hasn't the same domain.
Answer: Two isomorphic structures may have different domains, but A and C are not isomorphic.
Two structures $X$ and $Y$ are isomorphic if there is a bijection $f$ between them which preserves the structure (e.g. if $P(a)$ holds in $X$, then $P(f(a))$ holds in $Y$, etc.). Since A has two elements and C has three, there are no bijections between them at all, let alone structure-preserving ones!
There is an embedding of A into C - if we consider the map $1\mapsto 1, 2\mapsto 2$, this is an injection from A to C, and preserves structure. However, it's not an isomorphism, since it's not a bijection.
Note that "structure-preserving maps" are called homomorphisms - I've used the phrase above since I think that makes things clearer in the beginning.


Differential equation $\frac{dy}{dx}=f(y),y(0)=y(1)=0$

Question: Differential equation $$\frac{dy}{dx}=f(y),y(0)=y(1)=0$$ where $f:\mathbb{R}\rightarrow\mathbb{R}$ is Lipschitz continuous. Then
$1.$ $y(x)=0$ if and only if  $x\in (0,1)$
$2.$ $y$ is bounded
$3.$ $y$ is strictly increasing.
$4.$ $y^{'}$ is unbounded.
Please help me. Can i say that $y$ must be bounded by given boundary conditions?
Comment: What have you tried, and where are you having trouble? What background material do you know about? Please don't just pose a question with no thoughts or efforts shown. However, notice that the system *only* depends on the current state, so if it starts increasing, how can it come back down through that same $y$-value?
Comment: To be fair, you didn't say that - you asked it. What relevant background results do you know? Where did you encounter this problem?
Comment: Note that 1. & 3. can be eliminated purely from the fact that $y(0) = y(1) =0$.
Comment: i already said that according to me its bounded as boundary conditions..
Answer: Let $y$ be the unique solution.
Suppose $f(0) >0$, then $y$ has a $\max$ at some $x^* \in (0,1)$, and
$y'(x^*) = f(y(x^*)) = 0$, with $y(x^*) >0$.
However, since
$x \mapsto y(x^*)$ and $y$ satisfy the differential equation with initial
condition $y(x^*)$ we must have $y = y(x^*)$ which is a contradiction.
If we assume $f(0)<0$ we obtain a similar contradiction.
Hence $f(0) = 0$, from which we obtain $y=0$.
(Note that Condition 1. can never hold since $y(0) = 0$.)
Note: From the above we can see that if a solution $y$ has a local maximum
or minimum at $x^*$ with $x^* \in (0,1)$, then the solution is constant.
Hence any non constant solution must lie strictly between the boundary conditions and is monotone.
Comment: how its solution is unique??
Comment: its boundary value problem...
Comment: It satisfies a first order differential equation with a specified initial condition and is Lipschitz.
Comment: ok sir....thanks a lot...


How to derive $r, \theta, \phi$ for the sperical coordinate gradient?

Question: I'm trying to figure out how to get the gradient in spherical coordinates.
I'm as far as the author writes in this answer: https://physics.stackexchange.com/a/78514
and I understand how and why to get to this point.
I will just look at the x-component now: $\frac{\partial r}{\partial x}\frac{\partial}{\partial r}+\frac{\partial \theta}{\partial x}\frac{\partial}{\partial\theta}+\frac{\partial \varphi}{\partial x}\frac{\partial}{\partial \varphi}$
So firstly I have to derive $r$ for $x$, but which formula for $r$ should I derive? Simply $r=\sqrt{x^2+y^2+z^2}$?
I don't see how to get to the right result ($1$. For the y and z components: $\frac{1}{r}$ and $\frac{1}{r \sin \theta}$) this way, looking at how $\theta$ and $\varphi$ are defined.
I'm getting more and more confused thinking about what to do next. Googling hast confused me just more, as it seems to be obvious for everyone (except me) how to do this.
Comment: This seems to be a pure math question.
Answer: Yes. $$r = \sqrt{x^2 + y^2 + z^2} \implies \frac{\partial r}{\partial x} = \frac{2x}{2\sqrt{x^2 + y^2 +z^2}} \implies \frac{\partial r}{\partial x} = \cos \theta \cos \phi $$ In the same way you get: $$\frac{\partial r}{\partial y} = \cos \theta \sin \phi \quad\text{and}\quad \frac{\partial r}{\partial z} = \sin \theta $$ You do the same for the other ones: express $\theta = \theta(x,y,z)$ and $\phi = \phi(x,y,z)$ and differentiate. I'll express it for you:
$$\theta =  \arctan\left(\frac{z}{\sqrt{x^2+y^2}}\right) \qquad \phi = \arctan\left (\frac{y}{x}\right)
$$
If $r,\theta,\phi$ aren't expressed only in terms of $x,y,z$, there will be some chain rules that'll only make our lives harder. We should try to reduce the number of variables as much as possible before differentiating. Can you go on?
Comment: Thanks for your answer. How do you get from $\frac{x}{\sqrt{x^2 + y^2 +z^2}}$ to $\frac{\partial r}{\partial x} = \cos \theta \cos \phi$?
Just replace $x = r\sin\theta\cos\phi$,$y=r\sin\theta\sin\phi$ and $z=r\cos\theta$ and then fiddling around with the trigonometric functions until I've got $\cos\theta\cos\phi$ left?
Comment: Well, $\sqrt{x^2 + y^2 + z^2}$ in the denominator IS $r$, right off the bat. Then substitute the expression for $x = x(r,\theta, \phi)$ and simplify the $r$. I just skipped that one step there.
Comment: I just noticed that too when I re-read my own comment. But isn't $x=r\sin\theta\cos\phi$ so $\frac{\partial r}{\partial x}\sin\theta\cos\phi$?
Comment: I used the definition that was on the question that you linked. There's not a standard convention on which angle you call $\theta $ or $\phi $.
Comment: $$x=r\cos\theta\cos\phi$$
$$y=r\cos\theta\sin\phi$$
$$z=r\sin\theta$$
Comment: Oh, sorry! I'm using a different formula here, so I just got a bit confused.
But when going on with $\theta$ or $\phi$ I get some pretty nasty derivations. Is this what you meant when you spoke of reducing the number of variables?
Comment: Yes. Express everything in terms of $x,y,z$. Differentiate. THEN plug back the expressions in terms of $r,\theta,\phi $.


Need to add filter with more than one word in view filter criteria Drupal7

Question: I need to add one filter that can take more than one word for searching.
Right now i selected "contains" option in Operator for filter criteria.
ie i need search string like this:
title=word1 or word2…
So in this case what should be my search url:
search-page?title=word1 word2
Answer: I am not sure if this is what you want.


Using Python to ssh with no modules

Question: I'm in a pickle with writing a script that can SSH into device, run a command and parse that data out to a file. I've written this using Pyparsing and Exscript then I found out that the device I'm going to be using this on is using Python 2.4.4 and Debian 4.1.1 so the modules will not work on this. Now I am back to the drawing board trying to find out how to do this with NO modules. Anyone have any reference or point me in the right direction for this? Thank you in advance.
Here is my code:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
import uuid
from pyparsing import *
import re
import yaml

account = read_login()
conn = SSH2()
conn.connect('126.96.36.199')
conn.login(account)

conn.execute('foobar')
data = conn.response
conn.send('exit\r')
conn.close()

###### PARSER ######

date_regex = re.compile(r'\d\d-\d\d-\d\d')
time_regex = re.compile(r'\d\d:\d\d:\d\d')
pairs = [{'category': 'General Information',
          'kv': Group(Word(alphanums) + Word(alphanums))},
         {'category': 'Last Reset:',
          'kv': Group(Word(alphas, max=1) + Word(alphas)) + Literal(':').suppress()
                + Group(Regex(date_regex) + Regex(time_regex)
                + Optional(SkipTo(LineEnd())))
          }
         ]
# build list of categories with associated parsing rules
categories = [Word("# ").suppress() + x['category']
               + OneOrMore(Group(x['kv']))
              for x in pairs]
# account for thing you don't have specific rules for
categories.append(Word("#").suppress() + Optional(SkipTo(LineEnd())) +
                  Group(OneOrMore(Combine(Word(alphanums) + SkipTo(LineEnd()))))
                  )
# OR all the categories together
categories_ored = categories[0]
for c in categories[1:]:
    categories_ored |= c
configDef = OneOrMore(categories_ored)
suppress_tokens = ["show all", "SSH>", "Active System Configuration"]
suppresses = [Literal(x).suppress() for x in suppress_tokens]
for s in suppresses:
    configDef.ignore(s)

result = configDef.parseString(data)
for e in result:
    print(e)
with open('/Users/MyMac/development/data.yml', 'w') as outfile:
        outfile.write( yaml.dump(e))

UPDATE
I have followed the advice below and now have Pexpect installed and found a older version of Python-Pyparsing that I have also installed. So I'm on my way again to getting my scripts to work with modules. Thanks!
Comment: `pexpect-2.4` is compact enough (I think) to 'install' by just adding one or two files to your own directory.  It doesn't have to be in a system directory.  `paramiko` might need to be in its own directory without yours.
Comment: How about using `subprocess` to talk to a system `ssh` utility?  `pexpect` looks like an early pure Python module that only needs `pty`.
Comment: http://www.lag.net/paramiko/legacy.html  paramiko is another early pure Python SSH library.
Comment: @hpaulj I was looking into using `subprocess`, but having issues with that connecting and running a command. I looked at `paramiko` before I wrote the script above but had some issues, which is why I went with `Exscript`. I'll look at the early releases of `paramiko` and see if that may work. The other thing is the `debian` is so old and won't let me install modules very easily.
Comment: @hpaulj thanks! I added `pexpect` and have the ability to `ssh` into the device, now hopefully I can find a solution with `pyparsing` or another module.
Answer: Looks like this is already solved, but...
As long as your SSH is configured for this host (or the host doesn't require you to log-in), you should be able to do the following.
import os

""" This will execute foobar on the remote host
and store the command output to a text file
on your machine."""
os.system("ssh 188.8.131.52 foobar > ~/data.txt")

""" Commence processing """
data = open("data.txt", mode='r')
# and so on and so on

You can also use the subprocess library, but os.system for these types of tasks is the simplest IMO.

Using Python to ssh with no modules


Prevent highest 3 notes of soprano recorder from "breaking"

Question: I have been using Yamaha YRS-23 soprano recorder (German fingering) since primary school.
My school teacher used to borrow music period for other subjects, so I self-taught most of the recorder techniques (music theory comes from my piano lesson outside school).
I can manage C5 to A6 (excluding C#5 and D#5) consistently. Bb6 and B6 are not so stable, but I usually still can get them right after practicing the related music piece several times.
C7 sounds squeaky in > 90% of the time. I am unable to play C#7 and D7 without squeaking even if I adjust my fingering for one minute. Unfortunately, quite a lot of classical pieces do use these notes (since recorder has a pretty small pitch range) so I can't play them. Any tips?
By the way, the fingering chart came with the recorder is a bit different from Yamaha's online fingering chart (for Bb6, C#7 and D7). Yamaha's online fingering chart seems to be more consistent with other websites' chart (and easier), so I am following that instead.
EDIT
A while ago I bought a Yamaha YRA-302B III alto recorder (Baroque fingering) as some pieces I want to play only fit into alto range. Quite expensive as it is a foreign product not imported in bulk (only one in store at that time). It definitely sounds more "real" than my soprano recorder. I can play the same B6 to D7 fingerings and they break less frequently. I wonder if this is due to "alto range" or "baroque design"?
Answer: Respectfully, switch to a recorder with Baroque/modern fingerings. German-fingered recorders are simply not up to snuff once one gets past novice tunes and you want to explore the real literature or play with others. The compromises necessary to get that 5 hole to work for the low F fingering cannot be overcome without extreme difficulty (or not at all) on the part of the player; the highest notes are just one area of pain.
Fingering charts usually only show the "easiest" fingering for the higher notes, not the best ones.
With a new plastic Yamaha soprano (Baroque fingering), a tuning meter should reveal that h12--56h (half-hole 7) is a good Bb that you can bring into tune as necessary shading 7 using a tiny amount of thumb as the previous answer says.
The high C# is usually played with the bell stopped by your thigh, knee, or pillow. You should be able to find people doing this on YouTube, fortunately it is not a common note.
If you really want to look at the literature as written you may want to
get an alto recorder, learning F-fingering (Baroque only, no German recorders in bigger sizes) . The alto is easier to play well, easier to listen to, and there is a lot of free, original source material to find and play from.
Keep playing.
Comment: Your alternative Bb6 baroque fingering seems to work on my recorder too, it does sound more stable. I have seen the tips for C#7 in another forum, I thought it was a hack invented by the author, finally know that it is a real technique.

I added my experience in alto recorder (baroque) in my original question, please take a look.
Comment: it should be the default fingering across all baroque-ish recorders on all sizes.
Comment: The alto is just easier to play for most people. The 302B is a good, basic instrument that shouldn't have any problems with the high range assuming one has solid technique. Get the matching soprano.
Answer: These notes are always tricky, because they are using the thumbhole, partly closed, to jump up the octave, and the thumbhole is not far enough up the instrument to be in the ideal position to do this for these notes.  You need to do two things: experiment with your thumb position and your articulation.  The way the thumbhole is opened is critical; it should probably be only open a tiny bit, and your thumb should make as clean an edge as possible, perhaps even using your nail so that the tiny bit of the hole that's open is not shaded by the thumb.  And you need to articulate fairly sharply- not necessarily with more force, but you need to start the notes quickly.
Comment: Excellent advice. "Air speed" isn't quite the same as "Air pressure" and for many recorders the very highest notes take more air speed and less pressure than the lower notes.
Answer: One thing I do when playing in the high register is to keep the thumb particularly still when playing the notes around high A.  Once you have found a thumb position that works, then being still with the thumb seems to be the key for me.


how to implement Form Validation in MasterPage using ASP.Net WebForm (bassistance.de form validation)

Question: if i have a single .aspx page my form validation is working fine but if i have masterpage and i have added all .js and .css file in the masterpage header and when i run then validation does not work, any idea how can i achive that?
PS: i am using Bassistance.de form validation
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="validation.aspx.cs" Inherits="Web.validation" %>

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>

    < form id="form1" runat="server">

              First Name :

            < input id="FirstName" name="FirstName" type="text" maxlength="25" class="required" />

              Last Name :

            < input id="LastName" name="LastName" type="text" maxlength="25" class="required" />

              Address :

            <input id="Addr1" name="Addr1" type="text" maxlength="25" />

              Address 2 :

            <input id="Addr2" name="Addr2" type="text" maxlength="25" />

              Zip :

            <input id="txtZip" name="txtZip" type="text" class="ZipCodeMask" />

              City :

            <input id="City" name="City" type="text" maxlength="25" />

              State :

            <input id="txtState" name="txtState" type="text" maxlength="25" />

              Phone :

            <input id="txtPhone" type="text" name="txtPhone" class="phone PhoneMask" />

              E-Mail :

            <input id="EMail" name="EMail" type="text" maxlength="100" class="required email" />

              Comment or Question :

            <textarea id="Comment" name="Comment" cols="40" rows="6" class="required"></textarea>

                <button id="btnCancel" name="btnCancel" type="button">
                  Cancel</button>

                <button id="btnReset" name="btnReset" type="reset">
                  Reset</button>

                <button id="btnSubmit" name="btnSubmit" type="submit">
                  Submit</button>

    </form>

Comment: i found the answer here is the link. http://www.dotnetcurry.com/ShowArticle.aspx?ID=310
Answer: this is because form id is generated when you put in a master page.
use the form id "aspnetForm" and it will work.
example:

and in the HTML it will look like this
<input type="text" id="name" class="required" />


How to prove that $a \begin{pmatrix} 3 \\ -1 \end{pmatrix} + b \begin{pmatrix} 2 \\ 7 \end{pmatrix}$ is true for any real number $a$, and $b$?

Question:
Show that any two-dimensional vector can be expressed in the form $a \begin{pmatrix} 3 \\ -1 \end{pmatrix} + b \begin{pmatrix} 2 \\ 7
\end{pmatrix}$, where $a$ and $b$ are real numbers.

I was able to simplify this down to:
$\binom{3a+2b}{-a+7b}=\binom{x}{y}\\$, where $\binom{x}{y} = a\binom{3}{-1} + b \binom{2}{7}$, but I am not sure what to do from here.
Comment: Please edit the title of the question, it doesn't make any sense since $\displaystyle a\binom{3}{-1}+b\binom{2}{7}$ is not a statement and so it can't be true in the usual sense.
Comment: The result (not yet) in the title holds because these two vectors are a free family and they are because the determinant $$\begin{vmatrix}3&2\\-1&7\end{vmatrix}=23$$ is not zero. So, one does not need to solve the system to show $(a,b)$ exists. But isn't all this in your notes?
Answer: You are almost there.
You have
$\binom{3a+2b}{-a+7b}=\binom{x}{y}\\
$.
This is the set of equations
$3a+2b = x$
and
$-a+7b = y$.
Just solve these for
$a$ and $b$
in terms of $x$ and $y$.
Comment: Oh, wow! Thanks, didn't know it was that simple.
Answer: Note that for all $x,y \in \mathbb{R}$, if we solve $3a+2b=x$ and $-a+7b=y$, we get that $$a=\frac{7x}{23}-\frac{2y}{23}$$$$b=\frac{x}{23}+\frac{3y}{23}$$
We have then that $$a \begin{pmatrix} 3 \\ -1 \end{pmatrix} + b \begin{pmatrix} 2 \\ 7
\end{pmatrix}=\begin{pmatrix} 3a+2b \\ -a+7b  \end{pmatrix}=\begin{pmatrix} x \\ y  \end{pmatrix}$$
Which follows from calculations.
Comment: But aren't you just looping around the problem instead of proving there is actually such values of a and b?
Comment: @ReginaDea I proved that there exists such $a$ and $b$ in $\frac{7x}{23}-\frac{2y}{23}$ and $\frac{x}{23}+\frac{3y}{23}$.
Comment: But you are relying on that there is a x and y value.
Comment: @ReginaDea Yes, $x,y \in \mathbb{R}$, so they exist. They're just arbitrary reals.
Comment: Oh, I see.  Thanks for explaining!


Shorten Tremolo Beam Length in Lilypond

Question: I have a simple tremolo, as the picture below shows. The beam lengths are too long and collide with the note heads. How can I adjust the length of the beams to shorten them a bit? I have tried putting a \override Beam.gap = #1.5 before the \repeat tremolo ... part, but it didn't do anything.
Answer: As explained here https://lilypond.org/doc/v2.25/Documentation/snippets/repeats_003a-engraving-tremolos-with-floating-beams the gap of the tremolo beams can be configured by overriding Beam.gap. The default of Beam.gap is 0.8, so try setting it to something higher?
But what bugs me is that this should not be happening by default, and in fact if I do
\paper {
  ragged-last = ##f
}

\repeat tremolo 8 { <f' fis'>16 g' }

in current stable (2.24) I do get the expected result. This does raise two points for me:

Do you perhaps use an outdated version of Lilypond?
If not, can you post an example where this happens, so we can analyze why this happens in the first place and eventually fix it?
Comment: @Student But it still does not answer the question why this is happening in the first place. This should not require a manual intervention.
Comment: The problem solved, I needed only bigger values to make the beam gap appear on the score.

Shorten Tremolo Beam Length in Lilypond


SQL query to delete data from 2 tables

Question: I am currently trying to delete data from a table (tbl_siphon_req_info) with conditions from another table (tbl_siphon_PO). I am using the following SQL query to do it, but it's still not working:
DoCmd.RunSQL " DELETE tbl_siphon_req_info.* FROM tbl_siphon_req_info a, tbl_siphon_PO b WHERE Concat(a.ross_PO_nbr, a.ross_sku12) = Concat(b.PO_ID, Sbstr(bitem_id,1,12))"

How do I correct and complete my query?
Comment: Please table your question with the database you are using.
Comment: access db//     tmpquery.Sql = Sql
    tmpquery.ODBCTimeout = 180

    Set tmpquery = Nothing

    strSQL = "INSERT INTO tbl_Siphon_po "
    strSQL = strSQL & "SELECT *FROM tmp "
    CurrentDb.Execute (strSQL)
    DoCmd.DeleteObject acQuery, "tmp"
End Sub
Comment: 1. This looks like your homework. You should put more effort into it :P,

2. Your title says QUERY to delete data from TWO tables, but your sql statement don't look like it (more like deleted from the tbl_siphon_req_info with conditions from another table).  You may want to rephrase your intention.
Comment: sorry my bad, its like you said, looking from the complete sql is basic  delete  information from one table  with conditions from another table
Answer: Not all databases support joins with delete, so a typical way to write such as query is:
delete from tbl_siphon_req_info ri
    where exists (select 1
                  from tbl_siphon_PO sp
                  where concat(ri.ross_PO_nbr, ri.ross_sku12) = Concat(sp.PO_ID, substr(bitem_id, 1, 12)
                 );

Note:  Depending on the database, substr() could be spelled substring().  Similarly, concat() is available in most databases, infix operators are also available.
Also, a more typical way to write the where clause is:
                  where ri.ross_PO_nbr = sp.PO_ID and
                        ri.ross_sku12) = substr(bitem_id, 1, 12)

The logic is not exactly the same, but this is probably your intention.
Comment: tmpquery.Sql = Sql
    tmpquery.ODBCTimeout = 180

    Set tmpquery = Nothing

    strSQL = "INSERT INTO tbl_Siphon_po "
    strSQL = strSQL & "SELECT *FROM tmp "
    CurrentDb.Execute (strSQL)
    DoCmd.DeleteObject acQuery, "tmp"
Answer: It really depends on the exact database you are using. But you can use:
DELETE tbl_siphon_req_info, tbl_siphon_PO
FROM tbl_siphon_req_info AS a
LEFT JOIN tbl_siphon_PO AS b ON concat(a.ross_PO_nbr, a.ross_sku12) = concat(b.PO_ID, sbstr(bitem_id, 1, 12)

Comment: here is what i current doing    in vba
 tmpquery.Sql = Sql
    tmpquery.ODBCTimeout = 180
    Set tmpquery = Nothing

    strSQL = "INSERT INTO tbl_Siphon_po "
    strSQL = strSQL & "SELECT *FROM tmp "
    CurrentDb.Execute (strSQL)DoCmd.DeleteObject acQuery, "tmp"
Comment: The VB script in this case is not relevant. What is important is what DATABASE engine you are using.
Comment: vba and access  is what i using to  create the user interface

SQL query to delete data from 2 tables


Find the number of rotations in a cyclic sequence

Question: I have been given two arrays by user. My code should find out how many rotations it had either to left or right . We can safely assume that elements don't repeat.
i/p:
array (arr1)           2, 6, 4, 10, 8 ,12 ,11
rotated array(arr2)     4, 10, 8, 12, 11, 2, 6
o/p: 2
Method1:
My approach to this problem would be like this:
1.Take first element from rotated array and also take the last element from rotated array. Name them "first" and "last" respectively. And also initialize the count to 0
2.Start comparing "first" with elements of arr1 from the beginning , until we reach the number "first" in arr1. At the same time start comparing "last" with elements of arr1 from the end  and keep decrementing until we reach the number equivalent to "last" in arr1.
3.We can do increment and decrement for the step 2 above in the same for loop for step2.And also increment count variable.
3.Thats it, whichever of "first" or "last" finds its equivalent early then break and print the count.
Method2:
Take first element of the arr2 and start comparing it with arr1 elements from the end , and do it until we find a match. The number of times we decremented the arr1 is equivalent to the number of rotations
Is there any better approach then above two ?
Comment: Double the size of the first array, and duplicate it. Loop through it and every time you find a `4`, compare the next `n-1` elements for a match. Store how many steps you had to make to find the `4`. If you know there are no duplicates, then just stop when you've found the `4`. Wrapping around instead of duplicating gets the same result in slightly more complicated code.
Comment: What if a number repeated?
Comment: At first blush, I would maintain an index for each array and start them both at the beginning of each array. (NOTE it's possible that the second array was shifted zero positions, so it's good to check for that.) Then set up a loop that goes the length of the array, comparing each element at each of the indices. If you hit a mismatch before you get to the end of the loop, then increment the second index only and start the loop over. In the comparison in the loop, make it a "wrap around" comparison (if you're at element `11` in a 10-element array, then it wraps to the first element).
Answer: If you "can safely assume that elements don't repeat", then there is no better way than stepping through the elements of arr1 until you've found the first element of arr2. The number of steps you had to make is your left rotation. You can calculate the right rotation by subtracting the left rotation from the length of either array and subtracting 1.
Comment: Even if there are duplicates @Paul Griffiths approach will help us.


How do I fix a categorical predictor at a mean value when predicting from a regression model with multiple categorical predictors in R?

Question: It is my understanding that when predicting from a multiple regression model with continuous predictors, the other predictors are often fixed at their mean. What is the equivalent method for a model with all categorical predictors?
I am running a GLM of the form:
continuous response variable ~ categorical predictor1 + categorical predictor2 + categorical predictor3
So, my question is, how do I fix categorical predictor1 & categorical predictor2 at their mean values to determine the effect of categorical predictor3?
I suspect that the answer may relate to the coding of my categorical predictors. Currently, they are 2-level and 3-level factors that are coded as text (e.g., Age has two levels, Female and Male). Do I need to re-code 2-level categorical predictors as 0,1 and 3-level categorical predictors as 0,1,2?
***Note that my original plan was to use emmeans to compare means between groups for a single model. But it turns out there is substantial model uncertainty among the models in my candidate set (several models with delta AIC <2), and it is common in my field (ecology) to make inferences based on model-averaging in this scenario. To my knowledge, emmeans is not fully equipped to produce means and contrasts for model-averaged objects. Therefore, I think I need to employ the predict.averaging function from MuMIn to get model-predicted means, but this involves holding some variables constant at their means (see example of what I mean here: https://rdrr.io/cran/MuMIn/man/predict.averaging.html).
Any advice would be very much appreciated.
Answer: It does not make much sense to take the average of a categorical predictor.
It would be better to set the values of Pred 1 and Pred 2 to some "typical" values, say their modes, and then draw the graph of the effect of Pred 3.  Unless you have interactions, the graph will look the same to matter which values you set Pred 1 and Pred 2 at; just the vertical scale will be different (shifted).
If you have interaction, say between Pred 1 and Pred 3, you can set Pred 2 to its mode and draw an interaction plot.  If Pred 2 does not interact in you model, then the graph will look the same no matter which value you set Pred 2 at, again the vertical scale will be shifted.
If you have a three-way interaction, then the two-way interaction plots will look different for different values Pred 2, so you should draw all of the interaction plots, one for each Pred 2 value, in order to understand the meaning of the three-way interaction.
See "interaction.plot" in R for a good graphical display.
Comment: Thank you very much for clarifying. Your answer is exactly what I was looking for.


AWS is sending emails thread safe

Question: Using AmazonSimpleEmailServiceClient.sendEmail() ; as per java docs

All service calls made using this client are blocking, and will not return until the service call completes.

Quick question is, is it thread safe?. Can multiple threads be using same instance of AmazonSimpleEmailServiceClient to call sendEmail() in parallel? Like, suppose, multiple users of my website trying to register on the website concurrently.
Answer: This is the answer I got from AWS:
Hi,
You should be able to use the same AmazonSimpleEmailServiceClient() object to send using multiple threads.
Regards,
Rohan
Comment: Fantastically detailed answer from Amazon to complement their fantastically detailed javadoc. Gold star to them.
Comment: @murdoch haha true .. and notice in their answer "should "
Answer: I am adding an updated answer since the original one is from 2012 and not very reassuring about the thread safety.
I am not sure in which version it was introduced, but in latest Java AWS SDK version available today (October 2016, version 1.11.43) the class is annotated as @ThreadSafe, so the sendEmail method can be assumed thread safe

AWS is sending emails thread safe


Creating a Closed Shape in AutoCAD VBA Using AddPolyline with Vertex List from Excel

Question: Sub CreateClosedShape()
    Dim myDwg As AcadDocument
    Set myDwg = AutoCAD.Application.ActiveDocument

    ' Assuming your Excel data is in Sheet1, starting from cell A1
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    ' Assuming your data consists of X and Y coordinates in columns A and B
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Check if there are enough points to create a closed shape
    If lastRow < 2 Then
        MsgBox "Insufficient data to create a closed shape.", vbExclamation
        Exit Sub
    End If

    ' Get the vertices as a list
    Dim verticesList As Variant
    ReDim verticesList(1 To lastRow, 1 To 2)

    Dim i As Long
    For i = 1 To lastRow
        verticesList(i, 1) = ws.Cells(i, 1).Value
        verticesList(i, 2) = ws.Cells(i, 2).Value
    Next i

    ' Create a polyline to represent the closed shape
    Dim polylineObj As AcadPolyline
    Set polylineObj = myDwg.ModelSpace.AddPolyline(verticesList)

    ' Close the polyline by adding a closing segment
    Dim firstX As Double
    Dim firstY As Double
    firstX = ws.Cells(1, 1).Value
    firstY = ws.Cells(1, 2).Value

    ' Add the first vertex again to close the polyline
    polylineObj.AddVertex firstX, firstY

    MsgBox "Closed shape created successfully!", vbInformation
End Sub

i am new to vba to make cad objects in autocad. I am getting error of invalid object for this line (Set polylineObj = myDwg.ModelSpace.AddPolyline(verticesList)). its seems ok but dont know why it giving that.
Answer: AutoCAD's AddPolyline method requires a zero-based array of doubles where the first element is X, the second element is Y, the third element is Z, the fourth element is X, the fifth element is Y, the sixth element is Z and so on.  However, you should consider using AddLightWeightPolyline instead of AddPolyline.  It only requires X, Y pairs instead of X, Y, Z triplets.  Also, AddPolyline is for backwards-compatibility only.
The following code implements this idea for AddLightWeightPolyline:
Dim verticesList() As Double
ReDim verticesList(0 To lastRow * 2 - 1)

Dim i As Long
Dim j As Long
j = -1

For i = 1 To lastRow
   j = j + 1
   verticesList(j) = ws.Cells(i, 1).Value
   j = j + 1
   verticesList(j) = ws.Cells(i, 2).Value
Next i

You don't need to manually close the polyline.  You can do this instead:
polylineObj.Closed = True


Core data to-many NSPredicate with AND

Question: I'm trying to write a query for the find-as-you-type search bar. What I want to do is query "Kind", and return any Kinds for which there is a LocalName with ('name' LIKE %@ AND localeIdentifier == %@).
If I'm only searching the names (so ignoring the localeIdentifier), I could do something like this:
ANY localized.name LIKE %@

What I want is something more like
ANY localized.(name LIKE %@ AND localeIdentifier == %@)

To sum up, searching "Kind", any one item in the to-many relationship "localized" should match both name and localeIdentifier.
Any ideas for the correct syntax of this?
Answer: What you want is a subquery. In predicate format syntax:
SUBQUERY(self.localized, $x, $x.name LIKE %@ AND $x.localeIdentifier == %@).@count > 0

where the SUBQUERY expression returns a collection of instances in the self.localized collection that match the predicate in the third argument. Kind instances for which this SUBQUERY expression is non-empty (ie @count > 0) match your desired criteria.
The SUBQUERY expression was introduced in OS X 10.5.
Comment: Great hint! Exactly what I needed!

Core data to-many NSPredicate with AND


integrating $\int \frac{1}{e^x +1}\:dx$

Question: I've found a method for integration of  $\frac{1}{e^x +1}dx$. However none of the information I found explains the intuition. It might be clear for most people, but I was hoping that somebody could expand on it.
The problem of trying to u-substitute  $\frac{1}{e^x +1}dx$ becomes evident.
Since  $\frac{1}{e^x +1}dx$, where I substitute $e^x$ for u, gives me:
$$\int\frac{1}{u}\frac{du}{e^x}$$
Which still leaves me with $e^x $.
The method that solves it is by expanding the numerator with $e^x - e^x$ which gives us the integral:
$$\int \frac{e^x + 1 - e^x}{e^x +1}dx$$
I have seen that it works. But what compels somebody to expand the numerator with $e^x - e^x$? What benefit does a mathematician intuitively see with this? How could I be sure that it just doesn't give me back the initial integral:
$$\int\frac{1}{u}\frac{du}{e^x}$$
 ?
Comment: Now that you have a link to the question https://math.stackexchange.com/questions/770114/how-do-i-solve-displaystyle-int-frac-mathrmdxex-1, you may see from its answers that nothing _compels_ anyone to change $1$ to $e^x + 1 - e^x.$ It is merely one of several different techniques that could be used.
Answer: Hint:
$$\frac1{e^x+1}=\frac{e^{-x}}{1+e^{-x}}.$$
And since the derivative of $1+e^{-x}$ is $-e^{-x}$, this suggests a useful substitution.
Comment: NO need of substitution: it is already of the form $$\;-\int\frac{f'}f \,dx=\log|f|+C\;$$
Comment: $-\log|f|\;$ , of course.
Comment: Cheers @Alejandro . So ideally when solving similar problems you want to find a common factor?
Comment: @DonAntonio The substitution suggested is $f=1+e^{-x}$
Comment: @ShubhamJohri I know. Still it isn't needed as if one recognizes the integrand as $\;\frac{f'}f\;$ , then the integral is immediate.
Answer: You can still substitute $u=e^x, \frac{du}{u} = dx$, and solve the integral. It's a perfectly valid choice for a substitution.
$$\int \frac{1}{e^x+1}dx = \int \frac{1}{(u+1)u}du  $$
You proceed by fractional decomposition of $\frac{1}{(u+1)u}$.
Answer: Various integrals - or really, a number of problems in math (I've seen it used in real analysis for stuff involving limits by the $\epsilon - \delta$ definition) - can be solved by this technique of adding and subtracting the same thing from a quantity. For example,
$$e^t = e^t + x - x$$
This is because $x-x$ (anything minus itself) is $0$. So adding and subtracting something from itself explicitly like this is fundamentally no different from adding $0$ to something, and thus perfectly valid - if pointless at face value. But sometimes this adding and subtracting suffices in giving us a manipulation that is more handy. In this case, we see that we can split up the fraction after this manipulation:
$$\frac{1}{e^x + 1} = \frac{e^x + 1 - e^x}{e^x + 1} = \frac{e^x + 1}{e^x + 1} + \frac{-e^x}{e^x + 1} = 1 + \frac{-e^x}{e^x + 1}$$
Notice how this might be easier to integrate, namely because of a $u$-substitution of $u = e^x+1$? This manipulation lets us do that!
I'm not sure if there is some sort of underlying intuition, necessarily, beyond trying to find a method which works. Some problems are a matter of trial and error to find something which works.
Sure, sure, in school you may often know ahead of time the method you need to use because you might be covering related material at the time and it's like "well, why would the homework be on something unrelated to the material, so obviously I'm expected to use this method that we're covering." But if a problem faces you out of the blue, say in competition mathematics or in the real world, you have less guidance and so trial and error might be necessary.
Of course, there are other ways to solve this particular integral, as was touched on in two other answers, you need not limit yourself to one method of problem-solving.
It's just a nice little tool to have in your arsenal, one that should be kept in mind because despite its simplicity it is deceptively helpful in some cases. I don't think there's an underlying reason as to why or when it should be used other than "it works," though.
Comment: Thank you for your very thought out answer! I do also try to manipulate whenever I might see a possibility to do so. For this particular problem I could not recognize any methods of manipulating inorder to help me. I actively try to not limit myself to methods discussed in the chapter, but I could not see how somebody would think of expanding the numerator by $e^x - e^x$.
Comment: The other key point about this solution is that you have to think _two_ or even _three_ steps (depending on how you count a "step") ahead, not just one. Because once you apply the trick you don't _directly_ get $du$ - instead, you have to first do the cancellation and then apply linearity before you have a $\frac{du}{u}$ form. But often this type of thinking is not taught - either you are born with it naturally or have to sweet laddie luckie have the right people to teach you this habit.
Comment: @peter.petrov - do you think that the skill for "competition" maths gives a huge edge in actual usage of maths in more sophisticated disciplines like research or application and this if you (meaning this poster writing this specific comment) didn't develop that to participate in that kind of thing then you are at a tremendous disadvantage that means you should give up or settle?
Comment: @The_Sympathizer I don't think anyone should give up. If one has interest in math they should play with it no matter what. I don't consider myself too talented in math (meaning I have seen contestants way smarter than me) but so what... Also as I said I am not sure what fraction is the talent and what fraction is the systematic every day work. I don't know if Einstein really really said this but I like this thought: "intuition is nothing but the outcome of earlier intellectual experience"...
Comment: For absolute clarity: "This is because x−x (anything minus itself) is 0" is valid when $x$ is finite.

integrating $\int \frac{1}{e^x +1}\:dx$


Way to define marginal probabilities

Question: I found this notation in one paper that focuses on copulas:

Consider a $d$ -dimensional continuous random vector $X=\left\{X_{1}, X_{2}, \cdots X_{d}\right\}$ with marginals $F_{i}\left(x_{i}\right)=$ $\mathbb{P}\left(X_{i} \leq x_{i}\right) .$ Given a $x \in \mathbb{R}^{d},$ the distribution function $F(x)=\mathbb{P}\left(X_{1} \leq x_{1}, \cdots X_{d} \leq x_{d}\right)$ specifies
all marginal distributions $F_{i}\left(x_{i}\right)$ as well as any dependencies between $X$.

I understood $X_i$ are random variables. I would kindly ask what is the $x_i$ in this case.
It should also be random variable, but then there is just $x$ which is a random vector then.
When I think of marginal probabilities I imagine something like this:

$X_1$
$X_2$
M

10
20
30

30
10
40

20
10
30

Totals
60
40
100

So marginal probabilities are these form the M column.
So isn't it better to define the marginal probabilities with the uppercase letter, just for consistency.
Your sanity may help me understand the notations.
Answer: The vector $X=(X_1,\ldots,X_n)$ is a random vector made of random variables as components. For instance, $X=(X_1,X_2)$ with $X_1\sim\mathcal N(0,1)$ and $X_2|X_1\sim\mathcal N(-2X_1,2^2)$ is such a thing. The marginal distribution of $X_1$ is $\mathcal N(0,1)$ and the marginal distribution of $X_2$ is $\mathcal N(0,8)$
The joint cdf is defined as
$$F(x)=F(x_1,x_2,\ldots,x_n)=\mathbb P(X_1\le x_1,\cdots,X_n\le x_n)$$
where $x=(x_1,\ldots,x_n)\in\mathbb R^n$. In the above example,
$$F(x)=F(x_1,x_2)=\mathbb P(X_1\le x_1,X_2\le x_2)=\int_{-\infty}^{x_1} \varphi(x_1)\Phi([x_2+2x_1]/2)\,\text dx_1$$
It defines marginal distributions${}^*$ through their cdfs
$$F_i(x_i)=F(+\infty,\ldots,\underbrace{+\infty,x_i,+\infty,}_\text{$i$-th position}\ldots,+\infty)$$

${}^*$I do not understand the table produced in the question, as the probabilities (?) do not add up to 100.
Comment: Gender would be the random variable $X_1$ with possible values "female" and "male" while the number of ice-creams per day would be the random variable $X_2$. These two random variables have a joint distribution given by a contingency table.
Comment: The table is not appropriate because the rows would correspond to the possible values of the rv $X_1$ while the columns would correspond to the possible values of the rv $X_2$.
Comment: Are the $x_i$ scalars then?
Comment: I will gladly accept the answer if you touch the later casing part.
Comment: Am I wrong when I imagine $x_i$ is a sum of $i$-th state of random variables $X_i$? You see my upper table and just replace $M$ with $x$ then.
Comment: OK, this is how I see the marginal probabilities, imagine a table full of numbers, two columns tree rows. Just like one I made in the question. Third column represent the marginal probabilities for the $i$-th value of the random variable. So the column $M$ in the image is random variable itself because it is the sum. If this is the case column $M$ represents a random variable.
Comment: OK, I added the sum to 100 which has sense but if you imagine you may have random variables Man, Woman as columns and many rows each representing how many ice-cream they eat per day. What you suggest each new RV adds a new dimension.

Way to define marginal probabilities


How do I get a function inside of a while loop in a function to work properly?

Question: I have looked and looked for an answer, but I am new to python and the answers I find seem to be over my head or not quite what I need. I am trying to take my code and turn it into multiple functions to complete the simple task of receiving some grades from the user and displaying the input back to the user as they want it. Hopefully this will be more clear when you see my code.
import sys

gradeList = []

def validate_input():
    try:
        gradeList.append(int(grades))
    except:
        return False
    else:
        return True

def average(count, total):
    ave = total / count
    return ave

def exit(gradeList):
    if gradeList == []:
        print "You must enter at least one grade for this program to work. Good Bye."
        sys.exit()

#def get_info():
while True:
    grades = raw_input("Please input your grades.(or Enter once you have entered all of your grades): ")
    if not grades:
        break
    elif validate_input() == True:
        continue
    else:
        print "Please enter a number."
        continue

def give_answers(gradeList):
    while True:
        print "\n",
        print "Please select what you would like to do with your grades."
        print "Press 1 for the Highest grade."
        print "Press 2 for the Lowest grade."
        print "Press 3 for the Average of the grades you entered."
        print "\n",
        print "Or you can press 'q' to quit."
        choice = raw_input("> ")
        if choice == 'q':
            break
        elif choice == '1':
            print "\n",
            print "The highest grade that you entered was %d.\n" % highest,
        elif choice == '2':
            print "\n",
            print "The lowest grade that you entered was %d.\n" % lowest,
        elif choice == '3':
            print "\n",
            print "Your average grade was %d.\n" % average,
        else:
            print "Please enter 1, 2, 3 or 'q'."

#get_info()
exit(gradeList)

gradeList.sort()
highest = gradeList[-1]
lowest = gradeList[0]
count = len(gradeList)
total = sum(gradeList)
average =  average( count, total)

give_answers(gradeList)

Everything works correctly as I have pasted the code, but when I try to define get_info the nested validate_input() function stops working. It no longer populates the list so exit() catches and ends the program. The loop seems to just pass over the validate_input()function altogether because the else statement trips after each time through. My question is how do I get the validate_input() function to work properly while continuing to accept input until the user presses enter?
Comment: You should provide explicit parameters and return values for your functions, rather than rely on scoping. Also, see: http://stackoverflow.com/q/23294658/3001761
Comment: I read through the link, Great Stuff! What do you mean about the explicit parameters and return values? SMH I'm such a newb!
Comment: https://docs.python.org/2/tutorial/controlflow.html#defining-functions
Answer: Pass grade to your function validate_input so it could add the grade to list like:
def validate_input(grades):

Comment: This worked perfectly! Thank you. I assumed that you meant `grades` because that was my variable. Instead of `grade`.
Comment: Yeah sorry for the typo. Thanks for bringing that to my attention.


Conflict of interests

Question: Varnish with Magento is asking about using Magento + Varnish.
I help maintain Nexcess_Turpentine obviously backed up by Nexcess, a Magento partner. I don't want to self promote me or the company but give an actual answer to the question by sending the OP to the extension's GitHub repo. The module is free and maintained mostly by the community.
Is this in some way opposite to the Magento Stack Exchange rules?
Comment: see this: http://meta.magento.stackexchange.com/q/27/146
Answer: This is a free extension. So sharing this extension as an answer is not a problem I guess. But it would be nice if you can add some general thoughts about OP's problem and need to explain how this extension can resolve that efficiently.
Otherwise the answer looks like a link only answer and can be treated as a promotion.
Comment: Agree, good call.
Answer: I'm not so sure about Magento SE but on the SO main-site, asking for a library is off-topic. So if the answer is a link to a Github page, most likely the question was off-topic already.
If however you give an answer and explain how Varnish and Magento (could) work together while the question was asked specifically (e.g. where are cookie-names of Magento documented and how do they affect caching with Varnish or what not) and then provide a link to source-code on Github that shows exemplary how you implemented that (and the code is well written ;)) I'd say there is no problem with that.
You already wrote that this is no self-promotion, so I don't cover self-promotion so far. It would be a no-go.
For me this is merely not about free or non-free, but that an answer is self-contained on the site so the idea of creating Q&A works in a stable manner. References to other websites should only be references, not the actual answer/content.
And don't self-promote. AFAIK for that extension, you should have enough knowledge to give good answers. Place that project on your about page and disclose that you're a developer of it.
And as you see a conflict of interest, do full disclosure in the answer so a user reading it has a better grasp on the context of your answer.

Conflict of interests


Add active class to link  using l()

Question: Seems so elementary but how does one get the active state onto the
 of a link when manually using the l() function?

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the
?
Comment: You won't need the third arg for the l() function at all because html and attribute parameters' default values are same as what you have entered.
Answer: You can't. The l() function is only responsible for rendering the HTML link, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).
The simple answer based on your question is to add it manually:

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

Comment: Thanks for the response, I ended up using arg(3) as it was a controlled set of views filters so it ends up as: `><?php print l('All',...`
Answer: menu_get_item() returns the current active menu item. So you can decide on that, ej:
$classes = '';
$path = 'my/hapiness/complete';
$current = menu_get_item();
if ($current == $path) {
  $classes .= 'active';
}
print "
" . l(...) . "
";

Comment: Thanks @jonhattan menu_get_item() is a good solution for most pages, but in this particular case (not mentioned in the question) the last argument is a views contextual filter so 'my/hapiness/complete' and 'my/hapiness/incomplete' both give 'my/hapiness' as a path in menu_get_item().
Answer: l('<link text>', '<link path>', array('attributes' => array('class' => array('class-a', 'class-b'))));

Comment: Yes this allocates a class to the  tag but the question was about adding the active state to the  wrapping the link.
Answer: $output = '';

$submit_links = array();

$outp = array('0'=>10, '1'=>'20');

foreach ($outp as $key => $value) {
  // if you have dynamic links
  $submit_links[] = l(t('LINK TEXT HERE'), 'node/'. $value, array('attributes' => array('target'=>'_blank', 'class' => 'menu',), 'html' => TRUE));
}

$output = theme('item_list', array('items' => $submit_links));

return $output;

Add active class to link  using l()


realizar soma de valores codeiginiter

Question: Preciso somar alguns valores ao final de uma tabela conforme imagem abaixo:

abaixo segue os códigos que estou utilizando:
Controller:
function index()
    {
        $this->template->set('title', 'Lista de Orçamentos');
        $config = array(
            "base_url" => base_url('orcamentos/p'),
            "per_page" => 9,
            "num_links" => 3,
            "uri_segment" => 3,
            "total_rows" => $this->model->countAll(),
            "full_tag_open" => "
",
            "full_tag_close" => "
",
            "first_link" => FALSE,
            "last_link" => FALSE,
            "first_tag_open" => "
",
            "first_tag_close" => "
",
            "prev_link" => "Anterior",
            "prev_tag_open" => "
",
            "prev_tag_close" => "
",
            "next_link" => "Próxima",
            "next_tag_open" => "
",
            "next_tag_close" => "
",
            "last_tag_open" => "
",
            "last_tag_close" => "
",
            "cur_tag_open" => "
",
            "cur_tag_close" => "
",
            "num_tag_open" => "
",
            "num_tag_close" => "
"
            );

        $this->pagination->initialize($config);

        $data['pagination'] = $this->pagination->create_links();

        $offset = ($this->uri->segment(3)) ? $this->uri->segment(3):0;
        $data['orcamentos'] = $this->model->listar('ocod','asc', $config['per_page'],$offset);
        $data['total'] = $this->model->soma();

        $this->template->load('layout', 'orcamentos_lista.phtml', $data);
    }

Model:
function listar($sort = 'ocod', $order = 'asc',$limit =null, $offset = null) {
    $this->db->order_by($sort, $order);

    if($limit){
        $this->db->limit($limit,$offset);
    }

    $this->db->select('orcdat, situacao, ocod, valor, cnome, pnome,numero,rnome');
    $this->db->from('orcamentos');
    $this->db->join('clientes', 'clientes.ccod = orcamentos.cliente');
    $this->db->join('produtos', 'produtos.pcod = orcamentos.produto');
    $this->db->join('representantes', 'representantes.rcod = clientes.representante');
    $query = $this->db->get();
    return $query->result();
}

function soma(){
    $this->db->select('valor');
    $this->db->from('orcamentos');
    $query = $this->db->get();
    return $query->result();
}

View:

                    ID
                    Cliente
                    Produto
                    Data
                    Situação
                    Valor
                    Numero
        Representante
                    Ações

                <?php foreach ( $orcamentos as $orcamento ) {?>

                        <?php echo $orcamento->ocod; ?>
                        <?php echo $orcamento->cnome; ?>
                        <?php echo $orcamento->pnome; ?>
                        <?php echo $orcamento->orcdat; ?>
                        <?php echo $orcamento->situacao; ?>
                        <?php echo $orcamento->valor; ?>
                        <?php echo $orcamento->numero; ?>
          <?php echo $orcamento->rnome; ?>

                            <a title="Editar" class="btn btn-warning btn-sm fa fa-pencil-square-o" href="<?php echo base_url() . 'orcamentos/editar/' . $orcamento->ocod; ?>">
                            <a title="Deletar" class="btn btn-danger btn-sm fa fa-trash" href="<?php echo base_url() . 'orcamentos/deletar/' . $orcamento->ocod; ?>" onclick="return confirm('Confirma a exclusão deste registro?')">

                <?php } ?>

        Valor Total: <?php  $total  ?>

<?php echo $this->session->flashdata('mensagem');?>

vejam que eu criei uma função para realizar a soma do campo valor mas não consegui montar a query ao utilizar sum ele me retorna que não é uma função reconhecida do CI, minha ideia é que essa soma seja realizada também no momento em que o usuário faça uma pesquisa utilizando filtros por exemplo, ele filtra os orçamentos de X representante e ao final da lista a soma total.
Se alguém puder me indicar a melhor forma de fazer isso agradeço.
Answer: A sugestão mais simples seria gerar a soma na hora do loop:
$total = 0;

// Antes desta linha, adicione a variável acima
foreach ( $orcamentos as $orcamento ) {
    // Adicione depois para somar o valor ao total
    $total += $orcamento->valor;
    ?>

Caso queira inserir o sum na query, você pode realizar a seguinte alteração:
// De
$this->db->select('orcdat, situacao, ocod, valor, cnome, pnome,numero,rnome');

// Para
$this->db->select('sum(valor), orcdat, situacao, ocod, valor, cnome, pnome, numero, rnome', FALSE);

Nota: $this->db->select() aceita um segundo parâmetro opcional. Se você configurá-lo como FALSE, o CI não tentará proteger seus nomes de campos ou tabelas. Isso é útil se você precisar de uma declaração de seleção composta onde o escape automático de campos pode quebrá-los.

realizar soma de valores codeiginiter


c# if or logic comparison

Question: Can someone explain the logic of the ifs with || in c# because at the moment all three ifs execute
     string bla = "0";
        if (bla != "0" || bla != "")
        {
           //
            Console.WriteLine();
        }
        if (bla != "0" | bla != "")
        {
            //
            Console.WriteLine();
        }
        if (bla == "0" || bla == "")
        {
            Console.WriteLine();
            //
        }

Comment: I would prefer it if you explained in detail what each statement does, what it evaluates to, what you expected it to evaluate to and why you expected this. That would be great.
Comment: All three execute because they are all three true.  If you only want the first matching `if` to execute, then use `else if` instead for the second and third.
Answer:
The first one says: bla is not "0" OR bla is not an empty string.
The second one says: bla is not "0" [bitwise] OR bla is not an empty string.
The third one says: bla is "0" or bla is an empty string

The bolded parts are what cause the IF condition to pass.
I won't explain bitwise operators in depth, but what you need to know here is that it will execute the 2nd part even if the 1st part is truthy (i.e. it's not lazy like logical operators).
Answer: All ifs are true because || and | are or operators and bla can't be equal to zero and and empty string at the same time. This means that one of the or clauses always evaluates to true and this results in all if statements executing.
Did you want to use the && (and) operator instead ?
Answer: That is the 'OR' operator.  Only one condition needs to be true for the if to execute.
By replacing the variable and reading "out loud" you get the following:
#1  if "0" != "0"  OR  "0" != ""  in this case it is true that "0" != ""
#2  if "0" != "0" | "0" != ""   in this case you have false | true (bitwise) which equals true
#3 if "0" == "0" OR "0" == ""  in this case "0" == "0" is true so the entire condition is true.
You might try these with the && (AND) operator to compare the difference.
Comment: Thanks && is what I am looking for, I am being an idiot
Answer: || is an alternative which derives from the bascics mathematics. It can be understood as OR connective, If we have given at least two logic formulas p,q, then following table applies. 1 is true 0 i false.
p | q |  p || q
0 | 0 |    0
0 | 1 |    1
1 | 0 |    1
1 | 1 |    1

The logical expression in any conditional instruction is evaluated by the logical rules known from mathematics.
Before asking more questions you should learn about: conjunction &&, alternative || , exclusive alternative ^ and unary operator negation ! also you should learn about lazy evaluation.
Answer: || in ifs means "or" condition, so in your code each if will be execute when bla equals to "0" or when bla equals to "". You have three if equal so they will be execute because bla equal to "0".
Answer: The difference between || and |, is that with logical Or (||), if the first operand evaluates to True, the second one is not evaluated. With bitwise Or (|), both are always evaluated. The outcome in your case is the same.
See MSDN for more details.
Answer: The way these are compared is like this:
With the "or" (||) comparator, if one or both are true, the whole comparison will be true. i.e.
true || false = true
true || true = true
false || false = false

So because in all three, one of the comparisons is true, all 3 execute
The opposite side of the coin: and (&&) works the opposite way
true && false = false
false && false = false
true && true = true

c# if or logic comparison


Visual C++ 2008 can't include its own static library

Question: I have two projects: a static library and a DLL that will link statically to this static library. Let's assume:
foo.lib (static library)
bar.dll (links against foo.lib)

foo.lib has the following function:
fooFile(...);

I successfully built the statically lib and dumpbin /symbols tells me that the function is there (although with some name mangling). When trying to link it against the bar.dll project, I get the following error:
error LNK2019: unresolved external symbol _fooFile referenced in function _fooSomething

Why is this failing? The same code works without issues in a Linux environment.
Answer: bar.dll project is compiled as C, or else includes foo.lib's headers under extern "C" {...}. Essentially, one project exports the function as having C++ linkage, while the other tries to import it with C linkage.
Comment: I forgot Visual C++ uses C++ as default :)