Transitioning from music theory to composition

Question: I have a good foundation in music theory (ABRSM grade 7 and currently studying grade 8) but don't know how to begin when composing my own works. My main emphasis is Baroque music.
Are there any resources that teach composition one form at a time for total beginners? And what form (fugue, chorale etc.) is best to start with?
Comment: definitely don't start with fugue
Answer: There is a book called 'Figuring Out Melody' by David Fuentes.
While it does not work progressively through the various forms, it does offer a very clear approach to writing music and focuses on JS Bach.
The book used to be a free download, but it looks like that download isn't free anymore.
Here is a good preview of the content...

https://figuringoutmelody.com/for-courses/

Not specifically Baroque, but very, very clear sequential analysis of form from smallest to largest is Caplin, Classical Form...

https://books.google.com/books?id=PBYjpKypCskC

If Caplin is too dense - it really isn't for beginners - try starting with something like the following. These offer the typical overview progressing from small phrase units to the various larger forms.

https://books.google.com/books?id=b8FdaMJaWl0C
https://books.google.com/books?id=x7-hCwAAQBAJ

This book seemed to me a practical and concise text for contrapuntal forms...

https://books.google.com/books?id=IawYAQAAIAAJ

Truthfully, the best "textbooks" are real scores. Look at Bach's small preludes and fugues, Anna Magdalena's Notebook, and minuets and other dance sets from Mozart and Schubert. (All of those are available for free at https://imslp.org/.) Minuet sets are an especially good starting point, because sometimes the set consist of simple binary-form minuets (usually 16 bars) while other sets pair minuets and trios which of course brings you to the next larger formal scale: ternary. Look for the smaller scale works of the great composers and make sure to balance textbook reading with analysis of actual composer's works.
Answer: Writing music in a historical style, such as Baroque music, is largely a matter of theory, so I think you should be well-equipped enough to start. Most of the time (in my experience, all the time), a composition teacher will not want you to write Baroque music, since it is very far from cutting-edge.
I must confess that I don't know of any resources that teach one form at a time, and in fact, I don't know of anything that teaches any Baroque music aside from fugues. I agree with the above comment that says not to start with fugues -- there are easier things to start with. I also wouldn't get to fugues last, since they tend to be incorporated into longer works.
You mentioned chorales. I assume you have been harmonizing chorales for your theory studies, so that seems like a good place to start. Instead of harmonizing someone else's melody, you would write your own melody and harmonize that.
Another good place to start would be the dance forms (allemande, etc), since the general style and accompaniment are already set in place for you. Shorter forms, like French overtures, are also easier to write.  I find it easier to compose if I am locked in to a set of parameters. The blank page can be a little intimidating.
Your main resource is going to be other works by Baroque composers, who you probably know better than I do. If you get stuck, take a break and look at Bach or Vivaldi or whomever you prefer. See what they did or didn't do, and try to draw inspiration from that. Once you listen to enough of those composers, you start to develop an ear for their style, and in fact, one of my theory teachers told me something like, "To learn to write a fugue, you could go to a book about fugues, but you would be better off just listening to fugues until they make sense."
Mostly -- and I apologize for this fairly generic advice -- you just need to start composing now, and worry later about what order you should do things. People definitely compose with less theory knowledge than you have. Composition is a skill distinct from theory, and you might not be satisfied with your results at first, but just keep trying. Ideally, you would want to compose a little every single day, but I can't say I always do.
This reply has run a little long, so let me recap a little:
1) I don't know of any resources that go form-by-form, but the best thing to do is to listen to Bach et. al., and compose as often as possible.
2) Analyzing scores is probably more useful than any book.
3) If I were in your position, I would do something like: Chorales and other short-form works, then dances, then imitative counterpoint and longer works.
Comment: Thank you for your very helpful advice! I have indeed spent much time harmonizing and studying chorales, so writing my own melodies seems like a great way to start. Thanks again!


Listening for a boolean change with Javascript/jquery (Proxy object)

Question: Javascript Proxy not triggering. I am triying to trigger some functionality after 10 seconds. But after 10 seconds, when I update the variable "dezSecondsNaPagina" nothing happens.
var dezSegundosNaPagina = new Object();
dezSegundosNaPagina.valor = false;

var targetProxy = new Proxy(dezSegundosNaPagina, {
  set: function(target, key, value) {
    target[key] = value;

    if (dezSegundosNaPagina.valor) {
      console.log("aumentar visualização");
    }
    return true;
  }
});

$(document).ready(function() {
  setTimeout(function() {
    dezSegundosNaPagina.valor = true;
    alert(dezSegundosNaPagina.valor);
  }, 3000);
});

Answer: you should use targetProxy.valor = true; in setTimeout method.

var dezSegundosNaPagina = new Object();
dezSegundosNaPagina.valor = false;

var targetProxy = new Proxy(dezSegundosNaPagina, {
  set: function(target, key, value) {
    target[key] = value;

    if (dezSegundosNaPagina.valor) {
      console.log("aumentar visualização");
    }
    return true;
  }
});

  setTimeout(function() {
    targetProxy.valor = true;
    alert(dezSegundosNaPagina.valor);
  }, 3000);
Comment: A checked the snipped several minutes and that one passed by me.


How to call outside function in filter for RDD data

Question: Now I know for dataFrame, we could use udf, but currently I am handling RDD, data. Except to use on top function, how can I define a method used by filter in all methods in the class
<code>   def date_filer_help(date1, date2):
        date1_arr = date1.split("-")
        date2_arr = date2.split("-")
        for i in range(len(date1_arr)):
            if int(date1_arr[i]) < int(date2_arr[i]):
                return True
            elif int(date1_arr[i]) > int(date2_arr[i]):
                return False
        return True

    def date_filter(prev_date, date, end_date):
        return date_filer_help(prev_date, date) and date_filer_help(date, end_date)

rdd = sc.textFile(action_file).map(lambda x: x.split(','))\
    .filter(lambda x: date_filter("0000-00-00", x[0], "2016-06-30"))
</code>
I want to write date_filter as static in this class or other classes.Otherwise, in each method, I need to redefine two helps as above again and again.  But it does not work if I run in cluster, how should I do it ?
Answer: Do you mean this:
<code>class DataFilter(object):
    def __init__(self):
        self.sc = SparkContext()

    @staticmethod
    def date_filer_help(date1, date2):
        return date1 <= date2

    @staticmethod
    def date_filter(prev_date, date, end_date):
        return DataFilter.date_filer_help(prev_date, date) and DataFilter.date_filer_help(date, end_date)

    def run(self):
        rdd = self.sc.parallelize(
            map(lambda x: ((datetime.date(2016, 6, 25) + datetime.timedelta(x)).strftime('%Y-%m-%d'), x), range(10)))
        result = rdd.filter(lambda x: DataFilter.date_filter("0000-00-00", x[0], "2016-06-30"))
        return result.collect()

if __name__ == '__main__':
    print(DataFilter().run())
</code>
Comment: Now I realize , it is because I run the main in another file and did not sc.addFile.


Test question regarding graph theory - please check my work

Question: I had a test today and there was a question regarding graph theory. I want some feedback on my solution.

Let $K_{20}$ be a complete graph with $20$ vertices. The edges of the graph are colored in $9$ different colors. Show that there is a circle which all of its edges are colored with the same color.

