What frequency ranges are most instruments in

Question: I made a spectrum analyzer, but I'm struggling to find a range where I can cover the most instruments, but also still make the bars visible.
I tried the range 20Hz - 800 Hz but seems like some songs I miss out on instruments. So, I tried to 20Hz - 2000 Hz.
I can see that drum and bass are in the lower region (20-200), I see that the piano is in the 400-700 range.
These are the ranges I show. The actual range I can show is up to 1/2 of the sample rate. (Most likely 24000 Hz)
Thus, the question arises "What frequency range fits the most songs in? Looking at Pop, Rock, House, Rap, etc."
Edit:
I want to gain knowledge with a spectrum analyzer for my next project which is an Arduino with LEDs that change color based on the frequency of the music.
The current setup is done by Javascript and AnalyserNode which uses FFT algorithm to convert signals into dB values.
As for limit of the analyzer. It should make catch the most common frequencies.
Comment: You need to do a lot more research, as there is a vast difference between different instruments' frequeny ranges. Also bear in mind all instruments produce *harmonics* which makes their range incredibly different from what it nominally appears to be.
Comment: @Helper If you divided the frequency range into 16384 steps, presumably you could then combine some of those 'bins' into ranges of your own choice...?
Comment: It would help to answer the question if you could tell in more detail what do you want to achieve. What is the purpose or application of your spectrum analysis?
Comment: also - can you add some detail about the problem of 'making the bars visible'? maybe that can be solved in a number of ways.
Comment: The problem is that you have to distinguish the frequency range of the instruments themselves from the frequency range of the equipment they are amplified/recorded/played-back  through. I think there are too many variables to give a direct answer unless you specify your precise setup.
Comment: A bit of research into frequency responses of microphones will help. After all, they're designed to capture useful sounds.
Comment: @Tim That is the plan, to do more research. Only I need a starting point. I will start looking into "harmonics". If you have other things I can look in to. Please let me know!
Comment: @topoReinstateMonica That's a more technical thing. If you take the screen with width X, then the width of a bar is X/amount of bars. The amount of bars depends on the frequency range and the amount of Hz represented by 1 bar. Which is calculated as follows frequency range / Hz by 1 bar. You can imagine that large frequency range is not showing much if the Hz by 1 bar is also larger. Thus I want to still be able to see the bars and tell with Hz they correspond with.
Comment: @user1079505 the post is edited
Comment: @Helper is splitting the frequency range up in a linear way like that the only way you could go? Could you perhaps split up the range into, say, 1/3 of an octave? That way you can represent a large range (20Hz-20KHz) with a manageable number of bars.
Comment: @topoReinstateMonica Yes, It is a linear function. As the last value is always 0.5 * sample rate of the song. The AnalyzerNode then divides it into steps of power 2, starting at 16 and ending at 16384. Giving steps of  1.4-1500 Hz. To quote the documentation: "Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz"
Comment: While I know playing w/ Arduino or other digital toys,  I'd like to suggest that it's pretty easy to build some analog filters / crossover nets and feed different frequency ranges directly to different output ports.
Answer: Full audible spectrum is 20Hz - 20kHz.
Having said that, if you don't want to or can't stretch to 20kHz, the lowest I would recommend going is to 8kHz.
I think the main question here is: what is the purpose of the analyzer?
Also, depending on the application, consider asking in Signal Processing; you could probably get better answers there.
Hope this helps!
Comment: Thanks for your suggestion. I shall take a look there. The purpose is to learn how spectrum analyzers work. How frequencies work in music and what they show. The ultimate purpose is to create a lamp that changes LEDs based on the frequency of the music.
Answer: When composing and engineering modern music, the full spectrum of audible frequencies may be taken into consideration. If you start at where the frequencies start to be heard as continuous tones and not drum beats (around 60Hz I think EDIT: remembering that wrong, around 20hz...), you can have instruments and sounds that cover the range all the way up to the threshold of hearing (around 15kHz).
Some audio engineers may separate the mix into different bands, having a low end bass, mid ranges and high "twinkle" sections. Mid range would be instruments like keys and guitars. Mid-high range could be things like voice, Harmonica, Accordion, and the high range instruments like whistles, Piccolo, cymbals and Tambourine.
If you are analyzing music you will probably want the full audible frequency spectrum, as even guitar heavy arrangements can have frequencies represented in the high range due to amp distortion and effects.
Comment: Surely frequencies start to be heard as continuous tones way lower than 60 Hz? The Low B string on a 5 or 6 string bass is about 31Hz, for example.
Comment: Recordings are not produced at 44.1kHz for nothing..
Comment: @topo yeah, that didn't sound right to me, but memory is a funny thing. I figured someone would correct me and I could edit... Looking it up, most people hear a tone around 20 hz, and some as low as 12...
Comment: You want the full range with an upper limit set to over 5 times the highest note you expect.  To avoid aliasing.
Comment: I was thinking of making buckets and  show each bucket. A bucket might be low end bass, mid ranges, etc. As you said. But do you have any chart or information where I could find the range of instruments?
Comment: @Helper the note ranges of various instruments was a question on this site not too long ago. I'll see if I can find it. It related to the range of symphonic instruments but I remember the answer had a good chart of the various ranges.
Answer: A piano can go all the way from A0 at 27.5Hz, up to C8 at 4186Hz (source).  If you wanted to capture harmonics in the notes, that would imply you'd need to handle higher frequencies than that.
Comment: Useful source I didn't know piano could go up to 4186 Hz. Any chance you also have a usefull source for this for other instruments?
Comment: @Helper Try http://www.orchestralibrary.com/reftables/rang.html but you will then have to look them up on the other site to find the frequencies.
Answer: The highest note on a piano is C8 and that's approximately 4186 Hz.  So, it is really hard to understand what you are using as a criterion for the limits of your spectrum analyzer.
There are instruments that go higher than that.  Regardless of this, you need to be able to sample higher than the harmonics that would normally get excited in real life or you will cause aliasing and generate false note detection within your instrument range.
You have not provided nearly enough info to determine what a good range is but if your limits will be used to set a max sampling frequency then I'd set that to something like 5*Max_Instrument_Note_Frequency.  Why?  Because it is very common for the first few harmonics of the fundamental to be present and detectable in a sound sample, either captured by a microphone or from a properly sampled wave file (or other format).  These harmonics are what create the unique tone of the instrument and are also dependent on the attack.  You might think that if all you want is the fundamental then you don't need to sample the harmonics.  The problem with that is that those frequencies are in the wave form and if you don't sample finely enough to get them they will be aliased into frequency bins in your analyzer.  This will then potentially be seen by you or some A.I. as a false fundamental and picked up.  Taking the highest note of a piano as the max (not necessarily a good choice) you should be sampling at least 20,000 Hz.  Room acoustics measurements sample a few times this, > 40kHz.  There could be high frequency sound present in the room that we cannot hear but would be picked up by a sensitive broad band microphone.
In addition to the points mentioned above the fact is, asking what a normal range for pop tunes is extremely subjective.  Some pop singers can hit notes in the 1000s Hz range.  The question is really too broad as worded.
Comment: I edited the start post with some info. It is always getting sampled at 1/2 of the sample rate. So if the sample rate is 48K Hz then the song is sampled at 24 K Hz. I edited in the post that the ranges I describe are what I show.
Answer:
For the purpose of music visualization you need logarithmic frequency range, as we hear the pitch as logarithm of the frequency. In other words you need narrow bands at low frequencies and wide at the high ones.

Full hearing range is 20Hz–20kHz, but you will rarely find a note with a fundamental frequency over several kHz. High frequencies however contain overtones of the notes, so they are more responsible for the sound, rather than note content. Percussive sounds have broad frequency range and often dominate at the high frequencies.

For the purpose of visualization, especially if you have limited number of channels (LEDs) you may choose some arbitrary frequency divisions, as you suggest "buckets". You may want to search internet for "music frequency chart" or similar, showing in which regions various instruments reside. Some guideline:

below 40 Hz: sub-bass
40–80 Hz: bass
80–200–400–800 Hz: low-middle-center mids. This is probably the most active region, this is where most melody notes (both vocal and instrumental) will fit, as well most of the harmonic/rhythmic instruments. You may want to divide this into several bands
800–4000 Hz: highest melody notes, overtones, percussive notes
above 4000 Hz: overtones and percussive notes

The sound power spectrum typically decays towards high frequencies, but on the other hand, if you make the bands wider at higher frequencies, they will pickup more power as well. Depending on how exactly you will do it you may need to adjust gain of each band so that you don't have "dead" regions in your visualizer. I believe there are math formulae for that, but I can't recall it at the moment.


Definition of the hessian as a bilinear functional on the tangent space

Question: In Milnor's Morse Theory, the Hessian of a smooth function $f : M \to \mathbb R$ defined on a manifold $M$ at a critical point $p$ is the bilinear functional on $T_p M$ defined as follows:
$$f_{**}(v, w) = \tilde v_p(\tilde w(f))$$
where $\tilde v, \tilde w$ are vector fields that extend $v$ and $w$.
It is written that $\tilde w(f)$ denotes the directional derivative of $f$ in the direction $\tilde w$ and that $\tilde v_p$ is, of course, $v$. I am assuming that this means $\tilde w(f) = T_p(f)(w)$, but

I do not know what it means to write $v(T_p(f)(w))$
it is claimed that $f_{**}$ is symmetric because $$\tilde v_p(\tilde w(f)) - \tilde w_p(\tilde v(f)) = [v, w]_p(f) = 0$$ since $p$ is critical.
If I am not mistaken, the argument used here is that since $p$ is critical, any directional derivative of $f$ at $p$ (e.g. $[v, w]_p(f)$) is zero, but wouldn't that also mean that $\tilde w(f) = \tilde v(f) = 0$?

