Get float value out of JSONValue in dlang

Question: I am parsing JSON to present a report. While parsing the field rating it can have either 3 which parses to JSONValue.integer or 3.4 which parses to JSONValue.floating and I need to convert them as float in the report. I have profiled the code to look for optimisation and the get_number function that converts the given input to floating point is taking a lot of time and also uses exceptions for the code.
I can use fast.d (https://github.com/mleise/fast) but I am trying to see if there are anymore optimisations that can be done on get_number function that is taking up time . Is there a way to get the floating point value without using the exceptions and are there any more optimisations that can be done?
redbus.d
import std.net.curl;
import std.exception;
import std.json;
import std.stdio;
import std.file;
import std.algorithm;
import std.array;
import std.conv;
import std.string;

auto fmt = "%35s | %10s | %10s | %10s | %15s";
auto value_fmt = "%35s | %10.2f | %10.0f | %10.2f | %15s";

void print_header() {
  writeln("-----------------------------------------------------------------------------------------------");
  writefln(fmt, "Name", "Price", "Window", "Rating", "Type");
  writeln("-----------------------------------------------------------------------------------------------");
}

float get_number(T)(T item) {
  float output = 0;
  try {
    output = to!float(item.integer);
  } catch(Exception e) {
    output = to!float(item.floating);
  }
  return to!float(output);
}

void print_item(T)(T item) {
  writefln(value_fmt, item["Tvs"].str, item["MinFare"].get_number(), item["WnSt"].get_number(), item["Rtg"]["totRt"].get_number(), item["BusCategory"]["IsSleeper"]);
}

void main() {
  auto content = readText("sample.json");
  auto parsed = parseJSON(content);
  auto raw = parsed["SRD"][0]["RIN"][0]["InvList"].array;
  auto filtered = raw.filter!(item => to!bool(to!string(item["BusCategory"]["IsAc"])));

  print_header();
  foreach(item; filtered) {
    print_item(item);
  }
}

App specific trace log when ran with dmd -g -run redbus.d | grep redbus
======== Timer Is 3579545 Ticks/Sec, Times are in Microsecs ========

  Num          Tree        Func        Per
  Calls        Time        Time        Call

180     8673696     8300660       46114     @safe immutable(char)[] redbus.get_number!(std.json.JSONValue).get_number(std.json.JSONValue)
 60     9448603       75423        1257     @safe void redbus.print_item!(std.json.JSONValue).print_item(std.json.JSONValue)
 60       17581       10002         166     pure @safe void std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.popFront()
  2      110576        6987        3493     void redbus.print_header()
122        5635        5441          44     pure nothrow @property @nogc @safe bool std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.empty()
 60        4002        2877          47     pure nothrow ref @property @nogc @safe std.json.JSONValue std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.front()
 60         690         690          11     pure @safe bool redbus.main().__lambda1!(std.json.JSONValue).__lambda1(std.json.JSONValue)
  2         386         348         174     pure ref @safe std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.__ctor(std.json.JSONValue[])
  2         480          94          47     pure @safe std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult std.algorithm.iteration.__T6filterS246redbus4mainFZ9__lambda1Z.filter!(std.json.JSONValue[]).filter(std.json.JSONValue[])
  2          28          28          14     pure nothrow @nogc @safe std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.opSlice()

Full trace log when ran with dmd -g -run redbus.d
======== Timer Is 3579545 Ticks/Sec, Times are in Microsecs ========

  Num          Tree        Func        Per
  Calls        Time        Time        Call

    180     8673696     8300660       46114     @safe immutable(char)[] redbus.get_number!(std.json.JSONValue).get_number(std.json.JSONValue)
 378142     7487455     5101529          13     pure @safe dchar std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).popChar()
 403760    11591911     4118861          10     pure @safe dchar std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).peekChar()
  13218    11298746     3847457         291     @safe immutable(char)[] std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).parseString()
      2     3416630     3410981     1705490     @safe void[] std.file.read!(immutable(char)[]).read(immutable(char)[], ulong)
  11694    26577653     2975245         254     @safe void std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).parseValue(ref std.json.JSONValue)
      2     3189533     2760109     1380054     pure @safe void std.utf.validate!(immutable(char)[]).validate(const(immutable(char)[]))
  50558     9391716     2176452          43     pure @safe void std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).skipWhitespace()
 378142     2199763     1819030           4     pure @property @safe dchar std.range.primitives.front!(immutable(char)).front(immutable(char)[])
 120448     4223189     1521014          12     pure @safe void std.array.Appender!(immutable(char)[]).Appender.put!(dchar).put(dchar)
 121018     1447202     1447202          11     _D3std5array17__T8AppenderTAyaZ8Appender11__T3putTAaZ3putMFAaZ10bigDataFunMFNaNbNemZAa
 121018     2663475     1216273          10     pure nothrow @safe void std.array.Appender!(immutable(char)[]).Appender.put!(char[]).put(char[])
 378144      429423      429423           1     pure @trusted dchar std.utf.decode!(0, const(immutable(char)[])).decode(ref const(immutable(char)[]), ref ulong)
 378142      380732      380732           1     pure @trusted dchar std.utf.decode!(0, immutable(char)[]).decode(ref immutable(char)[], ref ulong)
   3844     1585268      379140          98     _D3std4json18__T9parseJSONTAyaZ9parseJSONFAyaiE3std4json11JSONOptionsZ10parseValueMFKS3std4json9JSONValueZ11readIntegerMFNaNfZv
  17692     3044067      299545          16     pure @safe bool std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).testChar!(true, true).testChar(char)
   3694      302920      283609          76     pure @safe ulong std.conv.parse!(ulong, immutable(char)[]).parse(ref immutable(char)[])
  21172     5305573      253537          11     pure @safe void std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).checkChar!(true, true).checkChar(char)
   2858      241132      241132          84     _D3std5stdio4File17LockingTextWriter10__T3putTaZ3putMFNfaZ12trustedFPUTCFNbNiNeiPS4core4stdc5stdio7__sFILEZi
 749606      194721      194721           0     pure nothrow @property @nogc @safe bool std.range.primitives.empty!(char).empty(const(char[]))
    180      146178      146178         812     nothrow @nogc @trusted int std.format.formatValue!(std.array.Appender!(immutable(char)[]).Appender, float, char).formatValue(std.array.Appender!(immutable(char)[]).Appender, float, ref std.format.FormatSpec!(char).FormatSpec).__lambda6()
 168966      289542      140496           0     pure @safe dchar std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).getChar!(false).getChar()
    372      175283      138897         373     @safe bool std.format.FormatSpec!(char).FormatSpec.writeUpToNextSpec!(std.stdio.File.LockingTextWriter).writeUpToNextSpec(std.stdio.File.LockingTextWriter)
 378142      127665      127665           0     pure nothrow @nogc @trusted void std.range.primitives.popFront!(immutable(char)).popFront(ref immutable(char)[])
 120838       88309       88309           0     pure @safe ulong std.utf.encode!(0).encode(ref char[4], dchar)
   7004      269543       79286          11     pure @safe void std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).checkChar!(false, false).checkChar(char)
     60     9448603       75423        1257     @safe void redbus.print_item!(std.json.JSONValue).print_item(std.json.JSONValue)
    180      357433       73536         408     @safe immutable(char)[] std.conv.toStr!(immutable(char)[], float).toStr(float)
  11694     1701071       65993           5     pure @safe dchar std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).getChar!(true).getChar()
     62      546598       58901         950     @safe uint std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[])
    624       57414       57414          92     nothrow @nogc @trusted ulong std.stdio.trustedFwrite!(char).trustedFwrite(shared(core.stdc.stdio.__sFILE)*, const(char[]))
    310      287767       55386         178     @safe void std.format.formatRange!(std.stdio.File.LockingTextWriter, immutable(char)[], char).formatRange(ref std.stdio.File.LockingTextWriter, ref immutable(char)[], ref std.format.FormatSpec!(char).FormatSpec)
    180      283897       51186         284     @safe void std.format.formatValue!(std.array.Appender!(immutable(char)[]).Appender, float, char).formatValue(std.array.Appender!(immutable(char)[]).Appender, float, ref std.format.FormatSpec!(char).FormatSpec)
   2792      188331       44715          16     @safe void std.range.primitives.put!(std.stdio.File.LockingTextWriter, char).put(ref std.stdio.File.LockingTextWriter, char)
   3786       51453       42260          11     pure @safe bool std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions).testChar!(false, false).testChar(char)
      1    42812121       40946       40946     _Dmain
   2792      143615       40695          14     @safe void std.range.primitives.doPut!(std.stdio.File.LockingTextWriter, char).doPut(ref std.stdio.File.LockingTextWriter, ref char)
   2858      276528       35396          12     @safe void std.stdio.File.LockingTextWriter.put!(char).put(char)
     62      730778       28544         460     @safe void std.stdio.File.writefln!(char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).writefln(const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[])
     58       27284       25878         446     pure @safe double std.conv.parse!(double, immutable(char)[]).parse(ref immutable(char)[])
      4       61182       22565        5641     @safe void std.stdio.writeln!(immutable(char)[]).writeln(immutable(char)[])
    668       36701       22086          33     pure nothrow @safe void std.array.Appender!(immutable(char)[]).Appender.put!(char).put(char)
  10790       15562       15562           1     pure nothrow @nogc @safe dchar std.ascii.toLower!(dchar).toLower(dchar)
    180       14091       14091          78     pure nothrow @nogc @trusted immutable(char)[] std.algorithm.searching.find!("a == b", immutable(char)[], char).find(immutable(char)[], char).trustedMemchr(ref immutable(char)[], ref char)
    668       14165       12798          19     pure nothrow @nogc @safe void std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char)
    310      307336       11476          37     void std.format.formatGeneric!(std.stdio.File.LockingTextWriter, immutable(char)[], char).formatGeneric(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)
     62      741889       11111         179     @safe void std.stdio.writefln!(immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).writefln(immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[])
     60       17581       10002         166     pure @safe void std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.popFront()
    314       51833        9902          31     @safe void std.stdio.File.LockingTextWriter.put!(immutable(char)[]).put(immutable(char)[])
    310       30175        9395          30     @safe void std.range.primitives.doPut!(std.stdio.File.LockingTextWriter, const(char)[]).doPut(ref std.stdio.File.LockingTextWriter, ref const(char)[])
    310       40073        8883          28     @safe void std.range.primitives.doPut!(std.stdio.File.LockingTextWriter, immutable(char)[]).doPut(ref std.stdio.File.LockingTextWriter, ref immutable(char)[])
    180       23372        8492          47     pure @safe immutable(char)[] std.algorithm.searching.find!("a == b", immutable(char)[], char).find(immutable(char)[], char)
    310      295860        8093          26     @safe void std.format.formatValue!(std.stdio.File.LockingTextWriter, immutable(char)[], char).formatValue(std.stdio.File.LockingTextWriter, immutable(char)[], ref std.format.FormatSpec!(char).FormatSpec)
  16860        7657        7657           0     pure nothrow @nogc @safe void std.range.primitives.popFront!(immutable(ubyte)).popFront(ref immutable(ubyte)[])
    180        9026        7524          41     pure nothrow @nogc @safe bool std.functional.safeOp!("<").safeOp!(immutable(int), ulong).safeOp(ref immutable(int), ref ulong)
      2      110576        6987        3493     void redbus.print_header()
  17034        6217        6217           0     pure nothrow ref @property @nogc @safe immutable(ubyte) std.range.primitives.front!(immutable(ubyte)).front(immutable(ubyte)[])
    120        5515        5515          45     pure nothrow ref @property @nogc @safe std.json.JSONValue std.range.primitives.front!(std.json.JSONValue).front(std.json.JSONValue[])
    122        5635        5441          44     pure nothrow @property @nogc @safe bool std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.empty()
    310       20779        5296          17     @safe void std.stdio.File.LockingTextWriter.put!(const(char)[]).put(const(char)[])
    310       34821        4646          14     @safe void std.range.primitives.put!(std.stdio.File.LockingTextWriter, const(char)[]).put(ref std.stdio.File.LockingTextWriter, const(char)[])
    180       13549        4523          25     pure nothrow @nogc @safe immutable(int) std.algorithm.comparison.min!(immutable(int), ulong).min(immutable(int), ulong)
      2        5331        4353        2176     nothrow @nogc @safe std.internal.cstring.tempCString!(char, immutable(char)[]).tempCString(immutable(char)[]).Res std.internal.cstring.tempCString!(char, immutable(char)[]).tempCString(immutable(char)[])
    180      365563        4136          22     @safe immutable(char)[] std.conv.to!(immutable(char)[]).to!(float).to(float)
    130        4682        4089          31     pure nothrow @nogc @safe float std.conv.to!(float).to!(long).to(long)
    180      361427        3994          22     @safe immutable(char)[] std.conv.toImpl!(immutable(char)[], float).toImpl(float)
    310       44049        3975          12     @safe void std.range.primitives.put!(std.stdio.File.LockingTextWriter, immutable(char)[]).put(ref std.stdio.File.LockingTextWriter, immutable(char)[])
   3786        3530        3530           0     pure nothrow @nogc @safe immutable(char)[] std.string.assumeUTF!(immutable(ubyte)).assumeUTF(immutable(ubyte)[])
     34        3566        3268          96     pure @safe long std.conv.parse!(long, immutable(char)[]).parse(ref immutable(char)[])
     60        4002        2877          47     pure nothrow ref @property @nogc @safe std.json.JSONValue std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.front()
   3786        2775        2775           0     pure nothrow @nogc @safe immutable(ubyte)[] std.string.representation!(immutable(char)).representation(immutable(char)[])
     50        2790        2342          46     pure nothrow @nogc @safe float std.conv.to!(float).to!(double).to(double)
    180        1501        1501           8     pure nothrow @nogc @safe bool std.functional.safeOp!("<").unsafeOp!(immutable(int), ulong).unsafeOp(immutable(int), ulong)
    184         940         940           5     pure nothrow @property @nogc @safe bool std.range.primitives.empty!(std.json.JSONValue).empty(const(std.json.JSONValue[]))
     60         919         919          15     pure nothrow @nogc @safe void std.range.primitives.popFront!(std.json.JSONValue).popFront(ref std.json.JSONValue[])
     58         833         833          14     pure nothrow @nogc @safe ubyte std.ascii.toUpper!(immutable(ubyte)).toUpper(immutable(ubyte))
      2     6607022         831         415     @safe immutable(char)[] std.file.readText!(immutable(char)[], immutable(char)[]).readText(immutable(char)[])
    180         787         787           4     pure nothrow @nogc @safe bool std.utf.canSearchInCodeUnits!(char).canSearchInCodeUnits(dchar)
     62         779         779          12     pure nothrow @nogc @trusted pure nothrow @safe void function(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)* std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda9()
     60         690         690          11     pure @safe bool redbus.main().__lambda1!(std.json.JSONValue).__lambda1(std.json.JSONValue)
     62         668         668          10     pure nothrow @nogc @trusted const(void*) std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda14!(immutable(char)[]).__lambda14(return ref immutable(char)[])
    130         593         593           4     pure nothrow @nogc @safe float std.conv.toImpl!(float, long).toImpl(long)
     62         574         574           9     pure nothrow @nogc @trusted const(void*) std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda16!(immutable(char)[]).__lambda16(return ref immutable(char)[])
    668         517         517           0     pure nothrow @nogc @trusted void std.conv.emplaceInitializer!(std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).S).emplaceInitializer(ref std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).S)
     62         494         494           7     pure nothrow @nogc @trusted pure nothrow @safe void function(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)* std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda15()
     62         494         494           7     pure nothrow @nogc @trusted pure nothrow @safe void function(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)* std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda17()
    668         479         479           0     pure nothrow @nogc @trusted std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).S* std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).__lambda5()
    668         449         449           0     _D3std5array17__T8AppenderTAyaZ8Appender10__T3putTaZ3putMFaZ9__lambda2MFNaNbNiNeZAa
     50         447         447           8     pure nothrow @nogc @safe float std.conv.toImpl!(float, double).toImpl(double)
      2    26578112         437         218     @safe std.json.JSONValue std.json.parseJSON!(immutable(char)[]).parseJSON(immutable(char)[], int, std.json.JSONOptions)
     62         423         423           6     pure nothrow @nogc @trusted const(void*) std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda18!(immutable(char)[]).__lambda18(return ref immutable(char)[])
     62         422         422           6     pure nothrow @nogc @trusted const(void*) std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda10!(immutable(char)[]).__lambda10(return ref immutable(char)[])
     62         416         416           6     pure nothrow @nogc @trusted pure nothrow @safe void function(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)* std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda11()
     62         416         416           6     pure nothrow @nogc @trusted pure nothrow @safe void function(std.stdio.File.LockingTextWriter, const(void)*, ref std.format.FormatSpec!(char).FormatSpec)* std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda13()
     62         385         385           6     pure nothrow @nogc @trusted const(void*) std.format.formattedWrite!(std.stdio.File.LockingTextWriter, char, immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).formattedWrite(std.stdio.File.LockingTextWriter, const(char[]), immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[], immutable(char)[]).__lambda12!(immutable(char)[]).__lambda12(return ref immutable(char)[])
    668         370         370           0     pure nothrow ref @nogc @safe std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).S std.conv.emplaceRef!(char, char, char).emplaceRef(ref char, ref char).S.__ctor(ref char)
      2         386         348         174     pure ref @safe std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult std.algorithm.iteration.__T12FilterResultS246redbus4mainFZ9__lambda1TAS3std4json9JSONValueZ.FilterResult.__ctor(std.json.JSONValue[])
      2         583         343         171     pure nothrow @nogc @safe std.utf.byCodeUnit!(const(char)[]).byCodeUnit(const(char)[]).ByCodeUnitImpl std.utf.byUTF!(char).byUTF!(const(char)[]).byUTF(const(char)[])

