Detecting Enter keypress on VB.NET

Question: I am using .NET 3.5 framework of VB.NET 2008.
I have some textboxes in my form. I want the tab-like behavior when my user presses ENTER on one of my textboxes. I used the following code:
Private Sub txtDiscount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDiscount.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If
End Sub

But it doesn't work for me.
What is the solution?
Comment: It is a bad idea to press Tab when a user presses Enter. You make user experience inconsistent, which may be okay for home users. Power users, however, will hate working with your software.
Comment: works for me, although using SendKeys wouldn't be my ideal solution
Comment: when you say "But It doen't work for me.", please describe exactly what happens. we don't have crystal balls....
Comment: AcceptsReturn are set for Multiline Edit Control. But I have single Line TextBox.
Answer: In the KeyDown Event:
 If e.KeyCode = Keys.Enter Then
       Messagebox.Show("Enter key pressed")
 end if

Comment: `KeyCode` doesn't seem to be a property of KeyPressEventArgs.
Comment: @Panzercrisis: This only works in the KeyDown Event, not in the KeyPress event.
Answer: Make sure the form KeyPreview property is set to true.
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If

End Sub

Comment: This works for me even without the KeyPreview property set to true.
Answer: There is no need to set the KeyPreview Property to True. Just add the following function.
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, _
                                           ByVal keyData As System.Windows.Forms.Keys) _
                                           As Boolean

    If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
        SendKeys.Send("{Tab}")
        Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Now, when you press Enter on a TextBox, the control moves to the next control.
Comment: It moves to the next control everytime! It needs to change your `If msg.WParam.ToInt32() = CInt(Keys.Enter) Then` into `If msg.WParam.ToInt32() = CInt(Keys.Enter) AndAlso TypeOf Me.ActiveControl Is TextBox Then` to make it only works for text boxes
Comment: That's almost the same as my method, except at a lower level. Did you even try my code? It does work...
Answer: I'm using VB 2010 .NET 4.0 and use the following:
Private Sub tbSecurity_KeyPress(sender As System.Object, e As System.EventArgs) Handles tbSecurity.KeyPress
    Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
    If tmp.KeyChar = ChrW(Keys.Enter) Then
        MessageBox.Show("Enter key")
    Else
        MessageBox.Show(tmp.KeyChar)
    End If

End Sub

Works like a charm!
Answer: You can use PreviewKeyDown Event
Private Sub txtPassword_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtPassword.PreviewKeyDown
    If e.KeyCode = Keys.Enter Then
        Call btnLogin_Click(sender, e)
    End If
End Sub

Tested on VB.NET 2010
Answer: Private Sub SomeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles SomeTextBox.KeyPress

    If Asc(e.KeyChar) = 13 Then
         MessageBox.Show("Enter pressed!")
         e.Handled = True
    End If

End Sub

Comment: Don't forget about backspace: `Asc(e.KeyChar) = 8`
Answer: also can try this:
If e.KeyChar = ChrW(Keys.Enter) Then
     'Do Necessary code here
End If

Comment: -1: This is pretty much the same answer as http://stackoverflow.com/a/15994134/76337
Comment: Actually, when I tried the linked answer, it wouldn't work in VS2012.  Adding the 'ChrW' did the trick.  It IS, however, similar to http://stackoverflow.com/a/2752456/2711474
Answer: I see this has been answered, but it seems like you could avoid all of this 'remapping' of the enter key by simply hooking your validation into the AcceptButton on a form. ie. you have 3 textboxes (txtA,txtB,txtC) and an 'OK' button set to be AcceptButton (and TabOrder set properly). So, if in txtA and you hit enter, if the data is invalid, your focus will stay in txtA, but if it is valid, assuming the other txts need input, validation will just put you into the next txt that needs valid input thus simulating TAB behaviour... once all txts have valid input, pressing enter will fire a succsessful validation and close form (or whatever...) Make sense?
Answer: I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.
You would have to first handle the PreviewKeyDown on the textbox so when  ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:
Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.
Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
        Textbox1.Focus()
    End If
End Sub

Answer: Use KeyDown Event instead of KeyPress
If e.KeyCode = Keys.Enter Then
   MsgBox ("You pressed enter")
End if

Note: Make sure you don't have ACCEPT BUTTON set on your form. AcceptButton set it to 'none'
Answer: Private Sub BagQty_KeyPress(sender As Object, e As KeyPressEventArgs) Handles BagQty.KeyPress

        Select e.KeyChar

            Case Microsoft.VisualBasic.ChrW(Keys.Return)
                PurchaseTotal.Text = Val(ActualRate.Text) * Val(BagQty.Text)
        End Select

    End Sub

Answer: use this code this might help you to get tab like behaviour when user presses enter
 Private Sub TxtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtSearch.KeyPress
    Try
        If e.KeyChar = Convert.ToChar(13) Then
           nexttextbox.setfoucus
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Answer: Use this code it will work OK.
You shall click on TextBox1 and then go to event and select Keyup and double click on it. You wil then get the lines for the SUB.
Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Enter Then
        MsgBox("Fel lösenord")

    End If
End Sub

Comment: So 7 years later a suggestion with a Swedish Message ;) Maybe match his issue?
Comment: This will be better with a KeyDown, otherwise when you press Enter on the keyboard to dismiss it, and you get the same message alert, and you're stuck in a look.
Answer: The following code will work.
Public Class Form1
    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If e.KeyChar = Convert.ToChar(13) Then
            MsgBox("enter key pressd ")
        End If
    End Sub
End Clas

Public Class Form1
    Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            MsgBox("enter key pressd ")
        End If
    End Sub
End Class

Answer: I have test this code on Visual Studio 2019
Its working superb
Just Paste it into you form code
it will work on all textboxs on same form
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
    Dim keyCode As Keys = CType(msg.WParam, IntPtr).ToInt32
    Const WM_KEYDOWN As Integer = &H100

    If msg.Msg = WM_KEYDOWN AndAlso keyCode = Keys.Enter _
     AndAlso Me.ActiveControl.GetType.Name = "TextBox" Then
        Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        Return True

    End If
    Return MyBase.ProcessCmdKey(msg, keyData)

End Function

Answer: Someone suggested "PreviewKeyDown".
Given this code and results entering '1 2 tab 3' one can see that "PreviewKeyDown" can be used only to redirect a key (that would normally not pass thru "KeyDown/Press/Up") to it, so you can act upon it. Note that the key is NOT added to "Text". You can only remember having seen the key in Preview and then act upon this saved information in KeyDown/Up/Press
Dim eDotIsInputKey As Boolean = False
Private Sub AkteNr_TextChanged(sender As Object, e As EventArgs) Handles AkteNr.TextChanged
    Debug.WriteLine("ch !" + AkteNr.Text + "!")
End Sub
Private Sub AkteNr_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles AkteNr.PreviewKeyDown
    If e.KeyCode = Keys.Tab Then
        e.IsInputKey = True
    End If
    eDotIsInputKey = e.IsInputKey
    Debug.WriteLine("pr " + CStr(e.KeyCode) + " " + CStr(e.IsInputKey))
End Sub
Private Sub AkteNr_KeyDown(sender As Object, e As KeyEventArgs) Handles AkteNr.KeyDown
    Debug.WriteLine("kd " + CStr(e.KeyCode) + " " + CStr(eDotIsInputKey))
End Sub

Result if entering 1 then 2 then tab then 3:
pr 49 False
kd 49 False
ch !1!
pr 50 False
kd 50 False
ch !12!
pr 9 True
kd 9 True
pr 51 False
kd 51 False
ch !123!

Detecting Enter keypress on VB.NET


Spring: constructor injection of primitive values (properties) with annotation based configuration

Question: I'm trying to configure a class with Annotation based configuration in Spring 3, which takes primitive values as its constructor arguments:
@Component
class MyBean {
  MyBean(String arg1, String arg2) {
    // ...
  }
}

And an application context like this:
<beans [...]>
  <context:component-scan base-package="com.example" />
  <context:property-override location="/WEB-INF/example.properties" />
</beans>

I'm trying to find some way to specify that the constructor arguments should be taken from the properties file. Apparently this does work with constructors that take regular beans (e.g. MyClass(Bean bean1, OtherBean bean2)), but just properties?
I have also tried annotating the constructor arguments with Spring 3's @Value annotation and an EL expression for the value, like @Value("#{prop.Prop1}") arg1, but that doesn't seem to work either.
Answer: The following code works fine with <context:property-placeholder .../>:
@Component
public class MyBean {
    @Autowired
    public MyBean(@Value("${prop1}") String arg1, @Value("${prop2}") String arg2) {
        // ...
    }
}

But <context:property-override .../> is a very specific thing, it's not suitable here.
Comment: Will the property file have "myBean.prop1=foo" or just "prop1=foo"? That is, are the properties scoped by bean name?
Comment: Property file will have `prop1=foo`. If you need `myBean.prop1=foo`, write `@Value("${myBean.prop1}")`. It's the way how `` works.


Can't send data from ajax call to php to get database value