My try: First of all, the graph is complete, hence there are $\displaystyle {20 \choose 2}=190$ edges. There are $9$ different colors, hence by the pigeonhole principal there are at least $\displaystyle \lceil{\frac{190}{9}\rceil}=22$ edges of the same color.
Now, every vertex is connceted by $19$ edges, hence by the pigeonhole principal there are at least $\displaystyle \lceil{\frac{22}{19}\rceil}=2$ edges that are connected to the same vertex and there are with the same color. By the pigeonhole principal we also know that there are at least $\displaystyle \lceil \frac{22}{20}\rceil=2$ vertices that the same edges are connected to them. The graph is complete, thus these two vertices has two commom neighbors, and if we connect all of these 4 vertices we get a circle with length 4 of which all edges are colored in the same color.
Is that good? thanks!
Comment: I wanted to write $\displaystyle {20 \choose 9}$
Comment: @MarkG K(n) has $n\choose{2}$ edges.
Answer: Your answer is right, but you can see it more easily by just forgetting the rest of colors. You already proved that there is a color where you have at least 22 edges
Now take any graph with 20 vertices and (at least) 22 edges, suppose it has no closed loops (so it's planar), then by Euler's theorem (faces + vertices = edges + 2) the number of faces is at least 4. So it has closed loops.
Comment: (by the same Euler's theorem you get that the max number of edges you can have without loops is 19)
Comment: I'm ashamed to admit I forgot this theorem. Thanks for a BEAUTIFUL answer!


html5 canvas text not the specified size

Question: When I specify the HTML5 canvas font as "50px Arial", I'd expect that every uppercase letter would have a height of 50 pixels. However, I'm getting a height of 35 pixels. I couldn't find anything at MDN. What am I missing?
I'm using Firefox Quantum 69.0 (64-bit), with layout.css.devPixelsPerPx property set to 1.

var cnv = document.getElementById('cnv');
cnv.width = 300;
cnv.height = 200;
var ctx = cnv.getContext('2d');
ctx.font = '50px Arial';
ctx.fillText('Test',100,100);
canvas {
  background-color:green;
  width: 300px;
  height:200px;
}
<canvas id='cnv'></canvas>
Answer: I doubled up your "Test" text exactly 50 pixels below the original, then superimposed a 50x50 image over the text and guess what?

Turns out ctx.font actually defines line height in pixels. Or at least, there is no distinction made between controlling line height and font size. I can't find a good explanation exactly as to why.
Using pt in place of px to style your font gives you something much, much closer to what you want.
Comment: How exactly did you doubled it up?
Comment: @Rodrigo Just repeat the code and change the coordinates. In this case,  `ctx.font = '50px Arial';
ctx.fillText('Test',100,150);`
Comment: Then it wasn't `ctx.font` but your coordinates that defined the line height.
Comment: I guess that wasn't the best way to show what I was trying to say. The line height is still defined by the `font` setting. If you want your letters to truly be an absolute size (and not just within a 50px line) then use `pt` instead of `px` when defining font size. Because as you say, a "50px" font only takes up around 35px.
Comment: I've read about `pt` and how it's based on an arbitrary fraction of an inch (1/72). My site is going to produce a PNG (thus measured in pixels). Although `50 pt` gave me a better approximation (uppercase 46 pixels high), I wonder if that's the way to go, instead of understanding the rationale behind `px`.


Can I change my sendmail port?

Question: I am having a problem sending mail through sendmail. I have configured sendmail and it is fine. I telnetd the localhost and it connects but when i telnet port 25 is says telnet: Unable to connect to remote host: Connection refused. Also the smtp server uses port 25 so is there any way I can switch sendmail to listen to another port. I am using ubuntu. I don't have much experience with the mail server configurations so please help me out.
Thanks
Comment: Oh, I didn't notice this was an old question that had been bumped up. Sorry for the noise :-)
Comment: So you have both Sendmail and another SMTP server running?
Comment: Thats exactly the way it is
Comment: If I may ask, why are you doing that? Postfix, the default Mail Transfer Agent on Ubuntu, is perfectly adequate for most purposes and usually easier to configure than Sendmail. Running two MTAs on the same server is also likely to cause problems unless you carefully configure both MTAs to avoid each other.
Comment: @telcoM Let's just say I was too naive at that time.
Answer: The default server on Ubuntu is postfix which provides SMTP services. It should be able to be configured to listen on any or all of the standard ports SMTP(25), SSMTP(465), and Submission (587).  The port used for any of these services should be reconfigurable.  Configuration should be in /etc/postfix.com and or /etc/postfix.d.  Check the configuration for a port string. man postfix.conf should give you documentation on the configuration.
The command aptitude install postfix-doc will install the postfix documentation package into /usr/share/doc/postfix.doc.
I use Exim4, which does allow the ports to be specified, instead of postfix.  You should only have one SMTP package installed.  The sendmail interface is provided by the Exim4, postfix, and sendmail packages.
Make sure you have an SMTP program running with the command netstat -lnt | grep :25.  This should return at least one line.
Unless you have a static address configure your server to use your ISP's mail relay as a Smarthost.  Your ISP may (should) be blocking outgoing connections to the Internet on port 25.  This is done to deal with spambots which often run on virus infected PCs.

Can I change my sendmail port?


Read a PostgreSQL local file into R in chunks and export to .csv

Question: I have a local file in PostgreSQL format that I would like to read into R into chunks and export it as .csv.
I know this might be a simple question but I'm not at all familiar with PostgreSQL or SQL. I've tried different things using R libraries like RPostgreSQL, RSQLite and sqldf but I couldn't get my head around this.
Comment: What is the purpose of breaking the data into chunks?
Comment: What is "`PostgreSQL` format"? I've never heard of that, and I've used PostgreSQL a lot.
Comment: @DanBracuk, the file size is 18GB so I would like to do this task in chunks to go around the memory limitations in R.
Comment: @bgoldst I guess this gives you an idea of how unfamiliar I am with PostgreSQL. The file I have is zipped with name "gps_PostgreSQL.rar". The file name is "gps_p.backup"
Comment: Are you updating an existing file or creating a very large one from scratch?
Comment: @DanBracuk I'm creating one from scratch.
Comment: You don't need to do it in chunks.  You can just use the PostgreSQL `copy` command to write it directly to a csv file.  See http://stackoverflow.com/questions/1120109/export-postgres-table-to-csv-file-with-headings
Answer: If your final goal is to create a csv file, you can do it directly using PostgreSQL.
You can run something similar to this:
COPY my_table TO 'C:\my_table.csv' DELIMITER ',' CSV HEADER;
Sorry if I misunderstood your requirement.
Answer: The requirement is to programmatically create a very large .csv file from scratch and populate it from data in a database?  I would use this approach.
Step 1 - isolate the database data into a single table with an auto incrementing primary key field.  Whether you always use the same table or create and drop one each time depends on the possibility of concurrent use of the program.
Step 2 - create the .csv file with your programming code.  It can either be empty, or have column headers, depending on whether or not you need column headers.
Step 3 - get the minimum and maximum primary key values from your table.
Step 4 - set up a loop in your programming code using the values from Step 3.  Inside the loop:

query the table to get x rows
append those rows to your file
increment the variables that control your loop

Step 5 - Do whatever you have to do with the file.  Don't try to read it with your programming code.
Comment: It won't be me.  I'm a ColdFusion programmer who read the question because of the sql tag.  The approach I suggest should work with any language and database engine.  Another approach I recommend is to do one thing at a time.  Finally, during development, work with small amounts of data.
Comment: thank you for your answer, where you have laid out the logic of the process. I would be grateful if you or someone could develop this in `R` code.

regarding step 1: I've seen some tutorial on how to write a `data.frame` into a SQL database, but I couldn't find how to do write the my local file into a SQL database.


LogitBoost R in package "caTools", which algo is it?

Question: What is the name, and where can i find documentation on the algorithm used in LogitBoost for the "one node decision trees"?
R, package = caTools
Answer: Looking at the documentation for LogitBoost, we find

The function was adapted from logitboost.R function written by Marcel Dettling. See references and "See Also" section. The code was modified in order to make it much faster for very large data sets. The speed-up was achieved by implementing a internal version of decision stump classifier instead of using calls to rpart. That way, some of the most time consuming operations were
  precomputed once, instead of performing them at each iteration. Another difference is that training and testing phases of the classification process were split into separate functions.

So I follow the instructions and look at the "See Also" section, which has this note

• logitboost function from logitboost library (not in CRAN or BioConductor but can be found at http://stat.ethz.ch/~dettling/boosting.html) is very similar but much slower on very large datasets. It also perform optional cross-validation.

So I follow that link and find this article: "Boosting for tumor classification with gene expression data" by Marcel Dettling and Peter Buhlmann and published in Bioinformatics in 2002. Of particular interest is the abstract, which describes the paper's contents in the following words

Motivation: Microarray experiments generate large datasets with expression values for thousands of genes but not more than a few dozens of samples. Accurate supervised classification of tissue samples in such high-dimensional problems is difficult but often crucial for successful diagnosis and treatment. A promising way to meet this challenge is by using boosting in conjunction
  with decision trees.
Results: We demonstrate that the generic boosting algorithm needs some modification to become an accurate classifier in the context of gene expression data. In particular, we present a feature preselection method, a more
  robust boosting procedure and a new approach for multicategorical
  problems. This allows for slight to drastic increase in performance and yields competitive results on several publicly available datasets.
Availability: Software for the modified boosting algorithms as well as for decision trees is available for free in R at http://stat.ethz.ch/∼dettling/boosting.html.

So this paper appears to be the origin of the algorithm used in the LogitBoost function.


Eigenfunction expansion of second order PDE with time dependent boundary conditions

Question: I want to solve this 2nd order PDE-
$$
u_t = K u_{xx} \\
u(x=0,t)=f(t) \\
u(x=L,t)=g(t) \\
u(x,t=0)=\phi(x)
$$
Based on this answer - Heat equation with time dependent boundary conditions?, I solved it and got the answer as mentioned in the question as far as I understood -
$$
u(x,t)=\sum_{n=1}^\infty u_n(t) sin(\lambda_n x) \\
\lambda_n=\frac{n \pi}{L} \\
u_n(t)=e^{-\lambda_n^2Kt}\int e^{\lambda_n^2Kt}F(t)dt \\
F(t)=\frac{2\lambda_n}{L}[f(t)+(-1)^{n+1}g(t)] \\
u_n(0)=\frac{2}{L}\int_o^L \phi(x) sin(\lambda_nx)dx
$$
What I don't understand is how does this solution satisfy the boundary conditions? At $x=0$, $sin(\lambda_n x) $ will always be zero and thus $u(x=0,t)=0$ instead of $u(x=0,t)=f(t)$.
I thought I understood the solution but I guess not and I don't know if I am doing something wrong entirely. Because no matter how I solve $u_n(t)$ and what the solution for that is, $u(x=0,t)$ is always zero.
Comment: I think the BC zero is the one of the modified function v in the original problem.
Comment: I am sorry I didn't understand what you mean. What do you mean by modified function v?
Comment: BC $$u(0,t)=f(t)\textrm{ write } u(x,t)=v(x,t)+f(t)\Rightarrow v(0,t)=0$$
Comment: We can do this directly? But in the answer this is not done
Comment: Yes I think there probably is a mistake.
Comment: Btw : why there is not a relativistic boundary condition : $u(x=\pm ct,t)=0$ if the particle were localized at initial time ?
Comment: There is also the problem that the added function is not unique, for example $u(0,t)=f(t),u(\pi/2,t)=g(t)\Rightarrow v(x,t)+f(t)+h(x)(g(t)-f(t))$ with any function $h(x)|h(0)=0,h(\pi/2)=1$.
Comment: I don't know about the relativistic boundary, but I solved the problem based on what you said, and separated the problem into a homogenous and inhomogeneous component and then used eigenfunction expansion to solve it
Comment: For example I obtained for SE with relativistic boundaries : $u(x,t)=\sum_{n=0}^\infty A_ne^{-\frac{i\hbar(2n+1)^2\pi^2}{8mc^2t}}\cos ((2n+1)\frac{\pi x}{2ct})$, the An are found by projecting on the initial state delta.
Comment: Could you write an answer on how you solved it? I got a very different answer. I am not sure what relativistic boundary conditions would do in this scenario but I could also write an answer to  show how I solved it
Answer: From @Cretin2's comment I figured what the original answer was missing was splitting the equation into homogenous and inhomogeneous parts.So I start with that:-
$$
u_t=Ku_{xx} \\
u(x=0,t)=f(t) \\
u(x=L,t)=g(t) \\
u(x,t=0)=\phi(x)\\
$$
$u$ is composed of a homogenous and inhomogeneous term, represented by $u_h$ and $u_{ih}$ respectively
$$
u=u_{ih}+u_h \\
\frac{\partial^2u_{ih}}{\partial x^2}=0 \\
\implies u_{ih}=c_1x+c_2 \\
$$
Substituting-
$$
u_{ih}(x=0,t)=f(t) \\
u_{ih}(x=L,t)=g(t) \\
$$
we get,
$$
c_2=f(t) \\
c_1=\frac{g(t)-f(t)}{L} \\
\implies u_{ih}=\frac{g(t)-f(t)}{L}x+f(t)
$$
Plugging this into the equation for $u$, we get,
$$
u=\frac{g(t)-f(t)}{L}x+f(t)+u_h \\
\frac{\partial u}{\partial t}=\frac{\dot{g(t)}-\dot{f(t)}}{L}x+\dot{f(t)} + \frac{\partial u_h}{\partial t} \\
\frac{\partial^2 u}{\partial x^2}=\frac{\partial^2 u_h}{\partial x^2} \\
\implies \frac{\partial u_h}{\partial t}=K\frac{\partial^2 u_h}{\partial x^2}+\frac{\dot{f(t)}-\dot{g(t)}}{L}x-\dot{f(t)}
$$
Let $\frac{\dot{f(t)}-\dot{g(t)}}{L}x-\dot{f(t)}=F(x,t)$ which is now the "source term"
$$
\frac{\partial u_h}{\partial t}=\frac{\partial^2 u_h}{\partial x^2}+F(x,t)
$$
with boundary conditions :-
$$
u_h(x=0,t)=0 \\
u_h(x=L,t)=0 \\
u_h(x,t=0)=u(x,t=0)-u_{ih}(x,t=0) \\
\implies u_h(x,t=0)=\phi(x)-\frac{g(0)-f(0)}{L}x-f(0)=\psi(x)
$$
To solve this PDE, I can now use eigenfunction epansion. If there was no source term, by using separation of variables we could solve $u_h$
$$
u_h(x,t)=\sum_{n=1}^\infty u_n(t) \sin(\lambda_n x) \\
\lambda=\frac{n \pi}{L}
$$
Where $u_n(t)$ is the time dependent factor of $u_h(x,t)$.
$$
\frac{\partial u_h}{\partial t}=\sum_{n=1}^\infty v_n(t) \sin(\lambda_n x) \\
\frac{\partial^2 u_h}{\partial x^2}=\sum_{n=1}^\infty w_n(t) \sin(\lambda_n x) \\
$$
where,
$$
v_n(t)=\frac{d u_n}{dt} \\
w_n(t)=-\lambda_n^2 u_n(t)
$$
Let $F(x,t)=\sum_{n=1}^\infty f_n(t) \sin(\lambda_n x)$
Wecan substitute all of these in the original equation and after some simplification we get,
$$
\frac{du_n}{dt}=-K\lambda_n^2u_n(t)+f_n(t)
$$
This is a simple ODE in $u_n$ which I solved by multiplying by an integrating factor to get -
$$
u_n(t)=e^{-\lambda_n^2Kt}\int_0^t e^{\lambda_n^2 K\tau}f_n(\tau) d\tau + e^{-\lambda_n^2Kt} c
$$
where $c$ is a constant of integration
$$
u_n(0)=0+c
$$
So we need to now find u_n(0) and f_n(t). We know,
$$
\int_0^L \sin(\lambda_mx)\sin(\lambda_nx) dx=0, m\neq n \\
= L/2, m=n
$$
we have,
$$
u_h(x,t)=\sum_{n=1}^\infty u_n(t) \sin(\lambda_n x) \\
\int_0^L u_h(x,t)\sin(\lambda_n x) dx = u_n(t) L/2 \\
u_n(0)=\frac{2}{L}\int_0^L u(x,t=0) \sin(\lambda_nx) dx \\
\implies u_n(0)=\frac{2}{L}\int_0^L \psi(x) \sin(\lambda_nx) dx
$$
Similarly for $f_n(t)$ we have,
$$
f_n(t)=\frac{2}{L}\int_0^L F(x,t) \sin(\lambda_n x) dx
$$
Plugging everything in, we get,
$$
u(x,t)=\frac{g(t)-f(t)}{L}x+f(t)+\sum_{n=1}^\infty u_n(t) \sin(\frac{n \pi}{L} x) \\
u_n(t)=e^{-(\frac{n \pi}{L})^2 Kt}\int_0^t e^{(\frac{n \pi}{L})^2 K\tau}\frac{2}{L}\int_0^L \frac{\dot{f(\tau)}-\dot{g(\tau)}}{L}x-\dot{f(\tau)} \sin(\frac{n \pi}{L} x) dx d\tau \\
+ e^{-(\frac{n \pi}{L})^2Kt} \frac{2}{L}\int_0^L \psi(x) \sin(\frac{n\pi}{L}x) dx
$$
This satisfies all the BCs without the need to introduce any additional conditions
Comment: What happens if $f(t)$ and $g(t)$ are not differentiable, but are only continuous? I know that the problem has a solution (see, for example, Friedman's Parabolic PDE text, chapter 3, Theorem 9).  Is there still a way to make such an explicit formulation?
Comment: Also, how do we get a Fourier series for $F(x,t)$ if it does not have period $L$?
Answer: The equation is $$\partial^2_x u(x,t)=K\partial_t u(x,t)$$
Boundary : $$u(\pm ct,t)=0$$
Eigenfunctions of the lhs operator with the boundary : $$v_n(x,t)=\cos\left((2n+1)\frac{\pi x}{2ct}\right)$$
Expansion in the base obtained : $$u(x,t)=\sum_{n=0}^\infty a_n(t)v_n(x,t)$$
Plugging in the original function :
$$-\sum_n (2n+1)^2\frac{\pi^2}{4c^2t^2} a_n(t)v_n(x,t)=K\sum_n \dot{a}_n(t)v_n(x,t)+a_n(t)(2n+1)\frac{\pi x}{2ct^2}\sin\left((2n+1)\frac{\pi x}{2ct}\right)$$
Projection : $$\int_{-ct}^{ct}v_m(x,t)\cdot dx$$ based on :
$$\int_D\cos(ax)\cos(bx)dx=\frac{a\sin(ax)\cos(bx)}{a^2-b^2}-b\frac{\cos(ax)\sin(bx)}{a^2-b^2}=0,a\neq b$$ due to vanishing of cosines at boundary
$$\int_D \cos(ax)\cos(ax)dx=\frac{\sin(ax)\cos(ax)}{2a}+x/2=ct$$
$$\int_D x\sin(ax)\cos(bx)dx=1/2\left(\frac{\sin(x(a-b))}{(a-b)^2}+\frac{\sin(x(a+b))}{(a+b)^2}-\frac{x\cos(x(a-b))}{(a-b)}-\frac{x\cos(x(a+b))}{(a+b)}\right)=c(-1)^{m+n}\frac{2n+1}{(m+n)(m+n+1)}=C_{mn}, a\neq b$$
The sines vanish because sum and difference of 2 odd numbers is even.
You were right, This is where I made the mistake, the matrix is not diagonal but full.
Remains
$$\int_D x\sin(ax)\cos(ax)dx=ct/2a=\frac{c^2t^2}{(2n+1)\pi}=b_n(t)$$
Let $D_{mn}(t)=b_n(t)\delta_{mn}+C_{mn}$
The equation for the coefficients is :
$$-K^{-1}\left((2n+1)^2\frac{\pi^2}{4ct}\right)a_n(t)=\dot{a}_n(t)ct+\sum_{m=0}^\infty D_{nm}(t)a_m(t)$$
Hence we get an infinite system of odes written as a matrix system of the form : $$\dot{\vec{a}}(t)=F(t)\vec{a}(t)\Rightarrow \vec{a}(t)=e^{\int_0^t F(s)ds}\vec{a}(0)$$
Comment: Ah I see. With relativistic boundary conditions you could do it like this, but I don't think you need them for this specific problem. I will post how I did it.
Comment: It depends if one doesn't want to violate causality, other than the solution of qft in physics.
Comment: Depends of what u is I guess. If u is signifying temperature, this is just the 1-D heat equation, if u is the hydraulic head, it is just the groundwater flow equation, if u is concentration, it is the diffusion equation and so on.


Compute $\lim_{n \to \infty}\int_{\mathbb R}g(x)sin^2(nx)dx$ considering $\int g(x)dx = 1$ and $g \in L^1(\mathbb R)$.

Question: Compute $\lim_{n \to \infty}\int_{\mathbb R}g(x)\sin^2(nx)\,dx$ considering $\int g(x)\,dx = 1$, and $g \in L^1(\mathbb R)$.
My reasoning is the following: take $nx = t$, then we have
$$\lim_{n \to \infty} \int g(x) \sin^2(nx)\,dx = \lim_{n \to \infty} \int  \frac{1}{n}g\left(\frac{x}{n}\right)\sin^2x\,dx.$$
If $g$ is continuous, then the dominated convergence theorem says that the integral should be zero. If $g$ is not continuous, take $f$ continuous such that $\|f-g\| \leq \varepsilon$, then
$$\lim_{n \to \infty} \int \frac{1}{n}g\left(\frac{x}{n}\right)\sin^2x\,dx = \lim_{n \to \infty} \int \left(\frac{1}{n}g\left(\frac{x}{n}\right) - \frac{1}{n}f\left(\frac{x}{n}\right) + \frac{1}{n}f\left(\frac{x}{n}\right)\right)\sin^2x\,dx.$$
I am not sure why $\int g(x)\,dx = 1$ is needed here.
Comment: But having $g \in L^1$ is enough for that purpose.
Comment: Sorry, meant to add more: the limit depends on $\int g(x)\, dx$; it's not necessarily zero.
Answer: Using the identity
$$\sin^2(nx) = \frac{1}{2} - \frac{1}{2}\cos(2nx)$$
we write
$$\int_{\Bbb R} g(x)\sin^2(nx)\, dx = \frac{1}{2}\int_{\Bbb R} g(x)\, dx - \frac{1}{2}\int_{\Bbb R} g(x)\cos(2nx)\, dx$$Since $g\in L^1$ the Riemann-Lebesgue lemma gives $$\lim_{n\to \infty} \int_{\Bbb R}g(x)\cos(2nx)\, dx = 0$$Therefore$$\lim_{n\to \infty}\int_{\Bbb R} g(x)\sin^2(nx)\, dx = \frac{1}{2}\int_{\Bbb R}g(x)\, dx = \frac{1}{2}$$
Comment: Would you mind pointing out where I am wrong in my reasoning?
Comment: @penny the dominated convergence theorem cannot be applied directly when $g$ is continuous, because $g$ is not necessarily bounded on $\Bbb R$.
Comment: Oh, I see the problem, the bound has to be independent of $n$. Thanks


Confused about classical Roman life expectancy

Question: According to Wikipedia, the average life expectancy in classical Rome was 30. However, if a child survived to age 10, life expectancy was an additional 37.5 years, totaling 47.5 years.
My question is, what percentage of population would have to die before age 10 so that the average life expectancy is 30 years?
Comment: Depends on the distribution of deaths prior to age 10. You would have a different answer if everyone perished at 9.75 versus 0.25, for example
Comment: Let's assume those who die before 10, dies at birth. Historically, most of those deaths before 10 were infant mortality.
Answer: We assume, as per your comment, that most of the early deaths were shortly after birth.  Let $p$ be the probability of early death. Let $X$ be the lifetime of a randomly chosen newborn.
We are told that $E(X)=30$. We are also told that the conditional expectation of $X$, given the child survived to age $10$, is $47.5$. Then under our assumptions,
$$30=E(X)=(p)(0)+(1-p)(47.5).$$
That gives $1-p=\frac{30}{47.5}\approx 0.63$, and therefore $p\approx 0.37$.
One can play around with guesses about the actual mean lifetime given that the child died before the age of $10$. For example, if we replace the estimate we used (all deaths before $10$ occur at age roughly $0$) with say conditional mean is $2$, then we are solving the equation $30=(p)(2)+(1-p)(47.5)$. That gives $p\approx 0.385$.
Comment: (+1) but in case the OP is not comfortable with the language of probability:

 Let $R$= number of Romans, $C$ = number children who died at birth, and $O$ the number of Romans who make it to old age.
So $R = C + O$. Write $Y$ for the total number of years lived by all Romans, so that $R \,30= Y$. We also have $O \, 47.5 = Y$, since we assume that $C$ contributed $0$ years. Therefore $O/R = 30/47.5$, and so on, as in your answer.


High charts displays data only if we press F12 (developer tool) in chrome browser

Question: I have used high chart to display column bar and pie chart. I don't know why this problem is occurring.
The problem is that the chart should be displayed on load time of jsp file, but only data is showing on load time; when we press f12 then it renders the charts.
I don't know why.
If anyone faced this problem before.
Comment: Please show us the code you use.
Comment: It means that redraw is called, so it looks like problem with draw chart, during initialise chart. Anyway without any live demo it is difficult to debug it.
Answer: Do you have any console.log()'s?
Take them out if you do.


Show that a group of order $pq$ has subgroups of orders $p$ and $q$ without using Sylow's and Cauchy's theorem

Question:
If $o(G)$ is $pq$, $p>q$ are primes, prove that $G$ has a subgroup of order $p$ and a subgroup of order $q$.

This question is from Herstein and it comes before Sylow's and Cauchy's theorem. So I'm expecting an answer without using any of these.
Here's what I got so far:
If $G$ is cyclic, then we are done, otherwise we can assume that it is not cyclic, which means every non-identity element must be of order $p$ or $q$.
Case (1): if there exists $a \in G$ such that $o(a) = p$ and if there also exists an element of order $q$, then we are done. So we can assume that every non-identity element is of order $p$. Now pick $b \in G$ such that $b \notin \langle a \rangle$ then $o(b) = p$ and $\langle a \rangle \cap \langle b \rangle = \langle e \rangle$.
So we have $\langle a \rangle \langle b \rangle \subset G$ but $o(\langle a \rangle \langle b \rangle) = \dfrac {o(\langle a \rangle) o(\langle b \rangle)}{o(\langle a \rangle \cap \langle b \rangle)} = p^2$ but $p^2 > pq$ [since $p>q$] so we got a contradiction.
Give me a hint for the second case and correct me if my argument for the first case is wrong.
Comment: I didn't say that it's a subgroup, I only used it as a subset and that formula works for the product of two finite subgroups @DavidA.Craven
Comment: In general $\langle a\rangle\langle b\rangle$ is not a subgroup, but the subgroup generated by them has order at least what you suggest.
Comment: Your argument in the first case looks good to me.
Comment: @LucasHaobam OK, yes. It's just a subset. It's fine, but is not the way you are supposed to do it, as it doesn't work for the other prime.
Comment: Okay, give me a hint. I'll try @DavidA.Craven
Comment: There is an answer with a hint.
Comment: Hint: If all the elements of the group are of $q$ order, what would the centralizers of these elements look like?
Comment: @UmeshShankar How do you easily see that those are not also just of order $q$?
Comment: @TobiasKildetoft $p$ would divide the order of the group and the index of the centralizers.
Comment: @UmeshShankar Why should $p$ divide the index of the centralizer?
Comment: @TobiasKildetoft Because the centralizers are subgroups. You don't want them to be order $p$. Then, they should be of index $p$.
Comment: @UmeshShankar Right, sorry, I got myself confused with which prime was which here. So all of those subgroups are self-centralizing. Where does that lead?
Comment: I only mentioned the word centralizer to hint at a connection with the class equation.
Comment: @UmeshShankar Ahh, of course. I am apparently slow today. That is a good way to go about it.
Comment: This problem comes before class equations section so I'm searching for an elementary way @UmeshShankar
Comment: which will conclude that every $(N(a))$ will have order $q$ right? then? @UmeshShankar
Answer: Assume that every non-identity element generates a cyclic group of order $q$, the smaller of the primes.
Conjugacy is an equivalence relation on a group. So, we should be able to partition the group into its equivalence classes. The size of the equivalence class an element belongs to is the index of the centralizer of the element. Why? Fix $x\in G$. Make a homomorphism from $G \rightarrow G$ by sending $g \rightarrow xgx^{-1}$. The size of the equivalence class is the order of the image. What is the kernel of this map?
If the centralizer is of order $p$ or $pq$, we are done. Assume every centralizer is of order $q$, the index of the centralizer is $pq/q=p$. Every element would belong in a equivalence class of size $p$, except for the identity element.
A simple cardinality calculation shows that $pq= kp+1$, where represents the number of equivalence classes. However, this is absurd and therefore, not every subgroup is of order $q$.
Comment: This works for both cases
Answer: Firstly, if all the non-trivial elements of $G$ have order $pq$, then, for any given $g\in G\setminus\{e\}$, we get $e=g^{pq}=(g^p)^q$ and hence $o(g^p)\mid q$; but $g^p\in G\setminus\{e\}$, so, by assumption, $o(g^p)=pq$ and we end up with $pq\mid q$: contradiction. Therefore, there must be elements of order $p$ and/or elements of order $q$. If $G$ is Abelian, then your argument works for the "second case" either, because then every subgroup is normal and hence $\langle a\rangle\langle b\rangle$ is a subgroup of $G$ such that $o(\langle a \rangle \langle b \rangle) = \dfrac {o(\langle a \rangle)o(\langle b \rangle)}{o(\langle a\rangle \cap \langle b\rangle)} = q^2\nmid pq$: contradiction (Lagrange). So, there must be elements of both orders, $p$ and $q$. If $G$ is nonabelian, then it has trivial center (see here) and the Class Equation reads:
$$pq=1+k_pp+k_qq$$
where $k_i$ are the number of conjugacy classes of size $i$. None of the $k_i$ can be zero, because neither $p\nmid 1$ nor $q\nmid 1$. Say $O_p$ a conjugacy class of size $p$ and $O_q$ a conjugacy class of size $q$, which as said both exist; for $g\in O_p$, we get $|C_G(g)|=q$ (Orbit-Stabilizer Theorem) and hence $\langle g\rangle=C_G(g)$ (because in general $\langle g\rangle\le C_G(g)$) and finally $o(g)=q$. Likewise, for $h\in O_q$, we get $|C_G(h)|=p$ and hence $\langle h\rangle=C_G(h)$ and $o(h)=p$.
Comment: @David A. Craven, The OP has proved that *not all* the non-trivial elements have order $p$. With a similar argument, *in the case of Abelian $G$*, I (think to) have proved that not all the non-trivial elements have order $q$. So the Abelian case is done. Then, I dealt with the nonabelian case separately, as a whole, with the Class Equation. Is my logic flawn somewhere?
Comment: The main part of your solution is the statement that, for a non-abelian group, the centralizer of an element of order $p$ has order $p$, and similarly for $q$. Once you state that, which is just half a line, then everything else follows immediately. You seem to have buried the pertient part with lots of other things. For the abelian case, the proof is very fast.
Comment: You are trying to prove that $G$ has elements of orders $p$ and $q$. Certainly if $G$ has an element of order $pq$ then powers of it have order $p$ and $q$. So your only issue is if all non-trivial elements have order $p$, or all have order $q$. Which you don't appear to address.
Comment: Here is the proof. Assume $p\neq q$, but to make statements quicker, do not assume $p>q$. If $G$ has an element $x$ of order $pq$ then $x^p$ has order $q$, $x^q$ has order $p$, and done. So all elements have order $1$ or $p$, or $1$ and $q$. Let $x$ be an element of order $p$. If $G$ is abelian then $H=\langle x\rangle$ is normal, and $G/H$ has order $q$. Let $Hy$ have order $q$ in $G/H$. Then $y$ cannot have order $p$, because its image has order $q$. Done.
Comment: If $G$ is non-abelian then $G/Z(G)$ cannot have prime order, and $G\neq Z(G)$, so $Z(G)=1$. In particular, any element of order $p$ has centralizer of order exactly $p$. Thus if $G$ has no elements of order $q$ and $c$ classes of order $p$ (each of which as size $q$), then $|G|=pq=1+cq$, which is impossible.
Answer: Case $G$ abelian. If $G$ has all the nontrivial elements of one same order, say $p$, then there are $k=\frac{pq-1}{p-1}\ge2$ distinct subgroups of order $p$. Call $H$ and $K$ two of them. The set $HK$ is a subgroup of $G$ of order $p^2$: contradiction, because $p\nmid q$. Same conclusion if $G$ has all the nontrivial elements of order $q$, as $q\nmid p$. So, $G$ has elements of both orders $p$ and $q$.
Case $G$ nonabelian. Then $pq=1+kp+mq$ is the only possible class equation, for some positive integers $l$ and $m$, and hence $G$ has subgroups (centralizers, actually) of both orders $p$ and $q$.

Show that a group of order $pq$ has subgroups of orders $p$ and $q$ without using Sylow’s and Cauchy’s theorem


Why is my field not displayed?

Question: I got a template for drupal 8 and modifying a content type, when editing a new field, it does not show up.
I'm attaching the images of the structure (fields, form display, display), creation of content and impression.

For more that adds any field I do not manage to make it visualize at the end, in web portal
AND, As in the last page of print (celestial circles) I can not edit that, for more that I have edited in: filds, form display and display. Please where else is it that you can edit these texts in drupal 8?
Can someone help me please
regards
Comment: This doesn't seem to be a drupal-commerce question. Please update the tags.
Comment: In the screenshot, you haven't selected any value in the widget. But that's probably just the screenshot. Please show your template code and any preprocess function.
Answer: The template most likely does not print content directly only specific fields, you need to add {{ content.field_name }} to the template, where you want to have it displayed.
Comment: Could you please tell me how to do that? Or some example link to help me. thank you very much for your help. regards
Comment: I don't really know what else to tell you, you should find enough generic tutorials on how to work with templates in Drupal 8, start with enabling twig debug mode (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates), which tells you which template file is used. Open that and start changing it by adding your field as shown by example in my answer. See also http://www.md-systems.ch/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig

Why is my field not displayed?


C++ calling a function pointer stored in a struct in a map

Question: I am getting the error term does not evaluate to a function taking 1 arguments when trying to call a function pointer.
The function pointer is stored in a struct. The struct is then stored in a map.
Definition:
typedef void (CLIOptions::*OptionHandler)(QString);

struct OptionDefinition {
   QString name;
   QString description;
   QString type;
   OptionHandler handler;
};

typedef std::map<QString, OptionDefinition> CLIOptionMap;

I initialise the map like this:
CLIOptionMap optionMap =
{
   {
      QString("set-tcp-host"),
      {
         QString("set-tcph"),
         QString("Set the TCP server host address"),
         QString("string"),
         &CLIOptions::setTcpHost
      }
   },
  // etc...
}

The problem occurs when I try to iterate through the map and call the handler:
for (it = optionMap.begin(); it != optionMap.end(); ++it) {
    QString value = /*snip...*/

    (it->second.handler)(value)
}

What is my problem here?
Comment: How would the line of code you wrote know what instance of CLIOptions to call that member function on?
Comment: duplicate of https://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer me thinks
Comment: @EdgarRokyan : No.  `it->second.handler` is the pmf.  You then need something like `this->*(it->second.handler)(value)`.  This is complicated enough, I recommend an intermediate variable for readability.
Answer: Your problem is that you don't have a function pointer, you have a pointer to member function, and they are very different beasts.  A pointer-to-member-function isn't even a pointer in general (it has to be able to handle pointer to a virtual function in a second virtual base class!)
Given you have a pmf, you need an object to invoke the pmf on.  So something like:
for (it = optionMap.begin(); it != optionMap.end(); ++it) {
    QString value = /*snip...*/
    const auto pmf = it->second.handler;
    (mOptionHandler.*pmf)(value);
}

actually, if you going to use C++11 auto, you can also use the foreach loop:
for (const auto& option : optionMap) {
   const auto pmf = option.handler;
   (mOptionHandler.*pmf)(option.value);
}

Comment: Thanks. So I have an instance of "CLIOptions" available called ``mOptionHandler``, so I setup the call like ``(mOptionHandler.pmf)`` but this gives ``CLIOptions has no member pmf``
Comment: Oh I just missed a dereference I think: ``mOptionHandler.*pmf``
Comment: I've changed my example to use your name.  And yes - the `.*` operator is completely different to the `.` operator!


JavaFX license - is including javaFX jar on your app server not breaching the license?

Question: So I've got an application which starts via Java WebStart. It requires javafx jar to work properly. If  I place the javaFX jar on my server (so that it could be downloaded when starting the application) would it be ok with the license?
Comment: Ok, seems I found the answer here:
http://stackoverflow.com/questions/8372217/may-javafx-2-0-be-redistributed
Answer: I'm not sure about the license (it should be possibe to provide native bundles which include the jre + javafx), but for Java WebStart the recommended way is to install the latest JRE on client-side, which comes with JavaFX. So you don't need the javafx jar on the server.
You should include the JavaFX start classes in the main jar, however, and have the correct JavaFX Manifest entries. But since the JavaFX Ant task provided by Oracle is copying these start classes to the main jar, I guess it's ok to use them. But I'm not a lawyer.
Comment: It's recommended to use Java SE 7 as Java SE 6 reaches End-of-Life this month. Or make sure you have the necessary support contracts with Oracle. http://www.oracle.com/technetwork/java/javafx/overview/faq-1446554.html#5
Comment: Installing the JRE on client side is not an option, client will have to use Java 6.


Lifting property of a covering space

Question: A common example of a covering space is $p:\mathbb R \rightarrow S^1 $, $p(t)= e^{2 \pi it}$, which can be looked at as an infinitely long spiral placed over a circle. Consider the double loop $\gamma: [0,1] \rightarrow S^1$, i.e. the path that starts at $x_0$, goes twice around the circle, and ends at $x_0$.
I am having troubles visualising (in an "infinite spiral" fashion) a continious path $ \tilde \gamma: [0,1] \rightarrow  \mathbb R$ that will lift the double loop: $p \tilde \gamma = \gamma$. Could you please help me?
Answer: Take the path $\tilde\gamma(t)=2t$.
Think of the covering $\mathbb R\to S^1$ as that infinitely long spiral over the circle. Choose a point over $x_0$ on this spiral, then trace the spiral upwards until you've gone around the circle twice, ending at another point over $x_0$. The segment of the spiral that you've traced is the path $\tilde\gamma$.
Comment: Thank you! Just realised what was wrong with my thinking.. Somehow it seemed that since $\gamma$ is surjective to $S^1$, $\tilde \gamma$ should be surjective to $\mathbb R$ as well. Of course that's not true, that goes against the whole idea of a covering space. Thank you again!

Lifting property of a covering space


Can the sum of two pregaussian random variables be zero?

Question: Do there exist any two Sub-Gaussian random variables with variance 1 such that the sum of them is the $0$ random variable, whose value is $0$ with probability $1$?
Comment: Any helpful answers would be greatly appreciated!
Answer: Certainly; let $X \sim N(0,1)$ and $Y = -X$.
If you want them to be independent then this is not possible.  If $X,Y$ each have variance 1 and are independent, then $\operatorname{Var}(X+Y) = \operatorname{Var}(X) +\operatorname{Var}(Y) = 2 \ne \operatorname{Var}(0)$.
Indeed, the only way for the sum of two independent random variables to be 0 is if they are both constants. To be precise:

If $X,Y$ are any two independent random variables (not necessarily sub-Gaussian), and $X+Y = 0$ almost surely, then there is a constant $c$ such that $X=c$ and $Y=-c$ almost surely.

Proof.  If $X+Y = 0$ then $Y = -X$, so $X$ is independent of $-X$, and it follows that $X$ is independent of $X$.  In particular, for any $t$, the event $\{X > t\}$ is independent of itself, and so must have probability 0 or 1.  By taking $c = \sup\{t : P(X>t) = 1\}$, we can see that $P(X=c) = 1$.
Comment: Thank you for your answer, but do you mean that the Sub-Gaussian random variables will be both $0$ if independent? and why is that? Thanks!
Comment: @bolia: I added some more details.  Sub-Gaussian doesn't really have anything to do with it.
Comment: Dear Nate, Thank you for your answer, but Why must the event {X>t} is independent of itself have probability 0 or 1? as X and Y independent means $f_{X,Y}(x,y) = f_X(x) f_Y(y)$. Thanks!
Comment: @bolia: That isn't really a very good definition for our purposes, since if the random variable is constant it won't have a density.  But you could integrate that definition to find the same property of the cdf's: $F_{X,Y}(x,y) = F_X(x) F_Y(y)$.  If $F$ is independent of itself then $F_X(x) = F_{X,X}(x,x) = F_X(x)^2$, so $F_X(x)$ must be 0 or 1.  In particular, $P(X>t)$ is $1-F_X(t)$, so it must also be 0 or 1.  This fact follows more directly if you are doing probability from the point of view of measure theory.


Is $R/I$ flat over $R$ when $I$ is the nilradical of $R$ and $I=I^2$?

Question: This is a flowup of this question. To be precise, let $R$ is a commutative unitary ring with nilradical $I$. In the above URL, it is proved that if $R/I$ is a flat $R$-module, then $I=I^2$.
My question is whether the converse holds in general. Thanks !
Comment: If $I$ is finitely generated, yes, because by Nakayama $I=0$.
Comment: One can also work in the case $I$ is finitely generated but not necessarily $\sqrt R$. Assuming $I^2=I$, use the determinant trick to prove that $I=(e)$ for an idempotent $e$, and then it easily follows that $R/I$ is flat.
Comment: Dear Martin and @KarlKronenfeld, thanks for your comments.
Answer: Not in general, no.
Let $R$ be a zero dimensional local ring, and suppose that its maximal ideal $I$
satisfies $I^2 = I$.  Then $R/I$ is flat over $R$ only if $I = 0$.  (See this MO answer.)
E.g. if $S$ is a one-dimensional local domain with maximal ideal $\mathfrak m $ such that $\mathfrak m^2 = \mathfrak m$
and $x \in \mathfrak m$ is non-zero, then $R := S/(x)$ is a zero-dimensional local ring whose maximal ideal $I$ satifies $I^2 = I$.
E.g. Let $S = \overline{\mathbb Z}_p$ denote the integral closure of $\mathbb Z_p$ in $\overline{\mathbb Q}_p$, and take $s = p$.  Then $R = \overline{\mathbb Z}_p/(p)$ gives a concrete example.


When does iptable's conntrack module track states of packets?

Question: It first needs to store states.  With some old BSD firewall that I used, I guess was named IPFW, I used to put a rule that sated "keep track of the state of the leaving packet", and this was placed on the outbound direction of interfaces.  Then, another rule on the inbound direction that checked them against those states that were created by the rule on the outbound direction.  So there used to be 2 rules:  (1) to populate the states table, this was on the outbound direction, and (2) to lookup the states table, this was on the inbound direction.
But with connntrack, I see it applied on the INPUT chain, such as this rule:
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

This makes me wonder, what is that statement actually doing?

Is it saying that it will start tracking packets that match that rule by putting their information in the states table?
Or is it saying that it already has the states information, and it is going to act against inbound messages based on it?  (e.g. accept if they belonged to a previously accepted connection?).  But, in this case, where did the states table get populated?  Which rule does it?  Or is it rule-less and implicit?
Answer: Introductory presentation of Netfilter and conntrack
First the mandatory schematic about Packet flow in Netfilter and General Networking:

Netfilter is the packet filtering framework inserting itself over the rest of the network stack (represented by "routing decision" and other white round-edged box parts). Netfilter provides hooks and APIs for other subsystems and "clients". Among these parts are conntrack (the connection tracker) and iptables (or nftables). The separation between Netfilter and conntrack is quite fuzzy. You can just consider conntrack as an integrated part of Netfilter.
In the schematic describing the various steps a packet traverses you can see that at some point (between raw/PREROUTING and mangle/PREROUTING, or between raw/OUTPUT and mangle/OUTPUT) the packet traverses conntrack.
At this point, conntrack will search in its own lookup tables (a mini lookup database kept in kernel memory):

if this packet's charateristics are not found (and if not declared UNTRACKED in the raw table), a new conntrack bidirectional tuple entry (protocol, then specific family and protocol informations: initial source and port, initial destination and port, reply source and port, reply destination and port (those two last are usually the reverse, unless NAT or some strange protocols are involved, like echo reply matching echo request for ICMP)) describing the flow is created with state NEW.
if it matches (in any direction) a previous entry and is compatible with this flow's state, the flow state might be altered (eg: changing from NEW to ESTABLISHED if that wasn't the case before).
if for some specific reason the packet can't match an existing flow despite it having its characteristics (eg: a late TCP packet received after a retransmissions already kicked in successfully, so being out of window with regard to the sequence and SACK values) the packet will be tagged INVALID.
there are a few other cases like RELATED: this is about packets not part of the flow itself but related to a new flow that can be associated with an other existing (ie: in the database) flow. Two examples are an ICMP error created from receiving a packet (eg: UDP port unreachable) or when a special protocol helper like the kernel module nf_conntrack_ftp , which is a plugin to the conntrack subsystem, detects that a packet is part of the separate data flow associated with the FTP commands PASV/EPSV or PORT/EPRT done on the command flow (on port 21).

Addressing the question
All this being said, here are the answers to your two bullets:

in the main network namespace conntrack starts tracking connections as soon as its modules (including possible relevant protocol-specific sub-modules) are loaded. For non-initial network namespaces (containers...) this also requires that some other subsystem references it (such as OP's iptables's conntrack module or using once the command conntrack described later). This is the default and a packet must be specifically marked as UNTRACKED before the conntrack subsystem sees it for this packet to not be tracked. On Linux there are only a few cases where not tracking would be needed, but then of course stateful firewalling and stateful/dynamic NAT won't be available anymore (steless NAT which might even require to use UNTRACKED in the first place, can still be done, but not with iptables. tc or nftables can). To avoid conntrack handling some packets, this kind of iptables rule can be used (eg: port 80/tcp):
iptables -t raw -A PREROUTING -p tcp --dport 80 -j CT --notrack
iptables -t raw -A OUTPUT -p tcp --sport 80 -j CT --notrack

When the packet traverses filter/INPUT and reaches this rule:

 iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

The iptables's specific kernel module xt_conntrack queries the conntrack subsystem (handled by the various relevant kernel modules nf_conntrack*) and asks about the state of this packet in its lookup database. If the answer is RELATED or ESTABLISHED the packet matches and proceeds to the ACCEPT verdict. Actually the result is already cached in the packet the first time the lookup was done (usually by conntrack) so this is a cheap "lookup". This is thus a generic rule to handle flows already accepted before. Those flows can be initially  accepted in rules explicitly mentioning -m conntrack --ctstate NEW or simply rules not mentioning it but placed after this generic rule (but keep in mind the INVALID state, which should usually be DROPed before doing so).

adding a bullet: the handling of incoming packets and outgoing packets is quite symmetrical between PREROUTING and OUTPUT (even if those don't look symmetrical): conntrack interfaces in PREROUTING as well as in OUTPUT (and in a few other places, considering NAT is working with conntrack, except for its first packet in state NEW traversing iptables's nat table). This might be slightly different from the description you wrote about IPFW. If a server running applications is also restricting outgoing flows, then it most likely needs this same generic iptables rule both in filter/OUTPUT and in filter/INPUT, to allow outgoing reply packets of already accepted incoming traffic to pass.

Additional informations
There are dedicated tools to interact with the conntrack subsystem's lookup tables from conntrack-tools.

conntrack: to query, delete or update the contents of the lookup tables handled by conntrack.
Some examples.
You can list all tracked entries (which can be big without additional filter) with:
conntrack -L

If your system is doing NAT (eg a router in front of a private LAN, or running VMs and containers) you can use --any-nat, --src-nat or --dst-nat to only display resp. all NAT, all source NAT (masquerade), or all destination NAT (typically for forwarded ports):
Real-time monitoring of conntrack events:
conntrack -E

conntrackd: a daemon whose two main purposes are (conntrack) flow accounting and statistics, or high-availability stateful firewall cluster state synchronization.
Comment: @kilves76  a packet without state is actually in INVALID state. It can't be ESTABLISHED at the same time. What matters about INVALID is that it's DROPed  and never REJECTed. If you REJECT any packet which missed the ESTABLISHED -j ACCEPT rule, thinking there's nothing special to do about INVALID ones, you risk killing an innocent TCP connection when delayed packets are retried / duplicated, which could happen even hours after it was established. If your rules never REJECT, but use only DROP instead, then you can choose to not care about INVALID.
Comment: Side question, is there always only one state? So that a packet cannot have a state of INVALID and ESTABLISHED at the same time. That there is no need to drop all INVALIDs at the top of the chain, but all other states can be processed first and INVALID last, before processing any non-state rules.
Answer: Connection tracking is a separate function of Netfilter, and it is not configured with IPTables.

In the picture, there are two conntrack steps in INPUT path and one in OUTPUT path. These steps associate individual packets with existing connections tracked in the connection tracking table, or create new connection tracking entries in the table.
Conntrack functionality is a Linux kernel module, and it is often included in the kernel in default configuration.
Conntrack operation can be tuned by adjusting net.netfilter.nf_conntrack sysctl values.
Your second alternative is what happens. The state information is recorded by the Conntrack function, and the IPTables rule simply consults the Conntrack table for information.


Iconic (toy) models of neural networks

Question: My physics professors in grad school, as well as the Nobel laureate Feynman, would always present what they called toy models to illustrate basic concepts and methods in physics, such as the harmonic oscillator, pendulum, spinning top, and black box.
What toy models are used to illustrate the basic concepts and methods underlying the application of neural networks? (Please provide references.)
By a toy model I mean a particularly simple, minimally sized network applied to a highly constrained problem through which basic methods can be presented and one's understanding tested and enhanced through actual implementation, i.e., constructing the basic code and preferably to a certain degree doing/checking the basic math by hand or aided by a symbolic math app.
Comment: See also https://medium.com/towards-data-science/can-neural-networks-really-learn-any-function-65e106617fc6 and http://neuralnetworksanddeeplearning.com/chap4.html
Comment: Supplement: http://iamalearningcomputer.blogspot.com
Answer: One of the most classical is the Perceptron in 2 dimensions, which goes back to the 1950s. This is a good example because it is a launching pad for more modern techniques:
1) Not everything is linearly separable (hence the need for nonlinear activations or kernel methods, multiple layers, etc.).
2) The Perceptron won't converge if the data is not linearly separable (continuous measures of separation such as softmax, learning rate decay, etc.).
3) While there are infinitely many solutions to splitting data, it's clear that some are more desired than others (maximum boundary separation, SVMs, etc.)
For multilayer neural networks, you might like the toy classification examples that come with this visualization.
For Convolutional Neural Nets, the MNIST is the classical gold standard, with a cute visualization here and here.
For RNNs, a really simple problem they can solve is binary addition, which requires memorizing 4 patterns.
Answer:
The XOR problem is probably the canonical ANN toy problem.
Richard Bland June 1998 University of Stirling, Department of Computing Science and Mathematics Computing Science Technical Report
"Learning XOR: exploring the space of a classic problem"

