Unable to play sound twice Android MediaPlayer application crashing

Question: Unable to play sound twice causing Android MediaPlayer application to crash
    mp = MediaPlayer.create(context, R.raw.audio1);
    final ImageButton play = (ImageButton) findViewById(R.id.play_button_dua_seher);

    play.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.reset();
                    mp.release();
                    mp = MediaPlayer.create(context, R.raw.audio1);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    final ImageButton stop = (ImageButton) findViewById(R.id.stop_button_dua_seher);
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mp != null)
            {
                mp.stop();
                mp.reset();
                mp.release();
            }
        }
    });

Logcat
06-15 14:34:59.470 11697-11697/com.toptech.android.ramadanduas

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.toptech.android.ramadanduas, PID: 11697
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.toptech.android.ramadanduas.duaseher$2.onClick(duaseher.java:53)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit

Comment: mb player isPlaying and u play again?=)
Comment: First Time played correct second tap on stop button cause crashing in app. See Java file also Thank you in advance
Comment: Stop Button Working Properly Now (y) but Play button cannot play sound on second attempt after stop first time...!! Suggestion needed.
Answer: Seems like the problem is you call release() on your MediaPlayer instance when clicking the stop button, but you don't check it's state when (re)starting the playback.
This means you could call isPlaying() on a released MediaPlayer instance, which will lead to an IllegalStateException.
You should somehow keep track of the state of the MediaPlayer instance (with a boolean flag for example) or set it to null after the release so you could perform null value checks after.
You could do something like this:
// in your play button's onClick()
if (mp != null && mp.isPlaying()) { // check for null value also
    mp.stop();
    mp.reset();
} else {
    mp = MediaPlayer.create(context, R.raw.audio1);
}
mp.start();

and
// in your stop button's onClick()
mp.release();
mp = null; // set it to null


botão dentro de variável PHP

Question: Olá,
No php há alguma forma de fazer o botão abaixo chamar a função desliga()
$button2 = "<input type='button' id='php_button' value='desliga' onclick='desliga()'>";
echo $button;

ao clicar no botão aparece o erro: Uncaught ReferenceError: desliga is not defined onclick
Explicarei melhor o que preciso.
Preciso criar alguns botões de forma dinâmica pois o número de botões pode mudar. Por exemplo pode ser que eu necessite de 5 botões com nomes diferentes que chamem a mesma função.
usando só html conforme descrito abaixo funciona, mas desse jeito eu não consigo criar os botoes de forma dinamica.
Da forma descrita abaixo o código funciona, mas o que eu quero é poder criar quantos botoes eu quiser de acordo com o resultado do num_rows de uma query sql.
<?PHP
function liga(){
echo "teste";
}

<input type="submit" name="liga" value="liga"/>