Question: I've a problem to retrieve my data from database.
In my Ajax call, i have tested my form values and it worked.
$(document).ready(function(){
$("form#form").submit(function(event) {
    event.preventDefault();
    var color = $('#Color').val();
    var radio = $('input[name="filter_opties"]:checked').val();
    filter(color, radio);
    $.ajax({
        type: "POST",
        url: "db_querys.php",
        data: {'color' : color, 'radio' : radio},
        success: function(data) {
            alert(data);
        }
    });
});

But in my db_querys.php, I can't get the values of color and radio.
<?php
$gekozenGemeente = $_POST['color'];
$gekozenCategorie = $_POST['radio'];

if($gekozenGemeente != null)
  {
  echo $gekozenGemeente . $gekozenCategorie;
  }
else
  {
  echo "
 Values are null";
  }
?>

This is my form:
<form id = "form" action="#" method="post" >

    Selecteer uw gemeente:

    <select name="Color" id="Color">
        <option value="heemstede">Heemstede</option>
        <option value="bloemendaal">Bloemendaal</option>
    </select>

    Radio Buttons :

    <input type="radio" id="radio1" name="filter_opties" value="Betaald">Betaald

    <input type="radio" id="radio2" name="filter_opties" value="Vergunning">Vergunning

    <input type="radio" id="radio3" name="filter_opties" value="Blauwe zone">Blauwe zone

    <input id= "submit" name="submit" type="submit" value="Get Selected Values" onclick="filter()">
</form>

Can you guys explain what I'm missing?
EDIT:     Added the filter function.
function filter(color, radio){

    var locations = <?= json_encode($markers_json ); ?>;
    var locations2 = JSON.parse(locations);

    var polygons = <?=json_encode($polygons_json );?>;
    //var polygons2 = JSON.parse(polygons);
    //document.getElementById("demo").innerHTML = polygons2;

    initialize(locations2,polygons)

      }

Comment: php and html both tags for this?
Comment: where is onclick="filter()" function ??
Comment: @geminiousgoel, That are the stuff that I use
Comment: @SurajKhanra I've added the filter() function
Comment: should tag to which your problem belongs not to all keywords that you used. In that way to will tag "radio", "button", "form", "class"...?
Comment: @geminiousgoel, thanks for your feedback. I will change it.
Comment: Why are you mixing up php code with javascript in your filter function?
Answer: $(document).ready(function(){
$("#form").submit(function(event) {
    event.preventDefault();
    var color = $('#Color').val();
    var radio = $('input[name="filter_opties"]:checked').val();
    filter(color, radio);
    $.ajax({
        type: "POST",
        url: "db_querys.php",
        data: {'color' : color, 'radio' : radio},
        success: function(data) {
            alert(data);
        }
    });
});

Comment: It's very hard to tell what your code is doing, or what the difference is.  In your case you replaced `$("form#form")` with `$("#form")` Please add some explanation, without that, your answer is pretty much useless.


How come modern modes are based on the same set of intervals?

Question: I couldn't find any answer regarding this specifically, so I assume there's some basic concept behind this that I missed.
So, as far as I know:
Modern modes are based on the same set of intervals, as seen in this picture.

To play in a modern mode you would just have to start from a different degree of that set of intervals, and you would have a mode.
This evokes my curiosity: why is this pattern so crucial? After all, a scale can be composed of any allegedly random set of intervals.
So how did this specific pattern came to be? And what explains the adherence to it, compared to going full on crazy and using interval patterns that are remotely different from this pattern? (In western music, at least.)
Thank you for your time.
Comment: @ggcg Depends on what your definition of scale is. As far as I can tell, a scale is any set of musical notes ordered by fundamental frequency or pitch. So theoretically, any set of notes (including random) can be considered a scale.
To clarify, when I say intervals I refer to intervals belonging to 12 TET. (multiples of half steps)
Comment: Modes are very simple. With a piano and and five minutes to spare you can explain them to a child. You ask, "What explains the adherence to [modes] compared to going full on crazy?" I think modes are given undue attention on this site by people hoping to understand music by means of formulae and tables like yours. There are plenty of composers and musicians who DO go full-on crazy. And there are plenty of techniques and approaches to music that are rarely if ever mentioned here.
Comment: Does this answer your question? [Why are there just 7 modes?](https://music.stackexchange.com/questions/98905/why-are-there-just-7-modes)
Comment: Are you talking about a different sequence of whole and half steps? Or are you talking about other types of (microtonal) intervals?
Comment: I am referring to different sequences of whole and half steps
Comment: There are not that many reasonable ones, see my answer.
Comment: "After all, a scale can be composed of any allegedly random set of intervals."  Says who?  This would not really make a scale.
Comment: It looks to me as a kind of pleonam.. modes are actually defined by starting from different points of the major scale. So, to answer your question? because it's defined like this. Now if you want to know why the major scale has become such an important pattern, that's another very broad question
Comment: Just throwing it out there, the book "All Possible Scales" exhaustively enumerates all of the 12TET scales, useful or not. https://www.johndcook.com/blog/all-possible-scales/ Also where the scales have names (and thus, probably some utility), those are mentioned.
Comment: Just to play devils advocate, here. There's absolutely nothing stopping you from using a different scale based on a different set of intervals. Relatively common examples include a whole-tone scale (all whole tones, there's augmented fourth and fifths everywhere) and a diminished scale (all minor thirds, there's only 4 notes in this scale).
Answer: If you want to focus on scales made from steps in the chromatic scale, 12TET tuning, then there are dozens, at least 72 that I can think of (actually twice this if my memory is correct).  In the Carnatic style of music from India one builds scales using only notes from the 12TET chromatic scale with a few restrictions.  The larger set of Carnatic scales can have different ascending and descending patterns and do not have to have 7 tones.  However there is a set of modern Carnatic Ragas called Melakarta Ragas that all have 7 tones.  The set of 72 has a restriction of having a P5 (the dominant) present.  Other than that one has every possible unique combination of 2nds, 3rds, 4ths, 6ths, and 7ths.  And by every they allow major, minor and diminished intervals, as long as they do not coincide with the next note.  For example if a Raga has M2 it can have M3 and m3 but not d3.  However if the Raga has m2 then it can have a d3 (double flatted 3rd).  This allows for chromatic bits separated by large intervals.  From this set a whole new set can be generated by either augmenting or diminishing the 5th, for those Ragas that do not have a m6, or a4, respectively.  Between the modern Ragas and traditional Carnatic scales there must be well over 100.
So as part of your question the "modes" you have listed are simply those that Europeans have converged on.
A second part of your question seems to be more historical and cultural than technical.  The seven modes you have listed align the way they do primarily thanks to the 12TET tuning.  Keep in mind that over a few thousand years these scales became more widely used in Western European Cultures than others, and there were others.  Also, as music became standardized there was a desire to transcribe (or simply write) older folk tunes in new standard music notation.  This introduced changes to original tunes to get them to fit as best as possible to the standard Major scale that was evolving.  Sort of like a nearest neighbor interpolation applied to the notes.  If you do a search you may find some information on ancient modes that eventually became Dorian, Phrygian, etc.  The ancient versions did not sound exactly as the modern equivalent.  Add to this the fact that many eastern musical styles use 1/4 tones.  There is a Turkish instrument called the Saz which is guitar like and has quarter tone frets.  Similar things exist in Persian music.  Persian music has a great influence on classical Spanish music but the Guitar has evolved to 12TET tuning.  So melodic phrases are modified to fit as closely as possible to the diatonic scale.  A combination of many factors probably led to the diagram you posted in your original question.  In addition to some I've mentioned I'd include the evolution of large orchestras and the complex harmony probably forced the need for simpler standard scales as there is less improvisation in Western classical music and choir music than in folk music.
At the end of the day these are the memes that survived.  They developed while others were lost by force.  By the influence of composers and performers who preferred these scales.
Reference:  Classical Music of India by Subramaniam and Subramanium
Comment: *So as part of your question the "modes" you have listed are simply those that Europeans have converged on.* I don't think it's arbitrary that Western music focuses on these scale patterns. Western music has harmony that focuses on major and minor triads. The scales it uses are ones that make it possible to form lots of major and minor triads.
Answer: In order to narrow down the possibilities, let's focus on heptatonic scales with only whole and half tone steps. As a second restriction, let's agree that we don't want two consecutive half steps in our scales. These restrictions might seem arbitrary, but they are quite reasonable from a melodic and harmonic standpoint (for western ears, at least).
Apart from the modes in your question, it might surprise you that, given above restrictions, there is only one more 7-note scale (and its modes) that has a different pattern of whole and half steps: the melodic minor scale. In that scale the two half steps are separated by only one whole step. The modes of melodic minor are used a lot in jazz, so we actually do not exclusively adhere to the church modes.
Note that if we allow two consecutive half steps then there's again only one more scale (and its modes): the Neapolitan major scale. So there are only three systems (i.e., 3x7 = 21 scales) of heptatonic scales with only whole tone and half tone steps: the major scale and its modes, the melodic minor scale and its modes, and the Neapolitan major scale and its modes. All other scales either have at least one interval that is neither a half step nor a whole step, or they have more or less than seven notes (like the pentatonic minor and major scales, the whole tone scale, the diminished scales, bebop scales, etc.).
If you really want to go crazy, you should consider leaving the heptatonic scale system in 12-TET and look for new sounds in different temperaments.
Comment: Diminished and whole-tone scales are commonly used, so why limit to 7-note scales.
Comment: I've been trying to learn basic music theory. Your restriction "we don't want two consecutive half steps in our scales" was brilliant. The light bulb came on in my head. That makes total sense and really puts a "pattern of intervals" in a better light. (Major scale / minor scale).  Many thx.
Comment: @piiperiReinstateMonica: Fair point, but it's indeed an arbitrarily chosen limitation, just to get some focus. If I include the whole-tone and diminished scale, one could ask why not include 8-note-bebop scales, etc.
Comment: Barry Harris's "sixth diminished" scale has consecutive semitones and you can create beautiful sounds with it. Blues scales have consecutive semitones. But you don't necessarily play the consecutive semitones _at the same time._
Comment: @piiperiReinstateMonica: Of course, there are many scales with consecutive semitones. Also bebop scales have consecutive semitones, but they are mostly there for melodic reasons, not so much for harmonic reasons. The same holds for the blues scale. You don't usually accompany a blues with chords built from the blues scale. This is different from standard heptatonic scales, where we build chords by stacking thirds from each scale tone.
Comment: So do you assume that in _other_ scales the notes are for "harmonic reasons"? What does that mean? A guarantee that note combinations can be selected randomly? Or that stacks of thirds make sense? I think there's an elephant in this room and that is: *so what* if a scale has such and such intervals. What do you do with them? Or is there an implicit agreed upon assumption that unless stated otherwise, "scale" means "reference grid for building harmonic stacks of thirds"? By the way, that's exactly what Barry Harris's scale is for, and it has consecutive semitones. Assumptions!
Answer: One of the meanings of "mode" is simply the "rotation" of a scale. Playing the second mode of the major scale means to play the scale tones, but starting on RE, the second degree. In that sense "mode" means to not change the set of intervals of the scale but simply to rotate them.
The second point is the modes you listed are all diatonic modes. That is a crucial pattern in much music, because the diatonic tones are the foundation of the major/minor system. Why? One explanation is the diatonic tones can all be rearranged as ascending perfect fifths and that interval is acoustically significant.
The are many other modes. The modes of harmonic minor and melodic minor are pretty common in several different musical styles.
Answer:
why is this pattern so crucial?

It isn't, really - it just happens to subjectively work pretty well, with most of its starting points (apart from, arguably, the Locrian) yielding modes that have interesting harmonic and melodic possibilities.

After all, a scale can be composed of any allegedly random set of intervals.

Well, it depends what you're trying to achieve. If you want to allow consonant harmony, it makes sense to have some notes that are consonant with your root note, and with other notes in the scale; If you look at the notes in the diatonic scale, it allows 6 fifths, 6 fourths and 3 major thirds, for a start, in a scale with only seven notes - which seems quite a good yield to me.
(The fact that there are 6 fifths relates to Michael Curtis' point  that the diatonic tones can all be rearranged as ascending perfect fifths.)

And what explains the adherence to it?

I don't think there really is an adherence to it, if you look at a wide body of music. Minor key harmony? Usually goes outside of the diatonic scale. Modern major key harmony, for that matter, too. Whenever anyone 'modulates'? They probably go outside of the diatonic scale. 'Borrowed chords', likewise. Blues scale? Not diatonic.
Of course a lot of cases of these might be said to be almost diatonic, or represent a motion between one diatonic scale and another, or somesuch. Which is fine if it helps you as a way of communicating or doing your own analysis.
In case it sounds like I'm trying to denigrate or disenfranchise the diatonic scale, I am not. I like it!
Answer: You're starting out from a false premise.   Yes, there are 7 scales derived from the major scale. Label them the 'modern modes' if you like.  That doesn't give them any special status, or even imply they're used more often than other 8-note scales.   Historically, Harmonic Minor has probably been used  more than any of the 'modern modes' except Ionian (major).
Answer: You mention western music right at the end -- do you mean your question to be confined to just western scales? If so, then one factor which limits the choice severely is the prevalence of a temperament with just 12 pitches per octave. It leaves a limited number of options for each degree of the scale.
The 7th degree can be major or minor
The 6th degree can be major or minor
The 5th degree must practically be a perfect fifth above the tonic (if it isn't, the tonic triad sounds dissonant, and that is the one triad you want to sound consonant)
The 4th degree can be perfect or augmented
The 3rd degree can be major or minor
The 2nd degree can be major or minor
Even so, this allows some scales which are not in your list, e.g. the double harmonic major, Hungarian major, double harmonic minor (Hungarian minor) and Romanian Minor (Ukrainian Dorian) scales.


Converter Dados datatable em Json

Question: é possivel os dados do DataTable serem guardados em JSON?
Tenho este código:
<code>  public List<AgendaModel> MostrarTodosCalendar()
    {
        List<AgendaModel> lista = new List<AgendaModel>();
        AgendaModel item;
        DAL objDAL = new DAL();
        string sql = "SELECT id, title, start, end, AllDay, Color, TextColor FROM agenda";
        DataTable dt = objDAL.RetDataTable(sql);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            item = new AgendaModel
            {

                Id = dt.Rows[i]["Id"].ToString(),
                Title = dt.Rows[i]["Title"].ToString(),
                Start = dt.Rows[i]["Start"].ToString(),
                End = dt.Rows[i]["End"].ToString(),
                //AllDay = dt.Rows[i]["Allday"].ToString(),
                Color = dt.Rows[i]["Color"].ToString(),
                TextColor = dt.Rows[i]["TextColor"].ToString()

            };

            lista.Add(item);
        }

        return lista;
    }
</code>
Answer: Eu uso esta função que achei na comunidade em inglês
<code>public string DataTableToJsonObj(DataTable dt)
{
    DataSet ds = new DataSet();
    ds.Merge(dt);
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        JsonString.Append("[");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            JsonString.Append("{");
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                if (j < ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
                }
                else if (j == ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
                }
            }
            if (i == ds.Tables[0].Rows.Count - 1)
            {
                JsonString.Append("}");
            }
            else
            {
                JsonString.Append("},");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}
</code>

Converter Dados datatable em Json


How to hide # in nginx

Question: I have designed a page in html. I have created multiple links ( nav ) in and pointed it with same page section using id. for example, Next and this will display next section. While clicking the link, it updates the URL like ( localhost/myproject/index.html/#next ). But, I need to hide the '#' in that URL. ( localhost/myproject/index.html/next ). We are using nginx configuration. How can be it possible? Thanks in advance...
Comment: if you use angular try this [http://stackoverflow.com/questions/14319967/angularjs-routing-without-the-hash](http://stackoverflow.com/questions/14319967/angularjs-routing-without-the-hash)
Comment: no, i am using plain html
Comment: Is this what you're looking for? http://stackoverflow.com/questions/1397329/how-to-remove-the-hash-from-window-location-with-javascript-without-page-refresh and http://stackoverflow.com/questions/15322917/clearing-url-hash . Else Quentin answer is correct.
Answer: It isn't possible.
Fragment identifiers in URLs are handled entirely client side. They are never sent to the server, so the server can't access them.

How to hide # in nginx


how to find k nearest values to a value with hibernate?

Question: I want to implement k-NN algorithm in java, I need to fetch k value with minimum distance to our value fron database.
for example, I entered 123, and we have 10000 value in database. I want to find 10 value with minimum difference from database.
how can I do this.
thanks
Answer: You can retrieve the values from the database ordered by the value of interest.


Finding $x$, $y$ that minimize $(\frac{\sqrt3\sin y}{\sqrt2\sin(x+y)}+1)(\frac{\sqrt2\sin x}{3\sin y}+1)^2(\frac{\sin(x+y)}{7\sqrt3\sin x}+1)^4$

Question: This problem was given in 2018 in the entrance exams for MSU(8th problem). The only information online about the exam is its answers and is supposedly aimed at highschool students. I am in a maths-oriented high school so we are studying what we would in the 1st year in uni. The problem is:

Find all pairs of $x,y \in (0;\frac{\pi}{2}) $ where $f(x,y) = f_{min}$. (When is this equal to its minimum value)
$$ f(x,y) =   \left(\frac{\sqrt3\sin y} {\sqrt2\sin(x+y)} + 1\right)\left(\frac{\sqrt2\sin x}{3\sin y} + 1\right)^2\left( \frac{\sin(x+y)}{7\sqrt3\sin x} + 1\right)^4  $$

I only want a starting point, how do I approach this? Derivatives? Or do the (...)^4 ?
Comment: Mathematica gives (after *long* thought) $(x,y)\approx (0.494021, 1.42152)$. No symbolic answer given. Hard to believe this is really a high school level problem.
Comment: I should note that my maths teacher couldn't help me.
Comment: maybe $a,b,c=\sin(x),\sin(y),\sin(x+y)$ and [Lagrange multipliers](https://www.wolframalpha.com/input/?i=minimize+%28sqrt%283%29*b%2F%28sqrt%282%29*c%29%2B1%29*%28sqrt%282%29*a%2F%283*b%29%2B1%29%5E2*%28c%2F%287*sqrt%283%29*a%29%2B1%29%5E4+when+0%3Ca%3C1%2C0%3Cb%3C1%2Cc%3Dsqrt%281-a%5E2%29*b%2Bsqrt%281-b%5E2%29*a)?
Comment: Could you deliver a link to the answer?
Comment: Problems and their solutions(in Russian)
http://cpk.msu.ru/files/2018/tasks/math_solutions.pdf
Comment: an application of Holder's inequality is staring right at you. I am not sure if the equality condition from Holder would give the right answer though.
Answer: As @rogerl commented, it is "hard to believe this is really a high school level problem".
Running a CAS, what it obtained is, for the minimum,
$$x=0.61547971 \qquad y=0.95531662 \qquad \implies f_{min}=6.06562081$$
Searching with inverse symbolic calculators, the closest I found is
$$x=\cos ^{-1}\left(\sqrt{\frac{2}{3}}\right)\implies \sin(x)=\frac{1}{\sqrt{3}}$$
$$y=\sec ^{-1}\left(\sqrt{3}\right)\implies \sin(y)=\sqrt{\frac{2}{3}}$$ which make $\sin(x+y)=1$ and $f_{min}=\frac{131072}{21609}$.
Comment: If the optimum can be written in a reasonably nice algebraic way, that makes me suspect, there might be a clever way of proving it, but I don't see a way to do it either.
Comment: Is there a rigorous way to show that $\sin(x+y)=1$?
Comment: @AlexeyBurdin. I just computed.
Comment: @quarague. I tried with algebra : it is pure nightmare even assming that $x+y=\frac \pi 2$.
Comment: Assuming $a=\sin(x),\sin(y)=\sqrt{1-a^2}$ and getting $f'(a)$ with `sympy` yields $\left(21a + \sqrt{3}\right)^3\left(\sqrt{2}a + 3\sqrt{1 - a^2}\right)\left(-\sqrt{6}a^2\left(1 - a^2\right)^{\frac72}\left(21a + \sqrt{3}\right)\left(\sqrt{2}a + 3\sqrt{1 - a^2}\right) + 2\sqrt{2}a\left(1 - a^2\right)^3\left(21a + \sqrt{3}\right)\left(\sqrt{6 - 6a^2} + 2\right) - 4\sqrt{3}\left(1 - a^2\right)^4\left(\sqrt{2}a + 3\sqrt{1 - a^2}\right)\left(\sqrt{6 - 6a^2} + 2\right)\right)/\left(3500658a^5\left(1 - a^2\right)^5\right)$ -- not so scary)
Comment: @AlexeyBurdin. I had this one. As you say, *"not so scary"*. Just do it ! Cheers :-)
Comment: [OK](https://www.wolframalpha.com/input/?i=0%3D-%5Csqrt%7B6%7Da%5E2%281+-+a%5E2%29%5E%281%2F2%29%2821a+%2B+%5Csqrt%7B3%7D%29%28%5Csqrt%7B2%7Da+%2B+3%5Csqrt%7B1+-+a%5E2%7D%29+%2B+2%5Csqrt%7B2%7Da%2821a+%2B+%5Csqrt%7B3%7D%29%28%5Csqrt%7B6+-+6a%5E2%7D+%2B+2%29+-+4%5Csqrt%7B3%7D%281+-+a%5E2%29%28%5Csqrt%7B2%7Da+%2B+3%5Csqrt%7B1+-+a%5E2%7D%29%28%5Csqrt%7B6+-+6a%5E2%7D+%2B+2%29)
Comment: I checked on the answers and they are the following:

$ x = \arccos \frac{\sqrt2}{\sqrt3}$
$ y = \arccos \frac{1}{\sqrt3}$
Comment: I still don't have a clue how to get to that point however.
Comment: @Midaga. Me neither ! It is a very strange problem. Cheers :-)
Answer: I think maybe the question is poorly worded. It says "find all pairs" but provably finding all solutions to the stationary point equations is tedious (even a CAS struggles). Allow me to reword the question:
Find the unique stationary point of the function $f(x, y)$ in the given interval.
What difference does that change in wording make? It means that you don't need to directly find all solutions and can just guess at solutions until you find one that works. Bear that in mind and I will now hint but not explicitly give the solution.
The function you want to find the stationary point of is of the form $f(x, y) = a(x, y)b(x, y)^2c(x, y)^4$ so using $f_x$ for $\frac{\partial f}{\partial x}$ we have
$$
f_x = a_x b^2 c^4 + 2 b_x a b c^4 + 4 c_x a b^2 c^3
$$
but the key is we don't have to calculate this whole expression explicitly. Rather we recognise that it is zero if each term has a zero factor. The same goes for $f_y$.
Now the big hint: if you calculate $a_x$ etc what you will see is that the terms in $f_x$ and $f_y$ have some common factors. We just need to find $x$ and $y$ to make those common factors zero and then we have found a stationary point of $f$.
Following the above I find the same solution as in Claude Leibovici's answer.
Comment: It turns out this is much more Calculus than I should know but I read for a while more Calc and hope to finish it. I doubt myself though


The complement of an algebraic set in $\mathbb{P}^n$ is path-connected

Question: I'm studying the marvellous book "Algebraic Curves and Riemann Surfaces" of Rick Miranda and I've found this problem (III.5.Q pag.103). Actually it's not related to Riemann surfaces, but I think it's interesting anyway.
A subset $Z\subseteq  \mathbb{P}^n$ is an algebraic set if there is a set of homogeneous polynomials $\{F_{\alpha} \}$ such that  $Z=\{p\in \mathbb{P}^n | F_{\alpha}(p)  = 0$ for every $\alpha\}$. Here $\mathbb{P}^n$ is the complex projective n-space, i.e. the set of 1-dimensional subspaces of $\mathbb{C}^{n+1}$.
Show that the complement of an algebraic set in $\mathbb{P}^n$ is path-connected.
Remarks.

Since an algebraic set is an intersection of hypersurfaces, if the proposition above holds for hypersurfaces, a fortiori holds for generic algebraic sets. So, it suffices to prove that the complement of the set of zeroes in $\mathbb{P}^n$ of a homogeneous polynomial $F$ is path-connected.
Proof. (asked by ronno)
Assume that the proposition holds for hypersurfaces. Let $Z_1$ and $Z_2$ be two hypersurfaces defined by the zeroes sets in $\mathbb{P^n}$ respectively of $F_1$ and $F_2$ homogeneous polynomials. Since $F_1F_2$ is a homogeneous polynomial, its zeroes in $\mathbb{P^n}$ define a hypersurface $Z_3 = Z_1 \cup Z_2$, so the finite union of hypersurfaces is a hypersurface. Since $\mathbb{P^n} -Z_3 = (\mathbb{P^n}-Z_1) \cap (\mathbb{P^n}-Z_2)$, the intersection of the complements of two hypersurfaces is path-connected. Therefore $(\mathbb{P^n}-Z_1) \cup (\mathbb{P^n}-Z_2)$ is path-connected. Hence the complement of an algebraic set, being union of sets two-by-two path-connected, is path-connected.
The problem is equivalent to say that the open sets in the Zariski topology on $\mathbb{P}^n$ are path-connected.

Thanks for any hint or answer.
Comment: I don't understand the reduction to the hypersurface case. It is true that every $\mathbb{P}^n - (\text{algebraic set})$ contains some $\mathbb{P}^n - (\text{hypersurface})$ but why does this say anything about path-connectedness?
Answer: Let $x,y\in\Bbb P^n$ be two distinct points. Let $L\cong\Bbb P^1$ be the unique line containing these points. If we can find a path in $L$ which joins $x$ and $y$ while missing $L\cap Z$, then we win - the image of this path in $\Bbb P^n$ will be a path between $x$ and $y$ missing $Z$. But $L\cap Z$ is a proper closed subset of $L$ (since it does not contain $x$ nor $y$) so $L\cap Z\subset L$ is a finite set of points. Since $\Bbb P^1$ in the Euclidean topology is homeomorphic to $S^2$ and $S^2$ minus a finite set of points is path connected, we win.


Had a peculiar issue with my EC2 instance yesterday, disk space low?

Question: I've got an asp.net core application running on Linux/Nginx in Elastic Beanstalk.  All of a sudden it stopped working properly yesterday, the issue was that one of the main javascript files was no longer being served out, instead Chrome reported a ERR_HTTP2_PROTOCOL_ERROR.  Navigating directly to the file did work fine though, but when loading the app it self, the request to the file always failed with this error.
I tried different browsers (Chrome, Edge, Vivaldi), different devices (PC, mobile phone) and different network connections (LAN/WIFI/Mobile data) but the result was the same everywhere.
Googling the issue gave the impression that this error can be caused by multiple different things.  After some more digging and examining the network logs in Chrome, the actual error suggested that the server was probably the issue - it was terminating the connection before all the file had been sent (something related to HTTP/2).  Some more Googling and everything suggested that this was because of low diskspace on the server (Linux/Nginx) and when diskspace is low or completely exhausted, Nginx would sometimes do this.
I never received any notification that the instance was running out of disk space, nor did I see it mentioned anywhere.  Some more digging and I two other issues occurred that lead me to believe that the issue was indeed related to diskspace.
When I tried to request logs from the instance in the AWS console, the log file would be generated but it was always 0 bytes in size.  When I tried to deploy a new version of my app to the instance (Using the AWS toolkit in Visual Studio) everything seemed to be successful, no errors reported anywhere, but the changes were not reflected on the instance, it appeared to be still running the older version.  When I tried to retrieve the logs to see if there was an error somewhere ... but I just got empty log files.
It wasn't until I decided to apply a recommended update to the instance (Linux 2.3.5 instead of 2.3.4) which probably resets the environment completely - that everything seemed to go back to normal, and my app is running normally again.
What. The. Hell.  Any ideas what might have been happening?  Anyone had similar issues?  I had been thinking of migrating to Azure, this incident made me want proceed with that even more.
Comment: I would be surprised if anyone who has used EC2 for a period of time has not had disk space/performance issues.  That said, if you are using a operating system platform and cannot get a memory dump for analysis, it's difficult to pursue problems like this with almost no data.
Comment: Computers and software can act a bit weird when the disk is full. I suggest you set up Cloudwatch to alert you when the disk is full. It's not difficult, but you do have to install and configure the Cloudwatch agent as free disk space is an OS metric not a hypervisor level metric. The grass isn't always greener, it sounds like this problem could happen on any host. You might like to try to work out why the disk filled - updates, etc. You can also resize the EBS volume then restart to increase disk size, with Linux at least.
Answer: Just an update.  Had this happen again.  Spent some more time digging this time around.  Managed to connect to my instance via SSH to examine further.  Turns out that some logs where eating up all the diskspace.  I modified my instance and increased the root volume size and since I now have the SSH access up and running, it will be easier for me to monitor the diskspace in the future and prevent this from happening.
I find it a bit weird that you have to SSH into your instance to perform a mundane task like checking the available diskspace.  You can see all kinds of information about your ELB volume in the AWS console, but not the diskspace utilization.  Also, when you modify your volume and increase it's size, you still have to SSH in and run a couple of linux commands to increase actually be able to use the increased volume size.  I'm a bit surprised how things rapidly get extra complicated when you are performing tasks which are perhaps a bit more advanced than the really basic stuff.


Getting ExceptionInInitializerError when running tomcat (Initializing hibernate SessionFactory object from ServletContextListner)

Question: I am making a hibernate SessionFactory Object whenever tomcat server is starting and destroying it when server is stopping, so called a static method getSessionFactory() of HibernateUtil class which returns sessionfactory object from the HibernateContextListener which is implementing ServletContextListener but I am getting ExceptionInInitializerError when i am starting my tomcat, its working normal later but every time when i am running tomcat it is giving a big list of many exceptions, below are some stacktrace of those exceptions.
Sep 24, 2015 10:43:13 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.bss.util.HibernateContextListener
java.lang.ExceptionInInitializerError
    at com.bss.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
    at com.bss.util.HibernateUtil.<clinit>(HibernateUtil.java:7)
    at com.bss.util.HibernateContextListener.contextInitialized(HibernateContextListener.java:19)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.OutOfMemoryError: PermGen space
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2248)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2214)
    at org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider.<clinit>(C3P0ConnectionProvider.java:58)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:148)
    at org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator.c3p0ProviderPresent(ConnectionProviderInitiator.java:198)
    at org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator.initiateService(ConnectionProviderInitiator.java:121)
    at org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator.initiateService(ConnectionProviderInitiator.java:54)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:79)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:201)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:175)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
    at com.bss.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
Sep 24, 2015 10:43:13 AM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class com.bss.util.HibernateContextListener
java.lang.NoClassDefFoundError: Could not initialize class com.bss.util.HibernateUtil
    at com.bss.util.HibernateContextListener.contextDestroyed(HibernateContextListener.java:25)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4763)
    at org.apache.catalina.core.StandardContext$4.run(StandardContext.java:5472)
    at java.lang.Thread.run(Thread.java:662)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5481)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:225)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:153)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3854)
    at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:935)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:355)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:576)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

