Prove that $Q$ is rational if and only if $t$ is rational

Question: In the accompanying diagram from "The Language of Mathematics: Making the Invisible Visible" by Keith Devlin (Figure 6.21), he states that "It is then an easy exercise in algebra and geometry to verify that the point $Q$ will have rational coordinates if, and only if, the number $t$ is rational."  Note that the circle is the unit circle, and so the coordinates of $P$ are $(-1,0)$.

He gives certain examples, such as if $t = 1/2$, "a little computation shows that the point $Q$ has coordinates $(3/5, 4/5)$. Similarly, $t = 2/3$, leads to the point $(5/13, 12/13)$."
I understand these coordinates yield Pythagorean Triplets, but how are they obtained algebraically (and/or geometrically)? and how is the general case he gives above—regarding $Q$ being rational if and only if $t$ is rational—proven?
Comment: Are $(-1,0)$ the coordinates of $P$? In other words, are $1$ the radius of the circle?
Comment: Yes, sorry I forgot to indicate that; it is indeed a Unit Circle
Answer: The equation of the line is
$$y=t(x+1)$$
and the circle's,
$$x^2+y^2=1$$
The first equation implies that $x,y\in\Bbb Q\implies t\in\Bbb Q$.
Merging both of them we obtain
$$x^2+t^2(x+1)^2=1$$
 But if $t$ is rational, this is a quadratic equation on $x$ with rational coefficients and one rational root (namely, $-1$). So the other solution is rational, too.
 This implies that $t\in\Bbb Q\implies x,y\in\Bbb Q$
Answer: It follows from your post, but you didn't define it, that that is the unit canonical circle $\;x^2+y^2=1\;$ and thus $\;P(-1,0)\;$. Call $\;(0,t)\;$ the point where that cord intersects the $\;y\,-$ axis, that so by basic trigonometric we have that the slope of $\;PQ\;$ is  just $\;t\;$ , and if we call $\;Q(a,b)\;$ the coordinates of $\;Q\;$ , then
$$t=m_{QP}=\frac b{a+1}\implies b=t(a+1)$$
and since $\;Q\;$ on the unit circle, we get:
$$1=a^2+b^2=a^2+a^2t^2+2at^2+t^2\implies(1+t^2)a^2+2t^2a+t^2-1=0$$
The discriminant of the above quadratic in $\;a\;$ is
$$\Delta=4t^4-4(t^2+1)(t^2-1)=4\implies a_{1,2}=\frac{-2t^2\pm2}{2(t^2+1)}=\begin{cases}-1\\{}\\-\cfrac{t^2-1}{t^2+1}\end{cases}$$
Now just prove that the above means $\;a\;$ (and thus also $\;b\;$) are rational iff $\;t\;$ is...
Answer: A high-level handwavy explanation of why this must be so:
The $x$-coordinates of the two intersection points between the line and the circle are solutions to a quadratic equation whose coefficients can be computed from the known points $(-1,0)$ and $(0,t)$ by purely rational operations.
Thus, the quadratic equation has rational coefficients. Such a quadratic equation has either both roots rational or both roots irrational. (This is clear from the quadratic formula).
Since $P$ has a rational $x$-coordinate, $Q$ therefore also has.
Similarly for the $y$ coordinates.
Answer: The line $PQ$ is given by
$$
y=tx+t
$$
Inserting this into the circle equation
$$
x^2+y^2=1
$$
we get
$$
x^2+(tx+t)^2=1\\
(t^2+1)x^2+2t2x+t^2-1=0\\
x^2+\frac{2t^2}{t^2+1}x+\frac{t^2-1}{t^2+1}=0
$$
This is the equation that gives the $x$-coordinates of $P$ and $Q$. However, we already know the $x$-coordinate of $P$. So Vieta's formulas (or polynomial division, or actually solving the quadratic) tells us that the $x$-coordinate of $Q$ is $\frac{1-t^2}{1+t^2}$. Using the equation for the line, that gives a $y$ coordinate of
$$
t\cdot\frac{1-t^2}{1+t^2}+t=\frac{t-t^3+t+t^3}{1+t^2}\\
=\frac{2t}{1+t^2}
$$
So, clearly, if $t$ is rational, the $x$ and $y$ coordinates of $Q$ are both rational.
On the other hand, if the $x$ and $y$ coordinates of $Q$ are both rational, then the slope of the line (using the coordinates of $P$ and $Q$ to calculate it) is rational. And this slope is $t$.
Answer: The function $f(x)=\dfrac{1-x}{1+x},\; x\neq -1$ is its own inverse.
The slope of the line $PQ$ is $t$ and also $\dfrac y{1+x}=\sqrt{\dfrac{1-x}{1+x}}$.
Then, it is clear that if $x,y$ are rational, then $t$ either is.
Also, $t^2 =f(x)$, and hence $f(t^2)=x$. Then, if $t$ is rational, $x$ and $y$ either are.


Why does there exist an imaginary axis on the Argand diagram?

Question: Complex numbers can puzzle me a bit, and I think I have some gaps in my understanding that makes it confusing for me to wrap my head around.
The way I try to explain complex numbers to myself is this:

If we do not include complex numbers, we can find numbers that cannot exist on the Cartesian plane, such as with complex solutions to certain quadratics. We're missing numbers on our Cartesian plane, and we're trying to represent all numbers on this plane.
If we instead express all numbers as $a + bi$ instead of $a$ we can now identify all numbers and be able to express them on the Cartesian plane.

If my interpretation is wrong in some way please do explain why.
Regardless, my main question is why, this follows, that we now have the Argand diagram derivative of the reals-only Cartesian plane, with the imaginary axis on the $y$ axis and reals on the $x$ axis? Does this have to do with a logical progression of when I said "If we instead express all numbers as $a + bi$ instead of $a$ we can now identify all numbers and be able to express them on the Cartesian plane."? Let me elaborate:

Since numbers are now expressed as in the form $a + bi$, if the imaginary axis is on the $y$ axis and the real number line is on the $x$ axis, all numbers can be accounted for elegantly.
This is due to the fact that now, any number can be expressed by its projection in the imaginary and real axis.

But due to someone establishing this rule, we now have the following properties:

We now use vectors to typify numbers. $3 + 2i$ is now a projection in this plane, and we now use things like vector addition. And then that can snowball into Euler's identity?!
Multiplying by $i$ now causes projections to "rotate" in the plane.