The TensorFlow Playground is an interactive interface to several toy neural nets, including XOR and Jellyroll.

Computing the largest eigenvalue of a fixed-size (2x2 or 3x3) symmetric matrix is one I use in classroom demos.
A. Cichocki and R. Unbehauen. "Neural networks for computing eigenvalues and eigenvectors" Biological Cybernetics
December 1992, Volume 68, Issue 2, pp 155–164

Problems like MNIST are definitely canonical but aren't easily verified by hand -- unless you happen to have enormous free time. Nor is the code especially basic.
As far as NLP tasks, the Penn Tree Bank is a very standard benchmark data set, used for example in  Wojciech Zaremba, Ilya Sutskever, Oriol Vinyals
"Recurrent Neural Network Regularization," and probably hundreds of other papers.

Iconic (toy) models of neural networks


How to use custom tables in Views

Question: I have multisite DRUPAL6.26 website using VIEWS 3.0 module in it.
Both sites are install in single DB.
The first/parent site has no prefix for its tables.EX: node,block,role etc..
The second/childsite has prefix of child. EX: child_node,child_block,child_role etc..
I have a VIEW showing all pictures uploaded by user in there PARENT site account.
And the same VIEW for CHILD site showing pictures that they upload on CHILD site.
What I want is to show all pictures in PARENT site account of user whether they upload on PARENT site OR CHILD site.
[users are shared between the 2 sites.]
Any help of 'views master' required :)
Answer: There's a hook for exposing custom fields to Views: hook_views_data()

