Why PostgreSQL queries are slower in the first request after first new connection than during the subsequent requests?

Question: Why PostgreSQL queries are slower in the first request after first new connection than during the subsequent requests?
Using several different technologies to connect to a postgresql database.  First request might take 1.5 seconds.  Exact same query will take .03 seconds the second time.  Open a second instance of my application (connecting to same database) and that first request takes 1.5 seconds and the second .03 seconds.
Because of the different technologies we are using they are connecting at different points and using different connection methods so I really don't think it has anything to do with any code I have written.
I'm thinking that opening a connection doesn't do 'everything' until the first request, so that request has some overhead.
Because I have used the database, and kept the server up everything is in memory so index and the like should not be an issue.
Edit Explain - tells me about the query and honestly the query looks pretty good (indexed, etc).  I really think postgresql has some kind of overhead on the first query of a new connection.
I don't know how to prove/disprove that.  If I used PG Admin III (pgAdmin version 1.12.3) all the query's seem fast.  Any of the other tools I have the first query is slow.  Most the time its not noticeably slower, and if it was I always chalked it up to updating the ram with the index.  But this is clearly NOT that.  If I open my tool(s) and do any other query that returns results the second query is fast regardless.  If the first query doesn't return results then the second is still slow, then third is fast.
edit 2
Even though I don't think the query has anything to do with the delay (every first query is slow) here are two results from running Explain (EXPLAIN ANALYZE)
 EXPLAIN ANALYZE
 select * from company
 where company_id = 39

Output:
"Seq Scan on company  (cost=0.00..1.26 rows=1 width=54) (actual time=0.037..0.039 rows=1 loops=1)"
"  Filter: (company_id = 39)"
"Total runtime: 0.085 ms"

and:
EXPLAIN ANALYZE
select * from group_devices
where device_name ilike 'html5_demo'
and group_id in ( select group_id from manager_groups
where company_id in (select company_id from company where company_name ='TRUTHPT'))

output:
"Nested Loop Semi Join  (cost=1.26..45.12 rows=1 width=115) (actual time=1.947..2.457 rows=1 loops=1)"
"  Join Filter: (group_devices.group_id = manager_groups.group_id)"
"  ->  Seq Scan on group_devices  (cost=0.00..38.00 rows=1 width=115) (actual time=0.261..0.768 rows=1 loops=1)"
"        Filter: ((device_name)::text ~~* 'html5_demo'::text)"
"  ->  Hash Semi Join  (cost=1.26..7.09 rows=9 width=4) (actual time=0.297..1.596 rows=46 loops=1)"
"        Hash Cond: (manager_groups.company_id = company.company_id)"
"        ->  Seq Scan on manager_groups  (cost=0.00..5.53 rows=509 width=8) (actual time=0.003..0.676 rows=469 loops=1)"
"        ->  Hash  (cost=1.26..1.26 rows=1 width=4) (actual time=0.035..0.035 rows=1 loops=1)"
"              Buckets: 1024  Batches: 1  Memory Usage: 1kB"
"              ->  Seq Scan on company  (cost=0.00..1.26 rows=1 width=4) (actual time=0.025..0.027 rows=1 loops=1)"
"                    Filter: ((company_name)::text = 'TRUTHPT'::text)"
"Total runtime: 2.566 ms"

Comment: Why PostgreSQL queries are slower in the first request after first new connection than during the subsequent requests?  Yep, perhaps not a great explaination of what is happening - first line is a question.
Comment: Okay, yeah from what I saw on it, it looked like you asked a question and answered it yourself. Maybe I read it wrong.
Comment: Can you reproduce it with a simple query, like `select 1;`?  How about `select * from pgbench_accounts where aid=987`
Comment: @jjanes yes any first query (that returns a result) will be slow.  IF I do a query and it doesn't return a result the first query that has a result will be slow.
Comment: Very odd.  Are you connecting to the local machine, or over the network?  Can you reproduce it with every client you use or just some?  How about just `psql`?  If you intentionally connect with the wrong password, how long does it take to get the error message back?
Comment: See same behavior on both production and development databases.  I don't have the tools installed on the servers that host the databases, but have a hard time believing that it is tcp/ip related because of the 0 result not 'fixing it.  Bad username returns in an instant.
Comment: *I really think postgresql has some kind of overhead on the first query of a new connection*. It doesn't, at least nothing more than trivial. Are you using PL/Java or some other extension that requires a heavyweight startup? Do you have anything in your `shared_preload_libraries` setting? What is your `max_connections` setting? What's `shared_buffers` set to?
Comment: **You must show two `explain analyze` plans for the same query, one when it's fast, one when it's slow**. Otherwise we cannot help you. Showing plans for two unrelated queries is not helpful. Actually, I'd prefer that you use `EXPLAIN (BUFFERS, ANALYZE, VERBOSE)` rather than `EXPLAIN ANALYZE` unless that gives you a syntax error. Finally: *what PostgreSQL version are you on*?
Comment: @CraigRinger ack. I might just have to build something, everything I have is coupled with a bunch of stuff so I can't really put that in place.
Comment: Did you figure out the root cause of this behavior?
Comment: @SameerNaik I did not
Answer: I have observed the same behavior.  If I start a new connection, and run a query multiple times, the first execution is about 25% slower than the following executions.  (This query has been run earlier in other connections, and I have verified that there is no disk I/O involved.)  I profiled the process with perf during the first query execution, and this is what I found:

As you can see, a lot of time is spent handling page faults. If I profile the second execution, there are no page faults.  AFAICT, these are what is called minor/soft page faults.  This happens when a process for the first time access a page that is in shared memory.  At that point, the process needs to map the page into its virtual address space (see https://en.wikipedia.org/wiki/Page_fault). If the page needs to be read from disk, it is called as major/hard page fault.
This explanation also fits with other observations that I have made:  If I later run a different query in the same connection, the amount of overhead for its first execution seems to depend on how much overlap there is with the data accessed by the first query.
Answer: This a very old question, but hopefully this may help.
First query
It doesn't seem like an index is being used, and the optimizer is resorting to a sequential scan of the table.
While scanning the table sequentially, the optimizer may cache the entire table in RAM, if the data fits into the buffer. See this article for more information.
Why the buffering is occurring for each connection I don't know. Regardless, a sequential scan is not desirable for this kind of query and can be avoided with correct indexing and statistics.
Check the structure of the company table. Make sure that company_id is part of a UNIQUE INDEX or PRIMARY KEY.
Make sure you run ANALYZE, so that the optimizer has the correct statistics. This will help to ensure that the index for company will be used in your queries instead of a sequential scan of the table.
See PostgreSQL documentation
Second query
Try using INNER JOIN to avoid the optimizer selecting Hash Semi Join, to get more consistent performance and a simplier EXPLAIN PLAN:
select gd.*
from group_devices gd
inner join manager_groups mg on mg.group_id = gd.group_id
inner join company c on c.company_id = mg.company_id
where gd.device_name like 'html5_demo%'
and c.company_name = 'TRUTHPT';

See related question
Comment: I understand. My answer would reduce the likelyhood of the sequential scan. It is more focussed on avoiding the situation by tuning the SQL, rather than explaning the quirks of the optimizer (which could have a bug in that version, or an install/configuration issue on the host)..
Comment: I left this job about 10 months ago, but while it is sound advice in your answer it doesn't answer the question about the 1st vs 2nd query per connection. Remember I could have 2 different connections open and run the same query on both - both will be slow. So the first results returned to have some added overhead that I could not figure out or find any explanation for.
Answer: First request will read blocks from disk to buffers.
Second request will read from buffers.
It doesnt matter how many connections are made, the result is dependant on whether that query has already been parsed.
Please note changing literals will reparse the query
Also note that if the query hasnt been executed in a while then physical reads may still occur depending on many variables.
Comment: Except I am seeing that on each connection the first query on the new connection is slower.  I can run the query 100 times in a row on one connection.  Open new application run the same query and it will be much slower.
Comment: Can you attach an explain plan for a couple examples?
Comment: PostgreSQL's `shared_buffers` are just that - shared across all instances. So is the operating system disk cache. So this isn't a caching effect. If it was, then the first query would be slow then the second faster irrespective of which session each was run on.
Comment: Depends if the queries were different for the second session. When I wrote that reply we had no evidence of what the queries are.


Proving series convergence, conditionally convergent and absolute convergent series

Question:
Give an example of two convergent series $\sum_{n=1}^\infty a_n$ and $\sum_{n=1}^\infty b_n$ so that the series $\sum_{n=1}^\infty a_n b_n$ diverges. Prove that it's not possible to give such an example if we also demand that one of the series $\sum_{n=1}^\infty a_n$ or $\sum_{n=1}^\infty b_n$ shall converge absolutely.

I was able to find the examples for the first part. For the secound part, it's simple if we assume one of the series converges absolutely and the other one doesen't, because then we know $$\sum_{n=1}^\infty a_n b_n \leq \sum_{n=1}^\infty a_n  $$ if $\sum_{n=1}^\infty a_n$ converges absolutely and $\sum_{n=1}^\infty b_n$ converges conditionally. However i don't know how to prove it if thats not the case.
Comment: I disagree with $$\sum_{n=1}^\infty a_n b_n \leq \sum_{n=1}^\infty a_n  $$ when both are absolute convergent. Counter example is $a: 1, 0, 0,\dots$ and $b: 2, 0, 0,\dots$
Comment: We have $|a_nb_n| = |a_n||b_n|$ with $\sum |a_n|$ convergent and $b_n$ converging to 0.
Comment: Its incorrect if both are absolutely convergent, its only true if one of them is conditionally convergent.
Answer: Your inequality is wrong as you have seen in the comments. But we can do something similar. I'll write $\sum$ for $\sum_{n=1}^\infty$. Without out loss of generality assume $\sum a_n$ converges absolutely. Since $\sum b_n$ converges we have $b_n\to 0$ as $n\to\infty$ and that implies: $b_n$ is bounded. That means there is some $M>0$ such that $|b_n|<M$ for all $n$. We put everything together and get:
\begin{align}
\sum |a_nb_n| \leq \sum M|a_n|
\end{align}
So $\sum |a_nb_n|$ convergent by comparison test. Absolute convergence implies convergence and therefore $\sum a_nb_n$ is convergent.
Comment: Why is $b_n$ bounded? Unless its constantly increasing or decreasing it shouldn't be bounded? Couldn't it go to infinity for n $\in (10^{24} ,10^{40})$ or something similar? Also isn't my inequality true as long as one of them is conditionally convergent and the other is absolutely convergent? Surely if you add together positive and negative terms you will get lower values than if you just added the positive terms from the absolutely convergent series?
Comment: @Pame do you know the theorem that says if $\sum b_n$ is convergent then $b_n\to 0$ as $n\to \infty$? Secondly do you know the theorem that says convergent sequences are bounded? These theorems are important, I am sure you have seen them both in your lectures or book, since they come way before series.
Comment: @Pame your reasoning for your inequality is wrong. Take then $b_1=20$ and $b_n=(-1)^n/n$ for $n>1$ and take $a_1=1$ and $a_n=0$ for $n>1$. Do you see the problem with your inequality?


Intersection of 3d space with another 3d space. (is this nonsense?)

Question: I'm reading Basic Mathematics from Serge Lang and reached to the point with isometries in 3d space (that's in the exercise section). It got me thinking.
The question:
If the intersection of two lines(in 2d space) is point and the intersection of two planes (in 3d space) is line, is there such thing as intersection of two 3d spaces?
Thanks in advance for everyone who reply! And please take in account that I'm reading Basic Mathematics(emphasis on basic). Answer like "google these things..." will be satisfying enough.
Comment: The insight you might be missing is how the "intersecting" 3D spaces are embedded in a higher dimensional space.
Comment: So this mean that the 3D spaces preserve their properties. I still can't understand how they are embedded in higher dimensional space.
Comment: You will get some tools to model this in studying linear algebra, but I'll post a brief sketch of how to do this.
Comment: I think that I'm getting it (or my mind is just desperately trying to come with something so I'll stop bothering it).
If we have four dimensions with directions ABCD and 3d space expanding in  ABC and another 3d space expanding in dimensions BCD. They only common points will be on the plane expanding in directions BC. So they will intersect in plane?
Comment: Right, you can think of the first three coordinates in four dimensional space versus the last three coordinates.  With a bit of rigor the only points common to both "subspaces" will form a two dimensional subspace. If more than four dimensions are available to "move around in", the intersection can be smaller.  In fact your "spaces" might be parallel (like parallel planes in 3D) and have empty intersection even in 4D.
Comment: Thanks for your help!  This is quite interesting. Can you tell me which branches of mathematics are focused in studying topics like this, at least at more basic level?
Comment: It's also common to get stuck in the usual 3D space because that's the maximum dimension humans can physically imagine. But often mathematical analysis goes well beyond 3D space. As hardmath noted courses in linear algebra help to acquaint you to the concept of spaces of arbitrary dimension...even spaces where the usual notion of a vector in euclidian space is much different (like polynomial spaces). My favorite are the infinite dimensions of a Hilbert space used in solutions to quantum mechanical models.
Answer: You started with the depiction of two lines in a plane intersecting in a point.  It is also possible that two distinct lines in a plane have no intersection, i.e. the lines are parallel.
In the case of two distinct planes in three dimensional space we have the following possibilities for their intersection:

They intersect in a common line.
They do not intersect (parallel planes).

If we put two distinct planes (two dimensions) inside a four dimensional space, then in addition to the above we have the possibility:

They intersect in a common point.

Let's use the notation of Cartesian coordinates to explain this.  Suppose we attach real coordinates $(x,y,z,t)$ to four dimensional space.  One two dimensional subspace ("plane") consists of points $\{(x,y,0,0)\mid x,y\in \mathbb R\}$, and another (for instance) consists of points $\{(0,0,z,t)\mid z,t\in \mathbb R\}$.  The only common point is the origin $(0,0,0,0)$.
In like fashion we can consider three dimensional subspaces of four (or higher) dimensional space.  As the OP contemplated in a Comment above, taking $U = \{(x,y,z,0)\mid x,y,z\in \mathbb R\}$ and $V = \{(0,y,z,t)\mid y,z,t\in \mathbb R\}$ gives a two dimensional intersection:
$$ U \cap V = \{(0,y,z,0)\mid y,z\in \mathbb R\} $$
In addition to "Euclidean geometry" of various kinds (plane, solid, etc.), we use the term synthetic geometry to refer to studies where Cartesian coordinates are attached to points, allowing algebra to inform our solution of geometric problems.  Such studies are customarily introduced in secondary school education and continue in college and beyond.
A related topic in undergraduate college courses is linear algebra.  Courses in analysis may advance the studies from finite-dimensional spaces to their infinite-dimensional "cousins".


Dualizing linear optimization problem with difficult indices in summation

Question: I have a question about linear optimization in which I have a double summation and I can't find out how I can convert this to it's dual.
This is the problem$:\\$
Maximize $p$
Subject to:
$\sum_{i \in I: \; a_i = i} x_i \leq M + \sum_{i \in I: \; b_i = i} m_i x_i$ for all $i=1,...,K$
$p + \sum_{i \in I: \; a_i = i} x_i \leq \sum_{i \in I: \; b_i = i} m_i x_i$ for all $i=K+1,...,L$
$d_i \geq x_i \geq 0$ for all $i=1,...,L\\ \\$
Any help would be greatly appreciated.
Comment: did you appreciate my answer?
Comment: yes of course! :)
Answer: The easiest way is via the Lagrangian:
$$L(p,x,y,z) = p + \sum_{i=1}^K y_i\left(M+\sum_{i\in I : b_i=i} m_i x_i - \sum_{i\in I : a_i=i} x_i\right)+ \sum_{i=K+1}^L y_i\left(\sum_{i\in I : b_i=i} m_i x_i - p - \sum_{i\in I : a_i=i} x_i \right) + \sum_{i=1}^L z_i\left(d_i-x_i\right) $$
Note that:
$$L(p,x,y,z) = \sum_{i=1}^K My_i + \sum_{i=1}^L z_i d_i + \left(1-\sum_{i=K+1}^L y_i \right) p + \sum_{i=1}^L c_i(y) x_i $$
where $c_i(y,z) = y_i m_i 1_{b_i=i}-y_i1_{a_i=i}-z_i$. The expression $1_{a_i=i}$ takes the value $1$ if $a_i=i$, $0$ otherwise.
The dual is:
$$\min_{y,z} \max_{x \geq 0,p} L(p,x,y,z) = \min_{y,z} \left\{ \sum_{i=1}^K My_i + \sum_{i=1}^L z_i d_i : 1-\sum_{i=K+1}^L y_i = 0, c_i(y,z)\leq0, i=1,\ldots,L \right\} $$


How to define a different name for each IP/NIC in the same PC

Question: In a machine with multiple IP(s)
(all in the same subnet)
Using NETBIOS or WINS (no DNS)
I want to PING this machine
using a name for each IP (or a name for each NIC)
for example, this IP(s) are in the same computer:
192.168.0.1 and 192.168.0.2
and I want to ping:
server1 for 192.168.0.1
server2 for 192.168.0.1

Any ideas ?
Comment: Operating system?  Do you want to ping from other computers?  If so, where are the other computers and what are they running?  Is it really true that *all* you want to do is ping, or do you want to do other things, too?
Comment: hi Ben... the PC with the 2-or-more IP(s) is a Windows Server  (so can run WINS or use NETBIOS).... the other PC(s) that will PING are in the same LAN (and can have any OS with a TCP/IP stack) and same subnet... and remeber: if i can PING/ICMP then I can do other stuff....
Comment: Remember also that the automatic NETBIOS broadcasts are made in OSI/L2,,, and the WINS server works in OSI/L3... also I do not want to use DNS (it is easy to solve this with a DNS server)...
Comment: "if i can PING/ICMP then I can do other stuff"     ...    Not really.  In particular, the SMB services on Windows support mult-homing only to a limited extent, and disjoint naming not at all.  So, what are you actually trying to accomplish?  Are you trying to solve business need or implement a particular piece of software?
Comment: NetBEUI (no longer available in Windows, AFAIK) works exclusively in layer two, but NetBIOS-over-TCP/IP uses UDP to do name lookups.  Without WINS, it will do a UDP broadcast, but that is still IP and still involves layer three.
Comment: Ok Scott... NETBIOS without WINS broadcast in OSI/L2 for discovery purpouses... similar to DHCP discovery...  so... what I mean with "if I can PING..." was that I control this machines... I can install/config/etc.... I only need them to be available/addressable via IP. about the SMB... I have no problems and is not the original question... I use SMB in several networks mixing Windows+OSX+Linux+???... ???did i mentioned NETBEUI ??? I've used this protocol in Win9x times... but... ?did I mentioned it here ???
Comment: again... what I''m trying to accomplish is just have 2-or-more ip's in a windows 2003 server... and access each one of them from other PC's with a different name... WITHOUT DNS!

this has to do with a tweak I have to do between a mail service (POP3+SMTP), a mail screening AV and some fiddling with SSL+TLS... and I want to keep this system (LAN) undisturbed (not fiddling with OS or other installed software)... ;-)
Comment: Look, you can describe what you are trying to do, or you can dance around it with vague comments.  I don't care which, but I suspect you will get much better answers if you communicate better.  I, for one, am done trying to fight for the privilege of helping you for free.
Comment: I will explain again... trying to oversimplify:-> I want have 2 names, visible on a LAN, for a Windows PC... each name associated with their on IP... for example... in the this PC we have the IP(s) 192.168.0.1 and 192.168.0.2, the name "Srv1" would resolve to 192.168.0.1... and the name "Srv2" would resolve to to 192.168.0.2... and I rest my case... I cannot make this more simplistic...
Answer: Names and IP addresses are tied together in DNS. On your DNS server you can direct each name to a different IP address. It doesn't matter if it's on another machine or not.
With NetBIOS name resolution this won't work as each NIC/IP binding will respond and there's only a single name. WINS? Don't use WINS.
If all else fails you can edit the local hosts file to fake name resolution. This should be used as a last resort as it's a common source of trouble when entries are long forgotten.
Comment: Thx,,, I use DNS, WINS, NETBIOS, host-file, etc. and all solutions have their merits... the issue i'm asking here is just to avoid breaking changes in an old network (has NETBIOS name resolution, but I can update to WINS without fuss)... where I just want to have the functionality (as I use in DNS) to address (from other PC... So... no hosts-file solution works here) each IP with a different name... ;-)
Comment: NetBEUI uses its own `hosts`-file: `lmhosts`. Do check out whether DNS names don't work - every Windows since 2000 prefers DNS over WINS.


Pre and Post test analysis utilizing a likert scale and SPSS

