Android: Programmatically added Textview not wrapping text to next line

Question: I'm kinda sure I'm doing something stupid wrong but here's my problem.
Basically I try to make a history list using cardviews. In these cardviews I have a LinearLayout with a vertical orientation to put all my content for my card.
In this LinearLayout I have another LinearLayout with an orientation Horizontal which holds the title, ... . Below this linearLayout I have a textview which holds the actual string content. This content is quite large and for some kind of reason it doesn't wrap to the next line.
Maybe this is a bit easier to understand the structure:
CardView
_ LinearLayout (vertical)
_ _ LinearLayout (horizontal)
_ _ _ Textview
_ _ TextView (this is the one with the problems)
I set these components programmatically because I don't know how many cards I have to print beforehand.
Here is the code:
XML:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="url.Fragments.History_Fragment">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start">

        <LinearLayout
            android:id="@+id/historiekLijst_Layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:layout_marginRight="5dp"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:gravity="start"
                android:text="Historiek"
                android:textStyle="bold"
                android:textSize="25dp"/>

        </LinearLayout>
    </ScrollView>
</LinearLayout>

History_Fragment class:
LinearLayout linearLayout = (LinearLayout) historiekView.findViewById(R.id.historiekLijst_Layout);
        CardView card = DynamicComponent_Helper.makeNewCardview(5, Gravity.CENTER_HORIZONTAL,Gravity.CENTER , 5, 15, getContext());

    TextView title = DynamicComponent_Helper.makeNewTextView(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 5, Gravity.START, Gravity.START, 0, 20, "title",getContext());
                        title.setTypeface(null, Typeface.BOLD);
    TextView content= DynamicComponent_Helper.makeNewTextView(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 5, Gravity.START, Gravity.START, 0, 15, "content which is too long and doesn't get wrapped",getContext());

LinearLayout titleLayout = DynamicComponent_Helper.makeNewLinearLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.NO_GRAVITY, Gravity.NO_GRAVITY, LinearLayout.HORIZONTAL, getContext());
            LinearLayout cardLayout = DynamicComponent_Helper.makeNewLinearLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL, Gravity.START, LinearLayout.VERTICAL, getContext());

            titelLayout.addView(title);
            cardLayout.addView(titleLayout);
            cardLayout.addView(content);
            card.addView(cardLayout);
            linearLayout.addView(card);

My componentCreator_helper:
public static CardView makeNewCardview(int margin, int gravity,int layoutGravity, int radius, int padding, Context context){
// Initialize a new CardView
        CardView card = new CardView(context);

        // Set the CardView layoutParams
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context));
        params.gravity = layoutGravity;
        card.setLayoutParams(params);
        // Set CardView corner radius
        card.setRadius(geefDPAlsInt(radius, context));

        // Set cardView content padding
        card.setContentPadding(geefDPAlsInt(padding, context), geefDPAlsInt(padding, context), geefDPAlsInt(padding, context), geefDPAlsInt(padding, context));

        // Set a background color for CardView
        card.setCardBackgroundColor(Color.parseColor("#FFFFFF"));

        // Set the CardView maximum elevation
        card.setMaxCardElevation(15);

        // Set CardView elevation
        card.setCardElevation(9);

        return card;

    }
public static LinearLayout makeNewLinearLayout(int width, int length, int gravity, int layoutGravity, int orientation, Context context){
        LinearLayout linearLayout = new LinearLayout(context);
        LinearLayout.LayoutParams layoutLinearParams =
                new LinearLayout.LayoutParams(geefDPAlsInt(width, context), geefDPAlsInt(length, context));
        layoutLinearParams.gravity = layoutGravity;
        linearLayout.setOrientation(orientation);
        linearLayout.setGravity(gravity);
        linearLayout.setLayoutParams(layoutLinearParams);

        return linearLayout;
    }
    public static ImageView makeNewImageView(String imageSource, int width, int length, int margin, int gravity, int layoutGravity, int tag, Context context){
        ImageView imageView = new ImageView(context);
        LinearLayout.LayoutParams imageLayout = new LinearLayout.LayoutParams(geefDPAlsInt(width, context), geefDPAlsInt(length, context));
        imageLayout.gravity = layoutGravity;
        imageLayout.setMargins(geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context));
        imageLayout.gravity = gravity;
        imageView.setLayoutParams(imageLayout);
        imageView.setImageResource(context.getResources().getIdentifier(imageSource, "drawable", context.getPackageName()));
        imageView.setTag(tag);

        return imageView;
    }
    public static TextView makeNewTextView(int width, int length, int margin, int gravity, int layoutGravity, int tag, int textsize, String tekst, Context context){
        TextView tekstView = new TextView(context);
        LinearLayout.LayoutParams layoutTextParams = new LinearLayout.LayoutParams(geefDPAlsInt(width, context), geefDPAlsInt(length, context));
        layoutTextParams.setMargins(geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context), geefDPAlsInt(margin, context));
        layoutTextParams.gravity = layoutGravity;
        tekstView.setLayoutParams(layoutTextParams);
        tekstView.setGravity(gravity);
        tekstView.setText(tekst);
        tekstView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textsize);
        tekstView.setTag(tag);
        return tekstView;
    }

So I have tried a lot of stuff that I found on stackoverflow and else on the internet. A few things that I found a lot but didn't work are:
content.setMaxWidth(0) => my cards have no more content and the height becomes WAY to big

content.setWidth(0) => same result
content.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); => no change
content.setSingleLine(false); => no change
content.setMaxLines(10) => no change
content.setHorizontallyScrolling(false); => no change