Describe table structure to Views.
This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. This must either be in the same directory as the .module file or in a subdirectory named 'includes'.
The full documentation for this hook is in the advanced help.

The link also includes example code.

How to use custom tables in Views


Is the unbiased test always uniformly most powerful?

Question: I know that the uniformly most powerful test is always unbiased, if it exists, but is the unbiased test always UMP?
Comment: You've asked a reasonable mathematical question, but you provided little in the way of context.  This is a natural omission for new users, because the context is of course well-known to yourself.  But explaining what motivates the problem or how you researched it before posting can add significantly to the benefit of Readers present and future. Please edit the body of your Question.
Answer: No. Consider a randomized test that rejects the null with probability $\alpha$, independent of the data. Then the test has equal type 1 error and power and is unbiased level $\alpha$, but not necessarily UMP.


Is there a way to get the 75th percentile in the SummaryBy function in R?

Question: I'm attempting to collapse my dataset into the mean and 75th percentiles of a variable, but I can't seem to find the correct way to state that I want the 75th percentile. Code below.
six_month_agg <- summaryBy(pd ~ industry + region + date, FUN=c(mean, 0.75), data=six_month_pd)

Answer: We can use quantile
library(doBy)
summaryBy(pd ~ industry + region + date, FUN=
           function(x) c(Mean = mean(x), Quantile = quantile(x, probs = 0.75)), data=six_month_pd)