Adam's answer :
➜  D ldc2 -O3 -release redbus.d
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 80% cpu 0.021 total
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 81% cpu 0.021 total
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 82% cpu 0.023 total
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 81% cpu 0.021 total
➜  D perl -ne 'print if /========/...//' trace.log | grep get_number
    120        2249        2249          18     float redbus.get_number(std.json.JSONValue)

Original run with exception :
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.01s system 40% cpu 0.039 total
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 80% cpu 0.023 total
➜  D time ./redbus > /dev/null
./redbus > /dev/null  0.01s user 0.00s system 64% cpu 0.023 total
➜  D perl -ne 'print if /========/...//' trace.log | grep get_number
    120     4971306     4966534       41387     pure @safe float redbus.get_number!(std.json.JSONValue).get_number(std.json.JSONValue)

Comment: Start by [checking the `type`](http://dlang.org/phobos/std_json.html#.JSONValue.type) instead of using exceptions.
Comment: The timings given in the profile trace are *micro*seconds, not milliseconds, there's a 1000x difference between them. The trace shows a time difference between my answer and the original code of about 40,000 microseconds... or 40 milliseconds, or 0.04 seconds. Considering that profiling itself adds a bit of overhead, you wouldn't see the full 0.04 second change in the final binary.... which matches up with your numbers well enough, on average my answer gave you a 0.02s boost (or 20,000 microseconds!), which is close to matching given profiling overhead being removed too.
Comment: @rcorre Thanks. Ya I was checking on the same too. It will be good if some solution exists where I can simply coerce to float.
Comment: @rcorre I have updated the results. though the time has reduced significantly the overall time remains same
Comment: soooo wait a minute, it is taking less than half a second total? are you sure it actually needs to be optimized?
Comment: @AdamD.Ruppe I am fine with the optimisations. The python implementation is 10x slower. In the profile run I have noted that the time for `get_number falls` from 4900ms to 2ms . So I was expecting a similar boost in the binary compiled with `ldc2 -O3 -release` . Maybe I am misunderstanding the timings here which I want to clarify.
Comment: @adam Thanks a lot for the explanation. I will mark the answer as accepted.
Answer: I betcha just changing your get_number to this will help improve the speed a lot:
float get_number(JSONValue item) {
  float output = 0;
  if(item.type == JSON_TYPE.FLOAT)
    output = item.floating;
  else if(item.type == JSON_TYPE.INTEGER)
    output = item.integer;
  return output;
}

Can you test it and let me know?
EDIT: in the comment, you asked about why the profile difference isn't quite reflected in the time difference. It is, though! This individual function is now 1,000x faster... but it was already reasonably fast to begin with so it is not a huge difference in the end.
Here's my comment explaining why you're expecting more than you should:
The timings given in the profile trace are microseconds, not milliseconds, there's a 1000x difference between them. The trace shows a time difference between my answer and the original code of about 40,000 microseconds... or 40 milliseconds, or 0.04 seconds. Considering that profiling itself adds a bit of overhead, you wouldn't see the full 0.04 second change in the final binary.... which matches up with your numbers well enough, on average my answer gave you a 0.02s boost (or 20,000 microseconds!), which is close to matching given profiling overhead being removed too.
Comment: Sure. I will test it and post the results. Thanks.
Comment: I have updated question with results. Its strange that even though the `get_number` call reduced significantly yet there is no significant change in the whole program execution time.
Comment: The JSON is available at https://gist.github.com/tirkarthi/c4b2ea745f15dbc6a01327b86c1d059f . When I run the program with the if clause the process of writing to stdout takes a lot of time. When I write to `/dev/null` the parsejson takes a lot of time. Confused a lot over why different functions takes a lot of time to run after each run. I am using `dmd -profile -run redbus.d` and I am on a Macbook air early 2015 model with 4gb RAM.
Comment: Well, it should take long time when printing to the the standard output, and parsejson is expected to be the one of the longest running functions in the second case (when printing to /dev/null). What do you expect? Benchmarking code that prints to the stdout makes no sense.
Comment: @DejanLekic Sorry that my comment was little misleading. I agree that parsejson takes time and then writing to stdout also takes time. In the profile run I have noted that the time for `get_number falls` from 4900ms to 2ms . So I was expecting a similar boost in the binary compiled with `ldc2 -O3 -release` . Maybe I am misunderstanding the timings here which I want to clarify.


Error in a - b : non-numeric argument to binary operator

Question: Q

    {r}

    cambio2 <- data.frame(cambio)

    cambio2 %>%
      ggplot(aes(y = receita,
                 x = despesa
                          )
    ) + geom_point()

Quero fazer o gráfico, porém não aparece os pontos no gráficos e aparece o seguinte erro:

Error in a - b : non-numeric argument to binary operator

Desde já agradeço
Comment: Apresente uma amostra de seus dados para que possamos entender qual o tipo de problema está ocorrendo. Use dput(cambio2)  para obter a amostra e edite o poste com essa saída.
Answer: Segue os dados:
mês  ano  receita  despesa
1   1 2018 778.7376 1579.185
2   2 2018 611.4827 1362.005
3   3 2018 544.0717 1532.969
4   4 2018 498.8309 1324.723
5   5 2018 428.6952 1496.460

Desde já agradeço.
Answer: Creio que seja isso que você queria, correto?
lines = 'mês ano receita despesa
1 2018 778.7376 1579.185
2 2018 611.4827 1362.005
3 2018 544.0717 1532.969
4 2018 498.8309 1324.723
5 2018 428.6952 1496.460'

dados = read.table(textConnection(lines), header = T)

library(dplyr)
library(ggplot2)

dados %>%
  ggplot(aes(y = receita, x = despesa)) +
  geom_point()

Comment: Rodei sua sintaxe no RStudio e no R console e o erro se repete.                     Error in a - b : argumento não-numérico para operador binário
Comment: Você está rodando o script como ".R" ou como ".Rmd"? Seria mais fácil você colocar um print da tela para avaliar o erro.


ffmpeg run with c# avformat_open failed

Question: I want to expand the music with ffmpeg on c#
My c# code,
   proc2.StartInfo.FileName = "H:\\bin\\ffmpeg.exe";

            proc2.StartInfo.Arguments = "-lavfi amovie=input.mp3:loop=9 C:\\Users\\serhat-pc\\Desktop\\newinput.mp3";

            proc2.StartInfo.RedirectStandardError = true;
            proc2.StartInfo.UseShellExecute = false;
            if (!proc2.Start())
            {
                Console.WriteLine("Error starting");
                return;
            }
            StreamReader reader = proc2.StandardError;
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }

            proc2.Close();

