Does practicing set pieces on the piano lead to the ability to improvise or play accompaniment?

Question: I am thinking of somebody whose entire musical training consists of playing from sheet music.  He goes though all Bach, Beethoven, etc. and eventually becomes good enough for Carnegie Hall.  He is great at both sight reading and playing from memory ("from sheet" is intended to comprehend both these).
Now, will that give him, through an unconscious process, the ability e.g. to accompany the church choir on the piano on a random hymn (that is, without score for the accompaniment)?
Or are playing from sheet and improvising two (fairly) separate areas requiring separate application (learning, practice, agonizing, etc.)?
Another way to phrase the question may be to ask whether a good portion of famous pianists are incapable of the slightest extemporaneous deviation from the sheet.
"Is my church choir accompanist better at accompaniment than Alfred Brendel?"
I probably don't know enough about music or learning theory to phrase this question well.  Please feel free to answer the question I should have asked.  Thanks.
P.S. Since the posting, I have learned that a set piece does not mean something that's completely set, but has a narrower meaning. E.g. "a self-contained passage or section of a novel, play, film, or piece of music arranged in an elaborate or conventional pattern for maximum effect." I'm OK with that. Any Bach or Beethoven is a set piece of my life.
Comment: Improvising is not one skill but several.  Take a great jazz pianist and ask them to improvise a fugue and watch them very quickly lose track of what they're doing.  For that matter, take a church organist who can very well improvise a fugue in the style of Bach and ask them to improvise, say, an atonal fugue on the first phrase of Schoenberg's Piano Concerto and they'd likely struggle (unless they'd actually worked on that sort of thing, which some of them have).
Comment: @poppycat - I thought we'd avoided the 'sensitive' gender problems that sparked off other 'issues' on other sites, here. Please don't let this site get embroiled in that. Calling someone whatever will eventually upset someone, but I thought we were more mature here! Surely, we have bigger fish to fry. Stick to your guns.
Comment: @poppycat You may consider "he" and "she" to be inclusive, but most people do not - as a woman I really don't consider "he" to encompass me, and in fact I see it used generically far too often and it makes me feel excluded every time, and adds to general imposter syndrome problems in male dominated fields. Being sensitive to inclusion means considering how these things come across to everyone - I would encourage you to reconsider editing.
Comment: I received an edit suggestion to change *he* in the first two paragraphs to the inclusive *they* but turned it down. I consider *he* and *she* to be already inclusive.  *They* works in short bursts ("Everybody thinks their cat is the cutest"), but otherwise introduces an unwanted plurality.  Thanks for the edit suggestion nevertheless as a reminder to remain sensitive to issues of inclusion.
Comment: An every day example in the other direction, check out the popular (and very funny) Rick Beato online. He is unbelievably good at instantly picking up and playing along with songs, improvising, and has insane skills using chord systems. But even though he had a full extensive academic music education, he'd be the first to say he's just nothing in terms of classical formal playing technique on guitar/piano.
Comment: Worth noting that the **organ** is a notable exception to the trend within orchestral instruments – organists typically have to be fluent improvisers, not just to accompany singers but also to lengthen music on the fly, and fill time within a church service. See for example this video: https://www.youtube.com/watch?v=Lv48qZQI7-I
Comment: Why only piano? The concept will apply equally to all instrumentalists - and vocalists too.
Comment: @Tim I asked piano because that's the only instrument I know anything about.  But now that you ask, it would appear that transposition is more difficult on a piano (because of the black keys) than on e.g. a violin (which may involve mostly sliding the fingers up or down). Of course, I agree with your broader point. Thanks.
Comment: The funny part is that "Now, will that give him, through an unconscious process, the ability e.g. to accompany the church choir on the piano on a random hymn (that is, without score for the accompaniment)?" and "whether a good portion of famous pianists are incapable of the slightest extemporaneous deviation from the sheet." actually have two separate answers. I was forced to improvise Baroque ornaments for piano exams, so I will have to answer "No" for both, even if, intuitively, the answer to only the first is "No".
Answer: Have a look at classical violinist Ray Chen trying to learn to improvise with jazz pianist Tseng-Yi "Mike" Tseng in this video: Ray learns Improv - Jazz 101.
Ray is a world-renowned violinist who won the 2008 Yehudi Menuhin and the 2009 Queen Elisabeth competitions, but it's clear that his classical training has not prepared him for improvisation, while for the jazz pianist it comes naturally.
In the video How Classical, R&B, and Jazz Musicians Play Differently, classically trained pianist Nahre Sol joins two musicians from other genres in an improvisation session, and she also discusses a time when classical musicians were expected to be able to improvise.
She explores the issue in more detail in these two videos: Why Don't Classical Musicians Improvise? and Why is Improvisation SO DIFFICULT for Classical Musicians?
The answer basically boils down to: playing compositions and improvising are two different things, and you can't expect to be able to improvise without honing that skill through extensive practice.
Answer: Music theory and practice has neglected the way of Partimento and  teaching improvisation for almost 200 years. Now  it has been recovered and since about more than 10 years there's a great renaissance of this kind of approach to music composing and improvisation.
I bet the next generation of musician will answer your question with yes.
I had never heard about partimenti until last october when my grandchild started his study of music in Lucerne. And it was the revelation for me what I have been searching for many years and answered many questions I had when playing Bach's Inventions.
When I started with piano lessons at the conservatory I also studied at the Jazz School and mixing the both theories enabled me to play and improvise in a way your question implies.
I also know classical musicians (piano teachers) who are fixed on the sheet music and don't reflect what they are playing (analyze chords, harmony etc.)
Comment: maybe I mean I can improvise as bad as I can play pieces properly from dots. What I can see is that young music students are more adviced in improvisation and composition from the beginning, I mean also young children when starting with music lessons.
Comment: So you're saying you can improvise as well as you can play pieces 'properly', from dots? In my experience, that's less than say 10% of musos, who tend to fall into either category, but not both. I hope you're right that in years to come, players will be adept at both sides of the coin, but it will take a long time. But partimento is only one side of that coin, isn't it?
Comment: I wonder whether this neglect of composition (broadly construed) in music training comes of a collective assessment that all the best music has already been written. Many people say that there is "no such thing as objectively better or worse" out of politeness perhaps (and not just about music), but nobody believes it. The way twentieth century composers strain to be "original" also may be a confession that they have given up on being any good.
Comment: @Tim I can improvise and sight read. I'd say learning one is about as hard as learning the other. So after more than 40 years of learning music it doesn't seem surprising to me to have a bit of both skills.
Comment: I'm sure about this and I fully agree.  You could ask why aren't there more composer among all these piano teachers of the last 100 years? It must be their humility to say everything I could say has already been written. Everything has been said.  (We really need a fully cup of naivity to say: This is my composition! and even claim for  fringing of copyright when e.g. another band uses a similar melody or the same chord progression. Ridiculous!)
Answer: Funnily enough, "Now, will that give him, through an unconscious process, the ability e.g. to accompany the church choir on the piano on a random hymn (that is, without score for the accompaniment)?" and "whether a good portion of famous pianists are incapable of the slightest extemporaneous deviation from the sheet" have two separate answers. My personal finding is that the answer to both is no, even if the answer to the latter would intuitively be yes.
I was taught and repeatedly told to improvise ornaments (mordents, turns, etc.) on right-hand melody notes in Baroque music (yes, I was never told to improvise any ornaments on left-hand notes in fugues) for Royal Conservatory of Music piano exams. I have good reason to believe that learning to improvise Baroque ornaments is standard issue, at least in Canada. (I shared a piano teacher with the concert pianist Jan Lisiecki at one point, so I also have good reason to believe that concert pianists get much the same training as I do.)
This means that classically trained concert pianists, or at least those who took RCM exams, are indeed capable of the slightest extemporaneous deviation from the sheet.
This does not translate to being able to improvise left-hand parts for given music, it also does not translate to being able to improvise little hummed tunes, and it definitely does not translate to improvising fleshed-out pieces or even solos.
Improvising left-hand parts for given music, along the lines of the church choir accompanist mentioned in the question, requires you to figure out the dots and then purposefully avoid them, unlike the Baroque ornaments I was taught to improvise.
As someone who likes figuring out pieces by ear and has learned chord theory but is mainly self-trained in the practice of improvisation, my general finding is that I will get the accompaniment of nearly any piece I learn by ear at least slightly wrong. I will often unconsciously reharmonize in an attempt to get the accompaniment right (enough). Even when I get the harmony right, I nearly always mess up the precise accompaniment notes. This is made blatant to me when I listen to the original again. (This has also strongly molded which pieces I transcribe by ear - I strongly trend towards pieces where I can figure out all the accompaniment notes by ear, regardless of how much I like the piece.)
This lack of precision in my improvised accompaniment, and its contrast with the strong emphasis on precision in my piano lessons where I learned sight reading and playing/memorizing from sheet music, is one of the many things convincing me that playing from sheet and improvising are two separate areas of learning, and learning how to play from sheet will not train you on how to improvise.
These days, I often fix the key and the very rough style of the improvised tune I want to hum next before I start humming it, but this improvisation fundamentally means I need to make up all the dots as I go along, including the (implied) harmony. This likely requires a different type of training from improvising a left-hand part, accompaniment, or even a solo (which is often on a given chord progression or at least accompaniment part) because you are now forced to come up with the harmony and melody on the spot at the same time.
Comment: Accepted as answer as giving a concrete account of the extent of improvisation a classically trained pianist may be capable of (which does seem slight indeed) and the internal experience of the attempt.  Other answers were great too.  Thanks!
Answer: A pretty emphatic no!
Out of all the players I've had the pleasure of playing with, the vast majority fall into one category or the other. There's only been literally a handful who were good at reading and extemporising. Most were very good at one or the other.
The reason is often that when one is good at sight reading, one tends to use that as the main playing method. Consequently getting better and better, and not using anything but the printed dots to work from.
Conversly, if one isn't that good at sight reading, one will tend to use one's ears far more, and be aware of what's happening in the music, thus will be able to improvise more easily. Quite handy when the music gets blown away, or the stand gets knocked over..!
Of course, not all concert level players are good sight readers - they may just have very good memories, and take a while to be able to play the pieces at concert levels. That means they need, maybe, to practise hard, but improvisation isn't going to be part of their performance, so they need to be note perfect.
There's the story of Yehudi Menuhin and Stefan Grapelli - one an excellent sight reader, the other an excellent improvisor. Menuhin had all his dots to play from, while Grapelli needed none. Both sounded great until Stephan removed the other's music. Who then just couldn't play a note!
Answer: The answer to the question as posed clearly is "no", but in the process of working out set pieces, your fingers and motor control will get used to navigating common patterns in music without involving active thought processes.  That gives you considerably more refined building blocks to work with when actually learning and practising improvisation.
You'll find that a lot of the most renowned pop and jazz players have a classical education as background.  Just like a lot of successful basketball players have long legs.  But on their own, the legs get you nowhere.
Answer: If you practice playing from notation, you'll get good at doing that.   If you practice 'playing by ear' you'll get good at that. And, hopefully, you're also studying 'theory' in its various forms.  These skills feed on each other, they are not exclusive.
But maybe you need to consciously keep up to scratch at both.   There are many anecdotes of 'classical' players who have never needed to extemporise.  I can also offer anecdotes of well-trained musicians who  fall out of practice at playing notation literally - I was one of them!
Answer: The act of performing music from "sight"(reading sheet music and translating it in to sound) is a mechanical process. It is exactly analogous to "reading outloud"(which could mean reading outloud in your own mind = reading to ones subconscious).
The act works by looking at the scribbles on a page and translating them in to physical movements(kinematics which are represented by 3D space curves and why some part of practice/technique deals with the relative positions and motions of the body parts, mainly arms, hands, and fingers).
What one does when learning to sight read, more or less, is learn to place ones fingers where the notes tell them. One literally translates(maps) the specific note structure in to that of the instrument which we will take as the piano for arguments sake. One must do this "in time"(since the medium is time based, unlike, say, painting in which the performance is not time dependent) and music is clearly a function of time which musicians call rhythm/meter. (meter is the clock, rhythm is the expression of that clock in to interesting patterns)
If one see's some notes they must know how those notes translate in to their fingers. E.g., one first learns how the staff encodes notes and learns little "tricks" such as FACE and "EGBDF" but what one really is doing is learning what notes on the staff correspond to what notes on the piano.
Over time of doing this one develops/encodes a translation function that matches the written pitch to the finger pitch. Of course there is more to it since the mapping involves specific fingers(which one must learn to use any) along with physical motions and all that. Most of these things come naturally with (enough) practice and is no different than learning to solve a rubiks cube or, in some ways, a differential equation. It is "wrote" technique and is very complex but each piece is very simple(of course it must be or we would never be able to do it).
The idea though is that one is reading instructions and performing those instructions... much like a computer reads a program from memory(bits of 0's and 1's) and "performs" the program(translates those 0's and 1's in to on/off states of transistors which ultimately do things).
In "performing" it is nearly mechanical but there is some room for creativity such as varying certain unwritten things. that is, while the brunt of "fixed" music(pre-composed) is fixed there are some variables/variations: interpreting exactly what one means by: dynamics(what is forte really translate to in the muscular attacks on the keys), articulations(a trill is not a trill, or rather there is some room for variation/interpretation), rubato(playing with time in a purposeful way), etc.
But the idea is that most of the performance is mechanical and the choices for "musicality" are very limited. This is good and bad. 1. It lets everyone play almost the same thing(it's written down after all) 2. there is very little room for modifying the piece which allows one to focus on those modifications. Usually highly skilled performers will have very well developed understandings of those variables because, well, that is all they get to "mess with". A little is a lot. E.g., once you have memorized a piece to perform you have the notes down in "musicle(tm) memory" and so what you can vary are those limited things which will have your full attention.
Note that in such a thing one does not need to actually understand "music". It is simply a process of translating what is written to kinematics. There is no musicality needed to perform a piece of music perfectly. Robots have been created to do it. Computers can do it without the kinematics(e.g., midi to sound), etc. You can tell how non-musical it is by the blandness of these performances since, at least in the past, the "variables" for shaping music were generally flat(e.g., no dynamics or arbitrary dynamics, articulations played exactly the same way every time, etc).
To give an outline of how a sight reader thinks(at least from me, as I have no idea how other sight readers think, I'll also leave out a lot of details):
One looks at the music, notes the key signature to know how to interpret accidents and such. For me this is just the basic scale I'm using. The time signature tells me the meter and the tempo. Look at the music to see the general character such as the typical patterns used(block chords, arpeggios, etc). Most good music has underlying patterns that helps make a piece easier to perform because, say, it's just a repetition of something over an over(think of a fugue in which the melody(subject) is generally usually something like 90% of the piece). Obviously the more one can figure out those things the easier it will be.
Then as one starts to play one has to translate the notes to the fingers. I see a dot on the F I know I play an F(assuming the key signature doesn't have an F# in it but I've already established the scale I'm working from so I know). This is because I've done it a million times. Of course I need to know the rhythm so I look at the flag or group.
There are other complexities because it's just just banking notes out one at a time. For example, unless this is pre-rehersed, the fingering is very important. That F note requires the right finger to be used else one can end up in finger twisters(worse than tongue twisters). This involves looking ahead(and learning to look ahead is really what makes sight reading possible. A good sight reader will memorize the first few bars or phrases before he plays, then play them while memorizing the next, this way he always has time... so he acts as a "tape recorder" and is on autopilot with what he is playing while he figures out the next part).
Of course one will learn to recognize chords(e.g., stacks of notes), arpeggios(chords that are "stacked horizontally"), various patterns and such. All this comes with practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice practice. It's why most people can't play, because they won't practice.
Note that performance is not composing in the musical sense(but it is composing in the sense of putting the scribbles together in to sounds).
Contrasting all that to improvisation: Improvising is creating music on the spot. Composing is close to improvising in that a composer generally will create music "on the spot" as he builds his composition.
Improvising requires actually understanding music(although not necessarily formal music theory).
Improvising is mapping the musical elements(harmony, rhythm melody, dynamics, etc) in to sound(but if one writes it down first then it is composition). Improvising is real time composition.
For a composer to compose something good he must understand harmony, melody rhythm, dynamics, form, etc in some way shape or form. The better he understands them(even if he has no clue about music theory) the better his music will be.
In improvising one may start out with fixed elements like a fixed song structure(blues, two part form, rondo, etc), fixed harmonic progression(e.g., Am Bbb9/C D^#9 F7b5 C#b13 Dm), some melody or whatever.
Usually there is some general structure one is working with rather than just randomly sampling the entire musical space(as doing that will generally sound like crap). Even if one just sits down at the keyboard and plays something "out of the blue" there is still something one is working with subconsciously that probably was practiced in some way before more or less.
To improvise one must know their chords. By this I mean one must know how to play their chords instantly in every position, inversion, voicing, etc. Performers also generally have to know this to some degree but given that they practice the piece before hand and do not necessarily relate it to harmony(although any good performer will generally also think of chords but how they think bout them is different).
To improvise one must deal with choices. There are so many choices, one limits those choices down but there are far more than performing. Not only does an improvisor have to deal with the same issues, musically, as a performer, but also several orders of magnitude more(well, at least an order). A performer has rehearsed his music. Even if he is sight reading something new, he has rehearsed all the ways to map the notation to his fingers. An improviser sort of does that but it's much looser. He has rehearsed playing various shapes, dynamics and such but in the act of improvising he may play a combination of things he never played before. This is true for a performer to some degree but it is usually unintentional while for an improvisor it is intentional.
A way an improvisor thinks is more like this:
You have some general structure you are working in. But there is a large degree of freedom. You know your harmonies and you know just about everything a sight reader must know in terms of music theory and all that but you have to know more and better. You know your scales(all kinds, major, minor, dominant, modes, altered, etc), chords(all kinds, major, minor, diminished, augmented, extended, sus, slash, whatever), patterns(specific(licks, phrases, etc), general(e.g., you can play a Cm arpeggio but you can use it as a template to play a Csus4 arp which is replacing the m3 with a P4), dynamics, accents, form, etc.
It's far to complex for me to explain it all but basically improvising is expressing the entire accumulation of the improvisors body of knowledge, experience and being in the moment(in real time).
It is like sight reading music that is being created as you read it.
Now, when I improvise, the more comfortable I am with what I'm improvising(meaning that I'm playing things I've played before in some way(e.g., using some harmony I like or whatever but maybe melody is completely undefined) I'm not so much thinking in these terms. Same goes with sight reading.
Once you do it enough it becomes subconscious and you just learn to enjoy it. With improvising though I get to chose, say, if I want to play a b9 on a V7 chord to get a certain sound and I have to think of the implications of that(is it appropriate for the harmonic progression or the context(depending if one is playing with others, etc). I get to chose if I want to play a melody upside down or play it in 3rds or whatever. There are literally thousands of choices at any give second that one gets to(has to) choose from.
For me, the choices are, generally, second nature so the emotion I get to put in to it is what it's all about. I get to choose what I want based on what I'm feeling(it's a feedback loop type of thing). I can change the harmony if I want, I can get quite if I want, etc It's not just doing it to do it though, it becomes more than that, the music sort of becomes alive in that it sort of tells you what it wants. It's impossible to explain, you only know it when you have experienced it.
An improvisor practices using the tools of music so he can improvise when he improvises. A sight reader practices the playing written music so he can play written music when he plays written music.
The extremes are: No choice <------> Free choice.
Music lies somewhere in between.
My problem is I started on the RHS and my brain has been conditioned to make instant choices based on what I feel so for pieces of music I'm trying to sight read, specially if it's not emotionally capturing, my brain will wander and improvise. This is not a problem with someone that started on the opposite end. A  sight reader who doesn't improvise never has to worry about improvising... and I guess an improvisor who never sight reads never has to worry about sight reading.
So the answer to your question is basically this: They are two different things/skill sets. Not completely independent but at the core they are different. Most people choose one or the other, like left and right handedness... Because both are extremely difficult/complex skills to master(takes many years) rarely do people do both... just like rarely will you find a great mathematician who is also a great musician who is also a great painter, etc. There is only so much time to master anything and of course nothing is ever mastered. Someone that is good is only better than others and only better because they chose to put their time in to doing that. E.g., some people are good at stealing the worlds wealth(e.g., Ken Griffin) because they spent their entire life mastering that skill... other people are good playing piano because that is what they spend most of their time doing. Some people are good at playing Bach and others good at playing Chopin... because that is what they spent their time doing.
The confusion, of course, is that people ignorant of something cannot see the details. If a person never learns how to solve fractional distillation problems they won't understand it in any meaningful way. Looking in from the outside is totally different than looking out from the inside.... completely opposite. One ignorant of something will never understand something while being ignorant of it. It's true for anything as much as it's true for everything.
So understand that I've tried to condense down my decades of experience in to a few paraphrases... and each person has decades of experience... which are condensed down in to a few outside experiences... but the reality is that things are infinite fractally complex. Improvising is like, to me, is like living a life while sight reading is more like reading a book about someones life. I'm not nearly a good sight reader as I am an improvisor though... again, I started from improvising and hated sight reading initially so.... I'm sure though if I was really good and could improvise just about anything without feeling pressure and without making a lot of mistakes then I might also have similar feelings about sight reading(similar but different). Just like improvising was difficult when I first started out and it got to the point of being almost effortless(again, like anything, some things are harder than others) sight reading should also evolve the same way. I just love improvising so much that I do it far more. I'm trying force myself to sight read more though because I'm pretty sure it too can be just as rewarding.


How to restrict/secure access to developer's server hosted on Internet

Question: I am setting up two Ubuntu virtual private servers for my startup company.
The "public" server (let's call it www.example.com) shall contain the publicly open company web site and restricted but (relatively less sensitive) services such as the LDAP and mail servers. The "dev" server (dev.example.com) will be the company's Fort Knox holding the company's source code (GIT), artefacts (Artifactory) and developer tools (Atlassian). Access to www.example.com should be open to everyone whilst the dev server should be very secured, accessible only to a very limited number of authorized developers and the other public ideally shouldn't even be able to guess
that the server exists. Both servers will be hosted at a hosting company (with us having full root access).
I am planning to set up web access using the same domain name and virtual hosts. example.com will point to the "public" server. nginx installed on the "public" server will have the www.example.com virtual host (served normally) and the dev.example.com virtual host, all requests to that host will be proxied to the "dev" server running another nginx. The firewall on the "dev" server will be set up to deny all incoming traffic except HTTPS and SSH calls coming from the "public" server. So not only direct connections to the
nginx server running the developer tools on the "dev" server will not be possible, but we will also have to log in to the public server first in order to be able then to SSH into the "dev" server. Thus a potential hacker wouldn't be able to access directly the "dev" server without first breaking
into the public server.
If it matters, the servers will probably run Ubuntu 16.04 (we have a choice between 14.04, 16.04, 18.04
and other Linux flavours, but Ubuntu 16.04 sounds OK'ish to me). I am neither a security expert
nor a system administrator.
I have two questions.
1) Does this sound like a good secure setup confirming to "best practicies" or are there better (simpler or more secure)
ways to achieve same goals?
2) [Main question]. How can I restrict HTTPS access so that only developers can access dev.example.com
while other users don't see this virtual host at all even if they've guessed the URL? I have two ideas so far.

require an SSH tunnel. The dev.example.com virtual host in nginx on the "public" server will be set up to accept requests only from the "public" server's IP address itself, so the developers will have to set up the SSH tunnel to the "public" server in order to access dev.example.com. With tools like MyEnTunnel (Window) it is easy to setup a SSH tunnel so that it is automatically established during boot time. However
the big disadvantage I see is that each developer will have to define that "dev.example.com" refers to localhost in their hosts file (or are there other ways?)
Client certificates. nginx on the "public" server will basically require a client certificate in order to access dev.example.com. Each developer will have his/her own client certificate to access dev.example.com in addition to their usual login and password that they will use to access
the developer tools. However I am not very familiar with client certificates and don't understand all implications. One disadvantage I see is that probably when unauthorized person tries to access dev.example.com he/she will get a "client certificate" error which will reveal
that the dev server is there, while with the first approach they will simply not be able to connect.

What would you recommend me? The idea is to keep it simple, cheap and at the same time as secure as possible until the company grows to such an extent when it can afford sysadmins and its own data center.
Answer: Part 1:
Accessing a highly secured server through logging in to a public not-so-secured server gives me a bit bad feelings in the stomac, like passing the top in a rollercoaster.
If you want to have a secure dev server, secure it. Install required/helpful stuff only. Security is limited to what you control - your hosting provider has access anyway if they want - they have physical access.
If you want to conceal your dev server, conceal it. Drop any incoming network traffic. Maybe you want to use port knocking to open your private doors. But be aware, that your provider can see it all.
Part 2:
Yes, having all services of your dev server listen on localhost only is a simple, and effortless way to conceal and secure your server at the same time.
Requiring users to use ssh tunnels is ok. It works, is set up in a few minutes and can be done with about any ssh binary out there. Good idea in my opinion.
If you close all other doors, you have the ssh door left, which is visible to the outside world. You can move it to the backyard though, changing from port 22 to a random like 32109.
Client certificates complete this type of security to - in my opinion - more than enough. If more would be required, not having your own physical fort nox, where your server is secured against unauthorized physical access would be grossly neglegient.
Nobody will get an "client certificate" error before he has established his ssh tunnel, so don't worry about this.
No, your developers won't define, that dev.mydomain.com refers to localhost, else they wouldn't be able to ssh to it. They may safely access your dev server via localhost or a hosts entry "127.0.0.1 mydev" or whatever you name it internally. This doesn't require a publicly accessable name.
On your Ubuntu 18.04 - you are waaay ahead of time ;-)
If you want to use Ubuntu, use 16.04. It will endure your company's startup phase. Other Flavours are equally ok, though. Make sure there will be updates available for a few years at least, like 04/2021 for your Ubuntu-16.04
Btw: if you want to conceal your dev server, don't give it a name service entry like dev.myserver.com; you don't need it, others will need it less. Just put it in your developer's hosts files.
Have Fun!
TomTomTom
Comment: Thank you for the response, this sounds reasonable! Just to clarify, I wanted to access the dev server via a domain name for two (maybe rather aesthetic) reasons. 1) in this case I could use a normal "Let's encrypt" HTTPS certificate for the dev server which wouldn't be possible if it only had an IP address. 2) using a domain name I could use virtual hosts on the dev server if I wanted (like `dev.mydomain.com`, `jira.mydomain.com`, etc.)


Qual a melhor forma de buscar muitas variáveis no banco de dados?

Question: Estou desenvolvendo uma aplicação C# MVC e estou tendo problemas para apresentar os registros. Tenho uma lista com mais de 250 variáveis e o usuário escolhe qual delas quer ver no gráfico. Dentro do controller eu faço um switch case para o LINQ de cada variável da lista. O problema é que sempre dá erro System.StackOverflowException depois que passo de 200 variáveis. Existe alguma forma mais inteligente de fazer essa busca no SQL?
switch (tipoDados) {
case "Temperatura Ar de Combustão":
                    var pffeifer = db.PffeiferPRODs.Where(p => DbFunctions.TruncateTime(p.Data_coleta) >= data1 && DbFunctions.TruncateTime(p.Data_coleta) <= data2).OrderBy(p => p.Data_coleta).ToArray();
                    var dataTabela = pffeifer.Select(p => p.Data_coleta).Distinct().ToArray();
                    max = new double[dataTabela.Length]; min = new double[dataTabela.Length]; mediana = new double[dataTabela.Length]; quartil1 = new double[dataTabela.Length]; quartil3 = new double[dataTabela.Length];
                    for (int a = 0; a < dataTabela.Length; a++)
                    {
                        DateTime data = dataTabela[a];
                        int q1 = 0, q3 = 0;
                        double cont1 = 0, cont2 = 0;
                        var varDia = pffeifer.Where(p => p.Data_coleta == data).OrderBy(p => p.Temp_arcombustao_camcombustao).ToArray();

                        //pega o máximo e o minimo
                        try
                        {
                            max[a] = varDia.OrderBy(p => p.Temp_arcombustao_camcombustao).Max(p => p.Temp_arcombustao_camcombustao);
                            min[a] = varDia.OrderBy(p => p.Temp_arcombustao_camcombustao).Min(p => p.Temp_arcombustao_camcombustao);
                        }
                        catch
                        {
                            max[a] = 0;
                            min[a] = 0;
                        }

                        if (varDia.Length % 2 != 0) //se o tamanho do array for impar
                        {
                            int pos = (varDia.Length + 1) / 2;
                            mediana[a] = varDia[pos - 1].Temp_arcombustao_camcombustao;

                            if (((pos - 1) % 2) != 0) // se o tamanho dos quartis for ímpar
                            {
                                q1 = Convert.ToInt32((varDia.Length + 1) * 0.25);
                                quartil1[a] = varDia[q1 - 1].Temp_arcombustao_camcombustao;

                                q3 = Convert.ToInt32((varDia.Length + 1) * 0.75);
                                quartil3[a] = varDia[q3 - 1].Temp_arcombustao_camcombustao;
                            }
                            else //se o tamanho dos quartis for par
                            {
                                q1 = Convert.ToInt32((varDia.Length - 1) * 0.25);
                                try
                                {
                                    cont1 = varDia[q1 - 1].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    cont1 = varDia[q1].Temp_arcombustao_camcombustao;
                                }
                                cont2 = varDia[q1].Temp_arcombustao_camcombustao;
                                quartil1[a] = (cont1 + cont2) / 2;

                                q3 = Convert.ToInt32((varDia.Length) * 0.75);
                                cont1 = varDia[q3 - 1].Temp_arcombustao_camcombustao;
                                try
                                {
                                    cont2 = varDia[q3].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    if (q3 < 0)
                                    {
                                        q3 = 0;
                                    }
                                    else
                                    {
                                        q3 = q3 - 1;
                                    }
                                    cont2 = varDia[q3].Temp_arcombustao_camcombustao;
                                }
                                quartil3[a] = (cont1 + cont2) / 2;
                            }
                        }
                        else // se o tamanho for par
                        {
                            //se 10
                            int pos1 = varDia.Length / 2;
                            int pos2 = (varDia.Length / 2) - 1;
                            if (pos1 < 0)
                            {
                                pos1 = 0;
                            }
                            if (pos2 < 0)
                            {
                                pos2 = 0;
                            }
                            try
                            {
                                mediana[a] = (varDia[pos1].Temp_arcombustao_camcombustao + varDia[pos2].Temp_arcombustao_camcombustao) / 2;
                            }
                            catch (IndexOutOfRangeException)
                            {
                                mediana[a] = 0;
                            }

                            if ((pos1 % 2) != 0) // se o tamanho dos quartis for ímpar
                            {
                                q1 = Convert.ToInt32(pos1 / 2) - 1;
                                if (q1 < 0)
                                {
                                    q1 = 0;
                                }
                                quartil1[a] = varDia[q1].Temp_arcombustao_camcombustao;

                                q3 = Convert.ToInt32((pos1 / 2) + (varDia.Length / 2)) - 1;
                                if (q3 < 0)
                                {
                                    q3 = 0;
                                }
                                quartil3[a] = varDia[q3].Temp_arcombustao_camcombustao;
                            }
                            else //se o tamanho dos quartis for par
                            {
                                q1 = Convert.ToInt32(pos1 / 2);
                                try
                                {
                                    cont1 = varDia[q1 - 1].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    cont1 = 0;
                                }
                                try
                                {
                                    cont2 = varDia[q1].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    cont2 = 0;
                                }

                                quartil1[a] = (cont1 + cont2) / 2;

                                q3 = Convert.ToInt32((pos1 / 2) + (varDia.Length / 2));
                                try
                                {
                                    cont1 = varDia[q3 - 1].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    cont1 = 0;
                                }

                                try
                                {
                                    cont2 = varDia[q3].Temp_arcombustao_camcombustao;
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    if (q3 < 0)
                                    {
                                        q3 = 0;
                                    }
                                    else
                                    {
                                        q3 = q3 - 1;
                                    }
                                    try
                                    {
                                        cont2 = varDia[q3].Temp_arcombustao_camcombustao;
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        cont2 = 0;
                                    }
                                }
                                quartil3[a] = (cont1 + cont2) / 2;
                            }
                        }
                        mdia = varDia.Average(p => p.Temp_arcombustao_camcombustao);
                        listaDia.Add(Convert.ToString(dataTabela[a].ToShortDateString()));
                        listaDados.Add(new BoxplotSeriesData { Y = Math.Round(mdia, 2), Q1 = Math.Round(quartil1[a], 2), Q3 = Math.Round(quartil3[a], 2), Median = Math.Round(mediana[a], 2), Low = Math.Round(min[a], 2), High = Math.Round(max[a], 2) });
                    }

                    media = pffeifer.Average(p => p.Temp_arcombustao_camcombustao);
                    break;
}

Comment: Não entendi, você tem 250 cases desse? Acho que vai ser necessário repensar a sua estrutura como um todo
Answer: Se você tem a exceção System.StackOverflowException é porque está a ter muitas chamadas na pilha de execução. Isso não deverá ter relação com o teu switch (que nada mais é que uma sequência de IFs). O erro muito provavelmente ocorre por conta de um loop (for/foreach/while).


The boundaries of mathematics?

Question:
There are five possible answers to a multiple-choice question. Given that the student does not know the answer, what is the probability that the student chooses the first answer?

That is not a well formed math problem, to say the least, but I once told a student that it is not actually a math problem and he couldn't understand why, and thought it was obviously a math problem.
But I wonder if our understanding of what constitutes a mathematics problem should be expanded somewhat beyond what mathematicians conventionally think it is, in order to include instances of reasoning that can be done by mathematicians and is unknown to others, to the extent to which those others are not mathematicians.
Obviously this calls for examples, and at this moment I have only two:

Clearly Regiomontanus's angle maximization problem is a mathematics problem. One posits a painting hanging on a wall with its lowest and highest edges above your eye level. Given those two heights above your eye level, how far from the wall should you stand to maximize the angle whose vertex is at your eye and whose rays are incident to the top and bottom of the painting? (This has a solution by elementary geometry not involving calculus, another solution by a somewhat unconventional way of completing the square, and another by calculus, in which perhaps the most efficient way is to directly maximize the tangent of the angle.) However, often people phrase this incorrectly: they ask what distance from the wall gives you the best view of the painting. So let us suppose that I announce the following "theorem": The distance from the wall that maximizes the angle does not generally coincide with the distance that gives you the best view of the painting. If this is a theorem then it has a proof. Here it is:  First suppose that the lower edge of the painting is exactly at your eye level. Then you would maximize the angle by placing your eyelid in contact with the lower edge of the painting. As you approach that point, the angle approaches $90^\circ,$ and cannot get more than that. But this is clearly not the best possible view. Next, suppose the lower edge is a tenth of a millimeter above your eye level. If the top of the painting were one meter above eye level, then the angle is maximized by making the distance one centimeter. Clearly still not the best view. The quality of the view varies continuously with the distance, and the angle also varies continuously with the distance, so the angle cannot suddenly coincide with the quality as you slowly back away. Quod erat demonstrandum.
Suppose cheese and chalk are two commodities that you are in the habit of buying. If I steal some of your cheese or some of your chalk, I leave you worse off than you were, and if you gain some of either your lot is improved. Now suppose if you have $20$ units of cheese and $30$ units of chalk, you are just as well off as if you have $50$ units of cheese and $20$ of chalk. If $f(x,y)$ is your utility of $x$ units of cheese and $y$ of chalk, then the level set of $f$ passing through the two points just described could have any of many shapes; this is an "indifference curve". Discovering these curves is an empirical matter, not a matter of mathematics, and economists have found that in realistic situations they may have any of many shapes. None of that is a mathematical theorem; rather it is an empirical finding. But now suppose if you invest your wealth in a certain way, then the probability distribution of the amounts of cheese and chalk you will have next February 30th is thus-and-so, but if you invest your wealth in another way, you have a different probability distribution. Suppose you are indifferent between those two probability distributions. Now we state a "theorem":  The indifference curve between your two equally valuable probability distributions must be a straight line.  Proof: Since you are indifferent between them, you don't care if I throw dice to decide which one you get. Therefore any weighted average of the two distributions has the same utility as either of them. Q.E.D.

Why should we regard these "theorems" and "proofs" as belonging within mathematics rather than being located in some other region of the intellectual realm? To which I reply: Because only an understanding of mathematics can make it possible to understand them.
This is not a position of which I am convinced, but I do think the foundations of the subject are not as well understood as many feel they are.
Questions: Do such examples bear upon the question of where the boundaries of the discipline are?
Comment: The first example is my own. For the second I am indebted to Leonard Jimmie Savage.
Comment: I think those two steps: creating a model and solving it should be considered separately. Perhaps the right question is: do we include the model creation as part of mathematics? I am unsure of the answer.
Comment: Re the 1st question, applying Bayes' rule and total probability:
$$N=\{\text{doesn't know the answer}\}$$
$$A_1=\{\text{chooses the 1st answer}\}$$
$$...$$
$$A_5=\{\text{chooses the 5th answer}\}$$
$$P(A_1\mid N)=\frac{P(N \mid A_1) \cdot P(A_1)}{P(N \mid A_1) \cdot P(A_1)+P(N \mid A_2) \cdot P(A_2)+...+P(N \mid A_5) \cdot P(A_5)}$$
this problem can be expressed mathematically, which is used in probabilistic graphical models in machine learning.
Comment: It's called learning from data. Imagine we have a huge database of past examples. From that database we can calculate the frequencies and "pretend" they are $P(A_i)$ and $P(N \mid A_i)$, substitute and pretend we predict the future.
Comment: The question is extremely interesting, although allow me to note that the tag "soft-question" might be appropriate as well since a definitive answer is unattainable as the result of a proof of any sort. That is, we might agree that such examples as the two mentioned do merit a "grand reconsideration" of where the boundaries of Mathematics lie in order to include them, but in the end it will be rather subjective and always dependent on the specific example.
Comment: When I was a first year student the teacher told us that "mathematics is what mathematicians study and mathematicians are those who study mathematics" so the boundaries are not well-defined indeed. However, I believe that in your examples everything is clear: you implicitly create a mathematical model of those real life problems and then solve them using mathematical tools. In particular, the first example can be made rigorous by substituting "clearly not the best view" with appropriate optic laws. Those problems can be solved only by mathematicians because the models are quite difficult.
Comment: Maybe I should add that Jimmie Savage did not mention cheese or chalk.
Comment: I don't think I created a model; rather I gave mathematical criteria for rejecting any of certain models that have empirical content. Despite the empirical nature of the content, the grounds for rejection were purely mathematical.
Comment: I think these examples can fall within mathematics if you can define things precisely. Define an objective function for quality of view that takes into account distortion or whatnot and you can use math to maximize it. The second example should work as a real mathematical proof. It's only surprising if you forget that it applies in the space of *distributions* of allocations of goods, not allocations of goods themselves.
Comment: Sorry but I don't see how the first bulleted item is not a mathematical problem. The fact that we can't answer because we don't have enough information doesn't make it non-mathematical.
Comment: @rtybase : How is the problem of finding $P(B\mid A_1)$ or of finding $P(A_1)$ any simpler than that of finding $P(A_1\mid N) \text{?} \quad $
Comment: @YvesDaoust : Some of that missing information would come from empirical research rather than being mathematical theorems.
Comment: @MichaelHardy: you should have said that, otherwise we can't guess your meaning.
Comment: @MichaelHardy in a way, this is what I was referring for https://www.newscientist.com/article/mg21729032-200-mind-maths-your-personal-prediction-machine/
Answer: You probably have been thinking sometimes about everything I am going to say here but I will try to express myself in such a way that I will try to stay as much as possible inside the boundaries of the question, in a way in which I interpret your question.
First, it seems that question in itself includes a need for as precise as possible (with respect to the current state of this branch of science) the definition of "mathematics" itself.
Because, how to talk about the boundaries of mathematics if there is no clear enough definition of mathematics.
The definition of mathematics could be time-dependent and could be that it will have to change as the subject evolves (or avolves) in time and with such processes it could be that the boundaries of the subject will also "expand" to include more and more inside the subject.
Even if we do not have clear enough definition of mathematics, we could try to define the concept of "theorem" and of "proof (valid or invalid)".
When armed with some definitions of "theorem" and "proof" we can then argue what is and what is not a theorem, and what is and what is not a valid or invalid proof, but only with respect to the definition we use (or definitions).
This could lead to different "theorem theories" and different "proof theories", and, more generally, "theory theories", but all definition-dependent.
So, all of this is very subjective and opinion-based, at least if you ask me.
I do not know what else to say and I am extremely tired so I will stop here, aware that I explained almost nothing.
Answer: TL;DR your question hits at the Nominalism vs Realism debate. If stuff have actual mathematical properties in real-life (without people), then model-making does belong in mathematics since mathematics is essential within the universe. I think people give the mathematical properties to objects, and that model-making begins in the mind, not in reality nor mathematics proper.
As user Petr Naryshkin pointed out in the comments, your question is asking whether model creation belongs as a part of mathematics proper. I do know that the process of making models cannot belong in a formal proof, and I'm somewhat certain that it does not belong in mathematics proper.
If you ever try to make a formal proof of those aforementioned propositions, or really anything which applies the tools of mathematics to the real world, you'll find yourself importing axioms. That's your base model.
Where do these axioms come from? Are these axioms true?
You can't answer these within the proof theory. Maybe you can use proof theory to develop more basic axioms, and figure out whether the underlying axioms are consistent with each other (or whether it's possible to know consistency), but it makes no assumptions otherwise about the axioms.
To answer those two questions, you need to reach outside. Euclid never made any assumptions about what points, lines, and the "lying upon" relation were, only that these entities had a certain way of interacting with each other. And that process of meaning-making is purely social and unrigorous. It's a psychological process of developing analogies with previously-experienced objects and phenomena, in exactly the same way that language is developed. Pushing worldly notions into ideal forms of mathematics, and subsequently pulling out the consequence, is a psychological process. That a space shuttle correctly orbits and docks with immense precision, or that particles decay while conserving numerical quantities, simply reflects an effective, socially established common mapping of objects to concepts; the modelers "correctly" mapped their objects to their corresponding mathematical notions.
I don't know what name this philosophical view has, maybe Nominalism? I think it might be at-odds with the metaphysics of scientific realism, which says that "The entities described by the scientific theory exist objectively and mind-independently."
Answer: You seem to be asking two related questions: (1) are the boundaries of mathematics known? (2) have the foundations of mathematics been well understood?
Rather than answering these from first philosophical principles such as the realism/nominalism dichotomy, I would suggest that the answer lies in an examination of the history of mathematics. At the turn of the (19th) century mathematics was understood as arithmetized analysis as practiced by Weierstrass and his students. In 1900 in his famous lecture at the world congress of mathematicians in Paris, David Hilbert turned the tables on the traditional view by offering a broad scope of problems including set theory, logic, and axiomatisation of physics (only a minority of which relates to arithmetized analysis). This is of course not the only but perhaps one of the most famous instances when the boundaries of the subject have changed dramatically over time.
If the subject matter of mathematics evolves surely its foundations necessarily evolve as well, as is illustrated by the historical development of category theory starting in the 1950s, challenging the traditional set-theoretic foundations.
An important aspect of the picture is the fact that the boundaries of mathematics are not always growing; sometimes they are shrinking.  Thus, infinitesimals were part and parcel of the landscape of mathematical analysis for about two centuries: 1670-1870.  Sometime after 1870 a more-or-less official ban against them was issued (that was not uniformly followed however) that held for about 90 years.  Around 1960 infinitesimals were restored to respectability though some still seek to enforce the obsolete ban.
Therefore my answer to both questions is negative.

The boundaries of mathematics?


How do I know when I'm singing in key?

Question: I absolutely love to sing and do so on a daily basis,  usually in the shower or while practicing guitar.
When I sing it sounds fine to me and I don't think I'm off but I have this fear that I'm actually a horrible singer and I just don't know it.
Is it possible to be horrible and just not know it? if I was really bad would I be able to hear it myself?
Edit: So I recorded myself.  The first minute is a capella, the second is me with guitar. I'm quite amateur as far as guitar playing goes and my phone isn't the greatest recording device, I think it glitched once or twice. My bro says he thinks it sounds ok. I do get a bit wobbly toward the end of the a capella part.
Comment: For quick (and real-time) analysis, try a tuner app for your phone/tablet. If the app/mic are good quality, it will work just fine with vocals. I really like [PitchLab](https://play.google.com/store/apps/details?id=com.symbolic.pitchlab&hl=en)
Comment: Hi - you are not an awful singer ! you have a good sounding voice which is a great start because that's not true for everyone. You're generally in tune, but a bit wobbly here and there as you say, It sounds to me like you're hitting the notes you're aiming at, rather than wandering and going wildly out and ending up out of tune. I think it is possible to sound awful and not know it, but that's mainly because it's subjective; some people like one voice, some dont, or some people don't mind a bit of out-of-tune but others do. You have the basis of a good singing voice. Keep at it!
Comment: I should add- the wobblyness I referred to sounds to me like you just need to sing with more certainty - ie do what you're doing, just don't hold back. Be confident that you've hit the note and sing your heart out :-)
Answer: Simple solution - record yourself and play it back, to yourself and others.  Do it a capella after giving yourself a key, and play along to the recording; and while playing guitar,You'll soon find out. It also sorts out good friends from bad!
Playing and singing with others also gives good feedback.
Comment: I recorded myself and edited it in. Knowing the internet, I don't know if this decision is brave or stupid. Probably both.
Comment: It was really useful.  I recorded a lot more than what is here and listened to it carefully.  This has upped my singing self esteem! I had a couple of bad experiences as a kid that made me feel like I couldn't sing. I also had a discussion with my brother on this (he's a musician).  He's heard me sing irl and says my singing has improved and sounds fine.  So I'm all around quite happy and feeling quite a lot better!
Comment: @StaceyAnne - well done! More brave than stupid !There's a nice voice there that needs to be let out. You wandered between A and Bb acapella,(lots of folk can do that), but stayed in pitch when the guitar was played.I hope others will give their verdicts too. You don't need to look for the nearest tree or find a big lorry !!  Was that exercise a useful one to you for an answer?
Answer: You can use software to analyze your voice.
There is software that will draw a chart of what you sang (the frequencies you sang), where you can see how close or far you were from each note.
Some options include Melodyne, Waves Tune, Nectar, Canta, GSnap. There are a lot of options out there, from all the price range (some free).
On these charts your voice will be drawn into a piano roll. The closer the line is to the center of the key/note, the closer you are from that note. Depending on how detailed the software is, you can see things like how good you are at keeping a steady pitch, tremolo, and vibrato.

Another tool you can use is the pitch correction amount meter of real-time pitch correction software. You don't have to use the pitch correction, or know how to use it. You can mute that track.
As you sing you can use the correction amount meter as reference of how close or far you are from the note. This approach has the advantage that you don't need to record, you see the results as you sing, allowing you to make corrections on the go.

If the pitch corrector changed your voice's pitch +20 cents, it means that you were -20 cents out of tune from that note, making it an "out of tune" meter too. You can also see which note you are singing, it is the highlighted key in the piano keyboard.
A different option is to use a very accurate, reliable, fast tuner. Be very careful here, since some are optimized for specific instruments and can behave chaotic when used with voice.

This is similar, and maybe better and simpler, to using the change meter in a pitch correction software, but only if you find one that responds accurately and smoothly to your voice.
Pitch correction software is fine tuned to your voice, so it will tend to give you more accurate and smooth results, even if these results are not as explicit as they are in a tuner.
Be very careful when using all these visual aids. Use them as reference but don't rely on them. Don't train yourself to use them as a cue. You don't want to end up needing them to sing on tune!
All these are good at showing your pitch dynamics, but singing is much more than that. We know that what we hear when we sing is not a very accurate representation of what others are listening, so record yourself and hear what's going on. Maybe you want to do corrections and changes to things like your articulation, timbre, accent, etc.
Answer: It's been a couple of years since I asked this question, and over that time I've learned quite a bit. Here's what I learned:

With time and practice, it becomes much easier to tell when you're singing in key. I practice regularly and no longer am concerned about being out without knowing it.
Accompaniment with another instrument, like a guitar and piano, make it much easier to remain in key. The average untrained voice is going to have difficulty staying in key with no accompaniment at all.
It is possible to have a weak singing voice and be able to (with lots of practice) sing one or two songs well just by focusing on those songs. It is very difficult for an untrained person to sing a song right the first time. Every song needs its own practice.
Some songs are easier than others.Getting to know your range and which keys are comfortable really helps. Start with practicing the songs that are really comfortable. This can be as simple as just singing songs that "feel" easy. No need to go figuring out keys.
Church hymns and Christmas carols are great for practicing because they're written in keys designed for most people to sing.
Communal singing, in church or a community choir, can really help improve your singing because (1) lots of other voices and accompaniment and (2) your voice isn't singled out, so no pressure!
With time and practice and the tools mentioned in other answers here, it's possible to develop an ear for knowing what's in key.

(Yesterday, I thought I'd tuned my guitar correctly, but when I played an 'A' chord it sounded very off. I figured out it was the B string out by ear and re-tuned it. So proud of myself! )
Answer: Fun alternative: you can try a karaoke game like Singstar or Ultrastar, the latter being open source. They allow you to play a song and sing along, and will give you a score depending on how well you "hit" the notes.
I'm not sure how accurate it is, but I had a lot of fun playing with friends.
Comment: And I thought my 29 SE accounts was a lot! you have 42. Perhaps you've found the the answer to life, the universe and everything.
Answer: I like using software that charts your voice frequency over time.
Example of output of such software you can see on the following graphic. Space of screen where chart is drawn is devided into the fields that represent notes. You simply sing your part and try have your chart in the middle of each field, then you sing on pitch. When you are exactly in the middle between two notes you sing off-pitch, your note can't be considered neither as first or a second of those two notes.
With this kind of tool you can easily learn how important is breathing. Every teacher will tell you that, but there aren't many teachers that are capable of telling you why breathing is important (based on my experience). Here you can see that when you breathe more correctly lines on the chart are closer to straight lines and it is easier to maintaint them on certain level.

I'm not telling you to be completely dependant on machine, I'm simply saying that this let's you see for yourself how controlling your voice works and over time you learn to simply hear it. For me it's a start solution, later you start to simply hear that.
An example of such software would be Canta which is free but also very basic solution.
Answer: Singstar is very forgiving, wouldn't use it for deciding whether you can hit a note to within 10 cents.
Melodyne etc would be good to test not just whether you can hit the notes, but also whether you hit them easily, or take some time to settle to pitch.
Singing to a tuner is painful, the more you watch the indicator, the more nervous you'll get.
Singing to a reference pitch/chord sequence is always easier; unless you have perfect pitch, most people will drift over time without. I even know people with perfect pitch whose tolerance for small drifts is a lot higher than mine, & I don't have perfect pitch, only good relative pitch.
Answer: Practice with a tuner that can output flat tones. I use two. One outputs a tone to my earbud while I measure my intonation with the other. You can start to "feel" when your in tune since it will sound brighter.
Using a vibrato is also important since it will make that process not so "exact".
Comment: Honestly, I don't think it's a good idea to rely on a tuner for practising intonation, certainly not for vocals. Not only is the feedback mic->processor->display->eyes much slower than the immediate hearing you need when actually doing music, it also trains a cue you can't use when playing with others. (Also, it's not really accurate if you want proper just intonation.)
Comment: To be honest, I think using a tuner works well. I do this when practicing the ocarina, which is an instrument where it can be quite difficult to pitch correctly.
Comment: There exist tuners designed for singers that can display frequency of up to three simultainous voices and are very fast and accurate, unfortunately also expensive. In my opinion tuner is good if we want to learn just to hit a certain note, but if we want to practice singing in tune on a particular music part, for me it becomes useless, unless it charts the frequency over time.
Comment: I agree with all these comments. Using a tuner is just one of the many excersizes any musician should be doing while practicing. I think it goes without saying the most important activity to improve your ear is singing/playing with other people or a recording. Do that every day!
Comment: @LeeWhite The occarina has a more simple frequency pattern, which makes sense to use a tuner. The human voice has a more complex frequency pattern, which will more easily confuse the tuner without necessarily being off pitch.

How do I know when I'm singing in key?


Canonical vs Requested Type in Content Negotation

Question: So I was wondering what should be done with HTTP Content Negotiation regarding requests where the returned data may have multiple valid MIME types.
For example if say I have some arbitrary data that has the following possible MIME types:
<code>text/data,application/x-data,application/data+xml
</code>
Given that there are multiple MIME types possible a client application requesting data of this form from my web application should reasonably expect to receive that kind of data regardless of which of the MIME types they use in their requests Accept header.  BUT there will generally be some consensus about which type is the canonical type for this data (ie. one will be a proper registered MIME type with the IETF while the others will be pre-registration or pre-standardisation types).
So my question is should I in replying to these requests set my returned Content-Type header to be the canonical type or the requested type?  Which is better practice?
Should I always return the canonical type or should I echo back the requested type to ensure compatibility with older/poorly written apps that haven't been updated?   Currently I'm returning the canonical type as this seems to be to be a better approach and what most people are doing with the data types I'm working with.
This is somewhat subjective so if you think it should be community wiki instead of a question let me know and I'll consider changing it
Answer: When a user-agent (client application) requests a resource they will beacon out several different mime-types for that single requested resource.  This occurs for compatibility reasons to let the web server know what the user-agent is capable of accepting.  It is the job of the server to determine what the mime-type of the resource will actually be.
It doesn't hurt to make some decisions on the server side to in finding the appropriate response.  If you wish to serve all HTML pages as XML, for instance, but a major user-agent does not support the necessary mime-type you can supply a dynamic response using an assisting technology, such as PHP or ASP.  In the case of this example the best idea would be to set the correct mime-type as the canonical and if the user-agent does not support the canonical then serve them something else that they will support, otherwise everybody gets the canonical.
Comment: In my case the MIME types are all valid types for the same data format (the data returned will be identical regardless of the type) so it's not an issue of generating an appropriate response but of which MIME type should I return in the Content-Type header
Comment: In that case then pick the one you believe to be most widely supported and is most appropriate.


How to average random numbers in java?

Question: thanks in advance for any help I'm in an intro to java class and our home work was to generate 10 random numbers between 1&50 which I got and then average the generated numbers. I can't figure out how to average them here's what I have. Is there a way to store each random number as a variable?
public class randomNumberGen
{
     public static void main(String [] args)
     {
         Random r=new Random();

         for (int i=1;i<=10;i++){
             System.out.println(r.nextInt(50));
             System.out.println();
              int average = (i/4);

              System.out.println("your average is"+average);

         }
     }
}

Comment: average = i/4 ????
Comment: like for every average, sum and divide by amount of items.
Comment: `r.nextInt(50)` produces values between 1 and 50 ? I don't think so...
Comment: Hint: what is `String [] args`? But really there is no need to store the data, simply calculate the [moving average](https://en.wikipedia.org/wiki/Moving_average).
Comment: Hint 1: To both print and calculate average, you'll be using each random value twice, so you need to assign it to a variable. --- Hint 2: Formula for average is `sum(values) / count(values)`. You know the count is 10, so all you need to do is sum them.
Comment: first define insert two parameters `sum = 0` and `count = 0` , then calculate average with them
Comment: you must calculate it from updated `sum` and `count`
Comment: Incidentally, your code is wrong - [`Random.nextInt(bound)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) returns a value `[0,bound)` so in your case between `0` and `49` and not between `1` and `50` as required.
Comment: @fabian `r.nextInt(50)` produces numbers between [0 .. 49]
Answer: use streams with java 8
 final int numberOfRandom = 10;
 final int min = 0;
 final int max = 50;
 final Random random = new Random();

 System.out.println("The ave is: "+random.ints(min, max).limit(numberOfRandom).average());

Comment: I would use `DoubleStream.average()`
Comment: @PeterLawrey Pretty good!! I will defenetly consider that!
Thns a lot :)
Comment: In this case `IntStream.average()` is more appropriate than DoubleStream ;)
Comment: I think this is completely not the point. He is starting to learn Java, and this is his homework. I see no point neither on giving the code to copy/paste nor on using "plug and play" methods. This answeris perfect for the algorithm part, but not for the question being made.
Answer: First of all you have to replace "r.nextInt(50)" for "r.nextInt(50) + 1" because r.nextInt(n) returns a number between 0 (inclusive) and n (exclusive). Then, you know that an average is just a sum of n values divided by n. What you can do is just declare a "total" variable initialized to 0 before the loop. On each iteration you add to this variable the random value generated by r.nextInt(50). After the loop you can just divide the total by 10 so you get the average.
PS: it's a good practice to don't use "magic numbers", so it would be perfect (and luckily your teacher will have it in count) if you declare a constant for the number of iterations and then use it both in the loop condition and in the average calculation. Like this, if you have to make it for 100 numbers you only have to change the constant value from 10 to 100 instead of replacing two 10's por two 100's. Also this gives you the chance to give semantic value to these numbers, because now they will be "AMOUNT_OF_NUMBERS = 10" instead of just "10".
Answer: Average = Sum of numbers / amount of numbers
int sum = 0;
for (int i=1;i<=10;i++){
    sum += r.nextInt(50) +1; //nextInt 50 produces value 0 to 49 so you add 1 to get 1 to 50 OR as suggested in the comments sum/10d
}
System.out.println("Average is: " + sum/10) // If you want the result in double (with decimals) just write sum*1.0/10

You could also do the same with a while loop.
    int i = 0;
    int sum = 0;
    while(i < 10){
        sum += r.nextInt(50) +1;
        i++;
    }
    System.out.println("Average is: " + sum*1.0/i);

Or even shorter with lambda expressions: (/java 8 streams)
OptionalDouble average = IntStream.range(1, 10).map(x-> x = r.nextInt(50) +1).average();
System.out.println("Average is "+ average.getAsDouble());

.map(x-> x = r.nextInt(50) +1) // maps (changes) each value from 1 to 10 to a random number between 1 and 50
.average(); // calculates the average.

Comment: @Mohsen_Fatemi I know it's not good practice to solve homework for others, but this *is* a valid solution. So why downvote!?
Comment: Code without explanation is not helpful.
Comment: @f1sh Because giving away solution will encourage homework trolls. There are already enough of those around.
Comment: @Andreas I'm very aware of that, but at least OP has some code to show. And I refuse to downvote correct code.
Comment: for complex problems you can write the code , it's just a simple problem ...
you must write the idea ...
i he/she can't write this simple code , never can write complex codes
Comment: Write `sum/10d` instead of `sum*1.0/10` in case floating point values should be the result.
Comment: @Mohsen_Fatemi I am aware of the learning process behind this. I also know this is a very simple task. But working code is a valid answer, no matter the politics behind it. What's worse than answering homework questions is to downvote correct answers just because you personally don't agree with them.
Answer: Like every average, it's sum of elements / amount of elements. So let's apply it here:
import java.util.Random;

public class randomNumberGen
{
    public static void main(String [] args)
    {
        Random r=new Random();
        double sum = 0; // is double so to prevent int division later on
        int amount = 10;
        int upperBound = 50;

        for (int i = 0; i < amount; i++){
            int next = r.nextInt(upperBound) + 1; // creates a random int in [1,50]
            System.out.println(next);

            sum += next; // accumulate sum of all random numbers
        }

        System.out.println("Your average is: " + (sum/amount));
    }
}

Answer: Store variables outside of the loop to store both the total amount of numbers generated as well as the sum of those numbers. After the loop completes, divide the sum by the total amount of numbers.
public static void main(String [] args)
{
    Random r=new Random();
    double sum = 0;
    int totalNums;

    for (totalNums=1;totalNums<=10;totalNums++){
        int randomNum = r.nextInt(50);
        sum += randomNum;
        System.out.println(randomNum);
    }

    double average = sum/totalNums;
    System.out.println("your average is: "+average);
}

Answer: Simply create a variable sum starting at zero that you increment at each iteration. After the loop, simply divide by the number of elements..
Comment: `nextInt(50)` does *not* generate a random number between 1 and 50.
Comment: i would store the number of elements to a constant/variable so you don't have to put the ``10`` in there twice.
Answer: Average means you should add everything up and devide it by the number of elements (50).
import java.util.Random;
class Homework {
    public static final Random RANDOM = Random(); // never regenerate randoms
    public static void main(String args[]) {
        final int N = 50;
        int sum = 0;
        for (int i = 0; i < N; ++i) {
             sum += RANDOM.nextInt(50)+1;
        }
        System.out.println("Avg: "+ sum / (float) N);
    }
}

This should do the trick. Try to learn from it not just C+P.
Ps: Friggin annoying to write code on a phone.
Comment: Loop over numbers to sample numbers. Loop over numbers to sum numbers. This is logically rather ... poor.
Comment: I couldn't disagree more. This answer shows the sort of lack of "thinking it through" logic that we try and train _out of_ new programmers. You need need a sum of numbers there is absolutely no reason to store all the numbers. This is waste of space and time - the two things that are scarce in programs.
Comment: @BoristheSpider I know. Just thought that if he can't do the task himself he may not be an awesome programmer who will just take a Java8-Stream one liner and be ok.
Comment: Then why post it??
Comment: @BoristheSpider Explanation above.
Comment: I don't understand. Are you dismissing the _logic_ of the code because you were writing it on a phone? That makes no sense.
Comment: @BoristheSpider No. It's a pretty simple task. If the OP can't get it to work I'll better break the problem down (first generate numbers, then sum them, then do the average) instead of doing something he will not understand.
Comment: @BoristheSpider Disagree with the space thing. Every modern Computer should have that 200 bytes of memory.
Comment: @BoristheSpider Are you ok now?

How to average random numbers in java?


Expansão atrasada no corpo do laço for usando a opção /f

Question: Reduzi o código para ser breve:
<code>@echo off

setlocal EnableDelayedExpansion

set /a n_tokens=2

for /f "tokens=!n_tokens! delims=\" %%s in ("Program\Executable") do (
    echo %%s
)

pause > nul
</code>
Sei que nesse contexto não seria necessário usar exclamações (!!) para expandir a variável, mas no contexto que preciso é.
Ao usar a delayed expansion recebo o erro "tokens=!n_tokens! foi inesperado", gostaria de saber qual é o problema que acontece e alguma solução também.
Answer: Pesquisei no StackOverFlow em inglês e achei um post dizendo que simplesmente não é aceito delayed expansion no corpo do for, então resolvi usar a sugestão dada pelo usuário em uma das respostas:
<code>@echo off

setlocal EnableDelayedExpansion

set /a n_tokens=1

:: Este é um exemplo resumido do que eu tentava
for /f "tokens=* delims=\" %%s in ("Prog\Exe") do (
    set /a n_tokens=2

    for /f "tokens=!n_tokens! delims=\" %%s in ("Prog\Exe") do (
        REM erro !n_tokens! foi inesperado
    )
)

:: Solução que encontrei
for /f "tokens=* delims=\" %%s in ("Prog\Exe") do (
    set /a n_tokens=2

    call :Func
    REM Continuar o código...
)
goto end

:Func
:: Essa função é chamada após a atualização da variável n_tokens

for /f "tokens=%n_tokens% delims=\" %%s in ("Prog\Exe") do (
    echo %%s
    REM imprime corretamente "Exe" (segundo token de "Prog\Exe")
)

goto :eof

:end
pause > nul
</code>


Conditional Probability Question for A Continuos Random Variable

Question: Suppose $X$ is a continuous random variable with density $p$ with respect to the Lebesgue measure. According to Radon-Nikodym theorem $p$ is measurable itself so it can be seen as a random variable. Question is what is the following expression equal to
$$p(X=x_0|p(X=x_0)=3)\overset{?}{=}3$$
Or in a more general but vaguer sense
$$p\Big(X=x_0\Big|p(X=x)\ {\rm is\ given\ and\ is\ }f(x)\Big)\overset{?}{=}f(x_0)$$
I have guessed what they need to be equal to --after the question marks-- but I do not have any rigour argument to justify them. So I would really appreciate if you could please guide me how to do it (or prove me wrong).
Comment: "$p$ is measurable itself so it can be seen as a random variable." I don't think this is correct. It is a function on the measurable space $\mathbb{R}$ with the Lebesgue measure, but this measurable space is not a probability space. Further, in order for you to make sense of the conditional probabilities you have written, your "random variables" $X$ and $p$ need to live on the same probability space.
Comment: The expression you are conditioning on, "$p(X=x_0)=3$", makes no sense to me. $p(X=x_0)$ is a deterministic number, given by the value of the density function at $x_0$. The statement "$p(X=x_0)=3$" is therefore either true or false. You are conditioning on an event which is either empty (which is nonsense) or which is the whole space (which is trivial). Can you clarify what you mean? Did you mean to say "$p(X)=3$, which means you take the random value of $X$ and plug it into the density function, and condition on this random output being 3?
Comment: I can think of two interpretation of the notation $p(X=x_0|\dots)$. (i) If $X,Y$ are jointly continuous, then $p(X=x_0|Y=y_0)$ is the conditional distribution of $X$ given $Y=y_0$. (ii) If $(X_\theta)_{\theta\in \Theta}$ is a family of distributions parameterized by $\theta$, then $p(X=x_0|\theta=\theta_0)$ is the distribution corresponding to $\theta_0$. It seems like your post uses (i) (since you do not mention a parameter family), while your comment uses (ii). That is the difference.
Comment: Thank you for the comment. $p$ is measurable and integrates to $1$ over $\Omega$ (the original state space) so I don't see which assumption about being a random variable doens't hold about it? Again I do think they live in the same probability space. Regarding your second comment I don't see why then the following is a correct statement: Suppose $X\sim\mathcal{N}(\mu, 1)$. The quantity of $p(X=x|E[X]=x_0)$ is meaningful and so should be the quantity of what I asked, right?
Comment: @MikeEarnest I don't understand why you say that. Take for example $X$ coming from a discrete distribution which is dirac delta function and assume the functions peak (where $p(X=\theta)=1)$ is the parameter to be learned (say $\theta$). Now what is the difference between my question and the question such as $p(X=2|\theta=1)$. Can you tell me why do you find a difference between these two settings?
Comment: @MikeEarnest, thank you for your reply. I guess I have too many doubts about what exactly is what but I try to explain what I mean. I agree with you that I mix these two in a way but I have reasons for it. After all a parametric family in many cases is nothing but a function of the distribution. For example for a Gaussian $(\mu, \sigma)$ are $E(X)$ and $E(X^2)-E(X)^2$. So when the parameter is given it is equivalent to say that the first two moments are given. I am trying to carry the same reasoning to density (or pmf). Where the values of density at some points are given.
Answer: Let $p_{\small X}(x)$ be the probability density for the continuously distributed random variable $X$.   Then $p_{\small X}(X)$ is a random variable, and you seem to want to talk about the condtional measure $p_{\small X\mid p_{\small X}(X)=3}(x)$.
The nature of the conditional measure, and whether it even exists, entirely depends on the distribution for the random variable.

If $X$ has a probability density of $3$ in an integrateable interval of uncountable many points, say $A$, then the conditional probability measure $p_{X\mid X\in A}(x)$ will be a probability density function. $$p_{\small X\mid X\in A}(x)=\dfrac{p_{\small X}(x)\mathbf 1_{x\in A}}{\int_A p_{\small X}(s)\mathsf d s}=\dfrac {\mathbf 1_{x\in A}}{\int_A \mathsf d s}$$
If $X$ has a probability density of $3$ in an interval of finite many points, say $B$, then the conditional probability measure $p_{X\mid X\in B}(x)$ will be a probability mass function.
$$p_{\small X\mid X\in A}(x)=\dfrac{p_{\small X}(x)\mathbf 1_{x\in B}}{\sum_{x\in B} p_X(s)}=\dfrac {\mathbf 1_{x\in B}}{\lvert B\rvert}$$

For instance, if $X$ has density of $3$ at only one point, say at $x_3$, then the conditional probability that $X=x_3$ when $X=x_3$ will most surely be $1$.

In other cases it may not even be sensible.
Comment: $p_{\small X}(X)$ is a random variable, but $p_{\small X}(3)$ is a constant.  $$p_{\small X\mid p_X(3)=0.5}(3) = \begin{cases}0.5 &:& p_{\small X}(3)=0.5\\\textsf{undefined}&:& \text{otherwise}\end{cases}$$
Comment: Thank you for your thorough reply. I guess there is tiny difference between my question and what you wrote and that was conditioning on the value of the density at a single point. I guess I have a little bit of confusion and that is mixing the concept of parametric models with real conditioning. To me it seems rational to say for a discrete RV $X$ where we know $p(X=3)=0.5$ it indeed should be the case that $p(X=3|p(X=3)=0.5)=.5$. I would be happy to know how this can be formalized....
Comment: .... I guess your solution is a bit of a different case where you consider $p(X)$ as an RV (btw thank you for agreeing that $p(X)$ is indeed an RV.) and conditioning on the value that it takes.
Comment: thank you! That is all I needed, but could you please tell me how can I prove measure theoretically that indeed $p_{X|p_X(3)=0.5}(3)=0.5$ for $X=3$?
Comment: $p_{\small X}(3)=0.5$ is either certainly true or certainly false.  If it is true, then you definitely know what the density at three will be. If it is false, then the conditional measure cannot be defined.


Configure Bind9 to forward for a zone and reject all other requests

Question: I have an interesting use case where my hosting providers (Heroku) DNS has intermittent issues resolving a certain subdomain.
They have an option that allows you to insert a custom resolver as the primary lookup mechanism and then any failed requests will fallback to their DNS.
How might I setup a bind9 server to forward requests to 18.104.22.168 for one subdomain only? And all other requests need to fail, causing the client to use the secondary nameserver (which I don't know the IP of).
My first attempt was to add the zone and specify the forwarder;
zone "a-test.subdomain.com" {
    type forward;
    forwarders {
        188.8.131.52;
    };
};

And then setting
recursion no;
allow-query { any; };

But it results in
query failed (REFUSED) for a-test.subdomain.com/IN/A at query.c:5665

Answer: Inside the configuration file BIND9, locate the options section and add or modify the following lines:
options {
    recursion yes;
    allow-query { any; };
};

Below the options section, add the following lines:
view "forward-view" {
    match-clients { any; };
    recursion no;

    zone "a-test.subdomain.com" {
        type forward;
        forward only;
        forwarders {
            220.127.116.11;
        };
    };
};

view "fallback-view" {
    match-clients { any; };
    recursion no;

    // Add your secondary nameserver's IP address here
    // Replace 192.0.2.2 with the actual IP address
    zone "." IN {
        type forward;
        forwarders {
            192.0.2.2;
        };
    };
};

Save the changes and restart the BIND9 service to apply the new configuration.


composer extends class not found

Question: Como usar o extends com o autoloade do composer?
Da forma que está me retorna o seguinte error:
Fatal error: Class 'App\Modulos\Mail\Mail' not found in ...Google.php on line 7

Composer:
"autoload": {
    "psr-4": {
        "App\\": "app/"
    }
}

Estrutura:
- Public
    app/
        Modulos/
                Mail/
                     Google.php
                     Mail.php
    vendor/
    bootstrap.php
    cli-config.php
    composer.json
    composer.lock
    index.php
    router.php

Public/index.php
<?php
require __DIR__.'/vendor/autoload.php';

$google = new \App\Modulos\Mail\Google;

var_dump($google);

app/Modulos/Mail/Google.php
<?php

namespace Google;

use \App\Modulos\Mail\Mail;

class Google extends Mail {

}

app/Modulos/Mail/Mail.php
<?php

namespace Mail;

abstract class Mail {

}

Comment: no titulo @rray?
Answer: Consegui resolver mudando apenas os "namespace" nos arquivos:
app/Modulos/Mail/Google.php
<?php

namespace App\Modulos\Mail;

use \App\Modulos\Mail\Mail;

class Google extends Mail {

}

app/Modulos/Mail/Mail.php
<?php

namespace App\Modulos\Mail;

abstract class Mail {

}

composer extends class not found


The simplest JavaScript in the world won't work!

Question: I have this script in the separate Sample.js file:
function MyPrint(text)
{
 document.write(text);
}

And I have the following HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <title>Silly example</title>

Final result is that the text "Hello silly world!" is NOT printed on the page. What should I do to make this work? I would prefer not to move the script tag to the head, if possible. Thanks.
Comment: remove the src from the script tag and put in a new one.
Comment: In which browser? That's the problem with this 1990's legacy scripting stuff.
Answer: I think the src tag overrides whatever's inside.
Try the following:

Comment: Well, replace `JavaScript/Sample.js` with whatever the script is, then replace the `MyPrint(...)` call with the function.
Comment: I believe that the type attribute is not needed.
Comment: @Sime Vidas, it's not needed on html5
Comment: @Sinan OK, it is needed for validation. I meant that it is not needed in order for the JavaScript to execute properly in todays browers (regardless of the used DOCTYPE)
Comment: @Sinan The type attribute gets ignored in nearly all browsers
Comment: I think it's good practice to preserve the type anyways. Just my 2 cents.
Comment: John Resig wrote a pretty interesting blog post about this exactly. ["Degrading Script Tags"](http://ejohn.org/blog/degrading-script-tags/) deals with allowing something like ``. Give it a read!
Comment: I'm *guessing* it's the other way around than what you describe it - the internal script is ran on error (as in, when, say, the external script is missing)?
Answer: Your script can be considered loaded after the closing </script> element. This should work:

Answer:

Answer: window.onload = function(){
 MyPrint("Hello silly world!");
};

Comment: The script uses `document.write` so this will not have the desired behaviour.


AMP.goBack between different pages

Question: I couldn't figure out why AMP.goBack (on tap of button) didn't go back 1 page, like when you click the back button on the browser.
I found this: https://github.com/ampproject/amphtml/issues/5225
It's still open since March of 2017, so clearly the community has no need for a back button that spans different pages in an AMP document (I refuse to bind multiple documents into 1 page just for the sake of using a back button, the payload would be too much and asking a developer to take care of 1 big page is unreasonable and opens it up for way more issues than necessary)
Staying within the AMP space, and having their validater validate you still, how would one add a "history.back" to an AMP page?
Our site implementation is pure AMP for now, with the idea of PWA later-on (with AMP pages being loaded within PWA)
I can't understand why an AMP page (and the team behind the decision making) thought that having everything in 1 page seemed like a good idea.
Would love some feedback from someone who had this issue and what your work-around to this would be.
Answer: In the interim, I've used an amp-form POST to my back-end, that uses the DOCUMENT_REFERRER replacement that AMP offers (because it doesn't offer it on all elements yet), to redirect back to the previous page. The caveat of this is that your "history" will always just be the previous page you were on. So if you were on Page A, navigated to Page B and click back, you'd go back to Page A. If you click back again, you'd navigate to Page B (and not the page you were on before Page A or B).
This implementation would have to do for now.

AMP.goBack between different pages


ReactJS.net on Azure

Question: I'm hoping I'm able to get some help out there with people with more experience on ReactJS than me. I'm using MVC 5 with ReactJS (using ReactJS.net to take care of the translation from JSX to js) and I was able to some stuff done that works pretty well. Testing the my code on my local pc works fine for debugging, but once I publish it to Azure for testing I get this error:
GET http://mywebsite.azurewebsites.net/Scripts/jsx/FriendSelect.jsx?_=1429662139230 404 (Not Found)
This is usually the error I get when the jsx file doesn't get converted to js successfully. Does anyone know the steps I need to take to get ReactJS.net to work properly on Azure?
Comment: It's definitely doable, I've seen a few people do it (one user was using Azure websites for benchmarking pooling of JS engines). Can you check the error log for any errors? Do you know which version of IIS it's using?
Answer: I don't understand why you need to use anything react.net etc...? React comes with a JSXTransformer file which transforms your JSX to JS while you're in the process of developing your site.  Compiled and minified JS code should be used in production once you no longer need JSX.   Tools like Gulp can assist with automatically minifying your code for you.
Whether the site is Azure, Linux Ubuntu or anything else it shouldn't matter.
Comment: Chris, I agree with what you are saying. Once the files are converted/complied there shouldn't be an issue and that's why I was trying to use ReactJS.NET instead of Gulp.
Comment: I'm tested my configuration on other servers running IIS 7 and IIS 8 and the app works ok, ReactJS.net does it's work just fine. The problem seems to be specific to the Azure environment.
Comment: Chris, the reason I use React.Net is because it allows you to create bundles. You bundle up JSX files along with js files and you don't have to worry about minifying web.optimization takes care of that for you.
Comment: ah okay, I think Babel is a very popular tool that has this ability as well.  I typically use that to watch directories, transpile JSX and minify.

ReactJS.net on Azure


Automatically quitting ngspice after simulation

Question: I was working on an automation project which requires me to fire a simulation in ngspice, get the data in a .txt file and quit ngspice. I have the following code to call ngspice:
<code>import sys
import os

def invoke_ngspice():
    os.system(r"C:\Users\MyPC\Desktop\GUI\ngspice\bin\ngspice_con.exe C:\Users\MyPC\Desktop\GUI\ngspice\bin\test_circuit.circ")
    os.system(r"quit")
</code>
While calling the above function does the simulation and save part flawlessly, I am unable to quit because ngspice holds the execution. Is there anyway of quitting ngspice cleanly? I don't want to manually type in quit in ngspice command window everytime or kill it because simulation time is variable.
Answer: so I found the method to quit ngspice systematically using the control loop. In the test_circuit.circ file I added quit statement in the .control section and that's it!
<code>.control
set filetype=ascii
run
wrdata temp_file abs(v(A_1)-v(B_1))
quit
.endc
</code>