Using a reproducible example
data(warpbreaks)
out <- summaryBy(breaks ~ wool + tension, warpbreaks, FUN=function(x)
     c(Mean = mean(x), Quantile = quantile(x, probs = .75)))

str(out)
#'data.frame':  6 obs. of  4 variables:
# $ wool               : Factor w/ 2 levels "A","B": 1 1 1 2 2 2
# $ tension            : Factor w/ 3 levels "L","M","H": 1 2 3 1 2 3
# $ breaks.Mean        : num  44.6 24 24.6 28.2 28.8 ...
# $ breaks.Quantile.75%: num  54 30 28 31 39 21

Comment: Thanks, this is perfect!


Gii model generation not getting past first step - strange bevavior, what's causing this?

Question: I've installed the latest version of yii2 using the advanced template. The website is working fine. For some reason the Gii generation tool is stuck and does not react as expected after clicking the preview button. Instead of showing a new form with the "Generate" button, it shows the same form unchanged without any messages as to what is happening.
Using xdebug I can see in the "actionView" method of the DefaultController that the array value $_POST['preview'] is not set, i.e. it doesn't exist in the $_POST array. I have not changed anything in the Form of the view and everything looks OK. The submit button has the name "preview" and the form is submitted but the $_POST array is not being filled with the value of the submit button. Therefore the controller does not proceed with the next steps of the generation process.
<code>public function actionView($id)
{
    $generator = $this->loadGenerator($id);
    $params = ['generator' => $generator, 'id' => $id];

    // ###############################################################################
    // ### THIS IF STATEMENT IS NOT TRUE BECAUSE  $_POST['preview'] IS NOT SET !!! ###
    // ###############################################################################
    if (isset($_POST['preview']) || isset($_POST['generate'])) {
    // ###############################################################################

        if ($generator->validate()) {
            $generator->saveStickyAttributes();
            $files = $generator->generate();
            if (isset($_POST['generate']) && !empty($_POST['answers'])) {
                $params['hasError'] = !$generator->save($files, (array) $_POST['answers'], $results);
                $params['results'] = $results;
            } else {
                $params['files'] = $files;
                $params['answers'] = isset($_POST['answers']) ? $_POST['answers'] : null;
            }
        }
    }

    return $this->render('view', $params);
}
</code>
Does anyone have an idea what could be causing this? I have a hunch that it is something quite simple that I'm overlooking, but I've never had a situation where POST variable from a Form are not being sent to the server.
Comment: BTW - it is not the CASE that the Framework, Router, Controller etc, is removing the value from the Array. The value is missing from the very beginning.
Answer: False Alarm. I've found the problem. The Gii view was creating the HTML Form incorrectly.