BUT I'm receiving this problem:
ffmpeg problem
Please help me friends , thanks.
Answer: You can achieve this by concatenating same file.
Create a text file with content (concat.txt):
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'
file '/path/to/input.mp3'

then use following command:
ffmpeg -f concat -i concat.txt -c copy output.mp3

ffmpeg run with c# avformat_open failed


Definition of BUILTIN\Users?

Question: For a server on a Windows Domain, what is the membership of "BUILTIN\Users" exactly?
(I figure this has an obvious answer, but googling hasn't given me any clear definitions)
Comment: If you could expand your question a bit, what exactly are you not clear about?
Comment: @jscott - I just couldn't find a definition for it! But your answer is ideal, thanks.
Answer: From Microsoft KB 243330 Well-known security identifiers in Windows operating systems

SID: S-1-5-32-545
Name: Users
Description: A built-in group. After the initial installation of the operating system, the only member is the Authenticated Users group. When a computer joins a domain, the Domain Users group is added to the Users group on the computer.

When you install a Windows Server, the only member of the local Users group is local group Authenticated Users.  Upon joining the server to your domain, the domain group EXAMPLE\Domain Users would be added to Users.

Definition of BUILTIN\Users?


Conditioning on a future (post intervention/treatment and post outcome) event in a causal diagram?

Question: My team is conducting a pre/post-intervention comparison of health outcomes in treatment and control groups, and the question came up whether it's a good idea condition/match on a deceased flag for subjects after the post study period.
Instinctively, I know contaminating your model with future information introduces bias when you're trying to predict a future event (or the causal effect of a treatment on a future event).
However, in the context of causal diagrams, how do we know conditioning on a future variable variable is not good?
Based on the diagram below, the Deceased variable is a collider which introduces unwanted bias if included by opening the Y -> D <- A backdoor path, is that correct?
Answer: Conditioning on a collider would indeed bias the causal estimate
I am assuming the "Diseased" variable is $D$ in your casual graph, and you are trying to estimate the causal influence $A \to Y$. In the graph, $D$ is a collider, so conditioning on it would introduce a spurious correlation between $A$ and $Y$. As you are saying, you should not condition on $D$ (you should, however, condition on the confounder $X$). This is purely a result of the do-calculus. Reasoning about the time-precedence can be helpful for coming up with a suitable graph in the first place, but it is not needed for choosing an adjustment set once the graph is set up (although it may still aid intuition).


Formulário PHP com envio de anexo funciona em servidor web, mas não em servidor intranet

Question: Um formulário que testei em meu servidor web (www.sitedodaniel.com.br/caixa/envio/formgamer.php) funcionou perfeitamente.
Porém, ao transpor o código para um servidor intranet de minha empresa, o formulário é exibido, mas aparecem as seguintes mensagens na parte superior do navegador:
Notice: Undefined index: frm_ok in E:\Website[caminho do servidor]\formgamer.php on line 2

Notice: Undefined index: Nome do Remetente in E:\Website[caminho do servidor]\formgamer.php on line 3

Notice: Undefined index: email in E:\Website[caminho do servidor]\formgamer.php on line 4

Notice: Undefined index: destino in E:\Website\E:\Website[caminho do servidor]\formgamer.php on line 6

Segue código:
<?php
$subm = $_POST['frm_ok'];   // Váriavel que indica que o formulário foi submetido
$name = $_POST['Nome do Remetente'];     // Nome do remetente(Emissor)
$mail = $_POST['email'];    // Segue o endereço de email do remetente
$__sj = "Formulário de Contato";    // Informe um assunto para a mensagem
$__to = $_POST['destino']; // Defina o email do destinatário(Receptor), para mais de um separe-os com vírgula
// Verifico se o formulário foi submetido
if(isset($subm)):
// Descomente a linha abaixo, se você quiser analisar as variáveis que estão sendo passadas pelo formulário via post
//echo "
",print_r($_POST),"
";
// Filtro algumas váriaveis passadas
$find = "/(content-type|bcc:|cc:)/i";
if(preg_match($find, $name) || preg_match($find, $mail))
exit("
Sem meta/header inclusões, por favor.
");
// Valido o email do remetente, usando expressão regular
$regex = "^([[:alnum:]]+)([-._]([[:alnum:]]+))*[@]([[:alnum:]]+)([-._]([[:alnum:]]+))*[.]([[:alnum:]]){2}([[:alnum:]])?$";
if(isset($mail) && !ereg($regex, $mail))
$erro = 1;
// Mensagem formatada, enviada no corpo do email
$html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">

<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">

Nome: {$name}

Email: {$mail}

Telefone: {$_POST['telefone']}

Mensagem: {$_POST['mensagem']}

";
// Resolvo a diferença de quebra de linhas, entre o Linux e o Windows
$snap = (PHP_OS == "Linux")?"\n":((PHP_OS == "WINNT")?"\r\n":exit());
// Verifico se o formulário postado, possui arquivos anexos
$file = (isset($_FILES["arquivo"]) && in_array("0",$_FILES["arquivo"]["error"]))?$_FILES["arquivo"]:FALSE;
// Executo a condição seguinte, se identificar um ou mais anexos junto a mensagem
if($file){
// É removido da matriz os anexos falsos
for($x=0; $x<count($_FILES["arquivo"]["name"]); $x++):
if(empty($file['name'][$x])){
unset($file['name'][$x]);
unset($file['size'][$x]);
unset($file['type'][$x]);
unset($file['tmp_name'][$x]);
unset($file['error'][$x]);
}else{
$attach[] = array(
$file['name'][$x],
$file['size'][$x],
$file['type'][$x],
$file['tmp_name'][$x]
);
}
endfor;
$boundary = "==Multipart_Boundary_x".md5(time())."x";
$body = stripslashes($html);
// Criamos os cabeçalhos MIME utilizados para separar as partes da mensagem MIME
$html = "--".$boundary.$snap;
$html.= "Content-Transfer-Encoding: 8bits".$snap;
$html.= "Content-Type: text/html; charset=\"ISO-8859-1\"".$snap.$snap;
$html.= $body.$snap;
$html.= "--".$boundary.$snap;
for($i=0; $i<sizeof($attach); $i++):
if(is_uploaded_file($attach[$i][3])){
$Name = $attach[$i][0];
$Size = $attach[$i][1];
$Type = $attach[$i][2];
$Temp = $attach[$i][3];
if((strlen($Name)>1) && ($Size>0)){
$fopen = fopen($Temp,"rb"); // Fazemos a leitura do arquivo a ser anexado em leitura binária(rb)
$fread = fread($fopen, filesize($Temp));
$cript = base64_encode($fread); // Codificamos o arquivo de dados com Base64
$close = fclose($fopen);
$chunk = chunk_split($cript); // Convertemos a saída de base64_encode(), conforme semântica RFC 2045
$html.= "Content-Disposition: attachment; filename=\"{$Name}\"".$snap;
$html.= "Content-Type: {$Type}; name=\"{$Name}\"".$snap;
$html.= "Content-Transfer-Encoding: base64".$snap.$snap;
$html.= $chunk.$snap;
if(sizeof($attach) == $i+1) $html.= "--".$boundary."--".$snap;
else $html.= "--".$boundary.$snap;
}
}
endfor;
// Adiciono os cabeçalhos de um arquivo anexado
$head = "MIME-Version: 1.0".$snap;
$head.= "From: {$mail}".$snap;
$head.= "Content-type: multipart/mixed; boundary=\"{$boundary}\"".$snap;
$head.= $boundary.$snap;
}
// Caso contrário, enviamos uma mensagem html, sem anexos
else{
$head = "MIME-Version: 1.0".$snap;
$head.= "From: {$mail}".$snap;
$head.= "Content-type: text/html; charset=\"ISO-8859-1\"".$snap;
}
endif;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Multi-Anexos</title>
<link href="_css/typo.css" rel="stylesheet" type="text/css" />

Orcamentos - Provas - Outros Contatos

<?
// Se o formulário for enviado sem a presença do email do remetente, é exibido uma mensagem de retorno
if(isset($erro) && $erro==1):
?>

Clique aqui para retornar e informe um email válido!

<?
// Faço o envio da mensagem, se o formulário for submetido e passar no teste anterior
elseif(isset($subm)):
?>

<?
$msg1 = "
Sua mensagem foi enviada com sucesso!
";
$msg2 = "
Sua mensagem não pôde ser enviada.

Por favor tente novamente mais tarde.
";
$conf = @mail($__to, $__sj, $html, $head);
echo ($conf)?$msg1:$msg2;
?>

Clique aqui para retornar!

<?
// Exibe o formulário para preenchimento
else:
?>

Preencha o formulario abaixo para enviar sua mensagem.
Necessario preencher todos os campos.

<form id="frm" action="<?=basename(__FILE__)?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_ok" />
<fieldset>
<legend>Formulario de Contato</legend>

Nome:
<input id="nome" name="nome" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

E-Mail:
<input id="email" name="email" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

Telefone:
<input id="telefone" name="telefone" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

Para:
<select name="destino" class="texto">
<option value="firstname.lastname@example.com" selected>Selecione um Setor</option>
<option value="firstname.lastname@example.com">Provas</option>
<option value="firstname.lastname@example.com">Orçamento</option>
<option value="email@example.com">Administração do Site</option>
</select>

Anexo #1:
<input type="file" name="arquivo[]" size="50" class="file" />

Anexo #2:
<input type="file" name="arquivo[]" size="50" class="file" />

Anexo #3:
<input type="file" name="arquivo[]" size="50" class="file" />

Mensagem:
<textarea id="mensagem" name="mensagem" class="text"></textarea>

<input type="submit" value="ENVIAR" class="send" />

</fieldset>
</form>
<?
endif;
?>

Answer: Cara, aparentemente você não está realizando o post das variáveis, ou no primeiro momento de entrar neste formulário, não foi feito o post.
Outra dica é renomear as variáveis vê retirar o espaço em branco.
Na web não dá erro , pois, o php.ini não deve estar configurado para exibir notices...
Nas linhas com erro, pode melhorar o código com:
if (isset($_POST["frm_ok"])) {
    $subm = $_POST['frm_ok'];
}

Comment: Obrigado Sérgio!
Comment: Qual é o erro? Já verificou se os dados estão chegando para o seu PHP?
Comment: Um amigo deu a dica de que é a versão do PHP. A usada em meu trabalho é 5.3.5. Vou ter q debugar todo o código.
Comment: Mas se alguém conseguir bater o olho e ver qual são as incompatibilidades, agradeço!
Answer: As Notices sumiram, porém o email ainda não consegue ser enviado. Dá sempre a mensagem de erro.
<?php
if (isset($_POST['frm_ok']) == true){
$subm = $_POST['frm_ok'];
}
if (isset($_POST['nome']) == true){
$name = $_POST['nome'];
}
if (isset($_POST['email']) == true){
$mail = $_POST['email'];
}
if (isset($_POST['destino']) == true){
$__to = $_POST['destino'];
}

// Verifico se o formulário foi submetido
if(isset($subm)):

// Descomente a linha abaixo, se você quiser analisar as variáveis que estão sendo passadas pelo formulário via post
//echo "
",print_r($_POST),"
";
// Filtro algumas váriaveis passadas
$find = "/(content-type|bcc:|cc:)/i";
if(preg_match($find, $name) || preg_match($find, $mail))
exit("
Sem meta/header inclusões, por favor.
");
// Valido o email do remetente, usando expressão regular
$regex = "/^([[:alnum:]]+)([-._]([[:alnum:]]+))*[@]([[:alnum:]]+)([-._]([[:alnum:]]+))*[.]([[:alnum:]]){2}([[:alnum:]])?$/";
if(isset($mail) && !preg_match($regex, $mail))
$erro = 1;
// Mensagem formatada, enviada no corpo do email
$html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">

<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">

Nome: {$name}

Email: {$mail}

Telefone: {$_POST['telefone']}

Mensagem: {$_POST['mensagem']}

";
// Resolvo a diferença de quebra de linhas, entre o Linux e o Windows
$snap = (PHP_OS == "Linux")?"\n":((PHP_OS == "WINNT")?"\r\n":exit());
// Verifico se o formulário postado, possui arquivos anexos
$file = (isset($_FILES["arquivo"]) && in_array("0",$_FILES["arquivo"]["error"]))?$_FILES["arquivo"]:FALSE;
// Executo a condição seguinte, se identificar um ou mais anexos junto a mensagem
if($file){
// É removido da matriz os anexos falsos
for($x=0; $x<count($_FILES["arquivo"]["name"]); $x++):
if(empty($file['name'][$x])){
unset($file['name'][$x]);
unset($file['size'][$x]);
unset($file['type'][$x]);
unset($file['tmp_name'][$x]);
unset($file['error'][$x]);
}else{
$attach[] = array(
$file['name'][$x],
$file['size'][$x],
$file['type'][$x],
$file['tmp_name'][$x]
);
}
endfor;
$boundary = "==Multipart_Boundary_x".md5(time())."x";
$body = stripslashes($html);
// Criamos os cabeçalhos MIME utilizados para separar as partes da mensagem MIME
$html = "--".$boundary.$snap;
$html.= "Content-Transfer-Encoding: 8bits".$snap;
$html.= "Content-Type: text/html; charset=\"ISO-8859-1\"".$snap.$snap;
$html.= $body.$snap;
$html.= "--".$boundary.$snap;
for($i=0; $i<sizeof($attach); $i++):
if(is_uploaded_file($attach[$i][3])){
$Name = $attach[$i][0];
$Size = $attach[$i][1];
$Type = $attach[$i][2];
$Temp = $attach[$i][3];
if((strlen($Name)>1) && ($Size>0)){
$fopen = fopen($Temp,"rb"); // Fazemos a leitura do arquivo a ser anexado em leitura binária(rb)
$fread = fread($fopen, filesize($Temp));
$cript = base64_encode($fread); // Codificamos o arquivo de dados com Base64
$close = fclose($fopen);
$chunk = chunk_split($cript); // Convertemos a saída de base64_encode(), conforme semântica RFC 2045
$html.= "Content-Disposition: attachment; filename=\"{$Name}\"".$snap;
$html.= "Content-Type: {$Type}; name=\"{$Name}\"".$snap;
$html.= "Content-Transfer-Encoding: base64".$snap.$snap;
$html.= $chunk.$snap;
if(sizeof($attach) == $i+1) $html.= "--".$boundary."--".$snap;
else $html.= "--".$boundary.$snap;
}
}
endfor;
// Adiciono os cabeçalhos de um arquivo anexado
$head = "MIME-Version: 1.0".$snap;
$head.= "From: {$mail}".$snap;
$head.= "Content-type: multipart/mixed; boundary=\"{$boundary}\"".$snap;
$head.= $boundary.$snap;
}
// Caso contrário, enviamos uma mensagem html, sem anexos
else{
$head = "MIME-Version: 1.0".$snap;
$head.= "From: {$mail}".$snap;
$head.= "Content-type: text/html; charset=\"ISO-8859-1\"".$snap;
}
endif;
?>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Multi-Anexos</title>
<link href="_css/typo.css" rel="stylesheet" type="text/css" />

Orcamentos - Provas - Outros Contatos

<?
// Se o formulário for enviado sem a presença do email do remetente, é exibido uma mensagem de retorno
if(isset($erro) && $erro==1):
?>

Clique aqui para retornar e informe um email válido!

<?
// Faço o envio da mensagem, se o formulário for submetido e passar no teste anterior
elseif(isset($subm)):
?>

<?
$msg1 = "
Sua mensagem foi enviada com sucesso!
";
$msg2 = "
Sua mensagem não pôde ser enviada.

Por favor tente novamente mais tarde.
";
$conf = @mail($__to, $__sj, $html, $head);
echo ($conf)?$msg1:$msg2;
?>

Clique aqui para retornar!

<?
// Exibe o formulário para preenchimento
else:
?>

Preencha o formulario abaixo para enviar sua mensagem.
Necessario preencher todos os campos.

<form id="frm" action="<?=basename(__FILE__)?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_ok" />
<fieldset>
<legend>Formulario de Contato</legend>

Nome:
<input id="nome" name="nome" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

E-Mail:
<input id="email" name="email" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

Telefone:
<input id="telefone" name="telefone" onKeyDown="if(event.keyCode==13) event.keyCode=9;" />

Para:
<select name="destino" class="texto">
<option value="daniel.e.silva@" selected>Selecione um Setor</option>
<option value="daniel.e.silva@">Provas</option>
<option value="daniel.e.silva@">Orçamento</option>
<option value="daniel.e.silva@">Administração do Site</option>
</select>

Anexo #1:
<input type="file" name="arquivo[]" size="50" class="file" />

Anexo #2:
<input type="file" name="arquivo[]" size="50" class="file" />

Anexo #3:
<input type="file" name="arquivo[]" size="50" class="file" />

Mensagem:
<textarea id="mensagem" name="mensagem" class="text"></textarea>

<input type="submit" value="ENVIAR" class="send" />

</fieldset>
</form>
<?
endif;
?>


views header (contextual) filter

Question: I have a node type news with a taxonomy reference (news categories). And I have a view for the news. In this view I have a contextual filter by this categories. The category comes with the url.
In this view I need a rendered entity (node type "views header") within the view header. These node type also uses the taxonomy "news category". At this point all works fine.
BUT: for every news category I need another entity within the view header.
This approaches I have:

Adding all nodes of type "views header" in the view header and filter them in the same context as the view itself. I tried if it is filtered per default with the view context filter but is does not.

The BUT here: I don't know how. How I can filter the nodes in view header. Is there a module for it which I didn't find?

Publishing the view header nodes as blocks. Adding the blocks in views template and configure the block visibility settings pages/only the listed pages. This solution works but I think there's too much overhead.

Does anyone know a more elegant solution?
Answer: I can see a couple of ways ahead.

Instead of creating a content type (a Node) just for the header, why not use the taxonomy term (an Entity) itself? Terms are fieldable, so you can add your additional content there, including image, other terms, &c. Then you can grab the term fields using the *replacement patterns from the "first row". You may need to create a Relationship to the term.
If you really want another Node I think you could use the Views Field View module. This way you can create a second View on your "Views Header" type, returning only one result, and pass the term ID from the first View's header to your second View.

Note: Using Views Field View in this manner follows a pattern known as a representative view. IE: A View on a node that is representative of all other nodes using this term. Views 3 does actually support representative views natively though it has some limitations and is generally more difficult to use. I talk about it more over here.
Comment: I will give a try solution 2. That looks good.

views header (contextual) filter


Jquery click function question

Question: I have a function that when user click first it will add a class then in second click it will remove the class, and again.. so on.. it's like when first click it means active, then second is not active. Just like that.
Here is my code:

$('.sub-nav-add').css('display','none');
   $('.nav-add').click(function(){
   $('.sub-nav-add').slideToggle(200);
   $('.box-add').addClass('sub-nav-active');
});

How can I add a second click function that will removeClass?
Answer: Use toggleClass.
<code>$('.sub-nav-add').css('display','none');
$('.nav-add').click(function(){
    $('.sub-nav-add').slideToggle(200);
    $('.box-add').toggleClass('sub-nav-active');
});
</code>
Answer: Take a look at the <code>.toggle</code> method. It will do exactly what you want.
Comment: Man, how have I never seen that before? That is really convenient.

Jquery click function question


Integration Trig Substitution

Question: I have solved a problem using a double "u" substitution as follows:
https://s30.postimg.org/y0eveutkx/IMG_9745.jpg
But I was told I need to use trig. After brushing up on the rules I did the following:
https://s30.postimg.org/dhoknj51d/IMG_9746.jpg
But now I find myself stuck. I am not missing something and as far as I know, this is correct so far.
What trick am I missing?
Thanks in advance!
Oh yea, I can't use the reduction rule either... Grrr
Comment: All your links are broken. Please remove them and type directly: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Are you just stuck at $\int \sec^4x \,dx$ ? If so, then Hint: write $\sec^4x =\sec^2x\,\sec^2x = \sec^2x\, (\tan^2x+1)$
Answer: $$\int \sec^4 (\theta) d\theta$$
Noting the power of $4$ is even, leave $\sec^2(\theta)$ because this is the derivative of $\tan \theta$ and perform the identity $\tan^2 (\theta)+1=\sec^2 (\theta)$ on the left powers.
$$\sec^4 (\theta)$$
$$(\tan^2 (\theta)+1)\sec^2 (\theta)$$
$$=\tan^2(\theta) \sec^2 (\theta)+\sec^2 (\theta)$$
This can be easily integrated. The first with substituting $u=\tan \theta$ and the second by noting what the derivative of $\tan \theta$ is $\sec^2 (\theta)$
$$\int \tan^2(\theta) \sec^2 (\theta) d\theta+\int \sec^2 (\theta) d\theta$$
$$=\frac{\tan^3 (\theta)}{3}+\tan (\theta)+C$$
Comment: Thank you!! I should of thought of that!! Many thanks!

Integration Trig Substitution


Prove for any integer $N$ that there exists $n > N$ where $n!-1$ is not a prime

Question: I was thinking about Euclid's proof of the infinitude of primes and the fact that we could make the argument about $n!-1$ instead of $n!+1$ when I wondered if it would be easy to prove that for any $N$, there is some $n > N$ where $n!-1$ is a composite number.
Answer: Wilson's theorem says that for a prime $p$ we have $(p-1)! \equiv -1 \pmod{p}$. It follows that $(p-2)! \equiv 1 \pmod{p}$, and hence $(p-2)! - 1$ is composite for every prime $p > 5$, since then $(p-2)! - 1 > p$. Since there are arbitrarily large primes, the proposition follows.


Programmatically set the value of a multi-value field from multiple arrays

Question: I have 3 taxonomy vocabularies:

Fruits
Vegetables
Drinks

On the Article content type, I have set a multi-value entity reference field field_article_all_items referencing all of Fruits, Vegetables and Drinks taxonomy vocabularies.
Using the Webform module, I have created a webform with 3 elements:

fruits_category which is a non-required, multi-value Entity Checkboxes element referencing the Fruits Taxonomy Vocabulary
vegetables_category which is a non-required, multi-value Entity Checkboxes element referencing the Vegetables Taxonomy Vocabulary
drinks_category which is a non-required, multi-value Entity Checkboxes element referencing the Drinks Taxonomy Vocabulary

Now on webform submit, I want to:

Create a new node of type article.
Set the values of field_article_all_items equal to all selected values
from fruits_category, vegetable_category and drinks_category.

In my customhandler.php file, I have tried:
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

the above code created a new node but with field_article_all_items field empty.
Also I have tried:
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        //'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = $Item;
}

// Save the created node again.
    $article->save();

// Also I have tried the below method.
//   $article->field_article_all_items[] = ['target_id' => $AllItems]

  //Save the created node again.
//   $article->save();

But also this code created a new node but with field_article_all_items field empty.
How to set the values of field_article_all_items equal to fruits_category + vegetable_category + drinks_category ?
Answer: Educated guess: (The key was to merge the arrays by using array_merge())
// Put all values in an array().
$AllItems = array_merge($FruitsCategory, $DrinksCategory, $DrinksCategory); // use array_merge

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = ['target_id' => $Item];
}

$article->save();

Also it can be used within the node creation:
// Put all values in an array().
    $AllItems = array_merge($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,  // use array_merge
        ]);
