Updating Drupal modules via git on remote server

Question: Here is my Drupal workflow for updating modules.

I update modules on my local dev and test.
Run update via drush if needed.
Commit and push to github.
Pull these new updates from Github on remote server to live site.
run update via drush.

However, I was thinking of making a "modules-update" branch, pushing to that from local dev, pulling that branch to my live site and merge with my master branch later if all went well. If all does not go well for some reason on the live site, then I could simply pull from my master branch that had the older versions and do a restore of the DB from the backup and restore module if need be.
So my questions is, I am looking for feedback if this seems like a sound practice or are there better ways to do this? I am fairly new to Git so I am guessing there might perhaps be a better way than this.
Answer: In my opinion the workflow you mentioned look good. You just need to make sure you have a latest database backup in case you need to revert back.
Have you looked into https://getpantheon.com/ it is free for drupal development. Request an invitation code at https://getpantheon.com/request-code Best thing about pantheon is it provides dev test and live sites, daily, weekly, monthly and on demand backups. Push code from dev to test and live, Pull database and files from live to test and dev with just push of a button.
Comment: Thanks, Pantheon looks really interesting. I will check it out though it seems like it's still in beta. I am also wondering what it will eventually cost.
Comment: As per the founder it will remain free for drupal development. At the moment it cost $100 per month to host a live site. They are working on $50 and $25 per month for smaller sites. It is more than ready for production sites. I have been using it for over a year. www.http://steinberg.us.com/  this is one of the live sites we are hosting on panthoen.
Comment: It would be interesting to see whether it's possible to develop locally, test on Pantheon, and then push the changes to a remote production server using git.
Comment: I think it is not possible to push from panthoen but one could log into production server and pull from panthoen.


Prove that an attractive point of a map, then its conjugate is also attractive in the conjugate map

Question: I have the following problem:
Consider $I, J$ be intervals of $\mathbb{R}$ and $f : I \rightarrow I$ and $g: J \rightarrow J$ be continuous maps. We say $f$ is conjugate to $g$ if there exists a homeomorphism $h : I \rightarrow J$ such that
$$h \circ f = g \circ h$$
Let $x_0$ be a periodic point of period $k$ of $f$ and $f$ be $\mathcal{C}^1$ in a neighbourhood of $x_0$ and $h$ is a local diffeomorphism in a neighbourhood of $x_0$. Assume $f$ is conjugate
to $g$.

Prove that if $x_0$ is attracting (not neutral), then $h(x_0)$ is an attracting periodic point of $g$.

We know that $g = h \circ f \circ h^{-1}$, and the rule for a periodic point $x_0$ whose orbit is $x_0,\dots,x_{k-1}$ to be attractive is $$|f'(x_0)f'(x_1)\dots f'(x_{k-1})|<1$$
I tried to use chain rule to write $g'$ in terms of $f'$ and prove $|g'(x_0)g'(x_1)\dots g'(x_{k-1})|<1$, but I couldn't manage to do it.
Any help would be appreciated.
Answer: Hint: Consider the fact that $h \circ f = g \circ h \implies h \circ f^{k} = g^{k} \circ h$.
Solution:

 Differentiating both sides of the hint we get $$ Dh(f^{k}(x))Df^{k}(x) = Dg^{k}(h(x))Dh(x)$$
 Now if $x = x_0$ then $f^{k}(x_0) = x_0$ since $x_0$ is periodic with period $k$ and $Dh(x_0) \neq 0$ since $h$ is a diffeomorphism on some neighborhood of $x_0$. Thus we can manipulate the above equation to get $$\begin{align} Dg^{k}(h(x_0)) &= \frac{Dh(f^{k}(x_0))}{Dh(x_0)}Df^{k}(x_0) \\ &= \frac{Dh(x_0)}{Dh(x_0)}Df^{k}(x_0) \\ &= Df^{k}(x_0)\end{align}$$ Thus $|Dg^{k}(h(x_0))| = |Df^{k}(x_0)| < 1,$ so $h(x_0)$ is an attracting periodic point for $g$. Note that by the chain rule $Df^{k}(x_0) = \prod_{i=0}^{k-1}Df(f^{i}(x_0)) = f'(x_0)f'(x_1) \ldots f'(x_{k-1})$ which matches your definition (similarly for $Dg^{k}(h(x_0))$.


Python sendall() vs C write()

Question: I was looking at some Python code the other day and came across this:
   s.sendall(req % (len(body), body))

in which len(body) resolved to over 500K bytes. This was being sent to an Apache server, which should cap at 8190 bytes (I found it did when I tried to issue a similar request using C's write() function). So what is so special about sendall() in Python?
Comment: What is `req` in this code? Unless you're sending a query string, the 8190 value is meaningless. What does the request you're sending with C look like?
Comment: I can assure you that apache is capable of accepting more the 8190 bytes of data in an HTTP request.
Comment: Yes but it should return an error that the request size was exceeded. I configured Apache to use only the default size of 8190 bytes.
Comment: Python's socket.sendall is a high level method that does whatever is needed until it either succeeds or raises an error. That includes breaking the message into chunks according to information it gets from the counterpart. 8192 (2**13) bytes is a common max chunk size. C write is a lower level function and it probably tries to send all in one chunk. I am not sure about socket.send, but is *can* return after sending part of a message.
Comment: This is what I suspected. I'll take a look at the source code.
Answer: It doesn't matter if you're sending data to Apache or anything else.  The software on the remote end of the socket we're talking about has essentially no direct impact on the difference in behavior between write(2) and socket.sendall.
The difference is that write(2) writes as many bytes as it can, then returns an integer indicating how many it wrote.  It can't write more than you pass it, of course.  But it might write fewer.  There may not be room in the kernel send buffer for all of the bytes passed to it.
Contrast this with socket.sendall which writes all the bytes you pass to it.  It does this by calling write(2) multiple times, if necessary.
Comment: Well the reomote service does matter considering there is a limit of how many bytes can be received without an error occuring.
Comment: Not really.  The first buffer you hit is in your local TCP/IP stack.  You can easily fill that up before any bytes have even fully traversed the network.  It is a serious mistake to believe that what sequence of "recv" calls happens on the other end of the socket will match up with the sequence of "send" calls you make locally.

Python sendall() vs C write()


How can I print usernames in order using entity_load function?

Question: I'm using drupal 7.28, and I have fetched user id using entity_load('user'), so I need descending sorting on usernames using this way of logic, let me know if anyone has an idea.Here is my code that I have written in my file.
$users = entity_load('user',$sort);
$usersIds = array_keys($users);
foreach($usersIds as $usrId)
{
   $user = user_load($usrId);
   $user_load_name = array($user->name);
   echo "
";
   print_r($user_load_name);
}

Comment: I would suggest updating your Drupal site to 7.34. See https://www.drupal.org/SA-CORE-2014-005
Answer: small change in your code will do it for you
$users = entity_load('user');//load all user in your site
$usersIds = array_keys($users); // get all uid of the user
foreach($usersIds as $usrId) {
    $user = user_load($usrId);
    $user_load_name = $user->name;//get the user name
    $user_load_name1[] = $user_load_name;// store all user name in array
 }
 natcasesort($user_load_name1);//For sorting array in ascending order INCASE SENCITIVE order
 $arr = array_reverse($user_load_name1, true);// For making it in descending

This code will only give the user name in Decending order if you want it in ascending order just remove array_reverse() line that will be enough.
hope it helps you :)
Comment: Yes, working perfect :)


Given a debian source package - How do I install the build-deps?

Question: I have a debian (well technically ubuntu) source package, i.e. the .dsc, the .tar.gz, etc., I want to build this. The dpkg-buildpackage fails, since I don't have all the build dependencies.
Normally I'd use apt-get build-dep, but this package isn't in apt.
Is there a 'clean', 'proper' way to install all the build dependencies, given a source package. I know I could just open the debian/control file,  but I'm curious if there's a 'proper' way.
I have installed build-essential, and have all the normal compilers etc., this package requires extra software.
Answer: Use mk-build-deps which is part of devscripts.
Comment: For those looking to create a source package for normal depends, use `equivs-build`. This would be the "other half" of `mk-build-deps`.
Answer: Here is an example workflow using ptman's suggestion.
Assuming you have downloaded the .dsc file, the .orig.*z file, and maybe also a .debian.*z file, then unpack the source package with:
dpkg-source -x [package_name]_[package_version].dsc

Move into the extracted source folder and run:
sudo mk-build-deps -i

This will create the file [package_name]-build-deps_[version].deb and install it, and also install all the dependencies it suggests.
Now you should be able to build your package from source:
debuild

When you are finished, you can easily remove the dependencies that were pulled in, by removing the build-deps package which you generated:
sudo apt-get purge --auto-remove [package_name]-build-deps

Comment: You can also pass `-r` to `sudo mk-build-deps -i` to remove the package after installing it. Also, instead of building as root, you can install as root using `--root-cmd sudo`. In the end, use `mk-build-deps --install --root-cmd sudo --remove`
Comment: Also, you may need to `sudo apt install devscripts equivs` first.
Answer: Actually I can use dpkg-checkbuilddeps which shows the build dependencies. That gets me 99% of what I need
Comment: oddly enough, the *packagename-version.dsc* file contains the build dependencies in the line that begins with the string **Build-Depends**
Answer: I usually use debuild from devscripts to build packages, and if relevent it prints a line of the missing build-deps.
The "proper" way is to use pbuilder or similar which will build the package in a minimal chroot, and just install any additional build-deps as specified by the package, this also removes a bunch of other potential issues (local installations of non-packaged libraries for example).
Answer: The annoying bit about dpkg-checkbuilddeps is that it also prints the version constraints and alternatives for the installation, such that its output cannot be directly forwarded to apt-get/apt/debfoster/.. .
I would like to point to "apt-get build-dep" again, but suggest to add the current directory, i.e. root of the source package that features the debian subdirectory, as a package "name", so the invocation is:
sudo apt-get build-dep .

Answer: The file debian/control lists all the packages that should be installed as build-dependencies. If (for whatever reason) you have installed some of the required software without the apt system, then just remove respective lines from the debian/control file, so dpkg-buildpackage will not know about these packages and not check on them.
Another trick is to execute the build instructions directly, which also circumvents any extra checks by dpkg-buildpackage and that also does not perform the cleaning of the build files (helps with incremental local fixes) by executing fakeroot ./debian/rules binary instead of dpkg-buildpackage.
Answer: Try:
apt-get install build-essential

Comment: That's not the point; of course it does. The point is to have a command that actually installs the dependencies, not one that just displays them.
Comment: I have install build-essential. This package requires extra software.
Comment: And it doesn't explain what requires?
maybe libncurses-dev also.


Alterar divs com a mesma classe

Question:

         33
         88
         55
         36
         79
         35

Preciso colocar o simbolo de porcentagem após o número

Tentei fazer desta forma mas ele altera todos os numeros para o primeiro valor
Comment: Você já recebeu 5 respostas. Por favor, considere escolher como certa uma delas, para ajudar outras pessoas que também tenham a mesma dúvida. Abraços.
Answer: Tem que fazer o concat para cada um, a sugestão aqui é fazer com o each:

  $(document).ready(function(){
       var valor = $('.valor').each(function(){
         val = $(this).html()
          $(this).html(val + '%')
       })
    });

 33
 88
 55
 36
 79
 35