HibernateContextListener.java
public class HibernateContextListener implements ServletContextListener{

@Override
public void contextInitialized(ServletContextEvent sce) {
    HibernateUtil.getSessionFactory();
    System.out.println("HIBERNATE SESSION FACTORY INITIALIZED");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
    if (HibernateUtil.getSessionFactory()!=null)
    {
        HibernateUtil.getSessionFactory().close();
    }
    System.out.println("HIBERNATE SESSION FACTORY DESTROYED");
}
}

HibernateUtil.java
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {
        Configuration configuration = new Configuration().configure();
        SessionFactory factory = configuration.buildSessionFactory();
        return factory;
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}}

Comment: possible duplicate of [PermGen space Error in tomcat](http://stackoverflow.com/questions/10392255/permgen-space-error-in-tomcat)
Comment: Are you using a big framework like Spring? Those usually require that you dramatically increase your PermGen space from the default. Or, you could use Java 8 and try your luck with the metaspace.
Comment: but every time when tomcat shutdowns, i am also closing sessionfactory object
Comment: i am not using spring, instead i am using hibernate with c3p0 connection pooling.
Answer: you can use
-XX:MaxPermSize=128m

to increase perm gen space, for full answer go through this link


What is the relationship between the risk ratio and the weight of evidence?

Question: I've been reading about risk ratios as typical measures in clinical settings. In the finance and credit literature, there is the weight of evidence (WoE) measure that is used to encode and study variables.
Is there a relationship between them? I read somewhere that the WoE is pretty much the log of the risk ratio, if you condition things properly, but I've been unable to prove that.
Comment: Can you tell us where did you read that? And please, fix spellings ...
Answer: Weight of evidence (WoE) is used in different settings, but here I take it you mean the use by some in finance & risk modelling, see for instance this list of Qs. You can find your question answered here:   Intuition behind Weight of Evidence and Information Value formula.
Then, the fast answer is: WoE is the logarithm of a specific risk ratio.  The long answer is in the above link.


Many to many relationship when order metter

Question: I have many to many relation between User and Group: group may contains few users and consists in multiply groups.
Server send me json like this, and I need to store it to DB:
group: {
  name: "test", id: "UUID"
  users: [
    {name: "user1", id: "UUID"},
    {name: "user2", id: "UUID"},
    {name: "user3", id: "UUID"}
  ]
}

The problem is: users order in group matters - users should be displayed in the same order like in servers json.
The fist solution that I use is add to group field like
user_ids: [user1_uuid, user2_uuid, user3_uuid] and store it into DB in json fromat, but I see 2 problems in this solution:

It contradicts to first normal form (1NF)
When I SELECT values they have wrong order:

SELECT * FROM user WHERE id IN (:user_ids)
How to store it into DB and SELECT?
Answer: In SQL, table rows indeed are unordered; the only guaranteed way to get ordered rows is to use ORDER BY.
If the order of your array elements is important, add a column for the array index.
Comment: Yes, it is the user/group connections that you want to order. (You probably do not need the `_id` column, and `order` is an SQL keyword.)
Comment: Could you provide an example, please?
Comment: What exactly do you want to see? How to add a column? How to write ORDER BY?
Comment: I want to see DB structure. For me is unclear in what table to add column. For example I can't add it to `user` table cause in 1 group this user can be in 1 place and in another group it can be in the other place
Comment: So you have an M:N relationship between users and groups? How do you implement that in your database?
Comment: I use additional table `group_user` with columns `group_id` and `user_id` and `_id autoincrement`.
Comment: As far as I understand your proposition is to add to this `group_user` new column `order` and store there array indexes?
Answer: You could use the following schema:
CREATE TABLE user(id integer primary key, name text);
CREATE TABLE grp(id integer primary key, name text);
CREATE TABLE usergrp(userid integer, grpid integer, position integer);
CREATE INDEX positionindex on usergrp(grpid, position);

Then you can retrieve users belonging to a group with the query
SELECT userid FROM usergrp WHERE grpid=? ORDER BY position;

Also, maybe you would like to use the  "without rowid" sqlite table storage option for usergrp.


Tiling a $3$ by $n$ rectangle

Question: "We are looking to tile a rectangle with dimensions $3$ down and $n$ across, using only $3$ by $1$ rectangles. Prove the number of horizontal rectangles is a multiple of $3$"
I'm probably being stupid, but I can't see a way to rigorously prove this. Surely its as simple as that if we have one horizontal rectangle somewhere in our tiling, then there must be $2$ other rectangles in the same "column" as it, as otherwise there would be some area of the $3\times n$ rectangle not covered.
Am I missing something?
Comment: i would accept your obvious proof :) but if you wanna be rigorous you can induct on $n$ and consider: there are only 2 ways to cover the top cell of the new $(n+1)$th column, and in each case...  (left as an exercise)
Answer: It can be proved using induction. Let $H_n$ be the number of horizontal block in $3$X$N$ Grid.
Clearly $H_1 = 0$. So $H_1$ is multiple of 3.
Now let's suppose $H_k$ is a multiple of 3 for all $k<k_0$ .
i.e. $H_k = 3m$ where $k \leq k_0 $ & $m \geq 0$.
Now for $H_{k_0+1}$ there are 2 ways to place the last tile , vertical or horizontal.
Case 1 :If we place the tile vertical then $H_{k_0 + 1} = H_{k_0} = 3m$ which proves our claim.

