Is L'Hopitals rule applicable to complex functions?

Question: I have a question about something I'm wondering about. I've read somewhere that
L'Hopitals rule can also be applied to complex functions, when they are analytic.
So if have for instance:
$$
\lim_{z \rightarrow 0} \frac{\log(1+z)}{z} \stackrel{?}{=} \lim_{z \rightarrow 0} \frac{1}{(1+z)} = 1
$$
Now i'm wondering if this is correct? Also if we take $|z|<1$, is it then correct?
Thanks,
Comment: By the way, if $f, g$ analytic at $a$, and $f(a) = g(a) = 0$, then $\lim_{z\to a} \frac{f(z)}{g(z)} = \lim_{z\to a} \frac{f(z) - f(a)}{z-a}.\frac{z-a}{g(z)-g(a)} = \frac{f'(a)}{g'(a)}$.
Comment: Both $\log(1+z)$ and $1/z$ are meromorphic at 0. For meromorphic functions the Laurent series of their product is the product of their Laurent series: so you have $$ z^{-1}\log(1+z) = z^{-1}(0 + z + O(z^2)) = 1 + O(z) $$ and is holomorphic.
Comment: Your limit is just the derivative of $log(1+z)$ at $0$, and it is 1. What do you mean by taking $|z| < 1$? I think that we just care about a neighborhood of $0$.
Comment: I heard that L'Hopitals rule can only be applied to analytic functions in a certain region. So if we have that $|z|<1$, then we get no problems with the definition of the $\log$ right?
Comment: Since you're interested in the limit at $0$, bounding the functions to the unit circle is irrelevant.
Comment: The analyticity of log is not defined within a closed circle. You would need to choose a branch cut in order for log(1+z) to be an analytic function. Since you can't have log(0) then your branch point would be wherever (z+1) = 0 which is z = -1. Then your branch cut would extend from z = -1 and would have to avoid the point z=0 since you're taking the limit there. (I would use the principal branch $-\pi <\theta\le\pi$). (Also the reason we choose a branch cut is because log(z) is periodic and in order to be analytic, log(z) must be well-defined: have only one output for each input).
Answer: L'Hopital's rule is a local statement: it concerns  the behavior of functions near a particular point. The global issues (multivaluedness, branch cuts) are irrelevant. For example, if you consider $\lim_{z\to 0}$, then it's automatic that only small values of $z$ are in play.  Saying "take $|z|<1$" is redundant.
Generally, you have a point $a\in\mathbb C$ and some neighborhood of $a$ in which   $f,g$ are holomorphic. If $f(a)=g(a)=0$, then
$$\lim_{z\to a}\frac{f(z)}{z-a}=f'(a),\qquad \lim_{z\to a}\frac{g(z)}{z-a}=g'(a) \tag{1}$$
hence
$$\lim_{z\to a}\frac{f(z)}{g(z)}= \lim_{z\to a}\frac{f(z)/(z-a)}{g(z)/(z-a)} =\frac{f'(a)}{ g'(a)}$$
Note that the above is a  simple special case of  the L'Hopital's rule, because we have (1). It's basically just the definition of derivative.
Comment: We can use this when the limit goes to infinity, right ?
Comment: @Our Don't know if you still want to know, but I think it can be used. The function maybe not be holomorphic at the point, but should be holomorphic in the region around the point.
Comment: @LaxmiNarayanBhandari thanks!


Intersection of two planes $a \cdot x = 0 $ and $b \cdot x = 0$ with $(a, b)$ dependent and indpendent.

Question: I'm trying to solve the following question:
Let $U=\left\{\left(x_1, x_2, x_3\right) \in \mathbb{R}^3: a_1 x_1+a_2 x_2+a_3 x_3=0\right\}$ and $V=\left\{\left(x_1, x_2, x_3\right) \in \mathbb{R}^3: b_1 x_1+b_2 x_2+b_3 x_3=0\right\}$, where $a=\left(a_1, a_2, a_3\right)$ and $b=\left(b_1, b_2, b_3\right)$ are vectors in $\mathbb{R}^3$.
Express the intersection $U \cap V$ as the span of a list of vectors,
a) under the assumption that $(a, b)$ is linearly independent;
b) under the assumption that $(a, b)$ is linearly dependent.
I don't know what independent v. dependent tells us about the resulting planes. I realize that if the planes intersect the dimension of the subspace will be 1 and if not, it'll just be the zero vector. Any help is greatly appreciated.
Comment: $(a)$ the 2 planes must be non-parallel and hence intersect in a line. $(b)$ the 2 planes are parallel through $0$ and hence the same
Answer: Both planes pass through the origin.  If $a$ and $b$ are dependent then this means that
$ b = k \ a $
And it would follow that $U = V$, i.e. the two planes are actually the same plane.  So their intersection is the plane $U$ (which is also the plane $V$).
If $a$ and $b$ are independent, then the intersection will be the line
$ \ell(t) = t (a \times b) $
i.e., the line passing through the origin, and whose direction vector is the cross product between $a$ and $b$.


Blocking request to port 80 on gateway on Ubuntu

Question: I want to block access to the gateway (192.168.1.1) on port 80, to prevent network user from trying to access the router setup.  I'm using Ubuntu 9.10
Answer: iptables -A INPUT -j DROP -p tcp --to-destination 192.168.1.1:80 -i eth0

Change --to-destination 192.168.1.1:80 to the IP address of the gateway.
Change -i eth0 to the interface that you need the rule on.
Note that this will completely block all access to that IP/port combination unless you create a specific rule to allow traffic from one IP, like perhaps an administrative workstation.


Disable sleuth for from storing some traces

Question: I am using spring cloud finchley.rc2 with spring boot version 2 along with sleuth and zipkin.
I have a facade layer which uses reactor project. Facade calls services parallel and each service store some tracing info in rabbit mq.
Issue is I am seeing in zipkin some spans like
facade.async
service.publish > Because of mq

How can i stop such traces from being captured
Answer: You can create a SpanAdjuster bean, that will analyze the span information (e.g. span tags) and basing on that information you will change the sampling decision so as not to send it to Zipkin.
Another option is to wrap the default span reporter in a similar logic.
Yet another option is to verify what kind of a thread it is that is creating this span and toggle it off (assuming that it's a @Scheduled method) - https://cloud.spring.io/spring-cloud-static/Finchley.RC2/single/spring-cloud.html#__literal_scheduled_literal_annotated_methods


Remove language code from URL

Question: For example, with example.com/en/apple/12/article/11/23, in hook_init() arg(0) returns "apple," as I expect; in hook_boot() it returns en which is language prefix of English.
Answer: That is because hook_boot() is invoked too early in the bootstrap process, which means:

Not all the modules are loaded, including the Locale module that is the one that alter the path, and the reason why arg(0) returns "apple" in your example, when called in hook_init().
The language has not been set; it is initialized during the DRUPAL_BOOTSTRAP_LANGUAGE phase, while hook_boot() is invoked during the DRUPAL_BOOTSTRAP_PAGE_CACHE phase.
The call to drupal_path_initialize(), which alters $_GET['q'] with $_GET['q'] = drupal_get_normal_path($_GET['q']); is done during the DRUPAL_BOOTSTRAP_FULL phase, which is the last bootstrap phase.

Differently, hook_init() is invoked as last step done in the DRUPAL_BOOTSTRAP_FULL phase, which means all modules are loaded, the language has been set, and drupal_path_initialize() has been already called.
As side note, hook_boot() has been removed from Drupal 8; if you are using it, you will need to change your code. Using hook_init() is a possible alternative, since it is still used in Drupal 8.
Comment: so I should call `drupal_path_initialize()` manually in `hook_boot()`?
Comment: If you call `drupal_path_initialize()` in `hook_boot()` you would get an error about a not defined function; as per first point, it would not make sense doing it because the module that alters the result is still not loaded.

Remove language code from URL


Metric Modulation: Length of 'swing' notes

Question: I just exported a Piano score from Sibelius with a swing feel:

I wanted to edit the MIDI in my DAW and noticed, that the notes actually weren't in a triplet duration. The second note was always off the triplet grid:

So I went back to Sibelius and searched for the reason. I noticed, that in the playback options, it gives the first note a duration of 61,7% and the second one 38,3%

So my question is... Why would this be the default option?
Do you really play the swing feel like this. If the metric modulation is notated like above, shouldn't be the note duration actually 66,6% and 33,3% instead?
Comment: In comparison, the Musescore default is 60:40.
Comment: It's a lazy, relaxed triplet feel, not literal.  The notation given is a close and convenient representation only.
Comment: What ever it is default, you can adapt  the ratios and the dynamic emphasis. But only dilettantes will like e.g. military band chiefs will make us believe that it has to be always strictly the same!
Comment: What version of Sibelius is this? At least in Sibelius 6.2 (the last good version IMO), there are no such metric modulation symbols in the Playback Dictionary.
Comment: @piiperi It's the latest version of sibelius ultimate 2019.
Answer: If you study the timings of human players, you will notice that they almost never play mechanically exactly what the theoretical written values would be. Timings, pitches, dynamics, everything. Musical notation is a means of written communication about musical ideas from humans to humans. It's meant to be subjectively interpreted by a performer.
Exact triplet swing tends to sound awkward, and the faster the tempo is, the more you have to straighten out the swing.
Why it's the default - maybe they listened to the 66.6/33.3 swing and decided that it didn't sound realistic? I think all of the things in the playback dictionary have been adjusted so that it would correspond to how people would actually play it. Another example is the note length percentages for normal vs. tenuto - I think it's just based on trying out different things and adjusting to taste.
The meaning of the metric modulation marking is actually explained in the Sibelius manual: (from version 6.2. Sibelius Reference)

I cannot provide any statistics, but in my experience the symbolic metric modulation marking is more widely understood than the English word  "swing". And "swing 16ths" or "swing 8ths" would be even less widely understood... The symbols are a way to communicate the idea of swing without using English, even though there's the possibility of misunderstanding it to mean "to be played as triplet swing with machine-like mechanical microscopic accuracy".
To remedy the situation and cater for the microscopic interpretation - which might be becoming more and more common now that people experience life and communicate with each other through computerized filters instead of directly - it might be possible to use the "almost equal to" sign instead:

The downside of starting to use this would be, it would be contrasted with the old symbol, and it would enforce the incorrect interpretation of the old symbol as meaning "robotically precise triplets". Which usually isn't the original intention.
Perhaps the better alternative would be to educate the microscopic precision folks about the actual real-life use of the metric modulation marking? :)
FWIW, the metric modulation swing marking in Sibelius 6.2 seems to produce a swing of about 60% when exported to a MIDI file. Here it is imported to Ableton Live, and the background is set to triplet grid.