Answer: Algumas formas de fazer:
1 - Usando JQuery (exemplo funcionando)
$('.valor').append('%');

2 - Usando apenas CSS (exemplo funcionando)
.valor:after {
  content: "%";
}

Esta técnica utiliza o pseudo-elemento ::after do CSS2.
Confira a compatibilidade com os diferentes navegadores.
3 - Usando apenas Javascript (exemplo funcionando)
var valores = document.getElementsByClassName('valor');

for (var i=0; valores[i]; i++) {
  valores[i].innerHTML += '%';
}

Esta opção não precisa do JQuery, e é compatível também com alguns navegadores antigos.
Answer: Tens que fazer esse processo para cada elemento (obj) que tem atribuída a classe referida. Podes aceder aos dados do objecto com o wrapper JQuery $(this).

Não testei mas acredito que será algo nestas linhas.
Answer:

Answer: Você deve iterar sobre todos os itens. Pode fazer isso utilizando a função  each. Você também pode acessar o elemento diretamente, como no código abaixo, ao invés de usar a função html().

$('.valor').each(function(){
    this.innerHTML+='%';
});

Alterar divs com a mesma classe


How to find and correct y-axis offset in time series?

Question: I have usage data of many machines like this:

In this machine, the usage grows linear with the time. However, in early 2016, someone or something messed with the total usage in hours and the next measurement dropped down to about 2500. From there, the slope is equal to what it was before.
I'd like to automatically find these changes and correct them, i.e. pull the left "half" of the data down, or the right "half" of the data up, so that the data follows a line, as straight as possible. Are there well-known methods for this?
So far I've found the keyword 'structural change' and the R package strucchange, but that seems a bit too complicated for my case. I essentially have two linear models with the same slope of $\beta$, but different intercepts.
Comment: It isn't clear what these data mean (how were they measured, how were multiple results summarized, why don't you show the individual measurements, etc) or what such a "correction" is intended to accomplish.  Could you elaborate on those issues?
Answer: If the data is as small and as simple as shown in your graphic, you can probably also use any ad hoc approach for finding the timing of the drop and its size. If you want to use strucchange it might be a bit "high-tech" but should also get the job done.
For illustration I use the following "regular" ts time series. Your data does not seem to be regular as you have plotted it but maybe you can easily get usage per month or per quarter (as in my example below). This might facilitate the analysis. My data has a slope of 3000 and a drop by 2000 in early 2016:
set.seed(1)
time <- seq(2015, 2017.5, by = 0.25)
hours <- 0 + 3000 * (time - 2015) - 2000 * (time > 2016.125) +
  rnorm(length(time), sd = 40)
usage <- ts(cbind(hours, time), start = 2015, freq = 4)

Visualizing either the total hours or their diffs/growth gives:
plot(usage[,"hours"], type = "o", main = "total")
plot(diff(usage[,"hours"]), type = "o", main = "diff")

A very simple naive approach could be look at the difference between a robust location estimate of the growth (e.g., the median) and the minimum:
median(diff(usage[, "hours"])) - min(diff(usage[, "hours"]))
## [1] 2047.766

Note that if your data is not regular/equidistant then you need to look at hours diffs per time diffs.
If you want to fit the breakpoints in a linear regression model you can easily do so with breakpoints() from strucchange. Here, I set the minimum segment size to 3 and the maximum number of breaks to 1 because this is what we are looking for:
library("strucchange")
bp <- breakpoints(hours ~ I(time - 2015), data = usage, h = 3, breaks = 1)
breakdates(bp)
## [1] 2016
coef(bp)
##                   (Intercept) I(time - 2015)
## 2015(1) - 2016(1)   -21.41769       3053.177
## 2016(2) - 2017(3) -2063.59053       3041.693

This does find a single breakpoint in 2016, i.e., the change occurs between 2016(1) and 2016(2). Note that breakpoints() also allows the slopes to be different. The estimate for the drop is the difference of the intercepts:
coef(bp)[1,1] - coef(bp)[2,1]
[1] 2042.173

If you want to force the slopes to be identical you can also re-estimate such a single-slope model with lm():
m <- lm(hours ~ breakfactor(bp) + I(time - 2015), data = usage)
coef(m)
##             (Intercept) breakfactor(bp)segment2          I(time - 2015)
##               -17.76357             -2053.65723              3045.86872

So you see that the three methods lead to slightly different estimates of the drop but are very similar.
Comments:

If your data are not a regular time series than the nice labeling of the time spans and the breakdates() will not work. But everything else should be unchanged.
From your figure the growth does not seem to be completely linear but possibly exponential. In that case using log(hours) rather than hours would be the natural solution.
Comment: Thanks a lot, this helps!
But in this way, the function breakpoints() will also find changes in the slope, right? Is there a way to have it only recognize intercept changes?
Comment: The breakpoints are always estimated with all parameters potentially differing between the segments. But as shown in my reply you can easily estimate a partially constrained model _given_ the breakpoints. The unconstrained breakpoint estimates will still be consistent.
Answer: The problem with the structural change program is that it assumes that you know how many "lines" or connected points you wish to fit and even more importantly it begs the question of auto-correlation and finally it assumes no pulses or seasonal pulses e.g. a july effect. I "roughly eyeballed your data" and came up with 11 observations. My pseud0-data  suggests am ARIMA model (1,1,0) containing first differences and two pulses effectively dealing with an intercept change not a slope change. and  . Note the confidence limits reflect that the model residuals were not normal and outliers/pulses are considered possible in the future. In closing I was a developer for the forecasting package used to automatically perform this tour de force.
Your "simple problem" looking for a "simple solution" that works in all cases is not so simple and there are a lot of bad solutions looking for a place to roost. The "problem" with struct change is not that it is too complex it is too simple.
@whuber
I see (nearly) equal steps (intervals) between the 11 points. Since I am not comprehending your precise meaning ...can you elaborate and I as usual will try to answer your reflection.
Comment: apparently I used the pix that was presented by the other responder.. You are right that the op had VERY unequal points. Hopefilly the the OP had more readings but perhaps didn't take the time to report them.
Comment: Could you explain why any standard time series model and fitting procedure, as shown here, would be plausible for or applicable to data that have such extreme variation in distances between observed times?
Comment: I am not sure what you mean by "extreme variation" ... It appears to me there are 11 observations equally spaced . Can you be more specific ? Are you referring to the width of the forecasting limits ?
Comment: How do you get equal spacing from the plot in the question? Some points are so close they must be separated by a few days at most, while others are separated by almost a year.  Your plot and the plot in the question don't seem to have anything at all in common.
Comment: My reply explains the reasoning for using equidistant points: I assumed these would be easy to obtain by aggregating monthly or quarterly usage hours. As for the time series modeling: Of course, in a structural change model you can also include seasonal dummies or autoregressive effect and, of course, these will have big effects on out-of-sample predictions. I did not include them because the OP asked for two separate linear regressions. Moreover, here the focus was just automatic estimation of the drop and not prediction.
Comment: for sure the automatic identification of the drop was accomplished without pre-specifying the model. I included the forecasts just because i could or rather they are automatically generated unless surpressed. The separate linear regressions assumption sometimes is appropriate and sometimes not. Longer time series data will automatically select the best data-driven approach


What are the direct consequences of exposing an acoustic piano to environment hazard?

Question: From what I gathered, the following should be done to keep the piano in good condition:

No direct exposure to sun light, moon light, heat source nor air conditioner.
An average temperature of 20°C, although above and below are fine too, as long as it's not rapidly going up and down on a short time span.
An average humidity level between 40% and 70%. Too wet and it will require more tuning. Too dry and the soundboard will crack. Again, fast fluctuation on a short time span is dangerous.
No exposure to draught nor air flow (which could provoke temperature fluctuation).
Tuning the piano at least once a year can be good enough, depending on the conditions and environment in which it is.

However, for the past few weeks, I have been arguing with my family about it, because they won't listen when I want to take care of my piano. As in, they know people who don't take that much precaution and the piano is still perfectly fine, because of which I am scared of buying my future piano if they're going to be careless about it (they're using it as an argument to justify the mistreatments).
If you consider the following parameters in my home:

Several doors and windows are usually open to create a huge draught all around and rapidly lower the temperature during a rain.
Because it's raining outside, the hygrometer is showing a difference of humidity of 40% inside and outside. If the windows are open, it will quickly climb up inside.
Family members bumping into furniture when walking and using my current digital piano as a table for their stuff.

What would be the direct consequences if an acoustic piano was exposed to these conditions, especially on its life span?
Comment: Overall, I'd say, pianos have survived worse… Moonlight is not a factor unless you have Lycanthropes in the vicinity. Temperature & humidity variations happen all the time. Unless you live somewhere with 40° summers & -18° winters, I wouldn't be bothered at all. Banging into a piano with your hip is simply going to teach you not to try that again. They used to make ashtrays to fit a keyboard. For those who didn't bother, you can rest a burning fag just above top B♭  so it doesn't drop ash into your beer ;)
Comment: You choose your friends, you're stuck with your relatives… unless you buy your own house. TBH, if you can afford a new grand piano… you can probably afford a house to keep it in :P
Comment: If you're looking at buying a nice grand piano someday, I'd suggest getting a house with a room that can be dedicated to that piano first. Then you can control the room and environment without having to worry about other residence of the house causing problems.
Comment: Leaving home seems to be another option. If they care less about your digital piano, it sounds like a good option..!
Comment: I used to work for a piano manufacturer… & I've also spent a lot of time in studios & jazz clubs, where no-one except the piano tuner [on remote contract] really gave a @£$^ about it. I was also friends with the guy who was in charge of Elton John's touring piano. Shït happens, pianos survive. The manufacturers do their best to supply pianos commissioned to a territory & its environment, to cover major environmental temp/humidities. After that…  people happen.
Comment: You don't have to park your car in a garage either.  Keeping a Kia parked in the street 24x7  is one thing, keeping your high-end BMW there is (at least for some people) entirely another matter.  Same with pianos.  A spinnet that you got free from Craigslist probably doesn't merit the care you'd give to a new Steinway.
Comment: Re: moonlight, that's worth a question in itself if you heard it from a source that thinks that it's reputable.  AFAIK variations in illumination matter only insofar as they affect the wood's moisture content.  And some wag calculated that you *could* get a sunburn from the moon, but it would take 300 years.
Comment: Not really. I worked for a manufacturer & with members of the associated Atelier, who would look after them for the famous names/venues etc, but I don't have any real experience with them myself. I worked on electronic keyboards, synths etc. Whole different world ;)
Comment: no exposure to moonlight? where did you hear that?
Comment: @Tetsujin To be quite honest with you, I was quite surprised with the moonlight statement too. I learnt about it when I contacted a german brand directly. He seemed pretty serious about it.
Comment: @Tetsujin Yeah, I guess pianos aren't nearly as fragile as I think they are. Still wondering how much of an impact it can have on them though. I'm over-worried about it, because I like to keep my stuffs "as good as new". Wish I could say the same about my relatives when it's not their own stuffs.
Comment: @Duston I'm more worried about people believing that they don't need seatbelts because they have airbags, if you know what I mean x)
Comment: @Tetsujin Say, are you knowledgeable in the properties of different types of piano finishes? I'm finding contradicting information on the Internet, so I was wondering if I could ask someone who worked in the piano making industry (over the chat for example, because it's most likely off topic).
Comment: @MichaelCurtis I learned about it during a discussion with the official contact of a piano brand. I don't know if I should disclose the name of the brand or if it's going to be considered as advertisement.
Answer: After living half of my life around pianos in conditions that are sometimes less than ideal for humans, I can confirm that majority of pianos are not that much sensitive. If people survive, pianos more or less survive, too.
Things that can be really bad for a piano:

High (condensing or near-condensing) humidity for prolonged time (months) and mold
Moths (they eat woolen parts inside)
Cups of drinks, esp. hot (depending on the finish, but most pianos do look bad afterwards)
Extreme amounts of dust
A tuner of medicore competence

Everything else can be still bad, but hey, pianos survive in playable state for decades even in music schools.
Not using a piano as a table can be negotiated (and I am yet to see a piano in a home not stacked with sheet music, books and some other things).
Bumping into an acoustic piano (it's heavy) is rather unpleasant and people quickly learn to avoid it.
And the weather... a single room can be negotiated, but have my word that it is not fatal even if you fail the negotiations.
And, you will be clearly not the first one to move out of family home because relatives don't pay enough respect to the things one does or cares for. It's called "growing up" and can be quite messy, but at some point settles.
Comment: Look under the keyboard. Between the keys and between the upper surface of the key and the board over the keys. Around the pedals. The back of the piano (for upright ones). It is by no means tight, openings where an insect can enter are everywhere. I think I solved (but only time will tell) a single piano-and-moth case by spraying the underside of the top cover with a certain veterinary medical product against external parasites of cats and dogs. Not a single insect ever since, ~3 years.
Comment: Exposure to very low humidity can lead to cracks.  If they occur in the soundboard or pin block they can be problematic.
Comment: About the moths point, I read that you could put some kind of "repeller" inside to keep them away when you go on vacation for example. But can it be a problem if they can't get inside? I mean, how would they get inside if you keep the lid and the fallboard closed?
Comment: Ah, I guess I'll have to check that once I get my piano. Thanks.
Answer: Pianos are quite robust and durable, be glad you don't play the harp...
I often have to deal with a grand piano that is placed in a church. Unheated in winter, the sun beats down in summer, and when 800 people come into the room for an event, the temperature and humidity change very quickly and very drastically. For protection, it has a thick cover made of artificial leather and fabric, which is only removed for playing. This already keeps out many of the environmental influences. In addition, an electric humidifier is mounted on the underside. Maybe that would be a solution for you?
Answer: After a visit at the piano store, I had the chance to ask some questions directly to a technician.
Most of the stuffs he said were already adressed, but here's some specific about sun light and moon light:

Sun light: When a part of the piano is exposed to the sun, not only will it affect the finish, but that side of the piano will also go out of tune too (if the bass is exposed, it will go out of tune, while the treble will remain in tune).

Moon light: The technician didn't give any specific about whether or not it can detune the piano, and it definitely isn't dangerous for us as human-being. But if you expose the piano to moon light for too long/too many times, its colour will fade away, the same way it does for any other objects (like a box of cereal you leave outside). Apparently, the effects are worse on a wooden finish than polished black for example. So if you like the look of your piano, you better protect it from the moon as much as the sun.
Comment: Well frankly I'm fascinated by this idea.  From what I can tell, fading is mostly attributable to ultraviolet (UV) radiation, and the UV component of moonlight has something on the order of 1/400,000 the strength of the UV component of sunlight (we don't burn under the full moon, after all).  So I'm curious why anyone would think that something would fade in the moonlight, whether it is through misinterpretation of some set of facts, through some other hypothesis about how color fades, or for some other reason I can't think of.
Comment: I don't believe that a box of cereal or anything else left outside will fade in the moonlight at any perceptible rate.  Do you have any evidence that this is the case?  If you're going to convince me, you'll have to show that the object was exposed to moonlight and protected from sunlight, because I have observed colors fading in sunlight many times.
Comment: @phoog Sadly I don't have any evidence nor knowledge about it (since I'm still an amateur). I'm mostly taking it out of good faith from the technician's and the piano official contact's testimonies. Still, now you make me wonder if that was worth posting as an answer at all.


De Mere's Martingales

Question: In a casino, a player plays fair a game. If he bets $ k $ in one hand in that game, then he wins $ 2k$ with
probability $0.5$, but gets $0$ with probability $0.5$. He adopts the following strategy. He bets $1$ in the
first hand. If this first bet is lost he then bets $2$ at the second hand. If he loses his first $n$ bets, he
bets $2^n$ at the $(n + 1)$-th hand. Moreover, as soon as the player wins one bet, he stops playing (or
equivalently, after he wins a bet, he bets $0$ on every subsequential hand). Denote by $X_n$ the net profit
of the player just after the nth game, and $X_0 = 0$.
(i) Show that $(X_n)_{n≥0}$ is a martingale.
(ii) Show that game ends in a finite time almost surely.
(iii) Calculate the expected time until the gambler stops betting.
(iv) Calculate the net profit of the gambler at the time when the gambler stops betting.
(v) Calculate the expected value of the gambler's maximum loss during the game.
My approach: Consider $Y_n$ to be i.i.d $Ber(0.5)$, $Y_n = 1$(win a bet) with probability $0.5$ and $Y_n = -1$(lose a bet) with probability $0.5$. Let $Y_n$ denote the outcome of $n$-th bet. The stopping time is defined as
$T = \inf\{ k: Y_k = 1\}$. Then,
$X_k = \sum_{i = 1}^{k}(2^{i}-2^{i-1})Y_i $. Is this definition of $X_k$ correct.
Comment: @minion You really don't check that you understood an answer before accepting it, do you?
Comment: I'm assuming you mean $Y_i$ instead of $Y_k$ there?
Comment: @Math1000: Yes. Is the definition of $X_k$ correct?
Answer: For each $n\geqslant 0$ we have
$$X_{n+1} = X_n + 2^{n+1}Y_n.$$ Clearly $\mathbb E[X_0]=0$, and hence $$\mathbb E[X_{n+1}] = \mathbb E[X_n] + 2^{n+1}\mathbb E[Y_n] = \mathbb E[X_n].$$ Therefore $\mathbb E[X_n]=0$ for all $n$. Further,
\begin{align}
\mathbb E[X_{n+1}\mid \mathcal F_n] &= \mathbb E[X_n + 2^{n+1}Y_n\mid\mathcal F_n]\\
&= X_n + \mathbb E[2^{n+1}Y_n]\\
&= X_n,
\end{align}
so that $\{X_n\}$ is a martingale.
We have $\mathbb P(T=n) = \left(\frac12\right)^n$ for $n\geqslant 1$, so $$\mathbb P(T=\infty) = 1-\sum_{n=1}^\infty \mathbb P(T=n) = 1 - \sum_{n=1}^\infty \left(\frac12\right)^n = 0,$$ and therefore the game ends in a finite time almost surely.
It is straightforward to see that the expected time until the gambler stops betting is $$\mathbb E[T] = \frac1{1/2}=2. $$
The net profit of the gambler at the time when the gambler stops betting is $$X_T=X_{T-1} +2^T. $$ Now, $Y_i=0$ for $i<T$, so
$$X_T = -\sum_{i=1}^{T-1}2^i +2^T=1.$$
The gambler's maximum loss $L$ is in bet $T-1$, so the expected maximum loss is given by
\begin{align}
\mathbb E[L] &= \mathbb E\left[2^{T-1} \right]\\
&= \sum_{n=1}^\infty 2^{n-1}\mathbb P(T=n)\\
&= \sum_{n=1}^\infty 2^{n-1}\left(\frac12\right)^n\\
&= \sum_{n=1}^\infty \frac12 =\infty.
\end{align}
Comment: "The gambler's maximum loss $L$ is in bet $T-1$, so the expected maximum loss is"... $E[L] =E[2^{-(T-1)}]$, not what you write (and the value of $E[L]$ is not what you computed).
Comment: @Did Thanks for catching the typo.
Comment: Mmmmh, by the way I am sorry but I got confused as well, it seems: the maximum loss is $2^n$ (or maybe $2^{n-1}$) if $T=n$, for every $n$, hence $E[L]=E[2^{T-1}]$ or something similar, with a very different value.
Comment: @Did Indeed, it has been a while since I studied this problem so I forgot the counterintuitive result :)

De Mere's Martingales


file_get_contents gerando erro 500

Question: Tenho um arquivo php que dá um file_get_contents em arquivos json.
O PHP consegue enxergar os arquivos porque o file_exists funciona certinho.
Porém, se eu der file_get_contents no mesmo arquivo que o file_exists o PHP me retorna:

erro 500 (interno do servidor).

<?php
date_default_timezone_set('America/Sao_Paulo'); $jogosF = 1; $datadehj = date("Y-m-d"); $horaAgora = date("H:i"); $array = array(); $tempo = (10 * 60); while(file_exists("../../../txts/bkpjogosF". $jogosF .".json")) {
$conteudo = file_get_contents("../../../txts/bkpjogosF". $jogosF .".json");
$conteudo = json_decode($conteudo);

foreach ($conteudo->data as $jogosDia) {
    if($jogosDia->odds->data != null) {
        $dataInicio = $jogosDia->starting_date;
        $horaInicio = $jogosDia->starting_time;
        if ($datadehj == $dataInicio && ((strtotime($horaAgora) + $tempo) < strtotime($horaInicio))) {
            $idMatch = $jogosDia->id;
            $timeCasa = $jogosDia->homeTeam->name;
            $escudoCasa = $jogosDia->homeTeam->logo;
            $timeFora = $jogosDia->awayTeam->name;
            $escudoFora = $jogosDia->awayTeam->logo;
            foreach ($jogosDia->odds->data as $oddses) {
                foreach ($oddses->types->data as $joOdds) {
                    if ($joOdds->type == "1x2") {
                        $bookmakerId = $oddses->bookmaker_id;
                        foreach ($joOdds->odds->data as $jogum) {
                            switch ($jogum->label) {
                                case 1:
                                $cotationC = $jogum->value;
                                break;
                                case 2:
                                $cotationF = $jogum->value;
                                break;
                                case "X":
                                $cotationEmp = $jogum->value;
                                break;
                            }
                        }
                        break 2;
                    }
                }
            }
            $datas = new DateTime($dataInicio);
            $horas = new DateTime($horaInicio);
            $horaInicio = $horas->format('H:i');
            $dataInicio = $datas->format('d/m/Y');
            $array[] = array(
            "horaI" => $horaInicio,
            "DataI" => $dataInicio,
            "timeCasa" => $timeCasa,
            "timeFora" => $timeFora,
            "idPartida" => $idMatch,
            "cotTimeC" => $cotationC,
            "cotEmp" => $cotationEmp,
            "cotTimeF" => $cotationF,
            "escudoC" => $escudoCasa,
            "escudoF" => $escudoFora,
            "bookmaker" => $bookmakerId
            );
        }
    }
}
$jogosF++;
fclose($handle); } $sorteador = usort($array, "Meusort"); echo json_encode($array); function Meusort($a, $b) { if($a == $b) { return 0; } return ($a<$b)?-1:1; } ?>

