XAMPP tmp folder oversized

Question: I'm running some php file every 2 minutes via Windows Task Scheduler, but time-to-time I get notification about low space on my drive D:.
After check I found that in XAMPP tmp folder located on D:\XAMPP\tmp are lot of files with names similar to: cachegrind.out.1381478803-D__xampp_htdocs_Real_Estate_App_index_php and size of each file is more than 144 MB.
These files have content:
==== NEW PROFILING FILE ==============================================
version: 1
creator: xdebug 2.2.3
cmd: D:\xampp\htdocs\Real Estate App\index.php
part: 1
positions: line

events: Time

fl=php:internal
fn=php::header
3 0

fl=php:internal
fn=php::define
45 0

...

I understand that this is caused because of xdebug, but how to stop this process I don't know.
Mybe someone had same problem? Any ideas?
Answer: You have xdebug profiling enabled. If this is enabled xdebug will write runtime information about the scripts into systems temp folder (by default). Disable it in your php.ini (or in the xdebug.ini, depends on where did you set it)
xdebug.profiler_enable=Off

and restart the web server
Comment: you are welcome. you can delete the existing cachegrind files as well
Comment: I found [XDebug] category in my php.ini file with option: `xdebug.profiler_enable = 1`. I switched value to 0 and looks like my problem is solved. Thanks a lot!
Comment: can we delete those files in tmp folder it is really taking lot of space ?? @hek2mgl
Comment: @hek2mgl :     xdebug.profiler_enable = 0 | is zero in my php.ini but still i see tmp folder oversized, what are other things which might have caused this ?
Comment: @hitesh have you restarted the webserver?
Comment: @hek2mgl   no i didnt change the value, In php.ini the value was zero initially...since i didnt change it, i dont need to restart the browser, I wanted to know what are other things which might cause this  issue other than xdebug
Comment: @hitesh There are a 1000s of reasons possible. You need to check which files are in /tmp and who is creating that files.
Comment: @hek2mgl  : I have files of size 160 mb just now created when i started using my drupal site of name cachegrind.out.1393565671-H__xampp_htdocs_gemkt_trunk_index_php ..... htdocs/gemkt/trunk/index.php these are folders...|| and there are lot of files getting created here of almost same size
Comment: Thank you, Ive just deleted 860GB of cachegrind.out files from my PC. its only a 920GB HDD. I wont be turning xdebug.profiler_enable back ON any time soon, unless there is a way of disabling the cache only ?
Answer: Yes found out that turning xdebug.profiler to off does part of the trick
xdebug.profiler_enable= 0

Then also turn off also eAccelerator which precomplies codes
; The directory that is used for disk cache. eAccelerator stores precompiled
; code, session data, content and user entries  here. The same data can be
; stored in shared memory also (for more quick access).
eaccelerator.enable="0"

Then stop apache
Delete the files in the tmp dir
Resart apache does the trick

XAMPP tmp folder oversized


Unable to handle NaN in pandas dataframe

Question: I have a pandas dataframe with a variable, which, when I print it, shows up as mostly containing NaN. It is of dtype object. However, when I run the isnull function, it returns "FALSE" everywhere. I am wondering why the NaN values are not encoded as missing, and if there is any way of converting them to missing values that are treated properly.
Thank you.
Answer: Your NaN are strings
df = pd.DataFrame(dict(A=['Not NaN', 'NaN', np.nan]))
print(df)

         A
0  Not NaN
1      NaN
2      NaN

What's missing
print(df.isnull())

       A
0  False
1  False
2   True

The strings are not missing, the np.nan are.
You can mask the strings with
df.A.mask(df.A.eq('NaN')).isnull()

0    False
1     True
2     True
Name: A, dtype: bool

Comment: Thanks, it seems like another option is     df.replace('NaN', np.nan)
Answer: Building on from piRSquared, a possible method to treating NaN values (if applicable to your problem) is to convert the NaN inputs to the median of the column.
df = df.fillna(df.mean())


Quasar2 Vue3 Cypress slide toggle status mismatch with what is shown on Cypress browser

Question: My vue template:
<template>
  <q-item tag="label" v-ripple>
    <q-item-section>
      <q-item-label class="text-mono">
        {{ name }}
      </q-item-label>
      <q-item-label caption>{{ description }}</q-item-label>
      <q-item-label
        caption
        class="text-red"
        v-show="warning"
        :key="warning"
        v-for="warning in warnings"
      >
        {{ warning }}
      </q-item-label>
      <q-item-label caption class="text-red" v-show="warningMsg">
        {{ warningMsg }}
      </q-item-label>
    </q-item-section>
    <q-item-section avatar>
      <q-toggle
        color="indigo"
        v-model="model"
        :disable="isToggleDisabled"
        @triggerFunc="btnToggleTrigger"
      />
    </q-item-section>
  </q-item>
</template>

I have the following cypress E2E test code snippet:
  it('Verify Toggle Button from auto-generated page', () => {
    cy.get('[data-test="toggle-setting-0"]').should("not.be.checked");
    cy.get('[data-test="toggle-setting-0"]').click();
    cy.get('[data-test="toggle-setting-0"]').should("be.checked"); // XXX
  });

The status validation fails AFTER the click(). However, cypress browser UI shows that the slider button is clicked. The error message:
Timed out retrying after 4000ms: expected '' to be 'checked'

What do I miss?
Comment: Can you post the HTML of the checked element.
Comment: I am using Quasar 2 Vue 3 `q-toggle`. Not native HTML.
Answer: The <input> is within the element that has the data-test attribute.
You can verify the state by one of the inner element's class.
Does not seem ideal to me, but it works.
cy.get('[data-test="toggle-setting-0"]')
  .find('.q-toggle__inner')
  .should('have.class', 'q-toggle__inner--falsy')

cy.get('[data-test="toggle-setting-0"]')
  .find('input')
  .check({force: true});

cy.get('[data-test="toggle-setting-0"]')
  .find('.q-toggle__inner')
  .should('have.class', 'q-toggle__inner--truthy')

Ideally, you would check the value of the v-model variable.
Comment: I was going to check that next step - in principle you add a reference to the `v-model` variable to `window` and in the test can check it's value. But I'm wondering about Vue refs, how they would work in a Cypress test.
Comment: `Timed out retrying after 4050ms: cy.check() failed because this element is not visible:

This element  is not visible because it has CSS property: display: none`
Comment: Yes, have to use teh `force: true`. However, thesecond `should` fails: `Timed out retrying after 4000ms: expected '' to have attribute 'aria-checked'`
Comment: Don't use aria-checked, the input element should be checked.
Comment: Tried but to no avail.
Comment: `Timed out retrying after 4000ms: expected '' to be 'checked'`
Comment: Yeah those quasar controls behave quite strangely.
Comment: I have included the vue template in my post.
Comment: I think I missed your solution yesterday. It works but the way it works is very cryptic and not intuitive compared to a simple `should('be.checked')`.
Comment: How to check the `v-model` or any `props` value for that sake.
Answer: I can see that the value of aria-checked is changing for the toggle. So you can so like this:
//For toggle off
cy.get('[data-test="toggle-setting-0"]').should(
  'have.attr',
  'aria-checked',
  'false'
)

//For toggle on
cy.get('[data-test="toggle-setting-0"]').should(
  'have.attr',
  'aria-checked',
  'true'
)

Comment: `Timed out retrying after 4000ms: expected '' to have attribute 'aria-checked'`
Comment: Can you tell me which one matches yours from here - https://quasar.dev/vue-components/toggle
Comment: https://quasar.dev/vue-components/toggle
Comment: You have to point to me to the exact one.
Comment: https://quasar.dev/vue-components/toggle#qtoggle-api
Comment: I can see the `aria-checked` attribute. You have to select different locators.
Comment: I have included the vue template in my post.


Deploying dynamically created BPMN model using Activiti REST API

Question: I am new to Activiti. I am working on a project in which i should be able to create process dynamically using spring mvc. I have come acrossed http://stacktrace.be/blog/2013/03/dynamic-process-creation-and-deployment-in-100-lines/
Is it possible to deploy the dynamically created process using REST API directly or we should create bpmn-20.xml and deploy it. Also is there any example for creating complex process such as using boundary events dynamically.
Thanks
Answer: It is possible through this endpoint /activiti-rest/service/deployment!
Please check this forum thread for further infos + sample code.
You do not have to really create the file on your disk, just simulate it with an InputStream of some sort:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("deployment", new ByteArrayInputStream((<put-something-here>).toByteArray()), ContentType.DEFAULT_BINARY,"test.bpmn20.xml")

Answer: Here is the code for uploading .bpmn file content as string and starting the process at the same time:
@Autowired
private RuntimeService runtimeService;

@PostMapping("/deployAndStartProcess")
public void deployAndStartProcess(@RequestBody DeployWorkflow dw, @RequestParam(required = false) HashMap<String, Object> variables) {
  String processXml = dw.getBpmnFile();
  String processId = dw.getProcessKey();
  ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
  DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService().createDeployment().name(processId);
  deploymentBuilder.addString(processId + ".bpmn", processXml);
  deploymentBuilder.deploy();
  runtimeService.startProcessInstanceByKey(processId, variables);
}

Reference: Look at heymjo's answer in the last


ArrayList em C# não mostra valores digitados pelo usuário

Question: Fiz um ArrayList em C# que mostra apenas o nome, idade e curso de um estudante . Mas o erro CS0029 diz que não é possível converter implicitamente string paraint na linha 27 e 37, antes de eu inserir a variável idade tinha executado, mas não mostrava nada.
using System.Collections;
using static System.Console;

public class Estudante
{
    public string Nome;
    public int idade;
    public string Curso;

    public string Imprimir()
    {
        return "Nome: " + Nome + " Idade: " + idade + " Curso: " + Curso;
    }
}

public class ArrayEstudante
{
    static int Main(string[] args)
    {
        ArrayList Vetor = new ArrayList();
        Estudante estudante1 = new Estudante();

        Vetor.Add(estudante1);
        Write("Digite o nome do estudante: ");
        ((Estudante)Vetor[0]).Nome = ReadLine();
        Write("Digite a idade do estudante: ");
        ((Estudante)Vetor[0]).idade = ReadLine();
        Write("Digite o nome do curso: ");
        ((Estudante)Vetor[0]).Curso = ReadLine();

        WriteLine();

        Vetor.Add(estudante1);
        Write("Digite o nome do estudante: ");
        ((Estudante)Vetor[1]).Nome = ReadLine();
        Write("Digite a idade do estudante: ");
        ((Estudante)Vetor[1]).idade = ReadLine();
        Write("Digite o nome do curso: ");
        ((Estudante)Vetor[1]).Curso = ReadLine();

        ReadKey();
        return 0;
    }
}

