Firefox rendering issue when box-shadow and rgba(0, 0, 0, 0.5)

Question: When applying box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.5); to a div element on Firefox some thin black outline appears around the div.

The same code renders differently on Chrome as no black outline appears around the div.
I would like to know if this is a FF specific known bug issue and a work around (as after some search I could not find any information).
Notes:
The desired result is a box with no artifacts at the edge like in Chrome.

Border artifact are rendered in corners only on Firefox.

Answer: That sounds normal comprehensible to me :
You are asking to create an box-shadow which starts with 0 offset, 0 blur, 0 spread.
But FF will still try to generate it (just like if it were 1px 1px 0px 0px).

div{
  border-radius: 12px;
  box-shadow: 1px 1px 0px 0px red;
  height: 25px;
  }

Since the border is rounded, the shadow has to be antialiased.
What you see are the antialiasing artifacts.
To avoid it, you can either

don't set the box-shadow
set its color to transparent
set it's spread to -1

div{
  border-radius: 12px;
  height: 25px;
  box-shadow: 0px 0px 0px 0px red;
  background: rgba(0,0,0,.1);
  }
.no-box{
  box-shadow: none;
  }
.transp{
  box-shadow: 0px 0px 0px 0px transparent;
  }
.minus{
  box-shadow: 0px 0px 0px -1px red;
  }

Comment: @GibboK No it doesn't. My point was that i has to render `1px 1px 0px 0px` (I had a typo btw) or even `0.1px 0px 0px 0px`. So for it, it makes no difference if it's at x 0 y 0 or something else : it has to render it. While doing so, the antialiasing will kick in, leaving those artifacts we see. We could argue that they could be smarter and avoid rendering this exact value, but I'm pretty confident that nothing tells they shouldn't, hence not sure if we can call it a *bug* per se. (But might be worth an bug report anyway if you fell like so).
Comment: Thanks for your answer, do you have an idea why FF try to render it as`1px 1px 1px 0px`. Is it a bug in FF?
Answer: FF reads box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 1); just like
box-shadow: 1px 1px 1px 0px rgba(0, 0, 0, 1);
Just simply change the box-shadow to box-shadow: 1px 1px 1px 0px rgba(0, 0, 0, 1); and you will be okay.

div.styles {
  position: inherit;
  background-color: #fff;
  top: 0px;
  left: 0px;
  width: inherit;
  height: inherit;
  transform: rotateZ(0deg) rotateY(0deg) rotateX(0deg) skewY(0deg) skewX(0deg) scaleX(1) scaleY(1) scaleZ(1) translateX(0px) translateY(0px) translateZ(0px);
  backface-visibility: visible;
  border-radius: 10px;
  border-style: solid;
  border-width: 0px;
  background-color: rgba(0, 0, 0, 0);
  border-color: rgb(0, 0, 0);
  opacity: 1;
  box-shadow: 1px 1px 1px 0px rgba(0, 0, 0, 1);
  overflow: hidden;
  display: flex;
}

div.container {
  width: inherit;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  font-weight: 400;
  color: rgb(0, 0, 0);
  letter-spacing: 0em;
  line-height: 1.2em;
  padding: 16px;
  overflow-wrap: break-word;
  text-align: left;
  align-self: flex-start;
}

Border artifact are rendered in corners only on Firefox.

JSFiddle
Comment: Thanks, but it is not the result I expect. The desired result is no outline at all.
Comment: If you dont want an outline, change the `rbga(0,0,0,1)` to `rgba(0,0,0,0)`

https://jsfiddle.net/90q9tru1/2/ **OR** just delete the box shadow


How to display an Object in a column with apache-poi

Question: I have a big DTO with exactly 234 fields, and I have to display values of each fields of this DTO in a column of an Excel file created with apache-poi.
This is my code :
// Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Export values");

// Get the Entity
Simfoot simEntity = simService.findById(simId).get();

Row row = sheet.createRow(0);
row.createCell(1).setCellValue("Consult our values");

// and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).

I want to have in my first column : nothing , in my second only the String display ( "Consult our values" ) and in my third column I need to have my 234 fields. With an field ( the value of the field ) in one cell. So, 234 rows displaying one value in the third column.
I hope that it is clear.
Thanks a lot for your help.
Comment: I would combine all the 234 fields from your DTO into one field and write it to the cell you want using Apache POI.
Answer: Using some reflection:
    // Blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook();

    final Sheet sheet = workbook.createSheet("Export values");

    // Get the Entity
    final Simfoot simEntity = simService.findById(simId).get();

    Row row = sheet.createRow(0);
    row.createCell(1).setCellValue("Consult our values");

    // and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).
    Arrays.stream(simEntity.getClass().getDeclaredMethods())
            .filter(m -> m.getName().startsWith("get") && m.getParameterTypes().length == 0 && !void.class.equals(m.getReturnType()))
            .forEach(m -> {
                    try {
                            Object value = m.invoke(simEntity, null);
                            Row r = sheet.createRow(sheet.getLastRowNum()+1);
                            r.createCell(2).setCellValue(value == null ? "" : value.toString());
                    }
                    catch (Exception ex) {
                            // Manage Exception....
                    }
            });

Comment: Thanks I tested your proposition and it's working fine !
Answer: I'll add a method on Simfoot to return all the values:
public List<String> getAllValues() {
    return Arrays.asList(getAtt1(), getAtt2(), .. , getAtt234());
}

Then create a row per attribute, and then you can merge the rows of the first 2 columns. Example here with 6 attributes:
int n = 6; // would be 234 for you
XSSFCellStyle styleAlignTop = workbook.createCellStyle();
styleAlignTop.setVerticalAlignment(VerticalAlignment.TOP);
Row row;
for(int i=0; i<n; i++) {
    row = sheet.createRow(i);
    if(i==0) {
        Cell cell = row.createCell(1);
        cell.setCellStyle(styleAlignTop);
        cell.setCellValue("Consult our values");
    }
    row.createCell(2).setCellValue(simEntity.getAllValues().get(i));
}
sheet.addMergedRegion(new CellRangeAddress(0, n-1, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, n-1, 1, 1));

It shows like this:

Another way to list your attributes would be to use Reflection but I find it very clunky:
Simfoot simEntity = new Simfoot("pap", "pep", "pip", "pop", "pup", "pyp");

for(PropertyDescriptor propertyDescriptor :
    Introspector.getBeanInfo(Simfoot.class).getPropertyDescriptors()) {
        System.out.println(propertyDescriptor.getReadMethod().invoke(simEntity));
}

Outputs:
pap
pep
pip
pop
pup
pyp
class Simfoot

so you have to filter out getClass and any other unwanted methods and getters


How to Toggle Bluetooth in All Android Versions 1.5+ and Upwards

Question: I am trying to write a simple android application to toggle a users bluetooth connection.  I would like a single application that can work on all versions of Android 1.5+.
I am aware that the Android 2+ API officially added support for bluetooth however if I am targeting a SDK level of 3 (android 1.5) then I don't get access to the official BluetoothAdapter classes.
I have seen some examples on the web that use reflection and this will work on 1.5 and 1.6 but not 2.0.
I have also seen the following unoffical bluetooth API's however neither of their example apps (available in the market as "Bluetooth Samples" and "backport-android-bluetooth") work on my Nexus One.
http://code.google.com/p/android-bluetooth/
http://code.google.com/p/backport-android-bluetooth/
Does anyone have some sample code that will work on ALL versions of Android?
I know it is possible to achieve bluetooth toggling in a single app and for versions 1.5+ because there are many applications on the market, that I have tested and are able to achieve this.
Any help is really appreciated and thanks for reading.
NOTE: Please don't just suggest writing separate apps targeting different versions, this is not what I am trying to achieve.
Comment: you don't have to use differnt apps, you can read the api version from the code and adapt your code ;)
Comment: Thanks for your reply, I am aware I can determine the API version at runtime and run version specific code per device.
Unfortunately I haven't got the code that can enable/disable bluetooth on a version 2+ device using the native API targeted for API level 3.  Please share if you know how to achieve this.
Comment: What's stopping you from checking the API version at runtime and then determining which method to use? If you've already got code that works on the older versions, and official APIs that do what you want are introduced for the newer versions, then what's the issue? Just set min SDK version to 3, but target the level when the new Bluetooth classes were released. Before trying to use a higher-than-api-3 class, check the system version.
Comment: I had assumed that setting the minSdkVersion property lower than the projects target api would cause issues. I will give it a try however and let you know how I get on. Thanks Steve.
Comment: As suspected the application instantly force closes on a G1 (v1.6) with "application  has stopped unexpectedly. Please try again."

  All my code is surrounded with try catch blocks and debug toast messages so I can only assume this is caused because its not targeting the right API.

Works on a Nexus one however.
Comment: I've just found some additional documentation (link below) so I'm gonna experiment with the "targetSdkVersion" attribute tonight and see if that helps at all.  http://developer.android.com/guide/practices/screens_support.html#strategies.
Answer: I believe you are looking for this http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html. Bluetooth Adapter has been around since Eclair. However, there is no way of doing this before then unless an intent to the appropriate settings page is opened (as with the following example):
<code>Intent settingsIntent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(settingsIntent);
</code>
I would recommend that you use an intent to the Blueetooth Settings page as this is easier to implement and will identify if bluetooth is avaliable on the device.
I hope this helped.


Como abrir uma Activity quando não tiver internet?

Question: Estou com um projeto que utiliza internet, e quando não tem internet o mesmo não sai do menu pois eu coloquei um bloqueio de acesso a outras activit quando não há internet, mas em fez de não abrir eu queria que jogasse para outra activity especifica, eu até consigo abrir uma pagina em branco aleatória mas a pagina que eu solicito para abrir não vem, preciso de ajuda

Codigo MENU

public class TRABALHAR extends AppCompatActivity {

private WebView xp4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trabalhar);

    if(!isOnline()){
        startActivity(new Intent(TRABALHAR.this,NOTICIAS2.class));
        finish();
    }// verifica conexao com a net

    xp4 = findViewById(R.id.xp4);
    xp4.getSettings().setJavaScriptEnabled(true);
    xp4.setWebViewClient(new WebViewClient());
    xp4.loadUrl("https://clubcooeec1.blogspot.com/p/fazer-parte-da-equipe.html");

}
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnected(); // verifica se tem internet
}

se eu tirar a linha

startActivity(new Intent(TRABALHAR.this,NOTICIAS2.class));