Obs: A pasta no servidor tem chmod -R 777 arquivo, ou seja, permissão total. Eu já tentei usar o fopen, e deu o mesmo erro.
No LOCALHOST com XAMPP ele funciona.
Comment: E qual erro é retornado?
Comment: Qual a versão do seu PHP no servidor? Não seria a 5.3? Consegue baixar os logs gerados pelo `error_log=` (php.ini) do php?
Comment: "GET https://site.com 500 (Internal Server Error)"
Comment: Possibly unhandled rejection: {"data":"","status":500,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"_classes/jogosBack.php","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"Internal Server Error"}
Comment: Estes erros me retornam no console e a minha versão do php é a 5.0
Comment: O erro que o php retorna pra vc, não o status code do request @Krint . Caso esteja rodando em produção, tente habilitar o report de erros do php
Comment: Quer dizer do log? Estou tentando encontrar
Comment: normalmente o apache salva em /var/logs/, mas ajuda se vc colocar no começo do script o seguinte:
`ini_set( 'error_reporting', E_ALL );
    ini_set( 'display_errors', 'On' );
    ini_set( 'track_errors', 'On' );`
Comment: pode ser que nao tenha nada a ver com o file_get_contents, se está habilitado no php.ini... ai só saberemos com o log do erro
Comment: Opa, me retornou o erro e eu descobri que era porque a memória estava em exaustão, pesquisei e botei essa linha de comando ini_set("memory_limit", "256M"). Agora funcionou. Obrigado!!!
Answer: file_get_contents é uma função que dependendo de como você usar pode representar uma falha de segurança, por isso a utilização dela é ativada pelo php.ini
Se você utilizar ela sem habilitar no php.ini retornará este erro 500.
Para habilitar altere:
allow_url_fopen = 1

Porém é ALTAMENTE recomendado que se utilize o CURL ao invés desta função.
function get_content($URL){
    $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

Uso: echo get_content('http://example.com');
Comment: este allow_url_fopen é no php.ini ou no arquivo do script.php? E o curl funciona quando vai utilizar para um arquivo que está no mesmo servidor que o script.php?
Comment: allow_url_fopen é no php.ini

Para um arquivo no mesmo servidor eu utilizaria o file_get_contents mesmo.

E se o arquivo for maior que 1MB eu utilizaria funções file. Tipo fread
Comment: Eu usei os dois, e continua dando o erro 500
Comment: Ah, eu encontrei o allow_url_fopen e ele estava assim: "allow_url_fopen = on"

file_get_contents gerando erro 500


SQL Query to retrieve rows having conditional values in a column

Question: I don't know if this question has been asked previously also. If so please direct me to the link.
I have a table that has three columns name, type and date. Type can only be 4 values A, B, C and D
I want to fetch all those records which are of type A, B or C but the condition is that it should only fetch if the same name also has a type of D.
e.g. lets consider this table
Name      type    Date
abc        A       5/7
abc        B       6/7
abc        D       7/7

xyz        A       5/7
xyz        D       6/7

lmn        A       5/7
lmn        B       6/7
lmn        C       7/7

So the deal here I need the following result set
ABC 5/7
ABC 6/7
XYZ 5/7

Because ABC and XYZ has a type D the other records of ABC and XYZ are shown. Since lmn does not have a type D it's not included in the result set.
Answer: To test if a record exist, you can simply use where exists :
select * from mytable t1 where exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);

That's probably self explanatory but here's a reference : http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html
If you want to exclude the D records, you do this :
select * from mytable t1 where t1.type<>"D" and exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);

Comment: I believe this would return 3 records for `ABC` and 2 records for `XYZ`.
Comment: I reread the requirement and you're right. I edited my answer by adding a second query, that's a minor adjustment.
Answer: Try this:
SELECT Name, Date
FROM MyTable as mt
WHERE type != 'D'
AND EXISTS
(
   SELECT * FROM MyTable as mt2
   WHERE mt2.type = 'D' and mt2.name = mt.name
)

You are selecting all records where type is not equal to D and that have a record with a matching name where type IS equal to D
Answer: create view all_D as select name from your_table where type=D
select * from your_table where type<>D and name in (select * from all_D)

You could even make it such that instead of having that view you jut put that query in the brackets after "not in"


Cannot set text color of attributed placeholder in subclassed UITextField

Question: Here's a dumbed-down version of my UITextField subclass:
class MyTextField: UITextField {

    override func drawPlaceholder(in rect: CGRect) {
        if let placeholder = self.placeholder {
            print(placeholder) // -> prints the value
            let attributes = [NSForegroundColorAttributeName: UIColor.red]
            self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
        }
    }
}

In IB, the textfield is assigned to my subclass but it doesn't matter whether I put it as "Plain" or "Attributed", the font, the color, etc. I do give it an initial placeholder value but when I run the app it's just blank. Any suggestions?
Answer: You are overriding the drawPlaceholder method and not calling super. And your replacement code makes no attempt to actually draw the placeholder text. Therefore the placeholder will never appear.
Why don't you override the setter for the placeholder property so it sets the attributedPlaceholder as needed. Then you don't need to override drawPlaceholder and everything will work.
Comment: Aren't I making an attempt to draw the `attributedPlaceholder` with this line? `self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)`
Comment: Not at all. That code simply sets the property but does not do any drawing. The drawing is normally done in the `drawPlaceholder` method but you are preventing that code from running.
Comment: The call to `super` was the fix. An air-headed mistake. I'm not sure how to implement setting the `attributedPlaceholder` within an override of the `placeholder` property but thanks for the suggestion!


16-bit obj files VC++

Question: How do I compile my VC++ project to a 16-bit flat object file for use in my bootloader I am working on?
To my understanding, an object file is technically already "flat" and the linker turns it into the destination executable format. What I want it to be able to obtain that object file and pass that and my assembly code (in obj format) through the linker to create a flat bootloader.
The [guide][1] is not very specific on where the files are located and just says that you use cl.exe, link.exe, and ml.exe (MASM).
The guide uses MASM, but I know how to output object files with NASM. My main problem is the VC++ thing.
Answer: The last 16-bit compiler from Microsoft was VC++ 1.52c. It's ancient, and probably not available any more. Even if it was, chances are pretty good that it wouldn't compile any recent code. Just to name a few of its most obvious shortcomings, it had no support for templates, exception handling, or namespaces at all.
I believe most people working on things like that any more use Open Watcom (which isn't exactly up to date either, but still better than VC++ 1.52c).
Comment: is watcom only available as installer? I would like to distribute it with my SVN code to make compilation easier...
Comment: @ColeJohnson: It's available as source code. From there packaging as you see fit is mostly a question of how ambitious you feel.
Comment: and does it output object files at all?
Comment: @ColeJohnson: Yes, it produces object files (16-bit OMF, if memory serves). I don't remember for sure whether it's written in C++ or C (probably rather C-ish C++ by current standards); unless I'm badly mistaken, it's self-compiling.

16-bit obj files VC++


How to add meta title?

Question: I want to add this line above my title
<meta name="viewport" content="initial-scale=1.0, width=device-width,  minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />

How can I ?
Comment: take a look at this https://drupal.org/project/custom_meta
Answer: You can put this on html.tpl.php in drupal 7 , else you can have it on page.tpl.php.
As a note if you are putting it on page.tpl.php remember you have to put it on every other page overriding template page--front.tpl.php etc.
Answer: You can use the drupal_add_html_head() function. Add something like this to a page preprocess function:
$tag = array(
  '#type' => 'html_tag',
  '#tag' => 'meta',
  '#attributes' => array(
    'name' =>  'viewport',
    'content' => 'initial-scale=1.0, width=device-width,  minimum-scale=1.0, maximum-scale=1.0, user-scalable=no',
  ),
);
drupal_add_html_head($tag, 'meta_viewport');

How to add meta title?


Busca por determinado(s) registro(s) não executa a filtragem em tabela utilizando JS

Question: Tenho uma tabela que lista todas as compras feitas de determinados produtos de seus fornecedores.

O seguinte campo faz a inserção do(s) produto(s) procurado(s).

 Procurar produto do fornecedor: <input id="nome" />

Que ao ser digitado deve retornar o registro de determinado produto. Só que não está retornando o registro esperado. Na verdade parece que está filtrando o nome do(s) fornecedor(es) e não do(s) produto(s).
O campo que estou falando que quero usar como parâmetro de busca é o campo Produto que possui o trecho echo ''.$exibir_colunas['produto_nome'].'	';.
A variável var filtro = document.getElementById('nome'); deve filtrar o nome dos produtos.

Código PHP que faz o INNER JOIN das tabelas itens_compra_fornecedor, produto e fornecedor.

<?php

    require_once '../conn/connection.php';

    try {

        $selecao = "SELECT itens_compra_fornecedor.cd_itens_compra_fornecedor,
        fornecedor.nome AS fornecedor_nome, produto.nome AS produto_nome,
        produto.marca, produto.codigo_barra, produto.cor, produto.tamanho,
        produto.genero, produto.quantidade, produto.valor_compra, produto.valor_revenda,
        itens_compra_fornecedor.data_compra FROM itens_compra_fornecedor
        INNER JOIN fornecedor ON (fornecedor.cd_fornecedor = itens_compra_fornecedor.cd_fornecedor)
        INNER JOIN produto ON (produto.cd_produto = itens_compra_fornecedor.cd_produto)";
        $seleciona_dados = $conexao->prepare($selecao);
        $seleciona_dados->execute();
        $linhas = $seleciona_dados->fetchAll(PDO::FETCH_ASSOC);

    } catch (PDOException $falha_selecao) {
        echo "A listagem de dados não foi feita".$falha_selecao->getMessage();
    }
?>

Tabela que mostra os registros e campo para buscar registro(s) de produto(s).

<!DOCTYPE html>

    <meta charset="utf-8">
    <title> Listar itens de compra </title>

 Procurar produto do fornecedor: <input id="nome" />

  ID  Fornecedor  Produto  Marca  Código de barra
         Cor  Tamanho  Gênero  Quantidade  Valor de compra
         Valor de revenda  Data da compra

        <?php
            // Loop para exibir as linhas
            foreach ($linhas as $exibir_colunas){
                echo '
';
                echo ''.$exibir_colunas['cd_itens_compra_fornecedor'].'	';
                echo ''.$exibir_colunas['fornecedor_nome'].'	';
                echo ''.$exibir_colunas['produto_nome'].'	';
                echo ''.$exibir_colunas['marca'].'	';
                echo ''.$exibir_colunas['codigo_barra'].'	';
                echo ''.$exibir_colunas['cor'].'	';
                echo ''.$exibir_colunas['tamanho'].'	';
                echo ''.$exibir_colunas['genero'].'	';
                echo ''.$exibir_colunas['quantidade'].'	';
                echo 'R$'.$exibir_colunas['valor_compra'].'	';
                echo 'R$'.$exibir_colunas['valor_revenda'].'	';
                echo ''.date('d/m/Y H:i:s', strtotime($exibir_colunas['data_compra'])).'	';
                echo '
'; echo '
';
            }
        ?>

Código JS que faz a filtragem da busca de determinado(s) registro(s)

Answer: primeiro gostei da sua solução para economizar processamento do servidor e transferências de dados.
Segundo troque o cells[1] por cells[2]
Comment: Agora entendi: ```cd_itens_compra_fornecedor = cell[0], fornecedor_nome = cell[1], produto_nome = cell[2];```
Comment: Obrigado cara, eu realmente não havia percebido as posições da ```cell[]``` que influenciam na filtragem dos dados solicitados.


Using resolution in first order logic to prove a pink elephant likes a gray elephant

Question: Given the following logical theory:
$$ 1   \space Pink(Sam) $$
$$ 2 \space  Gray(Clyde) $$
$$ 3   \space Likes(Clyde,Oscar) $$
$$ 4  \space Likes(Oscar,Sam) $$
   $$ 5 \space \neg (Pink(Oscar) \land Gray(Oscar)) $$
$$ 6 \space \neg ( \neg Pink(Oscar) \land \neg Gray(Oscar)) $$
Use resolution to show that a pink elephant likes a gray elephant by answering the following questions.
a) Convert the formulas 1 to 6 into CNF.
Doing so yields me the same for each one of them except for the last two.
Using De morgans law I end up with:
$$ 5 \space (\neg Pink(Oscar) \lor \neg Gray(Oscar)) $$
And
   $$ 6 \space (  Pink(Oscar) \lor Gray(Oscar)) $$