how to access function or package documentation in pycharm

Question: My python book tells me how to ask for help about a function or a package, for example pandas :
import pandas as pd
pd?

This doesn't work in PyCharm...
I can access documentation by typing : help(pd)
Does the "?" not work anymore?  My book is too old? Or it doesn't work in PyCharm?
Answer:
Tested in PyCharm 2023.3.2 (Professional Edition) Build #PY-233.13135.95

PyCharm: Code Reference Information

PyCharm: Viewing Inline Documentation

In PyCharm, in the Python Console, after import pandas as pd, pd? and then enter, will produce the docstring for pandas.  Additionally, help(pd) will also produce the docstring.

help(print)

View Quick Documentation in a popup

Hover over the symbol (e.g. print)
Place the caret at the symbol and press Ctrl + Q
print
pd.DataFrame - top of docsting
pd.DataFrame - bottom of docsting

Scrolling to the bottom of the Quick Documentation window provides an option to open the documentation in the browser.

np
As show in pd, there's an issue with the link, so the docstring is not display, as of this edit.

This original component of the answer was for versions available closer to 2018. It's not clear when this changed.

In PyCharm, go to View -> Tool Windows -> Documentation should open a Documentation window.  If you have a python file open in PyCharm, highlight a function and the docstring will appear in the Documentation window.


Nativescript Angular:Android fullscreen turned off on phone lock

Question: I am using below code to make my app full screen but when someone locked his phone and than unlock it full screen turned off:
<code>  ngOnInit(): void {
    this.goFullscreen();
  }
   private goFullscreen() {
    if (androidApp && device.sdkVersion >= '21') {
      const View = android.view.View;
      const window = androidApp.startActivity.getWindow();
      const decorView = window.getDecorView();
      decorView.setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
          View.SYSTEM_UI_FLAG_FULLSCREEN |
          View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
      );
    }
  }
</code>
is there any way to make app again full screen on phone unlock?
Comment: Try running the same code on Activity resume event.
Answer: Listen to the resume event and set full screen. You can also use it in a base component class for your page components.
<code>import { on as applicationOn, resumeEvent, ApplicationEventData } from "tns-core-modules/application";

export class BaseComponent {

    constructor() {

        applicationOn(resumeEvent, (args: ApplicationEventData) => {
            //set full screen here
        });
     }

}
</code>


Entity Framework - Distinct on 2 columns but get back all data

Question: I've got a really complicated Entity Framework problem and I haven't got a clue how to write my query in SQL or EF.
My table is something like this:
RecordId - int
ListId - int
ScreenName - string
Name - string
Description - string
Community - string
Value1 - decimal
Value2 - decimal
Value3 - decimal