o aplicativo apenas bloqueia o acesso a pagina, mas este não é meu objetivo
como devo proceder neste caso ?
Comment: esse seu método isOnline não verifica conexão com a internet, apenas verifica se o usuário está com alguma rede de internet ativa(wifi, rede móvel...). Agora pra eu entender melhor, quando não há internet, você quer abrir uma outra acitivity? Pelo seu código não está abrindo? Para mim parece normal.
Comment: Tentou colocar já a parte desse webview dentro do else??
Comment: Quando eu executo o código sem o wifi ligado o mesmo abre uma tela Branca  menos a activity que eu quero, na activity que eu quero aparecerá  que o mesmo esta sem conexão, mass se tiver um codigo aplicável  que faça verificar realmente a internet  e avisar o usuário  ja ajuda .
Comment: Olá renan, tentei detalhar bem a resposta, pra mim funcionou bem, e com a Asynctask que eu coloquei tira a margem de erro pra quando um usuário tá com wifi ligado ou rede móvel, mas a internet tá oscilando ou muito baixa e não é possível carregar a url. Passa um feedback, se der certo ou errado. Abç
Answer: Fiz algumas alterações e testei em uma API 24, funcionou bem.
Primeiro crie uma classe extendendo de AsyncTask, como a seguir:
public class CarregaPagina extends AsyncTask<String, Void, Boolean> {
    TRABALHAR trabalhar;
    String sUrl;
    int timeout;

    //construtor
    public CarregaPagina(TRABALHAR trabalhar, String sUrl, int timeout) {
        this.trabalhar = trabalhar;
        this.sUrl = sUrl;
        this.timeout = timeout;

    }

    @Override
    protected Boolean doInBackground(String... strings) {
        //se tem algum conexão com a internet
        if (isOnline()) {
            //checa a conexão com a url
            try {

                URL url = new URL(sUrl);
                //abre a conexão
                URLConnection urlConnection = url.openConnection();
                //tempo de resposta
                urlConnection.setConnectTimeout(timeout);
                //conecta
                urlConnection.connect();
                return true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean b) {
        if (b) {
            WebView xp4 = trabalhar.xp4;

            //carrega webview da classe TRABALHAR
            xp4.getSettings().setJavaScriptEnabled(true);
            xp4.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            xp4.getSettings().setLoadWithOverviewMode(true);
            xp4.getSettings().setUseWideViewPort(true);
            xp4.setWebViewClient(new WebViewClient());
            xp4.loadUrl(sUrl);
        } else {
            Toast.makeText(trabalhar, "Erro na conexão", Toast.LENGTH_SHORT).show();
            //Erro na conexão
            chamaActivity();
        }

    }

    private void chamaActivity() {
        Intent i = new Intent(trabalhar, NOTICIAS2.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        trabalhar.startActivity(new Intent(trabalhar, NOTICIAS2.class));
        trabalhar.finish();
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) trabalhar.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnected(); // verifica se tem internet
    }
}

Essa classe será responsável, por verificar se o usuário tá conectado à internet e se é possível carregar sua url, se não for capaz de carregar a url no webview, a sua Acitivty NOTICIAS2 será chamada.
Já na sua classe TRABALHAR, deixe apenas:
public class TRABALHAR extends AppCompatActivity {
    //deixe público pra poder utilizar na classe CarregaPagina;
    public WebView xp4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trabalhar);
        xp4 = findViewById(R.id.xp4);

        //os parametros na ordem são: contexto, url, e timeout (tempo pra checar a url) em milisegundos.
        CarregaPagina carregaPagina = new CarregaPagina(this, "https://clubcooeec1.blogspot.com/p/fazer-parte-da-equipe.html", 2000);
        //executa a AsyncTask
        carregaPagina.execute();

    }
}

Comment: Mano ate agora deu certo, obrigado assim que liberar parar dar o premio te mando, so apartir de 7 horas  despois da postagem. Ok
Comment: @renansilvadasneves blz brother, mas deu pra entender como tá funcionando? Se ficar alguma dúvida me avisa que eu edito a resposta e detalho mais.
Comment: mano deu erro em 2 linhas
Comment: que foi estas aqui
Comment: CarregaPagina carregaPagina = new CarregaPagina(this, "https://clubcooeec1.blogspot.com/p/fazer-parte-da-equipe.html", 2000);
        //executa a AsyncTask
        carregaPagina.execute();
Comment: foi em CarregaPagina  e carregaPagina.execute   tão vermelhas
Comment: Qual erro q deu? E qual api vc ta testando?
Comment: Tou testando na  API 16, talvez seja isto, não cheguei execultar o codigo ,mas aquelas palavras  estão sublinhada em vermelho, aquelas que citei acima . Vou mandar print.


Como manipulo valores do tipo time no meu JS?

Question: Preciso efetuar um calculo com valores de input tipo time no meu JS usando o jquery, como faço isso? existe alguma biblioteca pronta?
Inicio

    <input type="time" class="form-control" id="inicio">

Fim

    <input type="time" class="form-control" id="fim">

$(function() {
    $('#calcular').click(function(){

        var inicio = $('#inicio').val();
        var fim = $('#fim').val();
        var ciclo = $('#ciclo').val();

    });

});

Comment: Qual cálculo quer fazer, somar todos os valores, dividir?
Answer:

$('#btnSoma').click(function(){

    var inicio = $('#inicio').val();
    var iniSplit = inicio.split(':');
    var inic1 = iniSplit[0];
    var inic2 = iniSplit[1];
    var fim = $('#fim').val();
    var fimSplit = fim.split(':');
    var fim1 = fimSplit[0];
    var fim2 = fimSplit[1];
    var ciclo = $('#ciclo');

    var somaInicio = Number(inic1) + Number(fim1);
    var somaFim = Number(inic2) + Number(fim2);
    var soma = somaInicio+ ' : ' +somaFim;

    ciclo.val(soma);
});

Inicio

    <input type="time" class="form-control" id="inicio">

Fim

    <input type="time" class="form-control" id="fim">

Ciclo

    <input type="text" class="form-control" id="ciclo">
    <button type="button" id="btnSoma">Somar</button>


What is the best way to organize chords/keys in a database (details below)?

Question: I am working on a project that involves putting together a database of chords/keys, and I'm wondering what you guys think is the best way to categorize each chord/key. For example, if I want users to input a chord into the database using several dropdown menus, what menus/choices do I need? The goal is to make the information easy to group/sort/filter in meaningful ways, however, I am far from an expert on music theory, so I would like to know what you think are the most meaningful ways to categorize/break down the data.
Here are the menus that I have so far, do these make sense? Am I even close?

Root

A
B
C
etc.

Accidental

Sharp
Natural
Flat

Quality

Major
Minor
Diminished

[Unsure of terminology here]

3rd
5th
7th
etc.

Thanks in advance for any suggestions/guidance!
Comment: Understanding the [circle of 5ths](http://randscullard.com/CircleOfFifths/) would probably help you a lot.
Comment: I like the way you present it now. Except I would put diminished in the last category and call that type or extra.
Comment: You might want to look at the Chordbot iOS/Android app for inspiration. It lets users put together chord progressions, so its UI for selecting chords is a major part of the app. http://chordbot.com/
Comment: May I ask what is the purpose of the data base is? When one has an understanding of chord construction a data base seems  unnecessary?
Comment: @Fergus, I am building a web-app that will allow users to query the database in a friendly, easy-to-use way for a musician (targeting amateurs and hobbyists) who is not necessarily knowledgeable in music theory. An example would be: two beginner/intermediate guitarists jamming to a chord progression they're not familiar with and one wants to play lead over it, so he puts the chords into the app, the app queries the database and returns a few possible keys that they might be playing in, and then renders a guitar fretboard showing which notes on the fretboard are in that key.
Comment: @jackerman09 Ok, so that will only work for diatonic progressions (unless you will have multiple diagrams that show what different scale/s to play over the non diatonic chords?). Unless you want to go down the (much more complex..) path of handling non diatonic progressions I would suggest using a visual input system based on the circle of fifths. I've given an answer below to give more detail.
Answer: I'll give you the off-the-cuff perspective of a guy who got his degree in piano and then spent the next 30 years in software design.  :)
Let me say first that it is important that you understand that the manner in which the data are stored is not the same thing as the manner in which they are displayed.  It looks like you have a pretty good start on the way that they are displayed.
Now, are you asking to have a user fill up a database with chords, or put in the characteristics of a chord and get output as to how the chord is spelled?  The first is what you're implying, but the second might be more useful.  I'll assume the second, and give you my first impression of how I would go about it.
I would consider starting this way.  Allow the user to type in the letter A-G. Have two option buttons (radio buttons) in a set, one for sharp and one for flat.  Then use another set of option buttons for major, minor, dimished, and augmented.  Finally, have a check box for 7th.
Leave other chords until you get these basics working.  This will give you all of the triads and all the 7th chords.
Now, there are two ways to store the data.  A "flat" database would simply have a record for each different chord, which would have the spelling of the chord.  A "normalized" database would have three separate tables: one for chords, one for notes, and one for which notes go with which chords.  Notes (a table called Notes) has two fields: a key (just a number, a different number for each record or row in the table) and a note name.  This table contains all the different possible notes in the scale, including all the enharmonic ones.  (Enharmonic notes are notes that are spelled differently but are the same pitch, for example F# and Gb.)  Include all the double sharps and flats as well; you'll need them for augmented and diminished chords with a sharp or flat root.  For example, Ab diminished is Ab-Cb-Ebb, and G# augmented is G#-B#-Dx.  Then, store all the chords in a Chords table.  (Skip chords whose root is a double sharp or flat; they theoretically exist but come up rarely if at all in practice) Each record in the Chords table has two fields: a key and the name of the chord.  Finally, you tie these together with a ChordNotes table.  This one has three fields: the key of the Chords table and the key of the Notes table, and also a number which shows the place in the chord for that note, from bottom to top.  For example, in C major, C is 1, E is 2, and G is 3.
I'll give an example to show how this works.  Suppose your user has selected C major as the chord.  You look up C major in the chords table; let's say its key (table key, not musical key) is 14.  You then go to the ChordNotes table, and find that there are three records with a Chord key of 14; these records have 3, 5, and 7 in the respective note key fields.  You then go and find the three records in the Notes table with keys 3, 5, and 7, and you have your chord.
Putting that example into SQL (I'll just make up names for the fields in your tables; you can use whatever field names and table names you want in your design):

SELECT C.CHORDNAME, N.NOTENAME FROM NOTES N
JOIN CHORDNOTES CN ON N.NOTEKEY = CN.NOTEKEY
JOIN CHORDS C ON C.CHORDKEY = CN.CHORDKEY
WHERE C.CHORDKEY = 14
ORDER BY CN.NOTEORDER

The result would look like this:

CHORDNAME    NOTENAME
-----------  -----------
C Major      C
C Major      E
C Major      G

That should give you a good base to start on.  You'll need to work out how to get the key of the chord that the user selects from your UI (user interface), and how to display the result to the user.  However, if you implement all this, you'll learn enough so that you'll have some idea of how to implement refinements that suggest themselves.  Hope this helps, and good luck.  :)
Comment: Hey, I'm currently at work (as an accountant, so in no way related to this question), but I will read through it ASAP. A quick read-through looks like we're very much on the same page, and if you would like to see how the database is set up (5 tables, Key, Keychord, Chord, Chordnote, and Note), please check out the repo: https://github.com/jackerman09/what_key_v003. I'll read through your response very carefully later and get back to you, thanks again!
Comment: You may find that key and keychord are unnecessary, although I may not have thought this through fully too.  Why do you have them?
Comment: One of the applications that will be built on top of this database (you can see a rudimentary, non-database, version of this at http://www.whatkeyamiin.com, which I built ~1 yr ago, but am now rebuilding from scratch). I plan to bring in a "music admin" to work on the new app, who would have the role of approving chords & keys submitted by users, which would allow them to enter the "public library" of searchable chords/keys. Does that interest you (or anyone else reading this) at all?
Comment: Why would users have to have their chords approved before being able to look in the library?
Comment: The user can look in the "library" of public chords at any time, but only those chords that have been approved by the "music admin" will be viewable in the library or included in the apps utilizing this database. This is done to ensure that the created chords (and the notes it includes) are correct before becoming available for public use. While I have a basic knowledge of music theory (and I am developing the app on my own, though I am open to collaborators), I am not qualified to approve/correct chords submitted by users.
Comment: So, how would the user look in the "library" of public chords?
Comment: I am building a full web-based UI that will allow the user to interact with the data in various ways. It is actually pretty far along in the development process (at least to a first release), and I hope to continue to develop it and add features (relatively) indefinitely. Like I said, I'm looking for a partner who has a much more robust understanding of the music theory than I do, so if you think you may be interested, let me know, and I can show you the current iterations of the site and give you any additional detail you want.
Comment: @jackerman09 Hey jackerman, if you're still interested in corresponding about this, I'm still at aol, and my name there is robtrodes.
Comment: Hi @bobrodes, thanks for following up. The website is live (whatkeyamiin.com), and I would be open to a conversation about partnering up to develop it further, however, I am not currently actively working on it, as I have a moved on to other projects. Is it something you'd be interested in developing?
Answer: The fundamental idea of a chord is that there is a pitch, the root, and then a series of other pitches that have relationships to that root pitch, and implicitly, to each other.
I wouldn't make a big distinction between the natural notes, and those with alterations on them as you indicated in your bulletized list, but this could be argued either way.
I'd look at it as:
1) The user selects the pitch class for the root
2) User selects from {major, minor, sus2, sus4, no-third [*]}

this is the characteristic of the "third"

3) The user selects from {P5, aug, dim, no-fifth? [*]}

The default is the  perfect fifth

4) The use selects from various extensions {7th, maj7, 13th, flat-9 ...}

