Do left handed violinists play in orchestras?

Question: I don't think I've ever seen any orchestra that uses left handed violinists (or viola/cello/bass players). My guess is that they would clash with the rest of the violinists, and they would seem out of the flow with the rest of the musicians.
But what happens if a left handed violinist wants to play in an orchestra? Are there any regulations against it?
Comment: Maybe they just play the violin like the right-handed players do? I don't know anything about violin, but there definitely are left-handed people who play guitar right-handedly, eventhough left-handed guitars do exist and some people play them as well. (And by the way: when playing guitar, my left (i. e. off) hand definitely does most of the heavy work while the right (dominant) hand "slacks off".)
Comment: yes by tradition, all violinists are required to play right handed for the purpose of not accidentally slamming another guy's arm
Comment: @Ramillies - this strengthens my theory that most of us should have learnt the guitar the other way round!
Comment: Can't remember seeing a left-handed string bassist, but they'd probably only be noticeable doing arco. Do you know of any?
Comment: Most left-handed musicians play "right-handed" anyway. It's such an anomaly to find a left-handed instrument that it wouldn't make sense for orchestras to make accommodations for it.
Comment: In a perfect orchestra one half of the string players would play left handed instruments and the other half  right handed ones, so all f-holes would face stereo-ish towards the audience's left and right ears. But the conservatism of classical musicians will certainly prevent that. In other parts of society things have changed for left handed people (like teaching writing).
Answer:
Do left handed violinists play in orchestras?

Well... I do... (cello).

I don't think I've ever seen any orchestra that uses left handed violinists

It sure isn't a common sight. The vast majority of lefty players plays right-handed regardless. And that's not without reason, because

My guess is that they would clash with the rest of the violinists, and they would seem out of the flow with the rest of the musicians.

Yup, it's definitely a bit awkward. I've gotten quite used to always watching out for my neighbours' bows and doing "evasive maneuvers". Often feels like making life harder than it needs to be.
"Out of flow" may also be an issue, though perhaps less with violin/viola than with cello/bass, because they bow in fact more up/down than left/right, and are in that sense somewhat parity invariant.
Violinist playing lefty will thus indeed have a harder time finding an orchestral job. In somewhat alternative emsembles or amateur orchestras it should usually be accepted though, there aren't "regulations" against it. I doubt there are officially such regulations even in traditional professional orchestras, but it might still be virtually impossible to get a job in one of those when playing lefty.
Where you find such players more commonly is in folk, where synchronised bowing isn't a thing anyway. One great example is Kimberley Fraser, who with her left hand does some of the finest bowing work I've ever heard.

Whether it is playing-wise benefitial for a lefty to play the other way around is a matter of debate. Many people argue that "in standard playing, the left hand actually does the more difficult job, and therefore right-handed playing is in fact better-suited for lefties".
I think that's missing the point though: dexterity isn't about "one hand is better than the other", it's about what tasks each hand specialises in. In most manual working processes, both hands are involved; they need to do division of labour. The "strong hand" may do the actual "actions", but the "weak hand" is just as important for fine-aligning and keeping the working material in place.And that is much the same thing in string instruments: the right hand (for a righty) gives the rhythmic and dynamic impulses, whereas the left hand makes the conditions for this to be musically useful, by fingering the right notes/chords.
Comment: Met someone recently who plays cello right-handed, but guitar left-handed. Work that out !  And, funnily enough, 'dexterity' often means 'right-handed', ironically. I'm right-handed, and those fingers work better on a computer keyboard where accuracy not strength is important. Perhaps this heralds another left/right question...
Answer: We could probably find a picture of a left-handed orchestral violinist.  But, mostly, it just isn't a thing.  Beginner string players aren't offered the option. The left hand does all the clever stuff anyway.  Just like on guitar.  Bit silly to give THEM the option, really.  Pianists have to do REALLY intricate things with both hands, and no-one whines for a left-handed piano.
Comment: Pianists have to do really intricate _and quite similar, or at least analogous_ things with both hands. That's why there's not much reason to think flipping the keyboard makes a difference. (Mind, left-handed pianos [are still a thing](https://www.youtube.com/watch?v=cowjrSTHKTw).) But for plucked or bowed string instruments, both hands do _completely different_ tasks.
Comment: @leftaroundabout - and with violin, the left *fingers* do the intricate bits, while the right *hand/arm* doesn't. Wonder if left-handed equates to left-fingered. Somehow yes. So why isn't the violin set up the other way, to cater for 8o%+ players? 'Cos we've always done it that way...
Comment: On piano, each hand/fingers do the same actions, unlike violin, etc. So there's much less urgency to swap around.
Answer: My personal experience as a lefty playing cello right handed and violin left handed has been that playing violin left handed has worked far better than playing cello right handed. I can not explain why, but since playing left handed on violin (custom built lefty violin), I am virtually unable to play the cello any more in the right handed manner. I will probably have my cello converted to be a lefty instrument.  (Maybe I was influenced by watching Rudolf Kolisch playing in the Pro Arte Quartet at the U of Wisconsin... :)  )
Comment: Interesting! So to clarify – you started with cello right-handed, then also learned violin but lefty?


Show TimePickerDialog from a Fragment

Question: I searched the web and I found a useful code which handles and manages TimePickerDialog like this one
http://androidexample.com/Time_Picker_With_AM_PM_Values_-_Android_Example/index.php?view=article_discription&aid=86&aaid=109
I did tried it and it works but when I integrate it on my class which extends to fragment, TimePickerDialog is not showing on button click
Do you have any idea how can I implement this one?
public class First_Activity extends Fragment implements ActionBar.TabListener {
 static final int TIME_DIALOG_ID = 1111;
    public Button btnClick;
    TextView STtime;
    int hour,minute;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

STtime = (TextView) getActivity().findViewById(R.id.textView2);

        /********* display current time on screen Start ********/

           final Calendar c = Calendar.getInstance();
           // Current Hour
           hour = c.get(Calendar.HOUR_OF_DAY);
           // Current Minute
           minute = c.get(Calendar.MINUTE);

           // set current time into output textview
           updateTime(hour, minute);

        /********* display current time on screen End ********/

btnClick = (Button) getActivity().findViewById(R.id.button4);
        btnClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                getActivity().showDialog(TIME_DIALOG_ID);

            }
        });
}

 protected Dialog onCreateDialog(int id) {
           switch (id) {
           case TIME_DIALOG_ID:

               // set time picker as current time
               return new TimePickerDialog(getActivity(), timePickerListener, hour, minute,
                       false);

           }
           return null;
       }

private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {

           @Override
           public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
               // TODO Auto-generated method stub
               hour   = hourOfDay;
               minute = minutes;

               updateTime(hour,minute);

            }

       };

private static String utilTime(int value) {

           if (value < 10)
               return "0" + String.valueOf(value);
           else
               return String.valueOf(value);
       }

 private void updateTime(int hours, int mins) {

       String timeSet = "";
       if (hours > 12) {
           hours -= 12;
           timeSet = "PM";
       } else if (hours == 0) {
           hours += 12;
           timeSet = "AM";
       } else if (hours == 12)
           timeSet = "PM";
       else
           timeSet = "AM";

       String minutes = "";
       if (mins < 10)
           minutes = "0" + mins;
       else
           minutes = String.valueOf(mins);

       // Append in a StringBuilder
        String aTime = new StringBuilder().append(hours).append(':')
               .append(minutes).append(" ").append(timeSet).toString();

         STtime.setText(aTime);
   }
}

Comment: Please, post your code inside the Fragment that should display the dialog.
Comment: refer this http://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments?rq=1
Comment: @Phil I just added the code
Answer: I would recommend that you create a layout file for your Frament looking like this:
your_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Spawn Dialog" />
</LinearLayout>

And a custom Fragment looking like this:
public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.your_custom_layout, container, false);

        Button b = (Button) v.findViewById(R.id.button);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                createDialog(YOUR_ID).show();
            }
        });

        return v;
    }

    public Dialog createDialog(int id) {
           switch (id) {
           case TIME_DIALOG_ID:

               // set time picker as current time
               return new TimePickerDialog(getActivity(), timePickerListener, hour, minute, false);

           }
           return null;
       }
}

So you have a Fragment whith a layout that contains a button, when clicking the button, the Dialog spawns.

Show TimePickerDialog from a Fragment


Mostrar dados SQLITE entre datas - Android Studio (penso ser between)

Question: Boas, pretendo que o utilizador escolha os dados a mostrar entre as datas que ele escolhe. Já tentei de tudo mas ainda não consegui.
Ou seja o que pretendo é filtrar entre datas, mas o utilizador é que as tem que escolher. Já consegui com um comando SQL, mas ficava manual. Queria que fosse o utilizador a escolher as datas. Obrigado!
Código:
input.java
private EditText DataEdit;
    private EditText editDescricao;
    private Button botaoadicionar;
    private Button botaover;
    static EditText DateEdit;
    private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input);
    createDatabase();

    DataEdit = (EditText) findViewById(R.id.iEditdata);
    editDescricao = (EditText) findViewById(R.id.ieditDescricao);
    botaoadicionar = (Button) findViewById(R.id.botaoadicionar);
    botaover = (Button) findViewById(R.id.botaover);
    botaoadicionar.setOnClickListener(this);
    botaover.setOnClickListener(this);
    DateEdit = (EditText) findViewById(R.id.iEditdata);
    DateEdit.setOnClickListener(new View.OnClickListener() {
        // ver se fiz asneira...
        public void onClick(View v) {

            showTruitonDatePickerDialog(v);
        }
    });
}