Comment: Há algum motivo para usar ArrayList e não usar IList genérica?
Comment: O assunto que estou vendo é ArrayList em POO nas aulas, IList eu nunca vi.
Comment: a entrada do ReadLine é sempre do tipo string, como seu idade é int aponta isso, o que você poderia era forçar um cast no readline para int ou chamar o parser, mas isso não necessariamente assegura que será digitado um numero
Answer: O ArrayList é uma classe usada anterior a chegada dos genéricos em C#. Na própria documentação da Microsoft sobre o ArrayList pode-se encontrar:

Não recomendamos que você use a classe ArrayList para o novo desenvolvimento. Em vez disso, recomendamos que você use a classe List genérica

Fonte: Arraylist Class
Recomendo que já comece a aprender de um jeito mais "certo".
Você pode ler sobre IList.
Como Lucas Miranda falou nos comentários, a função Console.ReadLine() tem um retorno do tipo string e esta conversão implícita não pode ser feita. O certo é você converter o resultado para inteiro e depois atribuí-lo a sua variável. E o mais certo seria validar o input do usuário.
Seguindo a sua lógica de raciocínio, usando List<T> teria um seguinte código:
static int Main(string[] args)
{
    // Criamos uma lista de estudantes
    List<Estudante> estudantes = new List<Estudante>();

    // criamos um novo estudante
    Estudante estudante1 = new Estudante();

    // solicitamos seus dados
    Console.Write("Digite o nome do estudante: ");
    estudante1.Nome = Console.ReadLine();

    Console.Write("Digite a idade do estudante: ");
    estudante1.idade = Convert.ToInt32(Console.ReadLine());

    Console.Write("Digite o nome do curso: ");
    estudante1.Curso = Console.ReadLine();

    // terminamos de solicitar os dados, podemos adicionar na lista de estudantes
    estudantes.Add(estudante1);

    // cria o segundo estudante
    Estudante estudante2 = new Estudante();

    Console.Write("Digite o nome do estudante: ");
    estudante2.Nome = Console.ReadLine();

    Console.Write("Digite a idade do estudante: ");
    estudante2.idade = Convert.ToInt32(Console.ReadLine());

    Console.Write("Digite o nome do curso: ");
    estudante2.Curso = Console.ReadLine();

    estudantes.Add(estudante2);
}

Perceba que não fazemos casting (converso explícita) em nenhum momento porque ele já sabe que dentro dessa lista há um objeto do tipo Estudante. No caso do ArrayList, você pode guardar qualquer coisa lá, inclusive, coisas que não são do tipo Estudante.
Perceba que usei Convert.ToInt32 para converter uma string para inteiro evitando assim o erro que você teve.
Lembrando que sempre deve validar o que o usuário digita.
Comment: A resposta não é de toda ruim, mas você não sabe o esforço que estou tendo para convencer ele converter string em número do jeito correto, agora vem você fala para ele fazer do jeito errado,,,
Comment: Entendo! Realmente, usar um int.TryParse seria muito melhor ou alguma coisa semelhante. Quando tiver um tempo, farei a edição.
Comment: Eu utilizei `if (!int.TryParse(ReadLine(), out estudante1.idade)) return 1;` e `if (!int.TryParse(ReadLine(), out estudante2.idade)) return 1;` agora o problema é o seguinte **Erro CS0246: O nome do tipo ou do namespace "List<>" não pode ser encontrado (está faltando uma diretiva using ou uma referência de assembly?)**
Comment: @CarlosA. Faltou importar o pacote: System.Collections.Generic é só adicionar ele no topo do código utilizando using
Comment: @KevinKouketsu na linha 21 ou seja `List estudantes = new List();` que você fez
Comment: @KevinKouketsu uso `estudante1.Imprimir()` e `estudante2.Imprimir()` ou `estudante.Imprimir()`?
Comment: usei `estudante1.Imprimir()` e `estudante2.Imprimir()` executa mais não retorna o que foi digitado.


reseting or clearing an input field with reactjs

Question: I having the following problem.
I have a react component which does a filter search on a list which is fine, but I want to clear the input field with a button, if i add a value attribute to the input field which I can set in the setState but then it stops the onChange from working as it does the filter search on the list:
I've created the following but this still doesn't work.
<input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick="React.findDOMNode(this.refs.form).reset()"></button>

Answer: set the value to empty as
handleClick = () => {
        ReactDOM.findDOMNode(this.refs.form).value = "";
      }

and yes onClick expects a function or a value not a string. Also React.findDOMNode() is deprecated. You should use ReactDOM.findDOMNode();

class Hello extends React.Component {
  handleChange = (e) => {

  }
  handleClick = () => {
    ReactDOM.findDOMNode(this.refs.form).value = "";
  }
  render() {

    return (

      <input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick={this.handleClick}>click</button>

    )
  }
}

ReactDOM.render(<Hello />, document.getElementById('app'));

Also Its a better idea to use state and change the state for input value.
as

class Hello extends React.Component {
  constructor() {
    super()
      this.state = {
        valueAttr : ''

    }
  }
  handleChange = (e) => {
    this.setState({valueAttr: e.target.value});
  }
  handleClick = () => {
    this.setState({valueAttr: ''})
  }
  render() {

    return (

      <input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" value = {this.state.valueAttr} onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick={this.handleClick}>click</button>

    )
  }
}

ReactDOM.render(<Hello />, document.getElementById('app'));

I personally prefer the second approach. But you can do it in whichever way you feel comfortable.
Comment: How to do it in a functional component
Comment: @yaswanthkoneri, for a functional component too, you can use state and refs with the help of hooks
Answer: Here onClick="React.findDOMNode(this.refs.form).reset()" you are assigning string to onClick value of button, not a function, if you want to assign a function it should look like onClick={React.findDOMNode(this.refs.form).reset}" or onClick={() => React.findDOMNode(this.refs.form).reset()}
Next, if i recall correctly, findDOMNode is deprecated in React, so you should use ReactDOM for this.
And last, I doubt there is reset method present, so I think you should try mutating input value directly.
Try this
onClick={() => this.refs.form.value = ''}
Answer: Just use:
this.refs.form.getInputNode().value = '';

Should do the trick


Por que os valores de x e v[0] não são iguais? - linguagem C

Question: Estou revendo alguns conceitos no site : Endereços e Ponteiros, até que encontro o seguinte código:
void func1 (int x) {
   x = 9 * x;
}

void func2 (int v[]) {
   v[0] = 9 * v[0];
}

int main (void) {
   int x, v[2];
   x    = 111;
   func1 (x); printf ("x: %d\n", x);
   v[0] = 111;
   func2 (v); printf ("v[0]: %d\n", v[0]);
   return 0;
}

Veja funcionando no Ideone
Para minha surpresa a saída foi:
x: 111
v[0]: 999

Minha dúvida:
Por que x e V[0] não são iguais? Já que possuem o mesmo valor (111)
Answer: Boa tarde Luiz,
Isso ocorre porque na função func1 (int x) você está passando o valor de x, e não a referência de x, portanto as alterações do valor do mesmo são feitas apenas dentro da função.
Se você jogar um printf() dentro da funct1 você verá que vai dar 999.
isso não ocorre no caso da funct2 pois, por se tratar de um vetor, o valor de v(sem referência) já é o próprio endereço de memória do elemento 0 do vetor.
Um exemplo disso é quando vamos trabalhar com strings em C, não se usa o & no scanf() pois a variável já guarda o endereço do primeiro elemento.
Solução:
Caso você queira manter o mesmo formato da função, isto é, não quiser passar como parâmetro um ponteiro pra alterar o valor de x, você pode modificar seu código pra x receber o resultado da função
Código:
#include <stdio.h>

int func1 (int x) {

   x = x * 9;
}

void func2 (int v[]) {
   v[0] = 9 * v[0];
}

 int main (void) {

  int x, v[2];

  x = 111;
  x = func1 (x);
  printf ("x: %d\n", x);

  v[0] = 111;
  func2 (v);
  printf ("v[0]: %d\n", v[0]);
  return 0;
}

Já no caso de você quiser alterar a função para passar x como parâmetro, ficará assim:
#include <stdio.h>

int func1 (int *x) {

  *x = *x * 9;

}

void func2 (int v[]) {

    v[0] = 9 * v[0];
}

int main (void) {
int x = 111, v[2];

func1 (&x);
printf ("x: %d\n", x);

v[0] = 111;
func2 (v);
printf ("v[0]: %d\n", v[0]);

return 0;
}

Onde *x se refere ao conteúdo da variável x.
Não sei se ficou claro, mas irei editar a resposta caso reste alguma dúvida.
Espero ter ajudado,
Abraços!
Comment: Caso queira edite sua pergunta adicionando o pedaço do código onde x passe por parâmetro e não valor.
Comment: No mesmo segundo em que enviei você editou, boa!
Comment: Boa tarde H. Lima!! perfeita a resposta, clareou bastante as coisas aqui! muito obrigado!!
Comment: Fico feliz em ajudar! boa sorte nos estudos :D


How is standard deviation different from average deviation?

Question: Standard deviation is used as a measure of deviation or distribution in a sample or a population.Similarly mean is used as a measure of something in a group(say average marks of a group of students).How is standard deviation different from average deviation?
Comment: But the standard deviation is not the "average deviation of the elements from the mean".
Comment: But it is used as a measure of deviation or distribution in a sample or a population.Similarly mean is used as a measure of something in a group(say average marks of a group of students).How is standard deviation different from mean?
Comment: you should point out specific assumptions/contextual things  to make it explicit. Statistics and mathematics have a large variety of problems and alternative solutions. It is not desireable to make sublimal assumptions to answer your question
Answer: Let $(x_i)$ be a data set. Denote by the average deviation $D$. Then
$$ D = \frac{1}{n} \sum_{i=1}^n (x_i - \mu) $$
and
$$ \sigma = \sqrt{ \frac{1}{n} \sum_{i = 1}^n (x_i - \mu) ^2 } $$
Certainly two different quantities. Variance (the square of standard deviation) measure the average squared deviation - i.e., the average positive distance to the mean.
Comment: But if average deviation can be used as a measure of distribution in a group, why was another quantity(standard deviation) defined? Or why was variance defined?(why should we measure the average of squared deviation when deviation is all we are concerned about.)
Comment: We want positive numbers to measure distances. Variance measures spread and better represents how tightly packed the data is. Average deviation doesn't really do a good job of that. TL;DR: Don't worry about it. It'll only complicate things.
Comment: Please suggest me some good books(introductory level ) to understand these things in statistics.


Is an off diagonal ROC curve not always better than random?

Question: I'm trying to better understand the ROC when used for machine learning model classification and was looking at this explaining curve, explaining what is better and worse. However, I am thinking, contrary what is shown on the curve, that perhaps worse is really whatever is closer to the random distribution. Because whatever is not random can always be functionally inverted. I.e. A curve well under the diagonal would actually be better than the diagonal?
Is an off (below) diagonal ROC curve not always better than random?
(Please, note that none of the previous answers actually address this question.)