I have tried some of these together as well. I really hope someone could fix this. Oh yea it works on Android 5.1 but not on Android version 7.
If you're still reading at this line than I would like to explicitly thank you for you're time and effort in advance!
Comment: Have you tried setting layout weight to 1 programmatically as described [here](https://stackoverflow.com/a/7254966/8762152)?
Comment: I tried this now but It doesn't change anything
Answer: Alright for anyone who has the same problem (I doubt it but still) Here is what fiex it for me. I recalculated the Width and Height of my views to dip's with a function (geefIntAsDp which I have written in a different helper). This works fine with normal Integers but you can't use it with wrap_content or match_parent. So all I needed to do was delete this conversion and it worked.


print BASE64 coded image into a FPDF document

Question: I've some as base64 stored images in a database. Is it possible to print those data directly in a PDF document, using FPDF?
Data sctructure of the image
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg7AAAfQAAACWCAYAAAAonXpvAAAfgUlEQVR4Ae2dC9BuVVnHuSN3QaBENA9h5A2IcJxMj8hUkymoQDfClIkmrQZr1EydMqapnKRMc8JmHLBBHadJJaV0lKQDZCmCQiqQ2KERUFARDhcFDpx /33W tznPe/ 3ttaa9/ a2Z9/32Xvt5nvVbl2evtdfee9dtS27bt4mACJmACJm8ACJtBvArv123xbbwImYAImYAImIAJ26K4HJmACJmACJjAAAnboAyhEZ8EETMAETMAE7NBdB0zABEzABExgAATs0AdQiM6CCZiACZiACdihuw6YgAmYgAmYwAAI2KEPoBCdBRMwARMwAROwQ3cdMAETMAETMIEBELBDH0AhOgsmYAImYAImYIfuOmACJm

I think $pdf->imagepng() should be the right function in FPDF.
Comment: I am also having the same problem. Did you find the answer?
Comment: Yes, I changed to TCPDF library. You can add an @ sign before your base64 string to convert. See: http://www.tcpdf.org/examples/example_009.phps
Answer: While the comments suggested a TCPDF solution, I did want to state that there is a way to do this entirely with FPDF. The thought process is like this:

Strip data:image/png;base64, from the URI using explode
Decode the URI with base64_decode
Save the decoded data to a PNG file with file_put_contents
Generate a PDF and add the PNG file with Image
Delete the PNG file with unlink

Always remember to error check. If the image fails to save to the server you obviously do not want to continue execution. Make sure to always strictly check if the functions return false!
Here is my solution. I used a tiny image for a small URI in this example.
const TEMPIMGLOC = 'tempimg.png';

$dataURI    = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAMAAADarb8dAAAABlBMVEUAAADtHCTeKUOwAAAAF0lEQVR4AWOgAWBE4zISkMbDZQRyaQkABl4ADHmgWUYAAAAASUVORK5CYII=";
$dataPieces = explode(',',$dataURI);
$encodedImg = $dataPieces[1];
$decodedImg = base64_decode($encodedImg);

//  Check if image was properly decoded
if( $decodedImg!==false )
{
    //  Save image to a temporary location
    if( file_put_contents(TEMPIMGLOC,$decodedImg)!==false )
    {
        //  Open new PDF document and print image
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->Image(TEMPIMGLOC);
        $pdf->Output();

        //  Delete image from server
        unlink(TEMPIMGLOC);
    }
}

Comment: Perhaps one day somebody will run into the same issue and find it useful. ^o^
Comment: @MariM I ran into this and I find it useful +1.
Answer: I know this is an old topic, but there is an easier way of solving this problem. Just try this simple steps:

Strip data:image/png;base64 from URI using explode
Concatenate data://text/plain;base64, with what is left from the stripped URI
Use the result string(base64) as argument of FPDF Image()

Example:
$dataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAMAAADarb8dAAAABlBMVEUAAADtHCTeKUOwAAAAF0lEQVR4AWOgAWBE4zISkMbDZQRyaQkABl4ADHmgWUYAAAAASUVORK5CYII=";

$img = explode(',',$dataURI,2)[1];
$pic = 'data://text/plain;base64,'. $img;

$pdf = new FPDF();
$pdf->AddPage();
$pdf->Image($pic, 10,30,0,0,'png');
$pdf->Output();

Remember to choose the correct image type for Image() method call.
Comment: This is great. How did you figure this out?
Comment: Won't it be faster if we simply str_replace "image/png" with "text/plain"?
Comment: See, it's things like this that makes me not completely give up hope in fellow programmers. Others who actually investigate how things work and not just go "oh, download this library with these 16 dependencies - and you'll need to downgrade your php version to 5.4 for it work"

Thank you for being awesome!
Comment: Thank you so much! I searched everywhere, you deserve more upvotes. Almost everyone says save it locally first before inserting it to fpdf but in my case that is not an option. Thank you so much!
Answer: To ensure the images work with FPDF and to avoid errors, here is a modified version of @pedro-soares' code:
function getImage($dataURI){
  $img = explode(',',$dataURI,2);
  $pic = 'data://text/plain;base64,'.$img[1];
  $type = explode("/", explode(':', substr($dataURI, 0, strpos($dataURI, ';')))[1])[1]; // get the image type
  if ($type=="png"||$type=="jpeg"||$type=="gif") return array($pic, $type);
  return false;
}

Because FPDF only allows these three file types, it is important to check that it is valid.
To use:
$pic = getImage($Base64StringGoesHere);
if ($pic!==false) $pdf->Image($pic[0], 10,30,0,0, $pic[1]);

Answer: Don't know why haven't anyone wrote this solution till now, but I have had success by directly passing the base64 string to FPDF's Image() function. Just make sure that your base64 string has data:image/png;base64, at the beginning.
$data = "base64_string.........";
$pdf -> Image($data, 0, 0, 0, 0, "PNG");

Please note that you have to explicitly specify the image type "PNG". The 4 0s are for the image X, Y width and height respectively. Set the width and height to 0 for FPDF to automatically use the image's dimensions.
Comment: Agreed. I only use the default base64 returned by Dropbox when downloading an image, I set the extension obtained from base64 string in the Image() method and it works, there is no necessity for transforming to text/plain as suggested in top answers.
Answer: To add a bit more to Mari M answer, I just added few lines to work with any types of images. (as for me FPDF complains if the image is jpeg and I try to load tempimg.png)
$this->tempImgLoc = 'tempimg';    // Here I just remove the file extension
$dataPieces = explode(',',$dataURI);
$encodedImg = $dataPieces[1];
$decodedImg = base64_decode($encodedImg);

// extract the image type from data:image/png;base64
$extension = explode('/', $dataPieces[0]);
$extension = explode(';', $extension[1]);

$this->tempImgLoc .= '.' . $extension[0];

I am sure there is a better way to do that with regular expression, but to be honest, regexp is not my cup of tea...
Answer: Ok, I wasted half day making test with this issue. I have to tell that this solution is for print images from db row, directly, without stored them on temp files.
I´m going to write some points to consider:

I´m using blob type on the DB to store human signature for print on pdf document
I´m sending the signature to store to the db by post method, from a canvas node.
When I print the string from the db blob, it´s come without the plus character "+" that don´t let me to print correctly the signature. To solve this issue, I make a "str_replace" to remove the blank spaces and insert the plus character.

Then the only thing that you have to do is:
$pdf->Image(str_replace(' ','+',$dbRow['blobImage']),160,150,20,10,'png');

If you need , like me, print several images from the db, you have to see if them come or not, because if the image come empty, you´ll have an error.
I just add this to the last code:
if( $dbRow['blobImage'] ){
                 $pdf->Image(str_replace(' ','+',$dbRow['blobImage']),160,150,20,10,'png');
            }

NOTE:

160 -> X position of the image
150 -> Y position of the image
20 -> X Scale of the image
10 -> Y Scale of the image
'png' -> The base format of my Base64 Image Type.
Answer: New solution with imagecreatefromstring()   Summer 2019

delete temporary .png if exist
create temporary .png file
use $pdf->Image   (fpdf)

My Api returns me a Datamatrix of 1234 as Byte Array. The folowing code shows you how to use that Byte Array as Png in Fpdf.
My $response = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABJSURBVChTjYwBCgAgCAP9/6dNreVUgg7Gps3EUOfD5Q4Au6YdAGcH8ygyVKrFnhmbc9FL7qRxWRxEkXWW4Q691UsGpZPzt7dEFyY47RMW+x2LAAAAAElFTkSuQmCC"
$filename = '/lk_Reptool/printing/tmp/tmppng.png';

if (file_exists($filename)) {
    unlink($filename);
}
$response = file_get_contents('https://myapi.com/TwoDCode/GetDatamatrixAsPngByteArray?datamatrixText=' . $RepID . '&pixelSize=100');
$response = base64_decode($response);
$img = imagecreatefromstring($response);
imagepng($img, $filename);

code for pdf
$pdf = new PDF('P', 'mm', 'A4');
$pdf->AddPage();
$pdf->Image('/lk_Reptool/printing/tmp/tmppng.png', 180, 20, 10, 10);

Answer: Simply extend Fpdf (tested on 1.8.1) with this function:
protected function _parsepngdata($data) {
    $f = tmpfile();
    fwrite($f, base64_decode(substr($data, strpos($data,",")+1)));
    fseek($f, 0);
    $info = $this->_parsepngstream($f,"pngdata");
    fclose($f);
    return $info;
}

and use it this way: (provide base64 data instead of file name, and set type to "pngdata" instead of "png")
$pdf->Image("data:image/png;base64,iVBORw0KGgo...", $x, $y, $w, $h, "pngdata");

It will create a tempory file, write / read data to/from and delete it afterwards.


Fisher's exact test gives non-uniform p-values

Question: I am trying to apply Fisher's exact test in a simulated genetics problem, but the p-values appear to be skewed to the right. Being a biologist, I guess I'm just missing something obvious to every statistician, so I would greatly appreciate your help.
My setup is this: (setup 1, marginals not fixed)
Two samples of 0s and 1s are randomly generated in R. Each sample n = 500, probabilities of sampling 0 and 1 are equal. I then compare the proportions of 0/1 in each sample with Fisher's exact test (just fisher.test; also tried other software with similar results). Sampling and testing is repeated 30 000 times. The resulting p-values are distributed like this:

Mean of all the p-values is around 0.55, 5th percentile at 0.0577. Even the distribution appears discontinuous on the right side.
I've been reading everything I can, but I don't find any indication that this behavior is normal - on the other hand, it's just simulated data, so I see no sources for any bias. Is there any adjustment I missed? Too small sample sizes? Or maybe it's not supposed to be uniformly distributed, and the p-values are interpreted differently?
Or should I just repeat this a million times, find the 0.05 quantile, and use that as the significance cutoff when I apply this to actual data?
Thanks!

Update:
Michael M suggested fixing the marginal values of 0 and 1. Now the p-values give a much nicer distribution - unfortunately, it's not uniform, nor of any other shape I recognize:

adding the actual R code: (setup 2, marginals fixed)
samples=c(rep(1,500),rep(2,500))
alleles=c(rep(0,500),rep(1,500))
p=NULL
for(i in 1:30000){
  alleles=sample(alleles)
  p[i]=fisher.test(samples,alleles)$p.value
}
hist(p,breaks=50,col="grey",xlab="p-values",main="")

Final edit:
As whuber points out in the comments, the areas just look distorted due to binning. I am attaching the QQ-plots for the setup 1 (free marginals) and setup 2 (fixed marginals). Similar plots are seen in Glen's simulations below, and all these results in fact seem rather uniform.
Thanks for the help!
Comment: These histograms look remarkably uniform to me.  You have to remember that histograms display probability (or frequency) by means of *area*.  The increasing gaps to the right (due to the unavoidable discreteness of the p-value distribution of any nonrandomized test of discrete data) cause the bar heights to increase, *but their areas seem to be almost constant.*  Instead of using a histogram to assess uniformity, graph the empirical CDF.
Comment: Try to repeat your simulation while holding not only the group sizes (500 each) but also the sum of "1" (over the pooled sample) constant. The p value of Fisher's exact test is derived under this "fixed marginal distribution" setting. Does the picture look better then? Btw. you cannot expect the p-value distribution to be exactly uniform by the discrete nature of the sampling distribution (i.e. the hypergeometric).
Comment: Aside from the specific distribution, this question appears to be completely answered [here](http://stats.stackexchange.com/questions/153249/distribution-of-p-values-binomial-test/)
Comment: It might be useful to have look at your R code.
Comment: @Glen it seems to me from the code that in each iteration both samples have the same number of 0s and 1s (i.e. null hypothesis should hold) or am I wrong?
Comment: Thanks for the suggestion, although it didn't solve the problem. I'll update the question right away
Comment: Added the R code. I get similar results if I export the columns of randomized 0/1s and calculate Fisher's test in a genetic software called PLINK - I was thinking, maybe it's some property of the test itself?..
Comment: You should set the seed for reproducibility. I used `set.seed(6069)`. I get a histogram with the same profile as yours, but I notice that `mean(p<.05)  # [1] 0.0516`. I'll do more later.
Comment: The p-value is uniformly distributed if the null hypothesis is true.  That's probably not the case for a majority of the tests.
Comment: @Glen, bdeonovic: Let's say sample 1 has some number A of 1s, and sample 2 has some number B of 1s. A and B are not equal here - if it were so, every time the test statistic would be the same - but A+B stays constant. In other words, it's always 500 zeros and 500 ones, but sometimes they are divided equally between the samples, and sometimes they are not.  Thinking this way, _"no difference between samples"_ is probably the most frequent case - but it should be reflected in the test statistic, not the p-value... Am I understanding this correctly?
Comment: @juod I see, then Glen's comment stands to explain the phenomenon: p-values are uniformly distributed under the null hypothesis, which does not hold in each of your simulation iterations.
Answer: The problem is the data are discrete so histograms can be deceiving.  I coded a simulation with qqplots that show an approximate uniform distribution.
library(lattice)
set.seed(5545)
TotalNo=300
TotalYes=450

pvalueChi=rep(NA,10000)
pvalueFish=rep(NA,10000)

for(i in 1:10000){
  MaleAndNo=rbinom(1,TotalNo,.3)
  FemaleAndNo=TotalNo-MaleAndNo
  MaleAndYes=rbinom(1,TotalYes,.3)
  FemaleAndYes=TotalYes-MaleAndYes
  x=matrix(c(MaleAndNo,FemaleAndNo,MaleAndYes,FemaleAndYes),nrow=2,ncol=2)
  pvalueChi[i]=chisq.test(x)$p.value
  pvalueFish[i]=fisher.test(x)$p.value
}

dat=data.frame(pvalue=c(pvalueChi,pvalueFish),type=rep(c('Chi-Squared','Fishers'),each=10000))
histogram(~pvalue|type,data=dat,breaks=10)
qqmath(~pvalue|type,data=dat,distribution=qunif,
       panel = function(x, ...) {
         panel.qqmathline(x, ...)
         panel.qqmath(x, ...)
       })

Comment: Such spikes and dips in histograms or bar charts of *discrete* data are often artifacts of the binning procedure.  Don't trust them: use more discerning plots of the distributions, such as QQ plots or graphs of the ECDFs. Even if they are real, nobody will care provided the distributions of p-values are approximately uniform and of the right density where it matters for decision making: in the interval close to zero (and certainly less than 0.5).
Comment: @whuber, Glen, thanks so much! In fact the binning was deceptive, as simply splitting Glen's histograms into more breaks gave a similar pattern to mine. And I also get linear empirical CDF/QQ with my simulations, so the problem seems to be solved.
Comment: Excellent point @whuber, I'll update with qqplots.
Comment: @juod: it would be highly appreciated if you could add the qqplot for illustration, maybe even for both simulations?
Comment: The qq plots really help--thank you.  Don't you want to change the first paragraph of your answer, though? Do you still maintain there is a problem with the simulation and that there is a "spike" in the p-value distribution?


O que é "One Level of indentation"?

Question: Estava esses dias atrás assistindo a essa vídeo aula no Laracasts, onde há uma explicação que ensina a evitar o acumulo de muito código em um método, separando em vários métodos com responsabilidades específicas e reduzindo assim o tamanho da indentação - pelo menos foi o que entendi, me corrijam se eu estiver errado.
Percebi também que existe o mesmo "ensinamento" nesse link, que me parece ser o blog da Microsoft.
O que é curioso é que, nessas vídeos aulas do Laracast, geralmente os assuntos tratados são do framework em PHP chamado Laravel. Não sei se é só uma coincidência, mas eu vi que o link acima é da Microsoft, e o criador do Laravel, o Taylor Otwell, disse numa vídeo-aula que, antes de programar em PHP, programava em ASP - que é da Microsoft.
Pode parecer irrelevante essa última colocação, mas ela é importante para minha dúvida:
Esse é um padrão específico ao desenvolvimento do ASP (ou qualquer outra coisa da Microsoft, como C# e etc), ou realmente esse "One Level of Indentation" é uma padrão de projeto ou um padrão de codificação?
Nota: Não conheço muito sobre as "coisas" da Microsoft, então perdoem-me se falei alguma bobagem.
Comment: É uma "boa prática", ou seja, algo que se você seguir só por seguir, vai te ferrar.
Comment: Como perdi o *timing* da pergunta não vou responder, mas esta é uma dessas regras esdrúxulas que alguém inventa e um monte de bobo segue. Não há vantagem algum em forçar isto. Se algo deve ter apenas um nível de *indent* deve ser porque faz sentido ali e não porque uma regra tola manda. Assim como é ruim juntar várias responsabilidades em um único método, separar responsabilidades que estão intimamente relacionadas também pode ser ruim. Complicação sem ganho.
Comment: Não sei se as tags microsoft e laravel se encaixam nessa pergunta ...
Comment: object calisthenics, cai na categoria boas práticas ou se prefrerir recomendações [aqui](https://github.com/object-calisthenics/phpcs-calisthenics-rules) tem algumas outras, isso serve para qualquer linguagem.
Comment: Repositories e Service Layers ajudam nisso. Ao invés do Controller ter contato direto com o Model, esses repositórios e camadas de serviços fazem todo o trabalho. O que ajuda em pouco código no Controller, na Identação e evita acumulo de códigos repetidos.
Comment: Para a prática ser boa tem que ter prática. Tem gente que sai usando os padrões de projeto e "boas práticas" só porque acha bonitinho, sem entender o sentido :D
Comment: Grande @rray. Preciosas informações :D
Comment: Podia ter isso em português, hein :D
Comment: @rray depois da sua referência, pude "aprender" a como a pesquisar sobre o assunto. Acho que vale a pena ver isso aqui [Object Calisthenics - Português](http://rogerio.me/object-calisthenics/)
Answer: Eles estão se referindo a indentação do código. Para manter a legibilidade do código eles estão defendendo que deve ser usado apenas um nível de indentação.
O exemplo a seguir estaria fora desse padrão.
public void func1(){
    for( i in list){//Primeiro nível de indentação
       if( i.foo == true ){//Segundo nível de identação
         //faça coisas
       }
    }
}

Para corrigi-lo você deve eliminar o segundo nível de indentação transportando ele para dentro de uma função.
public void func1(){
    for( i in list){//Primeiro nível de indentação
       facaCoisaComI(i);
    }
}

public void facaCoisaComObjeto(Objeto i){
   if( i.foo == true ){
         //faça coisas
   }
}

Esse padrão não específico de nenhuma tecnologia ou linguagem. É uma boa prática para melhorar a legibilidade do seu código.
Answer: Esse tipo de recomendação independe de linguagem. Não se prenda muito a definições de padrão de projeto ou codificação, ou se algo vem da Microsoft ou do PHP.
Tente separar o conceito da implementação em si. Você pode muito bem aplicar esse conceito em COBOL também, qual o problema?
Procure analisar o que as linguagens tem em comum. É a orientação a objetos? Então muito provavelmente você consegue aplicar os princípios de SOLID.
Seguir tudo que dizem que é boa prática também não é uma boa ideia. Singleton já foi considerado uma boa ideia, mas no contexto atual é considerado um Anti-Pattern.
Resumindo, procure interpretar as ideias e seja crítico, entenda o por que dizem que tal coisa é boa e se faz sentido no contexto que você está aplicando.
Comment: Bons pontos, bem feita. Minha própria COBOL terá so um nível de recuo, mas que a ajuda para a compreensão poderia facilmente estar sob por ter um multi-screen "case statement" . Ele não está a seguir as palavras que recebe a boa prática, mas compreender a intenção, e não apenas a letra da lei.
Answer: Isso é independente da linguagem ou ambiente. É apenas sugestão de boa prática na escrita de códigos. E para não achar que apenas falo por falar, eu programava em ASP (clássico), antes de entrar no PHP, por volta de 1999. A recomendação de níveis de identação é também questão de escolha pessoal. Não há nenhuma regra ou mesmo um padrão amplamente aceito que diga que deve ser assim com apenas um nível. Aliás, particularmente discordo de ter apenas um nível pois imagine a situação como no exemplo postado pelo Vinicius Zaramella,
for( i in list){//Primeiro nível de indentação
   if( i.foo == true ){//Segundo nível de identação
     //imagine que aqui precise fazer apenas 1 ou 2 linhas de código
     //particularmente acho desnecessário ter o trabalho de criar um novo método para algo tão pequeno.
   }
}

Independente disso, sempre evite muitos níveis de identação, como
if () {
    if () {
        if () {
            if () {
                if () {

                }
            }
        }
    }
}

Aqui temos 4 níveis. Se é aceitável ou não, isso dependerá do contexto, do real motivo em usar dessa forma. Contudo, se conseguir reduzir é sempre melhor.
Quando perceber que está criando condicionais dentro de condicionais, pare um pouco e reflita sobre a lógica. Pois quando chega nesse "espagueti de condicionais", pode ter algo errado ou algo que pode ser melhor escrito.

O que é "One Level of indentation"?


Create View with Two columns in Two Tables

Question: There are two tables: sales and expenses. sales has two columns: sale_date and price, expenses table has two columns: date and amount. also have a view with days in
year. (Create View with 365 days)
i want to add another two columns to this view: sales and expenses with data in sales and
expenses tables.
example :
Sales Table
sale_date   price

05-DEC-11   1,500
05-DEC-11     500
11-DEC-11     800
17-DEC-11   2,400

Expenses Table
date        amount

06-DEC-11      300
11-DEC-11      100
11-DEC-11      400
15-DEC-11    1,100

View should create as below
date        sales   expenses

01-JAN-11    null    null
02-JAN-11    null    null
03-JAN-11    null    null
04-JAN-11    null    null
05-JAN-11    null    null

...

05-DEC-11   2,000    null
06-DEC-11    null     300
07-DEC-11    null    null
08-DEC-11    null    null
09-DEC-11    null    null
10-DEC-11    null    null
11-DEC-11     800     500
12-DEC-11    null    null
13-DEC-11    null    null
14-DEC-11    null    null
15-DEC-11    null   1,100
16-DEC-11    null    null
17-DEC-11   2,400    null

...

28-DEC-11   null     null
29-DEC-11   null     null
30-DEC-11   null     null
31-DEC-11   null     null

sales and expenses columns in view created with sum of price and amount Columns in sale and expenses table group by date in those two tables.
how could i do this ?
Comment: I'm not sure but did you try to create that view on your own before you posted here?
Comment: @Lion i tried to do that. but unable to fill view with sum of columns group by date
Answer: This should get you there:
SELECT the_day, price, amount
  FROM year_days LEFT JOIN (SELECT sale_date, SUM(price) price
                              FROM sales
                             GROUP BY sale_date) ON the_day = sale_date
                 LEFT JOIN (SELECT expense_date, SUM(expenses) amount
                              FROM expenses
                             GROUP BY expense_date) ON the_day = expense_date
 ORDER BY the_day;

THE_DAY        PRICE     AMOUNT
--------- ---------- ----------
...
01-DEC-11
02-DEC-11
03-DEC-11
04-DEC-11
05-DEC-11       2000
06-DEC-11                   300
07-DEC-11
08-DEC-11
09-DEC-11
10-DEC-11
11-DEC-11        800        500
12-DEC-11
13-DEC-11
14-DEC-11
15-DEC-11                  1100
16-DEC-11
17-DEC-11       2400
18-DEC-11
...

Comment: How can i write above query with query in [http://stackoverflow.com/questions/8531269/create-view-with-365-days] as a one query ?


Question about Taylor's series

Question: Is there an example of a function whose taylor series converge at every point but does not equal the value of the function at every point?
Answer: The standard example is $f(x)=e^{-1/x^2}$ when $x\ne 0$, and $f(0)=0$. The Maclaurin series of this is identically $0$. So there is convergence to $f(x)$ only at $x=0$.
We cannot do better (or should one say worse?): The Taylor series at $x=a$, if it exists, converges to $f(x)$ at $x=a$. So there is always convergence to $f(x)$ at at least one point.
Answer: One well-known example is $$
  f(x) = e^{-\frac{1}{x^2}} \text{.}
$$
This $f$ is differentiable arbitrarily often, and $f^{(n)}(0) = 0$ for all $n$, meaning its taylor series around $0$ is identically zero. Yet $f(x) \neq 0$ for all $x \in \mathbb{R} \setminus \{0\}$.

Question about Taylor's series


passar valor de um select para uma página php sem atualizar a página!

Question: Bom dia, pessoal eu tenho um evento de onchange em um select, eu queria pegar o valor do select e enviar para uma pagina php.
    $(document).on("change", "#doc_sel_clinic", function(){

  var id = $(this).val();
  $("#id_clinic_hidden").val(id);
    console.log(id);

});

eu preciso enviar esse id e pegar na página php para fazer uma busca pelos dados somente por esse id, uso o codeigniter com url amigavel.
eu tentei passar via sessão pra pegar com php e não consegui, quais alternativas para fazer isso?
obrigado
Answer: Você precisa fazer uma requisição assíncrona (mais conhecida popularmente como AJAX) para alcançar o que deseja.
Assumindo que você tenha uma página PHP que trate os dados que você enviar, você pode usar o jQuery e fazer algo assim:
$('#doc_sel_clinic').on('change', function() {
  var id = $(this).val()

  // Se fosse uma requisição POST, você pode trocar `$.get` por `$.post`:
  $.get('/tratar-dados.php', {
    // Você poderá acessar essa propriedade pelo PHP com `$_GET['id']`:
    id: id
  })
    .done(function(resposta) {
      alert('Dados salvos com sucesso!')

      // Resposta é a mensagem que o PHP "mandou" de volta ao cliente.
      // Supondo que na sua página PHP você tenha um `echo $_GET['id']`, a
      // resposta irá ser uma `string` com o ID que você passou no objeto
      // como segundo argumento na função `$.get`.
      alert('Resposta do servidor: ' + resposta)
    })
    .fail(function() {
      alert('Whoops! Parece que houve um erro ao tentar tratar os dados.')
    })
})

Referência:

jQuery.get.
Comment: "*o objetivo do site não é [...] dar o código pronto como ele pede nesse contexto*" - Vc ;)
Comment: Obrigado, fiz dessa forma que falou. recebi a mensagem de sucesso porém quando vou buscar no php ele só mostrar que está vazio. Dessa forma array(0) { }. Alguém sabe o que pode ser?
Comment: O que está vazio? O que você está tentando acessar?


Prove that the number of ways to put $n$ distinct balls into $n$ distinct boxes is $n^n$

Question:
Prove that the number of ways to put $n$ distinct balls into $n$ distinct boxes is
  $n^n$

The only approach I've come up with is to start with $1$ ball in each box, count the permutations, then take a ball out of one of the boxes and put it in another and then take the permutations times $n$ choose $2$ but then the process begins to branch and begins to feel intractable.
I find it surprising that the resulting formula, $n^n$, is so simple and that it's the same formula as order matters repetition allowed; is there a way to map this problem into that one?
Comment: I think you require that the boxes be distinct. Otherwise, with $n=2$, the balls are either together, or separate, so there are only 2 ways and not 4. And if the boxes are distinct, use the rule of product.
Answer: We assume that the boxes are also distinguishable.
Where shall the ball with label $1$ go?  We can put it into any of the boxes, so we have $n$ choices.
For each way of choosing where  Ball $1$ goes, there are $n$ ways to decide where the ball with label $2$ goes.
So there are $n^2$ ways to decide the fates of Ball $1$ and Ball $2$.
For every way to decide where Ball $1$ and Ball $2$ go, there are $n$ ways to decide where Ball $3$ goes.
And so on.
Remark: More generally, suppose that we have $n$ balls and $k$ boxes. At each stage, we have $k$ possible decisions, for a total of $k^n$.
It is easiest to answer your second question in this more general setting. Imagine we have an alphabet of $k$ letters, and we want to make an $n$-letter word, repetition allowed. There are $k^n$ ways to do this. The mapping is as follows.
Suppose that we have a word of length $n$. Examine it, letter by letter. If the $i$-th letter of the word is the "letter" $j$, put the $i$-th ball into Box $j$. This establishes a bijection between words of length $n$ and ways to put balls into boxes.
Comment: This assumes that the boxes are distinct. If the boxes are indistinguishable, this won't work.
Comment: @CalvinLin: Thanks, I have made the assumption clear at the beginning. Didn't think of it because the stated answer is the answer for distinguishable boxes.
Comment: @CalvinLin Calvin I 've been looking up these questions and I am confused in this question(where you have commented)  and result of star and bars. Could you tell me what the difference between both these problems?https://math.stackexchange.com/questions/192670/n-unlabelled-balls-in-m-labeled-buckets
Comment: The balls are distinct or indistinct. (And in some other cases, check if the buckets are distinct/indistinct.)


Can you become a goalkeeper if you are only 5 ft 5 inches?

Question: I am 17. I used to play baseball in my school club but now I wanna change my sport and join a football club to become a goalkeeper.
Answer: Anyone can become a goalkeeper, but if you are talking about going on to play professionally then just take a look at some stats.
Brian Holt is currently the shortest goalkeeper in the MLS, at a height of 5'8" (172cm)
The shortest goalkeepers in the English Premier League (Michael Vorn/Mike Bunn) are 6'0" (183cm)
The shortest goalkeeper in the 2014 World Cup was Ivory Coast's Boubacar Barry at 5'11 (180cm)
So you can see that the top leagues/competitions are dominated by taller goalkeepers, and this is simply because the taller they are, the longer reach they have and the better chance they have of keeping shots out. This also commonly applies to central defenders since they have a greater chance of winning headers.
A shorter player would be best suited in a winger role, like Emanuele Giaccherini (5'6", 167cm) or Aaron Lennon (5'5", 165cm).
Lionel Messi and Sebastian Giovinco play as forwards and are 5'7" (170cm)
Comment: I would add on that if you really want to be a goalkeeper, you could look at arena/indoor football. The goals are smaller, so the height disadvantage may not be as big of an issue.
Answer: Your height will be a detriment to you being a goal keeper.   Your wingspan is probably a bigger indicator to whether you will have success though.  If your wingspan is 6'6" then you are much better off.
Given the main attributes of a goalie covering a goal (as most other goalie attributes would be outside the realm of height):

cover a fixed area (based on height and wingspan)
ability to move that fixed area (speed/quickness)
ability to anticipate where to move faster
ability to cover passes of a certain height

So you are already at a huge disadvantage to your 6'4" counterpart for #1.  I am going to assume that a shorter person would be quicker or more agile.  Maybe not by a lot but generally a little quicker since it is easier to move 150 pounds than 210 pounds.  So you might win on #2.  You may have issues with #3 since you are moving sports and this anticipation is learnt over many years.  And again you will have a major disadvantage on #4 unless you have outstanding vertical that can make up for you lack of height.  And there is really nothing that correlates with a shorter person having more hops.
So you can be a goalie for sure at a club level.  You have to demonstrate that your quickness, intuitiveness and vertical make up for your lack of height.   Note that you will probably have to be "better" than your competition to beat them out for a spot since you aren't the norm.  Going past club level though you will have to have world-class abilities in quickness or vertical (plenty of tall guys can be as intuitive as you) to carry on.  And if you do have world-class ability then maybe another position would highlight those things better.


Unable to see page context in cache context

Question: I created a page using Page Manager with Layout Builder. I created a path called: /my-account/{agent_number} witch allows me to create the agent_number string context.  I created my own custom block and able to get the agent_number like this:
$this->getContextValue('agent_number');

Now I build my block and would like to use contexts to cache my block:
/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data($this->getContextValue('agent_number'));
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['agent_number'],
      'max-age' => 86400,
    ],
  ];
}

I created my own CacheContext service:
<?php

namespace Drupal\earc_card_details\Cache\Context;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;

/**
 * Defines the AgentNumberCacheContext service, for caching.
 *
 * Cache context ID: 'agent_number'.
 *
 * @see \Drupal\Core\Session\AccountProxy::setAccount()
 */
class AgentNumberCacheContext implements CacheContextInterface {

  /**
   * The context repository service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * Creates LanguageInterfaceContext object.
   *
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The context repository service.
   */
  public function __construct(ContextRepositoryInterface $context_repository) {
    $this->contextRepository = $context_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t("Agent Number");
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
     $contexts = $this->contextRepository->getAvailableContexts();
     // Agent number is missing here.
     return $contexts['agent_number'] ?? '';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

The problem is that $this->contextRepository->getAvailableContexts() does not return the agent_number context.  Is there a way to get the page bulder context to appear here?
Answer: Try a route based context extending RouteCacheContext:
Example:
<?php

namespace Drupal\Core\Cache\Context;

/**
 * Defines the RouteCacheContext service, for "per route name" caching.
 *
 * Cache context ID: 'route.name'.
 */
class RouteNameCacheContext extends RouteCacheContext {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Route name');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return $this->routeMatch->getRouteName();
  }

}

You can use this core example and get instead of the route name a route parameter.
You can improve cache efficiency and prefix the context name with route.. Cache contexts are ordered hierarchically, so that the caching system can remove specific cache contexts already covered by more general ones when merging cache metadata.
This leads to further considerations. If the block is only visible on a specific route and the route has only one parameter, then the core route context would have the same results as the custom context. So a specific route context only makes sense if you have too many cached block variations because the block is used in different routes or because of other route parameters and the context aware block plugin doesn't have already an appropriate cache context.


Typescript: How to update select when object has changed

Question: I have this html code:

    G Level 3
    <select [ngModel]="selectedG3" (ngModelChange)="selectG3Changed($event)">
          <option></option>
          <option *ngFor="let g3 of gLevels3" [ngValue]="g3">{{g3.name}}</option>
        </select>

This is my ts-code:
gLevels3: GLevel[];
getGLevels3(): void {
   this.httpServerService.getGLevels(3).subscribe(glevel3 => this.gLevels3 = glevel3);
}

gLevels3 is an Array with Objects. I want to update the options of select every time I call the function getGLevels3().
Currently it is not working. After calling the function there are still the same options inside the select.
How can I trigger the update?
Comment: Have you looked at https://stackoverflow.com/questions/33181936/how-to-use-select-option-ngfor-on-an-array-of-objects-in-angular2?
Comment: @GetFuzzy no, but thanks. I wanted to make it easier for you to understand. actually it is working for select as I just got to know but not for a table with dynamic tablerows
Comment: Dynamic table rows sounds like you probably have a different binding problem. Might be worth a new question.
Comment: @GetFuzzy I see. Thank you anyways!
Comment: @GetFuzzy my problem is like this here: https://github.com/angular/angular/issues/15511 but not that I get an error. It is just not updating the table.
Comment: @GetFuzzy Actually I am getting closer. It is also not possible for select's. I send an object to another components function where I push the new object into the object-array. So far so good, it works. But there won't happen anything to neither the select nor the table.
Comment: I have started a new question: https://stackoverflow.com/questions/51710175/typescript-how-to-update-table-with-dynamic-tablerows-when-object-has-changed
Answer: I'm not sure if you have eliminated all other possibilities... Offhand your code looks correct. We have the same type of situation in a code base I work on. We have a filtering select options situation, and it is updating just fine.
        <select class="tool-controls__select" style="margin-right: 4px;" *ngIf="selectFilterOptions.length > 0 && chartIdsDefined" [(ngModel)]="selectedFilterOption" (change)="selectFilterOptionOnChange()">
            <option [ngValue]="filterItem" *ngFor="let filterItem of selectFilterOptions">{{filterItem}}</option>
        </select>
        <select class="tool-controls__select" [(ngModel)]="selectedOption" (change)="selectOnChange()">
            <option [ngValue]="item" *ngFor="let item of selectOptions">{{item.name}}</option>
        </select>


AWS EC2 instance reachabilty check failed for new instance with older Plesk Volume

Question: long story short.

5 year old Plesk environment (always updated) on an EC2 instance
for some reason the instance has two volumes attahed (root volume sda1 and a second sdf)
the mount point of the ec2 instance is the sdf though and the sdf volume is the volume with all the websites on it.
for cleanup reasons and cost reasons I want to remove the root volume (sda1) which is way older and is not the one running the plesk version

However I can't.

I of course can't remove the root volume (sda1) generally
I can however, detach the current root volume, also detach the secondary volume (sdf) and attach this sdf volume as the new root volume (what I'm actually after)

If I do that though I get a very long "initializing" phase followed by ½ checks failed and the reachability check of the instance is failing.
I also tried creating a completely new instance with the latest ubuntu, creating a new volume from a current snapshot of the sdf volume, but same problem. Always reachability check fails.
What could cause that? Why are there 2 volumes there in the first place? How could that have happened and how can I cleanup, so that the current mounted volume (sdf) is the root volume and the instance has the correct mount point.
Again, my simple goal is to get rid of the unused current root volume sda1
Thanks for your help.
Comment: Why would like to remove the root volume? why you don't use the ec2 without attach any volume and put your code and git and git clone and install everything using ansible or other tools?
Comment: I would like to remove the root volume cause for some reason it's old and unused! The current running volume is the secondary volume (sdf). This is the one running the current Plesk version and all websites hosted on this plesk environment. I would simply like to clean up and remove the other volume that is not necessary. However the one that is not necessary is currently attached as root volume. And if simply try to swap the positions I can't get it working as the reachabilty check fails.
Comment: sorry, the root volume is where you have the system installed :).
Comment: @c4f4t0r yeah, but what does that mean exactly :)
See … if I detach the secondary volume (sdf) the entire Plesk Environment with all it's websites, etc. is set back to the year 2019. So the root volume has basically a Plesk version and status of 2019 and only the secondary volume on (sdf) is the current version with the proper setup.
Comment: you need to check how you deploy the software, if you 1000 version of the software, you need to become crazy thinking about volumes.
Answer: A high level description follows of what I would try
First of all Create Backups/Snapshots of your volumes before touching them!!!
Use df -h and mount to help you review what mount points exist and what is used in each volume. Then (assuming that "some" things are being used from sda1) you can shutdown the VM and mount both volumes on a new temp VM that uses a separate root volume. Then use cp -a to copy from sda1 the directories that you saw being used to sdf. Then change /etc/fstab (that should be in sdf) to use these dirs from sdf instead of sda1. Shutdown the temp VM and now mount sdf to a new VM as root volume and try to boot it. When editing fstab you will most probably need to use UUIDs that are the same in all cases, or change device name to sda for all mount points since this volume will be the root volume of the new VM.


Drawing circles around image pixels with different radius

Question: I'm implementing the scale invariant feature transform algorithm... The entire point of the algorithm is to pinpoint on an image a set of features that can be used in further post-processing. I've succeeded into finding a vector that contains the key points and their co-ordinates in the form[x1co-ordinate y1co-ordinate circle1radius x2co-ordinate y2co-ordinate circle2radius..... N]
My objective is to draw a circle around those pixels... I tried using rectangle('curvature' circle1radius circle1radius) however I can't draw the ellipse around a certain point... Any suggestions? :)
Answer: Here is a function I have used for similar things.  Maybe it will work.
<code>function [circlesx, circlesy]=drawCircle(axes_handle,x,y,radius,npoints,c);
angles=0:(2*pi/(npoints-1)):2*pi;
circlesx=radius*cos(angles)+x;
circlesy=radius*sin(angles)+y;
patch(circlesx,circlesy,c);
</code>


Computing homology groups of a specific fiber bundle via the Serre spectral sequence

Question: Let $X=F_{\mathbb{Z_7}}(S^3,2)$ be the orbit configuration space, given by pairs of points $(x,y)$ of $S^3$ which dont lie on the same orbit, i.e., $x\neq g(y)$ for any given $g \in \mathbb Z_7$.  The projection on the first coordinate gives $F_{\mathbb{Z_7}}(S^3,2)$ the structure of bundle over $S^3$ with fibre $S^3\backslash\mathbb Z_7 \simeq \bigvee_6 S^2$ that admits a section.
Question: How do I compute its homology groups via the serre spectral sequence ${\displaystyle E_{p,q}^{2}=H_{p}(S^3,H_{q}(\vee_6 S^2))\Rightarrow H_{p+q}(X)}$ and what exactly went wrong on my attempt.

My incorrect attempt:
Using that $H_p(S^3;\mathbb Z^6)$ is $\mathbb Z^6$, if $p=0,3$ and $0$ otherwise and $H_q(\bigvee_6 S^2) $ is $\mathbb Z^6$, if $q=0,2$ and $0$ otherwise, we get for the $E^2$ terms of the spectral sequence:
$E_{p,q}^{2}=\mathbb Z^6$ if $p=0,3 \wedge q=0,2$ and otherwise $E_{p,q}^{2}=0$.
Therefore the differential map $d_2:E_{p,q}^{2} \to E_{p-2,q+1}^{2}$ is trivial for every $p,q$ (either $p\neq 0,3$ or $p-2 \neq 0,3)$. This implies $E_{p,q}^{2} = E_{p,q}^{\infty}$.
Furthermore we get the terms $E_{p,q}^{\infty}$
isomorphic to the successive quotients $F^p_{p+q}/F^{p-1}_{p+q}$ in a filtration
$0 \subset F^0_{p+q} \subset \dots \subset F^{p+q}_{p+q} = H_{p+q}(X)$ of $H_{p+q}(X)$.
Hence we have

$F^0_{0}/ 0=E_{0,0}^{\infty}=\mathbb Z^6$
$F^3_{3}/F^2_{3} =E_{3,0}^{\infty}=\mathbb Z^6$
$F^0_{2}/ 0=E_{0,2}^{\infty}=\mathbb Z^6$
$F^3_{5}/F^2_{5} =E_{3,2}^{\infty}=\mathbb Z^6$

and all the other quotients are $0$, since the other $E_{p,q}^{\infty}$ are zero.
We conclude:
$F^2_{3} = F^2_{5}=0$
$H_{0}(X) = F^0_{0}= \mathbb Z^6$
$H_{2}(X) = F^0_{2}= \mathbb Z^6$
$H_{3}(X) =F^3_{3}= \mathbb Z^6$
$H_{5}(X) = F^3_{5}= \mathbb Z^6 $
$H_n(X)=0$ for $n\neq 0,2,3,5$.
Answer: THe formula you wrote for $H^0(\bigwedge^6 S^2)$ is not correct; this wedge of spheres is connected and so its zeroth cohomology has rank one.


Block in custom module not registering on a particular site

Question: I'm having issues with a block that is created with a module I wrote. This module works on 2 out of 3 sites, all of which have a similar setup, so I'm not sure why it's being picky on one site.  Here is what I know:

The block is not showing up in the list on admin/structure/blocks, and is not available anywhere else.
hook_block_info() is being invoked on the site, but none of the other functions are being called. On the other two sites, calls are made to all the functions.
There aren't any blocks in the blocks table with the same name, but there is a record of the block in the table for each active theme.
I tried deleting these records out of the blocks table with no luck.
I've tried clearing cache and uninstalling/reinstalling with no luck.

Here code for my .module file. It is available here as well: http://pastebin.com/EYFgneie

/**
* Implements hook_block_info()
*/
function kcc_menu_block_info() {
    $blocks = array();

    //This IS being called
    dpm('hook_block_info');

    $blocks['kcc_menu_block'] = array(
        'info' => 'KCC Menu',
        'subject' => 'Menu within a block generated by a module.',
        'cache' => DRUPAL_NO_CACHE,
        'properties' => array(),
        'weight' => null,
        'status' => 1,
        'visibility' => null,
        'pages' => null,
        'region' => 'sidebar',
        );
    return $blocks;
}

/**
* Implements hook_block_view()
*/
function kcc_menu_block_view($delta = '') {
    $block = array();
    switch($delta) {
        case 'kcc_menu_block' :
            //Only show this block on non-admin pages
            if(!path_is_admin(current_path())) {
                $block['content'] = _kcc_menu_block_view_content();
                $block['title'] = _kcc_menu_block_title();
            }
        break;
    }
    return $block;
}

/**
* Implements hook_block_view_content()
*/
function _kcc_menu_block_view_content() {
    $results = _kcc_menu_block_links();
    return array(
        'message' => array(
            '#type' => 'markup',
            '#markup' => $results['markup'],
            '#prefix' => '
',
            '#suffix' => '
',
            ),
        );
}

/**
* Function to return the entire set of 1st-level links in the sidebar menu
*/
function _kcc_menu_sidebar_links() {
    return menu_tree_all_data('menu-menu-sidebar');
}

/**
* Function that returns the submenu for a specific link item out of a list of menu items.
*/
function _kcc_submenu_tree($menu_items, $mlid) {
    /**
    * The link returned is chosen by the mlid passed.
    *  An empty array will be returned if there are no children.
    *  $menu_items is from array returned from menu_tree_all_data()
    *  Sub-items of that array can be passed here
    */
    foreach($menu_items as $branch) {
        if($branch['link']['mlid'] == $mlid) {
            $child_tree = $branch['below'];
            return $child_tree;
        }
    }
}

/*
* Function to return the block title
*/
function _kcc_menu_block_title() {
    //The value is returned along with the
    //results from _kcc_menu_block_links()
    $result = _kcc_menu_block_links();
    return $result['title_link']['title'];
}

/*
* Function to determine and return the block content
*/
function _kcc_menu_block_links() {

    $returned = array();

    $sidebar_menu_links = _kcc_menu_sidebar_links();

    //An array of link items representing where the
    //user is currently located in the menu
    $current_trail_links = menu_get_active_trail($sidebar_menu_links);
    //Remove 'home' link from the current path
    unset($current_trail_links[0]);

    //Last item in the current trail is the current page
    $current_page_link = end($current_trail_links);
    reset($current_trail_links);

    //Get the set of links for the first level menu item
    $second_level_menu_items = _kcc_submenu_tree($sidebar_menu_links, $current_trail_links[1]['mlid']);

    if($current_page_link['depth'] == 1) {

        //1st level menu item with children
        //Display child links for level 1 menu
        $left_menu_items = $second_level_menu_items;
        $title_link = $current_trail_links[1];
    }
    elseif($current_page_link['depth'] == 2) {

        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_page_link['mlid']);
        $has_children = (!empty($third_level_menu_items)) ? true : false;

        if($has_children) {
            //Display child links in menu
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
            //dpm('2nd level menu item with children!');
        }
        else {
            //Display sibling links in menu
            $left_menu_items = $second_level_menu_items;
            $title_link = $current_trail_links[1];
            //dpm('2nd level menu item without children!');
        }
    }
    elseif($current_page_link['depth'] == 3) {

        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_trail_links[2]['mlid']);
        $fourth_level_menu_items = _kcc_submenu_tree($third_level_menu_items, $current_trail_links[3]['mlid']);
        $has_children = (!empty($fourth_level_menu_items)) ? true : false;

        //Display child links for level 2 menu
        //whether or not there are children
        if($has_children) {
            //dpm('3rd level menu item with children');
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
        }
        else {
            //dpm('3rd level menu item without children');
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
        }
    }
    elseif($current_page_link['depth'] == 4) {

        //Display child links for level 3 menu
        //dpm('4th level menu item without children');
        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_trail_links[2]['mlid']);
        $fourth_level_menu_items = _kcc_submenu_tree($third_level_menu_items, $current_trail_links[3]['mlid']);
        $left_menu_items = $fourth_level_menu_items;
        $title_link = $current_trail_links[3];
    }
    else {
        $left_menu_items = null;
    }

    $returned['title_link'] = $title_link;
    $returned['markup'] = '
';
    foreach($left_menu_items as $left_menu_item) {
        $returned['markup'] .= "
{$left_menu_item['link']['title']}
";
    }
    $returned['markup'] .= '
';

    return $returned;
}