This just seems bizarre to me, and it's because we've elected to define our $y$ axis as a number multiplied by the square root of $-1$, which sounds totally arbitrary.
Why couldn't I make my own diagram and instead of multiplying numbers in the y-axis by $i$, I multiply it by $k$ which I define as equal to $13$? And all these new properties I listed, like the extended Cartesian plane now being sort of like a vector space and have rotational properties seem crazy to me.
-
$$ \bbox[2px,border:2px solid red]
{
So,\ to\ recap,\ my\ main\ question\ is:\ why\ has\ all\ this\ been\ implemented*,\ keeping\ in\ mind\ the\ new\ odd\ properties\ our\ extended\ Cartesian\ plane\ now\ has?\
}
$$
What's the deal about all of this? How and why did we go from our number line of reals and end up with all this?
I hope I've made my question stated clearly enough. Please let me know if something needs to be made more clear.
*And by "all this been implemented", I mean creating a $y$ axis, the imaginary axis, for the real number line and allowing all these odd properties to form, hence the title.
Comment: You may (or may not) find my musings [here](https://math.stackexchange.com/questions/2225091/motivation-for-complex-numbers/2225168#2225168) enlightening.
Comment: Not a duplicate, but possibly of interest: [Why is the complex plane shaped like it is?](https://math.stackexchange.com/questions/1842968)
Comment: @HenningMakholm That's a great post! Just having some trouble reading some bits.
Comment: Try reading the wiki pages on [Imaginary unit](https://en.wikipedia.org/wiki/Imaginary_unit) and [complex numbers](https://en.wikipedia.org/wiki/Complex_number), and maybe you end up with a clearer picture. Basically, we define $i$ by $i^2=-1$ while requiring that the usual properties of addition and multiplication remain intact. Then, for numbers $z$ of the form $z=ai+b$, everything you've mentioned follows - including complex plane rotations and Euler's identity.
Answer: In principle we could do what you suggest -- take $\mathbb R^2$ and associate every point $(x,y)$ to the number $x+13k$. Though the trouble with that particular plan is that each number now represents many different points -- for example, $(13,0)$ and $(0,1)$ and $(26,-1)$ are now all associated to the number $13$. This means that we can't use the scheme for anything where we calculate a number and that number points to exactly one point in the plane.
We could, however, do something more general. Take some field that extends $\mathbb R$, pick some element $\alpha$ in that field, and then represent $(x,y)\in\mathbb R^2$ by $x+\alpha y$.
As it went for $13$, if we pick $\alpha\in\mathbb R$, then we get something where a number doesn't represent a unique point. Suppose, however, that we steer clear of that case, and furthermore that we end up in the lucky situation that every element of the field represents some $(x,y)$ in the plane.
Something wonderful happens then -- namely, we can then prove (though not in the space left for me in this margin) that the field we're using must be isomorphic to $\mathbb C$ -- in other words the field is essentially the complex numbers, just called something different. In particular, somewhere in the plane there is an $(x,y)$ whose corresponding number behaves exactly like $i$.
So we could actually have said: Pick some complex number $\alpha$, and let $(x,y)$ correspond to $x+\alpha y$.  As long as $\alpha$ is not real, this will give us a perfectly good one-to-one correspondence between points and complex numbers.
Now, among all the possible choices of $\alpha$ it turns on that exactly when $\alpha=i$ or $\alpha=-i$ we get the additional nice property that multiplication by any fixed nonzero complex number will correspond to a transformation of the plane that takes geometric figures to similar geometric figures.
Having multiplication correspond to similarity transforms is a pretty nifty property, which is a reason to prefer the representation $x+iy$ over other possible $x+\alpha y$.
Comment: I see! Few questions with this. (1) Why is it desirable to have a new field at all? Even if every element of the field represents some unique (x, y) in the plane, why is that even desirable for us? (2) Following from that, with this new field of $\mathbb R^2$, is the fact that multiplication correspond to similarity transforms a new discovery of multiplication, or insight to it, *due* to this analysis? Is this a fundamental property of multiplication that complex analysis illuminated, or something as a *result* of using complex numbers? Because if the latter is true, it sounds odd.
Comment: Plus, what does rotations in our plane even imply about multiplication and our plane to begin with? I feel like it's shedding some key insight to arithmetic that I haven't grasped.
Answer: I think your difficulty starts here:

If we do not include complex numbers, we can find numbers that cannot exist on the Cartesian plane, such as with complex solutions to certain quadratics. We're missing numbers on our Cartesian plane, and we're trying to represent all numbers on this plane.

To begin with, "the" Cartesian plane that we all know and love contains points that are identified with pairs of numbers,
specifically pairs of real numbers.
There is such a thing as a quadratic equation of two variables,
for example, $x^2 + 4xy - y^2  + 1 = 0,$
which we can plot in a Cartesian plane, but I bet that's not what you meant.
The usual introduction to complex numbers starts with equations such
as $x^2 + 1 = 0,$ for which each solution consists of just one number,
not a pair of numbers.
In fact, the reason for inventing complex numbers in the first place had nothing to do with the Cartesian plane; it took hundreds of years for those two mathematical ideas to be connected at all.
Cardano was already using $\sqrt{-1}$ as his "one weird trick" to solve cubic equations in 1545.
Descartes published his idea about coordinates of a plane in 1637--already almost a century later!--and Argand first published his diagrams in 1806.
Look at those dates. For over $250$ years after complex numbers first occurred in mathematics, nobody knew how to use a coordinate plane to represent them.
Moreover, complex numbers were not invented to solve quadratics.
Nobody cared that there were no solutions for $x$ in $x^2 + 1 = 0.$
At first, mathematicians came to grudgingly accept an occasional complex number in mathematics because they were able to make use of them while working on the problem of finding real solutions to cubic and quartic equations.
The full acceptance of complex numbers came much later.
In any case, Argand diagrams did not arise because Argand (or anyone else) was sitting around trying to think of odd properties that could be added to a Cartesian plane and dreamed this up.
They arose because the geometric interpretations of complex operations on an Argand diagram happen to exactly match what complex numbers were already known to do; those properties had all been proved by algebra with no geometric reasoning whatsoever.


Formatar data no PHP

Question: Preciso mostrar data no PHP no formato seguinte: "Domingo, 09 de Dezembro de 2014" ?

Tem que ser no horário de brasilia!
Se possível em português também!

EDIT:
<?php
setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' );
date_default_timezone_set( 'America/Sao_Paulo' );
echo strftime( '%A, %d de %B de %Y', strtotime('today'));
?>

detalhe é que o resultado é "terça-feira" e não "terça", queria saber como tirar o feira, é possível ?
Comment: http://pt.stackoverflow.com/questions/8317/como-fazer-a-fun%C3%A7%C3%A3o-date-formatar-uma-data-em-portugu%C3%AAs
Comment: cara valew, quase fiz tudo com IF, ia ficar um código imenso...valew!!!
Answer: aqui deu certo.
<?php

setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese");
date_default_timezone_set("America/Sao_Paulo");
print strftime("%A, %d de %B de %Y");

?>

output
terça, 12 de agosto de 2014

Comment: valew!!! era isso que eu precisava!!
Comment: detalhe é que o resultado é "terça-feira" e não "terça", queria saber como tirar o feira, é possível ?
Comment: engraçado, aqui aparece como terça....vish
Comment: aqui aparece terça-feira!!! estou usando o xampp como servidor!
Comment: ah, nesse caso, vai na gambi -
$str = strftime("%A, %d de %B de %Y");
$str = str_replace("-feira","",$str);
Comment: deu certo! valew!!
Comment: não buga sabado e domingo? ou uso IF ?
Comment: é provável q não, mais vai ter q esperar kkk
Comment: ^^ ah, valew!!!

Formatar data no PHP


How to create schema for neo4j graph database in nodejs?

Question: I was thinking, How we can prevent user/developer from adding unwanted nodes/relationships/properties?
What I read was - we should impose those schema's at application level. So, how can we do that in Node.js?
Is there any example on this? Or can someone post some code here?
Answer: It depends how your applications works.

You can create your own validation in your application, but it depends on the type of your application.
Better option is to create your own unmanaged extension for Neo4j. You can use Transaction Event API for that - http://graphaware.com/neo4j/transactions/2014/07/11/neo4j-transaction-event-api.html
GraphAware provides paid extensions for schema enforcemen - http://graphaware.com/enterprise/
Answer: Neo4j supports some limited schema enforcement. Specifically:

Uniqueness constraints. Specify a node property that acts as a unique id for Nodes with a given label. Transactions that attempt to violate the constraint will be rolled back. Uniqueness constraints are created in Cypher using this syntax:
CREATE CONSTRAINT ON (p:Person) ASSERT p.name IS UNIQUE
Property existence constraints. This constraint ensures that all Nodes of a given label contain the specified property. Any create statement that does not specify the given property will be rolled back. Property existence constraints can by created with this syntax:
CREATE CONSTRAINT ON (book:Book) ASSERT exists(book.isbn)

Note that property existence constraints are new in Neo4j 2.3 and are only available in Neo4j Enterprise.


Locus problem solve it using simple mathematics

Question: A line cuts $X$-axis at $A(7,0)$ and the $Y$- axis at $B(-5,0)$. A variable line $PQ$ is drawn perpendicular to $AB$ cutting $X$-axis at $P$ and $Y$-axis at $Q$. If $AQ$ and $BP$ intersect at $R$, Find locus of $R$.
Answer: $PQ$ is perpendicular to $AB$, $AP$ is perpendicular to $BQ$, hence $BP$ is perpendicular to $AQ$ (fairly trivial to demonstrate), and the angle $\angle BRA$ is a right angle.
The locus of $R$ is the figure that sees two points at a right angle... It is the circle of diameter $AB$.
Comment: How to prove that BP is perpendicular to AQ
Comment: There are several ways. One long way is to draw the triangle and see the inscribed angles etc... and show that the angle BRA is a right angle. A more direct way is to show that the $BP \times AQ=0$, using the fact that $PQ \times AB=0$ and $AP \times BQ=0$


Does using Views Aggregation break title field as node link?

Question: I have a working View that uses aggregate to count members of Organic Groups that I modeled off of the View described here.
The title of the Groups is also included in the View; however, even though "Link this field to the original piece of content" is selected the View does not configure the Groups title as a link.
Does anyone know if this is because Aggregate is interfering with the link? Should the Aggregate settings on the title field be something specific? Or does it have something to do with the way the Organic Groups Views relationships are defined?
Comment: This is fixed in the current dev version of views.
Comment: Does the title display as plain text instead of a link? No special aggregation settings necessary, just "group results together".
Comment: that's strange. The "Link this field to the original piece of content" option should take care of the linking. Are you using the latest versions of views and OG?
Comment: Can confirm that this is fixed in dev version.
Comment: @mototribe: Correct, plain text instead of link. I do have titles set to "group results together" in the aggregation settings for the title field.
Comment: @mototribe:  Views is 7.x-3.0, Organic groups 7.x-1.3.  Latest of both unless I am mistaken.
Comment: @DanielWehner sounds like an answer to me.  Submit it as such and I'll flag this as answered.
Answer: I can confirm this was fixed in a recent dev release of the Views module.


R: charting a summed running total

Question: I have data in this format:
Count, Thread1, Thread2, Thread3, Thread4,
10420162, 589768
46530936, 1164357
55563161, 275521, 12289
56741671, 25158, 28020
57792881, 44468, 91248

(As the additional threads come in to play, data appears in their columns)
I would like to plot the sum (running total) of the Thread data against the Count eg when x is 0, y is 0; when x is 10420162, y is 589768; when x is 46530936, y is 1754125; when x is 55563161, y is 2041935 and so on.
Not clear how I can do this - presumably it requires at least two steps - to sum the data and then plot it?
Comment: Would you like the threads to be summed too, or are you plotting each threat separately?
Answer: Your calculated numbers don't match mine so I have a feeling I didn't understand your questions correctly. Or did you calculate it wrong?
df <- read.csv(tex`t`Connection('Count, Thread1, Thread2, Thread3, Thread4,
10420162, 589768
46530936, 1164357
55563161, 275521, 12289
56741671, 25158, 28020
57792881, 44468, 91248'), header=TRUE)

dfcumsum <- data.frame(
count = df$Count ,
cumthreadsum = cumsum(rowSums(df[,-1], na.rm = TRUE))
)

Output -
> dfcumsum
     count cumthreadsum
1 10420162       589768
2 46530936      1754125
3 55563161      2041935
4 56741671      2095113
5 57792881      2230829

The most elementary plot would be plot(dfcumsum$cumthreadsum)
Comment: Apologies, there was an (smallish) error in my calculation of the final figure - not sure how I did that - now fixed.
I know how to read the csv data into a frame and it looks like you have identified the issue for me. I'll test it.

R: charting a summed running total


Dell PERC 5 - RAID-10 keeps rebuilding drive 2 every day

Question: I have a Dell PowerEdge 2950 with this card: RAID bus controller [0104]: Dell PowerEdge Expandable RAID controller 5 [1028:0015] and six disks in a RAID-10.
I replaced drive 2, because it didn't show up, and then it started to rebuild itself:
root@backup01:~# megaraidsas-status
-- Arrays informations --
-- ID | Type | Size | Status
a0d0 | RAID 10 | 5587GiB | DEGRADED

-- Disks informations
-- ID | Model | Status | Warnings
a0e8s0 | ATA ST2000DM001-9YN1 1863GiB | online | errs: media:0 other:5393
a0e8s1 | ATA ST2000DM001-9YN1 1863GiB | online | errs: media:0 other:5394
a0e8s2 | ATA ST2000DM001-1E61 1863GiB | rebuild | errs: media:0 other:99
a0e8s3 | ATA ST2000DM001-9YN1 1863GiB | online | errs: media:0 other:5393
a0e8s4 | ATA ST2000DM001-9YN1 1863GiB | online | errs: media:0 other:5393
a0e8s5 | ATA ST2000DM001-9YN1 1863GiB | online | errs: media:0 other:5393

The rebuild finishes, then the virtual drive becomes optimal, and drive 2 goes online.  Then once a day, drive 2 acts like it's been removed, and the rebuild starts all over again.  How do I make this once a day rebuild stop?
Event Description: Removed: PD 02(e1/s2)
Event Description: Removed: PD 02(e1/s2) Info: enclPd=08, scsiType=0, portMap=04, sasAddr=1221000002000000,0000000000000000
Event Description: State change on VD 00/0 from OPTIMAL(3) to DEGRADED(2)
Event Description: VD 00/0 is now DEGRADED1
Event Description: State change on PD 02(e1/s2) from ONLINE(18) to FAILED(11)
Event Description: State change on PD 02(e1/s2) from FAILED(11) to UNCONFIGURED_BAD(1)
Event Description: Background Initialization failed on VD 00/0
Event Description: Inserted: PD 02(e1/s2)
Event Description: Inserted: PD 02(e1/s2) Info: enclPd=08, scsiType=0, portMap=04, sasAddr=1221000002000000,0000000000000000
Event Description: PD 02(e1/s2) is not a certified drive
Event Description: State change on PD 02(e1/s2)
Event Description: State change on PD 02(e1/s2) from UNCONFIGURED_GOOD(0) to OFFLINE(10) from UNCONFIGURED_BAD(1) to UNCONFIGURED_GOOD(0)
Event Description: Rebuild automatically started on PD 02(e1/s2)
Event Description: State change on PD 02(e1/s2) from OFFLINE(10) to REBUILD(14)

Answer: To give you a preliminary.. It sounds to me like this is a double data fault/puncture, which means that you have bad blocks which are propogated within the RAID. This can cause some really really strange issues in my experience. You can read up on it here : http://www.dell.com/support/Article/us/en/04/438291/en
Any chance we can get an output of your RAID controller log? Do you have the dell open manage server administrator packages installed? If not that's the best place to start. It looks like you're running some flavor of linux, you can download the OMSA packages : http://linux.dell.com/repo/hardware/omsa.html.
Once you have open manage you can export a RAID controller log using this command : omconfig storage controller action=exportlog controller=id, where the controller is the ID of your controller (should be 0 unless you have more than one RAID controller). Once we have that output we'll be able to confirm what's going on. (hopefully).
Only one last thing, your expandable RAID 5, do you know if that's a PERC5i, a SAS5, or another model?
Hope to be of assistance!


Como evitar repetir código?

Question: Eu tenho um script em Python 3 que tenta ser um chatbot, aonde tem vários if e elses que são usados baseados no que o usuário responde.
O problema é que em todas as funções, tipo get_name() ou get_age(), esses if e else se repetem.
def get_name():
while True:
    global name
    name = question_renderer("What's your name?")
    name = name.lower().capitalize()
    if name == '':
        continue
    elif name.isdigit():
        typing(1)
        print("Please don't type numbers.")
    else:
        list = ["I like your name.", "I always wanted to have that name.", "My friend has the same name."]
        typing(1)
        print(choice(list))
        break

def get_age():
while True:
    try:
        age = int(question_renderer("How old are you, {}?".format(name)))
    except ValueError:
        typing(1)
        print("Please, just type numbers.")
    else:
        if int(age) <= 25:
            typing(2)
            list = ["You're still young.", "Being young is very good.", "Enjoy your youth."]
            print(choice(list))
        elif int(age) > 25:
            typing(1)
            list = ["You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends."]
            print(choice(list))
        break

Como faço para isso não acontecer em todo o código?
Comment: Por que em vez de daquele continue você não bota um if name !='': e bota o elif como if e o else dentro do primeiro if?
Answer: Não vejo uma forma melhor de fazer seu código retirar esses if, entretanto dei uma ajeitada no seu código e tirei coisas desnecessárias.
1 - Tirei o continue, não é necessário.
2 - Você criava duas listas de frases, o tipo lista é o tipo mais lento de Estrutura de Dados, e era algo desnecessário para o Choice, logo eu criei 2 Conjuntos(Sets) e já apliquei eles dentro do Choice.
from random import choice

def get_name():
    while True:
        global name
        name = input("What's your name?")
        name = name.lower().capitalize()
        if name != '':
            if name.isdigit():
                print("Please don't type numbers.")
            else:
                print(choice(("I like your name.", "I always wanted to have that name.", "My friend has the same name.")))
                break

def get_age():
    while True:
        try:
            age = int(input("How old are you, "+name+"?"))
        except ValueError:
            print("Please, just type numbers.")
        else:
            if int(age) <= 25:
                print(choice(("You're still young.", "Being young is very good.", "Enjoy your youth.")))
            elif int(age) > 25:
                print(choice(("You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends.")))
            break

Answer: Você pode também substituir o loop while chamando a função novamente nos lugares onde ela teoricamente não receberia o input desejado.

Estou reutlizando a o código do user92257

from random import choice

def get_name():
    global name
    name = input("What's your name? ")
    name = name.lower().capitalize()

    if name != '':
        if name.isdigit():
            print("Please don't type numbers.")
            get_name() # aqui

        else:
            print(choice(("I like your name.", "I always wanted to have that name.", "My friend has the same name.")))

def get_age():
    try:
        age = int(input("How old are you, "+name+"? "))

    except ValueError:
        print("Please, just type numbers.")
        get_age() # E aqui também

    else:
        if int(age) <= 25:
            print(choice(("You're still young.", "Being young is very good.", "Enjoy your youth.")))

        elif int(age) > 25:
            print(choice(("You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends.")))

Como evitar repetir código?


Using differentiation under the integral sign to evaluate a trigonometric function

Question: I am trying to evaluate the following: $\int_0^\pi (5+3\cos(x))^{-3} \mathrm{d}x$ by using differentiation under the integral sign, however I cannot seem to find a suitable position to insert my '$A$' variable.
I have tried substituting the power of -3 for '$A$' however this left me with: $\int_0^\pi (5+3\cos(x))^{A}\ln(5+3\cos(x)) \mathrm{d}x$ which after attempting to solve by parts appears to be invalid as a $\sin(x)$ ends up on the bottom. I also tried inputting '$A$' in place of the $x$ in the $\cos(x)$ however it quickly became obvious to me that is probably not a valid thing to do because now I have lost the factor of $x$. Adding '$A$' in front of the function was of no help because I ended up with the same function as I started with.
Would someone be kind enough to point out where I should position my '$A$' variable in order for the equation to simplify - I'm not sure if the position must be found by trial and error or if there is some logic behind it.
Many thanks!
Answer: We can use differentiation under the integral sign to reduce it to an easier integral. Using the tangent half-angle substitution ($u = \tan(x/2)$) you can find $$\int_0^{\pi} \frac{1}{A + 3 \cos(x)} \, \mathrm{d}x = \frac{\pi}{\sqrt{A^2 - 9}}, \; \; |A| > 3.$$ Now differentiate twice with respect to $A$ and evaluate.


Trying to add an html head tag in Drupal 8, beta 2

Question: With Drupal 8.0 beta2, drupal_add_html_head() has been deprecated in favor of #attached. So the old way was:
function MYTHEME_page_build(&$page) {
    $viewport = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=0.55, user-scalable=yes',
          ),
        );
        drupal_add_html_head($viewport, 'viewport');
}

Based on the change notice you now use #attached. So the code above is essentially the same with the last part changing to:
$build['#attached']['html_head'][] = [$viewport, 'viewport'];

This does not work though and no error messages in watchdog. I've also tried putting this in a page alter as well as swapping $build with $variables and $output but it still does not work. In addtion, I tried the entire thing as an array:
  $build['#attached']['html_head'][] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'viewport',
      'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
    ),
  );

... but that did not work either. I am not sure what I am doing wrong, seems like it should be working.
Update
Here is working code which uses hook_page_attachments_alter which is not in D8 Beta 2 as it was just committed to dev.
function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
  }

