soloing over I-IV-V blues progression (E-A-B)

Question: First of all I would like to say that I have absolutely no musical education whatsoever, I have been studying alone and in the past with a guitar teacher. However, I am really into blues, watching lot of blues guitar lessons etc.
So I am interested in the most basic E7-A7-B7 blues progression. I am studying both minor and major scales, however one thing is not clear for me.
I understand that aforementioned blues progression is in the key of E, which means I can use the E minor/major pentatonic scale. However, when it progresses to A chord, should I change to A pentatonic scales or continue in E pentatonic scales throughout? The same question comes up with B7 chord.
Comment: Check also [this answer](http://music.stackexchange.com/questions/16103/i-iv-v-blues-progression/16114#16114) (and the other ones) to a related question.
Comment: Also, check out [this blog post](http://www.mathiaslang.com/2013/11/scales-over-12-bar-blues-great-example.html).
Comment: Continue in the key of E. Overall, the piece is in E. All the chords in a particular key (E in this example) will use the notes of that scale (E in this example). So basically, all the notes that are in the A chord and in the B chord are in the scale of E. This means you can keep soloing in E.
Answer: You could use either.
When soloing you would want to center the notes you play around the chord being played. The E major and minor pentatonic  scale contains the notes E, F#, G, G#, A, B, C#, and D.  The notes in a E7 are E, G#, B, and D the notes of an A7 are A, C#, E, G, and the notes of a B7 are B, D#, F#, and A. Of all the notes used in the 3 chords, only the D# is left out, but it can easily be put back in just passing between the D and the E.
When you switch the scale you are playing to A major and minor when the progression goes to an A7 and to B major and minor when you are playing an B7 it obviously centers the notes you play around the chord being played and make the chord change pop more, but can be difficult for a beginner as the scale changes a lot.
I encourage you to do both as the solos you would make will sound slightly different and you may prefer one sound over the other.
Answer: Also listen to blues artists that you like. Look at transcriptions and you will see the scale parts being used over the chord changes. You will notice in the key of E that the E pentatonic minor scale is used over all chords for tension. Start with a  basic minor pentatonic scale in E first then try the major pentatonic to hear the difference of major/minor sounds over the progression.  Pay attention to the 3rd and 7th of the chords when playing over them. For example: the third in E7 (G#) resolves nicely to the 7th in A7 (G). You can use that technique over all the chord changes.
Answer: In E, the minor blues scale notes are E, G, A, Bb, B, D. In A, the minor blues scale notes are A, C, D, Eb, E, G. In B, the minor blues scale notes are B, D, E, F, F#, A.
You can see there are some common notes - A, D and E being them.Theoretically, if you only played these, they would work over all 3 chords. But the tune may start to get boring! Not all notes played over a chord HAVE to fit the chord, but the best one ought to be the one with the same name - the root, often played on beat 1. One on one, I call it. Other notes are usable, so you could just use the original minor blues notes all through, even over A7 and B7. Most will fit, and not sound too bad, especially if you phrase it right. However, using the better fitting notes as mentioned earlier, a better fit will be heard. I.e. the A notes fit A better than, say, the E.
There is the same idea available using the major blues notes. A lot of blues players will move between the two lots, but also tend to use the minor blues mostly, bending the G to G# on the E for instance, or even just tweaking it so it sounds like it was a G#, but actually only went half way there.
So, in summary - stick to the E notes all through, with careful omissions and timing, or, when you are feeling brave (adventurous !) change the set of notes to match the appropriate chord.
Cream's Sunshine of your Love shows this well, in that the riff changes when the chord underneath changes. Just like so many blues and pop numbers do.
Answer: The idea behind "Key" used here is a little different than traditional key signatures.  Blues in E can be played exclusively with E minor (or major) pentatonic or the "blues" scale, which is pentatonic with a b5 added.
However a lot of players will use the Mixolydian mode over each chord, both in Jazz and Blues.  From a pure theory point of view E7 is the V7 chord of the key of A maj, and A7 the V7 of D maj, and B7 the V7 of E maj.  This is a lot of moving around and the pentatonic allows one to make simple melodies that work over this without over thinking.
Rather than thinking of this as 3 different keys what a lot of players do is structure solos within the E pentatonic framework and add chord tones as desired.  This gives you options on the fly without overthinking.  But I would consider using all these scales, pentatonic, Blues (both maj and min), and mixolydian to work out interesting ideas.


Freetts is not working with external speakers

Question: I have used Freetts.jar file in my java application that announces the token number. My application is working perfectly in my laptop but is not working in my desktop that has an external speaker. I get a null pointer exception. NOTE: I use Windows 7 in both my computers.
The Below Code is the Sample Format I used.
package tsapp;

import java.util.Locale;
import javax.speech.Central;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.swing.JOptionPane;
public class TextSpeech {
 public static void main(String[] args){
 try
 {
   System.setProperty("freetts.voices",
    "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");

   Central.registerEngineCentral
    ("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
   Synthesizer  synthesizer =
    Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
   synthesizer.allocate();
   synthesizer.resume();
   String str;

        str=JOptionPane.showInputDialog(null,"Voice Check");
        if(str==null)
        return;
        synthesizer.speakPlainText(str, null);
   synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
   synthesizer.deallocate();
  }
   catch(Exception e)
   {
       System.out.println(e.getClass());
     e.printStackTrace();
   }
 }
}

Comment: You can use MaryTTS , a lot better ;) http://mary.dfki.de/
Comment: Thank You for ur suggestion. But I want to know what causes the error in my application.
Comment: Can you provide a simple piece of code that is running so we can test it? Maybe it has to do with the resource allocation or something internal.
Answer: Can we do one simple thing:

Download binary https://netix.dl.sourceforge.net/project/freetts/FreeTTS/FreeTTS%201.2.2/freetts-1.2.2-bin.zip
Add to your project
Write simple code.

Like this
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class TestVoice {

    public static void main(String[] args) {

        String text = "Voice check!";

        Voice voice;
        VoiceManager voiceManager = VoiceManager.getInstance();
        voice = voiceManager.getVoice("kevin");
        voice.allocate();
        voice.speak(text);

    }

}

Just be sure that all these libs are on your desktop too.
Comment: Thank You Mr. Saulius. But could you please explain the mistake I did.
Comment: I suspect that you haven't copied all libs to your desktop. Also next times please provide exception then I could say more about issue, and try to write simple code because this way you can get bets results. I'm not the expert with FreeTTS therefore I can't comment anything else.
Comment: Thank You though for your help Mr. Saulius


How to get maximum and minimum of a list in column?

Question: Given that, I have a dataframe as below:
import pandas as pd
import numpy as np

dict = {
        "A": [[1,2,3,4],[3],[2,8,4],[5,8]]
}

dt = pd.DataFrame(dict)

I wish to have the Maximum and minimum of each row in column B. My favorite output is:
              A    B
0  [1, 2, 3, 4]    [1,4]
1           [3]    [3,3]
2     [2, 8, 4]    [2,8]
3        [5, 8]    [5,8]

What I already tried is the below code which does not work:
dt["B"] =[np.min(dt.A), np.max(dt.A)]

Comment: i meant, something like a loop in this question:
https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas however, `apply` is a good solution.
Answer: Like this:
In [1592]: dt['B'] = dt.A.apply(lambda x: [min(x), max(x)])
In [1593]: dt
Out[1593]:
              A       B
0  [1, 2, 3, 4]  [1, 4]
1           [3]  [3, 3]
2     [2, 8, 4]  [2, 8]
3        [5, 8]  [5, 8]

As suggested by @Ch3steR, using map since it's faster:
dt['B'] = dt.A.map(lambda x: [min(x), max(x)])

Comment: `dt.A.map(...)` is a little faster than `pd.Series.apply` as `pd.Series.map` is made for element-wise calculations. And `map` was around ~20-30µs faster not much though.
Answer: You can create DataFrame, then minimal and maximal values by DataFrame.agg, convert to lists and assign back if requirement is no loops (Apply are loops under the hood):
df = pd.DataFrame(dt.A.tolist())
dt['B'] = df.agg(['min','max'], axis=1).astype(int).values.tolist()
print (dt)
              A       B
0  [1, 2, 3, 4]  [1, 4]
1           [3]  [3, 3]
2     [2, 8, 4]  [2, 8]
3        [5, 8]  [5, 8]

If no problem with loops another solution with list comprehension, it should be faster like apply, depends of real data:
dt['B'] =  [[min(x), max(x)] for x in dt.A]

Comment: Out of all the solutions `[[min(x), max(x)] for x in dt.A]` was the fastest. +1
Comment: @Erfan Yes, I `timeit` all the solutions. And *list comp* was the fastest by 10x than the second fastest solution. May be my analysis may not be fair cause I didnot test it with large lists and large DataFrame.
Comment: Ah oke, I think comparison should be done on reasonably large data to see the efficiency of the methods.
Comment: @Ch3steR was it faster than the first solution of jez? I wouldnt expect it.
Comment: @Erfan With large data I would use some custom function which would calculate `min` and `max` in a single pass may be using `cython`. Here we are iterating twice over the same iterable when it can be done in one pass and if lists are small it wouldn't matter anyway. Testing with large data is better I agree.
Comment: In the first method its not. Its all vectorized methods. Thats why I dont expect it to be slower than the loop. Actually im pretty sure it would be quite faster.
Comment: @Erfan - I modify answer, because I think it depends of data.
Answer: Just an alternative with explode:
dt['B'] = (dt['A'].explode().astype(int).groupby(level=0).agg(['min','max'])
           .to_numpy().tolist())
print(dt)

              A       B
0  [1, 2, 3, 4]  [1, 4]
1           [3]  [3, 3]
2     [2, 8, 4]  [2, 8]
3        [5, 8]  [5, 8]

Answer: Use list comprehension on sorted values in dt.A
 dt['B']= [[row[0], row[-1]] for row in dt.A.map(lambda x: sorted(x))]


How to fetch a specific column from multiple CSV files with pandas

Question: I am trying to fetch Adj Close column from multiple csv files.
Sample csv file (same content can be copied to aapl.csv, msft.csv and hcp.csv:
Date    Open    High    Low Close   Volume  Adj Close
10/14/08    116.26  116.4   103.14  104.08  70749800    104.08
10/13/08    104.55  110.53  101.02  110.26  54967000    110.26
10/10/08    85.7    100 85  96.8    79260700    96.8
10/9/08 93.35   95.8    86.6    88.74   57763700    88.74
10/8/08 85.91   96.33   85.68   89.79   78847900    89.79
10/7/08 100.48  101.5   88.95   89.16   67099000    89.16
10/6/08 91.96   98.78   87.54   98.14   75264900    98.14
10/3/08 104 106.5   94.65   97.07   81942800    97.07
10/2/08 108.01  108.79  100 100.1   57477300    100.1
10/1/08 111.92  112.36  107.39  109.12  46303000    109.12
9/30/08 108.25  115 106.3   113.66  58095800    113.66
9/29/08 119.62  119.68  100.59  105.26  93581400    105.26
9/26/08 124.91  129.8   123 128.24  40208700    128.24
9/25/08 129.8   134.79  128.52  131.93  35865600    131.93
9/24/08 127.27  130.95  125.15  128.71  37393400    128.71
9/23/08 131.85  135.8   126.66  126.84  45727300    126.84

My code is:
import pandas as pd
def test_run():
    start_date = '2008-10-01'
    end_date = '2008-10-09'
    dates = pd.date_range(start_date, end_date)
    df1 = pd.DataFrame(index=dates)
    dfSPY = pd.read_csv(
        'aapl.csv',
        index_col='Date',
        parse_dates=True,
        usecols=['Date', 'Adj Close'],
        na_values=['nan'])
    df1 = df1.join(dfSPY, how='inner')
    df1 = df1.rename(columns={'Adj Close':'SPY'})
    symbols = ['aapl', 'msft', 'hcp']
    for sym in symbols:
        df_temp = pd.read_csv(
            '{}.csv'.format(sym),
            index_col='Date',
            parse_dates=True,
            usecols=['Date', 'Adj Close'],
            na_values=['nan'])
        df_temp = df_temp.rename(columns={'Adj Close':sym})
        df1 = df1.join(df_temp, how='left')
    print(df1)
if __name__ == "__main__":
    test_run()

I get error when I run it:
Traceback (most recent call last):
  File "1.py", line 27, in <module>
    test_run()
  File "1.py", line 22, in test_run
    na_values=['nan'])
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 678, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 440, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 787, in __init__
    self._make_engine(self.engine)
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 1014, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 1749, in __init__
    _validate_usecols_names(usecols, self.orig_names)
  File "/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 1134, in _validate_usecols_names
    "columns expected but not found: {missing}".format(missing=missing)
ValueError: Usecols do not match columns, columns expected but not found: ['Adj Close']

I tried referring multiple links but couldn't figure out what I missing here. Thanks in advance.
Comment: `dfSPY` worked, but `df_temp` did not, despite the same structure.  Perhaps one of your files does not have the `Adj Close` field, or it has white space around it that needs to be trimmed.
Comment: I dint notice there was an extra . in Adj Close column! Thanks for pointing it out. You can post your comment as an answer, I will accept it.
Answer: Given your stack trace of the error (thanks for posting the full trace), you notice that the function is called on line 27 (test_run() at the bottom of your code).  The error, however, starts 5 lines up at line 22.  This is the initial assignment of df_temp, which is the second time you call the pd.read_csv function.  Because it worked the first time for dfSPY with virtually the same arguments, it means that there must be something different with the file format for one or more of the securities.   Perhaps one of your files does not have the Adj Close field, or it has white space around it that needs to be trimmed.
Comment: Thank you so much @ Alexander! Appreciate your quick and crisp answer!


Python mechanize: encode cause strange character

Question: Here is my code:
import re
import mechanize

br = mechanize.Browser()
br.open("http://www.douban.com/")
print br.title()

what I visit is a Chinese website, but the return title is strange character,
how can I fixed this problem?
Comment: Could you please give the strange character to us, by using repr(br.title())? Also please provide the original Chinese content.
Comment: @Sheng: the correct title should be `豆瓣`, but the strange character is `璞嗙摚`, which is not I want
Answer: If you just do br.title() it will give you the unicode string of the special character.
print attempts to display the non-ASCII character by encoding the Unicode string.
Answer: It is because the charset issue. For example, in Python 3.X:
>>> print("豆瓣".encode("utf8").decode('gbk'))
璞嗙摚

In other words, thte content "豆瓣" from the serive is encoded in charset "utf8". But your client try to display it as charset "gbk". To solve this problem, you need to transfer the content between these two different charsets, such as br.title().encode('gbk').decode("utf8")
Comment: so this is just the display problem? what I get is still right, when I save it to database, the content is still in utf8?
Comment: @hh54188 Kind of, yes. In the memory, or in terms of the bytes, what you get is what you want. But your system has to choose a charset to interpret these bytes and print them out. The string is encoded as utf8 into bytes. If you use gbk charset to interpret these bytes, you will get the incorrect print_out_content.


How can I add term's vocabulary name as body class?

Question: I already had following codes added, which adds term ID as body class. However, how can I change the ID to term's vocabulary name?
For example:

<body class="term-type-cameras">

<code>/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    // Load the term entity and get the data from there.
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term_id'] = $term->id();
    $variables['vocabulary_id'] = $term->bundle();
    $variables['attributes']['class'][] = 'term-' . $term->id();
  }
}
</code>
Comment: The original code looked like you did this in the Claro theme code. I hope that was just a sample and you created your own custom theme or module for that. Never hack core or contrib. Changes will get lost on the next update.
Comment: Thanks @leymannx, I did build my site based on Claro, but it's really my first ever time to know that...Appreciate your reminder!  :)
Answer: You can use <code>$term->bundle()</code> method to get term vocabulary and then use it as part of the class.
<code>$variables['attributes']['class'][] = 'term-type-' . $term->bundle();
</code>
Comment: You should pass the `$term->bundle()` through [cleanCssIdentifier](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Html.php/function/Html%3A%3AcleanCssIdentifier/8.2.x)


User logout automatically when the browser is closed

Question: I need to logout a user if the browser is closed. I'm using Drupal 8.
I tried setting a session cookie in php. But the problem is the cookie should be 'httponly' and 'secure'.
Please suggest me the right method or is Drupal having such settings to achieve  this.
Thanks.
Answer: Okay, I changed the cookie_lifetime: 2000000 to 0 in local.services.yml file.
Then set the cookie in php by giving the last 2 arguments as 'true' ,this makes the cookie to be httponly and secure.
Thanks for your reference.


Spamicide field still visible

Question: To prevent spambot making fake user accounts I've installed Spamicide.
I've enabled the module Spamicide (7.x-1.0-beta3) and enabled the field for form_id user_register_form, filled in a Spamicide directory and chose a custom FORM FIELD NAME.
Now when creating a new account I still see a empty field with a description:
"To prevent automated spam submissions leave this field empty". I was expecting that this was hidden by CSS?
Also the directory name I've setup can't be found, is it not created by itself?
The flooding of spambots creating fake accounts is stopped, but the empty field and belonging message looks stupid for real users.
Can you tell me if I did setup something wrong or if this could be an bug?
Answer: It's not really a bug. Simply hide it in your theme instead. Just try to use technique a bit less obvious than display: none; as many bots know it already. Note that newest version of Spamicide module (7.x-1.0-beta3 at the moment of posting) does not even provide CSS file. All it does is:
/**
 * #post_render callback on the spamicide field. This will wrap the field
 * in a div so it can be hidden with CSS.
 *
 */
function _spamicide_field_post_render($content, $element) {
    return '
' . $content . '
';
}

See line 81 of spamicide.inc.

Spamicide field still visible


<> Duvida no retorno do Map - //Map // - esta voltando: null

Question: vou deixar o bloco do codigo --(Recupera api da https://viacep.com.br/, os dados listados no cod, fim de estudos e treinamento)
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

    String _resultado = "Resultado";

  _recuperarCep() async {

    //String cep = "01001000";
    String url = "https://viacep.com.br/ws/01001000/json/";
    http.Response response;

    response = await http.get(url);

    //Map<String, dynamic> retorno = json.decode( response.body );

    Map <String, dynamic> retorno = jsonDecode(response.body);

    String logradouro = retorno["Logradouro"];
    String complemento = retorno["Complemento"];
    String bairro = retorno["Bairro"];
    String localidade = retorno["Localidade"];

    setState(() {
      _resultado = "${logradouro},${complemento},${bairro},${localidade},";
    });

    print(
        "Resposta logradouro: ${logradouro} complemento ${complemento} bairro ${bairro} localidade ${localidade}"
   );

    //print("Resposta:"+ response.statusCode.toString());
    //print("Resposta:"+ response.body);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Consumo de serviço web"),
      ),
      body: Container(
        padding: EdgeInsets.all(40),
        child: Column(
          children: <Widget>[
            Text(_resultado),
            RaisedButton(
              child: Text("Clique aqui"),
              onPressed: _recuperarCep,
            )
          ],
        ),
      ),

    );
  }
}