if (isset($_REQUEST['liga'])) {
    unset($_REQUEST['liga']);
    liga();

?>
Comment: Melhorou. Onde está esta função `liga()`? Ela está escrita em JS ou PHP? Se estiver em JS, já adianto que não é possível fazer isto. Como eu disse, as linguagens são independentes, apesar da crença popular que elas trabalham juntas. Não é fácil responder com códigos parciais. Não quer dizer que precisa colocar tudo o que você tem mas algo mínimo que possa produzir um resultado útil. http://pt.stackoverflow.com/help/mcve
Comment: Ainda não dá para entender o que você quer. Fora uns erros de organização e sintaxe o que você está demonstrando funciona mas eu duvido que faça o que você quer. Se você não conseguir demonstrar o que você quer fazer, eu não conseguirei responder. Espero que outra pessoa consiga mas provavelmente será quem der o melhor chute. Veja funcionando http://ideone.com/bRPhwd. Vou repetir: se você acha que PHP e JS são a mesma linguagem, que você pode escrever tudo misturado e vai funcionar, esqueça. Se quer uma solução para o problema, descreva coerentemente o real problema.
Comment: É impossível fazer o que você quer da forma como você está demonstrado. Se tiver outras partes de código que ajudem esclarecer o que está tentando fazer, talvez tenha uma outra solução. Mas em geral parece ser impossível. PHP e JS são linguagens diferentes e completamente independentes.
Comment: tentei explicar melhor veja se voc~e pode me ajudar
Comment: certo, eu coloquei um exemplo de função
Comment: é o típico erro dos principiantes em misturar o que é server side e client side.. Acho que um melhor caminho é orientar o Roberto a entender server-side e client-side, browser, servidores, etc.
Answer: Em PHP é possível sim, mas você está chamando um método em javascript. O mais próximo para o que você precisa é fazer este método em javascript que fará a chamada de uma nova página onde rodará o método em PHP:
HTML:
<input type='button' onclick='desliga(1)'>
<input type='button' onclick='desliga(2)'>

Note que um id está sendo passado como parâmetro, assim você poderá ter vários botões na mesma página, chamando o mesmo método, diferenciando a ação por esse id.
PHP

desliga($_GET['id']);

function desliga($id){
    echo "teste, id: " . $id ;
}

?>

Considere estuar mais a respeito de requisições client-side (HTML, javascript, etc) e server-side (PHP, acesso a banco, etc). Esta solução pode ficar mais "elegante" em ajax. Considere estudar isso também.

botão dentro de variável PHP


Como eu pego a posição que o usuário deseja?

Question: Funciona assim, Eu quero obter todas as possibilidades de jogada do cavalo no xadrez, mas como eu vou saber a posição que o usuário quer? Como eu faço? Eu não sei muita coisa de c. Na verdade com programação, estou começando. Por favor, preciso de uma luz!
<code>#include <stdio.h>
#include <locale.h>
#include <stdlib.h>

int main() {
  setlocale(LC_ALL, "Portuguese");

  int vetor[8], posicao, i, j;
  int matriz[8][8];
  matriz[0][0] = 'a1';
  matriz[0][1] = 'b1';
  matriz[0][2] = 'c1';
  matriz[0][3] = 'd1';
  matriz[0][4] = 'e1';
  matriz[0][5] = 'f1';
  matriz[0][6] = 'g1';
  matriz[0][7] = 'h1';

  matriz[1][0] = 'a2';
  matriz[1][1] = 'b2';
  matriz[1][2] = 'c2';
  matriz[1][3] = 'd2';
  matriz[1][4] = 'e2';
  matriz[1][5] = 'f2';
  matriz[1][6] = 'g2';
  matriz[1][7] = 'h2';

  matriz[2][0] = 'a3';
  matriz[2][1] = 'b3';
  matriz[2][2] = 'c3';
  matriz[2][3] = 'd3';
  matriz[2][4] = 'e3';
  matriz[2][5] = 'f3';
  matriz[2][6] = 'g3';
  matriz[2][7] = 'h3';

  matriz[3][0] = 'a4';
  matriz[3][1] = 'b4';
  matriz[3][2] = 'c4';
  matriz[3][3] = 'd4';
  matriz[3][4] = 'e4';
  matriz[3][5] = 'f4';
  matriz[3][6] = 'g4';
  matriz[3][7] = 'h4';

  matriz[4][0] = 'a5';
  matriz[4][1] = 'b5';
  matriz[4][2] = 'c5';
  matriz[4][3] = 'd5';
  matriz[4][4] = 'e5';
  matriz[4][5] = 'f5';
  matriz[4][6] = 'g5';
  matriz[4][7] = 'h5';

  matriz[5][0] = 'a6';
  matriz[5][1] = 'b6';
  matriz[5][2] = 'c6';
  matriz[5][3] = 'd6';
  matriz[5][4] = 'e6';
  matriz[5][5] = 'f6';
  matriz[5][6] = 'g6';
  matriz[5][7] = 'h6';

  matriz[6][0] = 'a7';
  matriz[6][1] = 'b7';
  matriz[6][2] = 'c7';
  matriz[6][3] = 'd7';
  matriz[6][4] = 'e7';
  matriz[6][5] = 'f7';
  matriz[6][6] = 'g7';
  matriz[6][7] = 'h7';

  matriz[7][0] = 'a8';
  matriz[7][1] = 'b8';
  matriz[7][2] = 'c8';
  matriz[7][3] = 'd8';
  matriz[7][4] = 'e8';
  matriz[7][5] = 'f8';
  matriz[7][6] = 'g8';
  matriz[7][7] = 'h8';

  printf("-----JOGO DE XADREZ-----\n");
  printf("Posição do cavalo: \n");
  scanf("Posição: %c\n", &posicao);
  vetor[0] = posicao;

  for (i = 0; i < 8; i++) {
    for (j = 0; j < 8; j++) {
      if (vetor[0] = matriz[8][8]) {

      }
    }
  }
}
</code>
Comment: Eae cara, eu entendi sua lógica, mas tem alguns problemas.
Primeiro: sua matriz é do tipo int(números inteiros) e vc está colocando uma string(texto) dentro.
Segundo: vetor também é do tipo int e vc está esperando receber algo como "a8"(que é uma string). Ou vc usa tudo como int ou tudo como string. Eu tenho um exemplo de tabuleiro de xadrez em C, mas é bom vc pensar um pouco, os problemas ajudam no aprendizado
Answer: <code>   // OBTÉM QUANTIDADE DE ROWS e itera no laço
  for (i = 0; i < sizeof(matriz) / sizeof(matriz[0]); i++) {
    //OBTÉM QUANTIDADE DE COLS
    for (j = 0; j < sizeof(matriz[0]) / sizeof(matriz[0][0]; j++)) {
      //COMPARA SE O TEXTO DIGITADO CONFERE COM ALGUM VALOR NA MATRIZ
      if (strcmp(matriz[i][j],posicao)) {
          printf("Posição escolhida: %c \n", matriz[i][j]);
      }
    }
  }
</code>
Talvez isso possa te ajudar. Não esqueça de declarar a matriz do tipo CHAR
char matriz[8][8];


Closed form of the Dirichlet kernel: $\sum\limits_{n=-N}^{N} e^{inx} =\frac{\sin((N+1/2)x}{\sin(x/2)}$

Question: I got some tedious computation on the way of showing the closed expression for the Dirichlet kernel. I do not understand one step. Perhaps one can help me? Is this somewhat Euler formula?
$$\sum_{n=-N}^{N} e^{inx} = ... = \frac{1-\exp(i(N+1)x}{1-\exp(ix)} + \frac{1-\exp(-iNx)}{1-\exp(-ix)}= \frac{\sin((N+1/2)x}{\sin(x/2)}$$
Question: how can I get the last equality?
Comment: what exactly is the problem?
Comment: I dont know how this last step follows...
Comment: OK: Try to muliply the first part by $e^{-ix/2}/e^{-ix/2}$ and the second part by $e^{ix/2}/e^{ix/2}$
Comment: Write instead that $\displaystyle\sum_{n=-N}^N e^{inx} = e^{-i N x} \sum_{n=0}^{2N} e^{inx} = e^{-i N x}  \frac{1-e^{i (2N+1) x} }{1-e^{ix}}$ and multiply the denominator and numerator by $e^{-ix/2}$
Answer: First (see Dirichlet kernel identity) prove that $$\sum\limits_{n=-N}^{N} e^{inx} = 1 + 2\sum\limits_{n=1}^{N} \cos (nx) .$$
Denote $D_N(x)=1 + 2\sum\limits_{n=1}^{N} \cos (nx)$, and multiply it by $\sin (\frac{x}{2})$ :
$$\sin (\frac{x}{2})D_N(x) = \sin (\frac{x}{2}) + \sum\limits_{n=1}^{N} 2\sin (\frac{x}{2})\cos (nx) ,$$
Use here the trigonometric product identity

$2\sin(\alpha)\cos(\beta) = \sin(\alpha + \beta) + \sin(\alpha - \beta) $

and the oddity of $\sin$ to get
$$\sin (\frac{x}{2})D_N(x) = \sin (\frac{x}{2}) + \sum\limits_{n=1}^{N} \bigg( \sin\big( (n+\frac{1}{2})x \big) - \sin\big( (n-\frac{1}{2})x \big) \bigg).$$
Hint: you can reorganize the right hand side of this last equation, so that a telescopic sum is obtained: all terms except of
$$\sin\big( (N+\frac{1}{2})x \big) $$cancel , therefore
$$D_N(x) = \frac{\sin\big( (N+\frac{1}{2})x \big)}{\sin (\frac{x}{2})}.$$
You could also see another proof here.


Change $_rendered output?

Question: In a node I get the values of CCK fields as $ array or $_rendered as the rendered view of the field. How can I change the <code>$<field_name>_rendered</code> from its default way of rendering?
Answer: The Custom Formatters module will help you quickly and elegantly. Here is a quote about it (from the module's project page):

... allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.
Answer: Drupal is amazing in the many ways it let's you override the final rendered HTML. I want to point out that you can also override how the field is rendered at the theme layer.
Just copy the file ...contrib/cck/theme/content-field.tpl.php to your personal theme folder. and rename it to
content-field-[field_name].tpl.php  where [field_name] is the id/name of the cck field you want to override.
Just edit that file to your liking.  And make sure you reconstruct the theme chache tables so that Drupal recognizes the new template file.
Answer: CCK fields use something called field formatters to control it's output. This is also how fields do it in Drupal 7. Field formatters is really just a theme function that's called.
In the content type setting: Display fields it's possible to select a formatter for normal view mode and teaser view mode. If the default formatters are not usable, you need to create your own formatter for the field and a theme function that will control how it's rendered.
I've written a blog post: Creating a field formatter for CCK a long time ago, at times I still use it myself for reference so it might help you out.
Alternatively you can use your theme to overwrite the default theme function for the formatter. This will however change all fields on your site with the selected formatter.

Change $_rendered output?


Geometric Brownian Motion Probability of hitting uper boundary

Question:
Let $(S_t)$ be a geometric Brownian Motion, i.e. $S_t = S_0 e^{\left(\mu-\frac{\sigma^2}{2}\right)t+ \sigma W_t  }$. Let $\alpha>0$ and $\tau = \inf\{t>0 | S_t \geq \alpha\}$. Compute $P(\tau \leq t)$.

What I have done:
I know that for $X_t = W_t - \beta t$,  $X_t^* = sup_{0\leq s \leq t} X_s$ and $\alpha \geq 0$
$$P(X_t^* \geq  \alpha ) = 1- \Phi\left( \frac{\alpha + \beta t}{\sqrt{t}}   \right) + e^{-2 \alpha \beta} \Phi\left( \frac{\beta t - \alpha}{\sqrt{t}}   \right) $$
Furthermore, I know that $P(\tau \leq t) = P(S_t^* \geq  \alpha ) $.
Hence I would have started with
$$ \log(S_t)=  \log(S_0) + \left(\mu - \frac{\sigma^2}{ 2 }\right)t + \sigma W_t \geq \alpha $$
$$ W_t \geq \frac{ \log\left(\frac{\alpha}{S_0}\right) -  \left(\mu - \frac{\sigma^2}{ 2 }\right)t}{\sigma}   $$
Now I would set $$\alpha^{'} = \frac{\log\left(\frac{\alpha}{S_0}\right)}{\sigma}$$ and $$\beta = -\frac{\left(\mu - \frac{\sigma^2}{ 2 }\right)}{\sigma}$$
and would use the formula for $P(X_t^* \geq  \alpha^{'} )$ as stated above.
Is this correct? I am not sure and I feel like I have done something wrong. Any hints or comment welcome -thanks!
Comment: For deterministic $\theta_t$,  $\mathbb{P}(W_t \geq \theta_t ) = 1 - \Phi(\theta_t) $. As you have already calculated, here $$\theta_t = \frac{1}{\alpha}\left(- \left(\mu - \frac{\sigma^2}{2}\right)t+\log \frac{\alpha}{S_0}\right).$$
Comment: @ChrisVarghese you mean $\frac{1}{\sigma}$ don't you?  But I can/should use the formula given by $P(X_t^{*} \geq \alpha)$ with my values for the cosntant $\alpha$ and the drift $\beta$ since I can rewrite my $W_t$ as $X_t = W_t + \frac{\mu - \frac{\sigma^2}{2}}{\sigma}$ define $X_t^{*} =  \sup_{0\leq s \leq t} W_s$ and then plug in?
Answer: $$ P(\tau \leq t ) = P(S_s \geq \alpha, s \in [0,t])  = P(\log(S_0) + \left(\mu - \frac{\sigma^2}{ 2 }\right)s + \sigma W_s \geq \log(\alpha), s \in [0,t])$$
$$=P\left( W_s \geq \frac{ \log\left(\frac{\alpha}{S_0}\right) -  \left(\mu - \frac{\sigma^2}{ 2 }\right)s}{\sigma}, s \in [0,t]  \right)  $$
Now set $$\alpha^{'} = \frac{\log\left(\frac{\alpha}{S_0}\right)}{\sigma}$$ and $$\beta = -\frac{\left(\mu - \frac{\sigma^2}{ 2 }\right)}{\sigma}$$
Then you have
$$P\left( W_s \geq \alpha^{'} + \beta s, s \in [0,t]  \right)  $$
Define $X_t = W_t - \beta t$ and   $X_t^* = \sup_{0\leq s \leq t} X_s$ and use the formula
$$P(X_t^* \geq  \alpha^{'} ) = 1- \Phi\left( \frac{\alpha^{'}  + \beta t}{\sqrt{t}}   \right) + e^{-2 \alpha^{'}  \beta} \Phi\left( \frac{\beta t - \alpha^{'} }{\sqrt{t}}   \right) $$


Remove all acronyms from PHP string

Question: I have a line of text that has acronyms inside is kind of like this...
$draft="The war between the CIA and NSA started in K2 when the FBI hired M";

I can't for the life of me figure out how to create a new string with all acronyms removed.
I need this output...
$newdraft="The war between the and started in when the hired";

The only php functions I can find only remove words that you statically declare like this!
$newdraft= str_replace("CIA", " ", $draft);

Anyone have any ideas, or an already created function?
Comment: You have to define or get a list of acronyms beforehand.
Comment: there is no already created functions for such tasks, be sure.
Comment: How do you define an acryonym? Is it from one of those specific keywords, or do you want to find any acronym in a string (could be tricky!) It sounds like a job for `preg_replace()`, but your question is too ambiguous to be certain.
Comment: Yes I am looking for ANY acronym, and it is getting tricky. I define acronym as any two letter or more word where either 1: All letters are CAPS, or 2: First and last letter are CAPS. I'll take a look more into preg_replace(). I wish awk/sed could be in the web enviorment! I love my awk/sed.
Answer: Ok, let's try to write something (albeit I can't understand what for it can be useful).
<?php

function remove_acronyms($str)
{
    $str_arr = explode(' ', $str);
    if (empty($str_arr)) return false;

    foreach ($str_arr as $index => $val)
    {
        if ($val==strtoupper($val)) unset($str_arr[$index]);
    }
    return implode(' ', $str_arr);
}

$draft = "The war between the CIA and NSA started in K2 when the FBI hired M";

print remove_acronyms($draft);

http://codepad.org/cIZSwwhV
Comment: Its useful because in the Air Force we write preformance reports using bullet statements in the following format. "Engineered NAOC comm sol; provided C2 to mobile CP--key to perfect POTUS/SECDEF msn...sq CC coined". The web application I an working on is being designed to strip all non-words such as acronyms from the above bullet statement and preform a thesaurus API lookup for all remaining "real words". That way with the click of a button you get a table of different "better sounding" words as recommended replacements.
Comment: Wow! That works perfect, and is very sexy indeed. Thanks so much.
Answer: Definition of an acronym: any word that is fully capitalized, and at least 2 chars long.
<?php
  $draft="The war between the CIA and NSA started in K2 when the FBI hired M";

  $words = explode(' ', $draft);
  foreach($words as $i => $word)
  {
    if (!strcmp($word, strtoupper($word)) && strlen($word) >= 2)
    {
      unset($words[$i]);
    }
  }

  $clean = implode(' ', $words);

  echo $clean;
?>

Comment: Of course, see the definition. I wouldn't want to remove "A" in the sentence "A little unicorn".
Comment: agree with you (about definition), but OP wants it to be deleted :)
Comment: Hum, I'm screwed then, so are you ^^
Comment: It looks like the single letter removal M is a rarity that doesn't need to be worked on. I found a workaround to it.
Answer: Try to define an acronym. You'd have to cut some corners, but stating something like 'any single word that is smaller then 5 characters and in all capitals' should be correct for this sample, and you'd be able to write a regular expression for that.
Other then that, you could make a huge list of known acronyms and just replace those.
Comment: OZ_'s function was perfect for this. For another area I am going to have to do something like your recommendation. It's more for converting abbreviations into full words though. Like translating Pilot'd into Piloted and so on and so forth.
Answer: Regex to remove multiple caps and/or numbers appearing together:
$draft="The war between the CIA and NSA started in K2 when the FBI hired M";
$newdraft = preg_replace('/[A-Z0-9][A-Z0-9]+/', '', $draft);
echo $newdraft;

Remove all acronyms from PHP string


How to enable/disable scoll view overscrolling?

Question: I am using a scroll view to display some data on the screen. The sroll view properties are wrap content fro layout height and fill parent for layout width. But my scroll view keeps on scrolling even when there is no content on the screen. how do i prevent this overscrolling ?
In general, is there any property to make enable/disable scrollview overscrolling? Everyone wants the iPhone bounce effect when you are scrolling. How to achieve this ?
Comment: This is weird. can you please post a screenshot and the XML here?
Comment: What adapter do you use? What does your `getView()` method do?
Comment: @Peter Knego: i am using a scroll view, where does the adapter get into picture?
Comment: I think there is a problem with another view which is inside the scrollview.. i mean in scrollview if there is linearlayout then check the orientation property.. may be it is the main problem.
Answer: check this method ScrollView.setOverScrollMode (int mode)


Why does 'jQuery' have to be passed into this function (see last line of code)?

Question: Source: http://blog.tomasjansson.com/creating-custom-unobtrusive-file-extension-validation-in-asp-net-mvc-3-and-jquery
$(function () {
    jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
        var params = {
            fileextensions: options.params.fileextensions.split(',')
        };

        options.rules['fileextensions'] = params;
        if (options.message) {
            options.messages['fileextensions'] = options.message;
        }
    });

    jQuery.validator.addMethod("fileextensions", function (value, element, param) {
        var extension = getFileExtension(value);
        var validExtension = $.inArray(extension, param.fileextensions) !== -1;
        return validExtension;
    });

    function getFileExtension(fileName) {
        var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
        if (extension != undefined) {
            return extension[0];
        }
        return extension;
    };
} (jQuery));

Wouldn't jQuery already be available inside this function, why would it be passed in at the end there? I don't get this and I've seen it a few times before, never had to use it so, was curious what's going on here.
Comment: What you've seen before is probably something done often with plugins and explained here  http://learn.jquery.com/plugins/basic-plugin-creation/  This looks like someone who patched things together and didn't really understand parts.
Comment: Is the `$` not inside `function($){`?
Comment: Are you sure this code works? AFAIK, the anonymous function would be immediately called with `jQuery` argument, and `undefined` would be passed as an argument to `$()` function, and these, AFAIU, does not make sense.
Comment: Guess that answers that question, pulled it from here: http://blog.tomasjansson.com/creating-custom-unobtrusive-file-extension-validation-in-asp-net-mvc-3-and-jquery
Comment: I don't get why the `jQuery` argument is being used here either, or the usage of both `jQuery` and `$` within the same scope. `jQuery(function ($) { } (jQuery));` seems more logical to me.
Answer: Passing it in isn't doing anything.  That syntax isn't right since the function, as it's used there, is a callback and not IIFE.
Only reason I could think to do that would be if no conflict mode is used.  Even then the syntax is still not correct.
Comment: exactly what I thought too... I have since updated the source maybe there are more clues there or maybe he just botched his example http://blog.tomasjansson.com/creating-custom-unobtrusive-file-extension-validation-in-asp-net-mvc-3-and-jquery
Comment: Should post a comment on his site.  You're right that jQuery is already defined in the global scope and is therefore usable regardless of that "passing in".
Answer: Read More: jQuery.noConflict
We pass jQuery or other jQuery Control variable ($, jQuery, jq, jQ, jQ1101) to the module or plugin because in the DOM, We can have multiple version of jQuery loaded or we can have other libraries which uses $ as control variable. Such as PrototypeJS or Zepto
By passing jQuery Control variable we ensure that we have right control variable for our module and internally we just use $ as jQuery variable.
Please see this example.

        <title>StackOverflow 19257741</title>

Answer: The code in that blog post is valid JavaScript syntax and will execute, but it doesn't do what the author probably expected. The $(function...) call looks like an attempt to run that function on DOM ready in the usual manner, but that's not what happens.
Let's deconstruct the code. First, strip out all the code in the function and add some logging:
console.log( 'before' );

$( function () {
    console.log( 'DOM ready' );
} (jQuery) );

console.log( 'after' );

This is (perhaps surprisingly) valid JavaScript and will log:
before
DOM ready
after

But here's the problem: If you put that script in a web page, you really want it to log:
before
after
DOM ready

After all, you're running the script before the DOM is ready, expecting the function to be run later, after the DOM becomes ready. That's the whole point of using the $() call.
What went wrong? To make it more clear, let's break out the inner function as a separate named function:
console.log( 'before' );

function ready() {
    console.log( 'DOM ready' );
}

$( ready(jQuery) );

console.log( 'after' );

And one more change to make it completely step-by-step:
console.log( 'before' );

function ready() {
    console.log( 'DOM ready' );
}

var result = ready( jQuery );

$( result );

console.log( 'after' );

Each of these versions has exactly the same semantics and runs in the same order.
Now it should be clear what happened. We're calling the ready function immediately and passing its return value into the $() call. The ready function doesn't return any value, so that value is undefined.
The last line, then, is the equivalent of:
$( undefined );

And that call simply returns an empty jQuery object ([]).
The culprit, of course, is that (jQuery) at the end. Adding that is what caused the function to be called immediately, instead of passing a reference to the function into the $() call. And the presence of jQuery inside the parentheses is meaningless: this ready function doesn't expect any arguments, so that is ignored. It would be the same thing if () appeared there.
It's very much like a common error you see with setTimeout() and similar calls:
// Oops - calls doStuff immediately, not after one second
setTimeout( doStuff(), 1000 );

This raises the question: why didn't this code run into a problem since it doesn't doesn't work as expected? Well, the function does get called either way - the only difference is when it's run.
So two possible reasons why it didn't cause a problem.

This block of code may have been placed at the end of the  as is popular practice these days. In that case the DOM would probably be ready-enough when the code is run. DOM elements are created in order as the  is loaded, and if you put a


Add multiple edges in a single gremlin query using vertex ids

Question: I am using gremlin REST server in my application and I want to create multiple edges to a vertex in a single query. I have the list of vertex ids from where to create edges to a single vertex.
For eg.- g.V(12,13,14,15).addEdge('uses', g.V(100))
I have tried many traversal steps but cannot get it to work.
Answer: You should look at the addE() step - here's one example for you can do it:
gremlin> graph = TinkerFactory.createModern()
==>tinkergraph[vertices:6 edges:6]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
gremlin> g.V(2,3,4,5,6).as('a').V(1).addE('likes').to('a')
==>e[13][1-likes->2]
==>e[14][1-likes->3]
==>e[15][1-likes->4]
==>e[16][1-likes->5]
==>e[17][1-likes->6]

Comment: gremlin> g.V().hasLabel('earms_user')
==>v[19660804192]
==>v[24576008272]
==>v[19660804216]
==>v[19660804248]
gremlin> g.V().hasLabel('earms_group')
==>v[18432004112]
==>v[20889604240]
gremlin> g.V(19660804192,24576008272,19660804216).as('a').V(18432004112).addE('eu_eg').to('a')
No signature of method: org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal.V() is applicable for argument types: (java.lang.Long) values: [18432004112]
Possible solutions: by(groovy.lang.Closure), is(java.lang.Object), any(), sum(), min(), max()
Comment: gremlin> graph2 = TinkerFactory.createModern()
==>tinkergraph[vertices:6 edges:6]
gremlin> g = graph2.traversal()
==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
gremlin> g.V(2,3,4,5,6).as('a').V(1).addE('likes').to('a')
No signature of method: org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal.V() is applicable for argument types: (java.lang.Integer) values: [1]
Possible solutions: by(groovy.lang.Closure), is(java.lang.Object), any(), sum(), min(), max()
Comment: what graph implementation are you using? and what version of tinkerpop?
Comment: got it working using this - [link](https://stackoverflow.com/questions/38185325/how-to-add-multiple-edges-in-a-single-gremlin-query).  Is this correct?
Comment: I am using titan graph db and tinkerpop3.
Comment: I have another doubt for which I have posted another question. Please check if you can answer that too - https://stackoverflow.com/questions/46027444/gremlin-only-add-a-vertex-if-it-doesnt-exists
Comment: You can do what is in that link, but that is a single script, not a single traversal. If that's not a problem for you then you I guess you are fine, but ultimately it would be best to have a single traversal to do that work. If you are using Titan it could be that you have an older version that doesn't support the form of traversal I suggested. {{addE()}} should still work though in some capacity. If I were you, I'd study that a bit more.
Comment: You might also consider using JanusGraph - http://janusgraph.org/ - so that you can get a newer version of TinkerPop to use.


Trying to clarify my argument in an automata proof

Question: The question:
Let $\Sigma$ be an alphabet and $L\subseteq \Sigma^*$ be a non-empty language over that alphabet.  Prove that if $L=L^2$ then $e \in L$ (where $e$ represents the empty string).
My Solution Sketch:
I first assume $L = L^2$. That is, every element in $L$ is also in $L^2$ and vice versa.
Because $e$ concatenated with itself ($ee$) is just $e$, then the only way for $L = L^2$ to hold is if $e \in L$. Otherwise, not every element in $L$ would be in $L^2$ and vice versa.
My concern:
It's only a sketch of a proof but I feel like it's very handwavy and not very rigorous. It is my first foray into automata so if anyone could provide some tips on how to formalize this argument and add more rigor to it, it would be very appreciated!
Comment: I would just say, suppose the shortest string in $L$ has length $\ell$.  Then the shortest string in $L^2$ has length $2\ell$.  If $L^2=L$, then $2\ell=\ell$, or $\ell=0$; hence $e\in L$.
Comment: I don't think this proof works.  What goes wrong if $e \not\in L$?
Comment: @mjqxxxx You could make that last comment an answer.
Comment: @mjqxxxx: It's a good answer, and it would get the question off the unanswered list. If you really want to add some substance, you could preface it by giving a little intuition: every $x\in L$ must have the form $yz$ for some $y,z\in L$, and if $e\notin L$, then $|y|<|x|$, so for each $x\in L$ there would be a shorter $y\in L$, and that's pretty clearly impossible. Yours is then simply a nicer way to make essentially this argument.
Comment: @saulspatz It's too short :).
Comment: @BrianM.Scott thanks for your comment! (Same to mjqxxx, although I can't tag 2 people at once). It seems after asking this question, I wrote a proof by contradiction similar to yours, but it was still less rigorous, so it helps a lot ))
Comment: @a6623: You're welcome!
Answer: Unfortunately, the answer is wrong. Indeed, if $L = \emptyset$, then $L = L^2$, but $L$ does not contain the empty word.
The correct statement should assume that $L$ is nonempty.


curl not available by default, so what can my script use instead to GET/POST?

Question: I am writing a Nautilus script that uses curl to GET/POST with a REST service.
Installing my script should be as simple as dropping a single file to ~/.gnome2/nautilus-scripts
My concern is that many computers might not have curl installed.
What would be a more widespread (should be installed by default on most distros) yet usable alternative to curl? Maybe wget or telnet?
Answer: Since the script is used under Linux (Nautilus), wget can be used in place of curl. Just change the command line arguments to the wget equivalents before running the script.
Comment: Is wget installed by default in most Linux distributions? (not just "available in the repos", really "installed by default")
Comment: In every system I've seen, GNU Wget is the default and cURL is occasionally installed as well. They both perform the same function, so it's really just a matter of picking one.
Comment: My bad, I had forgotten that I also need PUT, which wget can't do. Since it becomes a different question, I let this one and created http://stackoverflow.com/questions/5726572
Answer: To make it more clear, distributors can make their decisions about what to install by default, so "installed by default in most Linux distros" doesn't make any sense.


Does x approach some finite value according to this differential equation?

Question: So this question was on a midterm that I wrote recently and I couldn't figure out the answer. We were given the differential equation
$$\frac{dy}{dx} = x^2 + y^2$$
The question asked: As $y \rightarrow \infty$, does $x$ approach some finite value $x_0$?
Also, we were told to think about it intuitively and without solving the eqution. We have not learned how to solve this sort of equation yet.
I thought about it afterwards and this is the answer I got...
Attempt
The equation of the slope of function y is dependent on both the value of y and the value of x. It is in the form of an equation of a circle.
If $x$ approached some value $x_0$ as $y \rightarrow \infty$, then the slope would gradually approach infinity as $y$ got larger and larger. However, since this is an equation of a circle, the value of the slope is bound by the circle, meaning that it can't approach infinity. Therefore, $x$ does not approach some value $x_0$, and we get that $x \rightarrow \infty$.
Is that correct?
Comment: Every solution $y(\ )$ is increasing hence one can assume that $y(x_1)=y_1$ for some given $x_1$ and some finite $y_1>0$. Then $y'(x)\geqslant y^2(x)$ hence $\left(\frac1{y(x)}\right)'=-\frac{y'(x)}{y^2(x)}\leqslant-1$ hence, for every $x\geqslant x_1$ where the solution is finite, $\frac1{y(x)}-\frac1{y_1}\leqslant x_1-x$, that is, $y(x)\geqslant\frac{y_1}{1+(x_1-x)y_1}$. This proves that $y(x)$ cannot be defined for $x\geqslant x_1+\frac1{y_1}$, that is, that $y(\ )$ explodes at some finite point $x_0\leqslant x_1+\frac1{y_1}$.
Comment: @Did: I think you should make that into a solution, it covers a number of broadly useful features in regards to differential inequalities...
Answer: I don't think this is the case. The value of the slope isn't bound by the circle - it's saying that the value of the slope is ONLY proportional to the distance away from the origin. That is, on every point on the circle $x^2 + y^2 = r^2$, the slope is $r^2$.
From this picture, you see that as the distance from the origin increases, the slope increases more and more rapidly. So this makes it seem that there ought to be an asymptote.
Comment: I see. Oh well. It wasn't worth a lot of marks on the midterm anyway. Thanks
Comment: @The_Questioner Perhaps the marks were justified after all, see comment on main.
Comment: Doesn't your comment agree with mine? Why the downvote (if that was you)?
Comment: @Nitin. I didn't downvote you.


Update module issue - version_major in update_calculate_project_update_status()

Question: I am building a site using Drupal 7.26.
I get this notice all the time:

Notice: Undefined index: version_major in
  update_calculate_project_update_status() (line 628 of
  /XXX/public_html/modules/update/update.compare.inc).

Does someone knows what is the problem, and how to solve this?
Thanks!
Comment: It was tempting to say "post in issue queue, not here". But **which module** is responsible? Now figuring this out is interesting task. +1 from me.
Comment: Figuring out the module should be easy, I used a check like `if(isset($release['version_major'})){ //output debugging info/variables }`. That let me determine the module that was having a problem. IF you need drupal debugging tools, please see my comment below for links.
Answer: If you put:
if(!isset($release['version_major'])) {
    die('
'.print_r($project, TRUE).'
');
}

On line 625 of update.compare.inc then when the version_major is not set it will print out details of the problem module and die.
Once you know what module is causing the problem then remove this code again as otherwise kittens may die.
When you know what module is causing the issue then you can raise the problem in their issue queue.
Comment: Yes, hacking core for debugging purposes, and reverting back when you are done, is perfectly acceptable when working on weird situations.
Comment: if you install the [devel](https://www.drupal.org/project/devel) and [devel debug log](https://www.drupal.org/project/devel_debug_log) modules you can output to a debug log easily and inspect the giant crazy objects that drupal creates much easier, essential for debugging. Also, controlled by permissions so need to worry about anyone seeing the output except you.


IEquatable from class not being used (question about Lists)

Question: I have a class defined as
class MyClass : IMyClass, IEquatable<MyClass>
{
  //appropriately defined bool Equals(MyClass other) and int GetHashCode() methods
}

When I call the following code:
List<MyClass> list = new List<MyClass>();
//fill list here and then call distinct
var distinctList = list.Distinct();

in the above code, distinct correctly calls MyClass.Equals
but if I instead use the interface for the definition of the list (as shown below), the Equals from MyClass does not get called:
List<IMyClass> list = new List<IMyClass>();
//fill list here with objects of type MyClass
var notADistinctList = list.Distinct();

in the above code - notADistinctList  is not a distinct list because it looks like the Equals operator from MyClass is not being called and the base Object.Equals is being called.
If I create an IEqualityComparer for IMyClass and provide that to the Distinct method, then it works.
list.Distinct(new MyClassComparer());

where MyClassComparer is defined as:
class MyClassComparer: IEqualityComparer<IMyClass>

My question is why does the Equals operator on MyClass not get called when I define my list as List < IMyClass >, but does get called when I define the list as List< MyClass >? (after MyClass is an implementation of IMyClass).
Answer: Your interface doesn't implement IEquatable, only your concrete class does. When comparing them, it doesn't care what concrete class you are using (because you said it was an interface).
Try something like this:
public class MyClass : IMyClass
{
    public bool Equals(IMyClass other)
    {
    }
}

public interface IMyClass : IEquatable<IMyClass>
{

}

Answer: I figured out the solution,
My problem in the above code is that IEquatable was defined on MyClass.
Instead if I defined it (IEquatable) on IMyClass, then that fixes the issue.
interface IMyClass: IEquatable<IMyClass>{}

class MyClass: IMyClass
{
 //appropriately defined bool Equals(IMyClass other) and int GetHashCode() methods
}

Obviously as noted in my question, the other solution is to provide an IEqualityComparer to the Distinct method.
Though I still would like to know why the Equals method from MyClass was not automatically called on a List of IMyClass (as the objects in the list are all of type MyClass).
Comment: Because you said the list was IMyClass, not MyClass, it can't guarantee they're all of the same type. How should it compare MyClassB:IMyClass with MyClass? You haven't given it a method to call. When you're dealing with interfaces like this, the object is treated as _only_ having those properties/methods (as well as any derived through inheritance.. in this case, Object.Equals(), which it then calls instead)


A finite $\mathbb{Z}$-module whose submodules are totally ordered by inclusion.

Question: I have the following problem:

Let $M$ be a finite $\mathbb{Z}$-module such that set of the submodules is totally ordered by inclusion. Prove that there exist a prime $p$ such that $|M|=p^\alpha$ for some $\alpha$.

I'd like some hint to solve this problem.
Thanks a lot!!!
Comment: In fact, doesn't it have to by cyclic?
Answer: Ok so a finite $\mathbb{Z}$ module is a finite abelian group ! If its order is divisible by two different primes then there are 2 elements of relatively prime orders, and their subgroups cannot have an  inclusion one in the other.
Answer: Hint: let $L_1$ be the unique minimal submodule; then $L$ must be simple, so…
Let $L_2/L_1$ be the unique minimal submodule of $M/L_1$, so…


Are column vectors considered the "default" orientation in linear algebra?

Question: I am taking an online course where vectors are typically written out as column vectors. It seems like the only row vectors we have seen are the transposes of column vectors and labeled as such.
So I'm wondering if mathematicians (at least those in linear algebra) tend to favor column vectors. This is essentially a question about convention, i.e. is it such a strong convention that if you told a mathematician about a vector without specifying its alignment, would they assume it is a column vector?
Come to think of it I guess that might make sense since it is the first dimension.
Comment: Yes. This is so, when you want to act on a column vector with a matrix, the matrix goes on the left, the same way the name of a function $f$ goes on the left of its input $x$ when you write $f(x)$.
Comment: Yes it is more or less accepted convention to use column vectors. I have seen some (old) books favor row vectors over column but it seems main reason for it being to save page space and convenience while printing.
Answer: It's possible you haven't seen matrix multiplication defined yet. If that's the case, then this won't be much of a justification.
If $v$ is a row vector of length $n$ (so a $1 \times n$ matrix), and $M$ is an $n \times n$ matrix, then $Mv$ isn't defined although $vM$ would be (and gives back a row vector of length $n$): compare
$$\underset{``\text{nonsense''}}{\pmatrix{1 & 0 \\ 0 &1} \pmatrix{1 & 0}} \quad \text{versus} \quad \underset{``\text{less common, but fine''}}{\pmatrix{1 & 0}\pmatrix{1 & 0 \\ 0 &1}} \quad \text{versus} \quad \underset{``\text{the gold standard''}}{\pmatrix{1 & 0 \\ 0 &1} \pmatrix{1 \\ 0}.}$$
Because we like to think of matrices as functions from a vector space to itself, we probably want to emulate function notation (as in, $f(x)$) and apply matrices "on the left," as in $Mv$ rather than $vM$. Because of the way matrix multiplication is defined, this forces us to use column vectors.
It is much more common in general to see matrices act (from the left!) on column vectors (although there are niche "act on the right" markets).
Comment: (the OP should probably just ignore this comment) It *is* annoying, though, when you want to talk about the action of a group of matrices on a coordinate vector space, and then, rather confusingly, $$A\cdot(x,y) = A\begin{pmatrix} x \\ y\end{pmatrix}.$$ I suppose one could fix this by talking about actions on the right and multiplying on the right, instead of the left, but then you're going against two conventions.
Comment: @WillR I feel like by the time you're talking about group actions you've internalized matrix algebra well enough that this probably wouldn't throw you, even if it does look strange the first few times.
Comment: I learned algebra from those in the niche "on the right" market; it took me an embarrassingly long time to figure out why permutation matrices weren't working like they should, on basis vectors  -- because I'd learned the version that acts on the right, and had only used them amongst themselves, never on vectors!
Answer: This is slighty opinion based, I guess. However, I would say that I've seen column vectors as standard far more than row vectors. So yes, if nothing is stated I would assume column vector.


Clean way of building simple taxonomy browser of arbitrary depth

Question: I have spent days trying to determine a clean way to do the following:

Display a list of all top-level terms in a vocabulary with links to their child terms
Upon clicking a link, be taken to a list of the children of those terms.
Ad infinitum until the lowest-level term, for which a list of nodes tagged with that term will be displayed.

This seems like it would be pretty commonly-needed functionality but I can't find any solution that can handle arbitrary depth, particularly if not all term trees  descend to the same depth.
An ideal solution would be one that uses Views 3, Contexts, EntityFieldQueries, or anything else that's well-supported in Drupal 7.
I'm able to do almost exactly what I want by making a simple view with three node:term relationships (term, term's parent, and term's parent's parent) and user those for sequential contextual filters. The only problem with this is that if there's a node with a termpath of too little depth, it gets listed as "uncategorized" and generates a dead link. Instead of doing that I'd like it to link to the next child term available.
Answer: I figured out a way to do this with only the Views module. It's not perfect — it doesn't generate a nice URL and breadcrumb with the taxonomy lineage the way that my solution for a taxonomy of a single depth would do.
Static Depth Browser
For a taxonomy of static depth (where all terms have the same depth of child terms), you would do the following:

Create a view of nodes
Add relationship to taxonomy term (Term)
Add relationship to taxonomy term parent, accessible via Term (Parent)
Add relationship to taxonomy term parent, accessible via Parent (Parent Parent)
Repeat step 4 as many times as necessary for your taxonomy's depth.
Add contextual filters for each one and make sure they're in the proper order. Set to display a summary when filter is not in URL.
You'll probably want to override the breadcrumb and title for each filter.
???
PROFIT

Variable Depth Browser
For a taxonomy of variable depth (where some term trees have deeper levels of nesting than others), it's a bit more complex:

Add a new top-level term (Foo) to your vocabulary and put all other terms under it.
Create a view of terms with a page that displays term names
Add contextual filter: Taxonomy term: Parent term
When the default value is not in the URL, provide default value
Set default value to your top-level term name (Foo)
Specify validation criteria

Validator: taxonomy term
Criteria: your vocabulary name
Filter value type: Term name converted to term ID

Click the "+Add" button at the top of the Views panel to add an Attachment to the view.
Add to this attachment only (override) Relationship: Taxonomy term: Content with term
Add to this attachment only (override) display: fields: node titles linked to nodes, and remove (from this attachment only!) display: fields: term name
Add to this attachment only (override) contextual filter: Taxonomy term: Name
When filter value is not available, provide default value: Raw value from URL: Path component: 2 (or more if your Page path has >1 component)
Attachment settings: Attach to: [name of the page display you just made]
???
PROFIT

Screenshots of Views' UI for reference:
Comment: Nicely done! Upvoting both the question and your answer -- it seems like fairly common thing to need to do and your solution is better than anything I found while initially trying to answer.
Answer:
Create a view of the type Taxonomy
Add a contextual filter of the type Taxonomy term: Parent term
Set Provide default value and keep it as fixed. give the Term ID of the top Parent term
Add Taxonomy term ID as field and Exclude it from display
Add a Taxonomy Term Name click on out put this field as a link; give the link as "path-you-set-in-view/[tid]"
Note : You should uncheck "Link this field to its taxonomy term page"

When you visit the view page you would see the children of the top parent; as per the example you would get:

term1
term2

When you click on term1 you would get the children. Until you reach term1.1.1.
You wont get any result if you click on term1.1.1 yet. To achieve that we need to create one more view block in the above view.

Add a Block
Remove the existing contextual filter and field
Note : When you remove them make sure you select the This Page (Over Ride) from the drop down at the top next to For other wise the fields and contextual filters you created in the page would also be gone.
Add a new contextual filter Taxonomy term: Term ID
Add a relationship Taxonomy term: Content with term
Add the Content Title and you use the relationship from the drop down at the top.
Save the view and go back to the Page we create (This is important other wise you would not be able to complete the next step
Add a field in the FOOTER OR HEADER
Select "Global: View area" from the list and select the block we created from the drop down View to insert while you are there check Inherit contextual filters so that we can pass the value from this view to the block as well
Check Display even if view has no result so that when this view does not show the result the block would still be shown

Save the view, and you are done.
Comment: I followed the clear explanation of Mohammed Shameem. Thank you, works perfect !!
Answer: I think what you're wanting is Views Tree, a contrib module that uses Views to construct a tree of taxonomy terms.
(Give me a second and I'll write a quick how-to on using it view tax fields)
Apparently that module has an issue preventing it from working with taxonomy terms. Boo.
That said, I found the following code which seems to do what you're wanting (you can make it display/hide elements through some pretty rudimentary jQuery code):
<?php

// The ID of the taxonomy vocabulary for which you'd like to create a nested list
$vid = 10;

$depth = 0;
$num_at_depth = 0;
$tree = taxonomy_get_tree($vid);

print "
\n
";
foreach ($tree as $term) {
  $diffdepth = 0;
  if ($term->depth > $depth) {
    print "\n
\n
";
    $depth = $term->depth;
    $num_at_depth = 0;
  }
  if ($term->depth < $depth) {
    $diffdepth = $depth - $term->depth;
    while ($diffdepth > 0) {
      print "
\n
\n";
      $diffdepth--;
    }
    $depth = $term->depth;
  }
  if (($term->depth == $depth) && ($num_at_depth > 0)) {
    print "
\n
";
  }
  print l($term->name, 'taxonomy/term/' . $term->tid);
  $num_at_depth++;
}
print "
\n
\n";

Via "Nested category lists with links to pages".
Comment: I have enabled that module and tried experimenting with it and I have two problems: 1. I suspect it just gives you a flat list, not a multi-paged browsing experience and 2. I can't get it to work. A how-to would be most helpful.
Comment: Updated answer. Apologies, apparently Views Tree has an open issue re: using taxonomy terms. Alternative answer posted.
Comment: That appears to give a simple nested list rather than a sequentially-paged browser.
Comment: @beth -- Would it suffice if I wrote some jQuery that shows/hides elements of that list when parent/child items are clicked?
Comment: I don't want it to be JavaScript dependent.
Answer: If you just want to have a set of dynamic taxonomy-browsing pages, then I would go the following way, requiring 3 Views + Taxonomy Display module which allows you to use Views to display contents of taxonomy/term/% pages:

Top Level Terms - list terms whose parent is null
Mid Level Terms - list terms whose parent is NOT null. No result: display View #3
Nodes with Terms - list nodes tagged with terms.

As Views 1 and 2 will probably be themed in a similar way, you might consider merging them as displays into one View - it'd be manageable more easily.
I have successfully used that approach for my taxonomy. It fortunately was homogenous at each level - a given branch ended with either leaves (nodes) or branches (terms), but not both. If this would be a limitation, please test it first.
Of course this is a "pseudo-code". You'd want to set up validations and filters, and a nice, logically-looking pathauto patterns to reflect the structure.


Custom fields in array not posting when containing numbers

Question: I have a PHP form where I need to search custom fields. If the custom field contains a number, it won't show as posted, however a string of letters will.
If I var_dump($_POST['customfield']) it displays the field, key and value. I attempted a foreach loop to count how many fields post. It returns 0 if I only post with numbers.
$postCustomFields = $_POST['customfield'];

foreach ($postCustomFields as $key => $cfield) {
        if ($postCustomFields[$key][$cfield] != null) {
            $customfields++;
        }
    }

Fields are named customfield[0]. Inside the brackets is the field ID. I just need a way to have the numeric value be usable and count in the customfields array.
var_dump($_POST['customfield']) output. The key is the field ID:
array(9) {
  [3]=>
  string(1) "5"
}

Thanks
Answer: You are confused with array reference. You have array with array [key => value], but you try to access data like array[key][value] and there are not exists.
In your case your $postCustomFields[$key] will contains your ID 5
Comment: Doh! Thank you! I changed it to `$postCustomFields[$key]` and it works.


how to choose lambda value while working with elsaticnet package

Question: I am using elasticnet package in R .How to choose lamba value in enet() function and how to get coef. values ..??
fit2=enet(new1,q$mariner,lambda=0.5)

Though i have randomly chosen 0.5 ....but how should I choose the correct value and also how to check the coef of the selected variables
Answer: Note: I reccomend using the glmnet package to fit elastic nets.  It has a vey efficient implementation, and has become a standard.  This is written from the perspective of that package, which uses the notation that has become a standard in the statistical learning literature.  If you would rather use elasticnet, see the note below for an important caveat.
There are two parameters in elastic net $\alpha$ and $\lambda$.  $\alpha$ controls the relative balance between the lasso and ridge regularization, and $\lambda$ controls the overall level (intensity) of regularization.
$\alpha$ is often chosen based on intent and domain knowledge.  Do you want a sparse model with many zero coefficients?  Then chose $\alpha$ close to a pure lasso regression.  Do you want a dense model with many non-zero but small coefficients?  Then chose $\alpha$ close to a pure ridge model.
On the other hand, $\lambda$ is a parameter that is tuned during the fitting of the model.  The most common way to do this is with cross validation.  In cross validation, you split your training data into many "folds" - partitions into a training and tuning (validation) subset - and fit a a model on each fold, one for each lambda.  The various out of sample datasets in cross validation allow you to estimate the out of sample error for each value of $\lambda$, and then a heuristic is used to choose the best value of $\lambda$.  Common heuristics are choosing the $\lambda$ that minimizes the out of fold deviance, and choosing the largest $\lambda$ one standard deviation away from the minimizer lambda (standard deviation referring to the estimated standard deviation in out of fold deviances).
Here's a picture of out of fold deviance estimates by lambda:

Each data point on the curve is one value of $\lambda$, the plots tend to look better by $log(\lambda)$ though, so that has become a standard.  The error bars span the standard deviation of the estimated out of fold deviance, the variance is the estimates comes from the various cross validation folds.  I believe this picture was from a binomial (logistic) model, with $10$ fold cross validation.
If you are using the glmnet package in R, which I recommend over elasticnet, there is a built in function to perform cross validation, it's called cv.glmnet.  I highly suggest reading the documentation on this function before fitting your first glmnets.
To get coefficients, use R's coef function.  This is a general function that is overloaded to work on most model objects (technically a generic function).
For more details, I highly reccoment the following paper by the pioneers in this field:
Regularization Paths for Generalized Linear Models via Coordinate Descent

Caveat:  I checked the documentation for the elasticnet package, it uses a non-standard definition of $\lambda$:
lambda: Quadratic penalty parameter. lambda=0 performs the Lasso fit

This is not the use of $\lambda$ that has become standard in the literature - and I believe is equivalent to what is usually called $\alpha$.  Be warned.
Comment: lambda is the quadratic penalty parameter, not a convex combination parameter.  The elasticnet package fixes the quadratic penalty parameter and calculates the regularization path as the lasso penalty parameter ranges from infinity to 0.  By doing it this way the software is able to calculate the exact path by invoking the LARS algorithm rather than using the coordinate descent approach for a grid of penalty parameters as is done in glmnet.
Answer: There are two questions here so let me start with the less open-ended one about extracting the model coefficients.  Firstly, it might be worth noting that there are two parameters that need to be specified for the elastic net model; when calling the enet function, one parameter is specified (i.e. the lambda parameter), and the regression coefficient estimates are calculated for all possible values of the second parameter (i.e. an elastic net regularization path).  To obtain the regression coefficient estimates for various point along the EN path corresponding to the chosen value of lambda, use the predict function.  In predict, the formal argument s is used to specify that values of the second elastic net parameter, i.e. the points at which we wish to obtain the regression coefficient estimates.  But s means different things depending on the value of another formal argument, mode; see the function documentation for the details.  Finally, the formal argument type should be specified as "coefficients", as opposed to requesting the fitted model.
The question about selecting the appropriate value of lambda does not have a definitive answer.  There are two penalty parameters in the elastic net model; one that penalizes the $\ell_1$ norm and one that penalizes the squared $\ell_2$ norm of the regression coefficients.  The lambda parameter specifies the square of the $\ell_2$ norm.  So specifying a small value of lambda results in a path that will have lower ridge regularization, while specifying a larger value of lambda results in more ridge regularization.  Thus lower values of lambda tend to yield sparser model fits, while higher values of lambda tend to yield denser model fits.  Still, this does not give us a way to choose an actual value.  If prediction accuracy is the primary goal, then one way to choose the values of the elastic net parameters is to choose the parameters that give the smallest prediction error, as measured on a testing set or through cross validation.  So in this scenario, one might choose a sequence of values for lambda, and the find the minimum prediction error along the elastic net regularization path for each choice of lambda, and then choosing the lambda that had the smallest prediction value in its path.
Answer: Your choice of lambda is going to depend on your desired results. Choosing close to 1 you will get something that performs more like a lasso regression and closer to 0 gives ridge. This vignette: http://web.stanford.edu/~hastie/glmnet/glmnet_alpha.html
is extremely helpful in detailing both. I used it as a walk through the first time I needed with elastic net and it performed very well.
Comment: In the link you shared, you can see that the formula and what you say differs. You might wanted to say alpha instead of lambda in your answer?


ASP.Net Roles: Page-Level Security Question

Question: We're currently in the process of re-creating a brand new security model that dwarfs our existing process. Right now, we plan on grabbing a user's roles during the login process and then using a Base Page class to check if the user has the role of the corresponding page the user is navigating to.
We can limit the menu's options by the user's roles as well, but we have had problems with users navigating to pages in our system by typing them in or having old bookmarks. Obviously, we need some sort of page level access.
A simple function in our Base Page class that checks the role in the Arraylist against the page's assigned role would work, but I was wondering if there was any built-in functionality to support this or a cleaner solution possibly.
Answer: Have you looked at ASP.Net Membership for this yet?  It takes care of all of the scenarios you listed above (trimming menus, page security,) and in a very easy to use manner.
See here for more information about membership - http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx.
Comment: I suppose rolling our own role provider and calling a User.IsInRole function of the role on the page would suffice if I was referencing the session'ed Arraylist of Roles that the user has. That'd basically be the same thing as calling a Base Page class function.
Comment: If you were to use the Membership RoleProvider along with the Location/Authorization section of your web config to specify which roles can see which pages, you shouldn't have to ever reference your list of roles from the page.
Answer: Are you using built-in membership?
If so, you can use the location section of your web.config file to restrict access to individual pages or entire directories. From MSDN:

The following example allows an
  anonymous user to access the
  Logon.aspx page:

<configuration>
   <location path="Logon.aspx">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

Comment: The problem is that this is based on every user. There are roughly 10,000+ users, and each may or may not have a completely different set of rules. Adding all those distinctions into the web.config seems like a rather large and lengthy task.
Comment: @jlrolin - you can use `` or similar as well


how to link a group of check box tags to a corresponding group of  tags

Question: I have the following 3 checkbox tags where each represents a category.
<input type="checkbox" name="catpref[]" value=1> Politics

<input type="checkbox" name="catpref[]" value=2> Sports

<input type="checkbox" name="catpref[]" value=3> Economics

I need to add next to each category another <select> tag of countries that will return the country selected for the corresponding category.
<input type="checkbox" name="catpref[]" value=1> Politics
<select class="countrySrch"  name="countbox" id="countbox">@include('includes.country')</select>
<input type="checkbox" name="catpref[]" value=2> Sports
<select class="countrySrch"  name="countbox" id="countbox">@include('includes.country')</select>
<input type="checkbox" name="catpref[]" value=3> Economics
<select class="countrySrch"  name="countbox" id="countbox">@include('includes.country')</select>

If I submit the above, there is no link between each catpref[] and it's corresponding country <select>. How can this be done ?
Answer: You should modify your input names with specific keys like this:
<input type="checkbox" name="catpref[1]" value="true"> Politics
<select class="countrySrch"  name="catprefspec[1]">@include('includes.country')</select>

<input type="checkbox" name="catpref[2]" value="true"> Sports
<select class="countrySrch"  name="catprefspec[2]">@include('includes.country')</select>

<input type="checkbox" name="catpref[3]" value="true"> Economics
<select class="countrySrch"  name="catprefspec[3]">@include('includes.country')</select>

Then you should get 2 arrays catpref and catprefspec in your request. And they now have keys that matches each other.
P.S. id attribute should be unique in the document. Using id="countbox" multiple times might result in unexpected errors. You should probably use class attriubte instead.


Regularity of fundamental solution to heat equation

Question: Let $u(x)=\int_\mathbb{R} \frac{1}{\sqrt{2\pi t}}e^{-\frac{|x-y|^2}{2t}}g(y)\, dy,\quad x\in \mathbb{R}$ be the fundamental solution to
$$\begin{cases} u_t-\frac{1}{2}u_{xx}=0, &t\in (0,T],x\in \mathbb{R},\\ u(0,x)=g(x),&x\in \mathbb{R}.\end{cases}$$
I am considering the following problem: suppose $g$ is nice enough, does there exist $p>2$ and constant $C=C(p,g)$, such that
$$\|D_x u\|_{L^p(\mathbb{R})}\le C, \; \forall t\in (0,T].$$

Formally, by using the PDE and the identity $2DuDu_t=\frac{d}{dt}(|Du|^2)$, I got
$$\|D_x u\|_{L^2(\mathbb{R})}\le C\|D_xg\|_{L^2(\mathbb{R})}.$$
Answer: First, let me suggest carefulness when dealing with your equation. Your ``fundamental solution'' is a solution of the problem, and the only such that $u \to 0$ as $|x| \to +\infty$ (this condition is satisfied in L^p. Unless you add this condition, the problem you study is ill posed.
Also, when you bound the norms, you should be careful, since you are forgetting the time variable.
If you are looking for solutions $u \in W^{1,p}$ then your best bet is to think about the evolution semigroup, which can be studied by the eigenvalue decomposition of the $-\Delta$ operator.
In a bounded domain $\Omega$ (an I guess you extend that to unbounded domains) you can expect
$$ \| \nabla u (\cdot, t) \|_{L^2 (\Omega)} + \| u (\cdot, t) \|_{L^2 (\Omega)} \le C t^{-\frac 1 2} \| g \|_{L^2 (\Omega)} $$
Cheers
Comment: @JohnZHANG : Because of the equation $\frac{\partial u}{\partial t}=k\nabla^2u$, the heat semigroup solution operator $T(t)$ turns $H^{2s}$ spatial data into $H^{s}$ time data. There's a way to make that precise in $L^2$. More roughly, if the initial spatial data is $C^{2\alpha}$ Holder then the time dependence is *almost* $C^{\alpha}$ in time (everything up to that.)
Comment: Thanks for your suggestion. So in general, the norm of derivative will blow up?
Comment: As $t\to 0$, if your data is not smooth yes (logically). If the data is smooth, then there are better estimates towards 0.  Actually, the estimate I gave should be consider towards infinity. Locally $u \to 0$ as $t \to +\infty$, and it does so in the $H^1$ norm.
Comment: I see. But I care more about the behavior for $t\to 0$ and the data is smooth enough.
Comment: For every $t>0$ your solution is as smooth as you would like. Besides there is always a estimate of the form $\| D^n u \|_{L^p} \le C t ^{-\alpha} \| g \|_{L^2}$. As $t \to 0$ you cannot expect more regularity that $g$ has. In that sense, if $g \in X$ a functional space, then you can expect $u \in \mathcal C ([0,t_0], X)$, but, of course, nothing better.


Artifactory Search via REST API causes "Bad request" error

Question: I'm trying to search artifacts using a groovy script and the REST API:
def query = 'artifactory/api/search/artifact?name=at.mic.all.feature&repos=features-qa-test-snapshot'
def server = new RESTClient('http://mic-build2.mic.co.at:8081')
server.parser.'application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json' = server.parser.'application/json'
def resp = server.get(path: query)

this causes an exception:
groovyx.net.http.HttpResponseException: Bad Request
    at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:240)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
    at groovyx.net.http.RESTClient.get(RESTClient.java:118)
    at groovyx.net.http.RESTClient$get.call(Unknown Source)
    at Artifactory.getArtifacts(artifactory.groovy:157)
…

Only to see if server and query are correct, I tried the url = server + '/' + query (= http://mic-build2.mic.co.at:8081/artifactory/api/search/artifact?name=at.mic.all.feature&repos=features-qa-test-snapshot) in a browser, that results in a file that contains exactly my search result:
{"results":[{"uri":"http://mic-build2.mic.co.at:8081/artifactory/api/storage/features-qa-test-snapshot/at/mic/all/feature/at.mic.all.feature/20130313002236/at.mic.all.feature-20130313002236-win32.win32.x86.zip"},…..}
So, my server and query seem to be ok, but won't work in my groovy script.
Thanks in advance for any help, kind regards!
Frank
Answer: The uri path should start with '/', HTTP client won't append it for you.
def query = '/artifactory/api/search/artifact?name=at.mic.all.feature&repos=features-qa-test-snapshot'

This should work.
Answer: I had the similar problem with searching artifacts (it resulted with eigher "Bad Request" or "Not found" exceptions). The reason of the problem is that HTTP request created with your approach is malformed: in the artifactory request.log I see that the request
/api/search/artifact?name=test

turns into
/api/search/artifact%3Fname=test

which is obviously incorrect HTTP request. After investigation of the RESTClient documentation I found the right solution: form HTTP request using provided API instead of concatenating whole request as a string on your own.
def queryPath = '/api/search/artifact'
def server = new RESTClient('http://mic-build2.mic.co.at:8081')
server.parser.'application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json' = server.parser.'application/json'
def resp = server.get(path: queryPath, query: [name: 'test', repos: 'your-repo'])

This way you can chain any parameters to the query without need to form HTTP request manually with proper separators. Hope this will help


What is the purpose of doing (bind(this)) while handling the events in React .jst?

Question: (In React Coding) Whenever I click on the screen I would like to compute something by using OnClick event. For that I got a sample code from internet as follows,

The handleClick method and
 resides in the same method. Could anybody explain why binding is required here and why should not we call handleClick() method directly with out binding?
Comment: This question has already been asked on SO. https://stackoverflow.com/questions/38624799/why-is-it-necessary-to-use-bind-when-working-with-es6-and-reactjs
Comment: Possible duplicate of [Why is it necessary to use bind when working with ES6 and ReactJS?](https://stackoverflow.com/questions/38624799/why-is-it-necessary-to-use-bind-when-working-with-es6-and-reactjs)
Answer: "this" keyword refers the context of current component (let say Component A) in react. Basically in java-script it refers the current class or function but for react it refers the current component.
If you are not send this with your handleClick method then whenever handleClick  method you called then  handleClick  never know the things(like variables or functions) of component A.
Answer: In JavaScript there is something called context. It includes whats found in the current scope using the this keyword. So by using bind, you are passing the context where handleClick is called into the function handleClick so that this function can use this.values from the bound context.
More info here.


Does NFL have substitute referees?

Question: The line judge Sarah Thomas got hit during Green Bay Packers vs Minnesota Vikings game in week 16 of 2016 season. She was taken off the field for further evaluation. So given that she was not on the sideline and the game continued with no stoppage either a substitute referee took her place, or they moved on with one less line judge. But I doubt the latter happened. So are there substitute referees in the NFL (similar to 4th official in soccer) and what are the rules regarding them?
Comment: [Video of the hit](https://twitter.com/SBNationGIF/status/812766191802523648)
Answer: The 2016 NFL Rulebook states in Rule 15: Officials and Instant Replay:

Section 1 - Officials
Article 1. Game Officials
The game shall be played under the supervision of seven officials: the Referee, Umpire, Head Linesman, Line Judge, Field Judge, Side Judge, and Back Judge. In the absence of seven officials, the crew is to be rearranged according to the remaining members of the crew.

Sarah Thomas is on Referee Jeff Triplette's crew. (Official source, Alternate source)  Official crews do not travel with an alternate official.  If one official has to leave the game, the crew shifts from 7-Man Officiating Mechanics to 6-Man Mechanics, essentially combining the Back Judge and Side Judge positions.  There is also a 5-Man Mechanics protocol, if need be.  Any less than that, and I would guess that they'd have to call the game off.
According to the Football Zebras blog, Sarah Thomas returned later in the game.

Does NFL have substitute referees?


How to time something in Go, which takes less than a nanosecond?

Question: How would I proceed if I want to compare the time of two functions, but the functions take less than a nanosecond?
t := time.Now()
_ = fmt.Sprint("Hello, World!")
d := time.Since(t)
d.Round(0)
fmt.Println(d.Nanoseconds()) // Prints 0

I could run the function a couple of times and divide the time by the number of executions, but I would rather like a way to time a single execution. Is there a way to do this?
Comment: Benchmarking a single execution won't give you useful results, ever. Thats why benchmarking libraries call your function thousands, sometimes millions of times.
Comment: Yes, I am aware of that :) This is more or less out of curiosity :) The default benchmarking features of go are solid for me! But I still would like to know if I can measure times under a nanosecond.
Answer: If timing a function is generating a time less than a nanosecond, it usually means that the code was optimized out.
Compilers can detect that some code has no side effects, and decide "why would I do that".
1/(1 ns) is 1 Ghz.  Modern desktop computers cap out at about 5 Ghz, give or take.  So for it to be less than 1 ns, the operation plus the overhead of getting the time has to take fewer than 5 CPU cycles.  At that level of resolution, the CPU isn't doing one thing at a time.  The start of an instruction and the end can be multiple cycles apart, with the operation being pipelined.
So you have to look at the machine code and understand the architecture to determine what the real cost is, including what parts of the CPU's resources are used, and how it would conflict with other operations you might want to do nearby.
So even "before" and "after" stop having reasonable meaning at sub-1-ns time resolutions on most CPUs fast enough to run above 1 Ghz.
Answer: Something you could do, is answer the question "how many runs before this thing
takes at least one nanosecond":
package main

import (
   "fmt"
   "time"
)

func main() {
   d := 1
   for {
      t := time.Now()
      for e := d; e > 0; e-- {
         fmt.Sprint("Hello, World!")
      }
      if time.Since(t) > 0 { break }
      d *= 2
   }
   println(d)
}


A question about Gershwin interpretation

Question:
This is the start one of the famous trumpet tunes from An American in Paris by George Gershwin.  Gershwin famously borrowed jazz styling and harmony within his compositions. But I wanted to ask about rhythm. If I were handed this line in a big band situation, the expectation would be to swing the quavers.
My question is—given the jazzy nature of the piece, even though it's orchestral, would it OK to play this with swung quavers? Can any of the Gershwin scholars on here say definitively that playing it swung is a no go, or is there justification for swinging it? I'm wondering how much artistic licence is too much…
Answer: If Gershwin had wanted this swung he would have written dotted rhythms, as was usual at that time. Gershwin's original piano roll version has no swing, neither for this passage nor the other 'bluesy' trumpet solo. A lot of orchestras want to swing this, Leonard Bernstein's version with the New York Philharmonic  does so (it's a light swing, not a heavy big-band style).
Here's Gershwin's piano roll recording of this passage:

and Bernstein's version:

It probably doesn't really matter how Gershwin intended it, it works either way.
Another piece that is often mistakenly played as swing is Aaron Copland's Clarinet Concerto. Even though it was written for Benny Goodman, the rhythms, particularly in the cadenza, are intended to be more South American.
Comment: @AlbrechtHügli In those days swing was always notated with dotted eighths.
Comment: If it would have been notated dotted this would be still as far from swing as the equal eight notes.
Comment: @PiedPiper Thank you for this answer. I had no idea that piano-roll performances by Gershwin himself even existed. So the best answer is: it works either way. Even though Gershwin imagined it with straight quavers, I'm not going to argue if Bernstein says it's OK to swing it.
Answer: Bernstein was notoriously a terrible interpreter of Gershwin. Gershwin is NOT jazz, & he always stressed that his concerted works be played as notated, straight. To do otherwise would be in direct & flagrant disregard of the composer's intention.
Comment: Thanks for these. Can you provide links that support what you say? I'd like to read a bit more background…
Answer: You can say historical it isn't correct to play this piece with a swing, it is probably closer to the ragtime era than the swing.
This is rather staccato than swing:

But I don't care about it. I prefer Porgy and Bess performed with a light swing as I prefer to hear it sung by natural voices than classical trained opera voices.
Btw. Most Piano music by Bach has an inherent swing in my ears.
Edit: I know this quote isn't answering your question but I like to cite it anyway:
In the Rhapsody and its successors, linking material can indeed be weak, but the relationship between melodies and context is subtler than critics have suggested. And even when our heads might agree with their comments, our hearts don't. We keep on listening, keep finding sustenance, keep humming the tunes.
http://www.classical-music.com/article/george-gershwin-he-had-rhythm-he-had-music
Comment: I agree with you on the Bach, though I think the more classical way of putting it is saying it has a "lilt." One of the many reasons I like Bach so much.
Answer: As has been mentioned, Gershwin had a well established method of notating swing, when he wanted to.
This section strikes me more as in the 'bustle of the big city' than 'the city swings!' genre.
Answer: You ask for a link.  Here is a fine study of Gershwin's music and performance style:

I've been looking in Pollack's authoritative study of the composer, George Gershwin, His Life and Work (https://www.ucpress.edu/book/9780520248649/george-gershwin) for that quote.  I haven't found it yet, but I do distinctly remember reading of the composer's frustration with performers intent upon jazzing up his concert works.  He wanted his carefully-written notations to be taken literally.


jQuery .each() in a nested array

Question: My apologies for the long post but I'll give you the full story. I have a page that lists some products and below each has a little jQueryUI calendar to select a delivery date. I won't get into why, but I have to do what I'm doing with client side scripting.
I'm using jQuery to loop through each product name. For each one, it checks an array of keywords and takes action if the product name is found anywhere in the array.
The end action will be using a call to the associated calendar datepicker and apply a minimum and maximum date to it (that's easy).
What I'm having trouble with now is that I've decided to use a nested array for the product names and the dates you're allowed to choose to have those delivered.  So instead of just an array of keywords, I have:
var keywordArray = [
    //product name, start date, end date
    ["foo","2/1/2014","2/13/2014"],
    ["bar","2/7/2014","2/12/2014"]
];

So "foo" can only be delivered between 2/1 and 2/13.

Given this, my inner loop to go through the array needs modified, but I haven't figure out how to do it.  It worked great when the array was just a simple array of keywords, but now I need to test the first element of each array in the array of arrays (what a mouthful).
function checkAllowedDates() {
    $("div[id^='delivery_product_name_']").each(function(index) {   //outer loop (each product name)

        str = $("div#delivery_product_name_"+parseInt(index+1)).text(); //gets text inside 'delivery_product_name_1', _2, etc...

        $.each(keywordArray,function(index,value){  //test all array values to see if any are in the product name

            if (str.toLowerCase().indexOf(value) >= 0) {    //contains a keyword
            console.log(str+ " contains the special keyword " + value);
            }
        });
    });
}

I tried using value[0], no dice. I googled/binged how to use nested arrays, and found some great examples and I could probably do it using a normal for loop, but I really wanted to use jQuery on this.
So short form: how do I use $.each() to loop through an array of arrays, and test the 0th index of each inner array (the product name string) to see if it matches the current product name text of my outer loop?
Comment: Off topic of your question, but I would suggest looking into using data- attributes for storing data like "index" instead of parsing the IDs of your elements. That's got a strong "code smell" to me.
Comment: Since "value" is an array, you would need value[0] to get the keyword. You say that you tried the provided code with value[0] instead of value and it didn't work? Note: For efficiency, I'd convert str to lower case outside the loop.
Comment: I ended up getting this to work with value[0], I'm not sure why I was failing at first.

    if (str.toLowerCase().indexOf(value[0].toLowerCase()) >= 0) {  //contains a keyword
Answer: Why would you not simply use a data structure that is easier to work with like:
var keywordObj = {
    foo: ["2/1/2014","2/13/2014"],
    bar: ["2/7/2014","2/12/2014"]
};

This way you have a key against which you can perform a lookup. This prevents you from needing to do a nested loop at all.  You could simply get start/end dates based on your str value like this:
var startDate = keywordObj[str][0];
var endDate = keywordObj[str][1];

You could even have nested object to get specific startDate/endDate properties like
var keywordObj = {
    foo: {
        startDate: "2/1/2014",
        endDate: "2/13/2014"
    },
    bar: {
        startDate: "2/7/2014",
        endDate: "2/12/2014"
    }
};

And then access like:
var selectedItem = keywordObj[str];
console.log(selectedItem.startDate);
console.log(selectedItem.endDate);

To summarize, because you are not structuring you data for easy lookup, you are having to do an unnecessary loop to find the data you are looking for in your data structure. This means your operation has operational complexity of O(n) when it could have O(1).  Always think about your data structure and how it needs to be set up to get to the data in best manner.
Answer: Is this what you want?
$.each(arr, function(){
  console.log("outer loop")
  console.log(this)
  $.each(this, function(){
    console.log("inner loop")
    console.log(this)
  })
})

And output is like
outer loop
[1, 2]
inner loop
Number {[[PrimitiveValue]]: 1}
inner loop
Number {[[PrimitiveValue]]: 2}
outer loop
[3, 4]
inner loop
Number {[[PrimitiveValue]]: 3}
inner loop
Number {[[PrimitiveValue]]: 4}

Answer: function checkAllowedDates() {
    $("div[id^='delivery_product_name_']").each(function(index) {   //outer loop (each product name)

        str = $("div#delivery_product_name_"+parseInt(index+1)).text(); //gets text inside 'delivery_product_name_1', _2, etc...

        $.each(keywordArray,function(index,value){  //test all array values to see if any are in the product name

            if (str.toLowerCase().indexOf(value[0]) >= 0) {    //contains a keyword
            console.log(str+ " contains the special keyword " + value[0]);
            }
        });
    });
}

Hope it helps.
Answer: You are on the right track but got this line wrong
if (str.toLowerCase().indexOf(value[0]) >= 0) {

It should actually be the other way around
if (value.indexOf(str.toLowerCase()) >= 0)

The format is
array.indexOf(searchElement[, fromIndex = 0])

More info and examples here

jQuery .each() in a nested array


Views Rewrite return html string instead of rendering them

Question: I am using Drupal 8.1.3 and in simple views I want to use rewrite feature of views, and I put {{ totalcount }} in rewrite section and on out put I see

Where is the problem and why view template engine not render HTML in rewrite section?
UPDATE
Exactly it that views I try rewrite title field and for it works correctly is seems problem is with statistics total view field !!!
Comment: Can you provide which templates are you using to override your views fields?
Comment: @darol100 I used boostrap theme, but it's not relate to theme because I have the same in the views preview.
Answer: I think it could be because of the .... tags part, if you take that out, does it render? Seems like views uses Filter HTML, and only popular html tags are allowed on Custom Fields or Re-Write boxes.
You should be able to achieve your goal by creating a template file.
views-view-fields--[view-name]--[machine-name].html.twig
{{ fields.totalcount.content }}

Comment: Thanks for you attention, it was because statistics field, I try ti add global unformated field then put `{{ fields.totalcount.content }}` and work correctly. it seems it is a issue in statistics module


How To Remove Content Types?

Question: I installed a custom module that created few content type that I'm no longer need it. I disable and uninstall that module but I still have the content type. And it bother me every time I see it. So I try to delete it however, I cant because for some reason doesnt have the delete button. So now I have 5 content type that I don't need. Can anyone have a solution on how to remove these content types ?
In this picture you will see that doesnt allow me to delete the content type.
Comment: Are you certain that you completely uninstalled the module(s)?
Answer: If nothing else helps, delete them in the database directly (its probably advisable to make a backup):
<code>DELETE FROM `your_database`.`node_type` WHERE `node_type`.`type` = \'blog_post\'"
</code>

How To Remove Content Types?


Proof of Zariski lemma.

Question: I am studying algebraic curves but I have no background of commutative algebra.An important theorem in this topic is the weak Nullstellensatz which states that:

Any maximal ideal of $K[X_1,...,X_n]$ where $K$ is algebraically closed is of the form $\langle X_1-a_1,...,X_n-a_n\rangle$.

This follows from Zariski's lemma.The statement is as follows:

If the field $L$ is a finitely generated $K$-algebra where $K\subset L$ is a subfield,then $L/K$ is a finite extension,hence algebraic.

Where the definition of a finitely generated $K$-algebra is as follows:

Any quotient of the form $K[X_1,X_2,...,X_n]/I$ for some $n\in \mathbb N$ (and some ideal $I$ of $K[X_1,...,X_n]$) is called a finitely generated $K$-algebra.

Now I am looking for a proof of Zariski's lemma which does not use much of commutative algebra.But first I want some intuition about what we are trying to do and why this theorem should be true and what it really means because just by looking at the statement,it is not possible for me to understand its significance.I would also like some analogy with some known fact from field theory.Can someone provide me with an answer?
Comment: I don't think there is much intuition here, this is indeed a surprising result. Its significance is clear though, as many times we can say a field extension is finite when we know very little about that extension. For example, if $m$ is a maximal ideal of $F[x_1,...,x_n]$ then the quotient $F[x_1,...,x_n]/m$ is a finite (and hence algebraic) extension of $F$, which is very nontrivial. Not sure there is a proof which avoids using at least some commutative algebra though. After all, this theorem is more about ring theory than field theory.
Answer: Zariski's lemma and hence the weak Nullstellensatz has a "cheap proof" in the special case that $K$ is uncountable, which is one of the most relevant cases in practice anyway because it covers $K = \mathbb{C}$.
Here is a sketch, details left as exercises: let $L/K$ be a field extension where $K$ is uncountable. Then $L$ is either algebraic or transcendental. If $L$ is transcendental it has some transcendental element $t$. Now I claim that the elements $\frac{1}{t - a}, a \in K$ of $L$ are all linearly independent over $K$; this follows from the uniqueness of partial fraction decomposition in $K(t)$ (exercise #1). Since $K$ is uncountable, there are uncountably many of these, and so $L$ has uncountable dimension over $K$.
But if $L$ is finitely generated over $K$ as a $K$-algebra then it must have at most countable dimension over $K$ (exercise #2). So in this case $L$ cannot contain an element transcendental over $K$, and so must be algebraic. Since it is finitely generated it is generated by a finite number of elements algebraic over $K$ which implies that it is finite-dimensional over $K$ (exercise #3).
So, the basic idea is that transcendental extensions are "too big" to be finitely generated as $K$-algebras. There is actually a way to deduce the general case from the special case that $K$ is uncountable, which you can see at this MO question.
Answer: See Theorem 2.11 in https://kconrad.math.uconn.edu/blurbs/ringtheory/maxideal-polyring.pdf. Some applications are in Section 3. An analogous result is proved in a similar way as Theorem 5.1: a field that is finitely generated as a $\mathbf Z$-algebra (such as $\mathbf Z[x,y]/M$ where $M$ is a maximal ideal) is a finite field.

Proof of Zariski lemma.


Matrix Factorization in Recommender Systems: Multiple solutions?

Question: I have implemented a recommender system for predicting user ratings based on the matrix factorization approach.
$$
r_{ui}=μ+b_u+b_i+q_i^T p_u
$$
Where q and p are found by mimization of the squared error function with regularization of the rated itens
$$
(p^*,q^* ) = \text{argmin} \sum (r_{ui}- q_i^T p_u)^2+λ(q_i^2+p_u^2)
$$
Problem is that I'm getting slightly different predictions each time.
I suppose this a  local optima problem since the objective function is not convex. Yet I haven't seen any discussions on this issue on my research.
Increasing the value of the regularization parameters mitigates the problem in the simulation but the optimal value changes with the size of the utility matrix, and in real life application I won't really know in advance the size of the matrices.  Recalibrating  the "lambdas" in each situation would be extremely inconvenient.
Any clues on how to overcome this problem?
Answer: This is a well-known problem in the context of Matrix Factorization based methods: solutions are not unique.
Indeed, let's consider a non-singular matrix $U$. Let's introduce new vectors
$$
q'_i = U^T q_i \quad \quad
p'_u = U^{-1} p_u
$$
It's easy to see that inner product of new vectors is the same as inner product of old ones, since $U$ and $U^{-1}$ cancel each other out when multiplied. Moreover, if $U$ is unitary, then it's known to be norm-preserving, which means that L2 regularization term will stay the same.
That said, I'm not familiar with approaches to solve this problem. According to the Wikipedia, in order to fix the issue one should use sparsity constraints. There are several papers on the subject, though all of them deal with non-negative factorization:

Sparse and Unique Nonnegative Matrix Factorization Through Data
Preprocessing
Sparse Coding and NMF
First results on uniqueness of sparse non-negative matrix factorization


Downgrade Ubuntu 10.10 to 10.04

Question: It seems that U 10.04 has better ruby support than 10.10.
Should I downgrade? Would it be a lot of trouble?
If I do want to, what is the best way to do it?
I basically know nothing about server admin...
Comment: If you know nothing about this, you're probably best off just re-installing the desired distro version.
Comment: `It seems that U[buntu] 10.04 has better ruby support than 10.10.` <- Care to explain? What is "better" about it?  Generally you don't want to downgrade a whole distribution release just for Ruby...
Answer: Both Ubuntu 10.04 and Ubuntu 10.10 have a full suite of Ruby utilities available from their package management system.  I highly doubt they've supported less Ruby features as time has gone on so it's likely you just need to install the tools/libraries you need.
If you're using the GUI, you can look into Synaptic Package Manager to find various Ruby packages.  If you have only access to the command-line, commands like apt-cache search and apt-get install are your friends.  There is also the interactive command-line program aptitude.
In addition, if you have some reason for having 10.10 in the first place, you can install custom versions of Ruby either by downloading and installing them from source (this will take some learning if you're starting with no basic knowledge of systems administration, but is achievable), or using a tool called Ruby Version Manager.
If you have no reason for using 10.10 currently, @Zoredache is absolutely correct and you should check out 12.04.
Answer: The only supported way to downgrade is to backup, format, and re-install.  The amount of trouble this would be completely depends on how well you have documented your setup procedures.
Ubuntu 10.10 does not have long-term support and will not recieve security coverage after April 2012, so you should strongly consider either upgrading to a more recent release or going back to 10.04.  A new LTS release should be coming out very soon.  It might be stable enough now, that you could upgrade and start using it now.
Comment: Is upgrading quasi-simple?
Comment: @KevinBrown yes, but upgrade one version at a time. 10.10 -> 11.04 -> 11.10. Skipping versions makes a mess.
Comment: Super. Thank you.  You don't have to, but I'd appreciate a simple example of the upgrade process or a good tutorial?
Answer: If I were actually going to do this, I would use apt pinning to force old packages to replace current ones and current ones to be uninstalled if they have no replacement. I'd then cry a little inside when obsoleted packages are not replaced with their older versions because they've been removed in the newer release. I'd probably spend some time fighting with impossible dependency loops and having to fix them with manual wielding of dpkg.
You may want to force-downgrade some select packages related to ruby, but beware that his can make a hell of a mess. Unless you really know what you're doing, don't.
Whether the older packages will work with newer base libraries isn't a guarantee. If that's the case, consider learning how to compile packages from source if you want to work on a specific revision. That will allow you to get the version you want without possibly having to downgrade major system libraries (and, in turn, everything that uses them).
... but really, tell us what the actual, direct problem is. I think most of us suspect your root cause analysis and action plan are poorly chosen.

Downgrade Ubuntu 10.10 to 10.04


Can a router have the same ip on both sides?

Question: I intend to implement an interconnected star topology network.
For this, I am using 3 routers: Router A, A1 and A2.
<code>           internet
              |
           Router A
         172.16.0.1 /16
          /         \
         /           \
        /             \
     A1                A2
172.16.1.1 /24    172.16.2.1 /24
     /\                /\
    hosts             hosts
</code>
I wish to assign the IPs in a hierarchical manner, to allow the subnets A1 and A2 be independently managed and further broken into even smaller subnets.
How should I configure the IP address of each interface in this situation?
Could I use the same IP (172.16.1.1) on both A1's interfaces?
Lets say eth0:172.16.1.1/16 and br1:172.16.1.1/24
I would actually want to use host address 0, but I've omitted that above to avoid confusion, so I wrote 1 instead.
Answer: You technically could use the same address on both interfaces, but the traffic for /24 will only go to the interface with that subnet, since routing follows the longest network prefix. However, if the interface with the /24 is down, traffic for that subnet will go to the /16 interface, where it will die.
Best practice is not to have overlapping ranges, unless you have a specific requirement
Comment: I can imagine this scenario working in case of some dynamic routing protocol in place (the /24 subnets would be propagated "up" to A router). The question is if this would be understood as "simple" configuration or if the easier way would be just select other address schema. It may have sense to keep one /24 subnet as interconnection and other /24 subnets for "sub routers".
Comment: Actually, I would rip into any of my people that came up with a plan like this, unless there was a very good reason. It is fraught with problems and will bite you later.

Just assign non-overlapping network to each interface
Comment: So, a packet originating from the /16 subnet with destination 172.16.1.1 will first pass on the other side and arrive at the /24 interface. However, a packet originating from the /24 subnet will arrive at the same /24 interface.Did I get that right?
Comment: If the source is in the /16, it will stay local because it is not aware that another network with the same target as 172.16.1.1. With the exception of special cases, routing information is not propagated down to the end hosts. Since the destination is a local address in the /16 block, it would never need to be routed.
This type of config is bad news and sure to cause problems