Related topics:

ROC curve under diagonal?
ROC curve going below diagonal
How to calculate Area Under the Curve (AUC), or the c-statistic, by hand
ROC curve crossing the diagonal
The meaning of slope on a ROC curve
Area between the ROC curve and the Random Guessing Line
Comment: You want to take the opposite labels of a bad classifier...understandable. Let's draw an analogy. I predict if the weather will be rainy or sunny, and I'm inaccurate. I often predict sunny days as rainy and rainy days as sunny. You catch this, flip my predictions, and get good results. Am I suddenly good at predicting the weather? (Further, the model you get by flipping the categories of a poor classifier still suffers from issues related to probability predictions.)
Comment: Thanks Dave, but can you expand on the statement `"...flipping the categories of a poor classifier still suffers from issues related to probability predictions."`, in non-stat language?
Answer: It might be that you can calibrate the predictions in order to reverse the terrible model predictions to be good, as is suggested in the comments here. However, you need to know to do this, and I dislike that some popular software packages automatically flip the ROC curve when it falls below the diagonal. This puts the analyst in a position to use predictions that might be terrible while thinking those predictions are good. No! Those predictions are terrible. They might be able to be transformed into good predictions (calibration), but the predictions themselves are terrible.
Separate from pure predictions, if the model makes terrible predictions that can be made good through some calibration, interpreting the coefficients of the original model, as is common to do in many areas of science, is at least a bit dubious. If you calibrate the predictions and consider the final predictions to be the original model and then the calibration, then the coefficients from the original model no longer apply to the two-step strategy.


cant override method in a base class with my code

Question:    class Vehicle():

        def __init__(self, brand, model):

            print('Am a vehicle')

        def brand_name(self, brand):
            print('vehicle class')
            self.brand = brand
            return brand

        def Vehicle_model(self, model):
            print('vehicle class')

            self.model = model
            return model

     class Mazda(Vehicle):
            def __init__(self, model, brand):

            Vehicle.__init__(self,brand, model)

            def brand_name(self, brand):
                print('base class method')
                self.brand = brand
                print(brand +" " +'is a good brand')

            def Vehicle_model(self, model):
                print('base class method')
                self.model = model
                print('i am a '+ ' '+ self.model +''+self.brand+"model")

     maz = Mazda(2019,'camry')
     output>>>   Am a vehicle

     maz.brand_name('Toyota')
     output>>> vehicle class
     output>>  'Toyota'

i want override the method in the base class  but when i try using the derived class object to call the method inside the derived class, it not working to my expectation. i expect the derived class methods to be executed not the base class, please guys what am i doing wrong
Comment: `Vehicle.__init__(self,brand, model)` has the same indent level like previous line. Is this a typo?
Comment: I don't think this code snippet you put runs. All function declarations need a body and you don't have one for Mazda's `__init__` rn (unless the next line is part of the function body). The compiler should be complaining. You really need to fix the indentations.
Answer: Try the code after proper indentation:
class Vehicle():

    def __init__(self, brand, model):

        print('Am a vehicle')

    def brand_name(self, brand):
        print('vehicle class')
        self.brand = brand
        return brand

    def Vehicle_model(self, model):
        print('vehicle class')

        self.model = model
        return model

class Mazda(Vehicle):
    def __init__(self, model, brand):
        Vehicle.__init__(self,brand, model)

    def brand_name(self, brand):
        print('base class method')
        self.brand = brand
        print(brand +" " +'is a good brand')

    def Vehicle_model(self, model):
        print('base class method')
        self.model = model
        print('i am a '+ ' '+ self.model +''+self.brand+"model")

maz = Mazda(2019,'camry')

maz.brand_name('Toyota')

It is working fine.
Comment: Thanks a lot, I can see my problem now
Answer: class Vehicle():
    def __init__(self, brand, model):

        print('Am a vehicle')

    def brand_name(self, brand):
        print('vehicle class')
        self.brand = brand
        return brand

    def Vehicle_model(self, model):
        print('vehicle class')

        self.model = model
        return model

 class Mazda(Vehicle):
        def __init__(self, model, brand):
            Vehicle.__init__(self,brand, model)  # your problem was here wrong indentation

        def brand_name(self, brand):
            print('base class method')
            self.brand = brand
            print(brand +" " +'is a good brand')

        def Vehicle_model(self, model):
            print('base class method')
            self.model = model
            print('i am a '+ ' '+ self.model +''+self.brand+"model")

do well and check your indentation, that seems to be the problem, Vehicle.__init__(self,brand, model) was not indented well. hope it helps
Comment: yeah thanks a lot I over looked that the interpreter didn't complain, so I never look at that code thanks ..


send json object to mvc controller

Question: I want to send my json-object wich i got from a api and send i to my controller and parse it to my model.
   var playerstats = val.resultSets[4].rowSet[0]
                        $.each(playerstats, function (key, value) {
                            $.ajax({
                                async: false,
                                type: "post",
                                url: "/Stats/addBoxScore",
                                data: JSON.stringify(playerstats),
                                done: function (data) {
                                    console.log(data);
                                },
                                error: function (jqXHR, err) {
                                    console.log(err);
                                }
                            });

                        });

Here is my controller:
  public void addBoxScore(Games playerstats)
    {
        var gamesID = playerstats;
    }

For now im not doing anything in the controller because i can't get the data from the ajaxpost right.
Here is my model:
 public class Games
{
    [Key, Column(Order = 0)]
    public int GAME_ID { get; set; }
    public int TEAM_ID { get; set; }
    public string TEAM_ABBREVIATION { get; set; }
    public string TEAM_CITY { get; set; }
    [Key, Column(Order = 1)]
    public int PLAYER_ID { get; set; }
    public string PLAYER_NAME { get; set; }
    public string START_POSITION { get; set; }
    public string COMMENT { get; set; }
    public int MIN { get; set; }
    public int FGM { get; set; }
    public int FGA { get; set; }
    public int FG_PCT { get; set; }
    public int FGTHREEM { get; set; }
    public int FGTHREEA { get; set; }
    public int FGTHREE_PCT { get; set; }
    public int FTM { get; set; }
    public int FTA { get; set; }
    public int FT_PCT { get; set; }
    public int OREB { get; set; }
    public int DREB { get; set; }
    public int REB { get; set; }
    public int AST { get; set; }
    public int STL { get; set; }
    public int BLK { get; set; }
    public int TO { get; set; }
    public int PF { get; set; }
    public int PTS { get; set; }
    public int PLUS_MINUS { get; set; }

    public virtual Player player { get; set; }
}

When the data from the ajax post gets to the controller it is all null. What am i doing wrong?
Answer: I can write the datatype for your sending data and you not need to write the "strngify".
datatype: "json"

Comment: This doesn't work either:
  $.ajax({
       async: false,
       dataType: "json",
       type: "post",
       url: "/Stats/addBoxScore",
       data: playerstats,
       done: function (data) {
       console.log(data);
      },
       error: function (jqXHR, err) {
     console.log(err);
 }
Comment: I think the problem with wrong json which you send to controller. Check the correct of your json in your backend.
Comment: hmm... Is it realy json? doesn't this row make it to an array? var playerstats = val.resultSets[4].rowSet[0]
Comment: Try send array or other object, for example and check it in backend.
Comment: Try `data: { playerstats: playerstats }` instead.
Answer: When you are passing data as JSON.stringify(...) you are passing a string. I would suggest the following edit to the Action :
public void addBoxScore(string playerstats)
    {
       //Use a deserializing library to convert the string to a strongly typed class.
    }

You can use this library for deserialization.
Hope this helps!
Comment: If i do that playerstats will be null
Comment: As mentioned in the comments to your question, in order for the parameter to map itself to the action argument, you need to specify the name like so :- data: { playerstats: JSON.stringify(playerstats) }

send json object to mvc controller


UIImagePickerControllerDelegate not being called, selected image never displayed

Question: I'm stumped.  Everything is working except it's not.  I can call up the camera interface and take or select a photo yet UIImagePickerControllerDelegate is never being called (I've put two print statements that well, never get printed). Everything is correctly connected in IB, or so I believe it is (I'm fully ready for it so be something totally minor that I missed). Anyone care to take a frtesh set of eyes and go over this to see if I just can't see the forest for the trees?
Thanks in advance.
import UIKit
import Foundation

class afterPhotoViewController: UIViewController {

    //MARK: - IBOutlet Properties
    @IBOutlet weak var afterImageView: UIImageView!
    @IBOutlet weak var aftervwImage: UIView!

    @IBOutlet weak var cameraBtnPressed: UIButton!

    //MARK: - Useful Variables
    let afterImagePicker = UIImagePickerController()
    var hud = HKProgressHUD()
    var localTextFilePath : URL!
    var isImageSetted = false

    //MARK: - App Delegates
    var isMain = false
    var originFrame = CGRect()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Init UI Components
        self.initUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: - UI Init
    func initUI() {
        // Set Navigation Bar
        let backButton = UIBarButtonItem(title: "", style: .plain, target: navigationController, action: nil)
        navigationItem.leftBarButtonItem = backButton
        self.title = "\(h_proposalNumberStr)-\(h_itemIndex)"

        // Set ImageView
        self.afterImageView.image = #imageLiteral(resourceName: "ic_placeholder")
        self.afterImageView.clipsToBounds = false

        cameraBtnPressed.layer.cornerRadius = 15
        cameraBtnPressed.layer.borderColor = UIColor.lightGray.cgColor
        cameraBtnPressed.layer.borderWidth = 1

        self.isImageSetted = false

       // self.tableView.reloadData()

    }

    //MARK: - UI Actions
    @IBAction func cameraBtnPressed(_ sender: Any) {
        //Create the AlertController and add Its action like button in Actionsheet
        let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        }
        actionSheetController.addAction(cancelActionButton)

        let chooseLibraryActionButton = UIAlertAction(title: "Choose from Library", style: .default)
        { _ in
            self.isMain = true
            self.afterImagePicker.allowsEditing = true
            self.afterImagePicker.sourceType = .photoLibrary
            self.afterImagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
            self.present(self.afterImagePicker, animated: true, completion: nil)
        }
        actionSheetController.addAction(chooseLibraryActionButton)

        let takePhotoActionButton = UIAlertAction(title: "Take a Photo", style: .default)
        { _ in
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.isMain = true
                self.afterImagePicker.allowsEditing = false
                self.afterImagePicker.sourceType = .camera
                self.afterImagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .camera)!
                self.afterImagePicker.showsCameraControls = true
                self.present(self.afterImagePicker, animated: true, completion: nil)
            } else {
                Helper.showMessage(vc: self, title: CONSTANTS.APPINFO.APP_NAME, bodyStr: "No camera available.")
            }
        }
        actionSheetController.addAction(takePhotoActionButton)

        self.present(actionSheetController, animated: true, completion: nil)
    }

