How can I theme the Bootstrap base theme search block?

Question: I've created a sub-theme of the Drupal 8 Bootstrap base theme. My problem is that I'm using a customized version of the Bootstrap CSS Framework that does not include Glyphicons. Instead of Glyphicons, my project is using fontAwesome icons.  What I've realized though, is that the Bootstrap theme uses a Glyphicon Search Icon for the Search Form. Since I'm not using glyphicons and the CSS files are not included, I get a search form button that looks like this.

It should appear like this.

If i inspect the HTML markup using my browser, my theory is correct.
<button type="submit" value="Search" class="button js-form-submit form-submit btn-primary btn icon-only" name="">Search</button>

if I change the following markup, the button shows up correctly because it can find the icon.
  to

What I want to do is to be able to change the icon or the code in the base theme that generates this snippet of code.

My assumption is that I should use a preprocess function to alter the form block and output/replace the Glyphicon span with the Fontawesome span.
I believe that the input--button.html.twig in the bootstrap base theme is responsible for outputting the icon classes because of this code.
{% block input %}
    {% if icon_only %}
      <button{{ attributes.addClass(classes, 'icon-only') }}>
        {{ label }}
        {{ icon }}
      </button>
    {% else %}
      {% if icon_position == 'after' %}
        <button{{ attributes.addClass(classes) }}>{{ label }}{{ icon }}</button>{{ children }}
      {% else %}
        <button{{ attributes.addClass(classes) }}>{{ icon }}{{ label }}</button>{{ children }}
      {% endif %}
    {% endif %}
    {{ children }}
  {% endblock %}

Apparently, it is used to alter the button of many elements instead of only the search form.
Answer: Bootstrap theme is deeply bundled with glyphicons .. it guesses the icon from the button text.
You would need to override Bootstrap::glyphiconFromString() or Bootstrap::glyphicons(). I cannot tell you how to do this in your subtheme ...
If you removed the glyphicons, probably Theme::hasGlyphicons() will return FALSE and won't show any icon.
Workaround
You could replace the icon variable in template_preprocess_input, like:
function MY_TEME_preprocess_input(&$variables) {
  if ($variables['icon']) {
    if (array_key_exists('glyphicon-search', $variables['icon']['#attributes']['class'])) {
     foreach($variables['icon']['#attributes']['class'] as &$sValue)
     {
       if ($sValue == 'glyphicon') {
         $sValue = 'fa';
       }
       if ($sValue == 'glyphicon-search') {
         $sValue = 'fa-search';
       }
     }
    }
  }
}

or, I guess you have asked this question on do: https://www.drupal.org/node/2757463. There is a suggestion of overwriting the Input element:
Create a file at bootstrapsubtheme/src/Plugin/Preprocess/Input.php and add the following:
/**
 * @file
 * Contains \Drupal\bootstrapsubtheme\Plugin\Preprocess\Input.
 */

namespace Drupal\bootstrapsubtheme\Plugin\Preprocess;

use Drupal\bootstrap\Annotation\BootstrapPreprocess;
use Drupal\bootstrap\Utility\Variables;

/**
 * Pre-processes variables for the "input" theme hook.
 *
 * @ingroup theme_preprocess
 *
 * @BootstrapPreprocess("input")
 */
class Input extends \Drupal\bootstrap\Plugin\Preprocess\Input {

  /**
   * {@inheritdoc}
   */
  public function preprocessElement(Variables $variables, $hook, array $info) {
    $element = $variables->element;

    if ($element->icon) {
      $element->icon->replaceClass('glyphicon', 'fa');
      $element->icon->replaceClass('glyphicon-search', 'fa-search');
    }

    // Let bootstrap base theme preprocess the element normally now.
    parent::preprocessElement($variables, $hook, $info);
  }

}

Answer: Adapted from @remy's Answer.  Using $variables['icon'] wasn't working so i tried drilling down a little deeper into the variable array and i was able to change the icon to a font-awesome icon.  The preprocess function was added to my themes, .theme file.
Let me know if there is a better/ more concise approach.  Currently, i only need to change 1 icon, but what if there are 20 icons? (This solution might get pretty busy quickly).

  function MYBOOTSTRAPTHEMENAME_preprocess_input(&$variables) {

  $glyphiconclass = $variables['icon']['#attributes']['class'][1];
  $glyphiconname = $variables['icon']['#attributes']['class'][2];

    if (($glyphiconclass == 'glyphicon') and ($glyphiconname == 'glyphicon-search')) {
       $variables['icon']['#attributes']['class'][1] = 'fa';
       $variables['icon']['#attributes']['class'][2] = 'fa-search';
    }

  }

Comment: Updated my answer - your solution does not respect classnames in different positions.
Comment: And for a cleaner solution, as I mentioned, you would need to override the Theme:: and Bootstrap:: classes.
Comment: sorry - i was just assuming that ;) never really run the code
Answer: It is important that you should BY DEFAULT always have the bootstrap theme enabled, but be working from a subtheme. Look in the templates/bootstrap folder and look for a file named bootstrap-search-form-wrapper.func.php. Copy that file to your default theme. and you can then modify it to use Fontawesome rather than the glyphicon.
Comment: this was drupal 7 ...


Validação da cadastro repetido

Question: Tenho uma classe chamada Matricula. Ela recebe o cadastro de Aluno e de Serie.
Preciso fazer uma validação, onde caso o aluno já esteja matriculado em uma série cadastrada, a página apresenta uma mensagem informando que ele já está matriculado e não deixe que o mesmo seja matriculado novamente.
Abaixo está o código da matrícula:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace bj_cursosonline.Models
{
    public class Matricula
    {
        [Key]
        public int ID { get; set; }

        [Required(ErrorMessage = "Campo obrigatório!")]
        [Display(Name = "Aluno")]
        public int ALUNOSID { get; set; }

        [Required(ErrorMessage = "Campo obrigatório!")]
        [Display(Name = "Série")]
        public int SERIESID { get; set; }

        public virtual Series SERIES { get; set; }

        public virtual Alunos ALUNO { get; set; }
    }
}

Classe de Aluno:
public enum SEXOALUNO
{
    MASCULINO, FEMININO
}

public class Alunos
{
    [Key]

    public int ID { get; set; }

    [Display(Name = "Nome")]
    [Required(ErrorMessage = "Campo obrigatório!")]
    public string NOME { get; set; }

    [Display(Name = "Sexo")]
    [Required(ErrorMessage = "Campo obrigatório!")]
    public SEXOALUNO? SEXO { get; set; }

    [Required(ErrorMessage = "Campo obrigatório!")]
    [Display(Name = "Data de Nascimento")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [DataType(DataType.Date, ErrorMessage = "Data em formato inválido!")]
    public DateTime DATANASCIMENTO { get; set; }

    public virtual ICollection<Matricula>
        Matricula
    { get; set; }
}

Classe de Série:
public enum TURMA
{
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
}

public enum TURNO
{
    MANHÃ, TARDE, NOITE
}

public class Series
{
    [Key]
    public int ID { get; set; }

    [Required(ErrorMessage = "Campo Obrigatório!")]
    [StringLength(50)]
    [Display(Name = "Descrição:")]
    public string DESCRICAO { get; set; }

    [Display(Name = "Turma:")]
    public TURMA? TURMA { get; set; }

    [Display(Name = "Turno: ")]
    public TURNO? TURNO { get; set; }

    [Required(ErrorMessage = "Campo Obrigatório!")]
    [Display(Name = "Número da Sala:")]
    public int NUMSALA { get; set; }

    public virtual ICollection<Avaliacoes>
        Avaliacoes
    { get; set; }

    public virtual ICollection<Matricula>
        Matricula
    { get; set; }
}

Comment: A melhor forma é pelo banco de dados. Via C# é muito mais código.
Comment: Teria como colocar a classe SERIE e ALUNO também? Além disso você está utilizando o que para realizar suas consultas no Banco de Dados?
Comment: você poderia adicionar uma unique index na sua tabela, mas verifique sua regra de negócio, por exemplo: imagine que um aluno seja matriculado no ano de 2015, não completou a série, e agora em 2017 vai se matricular de novo. Teria que excluir a matricula anterior ? Perderia o histórico anterior dele ?
Answer: Nesse caso o ideal é antes de você salvar, você fazer uma verificação se já possui um cadastro desse no seu Banco, caso tenha ele retorne uma mensagem de erro.
Uma boa maneira de fazer essa validação é usando IValidatableObject, com ele você pode implementar suas próprias validações na sua classe.
namespace bj_cursosonline.Models
{
    public class Matricula : IValidatableObject
    {
        [Key]
        public int ID { get; set; }

        [Required(ErrorMessage = "Campo obrigatório!")]
        [Display(Name = "Aluno")]
        public int ALUNOSID { get; set; }

        [Required(ErrorMessage = "Campo obrigatório!")]
        [Display(Name = "Série")]
        public int SERIESID { get; set; }

        public virtual Series SERIES { get; set; }