// Save the created node.
    $article->save();

Comment: to be noted that  `foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = ['target_id' => $Item];
}` will append $allItems to existings, with possible duplication inside `field_article_all_items`


What's with the spherical basis vectors?

Question: My short calculation Regarding the representation of the point (1,1,0) in spherical coordinates led me to an error. Have I miscalculated or is my view on the point being specified by $r=\sqrt{2}$, $\phi= \pi/4$ and $\theta =\pi /2$ Somehow wrong in the first place?
My heads stuck for the moment :(
Comment: $r$ should be $\sqrt{2}$
Comment: Yeah, typo, thx
Answer: There are two mistakes. The first is that $r$ should be $\sqrt{2}$. The second, and perhaps more confusing thing is that in spherical coordinates, the radius vector $\mathbf{r}$ is simply $\mathbf{r} = r \mathbf{\hat{r}}$, it is NOT $ r \mathbf{\hat{r}} + \theta \mathbf{\hat{\theta}} +  \phi \mathbf{\hat{\phi}}$. This is a very common misconception.
So, yes, although the spherical coordinate representation of the point $p = (1,1,0)\in \Bbb{R}^3$ is $r=\sqrt{2}, \theta = \pi/2, \phi = \pi/4$, the radius vector is still
\begin{align}
\mathbf{r} &= \sqrt{2}\,\, \mathbf{\hat{r}}
\end{align}
Comment: This seems counterintuitive to me, as every vector in the R3 should be the linear combination of the three(!) basis vectors. As you state, it seems that the basis vectors of $\rho$ and $\theta$ are redundant in some way... is this because they are not constant through R3 and do depend on the angles?
Do you have any recommendations on further readings on the topic?
Comment: Another glimpse, that just came through my head: At each triplet (r,$\rho$,$\theta$), the corresponding basis vectors $\hat r, \hat \phi$ and $\hat \theta$ form a right hand coordinate system, that origins at the given point on the sphere. Is this somehow useful to declace right hand coordinate systems, that may be arbitrarily shifted and rotated from the origin of the cartesian coordinate system?
Comment: @PeterSanctus There's really too much to mention in a comment, but the thing is there's a slight abuse of notation and terminology going on. If we want to be really formal, then what is going on is that for each point $p \in \Bbb{R}^3$, the vectors $\hat{r}(p),\hat{\phi}(p),\hat{\theta}(p)$ are elements of what is known as the tangent space $T_p\Bbb{R}^3$. And these form a basis for that particular tangent space. If you go to a different point $q \in \Bbb{R}^3$, then the tangent vectors there $T_q\Bbb{R}^3$ is a completely different vector space.
Comment: at each point, there is a different tangent space, which is why you may have heard the statement "the spherical basis vectors vary from point to point". But where the confusion begins is when people start using isomorphisms of $\Bbb{R}^3 \cong T_p\Bbb{R}^3$. By the way, I'm not saying that the other basis vectors are redundant at all. They're very important. It's just that if you take a point $p \in \Bbb{R}^3$, and consider it's image point in $T_p\Bbb{R}^3$ (under the isomorphism $\xi_p: \Bbb{R}^3 \to T_p\Bbb{R}^3$) then $\xi_p(p) = \lVert p\rVert \hat{r}(p)$
Comment: However, if you consider the same point $p \in \Bbb{R}^3$, but if you consider its image in a different tangent space $T_q\Bbb{R}^3$, namely $\xi_q(p)$ (i.e draw a dot in space; call this point $p$. Now, imagine drawing the arrow from the origin to the point $p$, now "transport" that arrow so that the tail starts at the point $q$; this is what I mean by $\xi_q(p)$). Then, in this case, $\xi_q(p)$ will be a linear combination of all three basis vectors $\hat{r}(q), \hat{\phi}(q), \hat{\theta}(q)$. So, you see, the other two basis vectors are very important.
Comment: So, part of your confusion comes from the fact that in the usual notation of $\hat{r}, \hat{\phi}$ and $\vec{r}$, people suppress the dependence of these vectors on the point they "originate from" (i.e they don't explicitly mention that we're looking at different tangent spaces). So, not making these things explicit is a huge part of the confusion (and also not explicitly clarifying the various isomorphisms which are used).
Comment: so $r \cdot \hat r$ points to the origin of the considered tangent space. when I now add up those $\phi$ and $\theta$ components as I did in my orgininal calculation, I end up at a point shifted by $\pi /2$ in the $\theta$-direction and by $\pi /4$ in the $\phi$-direction to the origin of the tangent space?
Comment: thanks, anyways, for your clarification of these matters =)
Comment: Sort of. Roughly speaking, $\hat{r}(p)$ is a vector of length 1, whose direction is from the origin to the point $p$, and we think of it as "having the tail at the point $p$". So, $r \, \hat{r}(p)$ is the vector with length $r$, and direction is from $0$ to $p$, but with the tail beginning at $p$. Now, if you add things like $\pi/2 \, \hat{\theta}(p)$ to $r\, \hat{r}(p)$, you get another vector (again with the tail starting at $p$), but it points in a different direction and has a different length.
Comment: again, I've been somewhat purposely vague regarding the distinction between "point" and "vector", because the "definitions" you may see in introductory courses are very vague, but at the same time, I'm not sure I should just dump a whole bunch of definitions on you (because they require a bit of background to develop properly). Anyway,don't worry too much if you didn't understand every single subtle distinction I tried to make (I always had a "working understanding" of these matters but only properly clarified the fine details for myself after having taken a course in differential geometry)
Answer: If you want to convert to spherical coordinates, you need to do the following