//MARK: - UIImagePickerControllerDelegate
extension afterPhotoViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("called")
        dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print("called2")
        //getting actual image
        var image = info[UIImagePickerControllerEditedImage] as? UIImage

        if image == nil {
            image = info[UIImagePickerControllerOriginalImage] as? UIImage
        }

            afterImageView.image = image
            // Set Imageview Corner Radius
            afterImageView.layer.cornerRadius = 5
            afterImageView.clipsToBounds = true

            self.isImageSetted = true

        picker.dismiss(animated: true, completion: nil)
    }
}

Comment: Delegate not set. Set afterImagePicker.delegate = self in viewDidLoad()
Comment: Ugh, insert massive ::facepalm::
Answer: @raja Kishan caught my stupid simple error of forgetting to set the delegate.
Now, where's the facepalm emoji.
Answer: You have to specify that the UIImagePickerController's delegate is self, so that the events are triggered.
In your case:
afterImagePicker.delegate = self


Overriding node-view-VIEWNAME.tpl problems

Question: Hello i am trying to override a node view without much success. I dont know if its just the syntax for my view thats wrong.
When i go to theme information the Row Style output tpl suggestion is
views-view-row-node--taxonomy-term--page-3.tpl.php
i can override that fine but it suggests it would be better to overide node-view-VIEWNAME.tpl.php
So i have a tpl file named
node-view-taxonomy-term-page-3.tpl.php
but it doesnt seem to want to override. Am i missing maybe a '-' somewhere in the tpl title?
I am using Views 3 and D6. I have the tpl in the same folder as my node.tpl.php
all help appreciated thanks.
Comment: Obligatory CTFC comment: Have you tried clearing the cache?
Comment: sorry aendrew yes i have cleared the cache a few times but to no avail. thanks
Comment: Some more info would be helpful -- what are you wanting to do? views-view-row-* does something much differently than node-view-taxonomy-term-*: the former themes a View row, the latter themes a taxonomy term page.
Comment: thanks for the reply aendrew. I want to theme the node output on one of my taxonomy views. You can view the view here http://onlinebanter.com/blogs I am trying to theme the Page: Theming information (row style) as with my theme the node view is a bit odd as you can see. Its geared towards the frontpage. I was hoping to make the 'node' full width in this view and not as it is. Im sorry if i sound a little confused as i am :(
Comment: What suggests it would be better to override Reg?
Comment: When i go to Theme Information in the view itself Alex under Row style output: views-view-row-node.tpl.php it says in there "Rather than doing anything with this particular template, it is more
 * efficient to use a variant of the node.tpl.php based upon the view,
 * which will be named node-view-VIEWNAME.tpl.php. "
Comment: and its that node-view-VIEWNAME.tpl.php that i cannnot override. Sorry if i am not being the most helpfull its just after 6 years at drupal im finally starting to get to grips with it. I just want to override the node tpl for this view and this view only. Have it full width etc with a teaser etc. tx
Comment: Reg, can you try the code below to see what templates are on offer?
Answer: The best way to do this is to see what your available theme suggestions are for that node.
In your theme add the following snippet and clear cache, refresh page, etc.
<code>function YOURTHEME_preprocess_node(&$vars) {
   var_dump($vars['template_files']);
   //dsm($vars['template_files']); // if devel module installed
}
</code>
Comment: @RegGordon -- FWIW, try the module [Devel Themer](http://drupal.org/project/devel_themer) if  you're doing a lot of theming. It's *super* useful for figuring template suggestions.
Comment: a bingo i think im there. i just copied my node tpl in there and changed a few classes. sorted. tx again folks.
Comment: thanks for your time alex. I have added the code to my template.php but i am getting a white screen now across my website. I renamed it to function journalcrunch_preprocess etc (name taken from my info file) also tried function phptemplate_ as per some of the other code in my template but still the white screen of death. I have Devel installed if that helps at all?
Comment: Updated answer, its because your on v6.
Comment: lol k tx brb Alex :leaving
Comment: a brilliant Alex i think we've got there. the tpl name i was after is node-view-taxonomy_term-page_3.tpl.php I think we control the horizontal and the vertical now. I will keep that wee snippet to hand also as i like what it tells me. Ive a lot of node theming to learn in the next few weeks. Again thank you very much :)
Comment: Your welcome, glad to help Reg :-)
Comment: Thanks aendrew i will the now. I am starting to pick all this up i think. I remember about 7 years ago saying to a collegue 'that css thingy might be important in styling' and look at me now. Actually back to this now ive overridden my template i dont know what to put in it. errrrrr
Comment: bah i suppose this is now a differant question to what i asked as that has been solved. Ive tried many a thing in my new template but im either getting a wsod or im getting no rows at all.mmmmmm


$m\mathbb{Z}\cdot \mathbb{Z}/n\mathbb{Z}$

Question: I'm trying to find the tensor product $\mathbb{Z}/m\mathbb{Z}\otimes \mathbb{Z}/n\mathbb{Z}$ using this theorem.
Now I know what the end product is (namely: $\mathbb{Z}/\gcd(m,n)\mathbb{Z}$) and I proved it differently. However,

how do I get that $m\mathbb{Z}\cdot \mathbb{Z}/n\mathbb{Z}\cong \gcd(m,n)\mathbb{Z}/n\mathbb{Z}$?
Comment: For my own learning, I am wondering what does $m\mathbb{Z} \cdot \mathbb{Z}/n\mathbb{Z}$ mean? It is not a tensor product?
Comment: @Mike $\{k\cdot l \mid k\in m\mathbb{Z}, l\in \mathbb{Z}/n\mathbb{Z}\}$
Answer: More generally, if $I$ and $J$ are ideals of the commutative ring $R$, we have
$$
I\cdot R/J=(I+J)/J
$$
The proof is easier to formalize in the more abstract setting and is a simple verification.
In your case $I=m\mathbb{Z}$ and $J=n\mathbb{Z}$, so
$$
I+J=m\mathbb{Z}+n\mathbb{Z}=\gcd(m,n)\mathbb{Z}
$$
Comment: @UnexpectedExpectation Let $x\in I$ and $y\in R$; then $x(y+J)=xy+J\in (I+J)/J$. Let $x\in I$, $y\in J$. Then $(x+y)+J=x+J=x(1+J)\in I\cdot R/J$.
Comment: Where can I find a proof for this general case?


Drupal alternative for prettyprinting SQL results?

Question: Drupal seems to do two main things:

Create SQL queries to pull data you want.
Site design, incuding prettyprinting SQL query results.

The problems:

It can't use existing SQL tables; it must import tables into its
own format.
Manipulating "Create View" to get the query you want can be
frustrating, especially if you already know the query! I realize you
can type in a query directly, but you're
really not "supposed" to do that.

I can create complexish SQL queries myself, so I really just need a
prettyprinter/site designer.
What product can prettyprint queries on existing tables? Example
queries (scroll to bottom of each page to see query):
http://798d4dab518a91787e0e0be5c94f8bb1.ccgames.db.94y.info/
http://57442d9ce4c5063869883519f2a9cd0f.ccgames.db.94y.info/
http://9160fe29e3da336652ec98fbf7f2aeef.ccgames.db.94y.info/
http://a782c6b9be09f375e5f1b1d69f1e7c62.ccgames.db.94y.info/
Of course, I'd like hardcoded strings (like 'barrycarter')
"templated". In other words "drupal.foo.com/?p=xxx" would run the
query w/ "xxx" instead of "barrycarter".
Thoughts? Any way to coerce Drupal into doing what I want?
See also: Converting constantly updated SQLite3 db into Drupal site
Answer: Look at the table wizard module. It lets you use existing / non-Drupal tables with views, including support for relationships between tables.
P.S: I 100% disagree with your assertions re: what drupal is.
Comment: Thanks. I'm aware of the 'data' module (which replaces table wizard), but Drupal folks say that it integrates poorly with Drupal, although this may be OK in my case. OK, from a techie viewpoint, what is Drupal? I could have it wrong.
Comment: It's a content management system. SQL is just the persistence layer, not the point of the app.


What is the frequency range of a typical subwoofer in a club PA?

Question: I am an amateur producer of techno music. Needless to say, low frequencies have a high importance to the sound in this genre. I have often read that generally in a final mix, very low frequencies should not have any stereo components, as there might be noticeably bad effects on club systems that mix them down to mono, or by interference. I have been doing that sort of intuitively around 150Hz--by placing an EQ on the master and have it cut any stereo content below that frequency--but I've been wondering if someone who knows about where the frequency splitter of such a system operates could come up with a guide value.
Answer: Getting 10 Hz lower on a sub can double the cost. So a lot of affordable subs really kick in around 50 Hz while the most expensive ones maybe get as low as 35 Hz or so. On the high end, the subs will usually be able to go up to 300 or 500 Hz but the actual crossover frequency used is determined by the whole system, usually between 150 and 250 Hz.
I would cut the low frequency content out of reverb sends and maybe delay sends, and 150 Hz is a good choice for that. I would also use sidechain eq for bass and drum compressors and cut below 150 to 250 out of the sidechain, or use parallel compression.
You should always check the entire mix for mono compatibility. And you should not mix with a specific crossover point for subs in mind. Don't cut everything below 150 for the whole mix. If that's what you're doing (it's not totally clear from your question) then you're throwing away some really important frequencies. Do cut everything below 40 Hz from the whole mix before you do any final compressing or limiting. If your whole mix works in mono, then you have done your job making it good for clubs. The rest is up to the design and engineering of the club sound system.
Comment: Thanks Todd! No, I'm not cutting everything below 150Hz, only the stereo content, so that below 150 the mix is mono (I have updated my question to clarify this). Would you say doing that is unnecessary, or can have unwanted side effects?
Comment: @speedymcs I don't quite understand the idea of part of a mix being in mono, unless you're doing LCR mixing. I think what you're doing is making sure all the low frequency items are panned into the center. There are some very important differences between panning center and a truly mono mix. You should **not** use some kind of processor to automatically pan everything below 150 to the middle. You **should** pan your bass, bass synth, and kick drums to the middle. You **definitely should** listen to your **whole mix** in mono to make sure it works. Clubs often have entire mono systems.
Comment: I am using Ableton Live 9. Its eight band EQ can be toggled to show/actuate on just the mono or just the stereo part of its input. So what I do is I put one on the master bus, set it to 'stereo only' mode, and cut out any residue in those freuquencies frequencies with a steep filter around 150 Hz.
Comment: @speedymcs I'm guessing you're referring to the mid/side (M/S) mode of EQ 8. What that does is let you separately EQ the in-phase and center panned (M or mid) content from the out-of-phase or side panned (S or side) content. Completely turning off all of the out-of-phase content will ensure mono safety of your mix, and getting rid of everything not phase correlated below 150 Hz is one way to ensure mono safety of the low end, but it's potentially the messiest way. You're also cutting the lows of anything panned off-center.
Comment: @speedymcs I would say what you are doing is a poor practice and you shouldn't do it. You should instead do the things I mention in my answer: 1) Pan low frequency sources to the center. 2) High pass reverb sends. 3) Forget about focusing on the low end and listen to the whole mix in mono to make sure the whole mix is mono safe. Only getting mono safety on the low end means you are risking having only the low end sound right.
Comment: "You're also cutting the lows of anything panned off-center." Yes that is exactly the point, to avoid any off-center content in the low frequencies. Now to be clear, the low end will be almost mono since I use mono bass synths and kicks--anything I remove will be residue, e.g. the low end of a stereo lead synth that wasn't high-passed steeply enough. Of course I would not use a stereo bass synth and cut out the stereo content. Now I think what you're saying is that I should ensure this by high-passing properly earlier in the chain?
Comment: Listening to the whole mix in mono makes sense, I agree, I use Ableton's Utility for that, with `Width = 0%`. Would you say that is suitable? I'm just not sure if I can properly judge mono safety on my headphones or loudspeakers, as the low end and any interferences there are so much more emphasized on a system with large subwoofers.