I've exhausted all of my knowledge, so I'm up for any and all suggestions. Thanks in advance for you help!
Comment: Has the module name remained consistent? Make sure it matches what you are putting as the prefix before your hooks. That's gotten me a few times. Also, see if commenting out the "Only show this block on non-admin pages" condition makes it show up.
Comment: Thanks for the suggestion, but I'm still having no luck. I don't think it has anything to do with my module, but rather something on the site.  Also, the only function being called is kcc_menu_block_info(), whereas on the other sites they all get called.
Answer: I have no clue why, but having this in hook_block_info() is causing my problem:
'status' => 1,

That is supposed to set the block to be enabled by default, but for some reason it removes the block from /admin/structure/block for all three sites.
This solved my problem, but it doesn't seem right. Any thoughts?


Prove identity.

Question: Let $\xi >0$ and $\beta \in {\mathcal R}$. Define $x := x(\xi)$ as one of the roots of a quadratic equation:
\begin{equation}
\xi^{2 \beta} x^2 - x + 1 =0
\end{equation}
The question is to prove the following identity:
\begin{equation}
(-2\beta) \frac{\xi^{-2 \beta-1}}{(x - \xi^{-2 \beta})^2} + x \frac{\beta \xi^{2 \beta-1}}{1-2 x \xi^{2 \beta}} \left(1 - \frac{\xi^{-2 \beta}(3 x - \xi^{-2 \beta})}{x(x-\xi^{-2\beta})^2}\right) = 0
\end{equation}
Indeed, if you type the above into Mathematica and apply FullSimplify[] to it we get zero. How can we prove it analytically?
Answer: Let us first reduce both terms to the common denominator. We have:
\begin{equation}
\frac{-2 \beta \xi^{-1+2 \beta}}{(-1+x \xi^{2 \beta})^2} + \frac{\beta \xi^{2 \beta-1} \left(1 + x - 3 x \xi^{2 \beta} - 2 x^2 \xi^{2 \beta} + x^3 \xi^{4 \beta}\right)}{(-1+x \xi^{2 \beta})^2(1 - 2 x \xi^{2 \beta})}
\end{equation}
Now we factor out the common terms.
\begin{eqnarray}
\frac{\beta \xi^{-1+2 \beta}}{(-1+x \xi^{2 \beta})^2} \left(-2  +
\frac{\left(1 + x - 3 x \xi^{2 \beta} - 2 x^2 \xi^{2 \beta} + x^3 \xi^{4 \beta}\right)}{(1 - 2 x \xi^{2 \beta})}
\right) = \\
\frac{\beta \xi^{-1+2 \beta}}{(-1+x \xi^{2 \beta})^2}
\left(\frac{x^3 \xi^{4 \beta} - 2 x^2 \xi^{2 \beta} + x(1+\xi^{2\beta}) - 1}{1 - 2 x \xi^{2 \beta}}\right)
\end{eqnarray}
Now, a miracle appears!;-) It turns out that the third order polynomial in the numerator factorizes very nicely:
\begin{equation}
x^3 \xi^{4 \beta} - 2 x^2 \xi^{2 \beta} + x(1+\xi^{2\beta}) - 1 = (-1 + x \xi^{2 \beta}) (1 - x + x^2 \xi^{2 \beta})
\end{equation}
Since the last factor on the right-hand side is, from the definition of x, identicaly equal to zero the whole expression is also equal to zero. The only question remains, how can I find out in the first place that the third order polynomial factorizes so nicely?