Hopefully, I am only mixing up notations. I would appreciate any comment.
Answer: You don't need anything as sophisticated as Lie derivatives or connections to make sense of this. There are two main points to keep in mind:
First, if $w\in T_pM$ is a tangent vector at $p$, then $w$ acts as a linear map from $C^\infty(M)$ to $\mathbb R$; for any smooth function $f$, the number $w(f)$ is interpreted as the directional derivative of $f$ in the direction $w$. It can be written in a number of equivalent ways:
$$
w(f) = df_p(w) = T_p(f)(w).
$$
Second, if $\bar w$ is a smooth vector field and $f$ is a smooth function, then $\bar w(f)$ is another smooth function, whose value at $p\in M$ is
$$
\bar w(f)(p) = \bar w_p(f).
$$
So, given another vector field $\bar v$, we can apply $\bar v_p$ to this function and get a real number $\bar v_p(\bar w (f))$. Note that in general this value depends on knowing the vector field $\bar w$ in a neighborhood of $p$, not just on the value $\bar w_p$. Moreover, $\bar v_p(\bar w (f))$ and $\bar w_p(\bar v (f))$ might be different numbers, because
$$
\bar v_p(\bar w (f)) - \bar w_p(\bar v (f)) = [\bar v,\bar w]_p (f).\tag{$*$}
$$
(This is essentially the definition of the vector $[\bar v,\bar w]_p$.)
However, if $p$ is a critical point of $f$, then $[\bar v,\bar w]_p (f) = df_p([\bar v,\bar w]_p) = 0$, so $(*)$ shows that $\bar v_p(\bar w (f)) = \bar w_p(\bar v (f))$.  It also shows that this number is independent of the vector fields $\bar v$ and $\bar w$ chosen to extend the vectors $v$ and $w$, because the first expression depends only on $\bar v_p = v$ and the second depends only on $\bar w_p = w$. Thus at a critical point $p$, the Hessian of $f$ is a well-defined symmetric bilinear form on $T_pM$.  That's why Milnor treats the Hessian only at critical points.
Comment: This is exactly what I needed; thank you.
Comment: You're welcome!
Comment: One more thing: in order to see that $\bar v_p(\bar w(f)) - \bar w_p(\bar v(f))$ is of the form $z(f)$ for some vector $z$, we do need to use the bijection between derivations and vector fields, don't we?
Comment: Basically, yes. That's what I do my _Intro to Smooth Manifolds_, for example. But you can also just use that formula to define the _vector_ $[\bar v,\bar w]_p$ and show that it's a derivation at $p$ and hence a tangent vector at $p$, and then use a local coordinate computation to show it depends smoothly on $p$.
Comment: I see. Thanks again!
Answer: I have not read Milnor's book, so I cannot be sure that my notions agree with his, but I will take a shot.
First a bit of intuition in $\mathbb{R}^n$.  $H(v,w) \approx df(p+w,v)-df(p,v)$.  The Hessian really does tell you how the derivative changes infinitesimally.  In order to make sense of this on a general manifold, however, you need to be able to compare the tangent space at $p$ to the tangent space at $p+w$.  For this, we need the technology of a connection.  You may be interested in this answer for a more in depth idea.
The Hessian can be defined globally as a bilinear form given a connection $\nabla$ on the manifold just as $H = \nabla (df)$.  Thinking of a vector field as a gadget which eats functions and returns a new function (the directional derivative in the direction of the tangent field), we can also write $H(X,Y) = X(Y(f)) - df(\nabla_X Y)$.
This last formula shows that at a critical point, the Hessian is independent of the connection, and we just have $H(X,Y) = X(Y(f))$.  So we can actually make this definition of the Hessian at a critical point of a function on a manifold without a connection.  Another reason to think this is needed is that the second derivative (because of the product rule) transforms in a way that involves the first derivative, unless the first derivative is $0$.  So we cannot hope for an invariant definition of second derivative except at a critical point.
The Hessian is symmetric in this case since $[X,Y]_p(f) = df_p([X,Y]) =0$, since $p$ is a critical point.
Comment: I am not familiar with connections yet, but thank you nonetheless.
Answer: Part 1: In general, for a real-valued function $f$ on $M$ and a tangent vector $v$ at $p \in M$, $v(f)$ denotes the directional derivative of $f$ in the direction $v$.
By extension, if
$$
G : M \to \mathbb R^n: s \mapsto (G_1(s), \ldots, G_n(s))
$$
is a vector-valued function, then $v(G)$ denotes
$$
(v(G_1), \ldots, v(G_n))
$$
i.e., a list of the directional derivatives of the components of $G$. That's a list of vectors, which can be thought of as a matrix.

It's true that $\bar{w}(f) (p) = 0$; you have to understand that $\bar{w}(f)$ is a function defined in a neighborhood of $p$; its value at $p$ is zero, but it might have nonzero values elsewhere (and hence its directional derivative in some direction at $p$ might be nonzero, for instance). But $[v, w]_p (f)$ will be zero, for the reason you stated: $p$ is critical for $f$.

Let's make this concrete. Suppose that $M$ is the unit disk in $R^2$, $p$ is the origin, and $f(x, y) = x^2 + y^2$. Then $p$ is a critical point of $f$, right?
Let's pick $v = (1, 0)$ and $w = (0, 1)$. (And we can define $\bar{v}(x, y) = (1, 0)$
for $(x, y)$ near $(0,0)$ as well, and similarly for $\bar{w}$.)
Note that $v_p(f)$, the directional derivative of $f$ in the $x$-direction at $(0,0)$ is zero. But $\bar{v}(f)$ is the function $\bar{v}(f)(x, y) = 2x$, defined in a neighborhood of the origin. You can write out $\bar{w}(f)(x, y)$, I'll bet.
What's $w_p( \bar{v}(f)$? It's the directional derivative of $(x, y) \mapsto 2x$ in the $y$-direction at the point $(x, y) = (0, 0)$. That happens to be zero. Same goes for $w_P(\bar{w}(f))$.
You might want to work through all this stuff with a different $f$, like $f(x, y) = xy$, for possible further enlightenment.
Comment: So, using my notations, $\tilde v_p(\tilde w(f))$ is just the composition of Lie derivatives of functions $\tilde v \circ \tilde w$ applied to $f$ to yield a function which we then evaluate at $p$?
Comment: I'm not sure what "Lie derivative" means (I *used* to know), but if it refers to directional derivative in the direction of a vector field at each point, then the answer is 'yes, sort of'.I don't think that $\bar{v}\circ \bar{w}$ makes sense, because $v$ and $w$ are functions on $M$, but the values of $\bar{w}$ lie in $TM$, hence are not suitable as arguments for $\bar{v}$. If you replaced your "\circ" with a comma, then I'd say "yes".
Comment: Indeed, I should have written $L_{\tilde v} \circ L_{\tilde w}$, where $L_{\tilde v} : C^{k + 1}(M, \mathbf R) \to C^k(M, \mathbf R), f \mapsto (p \mapsto T_p f(\tilde v(p)))$ is a derivation.
Comment: Exactly. Couldn't have said it better myself (or typed the LaTeX so well!).
Comment: I think you're misinterpreting the action of a vector field on a function. In general, if $\bar v$ is a vector field, then $\bar v(f)$ is a _scalar_ function, obtained by taking the directional derivative of $f$ at each point in the direction $\bar v_p$. In your example, $\bar v(f)(x,y) = 2x$, not $(2x,0)$.
Comment: Absolutely right. I shouldn't answer questions before that first cup of tea in the morning. I was writing "directional derivative" and thinking "gradient", and ... I'll edit.


How to show all Elements in a Textview

Question: <code>    data class Fruit(val name: String, val price: Int)

    val fruits = arrayOf(Fruit(name = "Apple", price = 2), Fruit(name = "Grape", price = 3), Fruit(name = "Bananna", price = 4))

    for (index in fruits.indices)
        textView.text = fruits[index].name

    Output = Bananna
</code>
I cant seem to get all elements of "Name" to reflect in the Textview
Eg.
Apple, Grape, Pear
Comment: You're reassigning `textView.text` in the loop-- did you mean to append to it?
Comment: Not sure what you mean, but all I want is for all the "name" elements to appear in which ever text view.
Comment: It keeps only showing the last element, yet this does not happen when i dont use a dataclass
Comment: Try `textView.text += fruits[index].name`
Comment: No luck, its not excepting the "+"
Comment: How about `textView.text = textView.text + fruits[index].name`?
Comment: The other option is to "textView.text  = fruits.toString()" but then it prints everything as follows "(Fruit(name = "Apple", price = 2), Fruit(name = "Grape", price = 3), Fruit(name = "Bananna", price = 4))"
Comment: Still no luck with  "textView.text = textView.text + fruits[index].name" Still not excepting the "+"
Comment: OK, you need whatever string append is, which unfortunately I don't know
Comment: OK, final guess `text_view.text = "$text_view.text $fruits[index].name"`
Answer: I manage to figure it out !
<code>        val fruitNamesonly: MutableList<String> = ArrayList()

        for (item in fruits) {
            val token = item.name
            FruitNamesonly.add(token)
        }
</code>
val fruitNamesonly will be the vaulable you use for what ever

How to show all Elements in a Textview


How to change a list so that .setValues will display it in a specific range on a Google Sheet?

Question: I'm basically a beginner with coding and Google Apps Script and have hit the limits of my abilities. I have a list of values in Column A on sheet 1, and a second list (subset) in Column A on sheet 2. Sheet 1 is updated manually and includes a record number, file name, and color. Sheet 2 is only files designated "blue" in the color column and the goal is to run a check that makes sure that all record numbers for blue files from sheet 1 are on sheet 2, and if not, to add them.
Edited to add:
samplefile: https://docs.google.com/spreadsheets/d/1ji3R24V5y7j--1icUc4DpzOtulnEK9qT5N92lhuYSLI/edit?usp=viewing
Here's what I've got so far:
<code>    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var masterSheet = ss.getSheetByName('MasterList');
    var blueSheet = ss.getSheetByName('blue');

    var records = masterSheet.getDataRange().getValues();

    var lastBlue = blueSheet.getLastRow();
    var blueListAssigned = blueSheet.getRange(2,1,lastBlue-1, 1).getValues().flat();

    function getBluesOnly() {
      var allBlue = [];
      var newBlue = [];
      var colorColumn = records[0].indexOf("color");
      var recordColumn = records[0].indexOf("record");

      Logger.log('all records: ' +records);
      Logger.log('Blue finished ' +blueListAssigned);

     //Only keep records from MasterList when color is blue

      records.filter (function (row) {
        return (row[colorColumn] === "blue");
        })

      .forEach(function (row) {
      var newBlueRecord = row[recordColumn];
      allBlue.push(newBlueRecord);

        });

      Logger.log('All Blue Records: '+allBlue);

      //Check to see if blue records from MasterList are already on the Blue Sheet (assigned to blue)

      allBlue.forEach(function(each){
       if(!blueListAssigned.includes(each))
       {newBlue.push(each)}

        });

      Logger.log('New Blues to add: ' +newBlue);

      var firstBlankRow = blueSheet.getRange(lastBlue+1, 1, newBlue.length,1);
      var postNewBlues = blueSheet.setActiveRange(firstBlankRow);

      postNewBlues.setValues(newBlue);

    };

</code>
When I run this, all the logs show that all lists have the correct records in them, but then at the end I get this error:
Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues.
How do I change the parameters of newBlue so that those items can be added to the spreadsheet?
(I'm also open to completely different strategies for accomplishing this goal if there's a better approach)
Comment: What is a blue file?
Comment: Please provide a [mcve] which is reproducible by us. (i.e. that includes a sample of your data.)
Comment: here's the sample file https://docs.google.com/spreadsheets/d/1ji3R24V5y7j--1icUc4DpzOtulnEK9qT5N92lhuYSLI/edit?usp=sharing:
Comment: Everything you need for the code should be posted in the question. I do not follow links to other google accounts
Comment: apologies, as I said I'm new.  Sheet 1 includes 3 columns; record, name, and color. I'm trying to filter for those rows where the color is blue
Answer: Filter the blue lines:
<code>function filterthebluelines() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("MasterList");
  const [hs, ...vs] = sh.getDataRange().getValues();
  const idx = hs.reduce((a, h, i) => (a[h] = i, a), {})
  const blue = vs.filter((r,i) => r[idx["color"]] == "blue").map(r => r)
  blue.unshift(['record','name','color']);
  Logger.log(JSON.stringify(blue).replace(/],/g,'],\n'));//Added the replacement so lines would display vertically.  Otherwise blue is a a 2d array suitable for use in setValues() method.
}

Execution log
1:54:06 PM  Notice  Execution started
1:54:07 PM  Info    [["record","name","color"],
["A2","B2","blue"],
["A5","B5","blue"],
["A8","B8","blue"],
["A11","B11","blue"]]
1:54:08 PM  Notice  Execution completed
</code>
Data:

record
name
color

A2
B2
blue

A3
B3
red

A4
B4
green

A5
B5
blue

A6
B6
red

A7
B7
green

A8
B8
blue

A9
B9
red

A10
B10
green

A11
B11
blue
Comment: I can make that work! Thank you for your patience, and your help


How to use kotlin value class from java code?

Question: I have kotlin value class:
@JvmInline
value class MyValueClass internal constructor(val rawValue: String) {
    companion object {

        @JvmName("myTestValueClass")
        fun String.testValueClass(): MyValueClass {
            return MyValueClass(
                rawValue = "test",
            )
        }
    }
}

And now I'm trying to use my value class from java code.
MyValueClass test = MyValueClass.Companion.myTestValueClass("test");

But I get error: Required MyValueClass provided String.

Why is this happening? Please, help me.
Answer: testValueClass returns a String because that is exactly the point of value classes - they are inlined.
The whole point of value classes is that they are light-weight wrappers that has very little overhead. Kotlin tries very hard to not create instances of value classes.
In the JVM bytecode, value classes are replaced with the types they wrap, whenever possible, so that's why testValueClass returns a String as far as Java is concerned. The generated bytecode for testValueClass would be equivalent to return "test";.
In Kotlin, you can still use members declared in MyValueClass even without creating an instance of MyValueClass:
@JvmInline
value class MyValueClass internal constructor(val rawValue: String) {
    fun foo() {}

    // this actually generates a synthetic static method that does the same thing as foo:
    // public static void fooImpl(String str) { }
    // fooImpl is for demonstration purposes only, not the actual name of the method.
}

fun main(args: Array<String>) {
    // this doesn't actually create an instance of MyValueClass under the hood
    MyValueClass("Foo").foo()
    // this is translated to a static method call:
    // MyValueClass.fooImpl("Foo");
}

Recommended reading: Inline value classes in the Kotlin documentation.
In Java, however, there is no such language feature. If you want to call the foo method, you have to introduce an interface in Kotlin through which foo can be called, and provide a method that returns that interface. By using an interface type as the return type, you force an instance of the value class to be created.
interface MyValueClassInterface {
    fun foo()
}

@JvmInline
value class MyValueClass(val rawValue: String): MyValueClassInterface {
    companion object {
        // ...

        @JvmStatic
        @JvmName("box")
        fun box(x: MyValueClass) = x as MyValueClassInterface
    }

    override fun foo() {
        // ...
    }
}

MyValueClassInterface bar = MyValueClass.box(
        MyValueClass.Companion.myTestValueClass("Foo")
);
// now you can do
bar.foo();

Of course, you can also write a separate version of myTestValueClass that directly returns the interface.
Comment: Does the last Java code snippet actually run?
Comment: @JanItor Oh no. IntelliJ did its "this code does not compile but I will not show any errors" thing again. I'm really surprised that Java can't see the value class *at all*. Answer edited to do this in another way.


Como fazer para imprimir acentuação em um projeto Console Application .NET Core

Question:
using System;

namespace MediaDoisNumeros
{
    class Program
    {
        static void Main(string[] args)
        {
            Int16 numero1, numero2;
            Double media;

            Console.Write("Digite o numero 1 : ");
            numero1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("Digite o numero 2 : ");
            numero2 = Convert.ToInt16(Console.ReadLine());

            media = (numero1 + numero2) / 2;

            Console.WriteLine("A média dos dois numeros é {0}", media);
            Console.ReadKey();
        }
    }
}

Saída impressa no console :
A m├®dia dos dois numeros ├® 5
Como fazer para que seja impressa corretamente :
A média dos dois numeros é 5
Comment: A robustez do código não causa preocupação.
O problema é que o texto acentuado não é exibido corretamente.
Sim O média não e exibido corretamente.
O erro apontado é como utilizar acentuação em um projeto Console Application .NET Core.
Sim o arquivo .cs está gravado em unicode ( UTF-8 com assinatura ) - página de código 65001 pelo editor.
Comment: agradeço pelo esforço em tentar compreender o problema, mas me parece que não está preocupado em ajudar, e sim em que eu formule a pergunta de acordo com seus preceitos. Sinto muito não ter o seu nível de conhecimento para formular a pergunta de forma que lhe agrade.
Comment: @EricCastro se eu entendi direito, tente fazer o seguinte: Console.OutputEncoding = System.Text.Encoding.UTF8;
Comment: @miltoncamara muito obrigado cara acabei de achar esta solução no stackOverFlow em ingles acabei de testar funcionou mesmo, e vi sua resposta. Valeu!
https://stackoverflow.com/questions/5750203/how-to-write-unicode-characters-to-the-console
Comment: Bem vindo, dê um [tour] no site e veja [ask].
Comment: Fora este código ter uns problemas de estilo e robustez, qual o problema? O `média` no texto está dando problema? Qual o erro apontado? Onde está compilando? O arquivo `.cs` está gravado em UTF-8 pelo editor?
Comment: `O erro apontado é como utilizar acentuação em um projeto Console Application .NET Core` isso não é um erro que o compilador aponte. Só aparece errado? aí o problema deve ser onde está sendo mostrado, como eu não sei onde está compilando, rodando, não tenho como ajudar.
Answer: Para poder imprimir as acentuações é necessário definir o encoding do output do console, para isso adicione Console.OutputEncoding = System.Text.Encoding.UTF8 no início do seu código.
Ficando assim:
using System;

namespace MediaDoisNumeros
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            Int16 numero1, numero2;
            Double media;

            Console.Write("Digite o numero 1 : ");
            numero1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("Digite o numero 2 : ");
            numero2 = Convert.ToInt16(Console.ReadLine());

            media = (numero1 + numero2) / 2;

            Console.WriteLine("A média dos dois numeros é {0}", media);
            Console.ReadKey();
        }
    }
}


Question on semialgebra

Question: This exercise comes from A First Look At Rigorous Probability (Exercise 2.7.19):
Let $\Omega$ be a finite non-empty set, and let $\mathcal{J}$ consist
of all singletons in $\Omega$, together with $\emptyset$ and $\Omega$. Show that $\mathcal{J}$ is a semialgebra. Definition is semialgebra is here.
I don't think this is true. Consider the following
Suppose $\Omega = \{ \{1,2,3,4\}, 1, 2\}$. Then $\mathcal{J} = \{ \Omega, \emptyset, \{1\}, \{2\}\}$.
$\Omega \setminus \{1\} = \{ \{1,2,3,4\}, 2\}$, which cannot be written as a disjoint union of the elements in $\mathcal{J}$.
What's wrong with what I did?
Answer: Note that a singleton with respect to $\Omega$ is every set that contains a single element $w \in \Omega$. So in your example, $\{1,2,3,4\}$ is actually a singleton, and hence, it belongs to $\mathcal J$.
You can prove that it is indeed a semi-álgebra. First, let $A,B \in \Omega$ , the it is clear that $A\cap B$ is either a singleton or empty, hence, $A\cap B \in \mathcal J$.
Secondly, let $A, B \in \mathcal J$, then it's clear that $A-B$ is either empty, a singleton or the union of singletons. We then conclude that $\mathcal J$ is a semi-algebra.

Question on semialgebra


Telerik. Error! The requested URL returned 12030-

Question: I cant get to work my grid using telerik
here's my code:
MODEL
public class Office
{
    public int OfficeID { get; set; }
    public string OfficeName { get; set; }
    public string OfficeAddress { get; set; }
}

VIEWMODEL
public class OfficeViewModel
{
    public int OfficeID { get; set; }
    public string OfficeName { get; set; }
    public string OfficeAddress { get; set; }
}

VIEW
  @(Html.Telerik().Grid<Office>()
  .Name("Offices")
  .ToolBar(tb => tb.Insert())
  .DataBinding(binding => binding.Ajax()
  .Select("GetOffice", "Office")
  .Update("UpdateOffice", "Office")
  .Insert("InsertOffice", "Office")
  .Delete("DeleteOffice", "Office"))
  .DataKeys(keys => keys.Add(o => o.OfficeID))
  .Columns(cols =>
   {
      cols.Bound(c => c.OfficeID).ReadOnly();
      cols.Bound(c => c.OfficeName).Width(20);
      cols.Bound(c => c.OfficeAddress).Width(70);
      cols.Command(cmd =>
        {
           cmd.Edit();
           cmd.Delete();
        });
   })
)

CONTROLLER
public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }

[GridAction]
    public ActionResult GetOffices()
    {
        return View(new GridModel(GetOfficeViewModels()));
    }

 private IQueryable<OfficeViewModel> GetOfficeViewModels()
    {
        return db.Offices
                        .Select(
                        c => new OfficeViewModel
                        {
                            OfficeID = c.OfficeID,
                            OfficeName = c.OfficeName,
                            OfficeAddress = c.OfficeAddress
                        });
    }

LASTLY, THE LAYOUT.

@Html.ActionLink("Office", "Index", "Office")

please help me solve this problem i have already spent many hours on this. I'm only a beginner :(
Thanks
Comment: whats the problem you are getting
Answer: It's fixed now, it should be
.Select("GetOffices", "Office")

I missed the 's', sorry I'm new at this telerik thing
Thanks


Setting amount of time to pass when sending emails in a loop

Question: Forgive me for this noob question, but is there such a setting that sets a certain amount of time (e.g. milli/seconds) that has to pass in between sending emails through a script? How is that setting called and where do I change that setting?
I'll give an example:
I used to have a PHP script that sends emails like so:
for ($i=0; $i<count($emails); $i++) {
     mail($email[$i],'test','test');
}

It turned out that not all emails were sent successfully because the script ran so fast that there was not enough time in between sending emails that was required by the server.
Did I make sense?
Answer: You can use one of these functions to do nothing for a while :

sleep() : Delays the program execution for the given number of seconds.
usleep() : Delays program execution for the given number of micro seconds.

Putting one of those in your loop should help.
For example :
for ($i=0; $i<count($emails); $i++) {
    mail($email[$i],'test','test');
    usleep(100*1000); // 100 milli-seconds
}

Comment: If I remember correctly, at least on Linux, `max_execution_time` counts the amount of time during which PHP is *working* ; when *sleeping*, PHP is not *working*, and the time spent with `sleep()` or `usleep()` should not be included in the `max_execution_time` limit ;;; how much time should be used, in your case ? Well, you'll have to try a couple of values, to find the right ones for your servers ;-) *(There is no value that will be OK in all situations, I'd say)*
Comment: How many milliseconds/seconds should be enough?
I wouldn't want to set the sleep too high that the execution of my script would exceed the max_execution time :)
Comment: oh great! i only need to send around 200 emails. i don't think that would exceed the time limit. thanks man!
Answer: This script is untested but the theory is sound. Upon each send mail, check with a delay sequence to see if the mail has sent. I've set a limit to ensure the script does not fail - with the print, the execution time shouldn't be a problem.
for ($i=0; $i<count($emails); $i++) {
   $sent = mail($email[$i],'test','test');
    $count = 0;

   while($sent == false) {
    usleep(500); // half a second - test this number until the minimum is found
    $count++;

    if($count == 1000) {
        echo "Email to " . $email[$i] . " failed due to timeout
";
        break;
    }
   }
}