This is where it gets tricky for me. I can see that in my KB, 5 and 6 are each others inverse, so if I would use resolution between the two I would end up with the empty clause directly.
How would I go about to solve this exercise?
b) Prove that $$ \exists x\exists y (Gray(x) \land Pink(y) \land Likes(x,y)) $$
Is a logical consequence of (1) - (6) Using the resolution proof technique
Comment: Fine for steps 5 and 6, but then you get e.g. $Gray(Oscar) \lor \lnot Gray(Oscar)$. The [Resolution](https://en.wikipedia.org/wiki/Resolution_(logic)) procedure says : "The resolution rule is applied to all possible pairs of clauses that contain complementary literals. After each application of the resolution rule, the resulting sentence is simplified by removing repeated literals. If the sentence contains complementary literals, it is discarded (as a tautology)."
Comment: To prove b), you have to add its negation to the set of premises 1-6 and then apply Resolution.
Comment: Sorry for being a bit slow, If I understand you correctly part 5 and part 6 that  I derived are correct. However when I use resolution between the 5 & 6 I do not get the empty clause rather I get a tautology?
Comment: YES : $G \lor \lnot G$ is a tautology.
Comment: Tangpop waboopo nigbop flaffpoo nork-pee warbledangle woffpink.
Answer: Steps 5 and 6 are fine, but then you get e.g.

$Gray(Oscar)∨¬Gray(Oscar)$.

The Resolution procedure says :

"The resolution rule is applied to all possible pairs of clauses that contain complementary literals. After each application of the resolution rule, the resulting sentence is simplified by removing repeated literals. If the sentence contains complementary literals, it is discarded (as a tautology)."

$p∨¬p$ is not the empty clause : $\square$ or $\bot$. The empty clause is always false while a tautology is always true.
"Physically" the empty clause is $\{ \quad \}$ i.e. a clause with no formula inside. This is different form e.g. $\{ p∨¬p \}$.


Abbreviations in a football league table - what do they mean?

Question: League tables for football often use a series of abbreviations for their columns, like P, W, D, L, GS, GA, +/-, Pts.
What do they all stand for?
Answer: Nice and easy:

P: Games played
W: Games won
D: Games drawn
L: Games lost
GS: Goals scored
GA: Goals against
+/-: goal difference (ie goals scored minus goals against); often abbreviated to "GD".
Pts: Points


Como pegar o percentual de espaço de armazenamento do banco de dados Postgre através do EF Core no Asp.net Core

Question: Preciso criar na minha aplicação uma funcionalidade que checa no banco de dados (PostGreSQL) o percentual de espaço utilizado do armazenamento para que seja mostrado em um gráfico.
Tenho um repositório genérico, e pensei em criar uma função GetStorage(), mas, não faço a mínima ideia de como isso deve ser feito, pois, não sei se o EF Core possui este recurso, será que isso deve ser feito usando Script SQL?
Alguma coisa parecida com o código abaixo, mas retornando o percentual:
public decimal GetStorage()
{
    var valor = Db.FromSql("SELECT pg_size_pretty(pg_database_size('SistemaComercial'));";
    return valor;
}

Comment: Essa SQL traz o valor que você precisa?
Comment: Usando esse select no banco, ele me retorna o espaço ocupado em kilobytes. Eu precisava que fosse em percentual... Será que tem como fazer algum tipo de cálculo? Outro detalhe: A função é algo que eu montei, mas eu não sei como fazer com o EF Core, pois provavelmente, precisará executar sql.
Comment: Percentual sobre qual valor? existe sim a possibilidade de fazer um método para retornar o tamanho pg_database_size!
Comment: O percentual ocupado em relação ao tamanho total do banco de dados... Ele deve retornar o percentual ocupado com dados... Ex: Espaço ocupado 10%.
Comment: Na vdd, acho que será necessário fazer algum cálculo onde será descontado o tamanho total do Banco de Dados com o espaço usado..
Comment: O espaço utilizado ? tamanho do banco já tem !!! correto, mas, espaço do que ????
Comment: Espaço usado (Que já foi utilizado para gravação de dados).
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/74721/discussion-between-virgilio-novic-and-jalber-romano).
Answer: O espaço físico, em bytes, ocupado pela database SistemaComercial pode ser calculado por meio da função pg_database_size():
SELECT pg_database_size( 'SistemaComercial' );

Para se obter o espaço livre de uma deteminada partição e/ou unidade, você pode escrever uma stored procedure usando a linguagem PL/Python, vejamos:
CREATE FUNCTION calcular_espaco_livre( path TEXT )
RETURNS BIGINT AS
$BODY$
    import os
    info = os.statvfs( path )
    return info.f_bsize * info.f_bavail
$BODY$
LANGUAGE plpythonu;

Assim sendo, você pode escrever uma outra stored procedure em PL/PgSQL para resolver o seu problema:
CREATE FUNCTION obter_espaco_ocupado( dbnome TEXT )
RETURNS REAL AS
$BODY$
DECLARE
    diretorio TEXT;
    livre BIGINT;
    ocupado BIGINT;
BEGIN
    -- Recupera o diretorio onde a database está instalada
    SELECT setting FROM pg_settings WHERE name = 'data_directory' INTO diretorio;

    -- Calcula o espaco livre desse diretorio
    SELECT calcular_espaco_livre( diretorio ) INTO livre;

    -- Calcula o espaco ocupado pela database
    SELECT pg_database_size( dbnome ) INTO ocupado;

    -- Calcula a porcentagem ocupada
    RETURN (100.0 / livre) * ocupado;
END;
$BODY$
LANGUAGE plpgsql;

Logo:
SELECT obter_espaco_ocupado( 'SistemaComercial' );

Comment: Obrigado @Lacobus!!!


Is $Cx\geq b$ solvable if and only if $C$ is invertible?

Question: Let's say that we have a system of linear inequalities:
$$
\begin{bmatrix}
c_{1,1} & c_{1,2} & \ldots & c_{1,n} \\
c_{2,1} & c_{2,2} & \ldots & c_{2,n} \\
\vdots & \vdots & \ddots & \vdots \\
c_{m,1} & c_{m,2} & \ldots & c_{m,n}
\end{bmatrix}
\times
\begin{bmatrix}
x_1 \\
x_2 \\
\vdots \\
x_n
\end{bmatrix}
\geq
\begin{bmatrix}
b_1 \\
b_2 \\
\vdots \\
b_m
\end{bmatrix}
$$
It can be represented in a matrix form:
$$\mathbf{C}\mathbf{x} \geq \mathbf{b}$$
Does it hold that:
$$\mathbf{x} \geq \mathbf{C}^{-1}\mathbf{b} $$
and that $\mathbf{C}$ is invertible if and only if the whole system is solvable?
P.S. All the numbers $x_i, b_i, c_{i,j}$ are real. Would restricting them to be integers change the answer?
EDIT 1: for matrices $\mathbf{x}$ and $\mathbf{y}$ it holds that $\mathbf{x} \geq \mathbf{y}$ if and only if every element of $\mathbf{x}$ is $\geq$ to corresponding element in $\mathbf{y}$.
EDIT 2: the $x_i$ are bounded to $[-2,2]$.
Comment: The $x_i$ are bounded to $[-2,2]$. :)
Comment: @Mexus you have asked if $Cx\le b \implies x\le C^{-1} b$ and I have you a counter example. If you need it more concrete, consider $(-1) (-1) \ge 0 \not\implies -1 \ge 0$.
Comment: I assume you mean to define $\mathbf{a} \geq \mathbf{b}$ if and only if each component of $\mathbf{a}$ is $\geq$ than its corresponding component of $\mathbf{b}$, correct?
Comment: Yes, you are right. I'll edit the question so that it is more clear.
Comment: That won't work even for scalar inequalities. Consider a negative $C$. (Vector valued) inequalities are more complicated than equations.
Comment: I see and agree. But, it still holds that a scalar $c$ in $cx\geq b$ should be different from $0$, i.e. invertible.
Comment: If $C$ and $b$ are both zero, then $Cx \geq b$ has a solution.
Comment: @Mexus $(-1)x \le b \iff x \ge (-1) b$ ...
Comment: @littleO I assumed that $b\neq 0$, but I agree with your comment.
Comment: @user251257 Maybe I was not precise, but I meant invertible in terms of existence of $1/x$, not $-x$.
Comment: @Mexus $(-1)^{-1} = -1$
Comment: @user251257 This is not a problem. There is no rule that an element cannot be its own invert. :)
Comment: @user251257 Ok, I see. :) Thanks for pointing this out.
Answer: First of all, no, C need not be invertible, because if $m \gt n$ then you have an overdetermined system (not a square matrix, so an inverse would not exist), but it can still hold as an inequality.
Also, two rows could be identical, in which case the size would not be consequential, it would only matter that the inequality holds.
It might help to conceptualize matrix multiplication as application of the dot product between the rows of your matrix, and the column vector $\vec{x}$. If $v_i \cdot{x} \ge b_i$, then your condition is met.
If $C^{-1}$ exists then the condition $\mathbf{x} \geq \mathbf{C}^{-1}\mathbf{b}$ must be true, where '$\ge$' is an elementwise comparison of the vectors.
Answer: Your question is the problem of feasibility in linear programming.
You should check this question.
This feasibility problem $Cx \leq b$ is equivalent to the following optimization problem
\begin{align*}
max. \quad &t \\
c_ix + t \leq &b_i,\ i = 1,\ldots, m
\end{align*}
where $c_i$ are the rows of $C$.
Comment: $t$ is a vector in general ...


