Como recuperar o `mysqli->insert_id` de dentro desta função, além do retorno da query?

Question: public function executar($sql){

    $con = new conexao();
    $con->abrir();
    $re = $con->mysqli->query($sql);

    // Preciso retornar esta informação tambem:
    $last_id = $con->mysqli->insert_id;

    $con->fechar();
    return $re;
}

function inserir($tabela,$dados){

    $arrCampo = array_keys($dados);
    $arrValores = array_values($dados);
    $numCampos = count($arrCampo);
    $numValores = count($arrValores);
    if($numCampos == $numValores){
        $SQL = "INSERT INTO " .$tabela." (";
        foreach($arrCampo as $campo){
            $SQL .= "$campo, ";
        }
        $SQL = substr_replace($SQL, ")", -2, 1);
        $SQL .= "VALUES (";
        foreach($arrValores as $valores){
            $SQL .= "'".$valores."', ";
        }
        $SQL = substr_replace($SQL, ")", -2, 1);
    }else{
        echo "Erro ao verificar campos";
    }
    $this->executar($SQL);

}

Estou usando os seguintes códigos, e preciso retornar o ID da ultima inserção no banco.
$dados_cliente = array(
    'cliente_nome'=>$cliente_nome,
    'cliente_email'=>$cliente_email,
    'cliente_celular'=>$cliente_celular,
    'cliente_tipo'=>$cliente_tipo,
    'cliente_documento'=>$cliente_documento
);

$comando->inserir('clientes',$dados_cliente);

Que é enviado desta forma. Só que após executar o comando $comando->inserir('clientes',$dados_cliente); não consigo pegar o valor da última inserção do banco.
Comment: @WillianCoqueiro o problema dessa sua solução é que nem sempre o ID vai ser o MAX+1. Se registros do final da lista de IDS forem deletados, a autonumeração não vai reaproveitar os números, mas o MAX sim, o que pode ser indesejado.
Comment: @Bacco Sim. Se tiver usando auto increment. Geralmente não uso esta função. Mais caso ele use após o insert somente MAX consegue os valores corretos.
Comment: Select Max (coluna)+1 from tabela
Answer: Considerando que você tem a estrutura apresentada dentro de uma classe:
public function executar($sql)
{

    $con = new conexao();
    $con->abrir();

    $re = $con->mysqli->query($sql);

    // Preciso retornar esta informação tambem:
    $last_id = $con->mysqli->insert_id;

    $con->fechar();

    return $re;

}

public function inserir($tabela,$dados)
{

    $arrCampo   = array_keys($dados);
    $arrValores = array_values($dados);
    $numCampos  = count($arrCampo);
    $numValores = count($arrValores);

    if($numCampos == $numValores) {

        $SQL = "INSERT INTO " .$tabela." (";
        foreach($arrCampo as $campo){
            $SQL .= "$campo, ";
        }

        $SQL = substr_replace($SQL, ")", -2, 1);

        $SQL .= "VALUES (";
        foreach($arrValores as $valores){
            $SQL .= "'".$valores."', ";
        }

        $SQL = substr_replace($SQL, ")", -2, 1);

    }else{

        echo "Erro ao verificar campos";

    }

    $this->executar($SQL);

}

Considerei que o método inserir também pertence a mesma classe, visto que há a utilização de $this em seu corpo.

Você pode definir uma propriedade da classe chamada last_id e atualizar seu valor dentro do método executar:
public function executar($sql)
{

    $con = new conexao();
    $con->abrir();

    $re = $con->mysqli->query($sql);

    // A propriedade é atualizada aqui:
    $this->last_id = $con->mysqli->insert_id;

    $con->fechar();

    return $re;

}

Desta forma, ela ficará acessível em toda classe. Portanto, no método inserir você pode retornar o valor desta propriedade.
public function inserir($tabela,$dados)
{

    $arrCampo   = array_keys($dados);
    $arrValores = array_values($dados);
    $numCampos  = count($arrCampo);
    $numValores = count($arrValores);

    if($numCampos == $numValores) {

        $SQL = "INSERT INTO " .$tabela." (";
        foreach($arrCampo as $campo){
            $SQL .= "$campo, ";
        }

        $SQL = substr_replace($SQL, ")", -2, 1);

        $SQL .= "VALUES (";
        foreach($arrValores as $valores){
            $SQL .= "'".$valores."', ";
        }

        $SQL = substr_replace($SQL, ")", -2, 1);

    }else{

        echo "Erro ao verificar campos";

    }

    $this->executar($SQL);

    return $this->last_id;

}

Assim, ao invocar o método. você terá acesso ao id do registro adicionado.
$dados_cliente = array(
    'cliente_nome'=>$cliente_nome,
    'cliente_email'=>$cliente_email,
    'cliente_celular'=>$cliente_celular,
    'cliente_tipo'=>$cliente_tipo,
    'cliente_documento'=>$cliente_documento
);

$last_id = $comando->inserir('clientes',$dados_cliente);

echo "ID do registro adicionado " . $last_id;

Conforme documentação oficial da propriedade insert_id:

Atenção!  Se a última consulta não foi um INSERT ou UPDATE ou se a tabela modificada não tem uma coluna com o atributo AUTO_INCREMENT, esta função irá retornar zero.
Comment: +1, aproveitando a classe fica limpo o código
Comment: A melhor maneira é sem o OOP, assim fica sem $this tambem. Só defende OOP em PHP quem não entende de no mínimo uma das duas coisas (geralmente as duas).
Comment: Limpo e simples, era isso mesmo que estava precisando, estou em transição do `mysql` para `mysqli` e ainda tem algumas diferenças que estou tendo dificuldades.
Comment: Por favor, clique em aceitar a resposta para sinalizar o tópico como concluído.
Comment: 2019 e eu aqui novamente com essa questão. Existe alguma forma de fazer sem usar o $this?
Comment: @HelisonSantos Muitas formas, mas provavelmente isso é assunto para outra pergunta. Ou entra no [chat](https://chat.stackexchange.com/rooms/11910/estouro-de-pilha) para discutir melhor.
Answer: Altere o retorno do seu método para retornar um array.
public function executar($sql){

    $con = new conexao();
    $con->abrir();
    $re = $con->mysqli->query($sql);

    // Preciso retornar esta informação tambem:
    $last_id = $con->mysqli->insert_id;

    $con->fechar();
    return array($re, $last_id);
}

Depois pode recuperar os dados para uma lista, ou tratar o array da maneira que preferir.
list ($operationResult, $lastInsertedValue) = $comando->inserir('clientes',$dados_cliente);

Comment: Só cuidado que o método `inserir` não está, da maneira apresentada, retornando o resultado do método `executar`. Ao fazer isso implicaria em alterar o método `inserir` colocando `return $this->executar($SQL);`. Outro porém é que se o método `executar` for invocado por outros métodos, como `atualizar`, `remover`, implicaria em fazer esta alteração em todos eles.
Comment: Melhor seria neste caso usar um parâmetro por referência, executar($sql, &$last_id) assim não mexeria no que já existe, bastaria usar o parâmetro nas funções novas só quando precisar do ID. Mas é válido como solução bem alternativa. Para o caso em concreto, com classe, a solução do Woss é mais limpa, mas é bom mostrar mais de um jeito de fazer.


Animar um script que troca o src das imagens

Question: A minha duvida é a seguinte: eu possuo em meu código 2 funções JS que são chamadas com onmouseenter e onmouseout em meu codigo HTML, que são elas:
function passo1() {
      document.getElementById("imagem").src="imagens/002.png";
  }
function passo2() {
      document.getElementById("imagem").src="imagens/001.png";
  }

O evento de mouseenter muda a imagem para de 001.png para a 002.png (na função passo1), enquanto o evento de mouseout muda  a imagem de 002.png para 001.png (na função passo2), isso que eu descrivi já está funcionando e as imagens trocam ao passar e tirar o mouse, o problema é que fica algo "seco", nem tem nenhuma animação, eu queria saber se seria possivel adicionar algum tipo de animação ou transição para esses 2 imagens.
Comment: Cara muito provavelmente isso que vc está tentando fazer daria para fazer facilmente com CSS... já pensou nisso ou tem que ser com JS mesmo?
Comment: Tem várias opções, vc pode ter 2 imagens ao mesmo tempo uma encima da outra, o que seria o MAIS indicado, pois quando vc muda o src, vc vai ter que carregar a outra imagem, e isso pode fazer a imagem "piscar" na tela por um momento, pois vai ficar em branco enquanto carrega a a imagem nova. Tendo as duas uma encima da outra vc não teria problema. A outra opção, mais complexa um pouco é tem um elementos com dois backgrounds-image, um url() para cada imagem. Acredito não ser possível fazer "transição suave" de src, mesmo com JS
Comment: Entendi, mas obrigado, de verdade, deu pra ter uma boa ideia do que fazer.
Comment: Mas é possível por CSS trocar o src de uma imagem? porque ela não está como background de um elemento (se fosse isso, sei que seria possível colocar um hover e trocar o background), ela é o elemento
Comment: Gostei da ideia de ter uma por cima da outra, poderia deixar uma com z-index maior e ao ter o hover o z-index iria diminuir, mostrando a outra imagem, mas para que elas fiquem uma por cima da outra seria necessário mexer com position, além do top e left.
Comment: Sim teria que usar position, e vc na verdade apenas deixaria a imagem de cima com opacity:0; não precisa de z-index. Mas tudo depende do efeito que vc quer, se quiser que no hover uma imagem saia pela direita e outra entre pela esquerda não vai precisar de position, vc poderia usar margin, então tudo depende do que vc realmente quer... Só acho pouso provável que vc consiga fazer uma transição de SRC, além do problema do carregamento que te falei...
Answer: Porque não fazer isso com CSS somente? Abaixo segue a forma de fazer com os dois modos (com e sem javascript).

var ctImg = document.querySelector('.ct-imagem#com-js');

ctImg.onmouseenter = () => {
  ctImg.querySelector('.img.frente').style.opacity = '0';
  ctImg.querySelector('.img.tras').style.opacity = '1';
};

ctImg.onmouseout = () => {
  ctImg.querySelector('.img.frente').style.opacity = '1';
  ctImg.querySelector('.img.tras').style.opacity = '0';
};
.ct-imagem {
  width: 200px;
  height: 200px;
  position: relative;
  border-radius: 100px;
  overflow: hidden;
}

.ct-imagem .img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  transition: opacity 500ms;
}

.ct-imagem .img.frente {
  z-index: 2;
}

.ct-imagem .img.tras {
  z-index: 1;
  opacity: 0;
}

.ct-imagem#sem-js:hover .img.frente {
  opacity: 0;
}

.ct-imagem#sem-js:hover .img.tras {
  opacity: 1;
}

Sem javascript/CSS

Com javascript


CSS - How do I select children of sibling elements?

Question: If I have an HTML structure like:

<input id="first-name" type="text" />

<input id="last-name" type="text" />

How do I target the last-name input field if the first-name input field has a certain class that is applied about user interaction?
For example, if a user clicks on the first-name input field, my JavaScript applies a "is-active" CSS class to it:

<input id="first-name" class="is-active" type="text" />

<input id="last-name" type="text" />

I want to apply some CSS to the last-name field when that occurs.
I can't just do the following because the two input fields are not siblings.
input#first-name.is-active + input#last-name { }

I've tried something like this:
.wrapper input#first-name.is-active + .wrapper input#last-name { }