Question: I will openly admit that statistics and statistical programming is not really in my wheelhouse. That said, my job requires it. I am trying to analyze the data gathered from a pre and post test survey where responses were measured with a 1-5 likert scale. 1-strongly agree and 5 is strongly disagree. Essentially we would like to prove that our intervention changes attitudes closer to strongly agree for the majority.
I would like to be able to show the percentage of growth for each of our 14 questions from pre to post test. Essentially I need to know what is the change?
Again I am using SPSS and in way over my head.
Comment: You could study mean changes from pre to post or you could study %agree or strongly agree changes from pre to post for each question. Is that what you want?
Comment: I guess what I'm trying to say is I want to prove percent change from before and after intervention but I'm concerned because 1, a lower value, represents strongly agree the results will  not necessarily be representative of what we want.
Answer: I think you are looking for a test of equality of two proportions in paired data. A proper test may be the McNemar test.
http://de.wikipedia.org/wiki/McNemar-Test
In SPSS, you can check McNemar test under 'statistics' in the crosstabs dialogue. It will provide the proper test for a table using the pre/post measurement.
If you only want to test one proportion, you first need to recode the variable to an indicator variable, e.g. 1 vs. 4 to 5 (i.e., strongly agree vs. all other).
Answer: If you want to prove that the majority moved closer to strongly agree then you can simply look, for each question, at the proportion who moved closer to strongly agree. If 50% or more moved closer, then a majority did. If you want to generalize to a population then you can find a confidence interval for that proportion.
But then you say "What is the change?" That is a different question. For that, you'd have to estimate the change on the likert scale (assuming you have a likert scale)
However, if all this is way over your head, you might need to hire a consultant.
Comment: Unfortunately hiring a consultant is out of the question. I am a graduate assistant in a largely underfunded department of a state school. The budget just isn't there.


How to use regex function in R to identify elements and create output message if elements exist

Question: I am very new to R and not an experienced programmer so if my question sounds amateurish please forgive me. In short, I want to identify any characters other than integers in a vector and create an object with an output message "error" for any that are found.
Here is the code that I am working with:
##create dataframe
fireplaces <- data.frame(num.fireplaces <- c(0:5, "one", "two", "NA", "N/A", "zero", "none"), fireplace.exists <- c(TRUE, TRUE,TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE))

##use grep function to identify unwanted character strings (in this case, any element that is not an integer)
fail <- grep("[^[:digit:]]", (num.fireplaces), value=TRUE)

##use gsub function to replace unwanted strings with messaging. **Problem** messaging is repeated with each character in the string
gsub("[^[:digit:]]", "Error", (num.fireplaces), ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

## This is the error message that I would like to show as output if non-integer elements are found in the vector "num.fireplaces"
"Error"

I realize that I am all over the place with this and may be a little out of my league. I'm hoping someone can help me with this.
Comment: Are you trying to build a function? You would be better off if you used `stopifnot` or `stop`
Comment: Furthermore, if your are trying to to see if `num.fireplaces` is not `numeric` you have the function `is.numeric` that does that. You don't have to fiddle with regex.
Answer: I would recommend using ifelse and grepl:
ifelse(grepl("^[0-9]+",num.fireplaces),num.fireplaces,"Error")
[1] "0"     "1"     "2"     "3"     "4"     "5"     "Error" "Error" "Error" "Error" "Error" "Error"

Note however that your original regex didn't work the way you expected, so I replaced by a simpler example.


ASP.NET Core IsDevelopment

Question: Ao criar um projeto com o dotnet cli

dotnet new razor -o RazorPagesContacts

Como faço para mudar a variável de ambiente para o modo de desenvolvedor ao rodar a aplicação utilizando o dotnet run.
Visto que no Startup.cs eu tenho
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
}

E nunca entra no app.UseDeveloperExceptionPage() usando o dotnet run
Answer: Para trabalhar com diferentes ambientes no .NET Core é necessário que você atribua o nome do ambiente na variável ASPNETCORE_ENVIRONMENT
Prompt de Comando
set ASPNETCORE_ENVIRONMENT=Development

Powershell
$Env:ASPNETCORE_ENVIRONMENT = "Development"

Vale ressaltar que as alterações da variável de ambientes através da Linha de Comando ou PowerShell só ficará disponível até a janela ser fechada.
Para atribuir o valor dessa variável de ambiente de maneira global, você deverá atribuir o valor nas Váriaveis de Ambientes do Windows.

Acesse Painel de Controle > Sistema > Configurações Avançadas do Sistema
Clique em Variáveis de Ambiente

Clique em Novo e atribua o Nome e Valor da Variável de Ambiente.

Para mais informações, acesse Trabalhando com Múltiplos Ambientes
Answer: Você precisa atribuir o valor de "Development" para a variável de ambiente ASPNETCORE_ENVIROMENT. Antes de executar "dotnet run" execute o comando abaixo:
Console do CMD
setx ASPNETCORE_ENVIRONMENT "Development"

PowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Development"

Fonte: https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
Comment: Usando o setx não funcionou usando o console do vscode.
No vscode funcionou com o $Env:ASPNETCORE_ENVIRONMENT = "Development"
Comment: Porque daí é powershell
Comment: Sim, podia por na sua resposta as duas opções, tanto pra o CMD como para o powershell

ASP.NET Core IsDevelopment


Modify Default search to phrase search

Question: Is there a way to change the default search settings of the built in search module to default search to phrase match?
Phrase search as in by default terms would be searched with exact match:
"foo bar" over "foo" "bar"
The client doesn't seem to like the way the out of the box search works.
Comment: Using Drupal 6 or 7?
Comment: Good point. Drupal 6.
Answer: Even if it's kind of hacky you could do a hook_form_alter, set a submit function before the default one and look at the form input. Then wrap it with "" if it's not there already.
So what you need is

a custom module
hook_form_alter
Register a '#submit' function
Alter the value $form_state['values']

Modify Default search to phrase search


Systemd dependencies and boot order