The swing isn't 66.6%, the length of the downbeat notes isn't precisely 100.0%, the notes don't have the same velocity...? That's because they specifically tried to program the Sibelius application so that its MIDI output would be close to a human player's interpretation of the notation.
Comment: It's more than that.  No-one who has experienced Swing argues that it SHOULD be triplet.  The metric modulation notation is not only unnecessary but also misleading.  Stamp it out!
Comment: It bugs me that we're calling this a metric modulation at all.  To my eyes and in my experience a metric modulation means a very different thing.  The 4/4 to 6/8 example is a metric modulation.  But it implies a change in beat unit while keeping steady tempo.  Swing notation is not usually associated with a tempo/beat unit change.  The notation just looks similar.
Comment: @LaurencePayne I agree that the metric modulation notation can easily be interpreted to mean triplet swing - and why shouldn't it - but if in practice few people play it exactly like that, even if they _try_...? Then what is a software company to do - it's in their best interest to make the program sound less mechanical whenever they can. :) This is just my speculation, but I suppose they thought the current default just sounded more realistic.
Comment: How about options "swing" combined with "humanizer"?
Comment: @piiperi Reinstate Monica the software company implement a perfectly good version of Swing playback - and it isn't triplets!  They also make it possible to (mis)use  Metric Modulation notation to give an inaccurate description of what is perfectly well just labelled 'Swing'.
Comment: @LaurencePayne I don't have statistics, but the metric modulation symbol is more widely understood than the English word "swing".
Comment: @piiperi Reinstate Monica  Really?  Apart from a simple 'q=h' when moving from 4/4 to cut time, and the like, I don't think they were much known until Elliott Carter started using them (for a rather different purpose) in the 1950s.  By which time plenty of swing music had been written and published.  Most of us never encountered them until Sibelius and other score-writing programs made them available - and a lot of people with little practical experience of musical performance got the chance to write and hear their music. Which is all very wonderful, but they sometimes got funny ideas!
Answer: "Swing" only means "play exact triplets" in software where the authors didn't know any better.
For humans it depends not only on the genre of the music but also on the overall tempo. It can mean anything from only just over 50%, up to 75% or more.
If you include Viennese waltz rhythm as a sort of swing, the first beat is shorter than its written duration, not longer.
Comment: "Swing" only means "play exact triplets" in software where the authors didn't know any better." But this question is proof that that isn't true... You are neither answering the question or attempting to
Comment: @ByBw, I think I disagree. The question asks "Do you really play the swing feel like this" and the answer here is pretty clearly answering "no." The question also asks "If the metric modulation is notated like above, shouldn't be the note duration actually 66,6% and 33,3% instead?" and the implied answer here is "no, because that's not really how swing is played." That's my impression of what the answer is saying, but maybe I'm missing something?
Answer: One of the minor crusades of my musical life is persuading people NOT to use the 'metric modulation' notation when they mean 'Swing'.  Swing covers a range of 'Notes inégales' but almost always isn't triplets.  Sibelius playback recognises the word 'Swing'.  So do live musicians.   So does everyone, except some educators who seem frightened of the concept and prefer the precise but inaccurate 'metric modulation'.  Don't do it!
However, Sibelius is not 'reading' the metric modulation directly.  It's looking up that string of characters in the Playback Dictionary and performing whatever function has been assigned to it.  And that assignation can be completely arbitrary!   It would be quite possible to assign that metric modulation text string to 'Instrument change to Violin'  :-)
In this case the programmers haven't been so mischievous!  But they HAVE recognised that misguided composers often use a triplet when they want Swing.  So they've made it provide something closer to swing.  It's a nebulous concept, but we can be pretty sure that, at a medium tempo, Swing ISN'T triplets.
You can edit the definition if you like.   But I expect if you'd WANTED triplets, you'd have written them.  Or used 12/8.
Comment: I think the problem with 'swing' is that there *is* no accurate proportion agreed upon. Get 18 musos playing together (as we obviously do - at least you and me) and there could well be 18 subtly different proportions going on. That's one reason why some bands swing, and others nearly make it.
Comment: Good luck fighting the windmills! ;)
Comment: I'm not sure whether I understand you correctly. If you mean it is not necessary to notate ternary rhythm to indicate " swing" as musicians and programs know what to do ... then I fully agree. +1
Comment: Lots of interpretations of 'Swing', yes.  But a band generally reaches consensus pretty quickly.  We musicians DO listen, you know!  It's almost harder to NOT fit in than to fit in.
Answer: The question posted above poses a simply logical question : If the notation is accurately defined in the marking, - ie. 'duplet = triplet', why does the software not obey the clear terms specified? Fact is, if we write exact values, the software should honor them, especially in a function relating to metric modulation. That is, unless we use an interpretive function, such as the swing (as opposed to 'straight') option on whatever program we use. Then the software can interpret the swing according to its default percentage settings, and the composer has the right to alter those settings according to their sensibilities. One is exact replication, the other is approximated interpretation, and both are valid or invalid according to individual intentions and purposes, as is the case in comparing the functional purposes of 'Tempo giusto' to 'A piacere' or 'Rubato' in classical performance. A default fixed percentage of swing, no matter how perceived or preferred by software creators, is just that - fixed, not variable!
Therefore a {60:40%}, or a {66.6.:33.3.%}, or ANY other percentage default setting will not, by itself, offer a more accurate imitation of human/musical feel than another.
Now, back to our actual question : I am also a classically trained composer, and I use MuseScore to notate my work, jazz or otherwise. I do not use the swing function, because I am aware of the nuances inherent to different swing subdivisions, and because I want those to be accurately presented in my scores, to whatever extent practical, not to be limited to what a software company might try and dictate as being the best/most commonly accurate/most natural etc. Therefore, many of my charts, at the very least, involve a mix of triplet and semiquaver swing, and straight quavers/8th-notes, and some are theoretical charts presenting material demonstrating the logically available spectrum of unique swing divisions. When you become aurally aware of that spectrum, you become consciously able to identify the difference between a {2-1} swing, and a {5-3}(62.5%), or {7-3}(70%) swing. Knowing that, and writing like that [ie. - with microscopic precision] is way closer to natural than a fixed default, which will not transfer acceptably across tempo or style changes, let alone from section to section, bar to bar, or phrase to phrase. So, unless you perpetually groove with the one default setting, I'd say avoid them, unless you can apply them at any point in a score.
Finally, what is 'swing'? Ah, just go and practice your triplets for now folks.
I'm pretty confident that, to the average user of composing software, the colloquial Western term, swing has been assimilated and understood sufficiently the world over, and would likely be more readily comprehended than the advanced theoretical, pseudo-mathematical term, metric modulation. Furthermore, since swing is categorically not metric modulation (although they can relate to each other), I would say that to conflate them is a fallacious misnomer, only serving to confuse issues.
Comment: I have edited your post to remove the elements that didn't answer the question, were rude to others, and that should have been comments. I have also fixed the overuse of capitals as they really hindered readability. Please read our [answer] page to understand the requirements for post quality. And remember, we don't tolerate rudeness or harassment of others here.


Maximal Domain for the following functions

Question: Hi I am quite lost with understanding maximal domains. I understand that the numerator when dealing with maximal domains usually are not taken into consideration. Is this true for all cases?
Can anyone help me to understand, how can I better identify, understand maximal domain problems?
$f\left(x\right)=\frac{ln\left(x^3-11x^2+24x\right)}{\sqrt{\left(ln\:x\right)^2-3ln\:x\:+2}}$
Cases like this, my only concern should be the denominator am I right?
I hope someone can help me better understand problem sets like this and going about solving them, the thinking process.
Thank you.
Comment: You can safely disregard the numerator for rational functions, because they are polynomials and can be defined for any real number. However, you cannot disregard the numerator here because the logarithm function is not defined for negative numbers.
Answer: You need to consider the domains of both the numerator and the denominator, then take the intersection of the two domains. In this case (assuming you are working over the real numbers) you need to make sure that all the inputs to $\ln$ are greater than zero, all the inputs to $\sqrt{}$ are greater than zero, and that you don't divide by zero.
Since there is an $\ln x$ term, we must have that $x > 0$. Factor the polynomial in the numerator -- it has roots at $x = 0,3,8$ and is positive on the intervals $(0,3)$ and $(8, \infty)$. For the denominator, let $y = \ln x$ and factor to get $y^2 -3y +2 = (y-1)(y-2)$, which is positive for $y \in (-\infty, 1)$ and $(2, \infty)$, which corresponds to $x \in (0, e)$ and $(e^2, \infty)$. Since $e < 3$ and $e^2 < 8$ the domain is:
$$(0,e) \cup (8, \infty)$$
Wolfram alpha agrees.
Comment: Hi Marc, can I say that because numerator ln(g(x)) has condition of g(x) > 0. Therefore, I have to consider the numerator as well and work it out?

So in other words, x^3-11x^2+24x > 0 I have to solve this solution. Following which the denominator has
1. 3 ln x + 2
2. (ln x)^2

Please advise.
Comment: Yes, $g(x)$ has to be greater than zero, and so does the entire contents of the square root.


What values of the independent variable do I use to compute the predicted data when calculating RMSE?

Question: I have a data set with
x = [10 16.25 16.25 16.25 16.25 20 22.5 22.6875 24.57 24.57 41.86 47 47 53.8 66.43 77.9 91.201 96.2 97.2]
and
y = [1.28 4.15 3.42 1.53 3.44 4.89 2.91 8.51 9.03 14.91 9.73 8.07 18.56 20.68 42.02 65.72 65.00 83.95 82.17]
A linear regression analysis gives me y = 0.919x - 15.396 and I am trying to calculate the RMSE for this model, for which I need the observed and predicted y values.
What values of x do I use to calculate the predicted y values? Should I use values the original x values? Or do I come up with random x values within the range of the original ones?
Answer: You have to have the $y$-values to which the $x$-values correspond. Otherwise, you cannot calculate the differences between predicted $y$ and true $y$. Thus, randomly generating $x$-values does not help, even though there are no issues when it comes to making predictions for those $x$-values.
With that in mind, it is acceptable to calculate the RMSE on the data used to fit the model, and there are many techniques that hold out some observations from the model-fitting process in order to see what kind of performance the model achieves on data it has not seen before. This is related to the "test" or "validation" performance that is discussed in machine learning circles, and the "cross validation" for which this Stack is named relies on this idea.
Comment: Thanks a lot Dave! That clears it up for me. One final thing if you don't mind, does it matter that I have repeating x values in the original data (when computing y-predicted)?
Comment: @fttoinches My quick answer is that it doesn't matter (ANOVA works this way), but there could be some subtleties, and I believe your question warrants a separate post so it can get an answer, not just a comment.
Comment: Thanks very much Dave, this answers my question fully!


How do classical composers write music?

Question: I am starting to learn about music theory and today it hit me how do classical composers such as Mozart and Beethoven are able to write music for instruments they don't play, such as (for example purpose) timpani or trumpet.
Is it all music theory or just that they where such genius they could intuitive compose for any instrument?
Comment: It should be remembered that Beethoven is a really bad example, because he often wrote parts that were, in fact *not* playable on the instruments at that time. For instance, double basses or horns had to be developed a lot farther until they could actually perform some of his music as written. That wasn't ignorance, just overwhelming artistic determination.
Comment: Many composers these days trained with the orchestration textbooks by Samuel Adler (himself an accomplished composer) or Alfred Blatter (among others); two classic texts on orchestration by famous composers of the past are those by Hector Berlioz and Nicolai Rimsky-Korsakov. An important earlier source on writing for different instruments was the "Syntagma Musicum" of early 17th-century composer Michael Praetorius.
Comment: In his memoirs Berlioz gives the impression that he wrote music in some kind of ecstatic trance of inspiration; but the Symphonie fantastique, for example, features two harp parts, and writing well for harp requires you to know the harp's elaborate pedal mechanism. If you get a sheet of big orchestral staff paper you'll find that even just drawing in all the bar lines takes some time, and then there are all the transpositions for brass and wind instruments in different keys. This takes practice and depends on disciplined study of music by other composers.
Comment: One reason why Beethoven wrote such difficult music for double-bass might be that he reassessed what the instrument could do after a visit from Dragonetti: https://en.wikipedia.org/wiki/Domenico_Dragonetti#Vienna
Answer: Why the past tense? How do classical (or rather, orchestral) composers write music? How does any composer write music for instruments they don't themselves play?
Although a composer doesn't necessarily need to be able to play an instrument to a high standard, they do need to understand the mechanics of the instrument, its limitations and capabilities. This isn't really a matter of genius, just of study and knowledge.
It's certainly not "intuitive" - it's learned.
Composers tend to collaborate with musicians and make changes based on their input. So, for example, they might give a score to a soloist, have them spend some time with it, then come back with feedback - "this part is impossible to play, how about we change it like this."