The only issue now is that core's viewport tag does not get overwritten so I am stuck with my custom tag and core's. Not sure how to handle that one or should my tag be overwriting core's?
Answer: You don't have $build in preprocess, so can't work like that. $build needs to be a render array that is rendered somewhere. I also don't see how this could have worked before, as this is already converted in template_preprocess_html() before your function runs.
Add hook_page_attachments(_alter)() and deprecate hook_page_build/alter() was just committed, and as a theme, you can implement hook_page_attachments_alter(), look for examples in the committed patch, like common_test_page_attachments_alter().
So, something like $page['#attached']['html_head'][] = [$viewport, 'viewport']; should work in there.
Comment: Update your question with your current code examples then. Surely the example I pointed to is working , as it is used for tests. So you must be doing something differently. The hook I suggested to use is hook_page_attachments_alter(), not page_build(). When implementing a hook and something is not working, the first thing to verify is always if your code is even called, by adding an exit; for example.
Comment: That is what the second argument is supposed to be for, html_head elements are using that to be able to keep things unique. Looking at core, that element is added in DefaultHtmlFragementRenderer::setDefaultMetatags(). The new API there does not have a way for specify a key, which seems like a pretty serious issue. I suggest you open an issue for this. Maybe https://www.drupal.org/node/2350943 is related.
Comment: Well, thanks for your help but I am still lost. I'd be curious to see if you can get this to work. I've tried hook_page_build and alter but still no joy. I even grabbed some examples from core with no luck. It doesn't seem like it should be that hard.
Comment: I've added working code which uses your suggested ```hook_page_attachments_alter```. There is one side affect that I now have two viewport tags, one from core and the one I've added from my theme so I am not sure how to deal with that.
Comment: I opened a core issue: https://www.drupal.org/node/2359987


Uso do bindingNavigator

Question: Preencho um dataGridView via SQL e preenchendo um dataTable.
Gostaria de associar um bindingNavigator a este dataGridView.
Não estou conseguindo. Segue o código.
string arquivo = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Sistema_de_provas.accdb";
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + arquivo + ";Jet OLEDB:Database Password=; Persist Security Info=False;";
cn.Open();

OleDbCommand com = new OleDbCommand();
com.Connection = cn;
com.CommandText = "SELECT * FROM PROVAS";

OleDbDataReader dr = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
bindingNavigator1.BindingSource = dt;
cn.Close();

Está com problema nesta linha:
bindingNavigator1.BindingSource = dt;

Ou seja, depois do sinal de igual não aceita dt. Qual o erro?
Answer: Na propriedade BindingNavigator.BindingSource, informe um BindingSource:
// ...
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();

dt.Load(dr);
bs.DataSource = dt;

dataGridView2.DataSource = bs;
bindingNavigator1.BindingSource = bs;

// ....

Comment: Perfeito. Muito obrigado stderr.

Uso do bindingNavigator


Get term weight in node object for ordering with EntityFieldQuery

Question: Is it posiible to expose taxonomy term weight in node object ?
I need to sort nodes using EntityFieldQuery by term reference field, but weight is not exposed to node object so i can say for example
<code>->fieldOrderBy('field_custom_terms', 'weight', 'ASC');
</code>
and sort nodes by weight of terms.
Answer: No, this is not possible. You can only order on actual field values, the term weight would require a JOIN to a non-field table and EFQ is not capable of doing that.
You will have to create a manual SQL query to do this. Note that Drupal by default maintains the node <-> term associations in the taxonomy_index table, that one is easier and more reliable to query than a field data table.


how to Load CSS dynamically

Question: In my MVC application I want to apply themes. So, I am trying to load the CSS files from BundleConfig which is being initialized in Global.asax on App.Start method() Like
BundleConfig.RegisterBundles(BundleTable.Bundles);

