How to code multiple values field in Views PHP?

Question: I need help setting up ViewsPHP to evaluate 3 pieces of data? (I barely know any PHP)
ViewFields
I have a View with three embedded Viewfields:
Node count
$row->view
[views_field_view_view]
Time ago (1 unit)
$row->view_1
[views_field_view_view_1]
Success rate
$row->view_2
[views_field_view_view_2]
Value code
In the Value Code text area I want to call all the values. I currently have:
return $data;

Output code
In the Output Code I want to do something like this:
<?php
if ($row->view >= 5 AND $row->view_1 >= 5 AND $row->view_2 >= 80) {
    echo "Amazing person";
}
elseif ($row->view >= 3 AND $row->view_1 >= 3 AND $row->view_2 >= 70) {
    echo "Good person";
}
elseif ($row->view >= 1 AND $row->view_2 >= 60) {
    echo "Interesting person";
}
else {
    echo "Content needed";
}
?>

It's only outputting "Content needed" so what have I done wrong?
EDIT: Updating to 7.x-2.x-dev makes this work.
Answer: Structurally, your code looks fine, it's probably because
$row->view =

5

 basically the 5 has HTML tags around it.
so

5

 does not equal 5
You can use the PHP strip_tags() function to get rid off the tags.
if (strip_tags($row->view) >= 5 AND strip_tags($row->view_1) >= 5 AND strip_tags($row->view_2) >= 80) {

So try this:
<?php

$a = strip_tags($row->view);
$b = strip_tags($row->view_1);
$c = strip_tags($row->view_2);

if ($a >= 5 AND $b >= 5 AND $c >= 80) {
    echo "Amazing person";
}
elseif ($a >= 3 AND $b >= 3 AND $c >= 70) {
    echo "Good person";
}
elseif ($a >= 1 AND $c >= 60) {
    echo "Interesting person";
}
else {
    echo "Content needed";
}
?>

PS: no need to have anything for value code return $data;.
Comment: Maybe it needs more than just strip_tags to parse the ViewField because I'm getting crazy results. EQUAL TO works but LESS THAN does not.  $a = 3 is true, $a <= 3 is passed over even though the string is 3.
Comment: @JohnD `$a = 3 is true` equal to needs to be two equals signs `$a == 3` because if you use only 1 equal sign, it sets the variable to 3, rather than evaluate/test to see if it equals 3, which will always return true.
Comment: @JohnD when you `echo $row->view;` what gets printed? just a number or do you see more stuff?
Comment: `echo $row->view;` prints nothing, but `print_r ($data);
` prints this `stdClass Object ( [users_name] => Ben [uid] => 140 [users_created] => 1437618401 [views_field_view_view] =>
3
[views_field_view_view_1] =>
1 year
[views_field_view_view_2] =>
64
)`
Comment: @JohnD "`echo $row->view;` prints nothing" well then that's your problem, your view is empty. `$data` is irrelevant here.
Comment: Right, looks like global:View fields are not loaded in Views PHP.  [...does not work well with Views PHP](http://blog.hsl.virginia.edu/drupalpress/views-field-view-what-works-and-what-irks/) and [more](https://www.drupal.org/node/1677520). Time to construct the view without Global Views Field View.
Comment: @JohnD when you add the view as a field, does it show? Does the view that you're adding as a field have a contextual filter?
Comment: Yes, the View Fields output on their own as they should. Yes, they had a contextual filter operating OK. Now I have reconstructed the view without embedding View Fields and my conditional PHP is working but `echo $row->view;` still shows nothing, not to worry. Just need to get my User Date Created field to print.


Find right triangle vertex by 2 vertex, hypotenuse and angles

Question: Trying to solve this problem for 3D.
Please, see triangle below.

A and C are known vertices - A(x1, y1, z1) and C(x1, y1, z3)
Angle ACB is right angle, others are known
Distances AB and AC are known too
x and y coordinates are the same for A and B
z coordinate is the same for B and C
We need to find vertex B(x2, y2, z3)

I will appreciate for any help!
Triangle
Answer: The answer is not unique.
$$(x_1+a\cos \theta, y_1+a\sin \theta,z_3)$$
is a solution for any $\theta$, where $a=\sqrt{c^2-b^2}$ is known.
Comment: Is _θ_ **ABC** angle?
Comment: Angle $ABC$ is always the same no matter where $B$ is on the circle
Comment: In fact, all triangles are congruent no matter where $B$ is on the circle
Comment: If angle $ABC$ as I have shown here is not equal to the one specified, then there is no solution


Why did TCP-BSD server stuck in read() even data receives?

Question: I've created a TCP server application using BSD sockets and NUCLEO-H743ZI2 development board with STM32CubeMX 5.6.0 & LwIP 2.0.3 in Keil-MDKARM.
I noticed that:

If a client connects and sends 11 bytes or more at first, server
receives the data correctly and read() responds displaying the data.
However, if client sends the first data lower than 11
bytes, read() function blocks even next received data is higher than 11 bytes, until client disconnects. After the disconnection, all the data queued is displayed.

Namely, if first data sent from a client to my server is lower than 11 bytes, event_callback for a rcvevent is not triggered until disconnection.
My aim is to make the server available to one byte reception.
I've pasted my Server task/thread below. Let me have your kind response at your earliest convenience and feel free to request other related files/libraries(lwip.h, lwipopts.h..).
Kind Regards
void StartTask01(void const * argument)
{
    /* USER CODE BEGIN StartTask01 */
    MX_LWIP_Init();

    /*start a listening tcp server*/
    int iServerSocket;
    struct sockaddr_in address;

    if ((iServerSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Socket could not be created\n");
    }
    else
    {
        address.sin_family = AF_INET;
        address.sin_port = htons(80);
        address.sin_addr.s_addr = INADDR_ANY;

        if (bind(iServerSocket, (struct sockaddr *)&address, sizeof (address)) < 0)
        {
            printf("socket could not be bound\n");
        }
        else
        {
            listen(iServerSocket, MEMP_NUM_NETCONN);
        }
    }
    /*server started listening*/

    struct sockaddr_in remoteHost;
    int newconn;
    char caReadBuffer[1500];
    memset(caReadBuffer, 0, 1500);

    for(;;)
    {
        /*block until accepting an incoming connection*/
        newconn = accept(iServerSocket, (struct sockaddr *)&remoteHost, (socklen_t *)(sizeof(remoteHost)));

        if (newconn != -1)/*if accepted well*/
        {
            /*block until data arrives*/
            read(newconn, caReadBuffer, sizeof(caReadBuffer));
            printf("data read: %s\n", caReadBuffer);
            memset(caReadBuffer, 0, 1500);
        }
    }
/* USER CODE END StartTask01 */
}

Answer: The problem that's causing this issue is that you only call read once on each connection. If you don't happen to receive all the data from that single call to read (which is entirely unpredictable), you will never call read on that connection again.
When you call read on a blocking TCP connection, it will only block if there is no data available. Otherwise, it will give you whatever data is available up to the maximum number of bytes you ask for. It will not wait for more data if only some is available. It's up to you to call read again if you didn't receive all the data you expected.
One your second iteration of the for loop, you overwrite newconn with a new connection. You don't close the old connection. So you have a socket leak.
Comment: Think of simple, there is nothing to do within the scope of the loop. If I call `read()`, it should give output if there is and it gives when the arrival data is more than 11 bytes. Then re-running the application for the same case fails if the arrival data is lower than 11 bytes. There should be something to do within the BSD implementation of LwIP library for my chose of MCU or else may be.
Comment: @SarpEnginDaltaban Fix the two bugs I explained and I'm almost certain your problems will go away. If not, it will at least be possible to diagnose them because there won't be major confounding issues. Your code only calls `read` once per connection, making it entirely unpredictable what you will and won't receive depending on what data happens to be available by luck at the instant you call `read`.
Comment: @SarpEnginDaltaban i am planning to buy this board, does this board have issues with existing libraries, as compared to say an F767ZI ?
Answer: SOLVED:
The problem is, my server was listening port 80. I changed it to port 7 and thankfully bug is resolved, now read() works as expected.
This bug let me think that LwIP had problems on listening that web(80) port instead of others. There should be a some kind of discrimination between listening some spectacular ports even for unimplemented protocols.
Comment: That didn't resolve the bug. It just changed the buggy code from happening to not work under your test conditions to happening to work under your test conditions. Code with bugs in it may well work under some conditions and not others. Changing the conditions so that it happens to work without fixing the bug is a *bad* idea unless you continue to find and fix the actual bug.


How to setup a project with multiple levels of modules for local development

Question: I have multiple app projects of of roughly this layout:

example app (Java)

Java Wrapper with additional functionality

C++ + Shallow Java Wrapper

2nd example app (flutter)

flutter wrapper

Java Wrapper with additional functionality

C++ + Shallow Java Wrapper

3rd example app

flutter wrapper

Java Wrapper with additional functionality

C++ + Shallow Java Wrapper

All apps share the same main dependency (java Wrapper with additional functionality) and its dependency tree. Now I am developing on each app all the way down to C++ code. They are managed as git submodules in their respective parent project.
As there is a high change rate along the whole process, I want the final example to be built for testing from all sources.
I tried several approaches for tying this together into one gradle build:
1. Preferred (but failing) solution: settings.gradle in each project, each project only includes direct dependencies
Now I want this full tree to be managed in one flutter build. So I add the direct dependencies in each projects settings.gradle, just to learn that gradle only supports one toplevel settings.gradle. So this does not work. The presented solutions in aforementioned question mostly try to emulate support for multiple settings.gradle files.
2. Functioning but Ugly: Add all dependency projects are included in the toplevel settings.gradle
Do I really have to include all subprojects manually in the toplevel settings.gradle, when each of the subprojects knows its dependencies perfectly fine? Furthermore, since there are multiple projects depending on this, do I have to do this manually for each of them?
(And don't even get me startet about gradle not telling me, I have a wrong projectDir because I got a typo in the 100rth level of recursive descend!)
3. Probably Working Solution: Use composite builds
This will trigger the builds but now I have to resolve the build artifacts instead of the projects. So same problem with other artifacts.
4. Probably Working solution: Publish dependency projects to a maven (or other) repository and pull that into the app
I did not try this because I find the idea abhorent: I want to test one small change in the C++ code and now have to push that to a repository and potentially do the same on every project above?
This works for a stable project but not for flexible exploratory development. Sure, I want to publish something at the end but I don't want to publish every little step in between.

This left me wondering: Am I doing something unusual? I mean: is there nobody who has the same requirements that gradle does not seem able to fit:

live updates from all the way down to quick test local changes
no repeating of transitive dependencies on the toplevel

What is the common practice in this case?
Comment: *no repeating of transitive dependencies* I guess you are talking about the `include` statements in the `settings.gradle` file, but please note that you do not define dependencies this way, but projects inside the build. At this point there is no hierarchy and therefore, no dependencies. If your projects are really strongly discoupled at each level of your hierarchy, use composite builds. Otherwise, think about a more flat project hierarchy.
Comment: @LukasKörfer I am not sure if they would count as strongly discoupled. As I described, I'd like to codevelop the subprojects iteratively without having a large publish loop in between. As it looks to me, the composite builds would result in locally available .aar files that I would have to find in the toplevel project again, so I did not win anything. `you do not define dependencies this way`: I am new to gradle. All I want to say is: each project needs something from the subprojects. Therefore, they look like dependencies to me, no?
Answer: After Lukas Körfer's comment I took a closer look at composite builds again and noticed that I had a misconception about them. I did not understand that their dependency resolution will solve the finding of the build artifacts for me.
Now I use the composite builds to tie together the whole build while using
implementation 'my.group:project'

to import the code of the subprojects and
includeBuild '../path/to/subproject/'

to pull them in.


View block with contextual filter on taxonomy term name in URL doesn't work

Question: Say, I have taxonomy vocabulary 'fruit' with terms like 'apple', 'pear' and 'grape'.
Through content type 'Healthy', 'Healthy' content is made using a entity reference field to choose a term from the 'fruit' vocabulary.
Now, on a page with path /food/good/apple, a views block is placed that should show content related to taxonomy term 'apple'.
I've tried to make a contextual filter in the views block like this:
When the filter value is NOT available > Provide default value > 'raw value from URL'
And for 'Path Component', I checked 3 (for the third position in the url, 'apple').
This however doesn't return any content.
When I remove the contextual filter, the block shows all Fruit content items.
Can this even be accomplished without using contrib modules?
Any help on how to get the right setup would be welcome!
Answer: Your contextual filter will be expecting the term ID rather than the term name. You'll need remove that contextual filter and then add a relationship to the taxonomy which will then allow you to add a contextual filter for the taxonomy term name rather than the term ID
Comment: Thanks for your answer, I tested this without result: I removed the old filter and added the required relation to the taxonomy term entity reference field for the Fruit vocabulary. Then added a contextual filter on that field for the taxonomy term name, again with the settings: When the filter value is NOT available > Provide default value > 'raw value from URL' And for 'Path Component', I checked 3 (for the third position in the url, 'apple'). Did I do something wrong?
Comment: To debug, I turned on 'show the query' setting, what I found remarkable is that the query uses the 'food' part from the path instead of 'apple'.     SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
    FROM
    {node_field_data} node_field_data
    LEFT JOIN {node__field_fruit} node__field_fruit ON node_field_data.nid = node__field_fruit.entity_id AND node__field_fruit.deleted = '0'
    WHERE ((node__field_fruit.field_fruit_target_id = 'food')) AND ((node_field_data.status = '1') AND (node_field_data.type IN ('healthy')))
Comment: Is that MYSQL snippet after you've done the changes I suggested? As it doesn't look like it because it has no JOIN to the taxonomy_term tables and is still using the field "target_id" in the where clause which will be the term ID. What's ive said should work fine: 1)add a relationship to your taxonomy term reference field 2) add a contextual filter for "Taxonomy term: Name". Is this for a views page? What have you set the url to be for your page?
Comment: Sorry, the snippet was old. After doing the settings this is the query: LEFT JOIN {node__field_fruit} node__field_fruit ON node_field_data.nid = node__field_fruit.entity_id AND node__field_fruit.deleted = '0'
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_node__field_fruit ON node__field_fruit.field_themes_target_id = taxonomy_term_field_data_node__field_fruit.tid
WHERE ((taxonomy_term_field_data_node__field_fruit.vid = 'food')) AND ((node_field_data.status = '1') AND (node_field_data.type IN ('healthy')))
It is for a views block, URL /food/good/apple
Comment: When searching in the setup of contextual filters on 'Taxonomy', I couldn't find 'name' so I think last setup was wrong. Searching on 'name' helped. I think I've set it up like you said, but it doesn't show any output. Because it is a block, I still have to get the name from the URL, and the query shows searching in the wrong part ('food' instead of 'apple').


Como gerenciar o funcionamento e falha na execução das Spiders?

Question: Estou desenvolvendo um módulo para obter informações sobre as spiders que rodam no sistema da empresa. Segue abaixo o modelo onde guardamos o início das operações e o job. Gostaria de validar se os jobs foram realizados da maneira correta e preencher o resto dos campos.
models.py
# -*- coding: utf-8 -*-

from django.db import models

class CrawlerJob(models.Model):

    job_id = models.CharField(verbose_name=u'ID da Tarefa', editable=False,
                              max_length=255, blank=True, null=True,)

    job_started_dt = models.DateTimeField(
        verbose_name=u'data de início da tarefa', blank=True, null=True,
        editable=False)

    job_has_errors = models.BooleanField(
        verbose_name=u'erros?', blank=True, default=False)

    job_finished_dt = models.DateTimeField(
        verbose_name=u'data de fim da tarefa', blank=True, null=True,
        editable=False)

tasks.py
# -*- coding: utf-8 -*-

from app.models import CrawlerJob
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from django.utils import timezone
from scrapyd_api import ScrapydAPI
import celery
import datetime

scrapy_url = 'http://localhost:6800'
scrapyd = ScrapydAPI(scrapy_url)

@periodic_task(run_every=(crontab(hour="6-19")))
def funcao_assincrona():

    crj = CrawlerJob()
    job_id = scrapyd.schedule('projeto_X', 'rodar_spider')
    crj.job_id = job_id
    crj.job_started_dt = timezone.now()
    crj.save()

Uma ideia para isso era ter acesso aos logs do sistema e checar pelo json gerado como o que segue abaixo.
2015-01-09 12:40:18-0300 [spider] INFO: Closing spider (finished)
2015-01-09 12:40:18-0300 [spider] INFO: Stored jsonlines feed (11 items) in: scrapyd_build/items/projeto_X/spider/5a3bc7ca980e11e4b396600308991ea6.jl
2015-01-09 12:40:18-0300 [spider] INFO: Dumping Scrapy stats:
    {'downloader/request_bytes': 2448,
     'downloader/request_count': 5,
     'downloader/request_method_count/GET': 3,
     'downloader/request_method_count/POST': 2,
     'downloader/response_bytes': 28218,
     'downloader/response_count': 5,
     'downloader/response_status_count/200': 5,
     'finish_reason': 'finished',
     'finish_time': datetime.datetime(2015, 1, 9, 15, 40, 18, 93445),
     'item_scraped_count': 11,
     'log_count/DEBUG': 19,
     'log_count/INFO': 8,
     'request_depth_max': 4,
     'response_received_count': 5,
     'scheduler/dequeued': 5,
     'scheduler/dequeued/memory': 5,
     'scheduler/enqueued': 5,
     'scheduler/enqueued/memory': 5,
     'start_time': datetime.datetime(2015, 1, 9, 15, 40, 13, 90020)}
2015-01-09 12:40:18-0300 [spider] INFO: Spider closed (finished)

Existe alguma maneira mais prática de obter essas informações? E no caso de ocorrer erros obter as mensagens geradas por possíveis erros ou exceções?
Answer: Bem, como quem tem acesso aos stats de verdade é o Scrapy (o scrapyd só roda os jobs), acho que o caminho pra resolver esse problema é usar um spider middleware que envie as estatísticas do crawler para a sua aplicação quando o spider terminar.
Você também precisará duma maneira de atualizar a aplicação num spider do Scrapy, e acionar isso no spider middleware.
Eis um rascunho:
from scrapy import signals
import os

class UpdateStatsMiddleware(object):
    def __init__(self, crawler):
        self.crawler = crawler
        # registra método close_spider como callback para o sinal spider_closed
        crawler.signals.connect(self.close_spider, signals.spider_closed)

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def close_spider(self, spider, reason):
        spider.log('Finishing spider with reason: %s' % reason)
        stats = self.crawler.stats.get_stats()
        jobid = self.get_jobid()
        self.update_job_stats(jobid, stats)

    def get_jobid(self):
        """Gets jobid through scrapyd's SCRAPY_JOB env variable"""
        return os.environ['SCRAPY_JOB']

    def update_job_stats(self, jobid, stats):
        # TODO: atualizar as stats na aplicação Django
        pass

Ler mais:

Spider middleware
Scrapy Signals


new domain url for multi sites linked to sub domain drupal install

Question: Because my drupal install is not in the root of document but in a subdomain, everything is a little more difficult for setting up multi-sites.
I found a way of adding multiple subdomains successfully to the subdomain containing drupal install but now that I am wanting to add a new domain url pointing to same IP obviously it keeps wanting to direct to document root and if I set it up in virtualhosts what happens is it makes it so you have to go to URL example.com/drupal/install.php which obviously I don't want because I want it to 'appear' as other multi-sites in the exact url not path to drupal folder.
Do I need to use a symlink for this to work? See I have two domains pointing to the ONE IP but as I have the drupal core in a SUBDOMAIN of the main IP then the second domain name doesn't want to follow the same rules as the other subdomains running off drupal core subdomain and direct from vhost to html/drupal and APPEAR in subdomain url. Rather the second name url is following the path LITERALLY and so I can never install anywhere but path to drupal folder.
So completely stuck on what to do from here. How can I make my second domain url POINT to the subdomain root drupal install and not the root of IP which is static?
Answer: So finally figured this all out.
If like me you are weird and want to use a Sub-domain for your main drupal install and then create multi-sites from that you can just add your virtual hosts to the custom conf file or wherever you keep that.
I found that to do away with .htaccess in favour of the /etc/httpd/conf.d/custom.conf file as well as httpd.conf on linux vps.
BUT if you want to add a new domain directing to same IP it will obviously keep searching for doc root,so even if you add the Drupal folder direction in virtual host it will just go there and not install at your actual URL.
So you need to create a symlink in this case and then add that directive to your virtual host. so it would be something like /var/www/html/drupal/nameofmysite.com  which would be a symlink to the actual folder in sites folder of subdomain.


Sample estimators with big data - should I estimate the standard deviation?

Question: Reading about sample statistics I found that there are some that you use when the SD of the populations are unknown.
However, (assuming the SD of both populations are the same), if your sample size is big enough, can't you just estimate the standard deviations from the samples? Or is that dangerous?
Comment: You can and should estimate parameters from samples (at least when following the classical "frequentist" approach to statistics). Those are going to be only estimates for the true (unknown) parameters. What particular hypothesis test are you asking about?
Answer: What you're thinking of is doing a t-test when the variance is unknown instead of a z-test when the variance is known. If you know the variance, it's better to use the z-test. However, it sounds like you want to say that, since you have such a tight estimate of the standard deviation when you have many observations, you can say that you have the population parameter pinned down.
Well...even then, you don't actually know the population variance. Howeer, the t-test takes care of this internally. As you increase the degrees of freedom for the t-distribution by having a larger and larger sample size, the t-distribution converges to N(0,1). For a large sample size when you almost know the population variance, you're almost doing the z-test.


Let $A$, $B$ be square matrices of order $2$ such that $|I_2 + AB| = 0$. Prove that $|I_2 + BA| = 0$.

Question: In this question, I denote
$$A=\begin{bmatrix}a&b\\c&d\end{bmatrix},$$
$$B=\begin{bmatrix}e&f\\g&h\end{bmatrix}.$$
So, from $|I_2 + AB| = 0$, I'll have:
$$(ae+fc+1)(gb+hd+1) = (ga+hc)(eb+fd).$$
If $|I_2 + BA| = 0$ (which we have to prove here), then
$$(ae+bg+1)(cf+hd+1) = (af+bh)(ce+dg).$$
From both equations, I can see that what we're going to prove here is $cf=bg$, more precisely, $g=f$ and $b=c$.
Is my thinking path right or wrong?
I still have not figured out the solution yet, I appreciate any help.
Comment: Proof on wiki: https://en.wikipedia.org/wiki/Weinstein%E2%80%93Aronszajn_identity
Comment: Have you studied eigenvalues? If you do, try to think of what $\det(I_2+AB)=0$ means in terms of eigenvalues.
Comment: See https://mathoverflow.net/questions/31595/how-would-you-solve-this-tantalizing-halmos-problem and https://math.stackexchange.com/questions/1078781/proof-if-ab-i-invertible-then-ba-i-invertible
Comment: Regarding your approach so far, there is no reason to believe that we have $g = f$ or $b = c$. As an example, if we take
$$
A = B = \pmatrix{0&-1\\1&0},
$$
then it is true that $|I + AB| = 0$, but it is not true that $g = f$ or $b = c$.
Comment: Order 2 like $A^{2} = I$?
Answer: We have
$$
|I_2 + AB| = a e (d h + 1) - b c f g + d h + 1
$$
which is clearly invariant under swapping
$a\leftrightarrow e$,
$b\leftrightarrow f$,
$c\leftrightarrow g$,
$d\leftrightarrow h$.
Hence
$$
|I_2 + AB| = |I_2 + BA|
$$
Answer: Note that $|I + AB| = 0$ if and only if $I + AB$ is non-invertible, which is true if and only if the equation $(I + AB) x = 0$ has a non-zero solution $x$.
Suppose that $x \neq 0$ is such that $(I + AB)x = 0$. We see that
$$
Ix + ABx = 0 \implies ABx = -x.
$$
Note that because $A(Bx) = -x \neq 0$, it must be the case that $Bx \neq 0$.
Using our observations so far, note that
$$
BA(Bx) = B(AB)x = B(-x) = -Bx.
$$
In other words, $Bx \neq 0$, and we have
$$
BA(Bx) = -Bx \implies IBx + BABx = 0 \implies (I + BA)Bx = 0.
$$
So, the equation $I + BA y = 0$ has a non-zero solution. It follows that $|I + BA| \neq 0$, which was what we wanted.
Comment: I think maybe you want a couple of edits in your last two sentences?
Answer: It is just a corollary (taking $n = m = 2$) of the result below:
For $A \in F^{m \times n}, B \in F^{n \times m}$, it follows that
\begin{equation}
\det(I_{(m)} + AB) = \det(I_{(n)} + BA). \tag{$*$}
\end{equation}
To prove identity $(*)$, consider the block matrix:
\begin{align}
\Delta = \begin{pmatrix} I_{(m)} & A \\
-B & I_{(n)}
\end{pmatrix},
\end{align}
and verify decompositions below:
\begin{align*}
& \begin{pmatrix}
I_{(m)} & A \\
-B & I_{(n)}
\end{pmatrix}
\begin{pmatrix} I_{(m)} & 0 \\
B & I_{(n)}
\end{pmatrix} =
\begin{pmatrix}
I_{(m)} + AB & A \\
0 & I_{(n)}
\end{pmatrix}, \tag{1} \\
& \begin{pmatrix}
I_{(m)} & A \\
-B & I_{(n)}
\end{pmatrix}
\begin{pmatrix} I_{(m)} & -A \\
0 & I_{(n)}
\end{pmatrix} =
\begin{pmatrix}
I_{(m)} & 0 \\
-B & I_{(n)} + BA
\end{pmatrix} \tag{2}
\end{align*}
Taking determinants on both sides of $(1)$ and $(2)$ then yields
$$\det(\Delta) = \det(I_{(m)} + AB) = \det(I_{(n)} + BA).$$


Deprecation Warning - Compass Unsemantic

Question: Estou tendo um problema quanto a compilação de alguns códigos SASS + Compass + Unsemantic que gera o seguinte aviso:
DEPRECATION WARNING on line 17 of /Library/Ruby/Gems/2.0.0/gems/compass-unsemantic-0.1.5/stylesheets/compass-unsemantic/_unsemantic-grid-desktop.sass:
  @extending an outer selector from within @media is deprecated.
  You may only @extend selectors within the same directive.
  This will be an error in Sass 3.3.
  It can only work once @extend is supported natively in the browser.

Esse aviso sempre aparece quando eu compilo o código, e gera na verdade dezenas deles, enchendo todo o terminal do mesmo. Infelizmente não encontrei nada a respeito.
Answer: Parece que existe um problema de compatibilidade entre Unsemantic e SASS 3.3.
No link abaixo, o autor do Unsemantic afirma que o warning pode ser ignorado sem qualquer problema.
Quando o SASS suportar o operador @at-root, o Unsemantic vai ser actualizado e o warning vai ser corrigido.
Parece que, por agora, usar o SASS 3.2 pode resolver o warning.
Fonte: Unsemantic Issue: deprecation warning upon compile #3


Tonality and Modality together

Question: Tonality and modality form a unit in most music, right? You are in F Major or in D minor etc...
Is there a name for the two entities together seen as a unity? I'm working on some musical software and I am searching for a term to name that entity (rather than ToneAndMode).
Comment: Is there any particular reason that the word "key" is not sufficient?
Comment: The key signature is a good start point - if you're asking about relative major/minor, as the question suggests.
Comment: For me, key implies abstracting the overview from a tonal perspective but I might be wrong
Comment: Yes! key is perfect. As you can guess I'm not that current in music theory :-), thanks!
Comment: Well I meant that for me key usually implies concretely a tonal perspective where alterations are likely accidents. It is really a complicated question :)
Comment: http://en.wikipedia.org/wiki/Key_(music)#Keys_and_tonality (look second paragraph) This is what I mean, An scale can be used modaly and tonally, but if you use the word key it seems like you are working in tonality field, and seeing everything as altertions, borrowed chords, traditional harmony (tonal) and so on
Comment: http://music.stackexchange.com/questions/6401/whats-the-difference-between-modal-music-and-tonal-music?rq=1   ONE reference more, ESSENTIAL answer inside for this topic's sake
Answer: Tonality can be used to describe that you are in a key, major or minor, and that you have a Dominant V chord that is the primary means of resolving back to I.
Modality describes playing within a given mode or scale and that the primary means of returning to I is not from a Dominant V.  Most rock/hiphop/funk/rnb/soul is modal (certainly not all).
Important note- You can play in the major or minor mode (Ionian/Aeolian) and be playing modally.  The easiest way I can think of to illustrate the difference is with Minor vs Aeolian.  If you are in minor you will make a chromatic alteration to your 7th degree in the scale to create a leading tone that consequently makes the V chord dominant (would be minor), hence scales like Harmonic Minor.  If you are paying Aeolian your V chord will remain minor and won't always be used as a means of resolving to I; often in Aeolian bVII will fill that role.
So they are different things but they derive from the same set of notes.  So if you play any naturally occurring scale, then the same notes starting somewhere other than I, then you are playing another mode and all of the naturally occurring modes/diatonic scales are contained within that.
Answer: As far as I understand, the concept you look for is Scale.
An scale can be used for either modality or tonality. It all depends on the tonal center (or root if you want it generic since it would be more appropiate "modal center" in the distinction), in the shape of a drone note, emphasis on mode alterations or traditional cadences.
For instance, the principal example is the diatonic scale and its 7 grades which has been used for ages for both tonal and modal pieces, it is the minimum reduction shared concept or structure from my point of view.
We could also say, at least when dealing with harmony (and if you only have in mind ancient or greek modes), that both tonal and modal music can be categorized as ternary in 99.999% of cases, as they are both stacked in thirds, and usually as diatonic as well, but I am not sure that would be correct, as analogously, a quartal armony or non-diatonic scale can have grades and modes and even form a superset where some chords could be actually thirds-based and conform a tonal piece for a while.
Comment: I would think a piece in mixolydian with its tone center on G would normally be written as G major, with accidentals applied to cancel all the F-sharps.  Likewise pieces in lydian centered on F, or dorian centered on D would be written as F major and D minor, respectively, with accidentals cancelling all the B-flats.  None of those pieces would have any sharps or flats in their mode, but would all nonetheless typically be written with sharps or flats in the key signature.
Comment: Many contemporary guitarist will play mixed modal scales with a tonal center. The practice can be at least traced back to Claude Debussey's nocturne "Sirènes". Perhaps the term polymodal might apply?
Comment: I agree that scale is close to the concept but I prefer key (from a reply above) as I have the sensation that includes the tonality more than scale (I might be completely wrong). Thanks for your reply!
Comment: But is a bit heteredox (albeit done) to say you are in the key of G mixolidyan for instance. Most of classics would say you are in C major key. That is why im not sure if key is appropiated concept that aligns both as generic concepts. By the way, very interesting the polymodal perspective. But this has more to do on how this tonality/modality changes over time. Of course it is common to change the root or mode (even key changes), as in grunge

Tonality and Modality together


EMC Clariion metalun "expansion"

Question: I have metaluns stripped across 6 raid groups of 4+1 (2 DAE's) and I would like to add another DAE. I will create another 3 raid groups on this new DAE and would like the metaluns to be stripped across all 9 raid groups without having to migrate any on the metaluns or create concatenated metas. Is this possible?
Answer: Certainly. Create identically sized luns on the new sets, and simply add those to the metalun. The CX will rebuild the metalun creating new stripes accross all the member luns.
Comment: The rebuild time is dependant on the size of the s-ata spindles, rather than the number of spindles in the set. The increased risk of going from 5 to the reccomended 7-8 spindles per raid 5 set is marginal. If this worries you, you may want to consider migrating to raid 6.
Comment: This sounds like a migration task.? This will have performance impact as the "live" luns will be read and written to the same spindles again to be re-stripped.? Also, if I add new LUNs to the meta, am I not increasing the size?
Comment: just spoke to EMC and they "suggest" that I expand the raid groups and that will automatically stripe to the new disks. The only problem is that these disks are SATA and I don't want to do more that 5 disks in RAID5 because of possible rebuild time issues...
Comment: Yes, you are increasing the size of the metalun. Is this not what you're attempting to do? It won't be possible to redistribute the data without a loss of performance during the rebuild. I think, but haven't tested this, that the loss of performance will be minor as parity information does not need to be recalculated.

EMC Clariion metalun "expansion"


Polymer 1.x: How to reset entire app after logout

Question: I have a Polymer app. When a user logs out, I want to reset the entire app to its original state. (Right now, when the user logs back in after logging out, the app returns the user to the app state and page they were on when they logged out.)
Is there any convenient (i.e., global) app design or code pattern for accomplishing this? If there is nothing convenient/global, please show how to accomplish this locally (i.e., on an element-by-element basis).
Edit
After some research (and conversations in the Polymer slack group), it looks like there are two main suggestions so far. Others are welcome.
Reload Browser
One can imperatively refresh the browser page using the JS statement:
location = location;

and 534 other ways.
This solution is unsatisfying to me. It is essentially a hack and creates performance issues and other undesirable side effects such as waiting for the screen refresh and repaint.
Stateless Architecture
Someone has suggested using a stateless app architecture. But I'm not sure how to implement it in the coding context of a Polymer app. Again, suggestions and ideas are welcome.
Comment: Stateless means, that the behaviour of your app is determined bei the users actions so far. If this user would to the same action over and over again he would always do and see the same (basically).
Comment: @sascha10000: Thanks. By way of illustrative example, could you point to a Polymer app that uses stateless architecture? It seems to me Polymer apps are inherently *stateful* because of the fundamental reliance upon databindings, properties and other such entities which possess a state.
Comment: No I don't know any polymer app. But maybe you'll find some interesting articles about the discussion "Stateless vs Stateful"
Answer: Several possible solutions include:

Clear the session in local storage and whereever you have it stored
Maintain a path to all user defined information and set those objects to {} on logout.
Login as anonymous guest user in such a way the new user overwrites the previous users info.
Keep a deep copy clone of the original main wrapper element state, then replace the current element with the old one
Merge the changes if your users data was saved in attributes or annotations they will be reset.
Replace the one element that maintains the users information.
Answer: The best solution I have come up with is to refresh the browser upon user logout using the location.reload() method.
The trick is you've got to add some logic unique to your app that prevents an endless loop condition.

Reload upon logout:

user: {
  ...
  observer: '_userChanged',
},
...
_userChanged: function() {
  var bool = this.foo(); // Add logic here to prevent endless loop condition
  if( !this.user && bool ) {
    location.reload();
  }
},


Defining the smallest integer $k$ such that every graph of minimum degree at least $k$ contains a perfect matching?

Question: I am having some difficulty with how to think about this question. Graph theory questions like this are not my strong point.
Let $n\geq2$ be an even integer. Define $f(n)$ to be the smallest integer $k$ such that every graph $G$ on $n$ vertices with minimum degree at least $k$ contains a perfect matching. Determine $f(n)$ and justify your answer.
To begin with, I thought that complete bipartite graph on n vertices, where $n=2k$ (so as to ensure $k$ vertices in each independent set), would definitely contain a perfect matching. Therefore, $f(n)=\frac{n}{2}$. Can this answer be improved upon?
Answer: This is not the right way to think about the problem: just because a complete bipartite graph $K_{n/2,n/2}$ has a perfect matching, and satisfies $k = \frac n2$, doesn't mean that every graph with minimum degree $\frac n2$ would have a perfect matching.
You should think of it this way: you tell me a $k$, and I try as hard as I can to come up with a graph with minimum degree $k$, but no perfect matching, because I'm mean and don't like perfect matchings. You like perfect matchings, so you want to find a $k$ such that no matter what I do, I can't come up with such a graph.

If you want to take a moment to try to think about the problem again from this perspective, here is the point to pause reading.

Specific examples are good for the other direction. An unbalanced complete bipartite graph $K_{n/2-1, n/2+1}$ has minimum degree $\frac n2 - 1$, so if your choice of $k$ is $\frac n2 - 1$ or less, I can give you $K_{n/2-1,n/2+1}$, and you won't be able to find a perfect matching. So $f(n)$ must be at least $\frac n2$.
In this case, we do actually have $f(n) = \frac n2$, but we need a different argument: one that applies to all graphs with minimum degree $\frac n2$. A theorem you may be familiar with is Dirac's theorem: that any graph with minimum degree $\frac n2$ has a Hamiltonian cycle. If you can find a Hamiltonian cycle, then taking every other edge of that cycle will produce a perfect matching. This completes the proof.


Problem with session based login after moving relevant files to site root

Question: I have a site which I have been testing in a sub-folder of my client's site-root.
I had no log in problems during testing, but then I moved the new site files from a sub-directory to the main site root, and now I'm losing my logged in state after almost every page refresh in secure areas.
I am running a $_session based login system that refreshes the session id on every page load, with a comparison value stored in the MySQL database.
Does anyone have suggestions for what could be causing this problem?
Comment: DEBUUUUUUUG it! Debug it first, and only then both ask and **answer**!
Answer: krico was right in suggesting that the cookie path may be the cause (but the solution proposed seems a bit daft) however you've said that is not the case.
Check to see exactly what cookies (name, path, expiry, flags) are being set and returned by using iehttpheaders (MSIE) LiveHeaders (Firefox) or using a network sniffer like wireshark. Then ask the question again providing details of what you found out.
C.
Answer: Cookies are usually path relevant.  Your previous sub-directory based site was probably setting the cookie (that binds the browser to the user) only for that sub-directory.
A way to fix it is to put a redirection page on the old subdir that adds a cookie to '/' and then redirects to new site on root.
Comment: Not sure I follow. That sub-directory will not exist in the final deployment.
Comment: A cookie in a browser is usualy set for a specific path, so that for example the pages under /web-app-one cannot read the cookies from /web-app-two.
Comment: session.cookie_path is set to / in phpinfo. That sounds right since all the security stuff in handled in one folder.
Answer: If you change session id you will loose all data stored in previous session. You must set session name after every session start command
<code><?php
session_name('AnySessName');
?>
</code>
or use other mechanism to store your variables cross sessions.
Comment: Sorry, I mean a value called $_session['id']. Does this still apply?
Comment: ok. You can write
``
on your page.
Is it changed after reloading page?
Browser is storing session identificator in cookies
Comment: that is not returning anything!
Comment: ok. and if write  before session start wil it returns any errors? looks like seeion not started at all. or lost session. are other variables from session seen?
Comment: sorry. You must call session_name BEFORE you start session)))
I think that you have a new session every time reloaded page.
put  and refresh several times. Is that value chenged?
Comment: Now I'm seeing UserSess echoed.
Comment: Is it new every time or staying the same?
Now write instead $_COOKIE['UserSess']; $_SESSION['id'];
is it changed? if yes - check changing or placing conditions in your code.
Comment: sorry for my english)))
now we check if SESSION var reachable. What error it returns?
Comment: echoing $_COOKIE['UserSess']; or $_SESSION['id']; returns nothing!
Comment: seems session not reachable or started.