does that help?
Comment: great! :) but should usleep() be sleep(0.5) ? also, shouldn't the mail() be called again inside the while() ?
Comment: Well obviously if you want to be accurate about the code! Ha. my bad, I was thinking of actionscript and milliseconds usleep(500000) or sleep(.5) will both work. And I didn't want to put the mail() inside the while, as the while only ensures the previous email got sent before going "right ok, onto the next one" therefore creating a delay longer than half a second if required. The little counter and if statement is just a little defence to ensure the script doesn't endlessly loop. Effectively is pseudo for "send an email... am I done? am I done? am I done? am I do... Right NEXT ONE!"
Comment: thanks! I didn't know it's possible for the script to continue even though the mail() hasn't really finished yet, that's why i thought the mail() should again be put in the while. nice script :) thanks


Fazer loop percorrer de 20 em 20 linhas

Question: Gostaria que, a cada clique no botão contasse, e o mesmo invocaria a variavel para alterar a inicialização e a condição do laço for, para um valor númerico de 20 em 20.
Seria tipo percorrer do 0 à 20 e esperar outro clique. Logo noutro clique continuasse do 20 à 40 e aguardar novamente o próximo clique, que agora irá parti do 40 à 60 e parar novamente, e etc...
Isto é, o Laço for só é alterado na inicialização e a sua condição
for (inicialização; condição; incremento) {
...
}
Demonstração:
No primeiro clique
for (i = 20; i < 40; incremento) {
...
}
No segundo clique
for (i = 40; i < 60; incremento) {
...
}
No terceiro clique
for (i = 60; i < 80; incremento) {
...
}
e assim por diante, a cada clique.

Explicando - Aonde é 0 passa a ser 20 após o primeiro clique, logo onde era 20 torna-se 40 após o segundo clique, e assim se vai a cada clique no botão, sucessivamente, um após outro clique no botão será alterado seus valores.
Acho que ficou claro. Mudança dinâmica na sintaxe do loop a cada clique.
Comment: for (var i = 10; i < x; i += 10)
Comment: Explique melhor o último parágrafo, ele está confuso. Quer incrementar a inicialização? Tente certeza disto? Pra que? Quer incrementar a condição? Como?
Comment: O `i` terá o valor incremental de 1 mesmo? Tipo, será de 20 à 30, mas ele irá percorrer 21,22,23,24... E assim até chegar 30?
Answer: Se eu entendi a sua pergunta, basta criar uma variável com um scopo maior para ser o seu "contador" de click's, aplicando a regra no lool a cada clique. Veja um exemplo simples:

<button onclick="calcular()">
Calcular
</button>
Answer: o fromInclusive (inicialização) e o toExclusive (condição) devem vir de algum lugar. por exemplo, duas caixas de texto.:

var fromInclusive = document.getElementById("fromInclusive");
var toExclusive = document.getElementById("toExclusive");
var executar = document.getElementById("executar");
var resultado = document.getElementById("resultado");

executar.addEventListener("click", function (event) {
  var from = parseInt(fromInclusive.value);
  var to = parseInt(toExclusive.value);
  var result = 0;

  for (var indice = from; indice < to; indice++) {
    result += indice;
  }

  resultado.textContent = result;

  var diff = to - from;
  fromInclusive.value = from + diff;
  toExclusive.value = to + diff;
});

    fromInclusive:
    <input id="fromInclusive" type="text" value="0" />

    toExclusive:
    <input id="toExclusive" type="text" value="10" />

  <input id="executar" type="button" value="Somar Valores" />

Answer: Simples assim:
for (var i = 0; i < 100; i+=10)
{
    // ...
}

O incrementador ++ pode ser parametrizado.

++ incremento de 1;
+=n incremento de n, onde n deve >= 1;

Ele também pode ser um decrementador:

-- decremento de 1;
-=n decremento de n, onde n >= 1;
Answer: Depois de algumas tentativas baseado nas repostas aqui dos colegas, tive uma visão clara, basta definir duas variável com um scopo maior para ser inicialização e outra para condição, já o "contador de cliques" fica a parte. Vejamos o resultado disso, logo abaixo:

var n = 0; // Variável de Inicialização do laço
        var i = 0; // Variável de Condição do laço
        var j = 0; // Esta é variável que tão somente conta os cliques no botão

        function mais() {

            // Logo no primeiro clique inicia-se o Salto de 20 em 20 na declaração 2 - condição
            i += 20;

            // Exibi o(s) número(s) de clique(s) dado(s)
            document.getElementById('view').textContent = i;
            // Nesta linha iremos quebrar/dividir o(s) dado(s) de cada string
            barra = dados.split("|");

            for (x = n; x < i; x++) {
                if (barra[x]) {

                    // Logo abaixo exibimos a informação na página de cada string

                    document.getElementById('list').innerHTML += "
" + barra[x] + "
";
                }
            }
            // No segundo clique inicia-se o Salto de 20 em 20 na declaração 1 - inicialização
            // Isto se faz necessário para que não repita as primeiras linhas exibidas
            // mas que de continuidade nas seguintes após as primeiras e assim por diante ...
            if (j) {
                n += 20
            }
        }
        dados = //Isto é a nosso banco de dados para o nosso exemplo

            // O 1º clique - Mostra a listagem 1 do A - E
            "|A|Tam.: G|Cod.: 01|" +
            "|B|Tam.: M|Cod.: 02|" +
            "|C|Tam.: P|Cod.: 03|" +
            "|D|Tam.: P|Cod.: 04|" +
            "|E|Tam.: G|Cod.: 05|" +
            // O 2º clique - Mostra a listagem 2 do F - J
            "|F|Tam.: P|Cod.: 06|" +
            "|G|Tam.: M|Cod.: 07|" +
            "|H|Tam.: P|Cod.: 08|" +
            "|I|Tam.: P|Cod.: 09|" +
            "|J|Tam.: G|Cod.: 10|" +
            // O 3º clique - Mostra a listagem 3 do K - O
            "|K|Tam.: G|Cod.: 11|" +
            "|L|Tam.: M|Cod.: 12|" +
            "|M|Tam.: P|Cod.: 13|" +
            "|N|Tam.: P|Cod.: 14|" +
            "|O|Tam.: G|Cod.: 15|" +
            // O 4º clique - Mostra a listagem 4 do P - T
            "|P|Tam.: G|Cod.: 16|" +
            "|Q|Tam.: M|Cod.: 17|" +
            "|R|Tam.: P|Cod.: 18|" +
            "|S|Tam.: P|Cod.: 19|" +
            "|T|Tam.: G|Cod.: 20|" +
            // O 5º clique - Mostra a listagem 5 do U - Y
            "|U|Tam.: G|Cod.: 21|" +
            "|V|Tam.: M|Cod.: 22|" +
            "|W|Tam.: P|Cod.: 23|" +
            "|X|Tam.: P|Cod.: 24|" +
            "|Y|Tam.: G|Cod.: 25|";

        <input type="button" onclick="mais(j++)" value="Conta">

Mas porque teria que somar/percorrer de 20 em 20?
Digo! - Para o meu propósito como podem analisar estou buscando os dados de dentro de um método new String().
No entanto, queria somente exibir 5 strings por clique.
A cada dados entre as aspas duplas, temos as barras "|", que por sua vez faz a divisão dos dados, à saber são: 4 barras por string.
Sabendo disso, multiplica-se 4 barras por 5 strings = 20 linhas
Sendo assim, cria-se as var n=0, n += 20 e a var i=0, i += 20 para alterar a declaração 1 e declaração 2 do laço for
Então temos o salto de 20 em 20 linhas

NOTA - o que tinha em mente quando fiz esta pergunta era criar um efeito sroll infinito em Javascript Puro. Percebi que poderia fazê-lo com um loop jutamente com o método scrollTop(). Foi nessa intenção que cheguei a conclusão que, não só daria para criar o efeito scroll infinito com essa lógica, mas também, fazer paginação estática e randomizar a informações na página.
Pois não poderia utilizar a sintaxe do for como ela é em si, não teria como percorrer em sequência(números ordinais), naturalmente é assim que um laço faz.  Se eu o fizesse assim, a cada clique no botão ele me retornaria só a vigesima(última) linha de cada string.

Fazer loop percorrer de 20 em 20 linhas


SQL THREE TABLE QUERY FORMATION

Question: I have 3 tables
table a             table b                        table c
+--------+          ---------+-------            ------+-------+
| ID     |              ID  | STATUS|             ID  | STATUS|
+--------+         ---------+--------            -----+--------+
| 1      |              4   |  A    |              6  | A
| 2      |              5   | NULL  |              5  |NULL
| 3      |              1   | A     |              3  | A
| 9      |              2   | NULL  |              1  | NULL

Now I want a record from TABLE B and C which matches TABLE A ID
I wrote an query
SELECT DISTINCT ID
FROM
  (SELECT a.ID,b.STATUS FROM A a B b where a.ID=b.ID
   UNION
   SELECT a.ID,C.STATUS
   FROM A a,C C
   WHERE a.ID=C.ID) as T

it returns 3 records
but when I append where condition T.STATUS='A'
SELECT DISTINCT ID
FROM
  (SELECT a.ID,b.STATUS FROM A a B b
   WHERE a.ID=b.ID
   UNION
   SELECT a.ID,C.STATUS
   FROM A a,C C
   WHERE a.ID=C.ID) as T
WHERE T.STATUS='A'

it returns 2 records
again I changed WHERE condition as T.STATUS is null
SELECT DISTINCT ID FROM
 (SELECT a.ID,b.STATUS
  FROM A a,B b
  WHERE a.ID=b.ID
  UNION
  SELECT a.ID,C.STATUS
  FROM A a,C C
  WHERE a.ID=C.ID) as T
WHERE T.STATUS is null

it returns 2 records
totally 4 RECORDS but my first query without where condition it returns 3
How this mismatch? I know its my query problem but
I want to apply my where condition to only 3 records(query without where condition returns result).
Comment: Try to avoid comma seperated JOINS!
Comment: This can't be the SQL you're using.  Two from statements on the 2nd union select?
Answer: You are selecting distinct id.  id = 1 has rows with both 'A' and NULL.  The results make sense.
I would write the query as:
SELECT DISTINCT ID
FROM (SELECT a.ID, b.STATUS
      FROM A a JOIN
           B b
           ON a.ID=b.ID
      UNION
      SELECT a.ID, C.STATUS
      FROM A a JOIN
           C C
      WHERE a.ID = C.ID
     ) T

Note that your original query had at least one syntax error.  You should learn proper explicit join syntax.  Simple rule:  Never use commas in the from clause.
Comment: I was about to write the same! +1
Comment: Yes result make sense ,but i want to apply where condition to 3 records because i don't want to apply the where condition to duplicates of ID

SQL THREE TABLE QUERY FORMATION


$I = \int_{- \infty}^\infty \delta (n - \|\mathbf{x}\|^2) \, \mathrm d \mathbf{x} $ should not diverge