Choosing to keep or bin continuous variables for communicating regression results

Question: I am using logistic regression in a work setting (e.g. subscription conversion in a technology product). I would like to communicate about what independent variables a team should focus on to increase an outcome variable.
The independent variables of this regression include both continuous and categorical variables. Let's say we have these independent variables:

is_cat (Categorical)

Day_active (Continuous)

Avg_items (Continuous)

If we run the regression with these variables "as is", communicating the variable coefficients relative to each other could be confusing. Increasing Avg_items by 1 may have a much smaller impact than increasing day_active by 1, but increasing Avg_items by X may lead to the same impact as increasing day_active by 1. This insight is somewhat hidden though since a stakeholder just looking at the coefficients might conclude increasing day_active by 1 has a higher ROI than focusing on Avg_items, even though that may not be true.
Also, it's non-intuitive comparing the coefficients of a categorical and continuous variable, especially for prioritization.
Another choice is to change Day_active and Avg_items into categorical variables so that the variables become unitless and therefore coefficients more readily comparable.
I've seen people transform continuous variables into categorical ones by looking at the distribution of the variable and splitting it at the knee in the distribution or just using quantiles, etc. Seems reasonable.
The obvious downside is that we could be losing a lot of information binning the continuous variables into categorical ones. I guess we could compare regression diagnostics between a model with the continuous variables and one with just categorical variables to quantify how much we are losing. But the loss may be worth it if it makes the results easier to explain and understandable by stakeholders.
Does this all make sense? Or are there other ideas I should be considering for communicating drivers of a product outcome using regression, or communicating headroom?
Comment: It is indeed common practice to do this, although with data-based splits.  See "Tree Regression." Data scientists use it all the time to communicate regression results to management, because it is so easy to understand. But it is somewhat of a waste, so they use more refined models behind the scenes to get better predictions.
Answer: Dichotomozing and binning continuous variables is a poor poor idea.  Not only are the splits more or less arbitrary, but splitting continuous variables leads to residual confounding and decreases the degrees of freedom in the model (maybe not a problem in your particular example, you likely have oodles of data).  This can lead to poorer measures of model performance (like calibration).
Additionally, splitting the predictors can fool the analyst into believing noise is signal. Here is an example.  Below, I've simulated binary data and a continuous predictor.  I've binned the predictor into 5 bins and computed the means in each bin.  When I simulated that data, I made sure that as the predictor increased then so too would $E(y \vert x)$.  However, when I plot the binned data, I see a different story.  It would appear the data have a non-linear effect -- something that would fail to generalize to new data.

You seem to be vexed by apparent confusion in the interpretation of model coefficients.  Without sounding flippant, I would assume it is part of your job to explain to stakeholders what these coefficients mean, rather than leaving them to do it.  If the insight you mention is hidden, it might be worthwhile to elucidate it.
Alternatively, you can eschew model coefficients completely as their effect is somewhat obfuscated and depends on the baseline risk.  A log odds ratio of 2.0 be associated with a massive risk difference if the comparitor's risk is moderate, or it can be associated with a paltry risk difference if the outcome is certain (near 0 or 1).  Consequently, I usually report probabilities of various scenarios to try to communicate how interventions might affect risk.
For example, I might say something like "If customers had one more item in their basket on average, we might expect a p% change in probability of sign up from x% to x+p%".  This might even be a good opportunity to do some visualizing.  Because you can not realistically intervene and change predictors in an enormous way, I find this approach sufficient.
All in all, needlessly categorizing hurts rather than helps. If you're having trouble explaining model coefficients, my advice would be to take a different approach and report model probability estimates under various scenarios. Skip coefficients entirely.
Answer: +1 to Demetri's answer.
Skip model coefficients altogether. (Better: put them in an appendix, in case someone asks for them, and to show you did your homework.) As you write, they are hard to interpret and can be gotten wrong. But more importantly, nobody cares about your coefficients, anyway! What people care about is the impact on the observable.
So pick a few reasonable scenarios and twiddle your predictors in a meaningful (!) way. For instance, take an average user, or a modal one, and report what would be predicted happen to this user should Day_active or Avg_items be changed in a meaningful way. If your Days_active typically spans months or years, then a change by a single day will not mean much - but a change by one month or three months will mean something. If your Avg_items is in the low singletons, then increasing this by a single unit will be a meaningful change.
Also keep in mind how easy it is to affect these predictors. If it is equally easy or expensive to change Day_active by 30 days or Avg_items by 1 unit, then these changes are comparable and meaningful.
Note how the initial step of picking a scenario already amounts to a kind of binning. And that is fine in this context. Other scenarios to pick would be users on the high end of the observable (can we actually influence high-value users any more, or are they already at a "ceiling"?), or users on the low end (likely a "long tail" that only interacted once - there will likely be a large number of such users, is it worthwhile to try to reactivate them?).
Yes, this means that you need to consider the wider picture, not just your model, but also the business implications and costs or your report, and what baseline scenarios are "interesting" to look at. And in my opinion, that is how it should be. Part of our job as statisticians or data scientists is to help other people understand our results. For that, we need to understand their language and take much of the translation task on our shoulders.


Prove $f(x)f^{-1}(x)=g(x)g^{-1}(x)⇒f(x)=g(x)$ or $f(x)=g^{-1}(x)$

Question: When we donote by $f(x)$ and $g(x)$ the functions whose domain of definition and range are $[0,1]$ such that $f(0)=g(0)=0$ and $f(1)=g(1)=1$, prove that $f(x)f^{-1}(x)=g(x)g^{-1}(x)⇒f(x)=g(x)$ or $f(x)=g^{-1}(x)$ is true.
I tried to prove by differentiating both sides, but I can't. I have no longer ideas. Please help me solve it.
Answer: By evaluating your function at $x = f(y)$ we get
$f(f(y))=g(f(y))\cdot g^{-1}(f(y))$
or in other notation:
$f \circ f = (g \circ f) \cdot (g^{-1}\circ f)$
Now it is clear to see that the identity holds if  $f=g$ or $f=g^{-1}$ , one of the right handsides become the identity function , and the other $f \circ f$
Comment: If $f=g$ or $f=g^{-1}$ the proof is trivial, but how do you show that one of those cases **must** be true?
Comment: It's necessary conditions but is it also sufficient conditions?
Answer: It seems that it is tacitly assumed here that $f^{-1}$ and $g^{-1}$ exist as bona fide functions $[0,1]\to[0,1]$. But in this case it is obvious that
$$f\circ f^{-1}={\rm id}_{[0,1]}=g\circ g^{-1}\ ,$$
whatever $f$ and $g$ fulfilling the assumptions. Any pair $f(x):=x^m$, $\>g(x):=x^n$ with natural exponents $m\ne n$ provides a counterexample to the claim in the question.


10g network cards running at less than 1 gigabit

Question: I have installed 10 gigabit fiber-optic cards in two of my servers, but when I test their throughput they run at only around 600Mbps or so:
$ scp random.1G rcm2:/tmp
random.1G 100% 1024MB  73.1MB/s   00:14

My routes look correct.  The network drivers and hardware seem to be setup correctly.
Can someone please tell me where I should be looking next?
Here is more information:
Routing
172.16.157.34
$ ip route get 172.16.157.35
172.16.157.35 dev eth1  src 172.16.157.34

172.16.157.35
$ ip route get 172.16.157.34
172.16.157.34 dev eth2  src 172.16.157.35

Hardware/ifconfig
172.16.157.34
$ ifconfig
...
eth2      Link encap:Ethernet  HWaddr 90:e2:ba:38:aa:ee
          inet addr:172.16.157.34  Bcast:172.16.157.63  Mask:255.255.255.224
...
$ lshw -class network
   ...
   description: Ethernet interface
   product: 82599EB 10-Gigabit SFI/SFP+ Network Connection
   ...
   serial: 90:e2:ba:38:aa:ee
   ...

172.16.157.35
$ ifconfig
...
eth1      Link encap:Ethernet  HWaddr 90:E2:BA:38:AA:82
          inet addr:172.16.157.35  Bcast:172.16.157.63  Mask:255.255.255.224
...
$ lshw -class network
   ...
   description: Ethernet interface
   product: 82599EB 10-Gigabit SFI/SFP+ Network Connection
   ...
   serial: 90:e2:ba:38:aa:82
   ...

Driver setup
172.16.157.34
$ sudo ethtool eth2
Settings for eth2:
    Supported ports: [ FIBRE ]
    Supported link modes:   1000baseT/Full
                            10000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  1000baseT/Full
                            10000baseT/Full
    Advertised pause frame use: No
    Advertised auto-negotiation: Yes
    Speed: 10000Mb/s
    Duplex: Full
    Port: FIBRE
    PHYAD: 0
    Transceiver: external
    Auto-negotiation: on
    Supports Wake-on: d
    Wake-on: d
    Current message level: 0x00000007 (7)
                   drv probe link
    Link detected: yes

172.16.157.35
$ sudo ethtool eth1
[sudo] password for jsp:
Settings for eth1:
    Supported ports: [ FIBRE ]
    Supported link modes:   1000baseT/Full
                            10000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  1000baseT/Full
                            10000baseT/Full
    Advertised pause frame use: No
    Advertised auto-negotiation: Yes
    Speed: 10000Mb/s
    Duplex: Full
    Port: FIBRE
    PHYAD: 0
    Transceiver: external
    Auto-negotiation: on
    Supports Wake-on: d
    Wake-on: d
    Current message level: 0x00000007 (7)
                   drv probe link
    Link detected: yes

Comment: What kind of drives/RAID controller are you running. 600Mbps is about all an 11G Dell PERC700 controller can push. Do you see the same issue when you drop the 1G file onto a ramdisk and copy it to a ramdisk?
Comment: Use iperf for testing link speed.  It is a far better tool for this purpose.
Comment: @Zypher, yes it's a Dell Perc H710
Answer: scp has a large overhead for encrypting the data while in flight. Something thinner like nc will give you better throughput and a more realistic test of the physical capabilities of your server and network.
Also, make sure your bottleneck doesn't exist somewhere else like your disks. Use iperf or something similar to test non-diskbound throughput.
Comment: `t ~500bmps. My 10G network also runs at ~500mbps.`.  Not really, It is more likely that it implies that your **DRIVES** may be operating at 500mbps.  Use a tool that doesn't depend on disk I/O for testing your network capacity.
Comment: Your premise is invalid. 73.1 MB/s is 500 mbps. So you are not reaching the limit of your 1G network, either.
Comment: @jsp Your 1G network should be capable of more like 900 mbps of payload throughput. the fact that you only get 500 mbps means your bottleneck is somewhere else, i.e. the encryption overhead of `scp`.
Comment: Thanks, I will look into using `nc`.  However, I doubt that scp's overhead is causing a 10X slowdown.  In fact, the throughput of my 10G network is the same as the throughput of my 1G network, so I doubt that my choice of benchmark is the cause of the problem.
Comment: I'm not sure I follow.  My 1G network runs at ~500bmps.  My 10G network also runs at ~500mbps.  This implies to me that my 10G network is not really running at 10G.
Comment: I do not know scp or nc, but the rated speed in xbps can only be attained if the packets being sent are of max size.  The rated pps can only be attained if the packets aare min size.  FWIW.
Comment: @Zoredache good point.
Comment: @Zoredache i get get your point, i'll try iperf
Comment: @longneck duh, OK i get it, thanks for your help.  i tried using iperf -- it was easier for me than using nc -- and I am indeed running at 10G.  thanks again.
Comment: If you want to use drive independent network traffic speed, you should get your data from /dev/zero and write them to /dev/null, something like this:
`dd if=/dev/zero bs=4096 count=1048576 | ssh user@host 'cat > /dev/null'`. Because /dev/zero compresses well over ssh, but ssh uses encryption, it kind of balances itself out. Alternatively, you could use netcat and /dev/urandom (`nc -l -p 1111  dd of=/dev/null` to listen on the receiving host, `dd if=/dev/urandom bs=4096 count=1048576 | nc host 1111` on the originating host)