Case 2: If we place at last a horizontal tile then we also have to place 2 more horizontal tiles(we have no other choice). In which case we have

$$H_{k_0+1} = H_{k_0 - 2} + 3$$. Since $H_{k_0-2} = 3m$ for some m.
$$H_{k_0+1} = 3m + 3$$
$$H_{k_0+1} = 3(m+1)$$
Which is again a multiple of 3. So by induction it is true for all n.
EDIT : We also need to include $H_2 = 0$ and $H_3 = ( 0 $ or $3)$ as our base cases.
Comment: Logically speaking, you need a tiny bit more than this...  Since your induction can skip back by $1$ or by $3$, you need to prove base cases for $H_1, H_2$ and $H_3$ (or $H_0$).  Or equivalently: you need some remarks in the induction that **Case 2** doesn't apply for certain small enough $k_0$.
Comment: yeaah !! you are right !! Corrected
Answer: Let $V$ be the number of vertical tiles, and $H$ the number of horizontal tiles.
Each vertical tile lies in all three rows, so the number of horizontal tiles in each row is given by $H' = (N - V)/3$, which must of course be an integer** and is the same for each row. The total number of horizontal tiles is given by $H = 3H'$, and so $H$ is divisible by 3.
** This then also implies $N \equiv V \pmod{3}$.