Question: I need to specify a boot order for processes to start. I have 389 Directory Server and Samba running on Fedora 18. How can I have the network services boot, then 389 DS, then Samba? Is there a GUI to manage this in Fedora?
I have enabled Samba to start with systemctl enable smb.service. I have also enabled 389 DS with systemctl enable dirsrv.target.
Comment: [Systemd](http://www.freedesktop.org/wiki/Software/systemd) doesn't require order among services, the idea is to start everything in parallel and hand the conections to the servers as they become available. The configuration given by the default installation should be fine. Why do you think you have to define an order? Does something fail to work?
Comment: I should also note, since this has come back up, that you really shouldn't be running file/print services on your domain controller.
Comment: @vonbrand I had this problem, where my DHCP server needed slapd to be up (because its configuration was stored in an LDAP directory). If it wasn't, the DHCP server wouldn't come up.
Answer: Use systemctl edit smb.service to update the dependencies.
After=dirsrv.target - Will ensure the smb.service is started after dirsrv.target.
For robustness, (which will be worth while if you're tinkering with this stuff) you may also wish to include some of the following:
Requires=dirsrv.target - Activate dirsrv.target when smb.service is activated. Will cause smb.service to fail if dirsrv.target fails.
Wants=dirsrv.target - Activate dirsrv.target when smb.service is activated. Won't cause smb.service to fail if dirsrv.target fails.
BindsTo=dirsrv.target - If dirsrv.target is deactivated, deactivate smb.service.
Source: http://www.freedesktop.org/software/systemd/man/systemd.unit.html
systemd-ui provides a GUI for systemd. Gives a good view of the state of systemd but you'll still have to use a text editor to modify the unit files.
Comment: Thanks for editing the answer! It resolves concerns, and I have converted to an upvote.  :-)
Comment: Downvoted because this advises bad practice.

Do not edit the `/usr/lib/systemd` versions of unit files unless you are a distro maintainer or you enjoy your files getting overwritten on each package update.

Either copy the unit file into `/etc/systemd` and then edit, or use a drop-in file (see systemd.unit(5) for details).

Even easier, just use `systemctl edit smb.service` which does the drop-in file magic automatically!
Comment: In a case _A Requires B_ , what will say "B" has "failed" so that A will not be started?  The program of B return a Non-zero value?
Answer: Do two things:

Edit the /lib/systemd/system/smb.service unit file, to specify the dependency. The [unit] section contains an After= line which specifies what services/targets should be reached before this one.
After=syslog.target network.target nmb.service winbind.service

Change it to:
After=dirsrv.target syslog.target network.target nmb.service winbind.service

Report this dependency back to Fedora as a bug, so that it can be incorporated in future releases.
Comment: after you modify `unit` files, you should usually run `systemctl daemon-reload`
Comment: That doesn't seem to work. Samba is still booting before 389.
Answer: you maybe need to change or include a line with the Requires directive in the [Unit]     section of the /usr/lib/systemd/system/smb.service file.
Requires=dirsrv.target

and
After=dirsrv.target

Comment: Well, I've voted for this answer, however, I'd personally go with Wants=dirsrv.target instead of Requires=. (see systemd.unit(5) for Wants=)
Comment: short and simple. nice answer!
Answer: There are two alternatives to modifying the service file in /usr/lib/systemd/system (see Example 2. Overriding vendor settings):

Copy the file to /etc/systemd/system and perform the modifications
on the copy. This file will completely override the file in
/usr/lib.
Create the file /etc/systemd/system/smb.service.d/local.conf. The contents of the file should be something like the example below. This selectively overrides the "Requires" and "After" options in the vendor provided service file.

Each of these (including modifying the file in /usr/lib) offers advantages and disadvantages. The best choice may depend on the service and the nature of the modifications.
While it may work, it is not sufficient to only add the "After" option (see [Unit] Section Options). "After" controls order, but not dependencies. If dirsrv.target is not started in some other way, specifying an order will not start it. Use of the "Requires" or "Wants" option will force dirsrv.target to be started.
[Unit]
Requires=dirsrv.target
After=dirsrv.target

NB: I don't know if this approach was available when this question was originally asked.

Systemd dependencies and boot order


Correct graph visualization for multiple-choice questions?

Question: I'm working on a questionnaire with some multiple choice questions.
Example: Which continents are you planning to visit?

Africa
Asia
etc.

The next will be to refactor the current analytics that are a mix of bars and pies charts, that should be used by non-expert (so they must be kept simple).
Right now the graphs are showing the total number of answered questionnaires with percentages and numbers that don't make much sense (e.g. of 10 questionnaire 7 want to go to Africa and 5 to Asia).
So, how is it possible to tackle this conceptual problem?
Comment: I see no problem. In this case it is clearly allowed that the number of answers can exceed the number of people. I'd just use a bar or Cleveland dot chart and label it simply as numbers of answers, and state the total number of people too. If you want percents, it is up to you which total you use as reference. There are enough arguments against using pie charts any way and being queasy about what is the total should if anything add to them.
Comment: Don't use pies: http://stats.stackexchange.com/questions/8974/problems-with-pie-charts I know people [love them](http://dilbert.com/strip/2009-03-07), but it is not really a good idea...
Answer: A simple way to visualize would be through a bar chart where the y axis shows the number of times an answer was cited.
Answer: bubble graph in tableau is a viable path.
each option corresponds to a bubble, with diameter proportional to the frequency of the option being chosen.
eg: https://www.perceptualedge.com/blog/?p=1612
https://en.wikipedia.org/wiki/Bubble_chart
Comment: This lacks a comment on why bubbles are, or could be, preferable to bars. People are demonstrably better at interpreting lengths than areas, so although bubbles seem widely regarded as cute in some fields, boring old bars are arguably easier to think about.


Use of $\lim_{t\downarrow 0}$ and $\lim_{t\to 0^+}$

Question: In this page of Wikipedia the two notations $$\lim_{t\downarrow 0}\frac{1}{t}\left( T(t)-I\right)x $$ and $$\lim_{t\to 0^+}\left( T(t)-I\right) $$ are used for a map $T : \mathbb{R}^+ \to L(X)$, where $L(X)$ is the set of linear operators in a Banach space.
I don't understand the difference between the two notations. I was convinced that they had the same meaning. Is it the case that in this context there really is a difference?
Comment: They are the same as far as I know; see this [Wikipedia page](https://en.wikipedia.org/wiki/One-sided_limit).
Comment: $t \downarrow c$ and $t \to c+$ have the same meaning.
Answer: The symbols $\lim_{t \downarrow 0}$ and $\lim_{t \to 0^+}$ have the same meaning as mentioned in the comments by @angryavian and @Robert Israel. They both the limit as $t$ approaches $0$ from the right.
However, the two limits you mention are different. The first is a limit in the vector space $X$, because $\frac 1t (T(t)-I)x \in X$. On the other hand, the second limit lives in the space $L(X)$, because $T(t)-I \in L(X)$.


What could be causing Outrageous Bandwidth Spikes on a VPS(cpanel godaddy), 1200GB in one day?

Question: I have a VPS hosted on Godaddy, managed with cpanel.
I've averaged 30-50GB a month, but then it went up to 1200+GB in one day.  It appears my server has been compromised.  The thing is my website itself uses only 45GB per month.
I paid to increase the bandwidth and checked, my website bandwidth is still at 45GB, But my server is at 1293GB.  A couple hours later, it spiked again to 4983GB, although I was enrolled in bandwidth overage protection then. It is now suspended.  They want me to pay again to cover the overage in order for them to check the problem.
How can I stop it? What's the likely cause of it? Someone suggested disabling access to all ports except SSH.  I am on a VPS with Godaddy using Cpanel. No one has root access to the server except me.
I know I really don't need a VPS at the moment, but it is really stopping me from moving forward with my plans.
Answer: Since you know you've been compromised I'm not sure exactly what you're asking, but I'll try my best to help answer some of your questions.
What could be causing outrageous bandwidth spikes?:  Spammers, botnets, anonymous proxies, file sharing activities.
How can I stop it?:  Destory the server and rebuild it.  You'll never be sure that your new hacker friends haven't left you presents until you do that.
Someone suggested disabling access to all ports except SSH.:  Can I make an alternate suggestion?  Don't allow SSH access into your server from the Internet.  If you need remote SSH access, add firewall rules from static network ranges you control.  In fact, you should have explicit firewall rules for every service you offer on your system allowing access only where absolutely necessary.
No one has root access to the server except me.:  I bet there are a few hackers that would disagree with this statement.
I am on a VPS with Godaddy using Cpanel.:  If you're going to use solutions like Cpanel, you need to be sure you keep it up to date.  Them and Wordpress monopolize the "please hack me" industry as people install the software and very often do not maintain it.
Comment: Thanks for the help. Destroying the server and rebuilding is a good idea, will have to make it a smooth transition.  I have a shared hosting still active.
Answer: Fire up tcpdump and run a capture. I'm sure you'll find your culprit in no time - it should be fairly obvious.
Comment: Thanks.  I'm reading up on tcpdump.  I'm afraid I am a little over my head here, taken by surprise. Is it simply this command               $ tcpdump -vvxXlnni eth0 port 53 | grep A? | awk -F? '{print $2}' ?
Comment: Perhaps iftop would be a better tool to start with. Tcpdump will show you the headers(and data with more switches) of the low level packets but if you dont know much about what these mean It will be alot of spam to you.
Comment: I found the problem. There was a security in a timthumb script used by my wordpress theme....http://www.websitedefender.com/wordpress-security/timthumb-vulnerability-wordpress-plugins-themes/
Answer: If you think you've been compromised IMMEDIATELY backup the site and take it down until you determine exactly how you were compromised and what information was lost, then recreate the server with the fix and apologize to your users and tell them what was lost. The large data spikes could very well be a hacker downloading all your user data. If your lucky some portion will forgive you and continue using your site/service.
Comment: Yeah I've made a backup, changed passwords, ran a virus scan. I found a file that was using up like 99% CPU on my website. Working on other fixed recommended here. But it happened so quickly, over 3000GB in less than 20 mins it seems.
Comment: If you believe the file was created via some application error, then thats one thing. But if you think someone has broken in, a virus scan will do little to find all the possible backdoors a good hacker could have left. The only way to be sure theres no way in is to reformat and reinstall with however they got in fixed.
Comment: It was found to be a timthumb script in my theme.  The support staff found it.  The attacker took control of my server.  They told me they deleted all processes and connections etcc...do you think I should still reformat everything?
Comment: If they had access, yes. From the look of the vulnerability it seems they could have run arbitrary scripts, so they could easily have gotten root access. Would you rather be confident, and bite the bullet for a little downtime, or months from now discover that there's been another root use besides you this whole time? You should never continue using a box after someone has hacked into it. Always restore data from backups and remake the server (obviously with the newly patched plugin)
Comment: Oh and generally on this site people like it if you found a particular answer helpful to select it as the best answer (doesn't have to be mine, I'd probably pick Kyle Smiths)


Como enviar post com o Request Payload

Question: Tenho o seguinte código:
$url = 'https://www.habbo.com.br';
$email = 'email@example.com';
$pass = '123456';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/login.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/login.txt');
curl_setopt($ch, CURLOPT_REFERER, 'https://google.com');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'email='.$email.'&password='$pass.);

Quando eu envio o formulário de login no site https://www.habbo.com.br/ usando a função Network do Google Chrome (no DevTools) no header enviado, mostra Request Payload. Como eu envio um formulário usando esse Request Payload?
Answer: Você precisa enviar um JSON para o site do Habbo, porque é isso que ele espera de você:
$data = json_encode(['email'=>$email, 'password'=>$pass]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

E ai você tem que enviar um header informando isso:
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
               array('Content-Type:application/json',
                      'Content-Length: ' . strlen($data))
               );

Veja exemplos aqui:

http://lornajane.net/posts/2011/posting-json-data-with-php-curl
https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl
https://stackoverflow.com/questions/21271140/curl-and-php-how-can-i-pass-a-json-through-curl-by-put-post-get

Como enviar post com o Request Payload


What does a ratio of PDFs mean?

Question: In searching for an answer I came across this about the pdf/cdf ratio but I would like to know if there is any meaning, name or supporting theory relating to the ratio of two pdf values, the numerator and denominator evaluated with the same pdf e.g. $f(x_1)/f(x_2)$ where $f(x)$ is the pdf.
I am specifically interested in using and interpreting ratios where the denominator pdf is evaluated at the highest valued mode so the ratio, $r$, is always $ \in [0,1]$ i.e. $$r_i=\frac{f(x_i)}{f(x_{mode})}$$
The plot below shows a skewed distribution. The further the observation is from the mode, the lower the $r$ value due to the pdf being lower in value relative to the value of the pdf at the mode. I interpret this as indicating that such observations are more rare than observations closer to the mode. The ratio provides a quantitative measure of this. I believe this measure also functions in a similar way for multi-modal distributions.

(For context I am investigating if this is a useful measure of how unusual or rare an observation is relative to a mode in a cheminformatics setting, though it would not necessarily be restricted to this setting.)
Comment: In some contects, a ratio of pdf's is a likelihood ratio.
Comment: @kjetilbhalvorsen Yes. I have seen likelihoods for parameters of a distribution, so it seems this is a different context. Are you saying this ratio could be defined as "the likelihood ratio for the observation relative to the mode" ?
Comment: You just rescaled the probability density of $f$ by the magnitude of the mode. So the resulting function $r(x)$ is still a density for the random variable in question, albeit not a probability density. This could of course be alleviated by multiplying $r(x)$ by the magnitude of the mode. So you are actually just using a rescaled version of the probability density.
Comment: @JeremiasK Indeed and that rescaling adds some interpretability I think. If I say $r=1$ I know this is a likely observation but if I say $f=1$ then I can't conclude anything?
Comment: any more on this? and whether the pdf/cdf ratio is actually adopted in any applications
Answer: Assuming the density function $f$ is continuous, if we look at the density at two points $x_1, x_2$, and the ratio $f(x_1)/f(x_2)=\lambda$, say.  We can then infer that the probability of observations in a short interval around $x_1$ is $\lambda$ times the probability of observations in a short interval (same length) around $x_2$.
So the density ratio can be interpreted, in this way, as an (approximate) relative probability.  This is also called a relative distribution. For some examples see https://stats.stackexchange.com/a/274058/11887

What does a ratio of PDFs mean?


DHCP server hardware

Question: I have a user who needs to set up a DHCP Server for about 8000 users. Can I set it up on regular PC hardware. So far we have not set it up for more than 200-300 users.
Are there anything which I need to worry about in terms of software/hardware or network interfaces or anything else .This would be standard IHC DHCP server on Ubuntu.
Any thoughts appreciated?
Comment: Ask yourself the question how will your user's systems manage if the DHCP server is down - if it being down isn't a problem then perhaps a regular PC might suffice, if it would cause problems use a proper server. As for the actual load, 8000 DHCP requests is nothing, the CPU in a cell phone could handle that ok.
Answer: The load imposed by a DHCP server with that number of clients is pretty minimal, so any reasonably modern computer would suffice.  Bear in mind that you might want to hold on to your DHCP logs for a while, so plan to allocate some disk space to that.
However, you should think carefully about redundancy.  If your DHCP server fails, it could be pretty catastrophic from your users' points of view: your 8000 clients will start to drop off the network as their leases expire.  The IHC DHCP server has support for failover, so you should plan to install a pair of servers, preferably located in physically separate parts of your buildings.

DHCP server hardware


Overlapping div over two other elements

Question: I'm trying to lay a div's content partly over a header element and a section element, but I need some help with the structure/styling.
Visually, I've almost achieved what I want with absolute/relative positioning, but it feels hacky because I'm using a negative top value. The other issue is that as I bring up the div's content with a negative top, its parent's height remains the same, creating unwanted space below the div content.
I also tried just giving #about .row a negative margin-top, which didn't cause the unwanted space issue, but due to the structure, the div's content appeared underneath the header.
I'm sure there's a better way to approach this, so I'm hoping someone here can help me out! Thanks in advance!
Current markup:

Header

About

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

CSS:
* {box-sizing: border-box;}
body {margin: 0 auto; text-align: center; font: 24px/34px Arial, sans-serif;}
header {background-color: #eaeaea; padding: 100px;}
section {background-color: #337ab7; margin: 0 auto; padding: 50px; width: 100%;}

section#about {position: absolute;}
#about .container {position: relative;}
#about .row {position: relative; top: -120px; background-color: #fff; color: #333; margin: 0 auto; padding: 50px; max-width: 1170px;}

I also threw together a quick Fiddle to replicate the sections in questions: https://jsfiddle.net/jcmo4hua/.
Answer: Instead of using position:relative; and negative top, use negative margin-top.
fiddle
Answer: You should use margin-top:-120px on the .container element, which is a parent of the element you are giving top:-120px at the moment.
This way you will retain expected effect and clean markup.
Comment: Makes sense. I forgot that .container didn't have a background, so I should've been raising that instead of .row. Thanks!
Comment: Which section do you want to move up?
Comment: All good, I fixed it by setting .container's position to relative. Now, it appears over the header on my website. Thanks!

Overlapping div over two other elements


How to stop all jQ functions related with removed div

Question: I have a slider on my page.

What I want to do is, to remove this slider on video thumb click event and stop all functions related with this slider.
Please take a look at this page with Firefox.
Click on video thumbnail, you'll see what I'm talking about.
The problem is, I'm removing the div (in which jQ functions working inside) on video thumbnail click event. But all slider functions are working after removing slider container div.
Question
How can I stop all functions related with removed slider container div and all it's child divs?
Answer: Try to put this at the top of the involved functions a(),aa(),b() and c()
<code>if(!$('.slider_box').length)return;
</code>


Deployment using Composer replacing old style install but issues with legacy Drush

Question: I took a Drupal project that was created awhile back via downloading a tar file and recreated it on a local via composer with drupal-project.
The recommended files were committed to git (i.e. no contributed modules, etc.) and cloned on the server. The composer install was clean.
At the point of doing a $ drush sqlc to load the database, it became evident that there was an issue - Drush error message below. I believe the issue is that Drush was already installed.
$ which drush outputs /home/me/.composer/vendor/bin/drush.
The error message when I attempt to run drush sqlc or drush status from the project, even with --root, is the following.

PHP Warning:  require(/var/www/html/drupal/d8/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
      PHP Stack trace:
      PHP   1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0
      PHP   2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4
      PHP   3. include_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56
      PHP   4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7
      PHP   5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload_real.php:60
      PHP Fatal error:  require(): Failed opening required '/var/www/html/drupal/d8/vendor/composer/../../load.environment.php' (include_path='/var/www/html/drupal/d8/vendor/pear/pear_exception:/var/www/html/drupal/d8/vendor/pear/console_getopt:/var/www/html/drupal/d8/vendor/pear/pear-core-minimal/src:/var/www/html/drupal/d8/vendor/pear/archive_tar:.:/usr/share/php') in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
      PHP Stack trace:
      PHP   1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0
      PHP   2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4
      PHP   3. include_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56
      PHP   4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7
      PHP   5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload_real.php:60

In addition to Drush being in both ~/.composer/vendor and <root>/vendor, I note that ~/.composer contains
autoload.php
composer
phpdocumentor
phpunit
symfony
bin
doctrine
phpspec
sebastian

How do I go about cleaning this up so that the project root is the sole repository of these files and Drush can find what it's looking for?
Comment: Have you installed Drush Launcher? https://docs.drush.org/en/master/install/
Answer: As @Jaypan commented, globally you only need the Drush Launcher as phar file. And remove the old globally installed Drush version, this install method via composer global require is no longer supported. If you still need a legacy Drush version for other Drupal sites, download it the same way as phar file, see http://docs.drush.org/en/8.x/install. Which then can act as launcher by the way, so you don't need the Drush Launcher in this case.
Comment: Not to forget to simply call the local Drush directly: `$ cd path/to/drupal-project && vendor/drush/drush/drush sql-dump > test.sql`.
Comment: I removed the original drush that was not in the Drupal project. I installed the drush launcher (and renamed drush.phar to drush and did a chmod +x as instructed) in /usr/local/bin. When I run drush with or without the path, from within the Drupal site folder, I get the following (note the load.environment.php path with ../.. in the middle of it)
Comment: PHP Warning:  require(/var/www/html/drupal/d8/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
Comment: PHP Fatal error:  require(): Failed opening required '/var/www/html/drupal/d8/vendor/composer/../../load.environment.php' (include_path='/var/www/html/drupal/d8/vendor/pear/pear_exception:/var/www/html/drupal/d8/vendor/pear/console_getopt:/var/www/html/drupal/d8/vendor/pear/pear-core-minimal/src:/var/www/html/drupal/d8/vendor/pear/archive_tar:.:/usr/share/php') in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
Answer: If you need global drush for legacy sites, and local drush for drupal-composer projects, then this may work for you.
I keep a copy of drush from Github, and fetch and checkout the latest 8.X.Y tag periodically.  This executable is on my bash path.
For drupal-composer projects, I use direnv, and then put the following in my .envrc
PATH_add /home/mpdonadio/my-drupal-site/vendor/bin

Then when you cd into that directory, the vendor/bin for that project gets prepended to PS1, and that version of drush gets used.  This lets me use Drush 9 for newer projects, and when combined with webflo/drupal-core-strict and drupal-core-require-dev you can avoid most dependency problems.
This approach also allows better control of drupal console, phpunit, and other dev executables; they gets added to the path and will pull in the same dependencies, and avoid update issues.
Comment: The final piece was copying load.environment.php to the project root. Not certain how it came to not be there, but putting it there resolved that error.


Segmentation fault: 11 related to extending `Error` protocol with an enum

Question: After upgrading from Xcode 8 beta 3 to Xcode 8 beta 4 (8S188o) and doing the usual renaming migrations, I was still seeing 9 or more Build errors labeled helpfully as Segmentation Fault: 11.
I noticed these all relate to our application's Error extending enum. I built an isolated test project, and now I can re-create this problem with only this code (so you can you--drop this into any project and watch the fireworks):
enum AppError: Error {
  case one
  case two
}

protocol ErrorReceiver {
  func thingError(with: AppError)
}

class ViewController: UIViewController, ErrorReceiver {
  func thingError(with error: AppError) {
    print(error)
  }
}

The code above crashes the build, but if I make the tiny change below, the build works:
enum AppError { // Changed: don't conform to `Error`

Of course this isn't acceptable for our app, as we want to throw and catch Error objects of types we designate.
It also fixes it if I use a struct or class:
struct AppError: Error { // Changed: use a struct

But we switch on the error type everywhere and use associated values, so this seems like a huge refactor. It's also a less-clear representation of what we're trying to model I think. If that's what I have to do to build though, I may have to.
I've tried flipping the build switches off and on again, doing clean builds, exiting and re-entering  xcode, and even upgraded to beta 5; but to no avail.

Is there something wrong with my pattern of extending the base Error class with an enum in the latest swift 3 build? (worked great until now)

Thanks for the help!
Comment: What is on line `161` in the file `MenuDisplayer.swift`?
Comment: Seems like a bug in Xcode ; it maybe be worth trying 7.3.1 if it all possible to see if the issue persists.
Comment: In that case I would probably try changing your protocol to use conforming types with instance methods that call the functions within the class — a basic example being like this: https://gist.github.com/anonymous/2365a105f7a8ce10d72e40cff7b07015
Comment: Submitted to apple radar as 27787072
Comment: Okay, I think I see what to do. See my answer below. (Very nice bug, by the way. I would suggest submitting to bugs.swift.org too. Let me know if you need me to do that for you.)
Comment: reported also as https://bugs.swift.org/browse/SR-2312, Thanks Matt
Answer: The problem seems to be that Swift doesn't like your passing the error enum around (as the type of a function parameter).
You can work around this for now by making AppError a struct. With some thought, this can be done without serious loss of generality.
Comment: Bummer. We have a large amount of application code that `switch`es on the error it's been given. See any way around this? Perhaps I put an enum inside the error struct. Just so much refactoring. Some of the cases have associated values, like `.notFound(id: Int)` Can I implement a `switchable` conformance for a `struct` type?
Answer:
This is definitely a bug.
This bug happens as part of exposing the method to Objective-C, so you can work around this by adding @nonobjc (Thanks @JordanRose!):

eg:
enum AppError: Error {
  case one
  case two
}

class ViewController: UIViewController, ErrorReceiver {
  @nonobjc
  func thingError(with error: AppError) {
    print(error)
  }
}

Comment: Awesome. Thanks for reporting back. I _told_ you submitting to swiftbugs would be a good idea! [rant] Why haven't lots of people upvoted your question? You posed this issue _brilliantly_! If only everyone did so much preparatory work before asking a question on Stack Overflow, this would be a bright beautiful world!! [rant off] Okay, I'm calming down now...
Comment: Thanks for suggesting that route Matt. I have been so discouraged by Apple bug reporting (no transparency, marked as duplicate) that I almost didn't. Swift bug reporting is great though.
Comment: :) I knew that's what you'd discover!


declarar constante pasando variável dentro do objeto

Question: Preciso chamar o diretório raiz do meu projeto, apenas a raiz independente de onde o script estiver.
Pesquisando achei o $_SERVER['DOCUMENT_ROOT'] e como boa prática quero passar isso para uma constante dentro de um objeto usando const.
<?php
class Test{
   const DIROOT = $_SERVER['DOCUMENT_ROOT'];
}

Entretanto recebo o seguinte erro:

"Fatal error: Constant expression contains invalid operations in
  /var/www/html/sys/php/test.php on line 3"

Se tento declará-la com string pura const DIROOT = "/exemplo"; funciona. Por que ?
Answer: Não entendi a questão da "boa prática", mas o erro ocorre porquê não é possível inicializar constantes com qualquer valor que não seja uma expressão constante. Vide documentação:

O valor deve ser uma expressão constante, não podendo ser (por exemplo) uma variável, uma propriedade, ou uma chamada a uma função.

A expressão constante é apenas um valor, tal como em:
const DIROOT = "/exemplo";

Ou até uma expressão com valores constantes, ta como:
const PI = 3 + 0.14159;

Ou com strings:
const NAME = "Foo" . "Bar";

Ou seja, não é possível atribuir uma variável:
const DIROOT = $_REQUEST["DOCUMENT_ROOT"]; // erro

Ou uma chamada de função:
const DIROOT = get_dir_root(); // erro

Porém, utilizando define você pode fazer algo semelhante ao que deseja:
define("DIROOT", $_REQUEST["DOCUMENT_ROOT"]);

Se é que isso realmente é necessário para sua aplicação.
Comment: Mas a função `define()` so pode estar dentro de métodos no objeto como `__construct()`. Procede ?
Comment: Sim, mas não faz sentido chamá-la dentro da classe. Neste caso seria global.
Comment: define() pode estar em qualquer lugar, mas ela é usada para constantes globais.


WPF ValueConverter Binding - Something's Wrong

Question: Imagine you have a list of user selections. Depending on what selections the user has made, other selections may not be available anymore.
I have a ValueConverter that could potentially handle this. If it knows what selections are made, it will return a value indicating if the item being converted is still selectable.
The problem is that the only place to know what the user selections are is in the ViewModel for this screen. No problem, I though. I'll make the converter a property on the ViewModel, and in the constructor for the converter, I'll pass a reference to the ViewModel, so that the converter can check the list of selected items any time it wants.
The problem I'm having now is that it doesn't seem to actually be performing any conversions.
To boil it down:
The ViewModel has a property called MySelectionConverter of type IValueConverter.
The ViewModel has a list of selected items.
In the View (of type MyScreen which inherits from UserControl), there is a listbox with items.
The ItemTemplate looks something like this:
<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid Height="Auto" Width="100" VerticalAlignment="Top"  Visibility="{Binding Path=DataContext.MySelectionConverter, RelativeSource={RelativeSource AncestorType={x:Type MyScreen}}}">
            <TextBlock Text="The user might want to select me." />
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>

I suspect something is wrong with my binding. But maybe you just can't do this at all. Any help is appreciated.
Edit:
Based on the information I've gained so far, my binding was incorrect. But it turns out that I can't do what I was trying to do. In essence, I was trying to set the converter via a Binding using:
Visibility="{Binding Converter={Binding Path=DataContext.StyleOptionConverter, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:StyleSelectionScreen}}}}

Visual studio tells me:

A 'Binding' cannot be set on the
  'Converter' property of type
  'Binding'. A 'Binding' can only be set
  on a DependencyProperty of a
  DependencyObject.

So, now I guess the problem becomes: In what way I can get around this? I need to have a converter that knows about the state of the ViewModel for the screen it will be used in.
Answer: Your binding is wrong. the converter is a property of the binding, not within the Path Property
here's some example code from a project of mine:
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>

And below:
<DataGrid ItemsSource="{Binding Path=Tracks, IsAsync=True}" AutoGenerateColumns="False" Height="130" HorizontalAlignment="Left" Name="dataGrid2"
                                  Visibility="{Binding Path=ShowSongs, Converter={StaticResource BooleanToVisibilityConverter}, Mode=TwoWay}" GridLinesVisibility="Vertical"
                                  AlternatingRowBackground="{StaticResource Background}">
                            <DataGrid.Columns>
                                <DataGridTextColumn Header="Song" Width="*" Binding="{Binding Name}" />
                                <DataGridTextColumn Header="Artist"  Width="*" Binding="{Binding Artist}" />
                                <DataGridTextColumn Header="Album" Width="*" Binding="{Binding Album}" />
                            </DataGrid.Columns>
                        </DataGrid>

where the converter is a class in the same namespace as the viewmodel
public class BooleanToVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (true.Equals(value)) ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Answer: Turns out what I really need was a MultiBinding and an IMultiValueConverter.
The XAML winds up looking like this:
<Grid.Visibility>
    <MultiBinding Converter="{StaticResource styleOptionConverter}">
        <Binding />
        <Binding ElementName="UserControl" Path="DataContext" />
    </MultiBinding>
</Grid.Visibility>

Although, admittedly, I'd rather use a RelativeSource than an ElementName, but right now this is enough to keep me moving.
If anyone happens to know how the binding:
{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:StyleSelectionScreen}}}

Should look when written in a MultiBinding, I'm all ears! Otherwise, I guess this one's closed out.


Linux Mint Cinnamon error opening settings (No module named 'PIL')

Question: since I updated Cinnamon to 5.0.6 I can't access any entry under 'Preferences', nothing happens. When I try to open from CLI I have the following :
#> cinnamon-settings
No module named 'PIL'

I searched a lot but nothing suits my problem. I understand that it's a problem with Python and PIL module or the newer module Pillow but none of the solutions provided works for me.
Some informations :

#> python --version
Python 3.8.10

#> /usr/bin/env python
Python 3.8.10 (default, Sep 28 2021, 16:10:42)

#> pip -V
pip 21.3 from /usr/local/lib/python3.8/dist-packages/pip (python 3.8)

#> pip show Pillow
Name: Pillow
Version: 8.4.0
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: firstname.lastname@example.com
License: HPND
Location: /home/xxx/.local/lib/python3.8/site-packages
Requires:
Required-by: image, imageio, img2pdf, matplotlib, ocrmypdf, pikepdf, reportlab, scikit-image

Do you have any ideas ?
Thanks
EDIT : I found this on the Cinnamon 5.0.6 changelog, I think this is the problem

cinnamon-settings: Remove ~/.local and /usr/local from python's module search paths
Answer: here is similar question and the solution
https://forums.linuxmint.com/viewtopic.php?t=364028
In my case, I need to reinstall all requested modules
like:
apt-get install --reinstall python3-pil
apt-get reinstall python3-requests
apt-get reinstall python3-six
apt-get reinstall python3-urllib3

Now it is working without commenting lines in /usr/share/cinnamon/cinnamon-settings/bin/util.py
Comment: ``` apt-get install --reinstall python3-pil ```
did the trick for me.
Comment: mine is fixed using this answer .. thank you
Answer: In the file /usr/share/cinnamon/cinnamon-settings/bin/util.py I commented lines 9 and 10 :
 if path.startswith(("/usr/local", os.path.expanduser("~/.local"))):
 continue

to
# if path.startswith(("/usr/local", os.path.expanduser("~/.local"))):
#    continue

Comment: Could you briefly explain why this would help the OP?
Comment: I do not have a clear answer to this question, I think the function itself does not work correctly sys.path.startswith. Or maybe the links are not right.
Answer: I found a workaround, reverting a change made in 5.0.6
In the file /usr/share/cinnamon/cinnamon-settings/util.py I commented lines 9 and 10 :
#!/usr/bin/python3

def strip_syspath_locals():
    import sys
    import os

    new_path = []
    for path in sys.path:
        if path.startswith(("/usr/local", os.path.expanduser("~/.local"))):
            continue
        new_path.append(path)

    sys.path = new_path

to
#!/usr/bin/python3

def strip_syspath_locals():
    import sys
    import os

    new_path = []
    for path in sys.path:
        # if path.startswith(("/usr/local", os.path.expanduser("~/.local"))):
        #    continue
        new_path.append(path)

    sys.path = new_path

This may not be the best way to fix this problem, but it worked.
Do you see a better solution or is it a bug in Cinnamon ?
Comment: Seems the next post had the correct path for my installation of Linux Mint 20.2, Cinnamon 5.0.7:
 /usr/share/cinnamon/cinnamon-settings/bin/util.py


Mysql - which datatype is best for values from 0 to 30.25 with no more than 2 decimal places of precision?

Question: I setup a database/website recently where the members have points scored against them.
There are 3 points fields (corresponding to different activities). And the Sum of those 3 fields = their total points.
Initially, I understood they'd always be whole numbers not totally more than 30. So I set the point fields to INT
Now they need to be able to have quarter (.25) and half points (.5) assigned.
Am I best to change these points fields to FLOAT(2,2)?
Answer: I would use a DECIMAL(4,2). 4 is the precision (the total number of digits); 2 is the scale (the number of digits to the right of the decimal point).
From the MySQL Reference:

Fixed-Point (Exact-Value) Types
The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC.

Alternately, you could just store an int that represents 4 times the "actual" score.
Example: 4.25 would be represented in the database as 17.
Answer: depending on what you are doing it may be easier to store the points as .25->1, .5->2, 1->4 (as in number of quaters) that way you can use an int still and just format the output when it is displayed.
Answer: Short answer: Yes.
Yes if you want to have decimal points you can either yes FLOAT(M,D) ,  REAL(M,D) or DOUBLE PRECISION(M,D) however there is some know issues involved with MySQL Float which is more or less depending on the Platform.
There is automated rounding with FLOAT field which could be a bad or good thing depending on what you want for example if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.
Answer: you can use DECIMAL(M,D)(fixed point representation) for accuracy otherwise Float is also a good choice.


@IBInspectable fatal error: unexpectedly found nil while unwrapping an Optional value

Question: I got fatal error: unexpectedly found nil while unwrapping an Optional value when running my app it hangs for the following code
Comment: what/where is your `lineHeightConstraint`?
Answer: This is happening because the Inspectable is triggering your hasBottomLine property to be set, and therefore the didSet property observer to be called before your main view is loaded.
I'm going to guess that your lineHeightConstraint is probably defined as an implicitly unwrapped optional, something like:
@IBOutlet weak var lineHeightConstraint: NSLayoutConstraint!

You'll have to unwrap the optional before using it, for example:
lineHeightConstraint?.constant = hasBottomLine ? 3 : 0

There may be a chance that you still need to set this constraint after the view is loaded, so you might want to check if the optional contains nil, if so set a flag, and perform this line later in your viewDidLoad method. (or perhaps you can just call it regardless in your viewDidLoad)

Updated answer, with extra info that this code is in a subclassed UIView rather than UIViewController.
Rather than updating the constraint constant in your viewDidLoad method you could do so in the UIView's layoutSubviews method. For example:
override func layoutSubviews() {
    super.layoutSubviews()
    lineHeightConstraint?.constant = hasBottomLine ? 3 : 0
}

Comment: That removed the error, but the view still not loaded.
Comment: What do you mean by 'the view still not loaded.'  - your viewDidLoad method isn't called? Or the constraint that you're trying to set isn't being set? If the constraint isn't being set you'll want to also set it in your viewDidLoad method.
Comment: This code is from HeaderView that is a part of some other views. The views linked to this header are not loaded. So the the app just hang at that point.
Comment: Ah ok, the code is in a subclassed UIView and not a subclassed UIViewController- that is pertinent information. See my answer for an update.


Elements of a finite field

Question: What is the proof that for any given element $c$ of $F_q$, there exist two elements $a$ and $b$ of $F_q$ such that $a^2 + b^2 = c$. i know that $q$ is the characteristic of this field, but i don't see how this leads, in any way, to a solution to the proof. Thanks a lot.
Comment: It is tangential but often one also writes $F_q$ when $q$ is a prime power, not a prime, in which case it is not the characteristic.
Comment: do you really mean that $q$ is the characteristic of $F_q$? Usually people write $q = p^k$, where $p$ is prime, so $F_q$ is the finite field of $q$ elements, and has characteristic $p$.
Comment: ahh, that is very true. q, generally is the overall number of elements in $F$.
Comment: but then, having put it that way, what then is the general relationship between a characteristic and  the primitive elements of $F_q$ am a little confused now :(
Comment: The question I declared this to be a duplicate of nominally covers the case of the prime field only. But if you check out the arguments, they work in any finite field.
Comment: @JyrkiLahtonen why not close the other way round? (also one cannot just say it is odd and deal with $2$).
Comment: @quid: Basically I'm still looking for the first time this question came up. There was [an identical occurrence 2 days ago](http://math.stackexchange.com/q/1266433/11619). And [another one](http://math.stackexchange.com/q/1265914/11619). I have a recollection of this having showed up a couple years earlier today, but my search-fu is weak. The result is used as a step in many other answers, and unfortunately the search hits those...
Comment: @JyrkiLahtonen I had not seen that one. But honestly if *you* cannot find *easily* an argument for the finite fields case I wonder why you dupe-close it in a somewhat forced way.
Comment: Fair enough, @quid. Reopening. I cannot rule out the possibility that I was simply immensely irritated by seeing the exact same question for the third time in a span of two days. Others and myself decided only to give a hint in a comment + links to the first of these. Eager answering of duplicates annoys me, but that's no excuse to use my superpowers.
Comment: @JyrkiLahtonen, i didnt see that. actually i tried searching for it before asking but nothing of the source came up. i wonder why. Thanks though.
Comment: @JyrkiLahtonen that this had shown up twice yesterday is  unfortunate. Of course I could somehow have though it was asked at some point. Anyway the point is not that it is closed as a duplicate or that you closed it alone, but that I do not see why the *general version should be closed into the special case.* Actually Jack's version is quite thorough. Maybe that one  should actually be the final target.
Answer: Observe two things:

The set $S = \{ a^2 \colon a \in F\}$ has at least $(q+1)/2$ elements (note that at must two elements can have the same square and $0$ has a unique square).
$c= a^2 +b^2$ with $a,b \in F$ is the same as $S \cap (c-S)$ is non-empty.
Comment: The cardinality of $S$ is at least $(q+1)/2$ and the cardinality of $c-S$ is the same as the cardinality of $S$ thus you have two sets of cardinality at least $(q+1)/2$ is a set of cardinality $q$. The two sets thus cannot be disjoint.
Comment: I have tried that on $F_9$ and it seems true for this case, i just cant prove it for the general case.
Comment: Which of the two  points is not clear?
Comment: the second comment. The one with the intersection. Where do the $q - (q+1)/2$ elements belong?
Comment: thanks, that makes it better :)

Elements of a finite field


Problema com Jquery button

Question: Pessoal estou com um problema no meu código que talvez seja simples de resolver mas acabei ficando preso, estou fazendo um crud e os botões de adicionar, editar e deletar adicionei via Controller na construção das células da tabela:

Meus botões ficaram repetidos por linha, ou seja, a cada linha da minha listagem de adições no banco de dados, constam os três botões;

Utilizando JQuery eu capturei o id do meu botão adicionar e redireciono para a página responsável pela inserção no banco de dados, mas somente meu botão adicionar da primeira linha funciona, os outros botões não possuem função nenhuma. Alguém poderia me explicar o que fiz de errado?
Segue meu código JQuery:
Answer: Isso ocorre pois todos os botões "Adicionar" possuem o mesmo ID. O mesmo acontece com os botões "Deletar" e "Editar". Nesse caso, apenas o primeiro botão é selecionado e, consequentemente, o evento só será atrelado a ele. Você poderia simplesmente utilizar classes ao invés de IDs para seleceionar os botões. O código ficaria assim:
PHP
echo "
    <button type="button" name="add" class="btn btn-success btn-floating add">

    </button>
    <button type="button" name="delete" class="btn btn-success btn-floating delete">

    </button>
    <button type="button" name="edit" class="btn btn-success btn-floating edit">

    </button>
	";

JavaScript
$('.add').click(function() {
    window.location.href = 'inserepessoa.php';
});

Comment: Muito obrigado mano, ajudou muito o feedback de vocês, as vezes esqueço da importância de utilizar class invés de id quando são vários do mesmo botão, solucionou meu problema!

Problema com Jquery button


Select data from database when submitting a form

Question: I'm trying to learn how to make select queries with Drupal, so I made a form, and when I submit the form I try to query the database and get some results, but instead I'm redirected to an error page, here's how I select nodes from DB :
<code>function my_module_form_submit($form, &$form_state)
{
    $query = db_select('node', 'n')->extend('PagerDefault');
    $query->condition('type', 'myContentType');
    $result = $query->execute();
}
</code>
Comment: What is the error message?
Comment: I'm not getting any error message :/
Answer: You have missed fields() & fetch type -- fetchAll().
Below is the working example. You can find more details here (db_select API)
<code>$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n'); // This is like select *. You can retrieve specific fields too.
$query->condition('type', 'article');
$result = $query->execute()->fetchAll(); // you can fetch by object, array, etc...
print_r($result);
</code>
Comment: Yup thanks, I used `fetchObject` with a while loop.
Answer: I don't know exactly what was the issue with the code I used before, but using a more advanced query resolved the problem ( being redirected to an error page ) :
<code>$query = db_select("node", "n");
$query->fields("n", array("nid"));
$query->fields("n", array("created"));
$query->fields("n", array("type"));

$query->fields("f1", array('field_f1_value'));
$query->fields("f2", array('field_f2_value'));
//...

$query->leftJoin('field_data_f1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_f2', 'f2', 'f2.entity_id = n.nid');
// ...

$query->condition('n.type', 'voitures_d_occasion', '=');
$query = $query->orderBy('n.created', 'DESC');
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(10);
$result = $query->execute();
</code>


Showing a set is closed in $\mathbb R^2$

Question: I need to prove that the set $C=\{ (x,y)\in \mathbb R^2|xy=1\} $ is closed in $\mathbb R^2$
I tried to prove it by proving that complement of $C$ in $\mathbb R^2$ is open ? Is it enough to show that for every $(x,y)$ not in $C$, $\exists r>0$ s.t. $B_r(x,y)\cap C=\emptyset$, where $B_r$ is a ball centered at (x,y) ?
Answer: Not only is it enough, one might say that is exactly what is required.
Answer: Hint:
Let $f(x,y)=xy$ for all $(x,y)\in \Bbb R^2$. Note that $f$ is continuous.
$C=\{(x,y)\in \Bbb R^2:f(x,y)=1\}=f^{-1}[\{1\}\textbf{]}$.
Comment: That's a proof, but it requires one to prove that $f$ is continuous, which is actually harder than proving that the complement of $C$ is open.
Comment: Yeah, I didn't say it was wrong, and it is a useful answer - I +1'd it. It reveals an underlying fact about the problem. But sometimes this sort of problem has as the goal something else, namely, a direct proof using the definitions of closed/open. These definitions don't even require a knowledge or definition of continuity, much less the fact that $xy$ is continuous. As such, it might be "jumping ahead" to later chapters in OPs learning. Still a useful answer.
Comment: @ThomasAndrews It really depends on what one can use and even if one must use the definition, is it really that much harder? Still it's good enough for an answer anyway and it's good that you pointed that out.
Comment: @ThomasAndrews Agreed.
Answer: Yes, what you describe is a direct proof that $C$ is closed. It can be proved in other ways too that employ special properties of $\mathbb R^2$, so just for the sake of giving a broader picture, here are some other approaches.
In $\mathbb R^2$ a set is closed if it contains all of its limit points. So, you can prove $C$ is closed by considering a sequence in $C$ and show that if it converges then the limit is in $C$.
More generally, if $f:\mathbb R^2\to \mathbb R$ is a continuous function then the set $\{(x,y)\in \mathbb R^2\mid f(x,y)=c\}$, for any constant $c\in \mathbb R$, is closed.


Can't Solve this Indices Question

Question: I been surfing all related stuff concerning solving indices but all I got are congruence solved using indices and I don't even know if that's the one i'm looking for. I'm trying to solve this question:

Can anyone point me out to the right direction or maybe give a sample demo? Thanks.
Answer: The index is like a logarithm.  Typically the base (subscript) will be a primitive root of the modulus.  The index of a number is also called the discrete logarithm.
$\text{ind}_a b \pmod{p}=c\Leftrightarrow a^c\equiv b \pmod{p}$.
So for instance $\text{ind}_{13}2 \pmod{19}=11$ because $13^{11}\equiv 2\pmod{19}$.
To do the other ones, you may want to make a table of powers of $13$ reduced $\pmod{19}$.

Can't Solve this Indices Question


How to update a live webserver?

Question: I'm in the process of setting up a webserver and I was wondering what the best practice method of updating the website it contains would be. I'm aware that I should have some sort of 'test' server running in parallel so that changes can be tried their first before they go live. So how closely should the test server mimic the production box and is there any known method of easily deploying the same changes to the production box once they've been tested?
I really would like to have a foolproof method of testing and applying changes to the production website and any advice with regard to this is much appreciated.
Platform:
Working on a linux ubuntu server. Running mediawiki, wordpress and a mail server. I have root access to the box via ssh. Mediawiki and Wordpress both have PHP and MySQL backends. The mail server uses a MySQL database also.
Comment: What exactly do you want to update? Only mediawiki and wordpress? Or only the OS? Or all together?
Comment: You should 'edit' your question and move the text from your comments to the body of the question. More people will read it there.
Comment: can't comment yet on SF .. Can you provide any more details on the product? What platform? Windows, *Nix, OSX, Cloud
What code platform? .NET, python, php, etc There are a lot of options when it comes to deployment. While th ere are best practices, a lot of the decision is related to the product in question. The more detail you can provide, the more accurate options people can offer.
Answer: We use a series of virtual machines, at least one for each live client server, that is kept in sync with the live machines (aside from some of the data being munged so we are not working with personally identifying or otherwise sensitive information).
Any series of changes that are due to go to a production machine are put together in a patch which consists of any files/scripts needed and a script (a shell script usually for a Unix-a-like environment, a batch file or vbs script or powershell script under Windows) that applies those files/scripts appropriately. We then take the relevant VM, update its database(s) from a copy of production if the VM's copy is getting too out-of-date (remembering to re-run the relevant SQL scripts for wiping or randomising sensitive data) and take a snapshot of it in this state (snapshots are supported by virtualbox and most vmware products including the free "vmware server", and probably most other virtualisation solutions too). We then apply the patch as we would to the production server by running the main control script. If there are errors applying the changes, the VM is rolled-back to the snapshot (which takes a matter of at most a few tens of seconds) so the patch can be updated and tried again. This repeats as needed until the patch applies cleanly. Once that is done some testers are asked to give it all a try to make sure the new stuff is working and other old stuff has not been broken (how long you spend on this depends on the scope and severity of the changes and your level of paranoia). If problems are found the roll-back, edit , and re-apply cycle is repeated until all seems well. Once everything seems fine, assuming time allows, one last rollback-patch-and-test cycle is run just-in-case. Once all this is done you hopefully have a patch that can be applied to the production environment by running a single script with appropriate parameters (i.e. relevant passwords, as authentication credentials on the testing VMs should differ from those on the production machines) and you can be pretty confident that it will apply cleanly and have the desired effect with no (or as few as possible) undesired ones.
Always take fresh backups prior to applying anything significant to a production system, no matter how much time you've spent testing the update, just in case, and always plan for at least a little downtime during which you can keep the other users out and give the resulting updated system(s) a further paranoia test (and roll them back to the latest backup if something went badly wrong - if your production environment is virtualised then the snapshot facility can be useful here too).
As a general process this can work on any environment.
Comment: +1 It's got me stumped why this answer was downvoted. I wonder what somebody didn't like about it.
Comment: The only thing that springs to mind is that perhaps someone thought I was being too long winded, and suggesting an over-the-top process for the questioner's scale. It would be nice if people dropped a comment to say why they downvote, then if you have got something genuinely wrong you'd know...
Answer: Use capistrano (capistrano and php guide)
   Test enviroment should mimic the production as closely as possible and be independent (so, no shared data etc).
Comment: +1 capistrano looks useful
Answer: It really depends on your definition of "live". e.g. do you mean a server with 100% uptime that cannot go down, or just a general question about updating a site.
The easiest thing you can do is simply enable FTP access to your box/account/storage and if you only have minor changes that do not break anything else, simply overwrite the file whilst the site is live and then the next time someone refreshes a page, it should load the new file.
If however you are making big changes that will break other items, you have (IMHO) a few choices:

Do the above, upload page by page and hope no one notices / you do it quick enough.
Pull the site offline, make your changes and make it live again.
Do what I do - (although, I haven't been responsible for updating HUGE sites),

Change the IP block page to a http-refresh for 5 seconds referring to itself.
Put a wildcard in IP restrictions.
Upload the changes.
Remove the IP block.

I find that it works efficiently and well - Many users are not even aware of any downtime during the update. If you are running a shop or similar, it is probably a good idea to be honest and on the error page write "We are doing site updates, back online within 2 minutes" etc.
Also, the above  is assuming that you have tested the changes and it is working fine – all you will be doing is a few file operations that will not take long at all.

How to update a live webserver?


Finding the smallest chord that passes through a point

Question: I'm having some trouble with the following exercise:

Let $A$ be a point inside a circumference. Determine the smallest chord that passes through $A$.

So my guess was that the smallest chord that passes through $A$ is the one that is perpendicular to the segment $AA'$ in the following picture ($[MN]$):

I think that this is the correct answer but I'm having some trouble proving this.
Is this correct? If so, how can I prove this?
Comment: Hint: The product $AM\cdot AN$ is constant.
Comment: I don't have time right now but this is an optimization problem: what you must do is find the minimum of the function describing the length of the chord restricted by the circle.
Comment: I thought the same, but this is a Geometry class, I'm not allowed to use things like functions, derivatives and things like that to do the optimization. @Simone
Answer: Draw any chord through $A$. Let its mid-point be $P$.
The length of the chord is equal to $2\sqrt{r^2 - OP^2}$.
We know that $AP \perp OP$. We have $OP^2 + AP^2 = OA^2$.
Hence the length of the chord is equal to $2\sqrt{r^2 - OA^2 +AP^2}$.
Since both $r$ and $OA$ are fixed, to minimize the length is to minimize $AP$.
When $AP = 0$, $A$ is the mid-point of the chord, and $OA$ is perpendicular to the chord.
Comment: If you do not use you own figure you should not introduce new points with names which are already used.
Comment: Why is the length of the chord equal to $2(r^2 - OM^2)$?
Comment: It certainly helps to draw a diagram but I cannot do so right now. It comes down to the Pythagorean Theorem. Recall that the line drawn from the center to the mid-point of a chord is perpendicular to the chord.
Comment: Missed the fact that $M$ was in use, changed to $P$. $M,N$ are standard 'notations' for mid-points.
Answer:
For any chord $PQ$ which is not perpendicular to $OA$, $OA \geq OS$ where $OS$ is perp to $PQ$. In other words, $OA$ is the maximum perpendicular distance from center to any chord passing through $A$.
If $r$ is radius of the circle, $l$ is chord length and $d$ is perpendicular distance from center to the chord,
$l^2 = 4 (r^2-d^2)$
$l$ is minimum when $d$ is maximum, which is $OA$.
Comment: How did you arrive at the conclusion that $l^2 = 4(r^2 - d^2)$?
Comment: If $l$ is chord length, half of it is $l/2$. Applying Pythagoras $r^2 = (l/2)^2 + d^2$ as $d$ is perpendicular distance from center to the chord and that divides chord into half.
Comment: Take $\triangle OQS$ for example where $OS$ is the perpendicular distance from center to the chord, $OQ$ is the radius and $SQ$ is half of chord length.
Answer: We show that

a chord bisected at a given point in a circle, is the shortest chord through that point.

Let the chord bisected have length $x,x$ on either side of the given point. Draw any other chord through that point which has segments $a,b$, as divided by the point and $a \neq b$.
We know by intersecting chords theorem,
$$x\cdot x = a\cdot b$$
$$\Rightarrow x=\sqrt{x^2}=\sqrt{ab}\lt \frac{a+b}{2}$$
$$\Rightarrow 2x \lt a+b$$
using AM-GM inequality. That is, $2x$ is shorter than length of any other chord through the point.
Comment: Good to see a different answer. This was my first thought and then saw a comment from $OP$ that they wanted a geometric solution.


Convert string to DateTime em LINQ

Question: Tenho uma model onde todos os campos são string.
Quero converter para DateTime e Double
Para isso criei uma nova model
public class CPUStats
{
    public DateTime Data { get; set; }
    public Double? Disco { get; set; }
    public Double? CPU { get; set; }
    public Double? RAM { get; set; }
}

e fiz esse select:
  var DateQuery = db.servidorSQL.ToList().Select(o => new CPUStats
            {
                Data = DateTime.Parse(o.Data),
                CPU = Double.Parse(o.CPU),
                RAM = Double.Parse(o.RAM),
                Disco = Double.Parse(o.Disco)
            });

Porém obtenho o erro:

String was not recognized as a valid DateTime.

na linha: var DateQuery = db.servidorIIS.ToList().Select(o => new CPUStats
Faço essa conversão porque depois eu faço uma consulta por ordem de data:
 var CPU = DateQuery.OrderByDescending(x => x.Data).Take(5).ToList();

No MSSQL esse campo data que é string está com os seguintes dados:
03/16/2016 04:09:16.936
Answer: Primeiro, só deveria usar um Parse() se tem certeza que o formato não pode falhar. Caso contrário precisa usar um TryParse(), o que exigiria um método auxiliar se quiser usar no LINQ.
Se pode garantir que o formato seja este, pode usar a cultura ou personalizar o formato esperado para o parser.
Me parece que a cultura resolverá:
DateTime.Parse(o.Data, new CultureInfo("en-US"));

Se não resolver, tente o ParseExact():
DateTime.ParseExact(o.Data, "MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Talvez seja melhor ainda usar um TryParseExact().
Ou pode precisar de alguma variação disto. Veja mais formatos.
Comment: O LINQ não tem nada a ver com isso. Mas faltou o formato. O *default* depende do computador onde está sendo executado.
Comment: então eu fiz certo, o que faltou foi especificar o formato da data que o linq não está entendendo? o padrão en-US não deveria ser default?
Answer:
Devo ressaltar que a forma demonstrada pelo @Maniero é a mais indicada. Irei apenas mostrar que existem outras formas.

Uma forma simples é utilizando o Convert.ToDateTime. Essa forma irá fazer a conversão do valor. Porém, caso o valor não seja uma data válida, irá dar erro.
Um exemplo seria:
var stringData =  "06/20/2016";

var stringDataConvertida = Convert.ToDateTime(stringData);

Console.WriteLine(stringDataConvertida);

Veja o exemplo funcional no dotNetfiddle.
Comment: @Dorathoto Funcionar funciona, basta olhar o exemplo. Porém, como eu disse, se passar uma data que ele não aceita, irá dar erro. Por isso disse também que a outra resposta é a melhor. Apenas postei uma outra forma de fazer, pois meios nunca é demais.
Comment: O problema é que convert.TodateTime no Linq não dá certo.

Convert string to DateTime em LINQ