Here things start getting really complicated, and you'll have to decide what range of music you want to support.
maybe you want a set of independent checks for this.

I only see two complications:

Usually a diminisished chord impilies a minor third, but not always; sometimes, notably in jazz, you want a major third with a flattened fifth,
so disentangling this case might be harder.
Defining the range of chord "extensions" you'll need to have an idea of the scope of music that will be going into the data base, or a flexible system (vanilla strings maybe?) that allow for arbitrary extensions.

An option for handling the first case is
1) root pitch class
2) select from {major, minor, sus2, sus4, aug, dim, no-third [*]}

major/minor/sus2/sus4 implies perfect 5th
aug => major 3rd, dim => minor third

3) select extension

as above but include the various flat-5/sharp-5 options here.

[*] depending on how esoteric your music gets you may need additional concepts.
Comment: Just so everyone knows, your response is from the perspective of jazz theory and mine from that of classical theory. While the jazz approach is entirely valid, what you would or wouldn't do from a jazz perspective, and for good reason, might not apply from a classical perspective, also for good reason. For example, jazz doesn't go in much for different spellings of the same chord, and classical often does. This difference is driven partially by the fact that jazz rarely uses simple triads, and classical uses them more often than not.
Comment: Also, your "major third with flattened fifth diminished chord" wouldn't be analyzed that way at all in classical music. In jazz, this chord generally occurs as a "dominant 7th flat 5" chord, with the added minor 7th.  Such a chord generally occurs in classical music as an "augmented sixth" chord, specifically a "French sixth" chord, and spelled entirely differently.  For example the D7b5 chord C-E-Gb-Bb would be C-E-F#-A# (hence "augmented sixth") and would nearly always resolve chromatically to a B chord in root position.
Comment: As I understand it, the b5 chord usually functions in jazz as a substitute chord for the V in a ii-V-I progression, where the b5 root is a tritone from the root of the V chord, thereby making a nice chromatic ii-iib-I progression.
Answer: The optimal schema for any database largely depends on the type of queries. Think about that the user may ask from such a database. Maybe which chords are the good potential candidates to follow it in a chord progression? Then you need to read some theory about chord progression rules, and support queries along these rules. Here may be some hints to start from.
Answer: From the OP comments:
I am building a web-app that will allow users to query the database in a friendly, easy-to-use way for a musician (targeting amateurs and hobbyists) who is not necessarily knowledgeable in music theory. An example would be: two beginner/intermediate guitarists jamming to a chord progression they're not familiar with and one wants to play lead over it, so he puts the chords into the app, the app queries the database and returns a few possible keys that they might be playing in, and then renders a guitar fretboard showing which notes on the fretboard are in that key
You need to define your goal more strictly before writing any more code.
The main point is weather your app can handle non diatonic chord progressions.
What will happen when someone inevitably puts in the 12 bar blues chords? (I7, IV7 and V7)
Will your app be smart enough to recognize this extremely common non diatonic progression? and suggest the minor pentatonic, major pentatonic, mixolydian, blues scale, lydian dominant etc built from the roots of each chord as valid and common choices?
will it be smart enough to give the minor pent. as a valid choice for a dominant chord in this context? Will it know not to give this suggestion for 99% of other occurrences of dominant chords?
What will happen when other popular non diatonic chord progressions are input such as the Andalusian cadence? (http://en.wikipedia.org/wiki/List_of_popular_music_songs_featuring_Andalusian_cadences)
Will the app be smart enough to recognize that the phrygian dominant is an appropriate scale over the V chord?
What will happen when the user puts in "Hey Joe"?
These very common 'beginner' progressions will be the acid test. If your app can't deal with them then it won't be much use to anyone.
If you decide to avoid the complications of non diatonic progressions then it can be much simpler to achieve.
In that case there's really no point having the input system allow, say a diminished chord as that is never a diatonic chord. But your whatkeyamiin.com site  basically already does this..
If you go down this route I'd suggest simply having an image of the circle of fifths. the user selects chord after chord say, G, then C then Am then Em, as each additional chord is selected the possible diatonic chords reduces (non diatonic chords 'black' out) and the possible key become highlighted.
Answer: The first thing necessary to formulate your thesis is to understand your data and what other approaches have already been implemented. If you are thinking of a dynamic or interactive approach take a look at chords and scales identifier. The reference to "Lotus Music" was useful, but it presents a static interface.
Comment: Thanks for your input! This question is from a while ago, but if you're curious as to the outcome, here it is: www.whatkeyamiin.com :)
Answer: I just wanted to chime in and say that Databases are designed for items that are subject to change. Chords, Notes, Keys, etc don't change. So last thing you want in any music application is latency. Computers are built on mathematics, and so is Music Theory, so they get along quite well. Midi Messages are byte arrays.. And computers love bytes, they take very little space, and can be processed/streamed with minimal latency. I believe these things should be hardcoded as the computer can process millions of these types of instructions per second with no latency. A trip to the database will cost you milliseconds that add up.
So the only thing to begin is to describe each element as a class. For each element we want to keep them simple but avoid writing the same code twice. I'm building a midi application from scratch with no knowledge of music theory, and learning some music theory along the way.
Basically you just need a list of notes, each chord is made up of notes a certain distance from each other. This makes it easy to describe as a integer array
(List<int>)Notes.Add(new Note { Name="A", Pitch = 1, AltName="A" };
(List<int>)Notes.Add(new Note { Name="Bb", Pitch = 2, AltName="B Flat" };

Notice the Notes know nothing about Scales, or Chords.
Now we describe a scale
 Scales.Add(new Scale {  Name = "DIATONIC_MINOR_SCALE", Data= new int[] { 0, 2, 3, 5, 7, 8, 10 } });
 Scales.Add(new Scale {  Name = "AEOLIAN_SCALE", Data= new int[] { 0, 2, 3, 5, 7, 8, 10 } });
 Scales.Add(new Scale {  Name = "DORIAN_SCALE", Data= new int[] {0, 2, 3, 5, 7, 9, 10 } });

The numbers describe the distance from the root (notice the scale doesn't care nothing about a root note)
And finally a chord (you could do progressions using this same format)
  Chords.Add(new Chord {  Name = "DIMINISHED_SEVENTH", Data= new int[] { 4, 6, 9 } });
  Chords.Add(new Chord {  Name = "SEVENTH_FLAT_FIFTH", Data= new int[] { 4, 6, 10 } });
  Chords.Add(new Chord {  Name = "MINOR_SEVENTH_FLAT_FIFTH", Data= new int[] { 3, 6, 10 } });

Notice how the chord doesn't care about root notes, or scale.
I believe this is a good start for anyone looking to work with music theory in software engineering.
So im not smart enough to know how to find which chord the user typed, but since these are all list of integers. I think you can now know the root note, chord(s), and scale of any input. I think you could just brute force and find many possible chords. You could just store the users notes as a byte array in the database (the root note is assumed to be the first) and leave the "thinking" stuff to the compiler.


Calculating expected value of choosing red ball from 5 bins of different sizes

Question: MY ATTEMPT AT SOLUTION:
$P(win)=P(draw.at.least.3. red)=P(draw 3 R)+P(draw 4 R) + P(draw 5 R)$
Using the law of total probability:
$=P(bin1)*P(draw.3|bin1)+P(bin2)*P(draw.3|bin2)+P(bin3)*P(draw.3|bin3)+P(bin4)*P(draw.3|bin4)+P(bin5)*P(draw.3|bin5)+P(bin1)*P(draw.4|bin1)+P(bin2)*P(draw.4|bin2)+P(bin3)*P(draw.4|bin3)+P(bin4)*P(draw.4|bin4)+P(bin5)*P(draw.4|bin5)+P(bin1)*P(draw.5|bin1)+P(bin2)*P(draw.5|bin2)+P(bin3)*P(draw.5|bin3)+P(bin4)*P(draw.5|bin4)+P(bin5)*P(draw.5|bin5)$
Factoring this all out I simplify to get:
$P(bin1)*(P(draw.3|bin1)+P(draw.4|bin1)+P(draw.5|bin1))
+P(bin2)*(P(draw.3|bin2)+P(draw.4|bin2)+P(draw.5|bin2))
+P(bin3)*(P(draw.3|bin3)+P(draw.4|bin3)+P(draw.5|bin3)
+P(bin4)*(P(draw.3|bin4)+P(draw.4|bin4)+P(draw.5|bin4))
+P(bin5)*(P(draw.3|bin5)+P(draw.4|bin5)+P(draw.5|bin5))$
Since we are given the ratios of the sizes of the bins I tried to find the probability that way. So bin 5 is the smallest.
$P(bin1)=5*P(bin5)$
$P(bin2)=4*P(bin5)$
$P(bin3)=3*P(bin5)$
$P(bin4)=2*P(bin5)$
$P(bin5)=1*P(bin5)$
since the probabilities of all the bins need to add to 1 we have
$1=15*P(bin5) \implies P(bin5)=\frac{1}{15}$
Then I can calculate the remainder probabilities of bins.
$P(bin1)=1/3$
$P(bin2)=4/15$
$P(bin3)=1/5$
$P(bin4)=2/15$
$P(bin5)=1/15$
Then calculating $P(draw.3|bin1)=\frac{{12\choose 3}{13\choose 2}}{{25 \choose 5}}$
So I did these calculations for the remainder probabilities and got something around 0.58.
So the probability of winning 10 is 0.58 and the probability of losing $p$ is 0.42.
So then I set $E[X]=0$ and solved for how much you would lose if playing the game.
$10(0.58)+p(0.42)=0$
$p=-13.8$
This makes no sense. I'm losing more than I would win by playing the game?
I have a feeling I did this question all wrong. Can someone please help me with the solution?
Comment: Please use relevant titles. References to the difficulty of the question are subjective!
Comment: okay im sorry, will update
Comment: The phrasing implies to me that the net gain on a win would be $10-p$, not $10$. The equation you have implies a winner gets the price for playing back, plus 10 dollars on top of that. So your result says that with a win probability better than $1/2$, the player can afford to bet a bit more than $10$, usually getting it back plus $10$, and less often losing the bet.
Answer: Suppose a bin has $r$ red and $w$ white balls. The probability of pulling at least $3$ reds in a draw of $5$ from it is
$$\frac{\binom r3\binom w2+\binom r4\binom w1+\binom r5\binom w0}{\binom{r+w}5}$$
Computing this for each bin gives (from most frequent bin to least frequent)
$$\frac{739}{1610},\frac{627}{728},\frac{49}{143},\frac12,1$$
We now multiply the first fraction by $\frac5{5+4+3+2+1}$, this being the probability of choosing the corresponding bin; the second fraction is multiplied by $\frac4{15}$ and so on, and the results are added to give the final probability of winning:
$$\frac5{15}\frac{739}{1610}+\frac4{15}\frac{627}{728}+\frac3{15}\frac{49}{143}+\frac2{15}\frac12+\frac1{15}\cdot1=\frac{67289}{115115}$$
The expected number of dollars won is this fraction multiplied by $10$, i.e. $$\frac{134578}{23023}=5.8453720\dots$$
which is also the maximum amount you are willing to pay for the game.
Comment: wow this makes a lot more sense. thank you so much. so if I understand correctly, we win 10 with a probability of $67289/115115$ and our expected value is $5.84$. so when i was solving for $p$ i.e. the amount we lose, that was totally irrelevant right?
Comment: @user130306 Yes. No subtraction at all is needed in this problem.
Comment: actually looking at it, im a bit confused on how you got expected value. since with one X and p(x) we don't have a probability distribution unless p(x)=1
Comment: @user130306 It's OK that the probabilities don't add to one. It is just that the _value_ associated with the omitted probabilities is zero.


Two different series for $\frac{1}{x + 2}$

Question:
Find the appropriate power series for $f(x) = \frac{1}{x + 2} $

First method :  $\frac{1}{x + 2} =  \frac{1}{2(1 - (-\frac{x}{2}))} = \sum_{n=0}^\infty \frac{(-1)^n}{2^{n+1}}x^n$ , $|x|\lt2$
Second method : $\frac{1}{x + 2} = \frac{1}{1 - (-x-1)} = \sum_{n=0}^\infty (-x-1)^n$ , $-2 \lt x \lt 0$
Is there any problem in my answers ? Why these power series have different radii of convergence ?
Answer: There is no problem (in principle; I haven't checked the details). Note that one power series has general term $\frac{(-1)^n}{2^n}x^n$ and the other series has general term $(-1)^n(x+1)^n$.
A power series with general term $a_n(x-a)^n$ is said to be centered around $a$. For meromorphic functions (like rational functions), the radius of convergence for a power series turns out to be the distance from the center to the nearest pole.
$\frac{1}{x+2}$ has a pole at $x=-2$. Your first series is centered around $0$, and therefore has radius of convergence $2$, while your second series is centered at $-1$, and therefore has radius of convergence $-1$.
In fact, one can use this to gain a hint of the geometry of the complex plane using just the real numbers. The series of $\frac{1}{x^2+1}$  centered around $a\in\Bbb R$ has radius of convergence $\sqrt{a^2+1}$, hinting of a pole one unit away from $0$, perpendicular to the real line. We know its two poles as $\pm i$, of course.
Answer: Convergence is doomed to fail at $x=-2$, hence the convergence radius when developing around $a$ cannot be larger than the distance from $a$ to $-2$, i.e., $|a+2|$ (and for higher reasons, this is indeed the radius of convergence). So when developing around $0$, the radius is $2$, when developing around $-1$, it is $1$ (and when developing around $42$ it would be $44$)
Answer: Your computations are correct, but the radii of convergence aren't the same. It's $2$ for the first power series and $1$ for the second one.
Comment: If $x = -1$ then two series converge to different values . Why ?
Comment: @S.H.W What two different values are those?
Comment: @Arthur For the first series is $1$ and the second is $0$ .
Comment: @S.H.W When working with power series, you have to assume $0^0=1$. I would say you should use $0^0=1$ in general, but there are conventions to let it be undefined.
Comment: @Arthur Okay , thanks .
Answer: The first one is the series centered at $x=0$ while the second one is the series centered at $x=-1$ therefore the radius of convergence are different.


Reference slick instance from component (ngx-slick-carousel)

Question: I am having a tough time trying to reference the instance of a ngx-slick-carousel from within my component. I have a couple of carousels in a page and I need to unslick and intilize them when I toggle between the two. The only way at the moment that I have been able to reference the slick carousel from my component is if I use the afterChange method and pass the event object from my template.
For example
In Template
<ngx-slick-carousel
     class="carousel gallery-one"
     #galleryOne="slick-carousel"
     [config]="slideConfig"
     (afterChange)="afterChange($event)">

</ngx-slick-carousel>

In Component
afterChange(e) {
  console.log(e.slick);
}

How do I reference the slick instance like in the after change method from anywhere in my component? I tried a few ways and can't seem to get it to work. Any thoughts would be greatly appreciated.
Answer: Template
<ngx-slick-carousel
     class="carousel" #slickModal="slick-modal"
     #galleryOne="slick-carousel"
     [config]="slideConfig"
     (afterChange)="afterChange($event)">

</ngx-slick-carousel>

In the component use below code to do the changes
@ViewChild('slickModal') slickModal: SlickCarouselComponent;
To unslick use below code
this.slickModal.unslick();

Re initialize use below code
this.slickModal.initSlick();

Move to particular slide use below code
this.slickModal.slickGoTo(0);

Comment: Thank you so much for your time Rahul, I was able to get it working thanks to your help. There was an error with one piece to your answer. #slickModal="slick-modal" throws and error There is no directive with "exportAs" set to "slick-modal" I had to use #galleryOne="slick-carousel" and use @ViewChild('galleryOne') galleryOne;
Comment: Thanks @GalacticRanger i updated the answer. U can mark it as answered if it sloved your problem
Comment: How to get the current active slides? slickModal.slickCurrentSlide seems not working..


Why does my web server have more ifInOctets than ifOutOctets

Question: I need to track traffic in and out on our servers.  I have a nagios plugin that monitors either 32 or 64 bit counters for ifXXOctets.
$in_octet_table = '188.8.131.52.18.104.22.168.1.10.';
$in_octet_table_64 = '126.96.36.199.188.8.131.52.1.1.6.';
$out_octet_table = '188.8.131.52.22.214.171.124.1.16.';
$out_octet_table_64 = '126.96.36.199.126.96.36.199.1.1.10.';
I threw it at one of our web servers, using the 64 bit oids, and I was surprised to discover that the server reports many more inbound octets than outbound. (I made sure I was querying the proper interface.)
This seems counter intuitive for a web server.
Our webservers are Centos 7 cloud servers in Rackspace Cloud.
Any ideas?
Ed G
Comment: Does your webserver communicate with an appserver elsewhere?  Maybe an app on it connects to webservices elsewhere?  If it's Apache you can use `mod_logio` to enable [`%I` `%O` and `%S` logging options for request and response sizes](http://httpd.apache.org/docs/current/mod/mod_log_config.html).
Comment: Thanks, folks.  I think that they reason that in is higher than out is a combination of database and redis traffic.
Comment: Out on the server is in on the switch port, are you checking at the server or the switch?
Comment: for analyzing this net-flow can be really useful, you can see where the traffic is going
Comment: Byte counters tend to wrap, although I wouldn't expect an 64 bit counter to wrap very often.  Try gathering values over a period of time and see which value is increasing.
Comment: What had got the SNMP counters? Real network card on physical server, virtual interface on host or guess machine or interface on switch?
Answer: This is not uncommon. Your server might be accepting large uploads from clients, or making a request to a service on a different machine that then receives a large set of data. You need to understand your application model to know if this is unusual or not.
If you want to figure this out in more detail, try grabbing the counters from your switch as well as the server and see if the deltas move at the same rate (the absolute values will be different as they started counting at different times).
You can use things like Netflow if you want a more in-depth view of exactly what you are talking to, and which protocols it is using. ntop-ng is a neat tool for visualising flows, and supports more than just standard netflow.


Inserting a row in SQLAlchemy

Question: Been round the houses on this one, cant seem to get the right syntax.
All I want to do is insert a row into a table in SQLAlchemy. The documentation doesnt make sense to me thought:
class sqlalchemy.sql.expression.Insert(table, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs)

The closest I have come is
userChoices = meta.Session.query(model.CompUserChoices).filter(model.CompUserChoices.inmptl_user_name == postdict['userid']).filter(model.CompUserChoices.inmptl_option_id == postdict['leg']).all()

userChoices.insert({model.CompUserChoices.inmptl_user_name:postdict['userid']},\
                                        {model.CompUserChoices.inmptl_option_id:postdict['leg']},\
                                        {model.CompUserChoices.inmptl_comp_choice_id:newChoices[i]})

Could someone please tell me the correct syntax!
Answer: I'm not sure I understand what exactly you are trying to do, but adding a row is usually no harder than creating a model object and adding it to the session.
userChoices = model.CompUserChoices()
# Do stuff on userChoices
meta.Session.add(userChoices)
meta.Session.commit()  # if you have to commit manually

Comment: It is a MetaData object, but you often don't have to deal with it directly. More likely, you deal directly with a Session object.
Comment: Ok, thanks - I just got SQLAlchemy talking to a DB for the first time, with a Session object, so good to know I am on the right track. :-) *happy*

Inserting a row in SQLAlchemy


Android difference betwen API: 19 Android 4.4 (Kitkat) and Google APIs (Google Inc.) (API 19)

Question: Can any one tell what is difference between API 19: Android 4.4 (KitKat) and Google APIs (Google Inc.) (API 19) when we choose from Compile With: ??
Comment: you must read this : http://developer.android.com/google/play-services/setup.html
Answer: Android api level 19 means the android os version (kitkat). It contains the standard android packages(from Android Open Source Projects). But the google api 19 is the android api 19+ google api's like google settings and other packages provided by google.
Answer: From : Difference between target google APIs and target android
The google API includes Google Maps and other Google-specific libraries. The Android one only includes core android libraries.
As for which one to choose, you should go with the Android API until you find that you need the Google API; such as when you need Google Maps functionality.
Comment: copied from another [answer](http://stackoverflow.com/questions/5914775/difference-between-target-google-apis-and-target-android)
Answer: As answered here, Google API includes Google Play Services like Maps, Play Store, etc.
Answer: It is really pointless to use the Google API's now because most if not all things included in that have been deprecated and moved to google play services.
Selecting Google API will not do anything except maybe increase the size of your program. The difference being is in addition to the 4.4 SDK you would also get all the Google API stuff with it.
As answered here.


Parsing a question about the curl of a vector field on the surface of a sphere

Question: Given the following question and temptative answers:

I am not sure what the answer is for the $V(x,y)$ box.
Normally I would have converted the problem to spherical coordinates and solved it that way.
My guess is that when one is converting $\iint_M(\nabla\times F)\cdot dS$ to $\iint_DV(x,y)dydx$, there is a term that appears from the change in the differential that needs to be multiplied to the curl in order to obtain the correct term, but I am not sure what it should be.
Answer: We have that $\nabla \times \mathbf{F}=\langle2yzx^3,-3y^2zx^2,-2\rangle$ and we have $z=-\sqrt{\frac{1-x^2-y^2}{6}}$ since $z\leq0$. Then we have that
$$\begin{align}
\iint_M(\nabla\times F)\cdot dS & = \iint_M \langle2yx^3z,-3y^2x^2z,-2\rangle \cdot\langle-z_{x},-z_{y},1\rangle\,dA\\
& = \iint_M\langle-2yx^3\sqrt{\frac{1-x^2-y^2}{6}}, 3y^2x^2\sqrt{\frac{1-x^2-y^2}{6}}, -2\rangle \cdot\langle-z_{x},-z_{y},1\rangle\,dA\\
& = \frac{1}{6}\iint_M -2yx^4+3y^3x^2-12\,dA.
\end{align}$$
Then $$V(x,y)= \frac{-2yx^4+3y^3x^2-12}{6}.$$
Now we will convert to polar coordinates. Since $x^2+y^2=1$, we have that $r$ will range from $0$ to $1$ and since our figure is an ellipsoid we have that $\theta$ will range from $0$ to $2\pi$. Then our equation becomes
$$\begin{align}
\iint_DV(x,y)\,dy\,dx & = \frac{1}{6}\int_{0}^{1}\int_0^{2\pi}(-2r^5\cos^4(\theta)\sin(\theta)+3r^5\cos^2(\theta)sin^3(\theta)-12)r\,d\theta\,dr \\
& = \frac{1}{6}\int_{0}^{1}(0+0-12(2\pi))r\,dr \\
& = -2\pi\,r^2 \big|_{0}^{1} \\
& = -2\pi.
\end{align}$$


Why am I seeing different behavior between arrays allocated on the heap and the stack?

Question: I am inspecting the behavior of two 2D arrays in C++, one allocated from the stack, and one allocated from the heap.
I create two, 2D arrays of the same shape, and populate those arrays with some data.  Then I attempt to read the arrays in two different methods, the first being with the simple array index format "Arr[ROW][COLUMN]".  Then I read the arrays using a pointer dereference, and I get two different results for the heap allocated array, but identical results for the stack allocated array.  I am trying to understand why the results differ.  I would appreciate any clarification that someone can provide.  Thanks in advance.
The code I am running is below:
#include <iostream>

using namespace std;

int main(){

    int rows = 6;
    int columns = 3;

    // allocate from the stack.
    double q[rows][columns];

    // allocate from the heap.
    double ** a;
    a = new double*[rows];

    for(int i = 0; i < rows; ++i){
        a[i] = new double[columns];
    }

    // populate the arrays.
    for(int i = 0; i < rows; ++i){
        for(int j = 0; j < columns; ++j){
            a[i][j] = columns*i+j;
            q[i][j] = columns*i+j;
        }
    }

    cout << "*****************" << endl;
    cout << "Array indexing method." << endl;
    cout << "*****************" << endl;

    // print the heap allocated array using array indexing.
    for(int i = 0; i < rows; ++i){
        for(int j = 0; j < columns; ++j){
            cout << a[i][j] << '\t';
        }
        cout << endl;
    }

    cout << "*****************" << endl;

    // print the stack allocated array using array indexing.
    for(int i = 0; i < rows; ++i){
        for(int j = 0; j < columns; ++j){
            cout << q[i][j] << '\t';
        }
        cout << endl;
    }

    cout << "*****************" << endl;
    cout << "Pointer dereferencing method." << endl;
    cout << "*****************" << endl;

    // print the heap allocated array.
    for(int i = 0; i < rows; ++i){
        for(int j = 0; j < columns; ++j){
            cout << *(&a[0][0] + columns*i + j) << '\t';
        }
        cout << endl;
    }

    cout << "*****************" << endl;

    // print the stack allocated array.
    for(int i = 0; i < rows; ++i){
        for(int j = 0; j < columns; ++j){
            cout << *(&q[0][0] + columns*i + j) << '\t';
        }
        cout << endl;
    }
    cout << "*****************" << endl;

    // release the memory allocated to the heap.
    for(int i = 0; i < rows; ++i){
        delete[] a[i];
    }

    delete a;

    return 0;
}

And the results I obtain are:
*****************
Array indexing method.
*****************
0       1       2
3       4       5
6       7       8
9       10      11
12      13      14
15      16      17
*****************
0       1       2
3       4       5
6       7       8
9       10      11
12      13      14
15      16      17
*****************
Pointer dereferencing method.
*****************
0       1       2
0       3       4
5       0       6
7       8       0
9       10      11
0       12      13
*****************
0       1       2
3       4       5
6       7       8
9       10      11
12      13      14
15      16      17
*****************

And I can see that in the third block of output, the heap allocated array isn't being read properly, but the stack allocated array is.
Thanks again.
Comment: `double q[rows][columns];` VLAs aren't standard c++.
Comment: This isn't the problem, but do you really need the extra stuff that `std::endl` does? `'\n'` ends a line.
Comment: No, I don't, you're right for this example `\n` would have been fine.
Comment: It isn't related to allocating on the heap vs the stack, BTW. You could have allocated a single, contiguous block of memory on "the heap".
Comment: Yep, just allocating `arr = new double[rows * columns];` would yield better results. And then to access row 3, col 2 you could do: `arr[row * columns + col]`
Comment: @JoshM. -- [Related information](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048), if you want a contiguous 2D array and keep the `[ ][ ]` syntax.
Comment: @JoshM. -- Also, note that using the code at the SO link I provided, the `double **` created array shows the same results as the (non-standard) VLA version you posted,  [as seen here](https://ideone.com/f7CufD).
Comment: @JoshM.So the real issue is *how* you're allocating from the heap.  You can allocate from the heap, have contiguous data, and still use `double **`.  Your attempt allocated arrays in a naive fashion -- one allocation per row.
Answer: &q[0][0] gives you a pointer to the first double in a block containing rowsxcolumns doubles. While &a[0][0] gives you a pointer the first double in a block containing columns doubles (you've allocated it using a[0] = new double[columns];, remember?). So accessing it columns*i + j will be out of bounds and will triggers Undefined Behavior.
Comment: Ah, so my problem is that I'm assuming that the allocation from the heap was contiguous, but it actually isn't?  Presumably each row of columns is quite near the others, because in my output I am getting some of the appropriate values, just not where they should be.
Comment: @JoshM. Your heap allocations are not contiguous at all. You allocate 1 block containing `rows` count of pointers to double and then `rows` count of blocks containing `columns` count of doubles each. Though it makes sense that they are allocated one after another (with some padding in between) in this particular case since heap is not cluttered yet. But one should not rely on any assumptions of this kind about allocator behavior.
Comment: You might add this to your answer: the "pointer dereferencing method" invokes UB even on the stack-allocated array since it indexes past the bounds of the first subarray. Even though memory is contiguous, this is still illegal.
Answer: Arrays are usually a single allocation, on the stack in this case. The array value q[1][0] is being positioned right after q[0][columns-1]. The pointer implementation is allocating a disjoint block of memory for each row from the heap. By referencing beyond the end of the first row, you are in undefined behavior territory.
Answer: The stack based array is fully contiguous memory.  Your heap based one is one allocation per row, plus an allocation to hold all those allocations.  The memory for each allocation may be scattered throughout your heap in any order, with any amount of space between them.  You cannot assume that adding offsets to the base of the first row's allocation is valid if you go past its end, and it's certainly a bug to try to reach a separate allocation by walking far enough off the end of a previous allocation.
If you want to do what you're trying, change your new[] expression to be flattened into a single array:
double * q = new [rows * columns];

Then you can index into it as if it is a 2d array.
Also, in your original post you use the wrong type of delete call on a, which is also an array and needs to be deleted as one (with [] after it.)


How do I limit a taxonomy dropdown exposed filter to the terms used by nodes in view results?

Question: I'm trying to create a custom node search view, that takes Taxonomy terms as a filter (dropdown - autocomplete not an option). The problem I have, is that there could be >1000 terms and I would like to restrict the dropdown to show only the taxonomy terms that are already in use by the nodes returned in the initial view results. Does this make sense?
Can anyone advise if this is possible, and if so, how best to achieve it?
Answer: Like you can already read on the bug report from Drupal.org which you've copied from, a good solution is to use Views Selective Filters. It does exactly you're asking for.
Comment: Now, Views selective filters module is avilable for drupal7 but i want to used this functionality in drupal8.
Comment: @rahulkumar.it you should've mentioned that from the beginning.
Comment: Did you find a solution for this problem?


How do you play two chords at once on piano?

Question:
How would I play both of the chords in the bass clef at the same time? I'm self taught, and I can't seem to find an answer to this.
Comment: use the damper pedal
Answer: This notation looks rather silly to me. There is no way you can sustain the bottom D for the whole bar, and repeat it at the same time!
In practice, just ignore the whole-note bottom D. Hold down the other two whole-notes, and play the 8ths and dotted 8ths. You play the first two 8ths at the same time as the whole notes.
Comment: That sort of thing is not that unusual in piano notation. It indicates that the note should be sustained throughout the duration of the whole note while also being re-struck for the eighth notes, which implies that the damper or sostenuto pedal must be used to play it. I am familiar with an example from _Gymnopedie no. 1._
Comment: @BraddSzonye I'm familiar with it as well, but it's still silly. If the whole note D was intended to mean that, either (1) why isn't there a whole note F#, or (2) how do you play the F#'s differently from the D's? The notation of Gymnopedie #1 (at least in the first edition) doesn't make *that* silly mistake! I get the feeling the OP's example isn't a professionally produced score, otherwise the tie on the D wouldn't collide with the other notes in the bar. Assuming that any music score from the web "means what it says" is a bit risky.


Image of open donut under $\phi=z+\frac{1}{z}$

Question:
Source: Ch1 problem 11 on Function Theory of One Complex Variable by Greene and Krantz.
Let $S=\{z\in C: \frac{1}{2}<|z|<2\}$ and $\phi(z)=z+\frac{1}{z}$. Compute $\phi(S)$.

So far I have $$z=re^{i\theta}, \frac{1}{2}<r<2, 0\leq\theta<2\pi\implies \phi(z)=\left(r+\frac{1}{r}\right)\cos(\theta)+i\left(r-\frac{1}{r}\right)\sin(\theta)=Re^{i\varphi}$$
$$R=\sqrt{r^2+\frac{1}{r^2}+2\cos(2\theta)}$$
$$\varphi=\arctan\left(\frac{r^2-1}{r^2+1}\tan(\theta)\right)$$
but it doesn't look very helpful...
Comment: Don't focus on individual points. What curve is the circle $\lvert z\rvert = r$ mapped to?
Comment: Good. How does that help us determine the image $\phi(S)$?
Comment: Write $z=x+yi$, $\phi(z)=\bar{x}+\bar{y}i$, when$r\neq 1$, $\bar{x}$ and $\bar{y}$ satisfies $\frac{\bar{x}^2}{(r^2+1)/r^2}+\frac{\bar{y}^2}{(r^2-1)/r^2}=1$, which is an ellipse, and when $r=1$ the image is the segment from -2 to 2.
Comment: When r<1 it's hyperbola.
Answer: To understand the mapping behaviour of a holomorphic function $f$, it is often helpful to see how it transforms a family of curves - the most obvious candidates for such families are the lines of constant real or imaginary part, or a family of concentric circles and the rays emanating from the centre - and the preimages of such families, that is, the level curves of $\operatorname{Re} f,\; \operatorname{Im} f$ and of $\lvert f(z) - w_0\rvert$, $\arg\bigl(f(z) - w_0\bigr)$ respectively.
Another tool that often helps greatly is symmetry. If $f$ is even or odd, that helps understanding its behaviour, also if $f$ is real in the sense $f(\overline{z}) = \overline{f(z)}$. Other simple transformations are also something to look for.
Here, we have the symmetry $\phi(z) = \phi\bigl(\frac{1}{z}\bigr)$. Thus, to understand $\phi$, we only need to look at $1 \leqslant \lvert z\rvert$, the behaviour inside the unit disk follows from the behaviour outside it.
Since the domain $S$ we're interested in is an annulus centred at $0$, it is natural to look how $\phi$ behaves on the circles $\lvert z\rvert = r$, and on the rays $\arg z = \theta$.
For $r = 1$, we have $\frac{1}{z} = \overline{z}$, and hence $\phi(z) = 2\operatorname{Re} z$ on the unit circle. Thus the unit circle is mapped to the interval $[-2,2]$. Generally, you found that
$$\phi(re^{i\theta}) = \bigl(r + \tfrac{1}{r}\bigr)\cos \theta + i\bigl(r -\tfrac{1}{r}\bigr)\sin \theta.$$
For constant $r \neq 1$, that describes an ellipse with major semiaxis $r+\frac{1}{r}$ and minor semiaxis $\bigl\lvert r-\frac{1}{r}\bigr\rvert$, which is traversed counterclockwise for $r > 1$, and clockwise for $r < 1$.
To determine the image $\phi(S)$, that is already sufficient. Using the symmetry $\phi\bigl(\frac{1}{z}\bigr) = \phi(z)$, and the open mapping theorem, it then follows that $\phi(S)$ is a region bounded by the ellipse we get for $r = 2$, and since $\phi(\pm i) = 0$, it is the interior of that curve. We can write that in the form
$$\phi(S) = \{ z \in \mathbb{C} : \lvert z-2\rvert + \lvert z+2\rvert < 5\},$$
using that the foci of the ellipse $\{\phi(2e^{i\theta}) : 0 \leqslant \theta \leqslant 2\pi\}$ are $\pm 2$.
To more completely understand the mapping behaviour of $\phi$, one would also look at the curves $\bigl\{ \phi(re^{i\theta}) : \frac{1}{2} < r < 2\bigr\}$ for fixed $\theta$, and note that - for $\theta \neq k\frac{\pi}{2}$ - these are parts of the hyperbolas with foci $\pm 2$.


HWIOAuthBundle - FOSUserBundle - Symfony 2 - Redirect to custom path after login with facebook

Question: Reflected the following problem after the user login with the Facebook account: that is redirected to the following route /#_=_
How can I redirect it to this route instead: / Or to more to this /# ?
On the client side, I use the backbone.
Comment: Did you get answer to this question ?
Answer: Taking @Prynz's idea, we can get further and create a "redirect to page user comes from" this way:
1) In your firewall, take care to remove the following lines:
# security.yml

# ...
logout: true
logout:
    path: /logout
    target: /

As we will implment the logout ourselves to avoid redirecting to the specified target.
2) Add @Prynz's solution to your security.yml (or config.yml depending on your implementation)
oauth:
    resource_owners:
        google: "/login/check-google"
        facebook: "/login/check-facebook"
        twitter: "/login/check-twitter"
        sensio_connect: "/login/check-sensio-connect"
    login_path: /login
    failure_path: /login
    default_target_path: /welcome # THIS LINE CONTRIBUTES TO THE MAGIC
    oauth_user_provider:
        service: app.oauth_user_provider

3) In your routing, add a new controller (here, LoginController) before HWIO's imports:
fuz_app_login:
    resource: "@FuzAppBundle/Controller/LoginController.php"
    type:     annotation
    prefix:   /

4) Create the corresponding controller:
<?php

namespace Fuz\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class LoginController
{

    /**
     * @Route("/login", name="login")
     * @Method({"GET"})
     */
    public function loginAction(Request $request)
    {
        if ($this->getUser())
        {
            // already-logged user accessed /login
            return $this->redirect($request->headers->get('referer'));
        }
        else
        {
            // redirect to the login page
            return $this->forward('HWIOAuthBundle:Connect:connect');
        }
    }

    /**
     * @Route("/logout", name="logout")
     * @Method({"GET"})
     */
    public function logoutAction(Request $request)
    {
        // we do a manual logout just to redirect the user to where he comes from
        $this->container->get('security.context')->setToken(null);
        return $this->redirect($request->headers->get('referer'));
    }

    /**
     * @Route("/connect/{service}", name="connect")
     * @Method({"GET"})
     */
    public function connectAction(Request $request, $service)
    {
        // we overwrite this route to store user's referer in the session
        $this->get('session')->set('referer', $request->headers->get('referer'));
        return $this->forward('HWIOAuthBundle:Connect:redirectToService', array('service' => $service));
    }

    /**
     * @Route("/welcome", name="welcome")
     * @Method({"GET"})
     */
    public function welcomeAction()
    {
        // on login success, we're redirected to this route...
        // time to use the referer we previously stored.
        $referer = $this->get('session')->get('referer');
        if (is_null($referer))
        {
            return new RedirectResponse($this->generateUrl('home'));
        }
        return new RedirectResponse($referer);
    }

}

5) relax.
Comment: Thanks, happy to learn that this helps. For a more complete implementation, you can look at [this file](https://github.com/ninsuo/symfony2-quickstart/blob/master/src/Fuz/QuickStartBundle/Controller/UserController.php), [this one](https://github.com/ninsuo/symfony2-quickstart/blob/master/src/Fuz/QuickStartBundle/EventListener/LastRouteListener.php) and [that one](https://github.com/ninsuo/symfony2-quickstart/blob/master/src/Fuz/QuickStartBundle/Base/BaseController.php). Enjoy!
Comment: One thing I did differently was in the first file on line 27, inside the `else` I added `$this->get('session')->set('referer', $request->headers->get('referer'));` because my login page contains the links to my OAuth connect routes. So by setting the referer here I get the real referer, else the referer is always the login route for my OAuth users, as they always come via `/login`.
Comment: I also changed line 65 in that file to this as I was getting weird-ness `if(!strlen($referer) || preg_match("/login$/", $referer))`
Answer: You simply add default_target_path: /whatever/path/you/want to the oauth section under the firewall setup
oauth:
    resource_owners:
        facebook: '/login/check-facebook'
        google: '/login/check-google'
        windows: '/login/check-windows'
        twitter: '/login/check-twitter'
    login_path: /login
    failure_path: /login
    default_target_path: /whatever/path/you/want

Have a look at https://github.com/hwi/HWIOAuthBundle/issues/89
Answer: Redirect using javascript. Add following to the page.

Answer: If you want, you can redirect the users to the current page doing this way:
Add in your config.yml
hwi_oauth.target_path_parameter: "target_path"

In your view append the urls with:
&target_path=...

remember you can take the current route name with
app.request.get('_route')


Variável em uma url pelo powershell

Question: Estou montando um script que pega uma resposta de uma url e usa esta resposta para montar uma segunda url.
Exemplo:
$id = Invoke-WebRequest -uri "http://meusite/login?blablabla"
Esta primeira requisição vai me retornar um valor. Ex: 123
Minha variável fica com o valor correto. (123)
Quando vou montar uma segunda url que acontece o problema.
Estou usando:
Invoke-WebRequest -uri "http://meusite/blebleble=" $id
Queria que o resultado deste comando fosse "http://meusite/blebleble=123"
Mas está ficando assim:
http://meusite/blebleble=
123
Ai não consigo rodar a url.
O que uso entre a url e a variável?
Answer: Concatene a string e a variável colocando ela dentro das aspas e envolvido por um $( ):
Invoke-WebRequest -uri "http://meusite/blebleble=$($id)"

Encontrei essa informação nessa outra resposta.
Comment: Funcionou certinho. Muito obrigado!
Comment: De nada, mas não esqueça de marcar a pergunta como respondida, para que outros não acessem a pergunta para responder a solução que já existe!
Comment: Esta foi a minha primeira pergunta. Desculpa a falta de conhecimento, mas não estou encontrando a opção de marcar como respondido.. é alguma opção aqui na postagem ou altero o assunto com alguma tag?
Comment: Sem problemas, seja bem-vindo! Você deve encontrar um sinal de correto cinza ao lado esquerdo das respostas, simplesmente clique nela. Ela se tornará verde e a pergunta será marcada como respondida. Para mais informações e porque aceitar uma resposta, leia essa [resposta](https://pt.meta.stackoverflow.com/a/1079/140938)

Variável em uma url pelo powershell


Lifting a continuous linear functional

Question: A homework problem:

Let $\phi:X \twoheadrightarrow Y$ be a continuous surjection between compact Hausdorff spaces. Let $\lambda$ be a continuous linear functional on $C(Y)$.
Show that there is a continuous linear functional $\theta$ on $C(X)$ such that:

$\|\theta\|=\|\lambda\|$
$\theta(f \circ \phi)=\lambda(f)$ and any $f \in C(Y)$

My attempt: I am stuck about in the beginning. I read about the Hahn-Banach theorems in Rudin's functional analysis. Those theorems seem relevant because they talk about existence of functionals, but there are several versions and I'm confused about which of them to use, if any (I am allowed to quote this book). I think maybe the second condition can tell me how to define a functional on some subspae of $C(X)$ and then use an "extension theorem" (that's how some of those theorems are refered to in the book), but that's just general intuition.
Answer: Hints:
1) Show that $E=\{f\circ \varphi:f\in C(Y)\}$ is linear subsapce of $C(Y)$.
2) Show that $f_1\circ\varphi=f_2\circ\varphi\implies f_1=f_2$
3) Using 2) show that you have well defined functional $\theta_0:E\to\mathbb{C}:g\mapsto \lambda(f)$ where $g=f\circ\varphi$.
4) Show that $\Vert f\circ\varphi\Vert=\Vert f\Vert$
5) Using 4) prove that $\Vert\theta_0\Vert=\Vert\lambda\Vert$
6) Using Hahn-Banach get norm preserving extenesion $\theta$ of $\theta_0$. This will be the desired functional