Prove identity.


When voting to close as a duplicate of an unanswered question, the wording of the auto-comment "Does this answer your question?" makes no sense

Question: Currently, when voting to close a question as a duplicate of another question, the system automatically posts a comment in the following format:

Does this answer your question? [link]

However, this wording is somewhat out-of-sync at times. I have just now voted to close a duplicate question because the OP posted an essentially identical question; however, neither of the questions had answers.
In case anyone has suggestions for a better phrase, throw them out there.
Comment: thats a good point but I do not think we mods can change that automatic text, I added status review tag to it so some SE staff can take a note there is demand for this, but I doubt they would change it just for one site
Comment: Semi-related MSE posts: [The auto-comment "Does this answer your question?" generated when voting to close as a duplicate is sometimes confusing](https://meta.stackexchange.com/q/339563/335251), [New duplicate automatic comment makes literally zero sense when voting to close as a duplicate of an unanswered question](https://meta.stackexchange.com/q/340009/335251) – The former is [status-declined] with [this answer by Yaakov](https://meta.stackexchange.com/a/343285/335251).
Answer: This is a bit of an edge-case – unless you're a mod, you can only close a question as a duplicate of a question with no upvoted or accepted answers if both questions were posted by the same author (as noted in this FAQ on MSE). Otherwise, regular users can't close a question as a duplicate of an unanswered one in the first place.
As I mentioned in the comments, there have been some similar posts on MSE asking for a change to the wording of this comment. In particular, this one was marked as status-declined, with this explanation by Yaakov that the wording of the automated comment is, by and large, accomplishing its intended goal. This particular edge-case doesn't seem to justify making a change to this wording.


Imprimir radio checado no UlkitCSS

Question: Uso o UlkitCss e tenho trechos de um formulário com campos input radio conforme abaixo.
Ao imprimir (Ctrl+p ou  window.print() ou $windows.print) o campo não aparece checado. O radio selecionado simplesmente não aparece.
Como fazer para aparecer o campo checado na impressao?
Tenho um código:
 <form>

                        <input class="uk-radio" type="radio" name="item4">item 1.

                        <input class="uk-radio" type="radio" name="item4"> item 2

                        <input class="uk-radio" type="radio" name="item4" checked="checked" ng-checked="true">item 3

                        <input class="uk-radio" type="radio" name="item4">item 4

            </form>

Comment: Você precisa criar um [exemplo verificável](https://pt.stackoverflow.com/help/mcve) para demonstrar o problema, só esse pedaço de código não ajuda. Veja que coloquei esse código no fiddle e o print funciona perfeitamente no Chrome: http://jsfiddle.net/xpvt214o/528256/
Comment: Com o seu código do jeito que está na pergunta executado em uma página sem esse UIKit e sem o angular está funcionando normal, quando eu aperto Ctrl+p ele aparece checado, então é algo no CSS ou mais provavelmente no angular que esta tirando o checked na hora de imprimir a página
Answer: Israel não entendi muito bem a maneira que você utilizou o ng-checked, você ainda o usou junto com o checked do HTML, assim provavelmente não funciona. O mais indicado aí seria como no exemplo que fiz, utilizando model e setando um value nos inputs. Aí o que você setar no model refletira no input, aí é só mandar imprimir:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.marcado = 3;     // marca o terceiro checkbox
});