Nowadays composers can, if they wish, try multi-instrument arrangements out on a sequencer. It's still useful to be able to imagine how an arrangement would sound, and of course in the past that was the only way.
The archetypal composer sits at their piano; a very useful tool for trying out harmonies etc.

It would also make a great deal of sense to write mini-arrangements before expanding them to full orchestral arrangements. For example, score a segment of your symphony for a string quartet, and have a string quartet play it for you, as a prototype for the final work.
Comment: @DrMayhem I don't know why, but I can't believe that they were not gifted. IMHO they were gifted AND worked really hard, and that's why they're who they're.
Comment: @DrMayhem it's been said that genius is 1% inspiration and 99% perspiration...
Comment: There are some studies which refute that - there are some naturally gifted individuals, but it seems that the "big ones" just worked incredibly hard!
Comment: I think the archetypal composer does not sit at a piano. I think an archetypal composer sits at an empty desk with a piece of paper and a pen. There have always been composers that don't play piano.
Comment: Sorry - my wording was wrong. Yes I agree with you - I just separate gifted from genius level. Terminology difference.
Comment: Also recall that composers are generally the ones who actually progress the performer's ability on instruments by demanding performances that are difficult or impossible at the time of composition. Two examples: 1) Stravinsky's Rite of Spring starts with a bassoon solo which was so high it sounded "pinched". Today's bassoonists can play that high more easily, and now it doesn't quite have the sound it used to. 2) When told that a soloist would need six fingers to perform his concerto, Arnold Schoenberg replied, "I can wait."
Comment: I've participated in a few first-playthroughs of pieces which the composer or arranger brought to us for feedback. They range from phrasing/breathing problems;    timpani retuning issues (too much too quickly etc.);  Most moderns scoring software will tell you when you're writing out of an instruments range, so that generally doesn't come up.
Comment: +1 for the good detailed answer, but I would add that the big ones (Bach, Mozart, Beethoven, Bartok, Prokofiev, Tchaikovsky, etc...) are geniuses! That's why they're the "big ones".
Comment: @WheatWilliams maybe we're using different meanings of "archetypal". I think most people asked to draw a picture of a composer at work would have them sat at a piano. You don't need to play piano very well in order to use it as an aid to composition. Of course, musical composition pre-dates the invention of the piano... and manuscript... and desks!
Comment: @victor whether or not these people were geniuses, it's not their knowledge of the range and limitations of the instruments of the orchestra that makes them so. Anyone can learn that bit in a few hours of study. The genius is in what they did with that knowledge.
Comment: Excellent selection of images.
Comment: Anyone can learn the range and limitation of the instruments of the orchestra in a few hours? Please, do tell...
Comment: "[T]hey do need to understand the mechanics of the instrument, its limitations and capabilities." Unless they're Beethoven.
Answer: One point I would make in addition to slim's excellent answer is that theory is more to explain composition, not dictate it. In other words, talented composers write the music they do because they are translating what they 'hear' internally, not because the rules of music theory tell them that this is 'right'.
Although understanding theory is certainly a short-cut to being able to perform this translation, having a masterful understanding of theory will not make a good composer.
Answer: I am a composer and I agree with tpburch.
I am familiar with music theory but never studied it detail. Any good composer with a good ear will do a lot of those things naturally.
As a musician, I can figure out just about anything that makes sound and translate it accordingly.
Music theory or engineering won't teach you how to write good music.  That all comes internally and we are just the translator or the vessel.
I believe many composers to have been gifted 1.  The ability to hear a melody in their head and 2.  Having a great ear to translate into existence.
Reading a book won't teach you to write great music.  Listening to what's inside will.
Answer: Music theory is very key here. By understanding how notes together create consonance and dissonance, it's possible to compose some music without even playing, but to do this effectively most composers trained their ears to hear pitches, or at least to hear intervals( examples hearing a C note or a major third in a song).To do this an understanding of counterpoint helps.Counterpoint serves as the origin for modern harmony, so it can be very helpful. Beethoven, Mozart, and Wagner all studied Counterpoint from the same book, but that book is in latin and very expensive. While I  could list a bunch of information here,Instead I'll give you some sources.
http://en.wikibooks.org/wiki/Music_Theory/Counterpoint/Species_Counterpoint/In_Two_Voices
look up counterpoint on amazon for books, or google 'Fux's counterpoint' (The book used by the said composers has been abbreviated some places)
lastly, there is a youtube channel called 'artofcounterpoint' with some more information.
Answer: I can't play any instrument well, I play the piano but I would never ever perform in front of an audience, not even my own family, nor do I know much about music theory (I'm an autodidact), but I constantly hear music going on in my head and have been composing for many different instruments since the age of six. Some kind of schizophrenia, I guess, because I'm definitely crazy in some way. Maybe it was the same for Mozart or Beethoven, because I can tell that those melodies aren't the result of some fragmentised trial and error-improvisation process; there are continuous musical ideas behind their works. When I was eleven I started to work together with a producer to record some of my songs (I sing), and I've been using GarageBand and various notation programs on my iPad the last few years so that I could compose music wherever I am (I have zero patience, when I have an idea it will be gone if I don't write it down immediately, and then I get bored with it). Of course there needs to be immense amounts of skills and knowledge when it comes to creating great pieces of music, but I see it merely as the means to get the ideas out of one's head, and to get those ideas in the first place musical intuition is required.
Answer: Anyone can compose classical music the difference is what becomes a master piece and what not. There are plenty of boring/mediocre 'classical' composers & music  even though the composers/critics may think it's not, yet when you ask someone who is the best composer the same names usually come out. Why? This is because they knew much about music in general including how to write it, how each instrument sounds like, keys & theory, etc... then you add a whole life time of experience and feeling it! and boom! you come out with a decent piece of music...
Think if you knew how to play guitar (or another instrument)  you could come up with a small piece for 2 guitars or 4 guitars. If you are comfy in how they sound and each piece you could almost 'imagine' how 2 guitars would sound together although, many old composers had people that would come over (pupils even) that would play a piece just for a demo run. most composers like Mozart whom have a great imagination (which is one of the primordial keys) would write songs in piano or just writing the notes down, closing their eyes and 'hear' everything.
For the most part, the longest time in writing music for gifted composers is writing down what they already heard in their heads and its hard to do but not impossible. Think of a song you really like and close your eyes and attempt to hear it. Can you hear all of it or most? Well, same thing. Classical composers are just extraordinaire especially from centuries back because of the technology they had to work with and also because some symphonies have dozens of different instrument in different keys and voices!
It is rather insane when you think about it, but obviously doable. Also, music was a career. Hence you studied and worked your booty off daily and with so many musicians, you really had to be great in order to make it. Even the great ones struggled constantly, but they had music within their head constantly. Together with practice and theory and the drive to compose something great, you will hear symphonies. You can also build from templates in your head.
Example:

violin plays the key A (whole note), 4 bars:   A......A.......A......./etc
now a couple trumpets play quarter notes in C: C-C-C-C,C-C-C-C,C-C-C-C/etc
now bring a viola and play E in half notes:    E...E...E...E...E...E../etc

That probably sounds good enough and many would be able to 'hear' that in their heads. Now multiply that by a 100 if you are a decent musician and by 1000 if you were Mozart :D

How do classical composers write music?


Is it possible to back up and then restore a Windows volume partition?

Question: I installed Windows 7 on a MacBook using Boot Camp.
Using Boot Camp, I resized the MacOS partition to 20 GB and let the Windows partition consume the rest of the space - 128 GB. (Unfortunately this was the only option available with Boot Camp.)
Now I want to reduce the Windows partition to 40 GB and install Ubuntu on the remainder of the hard drive.
In order to do this, the first step is to resize the Windows partition.
This is the tricky bit.
On booting into Ubuntu Live and running gParted the entire partition comes up as 'Unknown'. I'm sure I formatted it as NTFS when installing Windows, but gParted can't recognize it as such, thus I can't resize it.
I did some research and it looks like the partition might be a 'Logical Volume partition', which is why it comes up as 'Unknown' and why I can't resize it.
So, seeing as I can't resize it, I guess the next best thing is to back it up, create a new partition and restore it.
(I've already installed quite a bit of software on it, so restoring a backup would be much quicker than installing everything all over again.)
Is it possible to do this?
Answer: I think I may have stumbled on the solution.
Under Control Panel -> System and Security -> Backup and Restore, there's an option on the left called 'Create a system repair disk'.
I've run this tool and backed everything up to a backup drive.
When I look on the drive, it seems to have created a VHD file as big as the amount of data I have stored.
I think this should work OK if I re-install a new copy of Windows.
Answer: Take a look into the native OS X diskutil tool:
Disk Utility Tool
Utility to manage local disks and volumes
Most options require root access to the device
Usage:  diskutil [quiet] < verb> < options>, where < verb> is as follows:
You can re-size and modify the partitions.  Backups are good! ;-)


Unable to find out how a content type node is getting themed

Question: I have a drupal 7 installation with a paid template which I am trying to tweak. The template has a demo installation, which has a content-type named 'Team'.
So I created a bunch of content with type as Team. Now if I create a Basic Page content and in the URL Alias if I give 'content/team', then it shows a grid view of all the team content I created (each team members photo, name & designation with a read more button).
There is a node--view--team.tpl file available in the codebase.
My problem starts when I try to rename the content-type called Team to 'Students(machine name was also changed tostudents). After renaming I renamed the tpl file tonode--view--students.tpl`. In the URL alias, if I give any url other than 'content/team', all I get is an empty page. If I change the URL alias to 'content/team' - everything works!!
This is driving me mad, I know I cannot get a complete answer since I am tweaking a custom theme, but any pointers would be greatly appreciated!
Answer: I have run into this before; it's the result of some bad practices commonly used by the commercial Wordpress—ehem, wait, I mean, Drupal—themers.
The culprit code is probably in a function in template.php or similar. Try searching the entire theme codebase for "team" - if you are on a Unix system you can use the grep command like this
grep -r "team" /path/to/theme

This might help you find the dirty function.


Set a default value to Class property in CoffeScript

Question: I try to set a default value for a given class property.
class MyClass
    name: (name = 'value') ->

The code above doesn't return value. It returns the whole function.
a = new MyClass
a.name
> function (name) {
if (name == null) name = 'value';
}

If I set a value to it then it works:
a = new MyClass
a.name = 'something'
a.name
> 'something'

I'm wondering what would be the proper way to set a default value for a Class property in CoffeScript.
Answer: This:
class MyClass
    name: (name = 'value') ->