Question: I'm having trouble evaluating this integral:
$$I = \int_{-\infty}^\infty \delta (n - \|\mathbf{x}\|^2) \,\mathrm d \mathbf{x} $$
where $\delta(x)$ is Dirac delta function, $\mathbf x$ is the real $n$-dimensional vector $(x_1,\ldots,x_n)$, and $\|\mathbf{x}\|^2 = \sum_{i=1}^n x_i^2$. Here I use the short-hand notation:
$$\int_{-\infty}^\infty\mathrm d \mathbf{x} = \int_{-\infty}^\infty\mathrm d x_1 \cdots \int_{-\infty}^\infty\mathrm d x_n$$
Here is what I tried to do. Using the integral representation of Dirac's delta function $\delta (x) = \int_{- \infty}^{\infty} \frac{d \lambda}{2 \pi} e^{i \lambda x}$, I get
$$I = \int_{- \infty}^\infty d \mathbf{x} \int_{-\infty}^\infty
\frac{d\lambda}{2\pi} \mathrm e^{i\lambda(n - \| \mathbf{x} \|^2)} = \int_{- \infty}^\infty \frac{d\lambda}{2\pi} e^{-i \lambda n} \left( \int_{- \infty}^\infty e^{i\lambda x^2} \, dx \right)^n$$
I evaluated the inner integral with Mathematica:
$$\int_{- \infty}^{\infty} e^{i\lambda x^2} \, dx = \sqrt{\frac{\pi}{2}} \frac{1 +i \operatorname{sgn}(\lambda)}{\sqrt{|\lambda|}}$$
But then when I try to substitute this I get a diverging integral in $\lambda$.
What did I do wrong?
Note that the original integral is well behaved. Using polar coordinates it can be shown that $I = n^{n/2-1} \pi^{n/2} / \Gamma(n/2)$ (see  https://doi.org/10.1093/qmath/12.1.165, or my answer below). Some step of my derivation leads to a fictitious divergence.
Update: @user587192's answer found the error in my calculation. I cannot exchange the order of integrations on $x$ and $\lambda$. My next question is whether there is a way to rescue this calculation? Manipulations with the Fourier transform of the Dirac delta are very convenient in more complicated situations. This is evident from the algebraic complexity of the spherical coordinates appraoch. Is there way to exploit the convenience of the Fourier representation of the Dirac delta here?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/86468/discussion-on-question-by-becko-i-int-infty-infty-delta-n-mat).
Comment: Already $\int_{-\infty}^{\infty} e^{i\lambda x^2} dx$ is divergent, but can be interpreted and handled using distributions.
Answer: Here is the solution in (hyper)spherical coordinates, proving that $I$ should be well behaved. The spherical coordinates are defined by:
$$x_1 = r \cos(\phi_1),\quad x_2 = r \sin(\phi_1)\cos(\phi_2),\dots,\quad x_n = r \sin(\phi_1)\dots\sin(\phi_{n-2})\sin(\theta)$$
where $0\le\phi_i\le\pi$, $0\le\theta\le2\pi$ and $0\le r<\infty$. The volume element is then:
$$\mathrm d x_1 \dots \mathrm d x_n = r^{n-1}\sin^{n-2}(\phi_1)\dots\sin(\phi_{n-2}) \mathrm dr \mathrm d\phi_1\dots\mathrm d\phi_{n-2}\mathrm d\theta$$
We have:
$$\begin{aligned}
  I & = \int_{\mathbb{R}^n} \delta (n - \| \mathbf{x} \|^2) \mathrm d
  \mathbf{x}\\
  & = \int_0^{\pi} \mathrm d \phi_1 \ldots \int_0^{\pi}\mathrm d \phi_{n - 2} \int_0^{2 \pi}
  \mathrm d \theta \int_0^{\infty} \mathrm d r \, \delta (n - r^2) r^{n - 1} \sin^{n -
  2} (\phi_1) \ldots \sin (\phi_{n - 2})\\
  & = \left( \int_0^{\infty} \delta (n - r^2) r^{n - 1} \mathrm d r \right)
  \left( \int_0^{2 \pi} \mathrm d \theta \mathrm d \theta \right) \left(
  \int_0^{\pi} \sin^{n - 2} (\phi_1) \mathrm d \phi_1 \right) \ldots \left(
  \int_0^{\pi} \sin (\phi_{n - 2}) \mathrm d \phi_{n - 2} \right)\\
  & = \frac{\pi^{n / 2} n^{n / 2 - 1}}{\Gamma (n / 2)}
\end{aligned}$$
This is not an answer to my question. My question is: What did I do wrong to that leads to a divergent integral?
Comment: This is not an answer to your question. I think you'd better add it to your post instead of here.
Comment: @user587192 It is not an answer. But it is customary on this site to sometimes post solution attempts as (incomplete) answers.
Answer: There is a trick one can do to use the Fourier transform and still have converging integrals. The trick is to multiply the integrand by $\mathrm e^{(1-||\mathbf x||^2)} = 1$. Then
$$\begin{aligned}
  \int_{- \infty}^{\infty} \delta (1 - ||\mathbf x||^2) \mathrm d
  \mathbf x & = \int_{- \infty}^{\infty} \mathrm d \mathbf x
  \int_{- \infty}^{\infty} \frac{\mathrm d \lambda}{2 \pi} \mathrm e^{(1
  +\mathfrak{i} \lambda) (1 - ||\mathbf x||^2)}\\
  & = \int_{- \infty}^{\infty} \frac{\mathrm d \lambda}{2 \pi} \mathrm e^{1
  +\mathfrak{i} \lambda} \left( \int_{- \infty}^{\infty} \mathrm e^{- (1
  +\mathfrak{i} \lambda) x^2} \mathrm dx \right)^N\\
  & = \int_{- \infty}^{\infty} \frac{\mathrm d \lambda}{2 \pi} \mathrm e^{1
  +\mathfrak{i} \lambda} \left( \frac{\pi}{1 +\mathfrak{i} \lambda} \right)^{N
  / 2}\\
  & = \pi^{N / 2} / \Gamma (N / 2)
\end{aligned}$$
which is the correct result. Here all intermediate integrals converge and the integration order can be exchanged.


calculate the limitation

Question: I have encountered a limitation:
$$ \lim_{h \to 0} \frac{\int_1^{1+h} \sqrt{x^2+8}dx}{h}$$
I wanted to use the L'Hopital rule, but to take the derivative of the integral?
Comment: Hint:  this looks a lot like a derivative.
Comment: I know it just the $\sqrt{x^2+8}$ but should we take the value 1 to calculate the limit?
Answer: Let me call the following function $F:$
$$F\colon\mathbb R\rightarrow \mathbb R\colon t\mapsto F(t)=\int_1^t\sqrt{x^2+8}\text dx.$$
Then, the limit you're trying to calculate becomes
$$\lim_{h\rightarrow0}\frac{\int_1^{1+h}\sqrt{x^2+8}\text dx}h=\lim_{h\rightarrow0}\frac{F(1+h)-F(1)}h.$$
If you still have problems continuing on your own, feel free to ask!
Comment: Hi, so actually by using the l'hopital rule in this case, since denominator and nominator both becomes 0 when $h \to 0$ it becomes: $\lim_{h \to 0}\frac{f(1+h)}{1}=\sqrt{1+8}=3$?
Comment: You can also avoid L'Hopital and just invoke the fundamental theorem of calculus.
Comment: Not only that, but $\lim_{h\rightarrow0}\frac{F(1+h)-F(1)}h$ is _defined_ as $F'(1)$ (unless the limit doesn't exist), and you correctly identified this as $f(1)$ already.
Comment: So, yes, your answer is correct.
Answer: If you have a continuous $f$ and call $\displaystyle F(x)=\int_0^x f(t)dt$
Then $f(x)=F'(x)=\lim\limits_{h\to 0}\dfrac{F(x+h)-F(x)}h$
Can you identify which is which is this exercise?
Answer: Mean value theorem, integrand is continuos.
$I(h):= (1/h) \int_{1}^{1+h}\sqrt{x^2+8}dx =$
$(1/h)h\sqrt{t^2+8},$  $1\le t \le (1+h)$
$\lim_{h \rightarrow 0} I(h) = $
$\lim_{h \rightarrow 0} \sqrt{t^2+8}$ , $1\le t\le 1+h.$
Can you take it from here?

calculate the limitation


Which metric should I trust to evaluate my predictive model

Question: I am working on predictive model and when I evaluate it, I find good accuracy_score, precision_score, recall_score, and f1_score. But I don't get good results using confusion matrix.
What is the metric that should I Trust ?
accuracy_score:  0.987727165447
confusion_matrix: [[338961   3857 ]
                   [   252     27  ]]
precision_score: 0.998449790932
recall_score:    0.987727165447
f1_score:        0.993031083087

I am using Scikit-Learn metrics.
'precision' sklearn.metrics.precision_score
'recall'    sklearn.metrics.recall_score
'f1'        sklearn.metrics.f1_score

Answer: The problem is that you have highly unbalanced classes. If 99% of the data have y = 0, to get high accuracy, all you have to do is predict y = 0 regardless of the features in the data set. This shows that your model is accurate only because the classes are so highly unbalanced, but it is not good at actually differentiating between the two classes. None of the statistics are best, they just tell you different things about your model's fit.
A metric like AUC, Gini or KS would be better for comparing models and evaluating model fit when you have highly unbalanced classes. These statistics rank order the predictions and remove the effect of unbalanced classes. Even with an unbalanced sample, if you predict y = 0 for all of your data, you will get AUC = 0.5. Keep in mind that you also want to use a hold out sample for these evaluation metrics.
For AUC details, check out http://en.wikipedia.org/wiki/Receiver_operating_characteristic or http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html for implementation in Python.
Comment: You can sample from your data set to obtain a balanced sample or penalize the model for missclassifying the minority class. Interesting article here: http://statistics.berkeley.edu/sites/default/files/tech-reports/666.pdf.
Comment: One more question, What are the techniques to balance the classes. I used two approaches to balance the data [1-weight function with SVM, and 2- KNN to predict based on the neighbors' results] Can you recommend anyother approaches ?
Comment: Yes, Thanks a lot, I was waiting the results as it's taking time. Just one more question, I found AUC varying between 0.7 and 0.8. Is this good sign, Can you give me an interval to say that my predictive model is acceptable, good, great.


Representation of a 5/16 note duration

Question: How can I write on a pentagram (another word for the staff in my country) a note that is 5 x 1/16 notes length?
If I use a dotted quarter note I get 6 x 1/16 length
I can get away with a quarter note (crotchet) and a 1/16 silence but still want to learn about it.
Comment: @Tim in some countries (Greece included) you call the staff a pentagram (from the greek πεντάγραμμο - πεντε + γραμμες = five lines) which make the staff
Comment: Do you mean a staff or stave, with its five lines?  A pentagram is a 5-pointed star.
Comment: Thanks, Shev. I googled it, and saw hundreds of pics with 5 lines, but they all made stars! I knew it was from Greek, but couldn't find any reference music-wise. I guess most folk would recognise staff/stave more easily. I love this site - something new to learn every day!
Comment: @Tim Oh, I didn't knew the word stave, I assumed that it was pentagram, as in Spanish we call it "pentagrama", at least in Argentina.
Answer: You'll have to represent it with a tie. In 4/4, the simplest and most direct way is to represent it with a quarter note tied to a 16th note as such:
Comment: Or  eighth tied to dotted eighth :-) but yours is certainly the easiest to read
Comment: Thanks Dom! I tried this on a music composition software but it didn't work, then after seeing your answer I changed the software and it worked. BTW I can't find the button to accept your answer
Comment: @Rombus another easy way to find what you're looking for is to fill the whole measure with 16th notes , tie the ones you want and then see what that leaves you with
Answer: A single note with this duration is a triply dotted triplet quarter note:

triple dotting increases the duration by a factor of 15/8
notes in a triplet are shortened by a factor of 2/3
the product of these factors is 5/4

But there are serious problems with this approach:

it is cumbersome if not impossible to apply triplet shortening to a single note
doubly and triply dotted notes are not readily comprehended except as one element of a pair (for example, dotted quarter and eighth, doubly dotted quarter and sixteenth, triply dotted quarter and 32nd)
nobody is going to be able to do all this arithmetic in their heads while they're playing an instrument or singing.

By contrast, reading tied notes is an elementary skill, and if the component values of the tie are chosen carefully, the relationship between the metrical pulse and the note's beginning and end will be clear.
The goal of music notation is not to express pitch and duration in the most efficient way possible, but to communicate with a reader, whether for performance or study.
Since the relationship between rhythm and meter is an important part of that communication, the use of tied notes to represent complex rhythms, especially unfamiliar ones, is a feature, not a bug.
Also see my answer to How to represent 5 eighth-notes as one note?
Answer: A double dotted quarter note triplet is correct. Quarter note triplet = 2/3. x1.5 for the first dot, that = 1, making it a quarternote, x1.25 for the second dot and that is 5 16th notes.
Comment: How can a single note be a triplet?
Comment: A triplet is just a note value, 1/3 for 8th note, 2/3 for quarter note, 1/6 sixtuplet. For a single note to be a triplet it just needs to be indicated as such.
Comment: This doesn't add up.  The second dot adds 0.25x the original note value- so, 1/4th of a quarter note triplet in this case.  It doesn't add 0.25x the dotted note value.
Comment: I see that someone else has also posted this answer and it was similarly explained why it's wrong.
Comment: @Edward but it's close!  I've posted an answer: https://music.stackexchange.com/a/135266/2257
Answer: Without ties can also use a double dotted triplet.
Comment: @awelotta the factor for a double dot isn't 1.5^2, which is 9/8, but 1.75, which is 7/4.  The equation should therefore be `a * 1.75 = 5/16` which gives a = 5/28.  This also can't be written with triplets :-)
Comment: Could you show the math? It seems like it shouldn't work. Also, I think this suggestion would be fairly annoying to read, if it does indeed work, though the performer would probably get used to it.
Comment: You could write out an equation, so like `a * 1.5^2 = 5/16`, where 5/16 is the note length we want and 1.5^2 is the double dot. Solving for `a` would give 5/36, which can't be written with just tuplets, and certainly not triplets.
Comment: @awelotta but the factor for a triple dot is 15/8, which has a factor of 5 in the numerator, so we're in luck.  Or not.  https://music.stackexchange.com/a/135265/2257

Representation of a 5/16 note duration


Drupal entity metadata wrapper no bundle property

Question: Using <?php
$wrapper = entity_metadata_wrapper('node', $nid);
?>

When I $wrapper->title->value(); I get error msg that property Title does not exist....
Using Entity 7.x 1-8 and D7.56. I am aware that $nid can be a node (from node_load) or a node id.
What am I missing?
Comment: I was just fiddling around with a test Drupal 7. The only way I could reproduce an error was by giving a non-existent `$nid` value. Are you sure the node in question exists?
Comment: The issue you linked is (in my opinion because I faced it last year) resolvable by increasing your opcache memory consumption value and your opcache memory value - in regards to the "missing token information". Basically if this is related, you don't have enough cache to store it all.
Answer: I solved it applying this patch:
https://www.drupal.org/project/entity/issues/2819665
although I to be honest don't understand why...


Error with MUI-dataTables when i get data from API

Question: enter image description herecodeI tried  to get data from API and show it with MUI-dataTables
but this error occurred (you can see it in attached image) I using it with create react app
**
import React,{useEffect,useContext, useState} from 'react'
import MUIDataTable from "mui-datatables";
import axios from'axios'
const columns = [
    {
        name: "name",
        label: " name",
        options: {
      filter: true,
      sort: true,
     }
    },
    {
        name: "username",
     label: " username",
     options: {
      filter: true,
      sort: true,
     }
    },
    {
        name: "email",
     label: "email",
     options: {
      filter: true,
      sort: true,
     }
    },
   ];

const options = {
    filterType: 'checkbox',
    serverSide: true
};

function Users() {
    const [users,setUsers]=useState('');
    useEffect(()=>{
      const getUsers = async ()=>{
         await axios.get('https://jsonplaceholder.typicode.com/users').then(response=>{
            setUsers(response.data);
         })
      };
      getUsers();
    },[])
    return (

             <MUIDataTable
                title={" Users"}
                data={users}
                columns={columns}
                options={options}
            />

    )
}

export default Users

Answer: Because props data in MUIDataTable is required an array. While fetching API, the users is a string `` (because const [users,setUsers]=useState('');). So this error appear.
To fix, you need to update initial value of users is an array like this:
[users,setUsers]=useState([]);

Comment: Thanks for your answer it worked and data are shown , but all functions (filtration , searching , pagination) doesn't work when i make option (serverSide :true ) is there any solution using hooks
Comment: It not related to this question


Highlight and replace arguments in autocompleted functions in PyDev interpreter

Question: When I hit Ctrl-Alt-Enter in PyDev and begin typing a function name into the interpreter, PyDev helpfully offers a list of autocompletions. When I hit Enter, PyDev completes the function name and adds the parameter names, in parentheses. This would be great, except that the parameter names aren't highlighted, so I have to delete the parameters (or type an octothorpe) before I hit enter.
Is there a way either of making PyDev highlight the parameter names (ideally letting you tab to the next one, as it does in the editor) or of omitting them altogether? Having to manually delete the parameters defeats any efficiency gains from autocompletion.
Answer: Unfortunately this cannot be currently configured.
Still, you should be able to apply the completion with Ctrl+Enter (instead of only with Enter). That way the completion is applied without the arguments (nor the parenthesis -- which may not be 100% what you want) -- note that the same can be done in the PyDev editor, not only in the interactive console.
Please add this to the PyDev features tracker.


Can the true guitar sound be made purely in software?