However, I want to load the css dynamically to change the display style(theme) of the page on drop down list OR link button.
How can I do this ? I have tried to write in BaseController and from there call 'RegisterBundles' method But it is not working.
Any help on this appreciated.
Answer: A solution for dynamic CSS is to link your theme CSS entry in your markup to an MVC controller action, passing in the theme/customer ID, e.q.:
<link rel="stylesheet/less" type="text/css" email@example.com("ThemeCss","Render", new { id = Model.AccountID})' />

and the ThemeCss action method could return the content like so:
    [HttpGet]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
    public ActionResult ThemeCss(int id) //accountID
    {
        Account account = Db.GetInstance().Accounts.FirstOrDefault(a => a.AccountID == id);
        AccountSite site = account.AccountSite;
        string col1, col2, col3, col4;
        if (site.Theme == null)  //custom colour theme
        {
            col1 = site.ThemeColour1;
            col2 = site.ThemeColour2;
            col3 = site.ThemeColour3;
            col4 = site.ThemeColour4;
        }
        else
        {
            col1 = site.Theme.PrimaryColour.Substring(1);
            col2 = site.Theme.SecondaryColour.Substring(1);
            col3 = site.Theme.OtherColours.Split(',')[0].Substring(1);
            col4 = site.Theme.OtherColours.Split(',')[1].Substring(1);
        }
        string lessFile = "custom";
        string less = System.IO.File.ReadAllText(Server.MapPath("~/Content/render/themes/" + lessFile + ".less"));
        less = Regex.Replace(less, @"(\d){6}",
                             delegate(Match match)
                             {
                                 switch (match.Groups[1].Value)
                                 {
                                     case "1":
                                         return col1 ?? "E6E6E6";
                                     case "2":
                                         return col2 ?? "B1B1B1";
                                     case "3":
                                         return col3 ?? "333333";
                                     default: //case "4":
                                         return col4 ?? "FFFFFF";
                                 }
                             });
        return new ContentResult() { Content = less, ContentType = "text/css" };
    }

The downside of this solution compared to bundling is that you lose out on the CSS minification. If your theme is going to be fixed per AccountID then you could optimise caching by changing the OutputCache attribute to vary by the id parameter.

how to Load CSS dynamically


Possibility of arranging $1$ and $-1$ in a grid such that the sum of the products is $0$

Question: Consider an $11$ x $11$ grid, where in each square, the number $1$ or $-1$ is written. One multiplies the numbers in each row and column, and then sums up these $22$ products. Is it possible for this sum to be equal to $0$?
My approach was to realize that the product in every row or column is either $1$ or $-1$. This means, since we have $22$ products, that $11$ of them must be equal to $1$ and the other $11$ to $-1$. If there is an odd number of $-1$:s in a row or column, the product will be $-1$, while if there is an even number of $-1$:s, the product will be $1$. Then, I considered coloring each square in the following way: black if the cell contains a $-1$, uncolored if the cell contains a $1$. Thus, the question becomes: can one color grid cells in an $11$ x $11$ grid in such a way that an odd number of cells is colored in $11$ rows/columns, and an even number of cells is colored in the remaining $11$ rows/columns? However, from here, I couldn't make much progress. Does anyone have any ideas?
Comment: @JMP, well it doesn't work for a 2x2, but I don't really know how to prove it for a 3x3... maybe you can prove that it works differently for an $n$x$n$ grid if $n$ is even or odd...?
Comment: What about a row of -1 and a row of +1 for 2x2? Or perhaps I don't understand correctly.
Comment: Can you work out the answer in a smaller grid? 2x2? 3x3?
Comment: 1/ Are you sure it doesn't work for a 2x2?  2/ Hint: What can you say about the product of all the values in the cells? What about the square of the product?
Answer: Start with a grid $11\times11$, with $1$ in each square. Total is $22$.
Change $1$ to $-1$ in one square, new total is $18$.
Start with a grid $11\times11$, with random values. Change $1$ value, new total of rows increase or decrease by $2$, new total of columns increase or decrease by $2$, new total of rows+columns change by $-4, 0$ or $+4$.
Total is always equal to $2\pmod 4$. Total cannot be $0$, neither $4$ or $8$ or $12$ ...
Comment: very clever solution... thank you very much
Comment: Nice description of your discovery process, +1.
Answer: While Lourrran's solution is very nice, I was wish to point out something that feels more natural to me.
Since $121$ is odd, there should an even no. of $+1$ or $-1$.
If the no. of negatives on the board is even, then the no. of rows/columns with odd number of negatives have to be even.
If we denote the no. of rows with odd number of negatives with $R$ and the no. of columns with odd number of negatives to be $C$, then the sum we are interested in is $(11-R)-R+(11-C)-C$. If this sum were zero, this would imply that $2(R+C)=22$ but $R,C$ are both even.
In the other case, take a look at the negation of the whole board. If sum of products of the original board is zero, so is the sum of products on the negated board. This board will have an even no. of negatives. The same argument follows
Comment: Fixed. Thank you.
Comment: "If the no. of negatives on the board is even, then the no. of rows/columns with odd number of negatives have to be even."

No. Take the case where we only have two negatives in the first row and nothing else. Then the number of columns with an odd number of negatives is 9, which is not even.
Comment: But there are only 2 columns with odd number of negatives? I'm not following. Can you elaborate?


Permissão de acesso para um sistema PHP + AD + Oracle

Question: Bom dia,
Sou novo no PHP e estou começando um sistema para a empresa que eu trabalho, gerando relatórios.
Atualmente meu código PHP se autentica com um Active Directory normalmente, e ao conectar, ele vai para uma página com varios relatórios.
Esses relatórios fazem uma conexão temporária com um Banco de Dados Oracle 10g e ao terminar a exibição do código, fechar essa conexão.
Porém, o meu problema, é que todos os usuários tem acesso a todos os relatórios, o que fica inviável, pois tem relatórios que apenas a Diretoria pode acessar, enquanto alguns relatórios apenas o setor Fiscal, e assim por diante.
Eu procurei algumas soluções, mas não achei nada que eu conseguisse aplicar no meu ambiente.
Gostaria de saber se alguém consegue dar uma luz para meu problema:
Quero que as permissões de cada relatórios fiquem por usuário ou grupo, de preferencia que eu consiga dar as permissões direto no AD.
É possível?
Obrigado
Answer: Se você esta autenticando uma base LDAP, obviamente consegue fazer consulta a qual grupo esses usuários pertecem. Em PHP existe uma função onde você traz esses grupos, parte da ideia onde o grupo "Diretoria" pode ver tais relatórios e o grupo "operadoradores" podem ver apenas estes outros relátorios. Na prática em PHP, ao fazer a consulta de qual grupo o usuario pertecem, pode fazer condições usando o Switch ou até um IF mesmo. Exemplos:
Switch "$usuario->grupo"{
Case "Diretoria":
echo "Olá, estes são os relatórios diretoria"
break;
Case "Operador":
echo "Olá, estes são os relatórios operador"
break;
default:
echo "Olá, voce não faz parte de nenhum grupo, contate o administrador"
break;
}

Utilizando IF
if($usuario->grupo == "Diretoria"){
    echo "Olá, estes são os relatórios diretoria"
}
elseif($usuario->grupo == "Operador"){
echo "Olá, estes são os relatórios operador"
}

Bom, eu só citei alguns exemplos, claro que vai da sua lógica de programação. Espero ter ajudado.
Obs: Para consultas em LDAP usando PHP, como trazer o grupo, de uma lida em http://php.net/manual/pt_BR/ref.ldap.php
Abs.
Comment: Muito obrigado pela ajuda. Seguindo suas dicas eu consegui o que precisava.


Signaling on RTCPeerconnection

Question: I wrote a simple code for testing RTCPeerconnection
peer = new RTCPeerconnection(...);
peer.onicecandidate = function(evt){
    console.log(evt.candidate);
    // into the console
    // RTCIceCandidate {candidate: "candidate:... 1 udp ", sdpMLineIndex:0, sdpMid:"data"}
    // RTCIceCandidate {candidate: "candidate:... 2 udp ", sdpMLineIndex:0, sdpMid:"data"}
}

i want send it to signaling server but i receive it 2 times and 2 different values.
Have i to record all candidate values?
When i receive candidate information from signaling server, have i to receive all the values about the same peer?
I have too, localDescription
// {type: "offer", sdp: "v=0↵o=- 6483...48 2 IN IP4 ...}
Have i to send it to signaling server and receive the description of other peer?
Answer: I think you need to do bit more reading up on WebRTC, for a single PeerConnection, there could be many ICE candidates, you usually send it to remote peer through some signaling server, no point storing it in server, as they probably expire after a period of time.
this and this might be good place to read up on the basics.
Comment: My idea was: i get my host info (sdp and candidates), i record into a database. If an other host is connected, i receive the infos from the server, in this way i can set the RTCPeerconnection and through dataChannel i can exchange messages whit other peer... Am i so wrong???
Comment: I do not think you can store the ice candidates, they probably time out after 15 minutes...
Comment: Ok now i have a little confusing.
I believed if host_A and host_B want to comunicate they have to known the sdp and candidate infos, because in that infos there is the public ip and other usefull informations, and the way to exchange this infos is using Ajax and Sent-Server Event ( signaling mechanism ).