Feeds importer pass header values when fetching feed

Question: We have been importing nodes with feeds importer from XML for awhile on this website and now the feed has been changed to a new XML but this time it's password/username protected. The XML feed is literally the same with the exception of a couple new fields.
When I used this XML feed inside of a custom module, I simply pass the username/password into a header of the curl call to authenticate. I currently cannot find the appropriate area to pass header values in within feeds import.
My question would be, is there any support for username/password authentication when pulling in a XML file with a HTTP Fetcher, with Feeds import? Are there any contrib modules that could extend feeds importer to provide the functionality i desire?
Answer: feeds httpfetcher append headers was the module I needed. Once i switched the fetcher I was able to pass in the password & user name into the get request to authenticate the request.
Comment: How to you set the key values? Any example? I don't know how to set up the headers inside the feed httpfetcher append headers modules
Comment: Solved, the problem was a empty final line in the textarea of configuration, passing the
`Authorization|Basic thesecretEncodedtext==`
works


Apache2 client ip and port

Question: Do anyone know if Apache by default is logging the port number of a client and were to find it. I know that it log the ip, but for mobile users there can be several devices with the same ip which uses a different port.
Comment: The source port of every request is random anyway and doesn't help to differentiate between different clients.
Comment: @Sven The source port is mandatory to trace the source of a connection originating behind Large Scale NAT.
Answer: By default Apache doesn't log the port number of the client but it can. Where the logs are is dependent on where you told Apache to log to.
You need to study the mod_log_config documentation, in particular the CustomLog directive and the CustomLogFormats.
Tne documentation is your friend.