/* função de impressão */
document.getElementById('imprimir').onclick = function(){
  window.print();
}

<form ng-app="myApp" ng-controller="myCtrl">

              <input class="uk-radio" type="radio" name="item4" ng-model="marcado" value="1">item 1.

              <input class="uk-radio" type="radio" name="item4" ng-model="marcado" value="2"> item 2

              <input class="uk-radio" type="radio" name="item4" ng-model="marcado" value="3">item 3

              <input class="uk-radio" type="radio" name="item4" ng-model="marcado" value="4">item 4

</form>

<button id="imprimir">Imprimir</button>
Answer: Identifiquei onde o problema acontece. Não se tratava do angularjs nem do jquery.
No arquivo do CSS do UlkitCSS, linha 1606 a 1627 existem as propriedades:
  .uk-radio,
.uk-checkbox {
  /* 1 */
  display: inline-block;
  height: 16px;
  width: 16px;
  /* 2 */
  overflow: hidden;
  /* 3 */
  margin-top: -4px;
  vertical-align: middle;
  /* 4 */
  -webkit-appearance: none;
  -moz-appearance: none;
  /* 5 */
  background-color: transparent;
  /* 6 */
  background-repeat: no-repeat;
  background-position: 50% 50%;
  border: 1px solid #cccccc;
  transition: 0.2s ease-in-out;
  transition-property: background-color, border;
}