But that doesn't work. Any help would be greatly appreciated.
Comment: `` is not allowed. You either need to self-close the `` or simply omit the closing tag completely.
Comment: Several errors here, the /input ofcourse, but also the added text in the id field. Since you already use js, just add al class to the siblings with js?
Comment: Sorry, this is me just writing some simple HTML just to get the point across. I'm going to update my post.
Answer: What you want to do is not possible with current available CSS selectors as you've already noticed.
You can check if this :focus-within workaround would work for you (browser support is very good, with IE being the usual exception):

.wrapper:focus-within + .wrapper > #last-name {
  background: yellow;
}

<input id="first-name" type="text">

<input id="last-name" type="text">

Comment: This is a neat workaround! Thank you.
Answer: You could also add a particular class using JS and apply some changes using css.

if ( document.querySelector("#first-name").classList.contains("is-active") ) {
  document.querySelector("#last-name").classList.add("your-class");
} else {
  document.querySelector("#last-name").classList.remove("your-class");
}
.your-class {
  background-color: red;
}

<input id="first-name" class="is-active" type="text"></input>

<input id="last-name" type="text"></input>

Comment: Check out `classList.toggle`, saves you alot of typing.


How to provide a translation for a string used within t()?

Question: On my site I use a module which creates text using t('text from module'). How can I tell drupal that I have a translation for that, and of course, that my translated text is being displayed?
Answer: First, make sure you install the Localization update module.  It is the key to handling anything that has to do with translation.  Enable automatic translation updates.
If the module is an "official" module with a stable release. the Localization update module will pull down translations from localize.drupal.org - provided they exist.  If they don't exist, you should provide them (read about how you can contribute on localize.drupal.org) - and the Localization update module will install them for you within 24 hours (if you've enabled automatic updates).
If the module does not have a stable release, there will not be anything on localize.drupal.org.  In that case, you must add local translations using the built-in translation interface.
Answer: As alternative, on admin/config/regional/translate/translate you can translate any string used by modules installed on that site, and on admin/config/regional/translate/import you can import the translation files.

Those are the paths for Drupal 7; for Drupal 6 they are, respectively, admin/build/translate, and admin/build/translate/import.
The first page is useful to translate the string provided by a custom module, but also to alter an imported translation, while the second page is useful to manually import the translations exported from a site, such as http://localize.drupal.org.
To automatically get translation strings from Drupal.org Translations there is the Localization update; to contribute back the translation to Drupal.org Translations there is the Localization client module. Both the modules have been written by Gábor Hojtsy, who is the administrator for Drupal.org Translations.
If you are interested in using both the modules, there is also the Localized Drupal Distribution distribution, which comes with those modules.


Prove that $B ⊂ X$ is open if $B∩∂B = Ø$.

Question: With $(X,τ)$ beeing a topological space.
The statement is pretty obvious. For a set B, if the topological boundary is not fully in the set, the set is considered open, per definition.
In our case, not a single element of the boundry is inside the set. $B∩∂B = Ø$.
Has someone an idea on how to approach this?
Comment: I'd start by writing out the definitions of $\partial B$ and "$B$ is open". Then it should be easy to relate these.
Comment: **Hint :** $$\emptyset = B \cap \partial B = B \cap \left( \overline{B} \setminus \mathrm{int}(B)\right)  = B \setminus \mathrm{int}(B)$$
Comment: Does $B$ without $  int(B)=∅$ imply that $B=int(B)$ and because of that $B$ has no boundry that is in $B$? That would explain why $B$ must be an open set.
Answer: This becomes obvious if you write out the definitions. Consider  some point $x \in X$ and the balls $B(x,r)$ for all values of $r>0$. There are three possibilities.

Some $B(x,r)$ is contained in $B$

Some $B(x,r)$ is contained in $X/B$

Every $B(x,r)$ meets both $B$ and $X/B$

By considering whether $x \in B$ or $x \in X/B$ we can see exactly one of the above is true for each $x$. i.e for $x \in B$ either (1) or (2) is true and for $x \in X/B$ either (2) or (3) is true.
Now (1) is the definition of the interior of $B$. (2) is the boundary. (3) is the interior of $X/B$.
The rest is straightforward.


How to create an Ubercart add to cart button programmatically with defaults?

Question: I am able to create an add to cart button:
<code>$nid = 27;
$node = node_load($nid);
$add_to_cart = array(
    '#theme' => 'uc_product_add_to_cart',
    '#form' => drupal_get_form('uc_product_add_to_cart_form_' . $nid, $node)
);
return drupal_render($add_to_cart);
</code>
This gives me an add to cart button, but with no attributes selected. How can I alter this code to allow for the defaults to be set to specific values. For example, if I have an attribute with aid = 1, called "action", and two possible value... oid = 3 = register ... and oid = 4 = transfer..... of which I want the default to be "transfer" for example?
Answer: I managed to use cart links instead:
<code>/cart/add/p27_a6osfsdfsdfsdf_a7o706_a2o8_a1o515_q1-idomainName?destination=cart
</code>
Answer: This is the updated updated and more correct answer:
<code>$node = node_load(123);
$drupalForm = drupal_get_form('uc_product_add_to_cart_form_' . $node->nid, $node);
$addToCartHTML = drupal_render($drupalForm);
</code>


Querying SCCM Server to get ADD/Remove Programs list of a specific computer

Question: First of all, i'm sorry for my english.
I'm new in vbs scripting and wmi queries and I need your help.
My goal is to get the Add/Remove Programs list of a specific computer.
I saw many scripts which query the Uninstall registry key on the target computer but I want to do it even if the computer is offline. That's why i'm querying the SCCM Server.
My query seems to be good because when i put it in Report Builder, it returns a good result.
Here is the query :
<code>Select sys.Name0,adv.DisplayName0 FROM v_R_System sys , v_Add_Remove_Programs adv where sys.ResourceID=adv.ResourceID and sys.Name0 like '%XXXXXXXX%'
</code>
My problem is to get the result of the query using vbscript. I'm getting an error on the line of the "For Each"
Here is my script :
<code>'Central SCCM Site Server name
strComputer = "SCCM_SERVER"

'Central SCCM Site Code
strSiteCode = "DC1"

'Set up the connection String
Set objWMIService = GetObject("winmgmts://" & strComputer & "\root\sms\site_" & strSiteCode)

'Get the info with a query
Set colGroups = objWMIService.ExecQuery("Select sys.Name0,adv.DisplayName0 FROM v_R_System sys , v_Add_Remove_Programs adv where sys.ResourceID=adv.ResourceID and sys.Name0 like 'XXXXXXXXXXX'")

'output the info
For Each objGroup in colGroups
    Wscript.echo objGroup.DisplayName0 & " - "
Next
</code>
Can you please provide me some help ?
Update : it seems that i'm not using the right language for the query. I'm using SQL instead of WQL.
I don't know how to translate my query into WQL.
Can you help please ?
Comment: Eww, vbs.  Use PowerShell instead, it sucks much less.
Answer: You are trying to use a SQL query to get results from CM07/CM12. You need to use WQL to query CM07/CM12. Translate your query to WQL and it should work or rewrite your VBS to query SQL directly.


How to create Media entity and attach to user field

Question:
I'm trying to import user profile pictures from Drupal 7 to Drupal 8. So far I've managed to upload the picture from the url and save it to the file system, create Media entity and use the user id as author. However, the picture doesn't show to the user profile (Manage Form Display), neither to the Edit Media Content Type page.
Here is the code I have so far:
$values = array(
      'name' => $user["name"],
      'pass' => [
         'value' => $user["pass"],
         'pre_hashed' => TRUE,
      ],
      'status' => $user["status"],
      'mail' => $user["mail"],
      'field_first_name' => $user["field_first_name"],
      'field_last_name' => $user["field_last_name"],
);

$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);

    $replaced = str_replace("\\", "", $user["picture"]);
    $imageData = file_get_contents($replaced);
    $fileName = basename($replaced);
    $file = file_save_data(
        $imageData,
        "public://". $fileName,
        FileSystemInterface::EXISTS_RENAME
    );

    $media = Media::create([
        'bundle' => 'image',
        'uid' => $userEntity->id(),
        'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
        'field_media_file' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
        ],
        'thumbnail' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
        ],
    ]);

    $media->setName($fileName)->setPublished(TRUE)->save();

    $userEntity->field_user_picture->appendItem($media);

Is the something missing in the code?
UPDATE
I noticed (as also pointed out in the comments) $userEntity->save(); is missing after $userEntity->field_user_picture->appendItem($media);.
However, after I added that line, I get the following error:
Error: Call to undefined method Drupal\media\Entity\Media::getFileUri() in Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (line 321 of /var/www/html/web/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php) #0 /var/www/html/web/core/lib/Drupal/Core/Field/FieldItemList.php(233): Drupal\image\Plugin\Field\FieldType\ImageItem->preSave()

Is it related to file_save_data() function?
Comment: First, I would be using Migrate for this. Second, I don't see you saving the user object. Is appendItem the proper method to use for adding a field value? If the field doesn't show on Manage Form Display, was it even created correctly?
Comment: @Kevin `appendItem` looks valid, the core `FileUpload` class uses the same method to append a file entity
Comment: Hi! I wrote down some updates on the question. @Kevin was right, `$userEntity->save();` was missing.
Answer: I've found the solution.
I don't need to create a Media entity and append it to the User entity, since the profile picture field type is Image, so I just need to add the file->id() to the specific field.
Here is the code:
$replaced = str_replace("\\", "", $user["picture"]);
$imageData = file_get_contents($replaced);
$fileName = basename($replaced);
$file = file_save_data(
      $imageData,
      "public://". $fileName,
      FileSystemInterface::EXISTS_RENAME
);

$values = array(
      'name' => $user["name"],
      'pass' => [
         'value' => $user["pass"],
         'pre_hashed' => TRUE,
      ],
      'field_user_picture' => array('target_id' =>$file->id()),
      'status' => $user["status"],
      'mail' => $user["mail"],
      'field_first_name' => $user["field_first_name"],
      'field_last_name' => $user["field_last_name"],
);

$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);

Then, if required, I can create the Media entity as following:
$media = Media::create([
          'bundle' => 'image',
          'uid' => $userEntity->id(),
          'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
          'field_media_image' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
          'thumbnail' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
]);

$media->setName($fileName)->setPublished(TRUE)->save();

Comment: Thanks. This just helped. For some reason, `entity/media` rest endpoint always throws 422. I ended up building my own resource using your code.


T-SQL Like statement behaves differently when using a string literal vs using a variable for the search text

Question: I have found that the T-SQL LIKE statement behaves differently when using a variable to hold the search text - please advise if there is something I doing wrong.
select 'True' where 'A242' like 'A2%';
True

create table temptable (code char(10),searchtext char(10));
insert into temptable ('A242','A2%');
select * from temptable where code like searchtext;
(no rows)

update temptable
set searchtext = 'A2%%'
where code = 'A242';

select *
from temptable
where code like searchtext;
A242

It seems like when using a variable the % match pattern doesn't match to any length string but only to the length of the search text.
Comment: Try VARCHAR, as CHAR pads with spaces. :) Nice on Monday morning. BTW in Stackoverflow when indenting with 4 spaces a code block is created, like `select ...`.
Answer: You are using char(10) columns, rather than varchar(10) columns, so your data is stored padded with spaces so that the values are exactly 10 characters long.
It should therefore be clear why the matching doesn't occur as you expect: "A242<6 spaces>" does not match "A2%<7 spaces>", but does match "A2%%<6 spaces>".