I want to search this table and I need the results to be distinct based on a combination of ScreenName and Community. In other words, if there are multiple records with the same ScreenName and Community, I only want one row back. If there are multiple records with the same ScreenName and two different communities, then I will should get 2 records.
I want the full row, not just the ScreenName and Community.
When grouping records, if I could select which record to keep based on the ListId (lower is better), that would be ideal.
Is it possible to do any of what I've asked in Entity Framework?
Answer: After a lot of research and a lot of time getting frustrated with SQL Server, I finally figured it out
SQL
select * from ListRecord lr
where ListRecordId =
(
    select top 1 ListRecordId
    from ListRecord
    where ScreenName = lr.ScreenName
    and Community = lr.Community
    order by ListId
)

Entity Framework
var query = from x in db.ListRecords
            where x.ListRecordId == (
                db.ListRecords.Where(y => y.ScreenName == x.ScreenName && y.Community == x.Community)
                .OrderBy(y => y.ListId)
                .Select(y => y.ListRecordId).FirstOrDefault()
                )
            select x;

var list = query.ToList();

Comment: Great Owen! I got stuck with the same thing, but your answer is brilliant!
Thank you very much!


Why application root "~" resolves to site root "/" in ASP.NET?

Question: I have an ASP.NET Web Forms site developed under Visual Studio 2012. There is a master page with navigation bar and links to CSS tables. Bot are specified using the application root operator "~"
<asp:PlaceHolder runat="server">
    <%: Styles.Render("~/Content/themes/base/css", "~/Content/css") %>
</asp:PlaceHolder>
...

Generate Table

Browse DB

When browsing the page http://localhost/Forms/SelectResults.aspx I see that the "~" is resolved differently for these cases:
<link href="/Content/site.css" rel="stylesheet" type="text/css" />
...

Generate Table

Browse DB

So path to CSS is absolute and path to other pages is relative. When running on localhost, all works fine. But after deploying my site to the server it has an address http://MyDomain/MySite/, so it is not located in the domain root. And because of absolute paths, no CSS files can be loaded! Navigation works fine, but all the styles are ruined.
Why doesn't "~" operator work in Styles.Render directive? Both code snippets was generated by the standard ASP.NET website template, I didn't modify anything.
Site was developed under Visual Studio 2012, .NET Framework 4.5. My server specifications are:

Windows 7 x64
IIS 7.5
Website Application Pool Framework 4.0
Answer: The problem was caused by our proxy server, who actually forwards http://MyDomain/MySite/ to http://InternalDomain:InternalPort/. And for that internal domain application root was actually a site root.
Comment: this kind of troubles are also caused by web.config files sometimes


Change title head of the pages in Drupal 7 by path

Question: I need to change the title head of the pages in Drupal 7 by path.  NOt to all content type.  I need to change the title head to a specific page generated with views.
For example, I have a site http://www.mysite.com
<title>My favorite website </title>

I need the  for pages:
http://www.mysite.com/test
<title> My test today </title>

http://www.mysite.com/examples
<title> My examples for share </title>

Thanks.
Comment: I'm not sure what you mean by "change the title head to a specific node."  Could you clarify please?  Two common modules that help in this area are http://drupal.org/project/pathauto and http://drupal.org/project/auto_nodetitle  You might check them out and if they don't work, explain how your use case is different than the ones these common modules handle.
Comment: I refer to the "title head" that appears in the meta tags.  The title that is shown in the tabs of the browser.  Thanks.
Answer: It sounds for your limited set of pages maybe implement THEME_preprocess_html() and examine the url path and override $vars['head_title']. See this blog post as an example: How to set custom page title in Drupal 7
If you have some patterns for the head title try Page Title
Comment: I saw the post and I have a question, if I want to assign a "head title" to the specific paths.  Not to all paths will have the same title.  For example I need http://mysite.com/test the  is "My tests" and I have other page http://mysite.com/examples I need that  "Examples for share".  Is this code useful for this purpose?  I have updated my post.
Comment: @cabita Tenken's post covers your use case. Besides what he already mentioned you can also use the [Meta tags](http://drupal.org/project/metatag) module. All 3 options allow you to set the head title for the specific node pages you want without touching the rest.
Comment: I tried with meta tags and allow change the title head for specific pages but no for specific pages generated by views.  I will update my question again.  I'm sorry.
Comment: @cabita Did you also try [Page Title](http://drupal.org/project/page_title)? It at least claims to have views integration. If this doesn't work out either you could just go ahead and do it in the code (it's easy to restrict changes to specific pages only by using $_GET['q'] or [arg()](http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7) to check the path).
Comment: I did in the code.  You are right, it's easy to restrict changes to specific pages only by using $_GET['q'] or arg().
Comment: The link "How to set custom page title in Drupal 7" given as answer is useful for change the main title.  Thanks to all for your answers.
Answer: Here is how I did it in Drupal 7.
In template.php:
function YOUR_THEME_preprocess_page(&$vars){
  $path = $_GET['q'];

  if (strpos($path,'YOUR_PATH_STRING') !== false) {
    drupal_set_title('YOUR_TITLE');
  }
}

For example, if your path was yoursite.com/boogabooga, then you would set 'YOUR_PATH_STRING' to 'boogabooga' and 'YOUR_TITLE' to whatever you want the page title to be.
Comment: this doesn't work for hook_preprocess_user_profile
Comment: What could be the string to write for targeting the  page?


How to use saved instance state and restore instance state?

Question: I have an application with a tab activity. The activity hosts 2 activities with a list of items. I have implemented checkboxes to each of the items also. On orientation change, I have set the tab activity to be oriented to the left hand side of the screen. ie. the tab activity and the child activity are recreated. If i press the menu button to display the check boxes and checks a few items and if the orientation is changed, the checked items will not be shown in the check boxes. I handled the display of checkboxes while orientation change using the SharedPreferences.
I am putting the checked items to an arraylist. the arraylist cannot be transacted through the SharedPrefereces.
I want the checked items to remain checked on orientation change.
Does anyone have any clue?
Answer: You may store this arraylist in the host Activity through a interface like this: Custom event listener on Android app . But if there aren't so many checkboxes I would divide arraylist into simple kay-value preferences and store them  as a Shared Preferences.
Comment: The tab activity is also getting recreated while orientation change. Are you really sure about storing the arraylist in the host activity would work?


How to transform equation into linear

Question: I would like to write the following models in a form (using suitable transformations on
either x or Y ) where the new dependent variable, call it $Y˜$ , is linear in the new predictor, call it $x˜$.
How can I define the new Betas ($β˜_0$, $β˜_1$) are in terms of the old Betas ($β_0$, $β_1$)? Or is it impossible?
In my case the additive noise in the original model should be ignored.
1)
Y ≈ $β_0$ + ${β_1}^x$
For this one I thought $˜x=logx$, however I'm not sure if this is correct and I don#t know how to write the new beta in terms of the old betas.
Y ≈ $β_0$ * ${β_1}^x$
Y ≈ $β_0$ * ${x^β}_1$
$e^Y$ ≈ $β_0$  * ${x^β}_1$
Comment: This is clearly self-study, so please add the `self-study` tag.
Answer: The following transformation centers $Y$ on $\beta_0$, while $x$ retains its original meaning.
\begin{eqnarray*}
\ Y &=&\beta_0 + \beta_1^{x} \\
\ Y-\beta_0 &=& \beta_1 ^{x}\\
\ log(Y-\beta_0) &=& log(\beta_1) \cdot x\\
\ \tilde{Y} &=& \tilde{\beta_1} x
\end{eqnarray*}
Where $\tilde{\beta_1} = log(\beta_1)$. The original intercept cannot be identified anymore.
The following question might be useful as well:
Transform this non linear model $y=\beta_0+\beta_1x_1^{\beta_2}+\epsilon$ to a linear model $y^*=X\beta^*+\epsilon^*$

How to transform equation into linear


How to customize the daterangepicker(ngxDaterangepickerMd )

Question: I want to customize daterangepicker am using ngxDaterangepickerMd so that am getting start date in single input field i want to split start date and end date in two different fields so that if i do any modifications in start date or end date individually

        <input id="datepicker1" class="form-control dpFrom" type="text" name="daterange" placeholder="Departure"
                ngxDaterangepickerMd [(ngModel)]="selected" [minDate]="minDate" [showClearButton]="true"
        [singleDatePicker]="false">

        <input id="datepicker2" class="form-control dpTo" type="text" name="arrival" placeholder="Return">

Comment: Well, if you want start date and end date in two different fields, why're you using ngxDaterangePicker. Instead use Datepicker provided by angular-material. Have a look, it's easy to implement with the help of docs: https://material.angular.io/components/datepicker/overview
Comment: am using it because i need range in between two dates so am using this daterangepicker is there any daterangepicker with two fields  that is start date and end date.  I had done all my trials to customize the daterangepicker and finally am here  can you please refer me. Thank you
Answer: Call a event function using (datesUpdated) on input tag in html
html:
<input (datesUpdated)="datesUpdated($evnets)"/>

ts:
datesUpdated(range){
console.log(range.startDate._d);
console.log(range.endDate._d);
}

store start date and end date in different blocked variables.


How to allow a route to a user as long as he has the good role?

Question: Maybe this is a noob question but here goes:
I have a menu a menu that contains four links. However, I need one of the items to be accessible only if the current user has "beneficiary" as role.
Since the user's 'roles' is an array containing all kind of roles, how can I set my route in a way that as long as the user has the correct role ?
IE, let's say that a random user has the following:
<code>$user['roles'] = ['authenticated', 'beneficiary', 'elected'];
</code>
and would pass, but another random user having the following:
<code>$user['roles'] = ['authenticated', 'elected'];
</code>
wouldn't.
I'm pretty sure there is a way but I can't find explicitely what I'm looking for in Drupal's documentation
Thank you in advance
Comment: So essentially you need to allow access to a route if the current user has the "beneficiary" role?
Comment: Is this Drupal 8? Are you defining your route in a custom entity routing.yml file?
Comment: @Clive > yes, that's right, and yes this is Drupal 8 (I'll add a tag)
Answer: I've never personally tried this, but it looks like in your routing.yml file, you can specify a _role permission under requirements:
https://www.drupal.org/docs/8/api/routing-system/structure-of-routes
<code>my_module.your_route:
  path: '/your_menu_path'
  defaults:
    _controller: '\path\to\your\controller'
    _title: 'Menu title'
  requirements:
    _role: 'beneficiary'
</code>
Comment: You can also specify multiple permissions by separating them with ',' (comma) for AND logic or '+' (plus) for OR logic (e.g., _role: 'administrator,beneficiary').
Comment: I just had issues wether to place it since there was several possibilities, but now it works fine, I get 404 with a wrong user, thank you !


What is the term for the left hand part on piano and how do people create it?

Question: On a piano what does the left-hand part play, is it the counterpoint that is being played with the left hand? While the right-hand plays the melody?
Creating melodies on piano seems easy, but how do people create the left-hand part that makes the music sound much better like for example here at Badinerie - J.S. Bach BWV 1067.
Comment: Geenerally speaking - *accompaniment*.
Comment: This will depend very much on the particular role of the left hand, which simply plays *notes that are lower*. Different styles from different periods vary.
Answer: As Tim already mentioned in the comments, it could generally be called accompaniment.
You can categorize these in different types like:

Baselines
Chords
Arpeggios
Melodies
Ostinati
mixtures of multiples
...

