Can Cartodb map show only United States?

Question: I have made my map with cartodb, showing where certain work is going on throughout the United States. I want to send it out, but would prefer the map to only show the United States--whereas now it shows Canada and Mexico as well. I am using the free cartodb.
Answer: If you are asking if you can remove countries from the CartoDB map server, then no. But you can change your zoom level of where the map starts. When you do that you will be provided a new share link. You will want to play with the settings before to send out the final shared link.


Blocking calls with no SIM card automatically on new?

Question: If I block a number from my old iPhone without a SIM card, does that block the number on my new iPhone with SIM card? This is a replacement iPhone for my broken one.
Answer: The Call Blocking feature built-into iOS doesn't depend on having a SIM card per se. However it does synchronize over iCloud, meaning that if your previous iPhone had an Internet connection at any point (and you were logged in to your iCloud account) then its blocked numbers were synced with iCloud.
Conversely, your new iPhone would synchronize its block list as soon as you connected it to your iCloud account.
You can verify whether your block list transferred by opening Settings → Phone → Call Blocking & Identification.


Should we downvote answers that begin with "I think..."?

Question: People often speculate rather than answer. If you think you know the answer then you don't.
Comment: Why would you focus on whether or not the answer begins with "I think" rather than whether or not the content is actually unfounded speculation or not?
Comment: Starting an answer with "I think" definitely reduces its overall credibility. Unless it's an especially difficult subject, I would much rather hear from someone who is more sure. I wouldn't automatically downvote it though.
Comment: @D.Halsey Judging the answer by how confidently it sounds is an [*argument from authority*](https://en.wikipedia.org/wiki/Argument_from_authority) - it works well in practice, but it is still a logical fallacy.
Answer: I think this is a terrible idea.
Comment: I think you're right.
Answer: Phrasing
I think that downvoting and criticizing questions should be based on their (physics) content rather than on the particular phrasing - which may reflect one's individual habits, cultural background, or simply the turns of phrase used in the one's native language (many users of PSE are non-native English speakers).
Falsifiability
On more scientific level: the notion that all questions have an answer, and that this answer is unique is simply not true. In physics we are closer to this notion, since we deal with the subject that can be extensively tested experimentally in controlled conditions (which is not always the case in biology, economics, social sciences, etc.) Yet, even physics theories cannot be proved, but only falsified by new evidence. In fact, thinking that our answer is correct rather than believing that it is correct is the difference between the science and a religion.
Criteria of correctness
There are also many known logical fallacies, where correctness of a statement is judged not by objective criteria, without perhaps even realizing it:

Years of schooling make us consider as correct whatever the graders typically consider correct
Popular opinion - e.g., judging the answer as correct, because it is highly upvoted
Appeal to authority - e.g., judging the answer as correct, because it is made by a high-reputation user.

Anecdote
A popular anecdote is that the original idea behind the IQ testing was to give as many answers to the same question as possible, using different reasoning... but it became a multiple choice test, in order to adapt it to general population.


Zeros of a function of degree 4

Question: I'm trying to show that the following function has no zeros
$$
60x^4-44x^3-25x^2-44x+60=0.
$$
I already tried using Eisenstein's criterium, but since the first and the last coefficient are both $60$, there is no prime which holds.
Comment: See http://math.stackexchange.com/questions/480102/quadratic-substitution-question
Comment: The roots are $(11\pm  A(2\sqrt{574}+iB\sqrt{1183-A\sqrt{574}}))/60$, with $A,B=\pm 1$, none of which is real.
Answer: In this answer I showed that the polynomial
$$
p(x) = x^4 + ax^3 + bx^2 + ax + 1
$$
has no real zeros if $|a| \leq 4$ and $b > 2 |a| -  2$.
We have
$$
60x^4-44x^3-25x^2-44x+60 = 60 \left(x^4 - \frac{44}{60}x^3 - \frac{25}{60}x^2 - \frac{44}{60}x+1\right),
$$
so in this case $a = -44/60$ and $b = -25/60$.  Indeed, $|a| \leq 4$ and
$$
b = -\frac{25}{60} > -\frac{32}{60} = 2|a|-2,
$$
so the given polynomial has no real zeros.
Answer: Following the hint in the comments, we divide by $x^2$ and rearrange to get $$60\left(x^2+\frac{1}{x^2}\right)-44\left(x+\frac{1}{x}\right)-25=0$$
Set $y=x+\frac{1}{x}$ and note that $y^2=x^2+\frac{1}{x^2}+2$ to get
$$60(y^2-2)-44y-25=0$$
which rearranges to the quadratic $$60y^2-44y-145=0$$
This has roots $y\approx -1.23, 1.96$.  [Alternate answer: $g(y)=60y^2-44y-145$ is an upward-pointing parabola, and $g(2)>0$ and $g(-2)>0$, so any roots are in $(-2,2)$.]
However $|x+\frac{1}{x}|\ge 2$ for all real $x$, so there are no real solutions.
Cute proof of the last fact: for $x>0$, the arithmetic-geometric mean inequality gives $x+\frac{1}{x}\ge 2\sqrt{x\cdot \frac{1}{x}}=2$.

Zeros of a function of degree 4


How can I include radiobuttons to a view's results?

Question: I want to include two radio buttons to EVERY view's results, so a user can select one of them. This is actually a view with users results. Next to each result the following radio buttons will appear: "Active", "Suspend this member" and "Delete this member". How can I make these radio buttons appear on each view result?
Thanks
Comment: Can you please add more information to your question? A view is not a form, and simply adding a radio button will not turn it into a form. I can help you better if I understand what you're trying to achieve.
Comment: That's not really what I meant. I assume that clicking a radio button is not a goal in itself; you probably want to do something with the gathered information. What do you want to do with the selected views rows? Are selected rows stored in the user's profile (eg. like bookmarks)? Do you want to perform an action on the selected nodes (eg. publish/unpublish? Something else? (PS. you can edit your question to add the information, that will keep all information in one place.)
Comment: Well,I have some view's results.On every result I want to appear two radiobuttons,next to each result,so as a user can select one.I hope this is more clear
Answer: Is it very important to you to have radio buttons exactly like you describe? If not, I can recommend the Views Bulk Operations (VBO) module. VBO is a popular module which allows you to select views rows and perform a certain action on those rows. Each row gets a checkbox and you select the action to be performed with those rows using a select box. Here is a screenshot to illustrate that:

I think VBO is by far the most mature option available to solve your problem. If you insist on having the radio buttons in your view and you don't mind writing code yourself, have a look at Views Form Field (interesting, but no releases yet), or Create the "View as form" style (work-in-progress in the Views issue queue).
Comment: I don't think you can use Editable Fields, because the user status is not stored as a field (I mean "field" as defined by CCK in Drupal 6 or Field UI in Drupal 7).
Comment: Really thanks for your answer,I think Viewsbulkoperations will solve my problem,really thanks for your excellent answer
Comment: Could I use editable fields for this?http://drupal.org/project/editablefields


Test whether data set approximates normal distribution using mean and median

Question: I am of the knowledge that to test whether a data set approximates a normal distribution, the median and the mean should be approximately equal. So my question is to what degree should the difference between the median and the mean be accepted?
Comment: @Glen_b even understates the problem as there are also asymmetric distributions for which mean = median, such as some Poisson and binomial distributions.
Comment: You could work out (via simulation at the very least) a distribution for the difference in sample mean and sample median, which would be symmetric about 0 and whose variance multiplied by $n$ would asymptotically go to some constant. As such you could construct some kind of test for normality, but it would be a pretty poor test for it, since it would have fairly poor power against a host of symmetric alternatives that aren't normal. If you're interested in assessing normality, there are better ways
Comment: See also http://stats.stackexchange.com/questions/2492/is-normality-testing-essentially-useless
Comment: You should first tell us why this matters to you/what you intend to do with this information.
Answer: As I said in comments, you could work out (via simulation at the very least) a distribution for the difference in sample mean and sample median, which would be symmetric about 0 and whose variance multiplied by n would asymptotically go to some constant. As such you could construct some kind of test for normality, but it would be a pretty poor test for it, since it would have fairly poor power against a host of symmetric alternatives that aren't normal -- nor indeed even against  asymmetric alternatives that happen to have mean=median. If you're interested in assessing normality, there are certainly better ways.
To answer the question though, this paper says that asymptotically, that constant I mentioned is $\pi/2-1$ (that is the variance of $\bar x - \tilde{x}$ in large samples is about $0.571\sigma^2/n$. In small samples, it's a bit smaller. As a rough rule of thumb, you expect the standard deviation of the difference between mean and median to be about $0.75 \sigma/\sqrt{n}$ (in odd samples; a bit smaller for even $n$).
Simulation of 10000 samples of size 25 gives a constant of $0.7390$ (that is, the s.d. of the difference was about $0.739\sigma/\sqrt{n}$, which is consistent with the results from the paper.
This boils down to basically using Pearson's second skewness coefficient as a way of assessing normality (I haven't used the factor of 3 here, though - I agree with Nick Cox's comment below that it's more intuitive without it in any case). That's sometimes called the nonparametric skew (though there's nothing that makes it any more nonparametric than any other skewness coefficient).
Now, considering it as a test statistic, since $\sigma$ will generally be unknown, it must usually be estimated; except for large samples (when we may apply Slutsky's theorem), this will lead to a coefficient that's heavier tailed than normal - though not actually t-distributed, it will probably be close to it* - meaning a critical value will tend to be larger for smaller samples. This will somewhat counteract the effect above of the coefficient being smaller with smaller $n$, though not completely; an asymptotic 5% test rejects when $\frac{\mid\bar x - \tilde{x}\mid}{k.s/\sqrt{n}}>1.96$ where $k = \sqrt{\pi/2-1}\approx 0.756$.
Using 0.75 for $k$ is easy to remember and works quite well for odd $n$ down to about 25 or even a bit lower; the actual significance level at $n$ = 25 is close to 4.5% (on normal data, naturally). It's a reasonably easy test to remember even if it's not always useful.
* though we won't know suitable approximate df without further effort
Comment: I think it's simpler and clearer to work with (mean - median) / SD. Multiplying that by 3 does have historic roots in Pearson's system of distributions. But setting that aside this measure then has the property, intermittently rediscovered and often thought contrary to intuition, that it is bounded by -1 and 1. It is clearly 0 for mean = median.
Comment: Thanks for your answer. It is exactly what I was looking for. The publication from Electronic Journal of Applied Stats clarifies the issues that led to my post. Much appreciated.
Comment: @NickCox I agree, but felt the connection was worth pointing out.
Answer: There is no hard and fast rule for that, Its depend on your data. Please specify your data for more detail and you may try other methods to check the normality of data.
Comment: I'm actually trying to establish control charts. I have collected the data. So all I needed was a way to determine whether my data is distributed normally, so that I could use appropriate formulas to calculate limits. Hence my post.


What to do to minimize taxes on a prize in the US

Question: I won a $30K prize from a challenge where the institution did not withheld any taxes. Before the year ends I would like to know what steps I can take to minimize the taxes I have to pay, what options do I have? (in the US).
Answer: If you want to minimize the penalty for not withholding any of the prize, then you can either send in an estimated quarterly tax payment, or increase your tax withholdings with your employer for the remainder of the year.
If you want to reduce the tax, then you need to either save the money in tax-advantaged accounts like an IRA (which is not taxed until you withdraw the money) or an educational savings account like a 529 or Education IRA, which are deductible at the state level by many states, but not the federal level.  Or you can spend is on tax-deductible things like charity.
(I'm sure there are other legal tax avoidance strategies, but those are the main ones that come to mind)
Note that you should not spend it on items just to get the tax break.  i.e. you should NOT keep a mortgage just to deduct the interest.  It makes no sense to to spend $800 a month on mortgage interest to save $200 in tax.  And don't spend $10,000 in solar panels to get a clean energy tax break (if they even exist anymore).
Also note that the more practical use of the money may be to pay off debts. While you might save more this year in tax (assuming your marginal tax rate is higher than your interest rate), long-term you may be better off reducing your debt burden so you have more of your income to save and invest.
Comment: Just to clarify, contributions to a 529 or ESA (Education IRA) are generally not deductible on your federal return.
Comment: Note that IRA contribution limits are much lower than $30k, so you won't be able to shelter much from taxes in that way.
Comment: Thanks for the answer! do you think that starting a new Business with some of the money could lead to better savings?
Comment: Probably not for a long time.  Businesses generally take a LONG time to become profitable unless you have some very unique resource, skill, or idea that there's already a market for.  But that a completely different discussion.


can I identify the origin computer for a program?

Question: I am Developing a program in several platforms and languages, But I don't want anybody to discover the origin computer where the program was developed, is there any way that someone can discover that ?
Comment: What about compiling inside a virtual machine?
Comment: @maligree possibly, will certainly help, but I wouldn't expect it to a perfect magic bullet. I would check over very carefully the output for anything that could link back.
Comment: Can you develop your program in a scripting language? Whether Perl or Javascript, none of the scripted languages is very susceptible to accidental hidden channels. (Intentional hidden channels, OTOH...)
Answer: Source code consists in a bunch of text files. The contents of a text file are exactly what a text editor shows, so you can control that "visually". Beware of revision control systems such as CVS or Subversion: they can automatically replace some specific tags in source code (like "$Id$") with an identifying string which may contain the current date and time, your login name, and other information -- that feature is considered to be good for traceability, but I understand that you would not like it in your specific case.
Compiled code is quite something else. Some compilers may automatically added identifying strings like what revision control software does, as "comment" fields in the executable structure. This needs not even be a deliberate spying device: traceability is really a good idea in the general case; no need to imagine a government bribing compiler developers into adding such things in compilers just to be able to spy on programmers. Also, executable formats often include some "blanks" -- unused parts added for alignment reasons -- which the compiler might not have bothered with filling with zeros, instead of just writing what was in RAM at that place. This has occurred with an older version of lcc-win32, which was thus writing out random excerpts of the RAM contents which could contain confidential information (I think this has been fixed for lcc-win32, but it could happen with other toolsets).
Other file formats can also embed (and thus leak) some information. For instance, PNG images can include "comments" (which do not change the visual aspect of the picture in any way). GIMP, an image manipulation program, uses the comment field to state that it was involved in the image processing; any tool could also add some information which, in your view, would be less benign.
Many potential leaks can be detected visually, by looking at the files as if they were text. But this does not cover the possibility of one of your tools being voluntarily bugged so that it includes incriminating evidence in its output (such tracing information would be encrypted so as to "look random" except for whoever knows where to look).
Unfortunately for the state of the World at large, "a revolution in my country" is not a very precise indication. There currently are armed insurrections or similar unrest in quite a few countries just now, including, but not limited to, Afghanistan, Yemen, Syria, Somalia, parts of Libya, Colombia, Sudan, and Southern Sahara; and things are not completely clear in Egypt, Iraq or Iran, just to include the few I can think of from memory.
Comment: Worse than that - Microsoft compilers (the ddk does this especially) embed absolute file system references to pdb (debug database) files into compiled C/C++ code. Search your compiled exe for `c:\Users\username\...` if you've used that path. Not good if your user name happens to be your full name...
Comment: Microsoft's compilers like to go further and start signing the applications by default (usually with self signed keys).
Answer: There's a whole discipline devoted to extracting information out of computer files and systems: computer forensics.
Computer files are relatively easy to make anonymous. Relatively to network traffic, that is: files are just a bunch of bits, whereas network traffic carries a lot of information through timing. On an absolute scale, anonymity of nontrivial files is often not so easy to carry out.
The first thing to make sure is that there is no identifying information in your source files, except for comments. Comments are mostly safe, though they do influence line numbers that can appear in debugging information (e.g. __LINE__ in C). In particular, as Tom notes, make sure your source files don't have RCS tags or the like. Use very generic names for functions, variables, classes, source files, etc., as well, as many of these make their way into the executable.
Your compiler can be identified with a good success rate by a sufficiently motivated examiner, as different compilers compile and optimize commonplace code in different ways. So make sure to use a very common compiler. The same applies to any libraries your program is linked against.
Then, make some basic tests. Compile the same program on several machines with the same compiler version, and make sure the results are bit-for-bit identical. The test will be more conclusive if the machines are as different as possible apart from the compiler and libraries (different OS version, different user name, different language settings, …).
Under unix systems (such as Linux, or Cygwin under Windows), run the strings command on your binaries to find printable substrings. This is just a basic sanity check, it won't find all potentially incriminating information by any count. For example, it won't find strings encoding in multibyte character sets such as UTF-16 (used by Windows and Java).
If at all possible, try to separate your program between an innocent-looking program that won't raise any flags and a small text file containing the sensitive data. Distribute the two through different channels. Even better, arrange to make your program a small text file; ideally, use a popular interpreted language and only distribute the program source. Don't distribute your own working source, though: distribute a sanitized source with no comments, sensitive variable names, etc.
When you distribute your program, you might decide to use an archive format such as zip or tar. Note that these archives store the date of the file, and some archive formats (e.g. tar) can store a user name.
While there is no such thing as complete anonymity, I think it is possible to achieve good enough anonymity for a one-man programming effort. Your biggest worry will be distribution. It is a lot harder to remain anonymous when you're moving bytes around, and even less so once you start interacting with people.
Using Tor helps, but it's not a magic bullet, especially against interceptors with government resources.
(In particular, this question may be traceable to you! Particularly if you live in a country with a government filter on all Internet accesses, which can correlate your Internet activity with the public information about your interactions with Stack Exchange.)
Answer: I don't know of any way for someone to trace back what computer you wrote the program on or what program you compiled it on.
But, if you want to be safer, one possibility might be to buy access to computing resources on some other system (e.g., on Amazon EC2, or on a virtual private hosting service), and compile your program there.  I would also "strip" the binary, to remove all debugging symbols, just in case.  If you're able to obtain access in a way that can't be traced back to you, then even if there is some crazy way to identify the computer it was compiled on, that won't be directly linkable back to your identity.  Perhaps folks here can suggest a way to get remote shell access (or to run a virtual machine) on some machine, without revealing your identity.
Comment: I'm not convinced that working on the cloud is a good idea, as it introduces the quite realistic possibility of correlating user activity with program distribution. Distributing the program would presumably be as incriminating as writing it.
Comment: @Gilles: Agreed. *Traffic Analysis* — where they don't necessarily know the contents of the message but they know some of (time | duration | source ip | dest ip | etc.) — can yield surprising (and disturbing) results. I think developing locally and then using something like TOR to distribute to an anonymizing server might produce the lowest traffic profile.
Comment: Compiling the program inside a docker container running in a service like AWS Fargate that doesn't let you pick a specific virtual machine sounds like a good idea. AWS might be able to trace the compilation to you, though I doubt it. Anyone else (including you), not a chance. Also, I wonder if doing it in the AWS region govcloud would help make it more difficult for a government other than the US to access the (theoretically existent) AWS logs that would trace the compilation to you. You might want to ask that on Law SE


Vagrant Access index.php

Question: I believe this is the right place to ask.
First, I've installed VirtualBox and Vagrant.
After that, I've cd'd to this: https://github.com/LearnWebCode/vagrant-lamp (downloaded zip, extracted folder)
Then after running vagrant up, I've reached the Congratulations page through IP http://192.168.56.101/
After that, I've set an easy-to-read URL in the hosts file, and able to run it but it leads to the Congratulations page and not the index.php's Hello World.
Any idea how to rectify? Not sure if this is part of the cause, this came up during the first set-up: The following SSH command responded with a non-zero exit status
Answer: Never mind, the URL MUST be fictional-university.test for it to access the index.php, it cannot work otherwise.

Vagrant Access index.php


What do the permit types in Chicago's Building Permit Data mean?

Question: The documentation for Chicago's building permit data seems to be out date. Anybody know what Permit Type "PERMIT - NEW CONSTRUCTION" and "PERMIT - RENOVATION/ALTERATION" mean?
Answer: Those are pretty common terms for building permits.
"New construction" means that they're building (or placing) a new building.
"renovation/alteration" means that there's an existing building that's being modified.
What qualifies as a renovation can get a little interesting by area ... I remember one of my co-workers telling me that in Virginia if you leave one wall standing, you can declare it to be a renovation, and avoid having to pay all of the fees required for new construction if you're looking to tear down an existing building.
See the city's website for details on the other permit types.


Is it possible to create a cubic function that coincides with a trigonometric function in the interval between two local extremums?

Question: Is it possible to create a cubic function with the roots $a$, $b$ and $c$, $f(x) = K(x-a)(x-b)(x-c)$, that coincides with a sine or cosine function, $g(x)$, in the interval $d \le x \le e$, $g'(d) = g'(e) = 0$?
Comment: Just look at the Taylor-series of sine and cosine, and you can easily see, that it won't be possible.
Answer: It is not possible, because $f^{(4)}\equiv0$, and $g^{(4)}\not\equiv0$.
Answer: It's not possible (assuming $d\neq e$). I am not sure what the quickest way to prove this is, but using complex analysis you can just say the following: if this is true, then $f-g$ is a function that can be extended to all of $\Bbb{C}$ which is $0$ on all of $[d,e]$. Since $[d,e]$ has a limit point, this impies $f-g$ is constantly zero, i.e. $f=g$. But this can't be true (for instance because $g$ has infinitely many zeroes while $f$ is only zero at $a$, $b$ and $c$).
If you don't know/don't like complex analysis though, there's probably some other way to see this.
Answer: It is not possible for a cubic function to coincide perfectly with a trigonometric function over any interval. If $f(x)$ and $t(x)$ were such cubic and trig functions, then their difference $g(x)=f(x)-t(x)$, would be an entire function that is identically zero on an interval. Therefore, by the identity principle from complex analysis, we would have $g(x)=0$ everywhere.
That said, we can get a cubic function that is pretty close to a trigonometric function. One standard way to do that is by writing the $3$rd degree Taylor polynomial approximating the trig function at a point in the interval of interest.
Answer: No. One argument could rely on the algebraic independence of various values of the trigonometric functions. But it's probably easier to note that for $g(x)=\cos{(\alpha x+\beta)}$ with $\alpha \neq 0$ (notice this includes sine functions too),
$$ \frac{g''(x)}{g(x)} = -\alpha^2 $$
is independent of $x$ and not zero (apart from finitely many removable singularities), whereas for any cubic $f(x)=ax^3+bx^2+cx+d$ with $a\neq 0$,
$$ \frac{f''(x)}{f(x)} = \frac{6ax+2b}{ax^3+bx^2+cx+d} $$
is not constant.


Create electrum server with bitcoin core

Question: I installed bitcoin core pruned node today on my laptop. I want to connect my blue wallet to my bitcoin node I created with bitcoin core. I read somewhere that for it to happen I need to have electrum server. So can someone explain how to create electrum server with my bitcoin core to connect to my blue wallet
Answer: You need to install an Electrum server from outside of the Bitcoin Core software, there are various options: Electrum Personal Server, electrs, ElectrumX.
Alternatively you may be interested in Bitcoin Wallet Tracker (BWT) which offers more options including a one click setup and Electrum wallet plugin option.
BlueWallet also provides some Electrum servers to connect to if you want to use those.
Comment: How can I connect my blue wallet to my bitcoin core prune node?
Answer: I struggled a lot to connect Electrum <-> EPS <-> Bitcoin Core, especially 'cause of the .cookie path, the certificat problem, the configuration of config.ini and the 127.0.0.1 cookie file of Electrum.
There aren't lots of helps on Windows. That's why i've decided yesterday to do a full-explained tutorial on youtube, which explains everything: how to do, how to resolve all configuration problems, etc...
Link: https://www.youtube.com/watch?v=wxiH8hG9G-4&ab_channel=ProfEduStream
It's in french, but you can add subtitles on your own langage.
Hope it gonna help the community.
Bye
Comment: Welcome to Bitcoin.SE! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. Since your link also is to your own content, it's generally advised to disclose that. However please avoid excessively promoting your own content here, this is not an advertisement platform.


Free Arbitrage conditions in ATM swaption surfaces

Question: I'm wondering how can we check free arbitrage conditions in ATM swaptions surfaces since we only have access to Expiry, Tenor and volatility?
Can someone help me please, i didn't find any article about it.
N.B:I'm working on python
Answer: There are no no-arbitrage conditions on ATM vols of swaptions with different expiries/tenors, because the underlying swaps forward rates are different instruments. There are conditions however for these vols to be compatible with specific IR models. For instance when calibrating a Hull & White model on a set of coterminal swaptions, it sometimes happens that the models fails to fit a specific coterminal, because that would require a negative short rate instantaneous variance on the corresponding time bucket. It does not imply that the coterminal vols are not arbitrage free, but rather that the Hull & White model can only fit a limited set of market configurations.
Answer: See
Johnson, Simon and Nonas, Bereshad, Arbitrage-Free Construction of the Swaption Cube (January 5, 2009). Available at SSRN: https://ssrn.com/abstract=1330869 or http://dx.doi.org/10.2139/ssrn.1330869


How do I achieve contrary motion in second species counterpoint?

Question: I am working on this counterpoint exercise. In 9a the second half goes down. I for the life of me can't do contrary motion without it going too high. I know I need 16th notes but there are too many. I know I need to start with the octave or unison. But from there I am stuck
Comment: Using contrary motion doesn't have to mean using only contrary motion. You can adjust your counterpoint so that it makes use of contrary motion but also breaks off when necessary to stay within a reasonable range.
Comment: Where is your counterpoint? You say it goes too high. Show what you tried.
Comment: @DylanCataldo  What book is your example from please?
Answer: Starting at the octave is definitely going to be easier.
I've submitted an example of avoiding voice crossing, but I just noticed that you think you need 16th notes. The second species is 2:1 so I would have expected eighth notes against quarters and vice versa.
Also, I had to wipe my computer recently and I rushed to install notepad which doesn't support 6/4 but luckily did have 12/8. :-(


In C#, is there a way to consistently be able to get the selected text contents of currently focused window?

Question: In my c# .Net application, I've been trying to be able to retrieve the currently selected text in the currently focused window. (Note that it can be any window open in windows, such as word, or safari).
I'm able to retrieve the handle to the currently focused control. (Using a couple of interop calls to user32.dll, and kernel32.dll).
However, I've been unable to consistently be able to get back the selected text.
I've tried using SENDMESSAGE and GET_TEXT. However this only seems to work for some applications (works for simple applications like wordpad, doesn't work for more complex applications like firefox, or word).
I've tried using SENDMESSAGE and WM_COPY. However, again this only seems to work on some controls. (I would think that WM_COPY, would cause the exact same behaviour as manually pressing CTRL-C, but it doesn't).
I've tried using SENDMESSAGE and WM_KEYUP+WM_KEYDOWN to manually stimulate a copy command.   BUt this doesn't constantly work either. (Perhaps of an overlap with the actual hotkey pressed by a user to invoke my applications).
Any ideas on consistently being able to retrieve the currently selected text ? (on any application).
Answer: I got this working by a combination of a couple of things.  So:

Wait for whatever modifiers are currently held down to be released.
Send control+c (using this answer Trigger OS to copy (ctrl+c or Ctrl-x) programmatically)
        bool stillHeld = true;
        int timeSlept = 0;

        do
        {
            // wait until our hotkey is released
            if ((Keyboard.Modifiers & ModifierKeys.Control) > 0 ||
                (Keyboard.Modifiers & ModifierKeys.Alt) > 0 ||
                (Keyboard.Modifiers & ModifierKeys.Shift) > 0)
            {
                timeSlept += 50;
                System.Threading.Thread.Sleep(timeSlept);
            }
            else
            {
                stillHeld = false;
            }
        } while (stillHeld && timeSlept < 1000);

        Keyboard.SimulateKeyStroke('c', ctrl: true);

I'm using WPF so Keyboard.Modifiers is System.Windows.Input.Keyboard, whereas Keyboard.SimulateKeyStroke is from Chris Schmick's answer.
Note, timeSlept is my max time to wait for the user to let go of the key before continuing on its merry way.
Answer: I managed to get text for wordpad/notepad and anything that supports UI automation.
The code below may work for you in some cases. I'm going to get a start on using Reflector to see how windows does it for textboxes in the TextBoxBase.SelectedText property.
public static string SelectedText
{
    get
    {
        AutomationElement focusedElement = AutomationElement.FocusedElement;

        object currentPattern = null;

        if (focusedElement.TryGetCurrentPattern(TextPattern.Pattern, out currentPattern))
        {
            TextPattern textPattern = (TextPattern)currentPattern;
            TextPatternRange[] textPatternRanges = textPattern.GetSelection();
            if (textPatternRanges.Length > 0)
            {
                string textSelection = textPatternRanges[0].GetText(-1);
                return textSelection;
            }
        }
        return string.Empty;
    }
    set
    {
        AutomationElement focusedElement = AutomationElement.FocusedElement;
        IntPtr windowHandle = new IntPtr(focusedElement.Current.NativeWindowHandle);
        NativeMethods.SendMessage(windowHandle, NativeMethods.EM_REPLACESEL, true, value);
    }
}

Comment: Nice idea, although on my machine (Win 7) .. it doesn't work on .Net 3.5 WPF apps .. the windowHandle returned is always zero.
Answer: I don't believe that it is possible, the currently focused may not contain any selected text. (It may not even contain any text at all). Or the current selection could be an icon, or an image.
Perhaps requiring the user to copy the selected text to the clipboard first may be a solution.
Comment: In my case, I can assume that it's alway text selected.
Answer: I've possibly misunderstood the question, but could you just send Ctrl+c? If you know the window is always foremost and the text to be copied is selected?
SendKeys.SendWait("^c");

Once copied to the clipboard, it's not tricky to programatically retrieve the contents (you could even check it's actually text at that point).
Comment: I tried this along with SENDMESSAGE KEYUP/KEYDOWN. It doesn't always work either. I think its an overlap of the keys. (i.e. user pressed down on some key combination to activate my program say ctrl-shift-p, ctrl-c is invoked by program, and keys up on ctrl-shift-p, and ctrlc isn't understood).
Answer: I think creating clipboard monitor is a good option. I suggest you to look at Klipper (KDE clipboard module), it copied everything you select in the clipboard list, either content is file, folder or some text.
More details can be found here.
Answer: Hm... you find it to be easy? How come?
The best alternative to SendKeys.SendWait("^c"); I found was this one:
http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=46203
However, it only works for a few apps, like notepad. For web browsers, it just crashes.
Anyone got anything better?
Answer: Try the GetWindowText() API on controls for which the other methods do not work.