simply defines name as a method which takes one parameter, also called name, and the default value for that parameter is 'value'. So, if we add a body and execute the method:
class MyClass
    name: (name = 'value') ->
        console.log(name)
new MyClass().name()
new MyClass().name('pancakes')

You'll see 'value' and 'pancakes' in the console. Here's a demo, open your console to see what happens.
If you want instances of MyClass to have a name property whose default value is 'value' then you want to say this:
class MyClass
    constructor: (@name = 'value')
console.log(new MyClass().name)
console.log(new MyClass('pancakes').name)

That will also give you 'value' and 'pancakes' in the console.
Answer: Why not a default value in the constructor?
class MyClass
  constructor: (@name = 'default') ->

If you want to set a property on the actual MyClass function you could do:
class MyClass
  @Name = 'value'

but I suspect that isn't what you meant.


Check, anywhere during a session, if a logged in user has previously logged in

Question: There are a number of properties on the global $user object
https://api.drupal.org/api/drupal/developer%21globals.php/global/user/7
But I can't figure out how to see if a logged in user has ever previously logged in, or if this is his/her first session. When logged in, the $user->access, $user->login, $user->timestamp values all seem to point of the current session.
I can set a cookie and check for that cookie myself. But I suspect I'm just missing something Drupal already has ?
Comment: $user->access should work for you. http://drupal.stackexchange.com/questions/34397/in-hook-user-login-is-there-a-way-to-know-if-this-is-the-first-time-the-user-has
Comment: good find @arpitr this question could qualify as a duplicate of 34397
Comment: $user->access seems set to the current login here, not the previous. perhaps that's not true on hook_user_login, but it seems to be so in subsequent requests ?
Comment: in the subsequent requests it will set to timestamp when accessed, but not will be 0
Comment: exactly. so its not a duplicate of 34397
Answer: A cookie would work. Another way is to add a field to the user entity that you can check that field first to see if it's empty, and then modify it with a Rule, triggered by the log in action


Translatable image field gets replaced when adding content

Question: I have added an image field with Translatable Content enabled. My content type has enabled translations too. But when I add an image in the translation, the english contents field get replaced with the newly added translated image. (English is my base language, and I have Japanese and Chinese as translations). This happens vise versa too. What could be the issue?
Answer: By default only the image alt and title are translatable and the file itself isn't. By the default the file is always the same in all languages. You can simply make the file to be translatable as well under https://example.com/admin/config/regional/content-language.

Note: After you've done this, all your existing translations will need to have the file re-uploaded (or a new file uploaded), as the default only gets added once when translating content through the UI.

Taken the above Hero image field this can be done manually be editing field.field.node.page.field_hero_image.yml (which translates to field.field.ENTITY_TYPE.BUNDLE.FIELD_NAME.yml):
Before file checked:
third_party_settings:
  content_translation:
    translation_sync:
      alt: alt
      title: title
      file: '0'

After file checked (alt and title are mandatory if file is checked, that's why they have '0' now):
third_party_settings:
  content_translation:
    translation_sync:
      file: file
      alt: '0'
      title: '0'


Whats the difference between a series and sequence?

Question: I was looking at a question earlier that involved sequences and found out that the sequence converged to 0 but the series diverged to infinity. How is that possible? for example the sequence was $a_n$ $=$ $\frac{1}{x_n}$
The question was here: Convergence of $x_n=f\left(\frac{1}{n}\right), n\geq 1$
Comment: I do not understand. The referenced question did not mention series. Do you mean how can you have $\sum a_n=\infty$ even though $\lim_{n\to\infty}a_n=0$? If so, the answer is yes, eg $a_n=\frac{1}{n}$.
Answer: A sequence is an infinite list of numbers:
$$a_1,a_2,a_3,\ldots$$
while a series is the formal expression you get when you insert "plus" symbols:
$$a_1+a_2+a_3+\ldots$$
Loosely stated, the sequence converges iff the numbers in the list approaches some limit number $a$. And the series converges iff some number $s$ can be said to be the sum of the series.
If the series converges to some sum $s$, it is not hard to show that the corresponding sequence converges to $a=0$. However, the converse is not true; if the sequence converges to $a=0$, the series obtained by inserting plusses may not converge. In a sense this happens when the terms $a_n$ tend to zero too slowly.
Answer: A series is in some sense a type of sequence. However, it is a sequence of partial sums.
For example, if we take some sequence $\{a_n\}_{n\geq 1}$, then we can in turn retrieve a series from this sequence by considering the following partial sums:
$S_N=a_1+...+a_n=\sum_{n=1}^{N}a_n$
Then if we consider the following sequence: $\{S_N\}_{n \geq 1}$ We have actually defined a series!
$S_1=a_1$
$S_2=a_1+a_2$
and so on.
Thus, the difference is the following:
Consider the sequence $\{a_n\}_{n \geq 1}$ defined by $a_n=\frac{1}{n}$.
It is intuitively clear (and if not, use the Archimedean property) that $\lim_{n \to \infty} \frac{1}{n}=0$.
Now, we can consider the sequence of partial sums:
Let $\{S_n\}_{n \geq 1}$ be defined by $S_n=1+\frac{1}{2}+...+\frac{1}{n}$
Then $$\lim_{n \to \infty} S_n=\lim_{n \to \infty} \sum_{k=1}^{n} \frac{1}{k}=\sum_{k=1}^{\infty}\frac{1}{n}$$
Which is called the harmonic series, and it diverges.
We can show this by either the integral test, or just note:
$\begin{align} &1+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}+\frac{1}{5}+\frac{1}{6}+\frac{1}{7}+\frac{1}{8}+...\\
>&1+\frac{1}{2}+\frac{1}{4}+\frac{1}{4}+\frac{1}{8}+\frac{1}{8}+\frac{1}{8}+\frac{1}{8}+...\\
=&1+\frac{1}{2}+\frac{1}{2}+\frac{1}{2}+...
\end{align}$
Which very clearly diverges.
As an aside, it should be very clear that $\{S_n\}$ will not converge at all if $\{a_n\}$ does not, but the converse is not true.
If you want an example where they both converge, just take $\{a_n\}$ to be defined by $a_n=\frac{1}{2^n}$. Then you can consider the sequence of partial sums for $a_n$ (and hence, define a series.)
Then $\{a_n\} \to 0$ as $n \to \infty$. Yet we also have that
$$\lim_{n \to \infty} S_n=\lim_{n \to \infty} \sum_{k=1}^{n}\frac{1}{2^k}=\sum_{k=1}^{\infty}\frac{1}{2^k}=\frac{1/2}{1-1/2}=1$$
To see a derivation of the penultimate equality, you can look further into what are called geometric series
Answer:
An essential difference is that

a sequence has  one specific  meaning and
a series has two  different specific meanings.

For convenience only we look at real-valued sequences and series.

Sequences: A sequence of real numbers
  \begin{align*}
\left(a_n\right)_{n\geq 0}=(a_0,a_1,a_2,\ldots)
\end{align*}
is a function from $\mathbb{N}$ to $\mathbb{R}$. The  index  set  $\mathbb{N}$ is the  domain of the function and    the real   numbers $\mathbb{R}$  is   the codomain.

Now let's have a look at series. We have to clearly state the meaning(s) of the symbol
\begin{align*}
  \sum_{n=0}^{\infty}a_n\tag{1}
  \end{align*}
with $a_n$ being real numbers.

Series (as sequences): Infinite series are sequences of partial sums
When looking at a sequence $(a_0,a_{1},a_{2},\ldots)=(a_n)_{n\geq 0}$
  we consider
  \begin{align*}
  (a_0,a_{0}+a_{1},a_{0}+a_{1}+a_{2},\ldots) = \left(\sum_{n=0}^{N}a_n\right)_{N\geq 0}
  \end{align*}
  and define the infinite series (1) as the sequence of partial sums
  \begin{align*}
    \sum_{n=0}^{\infty}a_n:= \left(\sum_{n=0}^{N}a_n\right)_{N\geq 0}\tag{2}
  \end{align*}

So, the LHS of (2) is just a new and very convenient representation for the sequence of partial sums
\begin{align*}
  \left(s_N\right)_{N\geq 0}, \qquad s_N=\sum_{n=0}^{N}a_n\tag{3}
  \end{align*}
The symbol $\sum_{n=0}^{\infty}a_n$ has also a second meaning, namely

Series (as values): Infinite series are the limits of the sequences of partial sums
An infinite series $\sum_{n=0}^{\infty}a_n$ is said to be convergent, definitely divergent or indefinitely divergent according as the sequence of its partial sums shows the behaviour indicated by those names.
If, in the case of convergence, the sequence of partial sums, $s_N\rightarrow s$, then we say that $s$ is the value or the sum of the convergent infinite series and we write for brevity
\begin{align*}
  \sum_{n=0}^{\infty}a_n:=\lim_{N\rightarrow\infty}s_N=s
  \end{align*}
  so that $\sum_{n=0}^{\infty}a_n$ denotes not only the sequence $(s_N)_{N\geq 0}$ but also the limit $s$, provided this limit exists.
Answer: A sequence of real numbers is a delineation; more specifically, it is a function from the positive integers into $\mathbb{R}$; e.g., $\lbrace a_{n} \rbrace_{n=1}^{\infty} = a_{1}, a_{2}, \ldots $, where the $a_{i}$ are real numbers.
A series is a summation of a particular sequence.


Additional Uncaught Exception?

Question: I updated some modules, and the site was working fine afterward; then, I made some changes to my .info file, uploaded, and suddenly I'm getting this error.

Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column "base.access_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).
Additional
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column "base.access_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).

I do have a database backup that was made before updating the modules.
The error cites entity, but nothing has changed there since Drupal was installed.
Answer: If you updated the modules manually, rather than using the Drupal UI system then you must run example.com/update.php on the URL.  It is likely that one of the modules you updated made changes to the database table system.  If you do not run update.php, then the modules may not have made the necessary table structure changes that match the code.
Answer: Entity API is constantly evolving and still has backwards-incompatible changes with new releases.  Furthermore, the latest stable release is pretty old (5 months ago).
There's a good chance some of the modules you updated rely on an updated version of Entity API.
Try updating Entity API to the dev version and running update.php.
Comment: Thanks, while this issue was resolved after running update.php, updating entity sounds like a good idea anyway?
Comment: If it's working you shouldn't touch it! :)

Additional Uncaught Exception?


iDRAC9: The disk ID returned by "get storage.physicalDisk" cannot be recognized for boot sequence