after the installation via MacPorts of gcc45, how can I use it to build C language on my Mac?

Question: The following html link contains all the relevant bash command line records of the installation process. Thank you for help!
That was a bad question
I didn't use XCode through I know Xcode will make it easier! I use an Air, memory of 4GB currently.
If this won't work easily I probably will quit learning C or run and compile C on Windows. :(
And XCode stuff, whatever.
Comment: Why not just install Xcode and save yourself a lot of pain?
Comment: You can still use command line tools to compile C if you install Xcode.
Comment: An important follow-up question: The installation of gcc45 +universal seems successful(or not?), why it is still a version of 4.2.1 other than a upgraded version?
Answer: You command-line output indicates rather clearly that you aren't telling gcc what to compile, so it's throwing its hands up in exasperation:
$ gcc
i686-apple-darwin10-gcc-4.2.1: no input files

You'll need to specify the file you're compiling. Better yet, use an IDE, like Xcode.
Answer: <Shrug> What do you want us to say?
Obviousy Macports is trying to build/install gcc but it can't without a compiler.  Yes gcc can be built without a preexisting compiler, but good luck and why?  Especially when XCode is a free download, click click let it start and a little while later it's done. At that point as pointed out elsewhere, gcc, g++ will work, but it's not actually gcc but clang in disguise.
If you want, you can use macports or brew or whatever later if you really want to, but again why? For programs that only work using gcc extensions?  Doubt it. You just want a c/c++ compiler.  If you ever want to do programs for the Mac or IPhone, you need XCode anyway, gcc won't do.
Comment: That is true. I was concerned that XCode would take too much memory while it's working on an Air, and that's all. Thank you for the suggestion.


Eigenvectors for correlation and covariance matrix PCA

Question: I know the generally reasons of using correlation matrix vs a covariance matrix when doing PCA (and visa versa) however when thinking about the eigenvectors (principal components of the data) of each of these matrices I still have a question which is:
Obviously, these eigenvectors will be different however since we are just scaling one to get the other is there just a 1:1 mapping to the eigenvectors of a correlation matrix to a covariance matrix? I.e are the principal components we get for one conceptually the same just in different coordinate system or are there total different interpretations for each set of principal components we get when doing PCA with correlation or covariance?
Comment: My answer at https://stats.stackexchange.com/questions/140711 offers illustrations that may help give you the intuition to answer your questions easily.
Comment: @whuber appreciate the comment. Helpful post indeed. So, am I correct in saying that then the principal components are different when using correlation or covariance matrices? Because we change the scale, and per your post this does have an impact (as it changed the # of clusters in your case) thus - depending on the data the principal component gleaned from PCA via correlation or PCA via covariance maybe more useful than the other?
Answer: The starting covariance and correlation matrices are a different coordination system and only under very limited circumstance would they bear close resemblance.
In a covariance matrix the variables can have any magnitude of relationship to each other, but in correlation it is constrained so the total variance is 1 and the covariance any fraction of that.
I work mainly with digital signals and they provide evidence that there is no guarantee of correspondence. In the signals I work with the noise level is inversely related to the square root of the intensity. This means for variables with high intensity the covariance matrix picks these out strongly over weak variables. In a correlation matrix the weak variables are given the same weighting even though they are more noisy. Thus a correlation matrix increases noise.
Noise by definition is orthogonal to signal, so it will not be possible to have 1 to 1 correspondence if you have sizeable differences in variable intensity within a signal. If the noise after standardisation is greater than the signal, then your signal disappears from your eigenvectors (or to be precise, it gets split across many noisy eigenvectors based on chance Cross correlations specific to your training set)


Does a phylogeny of Afro-cuban rhythms exist?

Question: I've recently been immersing myself in Afro-cuban rhythms. There are many similarities between them, and it struck me that it would be interesting to learn how they are related to each other with a kind of family tree. Does this exist, and if so, can I be pointed in the right direction?
Answer: I'm not sure about a "family tree" per se, but you may be interested in reading Rhythmic Archetypes in Instrumental Music from Africa and the Diaspora. It's a scholarly article available for free at Music Theory Online.
The author (James Burns) discusses six rhythmic archetypes in instrumental music of Africa and the Diaspora. (Here I slightly broaden your definition of the already broad Afro-Cuban tradition.)
His first three archetypes are what he calls "weaving" archetypes; note how the surface rhythms jar against the metric background of straight eighth notes:

His remaining three archetypes—the "ups," the "341," and the "shifting three"—are shown in the latter half of the article. If this is the type of thing you're looking for, I recommend checking out the article.
Furthermore, his bibliography may point you towards other sources that may be helpful in other ways.


An Elementary Approach to How Many Singular Points a Curve Can Have

Question: Consider an irreducible plane curve, $C \subseteq A^{2}_{\mathbb{C}}$. Prove that C has only finitely many singular points.
My idea is to consider the subset $S$ that contains the singular points of C. Then we would want to show that it is a closed subset--but I do not see where to go from here. Could someone help, with elementary methods?
Answer: Hint: The singular points should satisfy some equation, and so should be Zariski closed. That means they are either everything or finite (why?). But, they can't be everything (why?).
Comment: This is a good hint.
Comment: For an irreducible curve, the only closed subsets are a finite set of points or the curve itself. They cannot be everything because the set Zariski closed set has a polynomial which is of lower degree, and therefore less roots.


Using try/catch to break infinite loop

Question: I just solved a fun little practice problem with basically boils down to this:
int [] array = new int [10];
int i = 0;
try{
  while (true){

     array[i++] = 10;

  }
}
catch(ArrayIndexOutOfBoundsException e){
   for(i = 0; i < 10; i++){
      System.out.println(array[i]);
   }
}

How evil is this? Goto evil? Lots of Global Variables evil? or is this totally fine?
Comment: Why not use a for loop?
Comment: I wouldn't call it _evil_ per se, just stupid. I mean GOTO at least could be useful, but this is just obfuscation for no reason.
Comment: "How evil is this?" It is very evil because it's not readable at all. By reading your code I cannot figure out what the intention is.
Comment: You should use exceptions as normal behavior when the exception **is** part of the normal behavior of the application e.g. having a EOFExceiption when reading a file where you don't know the number of entries. In this case, it shows a bad design.
Comment: @LiverpoolFTW its more a question of theory at this point but looking back, you're right, that would probably be a better choice.
Comment: afaik, your code should not compile since your counter 'i' is re-declaration of variable i on line 2 , though it is not your concern in the question.
Answer: Exception handling is tremendously expensive in terms of performance (and somewhat expensive in terms of memory). As a general rule, you should always prefer other techniques where possible.
Comment: Expensive in terms of memory? Sorry, but I don't think 4KB of RAM (or around that amount) can compare to 2GB of data in arrays/maps.
Comment: @LuiggiMendoza that's a false choice though, you don't have to choose one or the other
Comment: This seems like the weakest reason to avoid this code.  Even if try/catch was faster than for loops, there's reasons you shouldn't use exception handling for flow control.
Comment: @mattb never said it wasn't a false choice. It would always depend on design.
Comment: @tieTYT using exceptions as part of the application behavior is not always a wrong choice. For example, there's a system X (that you cannot modify) that generates files wich unknown number of registers and you must consume them in your Java app. Since you don't know the number of registers to process by any means and you can't change that app, the only thing you can do to know where you can't read any more data is through a EOFException. As said in my comment on OP's question, using an exception in this case just shows a bad design.
Answer: Here are some possible ways to do it without try catch:
First
int [] array = new int [10];
int i = 0;

while(i<10){
  array[i]=(i+1);
  System.out.println(array[i]);
  i++;
}

Second
int [] array = new int [10];

for(int i=0; i<array.length; i++){
  array[i]=(i+1);
  System.out.println(array[i]);
}

What I mean is, if it's not really necessary to use try catch, don't!
Try catch only supposed to prevent user error (usually in my program), or unless the program ask you to use it.
Comment: The **First** never increments `i`; it's infinite
Comment: oopps, I forgot to add increment hhehe :)

Using try/catch to break infinite loop


Modelling diminishing returns of investments using regression models

Question: I encountered a real-world problem where I want to model the effectiveness of various advertising media of a brand (measured in terms of sales). Basically, the Y in this case is weekly sales, and the X's are media investments in newspaper, magazine, display boards, tv, radio and online, as well as incentive, which is a percentage (like 10% off the original).
There are a few problems with the modelling work:

all variables should have positive coefficients. Typically, more advertising or incentive is at least as good as less advertising/incentive (maybe this is not true if you buy all of the advertising spots in the world, as then your consumer will start to hate your brand, but this is not going to happen here). However, when I fit a typical regression (e.g. lm, glm, gls etc), some coefficients turn out to be negative (as data may be a bit noiser than expected, hence causing this problem?). I wonder if this can be controlled (I know in nonlinear regressions you can set constraints for parameters)
there should be some sort of diminishing marginal return of advertising spendings, but I am not exactly sure how to model that. Some ideas include using a log or square root transformation, another idea may be to use a nonlinear regression and estimator something like a*newspaper^b, where a is some coefficient, and b is an exponent between 0 and 1.
this is serial correlation, but this may not be exactly important here as the goal is only to estimate the parameters (if I use a regression I think I still get the unbiased estimators right? Autocorrelation only screws up the p-values, which is ignored here). Also, how to deal with seasonalities? I don't have much data (2 years) so maybe there is nothing we can do about it, but I have seen adding cos(0.0172*time) + sin(0.0172*time) to the regression equation to adjust for seasonal changes.

Thanks.
Comment: If you haven't already, it might be worth considering using some sort of polynomial lag model - an almon model for example. If you search distributed lag model, almon model, polynomial lag model, modelling sales in response to advertising, or terms like that, you should get some useful results.
Comment: It seems to me you need to be very careful before you constraint the slopes. Is there a particular x that is causing this and is multicollinearity an issue? Have you tried a ridge regression?
Answer: 1) All coefficients positive:
I could lay out an argument why this may not be so ("if you swamp consumers with advertising, they may get sick of you"), but let's accept this is a fringe result, not very likely to happen. And why data are "noisy"? From what I understand they are sales figures and advertisement expenses, why should they have increased noise?
Anyway, if you want to constraint the parameters to be positive, you can run "Inequality Constraint OLS" - see this post
Negative values in predictions for an always-positive response variable in linear regression
and don't forget to read Whuber's comment. See also other approaches here:
Linear regression with slope constraint
2) Diminishing marginal returns
You can include the squares of the variables -see the rationale here:
Why is functional form so important when specifying models?
3) Autocorrelation:
Make the distinction between autocorrelation, which technically leads to the inclusion of lag dependent variables in the regression, and reflects "habit formation" from the part of consumers (is your product such that creates strong habits? Is the brand really a brand, commanding "consumer loyalty"?), an effect which in any case, is partially captured by the constant term,
and time-deferred effects of the regressors on the dependent variable. If your data is weekly, most certainly you are going to have such effects: "non-perishable" advertisement (like press), may hang around for a while and affect consumer choices at a later week. Even "perishable" advertisement (radio, TV, etc) may show effects later on -the consumer is persuaded now, but it consumes later. Here you need to include lags of the regressors. You have 104 observations -you can spare one or two. Lags of regressors do not violate the standard assumptions on the linear regression model -they may make the dependent variable autocorrelated but this happens not through the error term but through the regressors. The only price to pay here is that, for asymptotic properties to hold, the assumption of strict exogeneity (which is needed for finite-sample unbiasedness) cannot be weakened to contemporaneous uncorrelatedness.
4) Seasonality
Do you have a priori knowledge that your dependent variable (Sales) exhibits or is expected to exhibit seasonality? If yes, does your regressors perhaps exhibit the same pattern?