We can generalize the result for $3M \times N$ rectangles:
We color the rectangle so that cells in the first row are red, in the second row green, in the third row blue, and repeat the pattern.
Let $H_R$, $H_G$, $H_B$ be the number of red, green, blue horizontal tiles respectively. Notice that vertical tiles cover each color once.

The number of red cells is given by $MN = 3H_R + V$.
The number of green cells is given by $MN = 3H_G + V$.
The number of blue cells is given by $MN = 3H_B + V$.

From this we can $H_R$, $H_G$ and $H_B$ are all equal and given by
$H_R = H_G = H_B = (MN - V)/3$, and this must be an integer.
The total number of horizontal tiles must be $H = 3H_R$, which means $H$ is divisible by 3.
As before, an additional constraint is $MN \equiv V \pmod{3}$.

Tiling a $3$ by $n$ rectangle


"table or view does not exist"

Question: I am trying to create some tables but i get every time i try table or view does not exist.
I cant find any solution. Here is my code.
 CREATE
  TABLE "User"
  (
    anon_id      NUMBER (38) NOT NULL PRIMARY KEY,
    querytime    TIMESTAMP ,
    state_symbol VARCHAR2 (5) NOT NULL
  ) ;

CREATE
  TABLE "state"
  (
    symbol            VARCHAR2 (5) NOT NULL PRIMARY KEY,
    name              VARCHAR2 (30 BYTE) ,
    "size"            NUMBER (38) ,
    population        NUMBER (38) ,
    tourists          NUMBER (38)
  ) ;

CREATE
  TABLE "population_goup"
  (
    name              VARCHAR2 (255) NOT NULL PRIMARY KEY,
    COUNT             NUMBER (38)
  ) ;

The first 3 tables are createt and now he starts "table or view does not exist" and i dont know why.
CREATE TABLE "location"
  (
    zip         NUMBER (38) NOT NULL PRIMARY KEY,
    city        VARCHAR2 (30 BYTE) NOT NULL,
    state_symbol VARCHAR2 (30 BYTE) NOT NULL ,
    timezone    VARCHAR2 (30 BYTE) NOT NULL ,
    latitude    FLOAT ,
    longitude   FLOAT ,
    population  NUMBER (38) NOT NULL ,
    FOREIGN KEY (state_symbol) references state(symbol)
  ) ;

CREATE
  TABLE landmark
  (
    name              VARCHAR2 (30 BYTE) NOT NULL PRIMARY KEY,
    tourists          NUMBER (38) NOT NULL ,
    location_zip      NUMBER (38) NOT NULL REFERENCES location (zip)
  ) ;

CREATE
  TABLE event
  (
    name              VARCHAR2 (255) NOT NULL ,
    from_date         TIMESTAMP ,
    to_date           TIMESTAMP ,
    location_zip      NUMBER (38) NOT NULL REFERENCES location (zip)
  ) ;

CREATE
  TABLE lives_in
  (
    population_goup_name VARCHAR2 (255) NOT NULL REFERENCES population_group(NAME),
    state_symbol         VARCHAR2 (5) NOT NULL REFERENCES state(SYMBOL),
    PRIMARY KEY(population_goup_name, state_symbol)
  ) ;

  CREATE
  TABLE "searchquery"
  (
    query        VARCHAR2 (4000 CHAR) NOT NULL PRIMARY KEY,
    User_id NUMBER (38) NOT NULL REFERENCES User(anon_id),
    state_symbol VARCHAR2 (5) REFERENCES state(symbol),
    population_name VARCHAR2 (255) REFERENCES population_goup(name),
    landmark_name  VARCHAR2 (30 BYTE) REFERENCES landmark(name),
    event_name  VARCHAR2 (255) REFERENCES event(name),
    location_zip NUMBER (38) REFERENCES landmark(zip)
  ) ;

For searchquery i get "invalid table name" but its not a reserved word so why?
I cant find any help from the script of my uni so i thanks to every one that can help me!
Comment: case sensitive object names and objects using reserved words as names are both recipes for unintended consequences if not disaster down the line at some point
Answer: state is a keyword, so you double quoted it to use it as a table name. Now you need the quoted name whenever you access that table:
CREATE TABLE "location"
  (
    zip         NUMBER (38) NOT NULL PRIMARY KEY,
    city        VARCHAR2 (30 BYTE) NOT NULL,
    state_symbol VARCHAR2 (30 BYTE) NOT NULL ,
    timezone    VARCHAR2 (30 BYTE) NOT NULL ,
    latitude    FLOAT ,
    longitude   FLOAT ,
    population  NUMBER (38) NOT NULL ,
    FOREIGN KEY (state_symbol) references "state"(symbol)
  ) ;

Answer: In order, every object is saved with UPPER CASE name. Unless enclosed within double quotes.
Remove the double quotes to all your table names in the DDL. Also, User, State all are reserved keywords. You cannot use them as table names.
"state" --> state
OR
Refer your tables in the constraints with double quotes, same as in DDL previously..
references state(symbol) --> references "state"(symbol)

searchquery DDL ended with invalid table name because, you refer
  User table, which is a datadictionary table. So, embed them in
  double quotes

Example:
CREATE
  TABLE "searchquery"
  (
    query        VARCHAR2 (4000 CHAR) NOT NULL PRIMARY KEY,
    User_id NUMBER (38) NOT NULL REFERENCES "User"(anon_id),
    state_symbol VARCHAR2 (5) REFERENCES "state"(symbol),
    population_name VARCHAR2 (255) REFERENCES "population_goup"(name),
    landmark_name  VARCHAR2 (30 BYTE) REFERENCES "landmark"(name),
    event_name  VARCHAR2 (255) REFERENCES "event"(name),
    location_zip NUMBER (38) REFERENCES "landmark"(zip)
  ) ;

From DOCs.

Nonquoted identifiers are not case sensitive. Oracle interprets them
  as uppercase. Quoted identifiers are case sensitive.
By enclosing names in double quotation marks, you can give the
  following names to different objects in the same namespace:
employees "employees"
  "Employees"
Note that Oracle interprets the following names the same, so they
  cannot be used for different objects in the same namespace:
employees  EMPLOYEES  "EMPLOYEES"

More on the Schema Object Names and Qualifiers
Comment: Thanks you are right but did you know why searchquery is a invalid table name?
Comment: Apparently there is an issue with the examples in the manual. Both lists  include `employees` and `"EMPLOYEES"`, effectively saying first that those names are different and then that they are identical. As far as I understand, only the second statement is correct.
Comment: I removed the "" and he still tells me invalid table name for searchquery
Comment: @The8Monkey the problem is referring the User table, I added the exact DDL to answer.

"table or view does not exist"


How to get return binding Attribute for Azure FunctionApp binding

Question: I have function:
<code>[FunctionName("test-function")]
        [return: ServiceBus("topic-name", Connection = "connection-string")]
        public static Task<Message> TestFunction([TimerTrigger("%TimerSchedule%")]TimerInfo timer, ILogger log)
        {
            return Task.FromResult(new Message());
        }
</code>
How can I get ServiceBus attribute through reflecion as it is not part of methods CustomAttributes collection?
Answer: Getting Attribute Data For Return Value of .NET Method
<code>x.ReturnParameter.GetCustomAttributesData()
</code>


Boot without nftables | Debian 10

Question: While rebooting our newest strorage servers, we're experiencing a kernel error (probably) caused by nftables. Please see attached call trace:

After configuring the server (incl nftables), everything worked fine. When we'd tried to reboot the server, it won't boot anymore. Booting using Debian's recovery mode shows the above error.
Question, is there an option/parameter that I can pass to Debian to boot without nftables?

Additional information
Linux version