Question: I'm using iDRAC9 (v5.10.10.00) on PowerEdge R750.
get storage.physicalDisk shows it has a disk AHCI.SL.6-1:
racadm>> get storage.physicalDisk
Storage.physicalDisk.1 [Key=Disk.Bay.0:Enclosure.Internal.0-1#PhysicalDisk]
Storage.physicalDisk.2 [Key=Disk.Bay.1:Enclosure.Internal.0-1#PhysicalDisk]
Storage.physicalDisk.3 [Key=Disk.Direct.0-0:AHCI.SL.6-1#PhysicalDisk]

But AHCI.SL.6-1 cannot be recognized when setting UefiBootSeq:
racadm>> set BIOS.UefiBootSettings.UefiBootSeq AHCI.SL.6-1
ERROR: BOOT016: Input source argument value for the boot device is incorrect or
        not found among the boot devices on the system.

Instead I must use AHCI.SL.6-2:
racadm>> set BIOS.UefiBootSettings.UefiBootSeq AHCI.SL.6-2
[Key=BIOS.Setup.1-1#UefiBootSettings]
RAC1017: Successfully modified the object value and the change is in
       pending state.
       To apply modified value, create a configuration job and reboot
       the system. To create the commit and reboot jobs, use "jobqueue"
       command. For more information about the "jobqueue" command, see RACADM
       help.

So how can I get the "correct" disk ID AHCI.SL.6-2 with racadm commands?
Comment: Just tried that out myself on an R7525 and got the same results. I'm guessing that's a BOSS drive you're looking at?
Comment: yes. from idrac web ui it has `BOSS-S2 / AHCI controller in SL 6` on the Storage page.
Comment: I have asked about this internal to Dell. It looks like a bug in how racadm for how this command is handling the BOSS card. Will report back with what I find out.
Answer: See https://www.dell.com/support/kbdoc/en-in/000198504/boot-device-fqdd-name-changed-in-15g-bios-uefi-boot-sequence-after-bios-update
To summarize, they used to use the fully qualified device descriptor (FQDD) to identify a storage controller in the UEFI boot sequence. The problem with that is you could have a regular RAID card that had multiple virtual disks that were bootable. Ex - you could end up with something like this:
racadm>>racadm get BIOS.biosbootsettings.uefibootseq
[Key=BIOS.Setup.1-1#biosbootsettings]
UefiBootSeq=RAID.SL.8-1,RAID.SL.8-1,NIC.PxeDevice.1-1,NIC.HttpDevice.1-1,Floppy.iDRACVirtual.1-1,Optical.iDRACVirtual.1-1,AHCI.Slot.4-2

You have two instances of RAID.SL.8-1 which doesn't work. So what they did is take the FQDD and then specified the bootable disk volume in the sequence starting with 2. I'm not sure why they decided to start at 2 but they did. Subsequently, since your BOSS card is running RAID 1 (I assume) and it has a single bootable virtual disk - you end up getting only AHCI.SL.6-2 as being valid. Since you looked at the physical disks it is returning just the FQDD.
If you do get bios.uefiBootSettings.UefiBootSeq then you will correctly see AHCI.SL.6-2. Ex on my box:
racadm>>get bios.uefiBootSettings.UefiBootSeq
[Key=BIOS.Setup.1-1#uefiBootSettings]
UefiBootSeq=AHCI.SL.7-2,NIC.PxeDevice.1-1


Webform Mail not arriving at gmail address

Question: I'm having problems with the mailing of the Webform Module.
I have an online website where you can fill in a form. The results will be sent to the email-address the user gave in and the user of the site.
When the user fills in an email like firstname.lastname@example.com or email@example.com there are no problems. They receive the results perfectly. But when they use a gmail address like email@example.com they DON'T receive the email. So it never works with a Gmail address.
The user of the site (who normally also receives the results) then gets an error like this:

Subject: Undelivered Mail Returned to Sender

This is the mail system at host myhost.com.

I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

                 The mail system

: host gmail-smtp-in.l.google.com[ip-adres]
    said: 550-5.7.1 [ip-adres      12] Our system has detected that this
    message is 550-5.7.1 likely unsolicited mail. To reduce the amount of spam
    sent to Gmail, 550-5.7.1 this message has been blocked. Please visit
    550-5.7.1 http://support.google.com/mail/bin/answer.py?hl=en&answer=188131
    for 550 5.7.1 more information. 44si1984154eef.10 - gsmtp (in reply to end
    of DATA command)

What could be the problem with this?
Comment: Post the complete bounceback message; there has to be stated at least error code and/or full reason why the message hasn't been delivered.
Comment: Added this to my topic;
Answer: From the link in your bounceback message:
"A message might be blocked if it contains suspicious-looking or spammy text or if the sending IP has had a history of sending unsolicited messages."
Either one of these possibilities might be the issue.  To rule out "suspicious-looking or spammy text" you should look at the emails your webform generates.  Is there any text they have in common that might be triggering gmail's spam rules?  If you send such a message to a gmail address manually, do you get the same bounceback?
The more likely explanation is that the sending IP has had a history of sending unsolicited messages.  This is especially likely if you're running in a shared web hosting environment.  If this is the problem, there's likely little you can do about it, other than asking your host to move your account to a different server.


Returning non-empty row numbers using VBA

Question:
I have a spreadsheet like this, and I would like to have a function that returns the list of row numbers non-empty cells in column B. In this case, it should return "2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 22, 23, 25, 26)
How do I do this in VBA?
Comment: Can you show us what you've tried?  We might be able to help you figure out why it's not working.
Comment: Is the list the end or are you going to use those rows somewhere else to get to the final output?
Answer: Function GetEmptyCount()
    Dim arr(), x&, cell
    With Range("B1:B" & Cells(Rows.Count - 1, "B").End(xlUp).Row)
        For Each cell In .SpecialCells(xlCellTypeBlanks).Cells
            x = x + 1
            ReDim Preserve arr(1 To x)
            arr(x) = cell.Row
        Next
    End With
    GetEmptyCount = arr
End Function

Sub Test()
    Dim x, c
    x = GetEmptyCount()
    For Each c In x: MsgBox c: Next
End Sub

Answer: You can check the length of the cell value something like
IF(Length(Cell) > 0 THEN
      // Include the row
ELSE
      // skip the row

Comment: Thank you very much for your answer. You may be able to format the code even better.
Comment: Looks better now. However, two brackets open and only one closes. Downvote.


Como fazer insert no banco para formulários na mesma página?

Question: Estou testando um form antes de colocar na produção, porque já temos um sistema que insere a movimentação de patrimônio 1 a 1 e estou querendo fazer com que o operador consiga fazer várias ao mesmo tempo, por exemplo, vai mover 5 impressoras pro mesmo lugar que ele não tenha que fazer o processo 5 vezes...

então ele diz quantos produtos vai movimentar e clica em enviar e abre o número de formulários desejado

Minha dúvida é : Como eu faço para que quando ele clique no primeiro botão gravar ele faça o update no banco sem sair da página e se não for pedir muito, aparecer uma mensagem de inserido no 'quadrado' que clicou em gravar porque quem vai operar isso, não tem muita facilidade com computadores. Segue o código.
    <?php

$produtos = $_POST['produtos']

?>

<?php

 for ($i=0; $i < $produtos; $i++) {
   # code...
?>

                    <form>

                            Patrimonio
                            <input name="data[PessoaEmail][0][email_tipo_id]" required="required" id="PessoaEmail0EmailTipoId" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">

                            Teste
                            <input type="text" class="form-control" name="data[PessoaEmail][0][email_tipo_id]" required="required" id="PessoaEmail0EmailTipoId" placeholder="teste">

                      <button type="submit" class="btn btn-success btn-sm">Gravar</button>

                    </form>

<?php } ?>

Comment: Pesquise sobre requisições assíncronas com JavaScript.
Answer: Se seu problema for apenas quando clicar no botão enviar não quer que a pagina recarregue tu pode usar o Javascript o método preventDefault(), mas caso sua dúvida seja outra, tente deixar mais clara para que possamos te ajudar.
Answer: tira os campos de dentro do form e usa ajax para enviar os dados.
quando você tem um button type="submit" dentro de um form, sempre que o button type="submit" for acionado, ele vai atualizar a pagina e enviar os dados dos input dentro daquele form


How to define multiple "yield :something" in the Phoenix layout?

Question: I have a layout with this:
# main_layout.html.eex

    <............>

      <%= render(@view_module, @view_template, assigns) %>

And many child pages. However, in some(!) child pages I want to render html outside of

      <%= render(@view_module, @view_template, assigns) %>

That is, I want to append some additional html into "" and above the "
" tag
The rest of the pages should continue rendering the normal way: without these additional htmls parts.
How can I do this?
Answer: One might render as many templates as they needed.

  <%= render(@view_module, @view_template, assigns) %>

  <%= render(@footer_module, @footer_template, assigns) %>

The conditional rendering might be done either from the topmost template:

  <%= if ... do %>
    <%= render(@footer_module, @footer_template, assigns) %>
  <% end %>

Or from the FooterModule itself, rendering nothing if there is no need to.

In case the information you are to add to the footer differs from child to child, use Phoenix.View.render_existing/3 and simply do not provide templates where they are not needed: phoenix will silently ignore this directive for non-existing templates.
Comment: What's `footer_module`? How would I render it in my child template?
Comment: `footer_module` is your module providing a functionality you want to add to the footer. It's rendered from the main template as shown above.
Comment: @Ojrojako when mudasobwa says FooterModule he's only using that as an example of what you're trying to render into the layout. To expand on that example each template e.g. `app/lib/app_web/templates/page/index.html.eex` eventually gets converted into functions in their corresponding view e.g. `/app/lib/app_web/views/page_view.ex`. A common practice is to have a shared folder and SharedView for shared templates e.g. `<%= render AppWeb.SharedView, "_foot.html", conn: @conn %>`. Depending on where or when you need that template rendered you could use `if`, `cond`, `case`, `unless` to display it.


How do you make a submit button redirect to another page after the user has inputted the correct username and password?

Question: When you click the login button after you enter the correct username and password, it is supposed to redirect you. I posted the same question yesterday, but now I have slightly changed the code like some of the answers said, but it still hasn't worked. Please help.

<title>Login: MessengerX</title>
<link rel="stylesheet" type="text/css" href="C:\Users\Tania\Documents\Website\style.css">
<meta charset="UTF-8">
<meta name="description" content="HTML website called MessengerX. Send messages to anyone who has logged in.">
<meta name="author" content="Joshua Hurley">
<meta name="keywords" content="HTML, MessengerX, Joshua Hurley, Website, Supremefilms">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css"/>

Login: MessengerX

<form id="form_id" method="post" name="myform">
User Name :
<input type="text" name="username" id="username"/>
Password :
<input type="password" name="password" id="password"/>
 <button type="submit" value="Login" id="submit" onclick="validate()"/>
</form>
Submit

Comment: User validation in javascript? Without any api? Seriously? It's so easy to break that you might not do any validation at all, it's almost the same
Comment: Does this answer your question? [How do I redirect to another webpage?](https://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage)
Comment: Can you be more specific like what is not working? Redirection ? login code? what's the error? any alert is triggered? if yes which one?
Comment: The form submission already redirects (to the same page), you can't redirect from JS when there's a pending form submission.
Answer: you have to prevent the default behavior of Submitting, and once you do that- you can redirect.
    $("form").submit(function(event){ //edited
        event.preventDefault()
..your code here
    });


Remove/Hide the block if the View is empty?

Question: Is there any API to know if the block is empty? Basically what I'm trying to do is to hide/unset the block inside template_preprocess_page.
Here is my currrent code:
 if ($variables['page']['rail_full']) {
    foreach ($variables['page']['rail_full'] as $keys => $blocks) {
      if (isset($blocks['content']['#views_contextual_links_info'])) {
        $name = (isset($blocks['content']['#views_contextual_links_info']['views_ui'])) ? $blocks['content']['#views_contextual_links_info']['views_ui']['view']->name : '';
        $display_id = explode('-', $blocks['#block']->delta);
        $block = views_get_view_result($name, $display_id[1]);
        if (empty($block)) {
          unset($variables['page']['rail_full'][$keys]);
        }
      }
    }
  }

But the above code always return a count of 1 when I print $block.
The below works fine but not a good solution. I want it to be dynamic in all block as possible.
if (!isset($variables['node']->field_author_favorite_links['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_2']);
}

if (!isset($variables['node']->field_article_column['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_3']);
}

Comment: could you let me know how you have created the view?
Comment: there is a setting in views to hide block if view empty, isn't it?
Answer: I had the same behavior with "empty" fields. Unless you don't hide the fields themselves, the design/ markup still renders.
Solution for me was to filter for fields being "NOT NULL".
(Maybe it depends on the "fences"-module i have installed, too. Not sure, because not tested ...)
Comment: Wow, that did the trick for me! Thank you for sharing :-)
Answer: By default, if a view with a Block display returns no results, it won't be rendered. That is unless you've set some "No Results Behavior" which the view will display when empty. So check to make sure it has nothing set.

So coding shouldn't be necessary unless you're trying to do something more custom. If so, you may want to clarify what it is you're trying to accomplish.
Comment: If you're creating a block with a view, then the *block* will still be rendered in the markup, however the contents will be empty.
Comment: @apower If you are creating a block view that is simple then yes you are correct, but if you have one that has a contextual filter and the filter validates correctly, but there are no items in the result set, the block wrapper does still load.
Comment: Actually **that's not true**. I created a test view with a block display that purposefully returned no results and it wasn't rendered in the region I assigned it to, not even the title. As soon as I modified the block to show results it rendered.
Comment: @Chapabu's comments are absolutely correct. I am also running in the same situation


Eclipse package does not exist

Question: I have a problem with imports in Eclipse. I have following exceptions:
[ERROR] .../ctc/wstx/io/ReaderSource.java:[9,24] package com.ctc.wstx.api does not exist
[ERROR] .../ctc/wstx/io/ReaderSource.java:[10,24] package com.ctc.wstx.exc does not exist

I use Maven, and I think I have the correct dependencies. In Maven the depedencies exist in the correct jar:
woodstox-core-asl-4.1.1.jar
  - com.ctc.wstx.api
     - CommonConfig.class
     - EmptyElementHandler.class
     - InvalidCharHandler.class
     - ReaderConfig.class
     - ValidatorConfig.class
     - WriterConfig.class
     - WstxInputProperties.class
     - WstxOutputProperties.class

com.ctc.wstx.exc

also exists. If I remove imports I can use Eclipse (ctrl + 1) to import, so Eclipse sees that jar. Why do I have this problem? And how I can resolve this?
Comment: Which Maven scope has the `woodstox-core-asl-4.1.1.jar` (please show your `pom.xml`)? What is exactly in `.../ctc/wstx/io/ReaderSource.java` line 9 and 10?
Comment: Okay, it works... woodstox was added by cxf-api. If I added separately woodstox (created separately depedency) it started to work. Maybe someone know why?
Answer: Check the path of your package  and  output file,I have met this problem past, it probably be resolved in the menu of configure buid path

Eclipse package does not exist


ApiPaltform - recover soft deleted element

Question: I'm using ApiPlatform and Symfony5
I've implemented softdelete on an entity User
This entity is softdeleted properly, I still want to displayed the deleted users for some roles, so I'm trying a DoctrineExtension to modify the request dynamically.
Here is my UserExtension.php:
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []): void
    {
        $this->addWhere($queryBuilder, $resourceClass);
    }

    private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
    {

        if (User::class == $resourceClass &&
            $this->security->isGranted(GenericRoles::ROLE_ADMIN)
        ) {
            $rootAlias = $queryBuilder->getRootAliases()[0];

            $queryBuilder->andWhere("$rootAlias.deletedAt > '2019-01-01'");
        }
    }

I verified that I enter in the if condition.
But I still get a 404 on the item I'm trying to recover (which is still in base)
The same request entered in command line in the db return me the item I want to recover.
I've also tried to disable softdelete as follow :
$this->entityManager->getFilters()->disable('softdeleteable');
But doing so disable it for the whole application, and I can't re enable it in the UserExtension
Does anyone know what I'm doing wrong ? Or if there is another way to recover soft deleted items
Or if you got more docs on the subject I'd be gratefull cause I'm runnning out of options
Thanks!
Answer: Yeah, it's not straightforward, as your query executes outside of the extension. I would probably try to disable soft deletable filter for User entity only in case authenticated user has Admin role. It still would be disabled after the execution of the query, but it shouldn't cause too many side effects, as admin user should be able to see deleted User entities. Something like this.
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []): void
{
    $this->addWhere($queryBuilder, $resourceClass);
}

private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
{
    if (User::class === $resourceClass &&
        $this->security->isGranted(GenericRoles::ROLE_ADMIN)
    ) {
        $filter = $this->entityManager->getFilters()->enable('softdeleteable');
        $filter->disableForEntity(User::class);

        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder->andWhere("$rootAlias.deletedAt > '2019-01-01'");
    }
}

Comment: Thanks for you comment! I havn't tried this solution, but through a `DataProvider` I can `disable` the filter, query the entity I want to query and then `enable` the filter again, while returning the object of interest.
Answer: This solution worked for me, I hope it'll work for whoever fall onto this :
Through a DataProvider it's possbile to disable the filter, query the soft deleted object you want to query and stock it in a variable, then enable the filter again and return your object.
I don't know if using the a DataProvider this way is a good practice, but it has not created side effect on my application.
Here is an example:
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
    {
        if ($this->security->isGranted(GenericRoles::ROLE_ADMIN))
        ) {
            $this->entityManager->getFilters()->disable('softdeleteable');
        }

        $softDeletedObject = $this->itemDataProvider->getItem($resourceClass, $id, $operationName, $context);

        $this->entityManager->getFilters()->enable('softdeleteable');

        return $softDeletedObject;
    }


Erro: handle não declarado no escopo

Question: <code>#include <iostream>
#include<conio.h>
#include<dos.h>
#include<windows.h>
#include<time.h>

#define SCREEN_WIDTH 90
#define SCREEN_HEIGHT 26
#define WIN_WIDTH 70

using namespace std;

HANDLE console=getStdHandle(STD_OUTPUT_HANDLE);
COORD cursorPosition;

int enemyY[3];
int enemyX[3];
int enemyFlag[3];
char car [4][4]={' ','±','±',' ',
                '±','±','±','±',
                ' ','±','±',' ',
                '±','±','±','±'};

int carPos=WIM+WIDTH/2;
int score=0;

void gotoxy(int x,int  y){
    if(size==0)
    size=20;

    CONSOLE_CURSOR_INFO lpCursor;
    lpCursor.bVisible=visible;
    lpCursor.dwSize=size;
    setConsoleCursorInfo(console,&lpCursor)
}

void drawBorder(){
    for(int i=0,i<SCREEN_HEIGHT;I++){
        for(int j=0;j<17,j++){
            gotoxy(0+j,i);cout<<"+-";
            gotoxy(WIN_WIDTH-J,I);COUT<<"+-";
        }
    }
    for(int i=0;i<SCREEN_HEIGHT;i++){
        gotoxy(SCREEN_WIDTH,i);cout<<"+-";
    }
}
void genEnemy(int ind){
    enemyX[ind]=17+rand()%(33);
    }
    void drawEnemy(int ind){
    if(enemyFlag[ind]==true){

        gotoxy(enemyX[ind],enemyY[ind]);   cout<<"****";
        gotoxy(enemyX[ind],enemyY[ind]+1);  cout<<"**";
        gotoxy(enemyX[ind],enemyY[ind]+2); cout<<"****";
        gotoxy(enemyX[ind],enemyY[ind]+3); cout<<"**";
    }
}
    void eraseEnemy(int ind){
        if(enemyFlag[ind]==true){

        gotoxy(enemyX[ind],enemyY[ind]);   cout<<"  ";
        gotoxy(enemyX[ind],enemyY[ind]+1);  cout<<"  ";
        gotoxy(enemyX[ind],enemyY[ind]+2); cout<<"   ";
        gotoxy(enemyX[ind],enemyY[ind]+3); cout<<"   ";
    }
}
void resetEnemy(int ind){
        eraseEnemy(ind);
        enemyY[ind]=1;
        genEnemy(ind);
}
void drawCar(){
    for(int i=0,i<4;i++){
        for(int j=0;j<4;j++){
            gotoxy(j+carPos,i+22);cout<<car[i][j];
        }
    }
}
void eraseCar(){
    for(int i=0;i<4,i++){
        for(int j=0;j<4,j++){
            gotoxi(j+carPos,i+22);cout<<" ";
        }
    }
}
int collision(){
    if(enemyY[0]+4>=23){
        if(enemyX[0]+4-carPos>=0&& enemyX[0]+4-carPos<9){
            return 1;
        }
    }
    return 0;
}
void gameover(){
    system("cls");
    cout<<endl;
    cout<<"t\t--------------------"<<endl;
    cout<<"t\t--------game over-------"<<endl;
    cout<<"t\t--------------------"<<endl<<endl;
    cout<<"t\tPress any key to go back to menu."<<endl;
    getch();
}
void updateScore(){
    gotoxi(WIN_WIDTH +7,5);cout<<"score:"<<score<<endl;
}
void instructions() {

    system("cls");
    cout<<"instructions";
    cout<<"\n--------------------------";
    cout<<"\n avoid cars by moving left or right.";
    cout<<"\n--Press 'a' to move left------------";
    cout<<"\n--Press 'd' to move right----------------";
    cout<<"\n--Press 'q'-to exit------------------";
    cout<<"\n--press any key to go back to menu.-------------------";
    cout<<"\n--------------------------";
    getch();

}
void play(){
    carPos=-1+WIN_WIDTH/2;
    score=0;
    enemyFlag[o]=1;
    enemyFlag[1]=0;
    enemyY[0]=enemyY[1]=1;

    system("cls");
    drawBorder();
    updateScore();
    genEnemy(0);
    genEnemy(1);

    gotoxy(WIN_WIDTH +7 ,2);cout<<"car game";
    gotoxy(WIN_WIDTH +6,4);cout<<"------";
    gotoxy(WIN_WIDTH +6,6);cout<<"------";
    gotoxy(WIN_WIDTH +7 ,12);cout<<"control";
    gotoxy(WIN_WIDTH +7,13);cout<<"------";
    gotoxy(WIN_WIDTH +2 ,14);cout<<"A key -left";
    gotoxy(WIN_WIDTH +2 ,15);cout<<"D key -right";

        gotoxy(18,5);cout<<"Press p key to start";
        getch();
        gotoxy(18,5);cout<<"           ";

        while(1){
            if(kbhit()){
                charch=getch();
                if(ch=='a'||ch=='A'){
                    if(arPos>18)
                    carPos-=4;
                }
                if(ch=='d'||ch=='D'){
                    if(carPos<50)
                    carPos+=4;
                }
                if (ch==27){
                    break;
                }
            }
            drawCar();
            drawEnemy(0);
            drawenemy(1);
            if(collision()==1){
                gameover();
                return;
            }
            sleep(50);
            eraseCar();
            eraseEnemy(0);
            eraseEnemy(1);

            if(enemyY[0]==10)
              if(ememyFlag[1]==0)
              enemyFlag[1]=1;

            if(enemyFlag[0]==1)
            enemyY[0] +=1;

            if(enemyFlag[1]==1)
            enemyY[1]+=1;

            if(enemyY[0]>SCREEN_HEIGTH-4){
                resetEnemy(0);
                score++;
                updateScore();

            }
            if (enemyY[1]>SCREEN_HEIGTH-4){
                resetEnemy(1);
                score++;
                updateScore();
            }
        }

}
intmain(){

    setCursor(0,0);
    srand((unsigned)time(NULL));

    DO{
        system("cls");
        gotoxy(10,5 ); cout<<"------------------  ";
        gotoxy(10,6 ); cout<<"|   CAR GAME      | ";
        gotoxy(10,7); cout<<"  ------------------ ";
        gotoxy(10,9 ); cout<<"1.START GAME         ";
        gotoxy(10,10 ); cout<<"2.INSTRUCTIONS         ";
        gotoxy(10,11 ); cout<<" 3,QUIT        ";
        gotoxy(10,13 ); cout<<" SELECT OPTIONS ";

        if(op=='1')play();
        else if(op=='2')instructions();
        else if(op=='3')exit(0);

    }while(1);
    return 0;
}

    }
}
</code>
Comment: Esta pergunta não tem muita informação. Quando acontece o erro? Compilação? Qual é a mensagem exata? Você já tentou criar uma versão mínima do programa (cortando código até que o programa ficar o mais curto possível enquanto ainda mostrando o erro)?
Comment: `GetStdHandle` é com letra maiúscula.
Answer: na Linguagem c / c++ , existem palavras reservadas , e não podem ser usadas pelo usuário em um programa , e "size " é uma delas , e muitos comandos são com letras minúsculas , e precisa usar a syntaxe correta também , por exemplo o "for" precisa de ponto e vírgula , e não vírgula simples , e no final tem fecha_chaves sobrando , e o código corrigido poderia ser assim  :
<code>#define  _WIN32_WINNT 0x0600
#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <conio.h>
#include <dos.h>
#include <windows.h>
#include <time.h>
#define  _h GetStdHandle(STD_OUTPUT_HANDLE)
#define  SCREEN_WIDTH 90
#define  SCREEN_HEIGHT 26
#define  WIN_WIDTH 70
#define  getch() _getch()
#define  kbhit() _kbhit()
using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD cursorPosition;

int  sizen = 0;  // size eh uma palavra reservada da linguagem C++
int  enemyY[3];
int  enemyX[3];
int  enemyFlag[3];
char car[4][8] =
{
    ' ' ,'±','±',' ' ,
     '±','±','±','±',
    ' ' ,'±','±',' ' ,
    '±','±','±','±'
};

int carPos = WIN_WIDTH / 2;
int score = 0;

void gotoxy(int coluna, int  linha)
{
    if (sizen == 0)
        sizen = 20;
    CONSOLE_CURSOR_INFO lpCursor;
    //lpCursor.bVisible = visible;
    lpCursor.dwSize = sizen;
    SetConsoleCursorInfo(console, &lpCursor); // faltou um ponto_e_virGuLa
    COORD c;
    c.X = coluna;
    c.Y = linha;
    SetConsoleCursorPosition(_h, c);
}
void drawBorder()
{
    for (int i = 0; i < SCREEN_HEIGHT; i++)  // virGulA o lugar de ponto_e_virgula e variavel i eh minuscula
    {
        for (int j = 0; j < 17; j++)   // virGulA no lugar de ponto_e_virgula
        {
            gotoxy(0 + j, i); cout << "+-";
            gotoxy(WIN_WIDTH - j, i); cout << "+-"; // j e i Sao minusculas
        }
    }
    for (int i = 0; i < SCREEN_HEIGHT; i++)
    {
        gotoxy(SCREEN_WIDTH, i); cout << "+-";
    }
}
void genEnemy(int ind)
{
    enemyX[ind] = rand() % 33 + 17;
}
void drawEnemy(int ind)
{
    if (enemyFlag[ind] == true)
    {
        gotoxy(enemyX[ind], enemyY[ind]); cout << "****";
        gotoxy(enemyX[ind], enemyY[ind] + 1); cout << " **";
        gotoxy(enemyX[ind], enemyY[ind] + 2); cout << "****";
        gotoxy(enemyX[ind], enemyY[ind] + 3); cout << " **";
    }
    gotoxy(79, 25);
    //cout << "desenhou" << endl; getch();
}
void eraseEnemy(int ind)
{
    if (enemyFlag[ind] == true)
    {
        gotoxy(enemyX[ind], enemyY[ind]); cout << "    ";
        gotoxy(enemyX[ind], enemyY[ind] + 1); cout << "    ";
        gotoxy(enemyX[ind], enemyY[ind] + 2); cout << "    ";
        gotoxy(enemyX[ind], enemyY[ind] + 3); cout << "    ";
    }
    gotoxy(79, 25);
    //cout << "desmanchou" << endl; getch();
}
void resetEnemy(int ind)
{
   eraseEnemy(ind);
    enemyY[ind] = 1;
    genEnemy(ind);
}
void drawCar()
{
    for (int i = 0; i < 4; i++)  // virGulA no lugar de ponto_e_virgula
    {
        for (int j = 0; j < 4; j++)
        {
            gotoxy(j + carPos, i + 22); cout << car[i][j];
        }
    }
    gotoxy(79, 25);
}
void eraseCar()
{
    for (int i = 0; i < 4; i++)  // virGulA no lugar de ponto_e_virgula
    {
        for (int j = 0; j < 4; j++)   // virGulA no lugar de ponto_e_virgula
        {
            gotoxy(j + carPos, i + 22); cout << " ";
        }
    }
}
int collision()
{
    if (enemyY[0] + 4 >= 23)
    {
        if (enemyX[0] + 4 - carPos >= 0 && enemyX[0] + 4 - carPos < 9)
        {
            return 1;
        }
    }
    return 0;
}
void gameover()
{
    system("cls");
    cout << endl;
    cout << "t\t--------------------" << endl;
    cout << "t\t--------game over-------" << endl;
    cout << "t\t--------------------" << endl << endl;
    cout << "t\tPress any key to go back to menu." << endl;
    getch();
}
void updateScore()
{
    gotoxy(WIN_WIDTH + 7, 5); cout << "score:" << score << endl;
}
void instructions()
{
    system("cls");
    cout << "\n           instructions                    \n\
             \r-------------------------------------------\n\
             \r avoid cars by moving left or right.       \n\
             \r-- Press 'a' to move left -----------------\n\
             \r-- Press 'd' to move right ----------------\n\
             \r-- Press 'q'-to exit ----------------------\n\
             \r-- press any key to go back to menu . -----\n\
             \r-------------------------------------------";
    getch();
}
void play()
{
    carPos = -1 + WIN_WIDTH / 2;
    score = 0;
    enemyFlag[0] = 1; // VariaveL o no lugar do valor zero
    enemyFlag[1] = 0;
    enemyY[0] = enemyY[1] = 1;
    system("cls");
    drawBorder();
    updateScore();
    genEnemy(0);
    genEnemy(1);
    gotoxy(WIN_WIDTH + 7, 2); cout << "car game";
    gotoxy(WIN_WIDTH + 6, 4); cout << "------";
    gotoxy(WIN_WIDTH + 6, 6); cout << "------";
    gotoxy(WIN_WIDTH + 7, 12); cout << "control";
    gotoxy(WIN_WIDTH + 7, 13); cout << "------";
    gotoxy(WIN_WIDTH + 2, 14); cout << "A key -left";
    gotoxy(WIN_WIDTH + 2, 15); cout << "D key -right";
    gotoxy(18, 5); cout << "Press p key to start";
    getch();
    gotoxy(18, 5); cout << "                    ";
    while (1)
    {
        if (kbhit())
        {
            char ch = getch();  // faltou hum espaço depois do char
            if (ch == 'a' || ch == 'A')
            {
                if (carPos > 18) // faltou a letra c de carPos
                    carPos -= 4;
            }
            if (ch == 'd' || ch == 'D')
            {
                if (carPos < 50)
                    carPos += 4;
            }
            if (ch == 27)
            {
                break;
            }
        }
        drawCar();
        drawEnemy(0);
        drawEnemy(1); // enemy com lera minuscula
        if (collision() == 1)
        {
            gameover();
            return;
        }
        Sleep(150); // funcao eh com inicial maiuscula
        eraseCar();
        eraseEnemy(0);
        eraseEnemy(1);
        if (enemyY[0] == 10)
            if (enemyFlag[1] == 0) // enemyFlag com "m" no lugar de "n"
                enemyFlag[1] = 1;
        if (enemyFlag[0] == 1)
            enemyY[0] += 1;
        if (enemyFlag[1] == 1)
            enemyY[1] += 1;
        if (enemyY[0] > SCREEN_HEIGHT - 4) // HEIGHT com T no lugar errado HEIGTH
        {
            resetEnemy(0);
            score++;
            updateScore();
        }
        if (enemyY[1] > SCREEN_HEIGHT - 4) // HEIGHT com T no lugar errado HEIGTH
        {
            resetEnemy(1);
            score++;
            updateScore();
        }
    }
}
int main()  // faltou um espaco depois do int
{
    //SetCursor(0); // funcao com letra maiuscula
    srand((unsigned)time(NULL));

    do // do é com letra minusculas
    {
        system("cls");
        gotoxy(10, 5); cout << "------------------   ";
        gotoxy(10, 6); cout << "|   CAR GAME      |  ";
        gotoxy(10, 7); cout << " ------------------  ";
        gotoxy(10, 9); cout << "1 . START GAME       ";
        gotoxy(10, 10); cout << "2 . INSTRUCTIONS     ";
        gotoxy(10, 11); cout << "3 . QUIT             ";
        gotoxy(10, 13); cout << "    SELECT OPTIONS   ";
        int op = getch() - 48;
        if (op == 1)
            play();
        else
            if (op == 2)
                instructions();
            else
                if (op == 3)
                {
                    cout << "\n\n\n" << endl;
                    exit(0);
                }
    } while (1);
    return 0;
}
</code>
Comment: `size` não é palavra reservada. Talvez vc tenha confundido com `sizeof`? https://en.cppreference.com/w/c/keyword

Erro: handle não declarado no escopo


Label nonzero neighbour values in 2d array

Question: I have a 2d list consist of 0 and 1 like this
a=[['0', '0', '1', '1', '0', '0', '0', '0', '0', '0'],
   ['0', '0', '1', '0', '0', '1', '0', '0', '0', '1'],
   ['0', '0', '0', '1', '0', '0', '0', '0', '0', '0'],
   ['0', '0', '0', '0', '0', '1', '0', '0', '0', '0'],
   ['0', '1', '1', '1', '0', '0', '0', '0', '0', '0']]

I want to group '1'  that are near each others in every direction and replace them with a group number like this
a=[['0', '0', '1', '1', '0', '0', '0', '0', '0', '0'],
   ['0', '0', '1', '0', '0', '2', '0', '0', '0', '3'],
   ['0', '0', '0', '1', '0', '0', '0', '0', '0', '0'],
   ['0', '0', '0', '0', '0', '4', '0', '0', '0', '0'],
   ['0', '5', '5', '5', '0', '0', '0', '0', '0', '0']]

Is there anyway to do it?
Answer: What you're trying to do is known as connected component labeling, and you have scipy's scipy.ndimage.measurements.label for that:
from scipy import ndimage
import numpy as np

a = np.array(l, dtype=('i1'))
x_components, _ = ndimage.measurements.label(a, np.ones((3, 3)))

array([[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 2, 0, 0, 0, 3],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 4, 0, 0, 0, 0],
       [0, 5, 5, 5, 0, 0, 0, 0, 0, 0]], dtype=int32)


calculating the integral $\int x^{-2} e^{-x^2}dx$

Question: How can I calculate the integral $\int x^{-2} e^{-x^2}dx$.
Is it possible to calculate? I think it is impossible.
Comment: It's impossible to represent the result by means of "elementary" functions, however using partial integration one can deduce a representation involving the [error function](http://en.wikipedia.org/wiki/Error_function) $\mathrm{erf}$, for which there are many rapidly converging approximations.
Comment: Ok AlexR. Thanks. So it is impossible to find an elementary function.
Comment: By the usual notion of elementary function, yes. Only a sequence of elementary functions can be given which converges to the desired function.
Answer: Integrate by parts.  $u=e^{-x^2}$ and $dv=x^{-2}dx$.
$$
\int x^{-2}e^{-x^2}=-x^{-1}e^{-x^2}-2\int e^{-x^2}dx=-x^{-1}e^{-x^2}-\sqrt{\pi}\operatorname{erf}(x)
$$
Comment: @hamed: Gaffney already gave an exact answer in terms of `Erf`.
Comment: erf(x) is the error function. but I have another question. Can we find Exact answer?
Answer: It's somewhat impossible to compute the integrand.  Based on WolframAlpha, you get the following expression:
$$\int x^{-2}e^{-x^{2}}\,dx = -\dfrac{\sqrt{\pi}x\,\mathrm{erf}(x) + e^{-x^2}}{x} + \mbox{C}$$
Comment: I'm not really sure of your first sentence. Nonelementary functions are just as valid as elementary ones.
Answer: Integrating by parts you'll get the general expression
$$
\int x^{-2}e^{-x^2}=-x^{-1}e^{-x^2}-2\int e^{-x^2}dx
$$
but if you want to evaluate the integral over $[-\infty,+\infty]$, by the gaussian integral the result is $-2 \sqrt{\pi}$
Comment: That would be surprising, as the integrand is always positive.  I think the issue is that the integral diverges at zero.
Comment: You're right, it's wrong, but where's the mistake? The use of the error function is essentially I imagine
Comment: Well, suppose I told you that $\int_{-\infty}^\infty x^{-2} = -x^{-1}|_{-\infty}^\infty = 0$.  You can't do this when the thing you're integrating isn't defined everywhere.
Comment: What a mistake! the function isn't defined in $(0,0)$. Forget it!


Is .NET 3.5.1 Supported on Windows Server 2016?

Question: I can't find any documentation regarding this, take a look at..
https://support.microsoft.com/en-us/gp/framework_faq/en-us

.NET Framework 3.5 SP1: Beginning with .NET Framework 3.5 Service Pack
  1 (SP1) the .NET Framework is defined as a component instead of an
  independent product. So, support for .NET Framework 3.5 SP1 is driven
  by the support lifecycle policy of the Windows operating system (i.e.
  when Windows is in the Mainstream Support phase or Extended Support
  phase, so are its components). When a product such as Windows reaches
  the end of support, so do its related components. .NET Framework 3.5
  SP1 is supported on Windows Server 2003 SP2, Windows Vista SP2,
  Windows 7 SP1, Windows Server 2008 SP2, Windows Server 2008 R2 SP1,
  Windows 8.1 Update, Windows Server 2012, Windows Server 2012 R2, and
  Windows 10 according to the end of support date for each operating
  system.

Windows 2016 Server is not listed, but I have a feeling maybe the document isn't updated to reflect the new server OS? I know as I was able to add it as a "Feature" but it wasn't installed as part of the OS.
If anyone has any updated information regarding this, It will be beneficial to me and the community.
Comment: Yes, same as Windows 10.  .NET 3.5/CLR 2.0 will be around and supported for quite a long time.
Answer: Yes, Net Framework 3.5 is working on Windows Server 2016, I have it installed on my Servers. So far, we haven't had any reported issues from our programmers.
Remember, You need to install it as a server feature. (Make sure to Specify an alternate source path during the installation. You need to mount your Windows 2016 Disk and set the path to Drive:\sources\sxs).
Comment: If you don't specify an alternate source, Windows should download the installer via Windows Update. Which requires the prerequisites for installing any server roles that the Windows Update service is enabled. It's doesn't actually require that the update is there, just that the service is enabled.
Comment: FWIW, This is kind of BS, since several Microsft utilities still rely on it.  Right now I'm trying to use the RSKeyMgmt tool for SQL 2016, which requires .NET 3.5.1 which I now need to remount an ISO for.  They ought to have recompiled all of their SQL 2016 (and other) utilities before starting to orphan 3.5.1
Comment: I know this is an old post, but are you actually getting any patches (security or otherwise) for .Net on Server 2016? I'm looking in SCCM and I'm not seeing any listed.
Comment: Yes, I'm using SCCM 2016 to downloading and deploying Security and Critical updates for .Net frameworks on Windows Servers 2016. Make sure to use SCCM 2016 or latest RU version. SCCM 2012 do not support Windows Server 2016.
Answer: Microsoft has updated their FAQ
https://support.microsoft.com/en-us/help/17455/lifecycle-faq-net-framework

.NET Framework 3.5 SP1: Beginning with .NET Framework 3.5 Service Pack
  1 (SP1) the .NET Framework is defined as a component instead of an
  independent product. So, support for .NET Framework 3.5 SP1 is driven
  by the Lifecycle Policy of the Windows operating system (that is, when
  Windows is in the Mainstream Support phase or Extended Support phase,
  so are its components). When a product such as Windows reaches the end
  of support, so do its related components. .NET Framework 3.5 SP1 is
  supported on Windows Vista SP2, Windows 7 SP1, Windows Server 2008
  SP2, Windows Server 2008 R2 SP1, Windows 8.1 Update, Windows Server
  2012, Windows Server 2012 R2, Windows 10, and Windows Server 2016
  according to the end of support date for each operating system.


Export Highcharts to jsPDF - canvg error

Question: I'm looking for a solution about highcharts export to PDF with jsPDF.
I used this solution to export my graph as image to my pdf -> Export Highcharts to PDF (using javascript and local server - no internet connection)
It's working fine, but for some graph i could not generate the image because of this error :
Uncaught TypeError: undefined is not a function -- canvg.js:2000
svg.Element.text.getAnchorDelta -- canvg.js:2010
svg.Element.text.renderChild -- canvg.js:1989
svg.Element.text.renderChildren -- canvg.js:679
svg.Element.ElementBase.render -- canvg.js:698
svg.Element.ElementBase.renderChildren -- canvg.js:679
svg.Element.ElementBase.render -- canvg.js:698
svg.Element.ElementBase.renderChildren -- canvg.js:679
svg.Element.ElementBase.render -- canvg.js:2723
svg.loadXmlDoc.draw -- canvg.js:2733
svg.loadXmlDoc -- canvg.js:2646
svg.loadXml -- canvg.js:62
canvg -- indicateurs.js:3237
$.bind.H.Chart.createCanvas -- indicateurs.js:3171
(anonymous function) -- jquery-1.10.2.min.js:4
x.extend.each -- indicateurs.js:3164
_indicateurs.hightcharts.graph_to_pdf -- indicateurs.js:3262
(anonymous function) -- jquery-1.10.2.min.js:5
x.event.dispatch -- jquery-1.10.2.min.js:5
x.event.add.v.handle

Following, the canvas method throwing the error (canvg.js) :
        this.getAnchorDelta = function (ctx, parent, startI) {
            var textAnchor = this.style('text-anchor').valueOrDefault('start');
            if (textAnchor != 'start') {
                var width = 0;
                for (var i=startI; i<parent.children.length; i++) {
                    var child = parent.children[i];
                    if (i > startI && child.attribute('x').hasValue()) break; // new group
                    width += child.measureTextRecursive(ctx);       // ######## PROBLEM LOCATED ON THIS LINE
                }
                return -1 * (textAnchor == 'end' ? width : width / 2.0);
            }
            return 0;
        }

Any first ideas about what could be make this error ?
Comment: can you let us know the error you are receiving
Comment: W.onerror : error : Uncaught TypeError: undefined is not a function
 on page: /js/library_bower/canvg/dist/canvg.js
 on line: 2000
 on column: 22
 on object: TypeError: undefined is not a function
Comment: The firefox error seem more readable : TypeError: child.measureTextRecursive is not a function canvg.js:2000:15
Comment: It would be better if you can provide a fiddle
Comment: I could not reproduce it on jsfiddle. I tried to make the more simple exemple. I copied the svg that highcharts provide but it doesn't fail on jsfiddle.... http://fiddle.jshell.net/dct9tfvn/78/
Comment: Cool .. so the problem is solved :p
Comment: ^^ troll-ed! Unfortunately, I can not put all online scripts to reproduce exactly the problem ... That sucks .
Comment: Finally, i used highcharts server side image generation http://www.highcharts.com/docs/export-module/render-charts-serverside
Answer: Use this bower package:
"canvg-gabelerner": "*"

And make sure you include these 3 dependencies:

The canvg bower package is old. It was created because original repo was stored on Google code service (now dead).
I hope it helps! :)
Answer: It is one of the common issues in HighCharts. This is due to the wrapped text that is found within the <title></title> tag. This usually occurs if your axis labels are too long and they are wrapped to multiple lines. The simple way to resolve this error is to remove all the title elements before exporting to PDF. This doesn't affect any part of your chart.
To remove the title element within your chart container, use JQuery
("#chart_container_id title").remove();