Answer: Preste mais atenção na API que você está utilizando... Ela retorna esse JSON abaixo e você esta lendo o mesmo de forma errada.

{
  "cep": "01001-000",
  "logradouro": "Praça da Sé",
  "complemento": "lado ímpar",
  "bairro": "Sé",
  "localidade": "São Paulo",
  "uf": "SP",
  "unidade": "",
  "ibge": "3550308",
  "gia": "1004"
}

O problema não é o Map<> retornado, mas sim como você está lendo os dados dele...
Flutter é caseSensitive, então...
Mude isso aqui
String logradouro = retorno["Logradouro"];
String complemento = retorno["Complemento"];
String bairro = retorno["Bairro"];
String localidade = retorno["Localidade"];

Para
String logradouro = retorno["logradouro"];
String complemento = retorno["complemento"];
String bairro = retorno["bairro"];
String localidade = retorno["localidade"];

Comment: perfeito deu certo, foi uma desatenção minha, sou muito grato a sua ajuda vlw obrigado.


All my observations are identical. Use a non-parametric test?

Question: I was doing test for normality on variables and came across one that had identical values for each observation.  I can't do a normality test.  I plotted the kernel density and it looks normal, however a qq plot says different.  I have not come across this situation before and am not sure how to proceed.  Can I assume normality and use t.test or should I go non-parametric?  I need to test for differences with another sample.
Forgive me if the answer is obvious.  Cheers.
Here is an example.
Say we have 10 stores selected at random in a city that all sell the same item.  The price of that item at some time point is say $50.00 for each store (sample 1).  Some time later, a material used to make that item becomes slightly harder to come by.  After the availability of the material changes, the price of the item is checked at each of the original 10 stores, with the prices this time being say 50,50,50,50,50,50,51,50,50,49 (sample 2).  I want to test if there is a difference in mean price before and after the availability of the material changed.  First I check for normality, but this is difficult for sample 1 as they are all the same price.  The usual tests for normality will not work for sample 1.  So, I am unsure if I can compare the mean difference using a t.test or if I need to compare location shift using a non-parametric test.
Comment: If your values are constant, even for a small sample, they're clearly not normal; why would you even try to test what you already know for certain? To apply any test, you should think about your situation and what assumptions might be reasonable for it.
Comment: OK that's more clear now.
Answer: A couple of points:

The KDE is not designed to assess normality, so don't use it that way.
It is clearly not reasonable to assume that your data (e.g. the vector of 10 price differences $d_i:=p_{2i}-p_{1i}$ where many of the $d_i$'s are 0) is normally distributed. You should, as a rule, prefer the sign test (specially as part of your working assumptions that the price differences are likely skewed). Furthermore, in a sign test, the large number of $d_i$ that are exactly 0 will simply 'drop' from the calculations, making this a non issue.
Comment: I am for sure dealing with a random variable, however I have a very small sample size.  My only concern is if I should use a non-parametric method to test for differences between paired samples or a t.test.  Only 1 sample has identical values, the other does not. I hope that clarifies.
Comment: No, it's not clear: how many repetitions do you have?
Comment: I added an example I hope will make my question more clear.


Let $L$ be the distance between two parallel normals of $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$, $a>b$, then find maximum value of $L$

Question: Let the equation of normal be
$$ax\sec t -by\csc t=a^2-b^2$$
Let the parameters of the two normals be $t$ and $r$
Their slopes are equal
$$\frac{\sec t}{\csc t}=\frac{\sec r}{\csc r}$$
$$\sin t \cos r-\cos t \sin r=0$$
$$t-r=n\pi$$
Let $n=1$
$$t-r=\pi$$
$$t=\pi +r$$
So the first equation becomes
$$ax\sec r -by\csc r =b^2-a^2$$
The distance between two parallel lines is
$$\frac{|a^2-b^2+b^2+a^2|}{\sqrt{ a^2\sec ^2r+b^2\csc^2 r}}$$
To  minimise the denominator , differentiating wrt $r$
$$2a^2\sec^2r\tan r-2b^2\csc^2r\cot r=0$$
$$\tan ^2r=\frac ab$$
Then $$L =\frac{2a^2}{a+b}$$
The given answer is $2(a-b)$, but I am unable to find what is wrong in my computation.
Thanks for the help
Comment: Did you mean $\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$?
Comment: @DhanviSreenivasan yes
Comment: Sin't the parametric form for a normal to an ellipse $\frac{x\sec\theta}{a} - \frac{y\tan\theta}{b} = 1$?
Comment: What about $r=0$ or $\pm\frac{\pi}{2}$? I think this cases are not covered as $1/\sin r$ and $1/\cos r$ are not defined there. @Aditya
Comment: @AlexeyBurdin I think the form is wrong, checked it on google
Comment: @AlexeyBurdin they aren't defined. What are you implying?
Comment: @DhanviSreenivasan I think my form is right. The one you gave is for tangent of hyperbola
Comment: Right, my bad. That's fine\
Comment: Isn't the numerator $|a^2-b^2+b^2-a^2|=0$? But maybe just a typo. Anyway I don't see how to get $2(a-b)$ from [$a^2\sec^2\left(\arctan\sqrt{\frac{a}{b}}\right)+b^2\csc^2\left(\arctan\sqrt{\frac{a}{b}}\right)=\dfrac{(a + b)^2 (a^2 - a b + b^2)}{a b}$](https://www.wolframalpha.com/input/?i=%28a%5E2%2Fcos%5E2%28atan%28sqrt%28a%2Fb%29%29%29%29%2B%28b%5E2%2Fsin%5E2%28atan%28sqrt%28a%2Fb%29%29%29%29)
Comment: @AlexeyBurdin it was a typo, thanks for pointing it out
Answer: Rather than using parametric coordinates, one can express the normal to an ellipse in the slope for
For a given slope $m$, the normal to an ellipse can be expressed as
$$y = mx \pm \frac{m(a^2-b^2)}{\sqrt{a^2 + b^2m^2}}$$
Hence, for any slope, the distance can be expressed as
$$L(m) = \frac{d}{\sqrt{1+m^2}}$$
where $d = \frac{2m(a^2-b^2)}{\sqrt{a^2 + b^2m^2}}$
Hence
$$L(m) = (a^2-b^2). \frac{m}{\sqrt{1+m^2}\sqrt{a^2 + b^2m^2}}$$
Comment: That's fine, but I want to know why mine didn't work, since $m^2=\frac ab $ is equivalent to $\tan^2 r =\frac ab$
Answer: Note that your distance expression is off. Given symmetry, the distance between the two parallel normals is twice the distance from origin to either line. So, continue with
$$ax\sec t -by\csc t=a^2-b^2$$
 to express the distance as
$$d(t)=\frac{2(a^2-b^2)}{\sqrt{ a^2\sec ^2t+b^2\csc^2 t}}\tag1$$
Set $d'(t)=0$ to get $\tan t= \pm\sqrt{\frac ba }$ and substitute into (1) to obtain the maximum distance
$$d_{max}= \frac{2(a^2-b^2)}{\sqrt{ a^2+b^2+2ab}}= 2(a-b)$$
Answer: Okay, another try.
Given $$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$$
and performing implicit differentiation we have
$$\frac{2x}{a^2}+\frac{2y'y}{b^2}=0$$
I won't consider a slope 'cause it may be equal to $\pm\infty$, instead a normal vector will be $$\left(\frac{x}{a^2},\frac{y}{b^2}\right)
\hbox{ or }(b^2x,a^2y)$$
with parametrization $x=a\cos t,\,y=a\sin t$ it will be $$(b\cos t,a\sin t)$$
Since the lines for parameters $t,r$ are collinear, we have cross product $=0$: $$(b\cos t)(a\sin r)-(b\cos r)(a\sin t)=0 \\ \sin(r-t)=0,\hbox{ so }\\r-t=\pi n$$
So the points will be $$(-a\cos r,-b\sin r),\,(a\cos r,b\sin r)$$
with the of difference $$(2a\cos r,2b\sin r)$$

and we have to dot multiply by the perpendicular to the normal vector and divide by its length to get the desired distance:
$$\begin{align*}\frac{|2(a\cos r,b\sin r).(-a\sin r,b\cos r)|}{\sqrt{(b\cos r,a\sin r)^2}}&=\frac{(a^2-b^2)|\sin(2r)|}{\sqrt{b^2\cos^2 r+a^2(1-\cos^2 r)}}\\
&=\frac{(a^2-b^2)|\sin(2r)|}{\sqrt{(b^2-a^2)\cos^2 r+a^2}}\\
&=\frac{(a^2-b^2)|\sin(2r)|}{\sqrt{(b^2-a^2)\frac{\cos(2r)+1}{2}+a^2}}
\end{align*}$$
so the formula for $L$ seems to correspond with OP's one.
Equating the derivative to $0$ we get
$$2r=2\pi n-2\arctan\left(\frac{\sqrt{b}}{\sqrt{a}}\right)$$
and substituting it back we have $$\frac{2(a^2-b^2)}{a+b}$$ so I'd suggest expanding the lines after finding the explicit formula for $L(r)$ so we can see if is there a mistake. Thanks.


How to use different ports on single Tomcat instance which listens on a single port?

Question: Using a single Tomcat instance, which listens on a single port, how can I host multiple websites under different hostnames and port numbers?
Example:
Let's say that the single tomcat instance is listening on a single port: At localhost:9090.
How can I configure Tomcat and/or my webpages in order for both of the following requests (which are sent to localhost:9090) to work?
Request 1:
GET /index.html HTTP/1.1
Host: www.sample.com

Request 2:
GET /index.html HTTP/1.1
Host: www.sample.com:120

Comment: Why do you need different ports?
Comment: @Stefan For learning. I suppose that it should be possible. So, I would like to learn how to do it.
Answer: Setup different connectors in conf/server.xml (don't choose ports below 1024):
....
<Connector port="80" connectionTimeout="20000" protocol="HTTP/1.1" redirectPort="8443"/>
<Connector port="1234" connectionTimeout="20000" protocol="HTTP/1.1" redirectPort="8443"/>

<Engine defaultHost="localhost" name="Catalina" jvmRoute="tomcat8">

    <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
    </Realm>

    <Host name="localhost"      appBase="webapps"           autoDeploy="true"unpackWARs="true"></Host>
    <Host name="www.sample.com" appBase="webapps-samplecom" autoDeploy="true"unpackWARs="true"></Host>
    ...

</Engine>
...

This will enable www.sample.com, www.sample.com:1234.
Comment: Will let you know after I get the chance to try it. Thanks.


How to pass arguments to callable method specifically for register_shutdown_function?

Question: I have method, in this method may be happened fatal error, for catching this error I make this
class a {

    function shutDownFunction() {
        $error = error_get_last();
        if ($error['type'] == 1) {
            echo "this is fatal error";
        }
    }

    function terribleFunction () {
        register_shutdown_function(array($this,'shutdownFunction'));

        // here is code, wich may causes fatal error

    }

}

Okay, this understand, but I need pass argument from terribleFunction to shutDownFunction. How to make this?
Comment: Maby you are looking for [call_user_func_array](http://php.net/manual/en/function.call-user-func-array.php)
Comment: Also, you can't catch fatal errors. They are fatal for a reason.
Answer: First you need to specify that shutDownFunction should accept a parameter.
function shutDownFunction($var)
Then you can call register_shutdown_function as so
register_shutdown_function(array($this, 'shutdownFunction'), $myVar);
Documentation is here and there are examples in the comments.
Answer: You should only use one register_shutdown_function and not use it just inside a method to catch errors in that method. For error catching use a try, catch, finally block
See:
http://php.net/manual/en/language.exceptions.php
Answer: You can check register_shutdown_function documentation. There is a second optional argument parameter which is passed to your shutDownFunction(). This function you can define like this:
function shutDownFunction($args) {
   //do whatever you want with $args
}


Member function self defined Type returns 'does not name a type' error in C++

Question: Inside of my class, I declare a type with the 'using' keyword, "bigvalue_t" and attempt to create a function that returns the same type (to_vector). I get returned this error through gcc:
 g++ -g -O0 -Wall -Wextra -std=gnu++11 -c bigint.cpp
 bigint.cpp:45:1: error: 'bigvalue_t' does not name a type
 bigvalue_t bigint::to_vector (string& strval) {
 ^

Here is the class from my header file:
class bigint {
  friend ostream& operator<< (ostream&, const bigint&);
private:
  long long_value {};
  using unumber = unsigned long;
  using digit_t = unsigned char;
  using bigvalue_t = vector<digit_t>;
  bool negative;
  bigvalue_t big_value;
  string to_string (unumber& num);
  bigvalue_t to_vector (string& strval);
  using quot_rem = pair<bigint,bigint>;
  friend quot_rem divide (const bigint&, const bigint&);
  friend void multiply_by_2 (unumber&);
  friend void divide_by_2 (unumber&);
public:

  //
  // Ensure synthesized members are genrated.
  //
  bigint() = default;
  bigint (const bigint&) = default;
  bigint (bigint&&) = default;
  bigint& operator= (const bigint&) = default;
  bigint& operator= (bigint&&) = default;
  ~bigint() = default;

  //
  // Extra ctors to make bigints.
  //
  bigint (const long);
  bigint (const string&);

Here is my constructor and the function in question:
bigint::bigint (long that): long_value (that) {
   using digit_t = unsigned char;
   using bigvalue_t = vector<digit_t>;
   if (that < 0) this->negative = true;
   else this->negative = false;
   unumber that_value = that;
   string that_str = to_string (that_value);
   bigvalue_t bignum = to_vector (that_str);
   }

bigvalue_t bigint::to_vector (string& strval) {
   digit_t digi;
   bigvalue_t digivec;
   for (auto it = strval.rbegin(); it != rend; ++i) {
       digi = strval[it];
   digivec.push_back(digi);
   }
  return digivec;
}

Any ideas as to whats going on would be much appreciated! It doesn't seem to pick up my type definition. I was allowed to use my other self defined variable "unumber" in an earlier method without fault so this has me scratching my head.
Comment: `using` directives are only valid in the scope where they appear.
Comment: Use `bigint::bigvalue_t bigint::to_vector (string& strval)` or `auto bigint::to_vector (string& strval) -> bigvalue_t`
Comment: Excellent, Piotr's answer resolved my issues with scope.
Comment: Shame he posted his answer as a comment.
Answer: As state in comment, use
bigint::bigvalue_t bigint::to_vector (string& strval)
{
    // body
}

or since C++11
auto bigint::to_vector (string& strval) -> bigvalue_t
{
    // body
}

Comment: Thanks a bunch.  Both of these resolved my scope problem.  The C++11 revision seems handy.


Can a rational number represent the area of square?

Question: Let $r = p/q>0$ be a rational number with $gcd(p,q)=1$.
Is it possible to find a square delimited by pairs of lines ($d_1$, $d_2$) and ($d_3$, $d_4$)
such that :

$d_1 \parallel d_2$ (blue lines) and $d_3 \parallel d_4$ (green lines)
$d_1 \perp d_3$
$d_1$, $d_2$, $d_3$ and $d_4$ pass through points with integers coordinates.
The polygon delimited by those lines is a square of area $r$.

We can assume $d_1=(AB)$ where $A(0,0)$ and $B(a,b)$.
The task is possible if we can find a point $C(x,y)$ such that $d(C, (AB)) = \sqrt{r}$ because :

we can then define $d_2$ as the parallel to $d_1$ passing through $C$.
we define $d_3$ and $d_4$ as the rotation of $d_1$ and $d_2$ around the point $A$ with an angle of $\pm \frac{\pi}{2}$.

The distance between $d_1$ and $d_2$ is the same as the one between $d_3$ and $d_4$.
So the polygon delimited by those lines has an area of $r$.
The distance between $d_1$ and $d_2$ is :
$$\frac{|-bx+ay|}{\sqrt{a^2+b^2}}=\sqrt{r} \Longrightarrow p(a^2+b^2)=q(ay-bx)^2$$

For example, if $r=\frac{4}{5}$, there is a solution with $a=2$, $b=-1$, $x=0$ et $y=-1$
because $4 \times(2^2 + (-1)^2) = 5 \times(2 \times(-1) + 1\times 0)^2$ (see picture)
If $r=\frac{1}{4}$, it is impossible. If it was, we would have four integers $a\not=0$, $b\not=0$, $x$, $y$ such that :
$$a^2+b^2=4(ay-bx)^2$$
So $a$ and $b$ are both even and $a'=\frac{a}{2}$ and $b'=\frac{b}{2}$ may define a solution to the same equation leading to $a=b=0$ (by repeating this).

My questions are :

How do we know programmaticaly if a solution exists? (no brute force)
In that case, how do we (for arbitrary large values of $p$ and $q$) find a solution ?

I suspect this is related to gaussian integers and modular arithmetic.
Answer: By rescaling the point $B$, you may assume that $\text{gcd}(a,b) = 1$. Then by Bezout's theorem, the expression $ay-bx$, as $x$ and $y$ vary over the integers, can be made to equal any integer. So, you are asking when there is a solution to the equation $p(a^2+b^2) = qc^2$ for certain given coprime positive integers $p$ and $q$.
If $p = k^2p'$, then $k \mid c$ and writing $c' = kc$, we reduce to $p'(a^2+b^2) = qc'^2$. Hence, we may assume that $p$ is squarefree. With this assumption, it follows that $p \mid c^2$ implies that $p \mid c$. So write $d = pc$ to obtain $a^2+b^2 = pqd^2$. We are thus asking for a number of the form $pqd^2$ to be the sum of two non-zero squares.
A number is the sum of two squares if and only if all its prime divisors $r \equiv 3 \mod 4$ occur an even number of times. This condition is vacuous for the factor $d^2$, so this is possible if and only if $pq$ is the sum of two non-zero coprime squares, which is guaranteed as soon as the condition about primes $3 \mod 4$ is fulfilled, with the additional requirement that $pq$ not be a perfect square itself.


Can one calculate the odds ratio from the contingency table in the multivariate case?

Question: The odds for logistic regressions can be computed as:
$$e^{x_i^{T} w}$$
If we thus only vary one regressor by one unit (e.g. a dummy variable) while holding constant the other variables, the odds ratio from comparing two observations yields:
$$e^{w_i}$$
But is there also a possibility to calculate the respective odds ratio from the contingency table in the multivariate case?
I know that in the simple case where we only regress on the dummy variable, we can relatively straightforward calculate the odds from the contingency table and compare it to $e^{w_i}$, which must yield the same outcome.
Comment: Well, technically, the answer must be "yes" since the computer does things we can do. But I'm guessing that there is no practical way to do it.
Comment: Suggested title:  something like "Can one calculate the odds ratio from the contingency table in the multivariate case?"
Answer: You can only do this with a saturated model, i.e., one with only categorical predictors that all fully interact with each other so that there are as many coefficients as there are cells of the design matrix. Otherwise, the logistic regression makes smoothing assumptions (i.e., that certain odds ratios are equal) that are not reflected in the contingency table itself.


How to add language prefix to form action?

Question: We have a multi lingual site that default is "en".
Sometimes editors are creating content in another language like "de" and than translate it to "en".
My problem is that we use Layout builder visibility rules for blocks.
And the form action attribute that is rendered as example below.
Does not have a language prefix.
And therefore ends up in a 403 response for every content page that is not created in sites default language.
My question is how can I add the language prefix to the action attribute the most drupalish way?
/**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, SectionStorageInterface $section_storage = NULL, $delta = NULL, $uuid = NULL) {
    $this->sectionStorage = $section_storage;
    $this->delta = $delta;
    $this->uuid = $uuid;

    // Any visibility conditions that have already been added to the block.
    $visibility_conditions_applied_to_block = $this->getCurrentComponent()->get('visibility') ?: [];

    // Visibility condition types that can be added to a block.
    $conditions_available_to_block = [];
    foreach ($this->conditionManager->getFilteredDefinitions('layout_builder', $this->getAvailableContexts($section_storage)) as $plugin_id => $definition) {
      $conditions_available_to_block[$plugin_id] = $definition['label'];
    }

    $items = [];
    foreach ($visibility_conditions_applied_to_block as $visibility_id => $configuration) {
      /** @var \Drupal\Core\Condition\ConditionInterface $condition */
      $condition = $this->conditionManager->createInstance($configuration['id'], $configuration);
      $options = [
        'attributes' => [
          'class' => ['use-ajax'],
          'data-dialog-type' => 'dialog',
          'data-dialog-renderer' => 'off_canvas',
          'data-outside-in-edit' => TRUE,
        ],
      ];
      $items[$visibility_id] = [
        'label' => [
          'data' => [
            'condition_name' => [
              '#type' => 'html_tag',
              '#tag' => 'b',
              '#value' => $condition->getPluginId(),
            ],
            'condition_summary' => [
              '#type' => 'container',
              '#markup' => $condition->summary(),
            ],
          ],
        ],
        'edit' => [
          'data' => [
            '#type' => 'link',
            '#title' => $this->t('Edit'),
            '#url' => Url::fromRoute('layout_builder.add_visibility', $this->getParameters($visibility_id), $options),
          ],
        ],
        'delete' => [
          'data' => [
            '#type' => 'link',
            '#title' => $this->t('Delete'),
            '#url' => Url::fromRoute('layout_builder.delete_visibility', $this->getParameters($visibility_id), $options),
          ],
        ],
      ];
    }

    if ($items) {
      $form['visibility'] = [
        '#prefix' => '
',
        '#suffix' => '
',
        '#theme' => 'table',
        '#rows' => $items,
        '#caption' => $this->t('Configured Conditions'),
        '#weight' => 10,
      ];
    }

    $form['condition'] = [
      '#type' => 'select',
      '#title' => $this->t('Add a visibility condition'),
      '#options' => $conditions_available_to_block,
      '#empty_value' => '',
      '#weight' => 20,
    ];

    // Determines if multiple conditions should be applied with 'and' or 'or'.
    $form['operator'] = [
      '#type' => 'radios',
      '#title' => $this->t('Operator'),
      '#options' => [
        'and' => $this->t('And'),
        'or' => $this->t('Or'),
      ],
      '#default_value' => $this->getCurrentComponent()->get('visibility_operator') ?: 'and',
      // This field is not necessary until multiple conditions are added.
      '#access' => count($items) > 0,
      // If there are two or more visibility conditions, this field appears
      // above the list of existing conditions. If there is only one visibility
      // condition, and a second one is being added, then this field appears
      // between the 'Add a visibility condition' dropdown and the submit
      // button.
      '#weight' => count($items) === 1 ? 30 : 3,
    ];

    // This is a submit button that only appears once two or more visibility
    // conditions are present. This submit button appears so the user can
    // update the visibility operator, a setting that impacts the entire block.
    // This is different than the default submit button/handler for this form,
    // which is used to add a visibility condition to the block.
    $form['update_operator'] = [
      '#type' => 'submit',
      '#access' => count($items) > 1,
      '#weight' => 5,
      '#value' => $this->t('Update operator'),
      '#submit' => ['::updateOperator'],
    ];

    if (count($items) === 1) {
      // If there is only one visibility condition, hide the operator field
      // until a second condition is selected to be added to the block.
      $form['operator']['#states'] = [
        'invisible' => [
          '[name="condition"]' => ['value' => ''],
        ],
      ];
    }

    $form['actions']['#weight'] = 40;
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add condition'),
      // Submit button is only visible if a condition is selected.
      '#states' => [
        'invisible' => [
          '[name="condition"]' => ['value' => ''],
        ],
      ],
    ];

    $form['#attributes']['data-layout-builder-target-highlight-id'] = $this->blockUpdateHighlightId($this->uuid);

    if ($this->isAjax()) {
      $form['actions']['submit']['#ajax']['callback'] = '::ajaxSubmit';
      $form['actions']['submit']['#ajax']['event'] = 'click';
      $form['update_operator']['#ajax']['callback'] = '::ajaxSubmit';
      $form['update_operator']['#ajax']['event'] = 'click';
    }

    return $form;
  }

Example won't work:
<form class="layout-builder-configure-visibility" data-layout-builder-target-highlight-id="28411f7a-940c-44a5-bf49-43ca6dfa3acd" data-drupal-selector="layout-builder-configure-visibility" action="/layout_builder/visibility/block/overrides/node.220/1/28411f7a-940c-44a5-bf49-43ca6dfa3acd/user_role?destination=/layout_builder_iframe_modal/redirect" method="post" id="layout-builder-configure-visibility" accept-charset="UTF-8">

Example work:
<form class="layout-builder-configure-visibility" data-layout-builder-target-highlight-id="28411f7a-940c-44a5-bf49-43ca6dfa3acd" data-drupal-selector="layout-builder-configure-visibility" action="/de/layout_builder/visibility/block/overrides/node.220/1/28411f7a-940c-44a5-bf49-43ca6dfa3acd/user_role?destination=/layout_builder_iframe_modal/redirect" method="post" id="layout-builder-configure-visibility" accept-charset="UTF-8">

Answer: Found a solution that works for me.
This form above is a modal form rendered as Iframe.
So in my .module file.
I had to adjust the action attribute itself:
/**
 * Implements hook_preprocess_HOOK().
 */
function freitag_layout_visibility_control_preprocess_form(&$variables) {
  if (isset($variables['attributes']['id']) && $variables['attributes']['id'] === 'layout-builder-configure-visibility') {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $variables['attributes']['action'] = '/' . $langcode . $variables['attributes']['action'];
  }
}

Not the nicest solution but it works.


Does doctrine allow 2 models to use the same table

Question: I have an abstract class User and 2 classes which inherit from it, namely BEUser and FEUser.
Information about all users (FEUser and BEUser) is stored in a single table.
Does Doctrine allows this kind of mapping? Any examples?
Also if doctrine supports it which object does the table class return (FEUser or BEUser)?
Answer: Yes, it does. It's called "simple" or "column aggregation" inheritance. Second one allows to store object type in database.


Problems installing jre-6u30-windows-i586.exe on a Windows 7 x64 system

Question: When I try to install jre-6u30-windows-i586.exe on a Windows 7 x64 system using the NT Authority\System account, I get a 1619 error ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx) returned to the starting process.  I've run the installation using SCCM and using PSEXEC -S and both ways return the same errors.
Command line used: jre-6u30-windows-i586.exe /s /v "/qn /norestart /lvx C:\temp\JRE630.log ADDLOCAL=ALL IEXPLORER=1  REBOOT=Suppress JAVAUPDATE=0 INSTALLDIR=\c:\Program Files (x86)\Java\jre6\"  SOURCEDIR=\"C:\temp\AppData\LocalLow\Sun\Java\jre1.6.0_30\""

When I enable verbose logging I see the following:
=== Verbose logging started: 5/16/2012  21:09:52  Build type: SHIP UNICODE 5.00.7601.00  Calling process: C:\Windows\SysWOW64\msiexec.exe ===
MSI (c) (D0:A4) [21:09:52:691]: Resetting cached policy values
MSI (c) (D0:A4) [21:09:52:691]: Machine policy value 'Debug' is 0
MSI (c) (D0:A4) [21:09:52:691]: ******* RunEngine:
           ******* Product: C:\Windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30\jre1.6.0_30.msi          ******* CommandLine: **********
MSI (c) (D0:A4) [21:09:52:691]: Client-side and UI is none or basic: Running entire install on the server.
MSI (c) (D0:A4) [21:09:52:691]: Grabbed execution mutex.
MSI (c) (D0:A4) [21:09:52:706]: Cloaking enabled.
MSI (c) (D0:A4) [21:09:52:706]: Attempting to enable all disabled privileges before calling Install on Server
MSI (c) (D0:A4) [21:09:52:722]: Incrementing counter to disable shutdown. Counter after increment: 0
MSI (s) (38:04) [21:09:52:722]: Running installation inside multi-package transaction C:\Windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30\jre1.6.0_30.msi
MSI (s) (38:04) [21:09:52:722]: Grabbed execution mutex.
MSI (s) (38:64) [21:09:52:737]: Resetting cached policy values
MSI (s) (38:64) [21:09:52:737]: Machine policy value 'Debug' is 0
MSI (s) (38:64) [21:09:52:737]: ******* RunEngine:
           ******* Product: C:\Windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30\jre1.6.0_30.msi
           ******* Action:
           ******* CommandLine: **********
MSI (s) (38:64) [21:09:52:737]: Note: 1: 2203 2: C:\Windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30\jre1.6.0_30.msi 3: -2147287037
MSI (s) (38:64) [21:09:52:737]: MainEngineThread is returning 3
MSI (s) (38:04) [21:09:52:737]: User policy value 'DisableRollback' is 0
MSI (s) (38:04) [21:09:52:737]: Machine policy value 'DisableRollback' is 0
MSI (s) (38:04) [21:09:52:737]: Incrementing counter to disable shutdown. Counter after increment: 0
MSI (s) (38:04) [21:09:52:737]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) (38:04) [21:09:52:737]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) (38:04) [21:09:52:737]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\InProgress 3: 2
MSI (s) (38:04) [21:09:52:737]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\InProgress 3: 2
MSI (s) (38:04) [21:09:52:737]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (s) (38:04) [21:09:52:737]: Restoring environment variables
MSI (c) (D0:A4) [21:09:52:737]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (c) (D0:A4) [21:09:52:737]: MainEngineThread is returning 3
=== Verbose logging stopped: 5/16/2012  21:09:52 ===