Question: I know that in modern sound-production software it is possible to reproduce all sorts of music instruments. But I don't remember that I've seen a software reproduction of a classical guitar.
Is it possible to create a guitar sound in software, which would sound as a real guitar, like in this track, for example?
It is electronic music, but I don't believe that the guitar sound there was created with software.
Comment: As a software engineer, my answer is that you cannot reproduce an analog sound with a digital substitute perfectly. However, you can reproduce it well enough that no human ear is able to distinguish between the two.
Comment: Strange but true anecdote. One friend had used a sample guitar to play a part he later wished to replace with the real thing. Other friend comes over, we mic up, he plays the part. Utter confusion... do we have the mutes wrong, why aren't we hearing the new part only the guide sample?... took a while to figure out... guitarist & equipment were the same guy/gear as made the sample set. Grins all round :)
Comment: Are you talking about samples or synthesis? Most of the "reproduced" instruments you are hearing are just multi-sampled and well-articulated.
Comment: @DonBranson nailed it.
Comment: That depends entirely on what you want the simulated "guitar" to sound like...
Comment: At the moment of writing the question I didn't really know about the two different techniques. For the matter of producing sound on a computer it doesn't really matter, but of course synthesis is a more interesting method.
Answer: (I think the sound in the song you linked is a steel-string guitar, if it's the sound my ear picked out, rather than a classical guitar.)
The most common way to reproduce a guitar sound with other technology is to use sample-based synthesis to replicate the guitar sound. Whether that counts as a "software reproduction" of a guitar by your criteria, you'll have to tell me :). It's very easy to get good representations of some instruments with this technique, but guitars are a little more challenging than you might think, due to a number of subtleties in, and combinations of, ways you can fret the strings and articulate notes. Modern sample libraries and sample-based instruments often deal with this simply by sampling many different instances of differently-struck notes, including samples that work well as part of a strum, and also fret noises and other playing sounds that make the part sound more authentic.
Here's a sample-based classical guitar:

and a steel string:

In both of those 'performances'', you can probably hear aspects that are convincing, and aspects that are less so. That isn't to say that it wouldn't be possible to do an even better job, but it comes down to the amount of effort that you would need to put into each track to fine-tune it to be really convincing - at some point, if realism is your aim, it's a lot easier just to find a guitarist who can play the piece for you.
It would also be possible to produce a realistic job using physical modelling or additive synthesis - this might more fully fit the brief of being a "software reproduction" of a guitar. However, I don't know of commercial products using these synthesis methods that go as far as commercial sample-based products in handling the many special cases of guitar playing techniques - you'd probably have even more work to do to get to a certain level of realism.
Comment: @CarlWitthoft I wasn't aware there was a controversy about golden ears. Only someone who can't believe that another person might have better hearing than they could disbelieve in golden ears. I know I hear better than many and worse than some, so I'm sure many hear things that I do not, just as many do not hear what I hear. I've sat in a room with engineers and musicians and said, "can we please stop that high pitched feedback?" To which everyone else responded that they did not know what I was talking about. Totally off topic, of course.
Comment: It's all the "golden ear"  controversy :-)
Answer: "true"?  No.  Truth does not depend on quality.
But listen to about 35:15 in this part of a multitrack demo session hacked together within a lecture and you'll find that the guitar track, a pure Midi rendition by Fluidsynth from the output of the music typesetter LilyPond (so with a very very rigid timing) is the least of the problems here.
Now Fluidsynth uses freely available audio samples.  Commercial Midi expanders tend to be noticeably better in quality.  At home, I'd rather use the output of a Solton MS40 and that thing is from the 90s.
If you are playing tricky solos, Midi expanders will have a bit of a problem delivering them believably.  But much much more so with continuous-tone instruments under constant pliable player control like a solo violin (violin sections actually work better).  Wind instruments like saxophones are already less conspicuous even though they are ostensibly continuous-control instruments as well.  Basically percussive instruments like piano and guitar can be pretty well represented by a limited number of samples and some envelope trickery.
You never can reach "true" by definition, but "good enough" is easily doable for a lot of purposes even with old technology, and certainly more so with newer devices.
Answer: I will assume you're asking about synthesis/simulation, and not just making a digital recording and playing that back.  Most people can distinguish between recorded sound and being in the same space as a real live instrument, the sound is being created by different mechanisms, sort of like comparing 2D with 3D.
For synthesis, if somebody did enough research, analysis and mathematics, there's no reason why they couldn't create a dedicated simulation of any instrument that didn't use real audio samples.
Reproduction of the sound is not a challenge for the computer, or the software, the challenge is determining the mathematics required to generate the sounds.
Some instruments will need a handful of parameters to generate a convincing tone, other instruments may need significantly more parameters.
Some of those parameters will be fixed because they are connected to the style or state of instrument being simulated, other parameters will be variable because they are determined by the way the instrument is being played.
So I think yes, software can produce a convincing digital reproduction of the sound of any instrument, indistinguishable from a digital capture, if only we solved the problem of how to actually do that.
None of the images in this page (https://www.flickr.com/photos/bbb3viz/) are photographs, they're all generated by a 3D rendering engine. If software can take a 3D model of a landscape and produce photo-realistic images. Then yes, software can absolutely take a model of a musical instrument, and produce the equivalent audio-realism.
We just need to learn how to model them.  Something I wouldn't mind experimenting with myself, if only I had the time. :(
As for actually performing that instrument in a way a human would, well that's a whole new level.  One step at a time, eh?
Comment: Although, the modellers making these models do use real artefacts to generate textures.  This could be compared to using samples of real instruments, but I'm sure that's just a shortcut to eliminate the difficulty/effort/time involved in simulating textures.


How to reload AppleFileServer without unloading it?

Question: I am using this commands to restart my AppleFileServer for sharing.
But how I can reload it, without killing, or unloading it?
sudo killall DirectoryService
sudo AppleFileServer
sudo launchctl unload /System/Library/LaunchDaemons/com.apple.AppleFileServer.plist
sudo launchctl load -F /System/Library/LaunchDaemons/com.apple.AppleFileServer.plist

P.S. The reason I'm asking when I kill it or unload, connection is getting disconnected. I want to reload it without losing connection.
Answer: If it's OSX Server, use sudo serveradmin start/stop afp.


Irreducibility of polynomial in $\Bbb F_p[x]$

Question: What can we say about the irreduciblity of $x^{q-1} + \cdots + 1 $ in $\Bbb F_p[x]$ where $p,q$ distinct primes?
In $\Bbb Z[x]$ we may apply a transformation and apply Eisenstein's criterion. But $\Bbb F_p$ has no more prime ideals.
Answer: $x^{q-1}+x^{q-2}+\cdots+x+1$ is the $q$-th cyclotomic polynomial.
It is irreducible over $\Bbb F_p$ iff $p$ is a primitive root modulo $q$.
This is because adjoining the $q$-th roots is unity to $\Bbb F_p$
gives $\Bbb F_{p^k}$ where $k$ is the least integer with $q\mid
(p^k-1)$.
Comment: In other words, irreducibility $\Leftrightarrow q$ does not divide any of $p-1, p^2-1, ..., p^{q-2}-1$.


textview not updating (shoutcast stream metadata in android 2.2)

Question: i have a IcyStreamMeta.class that gets the metadata info of shoutcast Stream i use the method below to update the textview in my main activity and display the current song title playing. the code below works on android 2.1 and android 1.5 somehow it doesnt work on android 2.2 i dont know whats wrong i cant figure it out. i need you help guys :)
here is my IcyStreamMeta class
public class IcyStreamMeta<Message> {

protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;

public IcyStreamMeta(URL streamUrl) {
    setStreamUrl(streamUrl);

    isError = false;
}

/**
 * Get artist using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getArtist() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    String streamTitle = data.get("StreamTitle");
    String title = streamTitle.substring(0, streamTitle.indexOf("-"));
    return title.trim();
}

/**
 * Get title using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getTitle() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    String streamTitle = data.get("StreamTitle");
    String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
    return artist.trim();
}

public Map<String, String> getMetadata() throws IOException {
    if (metadata == null) {
        refreshMeta();
    }

    return metadata;
}

public void refreshMeta() throws IOException {
    retreiveMetadata();
}

private void retreiveMetadata() throws IOException {
    URLConnection con = streamUrl.openConnection();
    con.setRequestProperty("Icy-MetaData", "1");
    con.setRequestProperty("Connection", "close");
    con.setRequestProperty("Accept", null);
    con.connect();

    int metaDataOffset = 0;
    Map<String, List<String>> headers = con.getHeaderFields();
    InputStream stream = con.getInputStream();

    if (headers.containsKey("icy-metaint")) {
        // Headers are sent via HTTP
        metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
    } else {
        // Headers are sent within a stream
        StringBuilder strHeaders = new StringBuilder();
        char c;
        while ((c = (char)stream.read()) != -1) {
            strHeaders.append(c);
            if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
                // end of headers
                break;
            }
        }

        // Match headers to get metadata offset within a stream
        Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
        Matcher m = p.matcher(strHeaders.toString());
        if (m.find()) {
            metaDataOffset = Integer.parseInt(m.group(2));
        }
    }

    // In case no data was sent
    if (metaDataOffset == 0) {
        isError = true;
        return;
    }

    // Read metadata
    int b;
    int count = 0;
    int metaDataLength = 4080; // 4080 is the max length
    boolean inData = false;
    StringBuilder metaData = new StringBuilder();
    // Stream position should be either at the beginning or right after headers
    while ((b = stream.read()) != -1) {
        count++;

        // Length of the metadata
        if (count == metaDataOffset + 1) {
            metaDataLength = b * 16;
        }

        if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
            inData = true;
        } else {
            inData = false;
        }
        if (inData) {
            if (b != 0) {
                metaData.append((char)b);
            }
        }
        if (count > (metaDataOffset + metaDataLength)) {
            break;
        }

    }

    // Set the data
    metadata = IcyStreamMeta.parseMetadata(metaData.toString());

    // Close
    stream.close();
}

public boolean isError() {
    return isError;
}

public URL getStreamUrl() {
    return streamUrl;
}

public void setStreamUrl(URL streamUrl) {
    this.metadata = null;
    this.streamUrl = streamUrl;
    this.isError = false;
}

public static Map<String, String> parseMetadata(String metaString) {
    Map<String, String> metadata = new HashMap();
    String[] metaParts = metaString.split(";");
    Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
    Matcher m;
    for (int i = 0; i < metaParts.length; i++) {
        m = p.matcher(metaParts[i]);
        if (m.find()) {
            metadata.put(m.group(1), m.group(2));
        }
    }

    return metadata;
}
    }

here is the method i use in my MAIN ACTIVITY to display the song title in my textview
private void getmeta()
{
    timer = new Timer();
    timer.schedule(new TimerTask() {
    public void run(){

    URL url;
    try{
        url = new URL("http://www.rakista.com:8000/listen.mp3");
        IcyStreamMeta icy = new IcyStreamMeta(url);
        A = icy.getArtist();
        Artist.setText(A);

    }catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
},0,2000);

    //Log.i("Artist: ", A);
}

Update:
my main Activty
private class

public class RakistaRadio extends Activity
{

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
Artist =(TextView) findViewById(R.id.ARTIST);

}
}

Comment: Please show me the line were you set a string to a TextView. Is it this: `Artist.setText(A);`? What class is `Artist`, where did you declare it?
Comment: it is declared on top of my oncreate().......... private TextView Artist; public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  Artist =(TextView) findViewById(R.id.ARTIST);
Comment: First of all you should follow the programming standard which says variable names start with lower case letters and classes start with uppercase. It's because of the better readability. Do you get any errors or warnings at Android 2.2 or when you call `Artist.setText(A)`? I guess you get an exception and can't see it because you used `e.printStackTrace()` to show it. Use `Artis.setText(e.toString())` instead or if you have LogCat simply `Log.v("IcyStreamMeta", e.toString())` to make it visible.
Answer: This is a bit late, but I was looking for the same answer as you and with a little re-factoring, I got your code to work. I hope this helps!
/**
 * Get Meta Data From SHOUTcast
 */
private void getMeta()
{
    Timer timer = new Timer();
    timer.schedule(new TimerTask()
    {
        public void run()
        {
            try
            {
                IcyStreamMeta icy   = new IcyStreamMeta(new URL("http://www.rakista.com:8000"));
                data                = icy.getArtist() + " - " + icy.getTitle();
                meta                = (TextView) findViewById(R.id.meta);

                runOnUiThread(new Runnable()
                {
                     public void run()
                     {
                         meta.setText(data);
                     }
                });
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    },0,5000);
}

Note that the variables data and meta are defined in the class root, not any method.


PHP and AJAX Web Content

Question: I am thinking of developing a website in PHP and I was thinking of using AJAX in order to send data to, and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
So my question:  would it be better to use AJAX to GET or POST to php pages or any other options are possible?
Answer: Rule of thumb (regardless of AJAX).
If you're going to send large amounts of data, or sensitive data... POST.
Otherwise, GET works just as fine.
Answer: There are not that many options when it comes to submiting data, either you use AJAX or use the normal http message like GET or POST. If you would like to determin witch is better i would say: it depends.
Ajax seems to me like a great way of making more dynamic a part of your site, but i dont think its always practical to use in all your site. Ajax is generally used when you need to show some context change on one page, like posting a commner, faving a question, or things like that. Another great thing about it is not to bound user to a form (you can save info with a link like when you vote a question here)
Using GET or POST its usefull to let the user now here's moving along a process or when things that happen after or before are different, or context change a lot when submitting.
Comment: Thanks. Hey mind explaining to me how do sites like youtube and google chrome web store works? Just out of curiosity.
Comment: I think that there is no real answer to that question,  i would love to know, but i really dont, sorry :P. Those site you mention are always working on edgy technology so you never now how are they build specifically
Comment: Yeh, this question always circles around my mind like how was Google build, how was YouTube, how was FB developed, Was Google Chrome Web Store built with PHP, Jquery or ASP. I guess there is no real answer to that unless Ur the one who worked on these web development.
Answer: I recommend use JQuery.
with $.ajax of Jquery, you can use it with multiple options depending that you need.
So you can work with POST, GET, receive data like text, json...
Here you can get more info:
http://api.jquery.com/jQuery.ajax/
Comment: Thanks. But do i need to consider anything in mind while using $.ajax of jquery to php?
Comment: i believe that ajax is better, i don't found another form to do some like you need. i usually use method GET, the POST only use to send form without AJAX.
Answer: I always use $_POST.  I wish I could give a reason why I think it's better, but I can't.  I guess it's because I've always preferred sending data via POST rather than GET so the user doesn't see it, and it just carried over to my ajax.
Comment: Yes, i aggree with you but you can't use POST all the time. There are some time when you are needed to use GET.
Answer: I would use $_POST just for the fact that it can store more data.

PHP and AJAX Web Content


Why is global convexity not possible in higher-dimensional settings for this loss function?

Question: I was reading this paper which discusses nonconvex penalized regression. They use the following notation:

$X\in\mathbb{R}^{n\times p}$ is a data matrix with $n$ observations in $p$ variables
$\beta\in\mathbb{R}^p$ is a vector of regression parameters
$\eta=X\beta$ is the expected value of the output $y$

For logistic regression, the goal is to minimize the loss function (eq. (3.2))
$$
Q_{\lambda,\gamma}(\beta)=-\frac{1}{n}\sum_{i=1}^n\{y_i\log\pi_i+(1-y_i)\log(1-\pi_i)\} + \sum_{j=1}^p p_{\lambda,\gamma}(|\beta_j|),
$$
where:

$p_{\lambda,\gamma}$ is a regularizer/penalty function controlled by parameters $\lambda$ and $\gamma$,
$\pi_i=e^{\eta_i}/(1+e^{\eta_i})$.

On page 13, subsection 4.2 it is written about $Q_{\lambda,\gamma}(\beta)$:

Local convexity diagnostics.
  However, it is not always necessary to
  attain global convexity. In high-dimensional settings where $p>n$, global convexity is neither possible nor relevant.

In other words, the number of predictors $p$ is bigger than the number of observations $n$.
Why is global convexity not possible in higher dimensions?
Comment: The authors' statement about convexity pertains specifically to the loss function they are dealing with. Proposition 2 in the paper states that the loss function in question $Q_{\lambda,\gamma}(\beta)$ is convex only when $c^*(\beta)>1/\gamma$, where $c^*(\beta)$ is the minimum eigenvalue of $n^{-1}X^TWX$. You can show that for $p>n$, some of the eigenvalues (in fact, $p-n$ of them) will be zero, so the convexity condition cannot be satisfied.
Comment: Could you maybe expand your question a bit, like explaining what $p$ and $n$ mean, so that it is understandable stand-alone, without having to read the referenced paper?
Comment: @scherm - you might want to expand that to an answer, since it is.
Comment: @jbowman that was the plan, but the question was put on hold while I was formulating my answer :)
Comment: OP, please check that @scherms edits match your intent. Furthermore, please add a full reference in addition to the link
Answer: The paper covers two choices for $p_{\lambda,\gamma}$: MCP and SCAD. Proposition 2 states:

Let $c^*(\beta)$ denote the minimum eigenvalue of $n^{-1}X^TWX$,
  where $W$ is evaluated at $\beta$. Then the objective function defined in (3.2) is a
  convex function of $\beta$ on the region where $c^*(\beta) > 1/\gamma$ for MCP, and where
  $c^*(\beta) > 1/(γ − 1)$ for SCAD.

where $W=\operatorname{diag}(\pi\odot(1-\pi))$ with $\odot$ signifying elementwise multiplication. I will deal with MCP here, but the argument for SCAD is the same.
Notice that $n^{-1}X^TWX$ has $p$ eigenvalues since it is $p\times p$, but if $p>n$, at most $n$ of them will be nonzero since $\operatorname{rank}(n^{-1}X^TWX)\leq\min(n,p)$. This leaves at least $p-n$ zero eigenvalues. Since $Q_{\lambda,\gamma}$ is convex only where $c^*(\beta) > 1/\gamma$ (but we have $c^*(\beta)=0 < 1/\gamma$), it is not convex.
On the other hand, if $p\leq n$, we should be safe because $n^{-1}X^TWX$ is likely full-rank and for the proper setting of $\gamma$, we can satisfy the convexity condition.


UIAutomation isValid() Immediate Alternative

Question: I am writing integration tests for an iOS app using UIAutomation.
As part of the test suite, I have incorporated a reset function that will return the app to the main menu by tapping on the left UINavigationBar item as long as it exists.
This is the code used to do so (written in tuneup.js):
function reset (app) {
    // While we have a left button on the nav bar, tap it.
    // This effectively resets our app

    while(app.mainWindow().navigationBars()[0].leftButton().isValid()) {
        app.mainWindow().navigationBars()[0].leftButton().tap();
    }
}

It does its purpose.
However, isValid() will wait for several seconds in case it can not immediately find an object. Thus the integration tests are running very slowly as every time we hit the main menu after resetting, isValid() will wait for some time to see if a left UINavigationBar item will appear.
Is there an alternative function or alternative implementation that would allow me to determine wether an element exists without this forced timeout?
Answer: You can overwrite the default timeout to 0 with:
UIATarget.localTarget().pushTimeout(timeoutInSeconds);

However it does not seem to be a good idea to check validation in a while cycle with 0 timeout.
function reset (app) {
    // While we have a left button on the nav bar, tap it.
    // This effectively resets our app

    UIATarget.localTarget().pushTimeout(0);
    if (app.mainWindow().navigationBars()[0].leftButton().isValid()) {
        app.mainWindow().navigationBars()[0].leftButton().tap();
    }
    UIATarget.localTarget().popTimeout();
}


How can i retrieve instrumentation key for an Application Insight (which resides in another resource group) in ARM template?

Question: Is there any way to retrieve the Instrumentation Key for an Application Insights (which resides in another resource group) in an ARM template ?
I have already created an appInsights using ARM template using the below code,
<code>{
  "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "22.214.171.124",
  "parameters": {
    "AppInsightsName": { "type": "string" },
    "Location": { "type": "string", "defaultValue": "westeurope" }
  },
  "variables": {
    //"apiVersion": "2018-02-01-preview",
    "apiVersion": "2016-08-01",
    "location": "[parameters('Location')]",
    "ApplicationInsightsName": "[parameters('AppInsightsName')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01",
      "type": "Microsoft.Insights/components",
      "name": "[variables('ApplicationInsightsName')]",
      "location": "[variables('location')]",
      "kind": "other",
      "properties": {
        "applicationId": "[variables('ApplicationInsightsName')]"
      }
    }
  ]
}
</code>
Now i am trying to link azure function app which runs in another resource group with this appInsights.
Below is the code i have tried,
<code>{
  "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
  "value": "[reference(resourceId(variables('AppInsightsResourceGroup'),'Microsoft.Insights/components', variables('ApplicationInsightsName'))).InstrumentationKey]"
}
</code>
But i am getting the below error,

Can someone give some idea how to crack this?
Answer: You can use the reference function for resources that are already deployed from another template.  You just need to pass in the apiVersion parameter as indicated in the docs at https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource#reference.  Note that you also need to change the property that you are referencing from '.InstrumentationKey' to '.properties.InstrumentationKey'.
<code>"value": "[reference(resourceId(variables('AppInsightsResourceGroup'),'Microsoft.Insights/components', variables('ApplicationInsightsName')), '2015-05-01', 'Full').properties.InstrumentationKey]"
</code>
You can deploy the following template to validate (just replace the two variables with your values):
<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "22.214.171.124",
  "parameters": {
  },
  "variables": {
      "AppInsightsResourceGroup": "myAIRG",
      "ApplicationInsightsName": "myAI"
  },
  "resources": [
  ],
  "outputs": {
      "appInsightsKey": {
          "type": "string",
          "value": "[reference(resourceId(variables('AppInsightsResourceGroup'),'Microsoft.Insights/components', variables('ApplicationInsightsName')), '2015-05-01', 'Full').properties.InstrumentationKey]"
      }
  }
}
</code>
Comment: This works great. One note, when not using 'Full', you don't need to add the .properties part


non stochastic regressors and causation

Question: Randomized controlled experiment is base case for causality (also) in regression.
However currently I'm analyzing  the role of causality in linear regression as shown in many econometrics  textbook. For example in Brooks 2014 – introductory econometrics for finance 3rd edition pag 76-83 the fixed (non-stochastic) regressors are the base scenario and causal interpretation is explicitly offered. In this book the causal interpretation of regression coefficients seems  the basic scenario too.
The example (pag 83) is about the CAPM and in this setting experiment, also ideal, and/or potential outcome language, at least in my experience, don't play any role.
I have several doubt but my questions are primarily three:

Fixed non stochastic regressors assumption produce (by costruction) independence between errors and regressors. Then, hypothesis of stochastic independence between errors and regressors is equal to hypothesis of fixed non stochastic regressors ?
If no (as I think see also here  regression and causation) the hypothesis of fixed non stochastic regressors is equal to known the "true model / true data generating process" ?
Known this "true model" is, at least in certain sense, equal to construct an (idealized) randomized controlled experiment?
Comment: If you read the very book you mention, Brooks (2014), he has a session on "omission of important variables", in which he says "The consequence would be that the estimated coefficients on all the other variables will be biased and inconsistent unless the excluded variable is uncorrelated with all the included variables. ".
Comment: I known that Brooks (2014), as any other econometrics textbook, speak about omitted variables bias and others source of bias. However the problem is exactly on his interpretation. Surely omitted variables bias is related on causal problems. In Brooks(2014) seems that basic regression parameters have causal meaning, therefore bias, independently of his source, have causal meaning too. In others textbooks this point is not clear, in some seems that bias not necessarily have causal meaning.
Comment: Brooks take the assumption as $corr(X,u)=0$ for demonstrate that there isn't bias (pag 179).  Brooks don't use here the term exogeneity but usually this condition is referred to it; or better a certain form of it, let me say form 1. But Brooks speak about this (exogeneity) also in the form of independence between u and X, let me say form 2, and in the form of non-stochastic X, let me say form 3 (pag 208/9).
Comment: Shortly, probably the main problem of Brooks(2014), as other econometrics textbooks, is that is not so clear what the error term (u) exactly is. This is true also for omitted variables example; see pag 224 where true model and an underspecified model have the same notation error.
Comment: I think that in his assumptions Brooks have in mind "true" error. However, true model/error or not, since the fact above are the origins of my guesses of think about form 2 and/or 3 as conditions related on causality (form 1 is surely not enough at least with estimated error). Form 2 is not enough and you helped me about convince me about that. If form 3 is essentially the same of form 2, the same is the result.
Comment: I'm not strongly convinced yet that form 2 and 3 are essentially the same because I think about 3 as related to experiment concept … but probably is not a great idea. However I trust you that non-stochastic  regressors is not enough for causal interpretation of regression/parameters.
Comment: Moreover I discover some months ago the book that you suggest (Pearl Glymour and Jewell - Wiley) and related Pearl literature … I'm studying. However this is not yet the standard in basic econometrics and for now I desired to remain closest as possible to econometrics current textbooks.
Let me some time and I open another, better posed (I hope), discussion about causality and regression.
Answer:
Fixed non stochastic regressors assumption produce (by costruction)
  independence between errors and regressors.

This is not true, fixed regressors assumptions just mean that the regressors are not "random". You can still have bias, as showed in here.
If you read a couple pages further in the very book you mention, Brooks (2014), he has a session on "omission of important variables", in which he mentions omitted variable bias (although I would not recommend this book if you want to learn causality, if you want to learn causality--and not just linear regression--start here).

The hypothesis of fixed non stochastic regressors is equal to known
  the "true model / true data generating process" ?

No, this hypothesis has more to do with the mathematics of the probabilistic manipulations. If regressors are fixed, you will treat them as "parameters", not as random variables. But this has no bearing on causal effects.

Known this "true model" is, at least in certain sense, equal to
  construct an (idealized) randomized controlled experiment?

Most authors do not really define what "fixed regressor" means except that it is treated as a fixed known quantity. Even when some authors do make the analogy to "fixed by experiment" (such as Seber, in a parenthetical remark), they do not offer any mathematics of causality.
In short, to make causal conclusions you need to make explicit causal assumptions, as in a causal model.
Comment: My confusion about this point coming from the fact that, as you said, some authors make the analogy between "non stochastic regressors" and "regressors  fixed by experiment"  and or "regressors fixed in repeated samples". I can mention at least two econometric books about that.  However non stochastic regressors and the so called "as if" (an experiment) condition are completely different things. Thanks.
Comment: @markowitz yes wikipedia is not reliable. I have been thinking of gathering some people to overhaul some parts of wikipedia, that do more harm than good.
Comment: Let me come back on this question. Today we can read on Wikipedia yet:
"When the explanatory variables are not stochastic, then they are strong exogenous for all the parameters."
https://en.wikipedia.org/wiki/Endogeneity_(econometrics)#Exogeneity_versus_endogeneity
Obscure sentences like that was precisely my starting point when write the question above.
Comment: @markowitz by the way, I think there are some questions I promised answering, but I forget. Can you point them to me again?
Comment: Hi Carlos! Actually I waiting your reply here: https://stats.stackexchange.com/questions/467570/linear-causal-model

non stochastic regressors and causation