I searched by long time and some people said to me i need a signaling mechanism for exchange infos.
Comment: This [website](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/WebRTC_basics#Signal_Channel) say: `"... we have an ICE candidate, we need to send that to our peer so they know how to connect with us ..."`

In the way i described before the ice candidate goes from a peer to other...
Comment: @VitoLipari  since websockets have 2 way communication, ppl usually prefer that, but you can have a signalling mechanism with ajax n SSE too. dont exactly get your last comment.

Signaling on RTCPeerconnection


Comparar dois DataFrame e criar um novo DataFrame

Question: Estou com uma dúvida e gostaria da ajuda de vocês. Tenho dois DataFrame e preciso comparar se algumas colunas destes DataFrame são iguais e, caso sejam iguais, então preciso armazenar os registros em um outro DataFrame. Ou seja, eu preciso criar um novo DataFrame a partir da comparação de outros dois.
O exemplo é referente ao df1 e df2 (preciso comparar 4 critérios - 'x', 'y', 'z', 'w') e após a comparação criar o dfNovo com os registros que foram verdadeiros na comparação. No caso do exemplo abaixo, o dfNovo seria formado pelo registro de índice 0 do df1 e pelo registro de índice 0 do df2, já que são iguais nos critérios mencionados.
 import pandas as pd

 df1 = pd.DataFrame({"x": ['f','m','f'],
                        "y": [11,22,39],
                        "z": ['C','nC','nC'],
                        "w": ['F','S','M'],
                        "var1":["no", "yes", "no"],
                        "var2":["yes", "yes", "yes"],
                        "var3":["no", "no", "no"],
                        "classe":["yes", "yes", "no"]})

df2 = pd.DataFrame({"x": ['f','f','m'],
                        "y": [11,22,40],
                        "z": ['C','C','nC'],
                        "w": ['F','M','M'],
                        "var1":["yes", "yes", "no"],
                        "var2":["no", "no", "yes"],
                        "var3":["no", "no", "yes"],
                        "classe":["no", "yes", "yes"]})

Answer: muito boa a sua pergunta, pois a qualquer momento podemos precisar fazer esse procedimento nesse link acredito que já tenha a solução: Compare two DataFrames and output their differences side-by-side
E aqui na biblioteca pandas tem algo sobre comparar dataframes:
pandas.DataFrame.equals
Answer: Baseado no exemplo dado, a solução seria usar o método merge
>>> dfNovo = pd.merge(df1, df2, on=['x', 'y', 'z', 'w'])

>>> dfNovo
   x   y  z  w var1_x var2_x var3_x classe_x var1_y var2_y var3_y classe_y
0  f  11  C  F     no    yes     no      yes    yes     no     no       no

Você pode definir o sufixo que desejar
>>> dfNovo = pd.merge(df1, df2, on=['x', 'y', 'z', 'w'], suffixes=['_left', '_right'])

>>> dfNovo
   x   y  z  w var1_left var2_left var3_left classe_left var1_right var2_right var3_right classe_right
0  f  11  C  F        no       yes        no         yes        yes         no         no           no

>>> dfNovo = pd.merge(df1, df2, on=['x', 'y', 'z', 'w'], suffixes=['_df1', '_df2'])

>>> dfNovo
   x   y  z  w var1_df1 var2_df1 var3_df1 classe_df1 var1_df2 var2_df2 var3_df2 classe_df2
0  f  11  C  F       no      yes       no        yes      yes       no       no         no

Espero ter ajudado


Is there way to export block layout settings?

Question: I created a custom theme and I was wondering if there is way to export my block layout settings (location and order of each block). This way will be easier to apply my theme in a different site.
I'm using the Features module to keep on track of my custom blocks and block types.
Comment: Yes, just enable config core module and export the blocks(they are basically just instances of blocks) via admin/config/development/configuration/single/export and put them into your theme's config/install directory.
Answer: This question is about D8, for which you can use an approach as suggested in the comment from Ivan Jaros, i.e.:

... enable config core module and export the blocks (they are basically just instances of blocks) via admin/config/development/configuration/single/export and put them into your theme's config/install directory.

What not everybody may know, is that this kind of block related facilities that are new in D8, is actually because of the Bean module which has been included with Drupal 8 core (refer to this issue for more information).
This implies that a similar question for D7 can be resolved also by using the Bean module. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet (in D7) should definitely start looking at it in preparation of some day upgrading to D8.


Send an email from Chrome extension with Mailgun

Question: I have a small Chrome extension that I use just for myself. Currently it uses Mandrill, but Mandrill is going to stop being free in about a month and I am looking for other ways to send emails from the extension.
What I need is something really simple, and pure Javascript-jQuery. I don't mind exposing an API key in the code since the extension is just for my own use. I've been looking at documentation in sites like Mailgun or SparkPost, but I can't find a simple and pure JavaScript example. For instance, this is the code I tried for Mailgun; it's raising a 404 even though I'm using my sandbox URL and it is active:
<code>$.ajax({
    type: "POST",
    url: "MY SANDBOX URL",
    data: {
      'user':'api',
      'key': 'MY KEY',
      'from': 'SENDER EMAIL ADDRESS',
      'to': 'RECIPIENT EMAIL ADDRESS',
      'subject': 'Subject',
      'text': 'Body'
      }
    }).done(function(response) {
        console.log("Email sent");
 });
</code>
Please, could you help me? Thanks!
Comment: Try `SendGrid` that have REST API to send emails. Further if that is for personal use you can also use Gmail APIs to send emails.
Comment: Thanks, SendGrid could do what I need. I'll try to use it when I get home and let you know.
Comment: hey @phr, unfortunately SparkPost doesn't allow REST requests from the browser. It sounds like you have a good use here (an extension that is only used by you), but most people I've seen who want to do this don't understand the risks of exposing their API key. Good luck!
Comment: Thanks! I've been very busy these days and couldn't try SendGrid yet, but I will!
Answer: Sorry for the delay, I was really busy and thought this would take many hours of struggling so I did not try it until I had some time. In fact all the process took less than 30 minutes because SendGrid has a nice documentation and is very easy to use, at least for what I need. Thanks Adnan Umer for pointing me to this tool.
Here is what I did:
1) Create a free account. Allows up to 12k emails per month, more than enough for me.
2) Wait until the account is provisioned. In my case this was instant, but there could be a delay sometimes, allegedly up to several hours.
3) Generate a general API key here: https://app.sendgrid.com/settings/api_keys with full access to "Mail Send".
4) Send an email adding an "Authorization" header, and the key as a "Bearer" token in that header.
In my case this is working ok:
<code>$.ajax({
    type: "POST",
    url: "https://api.sendgrid.com/api/mail.send.json",
    headers: {
        'Authorization': 'Bearer ' + SENDGRID_API_KEY
    },
    data: {
        'to': EMAIL_ADDRESS_TO,
        'from': EMAIL_ADDRESS_FROM,
        'subject': 'Email subject',
        'html': 'Email body',
    }
}).done(function(response) {
    console.log("Email sent");
});
</code>
Thank you all!


KCFinder dont show correctly

Question: I'm searching all over for solution for my problem and cant find anything that work.
The problem:
I work with KOHANA framework and try to integrate KCFinder with my CKEditor.
At first it didnt work because some routing problems.
after going through almost all the files in kcfinder to replace all "require" and all the functions that need to call other files to the correct route.
finally the kcfinder window load with all the files.
but now i got another problem,
now the window look like

Here is the console for this page:

does anyone have any idea how to fix it ?
Comment: Can you show joiner.php and browse.php in the relevant parts?
Answer: This looks like an HTML problem ... so basically do a view source and find the missing CSS file and make sure the HTML that gets pumped out is pulling the CSS file properly ... nothing to do with PHP or Kohana at all
Answer: this is my browse.php
<code>$base = APPPATH.'includes/kcfinder/';
require $base.'core/uploader.php';
require $base.'core/browser.php';
require $base.'core/autoload.php';
require $base.'core/types/type_img.php';
require $base.'core/types/type_mime.php';
require $base.'lib/class_gd.php';
require $base.'lib/class_input.php';
require $base.'lib/class_zipFolder.php';
require $base.'lib/helper_dir.php';
require $base.'lib/helper_file.php';
require $base.'lib/helper_httpCache.php';
require $base.'lib/helper_path.php';
require $base.'lib/helper_text.php';
$browser = new browser();
$browser->action();
</code>
and this is my joiner.php
<code>$base = APPPATH.'includes/kcfinder/';
require $base.'core/uploader.php';
require $base.'core/browser.php';
require $base.'core/autoload.php';

require $base.'core/types/type_img.php';
require $base.'core/types/type_mime.php';

require $base.'lib/class_gd.php';
require $base.'lib/class_input.php';
require $base.'lib/class_zipFolder.php';
require $base.'lib/helper_dir.php';
require $base.'lib/helper_file.php';
require $base.'lib/helper_httpCache.php';
require $base.'lib/helper_path.php';
require $base.'lib/helper_text.php';
$files = glob(dirname(__FILE__).'/*.js');
sort($files);
</code>
....

KCFinder dont show correctly


Sentry how to specify the name of the operation via the Go package OpenTelemetry?

Question: How do I specify the name of the span operation in the OpenTelemetry package of the Go language? Span names from the documentation list: https://develop.sentry.dev/sdk/performance/span-operations/
I tried to specify through an attribute, but it just creates another attribute with the same name:
ctx, span := trace.Tracer.Start(ctx, "name", trace.WithAttributes(attribute.String("Operation", "http.server")))
defer span.End()

Answer: ctx, span := trace.Tracer.Start(ctx, "name", trace.WithAttributes(attribute.String("faas.trigger", "http.server")))
defer span.End()

OR
import semconv "go.opentelemetry.io/otel/semconv/v1.4.0"

ctx, span := trace.Tracer.Start(ctx, "name", trace.WithAttributes(semconv.FaaSTriggerKey.String("http.server")))
defer span.End()


Cakephp 2.x relative path is not working but absulate path is working

Question: I have newly install Ubuntu server with Apache/2.4.7 ,Php  5.5.9 , mysql and uploaded my Cakephp project over there , My cakephp version is 2.4 but i am facing an issue, Its is not finding any css, images, or any other files which is define on webroot folder.
example
http://xx.xx.xx.xxx/css/style.css (Not working , giving 404 error)
http://xx.xx.xx.xxx/js/min.jquery.js (Not working , giving 404 error)
http://xx.xx.xx.xxx/app/webroot/css/style.css (working)
http://xx.xx.xx.xxx/app/webroot/js/min.jquery.js (working)
option which i have already checked.

htaccess is working
mod_rewrite is loading
SERVER API is Apache not CGI or FASTCGI
short Tag is open

any help will be appreciated.
Answer: Check that your virtual host is configured correctly. You should have AllowOverride All in your vhost's conf file, something like this:-
<VirtualHost *:80>
    ...
    <Directory "/var/www/vhosts/example.com">
        AllowOverride All
    </Directory>
</VirtualHost>

Answer: Check AllowOverride value at apache2.conf file. By default is none. In order to work set it to "all"


I m creating a cashier class but i cannot get name and price of each item to display