Which Expression of e Converges Fastest?

Question: Writing a program, would be helpful to know whether expressing e as the sum of the reciprocals of the factorials (as in the Taylor series expansion of $e^x$ with $x=1$) converges quicker than $(1+1/n)^n$. Tried Googling, no luck, so any help would be much appreciated. Many thanks!
Answer: The taylor series
$$e = \sum_{k=0}^{\infty} \frac{1}{k!} = 1 + \frac{1}{1!} + \frac{1}{2!} + \frac{1}{3!} + ...$$
converges much faster
Comment: ... and is much quicker to compute using Hermite evaluation
Answer: Note that $x_n=\left(1+\frac1n\right)^n$ is $x_n=u\left(\frac1n\right)$ where $u(x)=(1+x)^{1/x}$ hence $$u(x)=\exp\left(\frac1x\log(1+x)\right)=\exp\left(\frac1x\left(x-\frac12x^2+o(x^2)\right)\right)=\exp\left(1-\frac12x+o(x)\right).$$
Thus, $x_n-\mathrm e\sim\frac1nu'(0)=-\frac12\mathrm e\frac1n$. On the other hand, $y_n=\sum\limits_{k=0}^n\frac1{k!}$ is such that $y_n-\mathrm e\sim-\frac1{n(n!)}$, hence $y_n$ approaches $\mathrm e$ much quicker that $x_n$ does (and both underestimate $\mathrm e$).


Distance between rankings - Kendall tau

Question: I want to use Kendall in order to measure the distance between rankings A and B. How do we deal with different ranges? For example, as shown below: let's say we have the following rankings A and B - Number 7 in A is not available in B and number 8 in B is not available in A. How do we measure the distance between these rankings using Kendall tau?
<code>    A    B
1. 1      2
2. 2      4
3. 3      1
4. 4      8
5. 5      5
6. 7      3
</code>
What I meant by this is, let's say Person A ranks America as number 1, UK as number 2, Germany as number 3, France as number 4, Brazil as number 5 and Italy as number 6. In the other hand, Person B ranks UK as number 1, France as number 2, America as number 3, Spain as number 4, Brazil as number 5 and Germany as number 6
Comment: I think you need to tell us what you mean by rank. In statistics ranks go 1, 2, 3, 4, ... without any gaps (unless there are ties) so neither of yours is what we would call a ranking.
Comment: What I meant by this is, let's say Person A ranks America as number 1, UK as number 2, Germany as number 3, France as number 4, Brazil as number 5 and Italy as number 6. In the other hand, Person B ranks UK as number 1, France as number 2, America as number 3, Spain as number 4, Brazil as number 5 and Germany as number 6
Answer: Unlike Spearman's rho, Kendall's tau doesn't actually require assigning numerical rankings to entries. Instead, it functions off of concordant and discordant pairs.
For example, say you have the following rankings
<code>      A        B
   America  UK
   UK       France
   Germany  America
   France   Spain
   Italy    Germany
</code>
An example of a concordant pair would be America and Germany. If you ignore everything else, both A and B rank the two in the same order. An example of a discordant pair would be America and the UK. Here the order of ranking differs between the two people. A ranks America before the UK, but B ranks the UK before America. You don't need a numeric ranking or even a full global ranking in order to compute this - you just need a relative ranking for each pair of entries. Also, as you're just looking at the two entries, what's happening with other entries doesn't matter.
So how do you deal with missing entries?
Probably the easiest way is just to ignore them. That is, when you're counting the number of concordant and discordant pairs you just throw out any pairs involving those items. Since Kendall's tau isn't sensitive to the absolute ranking, throwing out an entry shouldn't greatly effect the correlation, so long as we don't affect the relative ranking of the other entries. The one trick here would be that the total number of entries (the "$n$" in the Kendall's tau formula) would be the post-censoring number of entries - the number of entries which are common to both. (Such that the $n(n-1)/2$ is still counting the total number of pairs considered.) For my table above this would be 4.
Another approach you could use is to treat the missing entry as a "tie" toward everything. The rationale being that you can't tell if a missing entry is ranked higher or lower than any other entry, so you can compromise by calling it a tie. Given that Kendall's tau is computed pairwise, there's no technical issue with considering an entry to be tied with all of the other entries. If you've settled on counting it as a tie, you then have to decide which of the various tie-handling methods for Kendall's tau you're going to use. When doing so, keep in mind that your $n$ will be the total number of possible entries, including the unpaired entries on both. For my table above, this would be 6.
Personally, I would suggest going the route of just ignoring unmatched entries, especially if there are other possible entries you're also ignoring from both sides. (e.g. Should we also include Burkina Faso in the ranking, despite no one mentioning it?) I'd only go with the ties approach if you deliberately want to penalize the correlation ranking because of the unmatched pairs.
Comment: thank you for the very good answer. If i got `tau = 0.899, 2-sided pvalue =5.2094e-05`, does it indicate the distance between the two rankings is similar? Generally, is it the higher the tau value the better the similarity is?
Comment: @Mahsolid Yes, like most correlation coefficients, Kendall's tau ranges between -1 and 1, with 1 being perfectly correlated, -1 being perfectly anti-correlated, and 0 being no correlation.
Comment: How about if i want to apply `Spearman's footrule` for the same question my dear?

Distance between rankings - Kendall tau


Transformar nome dos campos postados em variáveis de PHP

Question: Tenho um formulário com campos dinâmicos.
com inputs com names assim:
<input type="hidden" name="nome_prod1" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd1" type="text" id="1"/>

<input type="hidden" name="nome_prod2" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd2" type="text" id="1"/>

cada um com seu value, o problema é na hora de mostrar isso pois não queria mostrar tão pouco salvar no banco os campos que tem quantidade 0.
Usei o comando:
foreach( $_POST as $nome_campo => $valor)
{
   $comando = "$" . $nome_campo . "='" . $valor . "';";
   eval($comando);
}

Porem ele trouxe todos os inputs, tentei tratar pra não mostrar os que tem qtd = 0
mas o problema está em buscar a variável eu coloquei um contador $i dentro foreach, então o nome da variável qtd eu tentei chamar assim:
if ($qtd{$i} == 0 ) {}

Mas não funcionou, como eu faço isso buscar uma variável dinâmica?
$qtd1
$qtd2
$qtd3

Answer: Antes de mais nada, respondendo ao que foi perguntado, um caminho seria usar "variáveis variáveis":
foreach( $_POST as $nome_campo => $valor) {
   $$nome_campo = $valor;
}

Mas isso está longe de ser uma boa idéia. Qualquer mau uso do seu PHP (por exemplo, o cliente enviando dados arbitrários) vai sobreescrever variáveis da aplicação.
Como bem lembrado pelo Papa Charlie, o PHP até tem algo pronto que já faz isso automaticamente, o extract().
Como as soluções acima (seja o extract ou o loop) tem seus problemas inerentes, uma solução mais elegante seria usar esta estrutura:
<input type="hidden" name="nome_prod[]" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd[]" type="text" id="1"/>

E no PHP algo assim:
$nome  = $_POST['nome_prod'];
$qtd   = $_POST['qtd'];

// aqui é só usar os dados como quiser, já estão indexados desde a captura.
$count = count( $qtd );
for( $i = 0; $i < $count; ++$i ) {
   echo 'Produto: '.$nome[$i].' - Quantidade: '.$qtd[$i]."
\n";
}

Numa aplicação completa, é necessário sanitizar os dados antes do uso, obviamente (independente do approach usado).
Quanto a não usar valores zerados, basta algo assim dentro do loop:
if( 0 + $qtd[$i] ) {
    // usa o valor como quiser
}

o código dentro do bloco do if só será executado com valores diferentes de 0. O artifício usado é forçar um cast com 0 + para tratar o valor como numérico (tem várias maneiras de se fazer isto, essa é uma delas. veja como fazer os casts e conversões no manual do PHP, na parte de variáveis).
Comment: @PapaCharlie seria se fosse para incentivar a primeira idéia dele, que eu condeno. É que no extract não dá pra ele por um IF como eu mencionei acima, ou pega tudo ou não pega nada. eval, extract, $_REQUEST, $$variables e tudo que é muito "genérico" no PHP acaba sendo um problemão. Mas se você postar um exemplo com extract, acho que é uma alternativa válida (que eu não recomendo, mas não estaria errada a resposta). Só sugiro deixar claro que sofre dos mesmos problemas que eu mencionei acima. De qq forma, é um comentário válido.
Comment: @PapaCharlie neste caso, pus uma menção ao seu comentário na resposta, ao menos não fica faltando avisar da opção.
Comment: Não sei se entendi bem a questão, mas não seria o caso de usar `extract`?
Comment: Eu sei, concordo 1000%, e nem me atreveria a responder usando `extract`. O ideal seria recomendar uma abordagem mais correta como você fez. Eu é que não tinha entendido bem a questão, queria saber se o que precisava era na mesma linha do `extract`.


If $X$ and $Y$ are discrete random on the probability space $(\Omega , F, P)$, show that $U$ and $V$ are also discrete random variables.