Bastava comentar o trecho
-webkit-appearance: none;
      -moz-appearance: none;

e agora aparece o radio/checkbox selecionado na impressao

Imprimir radio checado no UlkitCSS


Probability of a specific sequence

Question: I was preparing for my probability exam and i came across this problem. A fair dice is rolled until either 6 comes up or two $5$ comes up in a row.
For example some of the possible outcomes are
$$52546, 6, 36, 3251541355, 55, 255 \,\, \text {etc} $$
Find the probability that the last number to come up is a $6$.
I have attempted to solve this problem this way.
Let $X$ be the number of times the die was rolled to obtain two $5$ in a row and $Y$ be the number of times the die was rolled to obtain a $6$. Intuitively i thought that there could be a  $c$ such that $c(P(Y=n)) = P(X=n)$ . Then
$$1=\sum_{n=1}^\infty P(X=n)+P(Y=n)=\sum_{n=1}^\infty cP(Y=n)+P(Y=n)=(1+c)\sum_{n=1}^\infty P(Y=n)$$
$$\implies \sum_{n=1}^\infty P(Y=n)=\frac {1} {1+c}$$
However i am unable to find such a constant $c$. Any help / insight is appreciated.
Thanks
Comment: Calculation using a Markov chain gave me a probability of 7 / 8, you should be able to find c now.
Comment: Is this a question about a conditional probability? (The probability that the last result is 6 provided that the last result was a 6 or the last two results were fives?
Comment: @zoli It's the probability that the last digit ends with a 6. It's not asking for conditional probability.
Comment: @bobbym How did you arrive to the probability of 7/8
Comment: In addition to my solution below, I have been trying to understand your working. I have a number of questions. **(1)** Are $X, Y$ intended to be the first times at which $55$ and $6$ are rolled? So you want to compute $\textbf{P}[ Y < X]$? **(2)** Given these interpretations it seems to me that you want: $\textbf{P}[Y = n] = \frac16 \textbf{P}[X = n-1]$, where we condition on the $(n-1)$st roll being a $5$. **(3)** Can you explain the first sum on the left hand side of your sequence of equations.
Comment: 1) Yes , $X$ and $Y$ are meant to be the first time. 2) Yup ! that's also helpful. 3) The dice stops being rolled when we obtain $55$ or $6$.This can happen in $1,2,3,4...$ number of rolls.$P(X=n)$ is the probability of the number of times taken to obtain $55$ and $P(Y=n)$ is the probability of the number of times taken to obtain $6$. So $\sum P(X=n)+P(Y=n) =1$.Note $P(X=n)+P(Y=n)$ is the probability that the rolling of the dice stops in $n$ goes.
Comment: At the moment it seems to me as though the definitions of the variables $X, \, Y$ need to be clarified. Is $\{Y = n\} = \{\text{ first 6 rolled occurs at time n}\}$, or is it $\{Y = n\} = \{\text{first 6 rolled occurs at time n, and no 55 rolled }\}$? If it is the former then the sum you say equals $1$ actually equals $2$. If it is the later then the equation **(2)** is not true (note in the original I had accidentally interchanged the notation of $X$ and $Y$).
Comment: In addition to these points: have you actually checked your hypothesis $c \textbf{P}[ Y = n] = \textbf{P}[X=n]$? You should be able to write down these probabilities for $n=1,2,3$... which in turn should make you doubt the hypothesis. Have you looked at the method I provided below?
Answer: Here is an alternative method of solution. In the following I will write $A\, \text{b.} B$ to denote the event that $A$ occurs before $B$. So you want to calculate $\textbf{P}[ 6\, \text{b.}\, 55]$.
Instead we work with $\textbf{P}[55 \, \text{b.} \, 6]$, and condition on the event $5\, \text{b.}\, 6$. So
\begin{align}
\textbf{P}[55 \, \text{b.} \, 6] & = \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6]\, \textbf{P}[5 \, \text{b.} \, 6]
\\
& = \frac12 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6].
\end{align}
To evaluate the remaining probability, we condition a second time: this time conditioning on what the roll immediately after the $5$ is.
\begin{align}
\textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6] & = \sum_{j=1}^6 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is $j$} ] \textbf{P}[ \text{next roll is $j$}] \\
& = \frac16 \sum_{j=1}^6 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is $j$} ] \\
& = \frac16 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is $6$} ]  \\
& \qquad \qquad + \frac16 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is $5$} ] \\
& \qquad \qquad + \frac46 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is neither $5$ or $6$} ] \\
&= \Big( \frac{1}{6} \times 0 \Big)+ \Big( \frac{1}{6} \times 1 \Big) +\frac46 \textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is neither $5$ or $6$} ] \\
& = \frac16 + \frac46 \textbf{P}[55 \, \text{b.} \, 6],
\end{align}
in the final lines we used that
$$\textbf{P}[55 \, \text{b.} \, 6\, | 5\, \text{b.}\, 6 \text{ and the next roll is neither $5$ or $6$} ] = \textbf{P}[55 \, \text{b.} \, 6],$$
which is true since the information that we saw a $5$ but it wasn't followed by a $5$ doesn't tell us anything about the event $55 \, \text{b.} \, 6$. So substituting this into the first equation we have
\begin{align}
\textbf{P}[55 \, \text{b.} \, 6] & = \frac12 \Big( \frac16 + \frac46 \textbf{P}[55 \, \text{b.} \, 6] \Big) \\
& = \frac{1}{12} + \frac{4}{12}\textbf{P}[55 \, \text{b.} \, 6].
\end{align}
Rearranging gives: $\textbf{P}[55 \, \text{b.} \, 6] = \frac18$, and hence
$$\textbf{P}[6 \, \text{b.} \, 55] = \frac78.$$
Remark. In general this type of problem is more easily phrased in the context of a Markov chain, for which the probability you are wanting becomes a hitting probability. The proof above is essentially exactly the same as would be done using Markov processes, the exception being that the notation is simplified in that context.
Answer: The absorbing chain matrix is
$$\left(
\begin{array}{ccccc}
 \text{} & o & 5 & 55 & 6 \\
 o & \frac{2}{3} & \frac{1}{6} & 0 & \frac{1}{6} \\
 5 & \frac{2}{3} & 0 & \frac{1}{6} & \frac{1}{6} \\
 55 & 0 & 0 & 1 & 0 \\
 6 & 0 & 0 & 0 & 1 \\
\end{array}
\right)$$
The states have been labeled o which represents a throw of (1,2,3,4), 5 which is the first 5 thrown, 55 which is 2 5's in a row and 6 which is the first 6 thrown.
$$ \text{Q=}\left(
\begin{array}{cc}
 \frac{2}{3} & \frac{1}{6} \\
 \frac{2}{3} & 0 \\
\end{array}
\right)$$
$$\text{R=}\left(
\begin{array}{cc}
 0 & \frac{1}{6} \\
 \frac{1}{6} & \frac{1}{6} \\
\end{array}
\right)$$
$$\text{0=}\left(
\begin{array}{cc}
 0 & 0 \\
 0 & 0 \\
\end{array}
\right)$$
Now B is the probability of ending in some absorbing state (first row) starting in some transient state (first column).
$$\text{B=}\left(
\begin{array}{ccc}
 \text{} & 55 & 6 \\
 o & \frac{1}{8} & \frac{7}{8} \\
 5 & \frac{1}{4} & \frac{3}{4} \\
\end{array}
\right)$$
When we check the element o,6 we see the answer of $ \frac{7}{8} $