4.19.0-13-amd64
4.19.0-13-amd64 (recovery mode)
4.19.0-12-amd64
4.19.0-12-amd64 (recovery mode)
Comment: Can you show the rest of the message, which appears above what you have shown here?
Comment: Thank you for your reply @MichaelHampton. Unfortunately I don't have any additional errors that were shown above the image since the system completely freezes, I'm unable to 'scroll up'. I'll take another look tomorrow (need to get to Datacenter) to check for additional output.
Answer: Edit the kernel command line and try adding module_blacklist=nf_tables
Upstream in the kernel, there is some possibly relevant fixes. Like this use after free bug fixed in 4.19.72
commit 5776970fb4ecf72db4e0142c03f49b03ed024b75
Author: Pablo Neira Ayuso <email@example.com>
Date:   Fri Aug 9 11:01:27 2019 +0200

netfilter: nf_tables: use-after-free in failing rule with bound set

[ Upstream commit 6a0a8d10a3661a036b55af695542a714c429ab7c ]

I am uncertain if any Buster kernel has this.  Try booting a newer Debian version and using the rescue mode. Bullseye is testing at the moment. However, you can test if its newer kernel is affected, and get a shell to try other things.

Consider setting up kdump and capturing these. Having the full text of the trace helps, and symbols and source even more so.

Boot without nftables | Debian 10


UITabBarController custom action with Storyboard

Question: I would like to prompt a user to sign in with a UIAlertView when the user presses a certain tab bar item in a tab bar controller.
This tab bar controller exists in storyboard, and as a result I'm not sure where i can do this. Apple claims that UITabBarController shouldn't be subclassed, further adding to my confusion. And furthermore, i am aware of UITabBarController's delegate pattern but i don't know what view controller i can hook it up to Note: My UITabBarController is generated from a modal segue from a UIViewController.
Thank you in advance.
Answer: I found the answer to this when answering another of my own questions, here.
I used the uitabbarcontrollerdelegate and set that in the root controller.
Answer: You can display your alert view when the selected view controller is displayed... Say you have a LoginViewController in the tab bar. inside that class create a method
- (void)viewDidAppear:(BOOL)animated;

which displays the alert view
Also look at the UITabBarDelegate
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

Comment: The point is to avoid that. So that i don't have to keep state of which controller i came from in case they don't log in and all the delegation around that. It's also confusing for the user. It makes more sense to have it displayed before changing views


FQDN, DNS, Hosts, postfix

Question: Let's say I bought this domain: example.com
Name servers under DNS manager all points to example.com
That subdomain(example.com) of nameservers points to an IP.
Also, note that hostname unique is under an A record to said IP
My First question: under etc/hosts, how should the FQDN be

xx.xx.xxx.xxx   unique.example.com unique OR
xx.xx.xxx.xxx   example.com example OR
xx.xx.xxx.xxx   unique unique

Both have dns records and both represent the same ip. In the first case unique is the hostname and the FQDN is unique.example.com. In the second case, example is the hostname and example.com is the FQDN.
So, given a FQDN have to represent the server name. Which one is true ?!
Given all that, when I try to install postFix, and it asks for FQDN, I just don't know what to write as both options seems valid.
However, if I write unique.example.com then my emails become firstname.lastname@example.com which is not what I would expect.
Context: Ubuntu 14.04 VPS, webmin/virtualmin. I accidentaly installed sendmail package and my whole postfix virtual min is no longer working! So, that question comes from me trying to install back postfix.
Answer: unique.example.com is the correct FQDN, where unique denotes the hostname  and example.comis the parent domain.
example is not a hostname, and com is a TLD (Top Level Domain), so example.com is not a fqdn and as such is not valid and not same as unique.exampl.com.  Read deatils here: What is a fully qualified domain name (FQDN)?

A fully qualified domain name (FQDN) is the complete domain name for a
  specific computer, or host, on the Internet. The FQDN consists of two
  parts: the hostname and the domain name. For example, an FQDN for a
  hypothetical mail server might be mymail.somecollege.edu. The hostname
  is mymail, and the host is located within the domain somecollege.edu.

When you enter unique.example.com as fqdn, this will be used as to configure myhostname and mydestination in /etc/postfix/main.cf and so there is nothing to be worried about.
Comment: Thanks for the answer, I wasn't able to fix the postfix problem as I completely destroyed the MTA bridge and the logs were driving me crazy issue after issue. It's my 4 days as a sysadmin lol, I just reformatted and now webmine controls the DNS zone therefore the associated mail stuff records.
Answer: The FQDN (Fully Qualified Domain Name) the is complete name ending with a dot (https://en.wikipedia.org/wiki/Fully_qualified_domain_name)
In /etc/hosts you put the full and short name (but no fqdn)
127.0.0.1 localhost
 126.96.36.199  mail.example.com mail
Forging the email address for locally generated mails is the role of your mailer program or your local mail server (like exim or postfix). There you can choose to generate email@example.com or firstname.lastname@example.com or firstname.lastname@example.com.

FQDN, DNS, Hosts, postfix


Limit calculation using derivative

Question: I encountered this exercise:
Let $f(x)$ be a differentiable function, and suppose  that there exists some $a$ where $f'(a) \ne 0 $.
Calculate the limit:
$$ \lim_{h\rightarrow0}\frac{f(a+3h)-f(a-2h)}{f(a-5h)-f(a-h)}. $$
I have no clue how I can solve this. I was trying to separate into two terms, and multiply and divide by $h$, but it solves just the numerator limit. What can be done with the denominator limit?
Comment: Hint: write the limit definition of the derivative "upside down."
Comment: I tried it but I can't see how it helps me.
Answer: For any $j \neq 0$, $(a + jh) - a = jh$ and with the transformation $k = jh$, you have
$$\lim_{h \to 0}\frac{f(a+jh) - f(a)}{jh} = \lim_{k \to 0}\frac{f(a + k) - f(a)}{k} = f'(a) \tag{1}\label{eq1A}$$
Thus, you get
$$\begin{equation}\begin{aligned}
\lim_{h\rightarrow0}\frac{f(a+3h)-f(a-2h)}{f(a-5h)-f(a-h)} & = \lim_{h\rightarrow0}\frac{(f(a+3h)-f(a))-(f(a-2h)-f(a))}{(f(a-5h)-f(a))-(f(a-h)-f(a))} \\
& = \lim_{h\rightarrow0}\frac{\frac{f(a+3h)-f(a)}{h}-\frac{f(a-2h)-f(a)}{h}}{\frac{f(a-5h)-f(a)}{h}-\frac{f(a-h)-f(a)}{h}} \\
& = \lim_{h\rightarrow0}\frac{3\left(\frac{f(a+3h)-f(a)}{3h}\right)-(-2)\left(\frac{f(a-2h)-f(a)}{-2h}\right)}{(-5)\left(\frac{f(a-5h)-f(a)}{-5h}\right)-(-1)\left(\frac{f(a-h)-f(a)}{-h}\right)} \\
& = \frac{3f'(a) - (-2)f'(a)}{(-5)f'(a)-(-1)f'(a)} \\
& = \frac{5f'(a)}{(-4)f'(a)} \\
& = -\frac{5}{4}
\end{aligned}\end{equation}\tag{2}\label{eq2A}$$
Comment: +1. Simple and clear.
Answer: Without loss, $a=0$.

Lemma. Let $f$ be any function differentiable at $0$. Then as $h\to 0$, $$\frac{f(Ah) -f(Bh)}{h}  \to (A-B)f'(0).$$

Proof.
\begin{align}
\frac{f(Ah) -f(Bh)}{h} = \frac{f(Ah) -f(0)}{h} - \frac{f(Bh) -f(0)}{h} \to (A-B)f'(0).
\end{align}
Therefore by the Lemma and the product and quotient rules of limits,
\begin{align}
\frac{f(3h) - f(-2h) }{f(-5h) - f(-h)}
&=\frac{f(3h) - f(-2h) }{h}\cdot \frac h{f(-5h) - f(-h)}
\\
&\to (3-(-2))f'(0)\cdot\frac1{(-5-(-1))f'(0)} = \frac{-5}4.
\end{align}
Answer: A bit late this answer but I think it is worth mentioning it.
Since $f$ is differentiable, we know that

$f(a+h) = f(a) + f'(a)h + o(h)$.

Now, replace $h$ by $3h,-2h,-5h,$ and $-h$ correspondingly and noting that $o(ch) = o(h)$ for any constant $c$ you get
$$\frac{f(a+3h)-f(a-2h)}{f(a-5h)-f(a-h)}= \frac{f(a) + 3hf'(a)+ o(h) - (f(a) - 2hf'(a) + o(h))}{f(a)-5hf'(a) + o(h)-(f(a) - hf'(a) + o(h))}$$
$$= \frac{5hf'(a)+o(h)}{-4hf'(a) + o(h)}\stackrel{h\to 0}{\longrightarrow}-\frac 54$$
Answer: $$ \lim_{h\rightarrow0}\frac{f(a+3h)-f(a-2h)}{f(a-5h)-f(a-h)}=\lim_{h\rightarrow0}\dfrac{3\dfrac{f(a+3h)-f(a)}{3h}+2\dfrac{f(a-2h)-f(a)}{-2h}}{-5\dfrac{f(a-5h)-f(a)}{-5h}+\dfrac{f(a-h)-f(a)}{-h}}=\frac{3f'(0)+2f'(0)}{-5f'(0)+f'(0)}.$$

Limit calculation using derivative


Display Main menu only on login page