protected void createDatabase(){
    db=openOrCreateDatabase("DadosDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS tabeladados(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, data DATE,descricao VARCHAR);");
}
protected void insertIntoDB(){
    String data = DataEdit.getText().toString().trim();
    String descricao = editDescricao.getText().toString().trim();
    if(data.equals("") || descricao.equals("")){
        Toast.makeText(getApplicationContext(),"Preencha todos os campos", Toast.LENGTH_LONG).show();
        return;
    }

    String query = "INSERT INTO tabeladados (data,descricao) VALUES('"+data+"', '"+descricao+"');";
    db.execSQL(query);
    Toast.makeText(getApplicationContext(),"Guardado com sucesso", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
private void mostrardados(){
    Intent intent = new Intent(this,output.class);
    startActivity(intent);
    finish();
}
@Override
public void onClick(View v) {
    if(v == botaoadicionar){
        insertIntoDB();
    }
    if(v==botaover){
        mostrardados();
    }
}
public void showTruitonDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public static class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        DateEdit.setText(year + "-" + (month + 1) + "-" + day);
    }
}

}
output.java
public class output extends ActionBarActivity implements View.OnClickListener {
    private EditText editDescricao;
    private EditText editTextId;
    private EditText editTextName;
    private Button botaoanterior;
    private Button botaoseguinte;
private static final String SELECT_SQL = "SELECT * FROM tabeladados";
private SQLiteDatabase db;
private Cursor c;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.output);
    openDatabase();
    editTextId = (EditText) findViewById(R.id.oeditTextId);
    editDescricao = (EditText) findViewById(R.id.oeditDescricao);
    editTextName = (EditText) findViewById(R.id.oeditTextName);
    botaoanterior = (Button) findViewById(R.id.botaoanterior);
    botaoseguinte = (Button) findViewById(R.id.botaoseguinte);
    botaoseguinte.setOnClickListener(this);
    botaoanterior.setOnClickListener(this);
    c = db.rawQuery(SELECT_SQL, null);
    c.moveToFirst();
    showRecords();

}

protected void openDatabase() {
    db = openOrCreateDatabase("DadosDB", Context.MODE_PRIVATE, null);
}

protected void showRecords() {
    String id = c.getString(0);
    String data = c.getString(1);
    String add = c.getString(2);
    editTextId.setText(id);
    editDescricao.setText(add);
    editTextName.setText(data);

}
protected void moveNext() {
    if (!c.isLast())
        c.moveToNext();
    showRecords();
}
protected void movePrev() {
    if (!c.isFirst())
        c.moveToPrevious();
    showRecords();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
    if (v == botaoseguinte) {
        moveNext();
    }

    if (v == botaoanterior) {
        movePrev();
    }

}

public void voltar(View view) {
    Intent intent = new Intent(output.this, input.class);
    startActivity(intent);
}

}

input.xml

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="VER"
    android:id="@+id/botaover"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Adicionar"
    android:id="@+id/botaoadicionar"
    android:layout_above="@+id/botaover"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/iEditdata"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="114dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_above="@+id/botaoadicionar"
    android:weightSum="1">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ieditDescricao"
        android:hint="Descrição:"
        android:layout_below="@+id/iEditdata"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_weight="1" />
</LinearLayout>

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:layout_below="@+id/iEditdata"
    android:id="@+id/Edithoras"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:hint="Total horas:" />

output xml

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/oeditTextName"
    android:weightSum="1">

    <EditText
        android:layout_width="match_parent"
        android:focusableInTouchMode="false"
        android:layout_height="161dp"
        android:id="@+id/oeditDescricao"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/botaoguardar"
        android:layout_weight="1" />
</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Anterior"
    android:id="@+id/botaoanterior"
    android:layout_weight="0.20"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:text="Voltar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="voltar"
    android:id="@+id/botaovoltar"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Seguinte"
    android:id="@+id/botaoseguinte"
    android:layout_weight="0.31"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignLeft="@+id/botaovoltar"
    android:layout_alignStart="@+id/botaovoltar" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/totalhoras"
    android:layout_above="@+id/botaoanterior"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

Comment: Você está armazenando a data como texto? Usualmente em SQLITE seria melhor usar REAL, junto das funções de julian date (que na verdade tem como base o proleptic gregorian calendar), ou INTEGER com funções de tempo Posix. Fazer com operações de string é sempre mais trabalhoso pro DB, além do desperdício de espaço.
Comment: db.execSQL("CREATE TABLE IF NOT EXISTS tabeladados(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, data DATE,descricao VARCHAR);");  -> Está no tipo data no SQLITE. O DateEdit é um popup que aparece um calendario pra inserir uma data no inputtext
Comment: Não existe DATE em SQLite. Salvo alguma extensão pra android usar isso. SQLite tem TEXT, INTEGER, REAL e BLOB só.
Comment: O que recomenda e como devo fazer?
Comment: Sem saber detalhes da aplicação, não saberia dizer o melhor caminho no seu caso. Só quis avisar para você entender que os tipos do SQLite são um pouco diferentes dos DBs mais comuns, e no caso de dinheiro e datas, é bom você ter algo mais especializado na sua aplicação para lidar com isso. Uma lida no manual do SQLite ajuda a dar uma noção, e na parte das funções de data tem como converter para INT ou FLOAT ao armazenar, e "desconverter" na hora do SELECT para mostrar como data mesmo.
Comment: Conhece algum exemplo do mesmo que eu quero fazer em algum lado? :/
Comment: Por enquanto, veja se consegue resolver com a solução do reginaldo, acho que é melhor depois você estudar e entender, só copiar um exemplo vai te dar mais duvidas do que solução. Depois que dominar melhor as funções de data, aí vc adapta.
Comment: A função que o caro Reginaldo deu funciona, mas pretendo é fazer select a dois inputs de data...
Answer: Assim funciona:
SELECT *
FROM tabela
WHERE datapesquisada BETWEEN '2017-01-01' AND '2017-12-31';

Comment: Boas, onde devo por este código? Quero que o utilizador escolha e não eu :/
Comment: Você pode criar uma caixa de dialogo pra ele informar a data inicial e data final e clicar em um botão. Portanto você colocaria o código no evento onclick do botão.
Comment: Penso ser esta a minha maior dificuldade! Sabe de algum exemplo onde possa aprender? Obrigado, vocês está a ajudar muito!
Comment: Você pode encontrar exemplos para todos os gostos e fins na web. Exemplo:
https://www.google.com.br/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=how%20to%20create%20a%20dialog%20box%20in%20android%20example
Comment: Com o código que tenho em cima, acha que dá? Será que consegue dar um jeitinho? :/
Answer: Como disse o Reginaldo acima, criando um botão pode resolver esse problema.
Crias as caixas de texto para o utilizador introduzir e depois vais buscar esse valor para efetuar a query de pesquisa à base de dados.
Não tenho a certeza da sintaxe mas deverá ser algo do género:
@Override
public void onClick(View v) {
   String dataInicial = (EditText)findViewById(R.id.dataInicial);
   String dataFinal = (EditText)findViewById(R.id.dataFinal); // EditText é só um exemplo

   String query = "SELECT * FROM tabela
   WHERE data BETWEEN " + dataInicial + " AND " + dataFinal;
   // aqui será o código para executar a query à BD.
   Cursor c = db.rawQuery(query, null);
   // depois terás de efetuar o tratamento dos dados
}

Comment: Devo colocar na parte do input certo?


d3.js: Cannot read property 'call' of undefined

Question: I created a d3 graph by reading a json object with the method d3.json (). But it does not load, this is because the browser console shows me the following error:

For this case I am using d3 v3, according to an example I copy from the web.
I would be very grateful if someone could explain me why this error occurs.
Without further ado, I say goodbye gratefully.
Below I leave the complete code of this example.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>D3 Test</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="./css/style.css">

<legend align="center">Convergencia de ODS con Plan Nacional de Desarrollo</legend>

Comment: You should use a non minimised version of the d3 library to understand what is going on, and then use your browser to trace what is happening
Comment: `d3.json()` is meant for loading external json files.  You can just call the json object within the script like any other variable.
Answer: d3.json is a function for getting data by calling external json file. d3.json function is trying to call an external json file and it expect a file path in first parameter. You pass a json data in first parameter and it's invalid for this function. That's why the error occored.
In your case, you don't need to call d3.json. You can remove d3.json this function and rename the json variable to data then it will work well.
If you have any json file instead of data, then you can use the function and you need to pass the file path in first parameter of this function.
Please check the below snippet.

var w = 1200;
var h = 550;
var radius = Math.min(w, h);

var dataset = [
    [ 600, 150]
];

var data = [
    {
        "pais": "Ecuador",
        "pais_nid": 14,
        "ods": "1. Fin a la pobreza",
        "ods_nid": 35,
        "ods_color_hex": "E5243B",
        "objetivos_plan_ods": 5
    },
    {
        "pais": "Ecuador",
        "pais_nid": 14,
        "ods": "2. Hambre cero",
        "ods_nid": 36,
        "ods_color_hex": "DDA63A",
        "objetivos_plan_ods": 9
    }
];

//d3.json(json, function(data) {

  var rScale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.objetivos_plan_ods; })])
      .range([2, 40]);

  //Crear un elemento SVG
  var svg = d3.select("div.jumbotron")
      .append("svg")
      .attr("width", w)
      .attr("height", h)
      .attr("viewBox", "" + -(w/2) + " " + -(h/2) + " " + w + " " + h + "");

  svg.selectAll("circle")
      .data(dataset)
      .enter()
      .append("circle")
      .attr("r", 125)
      .attr("stroke", "rgb(255, 255, 255)")
      .attr("stroke-width", "8")
      .attr("fill", "none");

  svg.on("click", function() {
      document.getElementById("msg").setAttribute("style", "display:none;");
      document.getElementById("msg").innerHTML = '';
      d3.event.stopPropagation();
  });

  var node = d3.select("svg")
      .append("g")
      .selectAll("circle")
      .data(data)
      .enter()
      .append("circle")
      .attr("style", "cursor:pointer;")
      .attr("r", function(d) { return rScale(d.objetivos_plan_ods);})
      .attr("fill", function(d) {
          return "rgba(" + Math.floor((Math.random() * 255) + 0) + "," + Math.floor((Math.random() * 255) + 0) + "," + Math.floor((Math.random() * 255) + 0) + ", 0.50)";
      })
      .attr("id", function(d) { return "circle-" + d.ods_nid; })
      .on("click",function(d) {
          document.getElementById("msg").removeAttribute("style");
          document.getElementById("circle-" + d.ods_nid).setAttribute("stroke", "rgb(140, 233, 255)");
          document.getElementById("circle-" + d.ods_nid).setAttribute("stroke-width", "6");
          document.getElementById("msg").innerHTML = d.ods;
          d3.event.stopPropagation();
      })
      .on("mouseout", function(d) {
          document.getElementById("msg").setAttribute("style", "display:none;");
          document.getElementById("circle-" + d.ods_nid).removeAttribute("stroke");
          document.getElementById("circle-" + d.ods_nid).removeAttribute("stroke-width");
          document.getElementById("msg").innerHTML = '';
          d3.event.stopPropagation();
      });

  d3.forceSimulation(data)
      .force("charge", d3.forceCollide().radius(function(d) { return rScale(d.objetivos_plan_ods); }))

      .force("r", d3.forceRadial(function(d) { return 125; }))
      .on("tick", ticked);

  function ticked() {
      node
          .attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
  }

  var color = d3.scale.category20();

  var pie = d3.layout.pie()
      .value(function(d) { return 5; });

  var arc = d3.svg.arc()
      .innerRadius(radius - 508)
      .outerRadius(radius - 480);

  d3.select("svg")
      .datum(data).selectAll("path")
      .data(pie)
      .enter()
      .append("path")
      .attr("stroke", "rgb(233, 236, 239)")
      .attr("stroke-width", "3")
      .attr("fill", function(d) { return "#" + d.ods_color_hex; })
      .attr("d", arc);