Probability of a specific sequence


History of "jazz minor/melodic minor" harmony

Question: I'm curious about the development of modern (post-bop-ish) jazz harmony. In Mark Levine's Jazz Theory Book, he shows how modes of the melodic minor scale can be used to form and improvise over chords with various types of alterations and functions. This would most famously include alt chords and their association with the seventh mode of the melodic minor, but also the Lydian dominant chord (fourth mode) used on a tritone sub, Lydian Augmented (third mode) subbed for a tonic chord, and playing melodic minor over a minor ii-V-i (sixth, seventh and first mode). These sounds have become closely associated with "straight-ahead" jazz as it's currently practiced. It's clear that Levine's approach was developed in hindsight from listening to (among others) Miles' and Coltrane's groups from the early sixties.
It's clear though that those groups were building on techniques that had been developed during and since the development of Bebop and even earlier (I've certainly heard sharp 5s and flat 9s played all over in swing-era recordings). I'm guessing the chord alterations were being used well before the associations with particular scales. I'd also guess that the "altered scale" (seventh mode) was "discovered" first, since it can be used over both the dominant and its tritone substitution.
How did melodic minor harmony develop in jazz, and when did it start being thought of as such in jazz pedagogy?
Can anyone suggest a source that provides a detailed account of this history?
Comment: I've found several short histories of jazz harmony, but none emphasize the melodic minor.  Mostly they talk about how 7th, 9th etc chords were added, and then came to dominate.  I also see talk of `functional harmony`.
Comment: @hpaulj I edited to make a little more clear exactly what harmonies I'm interested in and that Levine's Theory Book is my main source of knowledge on melodic minor harmony. That said, I'm broadly interested in how musician have thought about "playing changes" historically (even outside of jazz) so I'm interested in any historical account of musical improvisation, short or long, even if it doesn't answer this specific question.
Answer: I've talked to my jazz teachers about this over the years, and it is one of the great ambiguities of life!
In the 70s I took a bunch of lessons from a very prominent vibraphonist/pianist who had transcribed hundreds of great jazz solos and whose instructions revolved around the idea of reading through & memorizing the solos and then applying parts of them to your own soloing. I'll never forget coming back to him and asking "but where are the notes Jackie McLean is choosing from come from?" To this, he replied "don't worry about that; just keep learning the solos and you'll figure it out.
30 years later, at Guitar Center, a friend of mine and I happen to be in the "quiet room" when he said "Jeff I'm gonna show you something" and he played "the Jimi Hendrix chord"... An E seven sharp nine chord... "Now watch this: I'm going to play an F melodic minor over top of it." At the time I frankly was irritated with being schooled at Guitar Center, and just mumbled something and left, but about two weeks later I was sitting in front of the piano and it hit me like a ton a bricks. "How is that possible?"
I spent about two more weeks exploring and coming to the realization that the melodic minor presented the player with all of the voicing opportunities expressed in jazz. In other words, I reversed engineered that one seven sharp nine aspect and applied it to all of the other shapes & clusters formed in that scale including learning all the alternative names to each chord... so that I could see the commonality and apply the source scales improvisationally in any key.
And I'm still working on that because it takes a lot of maintenance.
The melodic minor model was so much easier and immediately accessible than thinking of the altered notes as "non chordal tones." Was I upset? You bet I was. Right up until I visited Mark Harris up at CSUN in the jazz department  and re-counted my story to him. "Why didn't my teacher Mr. Jones just tell me about the melodic minor?" Mark: Well I'll tell you Jeff... that approach to jazz harmony came after he learned how to play, and a lot of the older guys didn't learn it that way."
My current teacher, Terry Trotter, has a very informal attitude about this harmony and refers to its use in soloing as "source scales," which is very descriptive and convenient. I describe this melodic minor approach to jazz harmony as "the Berklee method," but you'll not be surprised to know that I'm still intent on finding out when the transition happened and who gets the credit.
I'm pretty sure the primary organizer of this evolved strategy is known and I'll get to the bottom of it. Whoever you are... thanks so much buddy!!!!!
Answer: I will post a few links, but I really hope someone else posts better resources, because I too would like to know the history from the perspective of the jazz musicians rather than reading deeper into the theory.
Two articles cited in the Wikipedia article for "altered scale"

http://dmitri.mycpanel.princeton.edu/files/publications/debussy.pdf
http://dmitri.mycpanel.princeton.edu/files/publications/consecutivesemitone.pdf

I suspect the history is something along the lines of jazz musicians admired the music of the Impressionist (Ravel & Debussy) and consciously incorporated scale and harmony elements from their music into jazz.


How do I Trace SQL Server 2005 through restarts?

Question: At my company I need to create a Trace on our SQL Server (for a workload file), that should run for several days. However, The Server is turned off every night, so the trace dies. How do I make a Trace that will continue automaticaly on the next day?
Answer: Have you thought about using Server Side Traces (SST)- it's essentially rhe same thing, but without the Profiler GUI. You can start it and stop it through SQL Server jobs - and hence you can tell SQL Agent to start the SST when SQL Server starts.
They are easy to do when you get the hang of them, and you can script it all out of Profiler too!
See also:
http://sqlserverpedia.com/wiki/The_Server-side_Trace:_What,_Why,_and_How
http://www.mssqltips.com/tip.asp?tip=1035


Checkstyle: access variable names?

Question: We have a standard that variable names must be spelled different (not just case).  For example, this is illegal:
int INDEX = 0;
int index = 0;

I am trying write a Checkstyle extension to support this, but ast.getText() is returning "variable_def" instead of the actual variable name.  How do I do it?  Thanks.
package check;

import java.util.ArrayList;

import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

public class VariableSpelling extends Check {
    private ArrayList<String> variables = new ArrayList<String>();

    public int[] getDefaultTokens() {
        return new int[] { TokenTypes.VARIABLE_DEF };
    }

    /**
     * This method is called when a node is found
     */
    public void visitToken(DetailAST ast) {
        String var = ast.getText();
    }
}

Answer: Nevermind.  I found the problem.  You can't get the text of a VARIABLE_DEF.  You have to drill down to the IDENT...then get the text on that.
Comment: Can you please update the code with the solution? I am facing a similar problem, and as I'm new to this CheckStyle, it would be helpful to see where to make the changes...

Checkstyle: access variable names?


What is Quotas in Amazon web service context

Question: what is AWS Service Utilization Quota (Limits) ? Based on the definition provided in docs it says " AWS implements quotas to provide highly available and reliable service to all customers, and protect you from unintentional spend. Each quota starts with an AWS default value. " .
Basically my question here is what are resources in that definition ?  Are they computers , nodes , cluster or some sort of distributed computation nodes or it is something else ?
Secondly , if they are different nodes or computation resources, they should be distributed, right ?
I really appreciate if someone can simplify this def for me ?
For instance what happens in a Sage Maker service with quota of 20 , does it mean in the training batches can be distributed over 20 nodes for fwd and back prop training ?
Comment: General definition of resource is as [follows](https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html): "In AWS, a resource is an **entity that you can work with**. Examples include an Amazon EC2 instance, an AWS CloudFormation stack, or an Amazon S3 bucket. "
Answer: Every service has different quotas that relate to how that service works.
For example, Amazon EC2 has a maximum number of concurrently-running instances, number of security groups, number of rules in a security group, etc. The limits are listed in documentation, and also under Service Quotas in the AWS management console.
Amazon SageMaker limits can be found here: Amazon SageMaker endpoints and quotas