Each of these can be categorized further like for example a baseline could be:

walking baseline
alberti bass
...

I think how these are typically build, depends a lot on the genre of the music. But they will all have in common, that they add some harmonic and rhythmic context to the melody.
Generally speaking, you could try to analyze the underlying harmony of your song/melody and use these harmonic information to build one of the types of accompaniment I have listed above.
Of course some theory knowledge will help you to analyze the harmonic information and choose how to make use of it.
Your question seems specifically pointed towards music in the style of Bach. I'm not very experienced in this type of music, so I will let this open to other users which might have a better grasp of explaining how an accompaniment could be build in this style of music.
As for the question if the left hand is counterpoint, Wikipedia says

In music, counterpoint is the relationship between two or more musical lines (or voices) which are harmonically interdependent yet independent in rhythm and melodic contour

So one could say, that you could play musical lines with your left hand which will create a counterpoint with your melody in the right hand, but your left hand playing will not necessarily be counterpoint.
Answer: you have to look up under accompaniment styles:
google search accompaniment styles
The software Band-in-a-Box offers hundreds of styles which include the rhythm section too - of course.
https://www.pgmusic.com/tutorial_realtrackslist.htm
Biab styles
In this song I have  written the melody and the counterpoint, all the rest is Band in a box accompaniment (except the brass fill ins in the chorus and at the end:

Creating melodies on piano seems easy, but how do people create the left-hand part that makes the music sound much better?

Well, this part can't be answered quite easy. You need some experience of listening and composing melodies and counterpoint to write in the style of Bach or Mozart. As you see in my own example I use in my counterpoint imitation, opposite movement, triads. Thus it is  the experience of listening and playing, but also the study of chords and harmony that enables you to write an accompaniment for the left hand (or an entire ensemble). Bach has used also triads and imitation and other elements I have mentioned.
The hints that Olli has given are all useful. The best way is listening, playing and analyzing lot of music and experimenting with these elements like you were playing with lego stones:
You need to have the music in your mind (and heart) that you can build your world like these lego-domino cracks:

You see: you need a lot of studying and practice and preparation to let the music flow like Bach, Mozart (and many others ...)


How can you retain the melody or tune you come up with in your head?

Question: I was trying to create a song and figured out what the melody would be like. I played it on my guitar and jotted down the chords in a notebook. The next morning i tried playing it, but i completely forgot how the tune went/what the rhythm was like. Is there any way to retain that tune in your memory? Or is it something wrong with me?
Comment: Someone once said that if the tune can't be remembered, it wasn't that good anyhow...Can't put a name to it, sorry.
Comment: @Tim: That's seems kind of apt, somehow!
Answer: I would recommend recording yourself. Recording devices are so cheap and common now, that it would be the easy solution.
As far a recalling a song or tune, there probably is not that much difference between remembering what you wrote yourself or someone else wrote.
Comment: I use the recording app that came free with my smart phone all the time.
Comment: My phone didn't come with a recording app by default (Nexus 6P). This one is very simple, and from a reputable source (Sony): https://play.google.com/store/apps/details?id=com.sonymobile.androidapp.audiorecorder&hl=en
Comment: iPhone comes with a voice recorder app. I use it constantly.
Answer: I also had this problem so i overcome by recording the tune by humming the melody using my mobile phone recorder as anyone always carry a i phone even during travel or any other moment.This had helped me to keep remember the melody which comes in my mind and later on i will sit with my keyboard and play the notes and write the notes in a music sheet using muse score notation software.You can also follow this method.
There is nothing wrong in you as human brain cannot remember the melody which accidently comes in our mind hence we need some method to instanty record it and refer for future.
Answer: Write it down.  If you don't know notation (and you've just told us why you would find it useful to know notation) record it.  You have a recorder in your pocket already, assuming you own a mobile phone.
Answer: I agree that you should record yourself. You could also learn to notate music. You either write it out on a staff or use something like solfege to make notes of how the melody went.
I think this is a common thing for many people. You hear about the great composers or writers who always keep a notebook with them on order to jot down notes so they won't forget them later. Remembering something new takes repetition or a strong context, which is likely since it is something new!


Prove that MLEs of two independent samples are independent

Question: I am trying to prove that if I have two samples of iid random variables, then MLE's based on these two samples will be also independent.
More formally, let
$$\mathbf{x} = (x_i)^T_{i = 1} \stackrel{iid}{\sim} \mathcal{N}(0,1), \quad \mathbf{y} = (y_i)^T_{i = 1} \stackrel{iid}{\sim} \mathcal{N}(0,1)$$ be two samples of the same size. Let
$$\theta_1 = \text{argmax}_{\theta} \mathcal{L(\mathbf{x}, \theta)}, \quad \theta_2 = \text{argmax}_{\theta} \mathcal{L(\mathbf{y}, \theta)}$$
be two MLE estimates of the same parameter $\theta$.
Problem: I want to prove that $\theta_1$ and $\theta_2$ are independent. Intuitively it is easy to see, because there are no chances for them to be dependent since the underlying samples are generated by iid random variables. But I am struggling to show this formally.
Any support will be appreciated.
Answer: If two random variables $X$ and $Y$ are independent, then for any (measurable) maps $f$ and $g$, $g(X)$ and $g(Y)$ are independent. This is a straightforward deduction of any definition you take for independence.
$\theta_1$ is a function of $\mathbf{x}$, $\theta_2$ is a function of $\mathbf{y}$, and $\mathbf{x}$ and $\mathbf{y}$ are independent. Therefore $\theta_1$ and $\theta_2$ are independent.
Comment: thank you! Indeed straightforward, didn't think from this perspective


Config import conflict, how to remove lock

Question: I am trying to import config on my staging site, and I repeatedly get the following message:

Another request may be synchronizing configuration already.

I know that there are no other processes currently importing config, so there is some rogue lock.
I am using config_split module on the site, but both methods of config import report the lock.
I have updated the site to Drupal 8.6.1 but the issue may have existed prior to the update.
Question: How can I remove the lock using Drush or some other method?
Answer: My specific issue was that Redis module update to 1.0 brought with it new redis.services.yml file in the module. Updating my site's Redis services file, in sites/default/, resolved the issue.
What was happening was that the alreadyImporting() method of ConfigImporter defaults to true, when in fact my mis-configuration would have been returning an error I think.
This issue pointed me in the right direction: https://www.drupal.org/project/redis/issues/2996655
If it had been a simple lock issue the following should have worked I think:
drush ev "\Drupal::lock()->release('config_importer');"

Comment: Bummer, unfortunately, this didn't resolve my issue. Oh well, thanks for posting.
Comment: This also happens when lock is moved to Memcached.
Answer: I had a memcache.yml file in sites/default that was switching the default lock backend with a memcache implementation. Since I did not have memcache running, I was unable to import the configuration.
Answer: Run drush cr, wait for 10 seconds, and try again. The import will work.


Como transformar uma string num objeto?

Question: Tenho a seguinte String:
$exp = "(10-9)+(7-6)";

Vamos supor que eu processe essa String e consiga retornar o seguinte resultado, no formato String:
$exp = "new Expressao(
    new Expressao(new Numero(10),new Operador('-'),new Numero(9)),
    new Operador('+'),
    new Expressao(new Numero(7), new Operador('-'),new Numero(6))
)";

Como faço para criar dinamicamente um objeto Expressao como indicado na String?
Comment: Tu quer fazer um parse em php eh?
Comment: @fernandoandrade estou fazendo uma função que recebe uma expressao numerica e transforma ela num objeto. Consegui tratar a string e monta-la como preciso, mas o resultado é uma string nao consigo executa-la. Eu quero executar o que está nessa string e assim criar um objeto expressao() com os atributos informados
Answer: Assim como o Tiago Luz respondeu, o eval serviria bem no teu caso, já que está tratando a string para receber apenas caracteres permitidos e acredito que você mesmo cria a string com os objetos, certo?
Um exemplo com o eval ficaria mais ou menos assim.
<?php
class Expressao {
    private $val;
    private $nu1;
    private $nu2;
    private $ope;
    function __construct($nu1, $ope, $nu2) {
        $this->nu1 = $nu1;
        $this->ope = $ope;
        $this->nu2 = $nu2;
    }
};
class Numero {
    private $val;
    function __construct($val) {$this->val = $val;}
};
class Operador {
    private $val;
    function __construct($val) {$this->val = $val;}
};
$exp = "new Expressao(
    new Expressao(new Numero(10),new Operador('-'),new Numero(9)),
    new Operador('+'),
    new Expressao(new Numero(7), new Operador('-'),new Numero(6))
)";

$r = eval('return ('.$exp.');');

var_dump($r);

Note que eu concateno um return com a expressão, isso é para que a variável $r receba o resultado da expressão e não apenas que ela seja executada. É como se o eval jogasse teu código dentro de uma função e executasse, então pra receber algo dessa função você precisa dar um return.
Espero que tenha ficado claro.
Eu ainda recomendo que você faça todo esse parser na classe Expressao, algo como
$exp = new Expressao('(10-9)+(7-6)');

E ali dentro você crie uma função que trate a string "(10-9)+(7-6)" e transforme ela nos teus objetos.

Você também consegue criar objetos "dinâmicos", por exemplo:
function getObj($val) {
    if (in_array($val, explode('', '(+-)'))) {
        $class = 'Operador';
    } else if (preg_match('/^[0-9]+$/', $val) > 0) {
        $class = 'Numero';
    } else return null;

    return new $class($val);
}

Porém não estou com tempo no momento para elaborar esse código ↑
Comment: Exatamente o que eu estava procurando
Comment: Legal! Não tinha visto sua resposta.
Answer: Você pode fazer isso com a função eval($code) do php.
O que estiver em $code será executado como se fosse código PHP. Cuidado com possíveis brechas de segurança!
Neste link está a explicação.
Comment: Já estava imaginando que seria eval(), porém não sei como utilizar essa função. Não há um exemplo no referido link que ajude a resolver o meu problema
Comment: No código há uma função que sanitiza a entrada string permitindo apenas números e  ( -  + ) acredito que não há maiores riscos com eval() de qualquer maneira é apenas um exercício de OO
Comment: A função eval($bla) executa o código php que está na variável $bla, como se ele estivesse escrito no seu script. Exemplo: eval("echo 'oi';");
Comment: Tiago Luz, você poderia formular uma respota, por que não consigo realizar a referida operação com eval(). Recebo a mensagem de erro: `eval()'d code on line 1`
Answer: A titulo de curiosidade
Pesquisando consegui achar uma forma de fazer com o que eval() crie o objeto tal como queria utilizando um closure
public function criaObjeto($obj){
        eval("\$newObj = function(){return $obj;};");
        return $newObj();
}

Não tenho total domínio sobre como trabalhar com eval() para afirmar se não gera uma falha de segurança.
No meu código coloquei uma função que sanitiza a entrada de dados permitindo apenas caracteres numéricos, ( , ) , + e -.
class Validacao{
    private function limpaString($obj){
        return preg_replace("/[^0-9\+\-\(\)]/", "", $obj);
    }
}

Contudo não tenho total certeza no que toca a segurança
Answer: O adequado seria você fazer dessa forma:
$ExpressaoObj->new Expressao();

Só que teu codigo está bem confuso e com erros!

Como transformar uma string num objeto?