//})
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>D3 Test</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="./css/style.css">

<legend align="center">Convergencia de ODS con Plan Nacional de Desarrollo</legend>


Functional where only way to prove property is to make it "appear" after the property is proven

Question: I have $f : \ell^{\infty}_{\mathbb{R}} \to \mathbb{R}$ with a bunch of properties and want to extend to $g : \ell^{\infty}_{\mathbb{C}} \to \mathbb{C}$ while preserving the properties. If we define $g(x+iy) = f(x)+if(y),$ then all the properties get satisfied except $||g|| = 1,$ which appears impossible to prove. Try and try as I might, it can't be proven. Using $||f|| = 1$ and any other properties, the inequalities just don't line up to force $||g|| = 1.$
Cnsider $f$ as a function $ \ell^{\infty}_{\mathbb{R}} \to \mathbb{C},$ then there is an extension $g$ with $||g|| = ||f|| = 1$ and $g|_{\ell^{\infty}_{\mathbb{R}}} = f$ by the Hahn-Banach theorem. However, this means $g(x+iy) = g(x)+ig(y) = f(x)+if(y),$ the exact extension we had in mind earlier.
Suddenly, we get a proof of $||g|| = 1$ for the explicit extension despite the fact that defining the extension immediately and then trying to prove this was impossible. Is this a common scenario, or have I made a mistake?
Comment: You probably have to give more information. Currently it seems like you say "It was very hard to solve a (mysterious) question without using Hahn Banach, is it common?" I do know of some instances where Hahn Banach have lead to simple proofs of very difficult results, but I am not sure if that is helpful.
Answer: I don't think this is a valid proof. Namely, for $\ell^\infty_{\Bbb{R}}$ to be a subspace of $\ell^\infty_{\Bbb{C}}$, you have to consider both of them as real vector spaces. Then you have a real-linear map $f : \ell^\infty_{\Bbb{R}} \to \Bbb{R}$ with $\|f\|=1$ which by Hahn-Banach extends to a real-linear map $g : \ell^\infty_{\Bbb{C}} \to \Bbb{R}$ with $\|g\|=1$. Nowhere is it said that this $g$ will be complex-linear (in fact it certainly won't be since the codomain is again $\Bbb{R}$) so you cannot use $g(x+iy) = g(x)+ig(y)$.
Here is an elementary proof that $g : \ell^{\infty}_{\mathbb{C}} \to \mathbb{C}$ defined by $g(x+iy) = f(x)+if(y)$ has $\|g\|=1$. First notice that for any $z \in \ell^\infty_{\Bbb{C}}$ we have
$$\operatorname{Re}g(z) = g(\operatorname{Re}z) = f(\operatorname{Re}z).$$
Let $z \in \ell^\infty_{\Bbb{C}}$ be arbitrary and let $$g(z) = |g(z)|e^{i\phi}$$
be the polar form of the complex number $g(z)$. Since $g$ is complex-linear, we have
$$|g(z)| = e^{-i\phi}g(z) = g(e^{-i\phi}z) = \operatorname{Re} g(e^{-i\phi}z) = f(\operatorname{Re}(e^{-i\phi}z)) \le \|\operatorname{Re}(e^{-i\phi}z)\|_\infty \le \|z\|_\infty$$
and hence $\|g\|\le 1$. Since $g$ extends $f$ we get $\|g\| \ge \|f\| = 1$ as well.


Basic Geometry: Finding the smallest angle

Question: There was someone on Facebook asking this question, I wanted to help, but I'm stuck right know. By the way, here's the question:

$ABC$ is a triangle in which
$$2\sin(A) = 3\sin(B) = 4\sin(C)$$
Find the measure of the smallest angle