Residuals in double seasonal exponential smoothing

Question: I have a time series with muliple seasonal cycles, which are 24 and 168 hours for my case. I would like to use Double Seasonal Exponential Smoothing method to forecast, which was published by James W. Taylor (http://users.ox.ac.uk/~mast0315/). The link for his article is here
When I check Taylor's paper and all other papers in the literature, I saw that AR(1) adjustment has been implemented to the residuals. Is it a coincidence to make AR(1) correction to residuals of all the time series, that have been used in these papers?
I am using "forecast" package in R by Rob Hyndman, http://cran.r-project.org/web/packages/forecast/forecast.pdf
Firstly, I run the code without using an AR(1) model for the errors.
    data <- scan("data.dat", skip=1)
    datatimeseries <- ts(data)
    library(forecast)
    dataforecasts <- dshw(datatimeseries, 24, 168, armethod=FALSE)
    res=dataforecasts$residuals
    acf(res)
    pacf(res)

Below, you can see the ACF and PACF graphs of the residuals.

As you can see there are some serious non-zera autocorrelation. I can not do AR(1) correction as papers suggest because PACF does not show it.I do not know what to do. I am sorry if it's a silly question however I am so new to time series. Would you please care to explain what to do next step-by-step and elaborately. Thanks in advance
Answer: The AR(1) error would help a lot. But if you want something more general and flexible, use the tbats function instead.
Comment: Mr. Hyndman, When I do AR(1), no matter what the graphs depict, I still get non-zero autocorrelations. That means I did not get a perfect model. thus, how I use this tbats function you mentioned and why?
Comment: First, you may never get a perfect model. Second, I've already explained why -- it is more general and flexible. Third, if you want to know how to use a function, read the help file.


When AWS free tier is going to expire?

Question: I started free tier some time ago, but then abandoned it. I want to restore usage of AWS, but I'm not sure for how long I can use it for free.
In billing it says I'm under free tier, but I couldn't find when it's going to expire. How can I figure this out?
I know it lasts 12 month in general. I want to know when MY 12 months period is going to expire.
Comment: https://www.krunalparmar.com/Blog
Answer: It is one year as of now. After one year, you will still get certain services for free.
Read more about it here. https://aws.amazon.com/free/
To get to know when your 12 month period started.

Login as a user with access to billing information. (root user / IAM with appropriate access)
Go to billings from top right drop down.
Click "Bills" on the left. Find the oldest bill in the list of months by date. Your free tier will expire 1 year after that date.

Alternately :
Try to find welcome email from AWS in your mailbox.
Comment: Sign in as a user who has access to the billing and cost area of the account.  (Possibly the root user, but could be Iam user if you have granted them access).  Click on your name in the top right, and choose "Billing and Cost Management". Click "Bills" on the left.  Find the oldest bill in the list of months by date. Your free tier will expire 1 year after that date.
Comment: Right, but how long before MY one year is going to expire?
Comment: interesting.. I used my billing information to assess that. Let me get you exact steps.
Comment: Apart from what chris said. Alternately , try to find that email AWS sent you.

When AWS free tier is going to expire?


Reference request: When is a conic birationally equivalent to the projective line?

Question: I am looking for a reference which contains the proof of the following theorem:
"A conic $C$ defined over the field $\mathbb{F}$ is birationally equivalent to $\mathbb{P}^{1}(\mathbb{F})$ if and only if $C(\mathbb{F})\neq\emptyset.$"
Google didn't seem to help me too much (but maybe I've been shortsighted!).
Comment: For what definition of conic?
Comment: I mean is "conic" a variety defined by a homogeneous degree 2 equation in 3 variables (when irreducible and smooth).
Comment: yes, indeed! :)
Comment: See Prop 19.3.1 of Vakil's book.
Answer: The idea of the proof is this:
Let $P$ be a rational point on $C$. Then look at all the lines through $P$. Each such line intersect $C$ in one more point.
This lets us define a rational map $\mathbb P^1 \to C$ since lines are parametrized by $\mathbb P^1$ (it is rational because the tangent line only meets $C$ at one point). The map is well defined and injective by Bezout.
Answer: 'Diophantine Geometry: An Introduction', by Silverman and Hindry, contains a proof in section A.4.3 (Page 74). A few minor steps are skipped, but it should be fairly easy to follow.


iOS App Crashing When Adding a New Entry after A Search with TableViewControllers using Core Data and NSFetchedResultsControllers

Question: I am facing an interesting issue with my app. Firstly the premise of the app is simple: A table view controller with a plus button in the navigation bar; a user presses the plus and a view controller appears modally. The user adds in a name, amount and event, presses save and through NSFetchedResultsController and Core Data, that information is successfully populated back in the Table View Controller.
That works very well. The TableViewController is also using a SearchBar so that the user can search for names or events in the Table View.
The issue is:
If a user searches for an entry in the Table View (and does not cancel out of the search) and then presses the Add button to add an entry, fills in the information and presses save, the app crashes with the error below:
CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet. with userInfo (null)
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet.'

However, if the user does actually cancel the search from the Table View and then adds a new entry, it does not crash. This is something I need to fix because some workflows may not see the need to cancel the search before adding a new entry.
My NSFetchedResultsController in the Table View has the following predicate:
if ([self.timelineSearchBar.text length] > 0) {
    NSPredicate *predName = [NSPredicate predicateWithFormat:@"ANY whoBy.name CONTAINS[c] %@", self.timelineSearchBar.text];
    NSPredicate *predOccasion = [NSPredicate predicateWithFormat:@"ANY occasion.title CONTAINS[c] %@", self.timelineSearchBar.text];

    // creating the orCompoundPredicate for the two conditions
    NSPredicate *compPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predName, predOccasion, predDate]];
    [fetchRequest setPredicate:compPredicate];
}

I understand what is happening, but I'm not entirely sure how to go about fixing it. The error appears to be very common and there are lots of fixes out there, all relating to slightly adjusting the predicates, but I'm not sure which direction to take with this.
I am adding a view of my model for further information as well.

Any assistance on this would be massively appreciated.
EDIT: I am presenting the view controller through storyboard rather than in code, but as per the comment by TheEye, it might be easier to actually just clear the search in code and present the view controller manually. I'm looking into exploring this as a way forward.
Comment: Why don't you just cancel the search yourself when the user presses the + button, before presenting the data entry screen?
Comment: Thanks @TheEye - I'm presenting it modally from the storyboard rather from code.. but I did think of adjusting it so I'm presenting it from code because that would be an easy way to fix this.. I'll look into this now
Answer: That error occurs if "ANY" is used with a to-one relationship instead of a to-many
relationship. For example, if "occasion" is a to-one relationship then you have to
replace
@"ANY occasion.title CONTAINS[c] %@"

by
@"occasion.title CONTAINS[c] %@"

in the second predicate.
Comment: Thanks for the reply Martin - that's very helpful. My apologies for not mentioning that earlier but occasion and whoBy are both to-many relationships and with removing the word ANY from the predicates, I'm still getting the same crash..
Comment: @amitsbajaj: According to the image of your model, *both* "whoBy" and "occasion" are *to-one* relationships.
Comment: Apologies Martin - I was mis-reading the direction of the relationship. You are correct with that, but am still being presented with the same error with the same scenario weirdly
Comment: @amitsbajaj: Did you remove "ANY" in both predicates? The error message clearly mentions "… ALL or ANY operator …".
Comment: Thanks Martin - I'm not really sure what was going on there as it kept crashing and I had removed ANY from both predicates, but closing Xcode and reopening did the trick. This issue is now resolved. Thanks for the prompt assistance with this one!


linear subsets of linear space

Question: Need help with graduate level work. I've been out of undergrad for almost 20 years.  The  problem says: Given $B$, a subset of a linear space $L$, $q$ element of $L$ and $p$ a point of $B$ such that when $q$ is a linear combination of points in $B$, the coefficient of $p$ is not $0$. Let $B'$ be the set obtained by replacing $p$ with $q$.  Then $B'$ also spans $L$.
Is this just asking me to show that $p$ allows me to form a different linear combination which will also spans $L$ since $p$ is a part of the subset which spans $L$?
If so, How do I approach proving this?
Comment: What is the set that spans $L$ when you talk about $B$ also spanning $L$?  The problem statement could be clearer IMHO.
Answer: (I think the  omitted  assumption is that $B$ spans $L$.) Starting with  the given assumption
$q = cp+\sum c_i b_i$ (for some scalars $c_i$ and some $b_i\in B$), write $$p=c^{-1}q-\sum c^{-1}c_i b_i \tag{1}$$ Using (1), you can eliminate $p$ from any linear combination in which it appears. Thus, anything that can be written as a linear combination of elements of $B$ can also be written as a linear combination of elements of $B'$.

linear subsets of linear space


How to regularise SGD in sklearn by using a gaussian prior with mean different than 0?

Question: I am using SGDregressor of Sklearn in order to fit a least squares linear regression in an online setting. I would like to use a normal distributed prior with mean 1 for my coefficients. In other words I would like to add the following regularizer term: $\lambda ||w-\frac{1}{d}||_2^2$ where $d$ is the number of coefficients.
With the penalty argument I can specify a l2, l1 or both but always with a prior mean of 0.
The closest I could get would be to use elastic net with a regularizer term $\frac{2}{d}$ larger for L1 than L2 regularization. Indeed
$$\begin{align}
reg &= \lambda ||w-\frac{1}{d}||^2\\
&=\lambda w^2 - \frac{2}{d}\lambda w + (const)
\end{align}$$
Minimizing the loss function with this regularizer is equivalent as regularizing using an elastic net with $\lambda_{L1} = 2\lambda_{L2}$ when $w_i <0, \ \forall i$ but not in the general case.
Thanks:)
Answer: Do a change of variables to $v = w - \frac1d \mathbf 1$. Since $v^T x = w^T x - \frac1d \sum x_i$, you should also use "fake" labels of $y_i - \frac1d \sum x_i$ to get the right optimization problem. At prediction time, remember to add $\frac1d \sum x_i$ to the output from the model's predict method.


Column Offset Excel Formula

Question: I have an excel spreadsheet with the names in each column;
Example
Column A=Name-01, Column B=Name-02, Column C=Name-03 etc
I want to copy the name of each column to another spreadsheet to rows
Example
<code>   A1=SheetName Column A=Name-01
   A2=SheetName Column B=Name-02
   A3=SheetName Column C=Name-03
</code>
Comment: so in the second sheet A1 you want the first sheet A1 and in the second sheet A2 you want first sheet B1 and so forth?
Answer: Use INDEX:
<code>=INDEX(Sheet1!$1:$1,ROW(1:1))
</code>
Now as you drag it down column A it will refer to the next cell in the first row of the other sheet.

Column Offset Excel Formula


what type of guitar scale is this?

Question: There is an mmorpg (game) where playing a guitar is possible, i want to know if this guitar scale or type relates anything to guitars in the real world