Question: If $X$ and $Y$ are discrete random on the probability space $(\Omega , F, P)$, show that $U$ and $V$ are also discrete random variables where $$U(\omega) = X(\omega) + Y(\omega)$$
$$ V(\omega) = X(\omega)Y(\omega)$$
Answer: If $E,E'$ are events with $\Pr(E)=1=\Pr(E')$ then: $$\Pr(E\cap E')=\Pr(E)+\Pr(E')-\Pr(E\cup E')=1+1-1=1\tag1$$
Countable sets $A,B$ exist with $\Pr(X\in A)=1=\Pr(Y\in B)$.
Then $(1)$ tells us that $$\Pr(X\in A\wedge Y\in B)=1$$ A consequence of this is:$$\Pr(X+Y\in A+B)=1$$ This for $A+B:=\{a+b\mid a\in A, b\in B\}$ which is a a countable set.
Same procedure for $XY$.


How would I prevent a domino-like STOPPED tasks effect and is it a good idea?

Question: When I launch a AWS ECS Task Definition revision using ecs-cli compose --file <...> --project-name <...> --aws-profile <...> service up --create-log-groups --cluster <...> --launch-type FARGATE --region eu-west-1 some of the tasks go from a PENDING to a RUNNING state. The issue is that if one container goes into a STOPPED state, the rest appears to automatically go into a similar STOPPED state. Is there a way to prevent this and only have the specific containers crash independently, or is that an "anti pattern"?
Having all containers crash simultaneously makes debugging more difficult.
Here is the Dockerfile provided for ecs-cli compose service up:
services:
  ...-file-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-file-api
    ports:
      - 3054:3054
    restart: always
  ...-frontend:
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-frontend
    ports:
      - 80:80
    restart: always
  ...-help-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-help-api
    ports:
      - 3059:3059
    restart: always
  ...-login-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-login-api
    ports:
      - 3055:3055
    restart: always
  ...-login-frontend:
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-login-frontend
    ports:
      - 8080:8080
    restart: always
  ...-mail-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-mail-api
    ports:
      - 3063:3063
    restart: always
  ...-main-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-main-api
    ports:
      - 3053:3053
    restart: always
  ...-mongo:
    image: mongo:3.4.20-xenial
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-mongo
    restart: always
  ...-plan-api:
    environment:
      ...
    image: ...
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-plan-api
    ports:
      - 3058:3058
    restart: always
  ...-redis:
    image: redis:4.0.14-alpine
    logging:
      driver: awslogs
      options:
        awslogs-group: /ecs/log
        awslogs-region: eu-west-1
        awslogs-stream-prefix: ...-redis
    restart: always
version: '3'

As an example "crash", the ...-main-api service gets a Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED which is visible under CloudWatch -> Logs -> Insights. Logs for e.g. ...-mongo - another service - is not available yet it still settles for the STOPPED state.
Expected: The remaining containers should not go into an immediate STOPPED state as a result of one or more other containers stopping. They should only go into a STOPPED state if they crash independently.
Currently: All containers apparently stop regardless.
Answer: You can try setting a parameter called essential as false in the task definition and that should do it.
Task Definition Parameters :

essential
Type: Boolean
Required: no
If the essential parameter of a container is marked as true, and that container fails or stops for any reason, all other containers that are part of the task are stopped. If the essential parameter of a container is marked as false, then its failure does not affect the rest of the containers in a task. If this parameter is omitted, a container is assumed to be essential.
All tasks must have at least one essential container. If you have an application that is composed of multiple containers, you should group containers that are used for a common purpose into components, and separate the different components into multiple task definitions. For more information, see Application Architecture.
"essential": true|false


Valores do sensor acelerômetro para graus decimais

Question: Preciso pegar o valor de inclinação e declinação do celular no modo paisagem, porém os valores que preciso são em graus decimais, de -90 a 0 a 90 graus.
Tentei usar o acelerômetro, mas os valores desse sensor são de 0 a 10. Também tentei usar o magnetômetro, mas alguns celulares não tem esse sensor. Como posso obter esses valores usando somente o acelerômetro?
Código usando o acelerômetro:
package br.eng.itech.smarthipsometer_01;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    SensorManager sensorManager;
    Sensor accelerometer;

    TextView textViewX;
    TextView textViewY;
    TextView textViewZ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewX = (TextView) findViewById(R.id.textViewX);
        textViewY = (TextView) findViewById(R.id.textViewY);
        textViewZ = (TextView) findViewById(R.id.textViewZ);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (accelerometer == null){
            Toast.makeText(this, "Sensor acelerômetro não encontrado no dispositivo", Toast.LENGTH_SHORT).show();
            finish();
        }else {
            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onPause() {
        sensorManager.unregisterListener(this);
        super.onPause();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {

        textViewX.setText(String.format("X: %.2f", sensorEvent.values[0]));
        textViewY.setText(String.format("Y: %.2f", sensorEvent.values[1]));
        textViewZ.setText(String.format("Z: %.2f", sensorEvent.values[2]));

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
}

Answer:
Nota: não sou programador Android, então estou respondendo isso apenas com os conceitos de física e matemática adquiridos ao longo dos anos. Talvez seja adequado olhar a documentação oficial sobre o posicionamento do dispositivo, mas ela passa por uma matriz de rotação 3x3 para então achar os ângulos; ele também faz uso das leituras do acelerômetro e do magnetômetro

O sensor do tipo TYPE_ACCELEROMETER vai retornar a força de aceleração em cada eixo (vide documentação). Nesse tipo de sensor, o retorno é um vetor com 3 posições:

SensorEvent.values[0], força da aceleração no eixo X
SensorEvent.values[1], força da aceleração no eixo Y
SensorEvent.values[2], força da aceleração no eixo Z

Esses eixos são considerados conforme a imagem abaixo:

Note também que a aceleração está em m/s², conforme unidade base do SI (a unidade poderia estar em N (newtons) também, mas isso implica conhecer a massa do aparelho e de qualquer outra coisa anexada a ele, mas no final das contas essa massa pode ser desprezada e a única coisa que importa mesmo é a taxa de aceleração).
Quando o corpo está totalmente na vertical sem sofrer mudanças em suas posições, você terá o efeito da força da gravidade (no eixo Y, apontando para baixo) e a força normal em perfeito equilíbrio com a gravidade. Esse sensor não se importa com a força normal, então no final das contas você está medindo apenas a força da gravidade. Como estamos na Terra, a gravidade terá efeito de acelerar a 9,8 m/s². Por isso então que você tem a impressão de que os resultados são entre 0 e 10, qualquer que seja a posição.
Para você detectar que o celular está mais "deitado" do que "de pé", o componente da gravidade no eixo X deve ser significante do que o componente da gravidade no eixo Y. Mas ainda assim isso não será capaz de dizer o quão "paisagem" ou o quão "retrato" de fato está o celular. Para responder essa pergunta, é necessário entender também como se calcula Φ e Θ dessa questão aqui do Mathematics. Vou reproduzir a imagem contina nessa questão abaixo para ficar melhor ilustrado:

Note que, no caso, o eixo que essa imagem considera "para cima" é o Z, e o eixo que "sai da tela de leitura" é o X. Essa é a representação mais clássica do espaço 3D; mas podemos reentender esses eixos de acordo com a orientação Android, e é isso que iremos fazer. Iremos considerar o eixo "para cima" como sendo o Y, e o eixo que "sai da dela" como o Z. Leve essa reinterpretação em consideração quando ler minhas explicações abaixo

No nosso caso, precisamos levar em consideração o valor de Θ para saber o quão inclinado o celular está. Quando o valor de Θ for 0 graus, o celular estará perfeitamente alinhado na vertical. Quando for Θ = 180 graus, ele estará de cabeça para baixo. Uma medida para verificar isso de maneira rápida é tirar o cosseno, pois cos(0) = 1 e cos(180) = -1. O ângulo, portanto, pode ser considerado como um valor intermediário que podemos descartar. Ou então, se precisarmos muito dele, podemos usar a função arco cosseno (acos): dado o valor do cosseno, qual o ângulo que gera esse cosseno?
Note que acos retorna em radianos; para converter para graus, leia esta resposta.
Para calcular o valor do cosseno de Θ precisamos da magnitude do vetor (hipotenusa) e de seu componente no eixo Y (cateto adjacente). Essa resposta mostra como achar a magnitude de um vetor em 3D. O componente no eixo Y é SensorEvent.values[1]. Então, para achar o cosseno da inclinação Θ, seria necessário o seguinte cálculo:
float xPart = SensorEvent.values[0];
float yPart = SensorEvent.values[1];
float zPart = SensorEvent.values[2];

float magnitude = Math.sqrt(xPart*xPart + yPart*yPart + zPart*zPart);

float cosTheta = ypart/magnitude; // <== variável de nosso interesse

Em cima dessa informação, você pode tomar alguma decisão sobre se está paisagem ou retrato ou o que for. Note que não estou considerando aqui se o celular está "olhando para o chão" (rotação no eixo X), apenas a inclinação dele (rotação no eixo Z). A rotação no eixo Y é desprezível para o seu cálculo e creio que ela, puramente, não seja detectável apenas pela gravidade (talvez seja detectável no momento em que se rotaciona o eixo Y junto de outras rotações, mas ela de toda sorte é desprezível).
Se desejar mesmo o ângulo em graus, só fazer o seguinte:
float thetaGraus = Math.acos(cosTheta) * 180.0/Math.PI;

Comment: muito obrigado pela ajuda! Resposta bem resumida, mas muito bem explicada. Consegui chegar no meu objetivo através da sua explicação.


Using PHP to print an image

Question: Unfortunately searching this on Google is very difficult due to the print() function. I have a form that posts to a page that creates an image based on the submitted values. I need to make it so that after creating the image it opens the print dialogue.
Should be simple enough, but it's late and I'm lazy -_-
Comment: -1 for 'it's late and I'm lazy'. It's amateurish comments like that that make me not want to answer questions like this at all.
Comment: wow, it's eaaaaaassssyyyyyy. But, sorry, I'm lazy too.
Answer: PHP itself can't do this, afterall it is a server side language and what you're asking to do is client side functionality.
Perhaps Javascript's window.print() method is what you are after?
Answer: I would say after it creates the image it should have a javascript function to open the print dialogue.  Something like:
<code><?php
if($imageisdone){
echo "<script>window.print();</script>";
}
?>
</code>

Using PHP to print an image


Core update error

Question: I'm trying to run a composer update from my webroot directory. When I use composer update drupal/core --with-dependencies, it returns:
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)

I wasn't sure if I needed to require the drupal/core package with composer? I tried that, but it had no effect. Following the advice of online forums, I adjusted the following settings in the composer.json file:
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "~1.4",
    "drupal/drush": "^6.0@RC",
    "drush/drush": "~9.0"
},
"replace": {
    "drupal/core": "~8.4"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},

I changed the drush version to ~9.0 and the core version to ~8.4. I then deleted the /vendor directory and the composer.lock file. After running the update again, it updated a few other packages, but ignored core. I feel like I'm missing something simple. Any help is appreciated!
Answer: If you downloaded Drupal from drupal.org (e.g. via the tarball download link, or with drush dl), then you cannot use Composer to update Drupal core.  The steps you are attempting above only work for sites based on the template project https://github.com/drupal-composer/drupal-project. This is the recommended method to use when managing Drupal 8 sites with Composer.
Comment: And as a footnote to this, it is possible to work a tarball install into a drupal-project install, if you are comfortable enough with composer and git (assuming you have site in git).  I would do this before 8.3->8.4, though, and also use webflo/drupal-core-strict pinning both it and core to the exact Drupal version while you work on the conversion.
Comment: This was immensely helpful! I'm so used to everything being contained inside the webroot. The Composer directory structure is odd to me. Is there documentation on setting up git, using this method? Typically, the webroot would be the git repo, but I assume I'll need all of the composer stuff on the server, so should I set the git repo a level above the web directory?

Core update error