Instrumental Variable Interpretation

Question: I have an explanatory variable, 'social class' which I am trying assess the effect on a child's test score. Social class is a 6 fold categorical that breaks down based upon the parent's occupation - professional, manergerial, unskilled etc.
Because of the endogeneity of social class, and unobserved factors that impact upon the allocation of households into social class, I wish to instrument for social class using a dummy variable which takes the value 1 if the family are on a medical card (this is given to low ses households in ireland for free healthcare), and 0 otherwise.
Is this okay to do? The estimates I'm getting are quite different to the OLS estimates, which has me worried.
Thanks in advance.
Answer: This instrument seems like it would fail on both the exogeneity and the relevance criteria.  One reason to do IV is that there is something unobservable, like motivation, that is correlated with SES. Your instrument needs to move around social class (relevance) without altering motivation (exogeneity). Proxies tend to make bad instruments: by definition, they are correlated with unobservables. The card is arguably a proxy for low SES. On the relevance front, you just can't predict a categorical variable that takes on six values with a binary one, so it mechanically irrelevant/weak for the high SES categories.
OLS and IV estimate different treatment effects, so even if there was no endogeneity to worry about, you should see different estimates if students' SES has a variable effect on scores. When instruments are weak and there is endogeneity, the bias of IV can more substantial than OLS.
Comment: The conventional abreviation for socioeconomic status is SES, [SS](http://en.wikipedia.org/wiki/Schutzstaffel) as an abreviation has a rather tainted history and is thus best avoided.
Comment: Thanks so much for your reply. I understand that the card is a proxy for low SES, but surely not a proxy for whether the parent is a professional, or unskilled. As such, there are surely unobservables that affect whether the parent is a professional/unskilled but which also affect the child's test scores? (parent's motivation, etc). The medical card is something that you only have if you'e in a low paying/no job situation, but having it itself doesnt affect the child's outcome?
Comment: That's exactly the problem. Your proposed instrument is irrelevant for some of the categories whose effect you are interested in. On the second point, one could argue that if unobserved motivation is a shared trait within families (either because it is heritable or environmentally transmitted), it will be negatively correlated with scores and might contribute to low SES and poor employment outcomes for the parents and cards. There are at least two possible channels. A low income might make it harder for parents to invest in their children. The low income could be an outcome of poor motivation.
Answer: (Notwithstanding the basic observation made by @DimitriyV.Masterov about the unsuitability of predicting a 6-values categorical variable with a binary one).
Finding candidate instruments and choosing among them, is one of the fine arts of statistics and econometrics. A very fine art. Although some hard quantitative procedures have been devised in order to assess the choices made, the fact remains that the non-quantitative, verbal and logical argument that supports the choice retains its central and critical importance in order for an instrument choice to have chances to be accepted as valid.
For your particular case, this means that prior to searching for instruments, you must first lay out what are the factors that affect a child's test score, by name and not by the general tag "unobserved factors".
After you name these factors and develop an argument as to why they do affect a child's test score, and so as to why they are thought of as "included in the error term" of your regression specification, then you have to separate those for which you have data available, and those that you do not.
For the factors on which data are available, probably you should include them in the regression specification as controls.
For those remaining factors that are either unobservable, or for which data are not available to you, you have to point out which among them is correlated with SES and why (logical argument again). Denote this subset by $W$.
Then, you have to think what observable and available variable(s) is correlated with SES but uncorrelated with $W$ -and you have to lay down (again) a convincing argument about this difficult to find "correlation / non-correlation" combination.
So, to the specific question  "Is this ok to do?", with "this" representing the whole approach as described by you in the question, the answer is a -multidimensional- "No".
Comment: Thank you again to both you and @Dimitriy, you've both given incredibly detailed answers and I'm extremely grateful. I have another idea, and since it's become clear to me that my understanding of IV approaches is clearly lacking (me thinking of IVs as proxies somehow), I had another idea that I thought I'd pass by you guys - see what you thought. Please let me know if I'm overstepping the bound here. I'll post it in the next comment to give some room! Again feel free to tell me to go ask elsewhere if I'm taking liberties - but I'm at a loss here.
Comment: @StephenB It would perhaps be better to post this other idea of yours as a new question, rather than as a comment here.
Comment: Actually scratch that. I understand IV properly now after an evening of thinking about it. I don't think I can plausibly instrument for SES as there's nothing available to me that would exogenously alter socioeconomic status that aren't correlated with the error term. The idea I was going to tell ye about was using the weekly cost of childcare to instrument for SES, as if it's more expensive the parent's are likely to have to change jobs, but it could also affect other things - i'm at a loss to be honest. Thanks for all the help.

Instrumental Variable Interpretation


Calling a variable with part of another variable

Question: I want to combine part of a variable name with another variable to complete the full variable name. "Box + A2G[i]" would be the BoxA, BoxB, or BoxC variable.
var A2G = new Array("A","B","C");

var BoxA = new Array("apple","peach","grape");
var BoxB = new Array("volvo","GMC","Honda");
var BoxC = new Array("Bob","Susan","Mark");