here's how C1 sounds : http://picosong.com/ESVu/
Comment: @Dom Actually I don't think it looks like a keyboard OR a fretboard (even though it looks like a board). I based my assessment on the fact that guitarist rarely refer to octave numbers the way pianist do. Probably because it would be useless in describing position.  A C4 is near the middle of an 88 key piano and a C5 is to the right and C3 to the left of C4.  With guitar - the note which corresponds to C4 can be played in several different places on a guitar fretboard.   But whoever created the game may have intentionally made it ambiguous so it could apply to any chromatic instrument
Comment: here's how B3 sounds http://picosong.com/ESVz/
Comment: The notes correspond more closely to a piano or other keyboard instrument than a guitar.  Same notes on guitar and piano but the octave numbers are more closely associated with keyboard instruments.
Comment: @RockinCowboy I'd argue that the layout is more guitar like than piano like as it looks like a fretboard. The numbers jus mark the octave which we can write out a for a guitar just as easily as piano.
Comment: The 3rd string of a ukulele is normally tuned from C4 (open) to C5 (12th fret)
Answer: It's just 3 octaves of the chromatic scale. Based on what you say it sounds like it is not the scale, but the range given to compose in. The game is just giving you the range from C1 to B3 to play with to create / make music.
Answer: I don't really understand the connection between the chart picture and the sound file, but the sequence...
C, C#, D, D#, E, F, F#, G, G#, A, A#, B
... is the chromatic scale.
The numbers next to the letters look to me to be "scientific pitch notation"
https://en.wikipedia.org/wiki/Scientific_pitch_notation

what type of guitar scale is this?


Tips on finding notes corresponding to a bass line

Question: I'm a drummer who knows very little about stringed instruments (I can play some basic stuff on the ukulele, but that's about it). I have "written" a bass line for a song I'm working on. By "written" I mean that I can sing out the notes, but I'm not sure where to start with actually figuring out what notes I'm singing. It's something fairly slow and simple (similar in complexity to the opening bass line in Seven Nation Army, not that I'm claiming quality of what I've got is comparable).
Do I have any hope of trying to figure this out myself or am I better off finding someone who knows more than I do to help?
Comment: @AndyBonner I have a keyboard, don't currently have a bass.
Comment: One clarification that would steer answers: do you actually have a bass and can mess around on it? Or maybe a keyboard?
Answer: find just one note in your head-tune that matches any note on the bass, bear in mind that you only have to go to fret 5 before you can find that same note playing the next thinnest string open without fretting anything.
Example ... play fret 5 of the thickest string and then play the second thinnest string open. It should be the same pitch, but likely a different tone to the sound.
If you stay within four frets of your given note and go across the strings, up and down as your head-tune goes, you should be able to pick out your tune given a little time. Google "interval training"; learning to find those notes and noting how far from your start note they are, will teach you some intervals. Many effective bass lines are made from simple intervals that work to outline the notes in chords.
Answer: An obvious anwer is 'find someone who can do it better than you', but what's wrong with trying to diy? Assuming you have access to a piano, say, (probably the best instrument here), then establish the key you want to be in, messing about with notes, till one sounds right. Then, the hit-and-miss process of finding the subsequent notes, one at a time. Even more complicated wielding a uke (or bass)!
The problem you then have is how to write them down, so someone else can read them and play the line/s.
That way, you'll learn more about what you're doing, for the future, if there will be more songs.
On reflection, the opening gambit sounds like the better move for now...
Answer: This is something you learn how to do when you take a music theory course.  Which you may want to consider doing.  (Save money by choosing a community college.)  You could also buy a second-hand textbook.
First you label the chords.  The most common ones are I, IV, and V.  What you do is work with the most important notes in the melody and write down what chords include the melody note.  For example, say the options are iii, V and vii.  The most common choice there is V, but you can experiment with the others and see how you like it.
If you buy a fake book or beginner piano book, there will probably be chords already written in.
Once you have a chord progression for the whole tune, then for each main beat, choose one of the notes in the triad belonging to the chord.  Often you will want the lowest note of the triad, but experiment until you like the way the bass line sounds.
There are other things you would learn in a music theory course (e.g. passing notes), but the above could get you started.
Have fun!
Answer: The original question is equivalent to "how to compose music." It's a lifetime study. However, if you want a nice melody to go with a given bass line, there are a few procedures (not rules, just what has been found by others to work well.)
The first idea is to avoid parallel perfect intervals. When two lines of music move by the same interval, the lines often sound more like a "rich" single melody, rather than two independent lines. The rule is often stated: "avoid moving to perfect unisons, octaves, or fifths by parallel motion.) The idea is to have the bass line support the melody, not merely reinforce it. If a pair of lines move a few steps (even 2, but 3 are easy to hear), the whole composition sounds a bit like one instrument dropped out. This rule also helps improvise a bass line when accompanying a jam session.
It helps vastly to know a bit about chord progressions, chord inversions, and a bit of other stuff.  This one can learn by trial and error or (much) faster by formal study.
Another useful procedure when just stuffing things above a bass line (which is not a bad way to compose a piece.) It's called the "Rule of the Octave" or more commonly "Regle d'Otava"). It was devised for Renaissance and Baroque keyboard players to improvise chords above a bass line. The idea is to suggest chords that work well above certain bass notes in rising or falling bass lines. This is a bit more complicated than just avoiding parallels.
https://www.partimenti.org/partimenti/about_parti/rule_of_the_octave.pdf
http://www.singanewsong.org/byu/theory/grad_review/The%20Rule%20of%20the%20Octave.pdf
http://musictheory.sites.gettysburg.edu/unit-4-1/the-rule-of-the-octave/
http://musictheory.sites.gettysburg.edu/unit-4-1/rule-of-the-octave-in-minor-keys/
There's more. Once you find a few things that work, you will find more; it becomes addictive.
Comment: I'm not looking to create a melody to go with the bass line. I'm looking to figure out what the notes are in the bass line.
Answer: If you have a tune in your head - which you can keep in your head whilst also playing a random bunch of conflicting notes over it - then just use the 'machine gun' method. Keep firing until you hit something.

Sing your note.
Start at any C on the piano* - sing your note, play the key.
Does it match?

Yes - move on to the next note in your tune & repeat the process.
No - play the next key up until you find the match.

This method, assuming you can actually tell when you have the right note, even if it's in the wrong octave, is literally fool-proof. It relies on no musical knowledge whatsoever, only on the ability to recognise when the two notes match.
Because of the high possibility that doing this will make you lose track of what note you're actually trying to find, record your sung line [on anything, computer, phone, it doesn't matter] so you can keep referring back to it.
*or start at any note you can recall the position of, even if you don't know its name. [You're going to have to find its name and its equivalent on the bass at some point, or you have to do this exercise again to translate it to bass guitar.]


Homotopy limits commute

Question: I'm looking for a reference for the fact that homotopy limits commute. That is
$\mathrm{holim}_U \mathrm{holim}_W E = \mathrm{holim}_W\mathrm{holim}_U E $.
Preferably looking for a result that define homotopy limit as the right derived functor of $\lim$.
Comment: This should be the Fubini theorem (31.5) in a paper by Chachólski and Scherer:
https://arxiv.org/pdf/math/0110316.pdf
Answer: I couldn't find a reference for this either, so came up with this argument of the cuff.
We can define homotopy limits as the right derived functor of $\lim$, and recall that this is a right adjoint - this is really the crucial thing to note.
Then $\mathrm{holim}_U \mathrm{holim}_W E = \mathrm{holim}_U \lim_W RE$, where $R$ denotes fibrant replacement.
(Note that I am implicitly assuming that $E$ is in a nice model category with a functorial factorisation, so the fibrant replacement functor exists)
Now $\mathrm{holim}$ is a right adjoint functor hence commutes with limits, it follows that
$\mathrm{holim}_U \lim_W RE = \lim_W \mathrm{holim}_U RE$
Now since $RE$ is fibrant already, this last is,
 $$ \lim_W \lim_U RE$$.
Now if you take the other side of the equation, and follow the same process we get
$$ \mathrm{holim}_W \mathrm{holim}_U E = \mathrm{holim}_W \lim_U RE = \lim_U \mathrm{holim}_W RE = \lim_U \lim_W RE = \lim_W \lim_U RE$$
with the last equality following by the fact limits commute [ this is just a special case of right adjoints preserving limits]

Homotopy limits commute


Descobrir evento executado

Question: Fiz o seguinte comando para exibir um loading sempre que fizer um submit dos forms do projeto.
<code>$("button[data-noPreload!='true'][type='submit']").click(openPreloading);
function openPreloading() {
    $("#icoCarregando").fadeIn();
}
</code>
Encontrei este outro código para ajudar a corrigir uma falha para fechar a tela de loading quando houver erros no preenchimento do formulário.
<code>$("form").bind("invalid-form.validate", function () {
    $("#icoCarregando").hide();
});
</code>
Até aqui tudo estava funcionando bem, o problema cujo estou precisando de ajuda é quando o usuário da um duplo clique para salvar um formulário cujo com erro, o evento criado acima parece não surtir efeito, assim abrindo a tela de Loading, ao debugar consegui identificar que as funções criadas acima estão sendo executadas porém parece esta executado algum evento a mais onde carrega o loading.
Existe alguma forma de identificar qual evento pode estar sendo executado e causando esse problema? Ou sabe como posso estar contornando essa falha?
Agradeço a atenção!
Comment: `C#` é realmente a _tag dominante_ para essa questão?
Comment: @LuizFelipe, tag removida.
Answer: Será que não está abrindo duas vezes o ícone carregando com o duplo clique?
Tenta alterar as tuas funções para essa forma:
<code>var carregando = false;
$("button[data-noPreload!='true'][type='submit']").click(openPreloading);
function openPreloading() {
    if(carregando === false){
        $("#icoCarregando").fadeIn();
        carregando = true;
    }
}

$("form").bind("invalid-form.validate", function () {
    $("#icoCarregando").hide();
    carregando = false;
});
</code>
Comment: Conseguiria fazer um exemplo do teu código funcionando para que possamos analisar melhor?
Comment: Refiz o teste conforme você passou! Funcionou perfeitamente! Agradeço muito a ajuda!

Descobrir evento executado


Forcing flag to be unique

Question: In Drupal 7, using Flags (and possibly Rules or another contrib module) how can I force a flag to be unique for a specific content type.  I do not want to force users to manually 'unflag' content before 'flagging' a new node.  I would like reviously flagged nodes to be automatically unflagged once a new flag has been set.
The goal is to allow users to select a 'default node' by use of flags.  Only one default node should be allowed.
How can I force and automate flag uniqueness?
Answer: Drupal Rules has a Trim-A-Flag action that lets you set a 'queue' size, or a 'max' number of flags allowed.  If you set the queue to 1, you can force a flag to be unique, and have it automatically update when a new entity is flagged.
Screenshot below.
Answer: You could use hook_flag($action, $flag, $content_id, $account) to do this. In this hook, check for content type, and then unflag all unneeded nodes.

Forcing flag to be unique


spring-boot-starter-thymeleaf and thymeleaf-layout-dialect works without explicit LayoutDialect bean - is it OK?

Question: I have a Spring boot Maven project:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath/>
    </parent>

In dependencies there are:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

The versions are:

org.springframework.boot:spring-boot-starter-thymeleaf:jar:3.2.0
nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar:3.3.0

This instruction says:

To get started with Layout Dialect we need to include it into the pom.xml. The dependency is:
<dependency>
  <groupId>nz.net.ultraq.thymeleaf</groupId>
  <artifactId>thymeleaf-layout-dialect</artifactId>
  <version>2.0.5</version>
</dependency>

We will also need to configure the integration by adding an additional dialect to our template engine:
@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    ...
    templateEngine.addDialect(new LayoutDialect());
    return templateEngine;
}