Prove that an even perfect square cannot have the form $4k+ 2$

Question: Using the conclusion of the proof that if $a\in\mathbb{Z}$ then a is even if and only if $a^2$ is even which is:
$$a^2 = (2j-1)^2 = 4j^2-4j + 1 =2(2j^2-2j) + 1 = 2K+ 1;K\in\mathbb{Z}$$
How do I Prove that an even perfect square cannot have the form $4k+ 2$ for $k \in\mathbb{Z}$?
Any help to point me in the right direction would be greatly appreciated!
Comment: Hint: factor out a "2" from the expression. The other number is even or odd?
Comment: What you have written in your post is a sketch of the proof that the square of an odd number is odd.  But what will be more helpful is to assume that $a$ is even, hence write it in a certain way, and then square that expression, and see what you get.
Comment: **Hint** $\ x^2$ even $\,\Rightarrow\, x\,$ even $\,\Rightarrow\,4\mid x^2,\,$ but $\,4\nmid 4k+2\ \ $
Answer: $4k+2 = 2 (2k+1)$. Since $2k+1$ is odd it doesn't have a factor of 2, so you cannot even write $4k+2$ as a product of two even numbers (so it can't possibly be a square of 2 even numbers).
Answer: Let the square root be $x$, we know that it is even.
If $x \equiv 0 \mod 4$, then $x^2 \equiv 0 \mod 4$.
If $x \equiv 2 \mod 4$, then $x^2 \equiv 4 \equiv 0 \mod 4$.


error C2011: '' : 'class' type redefinition

Question: One of the header files is as follows -
#include "stdafx.h"

class AAA
{
public:
    std::string strX;
    std::string strY;
};

When I try to compile the project, I get the error
error C2011: 'AAA' : 'class' type redefinition

Nowhere else in my program have I redefined the class AAA. How do I fix this?
Comment: You need to use include guards.
Answer: Change to code to something like this:
#ifndef AAA_HEADER
#define AAA_HEADER

#include "stdafx.h"

class AAA
{
public:
    std::string strX;
    std::string strY;
};

#endif

If you include this header file more than once in some source file, include guards will force compiler to generate class only once so it will not give class redefinition error.
Comment: AAA_HEADER is just unique string to identify the file. Read about include guards here http://stackoverflow.com/questions/8020113/c-include-guards
Comment: Is AAA_HEADER the AAA.h file?
Comment: The nice thing about this solution is that it will work for all C++ compilers, not just Microsoft's.
Answer: Adding
#pragma once

to the top of your AAA.h file should take care of the problem.
like this
#include "stdafx.h"
#pragma once

class AAA
{
public:
    std::string strX;
    std::string strY;
};

Comment: Should it be more likely at the very top of the file (at first line) not after some includes?
Answer: In addition to the suggested include guards you need to move #include "stdafx.h" out of the header. Put it at the top of the cpp file.
Answer: I met this problem today in VS 2017. I added #pragma once, but it didn't work until I added a macro definition:
    // does not work
    #pragma once

    // works with or without #pragma once
    #ifndef _HEADER_AAA
    #define _HEADER_AAA
    //
    // my code here....
    //
    #endif

I have no clue how to explain this, but it is a solution for me.
Answer: There are two ways to go about this but you can't use both. Make sure to wrap the class definition with a compiler directive that the class declaration only gets compiled once:
#include "stdafx.h"

#pragma once

class AAA{
public:
    std::string strX;
    std::string strY;
};

-or-
   #include "stdafx.h"

    #ifndef AAA_HEADER_
    #define AAA_HEADER_

    class AAA
    {
    public:

        std::string strX;
        std::string strY;

    };

    #endif

Also: note the class import statement should be at the top of your file.


How best to handle styles for nested h1's in html5?

Question: I'm currently working on some HTML5 themes for a few of my websites, and I keep running into problems with the way
's can be used multiple times. I can't seem to predict in what elements the headings will show up, but I do want to try and size them automatically based on their position in the DOM...
I was thinking about using something like
h1 { font-size: 3em; }
h2,
body > * > header h1 { font-size: 2.5em; }
h3,
body > * > header h2,
body > * > * > header h1 { font-size: 2em; }

But obviously that's far from waterproof. Having an extra element around an h1 that doesn't really mean it's deeper in the page structure will tend to pick way too small sizes. For example an unordered list with blocks that each have their own title will have something like

Title of a block

      content

Which makes the
 appear much deeper than it actually is. What are good ways to handle this?
Comment: They've changed the rules in HTML 5. Litso is using the correct choice of heading level for the language.
Comment: An H1 inside an H1 should still be an H1 with all associated formatting. Otherwise it should be an H2 or H3 or H4... What's the point in structure if you aren't going to follow it?
Comment: @Litso: so ,  doesn't increase the page deep, but which tag count? Can you list them all?
Answer: You should style the h1s based on the type of elements they are in, not just the depth.
For example, if you have general headings, article headings and sidebar item headings, you could do this:
h1 { font-size: 3em }
h2 { font-size: 2.5em }
article h1 { font-size: 2em }
article h2 { font-size: 1.5em }
aside h1 { font-size: 2.5em }

You would use whatever selector you use to select the articles or sidebar for layout (in my example, the article and aside tags, it might be section.sidebar or something else) to differentiate between different h1 tags.
There is not much of a connection between the depth of the tag, and the size (although there seems to be a pattern; deeper is smaller). There is however a connection between the convention used for marking up your sidebar, and the size of the headings in the sidebar. The CSS selectors for the headings will match up with the selectors for the layout, which shows the connection.
Comment: Fair enough. After making 3 or 4 HTML5 wordpress themes I've started to see patterns in the usage of articles, sections and asides and I think it's safe enough to use this approach as an initial styling. Some themes will differ a little, but at least this one lays a good foundation for most variants. Here, have a bounty.
Answer: Firstly I'm a little unsure why you would need a
section -> ul -> li -> header -> h1

Why not just
section -> header -> h1

It seems like an interesting way to set up your styles, but also confusing and possibly unnecessary. I mean HTML doesn't mean the end of class and id, why not use:
body section.class{}
body section.class header h1{}

Title

 <content>

Content

 </content>

  footer

Comment: I'd go farther and say there's no need for a 'header' element if you're only going to put a single child inside it.  'h1' is all you need.
Comment: The example I used comes from a wordpress theme. Wordpress often uses blocks in the sidebar that are constructed of an unordered list of widgets. Each widget has a title, and because each is a section of it's own it should have a `` or maybe a `` if the sidebar itself already has a title... And yeah, I'm currently working with classed but that means that for each template I'm building I have to define all the classes, where I could instead use a general stylesheet that calculates the heading sizes.
Comment: I agree reisio. However, in a lot of cases (wordpress posts/pages) I want some metadata in the header as well. But yeah, the sidebars could do without :)
Answer: It's not going to help you in any practical sense in the near future, but there is a proposal for CSS to make this sort of thing a bit cleaner, the any selector.  The general rule for a second level heading would go from this:
section section h1, section article h1, section aside h1, section nav h1,
article section h1, article article h1, article aside h1, article nav h1,
aside section h1, aside article h1, aside aside h1, aside nav h1,
nav section h1, nav article h1, nav aside h1, nav nav h1, {
  font-size: 20px;
}

To this:
any(section, article, aside, nav)
any(section, article, aside, nav) h1 {
  font-size: 20px;
}

Comment: Ahh, I remember reading about that! Sounds like the best solution so far :)
Answer: If you really can't tell where your h1 elements will appear you have a problem ...
You need to work into your stylesheets the places which affect the resolved level of the h1 in the outlining mechanism. These are the sectioning elements (article, aside, nav, and section) and the sectioning root elements (blockquote, body, details, fieldset, figure, and td)
The other elements don't affect the h1 level so they can be ignored, but might be wrappers like ul and li in your example so your css selectors should use descendent rather than child relationships.
Nevertheless, without building a stylesheet specifically for your page structure, the css rules set spirals out of control very quickly.
You want something like:
body h1 { font-size: 3em; }
body section h1 { font-size: 2.5em; }
body article h1 { font-size: 2.5em; }
body nav h1 { font-size: 2.5em; }
body aside h1 { font-size: 2.5em; }
body section section h1 { font-size: 2em; }
body section article h1 { font-size: 2em; }
body section nav h1 { font-size: 2em; }
body section aside h1 { font-size: 2em; }
body article section h1 { font-size: 2em; }
body article article h1 { font-size: 2em; }
  ...
  ...
  ...

And so on. Repeat for each sectioning root and for each of h1 to h6 and you have a massive css file.
Much easier if you know the structure of your page, at least for the sectioning and section root elements, then you can just write the rules for those combinations actually in use.
Comment: You can make the CSS slightly less complicated by comma-separating the selectors at the same level, though.
Answer: Firstly, according to the proper usage nested h1's should be treated exactly according to their significance of nesting (including article, aside, nav, section but not any other elements). This is correct behavior. An h1 nested inside a section element should be the same visually as an h2, and an h1 nested inside two section elements should be visually the same as an h3... Basically, in short, there's an alternative markup floating around that pretty much no-one uses but is really more semantically consistent which is to only use h1 ever, and allow the level of heading to be determined by the document outline.

authors are strongly encouraged to either use only h1 elements, or to
  use elements of the appropriate rank for the section's nesting level.
  per Section 4.3.11 of WHATWG