Insert this line at the beginning of the exporting module. Now try to export and this will work fine.
Comment: Wow! Great answer!
Comment: Removing title does not work. getSVG() still returns an SVG image with title elements. I have to do svg.replace(/[\w\d\s]*<\/title>/g,''). What am I doing wrong?


In Google Colab, can you add a Markdown setting which will be applied automatically?

Question: I write most of my text in Hebrew, or a mix of Hebrew / English. for this, I need to add the following line to each text block:
div dir="rtl" lang="he" xml:lang="he">
(this didn't paste very well...)
but it's annoying to paste this each time. Is there a way to have this auto-pasted? better yet, is there a method to configure colab to work right to left by default?
Answer: My answer is not exactly what you are looking for, but here is tip that may help. You can create a code snippet with the line that you want to insert to more easily add it to your notebooks.

I create a small notebook with your snippet here https://gist.github.com/alexheat/b1bf37371a2d132cbd5b562e89d008d5.
In Google Colab settings, there is a section that says "Custom notebook snippet URL' enter this URL https://colab.research.google.com/gist/alexheat/b1bf37371a2d132cbd5b562e89d008d5/ltr.ipynb
Now create a new notebook and insert a snippet. You can type "Hebrew" to find the snippet. Insert the snippet.
This will create a code cell. To convert it to a markdown cell type Command+M+M.
Comment: Thanks a lot alexheat!

this still requires quite a few clicks before actually writing some Hebrew text, but it's still better than what I currently do.

if you ever come across something fully automatic, please share -)

Gideon