Lifting a continuous linear functional


Harmonic functions of these chords

Question: I found this classical chord progression. What are the harmonic functions of these chords, especially the Adim.
1Amin Bdim Amin A Bb Adim Amin E Amin
I got it from here youtube.com/watch?v=zgBPiHTPCdg. The key here is C minor though.
Comment: I'm just asking for the harmonic functions. Particularly interested in what the Adim is doing here. Not asking you for the meaning of life.
Comment: @MiaLee the video you linked (youtube.com/watch?v=zgBPiHTPCdg) shows the chord progression (which you didn't accurately transpose to Am), with harmonic analysis. Are you asking how viio chords work?
Comment: There doesn't always have to be a 'scientific' reasoning behind a chord sequence. And often, the 'reasoning' is man-made anyway. Ever asked why cows moo, but horses don't?!
Comment: That's an easier one - 42!! Didn't mean to offend. Dim chords often exist to 'change key' or modulate. Doesn't look like it here though...
Comment: Give us some context? Like notation of the whole piece (if you mean the same by 'classical' as I do) or at least point us at a recording? Is this your own analysis, or are you quoting chord symbols? Chord progressions don't HAVE to be 'functional'. Sometimes they just meander around.
Comment: I got it from here https://www.youtube.com/watch?v=zgBPiHTPCdg. The key here is C minor though.
Comment: Why did you link to an ad? Is this question spam?
Comment: @Tim: Q: "Ever asked why cows moo, but horses don't?" A: "Nay".
Answer: Based on the reference you provided in comments your version of the chords in the key of A minor is incorrect and also leaves out the all important bass notes/inversions:
G#o7/B Am/C A7/C# Bb/D D#o7 Am/E E7 Am
If you look at this screenshot you will see the chords in the key of Cm at the top with the analysis directly below them. The analysis is also in the lower right corner:

If you want to understand this beyond a bunch of Roman numerals, numbers and slashes, just listening to it reveals that the first 6 chords of this progression has a chromatically ascending bass line which has a dramatic building quality to it.
Another important aspect of this progression is that chords 1,3,5 and 7 are either diminished or dominant chords that resolve to chords 2,4,6 and 8. This gives an added tension-release as you go from chord to chord.
Answer: The Adim chord is known as a "common-tone" chord. Common-tone diminished chords are often used to extend a tonic chord.1 In this case, it's acting to delay the tonic chord or smooth the transition from the Bb chord.
Here is each chord by function:

Amin:          Tonic
Bdim (=G#dim): Leading-tone chord; expansion of tonic
Adim:          Tonic
A:             Tonic major
Bb:            Neapolitan; more tonic expansion
Adim:          C.T.dim; transition from N to tonic
Amin:          Tonic
E:             Dominant
Amin:          Tonic

1. For more on common-tone diminished chords, see Understanding function of diminished chord in Paganini's 4th caprice

Harmonic functions of these chords


Image captcha module not showing in admin after updating Drupal to 7.35

Question: I have a site with Captcha module installed and Image captcha submodule working perfectly before upgrading.
I followed the recommended steps, and even did it in a nearly identical test site. Everything worked perfectly in the test site. But when I applied the changes (updating from previous core version) in production, I realized that Image captcha is not only not working anymore: it even doesn't appear as submodule in Admin.
The folder is there but is no longer detected. I am thinking of reinstalling the complete Captcha module, but I am very worried about the rest of modules.
Going back to my backup of my database is not an option as I realized the problem after 2 days and that means losing a lot of data (if I would restore my backup).
Any tip on what could be causing this?
Answer: I discovered that the upgrade has renamed the path of submodule Image captcha to sites/all/modules/captcha0/image_captcha instead of the correct sites/all/modules/captcha/image_captcha (renamed filename value in table system of database. Physical path not changed). After that I have been forced to reinstall the module.
This is simply not serious, This seems a Drupal or a module bug and I have spent very bad hours trying to figure out what went wrong when I followed steps one by one and was very cautious.


Complex strings of array sorting using Javascript

Question: I have a requirement to sort array of strings which contains numbers, letters and symbols in which the strings starting with letters will be on top followed by numbers and then symbols.
An example:
let stringArray =['def', '%rec', '456', '^we', '123', 'abc']

//desired output
['abc', 'def', '123', '456', '%rec', '^we']

Code that I am using
stringArray.sort(function(a, b){ return a - b })

Comment: The answer from Jack seems to be perfect for your needs
Comment: you want to compare  string  without symbols characters?
Comment: What issue are you having? Please supply a minimal reproducible example.
Comment: **Your desired output does not correspond to any logical order**. at least because in ascii the numbers are before the letters
Answer: This sort function will give you the results you want; it checks for matching types of string (starting with alphabetic, numeric or symbol) and compares directly if so, otherwise it returns a value appropriate to the desired ordering of alphabetic, numeric or symbol in the result. Note that I've assumed that you want to sort numeric strings in numeric order (i.e. 20 comes before 100), if that is not the case, replace
return parseInt(a) - parseInt(b);

with
return a.localeCompare(b);

const msort = (a, b) => {
  if (a.match(/^[a-z]/i)) {
    if (b.match(/^[a-z]/i)) {
      return a.localeCompare(b);
    }
    else {
      return -1;
    }
  } else if (a.match(/^[0-9]/)) {
    if (b.match(/^[0-9]/)) {
      return parseInt(a) - parseInt(b);
    }
    else if (b.match(/^[a-z]/i)) {
      return 1;
    }
    else {
      return -1;
    }
  }
  else {
    if (b.match(/^[^a-z0-9]/i)) {
      return a.localeCompare(b);
    }
    else {
      return 1;
    }
  }
}

input = ['def', '%rec', '456', '^we', '123', 'abc'];

input.sort(msort);
console.log(input);
Comment: @SaikatSaha `a15y%` will sort before `a16y#` because `5` comes before `6`. I think what you're trying to explain might take more than can reasonably fit into comments. I would suggest asking another question - you can refer back to this one - and give a more detailed explanation of how you want to sort and examples of values that are not sorting the way you want them to with this code.
Comment: How can I check the above sequence to work for the whole string
Comment: @SaikatSaha I'm not sure what you mean?
Comment: First of all Thanks for the solution, the solution sequence applies for the first character, can it be applied for the whole length, in case the string is very complex i.e., (a16y# and a15y%) then a15y% should come above the other
Comment: Yes @Nick you are right let me give you a proper example(a16y#, a15y%, aa5y%, ab5y%), as per above solution(a15y%, a16y#, aa5y%, ab5y%) but what I am expecting is it should be applied throughout the string that means (aa5y%, ab5y%, a15y%, a16y#)
Comment: @SaikatSaha I'm still not completely with you. It seems like it might be too complicated to explain through comments, I would suggest asking another question.


Detecting ENTER key in C++

Question: I have a program like this,
char name[100];
char age[12];
cout << "Enter Name: ";
cin >> name;

cout << "Enter Age: ";
cin >> age;

Now age is a optional field, so user can simply press ENTER key and have that value as NULL. But the problem is, cin doesn't take ENTER key and just stay there waiting for a valid keyboard char or numerical input.
I think the problem is because cin needs a valid input and thus stays there forever.
So i tried below approach to detect ENTER key press for Age.
cout << "Enter Age: ";
if (cin.get() == '\n') {
            cout << "ENTER WAS PRESSED" << endl;
        }

Now as soon as user presses ENTER key after entering a NAME, it goes straight to the IF condition.
I also tried:
getline(cin, age);

But that also simply doesn't stop at cout << "Age: "; waiting for an input from the user.
The user can either a valid age or simply press ENTER key not to enter a age.
For the below Code:
cout << "Enter Name: ";
        cin >> name;

        cout << "Enter Age: ";
        if (cin.get() == '\n') {
            cout << "ENTER WAS PRESSED" << endl;
        }

The Output is:
Enter Name: asdf
Enter Age: ENTER WAS PRESSED

I want the cursor to wait at Enter Age: _
How can i do that?
Comment: If you want the cursor to wait at `Enter Age: _`, then where do you want to see the output?
Comment: Do you want the cursor to wait at enter age even when user presses enter?
Answer: Have you tried this?:
cout << "Press Enter to Continue";
cin.ignore();

also check out this question
Comment: I cant use `cin >> myString`, but I can use `std::getline(std::cin, myString)` after `cin.ignore()`
Comment: cin.ignore() doesn't work. It gives signal: terminated, I suspect be it thinks it's read an EOL.
Answer: One way to do it is to use getline to read the input, then test the length of the input string. If they only press enter, the length of the line will be 0 since getline ignores newlines by default.
std::string myString = "";

do {
     std::cout << "Press ENTER to exit" << std::endl;
     std::getline(std::cin, myString);
} while (myString.length() != 0);

std::cout << "Loop exited." << std::endl;

Answer: You are several problems with your code:

you are calling operator>> with char[] buffers without protection from buffer overflows.  Use std::setw() to specify the buffer sizes during reading.  Otherwise, use std::string instead of char[].
cin >> name reads only the first whitespace-delimited word, leaving any remaining data in the input buffer, including the ENTER key, which is then picked up by cin >> age without waiting for new input.  To avoid that, you need to call cin.ignore() to discard any unread data.  Otherwise, consider using cin.getline() instead (or std::getline() for std::string), which consumes everything up to and including a linebreak, but does not output the linebreak (you should consider using this for the name value, at least, so that users can enter names with spaces in them).
by default, operator>> skips leading whitespace before reading a new value, and that includes line breaks.  You can press ENTER all you want, operator>> will happily keep waiting until something else is entered.  To avoid that, you could use std::noskipws, but that causes an unwanted side effect when reading character data - leading whitespace is left in the input buffer, which causes operator>> to stop reading when it reads a whitespace character before any user input is read.  So, to avoid that, you can use cin.peek() to check for an entered linebreak before calling cin >> age.

Try something more like this:
#include <iostream>
#include <limits>
#include <iomanip>

char name[100] = {0};
char age[12] = {0};

std::cout << "Enter Name: ";
std::cin >> std::setw(100) >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
if (!std::cin.getline(name, 100))
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
*/

std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
    std::cin >> std::setw(12) >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Or:
#include <iostream>
#include <string>
#include <limits>

std::string name;
std::string age;

std::cout << "Enter Name: ";
std::cin >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, name);
*/

std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
    std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, age);
*/

Answer: When you use cin.get() compiler will take the lastly used Enter(i.e Enter key pressed while entering name). so you need to make the compiler to avoid the lastly entered Enter key to do so you need to include cin.ignore() before using cin.get().
Answer: You might want to cin into a char variable and then check if it the ENTER key, and if not, continue getting characters and turn them into an int (using character substraction and all that). It is not a very pretty solution but it is the first thing that came into my head.
Answer: Just use:
std::cout << "\nPress Enter to continue";
fgetc(stdin);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

See more at http://www.cplusplus.com/reference/cstdio/fgetc/
Answer: you can include the "conio.h" library
and use getch();
#include <conio.h>
#include <iostream>

using namespace std;

int main(){

cout << "press enter";
getch();

return 0;

}

Detecting ENTER key in C++


Visualizing decision tree in scikit-learn

Question: I am trying to design a simple Decision Tree using scikit-learn in Python (I am using Anaconda's Ipython Notebook with Python 2.7.3 on Windows OS) and visualize it as follows:
from pandas import read_csv, DataFrame
from sklearn import tree
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

dotfile = open("D:/dtree2.dot", 'w')
dotfile = tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
system("dot -Tpng D:.dot -o D:/dtree2.png")

However, I get the following error:
AttributeError: 'NoneType' object has no attribute 'close'

I use the following blog post as reference: Blogpost link
The following stackoverflow question doesn't seem to work for me as well: Question
Could someone help me with how to visualize the decision tree in scikit-learn?
Comment: Can you debug the `export_graphviz` line as this is returning `None` so some error has occurred
Comment: Does the file `dtree2.dot` get created?
Comment: Yes. dtree2.dot does get created.
Comment: Scikit-learn from version `0.21` has method [`plot_tree`](https://scikit-learn.org/stable/modules/generated/sklearn.tree.plot_tree.html) which is much easier to use than exporting to graphviz. Anyway, there is also very nice package [`dtreeviz`](https://github.com/parrt/dtreeviz/tree/master/dtreeviz). Here is a comparison of the visualization methods for sklearn trees: [blog post link](https://mljar.com/blog/visualize-decision-tree/)
Answer: Here is one liner for those who are using jupyter and sklearn(18.2+)  You don't even need matplotlib for that. Only requirement is graphviz
pip install graphviz

than run (according to code in question X is a pandas DataFrame)
from graphviz import Source
from sklearn import tree
Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))

This will display it in SVG format. Code above produces Graphviz's Source object (source_code - not scary) That would be rendered directly in jupyter.
Some things you are likely to do with it
Display it in jupter:
from IPython.display import SVG
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
SVG(graph.pipe(format='svg'))

Save as png:
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
graph.format = 'png'
graph.render('dtree_render',view=True)

Get the png image, save it and view it:
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
png_bytes = graph.pipe(format='png')
with open('dtree_pipe.png','wb') as f:
    f.write(png_bytes)

from IPython.display import Image
Image(png_bytes)

If you are going to play with that lib here are the links to examples and userguide
Comment: This is how to install in Anaconda: `conda install -c conda-forge python-graphviz`
Answer: sklearn.tree.export_graphviz doesn't return anything, and so by default returns None.
By doing dotfile = tree.export_graphviz(...) you overwrite your open file object, which had been previously assigned to dotfile, so you get an error when you try to close the file (as it's now None).
To fix it change your code to
...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...

Comment: This does get rid of the error but the following command doesn't produce the plot:
system("dot -Tpng D:/dtree2.dot -o D:/dtree2.png"). However, dtree2.dot file gets created.
Comment: I don't know anything about using graphviz sorry. It's best if you ask a new question as that's a different problem entirely.
Answer: If, like me, you have a problem installing graphviz, you can visualize the tree by

exporting it with export_graphviz as shown in previous answers
Open the .dot file in a text editor
Copy the piece of code and paste it @ webgraphviz.com
Answer: Scikit learn recently introduced the plot_tree method to make this very easy (new in version 0.21 (May 2019)). Documentation here.
Here's the minimum code you need:
from sklearn import tree
plt.figure(figsize=(40,20))  # customize according to the size of your tree
_ = tree.plot_tree(your_model_name, feature_names = X.columns)
plt.show()

plot_tree supports some arguments to beautify the tree. For example:
from sklearn import tree
plt.figure(figsize=(40,20))
_ = tree.plot_tree(your_model_name, feature_names = X.columns,
             filled=True, fontsize=6, rounded = True)
plt.show()

If you want to save the picture to a file, add the following line before plt.show():
plt.savefig('filename.png')

If you want to view the rules in text format, there's an answer here. It's more intuitive to read.
Answer: Alternatively, you could try using pydot for producing the png file from dot:
...
tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file

import pydot
dotfile = StringIO()
tree.export_graphviz(dtreg, out_file=dotfile)
pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
...

Comment: see new version pydotplus in comment @Alexey Shrub
Answer: The following also works fine:
from sklearn.datasets import load_iris
iris = load_iris()

# Model (can also use single decision tree)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10)

# Train
model.fit(iris.data, iris.target)
# Extract single tree
estimator = model.estimators_[5]

from sklearn.tree import export_graphviz
# Export as dot file
export_graphviz(estimator, out_file='tree.dot',
                feature_names = iris.feature_names,
                class_names = iris.target_names,
                rounded = True, proportion = False,
                precision = 2, filled = True)

# Convert to png using system command (requires Graphviz)
from subprocess import call
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])

# Display in jupyter notebook
from IPython.display import Image
Image(filename = 'tree.png')

You can find the source here
Answer: I copy and change a part of your code as the below:
from pandas import read_csv, DataFrame
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

After making sure you have dtree, which means that the above code runs well, you add the below code to visualize decision tree:
Remember to install graphviz first: pip install graphviz
import graphviz
from graphviz import Source
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
graph = graphviz.Source(dot_data)
graph.render("name of file",view = True)

I tried with my data, visualization worked well and I got a pdf file viewed immediately.
Answer: You can copy the contents of the export_graphviz file and you can paste the same in the webgraphviz.com site.
You can check out the article on How to visualize the decision tree in Python with graphviz for more information.
Answer: Simple way founded here with pydotplus (graphviz must be installed):
from IPython.display import Image
from sklearn import tree
import pydotplus # installing pyparsing maybe needed

...
dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

Answer: Here is the minimal code to have a nice looking graph with just 3 lines of code :
from sklearn import tree
import pydotplus

dot_data=tree.export_graphviz(dt,filled=True,rounded=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_png('tree.png')

plt.imshow(plt.imread('tree.png'))

I just added the plt.imgshow to view the graph in Jupyter Notebook. You can ignore it if you are only interested in saving the png file.
I installed the following dependencies:
pip3 install graphviz
pip3 install pydotplus

For MacOs the pip version of Graphviz did not work. Following Graphviz's official documentation I installed it with brew and everything worked fine.
brew install graphviz

Comment: That's what really worked to me. I recommend to anyone seeking a solution to try with load_iris example database from sklearn.datasets.
Answer: If you run into issues with grabbing the source .dot directly you can also use Source.from_file like this:
from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')


Will downloaded WSUS updates be applied on shutdown if the schedule is per weekday?

Question: Assume the following scenario:
I have a schedule specified in Group Policy for a server that says "Apply updates on Saturday at 11pm".
I approve updates in WSUS on Monday at 9am.
Updates should be downloaded some time during the week, but not applied automatically until Saturday.
If I shut the server down some time before Saturday at 11pm, will the updates that have been downloaded be applied immediately?
Edit: Also, what about a remote shutdown using shutdown \\machinename? I know there is an Install and Shut Down option in the UI, but what about across a few dozen servers?
Answer:
If I shut the server down some time before Saturday at 11pm, will the updates that have been downloaded be applied immediately?

Not unless you specify "Install Updates and Shut Down," and I'm not sure if that's an option on Windows Server OSes.
Either way, it's a silly request.  You shouldn't shut your servers down - this misses the whole point of having a server.  Restart your server after installing updates, otherwise, leave it on.
Comment: Not so silly, since the background around this question is a the fact that I've got a datacenter power maintenance operation happening during the middle of a scheduled patch window, and I'm trying to ascertain whether the servers will patch when gracefully shut down.
Comment: @Urit No, it's still silly.  Patching them and shutting them down are two completely separate events, and should be treated as such.  Set the servers to apply patches before the maintenance window, then shut them down.
Comment: Whether or not I _want_ them to patch was not asked - I am trying to find out if they _will_ patch on shutdown (probably using shutdown.exe to request them to shut down), assuming patches have already been downloaded but not installed.
Answer: No they aren't. You need to check the option to shutdown after updates are installed.
Answer:
If I shut the server down some time before Saturday at 11pm, will the
  updates that have been downloaded be applied immediately?

In my experience, no.  They'll wait until you bring them back up and apply their patches then.
As for shutdown /s /m \\machinename, no, according to this question and answer.
There's an undocumented and unsupported wuauclt /updatenow command that might help.  There's also some info on how to update Server Core that might help you script updates.