This looks like it is attempting to extract the MSI to "C:\Windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30" but it is not able to extra the MSI from the executable so the installation fails.  Is there any way to get this to work?
Thanks in advance,
Keith
Answer: Yes, you can get this to work by creating the necessary directory ahead of time and then adding a junction point from the 64-bit profile to the 32-bit profile, like this:
mklink /J c:\windows\system32\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30 c:\windows\syswow64\config\systemprofile\AppData\LocalLow\Sun\Java\jre1.6.0_30

More detail can be found on my blog here.
(Incidentally, if you had tagged this question 'windows' I'd have answered it much sooner!)
Answer: https://bugs.java.com/bugdatabase/view_bug?bug_id=6995830
This is a known issue.  The package extracts to the syswow64 folder, but looks for the newly created msi in the system32 folder.
Apparently when they say 'i586' they mean it ONLY installs on a 32bit os/system.
Comment: +1 for referencing the bug report, but note that the installer works perfectly well if you run it in the context of a real user.


Como adicionar barra de rolagem em JPanel?

Question: Eu gostaria de adicionar uma barra de rolagem em um JPanel que usa Absolute Layout.
    package Default;
    import javax.swing.JFrame;
    import javax.swing.border.EmptyBorder;

    import java.awt.Dimension;

    import javax.swing.JButton;
    import javax.swing.JScrollPane;

    public class teste extends JFrame {

    private JPanel contentPane;

    public static void main(String[] args)
    {
        teste frame = new teste();
        frame.setVisible(true);
    }

    private static int qtButton = 0 ;

    public teste()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane panel = new JScrollPane();
        panel.setBounds(10, 11, 464, 439);
        contentPane.add(panel);

        for(int i = 0; i < 15; i++)
        {
            gerarButton(panel);
        }

    }
    public static void gerarButton(JScrollPane panel)
    {
        JButton NewButton = new JButton("New button");
        NewButton.setBounds(10, 11 + (34 * qtButton), 444, 23);
        panel.add(NewButton);

        qtButton ++;

        panel.repaint();
    }
}