Apache2 client ip and port


How do I change assigned redirect url to drupal root url?

Question: Sorry I really don't know how to actually ask this.... But let me explain....
I have my drupal installed in a subdirectory (www.mydomain.com/my-drupal-install). If I type that in the browser url address bar it works fine - drupal loads and I can navigate all links within the domain and the user and admin configuration loads as well. I have set a domain name to that directory in godaddy shared hosting so if I now type (www.my-drupal-install.com) the first page loads but it will not allow me to navigate to any links not even the user or admin login links. I get a 504 error... How can I fix this?
Answer: Fixed.........
You just have to reset the base url ($base_url = 'http://www.example.com';) in your main settings.php file to whatever your desired url is and refresh the page... It should work fine afterwards.
Thanks anyways.


Area of a parallelogram given one side and a perpendicular

Question: This came up while I was doing some tutoring yesterday.  Maybe it's simple, but it has been about 7 years since I last took geometry and I can't figure it out.
Given parallelogram $ABCD$ along with the length of $\overline{AB}$ and the length of the perpendicular from $D$ to $\overline{AB}$, how does one determine the area of $ABCD$?
If the perpendicular met $\overline{AB}$ at a particular point, such as its midpoint, then we could use the Pythagorean Theorem to find the hypotenuse of the right triangle that is formed, which is the other side of the parallelogram, and apply the usual area formula.  However, I can find no result in the book that states any such thing, and drawing out some examples does not convince me either.
Comment: Hint: Perpendiculars from $D$ to $AB$ and $B$ to $CD$ are the same. Now note some identical triangles there, and viola.
Comment: Ha.  So basically if I tilted the paper I would have seen the answer.  Thanks everyone.
Answer: The area is base times height.
Here is an only  slightly dishonest proof. You will need scissors and paper. Produce a  parallelogram $ABCD$. So that this parallelogram will look like the one I have in my head, the vertices $A$, $B$, $C$, $D$ are in counterclockwise order, the base $AB$ is at the bottom, and the point $A$ is on the left. Also, the parallelogram "leans" to the right, but does not lean by a ridiculous amount.
Let $P$ be the point where the perpendicular $D$ meets the line $AB$. If you are drawing the picture I have in mind, $P$ is between $A$ and $B$.  Draw th perpendicular from $C$ to the extension of line segment $AB$. Suppose that this perpendicular meets $AB$ extended at $Q$.
OK, we are all set up.  Note that triangles $APD$ and $BQC$ are congruent. This is easy, the angles match and $AD=BC$.
Now take a pair a scissors, cut out $\triangle APD$, and place the sliced off triangle so that it covers $\triangle BQC$.  So we have sliced our parallelogram into two pieces, and reassembled the pieces to make rectangle $PQCD$.  Thus the parallelogram and the rectangle have the same area. But the area of the rectangle is clearly $PQ$ times $DP$, which is $AB$ times $PD$.
Remark: My assertion that I cheated may be puzzling. But draw the parallelogram so that it leans ridiculously to the right, so that the perpendicular $DP$ meets the line $AB$ to the right of $B$. Then the argument just given breaks down. It can be fixed.
There is a lot of interesting mathematics connected with dissecting geometric figures, and rearranging the pieces to make another geometric figure. For example, there are very nice cut and paste proofs of the Pythagorean Theorem. You may also be interested in the Bolyai-Gerwien Theorem.
Answer: It's the common formula, area is base times perpendicular. Let's prove it, starting from only formula for area of rectangle.
Let the foot of perpendicular from $D$ to $AB$ be $D'$ and from $B$ to $CD$ be $B'$. The given lengths are $AB=CD=a$ and $DD'=BB'=h$. We note that $AD'=CB'=x$, right angles at $D'$ and $B'$ and $DD'=BB'=h$, so triangles $ADD'$ and $CBB'$ are identical.
The area of rectangle is $x\times y$ if $x$ and $y$ are lengths of sides. If we draw diagonal, we get two triangles with obviously same areas, so the area of right triangle is $\frac{x\times y}2$, were $x$ and $y$ are sides.
We have two identical triangles here, so their area (summed) is $x\times h$. We also have a rectangle $D'BB'D$, which has sides $h$ and $a-x$, so the total area of parallelogram is $$A=h\times x+h\times (a-x)=h\times(x+a-x)=h\times a.$$
This is the most basic formula for parallelogram. Alternatively, but a bit less formally, you could "cut" $ADD'$ and snap it to $CB$, so you'd get a rectangle with sides $a$ and $h$.
Answer: Look at the following figure.
$\hspace{2 in}$
$$\text{Area of the parallelogram}=\text{Area of}~~ \Delta ADB + \text{Area of}~~\Delta BCD $$
Now use the fact that area of the triangle is $\dfrac{1}{2}bh$ where $b$ is the length of the base on which the height of length $h$ stands.
Also, note that $AB=CD$ in a parallelogram and the distance between two parallels is the same. (i.e.) the length of the thicker height is the same ass that of the thinner one.
Comment: Another way to look at it is that you can cut one ear of the parallelogram and attach it at the other side (so AD and BC align). You will get a rectangle with known sides.
Comment: Sure. But, I am left with MS Paint to draw good pics. So, I can't draw this precisely to show what you want me to. But, nonetheless an answer in itself! :) (+1)