I don't add the SpringTemplateEngine bean and my project works.
Some other instructions say I need to add the nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect bean that I also don't add.
For investigation purpose I use the following controller:
@Controller
public class DemoController {

    @Autowired
    LayoutDialect layoutDialect;

    @GetMapping("/demo")
    public String getAllUsers() {
        System.out.println(layoutDialect);
        return "thymeleaf_first_page";
    }
}

And in the console i see:
nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect@7c6ab057

That means that the bean exists in the context.
QUESTION
Can you confirm that with my newer versions of Spring Boot and spring-boot-starter-thymeleaf it's not required to explicitly add the LayoutDialect bean?
Is there any documentation about it?
UPDATE
This is not much important for the question but will add some illustration of what was done.
The layout is (src/main/resources/templates/layout/layout.html):
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title layout:fragment="title"></title>

    LOGO LINK1 LINK2

This content must not be visible.

Footer information

The page is (src/main/resources/templates/thymeleaf_first_page.html):

    <title layout:fragment="title">Thymeleaf demo</title>

Thymeleaf template extension demo

Actual page content: []

The result is:
<!DOCTYPE html>

    <meta charset="UTF-8">

    <title>Thymeleaf demo</title>

    LOGO LINK1 LINK2

Thymeleaf template extension demo

Actual page content: [some value from the model]

Footer information

Answer: Looks like as for the Thymeleaf version 3.1 template extension is supposed to be done using the other mechanism described in Tutorial: Using Thymeleaf (3.1.2.RELEASE), chapter 8.5 Layout Inheritance:
The layout is (src/main/resources/templates/layout/layout_simple.html):
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title th:replace="${title}">Layout title</title>

Common block: header

This content must not be visible.

Common block: footer

The page is (src/main/resources/templates/thymeleaf_first_page_simple.html):
<!DOCTYPE html>

    <title>Thymeleaf demo simple</title>

Thymeleaf template extension simple demo

Actual page content: []

The result is:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Thymeleaf demo simple</title>

Common block: header

Thymeleaf template extension simple demo

Actual page content: [some simple value from the model]

Common block: footer

So no need to use the dependency nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar (and to define the LayoutDialect bean).


Erro nos índices de um array

Question: Estou tentando fazer um algoritmo de selection sort, só para treinar algoritmos mesmo, ao meu ver minha lógica está certa quanto a ordenação, mas ele está me retornando um erro que não entendo.
Código:
import java.util.Scanner;
import java.util.Arrays;

public class AlgoritmosOrdenacao {

static int[] SelectionSort(int vet[]){
    int aux, menor;
    for (int i=0; i<vet.length-2; i++){
        menor = vet[i+1];
        for (int j=i+1; j<vet.length-1; j++){
            if (menor > vet[j+1]){
                menor = vet[j+1];
            }
        }
        aux = vet[i];
        int idx = Arrays.asList(vet).indexOf(menor);
        vet[i] = menor;
        vet[idx] = aux;
    }
    return vet;
}

 public static void main(String[] args) {
    // TODO code application logic here
    // INPUT DO VETOR
    int vet[] = new int[5];
   Scanner teclado = new Scanner(System.in);
   for (int i=0; i<vet.length; i++){
       vet[i] = teclado.nextInt();
   }
   // PRINT DO VETOR ANTES DA ORDENAÇÃO
   for (int z=0; z<vet.length; z++){
       System.out.printf("Vet[%d] = %d\n", z, vet[z]);
   }
   SelectionSort(vet);

   // PRINT DO VETOR DEPOIS DA ORDENAÇÃO
   System.out.println("Depois da ordenação");
   for (int z=0; z<vet.length; z++){
       System.out.printf("Vet[%d] = %d\n", z, vet[z]);
   }
}

E o erro completo é esse:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at algoritmosordenacao.AlgoritmosOrdenacao.SelectionSort(AlgoritmosOrdenacao.java:48)
at algoritmosordenacao.AlgoritmosOrdenacao.main(AlgoritmosOrdenacao.java:69)
C:\Users\angel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 5 segundos)

Na linha: int idx = Arrays.asList(vet).indexOf(menor); o Netbeans sublinha vet e dá a seguinte sugestão:

array de primitiva confuso especificado para o método vararg.
Answer: O problema está em Arrays.asList(vet). Quando você passa um array de int, o resultado é um List<int[]> - ou seja, uma lista de int[] (de arrays de int), e não uma lista de int. Exemplo:
int v[] = { 1, 2, 3, 4, 5 };
for (Object obj : Arrays.asList(v)) {
    System.out.println(obj.getClass().isArray());
}

Estou usando getClass() para obter a classe de cada elemento da lista, e em seguida uso o método isArray(), que verifica se a classe em questão representa um array. A saída é:

true

true é impresso apenas uma vez, pois a lista retornada por Arrays.asList só possui um elemento: o array de int. Se quiser, pode verificar o tamanho da lista usando o método size():
int v[] = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.asList(v).size()); // 1

Este código imprime "1", pois a lista só possui um elemento (o array de int).
De qualquer forma, como os elementos desta lista são arrays, indexOf não encontrará o int que você está passando. indexOf verifica se o int é um elemento da lista, mas como a lista só possui um array como elemento, o int não é encontrado (o fato do int estar dentro do array não importa, indexOf não encontrará o int).
E quando ele não encontra o elemento, o retorno é -1:
int v[] = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.asList(v).indexOf(2)); // -1

E ao tentar acessar a posição -1 do array (vet[idx], sendo que idx é -1), ocorre o erro de ArrayIndexOutOfBoundsException, já que as posições de um array começam em zero (não há posições negativas).

Como você quer obter o índice do menor elemento, basta setar este valor quando você encontrá-lo. Não há motivo para criar uma nova lista e percorrê-la a cada iteração (além de ser desnecessário, é extremamente ineficiente ficar criando uma nova lista a cada iteração).
Se você setar o valor do índice quando o menor elemento for encontrado, não precisará criar a lista toda hora:
static int[] selectionSort(int vet[]) {
    for (int i = 0; i < vet.length - 1; i++) {
        int indiceMenor = i; // indiceMenor começa com o índice do elemento atual
        for (int j = i + 1; j < vet.length; j++) {
            if (vet[j] < vet[indiceMenor]) { // vet[j] é menor que o "menor atual"
                indiceMenor = j; // índice do menor passa a ser j
            }
        }
        int menor = vet[indiceMenor];
        vet[indiceMenor] = vet[i];
        vet[i] = menor;
    }
    return vet;
}

Repare também que dei uma mudada no algoritmo, e também coloquei o nome do método começando com letra minúscula, seguindo as convenções de código do Java.
Comment: Muito obrigado pela explicação, me esclareceu bastante além de ter aprendido algo novo também, muito obrigado mais uma vez. =D
Answer: Bom, Isso significa que está tentando pegar o elemento que está no index "-1", porem não existe
O que está acontecendo:
Nesta linha Arrays.asList(vet).indexOf(menor); o indexOf não está encontrando o menor valor na lista, e quando acontece isso essa função retorna -1.
Sendo assim nesta linha vet[idx] = aux; está dando a exceção ArrayIndexOutOfBoundsException que informa que está sendo acessado um elemento em um indice que não existe, como o array começa em 0 não tem como acessar o -1.
Para resolver isso sugiro guardar o índice do menor valor, junto com ele.
Assim esta linha:
menor = vet[i+1];

deveria ser modificada para
menor = vet[i+1];
idxMenor = i+1;

e esta linha:
menor = vet[j+1];

para:
menor = vet[j+1];
idxMenor = j+1;

Assim não precisa converter o array para lista e encontrar novamente o valor (o que por sinal é muito mais custoso, porque procurar as informações que estão um pouco mais acima no código?)
Answer: Na linha Arrays.asList(vet).indexOf(menor) o indexOf não estava encontrando o menor valor na lista e retornava -1.
Tente o seguinte código para fazer sua ordenação correta:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class AlgoritmosOrdenacao
{

    static int[] SelectionSort(int vetor[]){
        int aux = 0;
        for (int i = 0; i < vetor.length; i++)
        {
            for (int j = 0; j < vetor.length; j++)
            {
                if (vetor[i] < vetor[j])
                {
                    aux = vetor[i];
                    vetor[i] = vetor[j];
                    vetor[j] = aux;
                }
            }
        }
        return vetor;
    }

     public static void main(String[] args) {
            // TODO code application logic here
            // INPUT DO VETOR
            int vet[] = new int[5];
           Scanner teclado = new Scanner(System.in);
           for (int i=0; i<vet.length; i++){
               vet[i] = teclado.nextInt();
           }
           // PRINT DO VETOR ANTES DA ORDENAÇÃO
           for (int z=0; z<vet.length; z++){
               System.out.printf("Vet[%d] = %d\n", z, vet[z]);
           }
           List<int[]> a = Arrays.asList(vet);
           System.out.println();

           SelectionSort(vet);

           // PRINT DO VETOR DEPOIS DA ORDENAÇÃO 2
           System.out.println("Depois da ordenação 2");
           for (int z=0; z<vet.length; z++)
           {
               System.out.printf("Vet[%d] = %d\n", z, vet[z]);
           }
    }
}

Erro nos índices de um array


Wrong forwarding of rvalue reference

Question: I was experimenting with the newly added rvalue refernces ( in vs2012 express ).
I don't understand something tho. Given the code below ( most of it taken from the c++ standard where std::forward is explained ).
struct A
{
    A(int& i, const float& j):
        m_i(i),
        m_j(j){}

    int& m_i;
    const float& m_j;
};

template<class T, class A1, class A2>
T* factory(A1&& a1, A2&& a2)
{
    return new T(a1, a2);
}

void test()
{

    A* a1 = factory(1, 1.2f);

    //How does this work ?
    a1->m_i = 2;
}

I don't understand where is m_i binded to.
I will basically have a lvalue reference to an rvalue reference (& &&), that by the ref collapsing rules becomes (&) just a plain lvalue ref. But a reference to what?
Answer:
I don't understand where is m_i binded to.

m_i is bound to the argument of A's constructor. What is the argument of A's constructor here?
In this case, since factory does not forward its argument to A (i.e. it does not use std::forward<>()), then what is being passed to A is an lvalue. This is because a1 is named, and named objects are lvalues.
The type of a1 is not relevant to determine whether a1 is an lvalue or an rvalue. So even though a1 has type rvalue-reference to int (int&&), as is the case in your program, the parameter a1 is itself a named object, and therefore it is an lvalue.
This means, since m_i has type lvalue-reference to int, that m_i can be bound (and indeed is bound) to factory's (lvalue) parameter a1, which will be destroyed when factory() returns. In other words, you're left with a dangling reference.
Attempting to dereference it (as you do later on in your program) summons Undefined Behavior.
However, if your factory() function had forwarded its arguments to A's constructor:
template<class T, class A1, class A2>
T* factory(A1&& a1, A2&& a2)
{
    return new T(std::forward<A1>(a1), std::forward<A2>(a2));
}

This would have caused a compiler error, because the machinery of std::forward<>() would make sure that lvalues stay lvalues, and rvalues stay rvalues. Attempting to bind an lvalue-reference to an rvalue is illegal, and therefore the call to A's constructor would have failed.
Comment: As Scott Meyers pointed out, any use of a universal reference (`T&&` with a type-deduced `T`) without either a `std::forward` or a `std::move` is at the very least dubious. Now I can clearly see why.
Answer:
But a reference to what?