Calculate distance from origin - $r$

$$r = ||p|| = \sqrt 2$$

Calculate $\theta$ - angle made by position vector with z-axis: Since the vector is in $xy$ plane, this angle will be $\frac{\pi}{2}$

Calculate $\phi$ - angle made by projection of position vector onto $xy$ plane with x-axis: Since the vector is already in the x-y plane, the projection is itself, and it makes an angle of $\frac{\pi}{4}$ with it

Hence, point in $(r,\theta, \phi)$ system is $(\sqrt 2, \frac{\pi}{2}, \frac{\pi}{4})$, which is what you have got in the calculations. What you did after that I do not understand

What’s with the spherical basis vectors?


innerHTML example: With user input it doesn´t work, why?

Question: I have this working code, with an example of innerHTML:

Hola gente

<input type='button' onclick='cambiarColor()' value='Change Text'/>

But then I wanted to change color using some user input.
My problem is that it doesn´t work. It shows (in the color the user chooses) the word "undefined". I´ve used the console and I understand that "mensaje" variable is not defined? Why is that?

Mensaje que cambia de color

<input type="text" id="nuevoColor">
<input type='button' onclick='cambiarColorUser()' value='Cambia el Color!'/>

UPDATE
After reading your replies, I´ve updated the code, that still won´t work (http://jsfiddle.net/vjze5/):

Mensaje que cambia de color

<input type="text" id="nuevoColor">
<input type='button' onclick='cambiarColorUser()' value='Cambia el Color!'/>

Note: If I type "red" inside the text input, and open the console in Chrome, and type "cambiarColorUser()" it replies "undefined".
Comment: So, for me, here **[it works](http://jsfiddle.net/davidThomas/M7zHa/)**?
Comment: @DavidThomas - it's the second code block that doesn't work.
Answer: In this line of your code:
mensaje=document.getElementById('clase').value;

.value is for some form controls, not for paragraph tags.
Perhaps you meant for that line of code to be:
mensaje=document.getElementById('clase').innerHTML;

Also, all local variables (variables intended to be used only within a funnction) should be declared with var in front of them.  This isn't actually causing a problem in your current code, but is a very bad practice and will cause problems in the future.


How to restart my guitar studies from scratch?

Question: I have being playing the guitar for quiet a while now(12+ years but more dormant years within this). I am able to deduce guitar tabs of a given song on my own(mostly with some minor errors). I have made a completely independent fingerstyle version of a song(and tried for other songs, but have mostly remained unsuccessful, and I made peace with guitar tabs). I know how to vary the strumming pattern within a given song. I know Rumba Flamenco variations upto some extent. But above all of this, I innovate and try to insert my own style in whatever I play.
Now, I did learn from a guitar teacher when I had started out, but in all truth, this teacher didn't teach me music theory or so. Most of what I am capable of performing on my guitar is by practice based on learning from youtube videos, etc.
Now, I want to rigorously begin from the beginning, starting from music theory concepts, etc.
My goal is to become more independent in case of fingerstyle guitar. Learning as much as possible.
Comment: The easiest approach will be to get a good teacher.
Answer: The one best solution, having tried others, is to get back with a teacher. There are many questions/answers here regarding establishing an appropriate teacher. One who works with you successfully may not work so well for others, and vice versa, so you need to make a list of what skills, activities, pressures are appropriate, along with costs, availability, and, if you like, prowess and qualifications. Past records of students' achievements may be a good yardstick, but please read the other q/as.
Failing that, and there may be many good reasons for not using a teacher, there are workshops and open mic sessions, where you could go and rub shoulders with other guitarists - sometimes free, sometimes at a cost. You could also have a look at some of the exam board material available for guitar - RGT and Rockschool come to mind, not necessarily to take the exams (although that in itself isn't a bad move), but to immerse yourself more thoroughly in guitarring, in several different genres.
P.S. do not allow yourself to become reliant on tab, you will live to regret it!
Comment: From my heart, I want to properly progress in fingerstyle, but I have failed to make any significant progress in it. So, it felt maybe I need to revisit the basics, besides I don't know much about music theory(but I do want to), just practical usage of stuff. Yes, lead chords seem dry by themselves without having an environment of beats(one way to interject fingerstyle...).
Comment: i had this experience with bass - I went right back to "three blind mice" to fix my timing and some bad habits. A teacher is a good suggestion though you can get quite far with self-discipline also.


Como capturar conteúdo de span por JavaScript

Question: No WhatsApp Web, cada mensagem enviada é armazenada em um span. Preciso atribuir o valor da última mensagem enviada pelo interlocutor a uma variável, assim como faço com o conteúdo da caixa "Envie uma mensagem":
var textbox = document.querySelector('#main > footer > div.block-compose > div.input-container > div.pluggable-input.pluggable-input-compose > div.pluggable-input-body.copyable-text.selectable-text');
alert(textbox.textContent);

Imagino que eu preciso pegar o conteúdo da última span de cor branca (linha azul, na imagem acima), mas não estou conseguindo.
Tentei da seguinte forma, mas o retorno é null:
var ultima = document.querySelector('#main > div.pane-body.pane-chat-tile-container > div.copyable-area > div.pane-chat-msgs.pane-chat-body.lastTabIndex > div._9tCEa > div.msg.msg-group > div.message.message-chat.message-in.tail.message-chat > div.bubble.bubble-text.has-author.copyable-text > div._3zb-j.ZhF0n > span.emojitext.selectable-text.invisible-space.copyable-text');
alert(ultima);

Estou executando o script no Console mesmo, quando clico F12 no WhatsApp Web.
Comment: Seria melhor vc postar na pergunta o código HTML da span. Há muitas formas de capturar isso, mas é preciso saber o que tem nessa span.
Comment: Pronto. Conforme a imagem, preciso capturar o conteúdo daquela linha em azul (sempre a última mensagem do WhatsApp naquela conversa).
Answer: Você consegue com o seguinte seletor:
var els = document.querySelectorAll('.message-in span.copyable-text'); // seleciono todas
var conta = els.length; // conto a quantidade
var texto = els[conta-1].textContent; // pego o texto da última

A classe .message-in se refere às mensagens recebidas. Neste caso, basta contar quantas existem e pegar o texto da última, diminuindo a quantidade por 1 (o index da coleção começa com 0, portanto, o index do último elemento sempre é a quantidade menos 1).
Testar no Whatsapp Web
Se quiser testar na página do WA Web, abra o console (F12) numa conversa e execute a linha abaixo:
els=document.querySelectorAll('.message-in span.copyable-text');conta=els.length;texto=els[conta-1].textContent;

Comment: Aparece a seguinte mensagem: "VM64:3 Uncaught TypeError: Cannot read property 'textContent' of undefined
    at :3:26"
Comment: Aconteceu o mesmo erro... VM66:1 Uncaught TypeError: Cannot read property 'textContent' of undefined
    at :1:101
Comment: @lucaswmolin Aqui funcionou. Tem conversa na janela?
Comment: Opa, dei F5 e tentei de novo. Funcionou, sim. Obrigado.


Variance of an integer-valued parameter estimator for Poisson distribution

Question: Supposing I have a Poisson distributed random variable $X \sim \text{Poiss}(\lambda)$ with a parameter $\lambda$ that could take integer values only. Let $x$ be a single observation of a random variable. I could now get the estimate $\hat{\lambda}$ of the parameter by maximizing the likelihood function:
$$
\hat{\lambda} = \arg\max_{\lambda \in \mathbb{N}}{ \log{p(x|\lambda)} }, \tag{1}
$$
where $p(x|\lambda)$ is the Poisson PDF. To get the estimator variance $\text{Var}(\hat{\lambda})$ I first calculate the estimator distribution as
$$
f(\hat{\lambda}|\lambda_0)=\sum_{x\in\mathbb{N}}{p(x|\lambda_0)\mathbf{1}_{\{\log{p(x|\hat{\lambda})} \geq \log{p(x|\lambda)}, \forall\lambda\in\mathbb{N}\}}}. \tag{2}
$$
Here $\lambda_0\in\mathbb{N}$ is the true parameter value and $\mathbf{1}_{\{\cdot\}}$ is equal to 1 if condition in brackets holds and 0 otherwise. Since I computed (2) I can easily get $\text{Var}(\hat{\lambda})$. But things get worse when I try to estimate the parameter using a sample $x_1, x_2, \dots, x_n$ of the size $n$. In this case the estimator is
$$
\hat{\lambda} = \arg\max_{\lambda \in \mathbb{N}}{ \sum_{j=1}^{n}{\log{p(x_j|\lambda)}} }. \tag{3}
$$
Now the estimator PDF is
$$
f(\hat{\lambda}|\lambda_0)=\sum_{x_1,\dots,x_n\in\mathbb{N}}{p(x_1|\lambda_0)\cdot\ldots\cdot p(x_n|\lambda_0)\mathbf{1}_{\{\sum_{j=1}^{n}{\log{p(x_j|\hat{\lambda})}} \geq \sum_{j=1}^{n}{\log{p(x_j|\lambda)}}, \forall\lambda\in\mathbb{N}\}}}. \tag{4}
$$
There is no way to compute (4) for large $n$ (about $10^4$ in my case). So my questions are:

Can I somehow simplify (4) to break the sum into a product?
Are there some other ways to estimate the variance of the estimator (3)?

Things that I've tried
First of all I've tried to estimate the variance using Cramer-Rao bound by taking the finite difference derivative:
$$
\text{Var}(\hat{\lambda}) = \left(n\mathbb{E}\left[(\log{p(x|\lambda_0+1)}-\log{p(x|\lambda_0))^2}\right]\right)^{-1}. \tag{5}
$$
As expected, that didn't work quite well: the variance in simulation was lower than this value.
Then I came across a more general Hammersley–Chapman–Robbins bound. One can find that for my case the lower bound is (e.g. see [Dahiya R.C., Commun. Stat. - Theory Methods, 15(3), 709 (1986)])
$$
\text{Var}(\hat{\lambda}) = \left(e^{n/\lambda_0}-1\right)^{-1}. \tag{6}
$$
However, this bound turned out to be too tight and was unreachable for any estimator I could find due to exponential decrease of the bound with $n$ (the same problem stated in Dahiya's article).
Answer: If you need the exact variance you're in trouble, I think. If not, progress can be made.
To start with, the monotone likelihood ratio property of exponential families means that $\hat\lambda$ is either the integer below the mean $\bar X$ or the integer above the mean.  The variance of $\bar X$ is $\lambda/n$.
Consider some ranges of ($n$,$\lambda$):

If $\sqrt{\lambda/n}\gg 1$ then $\mathrm{var}[\hat\lambda]\approx \lambda/n$, since the reduction in variance caused by making $\hat\lambda$ an integer is small compared to the standard error of the mean.

For slightly smaller $\lambda/n$, $\mathrm{var}[\hat\lambda]$ is a bit smaller than $\lambda/n$. We can write
$$\mathrm{var}[\hat\lambda] \approx  \mathrm{var}[\bar X] - \mathrm{var}[\bar X-\hat\lambda]$$
and approximate the second term by the variance of a $U[-0.5, 0.5]$
$$\mathrm{var}[\hat\lambda] \approx  \mathrm{var}[\bar X] -1/12$$
(this is the opposite of the Sheppard correction for rounding)

The difficult case: $\lambda/n$ not far from 1. I think this needs actual calculation, but only over the relatively small number of $\hat\lambda$ values with non-negligible probability.

At the far extreme, if $\sqrt{\lambda/n}\ll 1$, $\mathrm{var}[\hat\lambda]\approx 0$ (and even $n\mathrm{var}[\hat\lambda]\approx 0$), since $\hat\lambda=\lambda$ with very high probability.
For example, if $\sqrt{\lambda/n}=1/10$, different integers are ten standard deviations apart, so it will be very unlikely for the closest integer to $\bar X$ not to be the true $\lambda$.
Comment: Can I interpret the last option as follows: for a continuous-valued parameter MLE asymptotically gives a normally distributed estimator, which I can then approximate to a discrete distribution by turning the PDF into a histogram with bin centers located at the discrete values?
Comment: Yes, but the condition is stronger than just 'continuous-valued'.  For some other type of distribution it might be possible for the discrete MLE to not just be a rounded continuous MLE, but for Poisson it will be.
Comment: Can I get some examples of a discrete parameter MLE? Is it like the one from [this question](https://math.stackexchange.com/questions/40319/maximum-likelihood-estimate-of-hypergeometric-distribution-parameter)?
Comment: Yes, balls in urns are a classic example where the parameter is discrete. Another two are from ecology:  estimating the population of a type of animal or the number of distinct species of animal. Often, though, you're in the first situation in the answer, where the discreteness can be ignored


Is there a way in JavaScript to directly get the content width of an element when box-sizing:border-box is set in CSS?

Question: If we set this in CSS (autoprefixed):
* {
  box-sizing: border-box
}

then getComputedStyle(elem).width includes the element's padding.
Live demo: http://jsfiddle.net/simevidas/EpUnp/
I would like to get the width of the element's content box (without the padding). Is there a standard API for this or do I have to manually subtract the padding?
Comment: I *think* you have to, but "I think" isn't an answer. :-)
Comment: http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
Comment: @Teemu …but *with* the padding -.-
Comment: I too am almost certain you have to calculate it yourself (though it should only be a very simple function).
Comment: @Paulie_D jQuery of course has its little, neat methods for this, but I'm curious if the Web Platform itself provides an API for this.
Comment: Looking at the jquery fix for this, that's exactly what they did: subtracted border and padding when border-box is set. https://github.com/jquery/jquery/commit/d7217cc29c24f582198ce2df7db54a55625e8259
Comment: @T.J.Crowder Turns out, there is a standard API for this, but it's only supported in Firefox (for now).
Comment: @ŠimeVidas: Apparently it's "at risk" though. Not so much a standard API as the beginnings of something that may, at some point, possibly become standard in some form. :-)
Comment: @T.J.Crowder The latest CSSOM View editor's draft is from January 9th and Firefox landed this API around the end of March. I hope that means that it's no longer at risk :)
Comment: @ŠimeVidas: Well, it still [says it is](http://dev.w3.org/csswg/cssom-view/#the-geometryutils-interface).
Comment: @T.J.Crowder My point was that this draft is from January, *before* it was implemented in Firefox. Not sure how old this API is, but when an API has no implementations, that can trigger an "at risk" flag. With Firefox's implementation, this flag could very well be lifted in the next editor's draft.
Answer: The getBoxQuads API can do it. (It's supported in Firefox Nightly).
var quad = elem.getBoxQuads({ box: 'content' })[0];
var contentWidth = quad.p2.x - quad.p1.x;

Live demo: http://jsfiddle.net/EpUnp/2/ (works in Firefox Nightly)
Comment: @mastaBlasta 1. Standard API means published by W3C, ECMA, etc., 2. Firefox Nightly means that it will be available in Firefox in a few months.
Answer: I don't think there is a standard API for this. I could be wrong though.
My approach would be something like as follows.
Demo
HTML

CSS
* {
    box-sizing: border-box
}
#box {
    width:300px;
    height:300px;
    padding:14px 10px;
    background-color:#000;
}

JavaScript
var supports = function () {
    var div = document.createElement("div"),
        vendors = "Moz Webkit O Ms".split(" "),
        len = vendors.length;

    return function (prop) {
        if (prop in div.style) return true;

        prop = prop.replace(/^[a-z]/, function (val) {
            return val.toUpperCase();
        });

        while (len--) {
            if (vendors[len] + prop in div.style) {
                return true;
            }
        }
        return false;
    };
};

var isBox = supports("box-sizing");

var getWidth = function (elem) {
    var width = parseFloat(window.getComputedStyle(box).width);
    var padding = window.getComputedStyle(box).padding.split(" ");

    if (!isBox) {
        return width;
    }

    switch (padding.length) {
        case 4:
            return width - (parseFloat(padding[1]) + parseFloat(padding[3]));
            break;
        case 2:
            return width - (parseFloat(padding[1]) * 2);
            break;
        default:
            return width - (parseFloat(padding[0]) * 2);
            break;
    }
}

var box = document.getElementById("box");

alert(getWidth(box));

Rough and ready but seems to work :)


What is the distribution of the limit of random variables in a problem involving Polya's Urn?

Question: I know this has been asked elsewhere, but I think the values or random variables are different or something.
From Williams' Probability with Martingales:

I proved that $M_n$ is a $\sigma(B_1, ..., B_n)-$martingale and $P(B_n = k) = \frac{1}{n+1}$
I guess $\Theta := \lim M_n$ exists $\because M_n$ is a nonnegative martingale.
So to give the distribution of $\Theta$, I tried to find the moment-generating function, though I'm not sure if we know that $M_{\Theta}(t)$ exists (also tried something else in answer posted):
$$M_{\Theta}(t) = E[\exp(t\Theta)]$$
$$= E[\exp(t\lim \frac{B_n + 1}{n+2})]$$
$$\stackrel{(*)}{=} E[\exp(t\lim \frac{B_{n+1} - B_n}{1})]$$
$$= E[\exp(t\lim (B_{n+1} - B_n))]$$
$$= E[\lim \exp(t (B_{n+1} - B_n))]$$
$$\stackrel{(**)}{=} \lim E[\exp(t (B_{n+1} - B_n))]$$
where
$$E[\exp(t (B_{n+1} - B_n))]$$
$$= E[E[\exp(t (B_{n+1} - B_n)) | B_n]]$$
$$= E[e^{t (0)}(1 - M_n) + e^{t (1)} M_n]$$
$$= E[(1 - M_n) + e^{t} M_n]$$
$$= E[(1 - M_n) + e^{t} M_n]$$
$$= E[(1 - M_n)] + E[e^{t} M_n]$$
$$= (1 - E[M_n]) + e^{t}E[ M_n]$$
$$= (1 - (\frac 1 2)) + e^{t}(\frac 1 2)$$
$$= (\frac 1 2) + e^{t}(\frac 1 2) = (1 + e^{t})(\frac 1 2)$$
Hence, $M_{\Theta}(t) = \lim (1 + e^{t})(\frac 1 2) = (1 + e^{t})(\frac 1 2)$.

Any mistakes?
Any suggestions for alternative solutions? Might I be able to evaluate $\lim (B_{n+1} - B_n)$?
This seems to say that $\Theta \sim Bernoulli (\frac 1 2)$. Is it? I tried $\Theta \sim Beta (\alpha, \beta)$ but it seems like $\alpha = \beta = 0$, which violates the assumptions of $\alpha, \beta > 0$, and I guess $Bernoulli(\frac 1 2)$ is kind of like $Beta(0,0)$ (p. 5-6)?
$(*)$ I used Stolz–Cesàro theorem. Is that right? If not, how else can I approach this problem? If so, is there a way to approach this problem without Stolz–Cesàro (it was never discussed in any class I attended in undergrad and grad)?
$(**)$ I think we can use something like a general bounded convergence theorem as $e^{t (B_{n+1} - B_n)}$ is bounded but not uniformly bounded right? If not, how else can I approach this?
Comment: To potential readers: this is 1. flawed, 2. in an obvious way, starting at the $(\ast)$ step.
Comment: You know that $B_{n+1} - B_n \in \{0,1\}$. So if that were a convergent sequence, from some point onward, we'd always have $B_{n+1} = B_n$, or always $B_{n+1} = B_n + 1$. What do you **know** about $P(B_{n+1} = B_n)$ and $P(B_{n+1} = B_n + 1)$?
Comment: $(\ast)$ cannot be true since almost surely the sequence $(B_{n+1} - B_n)_{n\in \mathbb{N}}$ contains infinitely many ones and infinitely many zeros, so the right hand side simply doesn't make sense.
Comment: @Did So why is it wrong, and how else can I approach this?
Comment: Is there any reason to believe that $\lim\limits_{n\to\infty} (B_{n+1} - B_n)$ exists?
Comment: @DanielFischer Prove it does not then...? If it doesn't exist, how else can I approach this problem?
Comment: @DanielFischer Okay so what do I do instead?
Comment: @DanielFischer Or: could $(*)$ be true by some other route?
Comment: @DanielFischer [Okay so what do I do instead?](http://math.stackexchange.com/questions/1590567/distribution-in-polyas-urn-existence-of-mgf-stolz-ces%c3%a0ro-alternative-domi?noredirect=1#comment3311892_1590567)
Answer: $$M_{\Theta}(t) = E[\exp(t\Theta)]$$
$$= E[\exp(t\lim \frac{B_n + 1}{n+2})]$$
$$= E[\lim\exp(t \frac{B_n + 1}{n+2})]$$
$$= \lim E[\exp(t \frac{B_n + 1}{n+2})]$$
$$= \lim \frac{1}{n+1}[\exp(t \frac{1}{n+2}) + \exp(t \frac{2}{n+2}) + ... + \exp(t \frac{n+1}{n+2})]$$
Case 1: $t \ne 0$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} (1-a(n)^{n+1}), \ \text{where} \ a(n) := e^{\frac{t}{n+2}}$$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} \lim (1-a(n)^{n+1})$$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} (1-e^t)$$
$$= \frac{1-e^t}{-t}$$
$$= \frac{e^t-1}{t}$$
Case 2: $t = 0$
$$= \lim \frac{1}{n+1}[\exp((0) \frac{1}{n+2}) + \exp((0) \frac{2}{n+2}) + ... + \exp((0) \frac{n+1}{n+2})]$$
$$= \lim \frac{1}{n+1} (1)(n+1) = 1$$
This is the mgf of $Unif(0,1)$


ln transformed data: how to report lme results in original units

Question: I conducted an experiment to observe the effect a repeated treatment had on the concentration of protein in a set of samples. I have no formal training in statistics.
My goal is to report how much protein is lost per treatment, and to condense this into a prediction for how much one might expect to lose at any given treatment.
I thought a linear mixed model would be an appropriate method to use, and created a model in R using the lme function of the nlme package (ver 3.1-118).
Problem: to meet model assumptions I transformed data by ln. I do not understand what the results mean in terms of my units of interest (pg/mL - protein concentration).
My code (should be plug and play):
# packages
library(nlme)
library(ggplot2)

# data vectors
Sample <- c("S9", "S9", "S9", "S9", "S9", "S9", "S9", "S9", "S10", "S10", "S10", "S10", "S10", "S10", "S10", "S10", "S11", "S11", "S11", "S11", "S11", "S11", "S11", "S11", "S12", "S12", "S12", "S12", "S12", "S12", "S12", "S12", "S13", "S13", "S13", "S13", "S13", "S13", "S13", "S13", "S14.1", "S14.1", "S14.1", "S14.1", "S14.1", "S14.1", "S14.1", "S14.1", "S14.2", "S14.2", "S14.2", "S14.2", "S14.2", "S14.2", "S14.2", "S14.2", "S14.3", "S14.3", "S14.3", "S14.3", "S14.3", "S14.3", "S14.3", "S14.3", "S15.1", "S15.1", "S15.1", "S15.1", "S15.1", "S15.1", "S15.1", "S15.1", "S15.2", "S15.2", "S15.2", "S15.2", "S15.2", "S15.2", "S15.2", "S15.2", "S15.3", "S15.3", "S15.3", "S15.3", "S15.3", "S15.3", "S15.3", "S15.3")
Treatment <- c( 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7)
ProtConc <- c(244, 160, 143, 129, 102, 91.1, 76.6, 58, 148, 85.3, 75.2, 60.9, 55.6, 41.9, 33.2, 27.9, 303, 205, 136, 114, 89.6, 71.9, 52.4, 42.6, 210, 124, 114, 94.1, 76.9, 56.1, 50.4, 38.5, 566, 431, 358, 287, 254, 193, 158, 113, 374, 239.5, 188, 150.5, 133.5, 102, 69.35, 51.85, 307, 193, 174.5, 160, 121, 87.25, 74.95, 57.2, 324.5, 219.5, 161, 161.5, 126, 106, 77.15, 59.85, 534, 316.5, 270.5, 209, 161.5, 127, 99.7, 74.9, 454, 280, 244.5, 197.5, 172.5, 130, 105, 67.7, 514, 252.5, 244.5, 217, 162, 126, 98.6, 77.3)
lnProt <- c(5.497168225, 5.075173815, 4.96284463, 4.859812404, 4.624972813, 4.511957804, 4.338597077, 4.060443011, 4.997212274, 4.446174454, 4.320151231, 4.109233175, 4.018183201, 3.735285827, 3.502549876, 3.328626689, 5.713732806, 5.323009979, 4.912654886, 4.736198448, 4.49535532, 4.275276265, 3.958906591, 3.751854253, 5.347107531, 4.820281566, 4.736198448, 4.544358047, 4.342505877, 4.027135813, 3.919991175, 3.650658241, 6.338594078, 6.06610809, 5.880532986, 5.659482216, 5.537334267, 5.262690189, 5.062595033, 4.727387819, 5.924255797, 5.478553417, 5.236441963, 5.013963084, 4.894101478, 4.624972813, 4.239166147, 3.948354935, 5.726847748, 5.262690189, 5.161924742, 5.075173815, 4.795790546, 4.468777561, 4.316821225, 4.046553898, 5.782285536, 5.391352233, 5.081404365, 5.084505143, 4.836281907, 4.663439094, 4.345751579, 4.091841432, 6.280395839, 5.757323242, 5.600272098, 5.342334252, 5.084505143, 4.844187086, 4.602165677, 4.316153891, 6.118097198, 5.634789603, 5.499215309, 5.285738584, 5.150397236, 4.86753445, 4.65396035, 4.21508618, 6.242223265, 5.531411249, 5.499215309, 5.379897354, 5.087596335, 4.836281907, 4.591071262, 4.347693956)

# data frame
df <- data.frame(Sample, Treatment, ProtConc, lnProt)
dftreat <- as.factor(df$Treatment)

# mixed model
mod1 <- lme(ProtConc ~ Treatment, random = ~1|Sample, data=df)
summary(mod1)
intervals(mod1)

# assumption tests
plot(mod1)
hist(residuals(mod1))
qqnorm(residuals(mod1)); qqline(residuals(mod1))
agostino.test(df$ProtConc)

# graph
ggplot(data=df, aes(x=dftreat, y=ProtConc, group=Sample)) +
geom_line(aes(colour=df$Sample, linetype=df$Sample), size=1) +
scale_y_continuous(limits=c(0,600), breaks=seq(0,600, 50)) +
labs(title="Effect of repeated treatment on protein concentration", x="Treatment", y="Concentration (pg/mL)",
   linetype="Sample", colour="Sample")

The 'assumption tests' show that data violate model assumptions of linearity and normality. This can also be seen in the graph, the first treatment clearly has a greater effect than subsequent treatments.
The data is playing hardball. Transform it by ln:
# mixed model ln
mod2 <- lme(lnProt ~ Treatment, random = ~1|Sample, data=df)
summary(mod2)
intervals(mod2)

# assumption tests
plot(mod2)
hist(residuals(mod2))
qqnorm(residuals(mod2)); qqline(residuals(mod2))
agostino.test(df$lnProt)

# graph
ggplot(data=df, aes(x=dftreat, y=lnProt, group=Sample)) +
geom_line(aes(colour=df$Sample, linetype=df$Sample), size=1) +
scale_y_continuous(limits=c(0,10), breaks=seq(0,10, 1)) +
labs(title="Effect of repeated treatment on ln protein concentration", x="Treatment", y="Concentration (pg/mL)",
   linetype="Sample", colour="Sample")

Great, assumption tests suggest data are now model compatible.
As I understand it, the coefficient -0.232904 describes the slope of the difference between treatments, and is my model's prediction of the effect of any given treatment event based on the data.
However, the coefficient should be exponentiated to transform it back into the original unit (pg/mL). 2.718281828^-0.232904 = 0.7922
This does not look even nearly sensible, and clearly I misunderstand something. Presumably one can treat 0.7922 as a negative value, but the average effect of treatment is manifestly not -0.7922 pg/mL.
I would gratefully appreciate your time and help in explaining where I am going wrong.
It would also be great to know how to get an output showing the coefficient between each consecutive treatment.
Cheers
Answer: Voting to close/move to CrossValidated. Since I'm impatient ...
Short answer: the exponentiated coefficient is not a linear change per unit of change in Treatment, but a multiplicative change (i.e., every 1-unit change in Treatment leads to multiplying the protein concentration by 0.79, or an approximately 21% decrease). For small values of the coefficient, you can read them directly (approximately) as a proportional change, so if you said "-0.23, that means approximately a 23% decrease" you would have been in the ballpark (off by 0.02 in the rate of change, or about 10% off in relative terms).


Modifying a Swing Timer's Delay during Runtime

Question: I'm developing a Queue simulation, using a Swing Timer to dequeue objects after certain amounts of time. The interval is determined by peeking at the next object in the queue, getting an integer from it, and setting the delay of its corresponding timer.
Here's the relevant snippet from the program (Note: _SECONDS_PER_ITEM is a constant defined elsewhere to 2000):
// stop the timer
qTimer[q].stop();

// peek at how many items the customer has, and set the delay.
qTimer[q].setDelay(customerQueue[q].peek().getItems()*_SECONDS_PER_ITEM);

// the next time around, this method will see the flag, and dequeue the customer.
working[q] = true;

// denote that the customer is active on the UI.
lblCustomer[q][0].setBorder(new LineBorder(Color.RED, 2));

// start the timer.
qTimer[q].start();

The problem I have is that every customer, no matter how many items they have, is processed in one second.
Is there some other method or technique I should be using to set the delay?
Answer: It would seem that when stop()ing a Timer, the delay that is used to fire the next event is the initial delay. Thus, the correct method to use in the above example, is setInitialDelay():
{
// stop the timer
qTimer[q].stop();

// peek at how many items the customer has, and set the delay.
qTimer[q].setInitialDelay(customerQueue[q].peek().getItems()*_SECONDS_PER_ITEM);

// the next time around, this method will see the flag, and dequeue the customer.
working[q] = true;

// denote that the customer is active on the UI.
lblCustomer[q][0].setBorder(new LineBorder(Color.RED, 2));

// start the timer.
qTimer[q].start();

}


htdocs in RAM disk?

Question: I was wondering the other day why wouldn't one place all the htdocs related files in a RAM disk.
It seems to me, that this would greatly improve the time it takes for the disk to lookup and read files, greatly improving performance - specially for high websites with a high concurrency hit rate.
Is there a package that can implement this in a transparent way for reading operations, while at the same time making sure the write operations are safely stored on disk? If not, is there a reason not to?
Answer:
Is there a package that can implement this in a transparent way for reading operations, while at the same time making sure the write operations are safely stored on disk?

Yes there is, it's part of the operating system.
All modern operating systems have what is called a filesystem cache.  This is a portion of RAM that is unused for any applications that gets used by the kernel to store recently accessed files.  It is also used to store recently written files until they are periodically flushed to the disk.
When an application needs the RAM, it is transparently given up by the kernel.
Answer:
I was wondering the other day why wouldn't one place all the htdocs related files in a RAM disk.

Because modern operating systems already cache stuff in memory as needed, and can usually manage this process more efficiently if left alone to get on with it. All you're doing with a RAM disk is creating your own manual version of this cache.
Answer: Since most websites are dynamic - accelerating access to just static data (htdocs) does not help that much. But most production sites do use Memcached/MemcacheDB like technologies.

Memcached is a general-purpose distributed memory caching system that
  was originally developed by Danga Interactive for LiveJournal, but is
  now used by many other sites. It is often used to speed up dynamic
  database-driven websites by caching data and objects in RAM to reduce
  the number of times an external data source (such as a database or
  API) must be read.
Comment: Yes, but we don't put _static_ assets in memcached. There's no point.

htdocs in RAM disk?


Liszt's 1st and Beethoven's 5th

Question: I don't even qualify as an amateur when it comes to music analysis, but I do sometimes hear similar contours across pieces. This is such a case. Is there any criticism that suggests an allusion in the first movement of Liszt's 1st piano concerto to the first movement of Beethoven's 5th ("Emperor")?
As I listened to both this morning, they seemed to share a recurrent chromatic buildup in the piano to grand orchestral entrances, even with similar rhythm — but each time Liszt has the orchestra hold back instead. I'm having trouble finding a score with numbered measures, but compare e.g. the first 7 measures on page 4 of this score (see video) and the measures where the orchestra comes in on page 8 (labelled 10) of this simplified score (see video), incidentally occurring around the same time in the two pieces. Something like this happens a few times, and the quieter passages also have a similar feel.
Am I out to lunch? Verstehe ich das nicht? :)
Comment: Of course Beethoven would have been a huge influence on any pianist-composer  during this time period... https://www.dpmms.cam.ac.uk/~tf/liszt.html
Comment: Let's not forget Beethoven taught Czerny who taught Liszt so there is a clear line of influence.
Comment: Beethoven had a huge direct influence on Liszt and this piece. I'll write an answer soon.
Comment: It wasn't until the 1950's when the integral serialist Pierre Boulez could finally state that Beethoven's influence had expired.
Comment: @CamilleGoudeseune Boulez was wrong. He tried to push his school of contemporary classical music (Darmstadt folks and the French school which followed him) ahead, but one may easily see today, in 2020, how Beethoven's influence stands still in his jubilee and how he still exert pressure on new composers, usually at non concert styles.
Answer: Well I think that it is because they were all composed in the 1800s, so the music had to cater to the styles of people back then, like how many pop songs today resemble each other (14 huge songs that basically sound the same as another), because they are for a specific audience.
Comment: Many of these pop songs sound very similar because they have similar scales, chord progressions, etc. There are tons of pop songs that sound somewhat different from each other, so what in particular do those pop songs share? The same could be said for classical music or any other genre.

Liszt's 1st and Beethoven's 5th


Is an Expected Value Fixed or Random

Question: Suppose I have a random variable, x, and then let E(x) = p denote its expected value. I believe p can be treated as non-stochastic (fixed), but the variable x obviously cannot.
Is that assumption correct?
Answer: Yes, it can. Recall the definition of the expected value (in the continuous case) of a random variable having density $f(x)$,
$$
E(X)=\int xf(x)dx.
$$
So, heuristically, what is random ($X$) has been averaged over in the expected value. Or, while the particular realization of a random variable is uncertain ex ante, the value we expect it to take is not.

Is an Expected Value Fixed or Random