Validate form before move to next page

Question: I have coded my own validation form. Is there anyway i can prevent page from submit to php (action="process.php" Method="POST") if form is not validated. I have been thinking all day. I have tried with ajax and json. When all fields validated the page never moves an inch or redirect.
Please i prefer my solution in pure javascript. I don't like the frameworks, jquery and stuff. https://codeshare.io/zy91Q7

      function validateForm() {

  firname();
  lasname();
  addr();
  citnma(),
  zipx();
  checkEmail();
  phnc();

}

Comment: Well what you may have not thought of is a *separate* function that validates the form and returns an array of "errors". When this array is empty, submit form, but when not empty display errors and dont submit the form.
Comment: I thought i just did "boss" your needed solution.
Comment: Alright I will give example of the concept. Look for below. This will be a pure javascript solution and is meant to be as an example. You'll have to have to modify to your requirements. Accept it as an answer if it helps.
Comment: But first I need to see what your `firname()` code looks like? You could have just sneaked peeked some code from another student? If it were your code you would have been "proud" to show it, but you didnt for some reason. Seems like you copied/pasted from somewhere and have *no idea* what you are doing.
Comment: Icuzua i wanted to help you. But I realized you just have zero code attempt and its not that you lied, I stand corrected on that. You just showed code that has zero code attempt on the quasi-functions you call which also have zero code attempt. That is you delegated the code problem on functions that simply do not exist yet, since you havent coded them: net sum: zero code attempt
Comment: I checked that helps. Next time include the link on check on question. But anyway, no disrespect to you as a person, I'm just checking. Solution below. You will have to modify it of course to how you like to work with javascript.
Comment: Wow, u got a point boss. can u make small illustration so i can look through?
Comment: i mean like small coding , or site with example or youtube video
Comment: oh yh copied and made changes, my changes were more anyway , i just
Comment: Sorry i didnt see your messages
Comment: i wish i could post my codes here but it isnt working .... says 184 long
Comment: https://codeshare.io/zy91Q7
Comment: i coded it myself, i just took the style by creating function for everything and calling them in , thats all.
Comment: you can check my code
Comment: ok, i'm adding the codes for the function i called.
Comment: you can refresh link and see the other codes
Answer: This solution is just plain js and html. It will need adjustments on validation requirements. It is only an idea to handle multiple form elements for validation before submitting.
Here is the "raw" example which can be run from any browser.
I will follow up with an example that can be run from here Stack Overflow.
Note that in this SOLUTION the error won't refresh to blank of any input change after the error occurred. You can add this logic in if you like.
I included code comments to explain as it goes along in the code.
RAW CODE TO PASTE TO YOUR EDITOR TEST:

<form id="theForm">
    A <input type id="a" name="a">

    B <input type id="b" name="b">

</form>

<button type="button" onclick="validateFormOrSubmit()">Submit</button>

For here on SO to test run this solution:

function errorsFormFrontEnd() {
    // returns an array of unacceptable input
    // Change these conditionals based on needs of valid form

    let errors = [];

    // TODO: trim .value to rid white space, not done in this example

    if ( document.getElementById("a").value == "") errors.push("a");
    if ( document.getElementById("b").value == "") errors.push("b");

    // it would have been easier (typing wise) to loop through form elements above,
    // but I didn't because this an example of the concept.

    return errors;

}

function validateFormOrSubmit() {
    // validates the form, if not valid reports errors, if valid submits to server

    let errors = errorsFormFrontEnd();

    if (errors.length == 0) {

        // Uncomment next line to do the real submit form to server

        // document.getElementById("theForm").submit();

        // Next line not needed if you handle it elsewhere

        document.getElementById("form_error_message").innerHTML = "All fields meet requirements.";

    }
    else {

        // errors exist in form, hence length != 0

        // Show some kinda form error.
        // Be more specific on these messages with separate spans above each element, idea?.
        // That is, loop over the errors array with explicit if conditions.

        // Alteratively make so errors array contains plain language and display that in div.

        // For this example "form_error_message" will contain literal text no matter which error occurs.

        document.getElementById("form_error_message").innerHTML = "All fields are required.";

        // Notice we don't submit the form in this else block.
        // We need validation to submit the form when this function runs next time.

    }

}

<form id="theForm">
    A <input type id="a" name="a">

    B <input type id="b" name="b">

</form>

<button type="button" onclick="validateFormOrSubmit()">Submit</button>
Comment: I see. Yeah frameworks are popular. Serious hires want you to know vanilla too so stick to that track. But if (like for me) is all just learning, I'd suggest vanilla at first too, then (or same time) frameworks to see how you would make it simpler for yourself.
Comment: *"i have to take it off and do it in js codes"* ... yeah submit on native functionality is for test purposes these days. You have to find option for "Accepted Answer". So it gets a checkmark.
Comment: No problem. I just didnt know you were serious at first.
Comment: Wow , i'm getting it, i think the major problem was the adding of submit to the button. i have to take it off and do it in js codes
Comment: thank u , u made this simple, i hate jquery syntax so i was thinking it wouldnt be possible with it .....
Comment: oh lol, very serious, i started learning javascript 5 months now... but only problem was that everyone seems to be coding with frameworks like jquery , was hard finding someone who knows fully the javascript codes and i didnt like it. i want to move straight to react and angular after understanding more of JavaScript language.   it took me a week coding my own validation .....
Comment: thank u once again, u r legend , i created an array and threw the letters in then called it. then I use for-loop to loop through . it worked miraculously... Thanks again once, i couldn't figure it out yesterday so slept , wake up , then i killed it simple
Answer: you can change the action of the form in js under condition you want in JavaScript
if ( your statement ) {
document.getElementById("yourFormID").action="pageYouWant";

}

Validate form before move to next page


How to tell the number of solutions to a simultaeneous equation?

Question:
How many solutions are there to the following simultaeneous equations?:
  $$
\begin{align}
x - 2y + 3z = 1\\
2x + 2y - z = 4\\
4x - y + 5z = 6
\end{align}
$$

How can I know the number of solutions that there are?
EDIT:
I have found z = 0, y = 2/7, x = 11/7 as solutions but the answers I have say that there are infinite solutions. How can one deduce this?
Please note that I am a high school student and am unable to understand advanced mathematics.
Comment: This kind of problem is usually the _very first thing_ a linear algebra textbook discusses. So it is difficult to imagine how you can know enough to have tagged the question "linear algebra" and still not know the answer already. Please extend the question with some discussion of what you already know, such that we can give an answer that addresses the knowledge you're actually searching.
Comment: My apologies, I have done this.
Comment: If you have a solution attempt that gives wrong results (or several solutions attempt that give _different_ results), **edit your question to show those attempts**. That will allow people who answer to figure out more precisely what the mistake or misunderstanding you need to correct is.
Comment: From rearranging, I can find several sets of solutions but the answers say there are an infinite set and I do not know how to deduce this.
Comment: There are only three possibilities for the number of solutions to a system of linear equations: none, one, or an infinite number. If, as you say, you can find several solutions, then you know that it's not the first two possibilities.
Comment: @CasperC. Your above solution $(x,y,z)=(11/7,2/7,0)$ is wrong: take the second equation. Then you have $2x+2y-z=22/7+4/7-0=26/7\neq 4$.
Answer: Find the augmented matrix corresponding to the system of equations, then, using Gaussian elimination, manipulate it into row echelon form. This will give you information about the number of solutions.
Answer: Hint: multiplying the first equation by $-2$ and addin g to the second we get
$$6y-7z=2$$ (I)
multiplying the first by $-4$ and adding to the third we get
$$7y-7z=2$$ (II)
can yuo finish?
multiplying (I) by $-1$ and adding to (II):
we get $$y=0$$ and $$z=-\frac{2}{7}$$
i have got $$x=\frac{13}{7}$$ Make a Control if my solution is right
Comment: Thanks. The answers I have say there are infinitely many solutions. Are they wrong/how can that be?
Comment: @CasperC. If the system matrix is invertible, then there is one and only one solution.
Comment: Pardon, but what is the meaning of 'invertible' in this context?
Comment: I made a Control that your solution is correct. Caspar's solution above is not correct.
Comment: thank you for this Information Dietrich!
Answer: Write the system as $Ax=b$ with the matrix
$$
A=\begin{pmatrix} 1 & -2 & 3 \cr 2 & 2 & -1 \cr 4 & -1 & 5 \end{pmatrix}.
$$
Since $\det(A)\neq 0$ we can form the inverse, so that there is a unique solution $x=A^{-1}b$. Indeed, $x=A^{-1}(Ax)=A^{-1}b=(13/7,0,-2/7)^T$. In general, use row-echelon form, and see how many elements your field $K$ has (such equations do make sense over finite fields, too).
Answer: The general result  for a square matrix of dimension $n$ is the following:

If the matrix has maximal rank $r=n$, there is exactly one solution.
If the matrix has rank $r<n$, and if the augmented matrix has the same rank, the solution are an affine subspace of dimension $n-r$.
If the matrix has rank $r<n$, and if the augmented matrix has rank $r'>r$, there is no solution.


Should I worry about this strap pin?

Question: I recently bought a Fender Stratocaster that came stock with Schaller straplocks. This is great, because I pretty much always play standing. In shows, I jump around and do all the tricks in the book. (Guitar behind head, guitar throws etc...)
Unfortunately, the neck-side strap pin wiggles a little bit whenever I jump around. The screw feels solid, when I pull on the offending pin. I have hesitated to do some of my tricks as a result of this thing.
The movement is 5 degrees at most. Should I take it to a luthier for inspection?
Answer: I had a similar issue with a pick guard screw that I stripped by removing my pick guard so much while experimenting with electronics. While I certainly didn't get this issue in such a colorful way as you--I'm way more boring--it still was an annoyance to me. I fixed the problem by purchasing some wood putty, filling up the old hole, drilling a small pilot hole, and screwing the wood screw back into place. It's been solid for about 2 years now.
The only additional issue I can see here is that you will be placing a lot of stress on the joint whilst you perform your cool tricks--so I recommend patching and re-drilling as I mentioned above along with getting a longer screw. Probably double the length of your current screw should suffice and you can get those types of wood screws at any hardware store cheap--just remember to take the original with you so you get the correct diameter, thread grain, and screw head. Wider screws have the potential of cracking the body just like @InternalConspiracy mentions, but a longer screw will increase the development length of the screw in relation to the wood. This will make your strap lock more sturdy, because there are more turns of the screw in contact with the wood allowing it to remain in place and dissipate the forces of your antics more evenly. Additionally, a deeper screw will be sturdier because it prevents more rotation--what's known as a moment in physics and engineering.
I realize that's way more technical than you probably care to go, but there are advantages to being married to a civil engineer XD.
Answer: Try tightening the screw a little more or to be safe and not risk cracking the body, you may want to also try removing the screw and drilling the hole just a little deeper.  That should secure it in there.  I had to do this when I installed my aftermarket Schallers on my Les Paul and BC Rich thin-line acoustic/electric.  Easy enough for me and I'm scared to do anything to my guitars that involve power tools.
Also I thought a small piece of felt cut to fit under the strap button.  That could work too if you don't want to drill.
Link to a How-To install Strap Locks
Answer: Are you saying there is a 5 degree play in the screw itself, or are you saying there is play within the straplok mechanism?
If it is within the screw itself, I would consider using a longer screw.
Schaller straploks generally have a bit of "wiggle" to them anyway.  If that bothers you, check out a few of the other systems around.
Comment: It's a wiggle on the button that gets screwed onto the guitar, but the screw itself is rock solid. I guess it just means that the screw isn't tight enough, but I think I need a deeper pilot hole to make it tighter.
Answer: There's no need to worry about this. I have Schaller Security locks on all my guitars and my bass. They all do wiggle around a bit, but that's nothing to worry about as long as the actual pin that's screwed on your guitar fits tight.
The Schaller system is one of the best on the market actually, I tried different systems before I switched to Schaller and was never satisfied with other solutions.
Even thought the Schaller wiggle around a bit, they NEVER came loose before, so I'd say it's safe. :)

Should I worry about this strap pin?


How do I write this rhythm correctly?

Question: I'm not that good in music theory. There is this rhythm I can't find the right way to notate. Logic Pro shows it like this: (if you need mp3. let me know).

And this is the rhythm I play. Right hand is very fast.  The 2 notes under is the left hand. The other notes are the right hand.
Answer: I don't personally see anything wrong with this notation; it's perfectly clear! If I came across it in a score, I would know exactly what was intended.
It's a slightly tricky rhythm to perform, because the performer must subdivide the first two sixteenth notes in three before immediately switching to a duple subdivision starting on the third sixteenth note. But this is a standard skill, so most competent musicians will perform it without problem.
This rhythm looks 100% correct to me as is, and I don't see any reason to try to improve it. But one possible improvement, as Heather S. mentions in the comments, is to beam all of the right-hand sixteenth notes into one beat:

If you're worried by what appears to be five sixteenth notes in the span of only four, the first three are part of a triplet. See What exactly does a 3 mean over a quarter note and an 8th note?
Comment: @HeatherS. I *almost* included that originally; you've inspired me to edit it in, thanks!
Comment: Agreed. It looks correct.
Comment: The only thing that would make it slightly easier to read is a bar connecting the last 16th to the triplet 16ths with the rest floating above it where the 3rd 16th note would be.
Answer: I don't see any mistakes in the notation, although the alternative beaming suggested by Heather S. and Richard is a good idea for clarity.
However, looking at the piano roll screenshot that you posted, and speaking from experience, perhaps that is not exactly what you intended to write. Automatic notation tends to cluster some of the notes and also create unwanted offbeats. What I see on the piano roll looks more like this to me:
Comment: This is a really great point; I didn't notice that they were staggered in the screenshot!
Comment: Although the eighth rests in the right hand should be sixteenths, no?
Comment: Maybe, but since I don't know whether that was intended or not, I wrote it based on the piano roll only. The 4 base notes are pretty equidistant in time, so that's why I wrote it like this.

How do I write this rhythm correctly?


How to call REST Api in Xamarin.forms Portable app in Visual Studio 2015

Question: I am trying to connect a Xamarin.Forms portable app using REST service. I am using Visual Studio 2015 Enterprise Edition.
Rest Service is published locally which is running fine by url.
When I am trying to call my Rest service in application. It is throwing an exception:

{System.Threading.Tasks.TaskCanceledException} with "One or more errors occurred."

C# Code at ServiceWrapper.cs:
public async Task<string> GetData()
        {
            try
            {
                var client = new HttpClient(new NativeMessageHandler());
                client.BaseAddress = new Uri("http://ipaddress/");
                client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync("IRESTApi.svc/xml/12").Result;
                string content = await response.Content.ReadAsStringAsync();
                return content;
                //using (var client = new HttpClient())
                //{
                //    var result = await client.GetAsync("http://ipaddress/IRESTApi.svc/xml/12");
                //    return await result.Content.ReadAsStringAsync();
                //}
            }

            catch (Exception ex)
            {
                var t = ex.Message;
                return t;
            }
        }