This is an undefined behavior. As you have guessed right, it is a reference to a temporary that was destructed in stack of the function factory. To catch such issues in compile time, you need to use std::forward
template<class T, class A1, class A2>
T* factory(A1&& a1, A2&& a2)
{
    return new T(std::forward<A1>(a1), std::forward<A2>(a2));
}

Comment: `A1&& a1` need not be a rvalue_ref it can accept a lvalue_ref too as they type is deduced by the template. so whenever a type is deduced by template and you wan't to preserve the type of the reference across function calls, you have to use `std::forward`
Comment: ups....i accidentally deleted my coment. thanks.
Old comment: do i always need to use std:: forward with lvalue references? )

Wrong forwarding of rvalue reference


The results of EFA are different from those of theory, how to conduct CFA?

Question: I have a dependent construct (attitude) which has at least 2 dimensions in theory (affective & behavioral). The scale measure adopted for this research is found to have 2 or 3 dimensions in literature. Thus, on the theoretical level, this construct should be a second order factor when conducting CFA in AMOS.
But, the EFA of 782 cases data-set in SPSS shows that there is only one factor, not two, and this is what the sample presents.
So, in this case, when the results of EFA are different from those of theory, what should we do? Can we still treat this construct as a second (higher) order factor with two dimensions (sub-factors)? Or do we have to respect the results of the EFA and treat it as only one factor?
Answer: If you have a theory, then you should test it with CFA.
The problem with EFA is that there are an infinite number of solutions, all of which are (statistically) equally good when (talking about rotation).
There is no point testing a second order factor with only two indicators - that model is exactly equivalent to a two correlated factor model.
Comment: +1, but "infinite number of solutions" probably refers to the freedom of factor rotations, which does not change the number of factors, whereas this Q seems to be primarily about number of factors in EFA being less than expected. Perhaps you can expand your answer to comment on that?
Comment: Thanks a lot for your response. Actually the general theory of consumer attitudes say that this concept is multidimensional. Attitude here is a DV in an overall model. And, I couldn't figure out how to treat the results of EFA in this case. Should I ignore it completely, sir? and what should I say in my report about that?
Comment: @amoeba, yes, I should have been clear about that.


Proving that $F$ is continuous

Question: Let $f:[0,1] \times \mathbb{R} \to \mathbb{R}$ continuous function and consider $F(y)= \int_0^1 f(x,y) dm(x)$. I want to show that $F$ is continuous.
I tried: Take $y' \in \mathbb{R}$. Let $(y_n)_n$ any sequence such that $y_n \to y'$. I have to show that $\lim F(y_n)=F(y')$. For that I want to use some convergence theorem. Define $f_n(x)=f(x,y_n)$ using continuity of $f$ then:
$$ \lim_{n \to \infty} f_n(x)= \lim_{n \to \infty} f(x,y_n)= f(x,y)$$
I cannot finish. I cannot the limit of the sequence $f_n$.
Answer: Fix $y \in \mathbb{R}$. Note that $f$ is uniformly continuous in the compact set $K:= [0,1] \times [y-1,y+1]$. Now, let $\varepsilon > 0$.
By uniform continuity in $K$, there exists $\delta > 0$ such that if $\|(x,y)-(x',y')\| < \delta$ and $(x,y),(x',y') \in K$ then $|f(x,y)-f(x',y')| < \varepsilon/2$.  Without loss of generality, we can additionally assume $\delta < 1$.
If $|y-y'| < \delta$, then we get that $\|(x,y)-(x,y')\| < \delta$ for each $x \in [0,1]$. Moreover it has to be $(x,y),(x,y') \in K$ because $|y-y'| < \delta < 1$. This says that
$$
|f(x,y)-f(x,y')| < \varepsilon/2 \quad (\forall y' \in B_\delta(y), x \in [0,1])
$$
and thus
$$
|F(y)-F(y')| \leq \int_0^1|f(x,y)-f(x,y')|d\mu \leq \int_0^1\varepsilon/2 \cdot d\mu = \varepsilon/2 < \varepsilon.
$$
which concludes the proof: for a given $\varepsilon$, we have found $\delta > 0$ such that if $|y-y'| < \delta$, then $|F(y)-F(y')| < \varepsilon$.
Answer: If we are allowed to use Lebesgue integration theory, it is easy.
Let $a\in\mathbb{R}$ be arbitrary. We go to show that $F$ is continuous
at $a$. Since $f$ is continuous on the compact set $[0,1]\times[a-1,a+1]$,
there exists $M>0$ such that $|f(x,y)|\leq M$ for any $(x,y)\in[0,1]\times[a-1,a+1]$.
Let $(y_{n})$ be an arbitrary sequence that converges to $a$. Without
loss of generality, we may assume that $y_{n}\in[a-1,a+1]$ for all
$n$. (For clarity reason for beginners...) For each $n$, define
a function $g_{n}:[0,1]\rightarrow\mathbb{R}$ by $g_{n}(x)=f(x,y_{n})$.
Define $g:[0,1]\rightarrow\mathbb{R}$ by $g(x)=f(x,a)$. Clearly
$g_{n}$ and $g$ are Lebesgue integrable (in fact, they are continuous).
Moreover, $|g_{n}|\leq M$ and $g_{n}\rightarrow g$ pointwisely by
the continuity of $f$ and the fact that $(x,y_{n})\rightarrow(x,a)$.
Therefore
\begin{eqnarray*}
 &  & \lim_{n\rightarrow\infty}F(y_{n})\\
 & = & \lim_{n\rightarrow\infty}\int_{0}^{1}g_{n}(x)dx\\
 & = & \int_{0}^{1}g(x)dx\\
 & = & F(a).
\end{eqnarray*}
By Heine's Theorem, it follows that $F$ is continuous at $a$.
Comment: The $M$ you use to limit $g_n$ depends on n?
Comment: No. The $M$ is an upper bound of $f$ restricted on $[0,1]\times [a-1,a+1]$. You can verify that $|g_n(x)|\leq M$ for all $x\in [0,1]$ and $n\in\mathbb{N}$.
Comment: A typo. It should be "$M$ is an upper bound of $|f|$ restricted..."
Answer: Another proof that does not involve any Lebesgue integration theory:
Let $b\in\mathbb{R}$ be arbitrary. We go to prove that $F$ is continuous
at $b$. Let $\varepsilon>0$ be given. For each $a\in[0,1]$, since
$f$ is continuous at $(a,b)$, there exists $\delta_{a}>0$ such
that $|f(x,y)-f(a,b)|<\varepsilon$ whenever $|x-a|<\delta_{a}$ and
$|y-b|<\delta_{a}$. Note that $\{(a-\delta_{a},a+\delta_{a})\mid a\in[0,1]\}$
is an open covering of the compact set $[0,1]$, so there exists a
finite sub-cover. Choose a finite sub-cover and denote it by $\{(a_{i}-\delta_{a_{i}},a_{i}+\delta_{a_{i}})\mid i=1,\ldots,n\}$
for some $n\in\mathbb{N}$ and $a_{i}\in[0,1]$. Define $\delta=\frac{1}{2}\min_{1\leq i\leq n}\delta_{a_{i}}>0$.
We go to show that $|F(y)-F(b)|\leq2\varepsilon$ whenever $|y-b|<\delta$.
Let $y\in\mathbb{R}$ such that $|y-b|<\delta$. Let $x\in[0,1]$
be arbitrary, then $x\in(a_{i}-\delta_{a_{i}},a_{i}+\delta_{a_{i}})$
for some $i$. For the point $(x,y)$, we clearly have $|x-a_{i}|<\delta_{a_{i}}$
and $|y-b|<\delta<\delta_{a_{i}}$. Therefore $|f(x,y)-f(a_{i},b)|<\varepsilon$.
For the point $(x,b),$we also have $|x-a_{i}|<\delta_{a_{i}}$ and
$|b-b|=0<\delta_{a_{i}}$, so $|f(x,b)-f(a_{i},b)|<\varepsilon$.
It follows that
\begin{eqnarray*}
|f(x,y)-f(x,b)| & \leq & |f(x,y)-f(a_{i},b)|+|f(a_{i},b)-f(x,b)|\\
 & < & 2\varepsilon.
\end{eqnarray*}
It follows that
\begin{eqnarray*}
 &  & |F(y)-f(b)|\\
 & \leq & \int_{0}^{1}|f(x,y)-f(x,b)|dx\\
 & \leq & 2\varepsilon.
\end{eqnarray*}
Answer: Suppose $y_n \to y$, note that $f$ is bounded by some $B$ on the compact set $[0,1] \times \{y_n\}_n \cup \{y\}$, hence $|f(x,y_n) | \le B$, which is integrable. Since $f(x,y_n) \to f(x,y)$ we see that $F(y_n) \to F(y)$.

Proving that $F$ is continuous


Is there a way to do concurrent editing?

Question: Is there a MediaWiki-like method for supporting concurrent editing of text bodies in Drupal 7?
If no feature currently exists, what are some decent PHP diff libraries that could be wrapped up by a Drupal module that could do the job?
Answer: You can use etherpad kind of feature which allows you to do concurrent edit of node body.
Etherpad is collaborative editor by which you can write any node field using concurrent editing. Check Readme.txt for installation purpose.
And one more thing if you have no permission to install etherpad on your server(as shared hosting will not allow it) then you can use Piratepad module, which allows you to embed the pad using iframe from piratepad site.
Comment: PiratePad is for D6, but +1
Comment: But i have ported to Drupal 7 with titanpad integration, but haven't posted on Drupal.org. if any one interested let me know, i can mail you
Comment: Yes please go ahead. Open Sandbox.


Need to show $f_k=o(f_{k-1})$ for $k > 1$