What is this card game called and it's rules

Question:
Does anyone recognize this layout? It's a home made board with arranged cards. I know it was played by 6 players, and pennies were placed by each player on the "kitty" that's shellacked on the board. Sorry, that's about all I remember. My parents and their friends played it on a regular basis circa 1970's.
Thanks for any input.
Comment: Are those cards supposed to be there from the beginning of the game or could this layout be some kind of 'snapshot' of a game in progress?
Comment: Are your parents still around to ask? (Sorry if that's a sensitive question.)
Comment: I notice that we only have Aces, deuces, and 10-K on the board. Could it be a reduced deck size? I thought it was Pinochle at first, but there are no deuces in that.
Comment: Would also help to know the country this game was played in, respectively nationality of players
Answer: This looks like a board that could be played similarly to the commercialized version of Rummoli (Canada).

Essentially, a number of hands are distributed to all players + a spare kitty hand (usually called widow in this game, but kitty, crib, or dead hand also can be heard).
4 phases to the game:

Ante: Everyone drops a penny (or whatever) into each of the nine pots. Your board seems to have 12.
Swap: The dealer can choose to keep his hand or swap it for the kitty. Otherwise, it can be auctioned off: whoever is willing to pay most among nondealers pays the amount to a central pot (although in this context could go right on the cat).
Poker pot (doesn't seem to be a thing on your board): One of the 9 pots is awarded to whoever can show the best poker hand among 5 of his best cards beating any other person's best cards.
Playing out: Whoever wins the poker pot phase (again, difference with your board) draws out the lowest card in hand, e.g. 4 of clubs. Any player can/should play the 5 of clubs. Then the next card in sequence and suit draws out cards until no one plays the next card. Last person to play the card in the previous sequence then must play his lowest card from an oppositely coloured suit (from clubs: either hearts or diamonds but not spades) or pass. This goes on until a person clears his hand down to zero cards. This person would win the central pot, and get paid out for opponent's dead cards. Having said all that, there's a few things to remember, which is where the other pots come in:
The other pots. When playing out, if you manage to play any of the cards on the board, you can claim from the pots. It's that simple. Commercial Rummoli pays out to: 10 of spades, jack of diamonds, queen of clubs, king of hearts, ace of spades, as well as any person able to play both the king+ace of diamonds or 789 together in any suit. These comprise the 7 card pots in Rummoli. Any card not played (by virtue of being in the kitty, not played due to being outmaneuvered, split between multiple players, or locked in hand due to a deadlock) leaves the pots intact, and grow on the next hand, and so on.
When a deadlock occurs, people must pay the central pot the number of cards' worth in coins, making the next pot bigger. This usually occurs if there is an inordinate number of one colour of dead cards in the kitty.

Differences between the commercial version and the table I see here:

The deuces: it makes sense to probably incentivize the reward of playing the twos of each suit as it makes you less likely to have the tail end of the sequence.
Sequence pot: 89T of diamonds.
Double diamond: QK instead of KA.
Tenner: Ten of hearts instead of spades.
No poker pot.

Otherwise, the resemblances are too similar for it to be something else.
Essentially, it's not the most neurostimulating game, but it does teach some basic decision-making (keep a hand with 1 pot to claim, or swap for a chance at better/more?) and failed probability (if you have the ace of spades and someone finishes with their king, you get nothing!). Great game to stimulate 6-14 year olds as well as some social gaming among adults or a family mix of sorts. The game is usually played with 50 "tokens", but could easily be 50 cents or 50 dimes. There's a possibility of some house rules applying as well as if someone forgets to claim their pot, how to deal with it locally (it's usually dead within a certain period x of playing the card (either as you play it, or before the cards are discarded for the next sequence of cards).
Hope this helps you with what you need to know!
Comment: It also looks like it has elements of Tripoli. https://www.pagat.com/stops/3in1.html
Comment: @LeppyR64 That looks closer than Rummoli.  Post it as an answer
Answer: Could be a derivative of the German/French game Pochen, see https://de.wikipedia.org/wiki/Poch , an early Poker-like game.


Is it possible to reference a locally-created VF component in a VF email template from a managed package?

Question: There is a Visualforce email template in a managed package that I would like to modify to include a locally-created Visualforce component. All aspects of the locally-created component - the component itself, and all attributes - are global (even its class and all its variables are global), so there shouldn't be any access issues.
However, there is a hard catch I'm seeing. If I reference c:MyLocalComponent in the template, there is an error upon saving the template which states: "Unknown component c:mylocalcomponent".
I'm betting the reason is because "c:" resolves to the managed package namespace, since this is in the context of a managed package template. But there is no local namespace I can explicitly reference as an alternative - this is meant to live in a normal production org which doesn't (and can't) have one. This is a huge catch, because the local namespace (or lack thereof) is normally captured by using "c:". So, it seems like a catch 22, and thus an impossible task to accomplish.
Hoping someone can prove me wrong?
Here is the managed package template throwing the error on save:
<messaging:emailTemplate subject="Please review" recipientType="User" relatedToType="ns__CustomObject__c">
    <messaging:htmlEmailBody >
        <c:MyLocalComponent recId="{!relatedTo.ns__RecordId__c}"/>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

Here is the locally-created component MyLocalComponent:
<apex:component controller="MyLocalComponent" access="global">
    <apex:attribute name="recId" description="Record ID" type="string" assignTo="{!recordId}" access="global"/>
    <apex:outputPanel>Record ID: {!recordId}</apex:outputPanel>
</apex:component>

And here is the class:
global class MyLocalComponent
{
    global MyLocalComponent(){}
    global Id recordId {get;set;}
}

Answer: I spoke with Salesforce support, who confirmed that indeed this isn't possible.


Modify Enunciate generated configuration file to use the latest jackson library for CXF

Question: Enunciate generates the cxf-jaxrs-servlet.xml file automatically and specifies: org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider as the JAX-RS provider.  This class has changed to com.fasterxml.jackson.jaxrs.JacksonJaxbJsonProvider in the latest Jackson library.  How can I make Enunciate specify the new class as the JSON provider in the automatically generated file? Or can I make Enunciate to use a user provided XML file?
Answer: I had a similar issue and am using Maven with Spring. I was able to solve this by using the maven replacer plugin and setting it to overwrite the org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider in jaxrs:providers and replacing it with com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.
Answer: Unfortunately, there's not a good way to do that at the moment. We're tracking support for Jackson 2 at ENUNCIATE-719.


Could we get an opt-in feature to get notified when fellow mods record an absence?

Question: I logged into one of the sites I moderate this morning and just happened to check the dashboard and noticed that one of the mods had recorded their absence. It got me thinking--if I hadn't happened to check, I would have had no idea we were down one mod. Now, I know any mod can easily notify fellow mods in chat, but I understand how sometimes that might fall by the wayside (it certainly has for me before). The mod absence record is already completely visible to other mods, so would it be possible to have a checkbox above it to be notified of changes? I don't care whether it's a Stack Exchange inbox notification or an email or either/both.
Comment: I just tend to leave a note on our group chat. If I'm on a mod break, I'm probably non communicable or just need a break so its nice to let the other mods know
Comment: @JourneymanGeek Yes, that's in my question.
Answer: The least intrusive solution might be to put an indication on the main dashboard at <code>/admin/dashboard</code> where the outstanding flags are displayed as this is probably where most moderators go to see if there's anything that needs their immediate attention.
This doesn't require you to view any other pages or opt in to a notification to find out that a moderator has marked themselves as absent and most moderators will visit the dashboard on a regular basis.
Comment: It already does that :D
Comment: @JourneymanGeek I know it's on the history tab, but it is on the main dashboard page?
Comment: @JourneymanGeek No, it doesn't. You're probably thinking of the `/admin` page which is also referred to as the dashboard.
Comment: I think I'd be fine with this solution. I check flags all the time, so I'd be likely to see it there.


Which peers does a node broadcast a new block to?

Question: In the Bitcoin network, when a miner discovers a new block, he needs to broadcast it to other nodes. Does the node only broadcast to outbound connections or does it broadcast to inbound connections as well? I hope to get the result according to the source code and it would be great if the answer would point out the file of the corresponding code.
Answer: All peers are treated equally when relaying chain-extending blocks (as James C. stated in a comment on another answer). The node will announce the block to all of its peers and since that block was just found, all of the peers should request the new block.
Many miners will also announce new blocks on Fast Internet Bitcoin Relay Engine (FIBRE) in addition. Any new block on FIBRE will be immediately broadcast to all participants in a compressed format based on compact blocks (BIP152).
Answer: The number of peers connected to your node is configurable. You can increase it from 8. Your node will broadcast to the connected peers, who, in turn, will broadcast to their connected peers.
Comment: You can configure inbound, outbound and permanent connections for your node. I am not sure what 117 refers to, inbound? Outbound connections are also foreign as their addresses are discovered on the network(not permanent). In any case, you can set the limits there. All connections are treated equally in respect to broadcasting, propagating of chain-extending blocks.
Comment: For each node, up to 8 nodes can be actively connected and 117 foreign connections can be accepted. So is the broadcast block broadcast to 125 nodes or just to the actively established nodes?
Comment: This is no longer true. Blocks are no longer sent unsolicited.


What happens when the direction of initial current through an inductor is opposite of the direction of applied current?

Question: I am having trouble understanding the behavior of current through an inductor when the direction of applied current is the opposite of what is initially flowing through it. An example is that when an inductor is initially connected to a current source that drives the current clockwise, and then at time t=0, the switch flips such that it is now connected to a current source that drives the current counter-clockwise. I know that the current cannot instantaneously switch directions and I think this is where my confusion stems.
Comment: What if a capacitor initially charged at 1V is connected to a -1V voltage source? Try comparing this....
Answer: The inductor will produce a voltage impulse at the instant the step change in current occurs.
Answer:
An example is that when an inductor is initially connected to a
current source that drives the current CW

Here's your first problem; connecting an inductor (a pure inductor) to a current source requires that to instantly drive the current, an infinite voltage must be present and things fall apart when that happens.
However, let's say you can overcome this initial problem by having the current source ramp up from zero amps...

then at time t=0, the switch flips such that it is now connected to a
current source that drives the current CCW.

And here's your next problem; current cannot change instantly in an inductor without an infinite voltage being present. It's basically as I said earlier but it's now unresolvable without the presence of infinite voltage i.e. no amount of fiddling with ramping up or ramping down currents can avoid infinite voltage without the "experiment" becoming flawed in what you are trying to achieve.
However, if you said that you applied a voltage across an inductor and after a short time 1 amp was flowing and then you reversed the voltage then that's OK. At the instant you reversed the voltage, 1 amp would still be flowing in the inductor (despite the voltage being reversed). Over a short time that 1 amp would ramp down to zero amps and, then begin climbing in value (at the same ramp rate) but in the opposite direction: -
$$V = L\cdot\dfrac{di}{dt}$$
It's all embedded in the above equation. Try this little diagram: -
Comment: +1. I enjoy your perspectives and your writing on inductors/transformers.
Answer: Qualitatively, anything that tries to reduce the current in the inductor is also trying to collapse the magnetic field in the inductor. When the magnetic field collapses the energy has to go somewhere and that energy goes towards keeping maintaining current through the inductor as best it can.
For example, suddenly introducing a high impedance in the current path to interrupt/reduce the current to the inductor will cause that stored energy in the collapsing magnetic field to produce a massive voltage spike to continue to drive that same current through that impedance so that the inductor current is maintained. This is like trying to rapidly, but passively, dump energy from the magnetic field.
Trying to instantaneously reverse the current through the inductor is even worse than that so the spike would be even higher. The energy released in the collapsing magnetic field of the inductor will not allow the current to change instantaneously no matter how hard you try. How hard you drive that opposing current only affects whether the the inductor holds out longer or shorter before it exhausts the energy stored in its magnetic field trying to resist and the current direction reverses. This is like trying to actively suck energy out of the magnetic field.


PHP Image Upload and Validation

Question: I have a PHP script that uploads an image file, checks it for size, extension, and type. It then converts it to png, saves it to a folder outside the web root with a randomly generated name, then moves it to a specific folder inside the web root with a new filename that matches the user's username. By default, users have a generic profile image, but if they use the script to change their picture the database is updated to reflect the new filename. So far it's working without any obvious problems, but I would just like to have the script reviewed for possible issues. Also, what changes should be made to make it more secure?

<?php
if(isset($_FILES["image"]["name"])) {
    $imageFile = ($_FILES["image"]["name"]);
    $imageType = ($_FILES["image"]["type"]);
    $imageSize = ($_FILES["image"]["size"]);
    $validext = array("jpeg","jpg","gif","png");
    $fileExt = pathinfo($imageFile, PATHINFO_EXTENSION);
    $fileExt = strtolower($fileExt);
    $imageErrors = array();

    if($_FILES["image"]["size"] > 1048576) {
        $imageErrors[] = "ERROR! File size was too large! It must be under 1MB.";
    }

    if((($imageType == "image/jpeg") || ($imageType == "image/jpg") || ($imageType == "image/gif") || ($imageType == "image/png")) && in_array($fileExt, $validext)) {
    }else{
        $imageErrors[] = "ERROR! Not an image file! Only jpg, gif, and png allowed.";
    }

    if($_FILES["image"]["error"]) {
        $imageErrors[] = "ERROR! Looks like there was an error. " . $_FILES["image"]["error"];
    }

    if(empty($imageErrors)) {
        if(exif_imagetype($_FILES['image']['tmp_name']) ==  IMAGETYPE_GIF) {
            $newpng = 'gifto.png';
            $png = imagepng(imagecreatefromgif($_FILES['image']['tmp_name']), $newpng);
        }
        elseif(exif_imagetype($_FILES['image']['tmp_name']) ==  IMAGETYPE_JPEG) {
            $newpng = 'jpgto.png';
            $png = imagepng(imagecreatefromjpeg($_FILES['image']['tmp_name']), $newpng);
        }
        elseif(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_PNG) {
            $newpng = '.png';
            $png = imagepng(imagecreatefrompng($_FILES['image']['tmp_name']), $newpng);
        }
        $temporaryPath = "../../images/" . uniqid() . $newpng;
        $sourcePath = $_FILES["image"]["tmp_name"];
        move_uploaded_file($sourcePath, $temporaryPath);
        $profilePictureMessage = '

          SUCCESS! Image file uploaded!

' . chr(13) . chr(10);
        $finalPath = "images/profilePictures/" . $username . $newpng;
        rename($temporaryPath, $finalPath);

        $query = $con->prepare("UPDATE users SET profilePic = :profilePic WHERE username=:un");
        $query->bindParam(":profilePic", $finalPath);
        $query->bindParam(":un", $username);
        $query->execute();
        unlink($newpng);
    }else{
        foreach($imageErrors as $imageError) {
            $profilePictureMessage = '
'
          .$imageError.
        '
' . chr(13) . chr(10);
        }
    }
}
?>

<?php echo $profilePictureMessage; ?>

      <form action="settings.php" method="POST" enctype="multipart/form-data">
        Change profile picture

          <input type="file" class="form-control-file" name="image" accept="image/png, image/gif, image/jpeg">

        <button type="submit" class="btn btn-primary" name="saveProfilePictureButton">Save</button>
      </form>

I welcome any and all feedback, and thanks for your time.
Answer: The code is pretty secure, but it could use some cleanup.
Security
Regarding security, you are doing the right thing checking the file extension.
Storing all images as png is a smart move, that should, in theory, prevent uploading PHP code inside files, as it can be done with jpg. But I wouldn't be so sure - sooner or later there will be found a way to keep the PHP code during this transformation too. I wouldn't call it much a problem though, as long as you don't have these files executed, through a web-server of via include. But to be completely 100% sure, consider having a different web server for the images, either your own or a DSN.
Code structure
The biggest flaw i see in this code so far is somewhat surprising. It's its place inside HTML. But in fact, it shouldn't have such a place. Any PHP data processing should be done before starting any output.
Moreover, when you process an HTML form, a successful processing should lead to HTTP redirect, which means there must be no HTML before form processing at all.
Storing the path
Do you really need it? given it's always constant and can be recreated from the user info, why bother storing the image path at all?
What you should really do is always use the row id instead of some other information to address a row in the database. Yes, I mean the username. Everywhere where you are using the username to identify a user, it should be the id.
Testing
Regarding the code, first of all I would like to give you a simple but often overlooked advise.

So far it's working without any obvious problems

Most people consider such a statement after testing only the good scenarios. But the real testing actually begins when you test for the bad scenarios. Hence you should really test not only with good images but with bad uploads as well.
From this point of view I would say that testing $_FILES["image"]["error"] should go first and prevent all other code from the execution as it will produce many unnecessary errors.
The same notion goes for the error echoed out. $_FILES["image"]["error"] is actually just a number and could be of some use only for a sophisticated PHP dev but not for a casual site visitor. Verbal error explanations can be found in the PHP manual so consider translating at least some errors for the user.
Code repetiton
I don't see much point in getting and testing the $imageType - don't you have the same test later on? just add an else condition to your exif_imagetype test.
There is also a lot of repetition inside this condition as well. I would rather create an array with function names and then just call it.
I also don't see much point in moving files around. Why not to create a file in one go?
Minor inconsistencies
they are minor but a good looking code shouldn't have it anyway

there is no use for braces when you assign a variable like this ($imageFile = $_FILES["image"]["name"];)
for some reason you assign every $_FILES array member to a distinct variable but tmp_file. Why such a discrimination?
Avoid "magic numbers". Every hardcoded value should really go into config section, so it could be easily changed in the future or assigned from some configuration setting. This is related to the max upload size and the input name
HTML formatting inside error messages is actually not a minor issue but a serious design flaw. Add every decoration at the output time.
inconsistent use of nested functions. imagecreatefromjpeg is nested but strtolower is not. why?
if with empty body is silly. Add a negation operator instead.
you can safely write chr(13) . chr(10) as just "\n"

The code
could be something like this
if (isset($_FILES["image"]["name"])) {
    $inputName = "image";
    $imageFile = $_FILES[$inputName]["name"];
    $imageTmp  = $_FILES[$inputName]["tmp_name"];
    $imageSize = $_FILES[$inputName]["size"];
    $imageType = exif_imagetype($imageTmp);
    $fileExt = strtolower(pathinfo($imageFile, PATHINFO_EXTENSION));
    $validext = array("jpeg", "jpg", "gif", "png");
    $maxFileSize = 1024*1024;
    $finalPath = "images/profilePictures/$userid.png";
    $functoions = [
        IMAGETYPE_GIF => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG => 'imagecreatefrompng',
    ];

    if ($_FILES["image"]["error"]) {
        $imageError = translate_file_error($_FILES["image"]["error"]);
    }elseif ($_FILES["image"]["size"] > 1048576) {
        $imageError = "File size is too large! It must be under 1MB.";
    } elseif (!in_array($fileExt, $validext) || !isset($functoions[$imageType])) {
        $imageError = "Not an image file! Only jpg, gif, and png allowed.";
    } else {
        imagepng($functoions[$imageType]($imageTmp), $finalPath);
        header("Location: ".$_SERVER['REQUEST_URI']);
        exit;
    }
}

Answer:
Try to keep your processing code separated from your markup printing code.  When you mix the two together and obey proper code tabbing, you end up with lots of tabbing which causes "arrowhead code" and excessive line width (horizontal scrolling isn't fun).

Please read all of the PSR-12 Coding Standards -- especially about control structures.  This will help you to write consistent and professional scripts.

$imageFile, $imageType, and $imageSize don't need their values to be wrapped in parentheses.

I think you should unconditionally declare a $validImageTypes array which can be used to validate submissions and to populate the accept attribute in your form.

Your two-point image type check should not have an empty if branch and it should not have so many piped conditions -- there should be just two in_array() calls.
if (!in_array($imageType, $validImageTypes) || !in_array($fileExt, $validext)) {
    $imageErrors[] = "ERROR! Not an image file! Only jpg, gif, and png allowed.";
}

You are making repeated calls of exif_imagetype($_FILES['image']['tmp_name']), but it would be better to use a switch to avoid redundant calls.

PHP Image Upload and Validation


Why are there multiple sequences for the same segment for an individual "strain" of influenza?

Question: I am looking at the genome of the influenza virus being used in the flu vaccine 2017-2018: A/Michigan/45/2015.
When I look below at the individual segments, there are 4 sequences for each segment - shouldn't there be only one for a single "strain"? Is this due to rapid mutation rates? Or is it that they are including both positive and negative sense of the virus?
Edit: sorry, link here:
https://www.fludb.org/brc/fluStrainDetails.spg?strainName=A/Michigan/45/2015(H1N1)&decorator=influenza
Answer: It looks to me that the website you're looking at is mostly taking publicly available data from Genebank (the NCBI repository for sequence data) an collects it to form an overview.
For your question this means that there are 4 available sequence datasets for the A/Michigan/45/2015 influenza strain - they are likely very similar but based on the reported segment length not quite identical.

Or is it that they are including both positive and negative sense of the virus?

If you mean the positive and negative strand of the DNA, then no - since the sequence of these two is always complementary the Genebank repositories only stores the forward sequence.
You can also see that the 4 different datasets have similar Acession numbers:
KY117020 - 27 (Passage M1/C3)
KU509700 - 07 (Passage E1)
KU933490 - 07 (Passage E3)
KY090607 - 14 (Passage M1/IR)
You can look up more details for these accessions on the genebank website:

It seems that all 4 datasets came from the same publication
... which apparently was never published (so it's not available online), but it might be part of some WHO program?
The main difference of the 4 datasets I can find is the passage of the strain. I'm no virologist, so I'm not quite sure what it means, but in cell biology passage describes the time a certain cell line has been in (in vitro) culture.
Answer: This is pretty typical for influenza, and reflects the ambiguity of "sequence" when talking about rapidly-mutating RNA viruses. Such viruses exist as a "cloud" of variable sequences; a single replication of influenza is likely to contain variants at every single site of the genome.  That also allows the virus to undergo extremely rapid natural selection, including during laboratory passages (which are obviously not performed using infected humans, but might be in various cell types, or very often in eggs).
A common scenario for an influenza isolate (especially one that, like MI/45, is used in vaccines) would be to swab someone's nose, use the swab to inoculate an egg to prepare a stock virus, send that stock to several other labs, grow a subset in cells, have another lab grow some in their cells or eggs, and so on. If it's used in vaccines, it might be made into a reassortant with a different (less virulent) backbone, but the surface genes would still be termed MI/45. Each lab would sequence the virus, often at multiple steps in the passage; and at each step, there's an opportunity for the virus to either undergo selection, or simply to drift, and change its sequence. Or, of course, if may not change, and identical sequences might be deposited into the databases, perhaps starting at slightly different points depending on each lab's sequencing protocol.
Many viruses are only sequenced once, perhaps as the original isolate or as an early passage, because there's no reason (or capacity) to look further at the tens of thousands of isolates that are taken every year, but where there's a reason to look at an influenza virus more than once, standard protocol is to re-sequence it each time it's used. I can guarantee that there are far more than just 4 sequences of MI/45 out there, probably there are more like 400 that have been done world-wide, it's just that there's no point in depositing all of them.


Using evolutionary algorithms in molecular biology?

Question: I am currently an MSc student studying molecular biology (on paper I'm a chemist) and soon I have to talk to my supervisor about my future, PhD research topic. Besides molecular biology I'm also interested in machine learning, mostly in evolutionary algorithms (evolutionary strategy alg.s, genetic alg.s) and Bayesian optimization, from both of which I have written multiple, working programs in C# at home. Due to the massive need for people trained in informatics I'd like to convince my supervisor to include this topic into my future research, especially as I have already acquired some basic skills in these areas. However I have only seen research examples that are purely computational and these didn't include any laboratory work. Can you provide me some insight into the use of these techniques in molecular biology and ways of connecting these with laboratory work?
Comment: Why are you coding in C-sharp? This is a language almost never used in bioinformatics or molecular biology, not least because it is specific for Microsoft Windows, a platform that is generally avoided in this area. Sounds rather as if you are putting the cart before the horse. If your supervisor can't suggest a wet project that requires computational analysis, this list isn't going to. Perhaps you need to find a new supervisor.
Comment: @David I don't restrict the language options only to C#. I can also program in Python at some level, but I am willing to learn new languages. The main reason I'm asking this is that my supervisor hasn't got much experience with machine learning but he is at home on for example MD simulations, model fitting, etc., and machine learning can come in handy in these areas. I know how to write GAs, I know how to do research in the lab, I know that these two can be somehow used together, but I cannot give concrete examples. It's just I have acquired this skill that I dont want to completely neglect.
Comment: @Zebrafish — These days everbody in bioinformatics (except oldies like me) seems to use Python wherever they can. The heavy-weight stuff is often written in C++ (e.g. parts of Trinity). Java is still used (because it is taught by CS Departments), but less than a few years ago. Web stuff tends to use MySQL or other relational databases and various JavaScript and other frameworks. PHP is less popular than in other areas. But that's just my impression — others may have a different view.
Comment: OK, but in my experience people tend to do "all informatics" PhDs, or do a PhD where they generate the sort of data (e.g. RNAseq) where it helps if you can use Unix and write the odd glue script, but for the most part you are using powerful programs written by professional computing scientists. I'm not sure it's as easy as some of your respondants make out.
Comment: @David What languages are mostly used for this sort of stuff?
Answer: The first thing that springs to mind is modeling and simulating the evolution and specificity determinants in protein - protein binding. You can easily include an experimental  part and make it as big as you like (the bigger, the better). For a useful set of physiologically important protein - protein interactions and background info on the specificity and affinity determinants in those systems, see Ivanov et al., 2017 and Ivanov et al., 2016, and the references therein.
Answer: There are countless really worthwhile ways to use evolutionary computation (EC) in molecular biology.  The chief advantage of EC is that it can find solutions to problems that are too complicated, too nonlinear, etc., to solve by more direct methods.  I've used genetic algorithms to evolve models, to find patterns in data, to design optical systems, you name it; and almost always a GA finds solutions I'd never find on my own.  Sometimes it's a challenge to find a representation for the solution space that fits the problem well, or to find recombination/mutation operators that work well, but that's where human insight is important. Bottom line: if you can list some problems that fascinate you (or better, fascinate both you and your supervisor), I'd be happy to give you some concrete suggestions.
Comment: Our groups research focuses mainly on the structural investigation of miniproteins (such as the Trp-cage motif) through NMR, XRD and CD studies, but we are pretty diverse when it comes to research; my current thesis-work is about bacterial expression optimization in a biorector, we also synthesize small peptides, sugar-derivatives (through classical organic chemical synthesis), do MD calculations and all of these topics are coordinated by my supervisor (so we could say that all of these fascinate him). As for me, I am willing to do almost any research in these areas.
Comment: I've opened a chat room, "EC in Molecular Biology", which should be a better place to carry on the conversation.  Optimizing bacterial expression in a bioreactor is probably a great place to start looking for an application for evolutionary computation.


Which are the databases used in gtk?

Question: We can use databases sqlite,mysql etc with python and qt.But i dont know which database is used in gtk and how to use it.can anybody help me to find the database for gtk and also give some example for HOW TO USE IT (i am beginner).
Comment: There is no "the database" for gtk. Your database selection depends on what you are trying to do.
Answer: GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets, but it is not a programming language itself. It is written in C but has been designed from the ground up to support a wide range of languages, not only C/C++. Using GTK+ from languages such as Perl and Python (especially in combination with the Glade GUI builder) provides an effective method of rapid application development, therefor you can use any of the technologies you wrote.
Answer: As ergosys said, GTK favors no database API. You can use what you want.

Which are the databases used in gtk?


How should this Untagged question be categorized

Question: Shouldn't  this question be moved to SO where a "release" tag exists or if not, how can this untagged question be categorized?
Answer: There's a couple issues with this, so I'll address them one at a time.
Should it go to SO?

No, because SO is for questions specifically about programming.

Should it go to Programmers

Quite possibly, because it certainly has to do with software engineering.

Does it belong here

Personally, I feel that questions about the general SDLC should be allowed here. However, I don't recall if this has been addressed on meta. A quick search didn't yield anything, but I fully admit I could have searched harder.

How should it be tagged?

If we decide that SDLC questions should be allowed here, then it should be tagged with a new tag, SDLC. If we decide they shouldn't, then we shouldn't tag it - I would then migrate it to programmers.
Comment: SO is about programming and Programmers is about s/w engineering? Hmm ok. I thought Programmers is to do with concepts about s/w development only. But the thing is this question talks about a release candidate. I've seen questions about release candidate and SDLC on SO.
Comment: @ilm you may have seen them (there are in fact more on SO than on Programmers), but they shouldn't be there. In 99% of cases, if you don't have code, it doesn't belong on SO.
Comment: I as well like the SDLC questions. By QAing the process we make QAing the code far easier.


Only 10% of the shares for employees

Question: I am in negotiations with a startup to join them as the 5th employee. The current offer includes 0.3% of the shares, which I thought it was low. When I sent them my counter offer asking for more, they explained to me that they only have 10% of the shares for the employees so they can't offer more. Is this normal? I thought a startup would have more shares to distribute among their employees. The founders also mentioned that even if they wanted to give their own shares to the employees, they would have to offer them to the investors first.
Comment: @JoeStrazzere title matters?  It's a 5 person company.
Comment: I will lead the development of their core software technology.
Comment: 10%? nice. i never worked in a company that offered any equity. i think your location and industry matters, so maybe include that in the question.
Answer: Early stage startups need to preserve their equity in order to attract new employees and investors. Giving away too much too early is a sure way to stunt future growth.
It shouldn't matter to you if it's "normal" or not. Decide if your compensation is sufficient. If not, ask for more. If denied, move on to other opportunities.
Comment: @balborian You need to keep as much equity as possible to attract angel and venture investors.  Many will insist on a controlling interest (50% + 1 share) if they're going to bankroll the startup.  There is also a potential for conflict of interest if employees own too much.
Comment: Thanks for your answer. Is it common to have only 10% of the shares allocated to employees? If not, does such low % indicate something about the prospects of the company?
Answer: Yes, setting aside 10-15% of stock for employees is the recommended amount in all startup playbooks - here's a Forbes article to that effect.
Having said that, as employee 5, I would expect .5-1% usually, though it does matter whether you are a strategic hire or just a temporary measure.  This stock offer indicates the latter. Which may be fine, startup stock is of equal value to magic beans and isn't a meaningful part of your total compensation.
Answer: Working for a tiny startup is very risky. The startup is likely to fail. There won't be any job security. As the person leading the development of its core technology, you will be overworked and you'll get as much stress as the CEO.
And even if the startup succeeds, which is very unlikely, expect that your shares will get so diluted that, that they'll be worth absolutely nothing.
Start the negotiation with that mindset in mind. Insist on getting market value for your skills. And if they say no, that's fine. Walking away is most likely your optimal outcome.
And in the future, if you really want to start some kind of partnership, read this book first, The Partnership Charter by David Gage.
Answer: In early stage startups who is a founder and who is an employee can get mixed up. Often people will join thinking they are a founder when really they are an employee and this sounds like what's happened here.
They see you as an employee and so have allotted a small amount of shares as an incentive to employees. The rest of the shares will be allotted to founders / seed investors and they will probably be thinking also about future investment and funding rounds.
Sounds like you'll be their main tech person. If you are the only tech person then run a mile as the current founders are building a tech company whilst not respecting that tech should be paid an good share of the company and seen as a founder. This is also common when the founder have put some of their own money into the company. As you are coming along and only adding your labour only then your are seen as an employee.
At this low equity make sure they are paying the correct wage if you really want to join.

Only 10% of the shares for employees


In the photoelectric effect, the current increases as the intensity of the light increases. Is there an equation for this?

Question: I've concluded the intensity of the light (which is proportional to $\frac{1}{r^2}$) is proportional to the change in flow of electrons per unit of time. Is there an explicit equation showing this relationship?
Comment: An implicit equation is very difficult, because it would depend on the dimensions of your surface, the orientation of the surface wrt to the source, the source distance and power of the source. At best, you can argue about an almost linear relationship if your source is quite close and the dimensions of surface are quite small.
Comment: I roughly calculated the requirement for an orthogonal rectangular surface. Would you be interested in that?
Comment: You've made an  observation; go ahead and write it up as an equation.   You're entitled to do that, it's totally normal science practice.
Answer: Essentially, calculate the number of photoelectrons emitted per unit time. This likely requires calculating the incident flux.
Note, a decent explanation from askiitians:

The number of photons incident on the plate per time (called photon
  flux) is given by
$$ \Phi = P' / E = (P/4 \pi r^2) A / hf \, .$$
If $f > f_0$ (threshold frequency) and photon efficiency of the metal
  plate is $\eta$, then the number of photoelectrons emitted per time is
  given by
$$n = \Phi \eta (P/ 4 \pi r^2) A / hf) \, .$$
Finally, the photocurrent i is given by
$$i = ne$$
where $e$ is the charge of an electron ($e = 1.6 × 10^{–19}$ Joules).
Answer: Once the photons have exceeded the energy threshold and are able to eject the electrons, you're correct that the intensity and electron ejection are proportional. I would expect that the proportionality constant is experimentally determined in each case. I've never seen an equation for it.
Answer: Basically, the number of photoelectrons emitted is proportional to the number of photons. We assume/know that each photon is associated with removing an electron from the metal. As the number of photons increase(i.e the intensity increases) the number of electrons increases hence the current increases since I=ne.
We can see this intuitively from the particle nature very easily.


mysql locking question

Question: Investigating/researching mysql/myisam locking. trying to find a good example of how to set the lock in appA, and determine/detect the tbl lock in appB.
searching google, not seeing much, so i must be missing something.
i'm going to be writing a php app that demonstrates this process.
pointers/thoughts/thanks..
-tom
Answer: You should have a look at MySQLs GET_LOCK() function.
Follow this link to get more information: MySQL Documentation for GET_LOCK()
This looks like it could solve your problem.
Answer: MySQL's GET_LOCK function gets named user locks, which are an extra feature MySQL provides over and above anything to do with tables.
No tables are involved so it does not invoke the storage engine and has nothing to do with myisam. GET_LOCK is available on all supported mysql versions regardless of what engines are used.

mysql locking question


no active checks on server [xx.xxx.xx.xx:10051]: host [host] not monitored

Question: I am using Zabbix Active Agent to monitor hosts over the network but getting "no active checks on server [xx.xxx.xx.xx:10051]: host [host1] not monitored." errors only in one host with same exact server/agent configuration as in other hosts. I have double/triple checked the hostname and other configurations but issue has not been resolved. I believe I must have broke something while working on Zabbix templates but not sure what I did. I noticed "cannot send list of active checks to "xx.xxx.xx.xxx": host [host1] not monitored" error in Zabbix server log. Please help.
Answer: The host is disabled.
As you say that you are not using Zabbix proxy and host seems to be enabled, possible reasons that mask the problem:

you are comparing DNS, not host name
host has visible name defined

Make sure to compare the name agent and server print in their logfiles with the Hostname field in the host properties. Keep in mind that it is case sensitive.
Comment: Hi @Richlv, Thanks for your response. The host in Zabbix Server Host Configuration page is enabled. I am not understanding what you meant by "The host is disabled Filler here". If you would not mind, could you elaborate more?
Comment: Are you using Zabbix proxy to monitor this host or is it monitored directly by the server?
Comment: Hi @Richlv, I am using Zabbix Active Agent and directly monitored by the server, no proxy.
Comment: Host is still likely disabled. Please show screenshot of host configuration.


How to express the idea of creating the story of a book?

Question: I want to find the correct way to say that I´m thinking and documenting about all the details of my book, possibly making some diagrams, describing characters, etc., instead of actually writing it. Is there a verb for that? How would I say it?
Comment: *Brainstorming*, *creating a preliminary sketch* / *outlining characters and the story*?
Comment: We would say _outlining_ in almost every case. (Interrogatives in English do not begin with an inverted question mark (¿). We use only one question mark at the end.)
Answer: If you document these, you would call that an "outline", a "sketch", or a "summary" of the book.  If you're just thinking then you would call that an "idea" for a book, as in:

I have a great idea for a book, let me tell you about it!

You can also have ideas for any kind of creative work: movies, artwork, music, etc. -- until you start on it, after which you might call it a "work in progress".
Comment: Yes, actually I want to document it. Edited. Thanks.


Item does not exist when check in TFS

Question: I use VS 2013 to check-in a file to TFS 2012 and get the following error:
The item $/MyTeamProject/MyProject/MyInterface/IAllocationBLL.cs does not exist at the specified version, or you do not have permission to access it.
Other files just work fine. I notice that the Last Check-in date is missing.

If I undo this file, it then disappears on TFS. When I edit this file again, it back to TFS and still missing Last Check-in. I still get the same error checking in this file. Any advice would be appreciated.
Answer: The best method is to save the file as a backup outside, and undo it, check in the whole project, then add the file to the project again.
Comment: well that was utterly awful. hours of work gone for me
Answer: I had same/similar issue today. Didn't found proper (or easy) solution online, and here is my workaround:

(Optional) Backup project just in case
Delete file locally
In Source Control Explorer undo changes (was delete because, auto generated files are always deleted then generated again, and i think this is just bug in studio). Ignore warnings. You will have now source controlled file with exclamation because file not exist.
Open designer and just move some table and save - that will generate all files again without updating model from database.

VOILA - your file is under source control again.
Answer: I received this error with Visual Studio 2019 and was able to resolve it by:

Backup your project, just in case.  You shouldn't need it though.
Undo the changes for everything in the project in the Team Explorer.
Go to the Source Control Explorer, Right Click the Project, and click Add Items To Folder.
Select all the items in the project folder. Click Finish
Items should reappear to check-in.  Click Check-in and it should work.

Item does not exist when check in TFS


should I let my sourdough loaf proof in the fridge or on the counter?

Question: I've been watching tons of videos on making sourdough recently, and quite a few say to let the sourdough loaf do its final proof, or rise, in the fridge. Is this necessary? Would it speed up if I just let it rise on the counter? Thoughts?
Answer: Speed is not the point. Speed is the opposite of the point. Refrigerator rising makes for a long, slow rise and flavor development - it's not unique to sourdough, it's very common in pizza dough (though not usually the "final rise" in pizza, as that would be very difficult to arrange enough fridge space for.)
You can do it, or not, or try both and compare.
Comment: I agree. In my experience, having worked at 4-5 different pizza places over my life. Typically you make the dough, break it up into dough balls of the appropriate weight for the size pizza, and stick it in the fridge overnight. Then the next day you pull the trays out, punch down the dough, and let it rise again in racks outside the fridge. When you get an order, you pull a dough ball of the rack and roll/spin it out (depends on the place) to prep the pizza. A longer proof time results in a more flavorful bread.
Answer: Two reasons to final proof in the fridge...

Flavour
Convenience

Time = flavour. Increasing the fermentation time helps bring out more flavour.
If you are too busy to follow the recipe through then you can use your fridge for convenience.


Why are lipid-soluble substances harder to excrete?

Question: I understand why water-soluble substances can be excreted. However, why are they easier to excrete than lipid-soluble substances? Why can't lipid-soluble substance be excreted just as easily in the kidneys?
Answer: Short answer
If you understand why hydrophylic compounds can be excreted, than it's kind of straightforward why hydrophobic ones can't - because they are not hydrophylic.
Background
The kidneys, through the production and excretion of urine, are the major gateway of clearing the body from toxins. Some toxins absorbed in the gastrointestinal tract can be excreted by the liver through the gall system.
Urine is watery and kidney's excrete water through ion homeostasis. Hydrophobic compounds do not dissolve in water and hence cannot be excreted by the kidneys. The liver has an important role in making hydrophobic toxins water-soluble. Often hydrophilic groups are attached to it in the liver, making them hydrophilic. If that can be achieved, they can be excreted through the kidneys. Hydrophobic compounds that are resistant to chemical modification tend to accumulate in the body in fatty tissues like the nervous system, for example the notorious polychlorinated biphenyls (PCBs).
Reference
- Chen. Activation and Detoxification Enzymes: Functions and Implications, Springer Science+Business Media (2012)
Comment: I guess what I'm wondering more about is what happens to those hydrophobic compounds that can't be excreted. (Even if this doesn't happen and the body makes sure they're made more water-soluble, let's say hypothetically it happens.) What happens to these substances then, if they aren't dissolved in the urine?
Comment: I should add that by my previous comment, I meant what happens to them as they pass through the nephrons of the kidney. They still move through the nephrons, right? Then what happens, if they aren't flushed out?
Comment: They accumulate, as said above
Comment: @lightweaver -They are, as AliceD stated, changed into more hydrophilic substances in the liver, then excreted, often through the biliary tract or the kidney.
Comment: @AliceD I understand they accumulate as fatty tissue in other places of the body. But I'm just not seeing how they end up as fatty tissue elsewhere if there isn't a mechanism by which they are saved from being excreted in the kidney, so to speak. What happens to the fat-soluble compounds as they move through the nephrons? Accumulate within the kidney? (And if this entire scenario doesn't happen, then hypothetically what would happen if it did?)
Answer: If I've interpreted your question right then I think this is the answer..
You have both lipid-solule and water-soluble in the filtrate.
Lipid-soluble substances can easily cross the phospholipid bilayer of cells lining the tubules and so are extensively reabsorbed by passive diffusion. Thus the kidney cannot actively excrete lipid-soluble substances. This means the kidneys cannot alter the plasma concentration of these substances.
Water-soluble substances are effetively trapped in the tubules. This means the kidneys can selectively secrete or reabsorb water-soluble substances via channels etc. So the kidneys can only control the excretion of (and actively concentrate in the urine) water-soluble substances.
Sorry I don't have a reference for you but you've probably already found an answer anyway since this was originally posted a year ago.
Answer: You need to understand how renal ultrafiltration works to answer this question.
In the glomerulus, hydrostatic pressure forces fluid (filtrate) across 3 barriers into the collecting tubule. The first is the membrane of the glomerular capillary, which has fenestrations (pores) which are about 8um wide; only molecules smaller than 8um and\or molecules that can diffuse across a lipid bilayer will pass this membrane.
Next, they must pass the glomerular basement membrane, which has a slight negative charge. Any negatively charged molecules will be repelled and not excreted.
Last, they must pass through the filtration slits formed by the interdigitations of podocytes that are applied to the glomerular basement membrane. This is also a very narrow passage and has a slight negative charge.
Now, none of those seems to immediately preclude hydrophobic molecules from passing through the glomerulus... but how do they get there? They have to be dissolved in blood! But that's impossible if they're hydrophobic- physiologically hydrophobic molecules are usually bound by proteins, which are hydrophilic but often have hydrophobic regions. Albumin is the classic example, and albumin is just slightly too large to pass through the filter. There is no carrier system that allows hydrophobic molecules to be shuttled to the glomerulus and then dumped off to be filtered.
Comment: Brian thanks for your effort on this answer - please add some references so that other users that are unfamiliar can understand what you're talking about and can read further if necessary


What is feat_dynamic_real, feat_static_cat and feat_static_real in gluonTS models?

Question: What is feat_dynamic_real, feat_static_cat and feat_static_real in gluonTS models?
When do we use these features while running the model? Can someone provide an example for the same?
Answer: feat_dynamic_real : dynamic (over time) real features, an array with shape equal to (number of features, target length).
if the target time series represents the demand for different products, an associated dynamic_feat might be a boolean time series which indicates whether a promotion was applied (1) to the particular product or not (0)
feat_static_cat: static (over time) categorical features, a list with dimension equal to the number of features.
You can use an array of categorical features to encode the groups to which the record belongs. Categorical features must be encoded as a 0-based sequence of positive integers. For example, the categorical domain {R, G, B} can be encoded as {0, 1, 2}. You must represent all values from each categorical domain in the training dataset. That's because the DeepAR algorithm can forecast only for categories that have been observed during training
feat_static_real: static (over time) real features, a list with dimension equal to the number of features
From gluonTS documentation here


Is it possible to program in binary?

Question: Is it possible to program in binary?
A friend of mine told me he knows someone who can program in binary. I've never heard of someone programming in binary and a few quick Google searches didn't return anything useful. So I figured I'd turn to the SO community. Does anyone have any info on programming in binary and if possible maybe a quick Hello World example.
Comment: @time4tea that's assembly, not binary...
Comment: Yes, of course. Ask this friend of a friend to produce the example. ;-)
Comment: Similar to [Can I write a program in binary directly ? How can I get the computer to execute it ?
](http://stackoverflow.com/questions/4197055/can-i-write-a-program-in-binary-directly-how-can-i-get-the-computer-to-execute).
Comment: $ad xx yy $20 $ff $d2 or something it's been a while
Comment: That By the way was my attempt at lda $xxyy jsr $ffd2, which would print something on a c64 or a vic 20, I think.
Answer: Of course.  It's more commonly called machine code.  It's basically assembly language without the mnemonic devices.  Someone who knows assembly very well could program in machine code with additional effort, referring to opcode listings (e.g. x86) as needed.
Would I do it?  No.  Even assembly is only useful in rare circumstances, and there's no reason (beside demonstrating your skills) to reject the assembler's help.
Since you asked about hello world, you should check out this article.  He shows how he wrote, then optimized, an x86 ELF program to output it.  It was originally written in nasm then modified in a hex editor.
Comment: I think I'd call that a skill like I'd call being able to touch the tip of your nose with your tongue; interesting and basically useless.
Comment: @Adam, yeah.  I was originally going to write "besides showing off", but that sounded a bit harsh.  And anyway, we all like to show off occasionally. :)
Comment: Yeah, this was more of an "out of interest" question more than a practical question. I never really intended to use it. I just wanted to see if it was possible and what it would look like.
Answer: It's very much possible to memorize machine code equivalent of assembly instructions. Actually, when writing code in assembly language, one often happens to see hex code through machine code monitors, disassemblers, assembly listings, etc. As a result, over time some instructions can be memorized in their hex form without any extra effort.

In the picture an 6502 ROM monitor is seen, where hex code and assembly mnemonics are shown side by side.

Second skill you're going to need is to transform hex code into binary which is quite easy with a trick I'll explain in a bit.
Think of the following instructions:
OPCODE       HEX
LDA #imm     0xA9 imm
STA adr      0x85 adr
STA (adr),Y  0x91 adr
LDY #imm     0xA0 imm

With above opcodes memorized only, we can write the following machine code using only pen and paper:
0xA9 0x00
0x85 0x01
0xA9 0x02
0x85 0x02
0xA0 0x00
0xA9 0x01
0x91 0x01

Actually the above is the following assembly code in mnemonic form:
LDA #00
STA $01
LDA #02
STA $02
LDY #00
LDA #01
STA ($01), Y

The above code puts a white pixel at the top-left corner of screen in 6502asm.com assembler/emulator, go ahead and try it out!

Now the trick for converting hexadecimals into binary and vice versa is to work it out only for nibbles (4-bit values).
First, remember how to convert binary into decimal. Every time you see 1, multiply that by its binary power. E.g. 101 would be 4 + 0 + 1 = 5. It can be visualized like this:
1   1   1   1 --> binary points
|   |   |   |
v   v   v   v
8 + 4 + 2 + 1
|   |   |   +---> 2^0 * 1   Ex: 13 is 8 + 4 + 0 + 1
|   |   +-------> 2^1 * 1             1   1   0   1 -> 1101 (0xD)
|   +-----------> 2^2 * 1   Ex:  7 is 0 + 4 + 2 + 1
+---------------> 2^3 * 1             0   1   1   1 -> 0111 (0x7)

With this in mind, and well practiced, the following should be possible:
LDA #00     -> 0xA9 0x00 -> 1010 1001 0000 0000
STA $01     -> 0x85 0x01 -> 1000 0101 0000 0001
LDA #02     -> 0xA9 0x02 -> 1010 1001 0000 0010
STA $02     -> 0x85 0x02 -> 1000 0101 0000 0010
LDY #00     -> 0xA0 0x00 -> 1010 0000 0000 0000
LDA #01     -> 0xA9 0x01 -> 1010 1001 0000 0001
STA ($01),Y -> 0x91 0x01 -> 1001 0001 0000 0001

With some retro computing spirit, motivation and fun, we could actually have written the entire code in binary without writing down the intermediate steps.
On a related note, Paul Allen coded a boot loader for Altair 8800 with pen and paper on an airplane, and possibly had to translate it to binary also with pen and paper: https://www.youtube.com/watch?v=2wEyqJnhec8
Answer: There isn't much call for it any more, but it has been done.  There was a time when code could be entered into a system in binary from the front console.  It was error prone.
I used to have a very short uudecoe program encoded in ASCII which could be prefixed to a UUEncoded file. The resulting file would be self-extracting and could be emailed around. I would expect the machine code was hand done.  I can't find it, and don't have a use for it even if I could.
Comment: +1 for historical perspective. Apparently there were some situations on early computers where code could be entered *only* via the front panel.
Answer: Well of course you can write the binary for the machine code and then enter the machine code via your hex key pad into your computer. I have put together a computer based on the TMS1100.
A simple program to display 5 on the hex LED would be 0001000 0000101 0000001 written in binary converted to machine code that would be 8 5 1 . This program would then run and display 5 on the LED.
You could follow this procedure for far more complex programs using the TMS1100 and I guess programming in binary.
Actually, I think this is very satisfying and rewarding if you are interested in mathematics and programming.
Answer: For the brave of heart: you can try getting a MikeOS floppy image and running the monitor.bin program. It allows you to enter hexadecimal opcodes by hand and execute them. For example (as stated on the docs), entering the following instructions:
BE0790 E8FD6F C3 4D00$ will produce a single M on the screen.
Answer: There are some esoteric programming languages. They are used as experiments, and are rather impractical, but one, called BrainF**k (yes, it is actually a real thing) uses eight different characters to modify byte values. Those kind of languages are about as close as you can get.
Comment: Downvoting for the following reasons: a) it doesn't answer the question; b) it's irrelevant; and c) it implies that there is no way, which is just plain wrong.

Is it possible to program in binary?