So, I believe you're on the right track with wanting this and I think the chosen correct answer is giving you subjective stylistic advice rather than attempting to answer your question, which is a valid one.
As far as implementation:
For webkit browsers (chrome and safari) and firefox you can use the "-moz-any" and "-webkit-any" css pseudoselectors. This is, in fact, how the default stylesheets in firefox and chrome style these elements perfectly according to the standards already:
For example, at level 3 headings in the firefox default css:
h3, *:-moz-any(article, aside, nav, section) *:-moz-any(article, aside, nav, section) h1 {
    display: block;
    font-size: 1.17em;
    font-weight: bold;
    margin: 1em 0;
}

This greatly simplifies the answer @Alohci rightly suggested.
The problem is, of course, it wont work in IE. One option is to use a CSS pre-processor, such as SASS. I have written the following snippet in SASS which I use to do my header markup and which I use to effectively normalize across browsers the presentation of nested h1 elements. (If you don't want to actively use a CSS pre-processor you can use one a single time to generate your initial template for these values and then modify the values as needed over time -- it will at least save you tons of typing and eliminate potential errors in the process):
@function bb_permute_lists($left_list, $right_list) {
    $permuted_list: ();

    @each $left_item in $left_list {
        @each $right_item in $right_list {
            $permuted_list: append($permuted_list, $left_item $right_item, comma);
        }
    }

    @return $permuted_list;
}

@function bb_html5_header_markup($level) {
  @if (1 == $level) {
    @return h1;
  }

  $header_containers: article, aside, nav, section;
  $header_markup: $header_containers;
  @for $i from 2 to $level {
    $header_markup: bb_permute_lists($header_containers, $header_markup);
  }
  $header_markup: bb_permute_lists($header_markup, h1);

  @return append(h#{$level}, $header_markup, comma);
}

This function can be used as follows:
#{bb_html5_header_markup(1)} {
  font-size: 2em;
    margin: .67em 0;
}

#{bb_html5_header_markup(2)} {
    font-size: 1.5em;
    margin: .83em 0;
}

Best of luck in trying to implement this alernative standard. There's plenty of documentation out there about this alternative and more-semantic usage of h1, but based on the fact that I could not find anyone else with a code snippet to help me along in implementing it, I think it's rather rarely used (perhaps because people are working with a lot of mixed content, whereas I am starting from scratch).
Comment: Unfortunately, this attempt has failed: [At some point we cannot claim that user agents are broken. They are instead rejecting our change request.](https://github.com/whatwg/html/issues/83#issuecomment-136883781)
Comment: And because the attempt has failed, the recommendation should now read: *"authors are strongly encouraged to use elements of the appropriate rank for the section's nesting level."*. It's too bad really but we may get a generic `` element one day to achieve what we wanted from the document outline.
Answer: HTML5 is supposed to make coding simpler and IMO you are taking the header and h1 thing way to far. They are both header tags so spamming both of them all over you page is just redundant.
A page should only have 1
 tag, to show what the entire page is about, each section does not need an h1 tag like I said above
Regardless the easiest way would be to use classes and IDs, just like in the past.

Title of a block

      content

Then you can remove all the extra selectors and they can be more generic.
section.widget h1 { }
section.something h1 { }

Comment: It has never been true that a page should only have one H1 tag, and with the new rules in HTML5 even less so. Anyway, I think you (and the others) are right about the classes/ID's. I hoped to be able to do it more dynamically (see robertc's answer) but that's just not going to happen yet.
Comment: If you read the HTML spec, you'll see that the headers H1 ... H6 essentially only describe their relative importance in sectioning the content. There's nothing in the spec that requires you to have only one H1. For search engine optmization and marketing purposes it's useful to have only one H1, but Google et. al. can certainly successfully spider pages with multiple H1s with no problem.
Comment: "It has never been true that a page should only have one H1 tag" -- really? Where are you getting this from?
Comment: In fact in new HTML5 it is explicitly allowed to have multiple `h1`s... They tried to make `h1` into a 'relative heading' element, which would become smaller as you go deeper into the document tree. So `h1` at the body level would be largest, `h1` within `article` would be smaller and `h1` within a `section` within a `article` would be smallest still. However, both W3C and WhatWG have now come to the conclusion that their efforts failed and basically the outlining algorithm is dead in the water. So it's back to `h1` ... `h6`.
Comment: The more important rule is: 'don't skip heading levels'. So if you have `My bookChapter 1` don't skip `h3` and suddenly go to `h4`. But you can use multiple `h1`s just fine. In fact, if you want to do this right, look into the definition of the `main` element... It defines the pages 'main' content and it may appear only once. So place your 'main' `h1` inside `main` and you are free to use `h1` again within `aside`, `article` etc.
Answer: Another thing you could do would to use an id on the
 tag. For example, your HTML would be:

My Blog

And then in your CSS, you could use:
h1#page-title { font-size:2.5em; color:#f00; [etc] }
Update: It just got mentioned to me that this may be irrelevant info, so here's my two bits: so the nested
 isn't styling properly? This is how I'd fix it, by making it a unique identifier rather than specifying it with each nested tag.
Comment: Though irrelevant to original question; it should be `h1#page-title` not `h1 #page-title`  # before 2.5em is not a valid value.


Views Slideshow Stops Working Alongside Other Slideshows