Question: I was asked to create a cashier, testcashier and get data java classes to mimic a simple cashier operation. I created all the classes and everything including making and displaying change works but the items names and prices are not being displayed, why?
        public class Cashier {
        private  int numberOfItems;
        private  double totalSum;
        private  double amount;
        private  String names;
        private  String s, name;
        private double price, tendered, change,  dollars, quarters, dimes,
        nickels, pennies;

        NumberFormat nf = NumberFormat.getInstance();
        DecimalFormat df = (DecimalFormat)nf;

        public Cashier(){
           this.name = "";
           this.price = price;
           price = 0;
           this.s = "";
         }
        public Cashier(String name, double price, String s)
        {
          //this.tendered = 0;
          this.name= name;
          this.price = price;
          //amount = tendered;
          //price = 0;
          //this.s = s;

           }

          public double average()
           {
              return totalSum/numberOfItems;
           }
           public void add(String name, double price)
           {
           totalSum = totalSum + price;
           s = s + name + "........" + price + "\n";
            numberOfItems++;
              }

             public void makeChange()
            {

             change = amount - totalSum;
             change = 100 * change;
             change = Math.round(change);
             change = change / 100;
             dollars = (int)(amount - totalSum) * 100 / 100;
             pennies = (int)(change * 100) % 100;
             quarters = (int)pennies / 25;
             pennies = (int)pennies % 25;
             dimes = (int)pennies / 10;
             pennies = (int)pennies % 10;
             nickels = (int)pennies / 5;
             pennies = (int)pennies % 5;
             pennies = (int)pennies;
              }
             public String getNames()
             {
               return name;
              }
                  public double getPrices()
                    {
                        return price;
                            }
                public double getTotal()
                    {
                       return totalSum;
                               }
                             public double getMoney()
                              {
                          return tendered;
                           }
                            public double getChange()
                             {
                      return tendered - totalSum  ;
                                   }
                           public double getQuantity()
                              {
                return numberOfItems;
                 }
                  public double getAverage()
                           {
                      return average();
                           }
                public double getDollars()
                   {
                    return dollars;
                            }
                        public double getQuarters()
{
return quarters;
}
public double getDimes()
{
return dimes;
}
public double getNickels()
{
return nickels;
}
public double getPennies()
{
return pennies;
}

public void tendered(double amount)
{
 // double tendered;
  tendered = amount;
}

}

public class TestCashier {

public static void main(String[] args) {

Cashier c = new Cashier();

String name = GetData.getWord("Enter name of item");
double price = GetData.getDouble("Enter price of item");
c.add(name, price);

name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);
name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);

// Add a two more entries of your own

// Now average the price of the items
c.average();

// Make payment
double amount = GetData.getDouble("Enter amount of money for payment");
c.tendered(amount);
//ndered(amount); // Twenty dollars were tendered

c.makeChange();

generateReceipt(c);

}
public static void generateReceipt(Cashier c)
{

String s= "ABC Groceries Shop \n";

s = s + "Welcome – thanks for stopping, \n";

DateFormat df = DateFormat.getDateInstance();

Date d = new Date();

NumberFormat f = NumberFormat.getCurrencyInstance();

s = s + "Today is " + df.format(d) + "\n";

s = s + "Item:" +(c.getNames());
       //\n";

s = s + c.getNames() + "..... " + f.format(c.getPrices()) + "\n" + c.getNames() +
        "..... " + f.format(c.getPrices()) + "\n" + c.getNames() + "....." +
        f.format(c.getPrices()) + "\n";

s = s + "____________________" + "\n";

s = s + "Total " + f.format(c.getTotal()) + "\n\n";

s = s + "Amount tendered " + f.format(c.getMoney()) + "\n";

s = s + "The change is " + f.format(c.getChange()) + "\n";

s = s + "There were " + c.getQuantity() + " items" + "\n";
s = s + "The average price is " + f.format(c.getAverage()) + "\n\n";

s = s + "The change includes :" + "\n";

s = s + c.getDollars() + " dollars" + "\n" + c.getQuarters()+ " quarters" +
        "\n" + c.getDimes()+ " dimes" + "\n" + c.getNickels()+ " nickels" +
        "\n" + c.getPennies() + " cents";

JTextArea text = new JTextArea(s,15, 25);

JScrollPane pane = new JScrollPane(text);

JOptionPane.showMessageDialog(null,pane, "Your bill",
        JOptionPane.INFORMATION_MESSAGE);

}

}

public class GetData {
    static String str;
static double getDouble(String s)
{
str = JOptionPane.showInputDialog(s);
return Double.parseDouble(str);
}
static int getInt(String s)
{
str = JOptionPane.showInputDialog(s);
return Integer.parseInt(str);
}
static String getWord(String s)
{
//str = JOptionPane.showInputDialog(s);
return JOptionPane.showInputDialog(s);
}

}

Answer: Your public void add(String name, double price) method concatenates the names and prices to the s member of the Cashier class, but you print the output of the getNames() and getPrices() methods, which return members that remain empty.
One way to get the output you want is to call a method that returns s and print it.
Comment: So should i return s instead of name or price? i m so confusedddd
Comment: @mariaandreaerramouspe replace all the calls to `getNames()` and `getPrices()` with a single call to `getNamesAndPrices()`, which would return s.
Answer: You need to instantiate Cashier using the contructor
 public Cashier(String name, double price, String s)

as in
 Cashier  c = new Cashier (name, price, "");

not
c.add (name, price);

which does not set the field's values


Is it possible to rent an IP address to mask the server real IP address?