My attempt:
Suppose I set the triangle like this screenshot below (sorry, it's a bit messy):

Using the sine rule, and dividing three sides with $12$, we have:
$$\frac{\sin(A)}{6} = \frac{\sin(B)}{4} = \frac{\sin(C)}{3}$$
From that, I assume:
$$x=6; \quad y=3; \quad z=4$$
Then, using cosine rule, I have:
$$\cos(A) = \frac{4^2 + 3^3 - 6^2}{2\cdot 4 \cdot 3} = \frac{-11}{24}$$
This is where I'm stuck. Why negative? Did I do something wrong with the assumption or the calculations?
Comment: Not -11/4, -11/24. And minus value of cosine means the angle is bigger than 90deg.
Comment: $C$ is the smallest angle. Now apply cosine rule.
Comment: @Nightflight Thank you. I did input -11/4 on my calculator, got the answer in complex number and turned out it was a typo.
Comment: The smallest side of the triangle will be opposite the smallest of the angles. So the smallest angle will be opposite the side of length $3$, i.e., angle $C$ as ACB has indicated.
Answer: $ABC$ is a triangle in which $\bbox[lightgreen]{2\sin(A)=3\sin(B)=4\sin(C)}$.
We will use the fact that $\bbox[lightblue]{\angle{A}+\angle{B}+\angle{C}=180^{0}}$.
Therefore
$$
\left\{
\begin{array}{l}
2\sin(B+C)=3\sin(B),\\
3\sin(B)=4\sin(C).\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
2\sin(B)\cos(C)+2\sin(C)\cos(B)=3\sin(B),\\
3\sin(B)=4\sin(C).\\
\end{array}
\right.
\iff
\\
\iff
\left\{
\begin{array}{l}
2\cos(C)+2\sin(C)\cot(B)=3,\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
2\cos(C)+2\sin(C)\cot(B)=3,\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\\
\iff
\left\{
\begin{array}{l}
2\left(1-\frac{9\sin^{2}(B)}{16}\right)^{0.5}+\frac{6\cos(B)}{4}=3,\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
2\left(\frac{7+9\cos^{2}(B)}{16}\right)^{0.5}+\frac{6\cos(B)}{4}=3,\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\\
\iff
\left\{
\begin{array}{l}
{(7+9\cos^{2}(B))^{0.5}}+{3\cos(B)}=6,\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
({(7+9\cos^{2}(B))^{0.5}})^{2}=(6-{3\cos(B)})^{2},\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\\
\iff
\left\{
\begin{array}{l}
{(7+9\cos^{2}(B))}=(36+{9\cos^{2}(B)}-36\cos(B)),\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
\cos(B)=\frac{29}{36},\\
\sin(C)=\frac{3\sin(B)}{4}.\\
\end{array}
\right.
\iff
\\
\iff
\left\{
\begin{array}{l}
\cos(B)=\frac{29}{36},\\
\sin(C)=\frac{3(1-\cos^{2}(B))^{0.5}}{4}.\\
\end{array}
\right.
\iff
\left\{
\begin{array}{l}
B=\arccos\left(\frac{29}{36}\right)=36^{0},\\
C=\arcsin\left(\frac{\sqrt{455}}{48}\right)=26^{0}.\\
\end{array}
\right.
\implies
\left\{
\begin{array}{l}
\angle{B}=36^{0},\\
\angle{C}=26^{0},\\
\angle{A}=118^{0}.
\end{array}
\right.
$$
Therefore, $\bbox[lightgreen]{\angle{C}\text{ is the smallest angle}}$.
Good luck!


Erro no upload de imagem PHP

Question: Blz Galera
Estou fazendo um teste de upload de imagem e está aparecendo o erro:
Notice: Undefined index: foto in C:\xampp\htdocs\cadastro.php on line 2
Notice: Undefined index: foto in C:\xampp\htdocs\cadastro.php on line 3
O que está errado? Desde já obrigado
Obs. O script no index.php é porque tenho mais de um botão no form.
index.php
<form id="cadastro" name="cadastro" method="post">
<input type="file" name="foto" />
<input type="button" value="Cadastrar" onClick="ExecutaAcao('cadastro');">
</form>

cadastro.php
<?php
$imagem = $_FILES['foto']['name'];
$tmp_name = $_FILES['foto']['tmp_name'];
$location = "imagens/$imagem";
move_uploaded_file($tmp_name,$location);
?>

Comment: Coloque um id no seu input, talvez seja isso ->
Answer: Adicione o enctype no seu form:
<form id="cadastro" name="cadastro" method="post" enctype="multipart/form-data">

Leia mais aqui e aqui.
Comment: Deu certo. Muito obrigado Junior

Erro no upload de imagem PHP


The effects of heavy thread consumption on ARM (4-core A72) vs x86 (2-core i5)

Question: I have a realtime linux desktop application (written in C) that we are porting to ARM (4-core Cortex v8-A72 CPUs). Architecturally, it has a combination of high-priority explicit pthreads (6 of them), and a couple GCD(libdispatch) worker queues (one concurrent and another serial).
My concerns come in two areas:

I have heard that ARM does not hyperthread the way that x86 can and therefore my 4-cores will already be context switching to keep up with my 6 pthreads (and background processes). What kind of performance penalty should I expect from this?

I have heard that I should expect these ARM context-switches to be less efficient than x86. Is that true?
A couple of the pthreads are high-priority handlers for fairly rare-ish events, does this change the prospects much?(i.e. they are sitting on a select statement)

My bigger concern comes from the impact of GCD in this application. My understanding of the inner workings of GCD is a that it is a dynamically scaled threadpool that interacts with the scheduler, and will try to add more threads to suit the load. It sounds to me like this will have an almost exclusively negative impact on performance in my scenario. (I.E. in a system whose cores are fully consumed) Correct?
Answer: I'm not an expert on anything x86-architecture related (so hopefully someone more experienced can chime in) but here are a few high level responses to your questions.

I have heard that ARM does not hyperthread the way that x86 can [...]

Correct, hyperthreading is a proprietary Intel chip design feature. There is no analogous ARM silicon technology that I am aware of.

[...] and therefore my 4-cores will already be context switching to keep up with my 6 pthreads (and background processes). What kind of performance penalty should I expect from this? [...]

This is not necessarily the case, although it could very well happen in many scenarios. It really depends more on what the nature of your per-thread computations are...are you just doing lots of hefty computations, or are you doing a lot of blocking/waiting on IO? Either way, this degradation will happen on both architectures and it is more of a general thread scheduling problem. In hyperthreaded Intel world, each "physical core" is seen by the OS as two "logical cores" which share the same resources but have their own pipeline and register sets. The wikipedia article states:

Each logical processor can be individually halted, interrupted or directed to execute a specified thread, independently from the other logical processor sharing the same physical core.[7]
Unlike a traditional dual-processor configuration that uses two separate physical processors, the logical processors in a hyper-threaded core share the execution resources. These resources include the execution engine, caches, and system bus interface; the sharing of resources allows two logical processors to work with each other more efficiently, and allows a logical processor to borrow resources from a stalled logical core (assuming both logical cores are associated with the same physical core). A processor stalls when it is waiting for data it has sent for so it can finish processing the present thread. The degree of benefit seen when using a hyper-threaded or multi core processor depends on the needs of the software, and how well it and the operating system are written to manage the processor efficiently.[7]

So if a few of your threads are constantly blocking on I/O then this might be where you would see more improvement in a 6-thread application on a 4 physical core system (for both ARM and intel x86) since theoretically this is where hyperthreading would shine....a thread blocking on IO or on the result of another thread can "sleep" while still allowing the other thread running on the same core to do work without the full overhead of an thread switch (experts please chime in and tell me if I'm wrong here).
But 4-core ARM vs 2-core x86... assuming all else equal (which obviously is not the case, in reality clock speeds, cache hierarchy etc. all have a huge impact) then I think that really depends on the nature of the threads. I would imagine this drop in performance could occur if you are just doing a ton of purely cpu-bound computations (i.e. the threads never need to wait on anything external to the CPU). But If you are doing a lot of blocking I/O in each thread, you might show significant speedups doing up to probably 3 or 4 threads per logical core.
Another thing to keep in mind is the cache. When doing lots of cpu-bound computations, a thread switch has the possibility to blow up the cache, resulting in much slower memory access initially. This will happen across both architectures. This isn't the case with I/O memory, though. But if you are not doing a lot of blocking things however, then the extra overhead with threading will just make it slower for the reasons above.

I have heard that I should expect these ARM context-switches to be less efficient than x86. Is that true?

A hardware context switch is a hardware context switch, you push all the registers to the stack and flip some bits to change execution state. So no, I don't believe either is "faster" in that regard. However, for a single physical core, techniques like hyperthreading makes a "context switch" in the Operating Systems sense (I think you mean switching between threads) much faster, since the instructions of both programs were already being executed in parallel on the same core.
I don't know anything about GCD so can't comment on that.
At the end of the day, I would say your best shot is to benchmark the application on both architectures. See where your bottlenecks are. Is it in memory access? Keeping the cache hot therefore is a priority. I imagine that 1-thread per core would always be optimal for any scenario, if you can swing it.
Some good things to read on this matter:

https://blog.tsunanet.net/2010/11/how-long-does-it-take-to-make-context.html
https://lwn.net/Articles/250967/
Optimal number of threads per core
Thread context switch Vs. process context switch
Comment: "A hardware context switch is a hardware context switch, you push all the registers to the stack and flip some bits to change execution state." It's worth pointing out -- [As with other tasks performed in hardware, one would expect this to be rather fast; however, mainstream operating systems, including Windows and Linux, do not use this feature.](https://en.wikipedia.org/wiki/Context_switch#Hardware_vs._software)


Jersey test gives NullPointerException when using UriInfo

Question: I am creating a application that should be able to create an account using a REST api. When I wrote the AccountController.java class everything worked fine. I used postman to verify that I got the right response.
So my AccountController.java works correctly but the unit test I wrote with it don't work. When the unit test is executed it returns a NullPointerException which results in a InternalServerError within the REST API. While debugging i found out that if I remove the use of UriInfo in AccountController.java and return Response.ok() instead of created the test is successfull.
So my question is. How do i properly test/mock a method that returns and URI?
Bellow are all relevant classes and dependencies. The Account.java class is in another package. But both the main application as the project that contains Account.java are part of the same parent pom. I am not sure if this is relevant to my question.
AccountController.java
@Stateless
@Path("/accounts")
public class AccountController {

    @Inject
    private AccountService accountService;

    @Context
    private UriInfo uriInfo;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response create(Account account) {
        final Account newAccount = accountService.create(account);
        System.out.println("Pre uriinfo message");
        //Removing this line and returning Response.ok() removes the exception
        final URI uri = uriInfo.getAbsolutePathBuilder().path(newAccount.getId() + "").build();
        System.out.println("Post uriinfo message");
        return Response.created(uri).entity(newAccount).build();
    }
}

AccountControllerTest.java
@RunWith(MockitoJUnitRunner.class)
public class AccountControllerTest extends JerseyTest {

    @Mock
    private AccountService service;

    @Override
    protected Application configure() {
        final ResourceConfig config = new ResourceConfig(AccountController.class);
        config.register(new AbstractBinder() {
            @Override
            protected void configure() {
                bind(service).to(AccountService.class);
            }
        });
        return config;
    }

    @Test
    public void createUserTest() throws Exception {
        final Account testAccount = new Account("testName", "firstname.lastname@example.com");
        when(service.create(testAccount))
                .thenReturn(testAccount);

        System.out.println("Create account test");
        //Create a new Account
        final Response correctResult = target("/accounts")
                .request(MediaType.APPLICATION_JSON)
                .post(Entity.json(testAccount));
        Assert.assertEquals(HTTP_CREATED, correctResult.getStatus());
        Assert.assertEquals(testAccount, correctResult.readEntity(Account.class));
    }
}

Account.java
@Entity
@XmlRootElement
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(nullable = false)
    private String fullName;
    @Column(unique = true, nullable = false)
    private String mail;
    private boolean active;

    public Account() { }

    public Account(String fullName, String mail) {
        this.fullName = fullName;
        this.mail = mail;
    }

    //Contains getters&setters
}

Test dependencies

<properties>
    <jersey.version>2.26-b03</jersey.version>
</properties>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.9.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-jetty</artifactId>
    <version>${jersey.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.4.Final</version>
    <scope>test</scope>
</dependency>

Answer: So I finally figured it out.
Somewhere on this line in AccountController.java a NullPointerException was thrown:
final URI uri = uriInfo.getAbsolutePathBuilder().path(newAccount.getId() + "").build();
This only happened when using my JerseyUnitTest so i guess Jersey must change some behavior of UriInfo.
Eventually I solved the problem by overriding equals in Account.java.


XmlTextReader.GetAttribute retorna o valor nulo

Question: Fiz um código base em XML e eu gostaria de importar os atributos e valores de acordo com o código:
<?xml version="1.0" encoding="UTF-8" ?>

<params count="3">
    <param name="commandLine" value="java.exe -jar @commandForge@ nogui" SerializeAs="[mscorlib]::System.Process" />
    <param name="commandForge" value="forge-1.7.10-10.13.4.1448-1.7.10-universal.jar" SerializeAs="[mscorlib]::System.String" />
    <param name="previewOutput" value="True" SerializeAs="Boolean" />
</params>

E executei o seguinte código para pegar o atributo count do primeiro elemento:
internal void LoadXML()
        {
            try
            {
                if (s != null)
                {
                    KeysAndValues = new Dictionary<object, object>();
                    XmlTextReader xmlreader = new XmlTextReader(s);

                    xmlreader.ReadStartElement("params");
                    int count = int.Parse(xmlreader.GetAttribute("count"));
         // acontece o erro aqui na linha acima!

                    for (int i = 0; i < count; i++)
                    {
                        var name= "";
                        var value = "";

                        xmlreader.ReadStartElement("param");
                        name = xmlreader.GetAttribute(0);
                        value = xmlreader.GetAttribute(1);
                        xmlreader.ReadEndElement();

                        KeysAndValues.Add(name, value);

                    }

                    xmlreader.ReadEndElement();
                }
            }
            catch (Exception e)
            {
                ExceptionForm exceptionA = new ExceptionForm(e);
                exceptionA.ShowDialog();
            }
        }

Logo depois disso eu compilo e executo a aplicação e aparece o seguinte:
System.ArgumentNullException: Valor não pode ser nulo.
Nome do parâmetro: String
   em System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   em System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   em Start.XMLScriptParser.LoadXML() na C:\Users\Nathan\Documents\Visual Studio 2008\Projects\Start\Start\XMLScriptParser.cs:linha 37
Sendo que eu já forneci todos os dados que ele pediu!
Código completo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace Start
{
    public class XMLScriptParser
    {
        Dictionary<object, object> KeysAndValues;
        Stream s;

        public XMLScriptParser(Stream s)
        {
            this.s = s;
        }

        public object GetValueFrom(object Key)
        {
            return KeysAndValues[Key];
        }

        public void TryParse() { LoadXML(); }

        internal void LoadXML()
        {
            try
            {
                if (s != null)
                {
                    KeysAndValues = new Dictionary<object, object>();
                    XmlTextReader xmlreader = new XmlTextReader(s);

                    xmlreader.ReadStartElement("params");
                    int count = int.Parse(xmlreader.GetAttribute("count"));

                    for (int i = 0; i < count; i++)
                    {
                        var name= "";
                        var value = "";

                        xmlreader.ReadStartElement("param");
                        name = xmlreader.GetAttribute(0);
                        value = xmlreader.GetAttribute(1);
                        xmlreader.ReadEndElement();

                        KeysAndValues.Add(name, value);

                    }

                    xmlreader.ReadEndElement();
                }
            }
            catch (Exception e)
            {
                ExceptionForm exceptionA = new ExceptionForm(e);
                exceptionA.ShowDialog();
            }
        }
    }
}

O Mesmo quero fazer com este documento XML:
<?xml version="1.0" encoding="UTF-8" ?>
<params count="12">
    <param name="Locale" value="PT-BR" SerializeAs="[mscorlib]::String" />
    <param name="DisplayName" value="Nathan Ferreira" SerializeAs="[mscorlib]::String" />
    <param name="MainText" value="Start :: [Empty.xml]" SerializeAs="[mscorlib]::String" />
    <param name="ExceptionText" value="Ops! Tem algo errado" SerializeAs="[mscorlib]::String" />

    <param name="MainForm.Label1" value="Arquivo de script:" SerializeAs="[mscorlib]::String" />
    <param name="MainForm.Label2" value="Enviar Comando" SerializeAs="[mscorlib]::String" />
    <param name="MainForm.Label3" value="Uso de Mem. RAM" SerializeAs="[mscorlib]::String" />

    <param name="MainForm.Button1" value="Carregar e Iniciar" SerializeAs="[mscorlib]::String" />
    <param name="MainForm.Button2" value=">>" SerializeAs="[mscorlib]::String" />

    <param name="MainForm.Page1" value="Linha de comando" SerializeAs="[mscorlib]::String" />
    <param name="MainForm.Page2" value="Configuração do Script" SerializeAs="[mscorlib]::String" />

    <param name="MainForm.ProgressBarValue" value="0" SerializeAs="[mscorlib]::Int32" />

</params>

Comment: `xmlreader.GetAttribute("count")` está retornando `null`. Eu costumo abrir XML usando Linq, então não sei o que pode estar errado, mas vou testar aqui e tentar ver qual é o problema.
Comment: Como seria usando Linq? Eu quero fazer como se fosse uma lista com `param name` e `param value` tudo em um `SortedDictionary ` ou um `Dictionary` normal.
Comment: Vou pegar um exemplo.
Comment: ok aguardo!              .  .
Comment: Você conseguiu resolver?
Comment: Ainda não tive tempo de editar o código mas fique tranquilo amanha irei fazer isto.
Answer: O problema é que o retorno de xmlreader.GetAttribute("count") está sendo null e, como o próprio erro diz, o valor passado para int.Parse() não pode ser nulo.
O erro eu realmente não sei onde está, talvez você precise pegar o atributo de uma maneira diferente, não sei.
Eu fiz um código de exemplo (usando Linq) com base no objetivo geral da rotina (que você explicou nos comentários)

Eu quero fazer como se fosse uma lista com param name e param value tudo em um SortedDictionary ou um Dictionary normal.

O código abaixo retorna um Dictionary com a Key sendo o valor do atributo name e o value sendo o valor do atributo value.
var doc = XDocument.Load("arq.xml");
var count = doc.Descendants("params").FirstOrDefault()?.Attribute("count").Value;

var query = doc.Descendants("param")
                    .Select(x => new
                    {
                        Name = x.Attribute("name").Value,
                        Value = x.Attribute("value").Value
                    }).ToDictionary(o => o.Name, o => o.Value);

Perceba que eu não validei se os nós ou atributos realmente existem.


Users Export module hook

Question: I'm using Users Export that provides a hook with no extra information.
I need somehow to explore the $info parameters in order to this extra fields
my code:
function display_my_users_loft_data_grids_info_alter(&$info) {
    var_dump($info);
}

But in that case the var_dump doesn't work.
Does someone know any example or documentation or help me to debug that?
Answer: Get the Devel module installed and use the dpm() function, e.g.
function display_my_users_loft_data_grids_info_alter(&$info) {
    dpm($info);
}

Then perform whatever action it would take to invoke that hook, and you'll see the $info variable exported to the messages area for easy browsing.
Comment: It doen't work, is there any way to check if something is invoked?
Comment: Well yeah, but the above method is it! Have a look through the code on the module for `module_invoke`, you should be able to see how the info array is built up there

Users Export module hook


Checking of Measurement in Grouped Data

Question: My teacher uses the formula below when looking for the median and mode of a grouped data.
$$
median = L_m + c\frac{\frac{n}{2} - F_{m-1}}{f_m} \\
mode = L_m +c\frac{f_m - f_{m-1}}{2f_m-f_{m-1}-f_{m+1}}
$$
I am so sorry about the format, I am using the mobile app and have limited access on tools upon writing this.
Where the value of $n/2$ that matches or in range in cumulative frequency of the group data will be the median class.
Where the $f_m$ or highest frequency will be the mode class.
$L_m$ is the lowest class boundary, $c$ is the class width, $F_{m-1}$ is the cumulative frequency that comes before the cumulative frequency of the median class, $f_{m-1}$ is the frequency comes before the highest frequency, $f_{m+1}$ comes after the highest frequency.
I am only showing this as a reference as I found different ways of solving the basic measures of a grouped data.
My question is, is there any possible way of telling whether you got the right answer? A checking or signs that you got it right? The same way how you check the sum by subtracting the sum and the value of one of the summand to get the value of other summand. Thank you so much.
Comment: Hope this would help you. https://www.mathsisfun.com/data/frequency-grouped-mean-median-mode.html
Answer: Note that the meaning of $m$ is different in each formula.

In the formula for the median, $m$ represents the first interval where the relative cumulative frequency reaches a value greater or equal to $50\%$, or, equivalently, the interval where the absolute cumulative frequency $F$ in your notation reaches a value greater or equal to $n/2$. Therefore, $F_{m-1} < \frac{n}{2} \leq F_{m}$, where $m-1$ represents the interval before (to the left of) that one. The absolute (non-cumulative) frequency of that interval is $f_m$.
In the formula for the mode, and considering equal width intervals, $m$ represents the interval with the highest absolute (non-cumulative) frequency $f_m$. The interval to the left of that one is represented by $m-1$ and the interval to the right is represented by $m+1$.
Note, however, that if the intervals have different width, we should use the density $d_j = f_j / c_j$, that is computed as the number of observations in interval $j$ divided by the width of interval $j$ and $m$ will represent the interval with the highest density.

Regarding the verification of your computations, a few checkpoints might be useful:

Of course that the result of the median and the mode must be between the lower bound of the first interval and the higher bound of the last interval.
Both the median and the mode must lie inside the respective closed chosen interval $m$, i.e., they must be in $[L_m; L_m + c]$. This means that when computing each fraction (that latter will be multiplied by $c$) we will get a value in $[0; 1]$.
Neither the median nor the mode will belong to an interval with zero frequency $f_m$.
If you plot a cumulative frequency polygon see the figure on the right, you can get an approximate value of the median by drawing an horizontal line at height $n/2$ until it intercepts with the polygon. The abscissa $x$ of the interception point is the value of the median.
If you plot an histogram and draw a segment line between the top right corner of the highest bar and the top right corner of the bar on its left, and another segment line between the top left corner of the highest bar and the top left corner of the bar on its right, the abscissa $x$ of interception point is the value of the mode. See an example.
Answer: My interpretation is that by 'right answer' you don't mean whether you
computed the formula correctly, but whether correct answers from the formulas match
the median and mode of the sample or of the distribution from which the sample was drawn.
Sample. The median of a sample is the middle value of the sorted data
for samples of odd size and the average of the middle two values for
samples of even size. If you have the actual sample values (before binning)
that is easy enough to find. For a sample with tied observations the
mode is defined as the most frequently occurring value (if there is one). But for samples from a continuous distribution (where any ties occur only by rounding), I know of no 'official' definition of the
mode of a sample, but more on that later.
Here are two histograms of the same dataset of size $n=100$ with somewhat different choices of intervals. Accordingly, your formulas will give somewhat different answers. [From your formula, I got about 16 and about 15, respectively. You can use the counts atop histogram bars to check my answers.]
The true median of the 100 observations is 16.52 (rounded to 2 places).
The modal interval is $(10,20]$ in the top histogram and $(10,15]$ in the bottom histogram, so your formulas will be looking for the 'mode' of the
sample in two different intervals. [From your formula, I got roughly 15 for
the mode from both histograms.]

A histogram is one way to get a rough idea of the shape of a population density function, and your formula tries to give a value for the mode that matches
that density function. Usually, a somewhat more accurate method is to use a kernel density estimator (KDE). The figure below shows a the second histogram
of the data along with the KDE from R statistical software. By looking at the
KDE a little more closely, we can find that its maximum value is at about 15.3.
<code>hist(x, prob=T, col="skyblue2")
lines(density(x, adj=1.5), col="red", lwd=2)
</code>

Population. If you know the CDF $F$ of the population, then the median
is the $x$-value where $F(x)=1/2.$ If you know the density function $f$ of
the population, then the mode is the $x$-value that maximizes $f(x),$ if
there is a unique maximum.
For example the distribution $\mathsf{Beta}(\text{shape}=\alpha=6, \text{rate}=\beta=1/3)$
has mode $(\alpha - 1)/\beta = 15$ and, by numerical integration,
the median is very nearly $17.01.$ [For more on beta distributions,
see Wikipedia.]
Of course, if the goal is to use a sample to estimate the median and mode of a population, a larger sample will tend to give better results than a smaller one. The figure below shows a histogram of a sample of size $n=2000$ from $\mathsf{Beta}(6,\,1/3),$ along with the population density function (black), and
the KDE of the sample (red).

Checking of Measurement in Grouped Data


Building a linear model for a ratio vs. percentage?

Question: Suppose I want to build a model to predict some kind of ratio or percentage. For example, let's say I want to predict the number of boys vs. girls who will attend a party, and features of the party I can use in the model are things like amount of advertising for the party, size of the venue, whether there will be any alcohol at the party, etc. (This is just a made-up example; the features aren't really important.)
My question is: what's the difference between predicting a ratio vs. a percentage, and how does my model change depending on which I choose? Is one better than the other? Is some other function better than either one? (I don't really care about the specific numbers of ratio vs. percentage; I just want to be able to identify which parties are more likely to be "boy parties" vs. "girl parties".) For example, I'm thinking:

If I want to predict a percentage (say, # boys / (# boys + # girls), then since my dependent feature is bounded between 0 and 1, I should probably use something like a logistic regression instead of a linear regression.
If I want to predict a ratio (say, # boys / # girls, or # boys / (1 + # girls) to avoid dividing-by-zero errors), then my dependent feature is positive, so should I maybe apply some kind of (log?) transformation before using a linear regression? (Or some other model? What kind of regression models are used for positive, non-count data?)
Is it better generally to predict (say) the percentage instead of the ratio, and if so, why?
Comment: Depending on your particular application and what you are trying to model, you should consider using Compositional Data Analysis (http://en.wikipedia.org/wiki/Compositional_data); there are some subtle things to consider when the features (independent variables) sum to unity. Please see the work of  John Aitchison.
Answer: Echoing the first answer.  Don't bother to convert - just model the counts and covariates directly.
If you do that and fit a Binomial (or equivalently logistic) regression model to the boy girl counts you will, if you choose the usual link function for such models, implicitly already be fitting a (covariate smoothed logged) ratio of boys to girls.  That's the linear predictor.
The primary reason to model counts directly rather than proportions or ratios is that you don't lose information.  Intuitively you'd be a lot more confident about inferences from an observed ratio of 1 (boys to girls) if it came from seeing 100 boys and 100 girls than from seeing 2 and 2.  Consequently, if you have covariates you'll have more information about their effects and potentially a better predictive model.
Answer: I've never seen a regression model for ratios before, but regression for a percentage (or more commonly, a fraction) is quite common.  The reason may be that it's easy to write down a likelihood (probability of the data given your parameter) in terms of a fraction or probability: each element has a probability $p$ of being in category $A$ (vs. $B$).  The estimate of $p$ is then the estimated fraction.
Note however: it's not standard to make a linear model for a fraction; more common is a generalized linear model, which is a linear model along with an invertible, nonlinear 'link' function that controls the range of the desired model (here $[0,1]$).
The most common model for fractions is (as you noted) logistic regression, which allows you to use regressors on the real line but have a fraction constrained to live on [0,1].  However, logistic regression is technically a model for binary data, meaning you observe a series of events where each input (set of independent variables) produces an independent observation of $0$ or $1$.  For the case where you just have a population divided into two different classes (i.e., and you don't have separate regressors for each member of the population), you might want binomial regression.
That being said, there's probably nothing to stop you from writing down a generalized linear model (GLM) for ratios. (Logistic and binomial regression are also GLMs). You'd need to pick a function mapping from the input space to the space of possible ratios (e.g., $\log$), then write down your likelihood in terms of the resulting ratio.
Comment: For ratios, search this site for poisson rate regression


Minimal Polynomial of $1+2^{\frac{1}{n}} +\cdots+2^{\frac{n-1}{n}}$

Question: I want to find the minimal polynomial of $1+2^{\frac{1}{n}} +\cdots+2^{\frac{n-1}{n}}$ over $\mathbb {Q}$. So I used Wolfram Alpha to observe that it is $$x^n -\sum \limits _{i=1}^{n} {n \choose i} x^{n-i}=0$$ But I am finding it difficult to prove this. Can anyone give any hints. Thanks.
Edit $ 1$: I have feeling that all the conjugate roots are $1+ {\zeta}2^{\frac{1}{n}} +\cdots+{\zeta}^{\frac{n-1}{n}}2^{\frac{n-1}{n}}$. And the rotations of only the $\zeta$ keeping the $1$ fixed that is one more root I guess would be $1+ {\zeta}^22^{\frac{1}{n}} + {\zeta}^32^{\frac{2}{n}} +\cdots+{\zeta}2^{\frac{n-1}{n}}$. If we assume this then the sum of roots is $n$. But I do not know whether this is true.
Comment: If may help to note that $1+2^{\frac{1}{n}} +....+2^{\frac{n-1}{n}}=\frac{1}{2^{\frac{1}{n}}-1}$
Comment: How did you "observe" that? And what is what you find difficult to prove? That the polynomial is irreducible or that it actually vanishes on that element?
Comment: @Timbuc I used wolfram alpha and observed this pattern and I am unable to show that polynomial vanishes and also the irreducibility
Comment: @marwalix after noting that what do we do? Can you please elaborate
Answer: $\displaystyle\sum_{k=0}^{n-1}a^k=\frac{a^n-1}{a-1}.~$ For $a=\sqrt[\large n]2,~$ this becomes $~\dfrac1{\sqrt[\large n]2-1}.~$ Now, what is the minimal polynomial
of $\sqrt[\large n]2-1,~$ and what can we infer from that ? :-$)$
Answer: $$\alpha=1+2^{\frac{1}{n}} +....+2^{\frac{n-1}{n}}=\frac{1}{2^{\frac{1}{n}}-1}$$
From that we deduce $$2\alpha^n-(1+\alpha)^n=0$$ and this shows $\alpha$ is a root of the polynomial $x^n -\sum \limits _{i=1}^{n} {n \choose i} x^{n-i}=0$
Comment: @Timbuc $$2x^n-(1+x)^n=x^n -\sum \limits _{i=1}^{n} {n \choose i} x^{n-i}$$
Comment: @marwalix You're right. I missed that $\;2\;$ there. Thanks


Can you start a getty on /dev/pts/x ? Want a serial connection between my Linux KVM server host and Windows Guest

Question: Here's what I have going on:
I have a Debian server running several services in Docker and a couple in KVM.
One of the KVM hosts is a Windows 10 VM that I actually use as a desktop by using PCI passthrough of GPU, USB and some other things.
On the Windows VM, I also have a virtual serial device which attaches to /dev/pts/1
If I fire up Putty on the windows VM and attach to Com1, I can echo "something" > /dev/pts/1 on my host server and it shows up in my putty window. I can also cat /dev/pts/1 and type data into my putty window and it shows up in the cat output.
What I'm trying to do:
I want a getty to run on /dev/pts/1 so that I can simply open a putty window and get the console of my host device.
This mainly came up when I've noticed that I've done something to the network stack on my host device and couldn't ssh to it.
I've tried just running agetty -s 115200 -t 600 /dev/pts/1 linux which does nothing.
It seems  /etc/inittab no longer exists.
I've considered just adding a separate vnic attached directly to my host, but I just don't want to do that.
Comment: I accomplished something similar to this by passing through a USB serial adapter to a guest, and connecting that serial adapter to the serial console port of the host. I did it that way because I generally have a lot of serial devices, and wanted the guest to be able to connect to them - yet also connect to the host in case of networking failure by simply swapping a cable. It's worth noting that this guest was using GPU and USB passthrough much like you're doing.
Comment: Why don't you just ssh in like everyone else? This serial port method will come back to bite you when you can't do simple things like copy files or have curses apps work properly.
Comment: @spooler I've done that, and I know it works, however, just looking at the cables and my office, I'd like to "keep it clean".  Also, it bothers me having a cable connecting from my computer to my computer.  lol.  Good suggestion though.
Comment: @MichaelHampton , of course I use SSH mainly, but as stated in my post, this serial connection is for when something goes wrong with the network stack.  For example, right now, I have this problem when every the host is rebooted, the main interface has no IP address even though it is set for DHCP.  Looking to fix this problem as a separate effort altogether.  This would be a more practical failsafe if anything happens with network connectivity.
Comment: This also, begs the question:  "What is the virtual serial port for anyway on a KVM guest?"  If I can echo strings between my guest and host, then I should be able to run a getty on it.
Answer: I have found that agetty, the default terminal login handler, doesn't like PTS devices. However mgetty works fine with it.  It's a little tricky to set up though.
First install mgetty - on Ubuntu that's sudo apt-get install mgetty.
Next you need to set up a systemd unit file for it. I've made one that specifically works on /dev/pts files. Save this as /lib/systemd/system/mgetty-pts@.service:
[Unit]
Description=Smart Modem Getty(mgetty)
Documentation=man:mgetty(8)
Requires=systemd-udev-settle.service
After=systemd-udev-settle.service

[Service]
Type=simple
ExecStart=/usr/sbin/mgetty -r /dev/pts/%I
Restart=always
PIDFile=/var/run/mgetty.pid.pts%I

[Install]
WantedBy=multi-user.target

And reload the systemd configuration to pick up the changes:
sudo systemctl daemon-reload

Next you need to set up the terminal types for any incoming connections. This is done in /etc/mgetty/mgetty.config. For each pts you need to add:
port pts/2
    term vt220

Change the /2 to whatever pts you are working with, and select the terminal type appropriately.
Finally enable and start the service for your chosen pty:
sudo systemctl enable mgetty-pts@2
sudo systemctl start mgetty-pts@2

You should now have a login available on the virtual machine's serial.  You can start as many mgetty sessions as you like on different pts devices by specifying a different pts number in the service enable/start. For /dev/pts/3 it would be:
sudo systemctl enable mgetty-pts@3
sudo systemctl start mgetty-pts@3

So just make sure you use the right numbers throughout.


É possível fazer validação de formulário no cliente e no servidor somente com JavaScript?

Question: No caso em particular, gostaria de criar um form para contato, com nome, tipo de serviço (menu dropdown: webdesign, mobile), assunto e mensagem. Gostaria também de enviar esse form com nome, tipo de serviço e mensagem para um e-mail específico no formato de texto.
Normalmente a validação de um form é feita no servidor com ASP, Java. Agora, seria possível fazer validação somente com JavaScript? Qual a tecnologia necessária para fazer isso?
Comment: http://pt.stackoverflow.com/q/13298/101
Comment: Veja http://pt.stackoverflow.com/questions/102522/%C3%89-poss%C3%ADvel-fazer-autentica%C3%A7%C3%A3o-valida%C3%A7%C3%A3o-de-formul%C3%A1rio-com-node-js-puro?rq=1 pode ser q ajude. E isto https://nodemailer.com/
Comment: Conheço sim, mas quer fazer as validações do lado cliente em javascript? (como fiz em baixo) Ou do lado servidor... Só o lado servidor que consegue enviar emails, seja ele em node/php/etc..
Comment: A parte de javascript tinha feito em baixo mas o envio do do email tem sempre de ser feito do lado servidor. Com php/ASP etc..
Comment: Node é servidor, AngularJS não é
Comment: Paulo , veja este plugin para jquery : https://jqueryvalidation.org
Answer: Você pode utilizar a validação Client-Side com Javascript (puro ou usando alguma bilioteca como JQuery, AngularJS, etc).
Esta vai ocorrer antes de você enviar os dados para o servidor. Algo assim:
function Valida() {
    if (document.getElementById("nome").value.length < 1) {
        alert("Digite um nome.");
        document.getElementById("nome").focus();
        return false;
    } else if (document.getElementById("idade").value.length < 1) {
        alert("Digite uma idade.");
        document.getElementById("idade").focus();
        return false;
    } else if (document.getElementById("sexo").value == 0) {
        alert("Escolha um sexo.");
        document.getElementById("sexo").focus();
        return false;
    } else {
        return true;
    }
}

Fonte: https://bytecrow.wordpress.com/2011/10/17/tutorial-para-iniciantes-05-validacao-de-formulario-com-javascript/
Você pode (e recomendo) fazer a validação também no lado servidor usando NodeJS e Javascript.
O código é grande, veja em https://udgwebdev.com/trabalhando-com-validators-no-node-js.
Dá para mandar e-mails txt ou html usando o nodemailer, plugin para express:
var nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://user%40gmail.com:email@example.com');

// setup e-mail data with unicode symbols
var mailOptions = {
    from: '"Fred Foo " <email@example.com>', // sender address
    to: 'firstname.lastname@example.com, email@example.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ', // plaintext body
    html: 'Hello world ' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
    if(error){
        return console.log(error);
    }
    console.log('Message sent: ' + info.response);
});

Fonte: https://github.com/nodemailer/nodemailer
Comment: O que aconteceria no caso do JS estar desabilitado em meu browser?
Comment: @MagicHat o céu cairia sobre a Terra.
Comment: @renan hehe, falando sério...
Comment: Enviaria o formulário normalmente, independente de inserir (ou não) qualquer informação nos campos. A pergunta que o bigown linkou nos comentários é uma boa: [Usar validação via cliente é suficiente?](http://pt.stackoverflow.com/q/13298/4808)
Comment: suspeitei desde o princípio....
Comment: Se o Javascript estiver desabilitado, o browser consegue enviar os dados (se não tiver usando ajax para isso). No lado servidor tudo ocorrerá normalmente. O que não vai acontecer é a validação no client-side.


Why are some Beethoven works given names like WoO 40 or Hess 238?

Question: Why is it called WoO 40 or Hess 238?
These are names of Beethoven's symphonies.
They have peculiar names.
Answer: Compositions are commonly referred to by what we call opus numbers. A famous sonata by Beethoven is his Opus 53, and—because "opus" is Latin for "work"—this is an identifier that tells us that it is his 53rd work (more or less).
But there are a couple problems with this system:

Sometimes, composers don't give a composition an opus number. For this reason, Beethoven scholars sometimes use WoO numbers. "WoO" is short for "Werke ohne Opuszahl," which itself is German for "works without opus number." As such, the WoO system helps categorize and identify works for which we don't have an opus number.
In other instances, opus numbers don't show a clear chronology. Typically, opus numbers are given in ascending order when they are written; a composer's first work is Op. 1, their next work is Op. 2, etc. But sometimes opus numbers are given in a different order, and so Op. 9 wasn't always written before Op. 10. Moreover, sometimes sketch fragments or unfinished pieces that did not receive opus numbers are important relics for following a composer's development (and therefore need to be catalogued). In cases like this, we devise other systems to categorize a composer's output. In Beethoven's case, Willy Hess published a catalogue in 1957 of Beethoven's work that includes sketches and unfinished works; Hess 238 is thus a listing within this Hess catalogue. (Perhaps surprisingly, Hess's catalogue isn't the only one for Beethoven's works!)

It's worth mentioning that other composers have similar systems: see the Köchel catalogue for Mozart's works, the Deutsch catalogue for Schubert, or the Hoboken catalogue for Haydn (coincidentally also written in 1957). Sometimes these works are listed by genre—all piano sonatas are numbered together, all string quartets are numbered together, etc.—but other times they are listed chronologically.
Answer: You got that wrong, WoO is no name, but a sort of disambiguation between the different works of a composer. While opus is used by many composers (they assigned the numbers themselves), they are not very reliable and often incomplete. Professional listings have different names, frequently taken over from the creator of that listing. Sometimes even more than one such listing exists for the same composer (Scarlatti sonatas e. g. by Longo, Kirkpatrick, since additional research suggested a revision.)
There are other kinds of disambiguation, like adding the key, see this question and its answers, and for symphonies often just the ordinal number is used. Especially for Beethoven the ordinal number (or a catching title like Pastorale) will much more likely be recognized than any listing reference.


What are Noether's "Fünfaxioms" for Dedekind domains?

Question: While reading the following article

Fuchs, Ladislaus. "Über die Ideale arithmetischer ringe." Commentarii Mathematici Helvetici 23.1 (1949): 334-341.

I ran across this allusion which I'm unable to clarify:

... alle Noetherschen Fünfaxioms-Ringe immer $A$-Ringe sind.

I know little of German but I can get along with machine translation.  The best I can make out is "all Noetherian Five-axiom rings are arithmetic rings."
But what's a "Fünfaxioms-Ringe"? Google gives me nothing...  Perhaps it is very archaic or I simply don't know something obvious that a fluent German speaker knows.
Can anyone help clear this up?

Huh naturally only after I posted did I think to attempt "five axiom ring" in English in google, and it got one hit, a biography of Emmy Noether, which says

Furthermore,
E. Noether established necessary and sufficient conditions for every ideal to be a product of powers of prime ideals (five-axiom-ring, or Dedekind ring). By eliminating individual axioms...

Switching to google "Noether five axiom" yielded another book by J.S. Milne with a clearer claim:

Emmy Noether re-examined Kummer's work more abstractly, and named the integral domains for which his methods applied "five-axiom rings". found here

So now it is clearer that it means "Dedekind ring." Now my question is: what are the five axioms?  (There's no mention of Noether specifically on the wiki page for Dedekind domains.)
Answer: I'm German and have never come across this term; I believe it is rather archaic. I'm no historian, so take all my interpretation of this text with a grain of salt. The origin of the term appears to be Emmy Noether's Abstrakter Aufbau der Idealtheorie in algebraischen Zahl- und Funktionenkörpern
. The introduction reads

Im folgenden wird eine abstrakte Charakterisierung all derjenigen Ringe gegeben, deren Idealtheorie übereinstimmt mit der Idealtheorie aller ganzen Größen des algebraischen Zahlkörpers — deren Ideale sich also eindeutig als Potenzprodukte von Primidealen darstellen lassen.

In rough translation,

In the following, the rings whose theory of ideals agrees with the theory of ideals in the ring of integers of an algebraic number field — that is, whose ideals can be uniquely written as products of powers of prime ideals — will be abstractly characterized.

In modern language, this means Dedekind rings. Note that rings are specified to be commutative. Then, she lists the five axioms.

I. Teilerkettensatz: Jede Kette von Idealen, bei der jedes Ideal ein echter Teiler des vorangehenden ist, bricht im Endlichen ab. [...]

In rough translation,

I. Theorem on chains of divisors: Every chain of ideals in which each ideal is a proper divisor of the preceding one terminates in the finite.

In modern language, the ring is Noetherian. Further,

II. Vielfachen-Kettensatz modulo jedem vom Nullideal verschiedenen Ideal: Jede Kette von Idealen — die sämtlich Teiler eines festen, vom Nullideal verschiedenen Ideals sind —, bei der jedes Ideal ein echtes Vielfaches des vorangehenden ist, bricht im Endlichen ab.

In rough translation,

II: Theorem on chains of multiples modulo a fixed ideal different from the zero ideal: Every chain of ideals — each of which dividing a fixed ideal different from the zero ideal —, in which each ideal is a proper multiple of the preceding one terminates in the finite.

In modern language, each proper quotient of the ring is Artinian. Further,

III: Existenz des Einheitselementes der Multiplikation.

In rough translation,

III: Existence of a unit element for multiplication.

This is self-explanatory, though surprising. It seems to suggest that "ring" in this time period meant not necessarily unital rings. Further,

IV: Ring ohne Nullteiler.

In rough translation,

IV: Ring without zero divisors.

This is self-explanatory. Lastly,

V: Ganze Abgeschlossenheit im Quotientenkörper: Jedes Element des Quotientenkörpers, das ganz in bezug auf den Ring ist, gehört dem Ring an.

In rough translation,

V: Integral closure in the quotient field: Every element of the quotient field, which is integral relative to the ring, belongs to the ring.

In modern language, the ring is integrally closed.
Thus, after interpretation and recasting everything in modern language, the crux appears to be the characterization of Dedekind rings as precisely the integrally closed domains that are Noetherian and each proper quotient of which is Artinian. This characterization is, of course, well-known to this day.
Comment: Thank you so much!  Since it seems still like a good definition it's sad that the wiki page doesn't attribute it to Noether.


Parse json to csv Python

Question: I'm building my first web scraper and have the following returning the info I need -
import requests
r = requests.get('https://greatbritishpublictoiletmap.rca.ac.uk/loos/54c234f02ec4abe957b84f37?format=json')
r.json()["properties"]

the output looks like this -
{'orig': {'amenity': 'toilets', 'source': 'survey', 'id': 'node/975749026', 'location': 'Victoria Street', 'postcode': 'DE1 1EQ', 'open': '07.00 - 19.00', 'closed': '19.00 - 07.00', 'male': '1', 'female': '1', 'unisex': '0', 'disabled': '1', 'radar': 'Yes', 'baby change': '0', 'cost': '�0.20', 'date': '15/04/2014', 'data collected from': 'FOI', 'geocoded': True, 'geocoding_method': 'postcode'}, 'geocoding_method': 'postcode', 'geocoded': True, 'fee': '�0.20', 'babyChange': 'false', 'radar': 'true', 'type': 'female and male', 'opening': '07:00-19:00', 'postcode': 'DE1 1EQ', 'name': 'Victoria Street', 'streetAddress': 'Victoria Street', 'accessibleType': '', 'notes': '', 'area': [{'type': 'Unitary Authority', 'name': 'Derby City Council', '_id': '57f268ed87986b0010177619'}], 'access': 'public', 'active': True}

I simply want to dump this information into a CSV but I'm struggling to adjust my code. How do I do this?
Comment: You can't adjust code that doesn't exist. How are you trying to write to a CSV currently? Can you please edit your question to show what you're currently using?
Comment: Possible duplicate of [How can I convert JSON to CSV?](http://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv)
Comment: The truth is that i'm learning as i go, i've tried writing to CSV but couldn't get it to work so didn't include the half baked code, i was delighted to get this far as my first attempt. Just after a pointer or 2 nothing major.
Answer: You really need to decide which data you want, and how you want it formatted as the JSON is nested. The following approach for example simply writes all entries that are either strings or boolean values:
import requests
import csv

r = requests.get('https://greatbritishpublictoiletmap.rca.ac.uk/loos/54c234f02ec4abe957b84f37?format=json')
properties = r.json()["properties"]

with open('output.csv', 'w', newline='', encoding='utf-8') as f_output:
    csv_output = csv.writer(f_output)
    header = []

    for k, v in properties.items():
        if isinstance(v, str) or isinstance(v, bool):
            header.append(k)

    csv_output.writerow(header)
    csv_output.writerow([properties[k] for k in header])

This would give you a CSV as follows:
opening,name,radar,active,accessibleType,type,postcode,geocoding_method,babyChange,notes,fee,geocoded,access,streetAddress
07:00-19:00,Victoria Street,true,True,,female and male,DE1 1EQ,postcode,false,,�0.20,True,public,Victoria Street

Tested using Python 3.5.2

Parse json to csv Python


Electric guitar on a mixer

Question: I just got my first electric guitar and am wanting to learn how to play it. now I want to try and let my friends listen in with me via discord. I have a studio microphone that I've connected in an XLR mixer. now I can connect the electric guitar to this and play but to do that I have to disconnect the microphone. so basically what I'm asking is. is there a mixer that allows me to play my guitar and talk through my studio mic at the same time?
thank you in advance
Comment: This is all a bit confused. I'm not quite sure what you're asking. Guitars don't plug into XLR sockets (nor should you try to find adaptors to force them).
Comment: sorry, I should have worded that better it's like a mix between an xlr and a 6,3mm jack. this is the mixer I have: https://www.bax-shop.nl/analoog-mengpaneel/behringer-xenyx-302usb-pa-en-studio-mixer and I could plug it into this (I have edited the question for people to better understand it)
Comment: that doesn't look ready to take a guitar; it's mic & 'consumer line level' suitable for a hifi line out, not guitar. https://www.behringer.com/product.html?modelCode=P0ADV
Comment: I get that it probably isn't supposed to be used for a guitar and that's why I'm asking. is there a mixer where I can hook up a studio mic and a guitar or do I need to get some other stuff (I am not really an audio guy so I don't know anything about gear and stuff)
Comment: That socket is for *either* xlr *or* standard jack. If that works with either guitar or mic, why wouldn't a mixer with two of those sockets work as you require?
Answer: It seems to me what you really want is an audio interface so you can simultaneously run your guitar and mic into a digital device for recording/sharing. I have one with two input channels that take both guitar cord and XLR mic cable, and a USB output which also serves to power the unit. It only has level controls, no EQ or pan, but is bundled with mixing software that will provide those functions, and more, digitally.
I understand it's not appropriate to recommend specific products here, but if you search for "audio interface" at your favorite music gear retailer, you should find some options at a range of prices.
Comment: I would recommend an audio interface for practice, but not all audio interfaces will work as standalone mixers.  If OP really needs a mixer then this will not work for him.
Comment: I don't necessarily need a mixer. the mixer is just there for my mic but If I can use an audio interface for both my mic and a guitar then that would be the solution

Electric guitar on a mixer


How to get page statistics with views?

Question: I need to do a lot of sort criteria based on the number of profile pages viewed in Views , but I do not have any fields related to statistics and I cannot find any module which would help me to add fields to Views displays. Is there any module that would do the job or what do I have to do to get statistics about certain pages?
Someone said to alter the view query but how do I know in which table and what reference is between that table and the page that I want the statistics for?
Comment: drupal version?
Comment: @indrock drupal 7
Answer: For this you have to enable the Statistics module which is provided by  Drupal Core.
Follow these steps :
1. First enable Statistics Module
2. Then make a view and add a field provided by Statistics module. It basically provides three options:
Most recent view
Total Views
Views today

and then use Total Views as mentioned in your requirement.
Answer: 1. Module Visitors
Have a look at the Visitors module. It comes with a set of Visitors Reports, such as:

User activity report (hits, nodes, comments).
A Visitor tab that is added to each node, with details about Referrer, Date, User, IP address, User agent.

This module comes with its own set of (fixed) reports, whereas these reports are about data stored in the tables this module maintains.
If the reports they come with don't meet all your reporting requirements, you could use something like the Forena module to create custom reports (and charts) about the data stored in any of these tables. Another option is to create a custom module (with custom queries) for this kind of reporting.
2. Module Forena
If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Views integration of the Forena module. Here is a relevant excerpt about that from its project page:

Use Views with Forena to create additional more complicated layouts than can typically be created using views. Forena provides a views rowstyle plugin that lets you use a Forena report to format the output of a view.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327.
Disclosure: I'm maintainer of the Visitors module, and co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.
Answer: There is also the Better Statistics Module that will further expand the core Statistics module by letting you omit paths/roles/lots of other customizations. Then all of this info is available on the node level in views.

How to get page statistics with views?


Excel VBA to Format as Table and then Change Orientation on all Sheets

Question: I am trying to get the code below to make a table for only the columns with data and to do so for every sheet in the workbook, and then after change the orientation of all sheets to landscape but its doing 2 things weird:

Not looping through sheets.
Making all columns into the table not just those with data.

Can it be done to only look for columns with data and format those into a table?
Sub Format_As_Table()

Dim tbl As ListObject
Dim rng As Range
Dim sh As Worksheet

For Each sh In ThisWorkbook.Sheets
    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
Next sh
Application.ScreenUpdating = False
Call Orientation

End Sub

'======================================================================

Sub Orientation()

Dim sh As Worksheet

For Each sh In ThisWorkbook.Sheets
    With ActiveSheet.PageSetup
        .Orientation = xlLandscape
    End With
Next sh
Application.ScreenUpdating = False

End Sub

Answer: You can combine both Subs into one.
Your original code was looping through the sheets, but the objects underneath are not fully qualified with the current sh of the loop. Instead they reference the ActiveSheet, which is whatever sheet was active when you run this code.
Once you add With sh, and underneath you nest your objects with a . as prefix, all objects will be fully qualified with sh. For example:
Set Rng = .Range(.Range("A1"), .Range("A1").SpecialCells(xlLastCell))

Note: Using SpecialCells(xlLastCell) to get the last cell might not be the most reliable way. Read HERE on different methods and advantages.
Code
Option Explicit

Sub Format_As_Table_and_Orientation()

Dim Tbl As ListObject
Dim Rng As Range
Dim sh As Worksheet

Application.ScreenUpdating = False
For Each sh In ThisWorkbook.Sheets
    With sh
        Set Rng = .Range(.Range("A1"), .Range("A1").SpecialCells(xlLastCell))
        Set Tbl = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
        Tbl.TableStyle = "TableStyleMedium15"

        .PageSetup.Orientation = xlLandscape
    End With

Next sh
Application.ScreenUpdating = True

End Sub


how to create Master Page in MVVM?

Question: I want to create master page in mvvm. I created a viewbox that it's name is container for showing my usercontrols and I have two classes, RelayCommand and ViewModel.
Here is my code:
public class ViewModel
{
    MainWindow objMainWindow = new MainWindow();

    UserControls.History objHistory = new UserControls.History();
    UserControls.NewItem objNewItem = new UserControls.NewItem();
    UserControls.SideEffect objSideEffect = new UserControls.SideEffect();

    public ViewModel()
    {
        OpenCommand = new RelayCommand(Open);

    }

    private ICommand openCommand;
    public ICommand OpenCommand
    {
        get { return openCommand; }
        set { openCommand = value; }
    }

    public void Open(object sender)
    {

        if (sender.ToString() == "btnHistory")
        {
            objMainWindow.Container.Child = objHistory;

        }

        if (sender.ToString() == "btnNewItem")
        {

        }

        if (sender.ToString() == "btnSideEffect")
        {

        }

    }

}

And this is my RelayCommand:
public class RelayCommand:ICommand
{

   public RelayCommand(Action<object> _action)
   {
       actionCommand = _action;
   }

    private Action<object> actionCommand;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        if (parameter !=null)
        {
            actionCommand(parameter);
        }

        else
        {
            actionCommand("Null");
        }
    }

}

but when I run solution I faced with NullRefrenceException when it wanted to show my child of container.
I don't  know how to make this work.
Answer: Your MainWindow instantiates when your program starts. So you shouldn't instantiate it again in your ViewModel (i.e. this line: MainWindow objMainWindow = new MainWindow();). You should use DataBinding instead.
Here is a sample code that gives you an idea:
First define a property of type FrameworkElement in you ViewModel and set it's value to your desired UserControl in the Open method.
ViewModel:
public class ViewModel : INotifyPropertyChanged
{
    FrameworkElement _myUc;
    public FrameworkElement MyUserControl
    {
        get
        {
            return _myUc;
        }
        set
        {
            _myUc= value;
            OnPropertyChanged("MyUserControl");
        }
    }

    public ViewModel()
    {
        OpenCommand = new RelayCommand(Open);
    }

    public void Open(object sender)
    {
        if (sender.ToString() == "btnHistory")
        {
           MyUserControl = objHistory;
        }
    }

    // rest of your view model ...
}

Then instantiate your ViewModel as the DataContext of your MainWindow in the Constructor.
MainWindow:
public ViewModel MyViewModel { get; set; }
public MainWindow()
{
    InitializeComponent();
    MyViewModel = new ViewModel();
    DataContext = MyViewModel;
}

And Finally use a ContentControl (instead of ViewBox) [see my note] and bind it's Content to the MyUserControl property of your ViewModel.
XAML:
<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ContentControl Grid.Row="0" Content="{Binding MyUserControl}"  x:Name="Container"/>
    <Button Grid.Row="1" Name="btnHistory" Content="ShowHistory" Command="{Binding OpenCommand}" />
</Grid>

This way each time MyUserControl changes, the ContentControl shows your desired UserControl.
Note that Child property of ViewBox is not a DependencyProperty and thus not bind-able.

how to create Master Page in MVVM?