I am trying above method using this reference in android device. Please help.
Comment: Can you check the inner exception? It says there are multiple errors, there should be some details somewhere :) Also is this error on Android, iOS?
Comment: As a side note, you should replace this `client.GetAsync("IRESTApi.svc/xml/12").Result` with this `await client.GetAsync("IRESTApi.svc/xml/12")` . Use `await` whenever you can and  I can't find any reason not to use it in your context.
Comment: @GeraldVersluis I have mentioned it for android device. and innerexception is "{System.Threading.Tasks.TaskCanceledException}".
Comment: That is the type of the inner exception. Please update your question with the messages of all the inner exceptions (an inner exception can have another inner exception)
Comment: @user3185569 Not working :( it is throwing `frame not in module` error.
Comment: @GeraldVersluis InnerException Count is only 1 that I have already mentioned
Answer: Try this one :D
  public interface IGetData
  {
       Task<string> GetApiData();
  }

  public class GetData : IGetData
  {

    public async Task<string> GetApiData()
    {
      var client = new HttpClient();
      var response = await client.GetAsync(string.Format("http://mysite/api/Data"));
      var responseString = await response.Content.ReadAsStringAsync();
      return responseString;
    }

   }

Comment: I have already tried this code in my question. its showing 'frame not in module' error.


Calcular o produto cartesiano com programação funcional

Question: Estou escrevendo uma função em Python que recebe duas listas e retorna uma lista de tuplas com o produto cartesiano da função de entrada. Não posso usar nenhuma função pronta da biblioteca do Python.
Ex:
print(cartesiano([1,2],[11,22]))
# [(1, 11), (1,22), (2,11), (2, 22)]

Meu programa está imprimindo isso: [(1, 11), (2, 22)]. Não estou conseguindo arrumar a recursão.
def cartesiano(lista1,lista2):

def aux(l1,l2):
    if l1==[] and l2==[]:
       return []

    return [(l1[0],l2[0])] +aux(l1[1:],l2[1:])

return aux(lista1, lista2)

Eu não posso usar laços de repetição, como é bem mais intuitivo. É uma questão de programação funcional, sem laços, etc...
Answer: Numa abordagem que me lembra um pouco mais a funcional e a lógica, podemos pensar em cabeças de lista e corpo de lista. As antigas funções CAR e CDR do lisp me veem a cabeça.
A função básica do produto cartesiano é descrita mais ou menos assim usando CAR e CDR (sobre listas de números):
produto_cartesiano(list1, list2):
  se list1 é lista vazia ou list2 é lista vazia:
    retorne {}
  senão se list1 não é lista:
    retorne { (list1, CAR(list2)) U produto_cartesiano(list1, CDR(list2)) }
  senão:
    retorne { produto_cartesiano(CAR(list1), list2) U produto_cartesiano(CDR(list1), list2) }

Em Python? Sem usar laços? Ainda não consigo pensar numa maneira direta. Mas podemos ter uma abordagem um tanto quanto mais prolog. Eu sei que o paradigma lógico não é exatamente o desejado, mas dá uma disfarçada. Ajuda a evitar os laços. Aqui, a questão é passar como argumento a lista de retorno. No paradigma lógico você não construiria a lista, você inferiria a lista, é uma questão bem diferente. Aqui, realmente inseriremos os resultados na lista de retorno. Então, podemos fazer o produto cartesiano assim:
def produto_cartesiano(lista1, lista2, resultado = []):
  if lista1 == [] or lista2 == []:
    return resultado
  elif !isinstance(lista1, list):
    resultado.append((lista1, lista2[0]))
    return produto_cartesiano(lista1, lista2[1:], resultado)
  else:
    produto_cartesiano(lista1[0], lista2, resultado)
    return produto_cartesiano(lista1[1:], lista2, resultado)

Note que estou usando CAR e CDR de jeito mais idiomático no Python, com lista[0] e lista[1:].
Só relembrando aqui, essa resposta se aplica a listas de números. Não se aplica a conjuntos generalizados, incluindo conjuntos que podem ter outros conjuntos como seus elementos.

No sua resposta, você andou ao mesmo tempo nas duas listas na chamada recursiva, mais ou menos assim:
cartesiano(l1, l2):
  se l1  é lista vazia e l2 é lista vazia
    return {}
  return { (CAR(l1), CAR(l2)) U cartesiano(CDR(l1), CDR(l2)) }

Isso elimina muitos elementos do resultado. Seja L1 X L2 o produto cartesiano, você está eliminando os subconjuntos CDR(L1) X CAR(L2) e CAR(L1) X CDR(L2), e também alguns outros subconjuntos devidos à recursão. Sua condição de parada também está estranha, pois a definição de produto cartesiano diz que, se um dos conjuntos for o conjunto vazio, o resultado também será vazio. Isso significa que deveria ser um OR, não um AND.
A grosso modo, um produto cartesiano seria composto dos seguintes subconjuntos:
L1 X L2 =
    ({CAR(L1)} X {CAR(L2)}) U
    ({CAR(L1)} X CDR(L2)) U
    (CDR(L1) X {CAR(L2)}) U
    (CDR(L1) X CDR(L2))

Se notar bem, ({CAR(L1)} X {CAR(L2)}) U ({CAR(L1)} X CDR(L2)) = {CAR(L1)} X L2; e semelhantemente para (CDR(L1) X {CAR(L2)}) U (CDR(L1) X CDR(L2)) = CDR(L1) X L2
Portanto, temos que:
L1 X L2 =
    ({CAR(L1)} X {CAR(L2)}) U
    ({CAR(L1)} X CDR(L2)) U
    (CDR(L1) X {CAR(L2)}) U
    (CDR(L1) X CDR(L2)) =
    ({CAR(L1)} X L2) U
    (CDR(L1) X L2)

Notou a semelhança com a minha recursão?

Agora, e para conjuntos generalizados? Conjuntos generalizados contém conjuntos dentro de conjuntos.
Pegando a fórmula completa:
L1 X L2 =
    ({CAR(L1)} X {CAR(L2)}) U
    ({CAR(L1)} X CDR(L2)) U
    (CDR(L1) X {CAR(L2)}) U
    (CDR(L1) X CDR(L2))

O caso conhecido da recursão é com os conjuntos vazios. Mas, também posso afirmar que, como CAR(L) retorna um elemento pertencente a L, temos que {CAR(L1)} X {CAR(L2)} é igual ao conjunto unitário {[CAR(L1), CAR(L2)]} cujo elemento é a tupla formada pelos primeiros elementos de L1 e L2.
Sendo assim, a fórmula recursiva para ambos os conjuntos não vazios:
L1 X L2 =
    {[CAR(L1), CAR(L2)]} U
    ({CAR(L1)} X CDR(L2)) U
    (CDR(L1) X {CAR(L2)}) U
    (CDR(L1) X CDR(L2))

Portanto, a função recursiva seria:
def produto_cartesiano(l1, l2, resultado = []):
  if l1 == [] or l2 == []:
    return resultado
  else:
    car1 = l1[0]
    cdr1 = l1[1:]

    car2 = l2[0]
    cdr2 = l2[1:]

    resultado.append( (car1, car2) )
    produto_cartesiano([ car1 ], cdr2, resultado)
    produto_cartesiano(cdr1, [ car2 ], resultado)
    return produto_cartesiano(cdr1, cdr2, resultado)

Comment: Eu também  não posso usar variáveis. Mas já deu certo. :)


Help me with analysis question on sequences.

Question: Question: Let $(c_n)_{n = 1}^\infty$ be a sequence such that $c_n =\frac{1}{n^2}$ if $n$ is odd, and $c_n = \frac{1} {n^4}$ if $n$ is even. Prove
that $c_{n+1} > c_{n}$ for infinitely many values of $n$. Also, show that $\sum_{n=1}^\infty (-1)^{n-1} c_n $ converges.
Attempt: Now I want to do induction for the first part but that proof is throwing me off. With the base of $n = 1$, I get $\frac{1}{16} > 1$ which is not true. I don't know if I am thinking this right or if there is a typo. For the second part, if the first part is true, then we cannot use alternating series test. I was leaning towards the ration test, but I am leading to a problem. Do I have to test the casea when n is even and odd? Please give me hints on how to solve this! Thank you very much guys!!
Comment: You're asked to show $c_{n+1} > c_n$ for *infinitely many* $n$, not for *all* $n$.  Induction in its usual form isn't really suited for proving this kind of statement.  Have you tried making a table of values for $(c_n)$ to see if you can find some $n$ for which the statement is true?
Comment: Hint: $(2n+1)^2=4n^2+4n+1<(2n)^4=16n^4$ for all $n\geq1$.
Comment: For the second part, note that $\sum c_n$ converges, and that absolute convergence implies convergence.
Comment: @MatthewLeingang Yes I have. It works for n = 2, n = 4 and all the other even n values. But when n is odd the statement is not true. Do I have to prove this for the even terms then?
Comment: What do you think?  You're asked to show a statement is true for *infinitely many* $n$.  You have convinced yourself through numerical evidence that the statement is true for *all even* $n$.  Do the even numbers count as an infinite set?
Comment: @MatthewLeingang Yes, even numbers are a countably infinite set so I would prove this in the context of the even numbers.
Answer: If $n $ is even then
$$c_{n+1}=\frac{1}{(n+1)^2}$$
and
$$c_n=\frac {1}{n^4} $$ but
$$n^4-(n+1)^2=$$
$$(n^2+n+1)(n^2-n-1)= $$
$$(n^2+n+1)((n-1)^2+n-2)>0$$ for $n\ge2$.
for the series, we have
$$|(-1)^nc_n|\le \frac {1}{n^2} $$ and comparison test.


displaying textView instead of a toast message

Question: I have the following instruction displaying some information from the database in Toast message, but I want an instruction that display the information but in a TextView
Toast.makeText(getBaseContext(), marker.getTitle(), Toast.LENGTH_LONG).show();

Thank you very much.
This is the declaration of my TextView:
displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);

Comment: `displayTextViewTitle.setText("your msg");`
Answer: Try this :
        displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);
        displayTextViewTitle.setText(marker.getTitle().toString);

Hope this helps.
Answer: Try

displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);
  displayTextViewTitle.setText(""+marker.getTitle());
Answer: write like below:
displayTextViewTitle.setText(marker.getTitle());

Answer: use displayTextViewTitle.setText(marker.getTitle())
Answer: Try this way,
displayTextViewTitle.setText(""+marker.getTitle());
Answer: "(..) but I want an instruction that display the information but in a TextView".
Why not read TextView documentation if you want to work with TextView? You just might find a method that can do what you require. The docs is your friend, learn to like it :)


Tool to capture outbound http packets in a linux server

Question: I was searching for a tool to capture http packets sent from a linux server to an external server. Normally I use iftop or  iptraf with filters to see real time information and tcpdump to get verbose information. But what I need right now is some way to capture all the url requests to some log file.
I know that I can configure a proxy to log all this information but this is impossible because our actual architecture. Do you know some tool that can get this information? Or do I need to make a script to process the information from tcpdump?
Answer: What you need is urlsnarf from the dsniff project. It will generate a log with all http request seen on one network interface. A very good tool !
Comment: Yes, that's what I was looking for. Is a little application, it can be used to log to a file in a standard format, and for real time analysis. Also it can work with tcpdump. Thanks.
Answer: Sounds like a job for Wireshark (formerly known as Ethereal).
Look at the HTTP protocol support and the display filters for it.  You probably want a display filter of "http.request.uri".
Comment: Wireshark will definitely do what you are asking.  Its easy to use and you can set it up so that you only capture http packets.
Answer: I'd normally suggest WebScarab, but it acts as an HTTP proxy which you said doesn't work in your situation...
You'll need something that can listen promiscuously and then analyze things at the application protocol level.  Here's a thread with a Perl script that looks to do what you want by analyzing tcpdump output.


Altering the admin/content form

Question: After having added a "changed by" on nodes I now need to display the user who modified each node on the node_admin_content form (at admin/content) right next to the "Author" column.
I've managed to easily solve this by altering node.admin.inc and adding just 2 lines of code:
...
'changed_by' => t('Changed By'),
...

...
'changed_by' => theme('username', array('account' => user_load($node->changed_by))),
...

This, of course, is not a proper solution since it alters the core.
So I then tried altering the form via:
function hook_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  $form['admin']['nodes']['#header']['changed_by'] = t('Changed By');
  // ... ?
}

Using dpm I can see that the form has the nodes in options. The problem is that this is the result of rendering the nodes as table options. I don't have access to the original nodes, nor do I want to re-execute the node fetch query in order to get the "changed by" information. I guess doing this in the form hook would not be solving it in the correct layer. Or is it?
So, what is a good way to alter the node_admin_content form to add more data that exists on nodes?
Answer: The bad news is that having inspected the code, the form alter layer is the only place to really do this; your approach is pretty much spot on.
The good news is, Drupal implements all sorts of static caching throughout the page load, which minimises the need to go back into the database. So while altering the content table may appear cumbersome, you're not actually taking a noticeable performance hit.
The following code (or similar) should work; see the comments for more info about the caching issue:
function MYMODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  // Load the nodes. This incurrs very little overhead as
  // "$nodes = node_load_multiple($nids);" has already been run on these
  // nids in node_admin_nodes(). The static cache will be used instead of
  // another db query being invoked
  $nodes = node_load_multiple(array_keys($form['admin']['nodes']['#options']));

  // Grab a list of all user ids that have been responsible for changing the node
  $uids = array();
  foreach ($nodes as $node) {
    $uids[] = $node->changed_by;
  }

  // Filter out duplicates (one user may have been the last to change more than one node)
  $uids = array_unique($uids);

  // Load a list of all involved users in one go. This is about as performant
  // as this is going to get, as you're going to need the user objects one
  // way or the other for the call to theme_username
  $users = user_load_multiple($uids);

  // Add another column to the table header
  $form['admin']['nodes']['#header']['changed_by'] = array('data' => t('Changed by'));

  // Loop through the rows in the table and add the changed by column
  foreach ($form['admin']['nodes']['#options'] as $nid => $row) {
    // Grab the user related to this node.
    $this_user = $users[$nodes[$nid]->changed_by];

    // Add data for the new column
    $form['admin']['nodes']['#options'][$nid]['changed_by'] = theme('username', array('account' => $this_user));
  }
}