Question: A customer would like to lease an IP address and point it to a dedicated web server with the intention of "masking" the server's IP address so it would be difficult to tell where the site is hosted.
I found a company that leases IP addresses here: http://www.webhostingtalk.com/showthread.php?t=1191688
Is this even possible? Can they rent an IP address from a 3rd party in order to hide the server's IP address?
Update:
My client will be hosting a government leaks site and is trying to become Raid-Proof similar to what the pirate bay did: http://torrentfreak.com/pirate-bay-moves-to-the-cloud-becomes-raid-proof-121017/
Only that I'm worried about using a reverse proxy because of the latency it could cause having the app servers hosted in one data center and the load balancer/reverse proxy in other and also having to pay twice for bandwidth.
Comment: Yes, but.. this will _not_ protect you from DDoS attacks, and it won't protect you from law enforcement.
Comment: Keep in mind, the pirate bay not only uses a Reverse Proxy, but they also have Encryption to protect their data. The raid-proof concept is how fast they can get the site on line, not really that the Govt can't figure out their identities.
Comment: The client will be hosting a government leaks site and is trying to become Raid-Proof similar to what the pirate bay did
Comment: Aha. Well. If that's what you're doing, then you probably want to look at Wikileaks and the challenges they've had with hosting their web site. Unfortunately the question is much too broad for us to handle completely here, and I would suggest you hire someone with experience in this area.
Comment: keep in mind that this can't completely hide the server's IP address. whatever IP you "rent" will need to know where to ultimately connect to. that MUST be in the configuration somewhere. if the person/organization trying to locate the server is persistent or powerful enough, they will get access to the "rented" IP (i.e., that server) and get the real IP from that machine.
Comment: It might help to tell us why they want this. Might be solving a problem that doesn't exist (or that can't be ultimately avoided)
Comment: @net-girl - your concerns about latency are valid. Another option is to look at someone like [PRQ](http://prq.se/?p=dedicated&intl=1) - they host ThePirateBay and their way of dealing with DCMA's are to delete them.
Answer: You can achieve this in multiple ways, but basically you need to set up a web server somewhere else, and then reverse-proxy the HTTP requests.
It doesn't matter where, and don't bother with "renting" any IP space.
You can do something like this for free with Amazon's EC2 micro (free) instances, or basically any VPS provider that will give you root access to a Linux installation.
Good news is doing this with Amazon's EC2 is that it's simple enough to change your IP address if you need to in future, just release your old IP and assign a new one.
I have used methods to bypass geographical restrictions on certain services. Starting a free Micro instance, and then proxying via a VPN into an area that people can't normally access. Just don't be surprised when you receive a Cease and Desist.
Comment: Similar to the problems with Cloudflare in [this answer](http://serverfault.com/a/448449/32986) hosting with Amazon (even in diverse availability zones would make you vulnerable to takedown notices.  You really need multiple diverse hosting arrangements, in areas with strong freedom of speech protections.
Answer: You could probably kill two birds with one stone by setting up  your website with a content distribution network. Cloudflare is getting a lot of press lately, and seem to be pretty well recommended, but there's other options.
This will also probably speed up your website for people near CDN servers, and possibly add another level of protection of ddosing with some CDNs.
If this is to avoid legal entanglements, I have no idea. Someone somewhere needs to know who you are to reach your website.
Comment: In this particular case (government leaks site) a CDN would probably be a bad choice -- a takedown order to the CDN would knock out all of your distributed data.
Comment: Thats wasn't mentioned when I actually answered it ;p
Comment: I know, but the person who stumbles on this in a year, hosts their site on Cloudflare, and then gets knocked off the net by a nastygram from the attorney general's office might not be bright enough to figure it out :)


How to loop dataframes by name in R

Question: I have trouble looping dataframes by their name. And have no idea how to fix this. I am using census data from multiple years and have to apply the same operations over multiple datasets.
Here is a simplified example of that I want to do. I create a dataset called df1. And make two copies of it called df2 and df3. Let's say that for each data frame I want to make a variable 3 (v3) which is v3=v1+v2.
The loop that I made won't work. And I don't know how to loop date frames correctly by their name.
v1<-c(1:10)
v2<-c(1:10)
df1<-data.frame(v1,v2)
df2<-df1
df3<-df1
x<-c("df1","df2","df3")
for (i in x) {v3<-v1+v2}

Comment: David's answer touches on this, but the better way is to use [a list of data frames. See this answer for lots more detail.](https://stackoverflow.com/a/24376207/903061)
Answer: What you are looking for is the get and assign-functions.
For example you can use it like this:
df1 <- data.frame(v1 = 1:10, v2 = 1:10)
df2 <- df1
df3 <- df1

x <- c("df1","df2","df3")

for (i in x) {
  # load the dataset "i" to the tmp-variable
  tmp <- get(i)
  # do something
  tmp$v3 <- tmp$v1 + tmp$v2
  # assign the tmp variable to the value of "i" again
  assign(i, tmp)
}

# lets have a check
df1
#>    v1 v2 v3
#> 1   1  1  2
#> 2   2  2  4
#> 3   3  3  6
#> 4   4  4  8
#> 5   5  5 10
#> 6   6  6 12
#> 7   7  7 14
#> 8   8  8 16
#> 9   9  9 18
#> 10 10 10 20

df2
#>    v1 v2 v3
#> 1   1  1  2
#> 2   2  2  4
#> 3   3  3  6
#> 4   4  4  8
#> 5   5  5 10
#> 6   6  6 12
#> 7   7  7 14
#> 8   8  8 16
#> 9   9  9 18
#> 10 10 10 20

df3
#>    v1 v2 v3
#> 1   1  1  2
#> 2   2  2  4
#> 3   3  3  6
#> 4   4  4  8
#> 5   5  5 10
#> 6   6  6 12
#> 7   7  7 14
#> 8   8  8 16
#> 9   9  9 18
#> 10 10 10 20

Improvement
Having said that, you probably dont want to do it this way, instead try to use the apply-family of commands.
I usually tend to use a lot the lapply-function. In your case it would look like this:
# create some data again
df <- data.frame(v1 = 1:10, v2 = 1:10)

# create three data-frames in a list
# here you would for example, load the dataframes from your source into the list
df_list <- lapply(1:3, function(x) df)

str(df_list)
#> List of 3
#>  $ :'data.frame':    10 obs. of  2 variables:
#>   ..$ v1: int [1:10] 1 2 3 4 5 6 7 8 9 10
#>   ..$ v2: int [1:10] 1 2 3 4 5 6 7 8 9 10
#>  $ :'data.frame':    10 obs. of  2 variables:
#>   ..$ v1: int [1:10] 1 2 3 4 5 6 7 8 9 10
#>   ..$ v2: int [1:10] 1 2 3 4 5 6 7 8 9 10
#>  $ :'data.frame':    10 obs. of  2 variables:
#>   ..$ v1: int [1:10] 1 2 3 4 5 6 7 8 9 10
#>   ..$ v2: int [1:10] 1 2 3 4 5 6 7 8 9 10

# do some operations:
df_list2 <- lapply(df_list, function(d) {
  # do something
  d$v3 <- d$v1 + 100 * d$v2
  return(d)
})

df_list2
#> [[1]]
#>    v1 v2   v3
#> 1   1  1  101
#> 2   2  2  202
#> 3   3  3  303
#> 4   4  4  404
#> 5   5  5  505
#> 6   6  6  606
#> 7   7  7  707
#> 8   8  8  808
#> 9   9  9  909
#> 10 10 10 1010
#>
#> [[2]]
#>    v1 v2   v3
#> 1   1  1  101
#> 2   2  2  202
#> 3   3  3  303
#> 4   4  4  404
#> 5   5  5  505
#> 6   6  6  606
#> 7   7  7  707
#> 8   8  8  808
#> 9   9  9  909
#> 10 10 10 1010
#>
#> [[3]]
#>    v1 v2   v3
#> 1   1  1  101
#> 2   2  2  202
#> 3   3  3  303
#> 4   4  4  404
#> 5   5  5  505
#> 6   6  6  606
#> 7   7  7  707
#> 8   8  8  808
#> 9   9  9  909
#> 10 10 10 1010

How to loop dataframes by name in R


Locally flat submanifold

Question: Recently I found the following definition:
Let $M^{n}$ be an $n-$dimensional topological manifold. Then $N^{k}\subseteq M^{n}$ is a locally flat submanifold if for every $x\in N$ there exists an open set $U$ in $M$ such that the pair $(U,U\cap N)$ is homeomorphic to the pair $(R^{n},R^{k})$.
The first thing I noted is that if $N$ is a locally flat submanifold of $M$, then $N$ in fact is a sumbanifold of $M$. The second thing I noted is that in the category of smooth manifolds the notion of locally smooth submanifold and submanifold are equivalent.
I would like to know if there is an example of a topological submanifold of a manifold that is not a locally flat submanifold or if the notions of locally flat submanifold and submanifold are equivalent in the category of topological manifolds?
Comment: [Local flatness definition on Wikipedia](http://en.wikipedia.org/wiki/Local_flatness).
Answer: Consider a knot $K\subset S^3$. Then think of the $4$-ball $B^4$ as the cone on $S^3$: $B^4=C(S^3)$. Consider the cone on $K$ inside the $4$-ball, $C(K)\subset B^4$. This is homeomorphic to a disk and is a submanifold of $B^4$. However it is not locally flat since any small ball around the cone point will have a knot on the boundary, so won't be locally standard, as in the definition of locally flat.
Comment: @Antonio: Yes the knot must be knotted. It doesn't work with the trivial knot.
Comment: I was not expecting that :D
Comment: @MattN.: the tameness of $K$ is a separate issue. I was actually thinking that $K$ is tame, but the cone on $K$ is still not locally flat. A knot $K$ in $\mathbb R^3$ is tame if and only of it is locally flat.
Comment: @Karl Yes, I believe you are correct that it is knotting at the boundary that destroys local flatness. I believe all 2-submanifolds of $\mathbb R^3$ are indeed locally flat, but wild embeddings like the Alexander Horned Sphere would need to be carefully considered. You could always ask this as a separate question.
Comment: I'm not sure about the example, does it works with a trivial knot? Or the knot must be "knotted"?
Comment: Ok, let me study this example more carefully to be completely sure that I understand it. Thank you so much.
Comment: I don't know if you can give some comments about the definition of locally flat submanifold and also if you can give me some bibliography where I can found about the topic?
Comment: @Antonio: The way I think of it, a locally flat submanifold mimics all of the nice properties of a smooth submanifold. I really don't know any good references. I learned about this stuff talking to my advisor in grad school.
Comment: @Antonio: The manifold atlas project http://www.map.him.uni-bonn.de/Main_Page might be a good place to get started.
Comment: Rolfsen's "Knots and links" textbook is a good source for this material. Roseman's "Elementary Topology" would also be another good source.
Comment: @JimConant Do you make any assumption on tameness of $K$? I am wondering whether a knot is tame if and only if it is locally flat or whether we can have tame knots that aren't locally flat.
Comment: Dear @JimConant, thank you very much for your comment!
Comment: Just to be sure: in $\mathbb R^3$ we have "$K$ is tame" <=> "$K$ is locally flat" but in $S^3$ this doesn't hold?
Comment: @MattN: No, it's still true in $S^3.$ I just wanted to point out that it's not true in other pairs of dimensions. My cone example is tame but not locally flat.
Comment: I wonder whether all counterexamples involve knotting like this in some sense. Is every 2-submanifold of $\Bbb R^3$ locally flat?

Locally flat submanifold


HttpPostedFileBase sempre vazio ao passar csv para o controller

Question: Boa Tarde Pessoal,
Estou dificuldade para passar um csv que esta sendo mandado do ajax usando jquery para o controller aonde sempre chega null.
Poderiam me ajudar?
View :
@using (Html.BeginForm("Importar", "Contatos", FormMethod.Post, new { enctype = "multipart/form-data",id="formUpload" }))
{

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

  Importar CSV

                        @Html.TextBox("arquivoExcel", "", new { type = "file", required = "required" })

                        @Html.Label("O que deseja fazer com os contatos deste arquivo ?", null, new { @class = "lead" })

                            @Html.RadioButton("0", "", new { id = "vinculaAtualizaG", required = "required" })
                            Vincular e atualizar um grupo

                            @Html.RadioButton("0", "", new { id = "vinculaNaoAtualizaC", required = "required" })

                            Vincular a um grupo, sem atualizar os dados dos contatos

                            @Html.RadioButton("0", "", new { id = "vinculaNovoGr", required = "required" })

                            Vincular a um novo grupo, sem atualizar os dados dos contatos

                        @Html.DropDownList("grupos", (List<SelectListItem>)ViewBag.Grupos, new { @class = "form-control" })
                        @Html.TextBox("grupooo", null, new { @class = "form-control text-box single-line" })

                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-warning " id="dados">Importar</button>

}

Jquery:
$('#dados').on('click', function () {
    var txtGrupo;
    var option;
    var radioSelected;

    var radios = document.getElementsByName("0");
    for (var i = 0; i < radios.length; i++) {

        if (radios[i].checked) {
            var id = $(radios[i]).attr("id");

            radioSelected = id;

            if (id == "vinculaNovoGr") {
                txtGrupo = $("#grupooo").val();
            } else {
                option = $('#grupos').find(":selected").text();
            }

        }
    }
    var formData = new FormData($('#formUpload')[0]);
    debugger;

    $.ajax({
        url: "/Contatos/Importar",
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify({

            grupooo: $("#grupooo").val(),
            id: radioSelected,
            opcaoCombo: $('#grupos').find(":selected").text(), //,
             arquivoExcel: formData

        }),
        async: false
    });

});

CONTROLLER:
    [HttpPost]
    public ActionResult Importar(HttpPostedFileBase arquivoExcel,string teste, string id, string grupooo, string opcaoCombo)
    {

        var d = HttpContext.Request.Files[0];
        var r = id;
        var opc = grupooo;
        var fs = opcaoCombo;

        return RedirectToAction("Index", "Contatos");
    }

Comment: Você não pode fazer `JSON.stringify()` de um `FormData`. Faça `formData.append()` para adicionar dados e envie o `formData` sem transformá-lo em string.
Comment: https://developer.mozilla.org/pt-BR/docs/Web/API/FormData/append
Comment: Acredito que o  seu post não poderia  ser `application/json` para realizar o upload, deveria ser `multipart/form-data`
Answer: Pegue os dados do form:
var formData = new FormData($('#formUpload')[0]);

Configure a propriedade Data da função Ajax assim:
data: formData

Segue abaixo um exemplo de postagem de arquivo com Ajax e ProgressBar:

        0%

<form id="frmEnviar" action="~/enviar")" method="post" enctype="multipart/form-data">
    <input type="file" name="arquivo" />
    <input type="file" name="arquivo2" />
    <button>Enviar</button>
    <input type="reset" />
</form>


How to attach a database of data to a content / entity type

Question: I have an sqlite database representing a collection of Foo which is immutable. I would like to be able to take this collection of Foo in the GUI of Drupal, and append a few fields onto each Foo instance, these new fields are to be editable.
I see no point to inserting the data as nodes / entities directly as the data is only going to reflect what's already in the database and inserting data using node_save is incredibly slow for duplicating the data.
How would I accomplish this so that a content-type / entity type uses data from another database, but manages a few additional editable fields?
Would it be a custom content type with a module to manage the pulling of the data from another database, or would it be a custom entity?
Answer: I would use a custom content type that stores the primary key (pk) of an instance of Foo as text, integer or whatever you need, just that one field.  Let's call the content type Bar.
Then for display create a node template for Bar that:

Queries your database by sending Bar->pk and returns the Foo row/object
Iterates through the fields in the row and displays them where and how you choose

In case you haven't already come across it, if you're intending to use an external database, it is best to define it in your settings file and call it when you need it as described here.
Comment: would this allow the data to be searchable, and viewable with views?
Comment: Ahh, now that's a different question, searching the content inside your external db would require a fairly complicated custom module I think.  Better off replicating the data as nodes, just export as csv or xml and use Feeds to import into a content type.


How to convert a .npz format to .csv in python?

Question: I'm new to python. I want to convert a .npz file (.npz is a numpy file format) to .csv file to use it in R. Please suggest a way
Answer: Try something like:
<code>import numpy as np

data = np.load(filename)
for key, value in data.items():
    np.savetxt("somepath" + key + ".csv", value)
</code>
Comment: What about the other way around, from .csv to .nyz?
Comment: [np.loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) and [np.savez](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez) would be the keywords to look for
Comment: I found that ```np.load(filename)``` was needed; .loadz wasn't found.


A sum of terms like $(1 + \sin^2x)^{-1}$

Question: How to prove that
\[
\frac12\frac1{1+\sin^2 x} + \frac12\frac1{1+\cos^2 x} + \frac12\frac1{1+\sec^2 x}+ \frac12\frac1{1+\csc^2 x} = 1?
\]
Some genius please help me I have been stuck at this for one whole day.
Comment: Please be clearer about the equation.  Some would read  1/2(1+sin^2 x) as $\frac 1{2(1+\sin^2 x)}$ or at least worry that you meant that.  Either  (1+sin^2 x)/2,  (1/2)(1+sin^2 x), or (best) $\LaTeX$.  Trying to solve the problem, I see I had it wrong, so please  1/(2(1+sin^2 x)), or $\LaTeX$
Comment: I would start by getting rid of $\sec$ and $\csc$, replacing them with $\frac 1\cos$ and $\frac 1\sin$.  Then you must have identities for $1+\sin^2 x$ and $1 + \cos^2 x$.  Where does that take you?
Answer: Forget about the $2$'s for a while. We have
$$\frac{1}{1+\sec^2 x}=\frac{1}{1+\frac{1}{\cos^2 x}}=\frac{\cos^2 x}{\cos^2 x+1}.$$
Now add $\frac{1}{1+\cos^2 x}$. We get something very simple.  Continue.
Answer: Observe that for any $\alpha> 0$ we have
$$
\frac{1}{1+\alpha}+\frac{1}{1+1/\alpha}=\frac{1+1/\alpha+1+\alpha}{(1+\alpha)(1+1/\alpha)}= 1
$$
so
$$
\frac{1}{1+\sin^2x}+\frac{1}{1+\csc^2x} = 1
$$
wherever $\csc x$ is defined and similarly
$$
\frac{1}{1+\cos^2x}+\frac{1}{1+\sec^2x} = 1
$$


How to downgrade from SQL2005 Enterprise to SQL2005 Standard?

Question: How to downgrade from SQL2005 Enterprise to SQL2005 Standard in Windows Server 2003?
Answer: I'm afraid the only possible solution is to backup all your databases, uninstall SQL Server 2005 Enterprise, install the Standard version and restore the databases.
Don't forget to script any user objects of your master database and other system databases (job definitions etc.)
Comment: You might also want to mention that they can check to see if their databases are using any EE-only features.
Comment: Yes, Brent's absoluteley right. I would test it on a staging machine, before doing this on a production/important server.
Comment: Wht's the command to script out usr obj & system in master db? I'm poor in script.
Comment: Here is a link: http://www.mssqltips.com/tip.asp?tip=1531  --  Be careful, make a backup of all databases before you begin...
Answer: Unfortunately there is no easy path to downgrade. You will need to:

Take a backup of all your databases
Uninstall SQL 2005 EE
Reboot the server
Re-install SQL 2005 standard, ideally in the same location as the previous version.
Restore your databases to this new server.

You may be able to make the process quicker by copying your existing databases to another location, doing the re-install and then copying the databases back, overwriting the existing DB's, including the system DBs. However, make sure you have a good backup off all DB's as well in case this does not work as you want.
As Brent said, your also going to want to check that any of your DB's are not using the features of the EE edition.


Sum multiple counts from multiple tables

Question: I have different tables (per region) with some columns that are the same. Now I need to have a count for each value that is placed in one column over multiple tables. I'm trying to get a sum for this so I don't have to use 4 separate queries and outputs. Furthermore the values are matched with a lookup table
Region table(s) - Table1:
    id       | Column1 |
    ---------|----------|
    1        | 1
    2        | 2
    3        | 3
etc

Lookup table
    id       | Description |
    ---------|-------------|
    1        | Description1
    2        | Description2
    3        | Description3

The query I'm using to get the count from 1 of the tables is :
SELECT Description, Count(*) as Number from Table1, LookupTable
WHERE Column1 = LookupTable.id GROUP BY Column1 ORDER BY Number Desc

The output is
 Description   | Number
---------------|--------
Description1   | Number
Description2   | Number
Etc.

Any idea on how to sum up the counts for each Description/value of Column1 from 4 tables that generates the output as displayed above (but then with the sum value for each description)?
Answer: It's not clear but I guess you can use:
select LookupTable.id,LookupTable.Description, SUM(Cnt) as Number
from LookupTable

JOIN
(
    SELECT Column1 as CId, count(*) as Cnt from Table1 group by Column1
    union all
    SELECT Column2 as CId, count(*) as Cnt from Table2 group by Column2
    union all
    SELECT Column3 as CId, count(*) as Cnt from Table3 group by Column3
    union all
    SELECT Column4 as CId, count(*) as Cnt from Table4 group by Column4
) T1 on LookupTable.id =T1.Cid
 GROUP BY LookupTable.id,LookupTable.Description
 ORDER BY Number Desc

Comment: Perfect that worked!

Now what if I would want to include another column from all the tables in this? So not a count per value of Column1, but a count per combination of the value of Column1 and column2?
Answer: Use this query:
SELECT LookupTable.Description, Count(*) as Number
   FROM Table1, LookupTable
      WHERE Table1.Column1 = LookupTable.id
          GROUP BY Table1.Column1;

You have leave the name of table or its alias to call the column.


DNS address on a roaming laptop

Question: I have a local DNS server that we use for our intranet. Its IP address is 192.168.0.25.
In order to see pages on our intranet, our employees have to use 192.168.0.25 for their DNS server. If they provide two DNS server IP addresses - one local and one remote - it seems to cause problems.
The problem with having just the local domain, though, is that when the employees take their laptops home, they have to remove that local IP address in order for the internet to work.
Is there a way to make it so the employees don't have to change their DNS servers every time they leave the office?
Answer: Set up a DHCP server and scope on your network for the clients, assign your DNS server in your DHCP scope\server options, set the clients to get their ip address and DNS servers from DHCP, done.
Comment: Agreed.  DHCP configuration should be able to solve this fairly easily.
Comment: +1 Always avoid hardcoding a DNS server address on a non-server machine.

DNS address on a roaming laptop


Vue 3 issues importing / resolving component

Question: Hi new to Vue and learning through tutorials. I have created a component Header.vue and try to import it to App.vue.
This is the structure:
code structure
here is App.vue:

<template>

</template>

Here is the Header.vue component:

<template>

Income Tracker

$0

</template>

I am getting the styling from the App.vue but the component isn't resolving. In the console I get this error:
error message
What I have tried is stack overflow and google search based on the error message text.
Either I am not searching correctly, or I do not have enough experience at this point to identify the issue causing this problem.
Education on how to resolve this would be greatly appreciated.
Comment: I recommend against using `Header` as a component name, since it could conflict with the HTML [`header` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header). This violates the [very first rule in the Vue Style Guide](https://v3.vuejs.org/style-guide/#priority-a-rules-essential-error-prevention).
Comment: I think this tutorial is a lil wack.. already learned more here fixing the problem the the first 4 min of the tuts.
Answer: You need to register components in the components option.
export default {
  components: {
    Header,
  },
};

See the docs.
Note that including a valueless entry in a JavaScript object (e.g. Header) is ES6 syntax for Header: Header.
Comment: Ders thank you. Your solution brought the text over which means that the component import works now. For some reason the component styling is not displaying now, but the  and the  displays. One step further along thanks for the assist.
Comment: No problem. It is good to jump right into things because that's a great way to learn, but at some point I would recommend reading the entirety of the [Vue docs](https://v3.vuejs.org/guide/introduction.html). They are great, and you should be referencing them a lot.
Answer: You need to use components like this
<template>

</template>

Comment: Jay Patel thanks you .. but using "header":Header didnt work. In combination with your code structure and @Ders answer also I was able to move it forward.
Comment: it will work see template tag and change it accordingly like     .
Answer: In your Header.vue replace your div tag with header tag, because you are styling header tag in your CSS and not div tag.
<template>

Income Tracker

$0

</template>

Comment: Thank you Amit! Every new bit of education helps. But it now displays the  and the  but not the component styling.
Comment: In your Header.vue, you have done styling using CSS element selector i.e.  in your case, but you havn't used that tag in your code. So in your Header.vue, change your parent  tag with  tag.
Comment: `name` does not register components. It is useful for debugging purposes.
Comment: my bad! Thanks @Ders for bringing that to my knowledge.
Comment: Amit and @Ders Thank you both.


Integrable function and it's upper Riemann sum

Question: I got this question:
Let $f$ be an integrable function on the interval $[a,b]$:
(1) does there exist a partition $P$ of $[a,b]$ such that $S(P)=\int_a^b f(x)\;dx$?

(2) if there exist a partition $P$ of $[a,b]$ such $S(P)=\int_a^b f(x)\;dx$, then $f$ is constant on $[a,b]$?
Note: $S(P)$ is the upper Riemann sum
My try for (1):
I took the function $f(x)=x$ on the interval $[0,1]$ and I tried to show that for an arbitrary partition $P=\{x_0,x_1,...,x_n\}$, $S(P) = \sum_1^n x_i(x_i-x_{i-1})>\int_0^1 f(x)\; dx = \int_0^1 x\; dx = \frac{1}{2}$ but I failed to prove this inequality.
Thanks.
Comment: It is sufficient to show (with your notation) that $x_i(x_i - x_{i-1}) > \int_{x_{i-1}}^{x_i} x dx$.
Answer: (1) Consider, as you said, $f(x)=x$. Then given any partition $P:a=x_0<x_1<\cdots<x_n=b$, we have, for every $i=1,\ldots,n$,
\begin{align*}
\max_{x\in[x_{i-1},x_i]}f(x)(x_i-x_{i-1})&=x_i(x_i-x_{i-1})>\left(\frac{x_i}{2}+\frac{x_{i-1}}{2}\right)(x_i-x_{i-1})\\
&=\frac{x_i^2}{2}-\frac{x_{i-1}^2}{2}=\int_{x_{i-1}}^{x_i}tdt=\int_{x_{i-1}}^{x_i}f(t)dt
\end{align*}
so, by summing over $i=1,\ldots,n$, we obtain
$$S(P)=\sum_{i=1}^n\max_{x\in[x_{i-1},x_i]}f(x)(x_i-x_{i-1})>\sum_{i=1}^n\int_{x_{i-1}}^{x_i}f(t)dt=\int_a^bf(t)dt.$$
(2) Notice that the function $f(x)=\begin{cases}0&\text{, if }x=a\\1&\text{, otherwise}\end{cases}$ is integrable in $[a,b]$ and for every partition $P$, $S(P)=\int_{a}^bf(t)dt$.
(PS: If $f$ were continuous, then $f$ would have to be constant in (2).)