        public virtual Alunos ALUNO { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // aqui você faz uma consulta no Banco de dados e busca se já existe um cadastro desse aluno na serie
            var result = db.Matriculas.Count(m => m.ALUNOSID == ALUNOSID && m.SERIESID == SERIESID);
            if (result > 0)
            {
                yield return new ValidationResult("Já existe uma Matricula para esse aluno nessa Serie", new string[] { "SERIESID" });
            }

        }
    }
}

Segue mais exemplos de como utilizar o IValidatableObject https://pt.stackoverflow.com/search?q=ivalidatableobject

Validação da cadastro repetido


Unable to get dependency in an internal repository

Question: We are using Maven 3.0.3.  We have deployed a JAR file to an internal repository at
http://maven/maven_repo/repositories/release/org/openqa/selenium/server/selenium-server/0.9.2/selenium-server-0.9.2-standalone.jar
I have then included this dependency ...
    <dependency>
        <groupId>org.openqa.selenium.server</groupId>
        <artifactId>selenium-server</artifactId>
        <version>0.9.2</version>
        <scope>test</scope>
    </dependency>

Also, in my ~/.m2/settings.xml file, I have our internal repository ...
            <repository>
                <id>mycoInternalRelease</id>
                <layout>default</layout>
                <name>myco Internal Repository</name>
                <url>http://maven/maven_repo/repositories/release</url>
                <releases>
                    <enabled>true</enabled>
                    <checksumPolicy>fail</checksumPolicy>
                    <updatePolicy>always</updatePolicy>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                    <checksumPolicy>fail</checksumPolicy>
                    <updatePolicy>always</updatePolicy>
                </snapshots>
            </repository>

Despite all this, when I run my pom, I get the error
[ERROR] Failed to execute goal on project myco-productplus-web: Could not resolve dependencies for project myco-productplus:myco-productplus-web:war:1.0-SNAPSHOT:The following artifacts could not be resolved: org.openqa.selenium.server:selenium-server:jar:0.9.2, org.openqa.selenium.server:selenium-server-coreless:jar:0.9.2: Could not find artifact org.openqa.selenium.server:selenium-server:jar:0.9.2 in mycoInternalRelease (http://maven/maven_repo/repositories/release) -> [Help 1]
[ERROR]

How can I heal the pain?  Thanks, - Dave
Answer: Given your artifact is named "selenium-server-0.9.2-standalone.jar" you might need to add <classifier>standalone</classifier> to your dependency declaration in your pom.


Probability of a random variable being no more than A, given that it is at least B

Question: Example question

It is known that 30% of all laptops of a certain brand experience hard-drive failure within 3 years of purchase. Suppose that 20 laptops are selected at random. Let the random variable $X$ denote the number of laptops which have experienced hard-drive failure within 3 years of purchase.
If it is known that at least 3 laptops experience hard-drive failure, what is the probability that no more than 6 laptops will experience hard-drive failure?

I know $X\sim\operatorname{Bin}(20,0.3)$.
I know how to calculate probabilities like $P(X = x), P(X \gt x), P(X \ge x),$ and $P(X \le x).$
Relevant formulae:
$$P(X = x) = {n \choose p}p^x(1-p)^{n-x}$$
$$P(X \gt x) = 1 - P(X \leq x)$$
and if $X$ is discrete,
$$P(X \ge x) = 1 - P(X \leq (x-1))$$
Additionally, what if the question was:

If it is known that at least 3 laptops experience hard-drive failure, what is the probability that at least 6 laptops will experience hard-drive failure?

or

If it is known that no more than 6 laptops experience hard-drive failure, what is the probability that at least 3 laptops will experience hard-drive failure?
Answer: $$
\Pr(X\le 6 \mid X\ge 3) = \frac{\Pr(X\le6\ \&\ X\ge 3)}{\Pr(X\ge 3)} = \frac{\Pr(X=3\text{ or } X=4 \text{ or } X=5 \text{ or }X=6)}{1 - \Pr(X=0\text{ or }X=1\text{ or } X=2) }
$$
Comment: Awesome. I'm reviewing for an exam and forgot that conditional probability came before this section, so I didn't think about using the conditional probability formula. Is your answer the same as $\dfrac{P(X \le 6) - P(X \le 2)}{1-P(X \le 2)}$?
Comment: Yes. $\qquad\qquad$


Two different versions of jQuery causing failure in event listening

Question: I am using two versions of jQuery. The code of a meme generator I am using uses jQuery version 1.7.1. The version of jQuery I am using with bootstrap is 2.x The issue is that after I add some code to trigger download after button click it does not work. If I include just my version that is 2.x meme generator stops working. If i include just 1.7.1 the download button event stops listening. How should I solve this issue?
Comment: I would suggest patching the meme generator to work with newer versions of jQuery. Using two versions of jQuery at the same time is a bad idea.
Comment: What does patching exactly mean here? How do I know what in the code is jQuery specific there?
Comment: It would generally mean debugging the code to find which parts are producing errors or failing to work, and manually updating them.
Comment: Firstly try jQuery migrate: http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/
Answer: You can use no conflict mode, see this question for some details.
If possible I would try to use versions which use the same jQuery though, as using two versions in the same page adds a lot of bloat and potential bugs.


Linked images from the Media module in WYSIWYG having A tags stripped when rendered to template

Question: I am using the WYSIWYG module to load TinyMCE 4.x, I am then uploading an image via the Media button in the toolbar of TinyMCE finally I am using LinkIt to link the image to a location.
All of this is fine inside the WYSIWYG editor, but once it is published and viewed on the page the wrapping  tag is stripped.
So in the editor if I view the source I see:

    [[{"fid":"7","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"","field_file_image_title_text[und][0][value]":""},"type":"media","link_text":null,"attributes":{"height":376,"width":640,"class":"media-element file-default"}}]]

However once this is rendered to the template I see simply:

If I then edit this piece of content again and view the source of the WYSIWYG editor the  tag is definitely still wrapped around the Media module's little string of JSON.
In a bid to prevent this from happening I changed the Wysiwyg Profiles and Text Profiles so that they don't remove broken tags or attempt to clean up an HTML or introduce any of their own HTML. Unfortunately this has had no effect.
Is there some way that Media/Drupal/WYSIWYG/LinkIt can be setup so that it will allow images to be linked? I have been unable to find a relevant issue or patch floating about out there on the web either.
Comment: OK, that was fun. So why the down vote? How can this question be improved in your opinion?
Comment: I didn't downvote this, but this is most definitely an issue with misconfigured Input Filter ("Text Format" in D7). Have you checked the settings of the Input Filter you're using? Does it allow  tags? Have you tried setting to a different Input Filter? Like Full HTML or "Plain Text"?
Comment: @Beebee yes, as I mentioned in the question I have removed all HTML filters from the profiles in use by the WYSIWYG editor. Other content is fine in the same WYSIWYG as well - I can link piece of text for example. I am working with the Full HTML filter, but I have made it even fuller!
Comment: @Treffynnon you definitely saved me a lot of work.
Answer: I posted this as an issue on the media_wysiwyg module bug tracker over at https://www.drupal.org/node/2357993 and have been working my way through it since. Here is the best result I have managed to achieve so far copied from my responses to that issue.

This issue is mostly caused by the file_entity module. To work round this I have restricted the view modes available to media_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

I have then created an override template for the file entity called file--image--wysiwyg.tpl.php (see https://www.drupal.org/node/1793548) and I have the following code in it:
<?php

hide($content['links']);
print render($content);

This has now removed all the annoying links, headers and wrapping
s from the output EXCEPT for the media_wysiwyg wrapping  mentioned in comment #4.
As this is just one wrapping
 and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping
.


Difference between Strike, Brush, Crescendo and Arpeggio

Question: When playing guitar I stumble upon tabs that either have striking the chords, brushing them with the pick, doing a crescendo or playing them as an arpeggio. As far as I learned when you strike you hit all the notes of the chord simultaneously, when you brush a chord you just hit the notes all the way up or down, a crescendo strum is a kind of a brush downward but you stop on every note. And arpeggio is just picking them in order.
Am I right with what I think I know?
Comment: Crescendo means getting louder. Don't see how that's possible with one strum up or down.
Comment: Perhaps you mean glissando instead of crescendo?
Comment: @RockwellRice No. Definitely not. I meant strumming techniques. Crescendo strumming and Diminuendo strumming are two of those techniques!
Comment: Crescendo strumming is not what you have described. It refers to increasing the volume with each strum, not during one strum.
Answer: Unfortunately you haven't really got those right. Here are the correct meanings:

striking means to play through the strings, hitting them as simultaneously as possible. As it is not actually simultaneous, an upstroke sounds different to a downstroke as the order of hitting the strings is different.
brushing is an odd term that doesn't appear to have a single meaning. It can either mean a slower version of striking, or it can mean a lighter version (i.e. Holding the pick more softly
arpeggio is playing the notes of a chord, not necessarily in order, with an audible delay between them.
crescendo is the odd one out. This term doesn't have a connection with playing a chord, but instead is an increase in volume over time. E.g. If you were strumming, and you wanted to play 4 bars of strumming with and increase in volume from the 3rd bar to the 4th you could have a crescendo there.
Comment: It's very odd but I'll stick to what you've answered!


Localizar aplicativo pela busca da play store

Question: Publiquei pela primeira vez um app do Google Play Store, mais para teste mesmo,
o google que entra direto na página do aplicativo. O link funciona, mas queria encontrar ele pela busca e não consigo.
Alguém sabe me dizer se tem alguma coisa que tenho que fazer para o aplicativo aparecer nas buscas? Estou meio perdido no console do Google Play Developer ainda.
Answer:
A pesquisa do Google Play é uma ferramenta-chave para usuários
encontrarem apps importantes e populares para dispositivos Android.
Garantir que seu app e os detalhes dele sejam detalhados e otimizados
é um fator importante para ser descoberto por usuários no Google Play.

De acordo com o Google, desenvolvedora da plataforma Android, o texto dos detalhes do seu app são cruciais para a descoberta dele, começando pelo título:
Título

Deve ser único e acessível. Evite termos comuns e reforce a temática do seu app.
Tenha como foco seu título, pois títulos mais longos provavelmente ficarão truncados dependendo do dispositivo que seus usuários utilizarem.
Evite erros sutis de ortografia de termos gerais, já que os usuários podem corrigir erros de ortografia de termos de pesquisa.

Veja mais detalhes na documentação de suporte do próprio Google de como fazer com que seu app seja mais fácil de encontrar na pesquisa do Google Play. E além disso também, você pode dar uma lida também sobre como funciona a pesquisa.


Tenho como montar uma página de upload, que possa receber fotos, vídeo e pacotes zip contendo fotos e/ou vídeos?

Question: Estou como uma aplicação onde o usuário cadastrado possui uma página de uploads de imagens e vídeos e queria saber se tem como, além de receber fotos e vídeos por uploads, se eu posso receber pacotes zips com fotos e vídeos, onde, a aplicação consiga tirar esses pacotes do zip pra poder nomear e depois alocar esses arquivos no servidor. Estou utilizando ASP.NET MVC 5, razor e alguns recursos em javascripts.
Answer: Sim. Utilizando o mesmo input file. Somente mude a forma de tratamento do arquivo no lado do servidor dependendo da extensão do arquivo.
Salve o arquivo e manipule utilizando a referencia do System.IO.
Referencie um componente de extração do ZIP como DotNetZip 1.10.1 (Nuget Pack)
<code>  using (ZipFile zip = ZipFile.Read(PathDoArquivo))
  {
    foreach (ZipEntry e in zip)
    {
      e.Extract();
    }
  }
</code>


Using the click package: Making an option be a choice of `int`

Question: I'm trying to make a click.option be a choice between the numbers 0, 1 and 2. I tried this:
@click.Option('--verbosity', default=1, type=click.Choice([0, 1, 2]))
def f():
    # ...
    pass

But I get the exception TypeError: sequence item 0: expected str instance, int found. I guess click expects only strings in click.Choice. Any way to get it to accept ints? I know I can convert to int manually after it's received, but if there's an idiomatic way to receive an int choice, that'll be better.
Answer: You can use IntRange(min=0, max=2):

class click.IntRange(min=None, max=None, clamp=False)
A parameter
  that works similar to click.INT but restricts the value to fit into a
  range. The default behavior is to fail if the value falls outside the
  range, but it can also be silently clamped between the two edges.

From the docs.


Licensing and Editions of Microsoft BizTalk and SQL for Development, QA, Stage vs Production

Question: My question is similar to this one, but I am gearing mine more toward which edition to use.
In the past places I've worked, these decisions were made by other teams, and now I'm being asked to advise.

Edition: Do most sites consider it satisfactory to have a Developer edition running in DEV, QA, and STAGE environments, and then only run Enterprise Edition in Production?  I'm specifically referring to server products such as BizTalk (2010/2013) and SQL Server (2008/R2 and 2012).
In other words, if some software runs on Developer Edition, does Microsoft guarantee it will run on Enterprise.  I realize of course that 99.9% of the time it will, but is it a safe and best practice?
Licensing: The developer edition is significantly lower priced; I think Premium MSDN includes the rights to run the Enterprise edition non-Prod environments. If QA accesses a file on a QA server, which license do they need?
Clustering: Further, we run clustered environment in production.  I've rarely been anywhere that we have clustering in QA or even STAGE.
Comment: **(1)** Depends. Primarily opinion based and variable. **(2)** Sorry, we cannot help you with your software licensing question. It's Microsoft licensing, so there's a decent chance that even Microsoft will be unable to help you with your software licensing question. **(3)** Clustering. Yes, this is thing. What of it? I've been in environments where both Dev and QA had many clustered systems, and I've also been in environments that hadn't ever heard of clustering.  Or test environment. (That was a rough one). So, much like #1, "Depends. Primarily opinion based and variable."
Comment: Please see line one of my question:  My question is more about "which edition" to use.  Suppose I have all licenses I need, but still want to be cost effective and follow best-practices.  Maybe #2 in my question is duplicate, but not #1 and #3.
Comment: Meaning, maybe you ought to split your 3 questions into... 3 questions, but since all three questions are off-topic and likely to be closed, that might be a waste of effort on your part.
Answer:
Edition: Do most sites consider it satisfactory to have a Developer
  edition running in DEV, QA, and STAGE environments, and then only run
  Enterprise Edition in Production? I'm specifically referring to server
  products such as BizTalk (2010/2013) and SQL Server (2008/R2 and
  2012).
In other words, if some software runs on Developer Edition, does
  Microsoft guarantee it will run on Enterprise. I realize of course
  that 99.9% of the time it will, but is it a safe and best practice?

I don't think Microsoft will guarantee ANYTHING will work, ANYWHERE.  The can offer guidance and best practices, and in this case the Developer Edition does have a few differences from Enterprise.  The full details for the 2010 version are here: http://social.technet.microsoft.com/wiki/contents/articles/6987.biztalk-server-2010-pricing-and-licensing.aspx but you probably already know what they are.
Yes, most sites will run Developer edition in Dev, QA, Stage...just as MS says in the prior link.
<code>"Many customers who deploy BizTalk Server implement separate development, testing, and production environments for their BizTalk Server 2010 solution. For the development and testing environments, you can use the free download of the BizTalk Server Developer Edition."</code>

Licensing: The developer edition is significantly lower priced; I
  think Premium MSDN includes the rights to run the Enterprise edition
  non-Prod environments. If QA accesses a file on a QA server, which
  license do they need?

This isn't something that SHOULD be answered here.  It could be, but it isn't smart to give licensing answers on SF and is OT regardless.

Clustering: Further, we run clustered environment in production. I've rarely been anywhere that we have clustering in QA or even STAGE.

Are you asking if you should deploy a cluster in QA or STAGE?  It's not a requirement...the cluster is for HA not for the functionality of the app itself but for uptime reasons.
Comment: My coworker fears that if you don't test it on a cluster, it might not work on a cluster. The deploy to a cluster is somewhat different as well.  I'm not quite as concerned.


Notation for length of arbitrarily long sequences in a set

Question: Suppose I have the set of arbitrarily long sequences of dice rolls:
\begin{equation}
\Omega = \bigcup_{n = 1}^\infty [6]^n = \{ (1),(2),(3),(4),(5),(6),(1,1),(1,2),\ldots \}
\end{equation}
Given some sequence $\omega \in \Omega$, what's the notation to get the length of the sequence? Is it $|\omega|$?
Comment: I have seen that notation before; regardless, I would just take one sentence to define it before you use it to reinforce your meaning
Comment: I hope it is helpful to point out that $[6]^+$ is a common notation for the set of nonempty finite sequences with elements in the set $[6]$.  (See [Kleene plus](https://en.wikipedia.org/wiki/Kleene_star#Kleene_plus) for example.)
Comment: @MYUSERNAMEISALIE I thought that only worked for sets of strings.
Comment: Strings are exactly finite sequences.
Comment: Related: [How to denote the size of a list?](//math.stackexchange.com/q/1169890)
Answer: I have seen each of the following notations used to represent the length of a finite sequence $\sigma$:

$\vert\sigma\vert$
$length(\sigma)$
$lh(\sigma)$

Personally, I think all three are perfectly fine, although it's worth spending a sentence saying what your notation means.
Note that "$\vert\sigma\vert$" is actually perfectly correct for finite sequences: a sequence is a set of ordered pairs, so it's length is indeed its cardinality. That said, once we look at infinite sequences this breaks down - a sequence of ordertype $\mathbb{N}$ and a sequence of ordertype $\mathbb{N}+1$ have the same cardinality. Since I often deal with infinite sequences, I tend to prefer $length$ or $lh$.


How to notate a "softened" dotted rhythm?

Question: In a score I'm preparing, I have many pairs of notes whose durations should be played in the ratios 2:1 or 1:2, with each pair having a total duration of a half note.  The common way to notate this is using triplets, as shown in example #1 below.  However, it looks a bit clumsy to me, and my (amateur) choristers don't know how to sing it until I explain it to them.  Example #3 is easier to understand, but I've got a lot of these and I don't like how  cluttered it looks.  I'd like to notate it as shown in example #2, with something small to indicate that the dotted rhythm should be "softened" or "relaxed" so that it sounds more like example #1.  The rhythm doesn't have to sound exactly like a tied triplet, but I really don't want the abruptness of a true dotted rhythm.
Is this a done thing?  I've seen music with an indication at the beginning of the piece like Example #4 (which is actually a pair of examples), but that approach doesn't work for me in this case because I want most of these rhythms "relaxed", but not all.

Any suggestions will be most appreciated.
Comment: "Swing feel" and example 2 is common in pop styles and likely to be understood by your amateur performers.
Comment: Is this something you are notating for the exclusive use of ensemble(s) you'll be conducting?
Comment: Is the whole tune, or section swinged, or do does it keep mixing swinged and straight 8th notes.
Comment: @dissemin8or The first example is reversed from "swing feel" because the longer note comes after the shorter one.  (Unless you have swing eighths with the second one tied to a quarter.)
Answer: Sorry, but "I don't like the way it looks" isn't a reason to avoid an established convention and substitute something that means something else. Yes, there are pieces that are full of those bracketed triplets; see the first movement of Lalo's Symphonie Espagnole.
However, you say "The rhythm doesn't have to sound exactly like a tied triplet, but I really don't want the abruptness of a true dotted rhythm." That's another matter; if you want something that's "not quite A, but definitely not B," then we enter the realm of performative inexactness and things for which there is not established notational convention. The only real approach in these cases is to communicate verbally with the performers, probably in an introduction or footnote. A lot of ink is spilled, and rehearsal time spent, by early music performers defining "just how inegales these particular notes inegales are," or by jazzers in determining a certain groove or swing.
You have to ask yourself, if any performers ignore or overlook (or can't understand) your textual instructions, how would you rather have it misperformed. If you'd rather have true triplets than an eighth-plus-dotted-quarter combo, then notate it that way. If the true triplets are closer to your intent than the dotted notation, then use them.
Of the triplet examples, I would personally prefer #3 as clearer, but #1 is totally allowable.
Comment: What I see in the first movement of Lalo's Symphonie Espagnole are triplet crotchets (8ths), each triplet played in the time of 1 of the 2 beats of a 2/2 bar. The rhythm the OP wants is a triplet sung in the time of 2 of the 3 beats of a 3/4 bar. This is less usual and perhaps trickier to perform, because the triplet goes across 2 beats.
Comment: @RosieF Interesting; when I look at the 1875 Durand score on IMSLP, the 2-beat triplets don't have brackets, just a little "3" floating above a group of crotchets (e.g. second measure). Most modern engravings use the brackets, though. And I probably should have referenced the third movement instead, where they're even more prevalent.
Comment: Ah, I was concerned only with the rhythm and the note values, but not with the brackets.
Answer: I do agree that Example #1 does not look very good, because it makes it harder to sightread the beat structure.
Thus I'd rather do something like using a quarter triplet and ties. I've appended this way, also the same using a 9/8 timesig.
Also there is nothing that speaks against creating your own notation as long as you explain it and it is clear to read. I've also appended a suggestion that uses an arrow to specifiy an elongation at the cost of the left or right neighbor.
Comment: +1 for the 9/8 suggestion, which would seem to me to be the best option.
Comment: 9/8 would work well if there are more triplets than even quavers. You don't want to avoid triplet marks only to have to add even more duplets markings.
Comment: IMO your top example is the best answer to this question because it is exactly equivalent to the original Example #1, but restricts the triplet notation to subdivisions of the bar. The reason Example #1 is hard to read is that we are used to counting triplets as repeating subdivisions of the beat but Example #1 doesn't allow us to do that.
Comment: I also like the 9/8 option, though the "amateur choristers" might have just as much trouble reading it.  I might myself have notated it in 9/8 with a [non-standard] quarter + half + dotted quarter.
Comment: I also favour the 9/8 option, because it uses the same internal subdivision each performer will need to be doing in order to get the lengths of all the notes exactly correct, and thus play together.
Comment: @IanGoldby:  The OP did say that they wanted "most of these rhythms 'relaxed', but not all".
Answer: Example 2 will not give the timing of triplets, so that's out of the running. 1 and 3 work well, just as well as each other, perhaps the edge going to 3 for amateurs. It will depend also whether it's just crotchets or if there are quavers there too. A legend at the top, stating 'swing' with the usual very last bit of ex.4, but without the tie, should be sufficient. And once the singers have the feel for it, they'll probably ignore it, and sing it like you want, anyway.
Answer: If you want strict 1:2 or 2:1 triplets in the space of a half note in 3/4 time, notating them with "3:2" instead of "3" should make things clearer:
From Dorico's https://steinberg.help/dorico/v2/en/dorico/topics/notation_reference/notation_reference_tuplets_numbers_ratios_c.html:

From Musescore's https://musescore.org/en/node/303432, uses 4:3 instead but the premise is similar:

Made by me with Musescore:
Comment: I'm don't think this looks any less clumsy than Ex. #1.
Comment: @ElementsinSpace - At the very least, the ratio warns that the tuplet is unusual, so I find these tuplets with ratios more intuitive to read.
Comment: Yeah, this notation does have a use.  But I don't see how it solves OP's problem.
Comment: @ElementsinSpace - Note that the question asker says, regarding Example #1, "my (amateur) choristers don't know how to sing it until I explain it to them". The ratio notation should be more intuitive and require less explanation than Example #1 or perhaps even Example #3. It's tough for me to approve of Example #2 without it needing Example #4 or a longer explanation accompanying it.
Comment: Even after reading this answer, I'd have to look these up if I came across them in a score. I guess 3:2 just means triplet? But then why not just a bracket with a 3 over it? Since I've seen the bracket or slur with a 3 at least a hundred times, I don't even have to think to read it. 3:2 I've never seen and it would stop me dead.
Comment: @ToddWilcox - I use 3:2 for this quarter-note triplet instead of the usual 3 because it spans 2/3 of a measure, which is not the usual fraction of a measure that a triplet spans (whole measure, one beat, half a measure, etc.). Counting it out is therefore less intuitive, and readers will need all the help they can get, so the ratio should clarify how many notes they *really* need to jam into the space of how many other notes instead of naively assuming any of the more usual fractions of measures.


Mocking a repository

Question: I am trying to mock a repository in symfony 2, so that I can work on a test data. The problem is that the entity manager returns empty entity object, with all values as NULL, as if it's from the real database. What's wrong here? This is the code I've written so far:
$user = $this->getMock('\Acme\AdminBundle\Entity\Users');
        $user->expects($this->once())
             ->method('getId')
             ->will($this->returnValue(1));
        $user->expects($this->once())
             ->method('getEmail')
             ->will($this->returnValue('aaa'));

        $userRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $userRepository->expects($this->once())
            ->method('find')
            ->will($this->returnValue($user));

        $entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $entityManager->expects($this->once())
            ->method('getRepository')
            ->will($this->returnValue($userRepository));

        var_dump($entityManager->getRepository('Acme:Users')->find(1)); die();

Answer: When you Mock an object like that, using var_dump won't work.  Read this tutorial for a full explanation of mocking.  Another good explanation is the PHPUnit documentation itself.  Here's the relevant information to note:

By default, all methods of the original class are replaced with a dummy implementation that just returns null (without calling the original method). Please note that final, private and static methods cannot be stubbed or mocked. They are ignored by PHPUnit's test double functionality and retain their original behavior.

Think of your mocked entity as an entity that behaves like your User, except every variable and every function is null.  That is why you had to stub individual methods to return the values that you wanted - however, they only return those values when you call those functions directly.  So, everything is absolutely correct in your Mocking.  If you do:
var_dump($theUser->getId());
var_dump($theUser->getEmail());

You will get the following result:
int(1)
string(3) "aaa"

This is correct - it is exactly what you Mocked.  So if you wanted to add an assertion you could do this (after removing the var_dump calls):
$this->assertSame(1, $theUser->getId());
$this->assertSame("aaa", $theUser->getEmail());

Note that those 2 tests wouldn't be very useful on their own because you'd essentially just be testing that PHPUnit itself works.  The point of your Mocks would be in combination with some other methods that rely on a user being fetched from the database and having a particular id or email value.

Mocking a repository


"The breakpoint will not currently be hit. No symbols have been loaded for this document." visual studio 2005

Question: I have a class library(C++) project in visual studio 2005, and want to debug this project using an application installed on the same PC. I have checked it was under debug and win32 platform.
But when I use the application to call one function in the class library, the breakpoint in the function can't be hit. The error is "The breakpoint will not currently be hit. No symbols have been loaded for this document."
Any ideas ?
Answer: It is likely that the library you are currently running does not match the code you have. I guess you did not compile and deploy the latest version of the code.
Comment: Hi, I have build the latest code of the class library before I right click debug in the project  @lolando
Comment: hmm. on PC there is a earlier dll installed, the application is written in C#, it only uses dllimport to import the dll file and call the function. I am not sure if the application is using the earlier dll installed on the PC @lolando
Comment: well, then you can check the timestamp or checksum
Comment: I fix the problem, it turns out to use the old dll installed in my PC instead of the new dll file. There are some problem when installing the new dll, the new dll doesn't repleace the old dll. Thanks @lolando
Comment: @Heidi: you are welcome, thank you too for confirming & providing feedback.


How do ring and bus network connect to router?

Question: Sorry this is probably a very silly question, but for some reason i am confused.
How does a LAN with bus or ring topology connect to a router and other LANs?
For example in a star network they all connect to a switch which can then connect to a router, but where does a switch go and fit in a bus or ring topology?
In this image of a ring network there is no switch: http://www.brainbell.com/tutorials/Networking/images/01fig04.gif
would the switch in the ring network simply be placed alongside the other nodes?
Thank you very much
Answer: Although the image in the question is a standard example of a token ring network - with each system having connections to two adjacent machines - that's not the only way they were implemented.
IBM introduced multistation access units which essentially functioned as token ring hubs - you could plug systems into them and remove them without breaking the ring.  The Wikipedia article on Token Ring describes these.
I don't think this is what you're asking about, but if you wanted to hook a legacy token ring network to the Internet these days, you can get media converters and/or bridges.
For a bus network like thickwire or thinwire, if you wanted to connect a router, you'd just hook it up like any other device (to a transceiver on thickwire).  Like IBM's MAUs for token ring, you could get equipment that would simplify the cabling, e.g. DEC and AMP made special cables and connectors that would let you plug in to a thinwire chain w/out having to break the chain.
Comment: Might as well have a link to the Wikipedia Bus Network Article: http://en.wikipedia.org/wiki/Bus_network
Answer: In ring and bus there is no switch, the traffic is passed along by each node.  This is one of the reasons why you don't see them in use.  When lines along the way fail, it breaks the communication instead of just taking out that one machine.
In your picture, they aren't labeled so let's say the headless machine is 1 and the rest are 2-6 going clockwise.
For 1 to talk to 3 it would have to pass through 2 or if 2 was down, then 6, 5 and 4.
Worse off is bus topology, without the loop around, one downed machine would segment the network in two basically.
Take away the link between 1 and 6 on your picture and you'd have bus topology.
Now let's say 3 goes down, 1 and 2 can talk, 4, 5 and 6 can talk, but 1 and 2 cannot reach 4, 5 and 6.
As far as a router, it would be in line the same as any workstation or server and could fall to the same communication breakdowns as described above.
Sure you could say with star topology, you lose 1 switch and everybody is down, but it is a lot easier to have a replacement switch on hand.
Comment: Your comment about bus networks is wrong.  In a thick or thinwire network (the usual example of a bus network), each node essentially taps into the bus (and does so literally in the case of thick wire), and if one goes down it doesn't affect the rest of the network.
Comment: Sorry, -1 for not understanding Bus topology in the slightest.


MSSQL: High-Availability, Witness and Principal down case

Question: The Setup is as follows:

1x Principal
1x Secondary
1x Witness

If the Witness and Principal are gone (Hardware- or networkfailure), the secondary DB stays offline. I know this is by design. But if the Witness comes back up and the principal stays down, there is no switchover. Why?
Answer: DO you have high safety with automatic fail over enabled in your mirroring settings? With out the automatic fail over enabled the witness wont enable the databases on the secondary server.
Comment: Yes, it's set up to switch automatically and works - IF the witness stays up all the time.


Sempre redirecionar para HTTPS com Codeigniter

Question: Tenho uma aplicação com CodeIgniter e preciso forçar sempre a conexão redirecionar sempre para https.
Fiz da seguinte maneira:

Alterei dentro de config\config.php a linha
$config['enable_hooks'] para TRUE.
Dentro de config\hooks.php
adicionei as linhas.
$hook['post_controller_constructor'][] = array(
    'function' => 'redirect_ssl',
    'filename' => 'ssl.php',
    'filepath' => 'hooks'
);

Na pasta hooks criei o arquivo ssl.php com a seguinte função:
function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('client');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
        // redirecting to ssl.
        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    } else {
        // redirecting with no ssl.
        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}

Após efetuar o teste a pagina ate e redirecionada para https:// mais vem o erro no Chrome:

Esta página não está funcionando
  Redirecionamento em excesso por meusite.com
  Tente limpar os cookies.
  ERR_TOO_MANY_REDIRECTS`
Comment: Esse tipo de redirecionamento pode ser feito direto pelo servidor de dns ao invés de pelo código, no cloudflare em crypto > Always use HTTPS  você pode configurar para fazer esse redirecionamento automático, eu sei que não resolve o seu problema, mais serve como uma possível opção.
Comment: por padrão ele não redireciona, tem que alterar as configurações na aba Crypto
Comment: Não acredito. Deu certo. kkkk Não conhecia essa função. Em `base_url` agora so preciso forçar a troca de `http` para `https`.
Comment: Eu estou com o cloudflare. E ele não está fazendo automatico.
Answer: Opa.
É mais seguro você fazer o redirecionamento no .htaccess e também no CodeIgniter.
Htaccess
01 - Crie um arquivo com o nome ".htaccess"
02 - E coloque entro dele
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.nomedosite.com.br/$1 [R,L]
Mas é interessante fazer também no codeigniter
seguindo as instruções nesse link :
https://stackoverflow.com/questions/8503663/force-https-www-for-codeigniter-in-htaccess-with-mod-rewrite
Comment: Vou testar pelo arquivo então. A que ponto de vista seria mais seguro?
Comment: Vou melhorar o texto.


How do I notate this rhythm?

Question: I've written this riff and cannot for the life of me figure out how to notate the rhythm. I need to know the subdivisions to set up DAW and write drum track for it.
Here's the riff, played twice: https://soundcloud.com/oleksii-donoha/rhythm/s-F7G5EhEwVdW
I've notated the first part in 6/4, it looks something like this: https://i.stack.imgur.com/FduiN.png
But I'm completely lost at the second part. I'm sheet music illiterate :(
Answer: This is a plain simple 4/4 rhythm with "3-on-4" patterns (sorry, I don't know if that's the correct name in English):

Consider that you can also write it like this, which could probably better follow the "feeling" of the riff, but from the point of view of reading it would only make it unnecessarily confusing to a trained musician:

Your confusion might have its origin on the position of the patterns, for which one could also try to think it as a 12/16+1/4, but I sincerely doubt one would think it in that way, even if all instruments are going to follow that rhythm.
Comment: Same rhythmically as mine but a different take on the time. It does work in 4/4 I just felt that strong 12/8 like pulse setting it up, plus your beat 4 sounds like a downbeat to me so I went with that. +1.
Answer: This will get closed because transcription questions are off topic here but I had to give it a shot because it's so interesting. This is what I hear:

The overall feel starts like 12/8 but then breaks into groups of 2 and 3 in the two 10/8 bars. The subdivisions are above in parentheses. Tricky but very cool the way the subdivisions are reversed in bars 2 & 3.
Sorry about the green line in bar 1, it's the cursor, not some mysterious new notation :)

How do I notate this rhythm?


nio HTTP decompression in Java

Question: Is there any Java library that does nio decompression of GZIP (and possibly other formats) out there?
I'm trying to analyze compressed HTTP content and need it to be non-blocking.
I found GZipInputStream but it expects InputStream which is blocking.
Any ideas?
I also found Iterable gzip deflate/inflate in Java
talking about compression (deflate) but couldn't find a decompression equivalent.
Thanks
Answer: How about using Netty's ZLibWrapper?

nio HTTP decompression in Java


When a batter reaches second safely after a rundown, does the batter get credited with a single or a double?

Question: A batter hit a single toward right field, but instead of stopping at first, he rounded the base and - intentionally - caused a rundown (the player told me after the game he did this intentionally). He eventually reached second base safely. The defence committed no errors.
Should that be scored as a double?
Or should it be scored as a single with a stolen base?
Or should it be something else?
Thanks.
Answer: That's a double. If you get a base hit and reach second on the play without any errors being made on the player it is scored as a double, assuming it was not on a fielders choice (which is unlikely to allow you to reach second anyway, unless if there is an error).
Comment: It's probably up to the official scorer's judgement. If the defense wakes up in the middle of the rundown and sees a runner trying to score, they may stop the rundown and throw home. If the scorer believes that the runner would have otherwise been forced to return to first or tagged out, it would probably be scored as a single, with the runner advancing on the throw home.


Choosing good sample from the Universe

Question: Let ,  be two disjoint subsets of a universe  such that ||=||=. Suppose we select a random subset ⊆ by independently sampling each element of  with probability ; that means, for each element  of  independently we include  in  with probability . We say that the random subset  is good if the following two conditions hold: ∩=∅ and ∩ has at least one element. Show that for =1/, the probability that  is good is larger than some positive constant.
How would we do this? How to show it has a positive lower bound?
Answer: HINTS: Since you're looking for a lower bound, you might focus on the worst-case scenarios.
At a minimum, you need:

nothing drawn from set $T$
something -- or, rather, not nothing drawn from set $S$

You can find the probabilities of each of these things occurring, and you can multiply them together since they're independent. I claim that the resulting expressions are related to a famous calculus limit, which is how you can get the more difficult of the two bounds.
Can you take it from here?

Choosing good sample from the Universe


Recurrence relation telescoping

Question: Hi there I am trying to solve the following recurrence relation using telescoping. How would I go about doing it?
$$T(n) = \frac 2n \Big(T(0) + T(1) + \ldots+ T(n-1)\Big) + 5n$$
Assuming $n\ge 1$
Comment: Have you tried a few first terms? if yes include them as well
Answer: Rearrange $$T(n) = \frac 2n \Big(T(0) + T(1) + \ldots+ T(n-1)\Big) + 5n\tag{1}$$ to get
$$T(0)+T(1)+\ldots+T(n-1)=\frac12\Big(nT(n)-5n^2\Big)\;,$$ and hence $$T(0)+T(1)+\ldots+T(n-2)=\frac12\Big((n-1)T(n-1)-5(n-1)^2\Big)\;.$$
Then substitute this into $(1)$:
$$\begin{align*}
T(n)&=\frac2n\left(\frac12\left((n-1)T(n-1)-5(n-1)^2\right)+T(n-1)\right)+5n\\
&=\frac{n-1}nT(n-1)-\frac{5(n-1)^2}n+\frac2nT(n-1)+5n\\
&=\frac{n+1}nT(n-1)-\frac5n(n^2-2n+1)+5n\\
&=\frac{n+1}nT(n-1)+10-\frac5n\;.\tag{2}
\end{align*}$$
Now let $a=T(0)$, and calculate a few values of $T$:
$$\begin{array}{c|l}
n&T(n)\\ \hline
0&a\\
1&2a+5\\
2&3a+15\\
3&4a+\frac{85}3\\
4&5a+\frac{265}6\\
5&6a+62
\end{array}$$
This suggests that $T(n)=c_na+b_n$, where $c_n$ is probably $n+1$. Indeed, if $$T(n-1)=na+b_{n-1}\;,$$ then from $(2)$ we find that
$$\begin{align*}
T(n)&=(n+1)a+\left(1+\frac1n\right)b_{n-1}+10-\frac5n\\
&=(n+1)a+b_{n-1}+10+\frac1n(b_{n-1}-5)\;,
\end{align*}$$
confirming that $c_n=n+1$. Thus, the problem reduces to solving the recurrence $$b_n=b_{n-1}+10+\frac1n(b_{n-1}-5)$$ with initial condition $b_0=0$.
It appears to be convenient to let $u_n=b_n-5$, so that $u_0=-5$, and
$$u_n=u_{n-1}+10+\frac1nu_{n-1}=\frac{n+1}nu_{n-1}+10\;.$$ Then
$$\begin{align*}
u_n&=\frac{n+1}nu_{n-1}+10\\
&=\frac{n+1}n\left(\frac{n}{n-1}u_{n-2}+10\right)+10\\
&=\frac{n+1}{n-1}u_{n-2}+10\left(1+\frac{n+1}n\right)\\
&=\frac{n+1}{n-1}\left(\frac{n-1}{n-2}u_{n-3}+10\right)+10\left(1+\frac{n+1}n\right)\\
&=\frac{n+1}{n-2}u_{n-3}+10\left(1+\frac{n+1}n+\frac{n+1}{n-1}\right)\\
&\qquad\qquad\qquad\vdots\\
&=(n+1)u_0+10\left(\frac{n+1}{n+1}+\frac{n+1}n+\frac{n+1}{n-1}+\ldots+\frac{n+1}2\right)\\
&=-5(n+1)+10(n+1)(H_{n+1}-1)\\
&=-5-5n+10(n+1)(H_{n+1}-1)\;,
\end{align*}$$
where $H_n$ is the $n$-th harmonic number. (Properly speaking, this should now be proved by induction on $n$.)
Finally, then, $b_n=u_n+5=10(n+1)(H_{n+1}-1)-5n$, and
$$\begin{align*}
T(n)&=(n+1)\Big(T(0)+10(H_{n+1}-1)\Big)-5n\\
&=(n+1)\Big(T(0)+10H_{n+1}\Big)-10(n+1)-5n\\
&=(n+1)\Big(T(0)+10H_{n+1}\Big)-15n-10\;.
\end{align*}$$

Recurrence relation telescoping


Binomial distribution.

Question: Let $X$ and $Y$ be i.i.d binomial random variables with parameters $n$ and $\dfrac{1}{2}$ and let Z be another binomial random variable with parameter $2n$ and $\dfrac{1}{2}$. Then $P(X=Y)$ equals?
(a) $P(Z=0)$
(b) $P(Z=n)$
(c) $P(Z=2n-1)$
(d) $P(Z=n+1)$
I did this :
$P(X=Y)$ --> $P(X-Y=0)$ then i thought $X$ and $Y$ follows same distribution subtracting them would give zero that is $X-Y$ $\sim$ $B(0,\dfrac{1}{2})$
But that doesnt seem to help me. Any ideas?
Comment: $X-Y$ is not binomially distributed and can take negative values.
Comment: @ArchisWelankar No. Answer is option b
Answer: Observe that $n-Y$ also has binomial distribution with parameters $n$ and $0.5$, and that $X$ and $n-Y$ are independent.
Then $S:=X+(n-Y)$ will have binomial distribution with parameters $2n$ and $0.5$.
Now observe that: $$X=Y\iff S=n$$
So: $$P(X=Y)=P(S=n)=P(Z=n)$$
Comment: How did $n-Y$ follows binomial distribution ?
Comment: $P(n-Y=k)=P(Y=n-k)=\binom{n}{n-k}0.5^n=\binom{n}{k}0.5^n=P(Y=k)$. Also if $Y$ denotes the number of "successes" then $n-Y$ is the number of "failures" (hence binomially distributed with parameters $n$ and $1-p$.
Comment: Ohh is it like if n=30 . P(x=1)=p(x=29)?
Comment: In this case "yes" because the parameter is $p=0.5$ so that $p=1-p$. The number of successes follows the same distribution as the number of failures.
Answer: Using independance of $X$ and $Y$, it comes
\begin{align*}
 P(X=Y) & = \sum_{k=0}^n P((X=k)\cap(Y=k)) \\
        & =\sum_{k=0}^n P(X=k)P(Y=k) \\
        & =\frac{1}{2^{2n}}\sum_{k=0}^n \binom{n}{k}^2
\end{align*}
It is well-known (at least a classical result) that $\sum_{k=0}^n \binom{n}{k}^2=\binom{2n}{n}$, so
$$ P(X=Y)=\frac{1}{2^{2n}}\binom{2n}{n}=P(Z=n)$$
PS : your assertion that $X-Y\sim B(0,\frac{1}{2})$, makes no sense at all...
Comment: Like in iid random variables from normal distribution we subtract two random variables mean gets subtracted or can b added. I had that thing in my mind . Could you tell me where my confusions lies?
Comment: This well-known result can easily be proved by means of my answer.
Comment: @drhab okay. And about that classical result you mentioned can i have its proof somewhere?
Comment: @Daman In this answer it is shown that $P(X=Y)=2^{-2n}\sum_{k=0}^n\binom{n}{k}^2$. In my answer it is shown directly that $P(X=Y)=P(Z=n)=2^{-2n}\binom{2n}{n}$. This together proves that $\sum_{k=0}^n\binom{n}{k}^2=\binom{2n}{n}$.
Comment: @Daman : you can add two independent binomial r.v., but you can't subtract them ; as drhab said, $X-Y$ can have negative value and, at least, is not binomial! But also as he showed, you can add $X$ and $n-Y$ ...  it might remind you a little the addition in $\mathbb{Z}/n\mathbb{Z}$, if you are familiar with arithmetic.
Comment: @Daman : it is proven here : https://math.stackexchange.com/questions/373122/sum-of-square-binomial-coefficients

Binomial distribution.


Simple jQuery script required to create show/hide continuous loop

Question:
I have to the best of my knowledge researched the questions on this forum, but not quite got the answer.
I am a newbie in terms of jQuery.
I  have got this div

Item1

Item2

Item3>

And I want to fade in each div in turn, then hide and fade in the next div.
I want this to do a continuous loop through the divs until the visitor leaves the page.
I need step by step help to achieve this.
I am new on stackoverflow, but I learn fast so bear with me :)

Any help is much appreciated.
//Ot_Gu
Comment: do you mean you need 'Carousel'?
Comment: see here http://stackoverflow.com/questions/4822524/continuous-movement-animation-with-jquery
Comment: Please try to write the code yourself first and post the attempt here when you're stuck
Comment: http://stackoverflow.com/questions/2372301/how-to-write-a-loop-in-jquery-which-waits-for-each-function-to-complete-before-c
Comment: 55 "best" carousel plugins: http://www.tripwiremagazine.com/2012/12/jquery-carousel.html - there is bound to be one in there that does exactly what you are looking for.
Answer: Create a function and use it as fadeOut's callback, the function will be called when an element is faded out.
var $elem = $('#main .trip'), l = $elem.length, i = 0;

function comeOn() {
    $elem.eq(i % l).fadeIn(700, function() {
        $elem.eq(i % l).fadeOut(700, comeOn);
        i++;
    });
}

http://jsfiddle.net/MtmxN/
Comment: ...Is there a way to set a length of time before it starts fading out?
Comment: ...and could this length of time be a variable - so that for example, if the div contained a video it could play to end and then fade out.
Comment: @Ot_Gu Yes, you can use `delay` method  `var d = 1000; $elem.eq(i % l).delay(d).fadeOut(700, comeOn);` If it's a video you can call the function on it's `end` event.
Answer: This is my fiddle
function name_of_the_function() {
    $('.trip').each(function (index) { //for each element with class 'trip'
        $(this).delay(index * 1000).animate({ //delay 1000 ms which is the duration of the animation
            opacity: 1 //animate the opacity from 0 to 1
        }, {
            duration: 1000, //duration
            complete: function () { //when the animation is finished
                $(this).css({
                    opacity: 0 //turn the opacity from 1 to 0 without animation
                });
                if (index == 2) { //if the index == 2 which means we are in the last element in this case as we have 3 elements (0,1,2)
                    name_of_the_function(); //go back to the function
                }
            }
        });

    });
}

name_of_the_function(); //call the function at first

and the css I used:
.trip {
    opacity:0;
    background:red;
    height:100px;
    width:100px;
}

Answer: Here is how to do it using recursion with a list of element IDs for a more flexible solution.
var ids = ["#1","#2","#3"],
    time = 1000;

function cycleShowHide (i,ids,time) {
    if (i>=ids.length) {
        i = 0;
    }
    //hide previous
    if (i==0) {
        $(ids[ids.length-1]).hide(time);
    } else {
        $(ids[i-1]).hide(time);
    }
    //show next and repeat
    $(ids[i]).show(time, function(){
        i++;
        cycleShowHide(i);
    }
}

cycleShowHide(0,ids,time);

Answer: you can use jquery toggle

Item1

Item2

Item3>

<button id='mb'>Chick here</button>

write in script tag..
 $("#mb").click(function(){
     $('#main').toggle();
 });


Scheme for Weighted Voting on Ensemble Machine Learning System

Question: I'm designing a machine learning system in which i'm training 4 different classifiers and voting among it's predictions to decide on an output. Presently i'm just making a simple vote (i.e. selecting the most recurring predicted class) but can't I do something better using the outputted probabilities of the models as a sort of weight to decide on the best class?
Answer:
can't I do something better using the outputted probabilities of the models as a sort of weight to decide on the best class?

Yes, see ensemble learning for ideas. E.g. stacking sometimes outperforms the majority vote scheme.


DKIM validating, but mxtoolbox reports as "DKIM-Signature Not Verified"?

Question: I'm trying to figure out why a lot of emails from one of my sites are not getting through (in particular sky.com and gmail.com).
With my server, we have a tool that generates the DNS records for us:
RECORD            TTL         TYPE      VALUE
------            ---         ----      -----
_domainkey        3600   IN   TXT      "t=y; o=~;"
mail._domainkey   3600   IN   TXT      "k=rsa; p=xxxx"

(xxx is the full key)
This is what I have in my DNS record TXT records:

mail-tester.com comes back with this (which all looks good);

...yet mxtoolbox comes back with:

The frustrating part is that if I check the original email on my own gmail.com account, it comes back as DKIM valid:

What is the DKIM-Signature Not Verified error telling me? I'm at my witts end trying to get deliverability up (I've tried testing via GlockApps and it still comes back with lots of rejections for whatever reason). I must be missing something
UPDATE 2: Unfortunately MXToolbox is still ranking this as a problem. Every other tool says its fine though, so I'm wondering if its a false positive. Using GlockApps I can now see its only the Gmail stuff that gets bounced out of their tests:

I've read up about it - and it sounds like we may have shot ourselves in the foot when informing people about the crappy GDPR stuff that came out a while back. We emailed everyone (before it came in), to make them aware we would not be able to contact them if they don't give us permission. Maybe gmails filters picked that up as spam (as quite a lot of our users are on gmail), and punished us for it. Oh the irony! So now it sounds like the only way around it, is to ask people to check their SPAM box (and mark as "not spam")
Comment: I can confirm I had the same experience with mxtoolbox.com falsely reporting that my dkim doesn't pass verification.  Passes for body only.  I assume their mail server is incorrectly messing with headers before it gets to their dkim validator.
Comment: @LasseMichaelMølgaard it was actually a bug in mxtoolbox's testing tool. The DKIM was indeed valid, and working fine. It was just their silly system telling me it wasn't, and sending me on a wild goose chase!
Comment: Regarding your `DKIM-Signature Not Verified` is it still an issue? Because as far as I know it is only related to you have published the wrong DKIM key to your DNS server, which means email cannot be verified due to using the wrong key.
Answer: Well for starters: Your TXT record is wrong.
If you are sending mail from the domain example.com with a key named mykey (aka the selector), then the syntax is:
mykey._domainkey.example.com     IN TXT    "v=DKIM1; p=xxx"

You might also want to add t=s.
When you are confident that key signing and verification works, then I would recommend you add a DMARC and ADSP resource record, because it informs receiving mail server about what it should do, in case it receives a mail that is unsigned or using wrong key.
Syntax is simple enough (based on my own mail server settings):
_adsp._domainkey.example.com  IN TXT  "dkim=all"
_dmarc.example.com            IN TXT  "v=DMAR1; p=quarantine;  sp=reject; pct=100; adkim=s; aspf=s; rua=mailto:firstname.lastname@example.com; ruf=mailto:email@example.com; rf=afrf; ri=86400; fo=1

UPDATE
If you send a test mail to for instance a Gmail account, then there is an easy way to see if DKIM and DMARC is up and running.
I have enabled DKIM for my own domain molgaard.eu, so among others an email from me to Gmail will contains these headers:
Authentication-Results: mx.google.com;
       dkim=pass email@example.com header.s=mar2018 header.b=db8+ExPV;
       spf=pass (google.com: domain of ... as permitted sender) smtp.mailfrom=...;
       dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=molgaard.eu

<SNIP>

DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=molgaard.eu;
h=content-language:x-mailer:content-type:content-type:mime-version
:message-id:date:date:subject:subject:from:from; s=mar2018; t=1583565649;
x=1585380050; bh=...; b=...

The selector for my mails is called mar2018, since that is the month and year I made the key. :-)
And as you can see from Authentication-Results, both DKIM and DMARC passes (and SPF too), which means mails from my mailserver should land in peoples inbox - instead of a spam folder. :-)
And actually my policy a bit more strict, since I have declared in my DMARC record, that any mail not signed or signed with wrong key should be tossed out instead of landing in any folder at receiver. :-)
Comment: Try again in 12-24 hours or so. DNS have a habit of not being update DNS records worldwide for a while - giving you false results when you test.

An alternate way is to send a test mail to a Gmail account and read the headers. Updating my answer with an example of waht to look out for.
Comment: thanks for that. I'm a bit confused though. The domain is educationusingpowerpoint.co.uk. I thought it was just **mail._domainkey**. I tried adding it with the domain as well - ie `mail._domainkey.educationusingpowerpoint.co.uk`, but Linode always converts it to remove the domain part. Where does the "key" come from? (I'm just using the built in DKI*M stuff with VestapCP). **UPDATE:** Ah I see what you mean now - I was missing the `v=DKIM1;` bit from the value. I've updated that, and will wait to see how it works after the DNS has updated :)
Comment: BTW in our exim4.conf.template file we have: `dkim_selector = mail`
Comment: thanks, but still doesn't validate :( https://mxtoolbox.com/deliverability/b1288dbb-5869-4354-a2e7-5dac893233c2  (hopefully you can see that)
Answer: do not trust MXtoolbox for this particulat DKIM check. I personally saw several times such false positives in MX toolbox

revert DMARC policy to "none" for some time
use Glock Apps to improve message content to get off Gmail spam filters
use one of DMARC reports processing systems (EasyDMARC, DMARC Analyzer, Dmarcian) to identify all legitimate souses and make them DMARC compliant and only after that consider transitioning of domain policy to "rejects"
Comment: thanks - I've actually signed up for a PAYG on GlockApps, so I'm hoping I can improve. I'm wondering if I need to go down the route of asking our Gmail users to mark as "not spam" when we send to them. Our email content is not spammy at all. We also send a plain text and html version. I guess we will just have to see how it goes :)
Comment: definitely, it worth to ask you Gmail users to mark you emails as "not spam", to improve situation. Not familiar with GlockApps' DMARC data visualization, so cannot express my opinion re how much that will help you. Ony familiar with the systems I mentioned earlier


Erro "arquivo fonte não compilado"

Question: Estou usando o Dev-C++. Compilo e quando vou executar aparece a mensagem:

arquivo fonte não compilado

O que estou fazendo de errado?
#include <stdio.h>
main()
{
    float lado, area ;
    cout<< "digite o lado";
    cin>> lado;
    area= lado*lado;
    cout<< area;

  system("PAUSE");
  return 0;
}

Comment: Quando tiver outros problemas e for fazer outras perguntas, coloque mais detalhes. Este é um caso muito simples e deu para perceber logo o que tinha de errado, mas na maioria dos casos se não colocar tudo o que está usando, descrever o que está tentando fazer, dar detalhes, mostrar o erro que ocorre, onde, quando, etc. a pergunta será fechada por não estar clara, até você melhorá-la.
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Você está misturando C com C++. A primeira coisa a fazer é decidir se vai programar em uma linguagem ou na outra. Como parece ser C++, vou tentar acertar para ela:
#include <iostream>
using namespace std;

int main() {
    float lado;
    cout << "digite o lado";
    cin >> lado;
    float area = lado * lado;
    cout << area;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
As mudanças que eu fiz:

Coloquei o cabeçalho certo, o iostream que contém o cin e cout. O que está usando é cabeçalhop de C.
Coloquei um using para não ter que chamar o método pelo nome completo, assim não precisa usar std::cin, por exemplo.
E acertei o tipo da função main() que retorna um int, então tem que tipar ela.

Depois se quiser pode melhorar para a saída ficar mais apresentável.
Dei uma organizada no código também. Acostume-se fazer isto. É importante.
Consertando essas coisas deve compilar. O meu compilou. Não sei no DEV C++ porque é um IDE bem ruim.
Comment: +1 pela explicação correcta. Talvez fosse interessante complementar a resposta com as razões pelas quais considera que o DEV C++ não é um bom IDE.
Comment: @AlexandreCartaxo Acho que não caberia aqui. Precisaria de uma pergunta específica. Mas teria que ser muito bem feita pra não ser ampla ou baseada em opiniões.

Erro "arquivo fonte não compilado"


Make a views of data entered in composed fields

Question: How to output the data entered in Composed Fields to Views?
I have used Composed fields of 3 subfields, it was OK while entering the data. But When I want to display the entered data in Views, I get only blank fields.
After digging dip into it, I tried rewrite the Result, Only in Write result I get Token like [field_field_name-composed], which outputs the serialized PHP code:
a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}
where First Subfield, Second Subfield, Third Subfield are the data I entered into 3 subfields of Composed field, and is also defined by s: before it. If it is String type and 14 Characters long, then its written as s:14:
I also see the Token like [field_field_name] but it outputs blank (NULL).
So, I planned to use Views PHP to get the data from Composed Field and use some PHP code, but in Views PHP field, I am unable to use the Token [field_field_name-composed].
I want to make a Views with 3 fields to display each Subfield in its own field, is it possible?
EDIT:
I came to know this is using PHP Serialize function, but when I tried PHP Unserialize in Views PHP, I get blank string.
EDIT2:
The result of Unserialized value of above serialized field is:
print_r(unserialize('a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}'));
Array
(
    [1] => First Subfield
    [2] => Second Subfield
    [3] => Third Subfield
)

Comment: In your last sentence, do you mean, 'I want to make a View with 3 columns to display each subfield in it's own column' or did you mean 'I want to make a View with 3 rows to display each subfield in it's own row'?
Comment: I might not be much familiar with terminology, but for eg: In views If I want to select `Title` then in fields to add, I select title and so on. I can add three fields in views, if that lets me display all the three values (subfields1..3) separately.
Comment: Please read and re-read what I wrote. You say you want a View with 3 rows but the number of rows in a view is determined by the number of results. I think you mean you want 3 rows for each result but then you go on to say you want 3 columns as well, which makes more sense. Which do you want? 1 row for each result with 3 columns or 3 rows for each result?
Comment: In the above serialize code there are 3 strings as I mentioned in question. I want to output those 3 different string in 3 different forms. I don't want to display 3 strings together in same field, but make 3 different fields and display each string in each of these.
Comment: @leexonline: I have adjusted the question if that was confusing you. If you still have confusions then please let me know, I'll try to explain as much as possible.
Answer: Write a function in your module/theme that will accept two arguments,
1) the serialized value a:3:i:1;s:3:"First Subfield";i:2;s:4:"Second Subfield";i:3;s:7:"Third Subfield";
2) the name of the key you want to use.
Have it return the value.
Create three new columns that use PHP code in your view,  and pass the appropriate arguments to your module/theme.
Comment: Being a newbie, I am not sure how to return the value to Views, so, I was trying to use Views PHP module, to apply the code directly to views field.
Comment: that would work too, you'd just be duplicating the code in each PHP column and echo'ing the result, rather than returning it.
Answer: There are several problems with Composed Field module. Some issues with text format handling prevented the values from ever showing up at views! See https://drupal.org/node/1929462 for a fix for that.
Now, once displaying the field in views is fixed, choosing the field components to display is not hard. First of all, you will have to override the field handler for composed fields. It's not harder than this:
 /**
    * Implements hook_field_views_data_views_data_alter().
    */
    function composed_field_field_views_data_views_data_alter(&$data, $field) {
      $field_name = $field['field_name'];
      $data['field_data_' . $field_name][$field_name]['field']['handler'] = 'composed_field_handler_field_composed_field';
    }

Then, in the overriden handler, inherit all you can from views_handler_field_field, which implements everything you need to display a field in views. But let's override three methods:
/**
 * Defines options for composed fields.
 */
function option_definition() {
  $options = parent::option_definition();
  $options['composed_field']['components'] = array('default' => array());
  return $options;
}

This just tells Views we will be setting up some options in the form. It is needed to actually save the values. Mind the parent call, it is needed.
/**
 * Defines checkboxes for composed field components in a fieldset.
 */
function options_form(&$form, &$form_state) {
  parent::options_form($form, $form_state);

  $field_name = $this->field_info['field_name'];

Composed Field lets you set the components for every field instance, meaning the same field might be used in wildly different ways. And since views uses the same handler for any field_instance of the same field, we can't rely on component titles (the composed_field doesn't enforce the titles anyway) nor how many components a field has. We have to figure it out in a more abstract way: just pick the biggest number of components for that field.
  $cardinalities = array();

  foreach ($this->field_info['bundles'] as $entity_type => $bundles) {
    foreach ($bundles as $bundle) {
      $instance = field_info_instance($entity_type, $field_name, $bundle);
      $cardinalities[] = $instance['widget']['settings']['number_of_subfields'];
    }
  }

  // Let's just get the maximum number of subfields.
  $cardinality = max($cardinalities);

Then, just create a form. No surprises here, except tha #tree is TRUE by default (and that's why we have to put option in a keyed array in the previous method).
  $form['composed_field'] = array(
    '#type' => 'fieldset',
    '#title' => t('Composed Field Components'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    'components' => array(
      '#title' => t('Select the field components to display'),
      '#description' => t('If no component is selected, all will be displayed.'),
      '#type' => 'checkboxes',
      '#options' => $this->composed_field_component_options($cardinality),
      '#default_value' => $this->options['composed_field']['components'],
    ),
  );
}

That will be enough to have a UI in views to choose the components (composed_field_component_options() is an implementation detail, but it has to be keyed by the component numeric id, which is not 0-indexed).
Now, to display only the selected components:
/**
 * Filter out disabled components.
 */
function set_items($values, $row_id) {
  $items = parent::set_items($values, $row_id);

  $components = array_filter($this->options['composed_field']['components']);
  // If no component was chosen, show all. This makes for a good default.
  if (!empty($components)) {
    foreach ($items as $delta => $item) {
      foreach ($item['rendered']['#item'] as $component => $value) {
        if (!in_array($component, $components)) {
          unset($items[$delta]['rendered']['#item'][$component]);
        }
      }
    }
  }

  return $items;
}

That last part is easy: retrieve data from the handler options and unset the components that were not selected to be displayed. Of course, display every component if no component was selected (a reasonable default).


CSS Overlow doesn't appear to be honored

Question: I have read a number of questions on here pertaining to the overflow property. It seems straightforward enough, but some basic expectations are not getting met.
Consider the code below. I've got a tall div specified as this:

big

It appears inside another div that should be clipping it:

But the tall div is not clipping. Why?
My understanding would be that, since the parent is 100 pixels tall with no overflow allowed, then the child, which is 100 pixels tall, would not appear onscreen as 1000 pixels tall.
But that is not what is happening. The entire 1000 pixels are visible, causing the page to scroll.
Here are my guesses about why this is happening:

The parent with the overflow property is a display:table-cell and overflow only works on display:block?
Or, the parent is flexibly height because it is part of a table that fits to the page, and overflow only works on fixed sizes? (Even though for experimentation I tried to force a height on the table cell anyway to see if I could force the overflow to work)

.fixed-width100 {width:100px;}
.fixed-height75 {height: 75px;}
.fixed-height1000 {height: 1000px;}
.height50percent {height: 50%;}
.height100percent {height:100%;}
.width100percent {width: 100%;}

.table {display: table;}
.row {display: table-row;}
.cell {display: table-cell;}

.overflow-hidden {overflow:hidden;}
.overflow-auto {overflow:auto;}
.overflow-scroll {overflow: scroll;}

.yellow {background-color: yellow;}
.orange {background-color: orange;}
.red {background-color: red;}
.green {background-color: green;}
.blue {background-color: blue;}

 top header

fixed

clipped?

big

          height 50%

          height 50%

flex.

fixed

bottom footer

Comment: [Fiddle](http://jsfiddle.net/jbutler483/11n900jm/) I slightly confused as to what you want to happen here?
Comment: @jbutler483 I want the tall div 1000 pixels in height to clip (excess be hidden) inside it's smaller parent.
Answer: I would say your problem is the display:table-cell.
from w3schools:
"Let the element behave like a td element."
A td element adjust to the content and you can't really set a height on it and especially not hide the overflow :)
As far as i know
Answer: Try putting your large content inside a div with display:block; set, as that honors overflow, while a table cell may not:
css: .block100percent {display:block; height:100%;}

big

Comment: and actually the `display:block;` is optional as it is the default anyway


When not to look at p-value

Question: I am trying to indentify correlations between the columns of a dataset I have. I am using the pearson correlation index, and am looking at the p-value I get from the "correlation test" of R. I know that, in theory, the p-value is the probability of the correlation being due to chance. Now, what I wanted to know, can I always look at this value to have a good metric of how certain the relation between the variables is, or are there any assumptions that have to be statisfied?
EDIT
I'll add some context in order to better explain the question
I am actually studying the relationship between some variables I extracted from a tv series (eg number of character, number of cuts, IMDB rating etc.) and wanted to see if there is any kind of relation between them. In order to do this, I thought correlation might be a nice idea. Some variables have got interesting correlations, with very little p-values, and reading online it seemed like a good idea looking at this value.
After the comments I am not sure I really understood what this value means, but reading online I found this:
"The p-value is the probability that the null hypothesis is true. In our case, it represents the probability that the correlation between x and y in the sample data occurred by chance" (source).
Comment: " I know that, in theory, the p-value is the probability of the correlation being due to chance." This is not true. The p-value is the probability under the assumption that there is no correlation that a correlation as large or larger (in absolute value) than the one actually observed will occur in data.
Comment: The explanation of p-values in that source is incorrect. Unfortunate, but not that surprising. [This thread](https://stats.stackexchange.com/questions/31/what-is-the-meaning-of-p-values-and-t-values-in-statistical-tests) and [wikipedia's article](https://en.wikipedia.org/wiki/P-value) both contain more accurate descriptions, which Christian has already summarized. In this case the p-value is the probability that, if there truly were no correlation, we happen to see a correlation at least this large just by random chance. I'm afraid I don't understand @DLTS 's comment
Comment: What kind of "relation" between variables are you interested in? There are certain nonlinear relations that are not connected to correlation at all.
Comment: Use the p-value to see whether your observed correlations are *compatible* with the idea that there is no relation at all (in case of insignificance). This, however, doesn't mean that indeed there is no relation.
Comment: I think what Jonathan meant by the p-value being the probability of a correlation due to chance is that the null of the test is that there is correlation. So if we reject the null, i.e. the p-value is small, and there still appears to be some sort of correlation, we can infer that this observed correlation is due to chance and not actually in the data, otherwise we shouldn't be able to reject the null. So, while this way of looking at the p-value is not generally a good way, it might be true here specifically.
Comment: Thank you both for your comments. I updated the question with some context which might be useful
Comment: It is a pity that the term "statistically significant" has been connected with small p-values, because it misleads too many into thinking this has something to do with significance in its colloquial meaning. The essential point is how large your effect is (in this case the correlation coefficient). The p-value is only a safeguard whether your sample fluctuates too strongly, and as long as it is small (say below 0.05), you can simply ignore it. Or just follow @dipetkov's advice in his answer: forget about statistcial significance and p-values.
Answer: Documentation forcor.test in R says "By default, probabilities for method="spearman" and method="kendall" are found by normal theory. If normal=="FALSE", then repetitive calls are made to cor.test. ..."
What attention have you given to normality of data based on "(number of characters, number of cuts, IMDB rating etc.)"?
From what is said in your Question and in some of the Comments, I would wonder which P-values should be taken seriously which should not.
Comment: I'm pretty sure "normal theory" there refers to the usual normal approximation of the null distribution of those (nonparametric) test statistics. Those null distributions and their approximations don't rely on normality for the original variables (only on continuity, usually, but for the normal approximation there's also a variance adjustment for ties)
Answer: It sounds like you might want to do exploratory data analysis instead of a deep dive into the meaning of p-values. Basically, make plots, lots of them, to understand the patterns in your data.
It might help to keep in mind to following advice from [1]:
Quick tips to improve your [regression] modeling

Think about variation and replication (ie., patterns you observe in one dataset won't necessarily replicate in another dataset about the same phenomenon)
Forget about statistical significance and p-values
Graph the relevant and not the irrelevant; make many graphs

There are 7 more steps (see below) but the first 3 steps are most relevant to you since you seem to be at the start of your investigation.
Notes

The Pearson's correlation coefficient measures strength and direction of a linear relationship. So by choosing Pearson's correlation out of hand you've implicitly decided to see if there is a linear relationship between the variables. Again, plotting the data might turn out to be more informative than computing correlations.
You plan to run multiple statistical tests with the goal of discovering interesting hypotheses. It's important to correct for doing all those tests because each test has a probability of making a false discovery (type I error). The probability of making false discoveries grows quickly with multiple testing. This is an advanced topic. You can learn more about it here.

Quick tips to improve your [regression] modeling, continued

Interpret regression coefficients as comparisons
Understand statistical methods using simulations
Fit many models
Set up a computational workflow
Use transformations
Do causal inference in a targeted way, not as a byproduct of a large regression
Learn methods through live examples

[1] A. Gelman, J. Hill, and A. Vehtari. Regression and Other Stories. Cambridge University Press, 2020.
Comment: (+1) for point 2., although the whole point of introducing p-values was to take care of point 1. in an automated way ;-)
Comment: @cdalitz Where is the fun in automating EDA? At the very early exploratory stage, it tends to be hard to report p-values with a straight face. Either the p-values are not corrected for multiple testing at all, or they are corrected only in the reported analysis but other (unreported) analyses were done as well.
Comment: Sorry, I did not want to start a hair splitting thread...
Answer: If you are looking for correlations, your first look should not be at the p-value, but at the value of the correlation coefficient $r$. High correlation means high $|r|$, not high p-value.
The p-value only tells you how likely the observed correlation value is under the assumption that the correlation is exactly zero. In a situation that has a correlation different from zero (which is the case in almost all situations), you can make the p-value arbitrarily small simply by collecting more data, however small the correlation is.
The R function cor.test also provides a confidence interval for the correlation coefficient:
> cor.test(faithful$waiting, faithful$eruptions)
[...]
95 percent confidence interval:
 0.8756964 0.9210652

This is more informative than merely a p-value because it includes the information about the actual value of the correlation.
Answer: Before you look at anything at all you should have a clear goal or research question. You need a reason why you want to look at the correlations. What are you gonna do with it?
For instance,

Do you want to make some tv-show yourself and see what parameters can influence the success? Then you have to deal with the problem of spurious relationships.

Do you just want to make a statistical model, to predict the success of a show based on some features? (in this case the question about causality is not important as in the first case) Then you need to take care that you are not overfitting. You are looking at multiple features this brings along the problem of multiple comparisons. Along with using correction formulas you can also use a cross validation method to find an optimal model (and you don't care about the p-value bit you care about the best model).

Do you want to do hypothesis testing? Then another issue is that multivariate tests can be made more powerful when you use a linear model instead of seperate correlations. Individual correlations can be small while a combined model is very significant (See for an explanation in this question which is about the opposite case Can ANOVA be significant when none of the pairwise t-tests is? ) Also some variable may become significant when it is corrected for another variable (related is When is MANOVA most useful ).

can I always look at this value to have a good metric of how certain the relation between the variables is, or are there any assumptions that have to be statisfied?

As described in the above three points there are situations where you want to look at it differently.
But if correlations are what you after, then you also need to consider the distribution of the data points. Asside from independence of seperate points (I don't think this is true for the IMDB database and there might be all sort of bias in sampling), it is also important that the distribution is normal distributed (if you use the standard computation of the p-value). The Kendall rank correlation coefficient and associated tests is an alternative.

When not to look at p-value


Setup migration of a Drupal 8 node(s) to Drupal 9

Question: Are there plugins that exist that can read a Drupal 8 source by node type and help get set up for a scripted migration? The content type name is different between the source and the target. I found ContentEntity, but I am not sure if this can facilitate the need. I have a Drupal 8 database next to a Drupal 9 database. Otherwise, I assume I will have to build out an entire SQL source plugin.
Answer: It is possible by using Migrate Drupal D8 module.
If you don't like the above module approach another way to achieve it is to expose content as json in old site using JSON API and use Migrate API to import data in the new site. It gives you the flexibility to define bundles and fields in new site.
Here is another guide on how to achieve it


views_embed_view() ignores template file using Ajax

Question: I have a view shown in two ways. Once I show it as a normal block and one time using views_embed_view() in combination with Ajax.
For the regular block I created a views-view-list.html.twig template in my theme adding a div wrapper. My styling is based on this added div.
For the embedded block, this views-view-list.html.twig block is ignored and therefor the styling is off.
Using views_embed_view() inside a preprocess does work the way you'd expect, but using it with Ajax ignores the templates.
How can I make sure the template is not ignored, or is there a way to add another template that is seen when embedding the view?
I have a custom module my_view_ajax
I attach the js file in my .module file:
function my_view_ajax_preprocess_node(&$variables) {
  $node = $variables['node'];
  //check content type
  if ($node->getType() == 'article' || $node->getType() == 'issue' ) {
    $variables['#attached']['library'][] = 'my_view_ajax/my_view_ajax__js';
  }
}

In my .js file I use Ajax to get my views block.
const routing_url = '/custom/ajax/articles';
$.ajax({
  type: 'GET',
  url: routing_url,
  data: 'nid='+nid,
  dataType: 'html',
  async: true,
  complete: function (data) {
    $containerContent.empty().html(data.responseText);

    $containerContent.fadeIn();
    $ajaxLoader.fadeOut();
  }
});

In my routing.yml I create the Ajax path
my_view_ajax.articles:
  path: '/custom/ajax/articles'
  defaults:
    _title: 'Articles'
    _controller: '\Drupal\my_view_ajax\Controller\viewsajaxController::issueArticles'
  requirements:
    _permission: 'access content'

And finally in my viewsajaxController.php
namespace Drupal\my_view_ajax\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use \Symfony\Component\HttpFoundation\Response;

class viewsajaxController extends ControllerBase {
  public function issueArticles() {
    $nid = 11;

    $markup = \Drupal::service('renderer')->render(views_embed_view('ccr_overview', 'block_articles_view', $nid));
    return new Response($markup);
  }
}

Answer: I have tried to replicate the case as follow.
1.Added following structure in views-view-table--articles.html.twig

{% for row in rows %}
  {% set titletxt = '' %}
  {% set viewnod = '' %}
  {% set editnode = '' %}
    {% for key, column in row.columns %}
      {% for field in column.fields %}
        {% for content in column.content %}
          {% if field == 'title' %}
             {% set titletxt = content.field_output %}
          {% endif %}
          {% if field == 'view-node' %}
             {% set viewnod = content.field_output %}
          {% endif %}
          {% if field == 'edit-node' %}
             {% set editnode = content.field_output %}
          {% endif %}
        {% endfor %}
      {% endfor %}
    {% endfor %}

        {{titletxt}}

        {{viewnod}}

        {{editnode}}

{% endfor %}

In node--article.html.twig embed following view

Articles From Block View

   {% if articles %}
     {{ articles }}
   {% endif %}

in fluffiness.theme add as follow
function fluffiness_preprocess_node(&$variables) {
$relatedArticles = views_embed_view('articles', 'block_1');
$variables['articles'] = \Drupal::service('renderer')->render($relatedArticles);
}

Then i noticed in node view mode, structure with template of view is rendered as follow.
Comment: Thanks for your reply, I found out. Because of your test that the problem is in using views embed in combination with Ajax. I updated my question with some extra information.


MySQL comparar um numero com string retorna verdadeiro se a string começar pelo número

Question: Tenho a seguinte tabela na base de dados:
idUser - Username - Group
1 - John - 5GR
2 - Doe - 1GR
E a seguinte query:
    SELECT * FROM `table` WHERE `idUser` = '$name' OR `Group = '$name'

$name é a variável que contem o valor que utilizador introduz.
Quando o utilizador introduz 1, apenas o utilizador com o idUser=1 é apresentado.
Isto está correcto.
Quando o utilizador introduz 2, apenas o utilizador com o idUser=2 é apresentado.
Isto também está correcto.
O problema é quando o utilizador introduz '1GR'.
O correcto seria apresentar apenas o utilizador com o Group = 1GR, neste caso o utilizador Doe.
No entanto o utilizador John é também apresentado porque o seu idUser = 1 e a string introduzida pelo utilizador contém 1.
O problema é da comparação com o idUser, eu verifiquei se retirar essa comparação da query ele apresenta correctamente (no entanto o utilizador ja nao podera procurar por id user e isto é essencial).
Existe alguma maneira de arranjar isto?
Answer: O problema é que está havendo um cast implícito da string buscada, pois você está comparando um número com uma string. Você pode forçar a interpretação do idUser como string desta forma:
CAST(`idUser` AS CHAR)

Note que também há um errinho na query, falta um ` no Group.
Aplicando os ajustes ao seu caso:
SELECT * FROM `table` WHERE CAST(`idUser` AS CHAR) = '$name' OR `Group` = '$name'

Não se esqueça de usar o mysqli_real_escape_string() do lado do PHP para evitar injeção de SQL caso o usuário digite o caractere ' (ou outros caracteres especiais) na busca.
Simplificando a query
Como busca o mesmo valor em mais de uma coluna, pode escrever desta forma:
SELECT * FROM `table` WHERE '$name' IN ( `Group`, CAST(`idUser` AS CHAR) )

Mais detalhes aqui:

Checar se um mesmo valor está em algum dos dois campos


SVG Translate Path object with a user defined coordinate system

Question: I have a simple path definition (just an example) that I want to be able to translate with accuracy on the svg canvas.
<code>M 30.872704,198.53891 C -143.04429,-148.7562 503.71813,57.927231 257.70273,102.67753
</code>
What I want to do is set the origin (top left corner) of the path to the origin of the svg document (top left corner) by using transform="translate(0,0)" on the path object. Basically I want to set the path in the top left corner so I can then apply further translations to it in relation to the svg document.
I want to avoid using any javascript to do this if possible.
My thoughts are I can return the bounding box of the path by using php to exec Inkscape and use the commandline option --query-all. I could then calculate the distance from the path to the document origin and reset it.
Is there a better way to do this?
Thanks in advance.
Answer: A bezier curve never extends outside of the quadrilateral formed by it's endpoints and control points.  The same is obviously true of straight lines also.  Therefore you can get an excellent approximation to the bounding box of the path by just parsing all the points and keeping track of the min and max values of the X and Y coordinates.
The resulting bounding box will sometimes be slightly bigger that the real bounding box of the path, but it may well be close enough for your needs.
Parsing the path with a small PHP script is probably going to be easier and faster than invoking Inkscape.