The above code produces a nice shiny new column like this on the content admin page:
Comment: Superb! Thanks a lot for providing quality documentation with your answer.
Comment: @cherouvim No worries :)
Comment: Thanks its working for me as well but I want to alter existing columns like I want to display Author user name or real name instead of Author email in author column.
Answer: Just replace admin/content with a View, and then add whichever fields you want.
Admin Views will even do it for you.
Comment: That was my first thought too, but would Views automatically know about the new column that was added to the node table? Does it get info about entity properties from `hook_schema()`/ `hook_schema_alter()` implementations?
Comment: I assumed you just added a CCK field. I see now that you went with hook_schema_alter(), which is very yuck. Still, you can implement hook_views_data_alter() to expose the new column.
Comment: Yeah it didn't feel 'right' to do that but I can't put my finger on why. Can you think of a scenario where adding the column in that way would actually cause a problem?
Comment: It doesn't cause any problems, just gives you a bit of extra work (like needing hook_views_data_alter() for Views, same for properties if you're on D7) while being "ideologically" wrong, it's a very Drupal 5 way of thinking. Oh well, no big deal.
Comment: Thanks that's good to know. Personally I'd always use fields for this kind of thing but it was interesting to find out that it could be done without big side-effects. Your answer speaks volumes about that though; if you do it the proper/recommended way (i.e. with fields) you save yourself a lot of work later on
Comment: Yes Clive answer was excellent, but this solution sounds more scalable (and a bit cleaner)
Answer: A little off subject, but this answer shows how you can do this programmatically (for example by adding it as a module update in the MY_MODULE.install file.)
You'll need a little more work if you want to add your new field before last existing field. Merge it in before the end of the $view->display['default']->display_options['fields'] array.
    function MY_MODULE_update_7101(){
        // update the admin/content view, need to do it manually because it's
        // set by admin_views module
        $view_name = 'admin_views_node';
        $view = views_get_view($view_name, TRUE);

        //  add the relationship
        $view->display['default']->display_options['relationships']['uid_1']['id'] = 'uid_1';
        $view->display['default']->display_options['relationships']['uid_1']['table'] = 'node_revision';
        $view->display['default']->display_options['relationships']['uid_1']['field'] = 'uid';
        $view->display['default']->display_options['relationships']['uid_1']['label'] = 'Revision User';
        // new column settings
        $new_column = array(
            'name_1' => array(
                'id' => 'name_1',
                'table' => 'users',
                'field' => 'name',
                'relationship' => 'uid_1',
                'label' => 'Updated By',
            )
        );
        // need to use this because array_splice by itself resets 'name_1' key to '0'
        // see http://php.net/manual/en/function.array-splice.php#56794
        $temp_array = array_splice( $view->display['default']->display_options['fields'] , 0, 7);
        $view->display['default']->display_options['fields'] = array_merge($temp_array , $new_column, $view->display['default']->display_options['fields']);

        views_save_view($view);
    }

Altering the admin/content form


Creating a Simple 1D CNN in PyTorch with Multiple Channels

Question: The dimensionality of the PyTorch inputs are not what the model expects, and I am not sure why.
To my understanding...
in_channels is first the number of 1D inputs we would like to pass to the model, and is the previous out_channel for all subsequent layers.
out_channels is the desired number of kernels (filters).
kernel_size is the number of parameters per filter.
Therefore, we would expect, as data passed to forward, a dataset with 7 1D channels (i.e. a 2D input).
However, the following code throws an error that is not consistent with what I expect, where this code:
import numpy
import torch

X = numpy.random.uniform(-10, 10, 70).reshape(-1, 7)
# Y = np.random.randint(0, 9, 10).reshape(-1, 1)

class Simple1DCNN(torch.nn.Module):
    def __init__(self):
        super(Simple1DCNN, self).__init__()
        self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2)
        self.act1 = torch.nn.ReLU()
        self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
    def forward(self, x):
        x = self.layer1(x)
        x = self.act1(x)
        x = self.layer2(x)

        log_probs = torch.nn.functional.log_softmax(x, dim=1)

        return log_probs

model = Simple1DCNN()
print(model(torch.tensor(X)).size)

Throws the following error:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-5-eca5856a2314> in <module>()
     21
     22 model = Simple1DCNN()
---> 23 print(model(torch.tensor(X)).size)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

<ipython-input-5-eca5856a2314> in forward(self, x)
     12         self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
     13     def forward(self, x):
---> 14         x = self.layer1(x)
     15         x = self.act1(x)
     16         x = self.layer2(x)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input)
    185     def forward(self, input):
    186         return F.conv1d(input, self.weight, self.bias, self.stride,
--> 187                         self.padding, self.dilation, self.groups)
    188
    189

RuntimeError: Expected 3-dimensional input for 3-dimensional weight [20, 7, 5], but got 2-dimensional input of size [10, 7] instead

Edit: See below for solution, motivated by Shai.
import numpy
import torch

X = numpy.random.uniform(-10, 10, 70).reshape(1, 7, -1)
# Y = np.random.randint(0, 9, 10).reshape(1, 1, -1)

class Simple1DCNN(torch.nn.Module):
    def __init__(self):
        super(Simple1DCNN, self).__init__()
        self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2)
        self.act1 = torch.nn.ReLU()
        self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
    def forward(self, x):
        x = self.layer1(x)
        x = self.act1(x)
        x = self.layer2(x)

        log_probs = torch.nn.functional.log_softmax(x, dim=1)

        return log_probs

model = Simple1DCNN().double()
print(model(torch.tensor(X)).shape)

Comment: You should batchnorm
Answer: You are forgetting the "minibatch dimension", each "1D" sample has indeed two dimensions: the number of channels (7 in your example) and length (10 in your case). However, pytorch expects as input not a single sample, but rather a minibatch of B samples stacked together along the "minibatch dimension".
So a "1D" CNN in pytorch expects a 3D tensor as input: BxCxT. If you only have one signal, you can add a singleton dimension:
 out = model(torch.tensor(X)[None, ...])


Force redirect in submit handler even though destination parameter set

Question: I add a custom submit handler and now I want Redirect to custom route after form submitted.
This is what I used
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;
use \Drupal\Core\Url;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {

        foreach (array_keys($form['actions']) as $action) {
            if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
                $form['actions'][$action]['#submit'][] = 'zyetondev_sync_trends_submit';
            }
        }
    }
}

function zyetondev_sync_trends_submit(array $form, FormStateInterface $form_state) {
    $url = Url::fromRoute('view.trends.page_1');
//    die(Url::fromRoute('view.trends.page_1')->toString());
    drupal_set_message("Done");
    $form_state->setRedirect($url);
}

Submit Handler getting run and redirect redirection work correctly, Problem is when we have ?destination= on Url, How can I force redirect even though ?destination= is on Url?
Comment: If I've understood your requirement correctly, you want to include query parameters as well during redirection? Correct me if wrong.
Comment: @Yogesh let's suppose you are on /admin/content , when try to edit a node `?destination=/admin/content` added to url, I want to redirect my custom path even though `?destination=` exists in url.
Answer: The only correct way to do this is to alter the Request object and drop the destination.
In your submit callback:
\Drupal::request()->query->remove('destination');

Depending on the context, you might want to store it somewhere, for example pass it along to the URL you are redirecting to, so that it is respected again later.
See https://www.drupal.org/node/2325463 for a core issue that is doing exactly this to fix the preview button if a destination is given.
Answer: This code will help you.
 $url = \Drupal\Core\Url::fromRoute(
        'node.add',
         array('node_type' => $type->id()),
         array(
           'query' => array('destination' => $destination),
           'absolute' => TRUE,
         )
    );
   $form_state->setRedirect($url);

Comment: The code you are showing would not even redirect users. It is just creating a URL object, which doesn't do any redirect, by itself.


Term for reverse engineering a song

Question: Like most musicians, sometimes I sit down and listen to a song, and attempt to "reverse engineer" what the notes and chords and so on might be.
Is there a widely understood term for that?
Comment: Do you mean sort of "picking out the melody"?
Answer: Transcription: Is the process of listening to a piece of music and "reverse engineering" it. It can also mean just the process of writing down a piece of music.
You'll find a number of questions on this site related to transcription. As a starting point, just search for the word "transcribe" or for the transcription tag.
EDIT: Transcription is different from copying, as pointed out by Dekkadeci in the comments. "Copying" is the act of literally transferring one sheet of notated music to another. "Transcribing" requires writing down a sound that was not previously written: from a recording, from nature, by re-writing notated music for one or more instruments other than in the given notation.
Comment: @MathematicalOrchid - As far as I've learned, copying music straight from one sheet of paper to another is called **copying**, and someone who does this is called a **copyist**. Transcribers at least either have to figure out music from audio or change the instrumentation.
Comment: @Tom Funny you mention that. I first encountered the term studying jazz, and it was just used to mean learning from a recording. Writing it down wasn't mentioned. I used to get quite confused when I read of early Classical musicians "transcribing" music.
Comment: Interesting. I would have thought "transcription" just means copying something from one sheet of paper to another...
Comment: @MathematicalOrchid Historically (and literally), it does. But, at least in jazz circles, it has come to mean "learning from the [sound-] recording".
Answer: Transcribing would be the act of sitting down and writing the notes and rhythms you hear,  This is a pretty standard practice and how we learn songs.  This can get difficult to do with a completed piece of recorded music as parts bleed together and effects can obfuscate notes.  It is a little different if you want to "reverse engineer" the engineering and production of the finished piece.  At the end of the day the starting point is your ear, a well trained ear could determine if there is chorus, delay, etc added to the instruments.
In addition to your ear there are software packages that apply signal processing techniques to try and separate the individual notes in a small time window of the entire piece of music.  This can be a helpful aid if you cannot figure something out but it's still transcribing.
Comment: Do you have any names for these packages, or at least a search term? They  sound interesting.
Comment: One is transcribe.   I tried it many years ago and it was only 30$ at the time.  It lays an fft spectrum over a keyboard and you have to pick what you think is reasonable.  At the time there was no side lobe suppression so you need to understand what you are looking at.   I think there are commercial packages that cost $1000's but attempt to convert recordings to scores.   I could be wrong and have never tried anything that expensive

Term for reverse engineering a song