for(i=0;i<A2G.length;i++) {

$("#row1").prepend('
 \

 \

 \

Circuits<br' + Box + A2G[i] +'
 \

 \

' + A2G[i] + '
 \

 \

 \

');
};

Comment: https://www.google.com/search?q=using+eval+for+dynamic+variable+names&oq=using+eval+for+dynamic+variable+names
Answer: Your "Box" should be an object:
var Box = {
  A: ["apple", "peach", "grape"],
  B: ["volvo", "GMC", "Honda"],
  C: ["Bob", "Susan", "Mark"]
};

Then you can just use Box[ A2G[i] ].


Contact Form 7 Change Form-Tag Output

Question: I'm trying to change the output of contactform7 forms from
<form action="/#wpcf7-f583-p294-o1" method="post" class="wpcf7-form">

to
<form action="/#wpcf7-f583-p294-o1" method="post" class="small-12 column wpcf7-form" novalidate data-abide>

Therefore I've added some hooks
add_filter('wpcf7_form_class_attr', function($html_class) { return 'small-12 column ' . $html_class; }); // adds respsonsive classes to the form-tag
add_filter('wpcf7_form_novalidate', function($support_html5) { return true; }); // adds novalidate-attr to the form-tag

So the only thing I'm missing is the data-attribute. Is there any hook or any idea, how to get there, without toching the core-Files?
I've found the magic in /contact-form-7/includes/contact-form.php starting in line 297
/* Generating Form HTML */
public function form_html( $args = '' ) { // ...

and then, from line 409 on
$enctype = apply_filters( 'wpcf7_form_enctype', '' );
        ...

        $atts = array(
            'action' => esc_url( $url ),
            'method' => 'post',
            'class' => $class,
            'enctype' => wpcf7_enctype_value( $enctype ),
            'autocomplete' => $autocomplete,
            'novalidate' => $novalidate ? 'novalidate' : '',
        );

        ...
        $atts = wpcf7_format_atts( $atts );

        $html .= sprintf( '<form data-abide %s>', $atts ) . "\n";
        ...

        $html .= '</form>';
        $html .= '
';

SO: pushing my values to the atts array in the form_html function would be my solution. But honestly I don't know how-
Thank you in advance!
Answer: Use jQuery.  If I read your question correctly... You are trying to add the classes small-12 and column... remove novalidate and add data-abide?
jQuery('#wpcf7-f583-p294-o1 form').addClass('small-12 column').removeAttr('novalidate').attr('data-abide', true);

Comment: There is no solution for you. Within the form_html function, the $args themselves can't have additional args added.
Comment: HI Howard, thanks for your reply.
I've allready added small-12 column and the novalidate tag. What's missing now is the data-abide attribute which needs to be added.

Your solution wouldn't work for me as it needs to be part of the HTML before JS gets rendered - therefore adding it afterwards is sadly no solution for me.

Contact Form 7 Change Form-Tag Output


What are expressions in mathematics?

Question: Like algebraic expressions are logarithmic, Experimental, trigonometric, differential, etc., expressions also there?
I am not referring to functions, but just expressions or equations. Are their definitions similar to how we define their corresponding function?
I know Functions are more frequently and widely used than any expression, why?
Comment: https://en.wikipedia.org/wiki/Expression_(mathematics)
Comment: In my mind, the word "expression" does not have a precise meaning, and if I'm developing math rigorously I would avoid using the word "expression" entirely. (Maybe in some other areas of math like logic the word "expression" is given a precise meaning.)
Answer: An expression is essentially a string of symbols (e.g., $$\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$ or $x^2$) with some technical requirements; an equation is a relationship between expressions that is given by an equality (e.g., $c=2\pi r$).

I doubt that functions are more frequently/widely used than expressions. In mathematical literature, a typical author talks about the LHS or the RHS of the definition of a function (and the derivations thereof) far more often than the function itself. For every equation, there is at least two expressions.
Comment: Not necessarily.
Comment: More than just "a string of symbols", an expression has to be a syntactically correct well-formed formula (in some formal language that's usually typical math notation).
Comment: Aren't Expressions classified on bases of their corresponding functions, like logarithmic expression, trigonometric expression, etc
Comment: Then what logx called without equating it to y, and sinx, tanx ,logx should all be then same category expression inspite their corresponding function are different
Comment: Well, yeah; you're right. In those cases they are expressions involving those functions.
Comment: Yes, I suppose the use of mathematical logic and formal languages is more appropriate to nail down the definition here, @JohnForkosh; you're absolutely right. I'll provide a link to your comment in this answer.
Comment: Oh, and thank you :)

What are expressions in mathematics?


How to model predicted proportion data without weights

Question: Research Question
I am trying to determine if maternal nest-site choice influences offspring sex ratio in a species where nest temperature determines sex.
Data
I have temperature traces from real nest sites and random sites at six nesting locations. The data was collected over five years. From these temperature traces, I have calculated a predicted sex ratio for each nest and random site. The sex ratio data is continuous, bounded by 0 and 1, with a large number of zeros and ones. Here is a histogram of the data:

I'd like to know if sex ratios vary between nests and random sites, and if this relationship varies between locations.
Analysis Options
Normally, when analysing sex ratio data, I would use a glmm with the binomial or betabinomial error distribution and the number of sexed individuals as the weight term. However, I can't do that in this case because the sex ratios are predicted values, not associated with any real individuals. I have considered three options to solve this issue.

Use my predicted sex ratios to generate a number of "fake" individuals for each nest/random site and then use that number as the weights for a binomial/betabinomial glmm. This seems a little too hacky.

Use a zero-one inflated beta model (ZOIB). Based on my reading, ZOIB models are appropriate when zero or one values originate from a different underlying process than intermediate values (sources:1,2,3). I don't think this is the case with my data (the difference between a sex ratio of 0 and 0.1 is biologically the same as the difference between a sex ratio of 0.1 and 0.2), although maybe the fact that there are a wider range of temperatures that produce 0 or 1 sex ratios means these results should be treated differently to intermediate values.

Use ordered beta regression. Robert Kubenic's method for analysing continuous proportions seems like it might be appropriate for my data (source: 2). I trialed it using the "ordbeta" family in glmmTMB (the model was: Sex Ratio ~ Location*SiteType + (1|year), family=ordbeta), however I don't think the error distribution of my data matches the ordbeta error distribution. My residual plots (made in DHARMa) suggest that the residual error isn't uniform.

Further inspection suggests that there is variation in residual error between the locations:

I used performance::check_predictions to compare model predicted and real values. It seems like there is greater prediction error around zero and one than intermediate values.

I'm wondering if ordered beta regression is the best approach to analysing my data, or if I should try a different solution? If ordered beta regression is the right way to go, what should I do about the error variance issues?
-Thanks
Sources:

https://www.theanalysisfactor.com/zero-one-inflated-beta-models-for-proportion-data/
https://www.robertkubinec.com/post/limited_dvs/
https://twitter.com/bolkerb/status/1577755600808775680
Comment: @whuber I'm not actually looking at the relationship between sex and temperature. I'm testing whether the maternally selected sites would produce different sex ratios than the random sites.
Comment: @gung-ReinstateMonica, I'm only comparing the model predicted sex ratios, as we don't have true sex ratio data for many of the nests (for turtles juvenile sex can't be determined without euthanizing hatchlings).
Comment: Could you explain the sense in which a sex ratio -- which sounds like one count divided by another -- should be considered "continuous"?  What are you counting, what is this a ratio of, and what are typical values of those counts?  Since you describe this as "predicted," then in what sense does that help you assess its relationship with temperature?
Comment: Are you only comparing the model predicted sex ratio between actual nesting sites and randomly selected sites, or are you comparing observed sex ratios of baby birds born in those nests to the model predicted sex ratios?
Comment: @whuber My data is an expected sex ratio rather than a real sex ratio. I used an equation that describes the relationship between sex and temperature for our study species and predicted the chance of developing as a male at the recorded temperatures (0 = no chance to be male, 1= 100% chance of being male). Any value between 0 and 1 is possible, so I don't think I can model it as a discrete varaible, though I should have described it as a probability, not a ratio, sorry! With real sex data you would divide the number of males by the number of females to get the sex ratio.
Comment: I'm guessing `siteType` is actual nest vs random spot.  What then is `location`?  Do you have observations at matched times?  If the model predicted sex ratios are just based on temperatures, can you eschew the whole thing and just compare the temperatures of the actual nests vs random spots?
Comment: Ah, turtles!  I read "nests" and assumed *birds*.  Lol.
Comment: @gung-ReinstateMonica, location is the different river banks that we recorded nesting. They are distributed over a wide geographic range, and experience different climates, so we expect that sex ratios may vary between the locations.
Comment: Sure.  Can you just compare the temperatures?  Are the observations of the actual nests and random spots paired?
Comment: I could compare temperatures (which would certainly be more simple), but there are potential differences in temperature that would not result in differences in sex ratio (e.g cold and very cold nests are still 100% male). Random nests tend to be more extreme temps, so I'm worried that just comparing temps wouldn't answer the question of if maternal nesting behaviour influences sex ratio.
Comment: Huh, interesting.  Is it the variances of the temperatures that matters and not the means?  (Be sure to "@" me to ensure that I am aware of your response.)  It is possible to compare variances.  Also, are the sex ratios predicted directly, or are they based on, say, predicted probabilities or predicted odds, etc?  Would you have those?  If they were, say, probabilities, are they actually exact 0's, eg, or would it be something like .0000001, where realistically you would get all one sex?
Comment: @gung-ReinstateMonica, after considering it over the weekend, I think your suggestion to analyse the temp data rather than predicted SRs is probably the way forward. I was concerned that I would find a statistically significant difference between the sites, that wouldn't relate to a biological difference in SRs. However, I can use the parameter estimates of a temp ~ location*site_type model to see what SRs the different categories would produce and decide if there are biologically relevant differences between the sites.
Comment: That sounds good.  Let me know if you are interested in the variability of the temps (higher highs and lower lows) instead of the mean temps.  Otherwise, I might just condense these comments into an 'answer' to give this thread some closure.
Comment: @gung-ReinstateMonica, I am interested if you have time to elaborate. Thanks very much for your help so far.
Answer: Those plots are not valid for the ordered beta distribution, which is a mixture of discrete and continuous responses. To get a better view of fit, use the pp_check_ordbeta function in the ordbetareg package (see https://cran.r-project.org/web/packages/ordbetareg/vignettes/package_introduction.html). However, in any case I wouldn't say that any of those plots show substantial misfit. For a distribution to be useful, it doesn't need (nor do you necessarily want) to incorporate all the features of your data.
Comment: Absolutely, that's the exact sort of distribution I wrote the model for. Use the marginaleffects package with ordbetareg and you'll get easy to interpret covariate effects. See the package vignette for info.
Comment: Thanks for your reply! Do you think it's appropriate to model this data with an ordered beta regression? I am considering using the underlying temperature data instead.


JSP String encoding issue

Question: I have a code like this in my JSP page
 <% String value = function();
    System.out.println(value);
 %>

I am pretty sure my function() returns a string which is viewable. However when I run this on server the printed text i can see in my console is a bunch of question marks. Im sure this is an encoding issue but not able to figure it out. I tried converting the string from from unicode to iso-8859-1 and vice versa but it was of no help. the encoding of my html page is UTF-8 can anyone help me with this?
Answer: Rather than printing to the console, why don't you return the text to the browser, for example:
<%
    String value = function();
    out.println(value);
%>

Use this page directive in your JSP to ensure the page encoding is UTF-8:
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>

JSP String encoding issue


Prove that every tangent line to the function $f(x)$ only intersects the function once.

Question: Prove that every tangent line to the function $f(x)$ only intersects the function once.
$$f(x) = \int_{0}^{x^2}e^{t^3}dt, x \in(0,\infty)$$
My Attempt:
Lemma 1: $f'(x)$ is an increasing function.
By the fundamental theorem of calculus we get $f'(x) = 2xe^{x^6}$. Assume $x_1, x_2 \in (0, \infty)$ such that $x_1 < x_2$. Then:
$$2x_1 < 2x_2$$
$$2x_1e^{x_1^6} < 2x_2e^{x_2^6} \rightarrow f'(x_1) < f'(x_2)$$
This lemma allows us to conclude that every slope of $f(x)$ is unique. Assume that there is an intersection point for some slope. Let the slope be at $(x_1, y_1)$ and the intersection point be $(a,b)$. By the MVT there is a $f'(c) = f'(x_1)$ where $c \in (x_1, a)$. This contradicts lemma 1. QED
Is this strategy correct?
Comment: Very nice. Looks good to me.
Answer: The strategy is good. There is a small, somewhat inconsequential error though: the derivative of $f$ is $2xe^{x^6}$ not $2xe^{x^6} + C$. Remember, you're not integrating here, but differentiating a function (defined by a definite integral, which wouldn't need a constant of integration anyway).
What you're essentially doing here is showing that $f$ is a strictly convex function; if a differentiable function $f$ has a strictly increasing derivative, then $f$ is strictly convex. Tangents to convex functions lie on or below the graph of the function. In the case of strictly convex functions, the tangent only touches the function once.


server_name in nginx.conf seems to be ignored

Question: I've got a domain name, let's say example.com that point to my server. And my nginx.conf is:
upstream domain {
    server 127.0.0.1:8002;
}

server {

    listen 80;
    server_name <example.com>;
    client_max_body_size 10M;
    keepalive_timeout    15;

During development, I want to deactivate example.com. I replace it by <different_name>.
server {

    listen 80;
    server_name <different_name>;
    client_max_body_size 10M;
    keepalive_timeout    15;

It works fine as expected with <different_name> but it still continues responding to <example.com>. And I can't figure out why. I'd like nginx to not respond at all on <example.com>.
Naturally I didn't forget to restart services as gunicorn and nginx.
Edit: It may be a duplicated post as suggested. In my opinion the way the problem is exposed in the post you mentioned is confused. Even the title is not clear. "nginx open reverse proxy" What does it mean seriously? I tried to expose my problem which has a similar solution in clear terms keeping in mind that it could / should be reusable and much more explicit to everyone.
Comment: http://serverfault.com/a/690242/211028
Comment: Also consired change DNS for `domain.com` not to point to your IP
Comment: The way the problem is exposed in the post you mentioned is confused to me. Even the title is not clear. "nginx open reverse proxy" What does it mean seriously?  I tried to expose it in clear terms keeping in mind that it could / should be reusable and much more explicit to everyone.
Answer: In short: by removing the production domainname requests for that domain do not get blocked, they will go to default server.
Paraphrased from the manual:

Nginx tests only the request's header field "Host" to determine which server the request should be routed to. If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server. Unless explicitly configured with default_server the default server is the first one.

You could create a minimal default server that either returns a default page or an error message e.g.:
server {
    listen      80 default_server;
    server_name _ ;
    return 503  "No server is currently configured for the requested host." ;
}

Comment: Note that the `server_name` direcrive is not needed.
Comment: note that you need quotes around the second parameter to the return statement
Comment: config is missing a `return 503  "No server is currently configured for the requested host." ;` can't edit because it needs 6 chars at least
Comment: I didn't know about the default_server. But I changed your proposition since it raises a conf error. Instead, I just return a 444. Thanks!


"Fatou's Lemma" for a weak convergence sequence in a normed space .

Question: Suppose in a normed space $X$ we have $x_n \rightharpoonup x_0 $ (weakly converge). Prove $\liminf_\limits{n \to \infty} ||x_n|| \ge ||x_0||$.
Here, in a normed space $X$, a sequence $x_n$ weakly converge to $x_0$ is defined by:

$\forall f \in X^*$ (the space of all continuous linear functional), we have $f(x_n)\to f(x_0)$.

My attempt:
By Mazur's lemma, we know $\forall \epsilon > 0, \exists \lambda_i \ge 0 \, (i = 1,2,\dots n)$ and $\sum_i^n \lambda_i =1$ s.t. $||\sum_\limits{ i = 1}^n \lambda_i x_i-x_0|| <\epsilon$. Let $A = \{\lambda_1 x_1 + \cdots+\lambda_k x_k| k \in N^+, \lambda_i \ge 0, i = 1,\dots,k, \sum_\limits{i = 1}^k \lambda_i = 1\}$, then $x_0 \in \bar{A}$. Suppose $y_n = \sum_\limits{i = 1}^{k_n} \lambda_ix_i \to x_0$.
But I don't know how to carry on.
Answer: There exists $f \in X^{*}$ such that $\|f\|=1$ and $f(x_0)=\|x_0\|$. So $\|x_0\| =f(x_0)=\lim f(x_n)\leq \lim \inf \|x_n\|$.
Comment: The existence of such $f$ is due to Hahn-Banach Theorem?
Comment: Yes, it can be proved easily using Hahn Banach Theorem by first defining $f$ on the one dimensional space spanned by $x_0$.


Is there a unique polynomial function $f(x)$ of degree $\lt n$ such that $f(n) = a_n$ where $\{a_n\}$ is a sequence?

Question: Is it true that for every sequence $a$ of $n$ numbers there is exactly one polynomial function $f(x)$ of degree $\leq n$ such that all $f(1)=a_1,f(2)=a_2,\dots f(n)=a_{n}$? If so, is there an algorithm to, given the sequence, generate the coefficients of this function?
Intuitively, I feel like this is true, because:

Given $a$ and $b$, you can find a polynomial function $f$ that has degree $1$ such that $f(0)=a$ and $f(1)=b$.
By induction: given coefficients $a_1,a_2\dots a_n$, you can find a polynomial function of degree $n$ such that $f(x)$ yields a constant value for all $x$ in $\{1,2\dots n-1\}$.

Mostly, the reason I want to be able to find such a function is so when my math teacher says "find the function rule" and presents us with an obviously linear function I can give her some strange polynomial that just happens to give the correct answers for those values.
Comment: A linear function *is* a polynomial function, so if your assertion about uniqueness is indeed true, then your smartass plan won't work.
Comment: https://en.wikipedia.org/wiki/Lagrange_polynomial
Comment: Note that if `f has degree 1 such that f(0)=a and f(1)=b` then $f(x)+ x(x-1)g(x)$ will take the same values at $0,1$ for any $g(x)$. P.S. You've got the degrees off-by-1 a couple of times in the question.
Comment: @amd If I admit higher degrees of polynomials than the length of the sequence (which I intend to), then I can just pick an arbitrary value for $a_{n+1}$ and find a new function.
Comment: Not $\le n$, but $<n$. http://math.stackexchange.com/questions/144257/how-is-a-degree-d-polynomial-uniquely-characterized-by-its-values-at-d1-dis
Comment: Someone should really figure out a better title, this is extremely click-bait.
Comment: How about piecewise linear functions connecting the points? They are relatively easy to write down and look horrible enough to annoy your teacher.
Comment: The teacher is likely to then ask you to integrate the function.
Comment: How did you come up with such a click bait title ?
Answer: A polynomial degree $\leq n$ modeling $a_1,a_2, \cdots a_n$ would not be unique. Consider $f(1)=1$, $f(2)=4$. Obviously $f(x)=3(x-1)+1$ works, but we can let $f(x)=x^2$.
A polynomial of lowest degree that models $\{a_1,a_2,a_3,...a_n\}$ is unique. A polynomial of lowest degree that fits a set of points  is called the Lagrange Polynomial for that set of points. Here we want the Lagrange Polynomial for a very special set of points. A "closed form" is possible:
$$f(x)=\sum_{i=0}^{n-1} {x-1 \choose i} \Delta^i(1)$$
Here $\Delta^0(1)=f(1)$. Also $\Delta$ is defined as the operation mapping $f(x)$ to $f(x+1)-f(x)$. This operation is called the forward difference.Then $\Delta^i(1)$ is the operation iterated $i$ times then evaluated at $1$.
Ex: Find the Lagrange polynomial for $1,3,5$.
$$\color{red}{1},3,5$$
Taking forward differences once gets.
$$\color{red}{2},2$$
Twice,
$$\color{red}{0},$$
This gives a Lagrange polynomial,
$$f(x)=\color{red}{1}{x-1 \choose 0}+\color{red}{2}{x-1 \choose 1}+\color{red}{0}{x-1 \choose 2}$$
$$=2x-1$$
Using this formula, you can troll your teacher. For example if your teacher asks find the rule for $1,3,5,$ then you can use the formula to find a rule for a sequence that goes $1,3,5,\pi$.
$$1,3,5,\pi$$
$$2,2,\pi-5$$
$$0,\pi-7$$
$$\pi-7$$
This gives,
$$f(x)=1+2{x-1 \choose 1}+0+(\pi-7){x-1 \choose  3}$$
$$=1+2(x-1)+(\pi-7)\frac{(x-1)(x-2)(x-3)}{3!}$$
Comment: More generally, for the last example, you can take $2x-1+(x-1)(x-2)(x-3)P(x)$ for any polynomial $P$. This way you can have an arbitrarily high degree polynomial. For instance taking $P(x)=x^9-3x^2+1$ you obtain $x^{12}-6 x^{11}+11 x^{10}-6 x^9-3 x^5+18 x^4-32 x^3+12 x^2+13 x-7$ and you can check it works.
Answer: Regarding trolling your math teacher, if you have a linear function $f$ such that $f(1)=a_1,f(2)=a_2,\cdots, f(n)=a_n$ you can create a polynomial function of higher degree with the same property by adding $g(x)=(x-1)(x-2)\cdots(x-n)$ to $f(x)$. Then $f(i)+g(i)=a_i+0=a_i$.
Comment: Sorry, but isn't this just making the problem worse ? I feel like f(x) is the thing you were searching for in the first place and now you just calculated g(x) for nothing ?
Comment: @HopefullyHelpful: I was responding to the question about finding a higher-order polynomial that fits the same linear data. This is the last sentence of the original post.
Comment: Yeah, my reading comprehension is off, I thought OP searched for a super quick way to make polynomes from data in his head. duh.
Answer: Trolling here is far easier than you're making it out to be. If all you're given is a finite set of points and your teacher asks simply for a function -- not necessarily polynomial -- that fits them, you can just set $f(x_i)=y_i$ for $(x_i,y_i)$ in your list and $f(x)=0$ otherwise.
Comment: (That said, I wouldn't do this if you think your teacher will react badly or doesn't know the material well enough to understand your answer.)
Comment: "But functions are continuous!" - the teacher, upon seeing this
Comment: reminds me of https://xkcd.com/221/
Comment: @Emrakul: whether you're joking at the teacher's expense or taking that attitude yourself, I refer you to my comment above.
Answer: You could define a polynomial function
$h(x)=f(x)-a_x$ for your given sequence $a_x$
now if you have $n$ terms in your sequence,
$h(x)$ will be an $n$ th degree polynomial with roots equal to  $i$  for $i=1$ to $n$
$h(x)=(x-1)(x-2)\dots (x-n)=f(x)-a_x$ or
$f(x)=(x-1)(x-2)\dots (x-n)+a_x$
as long as your sequence $a_x$ is a polynomial you can find the coefficients this way.


sql update using a list of values on a list of targets

Question: I want to update a list of items using a list of values for example:
$fruits = "apple,banana,orange";
$prices = "10,15,20";
$sql = "UPDATE stuff SET fruit =?? ($fruits) where price in ($prices)

I know the "update x set a=b where c in (d)" part works, but I dont know it I can use a list of items as value for b
Comment: So you want to set fruit to multiple values in a single `UPDATE` statement?  That doesn't make sense.  `UPDATE` performs a modification of each matched row, and `fruit` can only have one value for a given row.  Maybe you want to use `INSERT` to create new rows, or maybe your statement structure doesn't match the actual problem you are trying to solve.
Comment: If I understand you right, you need to split data from fruits and prices, and then join by position in the list. Its possible to do in SQL server, I don't know about your RDBMS
Comment: Or do you mean using a list of items for `d`, rather than `b`? That would make more sense.
Answer: You can use a CASE expression:
UPDATE x
SET a = CASE c
           WHEN 'c1' THEN 'b1'
           WHEN 'c2' THEN 'b2'
           ...
        END
WHERE c in ('c1', 'c2', ...)

Comment: no but I dont want to check anything I just want all fruits to have a price.. actually in this example its the other way around :D I just want all prices to have a fruit :D
Comment: ok nvm Ill just do it the hard way..
foreach x as y {
update bla bla
}


Construct an inscribed equilateral triangle - proof

Question:
Construct an equilateral triangle inscribed in a given circle.  Prove the construction using synthetic geometry only.

There are two standard constructions for this:

Find a $\pi/6$ angle via a right triangle (angle on the circle subtending the diameter) with one leg half the length of the diameter.  See e.g. here or here.

Inscribe a regular hexagon by using chords equal to the radius.  Then connect every other point.  See e.g. here or here.

Can we prove these constructions using synthetic geometry only (no trig)?
Comment: @RobinSparrow You're right.  Construct an equilateral triangle (I.1) and "copy" it into the circle (IV.2).  This actually involves more steps than the methods in the OP (esp. because IV.2 requires constructing a tangent), but the proof is an immediate consequence of the Elements' propositions you cite.  Would you consider writing this up as a proper answer? I think others would find it useful.
Comment: Is IV.15 of Euclid's Elements not synthetic?
Comment: @RobinSparrow IV.15 constructs a hexagon.  The OP asks "Given that we can construct a hexagon, prove that connecting every other vertex gives an equilateral triangle."
Comment: My comment last night was off - I misread your question =)
Comment: But after rereading I think I am still missing something. Euclid provides a synthetic path to inscribe any triangle in any circle, culminating in IV.2 where it is accomplished. The constructs you link to essentially begin with that of I.1, construction of the equilateral triangle, and assume certain knowledge about trig. But Euclid has no trig. With I.1 you have equilateral, by I.5 we have equal bases imply equal angles so you have equiangular, and with IV.2 you have inscription of any (equiangular) triangle into any circle.
Comment: No problem, my longest post by miles =)
Answer: Proving the first method:
Suppose that $ABC$ is a triangle in which $\angle ABC=90°$ and $AC=2BC$, let's called $C'$ the symmetric of $C$ with respect to $B$, then, by the properties of the simetry, $BC=BC'$ and $AC'=AC=2BC$, but $BC'=BC$, then $CC'=2BC=AC=AC'$ and $ABC$ is an equilateral triangle, so angle $\angle BCA$ must be equal to $60°$.

Now I'll prove the second one. Let $ABCDEF$ be the regular hexagon, by the simetry of the regular polygons the diagonals $AC$, $CE$, and $EA$ are all equals, because they all "skip a vertex" to the right, then the triangle $ACE$ is equilateral as desired.
If the simetry argument is not convencing enough, note that $AB=BC=CD=DE=EF=FA$ because the hexagon is regular. Note that the sum of the interior angles is $180 \times (6-2)=720$, then each angle is $120°$. Note that triangles $ABC$, $CDE$ and $EFA$ have $\angle ABC = \angle CDE = \angle EFA = 120°$ and $AB=BC=CD=DE=EF=FA$ so that the three triangles are equal to each other and $AC=CE=EA$ and the triangle $ACE$ is equilateral.
Comment: The gaven construction in the post works based on the fact that if you have a right triangle in which one of the sides is half of the hypotenuse, then it's got a $60°$ angle. I proved with synthetic geo that this fact is actually true, which is not obvious, I understood that the problem was to understand why is that true.
Comment: @BrianMoehring "If you reflect $C$ across $AB$, then its image $C′$  is outside the circle, not on it." True - but so what? We know [$\angle PBQ$ ](https://tasks.illustrativemathematics.org/content-standards/tasks/1557) is $60 \deg$, and we know by symmetry that the other two angles are equal.  Hence the triangle is equilateral.  What do you feel is missing?
Comment: @BrianMoehring No, we need to show that $\triangle PQB$ is equilateral.
Answer: Euclid provides in book IV of Elements methods for inscribing in a given circle shapes of triangles, squares, pentagons, hexagons, and in general regular mn-gons where m and n are constructible regular polygons. Euclid is entirely synthetic and trig is involved only in the sense that right angles are defined axiomatically such that two of them form a straight line. I'll outline the main path to inscribing an equilateral triangle, and point out that other routes are possible.
The main road map: (1) construct an equilateral triangle; (2) prove that equilateral triangles are equiangular; (3) prove that equiangular triangles are equilateral; (4) construct an equiangular triangle in a given circle.
The proofs are general and apply to all triangles. And I'm not going to show or describe everything, just the highlights. In the images below, what is given is in red.
Step 1: Given any length (in red), use it as the radius of circles constructed at either end, then segments from the intersection of the circle to the centers have the same length, and we have an equilateral triangle.

Step 2: Equal sides imply equal angles. Given a triangle with equal sides, extend each side by a fixed length (//). Now, using mirror triangles in the triangle, by SAS we have two triangles with equal apex angles $\alpha$ and sides (/) and (/+//). Thus the diagonals under the base (///) are the same, as are angles marked $\beta$, as are the angles marked with the single arc. Further, again by SAS, the inferior mirror triangles composed of (//), $\beta$, and (///) are equal, meaning that the sections of the single-arc-angle under the original base (marked with double arcs) are equal. Hence the angles in the single-arc-angles above the base are equal. So equal sides in isosceles triangles imply equal base angles. This immediately implies an equilateral triangle is equiangular.

Step 3: Equal base angles imply equal sides. Given equal base angles, suppose for a contradiction that the sides were not equal. Whichever is larger, cut it down to equal the other, and connect it to the base (via the dotted line). Now, by SAS, the indicated triangles are equal, which is absurd. Therefore the sides must be equal. This implies an equiangular triangle is equilateral.

Step 4a: Prove that in a circle, an inscribed angle subtending an arc is half the central angle subtending the arc. Here, the angle in the middle is at the center of the circle. Draw the diameter from the inscribed angle through the center. Examining the triangles thus formed, we have an isosceles with sides the radius, thus equal base angles $\alpha$, and since exterior angles are the sum of opposite interior angles, the exterior angle on the diameter is $2\alpha$. And likewise for the triangles on the other side, so for an inscribed angle $\delta$, the central angle subtending the same arc has angle $2\delta$.

Step 4b: Prove that all inscribed angles subtending an arc are equal. Suppose two inscribed angles subtend the same arc. Draw the central angle subtending the arc, which is twice an inscribed angle on the same arc by (4a), hence the inscribed angles subtending the arc are the same.

Step 4c: In a circle, prove the angle between a tangent and a chord originating at the tangent is also the inscribed angle subtending the chord. Given the tangent and chord with angle $\delta$ between them, form the diameter at the point the tangent touches the circle. This diameter will be perpendicular to the tangent. Inscribed angles subtending a diameter are right angles. And since the angles of a triangle sum to two right angles, the angle subtending the chord is the angle $\delta$. And by (4b) any inscribed angle subtending that chord also has angle $\delta$.

Step 4d: Inscribe any triangle in any circle. Given a triangle and a circle, draw a tangent and form chords whose angles with the tangent are two of the angles of the triangle, here $\alpha$ and $\delta$. Connect the endpoints of the chords. By (4c), the enclosed angles are also $\alpha$, $\delta$ and the triangles are thus similar.
Step 5: The actual proof of inscribing an equilateral thus goes: construct an equilateral of any size. It is equiangular. "Copy" the equiangular triangle into the circle of interest. Equiangular triangles are equilateral. So you have inscribed an equilateral triangle in the circle.
Comment: I've obviously skipped some steps and proofs, I wanted to get across the gist, since you can read the entire chain of proofs in the original. Anyone can see that construction I.1 leads by repeated application to a regular hexagon inscribed in one of the circles. If you wished to use that construct purely, you need that the the sum of angles in a triangle are two right angles, and that if a set of neighboring angles sharing a vertex sum to two right angles, the outermost rays form a straight line. Such proofs are also in Book I of Elements. So you could use that route on the I.1 construct to prove an inscribed equilateral triangle. The proofs linked by the OP are based on Euclid I.1, using trig to skip some of these steps. If you are interested in synthetic geometry but haven't read Euclid's first 6 books, it can be found online and also Green Lion Press recently published a nice print version (that I have and like).
Comment: Thanks! No source, it's just what I would want someone to show me if we couldn't share a chalkboard or paper. In person you would point out what's important or new at each step, and probably erase stuff that no longer matters and clutters as the proof develops. This is the closest I can get to that.
Comment: Well done! That's a new mode of a diagrams, sequentially building the proof.  I haven't seen that mode before (most diagrams are "single scene", all encompassing, much harder to follow).   Can you share any information or sources on this style?
Answer: I will be referencing the diagram and vertex-labeling appearing in the IM link, but additionally call the left circle's center $C$.  The main difference is that I will be completely ignoring the 2:1 ratio in favor of an equilateral triangle we already have in the "usual" method 1.  In that sense, maybe I'm responding to 1' rather than 1.
In case that link is dead, the setup is as follows: Given a circle with center $C$ and a point $B$ on the circle, let $\overline{AB}$ be the diameter containing $B$.  Then draw a second circle with center $A$ that goes through $C$, and call the circles' two intersection points $P$ and $Q$.

Since $A,P$ lie on the first circle, $CA=CP$, and since $C,P$ lie on the second circle, $AC=AP$.  Together, this shows $\triangle ACP$ is equilateral, hence equiangular, so that $$\measuredangle BAP = \measuredangle CAP = 60^\circ.$$
Since $\overline{AB}$ is a diameter of a circle containing $P$, the angle $\angle APB$ is a right angle.  Therefore $\angle BAP, \angle ABP$ are complementary, so that $$\measuredangle ABP = 90^\circ - \measuredangle BAP = 30^\circ.$$
By a symmetric argument [replacing $P$ with $Q$], we find $\measuredangle ABQ = 30^\circ$.
Comment: Honestly, I don't like measuring angles in constructions, so I'd like to remove that, but it doesn't sound like that is necessary for your uses, and it would complicate things unnecessarily ("twice the complement of the angle $\alpha$ in an equiangular triangle is congruent to $\alpha$" by dropping a perpendicular and using congruence postulates isn't hard, but it is a bit of a sidetrack)
Comment: No problem with the usage of angle measure; it's an acceptable shorthand.  But the proof seems like it needs to be finished.  Which is the final inscribed equilateral triangle? If it's $\triangle PBQ$, you've shown $\angle PBQ = \angle ABP + \angle ABQ = 60 ^\circ$, but haven't shown either of the other two ($\angle PQB$ or $\angle BPQ$) are.
Comment: @SRobertJames Honestly, after you said the other answer sufficed, I'm a bit confused, as it didn't go even that far.  In short, the remaining proof would parallel what IM has, using congruence postulates to first show $BP=BQ$ and then (since it's an isosceles triangle) another congruence postulate to find the base angles are congruent.  I cannot recall if all the congruence postulates are trig-free, though
Answer: Do you know the center of the circle? A new circle centered anywhere on the circle having the same radius will intersect the original circle at two points whose corresponding arc subtends and angle of 120 degrees. We know this because the given points can be used to form 2 equilateral triangles. The sum of adjacent angles of adjacent equilateral triangles is $120^\circ$.  Continue creating circles in this way and then connect every other intersection. You get an inscribed equilateral triangle.
Comment: "Do you know the center of the circle?" _Yes; if not, [it can be found](http://aleph0.clarku.edu/~djoyce/elements/bookIII/propIII1.html)_.  "the original center and the two intersections are all equidistant from each other" _Are you sure? I think the original center, the **second circle's center**, and **one** of the intersection points are mutually equidistant; but the two intersection points are further apart_.  "...connect every other intersection. You get an inscribed equilateral triangle."  _This is Method 2 of the OP, which asks to **prove this**.  Have you done that?_


Mirotik : Client from interface 1 cant access client from interface 2

Question: I have a mikrotik here.
Both interface 1 and 2 have same network (10.10.30.0) and dhcp pool.
I can ping any client on interface 1 from mikrotik and also any client on interface 2. But I cant use to ping any client on interface 2 from any client interface 1. It seems each interface cannot communicate.
I have 3 interface enabled currently.
This is the current IP configuration :
<code>PC : 10.10.10.3/24 - interface1
ADSL router : 10.10.30.2/25 - interface2
WD My Cloud : 10.10.30.200/25 - interface3
</code>
Please help
Comment: You have conflicting subnets. Resolving that is your first step to getting this resolved.
Comment: @EEAA : Ok thanks. Now I already change the subnet.
Answer: Solved.
I just create a NAT in firewall panel.
Action : masquerade
Chain : srcnat
Out interface : Eth3 (one of my ethernet interface)
Comment: This is not a solution. As EEAA mentioned you have conflicting subnets. You need to create a bridge, assign all ethernet ports (that have the same subnet) to it and then add the IP address on the bridge interface. What you've done is a bodge at best and will certainly cause you problems in the long run.


How to implement tooltip in HTML 5 Canvas

Question:
I have drawn  this using HTML 5 canvas. I need to show a tooltip when I click on the user picture.
<code>    var kin = new Kinetic("myCanvas");

    kin.setStage(function(){
       var context = kin.getContext();
       kin.beginRegion();

       // draw rectangular region  including photo
       context.beginPath();
       context.rect(X + 50, Y + 50, 62, 72);
       context.closePath();

        kin.addRegionEventListener("mouseover", function(){
        document.body.style.cursor = "pointer";

        });
     }
</code>
Please help.
Answer: http://www.html5canvastutorials.com/advanced/html5-canvas-image-mouseover/
As far as a 'tooltip' - draw your text in a rectangle, or something suited to your design.
Then on mouseout, clear the region.
Comment: @MohammadUsman - Link as it stood when this answer was posted (6 years ago): https://web.archive.org/web/20111211050528/http://www.html5canvastutorials.com/advanced/html5-canvas-image-mouseover/
Comment: Link in your answer is broken.


Which hardware RAID 5+ cards have a true separation between Host CPU and controller CPU ops?

Question: For example, Windows talks with the 3Ware card as if it were a hard drive, and the 3Ware card takes care of writing content to the raid as an asynchronous process.  This frees up the CPU from disk operations.
Including 3Ware, what Server raid cards should I consider that truly separate raid operations from the server?  Contrary to popular believe, it's very hard to find cards that actually do this similar to 3ware.
Comment: "Contrary to popular believe, it's very hard to find cards that actually do this similar to 3ware." I strongly disagree. There's a reasonably obvious price difference between the hardware RAID HBAs and the fake-RAID (software based) impostors.
Comment: I agree. "Hard to find" means "clueless about the major brands". There are a handfull, well known.
Answer: Not sure it's hard at all, look at Adaptec, HP, IBM, Dell, Sun and LSI to name a few, they all make purely hardware driven disk controllers.
Comment: Just a remark: The Dell PERC 5/i, 6/i, H700, H800 and other Dell RAID controllers are revamped (OEMd) LSI RAID controllers.
Answer: pretty much any hardware raid card that has a BBU option.  Try LSI, Adaptec, most Dell PERC, Intel, HP, etc.


XMLs in C#, SimBrief XML

Question: I'm trying to extract the name of fixes of a flight plan from an XML file but cannot seem to get it to work. The XML link can be found in the code. The XML snippet is not the whole file there are other nodes and elements.
using System;
using System.Xml;
namespace SBDataTest
{
    public class Program
    {

        static void Main(string[] args)
        {

            XmlDocument fplxml;

            XmlDocument fplxml = new XmlDocument();
            fplxml.LoadXml("https://www.simbrief.com/ofp/flightplans/xml/KEWRMMPR_XML_1520819500.xml");
            var str = fplsml.Parse(fplxml);

            var result = str.Elements("fix").
                            Where(x => x.Element("name")).ToList();

            Console.WriteLine(result);
        }
    }
}

XML File
<?xml version="1.0" encoding="UTF-8"?>
<OFP>
  <navlog>
    <fix>
      <ident>PARKE</ident>
      <name>PARKE</name>
      <type>wpt</type>
      <frequency/>
      <pos_lat>40.683183</pos_lat>
      <pos_long>-75.076478</pos_long>
      <stage>CLB</stage>
      <via_airway>DCT</via_airway>
      <is_sid_star>0</is_sid_star>
      <distance>57</distance>
    </fix>
    <fix>
        <ident>TOWIN</ident>
        <name>TOWIN</name>
        <type>wpt</type>
        <frequency/>
        <pos_lat>40.535211</pos_lat>
        <pos_long>-75.400378</pos_long>
        <stage>CLB</stage>
        <via_airway>J6</via_airway>
        <is_sid_star>0</is_sid_star>
        <distance>17</distance>
    </fix>
  </navlog>
</OFP>

Comment: Can you clarify the elements or attributes your trying to access? Also put a snipet of the xml in your question so people do not have to click some random url please .
Comment: xml url gives a 404
Comment: @SoftwareCarpenter just added
Comment: @shamanthGowdraShankaramurthy Just ignore that for now
Comment: What exactly is the issue you are finding ? At a guess I'd say its because "fix" is not an immediate child of the root element, but you are querying the Elements() of the Root
Comment: I get "the name Xelement does not exist in the current context" @PhillipH
Answer: Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            new Navlog(FILENAME);
        }
    }
    public class Navlog
    {
        public static List<Navlog> logs { get; set; }

        public string ident { get; set; }
        public string name { get; set; }
        public string type { get; set; }
        public decimal? frequency { get; set; }
        public double latitude { get; set; }
        public double longitude { get; set; }
        public string stage { get; set; }
        public string airway { get; set; }
        public string star { get; set; }
        public int distance { get; set; }

        public Navlog() { }
        public Navlog(string filename)
        {
            XDocument doc = XDocument.Load(filename);

            Navlog.logs = doc.Descendants("fix").Select(x => new Navlog()
            {
                ident = (string)x.Element("ident"),
                name = (string)x.Element("name"),
                type = (string)x.Element("type"),
                frequency = (string)x.Element("frequency") == "" ? null : (decimal?)x.Element("frequency"),
                latitude = (double)x.Element("pos_lat"),
                longitude = (double)x.Element("pos_long"),
                stage = (string)x.Element("stage"),
                airway = (string)x.Element("via_airway"),
                star = (string)x.Element("is_std_star"),
                distance = (int)x.Element("distance"),
            }).ToList();
        }

    }
}

XMLs in C#, SimBrief XML


C puts() without newline

Question: I currently have this program that prints a text file on the console, but every line has an extra new line below it.
if the text was
hello
world
it would output
hello
world
the code is this
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    FILE* fp;
    char input[80], ch = 'a';
    char key[] = "exit\n";
    int q;

    fp = fopen("c:\\users\\kostas\\desktop\\original.txt", "r+");

    while (!feof(fp)) {
        fgets(input, 80, fp);
        puts(input);
    }
    fclose(fp);

    return 0;
}

Comment: Isn't `iostream` a C++ -only library and `using` a C++ -only keyword?
Answer: Typically one would use fputs() instead of puts() to omit the newline.  In your code, the
puts(input);

would become:
fputs(input, stdout);

Comment: I'm glad I found this answer, as I didn't want to have the overhead of `printf`
Comment: You could use printf() as well, but with a small amount of added overhead :-)
Comment: The `printf("%s", s)` has to parse the format string, which is definitely less overhead than a system call - but have you *seen* the code for parsing the format string?  That's definitely overhead.   q.v. https://code.woboq.org/userspace/glibc/stdio-common/vfprintf-internal.c.html
Comment: @AlexNorth-Keys if you printf with newline, gcc will turn it into puts. https://godbolt.org/z/784dEvnjP
Comment: In fact, `printf("%s", s)` have no overhead over `fputs(input, stdout)`, but `fputs` looks clean.
Comment: Well, wait long enough and gcc might turn it into some more efficient quantum computed thing.  Compiler magic marches on, although this often impedes debugging.
Comment: But it won't when using `printf("%s", ...)` without a newline, which was the original question: https://godbolt.org/z/h4jWeobY6

So `fputs(s, stdout)` really is the right answer here over `printf("%s", s)`.
Answer: puts() adds the newline character by the library specification. You can use printf instead, where you can control what gets printed with a format string:
printf("%s", input);

Comment: That "%s" instead of just using "printf(input);" is critical, lest any percent signs in input crash your program.
Comment: calling printf with "%s" is less efficient than fputs, but you probably don't care
Comment: @portforwardpodcast Compiler do change printf("%s",sting) to fputs(string,stdout), when you enalbe optimization, at least gcc does this. Some compiler maybe change it to fwrite() which is faster when you know the string lenght.
Comment: Why not just use the answer below?
Comment: @12431234123412341234123 when did it do that? I don't see this transformation being done with any version of GCC I have available.
I think the main issue is getting the stdout at the point of optimization.
Comment: @DanM. You are correct, my example was wrong, but in case when you have `"%s\n"` as format string gcc will replace it with `puts()`. Try to compile `main(){printf("%s\n","");}` with `gcc `.
Comment: @12431234123412341234123 but this question is about no newline specifically ;P
Answer: You can also write a custom puts function:
#include <stdio.h>

int my_puts(char const s[static 1]) {
    for (size_t i = 0; s[i]; ++i)
        if (putchar(s[i]) == EOF) return EOF;

    return 0;
}

int main() {
    my_puts("testing ");
    my_puts("C puts() without ");
    my_puts("newline");

    return 0;
}

Output:
testing C puts() without newline

Answer: This should work:
#include<stdio.h>
void put_s(char* s){
    while(*s) putchar(*s++);
}

Just for the sakes of having more examples, here is another one involving recursion:
#include<stdio.h>
void put_s(char* s){
    if(!*s) return;
    putchar(*s);
    put_s(s+1);
}

Note: I noticed that your code wouldn't compile, because of the #include<iostream> and the using namespace std;.
Comment: It works but could be quite inefficient if stdout is not buffered.

C puts() without newline


Why do I get the error 'list' object has no attribute 'update' when my for loop is too long?

Question: If I increase the number when the "for-loop" has to stop I get the error:  'list' object has no attribute 'update'. An example is: range(1000) instead of range(100).
That doesn't make any sense for me.
Could somebody help?
I need this code for school.
Here's the code:
import math
import operator

m = 1.60
t = 2.4

x_1 = 2
x_2 = 3
x_3 = 5
y_1 = 6
y_2 = 8.9
y_3 = 11.5

dictionary_sum_f_m = {}

for i in range(1000):

    m += 0.1
    ###############################################
    y_Wert_th_1 = m * x_1 + best_t
    y_Wert_th_2 = m * x_2 + best_t
    y_Wert_th_3 = m * x_3 + best_t

    d_y_Wert_th_1 = y_Wert_th_1 - y_1
    d_y_Wert_th_2 = y_Wert_th_2 - y_2
    d_y_Wert_th_3 = y_Wert_th_3 - y_3

    f_1 = d_y_Wert_th_1 **2
    f_2 = d_y_Wert_th_2**2
    f_3 = d_y_Wert_th_3 **2
    sum_f_m = f_1 + f_2 + f_3
    ############################################

    dictionary_sum_f_m.update({m : sum_f_m})
    if i == 99:
       dictionary_sum_f_m= sorted(dictionary_sum_f_m.items(), key=operator.itemgetter(1))
       sorted_dictionary_sum_f_m = dict(dictionary_sum_f_m)
       best_m = list(sorted_dictionary_sum_f_m.keys())[0]
       print(best_m)

Comment: This has nothing to do with the length of your loop, and everything to do with the fact that you apparently assigned a `list` to a name that used to (and is supposed to) refer to a `dict`.
Comment: If you hit `i==99` you reset `dictionary_sum_f_m` to a list. Also, `best_t` is undefined and your code will not run for any range large or small
Answer: When i == 99, you convert dictionary_sum_f_m to a sorted list and never convert it back to a dict. dicts provide .update, lists don't. You don't actually need it to be a list anyway (you're looking for the key with the smallest value, and the rest of the sorting is unnecessary), so you could solve the problem with just:
if i == 99:
   best_m, best_val = min(dictionary_sum_f_m.items(), key=operator.itemgetter(1))
   print(best_m)

which leaves dictionary_sum_f_m untouched, and reduces O(n log n) sort work to just O(n) work to retrieve the minimum value.
Side-notes:

Your code reads from best_t but I don't see it defined; guessing you made a copy-and-paste error and omitted it, since you'd never reach the point where you saw the failure as written.

This
dictionary_sum_f_m.update({m : sum_f_m})

is an unnecessarily slow way to spell:
dictionary_sum_f_m[m] = sum_f_m

update is for bulk updates, usually with existing dicts; if you're making a one-item dict just to call update, you should stick to simple key assignment.


What are the characteristics of calliope/circus music?

Question: I'm drawn to the happy nature of calliope music that is used in carnivals, fairs, circuses, theme parks, etc. Also, it sounds exactly like video game music. Where does this type of music come from, is it jazz or ragtime or some other genre?
I'm wondering what are the main elements or characteristics of this style.
So far I have found: sounds a bit like ragtime, 2/4 march time, syncopation (?), improvisation, allegro (~125bpm), tremolos, alternating bass between 1st and 5th root of current chord, chromatics, walking bass, reduced range (usually 3 octaves) so chords are not as full.
I'm sure I'm wrong on some of these so please let me know what I'm missing. Here's an example of a very talented performer:
Comment: Most of the carnival/circus music that started traipsing through my brain after reading the title was in 3/4 time, particularly highlighting "oom pa pa" music.
Answer: You'll hear a calliope playing marches, ragtime, waltzes - anything that a brass band might play on a park or seaside bandstand (when it wasn't trying to be too 'arty' at least!)    An actual calliope will probably be calling customers to a fairground attraction, so it's going to play happy, upbeat music, or maybe something stirring and patriotic.
What's being played in the example is typical calliope music.  I think you can tell whether there's any unusual time signatures or harmonies.   Sometimes a calliope is imitated orchestrally by 'wrong note' harmony - notably in the overture to 'Carousel'.  But that's a reference to something a calliope does by accident.  They aren't INTENDED to be out of tune!
Carousel overture
But just as there's a 'sad clown' meme, there's a 'sad calliope' one.
This may be the most famous example:
Tears of a Clown
Comment: In the video of the guy playing, I think the main distinction was the alternating bass (between the root and the fifth of whatever chord he's playing), chromatics, and just playing really fast.
Comment: also I think he was mainly playing in 2/4 no?
Comment: The march/ragtime stuff could well be written in 2/4, yes.  The modern trend might be to notate in cut time. You can't tell which by listening!  He doesn't give us any waltzes (3/4), another fairground favourite.
Comment: I wasn't aware that one couldn't know if it's 4/4 or 2/4 just by listening. I got to research time signatures a bit more, thanks for that.
Comment: You might tell 2/4 from 4/4, though they're close cousins.  But cut time (the C with a line through it notation) and 2/4 are both '2 in the bar'.  No way to tell them apart aurally, other than making an educated guess which would have been more likely used in a given style at a given period.   But this is a notation thing.  You don't do notation!


Translucent StatusBar with dynamic ActionBar color in Android

Question: I'm trying to realize a translucent statusbar (so that my navigation-view is BEHIND the statusbar) but still like to change the color of my actionbar dynamically. Because of this, the statusbar color needs to change to a darker version of my actionbar color.
If I set my statusbar to transparent, as many sources suggest, my primary_dark color is used as the background of my statusbar. However, as I will change the actionbar color during runtime, primary_dark must not necessarily be the dark color of my actionbar.
If I set my statusbar to the actionbar color, the transparency is gone. If I set my statusbar to the actionbar color and add transparency, the statusbar looks neither wrong nor right and my overlapping navigationview is still not very 'transparent' / 'colorful'.
Google Inbox has three separate colors: Inbox (blue), Snoozed (yellow) and Done (green).
What can I do to achieve this behaviour?
Answer: Actually, it's fairly easy to implement.

First step - is to change height of the Toolbar:

change height to wrap_content

so for me it looks like this:
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

Then you override resources for v19:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>

    </resources>

Then, in the Activity, setting padding for the Toolbar:
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
    ......
    ......
    public int getStatusBarHeight() {
        int result = 0;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = getResources().getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

And actually, it's pretty much it. Now once I want to change colour of the Toolbar, I'm calling this:
    if (getSupportActionBar() != null) {
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
    }

The activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="false"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

NB! On pre-Kitkat OS-versions, status bar remained the same, non-translucent.
I've uploaded the source code of the test-application to my dropbox - feel free to check it out.
I hope, it helps
Comment: Please, a question: why the trick of an extra View under the StatusBar for KITKAT?
Comment: Thanks Konstantin, I will have a look after work! However: You did not mention any NavigationView-related code. Is the NavigationView BEHIND the statusbar in your example?
Comment: @Frame91 My pleasure! NavigationView in my case is below the statusbar: http://i.stack.imgur.com/B3d9G.png Do you need it to be like that?
Comment: Updated the answer with a link to the test-application (it has navigation drawer and buttons to switch colour)
Comment: Thanks Konstantin, I need it exactly like you have it ;) I'll mark your answer as accepted and assign you the bounty as soon as I can reproduce it ;)
Comment: @GPack , Frame91 - my bad - with small modification (false) works like a charm on KitKat also. Updated code & test-app in dropbox.


What is chord Dm5b

Question: I have some notes in c minor, with chord notations. One of the chords is written as "Dm5b" and I'm wondering what that chord is. My logic would suggest d minor with the fifth lowered by a half note, but that would be D dim, and clearly there are such chords in the notes written as "H0" for example (this is a Hungarian note, and we use the German style notation, writing B as H).
Edit: attached the note.
Comment: If you can add a picture of the scan it might help someone pick up any other clues...
Comment: How professional is the notation? It may just be a misspelling of Dm7b5 or Ddim.
Comment: It seems to be a scan of a printed note. Clearly not handwritten or sg like that.
Comment: Would s and is be flat and sharp? If so, why not use the normal signs?  One gets used in the chord in question.
Comment: It seems pretty clear even from the missed second chord on the first measure that the chords were only given secondary, passing consideration here.  Unfortunately, that seems to be the norm on many published works, and errors and typos abound above the staff line, even on professionally produced scores.
Answer: I reckon it's a misprint, and should be Dm7b5. The dots indicate F, D, Ab and C. The rest of the run fits too, apart from the passing Eb. Dm5b isn't common (in UK at least), and had it merely been D F Ab, yes it should be Do.
Comment: @CarlWitthoft - you should read my answers more! Yes, on Mars, it's the accepted way to refer to them. In U.K. too ! isn't that what a lot of them resemble? Possibly not as appropriate in U.S. English - may sound like 'darts'?
Comment: I just call them "notes," since that's what they are :-) .
Comment: Interesting -- I never heard of printed notes described as "dots."  is that common in your regions?
Comment: interesting idea, that would make playing music the same as connecting the dots.
Comment: @CarlWitthoft - 'notes' are what I've written at the side of the music - conductor directions, changes in dynamics, etc...
Comment: @Tim  'Because you  know sometimes words have two meanings"   :-)
Comment: @CarlWitthoft - I am aware, and I can't think what the word is - for them! However, my way, I get to use different words. I'm happy that way. Homonym sounds about right.
Comment: @Tim - You missed the cultural reference :-(
Comment: @CarlWitthoft - I did, and still am missing . I'm not usually too thick - just help them out when they're short. Enlighten me, please!
Comment: @tim  Stairway to Heaven
Comment: @CarlWitthoft - I've looked upwards for a while, and still not got it...
Comment: @Tim   Led Zeppelin?  You never heard of them?  Or just trying to see how far you can fool me ?   :-)
Comment: @CarlWitthoft  I'm having a bad day. 'Course I know L.Z.  and Stairway to Heaven. What I've missed is the relevance.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/77331/discussion-between-carl-witthoft-and-tim).
Comment: isn't that like half-diminished D chord?
Answer: Dm5b would contain D, F, Ab
b means a - so it would mean a m5-
Comment: It does contain those notes. It also, in the dots, contains enough others to produce Dm7b5. A b sometimes may mean -, but that doesn't answer the question. And more usually, it's written Do, which could translate into Dmb5, meaninglessly. And, if you'd spotted the C note, it then becomes Dm7b5. -1.

What is chord Dm5b


Etymology of word "Octave"

Question: How come the etymology of the word octave is related to the number eight, when the numbers that you would associate with the meaning of the word are either two – doubling of the frequency – , or alternatively five, seven, or twelve, if we think about the number of notes within commonly used scales, starting from any note and stopping one octave higher?
Etymology dictionaries don't help as they simply point out the Latin root of the word - Related to the number eight – and also the Wikipedia article doesn't seem to mention anything about this.
My question is thus about why the number eight is anything special in dividing up one cycle of unique pitches , since it ("8") is only relevant for the diatonic scale , which is itself salient only in western cultures, and even there with strong competition from other scale types such as the chromatic or pentatonic. Why, then, is the interval that doubles the pitch not called a pent for instance?
Comment: "as they simply point out the Latin root" you mean "ocatvus" meaning the 8th as in it is the 8th note?
Comment: The frequencies have very little to do with it.
Comment: @phoog: Indeed. My comment was intended to address mathreadler's statement above that there are eight whole tones in an octave, which plainly there are not.
Comment: Choose a scale, start on it's root, or 1st, note. Move one step up the scale 7 times. Those are the second, third, fourth, fifth, sixth and seventh notes. The next one is called the eighth, or octave.
Comment: @mathreadler: There are not eight. There are twelve half-tones, so six whole tones in an octave.  If you play random notes taken only from a whole-note scale, you'll probably recognize it as the musical cue that indicates "this character is dreaming", or "we're going into a flashback" or some such, from early TV shows.
Comment: @EricLippert you're counting intervals rather than pitches.  There are twelve semitone intervals in an octave.  But if you play a chromatic octave scale, you'll play thirteen pitches.  Similarly, there are seven (variously sized) diatonic steps in an octave, but if you play a diatonic octave scale, you'll play 8 pitches.
Comment: @EricLippert yes I understand.  I wanted to call that out because there's a good deal of ambiguity in the terminology that doesn't distinguish adequately between pitches as zero-dimensional points and intervals as one-dimensional distances, and many of the statements here are suffering from that ambiguity.
Comment: There are 8 whole tones on one octave. Octa is latin for eight.
Comment: @EricLippert You are welcome. That is the least I could contribute. Don't you think?
Comment: The same etimology as octopus  and octagon , eight in latin.
Comment: Yes doubling of frequencies - all musical intervals can be defined as frequency ratios but this isn't factored into their names. Interestingly in Electronics Engineering a doubling of frequency is also called an octave, even if the signal is not audio. We have "harmonics" too, also borrowed from music (the Octave being the 2nd harmonic b.t.w)
Answer: It's because in music, when you're talking about intervals, you count the first note, all notes in between, as well as the final note. For example, if you play two notes that are right next to each other, the interval is a second - even though the second note is just "one note" away from the first. In fact, if you play the same note at the same time, it's called a prime, even though there's no distance between those two notes. A third is only two whole notes apart, a fourth only three, and so on. And the same way, an octave is only seven whole notes apart.
Comment: +1, this point was somehow missed in the other answers. The only thing that's new with the octave is that the _English_ interval names suddenly drop from counting in English to counting in Latin: "... fifth, sixth, seventh, octave, ninth ..." But some other European language uses Latin names throughout for these intervals, eg. German: "... Quite, Sexte, Septime, Octave, None ..."
Comment: This is the answer.  It should be noted that this method of counting appears in other contexts as well, such as the French expression *quinze jours* for "two weeks," and indeed [the use of *octave* in the Christian calendar](https://en.wikipedia.org/wiki/Octave_(liturgy)).  See also https://en.wikipedia.org/wiki/Counting#Inclusive_counting.
Comment: @HenningMakholm some of the German names are wrong, it is "Qui**n**te" and "O**k**tave".
Comment: @EricLippert correct.  An octave has seven diatonic scale degrees, however; some of those are semitones.
Comment: Just a guess, but doesn't "octava" predate the introduction of zero as a concept?
Comment: It might be a little confusing to use "whole note" here, as some of the intervals are half steps, depending on the mode.  Maybe "notes of the scale" or "scale degrees" instead, as in Basstickler's answer?
Comment: An octave is not seven whole tones. It is six.  Count on a piano: there are 12 half-tones in an octave, so there must be six whole tones.
Comment: @theREALyumdub indeed, Wikipedia [says](https://en.wikipedia.org/wiki/0#Transmission_to_Europe) " Until the late 15th century, Hindu–Arabic numerals seem to have predominated among mathematicians, while merchants preferred to use the Roman numerals. In the 16th century, they became commonly used in Europe."  In the 11th century, [Guido d'Arezzo](https://en.wikipedia.org/wiki/Guido_of_Arezzo) was using inclusive counting, for example the Greek *diatesseron* for the perfect fourth, where *four* is *téssera* in Greek *(τέσσερα).*  The concept probably existed earlier than the 11C, of course.
Comment: @phoog With the caveat that it was used elsewhere, but not yet where the octave was being described. Of course! This could make a nice historical answer someone should write, a shame this has turned out so real time...
Comment: It can be helpful to notice how inclusive counting — while strange when described as "number of steps from X to Y" — arises very naturally from *ordinal* counting. In a rising C major scale, C is the *first* degree of the scale, D is the *second* degree, E is the *third*, and so on, up to the C an octave above, which is the *8th* degree of the scale.
Comment: @Jim Garrison The system we use is originally from India I believe and was the first to include a zero concept to my knowledge. It's introduction was several centuries after Jesus, maybe latest 800AD, and well after Pythagorean tuning. My music history knowledge isn't great, but unless the octave started with the western music system it's probably far older than zero.
Comment: @rexkogitans: Indeed -- the editing timeout had run out before I noticed.
Answer: The term "octave" originated in the west, so it should be no surprise that it's based on features of western music. And the diatonic scale really is central in western music, as evidenced by the fact that a piano has eight white keys in an octave, and the notes are named by seven different letters, modified by sharps and flats (with the eighth note in the octave repeating the letter of the first). Other answers have made similar points with more sophistication, but I thought it would be good to have those two points up at the front of an answer.
Comment: Exactly this. OP seems surprised that the word would be based on Western musical conventions, but it's a Western word so why not!
Comment: "The notes are named by eight letters", erm, A,B,C,D,E,F,G - I count 7
Comment: @Rodney, well, Germans have H, but it's only to complicate the matter :)
Comment: @Rodney - I never thanked you for the correction, even though I fixed it based on your comment. Apologies and a belated thanks.
Answer: The octave would be the eighth note. There are seven scale degrees and if you take an additional step, you will land on the octave.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/84884/discussion-on-answer-by-basstickler-etymology-of-word-octave).
Answer: An octave is the space, pitch wise, which can be divided into eight. With seven intervals between. Take the octave C-C. C D E F G A B C eight notes later we're back on C.
You certainly wouldn't say 'octave of C is B', surely? The first C is not no. 0, like the start of a ruler, or a stopwatch. It's 1.
Comment: In fact this answer is worded badly. The octave is divided into seven diatonic interval, that stand between eight diatonic notes.
Comment: Of course - but that still assumes that the diatonic scale, with its 7 - 8 if you count the same note reached again - is the only way to divide the doubling-of-frequency space, or at least the most salient, whereas I would suspect it wasn't at the time when the meaning of the word came into use, not even in the Western world!
Comment: It's my understanding that at the time of developing the scales, which were derived from simple ratios, there were 7 notes per octave, so the eighth was named based on the word for 8.  There are plenty of ways to divide the octave but at the time the term was invented, there was really only the one approach.
Comment: "An octave is the space, pitch wise, which can be divided into eight". I don't understand this explanation. As you said, there are seven intervals inbetween.
Comment: Well in that case this would be a very obvious explanation as to the link between the number 8 and the physical concept of octave. I didn't know this was the case – many thanks for your contribution
Comment: "[Counting in] music is not baseball." -- my MT teacher
Comment: @Simone- I know what diatonic notes are, but not diatonic intervals.
Comment: Diatonic intervals are the intervals in a diatonic scale.
Comment: @Tim It may not be an accepted term. I've used it just to explain.
Answer: A lot of the musical terminology is in Italian. Partly because of the modes that come from Gregorian music (~9th century from the Roman Catholic church), the precursors to the modern day scales, and Renaissance (starting around 14th century) where Italy was prominent. A lot of musical dynamics are in Italian (Allegro, Piano, Tremolo, Calando ...), pitch registers (Soprano, Alto, Basso, ...) and music classifications (Concerto, A Cappella, Aria, Opera, Serenata, Sonata ...)
In this case it is just the index of the notes of the conventional scale, 1st, 2nd, 3rd ... 8th, in Italian.
Primo (C)
Secondo (D)
Terzo (E)
Quarto (F)
Quinto (G)
Sesto (A)
Settimo (B)
Ottavo (C)  <--- Octave
Since scales came from Gregorian Modes much earlier than Renaissance, it is probably the case that the monks at that time used Latin for formalising music structures (especially since the chants themselves are in Latin). So the modes themselves were probably in Latin, while more recent scales in Italian (not sure about the historical accuracy here). But in either case the etimology is the same. (Octavus instead of Ottavo).
Comment: This is a nice answer, but can you expand on it a little bit? What language is this for example?
Comment: @Shevliaskovic Added some more detail. I had wrote it partly with tongue in cheek because I thought it was too obvious (since other classical music terms are all in Italian) but it was a wrong assumption.
Comment: I lime this answer more that the top one! thanks!  Oh, and I suppose also Latin plays an important role as noted in @HenningMakholm comment of the "top" answer.
Answer: Your argument is, then, why is is not a "hexave" instead of an octave in the case of, say, a pentatonic scale and not a diatonic scale?
That is because in the standard western system, a pentatonic scale is represented with note names that correspond with the idea of the diatonic scale. It is more correct to say that, calling it an octave and using diatonic names is an approximation applied unto other scale types, for the sake of keeping talk about music the same.
It would otherwise be chaotic if, say, you have a pentatonic scale written C-D-E-A-B-C and a diatonic scale C-D-E-F-G-A-B-C, and the only notes on which people can agree on the sound on are then C, because they are at similar frequency intervals, but none of the degrees are agreeable.
It makes more sense to keep to a standard, if you will, so that music discussion is always on the same page. Given that the western standard of music revolves around the diatonic, when talking about music from a western perspective, it would make more sense to describe the pentatonic in terms of the diatonic, that is, assuming the Major Pentatonic scale, what would have been C-D-E-A-B-C in its own pentatonic format would be represented as C-D-E-G-A-C in the western standard, aligning the pitches of the diatonic and the pentatonic. Therefore, the "hexave" is the same as the octave, so for simplicity's sake, we refer to it as just the octave instead.
Answer: There are two ways of counting a range of things: inclusive counting, and exclusive counting.  "Exclusive counting" is where the first element of the range isn't included: "Monday + 3 days = Thursday".  "Inclusive counting" is where the first element is included: "Monday + 3 days = Wednesday".
The English language uses exclusive counting for almost everything, where the Romance languages use inclusive counting.  English music terminology comes from the Romance languages (mostly via French), and thus the range terminology reflects inclusive counting: "C + 8 notes = C", hence "octave".
Comment: Actually, it's not a question of inclusive/exclusive counting at all.  It's that the first is the first rather than the zeroth.  C + 7 notes takes us from the 1st to the 8th.  The name comes from the 8th, not from the number of steps between 1 and 8.
Answer: If you know some computer programming languages, note that in some of them the arrays begin with the index 0 and in others with 1. I'd say the way we count intervals is one-based, that's all :P If you count in one direction until you find the same note, you get the number 8.
Comment: You might want to read the other comments on here. My question was precisely why the number eight is anything special in dividing up one cycle of unique pitches , since it ("8") is only relevant for the diatonic scale , which isitself salient only in western cultures, and even there with strong competition from other scale types such as pentatonic. Why then is the interval that doubles the pitch not called a pent?
Comment: Oh, ok! It's a music history question then, if I understood it correctly. "Why diatonic scales became so important throughout history?" Because you could make the same question with all intervals: Why the interval of 5th is equal to such distance, why the word "3rd" is allowed to such and such distances, etc.
Answer: I don't have a source for this, but it seems self-evident to me that the context in which this term was developed was not an environment in which "pent" was a contending alternative - nor "sept", twelve, or any other number of scale degrees.
You seem to want to deny the saliency of the Western system, and the relevancy of the diatonic scale. You do make the valid point that today chromatic and pentatonic scales could arguably be "strong competitors" against the diatonic, but for one thing that wasn't true in the time and place when the expression "octave" came about, and for another the competition developed within the Western system in a context in which the term "octave" had already long since been defined. With the possible exception of very early Greek musical analysis, I (again unsourced) just cannot imagine a time when anyone talking about a chromatic scale or a pentatonic scale would have seriously considered trying to ignore the traditional diatonic modes in describing those scales.
The answer to your question seems to be, the reason we use the term "octave" even when "it's not all about the notes of the diatonic" is, at the time the term was developed, it was - and it has not stopped being useful within more-recent developments which use scales of some number of degrees different from the diatonic. People know what it means, people know why it means what it means, it would be asking more of them to throw it away and make up a different term than it is to just ask them to keep talking about "octaves" in the context of non-diatonic scales.
Answer: I've no idea if this is just an accident, but there is a very real physical connection between octave and eight. It is via the natural harmonics of a pipe, which of course are what a brass player selectively excites (and slightly "bends" into tune, if possible given the physical constraints of his instrument and his skill). The harmonic series can be expressed, approximately,
C  C' G' C'' E'' G'' Bb'' C''' D''' E''' F''' G''' A''' Bb''' B''' C'''' (and then sixteen further harmonics up to C''''' and onwards to infinity with double the number of further harmonics in each octave, largely theoretically)
The bottom octaves of the harmonic series are actually rather hard for a brass player to produce in a musical sense. They tend to sound like flatulence. So on an un-valved brass instrument one can play C'' E'' G'' Bb'' and then (perhaps) all notes of the scale in the next octave up. Above C''', C'''' is the 8th subsequent natural harmonic. Hence, octave?
NB the mathematical frequencies of all these harmonics except for Cs and Gs are somewhat out of tune compared to the even-tempered musical notes. This is where a brass player's skill comes in, to bend the notes into tune. Some need more bending than others. On an instrument with valves, there are of course multiple harmonic series to choose between, so fingering can replace the need to bend hard-to-bend notes.
You can research the history of early music, where the concept of keys and modulation was fighting with the natural harmonics which give perfect fifths and fourths.
Comment: This is indeed pure speculation. The octave formally comes from the division of the scale, into 8 notes. Most modern musicians (and probably ancient) would consider C''' **three octaves** above C. The doubling of pitch appears more accidental.
Comment: The D harmonic is pretty close to an equal-tempered D, being only about 4 cents sharp -- or rather the equal tempered 9th is about 4 cents flat, acoustically.
Comment: @theREALLyumdub but the division of the scale into eight notes is strongly related to the harmonic series, and the term octave goes back to early music before the advent of even tempering. There are other musical traditions, f.ex Indian, which do not use Western 7- (not 8) or 12-chromatic note scales.
Comment: I have to agree with @theREALyumdub.  If the 7-note diatonic scale were truly derived from the harmonic series, the notes wouldn't be so badly out of tune with it.  For example, if you apply Pythagorean tuning principles to the medieval hexachord system, b-flat:c comes out at 16:9 rather than 7:4.  It looks to me more like the tuning of the scale was altered for acoustical reasons (therefore becoming a closer fit to the harmonic series) as harmony became more important in the middle ages.
Comment: I think the only certain thing is that it goes back to the 12th century, and probably before. I was going to add that in German, B-flat is known as B, and B as H. But apparently on ancient manuscripts, flat and sharp were indicated by writing the note slanted backwards or forwards, and hence modern flat and sharp symbols. But a forward-slanted B in the script of the times looked  like an H and it stuck. So says wiki. Another mere coincidence with the harmonic series? And then there's the modern melodic minor key which uses both seventh notes...?
Comment: @nigel222 it's not so much slanting backwards and forwards as being a square B (which became H in Germany) or a round B.

Etymology of word "Octave"


Redirect all incoming mail to another user

Question: Preferably this could be done with a virtual instance of a mail server on an existing Linux machine but I'm willing to run a whole other install (Linux or Windows) to get this to work.
Basically a system we use generates emails to customers when we do certain things. On the testing setup, we regularly import a full live snapshot to test reports etc. The problem is that this can end up with us sending incorrect emails to our customers.
My goal is the specific a different mail server on the server which would accept all mail, then redirect it back to the dev team. Best I can come up with is creating catchall address forwards for every domain of every customers. There must be a better option though?
Machine will not be internet facing so spam is not a risk on this.
Edit: There a multiple customer address domains. Any catchall solution would need to not be domain specific. The from field also varies depending on the user logged in or section of the system.
We also need to see the emails which is why they are being redirected.
Answer: As towo pointed out, address rewriting is one way. Exim also has a nice framework for this:
http://www.exim.org/exim-html-3.30/doc/html/spec_34.html
BTW, what you want is often referred to as a "catchall" address. That might help in googling a config for your chosen mailserver.
You might also consider modifying your test system to dump mail to a file instead of sending it. That avoids the hassle of having a special "test" mailserver which does the catchall thing; also you could easily parse the file automatically to decide whether the test succeeded. Of course, might not be an option to change the system under test...
Comment: Catchall addresses are a *bad* idea. It won't be long before your domain is flooded with spam messages, since to the spammers every email they try will appear to be valid.
Comment: @Kamil: In principle you're right. But read the question: "Machine with not be internet facing so spam is not a risk on this.".
Answer: Most mail servers support rewriting addresses or changing delivery method base on some metric over the input mail. You could either rewrite all outgoing addresses with a local user, or just change the delivery method to dump it unceremoniously into a file.
If you're using postfix, for example, there's a rather thorough documentation available, even though it does not specifically list your case.
Comment: The rewriting all comes in from of from -> to. I've yet to see it handle a * -> to although I don't it can do *@domain -> to.
All these addresses a fully valid addresses that I need changed.
Answer: As a thought, your test setup of your app will have a different IP then the production one correct?
Could you setup your existing mail server so that all email from IP xyz get redirected to user abc?
This lets you keep your test app exactly the same with only mail server changes now.
Comment: Any idea what this would be called?
Answer: I would assume those emails are being sent from the one account. Is it practical to temporarily have your mail server refuse mail from that account for the duration of the tests?
Answer: I'd suggest using sieve for your needs, since it's not tied to a particular MTA. We use it extensively to filter/block for ourselves and our customers.
Answer: I'm looking for something similar to use as an SMTP server in a test environment. So far I've found subethasmtp, Devnull SMTP server and Dumbster, but I haven't had opportunity to test any of them yet.
Ideally I'd like something with a web interface to review and manage the emails it received.


Converting Base64 to data returning nil

Question: I am trying to convert base64 string to image, I checked the json response, base64 string is not empty, but Data returns nil in between.
let base64String = image.Image_bytes_1
var data = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters)
let image = UIImage(data: data! as Data)
imageView.image = image

at line#4 getting this below error

Thread 3: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
Comment: `base64` string in the json may not be empty, but what happens here `image.Image_bytes_1` is probably returning a `nil`. Put this in an `if-let` like so `if let base64String = image.Image_bytes_1` and then process `base64String` .. I don't think you will enter the block. Debug what happens in `Image_bytes_1`.
Comment: and were you able to verify that the base64 string is a valid image ?
Comment: i checked it, thats not empty
Comment: it is strange that you don't get a compiler error or at least a warning
due to using `image` in `let base64String = image.Image_bytes_1` and then
re-declaring the same name as `let image = UIImage(data: data! as Data)`.
Try `let myImage = UIImage(data: data!)` and `imageView.image = myImage`
Comment: @workingdog : no error if the first image is declared at outer level (struct property for exemple). But I agree that it is not good for maintenance to have multiple object with the same name.
Comment: What is line 64 ?
Answer: The Data initializer you are using, init(base64Encoded:options:) is declared as init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = [])
That's known as a "failable initializer", which means it can return nil. (note the question mark after init in the declaration.)
If the base64 data is not well-formed, it may fail and return nil.
Stop using force-unwrapping. Rewrite using optional binding:
if let base64String = image.Image_bytes_1,
   let  data = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters),
   let image = UIImage(data: data) {
      imageView.image = image
} else {
      print("Unable to load base64 data and convert to image")
}

Edit:
As workingdog pointed out in their comment, your code does not make sense:
let base64String = image.Image_bytes_1  // line 1
var data = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters) // line 2
let image = UIImage(data: data! as Data) // line 3
imageView.image = image // line 4

Line 1 references something called image. You don't show the code that declares it, so we don't know what it is.
Then in line 3, you declare a new local constant also named image. If the original image is an instance variable of your class, and the code you posted is inside a function, you are creating a new local variable that overrides the other variable called image. I strongly advise against using the same variable name in different levels of scope. That is confusing at best, and causes errors at worst.
Comment: (If one of those steps is failing and you can't tell which one you might need to rewrite it as a series of guard let statements with separate print statements that tell you which step failed.)
Comment: Brother i got crash in line#4
Comment: The lines in the code I posted are not numbered. Which one is line #4? The `imageView.image = image` bit?
Comment: I am referring to my question
Comment: If that line is crashing then perhaps `imageView` is an `IBOutlet` that's declared as implicitly unwrapped? (`@IBOutlet var imageView: UIImageView!` (The exclamation point after the type makes it implicitly unwrapped.) Check to see if `imageView` is nil. If it is, that's another problem to solve.
Comment: Don't use line numbers to talk about code that does not include line numbers. It's confusing. Are you referring to the line (in both your version of the code and mine) that reads `imageView.image = image`?

Converting Base64 to data returning nil