E aqui do jeito que fica

Como eu poderia fazer isso ??
Obs: os botões dentro são "infinitos"
Comment: Use JScrollPane, ao inves de JPanel.
Comment: @DiegoF Eu usei e mesmo assim não funcionou
Comment: Sete um tamanho para o `JScrollPane`, usando `setPreferredSize`.
Comment: @DiegoF Eu gostaria de um exemplo no código que eu coloquei na pergunta, poderia fazer isso ??
Answer:
Evite usar layout absoluto, a não ser que seja de extrema necessidade e que saiba as consequências disso, pois layout absoluto dificulta manutenção da tela e faz com que sua aplicação fique com aparência diferente dependendo do monitor e resolução que estiver sendo executada.
Existem vários gerenciadores de layouts para que você não tenha que se preocupar com posicionamento ou organização manual de componentes. Sem contar que o uso de layouts faz com que seu código fique mais fácil de dar manutenção do que ficar inserindo um monte de setbounds, e caso precise alterar a posição de algum componente, vai ter que reposicionar todos manualmente.

No código apresentado, o problema é resolvido de uma maneira alternativa e  bastante simples: utilizando GridLayout. Este layout organiza os componentes de um container na forma de uma grade, onde você define quantas linhas e colunas ele deve possuir. No seu caso, o número de linhas é indefinido, então basta passar 0 no primeiro parâmetro do construtor(que representa o numero de linhas) e deixar por conta do layout.
E para que o scroll funcione corretamente, você precisa criar um painel com o layout informado, e adicionar este painel ao JScrollPane, e não adicionar os botoes diretamente, pois assim o scrollpane não saberá em qual componente ele vai se basear no tamanho para exibir o scroll.
Fiz algumas alterações no seu código, removendo o layout absoluto, uma vez que misturar layouts relativo e absoluto não irá trazer o resultado esperado:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JScrollPane;

public class GridLayoutButtonsTest extends JFrame {

    private JPanel contentPane;
    private int qtButton = 0;

    public static void main(String[] args)
    {
        GridLayoutButtonsTest frame = new GridLayoutButtonsTest();
        frame.setVisible(true);
    }

    public GridLayoutButtonsTest()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(500, 500));
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JScrollPane scroll = new JScrollPane();
        scroll.setPreferredSize(new Dimension(464, 439));

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1, 10, 10));

        for(int i = 0; i < 15; i++)
        {
            panel.add(gerarButton());
        }
        scroll.setViewportView(panel);
        contentPane.add(scroll);

        pack();
    }

    public JButton gerarButton() {

        qtButton++;
        JButton NewButton = new JButton(String.valueOf(qtButton));
        return NewButton;
    }
}

Resultado:

Mais informações de uso a respeito deste layout podem ser encontradas no Guia oficial da oracle.


Algorithm complexity, solving recursive equation

Question: I'm taking Data Structures and Algorithm course and I'm stuck at this recursive equation:
T(n) = logn*T(logn) + n

obviously this can't be handled with the use of the Master Theorem, so I was wondering if anybody has any ideas for solving this recursive equation. I'm pretty sure that it should be solved with a change in the parameters, like considering n to be 2^m , but I couldn't manage to find any good fix.
Comment: I dont think these reasons are enough to say that this is not a recursive equation , because after all T(n) depends on another value of T , so this makes it recursive . and according to our instructor the start condition should be guessed by yourself , and sometimes the start condition is not even needed , like when using the master theorem .
Comment: this question was solved at this topic , http://cs.stackexchange.com/questions/14775/recursive-equation-for-complexity-tn-logn-tlogn-n
Comment: To be precise, functions can be defined **recursively**, equations can have **recurrence**. Did you try enumerating some values for this function? Intelligent guesswork should be the first attempt, it's easy to check if a guess is correct by induction.
Comment: thanks for the correction Daniel , but no guess comes to mind on this one , do you have any in mind ?
Comment: This question appears to be off-topic because it is not about programming.
Comment: This is not a recursive equation, for two reasons. First, T(n) depends on T(log n) ,and even if n is an integer log n is in general not. Second, there is no start condition, such as T(0) = 0.
Comment: It seems (if I am not wrong), you can atleast calculate the expression for some of the powers of 2. T(1) = 1, T(2) = T(1) + 2, T(4) = 2*T(2) + 4, T(16) = 56, T(256) = 704
Comment: yes , but where would that take us !? :|
Answer: The answer is Theta(n).  To prove something is Theta(n), you have to show it is Omega(n) and O(n).  Omega(n) in this case is obvious because T(n)>=n.  To show that T(n)=O(n), first