Question: I am using Webform module and I used main menu to display the form on Login page. I want to display menu only on Login page but Main menu is also displaying on front page. Is their any way to hide displaying main menu on front page.
Answer: You have 3 simple options (And even more with preprocessors, but I won't go into that):

Most themes auto output the primary and secondary menu (configured in Appearance -> Global/THEMENAME -> Settings). You can turn it off on the theme settings, and use the Block system (Structure -> Blocks -> Main menu -> Configure) to put it on the pages (2 valid urls):
/user
/user/login

pages only.
(This is exactly the same as 1 except it's not database configuration, it's a code edit) Edit the page.tpl.php and comment out the lines that go something like:
if($primary_menu) { print $primary_menu; }

and again use the block system to output the main menu block on the login page (2 valid urls - see 1)
Or alternatively you can create a new custom menu, stick your form link there, and use the block system to assign it to the login page (2 valid urls - see 1). And leave your Main menu empty.
Answer: In Drupal 7 use Block Visibility settings to control the block Visibility.
Use PHP code:

    <?php
        if(/* Your conditon */){
            return TRUE
        }
        else{
            return FALSE;
        }

    ?>

Comment: Except if the theme displays the main menu outside of a block, as is sometimes the case.

Display Main menu only on login page


How to make N equal instalments of any amount?

Question: I am working on a financial software, in it I would like to offer an option of paying for an item in 3,6 or 12 instalments. I would be deducting each instalment amount via there Credit Card every month.
for example if I have an item that
costs $700,
and I want to make 12 instalments.
each instalment comes out to be, 700/12 = 58.3333333333.
Now If i use 58.33, 58.33*12 = 699.96.
If i use 58.34*12 = 700.08
I cannot store the amount 58.3333333333 becuase when using payment gateways they require the amount to be mentioned nearest 2 decimal places.
So I am confused on how to solve this problem.
any solution, or recommendation would be highly appreciated.
Answer: The easiest ways are sometimes the best ones...
You can add the resting to the first installment.
<code>r=((700.00*100)%12)/100; //=00.04
installment[0]+=r;       //=58.37
</code>
I dont think that would be a big problem - the resting for 12 months would be at most $0.11\$$.


How to set HTTP-Header when streaming an Audio file?

Question: I was following the tutoriel "Building an Audio Player app with Angular and RxJS" and managed to get the audio player working.
However, in order to load the audio from my server, I need to set the Authorization header. Is there a way to do this? I am already using a HttpInterceptor for this for all other requests but it seems that the interceptor is bypassed as I load the audio file.
The code below is how the audio gets loaded and played:

private audioObj = new Audio();

// ...

private streamObservable(url: string): Observable<any> {
  return new Observable(observer => {
    // Play audio
    this.audioObj.src = url;
    this.audioObj.load();
    this.audioObj.play().then();

    const handler = (event: Event) => {
      this.updateStateEvents(event);
      observer.next(event);
    };

    this.addEvents(this.audioObj, this.audioEvents, handler);

    return () => {
      // Stop Playing
      this.audioObj.pause();
      this.audioObj.currentTime = 0;
      // remove event listeners
      this.removeEvents(this.audioObj, this.audioEvents, handler);
      // reset state
      this.resetState();
    };
  });
}

Comment: Do you want it by streaming specifically?
Comment: @RafiHenig Ideally I'd like to _really_ stream the audio from my server to the client such that I never have to download the entire file but it seems that his would be a much more challenging task. For now I'd be happy to just load the file content from the server and play ("stream") it on the client side. Speaking of.. is it possible to transform the audio data before it actually gets played via output device? That would be handy in order to regulate loudness and/or other effects.
Answer: You can add the Authorization header to the audio URL as a URL parameter, along with a custom authentication handler on the server.
You may also (if streaming is not essential) use Angular HTTPClient to download the audio file as a Blob:
private playObservable(url: string): Observable<any> {
  this.http.get<Blob>(url, { responseType: 'blob' })
    .pipe(
      map(blob => window.URL.createObjectURL(blob)),
      switchMap(url => {
        return new Observable(observer => {
          // Play audio
          this.audioObj.src = url;
          this.audioObj.load();
          this.audioObj.play().then();

          const handler = (event: Event) => {
            this.updateStateEvents(event);
            observer.next(event);
          };

          this.addEvents(this.audioObj, this.audioEvents, handler);

          return () => {
            // Stop Playing
            this.audioObj.pause();
            this.audioObj.currentTime = 0;
            // remove event listeners
            this.removeEvents(this.audioObj, this.audioEvents, handler);
            // reset state
            this.resetState();

            window.URL.revokeObjectURL(url)
          };

        })
      })
    )

Comment: I do realize now why you asked about whether I want it "_by streaming_". I guess that was a misunderstanding. You solution downloads the entire file first and after that it plays the file. This is unfortunately not a solution in my case because the user would have to wait too long until the audio plays.
Comment: @Simon I don't think so but I discovered [`shaka-player`](https://github.com/google/shaka-player) lately. Haven't used it yet and I don't know if I will but you might want to take a look at it.
Comment: I thought you said  "For now I'd be happy to just load the file content from the server and play ("stream") it on the client side."
Comment: Yes, I think that's because "stream" is a bit ambiguous here. What I meant was that I don't need a more sophisticated mechanism like spotify/audible where you can jump to any arbitrary position right away. I think what they do is basically request specific chunks of an audio and sends only those bytes to the client. That's another level - but I need the audio to (at least) play "right away" after clicking the play button. Some files can be 30MB plus and the waiting time would just be too long :/ Sorry for the confusion.
Comment: @StefanFalk I have the same requirement. When I specify an Authorization header, my audio files are downloaded completely before the files are played. Have you found a solution for this?
Comment: In the end we implemented it without Authorization Header via signedUrls...


Prove that $\sqrt{-1}$ is not an element of $\mathbb{Q}(\sqrt[4]{-7})$

Question: I know this result seems obviously true but I'm not sure how to start.
Comment: What definitions of $\Bbb Q\left(\sqrt[4]{-7}\right)$ do you have?
Comment: @CameronBuie, Let a = quarticroot(-7). Then the minimal polynomial of a over Q is x^4 + 7, which has degree 4. Therefore [Q(a):Q] = 4. So a basis for Q(a) is 1, a, a^2, a^3
Answer: Okay, so it seems that you know that $$\Bbb Q\left(\sqrt[4]{-7}\right)=\left\{q+r\alpha+s\alpha^2+t\alpha^3:q,r,s,t\in\Bbb Q\right\},$$ where $\alpha^4=-7$ is given.
Now, if we had $\sqrt{-1}\in\Bbb Q\left(\sqrt[4]{-7}\right),$ then $\sqrt{-1}=q+r\alpha+s\alpha^2+t\alpha^3$ for some $q,r,s,t\in\Bbb Q,$ yes? Consequently, we have $$-1=\left(q+r\alpha+s\alpha^2+t\alpha^3\right)^2,\tag{$\star$}$$ or put another way, $$-1=\sum_{k=0}^3f_k(q,r,s,t)\alpha^k,$$ where each $f_k(q,r,s,t)$ is a polynomial in $q,r,s,t.$ I leave the calculation of these polynomials to you. Just expand the square in $(\star)$ and simplify using the fact that $\alpha^4=-7$.
Since $-1\in\Bbb Q\subset\Bbb Q\left(\sqrt[4]{-7}\right)$ and $\left\{1,\alpha,\alpha^2,\alpha^3\right\}$ is a basis for $\Bbb Q\left(\sqrt[4]{-7}\right)$ over $\Bbb Q,$ then we have the following system of equations: $$\begin{cases}f_0(q,r,s,t)=-1\\f_1(q,r,s,t)=0\\f_2(q,r,s,t)=0\\f_3(q,r,s,t)=0\end{cases}$$ While cumbersome, we can conclude from this system of equations that at least one of $q,r,s,t$ is not rational, yielding a contradiction. If you take this route, I would recommend that you proceed by cases, dealing with the case that $q=0$ (with subcases $r=0$ and $r\neq 0$), then the case that $q\neq 0$ and $t=0$, then the case that $qt\neq 0$ (so that each of $q,r,s,t\neq 0$). That last case is the least obvious, but I managed to prove that $s$ was irrational on two post-it notes in that case, so hopefully it isn't too much of a struggle.
Let me know if you have any trouble, any more questions about my answer, or just want to bounce your work off of somebody.
Comment: I had the same idea but I thought it was more-or-less operative. Is there another less computational solution?
Comment: @Eu: What have you come up with so far?
Comment: @I got -1 = a^2 -14bd -7c^2, 0 = 2ab - 14cd, 2ac + b^2 -7d^2 = 0, 0= 2ad + 2bc, where -1 = (a + bx + cx^2 + dx^3)^2 where x^4 = -7.
Comment: @Eu: That's *much* easier than what I did (in part because I made a calculation error. If you've proved that $ad\neq0$ implies that $b,c\neq 0,$ then you can proceed as you say and conclude $7d^2+b^2=0.$ This isn't (on its own) enough to conclude that $b=d=0,$ though. Rather, we must also use our assumption that each of $a,b,c,d$ is *rational* (and so real), from which we get the contradiction you say. Nicely done! :-)
Comment: @Charter: I imagine there may be, but this isn't too involved, computationally.


Tratando arquivo XML com PHP

Question: Eu tenho o seguinte XML:
<offer categoryId="3588" id="154394195459775522">
    <offerName>
        CAMISETA DROP DEAD PRODUCTION – MASCULINA VERDE ESCURO
    </offerName>
    <links>
        <link url="http://links.lomadee.com/ls/d25zZjsyRHd2U1I3MzsyODY4NjE3OTswOzU3OTg7MDs1NzE0O0JSOzM7aHR0cCUzQSUyRiUyRnd3dy5jZW50YXVyby5jb20uYnIlMkZwcm9tb2NhbyUzRm5leHRVcmwlM0R0LXNoaXJ0LWRyb3AtZGVhZC1wcm9kdWN0aW9uLTcwMjE0MDE4LTgxODE2OC5odG1sJTI2dHlwZSUzRHBkcCUyNmlkJTNEODE4MTY4JTI2dXRtX3NvdXJjZSUzRExvbWFkZWUlMjZ1dG1fbWVkaXVtJTNEeG1sJTI2dXRtX2NhbXBhaWduJTNETG9tYWRlZS1Ta2F0ZS1DYW1pc2V0YS0tODE4MTY4LTg2JTI2b3JpZ2VtJTNETG9tYWRlZTswOzA-.html" type="offer"/>
    </links>
    <thumbnail url="http://images.centauro.com.br/250x250/81816886.jpg"/>
    <price>
        <currency abbreviation="BRL"/>
        <value>49.9</value>
        <parcel>
            <value>24.95</value>
            <number>2</number>
            <interest>0.0</interest>
        </parcel>
    </price>
    <seller id="84" isTrustedStore="false" pagamentoDigital="false" advertiserId="5714" oneClickBuy="false" oneClickBuyValue="0" cpcDifferentiated="false">
        <sellerName>Centauro</sellerName>
        <thumbnail url="https://wwws.lomadee.com/programas/BR/5714/logo_185x140.png"/>
        <links>
            <link url="http://www.centauro.com.br" type="seller"/>
        </links>
    </seller>
    <startOffer>1969-12-31T21:00:00-03:00</startOffer>
    <endOffer>8994-08-17T04:12:55.807-03:00</endOffer>
    <category id="3588" isFinal="true">
        <thumbnail url="http://imagem.buscape.com.br/bp5/categorias/3588.jpg"/>
        <name>Shorts Esportivo</name>
    </category>
</offer>

Chamei o xml, via php da seguinte maneira:
 <?php
$xml = simplexml_load_file('arquivo.xml');
foreach ($xml as $details){
    echo "<href='" . $details->links ."'>" . $details->offerName . "
";
    echo $details->thumbnail . '
';
    echo "R$" . $details->price->value . '
';
    echo $details->price->parcel->value->number . '
';
    echo $details->seller->sellerName . '
';

    echo '
';
    }
?>

O problema é que está mostrando apenas o título, sem o link. Mostra o valor, sem o parcelamento. Não mostra o thumbnail.
Adicionando ----->
Conforme o código informado acima, ele trás um resultado em branco sempre na primeira linha.
Answer: Bem, de acordo com seu XML, você está trabalhando com uma oferta, então quando você utiliza o foreach para percorrer o XML, ele passará por todos os nós filhos da tag principal . Sendo assim quando você faz a chamada, por exemplo, "$details->offerName", lhe retornará um vazio.
Aconselho a fazer a leitura e chamar os elementos individualmente desta forma:
<?php
    $details = simplexml_load_file('arquivo.xml');

    echo "links[0]->link["url"] ."'>" . $details->offerName . "
";
    echo $details->thumbnail["url"] . '
';
    echo "R$" . $details->price->value . '
';
    echo $details->price->parcel->value->number . '
';
    echo $details->seller->sellerName . '
';
    echo '
';
?>

Comment: tentei assim, e nenhum dado apareceu na tela.
Comment: Errado, ele está iterando `offer. Para acessar dessa forma seria algo como `$details->offer->blablabla`
Comment: Não está, ele está iterando os nós filhos do offer verifique no manual do PHP [link](http://php.net/manual/pt_BR/function.simplexml-load-file.php) os exemplos.
Comment: Acho que é por ai @casscarraro , problema é que nem todos dados estão aparecendo, já testei de várias maneiras e nada.
Comment: Realmente, está iterando os filhos. executei o código aqui. Falha minha.
Comment: Bem, @GustavoCave para pegar os elementos você pode utilizar como no exemplo que eu citei acima, utilize o $details->"nome do nó". Caso você queira buscar todos os dados você pode utilizar o foreach, no entanto você deve cuidar com os elementos que possuem filhos, como no caso dos "links", que você terá que utilizar outro foreach para percorrer ou buscar um elemento fixo como eu dei o exemplo do "$details->links[0]".
Comment: @casscarraro criei 1 variável $a = links[0]->link["url"] e chamei a variável no echo dentro do href. Ainda não obtive sucesso.
Comment: Você deve atribuir o valor da $details->links[0]->link["url"], ou seja, $a = $details->links[0]->link["url"].
Comment: Infeslimente sem sucesso, vou tentar outras maneiras, qualquer outra ajuda é bem-vinda, obrigado por tudo até o momento. casscarraro e gmsantos!
Comment: Dentro do xml na tag  tem uma chamada do tipo type=offer, isso não está influenciando será?
Comment: Eu fiz um echo $details->links[0]->link["url"] . ;  e mostrou o link, mas quando coloco ele dentro do href, não funciona
Comment: Ele funcinou, mas sem usar variável. Ficou assim: echo "" . $details->offerName . "";
Answer: Tenha atenção ao utilizar o XML. Todos seus erros são relacionados ao tentar usar elementos de forma errada, sem seguir a estrutura do seu documento.
Note também que alguns dados são atributos dos elementos. Você pode acessar esses atributos através de um array do elemento.
Conforme observado também na resposta do @casscarraro, seu foreach está iterando os filhos de offer. Como seu arquivo só tem uma oferta, o foreach é desnecessário.

1- Para exibir o thumbnail, você deve colocar o conteúdo dentro da tag img e acessar o atributo url.
echo 'thumbnail["url"] . '">';

2 - $details->links é um grupo de links, o correto é associar ao elemento correto
echo "<href='" . $details->links->link->["url"] ."'>"

3 - Novamente, você especificou o caminho errado no seu xml para exibir a parcela.
echo $details->price->parcel->number . '
';

4 - O link não está aparecendo pois a tag do link está incorreta, faltou o a
echo " {$xml->offerName}
";

No final o código corrigido fica assim:
<?php

$xml = simplexml_load_file('arquivo.xml');

$link_url = $xml->links->link["url"];
$imagem_url = $xml->thumbnail["url"];

echo " {$xml->offerName}
";
echo "
";
echo "R$ {$xml->price->value}
";
echo "{$xml->price->parcel->number}x de {$xml->price->parcel->value}
";
echo "{$xml->seller->sellerName}
";

echo "
";

?>

Comment: Apenas o parcelamento funcionou. O link e o thumbnail ainda não.
Comment: Sabe alguma solução?
Comment: Fatal error: Call to a member function attributes() on a non-object...
Comment: Agora sim. Corrigido
Comment: Sem sucesso, não aparece nada da tela. Tentei igual o meu código original, acrescentando as variáveis $link_url e $imagem_url e chamando elas no echo e não obtive sucesso tbm, mas os dados aparecem.

Tratando arquivo XML com PHP


Why jquery menu collapse on all pages except front page

Question: I have a Drupal 8 site and them (upgraded from Drupal 7) and the main menu collapses to a button when the page is narrow enough (i.e. on a mobile device).  Or at least it is supposed to.  I did not design the theme.
SITUATION
Unfortunately when the menu is collapsed into a button, clicking on the button does NOT open the menu.
SITE SETUP
It seems that the old theme used jQuery to handle the collapse of the menu.
I have installed the jquery_ui module.
I added jquery to the .libraries.yml file
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.once

There are 4 template files which the only reason I can see is so that the main menu (which is hardcoded) can style the active menu item for the page.

page--node--2.html.twig
page--node--3.html.twig
page--node--6.html.twig
page.html.twig

Each of those pages has as the last line of the page a reference to the JavaScript file located in the site as

FIXED SOME OF IT
Adding jquery.main.js to the /js directory and adding the reference to it in the .library.yml file as
  js:
    js/main.js: {}
    js/jquery.main.js: {}

was enough to get all of the pages to collapse and open the menu EXCEPT THE FRONT PAGE.
JURY-RIG
I can get the front page menu to work if I add a reference to the bottom of the page to the jquery.main.js file I manually added to the local /js directory.

But then the other pages (not node 2, 3 or 6) which should use page.html.twig are run, it does NOT un-collapse the menu.
So for now I make a page--front.html.twig file which includes BOTH script referecnes to the JavaScript files, and all other pages have just the one (to main.js).
QUESTION
I have a couple:

What is the more standard way to situate this? I don't imagine that having a local jquery.main.js file is the best solution but it wasn't working with out it.
Why would the front page not operate like the other pages in accessing the JavaScript and jQuery?

Thank you for any insight.
Answer: Doing

is bad Drupal practice. As per the docs you should be doing
my_theme.libraries.yml
menu-collapse:
  version: 1.x
  js:
    js/main.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.once

page--node--2.html.twig
page--node--3.html.twig
page--node--6.html.twig
page.html.twig
{{ attach_library('theme_name/menu-collapse') }}

inside the template file(s).
Note: If this functionality is meant to be for every single page, rather then having to always add this to every variation of page.html.twig, add this in html.html.twig instead.

If after doing the above, the issue still persists

Why would the front page not operate like the other pages in accessing
the JavaScript and jQuery?

Possibly due to jQuery being loaded twice.
Go to /admin/config/development/performance and uncheck Aggregate JavaScript files (remember to turn back on after your're finished debugging)
Then on your front page, right mouse click, and select inspect
Go to network, and select JS, then refresh the page with the inspector open. You'll be able to see all the JS files that are loaded.

If there are no jQuery duplicates, in the inspector go to the "Console tab" and see if there is a JS error.


IPv6 AAAA vs. CNAME for same domain name

Question: I reach my home site through a DynDNS name, and also have tunneled IPv6 there.
In the DNS zone, I have:
myhomesite CNAME example.dyndns.org.

How do I simultaneously point "myhomesite" to an AAAA record? If I trivially make it
myhomesite CNAME example.dyndns.org.
myhomesite AAAA  2001:db8::1:2:3:4

the zone is invalid (CNAME and other data).
Can you suggest a way for having the CNAME record and the AAAA record visible behind the same domain name?
What I'm not looking for is an ".ipv6."-infixed record, which already is in place.
Answer: I copy from DNS for Rocket Scientists:

CNAME RRs cannot have any other RRs
  with the same name, for example, a TXT
  - well that was true until DNSSEC came along and in this case RRSIG, NSEC and
  certain KEY RRs can now occupy the
  same name.

Therefore what you want to do cannot be done using a CNAME.  Use the CNAME to access your homesite via IPv4 and have a myhomesite-v6 AAAA record point to the IPv6 address
If you do not want such a solution, you have to implement a mechanism that updates your DNS zone each time your IP address changes with:
myhomesite IN A IPv4.add.ress
           IN AAAA IPv6.add.ress

But that depends on the API (if any) that your DNS provider exports to you.  For example if I had root access on the DNS server, I would periodically host -t a example.dyndns.org and use the output to update the zonefile with the IPv4 address for myhomesite.
Comment: Thanks for your reply. The alternative that I have now is a BIND dynamic zone with a permanent AAAA record that accompanies the dynamic A record. It's not particularly hard to understand that CNAME and AAAA for the same domain can't coexist, but still, maybe there's a clever workaround that allows the use of DynDNS.
Comment: There is no workaround to the "`CNAME` rides alone" problem.


Can Python be invoked against a script file with a parameter-name for the script filepath?

Question: Does anyone know if the python3 command on Linux can have some sort of SOME_NAMED_OPTION=filename.py after it rather than just calling python3 filename.py?
I have a job scheduling tool I'd like to execute a Python script with that's kind of dumb.
It can only run Linux CLI commands commandname param1 param2 param3 or as commandname AAA=param1 BBB=param2 CCC=param3.
There's an existing business convention of putting filename.py as param #1 and then just making sure your script has a lot of comments about what the subsequent numerically ordered sys.argv list members mean, and you set the scheduling tool into its first mode, so it runs python3 filename.py world mundo monde, but it'd be awesome to be able to name the scheduling tool's parameters #2+ so I can write more human-friendly Python programs.
With python3 -h I'm not finding a way to give a parameter-name to filename.py, but I thought I'd see if anyone else had done it and I'm just missing it.
It'd be cool if I could have my scheduling tool run the a command more like python3 --scriptsource=filename.py --salut=monde --hola=mundo --hello=world and then write filename.py to use argparse to grab hola's, hello's, and salut's values by name instead of by position.
Comment: Assuming that you are using Bash as your shell, would it be feasible to add a shebang to the Python source file (i.e., have the command `#!python3` as the first line of the Python script)? If so, you could then run it simply as `./filename.py --salut=monde --hola=mundo --hello=world`, without having to explicitly reference the Python interpreter in the shell script.
Answer: You can create a python file to be executed as a script like in the example bellow:
    #!/usr/bin/python3  # path to python in your system

    print('This is a script!')

If your python file is named test.py you can execute as ./test.py if the file has permission to be executed. To grant execution permission to your file use the command chmod +x test.py
Comment: It might be worth highlighting the shebang portion and how it works. The shebang (`#!/path/to/exectuable`) tells the shell with what command it should execute the script.
Comment: That's interesting ... the scripts my coworker gave me as a template already have the shebang at the top.

Perhaps our job-scheduling tool setups are redundant...
Answer: Using the Shebang as suggested by @daniboy000 is the preferred method for doing this, but if for some reason you can't do that, you should be able to do python3 mycommand --arg1 --arg2=x
Comment: ahh. Strange. Well like i said, the shebangs are definitely the first way to go.
Comment: My comment with `python3 myscript.py --arg1 --arg2=x` is that I can't get my tool to pass `myscript.py` one style and the rest of the arguments another style.  Thanks though.