Question: I've made several thumbnail-sized cycle slideshows as block views, which display fields from nodes created via an HTML feed. Each slideshow is basically the same, but they all use a different taxonomy term as a filter on a single content type, and have a different XPath parsing structure.
The slideshows work perfectly on each view's preview page. Each also works separately when its block is displayed on the main page. I've managed to get 6 slideshows at once scrolling normally as blocks on the main page.
However, when I display a 7th slideshow in a block on the main page, only two slideshows work properly, with the rest not progressing via time or clicking on the controls. If I add an 8th slideshow block, 3 of them work, and the other 5 do not.
The 7th and 8th slideshows have slightly different field output, as the feed source is configured differently, but I don't think this is relevant, as the view-generated HTML looks the same.
I can get sporadic results by re-arranging the blocks in the block list, and by displaying them in different block areas. Some permutations allow all the slideshows to function, some only allow a few.
Is there a limit to the number of JQuery slideshows that can be running at once? Or, is there maybe some kind of naming convention that's causing these mixed results with different ordering?
Totally confused, and disappointed. :(
Answer: After some inspired messing around, I determined that the issue only stopped slideshows that were displayed after a certain slideshow. Using that information, I deleted the isolated block, and re-created it in the same form as the other slideshows.
This appears to have solved the problem. I guess something was corrupt with that particular view. It was the one I was originally using as a clone base for all the other slideshow blocks.
Hopefully this "fix" persists!


Replace elements in Pandas column which have a distance measure greater than a threshold

Question: Consider a dataframe :
company  |  label

  comp1       fashion
  comp2       fashionitem
  comp3       fashionable
  comp4       auto
  comp5       autoindustry
  comp6       automobile
  comp6       food
  comp7       delivery

I want to clean-up the labels a bit, and I am using a string distance for that:
from difflib import SequenceMatcher

def distance(a, b):
    return SequenceMatcher(None, a, b).ratio()

The question is, how can I write a function that applies the distance function between any two elements on the label column and, at the end, replaces all similar elements (distance above a certain threshold) with the shortest string?
The result should be something like:
company  |  label

  comp1       fashion
  comp2       fashion
  comp3       fashion
  comp4       auto
  comp5       auto
  comp6       auto
  comp6       food
  comp7       delivery

I am thinking of performing 2 for loops, but my dataset may be quite large, is there an efficient way of doing this?
EDIT: While reading the below replies, I realize I made a mistake. The overall number of entries (number of companies) is large, BUT the overall number of unique labels is small, less than 1000. One could apply df.label(unique) and work with that, I guess.
Comment: How large is your dataset?
Comment: @Erfan right now it "only" has around 500k entries, but I think it could go to maybe 2-3 million entries in total.
Comment: Are you willing to accept approximate solution, the exact solution would take 500_000 ^ 2 operations at least. Does the similar elements always share a common prefix?
Comment: @DanielMesejo, I would love to have an exact function, that works for a small number of different labels as well (  < 1000). I made a correction in the question above, as I realize the number of different labels is small.
Comment: In your above example fashion, fashionable, fashionitem form a cluster therefore all of them must be replaced by the one shortest of them?
Comment: @DanielMesejo yep.
Comment: [This fuzzy_merge](https://stackoverflow.com/questions/13636848/is-it-possible-to-do-fuzzy-match-merge-with-python-pandas/56315491#56315491) function I wrote can help you. I came quite close, but couldn't get your exact expected output. Start of with a self join `fuzzy_merge(df, df, 'label', 'label', threshold=50, limit=5)` and proceed from there. Also play around with the `threshold` argument
Answer: Idea
The idea for this approach is to build an adjacency matrix from the threshold (ed) ratio matrix. From the adjacency matrix build a graph, and from it get the connected components (clusters). Getting to the desired output can be tricky, but it can be achieved with an (absolute) threshold of 0.49.
Setup
from difflib import SequenceMatcher

import networkx as nx
import numpy as np
import pandas as pd

df = pd.DataFrame(data=[['comp1', 'fashion'],
                        ['comp2', 'fashionitem'],
                        ['comp3', 'fashionable'],
                        ['comp4', 'auto'],
                        ['comp5', 'autoindustry'],
                        ['comp6', 'automobile'],
                        ['comp6', 'food'],
                        ['comp7', 'delivery']], columns=['company', 'label'])

def distance(a, b):
    return SequenceMatcher(None, a, b).ratio()

Code
# get unique labels
labels = df['label'].unique()

# compute ratios
result = np.array([[distance(li, lj) for lj in labels] for li in labels])

# set diagonal to zero
result[np.arange(8), np.arange(8)] = 0

# build adjacency matrix
adjacency_matrix = (result > 0.49).astype(int)

# create graph
dg = nx.from_numpy_array(adjacency_matrix, create_using=nx.Graph)

# create mapping dictionary from connected components
mapping = {}
for component in nx.connected_components(dg):
    group = labels[np.array(list(component))]
    value = min(group, key=len)
    mapping.update({label: value for label in group})

result = df.assign(label=df.label.map(mapping))

print(result)

Output
  company     label
0   comp1   fashion
1   comp2   fashion
2   comp3   fashion
3   comp4      auto
4   comp5      auto
5   comp6      auto
6   comp6      food
7   comp7  delivery

Comment: Seems to work well for a thresh of 0.8. I will accept this answer, thanks.
Comment: Sounds like an interesting approach, but I have applied it to my actual dataframe and get the label 'TV" for everyone on the new column.
Comment: What threshold did you use?
Comment: 0.49, and it returns "vi" and 0.60 returns "tv". Don't really understand why.
Comment: Try to see what are the values of component, by what you say it seems there is only one connected component.


How to configure multiple laravel projects on local server (Apache, Ubuntu 16.04)

Question: In our local network we are connected to an Ubuntu 16.04 server (Apache). We connect to it through local ip: 10.0.x.x and the default apache config serves whats inside /var/www/html, I have tweeked the config to serve /var/www/app-1 so when I visit 10.0.x.x I got my app running, I was wondering how to make the apache serve other apps like /var/www/app-2 and I maybe visit 10.0.x.x/app-2. I know how to configure this live with domains as I point the domain 'serverName' to the rootDocument I want, but now this is local server and no domains, how to get this done?
Comment: As you are working locally, you can use run multiple laravel app in different ports.
Answer: Edit your httpd.conf like this:
<VirtualHost _default_:80>
        DocumentRoot "/var/www/app-1"
        ServerName web1.example.com:80
        ServerAdmin firstname.lastname@example.com
</VirtualHost>
<VirtualHost _default_:80>
        DocumentRoot "/var/www/app-2"
        ServerName web2.example.com:80
        ServerAdmin firstname.lastname@example.com
</VirtualHost>

Comment: And edit your /etc/hosts files if you don't want to run a local network name server.
Answer: Okay, I found Apache virtual hosts on digitalocean.com
And step 6 is what I needed 'that case I don't need actual domains'.


What are the official modes from Ionian to Locrian?

Question: I am having some confusion is respects to the formal definition of what the various modes are. I know that their defined in relation to their scale, however, I've come to realise this may not be best way to define it.
For instance, the Phrygian mode of the minor scale is the major mode, as follows:
 T ST T T ST T T

      T T ST T T T ST

The Aeolian mode of the Major scale is also the natural minor scale.
However, because these two scales are one of the same, they have the same modes. However, the 'Dorian' mode of each scale is different, so is the Phrygian mode, and so on. Thus we could say we have 14 modes, but only 7 are unique. So what is the official status quo on this?
Also, I know that there are other modes which have a completely different arrangement, but the major and minor modes or scales, at least is respects to Western culture, dominant at least 95% of music, likely more (that's also accounting for the 7 modes, not just the natural minor/major scales). And as the two are the same, this is way I was wondering if there is a formal definition of the unique modes.
To those scales which are unique, would the modes that are then formed be given the same titles as the modes of the major/minor scale?
If I may ask another but related question - I hear there are many, many modes out there, but how many are actually unique? As an ambiguous example, say there were 1000 out there, only say, maybe 50 of them could be unique. By the way, by unique, I mean in the sense that they have a different sequential arrangement of semitones, but if two modes share the same sequence, regardless of order, then their combined total of modes is equal to the sum of just one of the original modes.
Comment: There is no such thing as "the Phrygian mode of the minor scale". [Phrygian](http://en.wikipedia.org/wiki/Phrygian_mode#Modern_Phrygian_mode) (in the modern sense) is a fixed diatonic mode. You can't simply start any scale on the third note and call it Phrygian.
Answer: You kind of have a skewed view of what modes actually are. The modes we name are set constructs, not based on if you build on any degree on any scale. The third scale degree is only Phrygian in Ionian(major). The scale built on the third of Aeolian(minor) is Ionian(major). The Phrygian mode does exist in Aeolian mode, but is built off scale degree 5 as building it off that would create the scale pattern we know as Phrygian.
To demonstrate this let's look at all the modes that exist naturally in the standard C major scale:

C Ionian        C   D   E   F   G   A   B   C
D Dorian        D   E   F   G   A   B   C   D
E Phrygian      E   F   G   A   B   C   D   E
F Lydian        F   G   A   B   C   D   E   F
G Mixolydian    G   A   B   C   D   E   F   G
A Aeolian       A   B   C   D   E   F   G   A
B Locrian       B   C   D   E   F   G   A   B

As you can see, they all contain the exact same notes and if we line them up, you can actually see how they relate.

C Ionian        C   D   E   F   G   A   B   C
D Dorian            D   E   F   G   A   B   C   D
E Phrygian              E   F   G   A   B   C   D   E
F Lydian                    F   G   A   B   C   D   E   F
G Mixolydian                    G   A   B   C   D   E   F   G
A Aeolian                           A   B   C   D   E   F   G   A
B Locrian                               B   C   D   E   F   G   A   B

So no matter how you arrange the notes above you get only 7 modes as the pattern is what defines what mode is not what relative scale degree you are building off of.
There does exist more exotic modes based off of variations we make to the natural scale and the same idea applies where there exists one pattern per scale degree. For example, the modes based of the harmonic minor scale are:

A   B   C   D   E   F   G#  A
B   C   D   E   F   G#  A   B
C   D   E   F   G#  A   B   C
D   E   F   G#  A   B   C   D
E   F   G#  A   B   C   D   E
F   G#  A   B   C   D   E   F
G#  A   B   C   D   E   F   G#
A   B   C   D   E   F   G#  A
B   C   D   E   F   G#  A   B

I did not name these because most of them don't have official names although it is rather easy to derive it using the modes we already know and accidentals.
Comment: Ahhh, I see, so the official title given to those modes are those that originate from the major scale. See, my confusion at first was defining what  a scale and what a mode is, then I learned that it's just a tautology (the same), and as you can see from my question I came to further realisations. Though I did not know that the major scale was the starting point with which other modes were built, so thank you for clearing that up! ^.^
Answer:
I am having some confusion is respects to the formal definition of what the various modes are. I know that their defined in relation to their scale, however, i've come to realise this may not be best way to define it.

Modes are not defined by how they are related. Modes are defined by their interval pattern, by how they are constructed. There are different ways to represent that construct, you used one of them to represent the minor scale, as a string of tones and semi-tones:
T ST T T ST T T
And that's how the modes are defined, by their construction, by their formulas, by how they are built. In your example above you just defined the minor scale. That's the form of the minor scale, it can't have any other or it would be another scale, another mode.
Before continuing, it's very important to note that major scale and Ionian mode are synonyms, they refer to the exact same thing. Minor scale and Aeolian mode are synonyms too. Keep this in mind. (you seem to think that they are different things)
Here are the definitions of the 7 modes. I'll include the definition as intervals in relation to the root and as tone and semi-tone steps (like in your examples). I'll also include an example with C as root.

    R = root, M = major, m = minor, T = tone, S = semi-tone

Lydian:

    R  M2 M3 A4 P5 M6 M7 P8
    C  D  E  F# G  A  B  C
      T  T  T  S  T  T  S

Ionian:

    R  M2 M3 P4 P5 M6 M7 P8
    C  D  E  F  G  A  B  C
      T  T  S  T  T  T  S

Mixolydian:

    R  M2 M3 P4 P5 M6 m7 P8
    C  D  E  F  G  A  Bb C
      T  T  S  T  T  S  T

Dorian:

    R  M2 m3 P4 P5 M6 m7 P8
    C  D  Eb F  G  A  Bb C
      T  S  T  T  T  S  T

Aeolian:

    R  M2 m3 P4 P5 m6 m7 P8
    C  D  Eb F  G  Ab Bb C
      T  S  T  T  S  T  T

Phrygian:

    R  m2 m3 P4 P5 m6 m7 P8
    C  Db Eb F  G  Ab Bb C
      S  T  T  T  S  T  T

Locrian:

    R  m2 m3 P4 d5 m6 m7 P8
    C  Db Eb F  Gb Ab Bb C
      S  T  T  S  T  T  T

So, if a scale has the form: R m2 m3 P4 P5 m6 m7 P8 (which can be also represented as S T T T S T T), it is the Phrygian mode.
For example: the scale D E F# G A B C D has the form R M2 M3 P4 P5 M6 m7 P8 (which can also be represented as T T S T T S T). This matches the description of the Mixolydian mode, so that scale (mode) is D Mixolydian.
As you can see, we don't need to know the relationship between the modes to define them.

For instance, the Phrygian mode of the minor scale is the major mode

That's incorrect. The Phrygian mode and the major scale have two different constructs, they are two different modes. We now know that each mode has a very specific definition, a very distinct construct.
This is your example:
T ST T T ST T T
     T T ST T T T ST

The upper scale is the minor scale (also known as Aeolian mode), and the lower scale is the major scale (Ionian mode). In your example the Phrygian mode would be found (and derived) from the 5th degree of the upper scale.
T ST T T ST T T             <- minor (Aeolian)
     T T ST T T T ST        <- major (Ionian)
         ST T T T ST T T    <- Phrygian

However, because these two scales are one of the same, they have the same modes. However, the 'Dorian' mode of each scale is different, so is the Phrygian mode, and so on. Thus we could say we have 14 modes, but only 7 are unique. So what is the official status quo on this?

Using the construction formulas of this answer, we can derive 7 modes only. The modes that you derived from the minor and major scales are exactly the same. Those 7 modes can be derived from any other mode. They all contain each other (but again, that's not how they are defined).
You are confusing degree with mode. That's why you think the Dorian mode is different, because while every mode contains the other modes, the position of the modes within a mode changes. The Dorian mode is not changing, it is just somewhere else, in other position:

    C D E F G A B C      <- C Ionian
      D E F G A B C D    <- D Dorian

In this case we found the Dorian mode if we start the scale in the second degree of the Ionian mode (remember, Ionian mode and major scale are the exact same thing).

    C D Eb F G Ab Bb C          <- C Aeolian
           F G Ab Bb C D Eb F   <- F Dorian

In this case we found the Dorian mode if we start the scale in the fourth degree of the Aeolian mode (remember, Aeolian mode and minor scale are the exact same thing).

To those scales which are unique, would the modes that are then formed be given the same titles as the modes of the major/minor scale?

We know that we can derive the 7 modes from one mode, depending on which degree we start the scale in. We now know that all those 7 modes are unique, and have a very specific definition in their construction, in their formulas. We now know that major scale and Ionian mode are synonyms, and that minor scale and Aeolian mode are synonyms too.

If I may ask another but related question - I hear there are many, many modes out there, but how many are actually unique?

All of them are unique. You might find synonyms (as we found with minor = Aeolian and major = Ionian), but the mode is defined by its construction, the name is only a reference to that construction.
Answer: It's difficult to add to the excellent answers already, but another way to see the modes is in a circular fashion. Can't do it here, but if the 7 notes (Like Dom and JCPedroza, I'll be in C),are written around a circle, the modes in note names will be easily read off as you go round.Keep going clockwise, and each letter name will give the next mode, in order - C Ionian, D Dorian, E Phrygian, F Lydian, G Mixolydian, A Aeolian and B Locrian. The notes for each are the other letter names. For the other 11 keys, write the notes in similar fashion round a cirle, so Eb would be Eb, F, G, Ab, Bb, C and D. From that F Dorian will be the sequence of notes starting on F.
Answer: I know its been a while, but I'd like to answer this using a different approach, although the current answers are technically remarkably well constructed.

I know that their defined in relation to their scale.

That is not entirely true. There are two ways to view modes, depending on how you want to use them. I will avoid the pattern approach because I think its more important to understand what Modes are supposed to do and how to use them before attempting to nail down a definition. I assume you know what all the Major Scales are and how to derive them. I also assume you know what a key signature is distinct from a root note.
For reference purposes in the examples, the 12 Major Scales are listed below.
A Major:    A   B   C♯  D   E   F♯  G♯
B♭Major:    B♭  C   D   E♭  F   G   A
B Major:    B   C♯  D♯  E   F♯  G♯  A♯
C Major:    C   D   E   F   G   A   B
D♭Major:    D♭  E♭  F   G♭  A♭  B♭  C
D Major:    D   E   F♯  G   A   B   C♯
E♭Major:    E♭  F   G   A♭  B♭  C   D
E Major:    E   F♯  G♯  A   B   C♯  D♯
F Major:    F   G   A   B♭  C   D   E
F♯Major:    F♯  G♯  A♯  B   C♯  D♯  F
G Major:    G   A   B   C   D   E   F♯
A♭Major:    A♭  B♭  C   D♭  E♭  F   G

Given a Major Scale key sigature, you may want to -
1) change the root note (key signature), but keep the notes of the orignal scale.
2) keep the root note (key signature), but change one or more notes in the scale.
In this example we will use the C Major Scale and the Dorian mode.
The notes in the C Major scale are: C D E F G A B
The Modes are, for each note position:
Ionion Dorian Phrygian Lydian Mixolydian Aeolean Locrian

In case 1) above, we change the root note from C to D, so the D Dorian mode is: D E F G A B C
All the C Major scale Modes are:
C     Ionian: C D E F G A B
D     Dorian: D E F G A B C
E   Phrygian: E F G A B C D
F     Lydian: F G A B C D E
G Mixolydian: G A B C D E F
A    Aeolean: A B C D E F G
B    Locrian: B C D E F G A

As shown above, you can keep the C Major scale, but change its root. Changing the root does not change the scale, so D Dorian is not the D Major scale (D E F# G A B C#), but the D rooted C Major scale. Only the Ionian Mode is identical to the Major Scale because it is the scale's first position which defines its key, so D Ionian Mode is the D Major scale.
There are 12 Dorian Modes, one for each Major scale, but only one D Dorian Mode. The Mode notes are defined by the Major Scale of that note in that scale's position. So D Dorian Mode is the Major Scale with D in the 2nd position, which is the C Major scale.
A Similar method applies to all other modes. There are 12 Phrygian Modes, only one is D Phrygian and that is Bb(or A#) Major with D in the 3rd position (B♭ C D E♭  F G A). Also C Dorian is the same Bb Major scale, but with C root, not D. So C Dorian and D Phrygian are Modes of the Bb Major Scale that root it in C (2nd) and D (3rd), in the same way D Dorian and E Phrygian are Modes of the C Major scale and root it in D (2nd) and E (3rd).
In case 2) above, we keep the root note C and find another major scale with C in the Dorian, or 2nd position. This is Bb (or A#) Major, and that scale, starting from C, is: C D Eb F G A Bb
The C Modes are C Ionian (C Major), C Dorian (Bb Major), C Phrygian (Ab/B# Major), C Lydian (G Major), C Mixolydian (F Major), C Aleolian (A Minor), and C Locrian (Db/C# Major).
It is also possible to change up to six notes of the C Major scale. Whether accidently, or intended, each note can be found in all seven positions and only in seven of the 12 Major Scales. Thus, the C note can be found in seven scales at a different position. So, we don't actually change any notes, we find a major scale that has our key and the changed notes. The Bb Major scale has C in the second position with the E and B notes changed to Eb and Bb. Thus, C Dorian is equivelant to the C Major scale with a flattened E and B, but is actually the Bb Major scale with a D root.
Below is a list of all the C Modes (i.e. all Major scales rooted in C), in lowered pitch and increasing note change order, with the actual Major scale in (Brackets):
(G M)    Lydian: C  D  E  F# G  A  B  [  ] 0
(C M)    Ionian: C  D  E  F  G  A  B  [F ] 1
(F M)Mixolydian: C  D  E  F  G  A  Bb [Bb] 2
(BbM)    Dorian: C  D  Eb F  G  A  Bb [Eb] 3
(EbM)   Aeolian: C  D  Eb F  G  Ab Bb [Ab] 4
(AbM)  Phrygian: C  Db E  F  G  Ab Bb [Db] 5
(DbM)   Locrian: C  Db Eb F  Gb Ab Ab [Eb] 6

So, the C Lydian Mode is actually the G Major scale with C in the 4th position and can be used to change the key from G to C in G Major, or, for the C Major scale, used to change F to F#. Although the actual C Lydian Mode is specifically the notes given as listed above, its meaning depends on what changes it makes to your scale. And this, I suspect, is what creates the confusion.
C Lydian is G Major (with C root), but is associated with the C Major scale because it has the same key. So while C Lydian is not derived from C Major it is frequently used with it because the two scales are so similar. In contrast, C Locrian is derived from Db/C# Major scale and only has 2 notes (C and F) in the C Major scale and yet is still associated with it because it has the same key.
It is the way in which the major scales are reordered that the Modes establish the association between scales and enables composers, improvs, and Jazz performers to switch between scales, playing all the 12 notes and yet sounding like a seven note octave with subtle and not so subtle pitch changes, tweeking a mood the scale sets with one or more Modes.

If I may ask another but related question - I hear there are many, many modes out there, but how many are actually unique?

The Modes are generated from the scale, so you will be able to derive all modes from any pattern distinct from the Major/Minor by following the same formulas applied to the Major pattern. For example, the pentatonic scale (five note scale), will likewise have 4 key changes, and 4 note changes, which will be the pentatonic Modes. However, I don't think they have official names, so you can make them up, using the naming convention used for the Major scale. So, just as you can have many unique patterns, the modes will be similarly all unique.
Comment: I am not following you here; you say "I also assume you know what a key signature is distinct from a root note." Then you say "change the root note (key signature), but keep the notes of the original scale." You can't have it both ways. Changing the key signature means changing the notes of the scale. If you ascribe a key signature to D Dorian, it would be C Major since these two note collections share the same notes (but different "root notes"). I usually favor using a key signature of D Minor for something in D Dorian, and then write the accidentals.
Comment: I wasn't clear on that, which is why you got confused. We're not changing the notes, only the order. You said it better and used root in the same way I intended. C Major is the obvious signature,  but I suppose any D scale would be okay.


Mixed effects/nested model giving different EMS tables in R and Minitab, and I believe Minitab is incorrect. Anyone know why it would be wrong?

Question: I have a dataset at https://docs.google.com/spreadsheets/d/1PB_S7oX2Tqgz_BEUUcHfLOww0cNJ-IgN6B34UTequlw/edit?usp=sharing that shows a mixed model where Machine and Station are fixed effects and Power is a random effect. Power is also nested within Machine.
I have run this in R using gad and it produced some results I expected when I calculated by hand:
machines$machine_f <- as.fixed(machines$Machine)
machines$station_f <- as.fixed(machines$Station)
machines$power_r <- as.random(machines$Powre)
mod <- aov(Value^2~power_r%in%machine_f+machine_f*station_f+power_r%in%machine_f*station_f, machines)
gad(mod)

OUTPUT
Analysis of Variance Table

Response: Value^2
                            Df  Sum Sq Mean Sq  F value    Pr(>F)
machine_f                    2   77867   38933   0.0392  0.962068
station_f                    2   62646   31323   1.6142  0.274835
power_r:machine_f            3 2981661  993887 183.8735 < 2.2e-16 ***
machine_f:station_f          4   63673   15918   0.8203  0.556701
power_r:machine_f:station_f  6  116427   19405   3.5899  0.006841 **
Residual                    36  194590    5405
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

#generate the EMS table
estimates(mod)

$mse
                            Mean square estimates
machine_f                   "Res + power_r:machine_f + machine_f"
station_f                   "Res + power_r:machine_f:station_f + station_f"
power_r:machine_f           "Res + power_r:machine_f"
machine_f:station_f         "Res + power_r:machine_f:station_f + machine_f:station_f"
power_r:machine_f:station_f "Res + power_r:machine_f:station_f"
Residual                    "Res"

And then I do it Minitab using Stat -> ANOVA -> General Linear Model -> Fit General Linear Model
Then, in the random/nested menu I put Power nested in Machine, and select Power as Random. I fit it using lambda=2 in the box-cox transformation to get y^2, and then it produces these results:
Analysis of Variance for Transformed Response

Source                    DF    Seq SS      Contribution    Adj SS     Adj MS   F-Value P-Value
Machine                    2    77867       2.23%           77867      38933    0.04    0.962
Power(Machine)             3    2981661     85.27%          2981661    993887   51.22   0.000
Station                    2    62646       1.79%           62646      31323    1.61    0.275
Machine*Station            4    63673       1.82%           63673      15918    0.82    0.557
Station*Power(Machine)     6    116427      3.33%           116427     19405    3.59    0.007
Error                     36    194590      5.56%           194590     5405
Total                     53    3496863     100.00%

And for the EMS table:
Expected Mean Squares, using Adjusted SS
Source                         Expected Mean Square for Each Term
1   Machine                    (6) + 3.0000 (5) + 9.0000 (2) + Q[1, 4]
2   Power(Machine)             (6) + 3.0000 (5) + 9.0000 (2)
3   Station                    (6) + 3.0000 (5) + Q[3, 4]
4   Machine*Station            (6) + 3.0000 (5) + Q[4]
5   Station*Power(Machine)     (6) + 3.0000 (5)
6   Error                      (6)

Now, the only differences between these two tables is the factor of Power nested within Machine. This means that Minitab and R are consistently using a different denominator for multiple other effects, but Minitab seems to miscalculate the nested effect. I have done this multiple times in R and Minitab rearranging the factors in both to determine if the EMS was shifting due to that, but that was not the problem.
The EMS table provided by R matches up with the work I did by hand, so I am almost certain Minitab is incorrect here. I am also almost certain there is probably something in Minitab I can do to correct this. Does anyone know how I can work in Minitab to produce the correct EMS table with the correct F test? Or will I have to do this in R because this is a shortcoming for Minitab?
Comment: Non-obvious differences in mixed-model assumptions can make a difference in the denominator for some F-tests (arising from the way Expected Mean Squares are computed). // Maybe google 'restricted' vs. 'unrestricted' model. Often one of the two is the 'default' for a software program. (I seem to recall Minitab changed it's default a few years back.) // When such differences btw software programs persist it is because there is controversy as to which method is correct in which circumstances. // Maybe worth noting for your data that both programs find same 2 interaction effects to be significant.
Answer: I think the reason why Minitab is giving you a different EMS than R is because it's either using a restricted mixed model or unrestricted mixed model. I'm not sure if R is using a restricted model or unrestricted model, but whatever it's using, Minitab is using the opposite. I'd say play around with Minitab and see if you can switch from restricted to unrestricted mixed model and see what you get...
-Amateur student in biostatistics