Adding an HTML div with input and label using javacript

Question: I have an HTML form, the user can add a name, and if there is an additional name required to be added to click on the button and a new div with input and label inside it.
Here is the HTML:

                  <input type="text" id="ownerName1" class="form-control" />
                  Name of Owner(s)/Major Shareholders:

                <button
                  onclick="newShareholder()"
                  type="button"
                  class="mb-2 btn btn-primary btn-sm ripple-surface"
                >
                  Add Shareholders
                </button>

I am trying to write a script to create the div and inside it the input and label.
I want to place the new div above the button.
here is what I have tried:

I am new to javascript so I search for a similar answer but I didn't grasp on how it works so if someone could provide explanation.
My current output is showing the additional input after the button and it is not inheriting the correct class.
here is a sample of the required output after clicking the add button:

                  <input type="text" id="ownerName1" class="form-control" />
                  Name of Owner(s)/Major Shareholders:

                  <input type="text" id="ownerName2" class="form-control" />
                  Name of Owner(s)/Major Shareholders:

                  <input type="text" id="ownerName3" class="form-control" />
                  Name of Owner(s)/Major Shareholders:

Answer: Try this:

var buttons = 2;
const button = document.querySelector('button');
function newShareholder() {
  var div = document.createElement("div");
  div.className = "form-outline mb-4";

  var input = document.createElement("input");
  input.id = "ownerName" + buttons;
  input.className = "form-control";
  document.body.appendChild(input);
  buttons++;
  var label = document.createElement("label");
  label.className = "form-label";
  label.innerHTML = "Name of Owner(s)/Major Shareholders:";
  div.appendChild(input);
  div.appendChild(label);
  button.parentElement.insertBefore(div, button);
}

  <input type="text" id="ownerName1" class="form-control" />
  Name of Owner(s)/Major Shareholders:

                <button
                  onclick="newShareholder()"
                  type="button"
                  class="mb-2 btn btn-primary btn-sm ripple-surface"
                >
                  Add Shareholders
                </button>
Comment: OP asked for the new divs to be placed above the button.


Replace floating point math with integer in sigmoid transfer function

Question: I would like to replace floating point math in these function without losing much precision, because I have no FPU. Is this possible? I think 3 numbers after comma is enough.
inline float smaller_f(float value, float bias) {
  return value < bias ? value : bias;
}

inline float pow2_f(float fVal) {
  return fVal * fVal;
}

float sigm_f(float fX, float fSlope) {
  float fVal = (180.f - smaller_f(fabs(fSlope * fX), 179.9f) ) / 180.f;
  return fVal / sqrt(1.f + pow2_f(fVal) );
}

Comment: Maybe, depending on huw much precision is enough. The only thing you need to write yourself is the sqrt function. Then just scale up everything, for example use integer 1 billion in place of float one everywhere. Do you have 64 bit integers? If not, maybe you need to emulate them, annother tricky part...
Answer: A fixed-point math library is what you need.  My preferred solution for this is Anthony Williams' fixed-Point math C++ library.  Because it is in C++ and defines a fixed class with extensive function and operator overloading, it can largely be used simply by replacing float or double in your existing code with fixed.  It uses int64_t as the underlying integer data type, with 34 integer bits and 28 fractional bits (34Q28), so is good for about 8 decimal places and a wider range than int32_t.
If your compiler supports C++, you can still essentially write your code using the essentially C subset if you prefer, using C++ only to support this library.
On 32bit ARM this library performs about 5 times faster than software-floating point and is comparable in performance to ARM's VFP unit for C code.
Note that the sqrt() function in this library has poor precision performance for very small values as it looses lower-order bits in intermediate calculations that can be preserved. It can be improved by replacing it with the code the version I presented in this question.
There are no doubt C libraries for fixed-point math but they will lack the simplicity and convenience of a "real" fixed-point data type provided by this library, and this library has a complete set of standard library math function equivalents, while many fixed point solutions just provide basic arithmetic operators.
Comment: @dgrat:  I cannot think of a single 8 bit micro ever that had an FPU, and even for 32 bit they are unusual.  Renesas SuperH have FPU support as do some ARM parts.  The FPU on ARM Cortex-F4 is only single precision.  64 bit integer operations will still be fairly slow on an 8 bit target,  32-bit fixed point may be preferable.
Comment: I use Arduino, so ATMega. I was never thinking before, that FPU could be not existing
Comment: @dgrat What CPU do you have in that Arduino? I never used them, anyways, wikipedia says there is an 8bit version, and a 32bit version. That makes a big difference here.
Comment: ATMega2560, should be 8 bit.
Comment: @BuellaGábor:  The 32bit Arduino is ARM Cortex-M3 based; Atmel AVR ATMega (as already mentioned by dgrat) is 8 bit.
Answer: Look at the slowest/hardest part:
fVal/sqrt(1 + fVal**2)
This is all you need to think about.
http://www.wolframalpha.com/input/?i=x%2Fsqrt%281+%2B+x%5E2%29
Its obvious that your fVal is less than or equal to 1.
You are after an approximation in the range x = 0 to x = 1 so something like this:
http://www.wolframalpha.com/input/?i=expand+x%2Fsqrt%281+%2B+x%5E2%29+around+x+%3D+0.5
That will likely be enough for your needs. Press the more terms button once to get more accuracy.
To make integers behave like floating points, you can use a simple multiplier scheme, like int = float*10000, but this creates problems when you need the fifth power - you will get overflow. Better to scale everything so all numbers are less than 1, then use fractional integer math library to multiply your numbers.
One simple fractional library I built used LONG_MAX to mean 1.0 (about 9 decimal places of accuracy), then to multiply two of these together (so that LONG_MAX*LONG_MAX = LONG_MAX) I used two lines of assembler. You may have access to a fractional math library in your system.
So basically, scale everything so that the max you have on the way in is 1.0.
When you are done, its fairly easy to test this function by going through a million or so values, and comparing them to the floating point version.
See http://gameprogrammer.com/4-fixed.html and similar pages for how to work with fixed point.
Comment: You basically nailed it.  But I'd suggest a Chebyshev approximation instead of a Taylor approximation.
Answer: One easy thing you can try, which is probably not good enough for you, but fairly simple:
 unsigned int scale = 1000; /* three number after the comma */

 inline int smaller_i(int value, int bias) {
       return value < bias ? value : bias;
 }

 inline int pow2_i(int iVal) {
     return (iVal * iVal) / scale;
 }

 int sigm_i(int iX, int Slope) {
     int iVal = (180*scale - smaller_i(abs(iX) * slope, (179*scale + 9*(scale/10))) / (180*scale);
     return iVal / sqrt_i(1*scale + pow2_i(iVal));
 }

If you have 64 bit integers, this can be enough for you. If you have only 32 bits, I'm not sure. If only 16 bits, these computations will likely overflow, so you need something a bit more complicated.
Also note that you need to write sqrt_i for yourself.
Comment: Greater performance can be obtained by using a binary fixed point; i.e. a scale factor that is a power of two.
Answer: The bottleneck is probably fVal / sqrt(1.f + pow2_f(fVal) ).
Try using the Fast Inverse Square Root procedure, which yields a very accurate approximation of 1.0 / sqrt(x) using integer arithmetic.
Answer: I had this issue for a neural network I wanted to implement on a Raspberry Pi 3 (weights between -127 and 127), and the fastest method I found was a binary search implemented as nested if statements; obviously the if statements needed to be autogenerated and Python came to the rescue.
code
Given a C function:
static
uint16_t sigmoid_lookup(int32_t i) {
#include "autogen_sigmoid_index.i"
}

and a sorted Python list of (sigmoid_value, at_argument), this function creates the if-else tree:
def produce_c_code(numbers_list, idxs, idxe, level):
    if idxs >= idxe:
        raise RuntimeError("idxs=%d idxe=%d")

    indent= " "*level

    if idxs + 1 == idxe: # end of recursion
        yield indent + "return %d;" % numbers_list[idxs][0]
    else:
        idxm= (idxe+idxs)//2
        yield indent + "if(i>=%d)" % numbers_list[idxm][1]
        yield from produce_c_code(numbers_list, idxm, idxe, level+1)
        yield indent + "else"
        yield from produce_c_code(numbers_list, idxs, idxm, level+1)

example
For this number list: [(0, 0), (1, 9), (2, 25), (3, 41), (4, 57), (5, 73), (6, 89)], the code produced is:
 if(i>=41)
  if(i>=73)
   if(i>=89)
    return 6;
   else
    return 5;
  else
   if(i>=57)
    return 4;
   else
    return 3;
 else
  if(i>=9)
   if(i>=25)
    return 2;
   else
    return 1;
  else
   return 0;

benchmarks
The benchmarks are based on the 127 * n / sqrt(n*n + 4194304) sigmoid function of my case, and they are over the input range [-8000000, 8000000].
Pentium M 1.2 GHz
testing lookup
CPU time: 300000
testing math
CPU time: 1460000
Raspberry Pi 2 800 MHz
testing lookup
CPU time: 474094
testing math
CPU time: 2897385
Raspberry Pi 3 1.2GHz
testing lookup
CPU time: 369665
testing math
CPU time: 1570066
Intel Core™2 Q6600 2.4 GHz
testing lookup
CPU time: 73623
testing math
CPU time: 797847


Varnish3 - how many clients causes 1 backend fetch? (antidogpile)

Question: When varnish cache is empty and I got X client requests for the same asset - Varnish gathers the clients and issues 1 backend fetch.
Do you know if there's possibility to control how many requests are held until fetch (or time window size)? - I would like to have backend fetch more frequently so the clients would wait shorter time.
When I test with return(pass) - I got nice flow, no long times for the client, but I got no caching - and because caching is set by backend - I would like to stay with "return(lookup)" which enables antidogpile effect - good but sometimes bad (because of holding reqs...)

EDIT: Kind of solution in my comments :)
Comment: I think that I will try to solve my issue producing hit_for pass for some period when I got miss.
Comment: I think I got what I wanted - "disabling antidogpile" when queuing has no sense at all - hit for pass worked. Still - if I could control this I would be glad.
Answer: As far as I know, the request to backend is fired immediately. If more requests for the same resource arrive before the first request is satisfied, those are served from the backend request in flight.
If you feel your cache misses are slow, then it is most probably because your backend is slow, or something else is misconfigured.
Comment: When I observe times (logged by nginx) on backend - they are very low for all the time - small part of second, but on the side of clients after 300-400 requests times for the client rise up to few seconds... This doesn't happen when I bypass cache lookup.