Question: Based off the description of an algorithm, I came up with the following worst-case run time
$$f_k(n)=n^{\frac 1 k}+f_{k-1}(n^{\frac{k-1}{k}})$$
$$f_2(n)=2 \sqrt n$$
I need to show that each $f$ becomes asymptotically slower than the previous, i.e.
$$\lim_{n \to \infty} \frac{f_k(n)}{f_{k-1}(n)}=0 \text{ for }k=2, 3, ...$$
I noticed after expanding the definition of $f_k$ for a few terms it is $O(n^\frac{1}{k})$ but from this previous question I asked, this was not enough to show the limit exists. At the moment I am stuck trying to prove this.
Comment: One possible way I see to have $f_{k-1}=\omega(n^{\frac{1}{k}})$. I'll think if it's possible to obtain this from recurrent relation, but, may be, from somewhere you already have such condition?
Comment: @zkutch I don't think I have that condition yet
Answer: As promised in comment I solve recurrent relation (but ask you double check it):
$$\begin{array}{l}f_k(n)=n^{\frac 1 k}+f_{k-1}(n^{\frac{k-1}{k}})=\\
=n^{\frac 1 k}+ n^{\frac{k-1}{k}\cdot \frac{1}{k-1}}+f_{k-2}(n^{\frac{k-1}{k}\cdot \frac{k-2}{k-1}}) = 2n^{\frac 1 k}+ f_{k-2}(n^{\frac{k-2}{k}}) =\\
= 2n^{\frac 1 k} +  n^{\frac{k-2}{k}\cdot \frac{1}{k-2}}+f_{k-3}(n^{\frac{k-2}{k}\cdot \frac{k-3}{k-2}}) = 3n^{\frac 1 k}+ f_{k-3}(n^{\frac{k-3}{k}}) =\\
=\cdots = mn^{\frac 1 k}+ f_{k-m}(n^{\frac{k-m}{k}}) = \cdots = \lvert \text{ taking }k-m=2\rvert=\\
=(k-2)n^{\frac 1 k}+ f_{2}(n^{\frac{2}{k}}) =kn^{\frac 1 k}\end{array}$$
Now it's obvious to say that
$$\lim_{n \to \infty} \frac{f_k(n)}{f_{k-1}(n)}=\lim_{n \to \infty}\frac{k}{k-1}n^{\frac{1}{k}-\frac{1}{k-1}}=0 $$
And, at end,  $f_k(n)=kn^{\frac 1 k}\in \Theta(n^{\frac 1 k})$.
Comment: Madman I think you did it. Looking back at my scribbles I had the arguments all wrong and nothing simplified down.
Comment: Glad to be useful.
May I know which algorithm you are working with? I myself deal with similar issues.
Comment: The algorithm I was looking at is a solution to Algorithm Design (Kleinberg-Tardos) chapter 2 exercise 8b. This article provides the problem text and the link to the pdf at the end of the article provides the description of the algorithm: https://itsiastic.wordpress.com/2013/08/15/algorithms-design-chapter-2-exercise-8/ Neither the article or the pdf really give a proper proof that $f_k(n)=o(f_{k-1}(n))$ so that's what I've been trying to prove.
Answer: $f_k(n)
=n^{\frac 1 k}+f_{k-1}(n^{\frac{k-1}{k}})
$
so
$f_k(n^k)
=n+f_{k-1}(n^{k-1})
$.
Letting
$g_k(n)
=f_k(n^k)
$,
$g_k(n)
=n+g_{k-1}(n)
$.
Therefore
$n
=g_k(n)-g_{k-1}(n)
$
so
$\begin{array}\\
(m-2)n
&=\sum_{k=3}^mn\\
&=\sum_{k=3}^m(g_k(n)-g_{k-1}(n))\\
&=g_m(n)-g_{2}(n)\\
&=g_m(n)-f_{2}(n^2)\\
&=f_m(n^m)-2n\\
\end{array}
$
so
$f_m(n^m)
=mn
$
or
$f_m(n)
=mn^{1/m}
$.
Therefore
$\begin{array}\\
\dfrac{f_m(n)}{f_{m-1}(n)}
&=\dfrac{mn^{1/m}}{(m-1)n^{1/(m-1)}}\\
&=\dfrac{m}{m-1}n^{1/m-1/(m-1)}\\
&=\dfrac{m}{m-1}n^{-1/(m(m-1))}\\
&\to 0
\qquad\text{as } n \to \infty\\
\end{array}
$
for fixed $m$.
Comment: Nice  approach .


How do I use the GTranslate module?

Question: I have installed the GTranslate module, and I am searching for how to use it. In the module page, the language selection drop-down box is there, but when I installed this module the drop-down list didn't appear. How do I use the GTranslate module?
Answer: Google Translate changed their policy, this module does not work anymore according to the issue queue.
There seems to be a newer version on an external website, which also offers a paid Pro version that seems to require ioncube encoder which means that it is encrypted, which sounds like a violation of the GPL to me.
Comment: Any free automatic translation (node) module available in Drupal ?

How do I use the GTranslate module?


Are there sports in which game theory is explicitly used?

Question:
Game theory [interactive decision theory] is mainly used in economics, political science, and psychology, as well as logic and biology.

I believe that I know that tennis serving and football penalty shooting more-or-less stick to their game-theoretical solutions. But are there sports that explicitly use game-theoretical analysis? (Or, perhaps easier to answer, are there game theorists employed or consulted by certain teams or individual players?)
NB: I am particularly interested in play or race strategy, not in acquisition strategy. (Moneyball, besides being statistical, not game-theoretical, isn't relevant to my question.)
Comment: I am sure the loaning of Romelu Lukaku by Chelsea to other premiership teams is an implementation of Game Theory. Giving your best striker to another team so they can defeat your competitors, yet is barred from playing against yourself.
Comment: Interesting article on penalties http://www2.owen.vanderbilt.edu/mike.shor/courses/game-theory/docs/lecture05/MixedSoccer.html
Answer: Game theory comes into play in American football play-calling.  To simplify the game, consider that the offense can run either a running play or a passing play.  The passing play generally has potential for more yards gained, but less chance of success than a running play.  The defense, on the other hand, also chooses a play that is either focused on stopping a running play or a passing play.
The coach calling the offensive play needs to look at the situation the team is in and balance the risk and reward for each type of play.  The Normal-form game matrix might look something like this:

Defense calls running
Defense calls passing

Offense calls running
0-3 yards gained
7+ yards gained

Offense calls passing
10-15+ yards gained
0 yards gained

Of course, the numbers in the matrix are just guesses based on how well the players on each team are playing, but coaches have something like this in mind when they are calling plays.


How to make a call via SIP protocol to landline phone in ios?

Question: I m working on a iPhone application to make a call from SIP protocol to landline phones, i got some samples to make a call from SIP to SIP but i did not get any solutions to make landline call from SIP protocol, please help me to do this.
Thanks.
Answer: From Apple Documentation ...
A Voice over Internet Protocol (VoIP) app allows the user to make phone calls using an Internet connection instead of the device's cellular service. Such an app needs to maintain a persistent network connection to its associated service so that it can receive incoming calls and other relevant data. Rather than keep VoIP apps awake all the time, the system allows them to be suspended and provides facilities for monitoring their sockets for them. When incoming traffic is detected, the system wakes up the VoIP app and returns control of its sockets to it.
There are several requirements for implementing a VoIP app:
Add the UIBackgroundModes key to your app's Info.plist file. Set the value of this key to an array that includes the voip string.
Configure one of the app's sockets for VoIP usage.
Before moving to the background, call the setKeepAliveTimeout:handler: method to install a handler to be executed periodically. Your app can use this handler to maintain its service connection.
Configure your audio session to handle transitions to and from active use.
To ensure a better user experience on iPhone, use the Core Telephony framework to adjust your behavior in relation to cell-based phone calls; see Core Telephony Framework Reference.
To ensure good performance for your VoIP app, use the System Configuration framework to detect network changes and allow your app to sleep as much as possible.
Including the voip value in the UIBackgroundModes key lets the system know that it should allow the app to run in the background as needed to manage its network sockets. This key also permits your app to play background audio (although including the audio value for the UIBackgroundModes key is still encouraged). An app with this key is also relaunched in the background immediately after system boot to ensure that the VoIP services are always available. For more information about the UIBackgroundModes key, see Information Property List Key Reference.
Try this link .. this might help
enter link description here


ImportError: libexslt.so.0: cannot open shared object file: No such file or directory

Question: I am trying to use python 2.7.8 came with splunk 6 for some XML parsing usign lxml.
from lxml import etree

I see below error
[root@**** bin]# ./python some.py
Traceback (most recent call last):
  File "some.py", line 1, in <module>
    from lxml import etree
ImportError: libexslt.so.0: cannot open shared object file: No such file or directory

Also I have this in splunk/lib/
lrwxrwxrwx  libexslt.so -> libexslt.so.0.8.17
lrwxrwxrwx  libexslt.so.0 -> libexslt.so.0.8.17
-r-xr-xr-x  libexslt.so.0.8.17

Thanks for the help
Comment: See: [Why can't Python find shared objects that are in directories in sys.path?](http://stackoverflow.com/questions/1099981/why-cant-python-find-shared-objects-that-are-in-directories-in-sys-path)
Answer: Assuming you're running an operating system with manageable library paths through ldconfig utility (like GNU/Linux), you can try the following:
# echo "/your/path/to/splunk/lib" >> /etc/ld.so.conf.d/splunk.conf
# ldconfig

The problem here is that the search path for the shared object isn't set, so the application has no way to know where to find it.
If you're running an operating system that doesn't have ldconfig, i suggest you search a bit for the utility that manages the library paths for that particular case (or just update your question with more information).
If you don't have privileges on that system to perform such operations, you can use environment variables to set such search paths, as suggested in the link referred in the comments to your question (by @jedwards).
Answer: If you want to run something out of $SPLUNK_HOME/bin you should use the "splunk cmd" command to properly set up the environment first:

./splunk cmd python some.py

This is the preferred method if you'd like to use the Splunk python, and correctly emulates the way a python script would run if it was triggered from inside Splunk (as an alert script, for example).


closed immersion onto an affine scheme - showing affineness

Question: Let $A$ be a ring, $X=\operatorname{Spec}A$ and $f: Z \rightarrow X$ a morphism of schemes such that i) $f$ is a homeomorphism of topological spaces and ii) $f^{\#}:\mathcal{O}_X \rightarrow f_* \mathcal{O}_Z$ is a surjective morphism of sheaves.
Question 1: How can we show that $Z$ is an affine scheme?
I am trying to follow the hint of exercise II.3.11(b) in Hartshorne, but i am getting stuck: i can show that $Z$ can be covered by a finite number of $\operatorname{Spec}B_i$ and each $\operatorname{Spec}B_i$ can be covered by finitely many $D(\phi_i(a_{ij}))$, where $a_{ij} \in A$, and $\phi_i: A \rightarrow B_i$ is the ring homomorphism that corresponds to the restriction of $f$ to $\operatorname{Spec}B_i$. Now, if i am to apply exercise II.2.17(b), i would need to show that each of the $Z_{\phi(a_{ij})}$ is affine, where $\phi: A \rightarrow \Gamma(Z,\mathcal{O}_Z)$ is the ring homomorphism of global sections.
Question 2: Any ideas how we can show that $Z_{\phi(a_{ij})}$ is affine?
Question 3: Alternatively, i have been able to show that each $\operatorname{Spec}B_i$ is isomorphic as a scheme with $\operatorname{Spec}(A/I_i)$, where $I_i$ is the kernel of $\phi_i$. Any ideas how to continue for there?
Answer: Take an affine open covering of $Z$ by principal open sets, which will come from principal open sets in $X$. Extend to a covering of $X$ by adding principal open sets. $X$ is quasi-compact since it is affine, so this is a finite covering. Now we have a finite covering of $X$ by principal opens $D(f_i)$ so $f_1, \dots, f_r$ generate the unit ideal of $A$.
Each $Z_{f}$ is a principal open subset of $D(f) \cap Z$, since $Z_f = X_f \cap Z$ and $D(f) = X_f$. $D(f) \cap Z$ was affine, therefore, $Z_f$ is affine.
Ex 2.17b (affineness criterion) applies to show that $Z$ is affine.
As shown, $Z = \text{Spec } B$. By Ex 2.18d now, the map of rings $A \to B$ is surjective. By the Isomorphism Theorem, then we know that $B \cong A / I$.
Comment: Ex 2.17b tells you that the scheme is affine provided that the distinguished open sets are affine and the elements generate the unit ideal.
Comment: You can also use a different affineness criterion: if a scheme admits a finite affine covering $(U_i)$ such that $U_i \cap U_j$ also has a finite affine covering, then the scheme is affine.
Comment: They are principle open subsets of affine space $D(f_i)$.
Comment: For a general scheme $X$, $X_f$ is supposed to be a generalized version of $D(f)$ for affine schemes.
Comment: I edited the answer adding both the line of reasoning I explained in above comments and also a new one that tries to incorporate Ex 2.16. I am confident in the reasoning in comments, but I just thought of the Ex 2.16 reasoning so let me know if you feel there is an error in it.
Comment: Well, being a subset set-theoretically is immediate since $D(f) = X_f$ and $Z_f = X_f \cap Z$. Similar reasoning should convince you that it is principal open.
Comment: Ok, I've done that.