Pick a large finite value N such that log(n)^2 < n/100 for all n>N.  This is possible because log(n)^2=o(n).
Pick a constant C>100 such that T(n)<Cn for all n<=N.  This is possible due to the fact that N is finite.

We will show inductively that T(n)<Cn for all n>N.  Since log(n)<n, by the induction hypothesis, we have:
T(n) < n + log(n) C log(n)
     = n + C log(n)^2
     < n + (C/100) n
     = C * (1/100 + 1/C) * n
     < C/50 * n
     < C*n

In fact, for this function it is even possible to show that T(n) = n + o(n) using a similar argument.
Comment: dude your final answer is correct , but your proof is faulty ! it is not logn^2 , its logn*T(logn) ! I think you forgot that !
Comment: T(log n) < C log(n) follows from the induction hypothesis.  Are you familiar with proof by induction?  http://en.wikipedia.org/wiki/Mathematical_induction
Comment: yes , As I examined my textbook your method was right and I was wrong . I made that mistake because your way of using induction was slightly different than the method I learnt ( like choosing the constants c and n ) . anyway , thanks
Answer: This is by no means an official proof but I think it goes like this.
The key is the + n part. Because of this, T is bounded below by o(n). (or should that be big omega? I'm rusty.) So let's assume that T(n) = O(n) and have a go at that.
Substitute into the original relation
T(n) = (log n)O(log n) + n
     = O(log^2(n)) + O(n)
     = O(n)

So it still holds.
Comment: hah okay I admit I'm not sure with this solution. Care to elaborate?
Comment: @AshkanKzme:  Why is this answer that T(n) is O(n) "completely and utterly wrong" when the solution to the Accepted Answer to your cross-post at cs.SE also says T(n) is O(n)?  There's some abuse of notation in the Answer above, but not much more than what is entailed by the Question itself.
Comment: This is correct.  You could make it a little more rigorous by saying "assume that `T(n)<cn` for `n<5`", and then using strong induction.  (And yes, it should be big omega.)
Comment: this is completely and utterly wrong my friend , I'd vote you down but I cannot .
Comment: well I think your mistake is that for T(logn) you cannot just write O(logn) , because we do not know what will happen with logn within the function T(logn) .
Comment: Be careful with these kind of proofs (induction proofs) and big-O notation. A simple *assume this-or-that* approach can produce wrong results!


using a callback function with useState

Question: The issue I am having is in the change() function. I want to call filteredData() function after the setState runs. Usually, I would use a callback function to call filteredData, but useState doesn't allow callbacks. I can't use useEffect because it will call the function initially before there is any data change.
import React, { useState, createContext, useEffect } from "react";
import data from "../Reducers/ListingsData";

   export const GlobalContext = createContext();

   export function GlobalProvider({ children }) {
     const [state, setState] = useState({
      name: "",
      city: "all",
      homeType: "all",
      rooms: 0,
      bathrooms: 0,
      min_price: 0,
      max_price: 10000000,
      min_floor_space: 0,
      max_floor_space: 40000,
      finished_basement: false,
      swimming_pool: false,
      garage: false,
      data: data,
      filteredData: data,
      populateFormsData: "",
      sortby: "price-dsc",
      search: "",
   });

  function change(event) {
    let name = event.target.name;
    let value =
    event.target.type === "checkbox"
    ? event.target.checked
    : event.target.value;

  setState((prevState) => ({ ...prevState, [name]: value }));
  filteredData();
 }

   function filteredData() {
    console.log(state);
}

  return (
   <GlobalContext.Provider value={{ state: state, change }}>
     {children}
   </GlobalContext.Provider>
 );

}
Comment: Does this answer your question? [How to use \`setState\` callback on react hooks](https://stackoverflow.com/questions/56247433/how-to-use-setstate-callback-on-react-hooks)
Answer: If you would like to run something whenever state changes, you can use a useEffect hook that has state in the dependency array:
useEffect(() => {
  console.log(state);
}, [state]);

If you just need to condition off of a property within your state object, you can just have that property in the dependecy array:
useEffect(() => {
  console.log(state.name);
}, [state.name]);

If you'd like to keep using the filterData function, it might be best to define it within the effect so you don't have to list it as a dependency in the dependency array:
useEffect(() => {
  function filterData() {
    console.log(state);
  }
  filterData();
}, [state]);

If you need to define the filterData function outside the effect for whatever reason, then you should probably use a useCallback hook to keep the same function reference whenever state is the same, and only change it when state is updated:
const filterData = useCallback(() => {
  console.log(state);
}, [state]);

useEffect(() => {
  filterData();
}, [filterData]);

Answer: This worked for me. I needed to find away to use useEffect without the initial run.
const { useState, useRef, useLayoutEffect } = React;

function ComponentDidUpdateFunction() {

 const firstUpdate = useRef(true);
 useLayoutEffect(() => {
   if (firstUpdate.current) {
   firstUpdate.current = false;
  return;
}

filteredData();

});
Answer: arent you overcomplicating it. I use a very simple approach
 export function GlobalProvider({ children }) {
     const [state, setState] = useState({
      name: "",
       ......
      search: "",
   });

  function change(event,'pass name of field as second argument') {
    //let name = event.target.name;
    //let value =
     //event.target.type === "checkbox"
    //? event.target.checked
    //: event.target.value;

      //create the copy of the state object
      let copyState=state
      //modify the new object with value and use second arg for getting key name
      copyState['second argument aka name in this case']= event.target.value
       //save to state
      setState(copyState)

      filteredData();
     }

this way you dont need to worry about overwriting the previous values if that is what you are trying to attempt
Answer: In your particular case, You can check when your name changes, then run it inside the useEffect() hook:
useEffect(() => filteredData(), [state.name]);

For further reference see How to use setState callback on react hooks
Comment: I'd recommend cleaning up this answer a bit. If anything is returned from the `useEffect` callback function, it should be a cleanup function. As-is, you're returning the return value of `filteredData`, which I guess we're fortunate isn't returning anything right now. Additionally, your dependency array is not comprehensive, it's missing `filteredData` and risks containing a stale reference.
Answer: Best way to do it is using useEffect and adding your state to the dependency array.
Rather than calling filteredData() within change function you can call it from useEffect and add state to the dependency array of your useEffect.
So,anytime your state is updated your useEffect is triggered.
useEffect(() => {
    filteredData();
  }, [state])

Comment: Your dependency array is incomplete and risks having a stale reference to `filterData`

using a callback function with useState


Checking whether a coin is fair

Question: Given a box that contains 90% fair coins and 10% loaded coins, (a loaded coin gives heads 90% of the time), what is the probability for a randomly drawn coin to give 5 heads in a row?
P(HHHHH | random coin from box of mixed coins) = ?

I used Bayes Theorem to calculate the probability
I got .219 or 21.9% probability for the random coin to give 5 heads in a row!

But I am still doubting if my answer is correct !!!
Any help appreciated :)
Comment: I like to use two nearly opposite, but still valid ways to get to the answer.  Will you accept an answer that isn't symbolic?  :)
Comment: Do you (a) draw one coin randomly and then flip it five times or (b) five times over, draw one coin at a time and flip it or (c) five times over, draw one coin at a time, flip it, and return it to the box?
Comment: It is simply 0.9*(0.9)$^5$ when you get a loaded coin and 0.1*(0.5)$^5$ when you get a fair coin.  Since the event getting a fair coin is mutually exclusive from getting a loaded coin you simply add these  probabilities.
Comment: @EngrStudent sure !!! if it satisfies my reasoning
Comment: @whuber `a` ...
Comment: Your attempted answer does not seem to consider the possibility that a loaded coin is drawn.  If it did, then one would expect to see an expression giving the chance that it lands heads five times, but no such expression is in evidence.
Comment: @whuber hmm, sorry my ignorance, I just started with statistics!!! all I was able to check for loaded coin (`0.9`) was to multiply it with number of times coin is being tossed!
Comment: That's right, if we understand you to mean $(0.9)^5$--but where in your work is that calculation performed?
Answer: Here is the code I use:
# Given a box that contains 90% fair coins and 10% loaded coins,
#(a loaded coin gives heads 90% of the time), what is the probability
#for a randomly drawn coin to give 5 heads in a row?
# draw one coin randomly and then flip it five times

Number_of_repeats = 1000000  #a million samples

#store values
store_values = numeric(length = Number_of_repeats)

#draw a coin
#    90% chance fair, 10% chance unfair
#    fair means 50% binom, unfair means 90% binom
draw_coin = sample(x=c(0.5,0.9),
                   size = Number_of_repeats,
                   prob = c(0.9,0.1),
                   replace = TRUE)

for (i in 1:Number_of_repeats){

     #flip it 5 times, count "heads"
     flips = rbinom(n = 1, size = 5, prob = draw_coin[i])

     #did I get 5 heads?
     if (flips==5){
          store_values[i] = 1
     }

}

print(summary(as.factor(store_values)))
print(mean(store_values))

The results it gives are:
> print(summary(as.factor(store_values)))
     0      1
913149  86851

> print(mean(store_values))
[1] 0.086851

To me this says you should be getting in the neighborhood of 8.6%.
This runs surprisingly fast for the number of samples.  Thank you, whuber, for suggestion.
The densest way, but one with slightly less clear intermediate step is this:
Number_of_repeats = 1000000

#draw a coin
#    90% chance fair, 10% chance unfair
#    fair means 50% binom, unfair means 90% binom
store_values = sample(x=c(0.5^5,0.9^5),
                   size = Number_of_repeats,
                   prob = c(0.9,0.1),
                   replace = TRUE)

print(summary(as.factor(store_values)))
print(mean(store_values))

It runs really (really!) fast.
So when I put in 5 million samples I get 8.709% and 8.706%, so it is one thousandths place that is moving.
I think other commenters were saying this:
(0.1*(0.9^5)) + (0.9*(0.5^5))

It evaluates to 0.087174, or 8.717%.
It is fun that this diverges from the 7.70x%.  At 5 million samples we could be hitting round-off related effects.  What fun!
Comment: +1 What I like about this is that straightforward efforts to simplify the code will lead to a non-programming solution.  For instance, do we really have to sample `c(0.5,0.9)` and only *then* flip the coin five times, or could we compute the chances of getting five heads and substitute those two values for `0.5` and `0.9`?
Comment: +1 for explaining both programmatic wise and mathematical wise :)

Checking whether a coin is fair


Limit of $\left(e^2 \frac{(1+x)^{1/x}}{(1+x²)^{1/x²}}\right)^{1/x}$ when $x\to0$

Question: I have been struggling with this limit for a while:
$$
\lim_{x\to0} \left(e^2 \frac{(1+x)^{1/x}}{(1+x²)^{1/x²}}\right)^{1/x}
$$
I suspect I have to use the $\lim_{x\to0}(1+x)^{\frac{1}{x}}=e$ limit and probably the L'Hopital's rule, but I don't know how to start.
Thank you so much for any kind of help, just to get me started
Comment: Not always is a good idea to use complete fraction symbol for powers, in particular when the expression is messy. I thinkl it must be clear the exponent of the denominator above is $\;1/x^2\;$ , as it looked, and still looks a little, like $\;1/x\;$ .
Comment: $a^b=e^{b\ln(a)}$ might help you.
Answer: For $x\to 0^+$, $(1+x)^{1/x}\to e$ and $(1+x^2)^{1/x^2}\to e$ and then
$$\left(e^2 \frac{(1+x)^{1/x}}{(1+x^2)^{1/x^2}}\right)^{1/x}\sim e^{2/x}\to \infty$$
For $x\to 0^-$
$$\left(e^2 \frac{(1+x)^{1/x}}{(1+x^2)^{1/x^2}}\right)^{1/x}\sim e^{2/x}\to 0$$
Answer: We can try arithmetic of limits. Since
$$\lim_{x\to x_0}\left(1+f(x)\right)^{1/f(x)}=e\;,\;\;\text{for any function such that}\;\;\lim_{x\to x_0}f(x)=0$$
we have that
$$\lim_{x\to0}(1+x)^{1/x}=\lim_{x\to0}(1+x^2)^{1/x^2}=e$$
so there exists a right neighborhood of zero, $\;I_\epsilon:=(0,\epsilon)\;$ such that for any $\;x\in I_\epsilon$:
$$0.9<\frac{(1+x)^{1/x}}{(1+x^2)^{1/x^2}}<1.1$$ , and thus
$$ (e^2\cdot0.9)^{1/x}\le\left(e^2 \frac{(1+x)^{1/x}}{(1+x²)^{1/x²}}\right)^{1/x}\le(e^2\cdot1.1)^{1/x}$$
and by the squeeze theorem the limit is $\;+\infty\;$, and thus the limit doesn't exist finitely (I think from the left it is zero nd thus the limit doesn't exist at all)


Polar coordinates - issue with direction denoted by angle

Question:
Convert $1-\sqrt{3}i$ to polar coordinates $(r,\varphi)$.

I started by computing $r=|1-\sqrt{3}i|=\sqrt{1^2+\sqrt{3}^2}=\sqrt{4}=2$. When I tried to compute the angle I did something like
$$\varphi=\arctan\left|\frac{y}{x}\right|=\arctan\left|\frac{-\sqrt{3}}{1}\right|=\arctan\sqrt{3}=\frac{\pi}{3}.$$
Although this answer seems plausible to me, I am unsure, because the angle should be $-\frac{\pi}{3}$ otherwise the resulting coordinates would be the first quadrant rather than in the fourth. How do I have to compute $\varphi$ to match the right quadrant?
Answer: Why did you do
$$\arg z=\arctan\left|\frac{y}{z}\right|??$$
It should be
$$\arg z=\arctan\frac{y}{z}=\arctan-\sqrt 3=-\frac{\pi}{3}\,,\,\frac{2\pi}{3}$$
Since in $\,z=1-\sqrt 3i\,\;$ the real part is positive and the imaginary part is negative, the vector(=the complex number) is in the fourth quadrant, so the answer must be $\,-\dfrac{\pi}{3}\,$ , or if a positive number is wanted, $\,\dfrac{5\pi}{3}\,$
Comment: Actually I don't know, but now it seems comprehensible what you said.
Answer: The arguement of an imaginary number, Z is the angle, $-\pi<\phi<\pi$, given by
$\phi(Z)=arctan(\frac{Im(Z)}{Re(Z)})$
$= arctan(\frac{-\sqrt{3}}{1})=-\frac{\pi}{3}$


Linear Model Output - which treatments are different from each other?

Question: How do you determine which supplements are not different from each other (within the listed rows)?
model <- lm(gain~diet+supplement)

                    Estimate Std. Error t value Pr(>|t|)
(Intercept)          26.1230     0.4408  59.258  < 2e-16 ***
dietoats             -3.0928     0.4408  -7.016 1.38e-08 ***
dietwheat            -5.9903     0.4408 -13.589  < 2e-16 ***
supplementcontrol    -2.6967     0.5090  -5.298 4.03e-06 ***
supplementsupergain  -3.3815     0.5090  -6.643 4.72e-08 ***
supplementsupersupp  -0.7274     0.5090  -1.429     0.16
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.247 on 42 degrees of freedom
Multiple R-squared:  0.8531,    Adjusted R-squared:  0.8356
F-statistic: 48.76 on 5 and 42 DF,  p-value: < 2.2e-16

Comment: The way you've set things up, you're only testing relative to whatever your reference level is.
Comment: This is not the (best) way to investigate which supplements are (not) different from each other. This is a way to investigate which supplements are (not) different from your baseline supplement (i.e. the one missing from your output) given that you control for variable `diet`.
Answer: To compare treatments you can use a pairwise comparison test, for example the Tukey HSD test:
TukeyHSD(aov(model), 'diet')


How do I change XML tag names?

Question: I've created views as XML data document using Views Datasource which looks like:
<?xml version="1.0" encoding="utf-8"?>
<node><node>
<title>My title</title>
<field_feed_description>My description</field_feed_description>
</node></node>

How do I now change generated XML name tags?
For example I want to rename field_feed_description name into something else.
Answer: On the Views UI tick the Create a label checkbox and enter in your element name in the Label textfield. The value of Label will be used for the element name.

How do I change XML tag names?


Facebook PHP SDK getLogoutUrl

Question: In the context of a facebook application what is the point in this? Since they cannot play your app till authorised and logged in. What purpose does logging them out of a facebook session and redirected to your app actually serve?
<code>This method returns a URL that, when clicked by the user, will log them out of their      Facebook session and then redirect them back to your application.
</code>
Answer: It is useful outside Facebook, in the context where the user authenticates via Facebook to log into your website.
Comment: Yeah, ok, is about the only use case I could think of for it for an application which actually sits within facebook already.

Facebook PHP SDK getLogoutUrl


Migrating an ip address alias from one server to another

Question: I run:
/sbin/ifconfig eth0:10 xx.xx.xxx.221 netmask 255.255.255.224 down

on box1, and on box2:
/sbin/ifconfig eth0:10 xx.xx.xxx.221 netmask 255.255.255.224 up

Both boxes are located on the same network.
After migrating, I'm able to ping the ip from both servers, I notice it responds 10x faster on box2 than on box1 so it seems like that went ok.  However I'm not able to ping the ip from outside of the network.
eth0 on both boxes are the public ips, the alias is also a public ip.
When I move the ip back to box1, I'm able to ping it outside of the network without any issue.
I am also able to ping the public ip (eth0) on box2 just fine, so it doesn't appear to be a firewall issue.
Do the routers need time to update the new one to point to the new MAC address?
What am I missing?
Comment: Does the problem disappear if you ping the router with the alias address as source address?
Answer: You need to send gratuitous arp.  Packages like heartbeat and keepalived will do this for you.  Otherwise, look at arping.
Comment: Thank you so much!  Running:
`arping -U -I eth0 xx.xx.xxx.221`
Made the box respond to that ip immediately.
Answer: Kevin instead of using ifconfig to set the virtual interface down, use ip to remove it:
ip addr del xx.xx.xxx.221 dev eth0

and yes, the router may need some time to update it's arp table. But, if you have access to it, you may manually remove the arp entry from the table, although the time for it to update isn't that long.
Comment: Thanks, unfortunately I do not have access to the upstream router at all.  But you did hit the nail on the head knowing it was an ARP table issue.
Comment: Not having access to your upstream router makes it just a matter of time, and it isn't that long. ;-)


AdonisJS catch database insert errors with api-only while using ORM

Question: Is there a way to catch database insert errors i.e. duplicate entry when using the Adonis ORM in api-only mode.
In the example below, if the username is a duplicate, it just sends a 500 internal server error and dumps a full html page of the error to the client.
Even if I don't know what the error is, I would at least like to be able to catch the error and send a more usable json object like
{error: "Unable to insert user"}
Here is some example code
const User = use('App/Models/User')

class UserController {
    async register({ request }) {
        const { username, email, password, first_name, last_name } = request.all()
        const user = new User()
        user.fill({
            username,
            email,
            password,
            first_name,
            last_name
        })
        await user.save()
        return user
    }
}

Partly Solved:
I have partly solved this issue with the following code, but I feel as though there must be a better / built in way to achieve this.
const User = use('App/Models/User')

class UserController {
    async saveData(object, errorMessage){
        try{
            await object.save()
            return object
        }
        catch(err) {
            return {error:`${errorMessage}`}
        }
    }
    async register({ request, response }) {
        const { username, email, password, first_name, last_name } = request.all()
        const user = new User()
        user.fill({
            username,
            email,
            password,
            first_name,
            last_name
        })
        return this.saveData(user, "Unable to save user")

    }
}

Answer: Try & catch is what you're looking for. You can also use global exceptions.
Regarding your duplicate error, you should also use the AdonisJs Validator to make sure you won't get this errors.
So before you save your model, check that the given user is unique for example.
So you would have something like this
async register({ request, response }) {
    const { username, email, password, first_name, last_name } = request.all()

    const rules = {
      username: 'required|unqiue:username'
    };

    const validation = await validate(request.all(), rules);

    if (validation.fails()) {
      response.status(500).send(validation.messages());
    }

    const user = new User()
    user.fill({
        username,
        email,
        password,
        first_name,
        last_name
    })

    await user.save();

    return user;

}


A Hamiltonian inequality using uniform convexity and Taylor's formula (Evans PDE, §3.3.3, Lemma 4, (36))

Question: In the proof of Lemma 4 (Semiconcavity again) in section 3.3.3 of the book "Partial differential equations" written by Lawrence C. Evans, there's a claim

We note first using Taylor's formula that (35) implies
(36)       $ H(\frac{p_1+p_2}{2}) \leq \frac{1}{2}H(p_1)+\frac{1}{2}H(p_2)-\frac{\theta}{8}|p_1-p_2|^2 $.

How does uniform convexity and Taylor's formula imply this?
I know that by Taylor's formula,
$ H(\frac{p_1+p_2}{2}) = H(p_1)+DH(p_1)\cdot(\frac{p_2-p_1}{2})+(\frac{p_2-p_1}{2})^TD^2H(p_1)(\frac{p_2-p_1}{2})  $,
and
$ H(\frac{p_1+p_2}{2}) = H(p_2)+DH(p_2)\cdot(\frac{p_1-p_2}{2})+(\frac{p_1-p_2}{2})^TD^2H(p_2)(\frac{p_1-p_2}{2})  $,
add them and then divide by 2, we get
$ H(\frac{p_1+p_2}{2}) = \frac{H(p_1)}{2}+\frac{H(p_2)}{2}+(\frac{DH(p_2)-DH(p_1)}{2})\cdot(\frac{p_1-p_2}{2})+(\frac{p_1-p_2}{2})^T(\frac{D^2H(p_2)-D^2H(p_1)}{2})(\frac{p_1-p_2}{2})  $.
But I can NOT get the result.
Answer: A couple of mistakes of execution first: (1) Your invocation of Taylor's theorem isn't correct – the second-order term needs be an error term since we want an exact equality, and should have an additional factor of $\frac{1}{k!} = \frac{1}{2}$; (2) The sign of "$D^2 H(p_1)$" (in quotes as by (1) we shouldn't evaluate at $p_1$) in the last equation should be $+$, because double negatives.
Even with those corrections, we have an unwanted nonzero first-order term, and a sign on the second-order term that's opposite of what we want. But: we can resolve these issues by applying Taylor at $\boldsymbol{\frac{p_1+p_2}{2}}$ instead!
Proof. Let $\xi = \frac{p_1-p_2}{2}$. By Taylor ($C^2$ with Lagrange remainders) there exist points $e_1, e_2$ on the line segment $\overline{p_1p_2}$ such that
$$
\begin{align*}
H(p_1) &= H\left(\frac{p_1+p_2}{2}\right) + \sum_{i=1}^n H_i\left(\frac{p_1+p_2}{2}\right) \xi_i + \frac{1}{2} \sum_{i,j=1}^n H_{ij}(e_1) \xi_i \xi_j,
\\
H(p_2) &= H\left(\frac{p_1+p_2}{2}\right) + \sum_{i=1}^n H_i\left(\frac{p_1+p_2}{2}\right) (-\xi)_i + \frac{1}{2} \sum_{i,j=1}^n H_{ij}(e_2) (-\xi)_i (-\xi)_j.
\end{align*}
$$
Averaging the two equations and rearranging, then applying uniform convexity,
$$
\begin{align*}
H\left(\frac{p_1+p_2}{2}\right)
&= \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - \frac{1}{4} \sum_{i,j} H_{ij}(e_1) \xi_i \xi_j - \frac{1}{4} \sum_{i,j} H_{ij}(e_2) \xi_i \xi_j
\\
&\leq \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - 2 \cdot \frac{\theta}{4} \lvert \xi \rvert^2
\\
&= \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - \frac{\theta}{8} \lvert p_1 - p_2 \rvert^2. \tag*{$\blacksquare$}
\end{align*}
$$
Comment: Nice answer and thanks a lot! I think that I should work harder then.  :-)
Answer: Only a small correction to the answer of @epimorphic. $ e_1 $ is NOT on the segment between $p_1$ and $p_2$ . Because $e_1 = \frac {p_1 + p_2 } {2} + \delta_1 \cdot \xi = \frac {p_1 + p_2 } {2} + \delta_1 \cdot \frac {p_1 - p_2 } {2} $  where $ 0<=\delta<=1 $ , so $e_1$ is on the line segment between $\frac {p_1 + p_2 } {2} $ and $ \frac {p_1 - p_2 } {2}$ . The similarity is in the case of $e_2$.
Comment: Disagreeing on that. The point $e_1$ is in fact more specifically between $p_1$ and $\frac{p_1 + p_2}{2}$ – the multidimensional Taylor's theorem comes from applying the one-dimensional version on the segment between the base point and the point where we are estimating.
Comment: Your expression $\frac{p_1+p_2}{2} + \delta_1 \cdot \frac{p_1-p_2}{2}$ has the form $v+aw$, which says "start at $v$ and move **parallel** to the vector $w$". This is distinct from the line connecting the points $v$ and $w$ (which in contrast takes the form of the weighted average $av + bw$ with $a+b = 1$)! Note that with $\delta_1 = 1$ and $\delta_1 = -1$, your expression equals $p_1$ and $p_2$, respectively.
Comment: You are right! @epimorphic


Print a Label after the last row of a datagridview in C#

Question: I want to print a label after the last row of a datagridview in C#. The number of rows will change. like this

And this

So what i want is to print a label containing the sum of amount in the red area I highlighted on the pics above. What i am doing is like counting the rows of the datagridview and setting it like this :
string psum = sum.ToString("#,##0");
int dgrows = dgvmain.Rows.Count * 20;
e.Graphics.DrawString("Total Amount :" + psum, print6B, Brushes.Black, 100, 160+dgrows);

And i have counted the sum like this:
sum = 0;
for (int i = 0; i < dgvmain.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dgvmain.Rows[i].Cells[3].Value);
}

I but the above solution is not working in the sense that there is a lot of space after the last row of the datagrid view and as the number of rows increases.
Answer: Just add another row with a different style that only contains the summary data.
Comment: Why don't you make an attempt yourself first and if you have problems I will help you.
Comment: I was able to insert the row at the end but its working on when ever the row is added. I want it to be in the end of the row. My code here : DataGridViewRow rows = (DataGridViewRow)dgvmain.Rows[0].Clone();
            rows.Cells[3].Value = sum;
            dgvmain.Rows.Add(rows);
Comment: Can you please update your original post with more complete code so I can have a look?
Answer: You can use of gridview footer template like bellow  and set the sum value to lable control
<footertemplate>
  <asp:Lablel id="lbltotal"   runat="server"/>
</footertemplate>

For more explains refer
http://msdn.microsoft.com/en-us/library/ms972833.aspx
http://www.codeproject.com/Questions/375489/how-to-calculate-total-price-in-the-footer-of-grid
http://www.dotnetfunda.com/forums/thread8330-grid-view-footer-column-calculation.aspx
Comment: `winforms` vs `asp.net`?
Comment: I am using it in winform not in asp.net
Answer: I am about to make this thing (called "statistic") in my project. While using ListView (in virtual mode), the solution should be same good for the DataGridView methink. You have to make a component (control), what will mimics headers of bound to it control and automatically takes either selection or the whole number of rows and calculate statistic. It may be possible to provide sort of info for this control via Header.Tag:
if(header.Tag is INoStatistic) { /* do nothink */ }

Advantage of such method compared to use of the ordinal row is what your statistic is always visible (sort of a "frozen column" or as @Ramakrishna.p just posted, a footer) and you can use it with any DataGridView in the future.
I'll update my answer when I am done with (if interested), or maybe you will finish first? =D


Migrate svn from Assembla to Atlassian

Question: I'm trying to migrate my subversion repo to Atlassian. Atlassian requires the imported repo dump to have a root directory with the same name as the project per project key. Let's say my project key in Atlassian is FOOBAR, then the repo dump should contain /FOOBAR for all revisions. It should also contain trunk, branches and tags subdirectories.
To rewrite the Assembla svn dump, I did this:
cat foobar-assembla.dump | svn-dump-reloc "/" "FOOBAR" > foobar-atlassian.dump

Then I tried testing it:
svnadmin create test
cat foobar-atlassian.dump | svnadmin load test

That produced an error message:
svnadmin: File not found: transaction '0-0', path 'FOOBAR/trunk'
 * adding path : FOOBAR/trunk ...

Any ideas?
Answer: I think this is because the dump file does not contain any transaction that would create the FOOBAR directory itself.
Try running svn mkdir file://$PWD/test/FOOBAR just before the svnadmin load test.
To give credit where it's due, I got this tip from http://dotslashstar.blogspot.com.au/2011/06/svn-hack-insert-missing-trunk-root.html
Comment: +1: Although I found my own way using a text editor (nano), I can see how `svn mkdir` **before** `svnadmin load` might work.
Answer: The following worked for me.
Using a text editor with all conversion options turned off:

Replace all instances of Node-path: trunk with Node-path: FOOBAR/trunk.
In the revision in which FOOBAR/trunk is created, manually add an entry immediately before the one that adds FOOBAR/trunk that creates FOOBAR, FOOBAR/branches and FOOBAR/tags.

I understand this may not work in some cases, such as when Node-path: trunk occurs within a file itself. But it worked in this case and should work in most others.

Migrate svn from Assembla to Atlassian


form set error is not working properly

Question: I am using Drupal 7
i am tracking login and setting errors but my error is not working properly
here is my code
  <?php

    function zloginsecurity_form_alter(&$form, &$form_state, $form_id)
    {
        switch ($form_id)  {
        case 'user_login':
        case 'user_login_block':
           $form['#validate'] = zloginsecurity_validators();
          break;
      }
    }

    function zloginsecurity_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate','zloginsecurity_validate');
    }

    function zloginsecurity_validate($form, &$form_state) {
           if (empty($form_state['uid'])) {
            //Check user Track Record
            echo "hello";
     form_set_error('name', t('hello test'));
          }else {
              zloginsecurity_removeevent();
            //Delete Track Records for Particualr user
        }

    }

 ?>

it is not showing hello test, it is showing default message .  Can anybody tell me how to solve this issue.   simple echo is working
Thanks
Answer: In form_set_error, the first parameter should be form name, if you are not sure of the name, just leave empty.
form_set_error('', t('hello test'));

This should work just fine.
UPDATED ANSWER
If you would like to have only your validation and skip the rest of Drupal core's validation for that particular form, you can unset the validator function and inject your own.
unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';

Or
If you like to have both and give priority to yours first, then
$default_validators = $form['#validate'];
unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';
foreach ($default_validators as $val) {
  $form['#validate'][] = $val;
}

Comment: just before you set the value for $form['#validate'], unset it. `unset($form['#validate']); $form['#validate'][] = 'zloginsecurity_validators';`
Comment: The first parameter should be Form Element Name, not Form name.
Comment: not working. this is not overwritting my previous message which has been defined in user module
Comment: HituBansal: you should use $form['#validate'][] array as mentioned by @inizio. and before doing that do unset($form['#validate']).
Comment: i done this. not working
Comment: have u done unset($form['#validate']) ??
Comment: no where i need to do unset
Comment: If you **unset** $form['#validate'] then the default validation will not work. It is not **prefer** to unset the **default validation**. We are adding **additional validation** for the **existing validate**.
Comment: i am not adding additional validation, jst want to overwrite
Comment: @pown: Can we unset validation above in my code.. as  i need to run this function loginsecurity_validators() { } also here user module is called first
Comment: pls see my updated answer
Comment: This is not working in my code. as i am calling loginsecurity_validators() { }  where some function of core user module is invoke...
Answer: Hope this will help you.
In Drupal 7, for validate and to set error you can use these code

/*
 * Implements hook_form_alter().
 */
function zloginsecurity_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $form['#validate'][] = 'zloginsecurity_validators';
      break;
  }
}
/*
 * Implements hook_form_validate().
 */
function zloginsecurity_validators($form, &$form_state) {
  if (empty($form_state['values']['uid'])) {//Check user Track Record
    form_set_error('[values][uid', t('hello test'));
  } //do your stuff here
}

  - You can Delete Track Records for Particular user in hook_form_submit by using $form_state['values'] array;
Note : Make changes as per  your requirement.
Comment: form_set_error is not working.. it is not showing  hello test
Comment: hey try to print **form_state** using **print_r(form_state)** and check the field name(uid).
Comment: still not working. u also forget to add $ . it must be if(empty(form_state['values']['uid'])) {
} also it will work if we put right password.
Comment: OH! sorry for that. Check for this - if($form_state['values']['uid'] == '') {form_set_error('name', t('hello test')); }
Comment: it will work in all cases. i am not able to login now . using ur code. :)
Comment: The code will just add an **extra validation** for the login and login block forms. Nothing more than that.
Comment: yeah.. but i dnt need this.. dats why i called loginsecurity_validators  function
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9983/discussion-between-inizio-and-hitu-bansal)
Comment: Hey I have updated my answer check it now.  Check this line **form_set_error('[values][uid', t('hello test'))**. Need to use **'[values][uid'** in the form_set_error. It will work.

form set error is not working properly