Pesquisa - Mostrar Mensagem caso os resultados não forem encontrados

Question: Estou com um probleminha no javascript, peguei um js que faz o search na tabela, porém quando não há registros ele apenas não mostra nada, como faço para colocar um "return" com alguma frase quando não houver registros,tentei algumas vezes mas sem sucesso. Segue:
// Write on keyup event of keyword input element
$("#search").keyup(function(){
    _this = this;
    // Show only matching TR, hide rest of them
    $.each($("#table tbody").find("tr"), function() {
        console.log($(this).text());
        if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
            $(this).hide();
        else
            $(this).show();
    });
});

Comment: Onde você quer mostrar essa frase? No lugar da tabela?
Comment: Isso, defini a tag tfoot lá no html com um id, e agora quando não mostrar resultado nenhum (que não foi encontrado), dar um append lá na tfoot
Comment: Dê uma olhada na minha resposta. =)
Answer: Tudo que você vai precisar fazer é identificar quanto todas as tr estiverem com display:none e quando estiverem mostrar a mensagem informando que não existe dados para o filtro informado.
Exemplo:
JS:
var table = $("#table tbody").find("tr");
var mensagem = $("#mensagem");
mensagem.hide();
$("#search").keyup(function() {
  _this = this;
  $.each(table, function() {
    if ($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
      $(this).hide();
    else
      $(this).show();
  });

  var tableDisplay = table.css('display');

  mensagem.hide();
  if (tableDisplay === 'none') {
    mensagem.show();
  }

});

HTML:
<form class="navbar-form navbar-left" role="search">

    <input type="text" class="form-control" placeholder="Search" id="search">

</form>

    Gabriel
    Rodrigues
    50

    Highlander
    Imortal
    94

Sem resultados

Fora do each() coloquei uma variavel para mostrar o display das tr, quando todas estiverem ocultas ele irá entrar na  condição  que mostrará a mensagem.
Veja funcionando no jsfiddle
Comment: Obrigado pela disposição em ajudar, eu estava querendo trocar o alert por um append diretamente na tfoot, algo semelhante a isso:

var table = $("#table tbody").find("tr");

$("#search").keyup(function() {
  _this = this;

  $.each(table, function() {
    if ($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
      $(this).hide();
    else
      $(this).show();
  });

  var tableDisplay = table.css('display');

  if (tableDisplay === 'none') {
      $("#paragrafosAdicionais").append("" +
        "Sem resultados" +
        "");
  }

});
Comment: Em vez de trabalhar com o tfoot que vai requerir css por que ficará mal formatada com as td coloque uma div no final e deixe ela com a mensagem, vou editar com exemplo
Comment: Agora sim deu certo, muito obrigado pela ajuda rss
Comment: @RafaelRibeiro Se minha resposta resolveu o seu problema marque ela como aceita ;)
Comment: Esse funcionou "corretamente", desculpa a demora mas nesse javascript até quando acha um registro ele tende a apresentar que não foram encontrados resultados.
Answer: Adicionei ID no tfoot e criei uma flag que recebe a quantidade de registros da tabela e subtrai toda vez que oculta um item, se ao final o valor da flag for 0 eu mostro a mensagem.
var table = $("#table tbody").find("tr");

$("#search").keyup(function() {
  _this = this;
  flag = table.length;

  $.each(table, function() {
    if ($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1) {
      $(this).hide();
      flag--;
    } else {
      $(this).show();
    }
  });

  if (!(flag > 0))
    $("#retorno").html("Não foram encontrados resultados");
  else
    $("#retorno").html("");
});

Exemplo funcional: https://jsfiddle.net/scs5jo2e/
Comment: Qualquer semelhança com a minha resposta e mera coincidência, detalhe testa ai que não esta funcionando direito com 1 registro encontrado.
Comment: Sim, eu usei seu fiddle como base e obrigado pelo alerta, corrigi! =)
Comment: Muito obrigado pela disposição galera, me ajudou muito, de verdade.
Answer: Veja se isso vai dar certo:

.....
$("#search").keyup(function(){
    _this = this;
    // Show only matching TR, hide rest of them
    $.each($("#table tbody").find("tr"), function() {
        console.log($(this).text());
        if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
            $(this).hide();
            $("#msg").html("Ops, nada foi encontrado");
        else
            $(this).show();
            $("#msg").html("Opa, encontramos alguma coisa");
    });
});

Comment: É exatamente isso que eu quero fazer mas ao invés de acrescentar na div colocar no tfoot, esse código não funcionou.
Comment: E assim, no lugar do
$("#msg").html("Ops, nada foi encontrado");

Vc usar isso:
$("#table tfoot").find("td").html("blablabla");

Ou ainda assim:

Ai usando a dica da resposta de ontem


How to use entity field as div background image in Views Slideshow?

Question: I have a "background image" field for a particular entity type. I want to be able to upload an image there, and have that image be displayed as a background image in a div created by a View. An example use case would be a Views slideshow where that background image would be the background image of the slide being viewed, and the entity title and any other chosen fields would be laid on top of that.
One thought I had was to rewrite the output of one of the slideshow fields but I'm not sure how I can rewrite the image into a "background image" position.
Is this possible? Any ideas on how to accomplish this?
Thanks!
Answer: This seems more like a css/html question but here goes:
You can theme your view so it outputs each slide as follows:

Overlay copy

With your css as follows:
.container {
    position: relative; /* this is required to keep all absolutely positioned child elements contained */
    overflow: hidden;
    height: 100px;
    width: 1200px;
}

.background {
    position: absolute;
    left: -200px;
    top: 0;
    height: 100px;
    width: 1200px;
    z-index: 1;
}

.foreground {
    position: absolute;
    left: 50px;
    top: 50px;
    height: 50px;
    width: 300px;
    z-index: 2;
}

This will position the background div at 0,0 (relative to container) and position the foreground div in front of the background.
Comment: Hmmm, that could work. My only issue with that, though, is that the slideshow background image needs to be the full width of the screen (let's say 1600px wide). If I did it in the way you describe, my website will be 1600px wide since it will be accommodating the full width of that background div, but I need the content area (including the "content" of the slideshow) to be 1200px wide.
Comment: I updated the answer to use overflow: hidden on the container which would do the trick.
Answer: Make sure to have a look at the Background Images Formatter module. It allows you to define a background-image (and size) for any given CSS-selector, as specified in your view (using an image field).
This actually takes care of the popular demand of using specific background images in views (and avoiding the inline-style method, which is impossible in Views)


Question regarding finding of formulas for piecewise function composition

Question: I've encountered the following exercise that's giving me a lot of trouble:

Let $X$ be a set. For any subset $A\subseteq X$, we can define a function $C_{A}:X \to \mathbb{Z}$ by:
  $C_{A}(x)=\begin{cases}
1 \text{ if } x\in A\\
0 \text{ if } x\notin A
 \end{cases}$

  Find formulas for $C_{A \cup B}$, $C_{A \cap B}$, and $C_{\overline{A}}$ in terms of $C_{A}$ and $C_{B}$. Explain why your answer works.

My problem is that we know what $C_{A}$ is, but how do you find the value of $C_{B}$?
Answer: The definition is not restricted for a particular subset $A$. It says, given any subset, which we call $A$ for the sake of this definition, we define a function which depends on that subset...
So $C_B(x)=1$ whenever $x\in B$, and $C_B(x)=0$ whenever $x\notin B$.
Comment: Thanks, that makes sense. So what format would my formulas generally look like? Would they also be piecewise?
Comment: Think what happens when you multiply two functions. What would the result be?


Caça palavras não encontra a palavra

Question: Galera, tô tentando fazer um jogo de caça palavras em java, mas não estou conseguindo encontrar a palavra, alguém pode ajudar?
Segue o código:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class File {
public static void main(String[]args) throws Exception{
//        File arquivo = new File ("C:\\teste01.txt");

FileReader arquivo = new FileReader ("C:\\teste01.txt");
    BufferedReader br = new BufferedReader(arquivo);
    Scanner sc = new Scanner(System.in);

char[][] matriz = null;
    String entrada = null;
    int coluna = 0;
    boolean primeira = true;
    while (br.ready()){
        String linha = br.readLine();
        if(primeira) {
            String []b = linha.split(" ");
            int a = Integer.parseInt(b[0]);
            int d = Integer.parseInt(b[1]);
            matriz = new char[a][d];
            primeira = false;
        } else {
            char[] auxLinha = linha.toCharArray();

            for (int i = 0; i < auxLinha.length; i++) {
                matriz[coluna][i] = auxLinha[i];
            }

            coluna++;
        }
    }

    for (int i = 0; i < matriz.length; i++) {
        for (int j = 0; j < matriz[i].length; j++) {
            System.out.print(matriz[i][j]+" ");
        }
        System.out.println("\n");
    }

br.close();

   int i, j, k, n = 0, p = 0, t; //Contadores

int encontrada = 0; // SIM = 1. NÃO = 0.

 char palavra[][] = null ;
for (i = 0; i < p; i++)
     System.out.println("DIGITE A PALAVRA:\n");
        String palavraNextLine = sc.nextLine(); //Armazena as palavras que serão buscadas na matriz.

System.out.println("RESULTADO:\n");

for (k = 0; k < p; k++) //Para cada palavra
{
    //Inicialmente a palavra é considerada Não-Encontrada.
    encontrada = 0;

    for (i = 0; i < n; i++) //Para cada linha da matriz
    {
        for (j = 0; j < n; j++) //Para cada coluna da matriz
        {
            if (palavra[k][0] == matriz[i][j]) //Se a primeira letra for encontrada
            {
                if (palavra[k][1] == matriz[i - 1][j]) //Se a segunda letra for encontrada acima (Norte)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k]).length; t++)
                        if (palavra[k][t] != matriz[i - t][j])
                            encontrada = 0;

                    if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i + 1][j]) //Se a segunda letra for encontrada abaixo (Sul)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i + t][j])
                            encontrada = 0;

                     if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i][j + 1]) //Se a segunda letra for encontrada a direita (Leste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i][j + t])
                            encontrada = 0;

                     if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i][j - 1]) //Se a segunda letra for encontrada a esquerda (Oeste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i][j - t])
                            encontrada = 0;

                    if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i - 1][j + 1]) //Se a segunda letra for encontrada acima-direita (Nordeste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i - t][j + t])
                            encontrada = 0;

                     if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i - 1][j - 1]) //Se a segunda letra for encontrada acima-esquerda (Noroeste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i - t][j - t])
                            encontrada = 0;

                    if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i + 1][j + 1]) //Se a segunda letra for encontrada abaixo-direita (Sudeste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i + t][j + t])
                            encontrada = 0;

                    if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }

                if (palavra[k][1] == matriz[i + 1][j - 1]) //Se a segunda letra for encontrada abaixo-esquerda (Sudoeste)
                {
                    encontrada = 1;

                    for (t = 0; t < (palavra[k].length); t++)
                        if (palavra[k][t] != matriz[i + t][j - t])
                            encontrada = 0;
                     if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }
            }
        }

                     if (encontrada == 1){
                        break;
                }else{
                    return;
                    }
                }
    }

    //Depois da verificação ele diz se a palavra foi encontrada ou não, então passa para a verificação da próxima palavra.
    if (encontrada == 1){
        System.out.println(" PALAVRA ENCONTRADA\n");
    }else{
        System.out.println(" PALAVRA NAO ENCONTRADA\n");
}
}
}

Comment: Voce deu alguns prints? Tentou debugar?  Mostre qual o caminho que seu código esta seguindo dado um conjunto de teste controlado. Ficar debugando código alheio do zero é dificil, sua dúvida deve ser direcionada!
Comment: O codigo nao da erro, ja debuguei , mas ele nao encontra a palavra , retorna sempre q a palavra nao foi encontrada
Answer:
Use o tipo boolean! Ele é seu amigo e serve para ajudar! Não utilize int com 0 e 1 para representar valores verdadeiro/falso ou sim/não.
Aprenda a identar o código. Só de ver a forma como você posicionou os blocos else, me dá a entender que você os colocou no lugar errado e com isso, você acaba entendendo errado o seu próprio código.
Isso daqui, que aparece repetido nove vezes no seu código NÃO faz o que você quer:
        if (encontrada == 1) {
            break;
        } else {
            return;
        }

Em especial, o return dentro do método main faz o seu programa abortar imediatamente, não importando se ele encontrou ou não a palavra. No caso do seu programa, você não deveria usar return em lugar nenhum.
Você não verifica os limites da matriz antes de acessar os seus elementos, e como resultado terá alguns IndexOutOfBoundsException. Por exemplo, nesta linha:
if (palavra[k][1] == matriz[i - 1][j]) //Se a segunda letra for encontrada acima (Norte)

Adivinha o que vai acontecer se i tiver o valor 0? O correto é verificar isso antes de tentar acessar o índice:
if (i > 0 && palavra[k][1] == matriz[i - 1][j]) //Se a segunda letra for encontrada acima (Norte)

Você pode dar nome para os seus laços for, while e do-while. Por exemplo:
a: for (int i = 0; i < n; i++) {
    b: for (int j = 0; j < n; j++) {
        // ... blablabla
        break a; // Interrompe o laço a (e também o laço b).
        // ... blablabla
    }
}

Usando isso, a lógica do seu programa pode ser simplificada um bocado. O mesmo vale para continue.
Dar o nome da sua classe de File é uma péssima ideia, afinal isso vai te dar dor-de-cabeça quando você for precisar da classe java.io.File. Use um nome diferente, tal como CacaPalavras.
Utilize a sintaxe try-with-resources para ler dados de arquivos, tal como você faz com o seu BufferedReader.
Prefira declarar as variáveis no ponto aonde serão usadas (dentro do for) do que todas elas juntas do lado de fora. A regra de ouro é não deixar elas terem um escopo maior que o necessário.
O algoritmo fica bem mais simples se você dividi-lo em vários métodos.
Comment: Olha, é uma bela de uma resposta essa, viu? Não só pelo trabalhão que deve ter dado analisar o código do AP, mas também pelo bom conhecimento da linguagem embutido em alguns dos seus tópicos. +1 merecido. :)
Comment: Serio que isso `a:` e isso `break a;` funcionam? (Estou sem IDE para testar agora), mas se isso funciona (que acredito que sim), por que nunca ninguém me falou? =(. Agora só posso dizer isso: "Só sei que nada sei"([Sócrates (é né? Não entendi se foi ele que falou ou ela)](http://pt.wikipedia.org/wiki/S%C3%B3_sei_que_nada_sei)), a  e +1, muito boa explicação e paciência em compreender e analisar o algoritmo do AP.
Comment: @Fernando Sim, é sério que isso funciona. :)
Comment: Já trabalho com Java há mais de um ano e também nunca ouvi falar ou li sobre essa de dar nomes aos laços de repetição **a: for(;). brake a;**. Todos os dias a gente aprende mesmo algo novo!
Comment: Dar rótulo pra loop é nova pra mim também. +1 por sugerir reduzir escopo das variáveis, dentre outros.
Answer: Uma abordagem orientada a objetos
Este problema pode ser resolvido também com um pouco da boa e velha orientação a objetos, diminuindo a repetição de código e a quantidade de loops e ifs a fim de facilitar o desenvolvimento e ter um resultado final mais simples:
public class CacaPalavras {

    public static boolean palavraEncontrada(char[][] tabuleiro, String palavra) {

        for (int posicaoY = 0; posicaoY < tabuleiro.length; posicaoY++) {

            for (int posicaoX = 0; posicaoX < tabuleiro[posicaoY].length; posicaoX++) {

                if (tabuleiro[posicaoY][posicaoX] == palavra.charAt(0)) {

                    for(Direcao direcao: Direcao.values()) {
                        if (TabuleiroNavegavel.existePalavra(palavra, tabuleiro, direcao,
                                posicaoY, posicaoX)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}

Eu utilizei a mesma lógica proposta por você: percorrer o tabuleiro da esquerda para a direita e de cima para baixo e, ao encontrar uma letra que coincida com a primeira letra da palavra procurada, passa a percorrer o tabuleiro nos mais diversos sentidos para ver se encontra a palavra completa.
O restante do código que faz a mágica acontecer está abaixo:
class TabuleiroNavegavel {
    public static boolean existePalavra(String palavra, char[][] tabuleiro,
                    Direcao direcao, int posicaoInicialY, int posicalInicialX) {

        StringBuilder palavraEncontrada = new StringBuilder();

        NavegadorLetras letras = direcao.letras(tabuleiro,
                                    posicaoInicialY, posicalInicialX);

        int qtdLetrasLidas = 0;

        while(letras.temProxima() && qtdLetrasLidas <= palavra.length()) {
            palavraEncontrada.append(letras.proxima());
            qtdLetrasLidas++;
        }
        return palavraEncontrada.toString().equals(palavra);
    }
}

interface NavegadorLetras {
    boolean temProxima();
    char proxima();
}

interface LetrasNavegaveis {
    NavegadorLetras navegador(final char[][] tabuleiro,
            final int posicaoInicialY, final int posicalInicialX);
}

enum Direcao {
    LESTE(new Leste()),
    SUDESTE(new Sudeste()),
    SUL(new Sul()),
    NORDESTE(new Nordeste());

    private LetrasNavegaveis letrasNavegaveis;

    Direcao(LetrasNavegaveis letrasNavegaveis) {
        this.letrasNavegaveis = letrasNavegaveis;
    }
    public NavegadorLetras letras(char[][] tabuleiro,
                            int posicaoInicialY, int posicalInicialX){
        return letrasNavegaveis.navegador(tabuleiro, posicaoInicialY, posicalInicialX);
    }
}

class Leste implements LetrasNavegaveis {

    public NavegadorLetras navegador(final char[][] tabuleiro,
                            final int posicaoInicialY, final int posicalInicialX) {

        return new NavegadorLetras() {
            int posicaoX = posicalInicialX;
            int posicaoY = posicaoInicialY;

            public boolean temProxima() {
                return posicaoX < tabuleiro[posicaoY].length;
            }
            public char proxima() {
                char letra = tabuleiro[posicaoY][posicaoX];
                posicaoX++;
                return letra;
            }
        };
    }
}

class Sudeste implements LetrasNavegaveis {

    public NavegadorLetras navegador(final char[][] tabuleiro,
                            final int posicaoInicialY, final int posicalInicialX) {

        return new NavegadorLetras() {

            int posicaoY = posicaoInicialY;
            int posicaoX = posicalInicialX;

            public boolean temProxima() {
                return posicaoY >= 0 && posicaoY < tabuleiro.length
                    && posicaoX >= 0 && posicaoX < tabuleiro[posicaoY].length;
            }
            public char proxima() {
                char letra = tabuleiro[posicaoY][posicaoX];
                posicaoY++;
                posicaoX++;
                return letra;
            }
        };
    }
}

class Sul implements LetrasNavegaveis {

    public NavegadorLetras navegador(final char[][] tabuleiro, final int posicaoInicialY,
                            final int posicalInicialX) {

        return new NavegadorLetras() {
            int posicaoY = posicaoInicialY;
            int posicaoX = posicalInicialX;

            public boolean temProxima() {
                return posicaoY >= 0 && posicaoY < tabuleiro.length;
            }
            public char proxima() {
                char letra = tabuleiro[posicaoY][posicaoX];
                posicaoY++;
                return letra;
            }
        };
    }
}

class Nordeste implements LetrasNavegaveis {

    public NavegadorLetras navegador(final char[][] tabuleiro,
                            final int posicaoInicialY, final int posicalInicialX) {

        return new NavegadorLetras() {
            int posicaoY = posicaoInicialY;
            int posicaoX = posicalInicialX;

            public boolean temProxima() {
                return posicaoY >= 0 && posicaoY < tabuleiro.length
                    && posicaoX < tabuleiro[posicaoY].length;
            }
            public char proxima() {
                char letra = tabuleiro[posicaoY][posicaoX];
                posicaoY--;
                posicaoX++;
                return letra;
            }
        };
    }
}

Um exemplo de código consumidor:
@Test
public void cacaPalavras() {

    char[][] tabuleiro = new char[][] {
            {'R','X','L','X','A'},
            {'X','A','U','X','X'},
            {'R','U','I','V','A'},
            {'X','A','Z','V','X'},
            {'C','X','A','X','A'}};

    assertTrue(CacaPalavras.palavraEncontrada(tabuleiro, "RUIVA"));
    assertTrue(CacaPalavras.palavraEncontrada(tabuleiro, "RAIVA"));
    assertTrue(CacaPalavras.palavraEncontrada(tabuleiro, "LUIZA"));
    assertTrue(CacaPalavras.palavraEncontrada(tabuleiro, "CAIXA"));
    assertFalse(CacaPalavras.palavraEncontrada(tabuleiro, "INEXISTENTE"));
}

Você pode envolver este código com a sua lógica de ler o tabuleiro de um arquivo e solicitar uma lista de palavras do usuário :-)
Como estender a solução
Veja que eu só implementei o padrão mais ocidental de leitura, por assim dizer: leste, sul, sudeste, nordeste.
Mas para implementar mais padrões é muito simples. Você não precisa inserir código no meio de um grande e complexo método nem reprogramar o fluxo do programa. Ao invés, você define um nova direção de leitura na enumeração e declara uma classe especializada em ler nesta direção.
Se você quiser por exemplo implementar agora a direção sudoeste de leitura, basta declarar a seguinte classe:
class Sudoeste implements LetrasNavegaveis {

    public NavegadorLetras navegador(final char[][] tabuleiro, final int posicaoInicialY,
                            final int posicalInicialX) {

        return new NavegadorLetras() {
            int posicaoY = posicaoInicialY;
            int posicaoX = posicalInicialX;

            public boolean temProxima() {
                return posicaoY < tabuleiro.length
                    && posicaoX >= 0;
            }
            public char proxima() {
                char letra = tabuleiro[posicaoY][posicaoX];
                posicaoY++;
                posicaoX--;
                return letra;
            }
        };
    }
}

E adicionar esta nova direção de leitura na enumeração:
SUDOESTE(new Sudoeste());

Agora, no teste abaixo, a palavra "Ruiva" será encontrada:
@Test
public void sudoeste() {
    char[][] tabuleiro = new char[][] {
            {' ',' ',' ',' ','R'},
            {' ',' ',' ','U',' '},
            {' ',' ','I',' ',' '},
            {' ','V',' ',' ',' '},
            {'A',' ',' ',' ',' '}};

    assertTrue(CacaPalavras.palavraEncontrada(tabuleiro, "RUIVA"));
}

E pronto :-)
Conclusão
Eu e muitos dos nossos colegas consideram este código bastante simples mas eu entendo que talvez você não o compreenda completamente ainda.
Minha sugestão, é claro, é que você tente compreender.
Alguns recursos do Java que foram utilizados aí:

Interface
Enumeração.
Extensão de enumeração: eu adicionei um atributo a cada item da enumeração, que é o objeto especializado em percorrer o tabuleiro naquela direção.

E apesar de eu não considerar quantidade total de linhas muito importante, eu observo que embora meu código funcione ele tem ainda menos linhas que o código original da pergunta.
Comment: Isto é mais um tutorial do que apenas uma resposta, não só um tutorial de Orientado-á-objeto, mas também de "lógica" do jogo +1, parabéns pela ótima resposta.

Caça palavras não encontra a palavra


Determine $k$ so that the function is continuous

Question:
$$y=\begin{cases}\Large{\frac{\left(e^{(k+2)x}-1\right)}{5x}}&x<0\\x^2+5k-2&x\ge0\end{cases}$$

Applying the continuity theorem, I tried this
$$\lim_{x\to0^-}\left(\frac{\left(e^{(k+2)x}-1\right)}{5x}\right)=\lim_{x\to 0^+}(x^2+5k-2)$$
And then seeing that the first limit was irrational I used L'Hôpital's rule and I got this
$$\frac{\left((k+2)e^{(k+2)x}\right)}5$$
After that I just replaced the $x$ term with $0$ and found that $k = 1/2$.
Did I do it right?
Answer: Yes. It's correct.
$$\frac{k+2}{5}=5k-2$$
$$k+2=25k-10$$
$$12=24k$$
$$k=\frac12$$


Showing that a cylinder transformation maps rays to horizontal lines and circles to circles

Question: I am reading through a text on time scale calculus and I came upon a certain transformation whose follow up question I cannot solve. Its defined as follows
For $h >0$, let $\mathbb{Z}_h$ be the strip
$$
\mathbb{Z}_h := \biggl\{ z \in \mathbb{C}: \frac{-\pi}{h} < Im(z) \leq \frac{\pi}{h}\biggr\}
$$  and for $h = 0$, let $\mathbb{Z}_0 := \mathbb{C}$
Definition:
For $h > 0$, we define the cylinder transformation $\xi_h : \mathbb{C}_h \rightarrow \mathbb{Z}_h $ by
$$
\xi_h (z) = \frac{1}{h} \log (1 + zh),
$$ whew log is the principal logarithm function. For $h = 0$, we define $\xi_0 (z) = z$ for all $z \in \mathbb{C}.$ Where $\mathbb{C}_h := \{z \in \mathbb{C}: z \neq -\frac{1}{h}  \}$
We call $\xi _h$ the cylinder transformation because when $h > 0$ we can view $\mathbb{Z}_h$ as a cylinder if we glue the bordering lines $Im(z) = \frac{-\pi}{h}$ and $Im(z) = \frac{\pi}{h}$ of $\mathbb{Z}_h$ together to form a cylinder. We define addition on $\mathbb{Z}_h$ by
$$ z+w:=z+w \;\bigl(\text{mod}\frac{2\pi i}{h}\bigr)\; for \; z,w \in \mathbb{Z}_h.
$$
The question is:
Show that the cylinder transformation $\xi_h$ when $h > 0$ maps open rays emanating from the point -$\frac{1}{h}$ in $\mathbb{C}$ onto horizontal lines on the cylinder $\mathbb{Z}_h$. Also show that circles with center at -$\frac{1}{h}$ are mapped onto vertical lines on the strip $\mathbb{Z}_h$ (circles on the cylinder $\mathbb{Z}_h$).
My attempt was taking an example ray, eg $\{z:  zh + 1 > 0  \}$ and try to plug it in the transformation $\xi_h$, but I get stuck and fail to show it maps to horizontal lines on the cylinder. Perhaps a fresh set of eyes might help
Answer: Any ray $R_{\theta}, -\pi < \theta \le \pi$ as in the OP is defined by $\arg(z+\frac{1}{h})=\theta$ so we have that $\arg (zh+1)=\arg (h(z+\frac{1}{h}))=\theta$ is constant too as $h>0$.
But this precisely means that $\Im \xi_h (z)=\frac{\theta}{h}, z \in R_{\theta}$ is constant so indeed the image of $R_{\theta}$ is a horizontal line in the strip.
For the circle $C_r$ we have that $|z+\frac{1}{h}|=r$ so $|zh+1|=rh$ or $\Re \xi_h (z)=\frac{\log hr}{h}$ is constant on $C_r$ which means that its image is a vertical line (hence a circle on the cylinder)


"global" keyword does not work from within drush script

Question: I have the following script:
<?php

$GLOBALS['foo1'] = "foobar1";
function g1() {
    echo "g1 " . $GLOBALS['foo1'] . "\n";
}

$foo2 = "foobar2";
function g2() {
    global $foo2;
    echo "g2 " . $foo2 . "\n";
}

g1();
g2();

Running it on the browser gives me:
g1 foobar1
g2 foobar2

Running it via drush scr example.php gives me:
g1 foobar1
g2

Any idea why the global keyword doesn't work when I run the script via drush?
I run this on a D7 site with PHP 5.3.5.
Comment: I haven't checked, but presumably Drush runs this in a non-global scope, so `$foo2 = "foobar2"` is not equivalent to `$GLOBALS['foo2'] = "foobar2"`
Answer: To solve it I had to add global $foo; before declaring $foo.
I suppose it relates to this: http://php.net/manual/en/language.variables.scope.php#98811


Communicating between fragments within an activity

Question: I am trying to write a test app which contains an activity. There are two fragments inside this activity, which are defined as LeftFragment and RightFragment. I used getFragmentManager().findFragmentById() to get connection from each other fragments. By using that methode I am able to get an LeftFragment object from RightFragment, but not RightFragment object from LeftFragment. It just works only oneway. I am doing this, because I want to call some operations from other fragment, that return some values. I was thinking about using EventBus but I failed too. How can I achive that?
Here is my LeftFragment
public class LeftFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        RightFragment rightFragment = (RightFragment) getFragmentManager().findFragmentById(R.id.rightFragment);
        if (rightFragment != null){
             makeToast(rightFragment.getMessageFromRight());
        }else {
            makeToast("does not found rightFragment");
        }
        return inflater.inflate(R.layout.fragment_left, container, false);
    }
    public String getMessageFromLeft(){
        return "Hi! Im left";
    }
    private void makeToast(String text){
        Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
    }
}

And here is my RightFragment
    public class RightFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        LeftFragment leftFragment = (LeftFragment) getFragmentManager().findFragmentById(R.id.leftFragment);
        if (leftFragment != null){
            makeToast(leftFragment.getMessageFromLeft());
        }else {
            makeToast("does not found leftFragment");
        }
        return inflater.inflate(R.layout.fragment_right, container, false);
    }
    public String getMessageFromRight(){
        return "Hi! Im right!";
    }
    private void makeToast(String text){
        Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
    }
}

Comment: It is all explained in the documentation how to communicate between fragments: https://developer.android.com/training/basics/fragments/communicating.html
Answer: There are many ways to communicate between 2 fragments . If 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.

You can use this link using obserable pattern to communication 2 fragments.
you can use EventBus lib for communication, it 's very simple

Your issue:

By using that methode I am able to get an LeftFragment object from
  RightFragment, but not RightFragment object from LeftFragment

I think your problem is LeftFragment is intitialized previous, so you can find it from RightFragment. Your solution is ok, using EventBus. YOu need to review  your codes to find the issue. You can test by creating other methods, after 2 fragment  was initialized.
For ex: click button in LeftFragment, toast a message in RightFragment.
Comment: Thanks for your answer. I wanted to mark your answer as correct, but Joels answer was first and it solved my problem too. I will try to use eventbus anyway.
Comment: No problems. :)
Answer: Probably what is happening is that the Left Fragment is getting the OnCreateView() call first, at which point the Right Fragment has not been inflated yet (therefore it can't be "found" by findFragmentbyId()).
I would suggest moving the code that gets the references to the other fragments into onStart(), and only inflate the fragments in onCreateView().


Tagging of tweets using NLTK

Question: Is there a method to perform tagging of tweets using NLTK? The pos_tag() function gives incorrect results on twitter data (which uses textese):
# checking if NLTK tokenizers work on SMS textese
tokens = pos_tag(word_tokenize("ikr smh he asked fir yo last name so he can
                                add u on fb lololol"))

print(tokens)

output:-
 [('ikr', 'NN'), ('smh', 'NN'), ('he', 'PRP'), ('asked', 'VBD'), ('fir', 'JJ'), ('yo', 'NN'),
  ('last', 'JJ'), ('name', 'NN'), ('so', 'RB'), ('he', 'PRP'), ('can', 'MD'), ('add', 'VB'),
  ('u', 'JJ'), ('on', 'IN'), ('fb', 'NN'), ('lololol', 'NN')]

Answer: The ARK Twitter Part-of-Speech Tagger from Prof. Noah Smith's group (back when he was at CMU) is one such resource. The tagset is different from the standard Penn Treebank tagset, and has been created to handle idiosyncrasies of the language on Twitter (http://www.aclweb.org/anthology/P11-2008)
Though the library is in Java, I think there's a python wrapper available somewhere out there!
Answer: Following is the link for the Python wrapper for CMU tweet tagger,
https://github.com/ianozsvald/ark-tweet-nlp-python
Its a Simple Python wrapper around runTagger.sh of ark-tweet-nlp. It passes a list of tweets to runTagger.sh and parses the result into a list of lists of tuples, each tuple represents the (token, type, confidence). Download the ark-tweet-nlp jar to use it.

Tagging of tweets using NLTK


How to prevent non-English characters from turning into jumbled words?

Question: Whenever I move database, even within the same server the non-English characters change into words that are unreadable. My site is not multilingual (it will be in the future) but users post products titles with accents and in French, Polish or another language. How do I retain the characters and prevent the jumbled words? Thank you.
Comment: How are you moving the database?  Some portion of the process isn't UTF8 clean.
Comment: I used phpmyadmin.
Answer: This is a bit of a guess, but it sounds like some part of the process isn't UTF-8 clean.  If Drupal is displaying everything properly, then it sounds like the database actually is UTF-8.  This leaves phpMyAdmin.
I would log into phpMyAdmin with Firefox.  Right-click, and do View Page Info.  Make sure the encoding say UTF-8.
Then install the Live HTTP Headers plugin.  Download a backup and restore one with the plugin running.  Make sure the Content-Encoding is always UTF-8.
If any of them aren't, then you have some server-specific configuration to fix.
Personally, I think phpMyAdmin is a terrible tool and a security risk.  I use the legacy MySQL Administration Tool for most of my server work and a fair number of backup tasks.  You can also try the Backup and Migrate module for taking and restoring backups.  You can also use the sql-* and/or bam-* commands in drush.


Image Upload Issues Same Image Different File Name Always Receive This Error

Question: We are currently working on fine tuning and updating the dev backend of our CMS we're rolling out for a new site.
I was familiarizing myself with the new system and uploaded some images in error.
I then deleted said images using module Reports > Audit Files > Managed not Used.
Once I removed the file another user tried to upload the same file with a different name and we keep getting this error.
We've removed the file from the Database and the  file server but still get the below error every time.
New to Drupal 8 and this forum... If you have solution or work around please let me know.
Answer: You may have the File Hash module installed, and the Optional duplicate file protection feature enabled. That configuration would result in exactly the error message you're seeing, but obviously you may have custom code that does this instead.
If you are using File Hash, and don't want that functionality, you can either disable it at /admin/config/media/filehash, or uninstall the module entirely.


Split 16x16 matrix in 4x4 in the same matrix

Question: Hi guys I am doing a small exercise splitting a 16x16 matrix in 4x4 chunks, creating a sort of diagonal of small matrix. I am representing the 4x4 matrix with a value of 1 and the rest with a value of 0, painting them in the big matrix itself.
This what it should look like:
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"

This is what I have achieved at me moment:

The red squares is what I am missing. These 4x4 matrix has to be "1" as well.
This is code (it is in javascript but I don't really care about the language).
let m = Array(16)
    .fill("0")
    .map(() => Array(16).fill("0"));

for (let i = 0; i < m.length; i++) {
    for (let j = 0; j < m.length; j++) {
        if (i % 8 < 4 && j % 8 < 4) {
            m[i][j] = "1";
        }
    }
}

m.map((a) => console.log(JSON.stringify(a + "")));

Anyone know how to solve this problem? Thank You in advance!
Comment: Your conditional works for the first and third rows of chunks but not for the second and fourth ones. To handle the even rows of chunks, you can modify your condition: `if ((i % 8 < 4 && j % 8 < 4) || (i % 8 >= 4 && j % 8 >= 4))`
Comment: `j&4 == i&4` should do, even `~(j ^ i) & 4`.
Answer: I'd try something like that: it uses even/odd comparison to determine position for "1"

let m = Array(16)
    .fill("")
    .map(() => Array(16).fill(""));

for (let i = 0; i < m.length; i++) {
    for (let j = 0; j < m.length; j++) {
        let mi = parseInt(i/4);
        let mj = parseInt(j/4);
        m[i][j] = ((mi&1) == (mj&1))?"1":"0";
    }
}

m.map((a) => console.log(JSON.stringify(a + "")));
Comment: @MichalRužičkaRužička sure, just use `%2` to figure out odd/even numbers
Comment: Interesting approach. Would it be possible to solve without the bitwise operator?
Comment: Are you "splitting" an existing 16x16 matrix into 16 4x4 matrices or constructing a 16x16 matrix that contains 16 4x4 matrices having the desired pattern of zeroes and ones? If splitting I don't see the relevance of zeroes and ones; resulting 16 4x4 matrices would contain whatever values were in the original array. If constructing I suggest you remove the reference to splitting.
Answer: In Ruby:
require 'matrix'

m = Matrix.build(16, 16) { |i,j| (i/4).even? == (j/4).even? ? 1 : 0 }

To convert the matrix object to an array:
m.to_a
  #=> [[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]]

See Matrix::build and Enumerable#to_a.
This should translate easily to other languages that have a matrix library, but even if such a library is not available, the clause
(i/4).even? == (j/4).even? ? 1 : 0

shows how the array can be constructed in an economic way.

Here's another way that does not use matrices.
a1 =  [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
a2 = a1.reverse
  #=> [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]

Array.new(16) { |i| ((i/4).even? ? a1 : a2).dup }

See Array::new and Kernel#dup.


t-SQL compound statement causes the deadlock, any idea why?

Question: I'm in the process of learning a more complex SQL Server 2008 techniques so I apologize in advance if I ask a too obvious question.
I have the following table created as such:
CREATE TABLE [dbo].[t_Log_2]
(
   [id] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
   [oid] INT,
   [idtm] DATETIME2,
   [odtm] DATETIME2,
   [type] TINYINT,
   [state] TINYINT,
   [huid] UNIQUEIDENTIFIER,
   [cnm] NVARCHAR(256),
   [cmdl] NVARCHAR(256),
   [batt] TINYINT,
   [dvtp0] SMALLINT,
   [dvtp1] SMALLINT
);

CREATE INDEX idx_idt
          ON [dbo].[t_Log_2]([idtm]);

CREATE INDEX idx_odt
          ON [dbo].[t_Log_2]([odtm]);

CREATE INDEX idx_huid
          ON [dbo].[t_Log_2]([huid]);

CREATE INDEX idx_cnm
          ON [dbo].[t_Log_2]([cnm]);

And then the following query can be run from several simultaneous threads from an ASP.NET web application. Note that this whole query needs to run atomically:
SET XACT_ABORT ON;
BEGIN TRANSACTION;

DELETE FROM [dbo].[t_Log_2]
      WHERE [idtm]<'2011-03-12 08:41:57';

WITH ctx AS(
     SELECT MIN([idtm]) AS mdIn,
            MAX([odtm]) AS mdOut
           FROM [dbo].[t_Log_2]
          WHERE [type] = 0
            AND [state] = 0
            AND [huid] = N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4'
            AND [odtm] >= '2013-03-11 06:33:32'
            AND [idtm] <= '2013-03-11 06:43:12'
           )
INSERT INTO [dbo].[t_Log_2]
([oid],[idtm],[odtm],[type],[state],[huid],
 [cnm],[cmdl],[batt],[dvtp0],[dvtp1])
SELECT
    2,
    CASE WHEN mdIn IS NOT NULL
          AND mdIn < '2013-03-11 06:33:32'
         THEN mdIn
         ELSE '2013-03-11 06:33:32'
         END,
    CASE WHEN mdOut IS NOT NULL
          AND mdOut > '2013-03-11 06:43:12'
         THEN mdOut
         ELSE '2013-03-11 06:43:12'
         END,
    0,
    0,
    N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4',
    null,
    null,
    0,
    1,
    null
FROM ctx

SELECT ROWCOUNT_BIG()

DELETE FROM [dbo].[t_Log_2]
      WHERE [type] = 0
        AND [state] = 0
        AND [huid] = N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4'
        AND [odtm] >= '2013-03-11 06:33:32'
        AND [idtm] <= '2013-03-11 06:43:12'
        AND [id] <> SCOPE_IDENTITY()

DELETE FROM [dbo].[t_Log_2]
      WHERE [type] = 0
        AND [huid] = N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4'
        AND [idtm] >= (SELECT [idtm] FROM [dbo].[t_Log_2]
                                    WHERE [id] = SCOPE_IDENTITY())
        AND [odtm] <= (SELECT [odtm] FROM [dbo].[t_Log_2]
                                    WHERE [id] = SCOPE_IDENTITY())
        AND [id] <> SCOPE_IDENTITY()

;WITH ctx1 AS(
     SELECT [idtm] AS dI
       FROM [dbo].[t_Log_2]
      WHERE [id] = SCOPE_IDENTITY()
             )
UPDATE [dbo].[t_Log_2]
        SET [odtm] = ctx1.dI
       FROM ctx1
      WHERE [id] <> SCOPE_IDENTITY()
        AND [type] = 0
        AND [huid] = N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4'
        AND [idtm] < ctx1.dI
        AND [odtm] > ctx1.dI

;WITH ctx2 AS(
     SELECT [odtm] AS dO
       FROM [dbo].[t_Log_2]
      WHERE [id] = SCOPE_IDENTITY()
             )
UPDATE [dbo].[t_Log_2]
        SET [idtm] = ctx2.dO
       FROM ctx2
      WHERE [id] <> SCOPE_IDENTITY()
        AND [type] = 0
        AND [huid] = N'18ef4d56-6ef3-906a-a711-88d1bd6ab2d4'
        AND [idtm] < ctx2.dO
        AND [odtm] > ctx2.dO

COMMIT TRANSACTION;
SET XACT_ABORT OFF

Note that the query above was copied 1-to-1 from the C# code that dynamically composes it. In reality its parameters are not hard-coded as is shown above.
This query works in most times but once in a while I get the following error in the log:

Transaction (Process ID 80) was deadlocked on lock resources with
  another process and has been chosen as the deadlock victim. Rerun the
  transaction.

Any idea what shall I do to prevent this deadlock?
Comment: Capture and attach the deadlock Graph (the XML, not the picture of it!) see [Save Deadlock Graphs (SQL Server Profiler)](http://msdn.microsoft.com/en-us/library/ms190465.aspx)
Comment: Use UPDLOCK hints on your selects.
Comment: @Arvo: Can you please explain a little bit more?
Comment: I have encountered deadlock on situations, where (inside transaction) I initially select some values from table and then update same table. Using UPDLOCK hint in first select (select ... from ... with(updlock)) places IX type locks onto affected records already while selecting and other transactions will wait until this one is completed. For our troubles UPDLOCK hints solved the problem.
Comment: Also, free advice, save `SCOPE_IDENTITY()` into a variable for maintainability, rather than using it directly everywhere.
Comment: Note, that `SET XACT_ABORT ON;` might cause the tran to rollback on the first error but the batch to continue without transaction...
Comment: @usr has a good point. You really need `BEGIN TRY`/`END TRY` and rollback in the `CATCH` block.
Comment: @Ben transaction abortion is really awfully implemented in SQL Server. I wish there was an XACT_ABORT_BATCH option that would kill the batch in case of any unhandled error.
Comment: You were saying that the C# code dynamically generates your statements; can you use SqlTransaction.IsolationLevel to tweak your isolation levels?
Comment: @usr, that is what 'BEGIN TRY' is....
Comment: Sure it is possible to achieve this but you don't want to wrap basically *every* batch with this. Also does not work across batches which is nasty with long DDL scripts.
Answer: You either need to hold more locks or fewer.
The easiest answer is to go either NOLOCK (best performance) or TABLOCKX (consistency without having to think).
If you cannot use with (nolock) because of consistency requirements, you can add with (tablockx).
This will effectively mean that only one thread can execute like statements at a time - there will be no concurrency.
The alternative is to analyse your requirements in a lot more detail, which cannot be done without an understanding why you are updating the table, what the data is for etc.
For example, does this statement really need to be in the transaction?  It smells like housekeeping:
  DELETE FROM [dbo].[t_Log_2]
  WHERE [idtm]<'2011-03-12 08:41:57';

If you take that out of the transaction, and put it in a separate batch, you may find the problems go away.
Comment: with nolock rarely is the answer. Just use READ COMMITTED which will not hold locks, just take and release them. Will not contribute to deadlocking in a major way.


How do I send an alert to a blackberry from an Excel 2007 spreadsheet?

Question: I've been asked to find a way to send an alert to a blackberry when certain conditions are met on an Excel 2007 spreadsheet. The alert can be an SMS (preferred) or an email. The cell values are changing throughout the day from a DDE feed.
What are the typical solutions that people use to solve this?
Answer: I know next to nothing on the specifics of Excel or Office programming, but I can think of a few ways to solve the problem generically. I'm also assuming that the solution can be .Net based since Excel is available.

hook into the update process to test the conditions at the end of the update.
Office interop if you wanted a separate .net program instead that ran as a service or as a scheduled task.
Create an add-in for Excel. I have VS2008 Pro and I can create an Excel 2007 Add-in project.
Parse the Open Office XML for your conditions in a standalone program. This solution doesn't require .Net, just an XML parser,

When your conditions are met, you can use the following link to send your SMS or email.
What kind of technologies are available for sending text messages?
Answer: Another possibility would be to use AddEmail. Their blurb says: Email ActiveX (COM) Control - create and send HTML email messages with embedded images and attachments using SMTP/ESMTP protocol. Easily add email support to your Visual Basic 6 (VB6), ASP, ASP.NET, VB.NET, C++, C#, FoxPro, Access, PowerBuilder or Delphi application.
We use it a lot to automate our software registration system, and it'd be no problem to splice it into a bit of Excel VBA,
<code>....
Dim oSmtpMail As New SmtpMail
Dim lRes As Long
lRes = oSmtpMail.SimpleSendScriptable(sRecipient, sRecipient, sSubj, sText, sError)
....
</code>
Okay, so it's email rather than SMS, but it's a start.
Comment: A quick search on the net for "SMS ActiveX" gave the following:
http://www.mondor.org/smscom.aspx
http://www.wirelessdevstudio.com/
http://www.logiccodesoft.com/default.aspx


G-test statistic and KL divergence

Question: According to Wikipedia, the G-test statistic is "proportional to the Kullback–Leibler divergence of the empirical distribution from the theoretical distribution." To get the relationship between $ G $ and the KL divergence:
$$
\begin{align*}
G &= 2 \sum_i O_i \ln\left(\frac{O_i}{E_i}\right) \\
&= 2 \sum_i n P(i) \ln\left(\frac{n P(i)}{n Q(i)}\right) \\
&= 2n \sum_i P(i) \ln\left(\frac{P(i)}{Q(i)}\right) \\
&= 2n \times D_{KL}(P \| Q)
\end{align*}
$$
This is where I'm a little confused. $ D_{KL}(P \| Q) $ represents the divergence of $ Q $ (the expected distribution) from $ P $ (the observed distribution). This is the opposite of the statement in the Wikipedia page (assuming that "theoretical" refers to expected and "empirical" refers to observed).
Now from an information theoretic interpretation of KL divergence, $ P $ is represents the "true" distribution and $ Q $ is the "approximation". But from this derivation, the result seems counter-intuitive. Shouldn't the expected distribution correspond to the true distribution and the observed distribution correspond to the approximation?
Answer: People use inconsistent language with the KL divergence. Sometimes "the divergence of $Q$ from $P$" means $KL(P \| Q)$; sometimes it means $KL(Q \| P)$.
$KL(\text{true} \| \text{approximation})$ indeed has a nice information-theoretic interpretation as the inefficiency due to encoding the true distribution with a code built based on the approximation.
But that doesn't mean that $KL(\text{approximation} \| \text{true})$ doesn't ever come up; it does all the time. An information-theoretic interpretation is how efficiently you can represent the data itself, with respect to a code based on the expected distribution. In fact, this is closely related to the likelihood of the data under the expected distribution:
\begin{align*}
D_{KL}(P \| Q)
  &= \underbrace{\sum_i P(i) \ln P(i)}_{-\text{entropy[P]}} - \underbrace{\sum_i P(i) \ln Q(i) }_{\text{expected log-likelihood of data under $Q$}}
\end{align*}

G-test statistic and KL divergence


How to fix Protractor, log4js configuration error?

Question: I am trying to run a protractor tests. But facing issue with log4js. I did npm install log4js. Does the before launch configuration looks right? Is there anything I should change in the format for current version of log4js?
Below is the error:
Error: Problem with log4js configuration: ({
  appenders: {
    out: {
      type: 'log4js-protractor-appender',
      category: 'protractorLog4js'
    },
    app: {
      type: 'file',
      filename: './logs/ExecutionLog.log',
      category: 'protractorLog4js'
    }
  },
  categories: { default: { appenders: [ 'out', 'app' ], level: 'info' } }
}) - appender "out" is not valid (type "log4js-protractor-appender" could not be found)
    at C:\Project\PrjectName\node_modules\log4js\lib\configuration.js:31:13
    at Array.forEach (<anonymous>)
    at Object.throwExceptionIf (C:\Project\PrjectName\node_modules\log4js\lib\configuration.js:29:9)
    at createAppender (C:\Project\PrjectName\node_modules\log4js\lib\appenders\index.js:47:17)
    at C:\Project\PrjectName\node_modules\log4js\lib\appenders\index.js:77:25
    at Array.forEach (<anonymous>)
    at setup (C:\Project\PrjectName\node_modules\log4js\lib\appenders\index.js:75:33)
    at C:\Project\PrjectName\node_modules\log4js\lib\configuration.js:46:33
    at Array.forEach (<anonymous>)
    at Object.configure (C:\Project\PrjectName\node_modules\log4js\lib\configuration.js:46:13)
npm ERR! Test failed.  See above for more details.

This is my before launch configuration in config file
beforeLaunch:function(){
          log4js.configure({
            appenders: {
              out:{ type: 'log4js-protractor-appender'},
              app:{ type: "file",
                    filename: './logs/ExecutionLog.log'}
              },
            categories: {
                    default: { appenders: [ 'out', 'app' ], level: 'info' }
            }
            });
        },

Thanks
Answer: the type of appenders that log4js supports are:
export type Appender = CategoryFilterAppender
    | ConsoleAppender
    | FileAppender
    | SyncfileAppender
    | DateFileAppender
  | LogLevelFilterAppender
  | NoLogFilterAppender
    | MultiFileAppender
    | MultiprocessAppender
    | RecordingAppender
    | StandardErrorAppender
    | StandardOutputAppender
    | CustomAppender;

If you remove the "appender" from the name you will get the supported type ex: console, file, multifile... etc
Here is an exmple configuration.
const log4js_config: Configuration = {
        appenders: {
            consoleErrors: {
                type: 'logLevelFilter',
                appender: 'console',
                level: 'error'
            },
            console: {
                type: 'console'
            },
        },
        categories: {
            default: { appenders: [ 'console', 'consoleErrors' ], level: 'debug' }
        }
    };

const Log4js = require('log4js');
log4js.configure(LOG4JS_CONFIGURATION);

Like this you have two types of appenders in the default category.

console appender will log everything in the console no matter the level.
consoleErrors overrides other rules for console and filter only error level messages or higher to console.

You can read more about log4js configuration in:
https://github.com/log4js-node/log4js-node
Examples how the appenders work and how to configure them:
https://github.com/log4js-node/log4js-node/tree/master/examples


How to display translated fields labels of a node view

Question: I would like to display a node in NL. This node is not translatable but I would like to have the fields labels translated in NL.
This rendering occurs in a cron job and is used to render an email in the recipient language (ex: NL).
Unfortunately, the following code output the labels in the current language of the page (if I run it outside the cron) or in the default language of the site from within the cron job
<code>$entity = Drupal\node\Entity\Node::load($nid);
$view_builder = Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
$summary = $view_builder->view($entity, 'summary', 'nl');
$render=Drupal::service('renderer')
->renderPlain($summary);
dpm($render);
</code>
Solutions I have already tested:
1-I have tried the solution which set the config override language to the desired language here without luck
2-I have also tried the solution which set a custom language negotiator here without success
3-Finally I have tried the solution which use the 'language' session parameter here without any result
I have traced the code and I think that the language is selected/choose in the render part... But it was really difficult to understand this due to the complexity.
I was also thinking to add a <code>'#langcode'</code> to the build but I couldn't find an example.
Comment: Try to add `$entity = $entity->getTranslation('nl');` as second line. Even if not translatable this might provide the entity in the right context.
Comment: Thank you. As it is not translatable, this code generate an exception: `Invalid translation language (nl) specified.`
Comment: Ah, okay, alright. Damn
Answer: To display translated field labels you need to add solution 1 to the code you have already and also clear the cached field definitions, which unfortunately don't cache per config language.
The complete code should look like this:
<code>$language_manager = \Drupal::languageManager();

$nid = 1;
$langcode = 'nl';
$language = $language_manager->getLanguage($langcode);

$original_language = $language_manager->getConfigOverrideLanguage();
$language_manager->setConfigOverrideLanguage($language);
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
drupal_static_reset('options_allowed_values');

$entity = Node::load($nid);
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
$summary = $view_builder->view($entity, 'summary', $langcode);
$render = \Drupal::service('renderer')
  ->renderPlain($summary);

$language_manager->setConfigOverrideLanguage($original_language);
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
</code>
Comment: Instead of all this, a different approach would be to make a sub-request or a guzzle request. The endpoint could be a path with language prefix for a controller returning the summary as already rendered response, bypassing the themed page.
Comment: Many thanks!!! This is working but with a side affect: after running this code, if I display `/fr/node/xxx/edit` field labels are in dutch (this issue arise for other kind of elements/pages but not everywhere, `node/edit` is just an example and sometimes it is in french as expected). A cache clear solve this. Another issue: this is not working for computed fields added in `entity_bundle_field_info()`: labels are not translated. And I am wondering if this code is suitable to send, by cron, +/-15 notifications each 7min knowing the fact that the code runs for each notification.
Comment: 1) Run clearCachedFieldDefinitions() again, see the edit. - 2) For labels defined in code try solution 2 (custom language negotiator).  3) You could cache the rendered summary with your own cache key containing the custom email language, invalidated by the node cache tag as any other rendered node.
Comment: The endpoint looks nice... I never use this Technic. I will make some test and I assume it will solve the computed fields issue. again, many thanks for your help.
Comment: If you want to go this route, this discussion might be helpful to choose sub-request vs guzzle and to work around a core issue https://drupal.stackexchange.com/questions/303396/making-an-http-subrequest-causes-currentroutematch-to-have-the-wrong-route
Comment: Unfortunately, I have the same problem with the endpoint solution... see: https://drupal.stackexchange.com/q/314997/61398


find nodes by attribute and modify at once

Question: If I want to filter content by attributes (besides content type name), is there is some module around? if I am able to find these nodes, some way to update this attribute for all nodes at once?
Comment: What do you mean by attributes?
Answer: Some options:

You can use Views in combination with Views Bulk Operations and Rules.
You can also have a look at Editable Fields in combination with Views
Comment: yeahhh this video http://vimeo.com/26884701 shows exactly how to use VBO, Rules and views for my purposes
Comment: great, glad that this module can help you.


Quantified Propositions

Question: I've been trying to translate the following sentences into quantified propositions by making sure I state all propositional functions that I use and any assumptions that I make.
Can you see if I'm on the right track here?

All engineers are good with computers.
Let $E(x)$ be '$x$ is an engineer' and $C(x)$ be '$x$ is good with computers,'
where the domain of $x$ is all people in the world.
Then, $\forall x\ E(x) \rightarrow C(x)$.
Some mathematicians also like poetry.
Let $M(x)$ be '$x$ is a mathematician' and $P(x)$ be '$x$ also likes poetry,' where the  domain of $x$ is all people in the world.
Then, $\exists x\ M(x) \land P(x)$.
There are no writers who do not like reading books.
Let $W(x)$ be '$x$ is a writer' and $B(x)$ be '$x$ likes reading books,' where the  domain of $x$ is all people in the world.
Then, $\neg\ \exists x\ W(x) \land \neg B(x)$.
Not every athlete is famous.
Let $A(x)$ be '$x$ is an athlete' and $F(x)$ be '$x$ is famous,' where the  domain of $x$ is all people in the world.
Then, $\neg \forall x\ A(x) \rightarrow F(x)$.
Only scientists properly value civilisation.
Let $S(x)$ be '$x$ is a scientist' and $C(x)$ be '$x$ properly values civilisation,' where the  domain of $x$ is all people in the world.
Then, $\forall x\ C(x) \rightarrow S(x)$.
Answer: I don't agree with number 4!
It should be
$$ \exists x \; A(x) \wedge \neg F(x) $$
Of course I mean, before your edit was made!
Comment: Sorry! I forgot to put the negation symbol before the universal quantifier. I was wondering if my logical expression is closer to the original English sentence, though?

Quantified Propositions


Topology Book Recommendation

Question: I am looking to take a graduate course in topology in a couple semesters, and I was wondering if there exists a book which gives a general overview of topology in the same way that Saunders Maclane's "Algebra 3rd ed" gives you a general overview of Algebra.
By this I mean covers the important topics, and has exercises that are not extremely difficult, but are more designed to increase your understanding of the concepts discussed.
Thanks
Comment: Possible duplicate of [Best book for topology?](http://math.stackexchange.com/questions/7520/best-book-for-topology)
Comment: I would say I gave more specific criteria rather than "best book to study from"
Comment: Yes, but the answers in that thread gave book names and explanations for their choices and I believe you have there the information you needed. Anyway, this is just my opinion
Answer: Topology by J. Munkres is widely used out there. You can also have a look at this thread for more recommendations.

Topology Book Recommendation


wso2: cep: siddhi: how to make time windows persistent

Question: we are currently testing siddhi wso2 cep.
we need to be able to restart the wso2 server process without loosing data which has been accumulated in a window (for example time window).
Is there a way to make time windows persistent so that the server can be restarted without loosing its state ?
Do we have to configure the server to use persistence ?
Or do we just have to adapt the query and use event table ?
Here a sample of our query:
<code>from every data= DataInStream[state == 1] ->
   every event = EventInStream[event.no == data.no] within 24h
       insert into duplicatesOutStream data.id as id
</code>
Answer: You can make the CEP persist it's state by enabling snapshots. The documentation can be found here. But note that this will persist the "entire state" of the CEP "periodically" (configurable in minutes). Since this is done only periodically, you may lose the latest few events that arrived after the last snapshot operation. If you want cep to recover after a crash, this is the easiest option.
Apart from this, there's no other way to make a pre-defined window persistent. But if you want, you can write a your own custom time window (documentation) that will do the persistence and plug it to CEP.
You can also use event tables instead. When you use event tables, you can make sure that all arrived events are persisted. (but one disadvantage of this approach is this can be a performance hit compared to windows + snapshots approach).
Comment: I have been able to activate cassandra and thus persist the bucket state. The issue we are having now is that when the server is shut down using cntrl-c or when wrapped with yajsw the shutdown hooks are executed in parallel and cassandra is shut down before the state is persisted. Is there a way to call shutdownGracefully from some static method or through a shutdown port (similarly to tomcat) ?
Comment: There are two ways to gracefully shutdown a wso2carbon based server: 1. from the terminal - open another terminal, switch to /bin and run the command ./wso2server.sh -stop
   2. you can also shut down from the web ui (management console)
Comment: thanks. to cleanly close the wso2 server i have added the following to the yajsw wrapper.conf: `wrapper.app.shutdown.script=${wrapper_home}/scripts/wso2_shutdown.gv` the groovy script is invoked when wso2 receives a stop command from yajsw. the script invokes shutdownGracefully on the mbean server: `import javax.management.*
servers = MBeanServerFactory.findMBeanServer(null)
beanName = "org.wso2.carbon:type=ServerAdmin"
servers.each(){try{new GroovyMBean(it, beanName).shutdownGracefully()} catch (Exception ex){println ex}}`
Comment: i will add this script and the wso2 configuration to the samples of the next yajsw release.


Move cursor within VMware

Question: OK, so I have been racking my brain on this for a while and I need some help. I have a small C# application that I have built and I want to move the cursor. Below is the following code snippet that "should" move the cursor:
<code>Console.WriteLine("x::"+Cursor.Position.X+" y::"+Cursor.Position.Y);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Console.Read();
</code>
What is driving me nuts is that this works on my host Windows 7 machine but not on my Windows 7 my VMWare guest.
Has anyone else experienced this issue? I've scoured the internet but haven't been able to find anything.
Thanks for your time!
Comment: What do you see instead?  Have you tried re-printing out the position after moving it to confirm the update?  Are you sure that subtracting 50 won't make either the X or Y position go negative?
Comment: You might be better off checking the VMWare support forum or asking there.
Answer: Consider using InputSimulator:

The Windows Input Simulator provides a simple .NET (C#) interface to simulate Keyboard or Mouse input using the Win32 SendInput method. All of the Interop is done for you and there's a simple programming model for sending multiple keystrokes.

You'll need to reference it in your application and later copy it to the guest machine alongside your compiled executable .
Comment: thanks. That is a good library, however that won't solve my issue in this case as it had to do with VMWare tool and the need for elevated permissions.
Answer: It turns out to be an issue with VMWare tools. I uninstalled VMWare tools and it worked. I think it has something to do with the virtual mouse driver, however when I tried to re-install VMWare Tools without the mouse drivers it still did not work.
The only solution I found was to completely remove VMWare Tools.

Move cursor within VMware


Method for a hypothesis testing non normal distribution number of retweets

Question: I am a stats-beginner, Using pandas I am analysing a small dataset. There are 60 data-points, 22 of which are from Group A and 38 are from Group B. The dataset is made up of the number of retweets gained by a single tweet. The Null Hypothesis is that a tweet in Group A is not more likely (<=) than one in Group B to be retweeted.
Because most tweets are not retweeted the majority of data-points are zero. This leads to a distribution that looks like this (using seaborn):

As this is a far from normal distribution, it wouldn't be appropriate to use a t-test, nor do I have any expectations regarding how many retweets each tweet should get, so I cant use Chi-Squared.
Please would you give me some hints as to what would be an intelligent, beginner-friendly (and statistically robust way) to conduct a hypothesis test on this data?
Answer: You could use Mann-Withney U-test

In statistics, the Mann–Whitney U test (also called the
  Mann–Whitney–Wilcoxon (MWW), Wilcoxon rank-sum test (WRS), or
  Wilcoxon–Mann–Whitney test) is a nonparametric test of the null
  hypothesis that two samples come from the same population against an
  alternative hypothesis, especially that a particular population tends
  to have larger values than the other.
It can be applied on unknown distributions contrary to t-test which
  has to be applied only on normal distributions, and it is nearly as
  efficient as the t-test on normal distributions.

In python, this test is available in scipy.stats mannwithneyu. Similarly to a t-test, you get a value of the U statistic and a probability.
Hope it helps.
Comment: Thank you so much. I'll try it out and let you know how it goes!
Comment: Thanks, this worked really well, do you know of a MWU table that goes up to 38? I could only find tables where the maximum value was 20 observations in each set, therefore I cant find a definitive level at which I can say I would reject the null.

The result was `(414.0, 0.46937135092121229)` . 414 is obviously too high to allow us to reject the null but it would be more scientific to know the value at which I would reject the null (or have another way to calculate this level).
Comment: The U value of the test is not so similar to a `t-test`, there is no table or anything like that. Actually, in the wikipedia page you've got an explanation of how it is calculated. Sorry if I got you confused. The bigger the U value, the more chances to reject the null. But your value is not so big. Just to give a compare point, in a test in which I did reject the null, I got 1924409167.0 for U and 0.025000 for p. The criteria would be to put threshold for p, e.g. 0.5. If you got a p<0.5 it would mean there is less than a 5% chance to get two samples as the one you have, if the null was true.
Comment: Thank you I think I finally get it now! What I did was use the formula in the 'Normal approximation' section of the wikipedia article to calculate a z score from the U value and compare this to the rejection regions on a normal distribution. The z-scores fell outside the rejection region so I would not reject the null hypothesis. I feel like I've learnt a lot from this, so thank you for being the catalyst for this!
Comment: You are more than welcome! I actually think your question is quite good, I have an old hashtag downloaded and I'd like to check it this works as a measure of different patterns for 2 communities... I will let you know.


What is the Minimal cost?

Question: A power house, $P$, is on one bank of a straight river $W$ meters (m) wide, and a factory, $F$, is on the opposite bank $L$ meters downstream from $P$. The cable has to be taken across the river, under water at a cost of $\$CW/\mathrm{m}$. On land the cost is $\$CL/\mathrm{m}$. What is the minimum cost?
Any help will be appreciated...
Comment: One way can be also:
    `L*CL+W*\sqrt{(CW^2-CL^2)}`
Answer: There are two ways of routing the cable -

Completely through water (if CW is not too high than CL) and
Maximum by land and then only the width of the river by water (if CW is too high than CL).

The costs are respectively C1= {(L^2+W^2)^.5}*CW {using pythagorus theorem} and C2= (CW*W + CL*L)
Hence, minimum cost = Min(C1,C2).
Answer: Set this up as a non linear programming problem.
1.Variables:
$x_L=$the meters of cable to be used on land,
$x_W=$the meters of cable to be used under water
2.Objective Function:
You want to minimize the total cost that is $$z=\min_{x_L,x_W}CL\cdot x_L + CW \cdot x_W$$
3.Restrictions
$$L^2+W^2=x_{L}^2+x_{W}^2-2x_Lx_w\cos(\gamma)$$
where $\gamma$ is the angle between the sides $x_L$ and $x_W$. The explanation of this condition is the following. You have a triangle with edges $P$, $F$ and another edge, say $D$ at the point where your cable meets the coast where $F$ is. Now, consider the right angle triangle with sides $W$, $L$ and $\sqrt{L^2+W^2}$. (Do you see it?). Begin to move edge $D$ towards $F$. The new triangle(s) has(ve) not sides  $W$, $L$ and $\sqrt{L^2+W^2}$ anymore, but $x_W$, $x_L$ and $\sqrt{L^2+W^2}$ instead. The side that remains unaffected is the straight line between $P$ and $F$.
Note now that you have also an angle that is constant and can be determined. Consider the following description. As already mentioned, you have a staight line (the hypotenuse) from P to F. The length  of this diagonal is equal to $L^2+W^2$ due to Pythagoras law (draw a shape). Then you can move along the coast and reduce $x_L$ but increase $x_W$. Note though, that the angle between the coast line (where F is) and the diagonal remains unaffected. Call this angle $\alpha$. In the right angle triangle with sides $W$, $L$ and $\sqrt{L^2+W^2}$ we can easily calculate $\alpha$, since $\sin(\alpha)=\frac{W}{\sqrt{L^2+W^2}}$. Then the law of sines implies that $$\frac{\sqrt{L^2+W^2}}{\sin(\gamma)}=\frac{x_W}{\sin(\alpha)}$$ Solving for $\sin(\gamma)$ and by substituting we find that $$\sin(\gamma)=\frac{W}{x_W}.$$ Therefore $$\cos(\gamma)=\sqrt{1-\sin^2(\gamma)}=\sqrt{1-\frac{W^2}{x_W^2}}.$$
So you have the nonlinear restriction
(1) $L^2+W^2=x_{L}^2+x_{W}^2-2x_Lx_w\sqrt{1-\frac{W^2}{x_W^2}}$
and the restrictions:
(2) $x_L \ge 0$ (nonnegativity condition)
(3) $x_W \ge W$ (you have to cross the river)
To sum up:
$$z=\min_{x_L,x_W}CL\cdot x_L + CW \cdot x_W$$
under the restrictions
(1) $L^2+W^2=x_{L}^2+x_{W}^2-2x_Lx_w\sqrt{1-\frac{W^2}{x_W^2}}$
(2) $x_L \ge 0, \, x_W \ge W$
Now use Excel NLP solver to solve it, or KKT conditions if you have the time.

What is the Minimal cost?


mounting ntfs usb drive in linux (with permissioning)

Question: I'm trying to mount an external harddrive in linux.
I added the following line in /etc/fstab
<code>/dev/sdf1               /path/to/my/mount      ntfs    defaults,umask=022      0 0
</code>
and then do
<code>sudo mount -a
</code>
Everything mounts fine (shows up in df, etc.) but after creating folders / files in the drive,  I can't "chown" them. It's all stuck as root.
Where did I go wrong?
Comment: I don't think any of the NTFS implementations support Linux permissions on NTFS volumes.  Everything is exposed as belonging to a single user.
Answer: NTFS permissions and *nix permissions don't mix well. If you want full *nix permissions on the external drive, reformat it to ext2/3 or your favorite non-Windows filesystem.


How to make a module prerequisite in drupal

Question: How should i make a module that is prerequisite for an existing module.
For example:
Step 1 : There is comment module in core itself.
Step 2 : In my module i am doing some form alter which affects comment module. Consider my module name as  comment_test.
Step 3 : While enabling comment module my custom module that is comment_test should be as required module.
Step 4 : How can this be done?
Thanks in advance...
Answer: using below format in .info file of the module.
<code>dependencies[] = D1
dependencies[] = D2
</code>
I the above lines, D1 & D2 represent the names of the modules you module depend on.
Answer: Have you looked into how Drupal manages module files? You define a module's dependencies in the .info file. Here is the documentation on drupal.org.
Answer: When you are enabling a module in Drupal, the module dependencies are checked from the module .info file, and you will have to enable all dependencies to enable you module.
Lets say you have two modules : foo & bar, and that foo requires bar.
If you add: dependencies[] = "bar" in the foo's .info file, you will need to enable bar in order to enable foo.
In your case if you are working with the core comment module, you could edit the comment module .info file. But usually when you set a dependency, it means that the module needs the dependency to run properly. So unless you have modified the core comment module, it should not need another module to run properly. If you have modified the core module, you should know that for many reasons its is not advised to do so. The first reason is that you will not be able to update the core modules. The good way to do it is to create another module alter the comment module behavior.
The logic should be :
If i only need the comment module, i can enable it without having to enable other modules.
If i need the comment_test module, i can enable it, but it will require the comment module as it is a dependency.
This is why you cannot set your module as a prerequisite to a core module without creating another module that would extend Drupal with such behavior or by modifying the .info file in the core module.


Change from button to plain text

Question: I've got a button. And this button when clicked, will produce popup. The problem is I don't want it to be a button, instead, I just want it to be a plain text. All the function will be the same.
Is there any way to get around this?
Comment: show the code, or the way how you tried to resolved it.
Comment: This is part of "HTML 101".
Comment: See Size Chart

I'm not sure whether to change the PHP code for the plugin or the HTM/CSS of the plugin..

My knowledge about HTML, CSS and PHP is basic, so any help here would be appreciate.

You can see the box I mentioned here > https://saradesign.my/product/kurung-jasmine-mustard/
Answer: The "See size chart" element is not a button, it is actually plain text with a button-like style. You need to change it's CSS rules
If you want it to be simple black text on white background, change this:
<code>.yith-wcpsc-product-size-chart-button{
    background: #0f0f0f;
    border: none;
    border-radius: 0px;
    color: #ffffff;
    display: inline-block;
    padding: 3px 10px 3px 10px;
    text-decoration: none;
    margin: 5px 3px;
    cursor: pointer;
    box-shadow: 0px 2px 7px -2px #dddddd;
}
</code>
to
<code>.yith-wcpsc-product-size-chart-button {
    color: #000000;
    display: inline-block;
    cursor: pointer;
}
</code>
and remove this
<code>.yith-wcpsc-product-size-chart-button:hover {
    background: #3f3f3f;
}
</code>
Comment: Thanks @orfaust ! However, I can't change that even put the !important behind the css..FYI, with the plugin, I can change the padding, colour and etc. So it comes with selector..I believe this is related to PHP (I think)..

I tried to look this .yith-wcpsc-product-size-chart-button in the plugin file, but cant find it..sorry for my noobness here though..

But I really appreciated your effort!

Change from button to plain text


Pass an array of array as a parameter

Question: I have such an array:
12 |  18  |  22   |   26   |   28  |  32   | 34  | 36   |  50
16           23                       33           37

As you can see, it consists of two rows, but some have one element and some have two.
I'm trying to write a function that takes an array of arrays as a parameter.
I declared myself a type:
type array_of_array_of_Byte = array of array of Byte;

function my_function(value_list: array_of_array_of_Byte)

And I call the function like this:
my_function([[12,16], [18], [22,23], [26], [28], [32,33], [34], [36,37], [50]]);

But I get error:

Ordinal type required

What am I doing wrong? I'm using Delphi XE4.
Comment: Please specify Delphi version and the exact source code. This works for me in Delphi 11.
Comment: The issue isn't really how to pass this as a parameter. The question is really how best to represent this data structure.
Comment: I use Delphi XE4
Comment: The ability to initialize a dynamic array from a constant array expression was added in XE7
How can I do it in XE4 version?
Comment: @Pele see the answer I just posted
Answer: Unfortunately, the ability to initialize a dynamic array from a constant array expression wasn't supported yet in XE4, it was added in XE7:
Dynamic Arrays in Delphi XE7

There is a significant new feature in the Object Pascal language for XE7 and that is the improved support for initializing dynamic arrays and operating on them.
...
So what's new in XE7? The Object Pascal language allows you to do a few new operations:

Assign a constant array to a dynamic array
Concatenate two constant arrays with the + symbol
Use the following RTL functions on any dynamic array (not just strings): Insert, Delete, and Concat

So, in your case, you have no choice but to simply build up your dynamic arrays manually the old fashioned way - using SetLength() and per-element assignments, eg:
type
  array_of_array_of_Byte = array of array of Byte;

procedure my_function(value_list: array_of_array_of_Byte);

...

var
  arr: array_of_array_of_Byte;
begin
  SetLength(arr, 9);

  SetLength(arr[0], 2);
  arr[0][0] := 12;
  arr[0][1] := 16;

  SetLength(arr[1], 1);
  arr[1][0] := 18;

  // and so on ...

  my_function(arr);
end

Pass an array of array as a parameter


AutoMapper does not unproxy NHibernate entity

Question: Consider this entity:
public class CondRule
{
    public virtual decimal Id { get; set; }
    public virtual string Name { get; set; }
    public virtual CondRuleType RuleType { get; set; }
    public virtual string Statement { get; set; }
}

and CondRuleType is:
public class CondRuleType
{
   public virtual int Id { get; set; }
   public virtual string Name { get; set; }
}

It is obvious that there is a one to one relation between CondRule and CondRuleType entities.
Also I have CondRuleDto:
public class CondRuleDto
{
    public decimal Id { get; set; }
    public string Name { get; set; }
    public CondRuleType RuleType { get; set; }
}

I have mapped CondRule to CondRuleDto using AutoMapper:
Mapper.CreateMap<CondRule, CondRuleDto>();

When I call Session.Get to get CondRule by id and the map the result to CondRuleDto, AutoMapper does not resolve proxies (here RuleType).
Here is my code:
var condRule = Session.Get<CondRule>(id);
var condRuleDto = Mapper.Map<CondRuleDto>(condRule);

When I watch condRuleDto, RuleType property is a NHibernate proxy. I want AutoMapper to map RuleType proxy to a POCO. How to make this work?
PS: I have to mention that when I use query and use automapper's Project, it will result a list with no proxies (I know that Project make this happen. May be I need something like Project to use after Session.Get):
Session.Query<CondRule>().Project().To<CondRuleDto>().ToList()

Answer: Casts won't change the underlying object (i.e. your CondRuleType will be still a proxy even if you map its instance to another property of type CondRuleType).
It seems like you need to create a custom mapping where CondRule.RuleType is mapped creating a new instance of CondRuleType.
Comment: How to do that custom mapping?
Comment: @alisabzevari try this: http://stackoverflow.com/questions/9132251/how-to-handle-custom-properties-in-automapper (I'm at work and I can't try things... but it might be in the right track)
Comment: Thanks, but I want to tel automapper to unproxy every proxied object automatically. With you solution I have to define custom mapping for every reference property of every entity.
Comment: @alisabzevari With some effort I'm sure you can generalize the solution... At the end of the day, you can't expect AutoMapper to solve your scenario "as is"... I believe that it might be fixed using some reflection to introspect property types and create an instance using `Activator.CreateInstance`...
Comment: I know that I have to use reflection. The problem is I don't know where I have to write this code or how to tell automapper when it sees these classes do my operation to performa mapping
Comment: BTW your answer is correct. I have to ask another question.
Comment: @alisabzevari Maybe. BTW, have you thought about wrapping that reflection into a re-usable delegate that can be given to many automapper class maps?
Comment: I wanted to write one CreateMap for any proxy class
Comment: @alisabzevari so this is what I try to say :D you can have some helper class like `CustomMappings.UnproxyAssociations(T Source someObject)`... there's more hard work than this, but I want to give you the idea........


How to get complete bucket access of aws s3 as public?

Question: When we set a file in s3 bucket as public, we can directly download it from its URL.
But, if I set a bucket or a sub folder in bucket to public, I am getting below error.
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>FD92231A86E4F761</RequestId>
<HostId>KcoKQ1mibo+NO9o46u9qDTp6ezTmUHuzR4bdWo6gZTJct5aBUxejjJ9Aqy72bCafEBBffcVeONI=</HostId>
</Error>

Any suggestions on how to access a complete bucket using public url?
Answer: So you can download files made public but not browse S3 folders? S3 doesn't have folders, it has objects with keys that can be viewed as / thought of as folders. In short, you can't browse to what looks like an S3 folder because it doesn't actually exist.
What exactly are you trying to achieve? Make S3 work like a web interface to a standard file share? Knowing what you're trying to achieve we might be able to make suggestions.
Comment: I have some cloudwatch logs and other resources which I want to share to users.These files are generally 1000s in number in a folder.So I want to share the folder to users so that they can access whichever they want.
Comment: My approach would probably be to give them IAM users and permissions to use commands such as "aws s3 ls"
Comment: In the S3  Web UI objects are presented as if they're in folders like you'd see in a filesystem but actually the whole "/this/looks/like/a/directory/structure" path is actually part of the object's name (called prefix). The prefix can be used as a condition for defining policies to access one particular set of objects but not the others.


Prevent replacing  with

Question: I am using Bootstrap 3 subtheme (7.x-3.1-beta2 ) on Drupal 7 for the administrative backend. It seems that the Bootstrap base theme replaces <input type="submit"> with a <button> element. That breaks the layout of the views backend.
I tried to change this by:

copying button.func.php into the subtheme
renaming the function according to the subtheme name
modifying the output to return <input> instead of <button>

Code in button.func.php
<?php
function bootstrap_subtheme_adl_admin_button($variables) {
  $element = $variables['element'];
  $value = $element['#value'];
   if (!empty($element['#icon'])) {
     if ($element['#icon_position'] === 'before') {
       $value = $element['#icon'] . ' ' . $value;
     }
   elseif ($element['#icon_position'] === 'after') {
     $value .= ' ' . $element['#icon'];
    }
  }

return '<input' . drupal_attributes($element['#attributes']) . '>\n';
}

However, this does not have any visible effect.
Any advise?
Comment: Did you clear cache?
Comment: @sam2de of course.
Comment: Is your function even called at all?
Comment: @Mołot maybe I am misunderstanding this, but the function is called by the base theme, I am just attempting to overwrite it in the sub theme. In fact, it works fine when I edit the function in the base theme.
Comment: Ok, but in the subtheme is it executed, but wrong results, or not called at all?
Comment: Not called at all. Actually I am trying to trace where it is even called in the base theme. @Mołot
Answer: If I'm reading the question directly, you've copied button.func.php into your sub-theme, modified the code inside it, and then tried to see if your changes work?
If that's what you did, the problem is that Drupal never sees the code. Fortunately (if that is the problem) the solution is simple: copy the code from that file into your sub-theme's template.php file and make whatever changes are required. Be sure the function is correctly named (i.e. to override theme_button, you'd need themename + button = themename_button()). In your example above, your sub-theme would have to be named 'bootstrap_subtheme_adl_admin' in order for your function to be called even if the code is in the correct file.

Incidentally, the reason the button.func.php file works in the base Bootstrap theme appears to be the theme's registry.inc file.

Basic sub-theme how-to with Bootstrap

Download Bootstrap sub theme into /sites/all/themes; don't bother to enable the theme
Copy bootstrap_subtheme from the /sites/all/themes/bootstrap/bootstrap_subtheme to /sites/all/themes/bootstrap_subtheme
Move /sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info.starterkit to /sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info
Enable bootstrap_subtheme

Overriding a theme function implemented by a parent theme

Set up parent and subtheme as described above
Never edit the parent theme in any way
Copy the theme function you want to modify from e.g. /sites/all/themes/bootstrap/theme/system/button.func.php into the file at /sites/all/themes/bootstrap_subtheme/template.php
Change the name of the function in /sites/all/themes/bootstrap_subtheme/template.php from bootstrap_button to bootstrap_subtheme_button
Comment: Thank you @bhotel for your answer and explanation. I thought so too, however, if I try to declare `function bootstrap_subtheme_adl_admin_button($variables) {}` in template.php I end up with a white screen of death. I am a bit confused. I really would like to do adjustments like those in the subtheme rather the base theme, but seem not to find out what the correct way of doing this is.
Comment: Well, the white screen of death means there's a PHP fatal error. Find out from the error log what that error is, and you'll likely have the solution to the problem. Also, please confirm: the machine name of your subtheme is `bootstrap_subtheme_adl_admin`?
Comment: oh well, the php error log shows that the issue is that `bootstrap_subtheme_adl_admin_button()` declared in template.php has been also declared in `button.func.php` in my subtheme (yes: `bootstrap_subtheme_adl_admin` is the machine name) - which, yes is correct: I declared the function there, but that didn't work. Now if this is cause of the error, doesn't this indicated that Drupal very well is aware of the code in `button.func.php` ?
Edit: If I remove the function from `button.func.php` in my sub-theme all is good again. Right. This still bugs me though.
Comment: That error **means the function has been defined with the same name in more than one place**. You've either a) renamed the function in the bootstrap parent theme so that it's the same as in your sub theme, or b) you have **not** renamed the function in your sub theme.
Comment: The issue was that the function was defined with the same name in `template.php` and `button.func.php` - both `bootstrap_subtheme_adl_admin_button`- in the sub-theme. Still haven't found a solution though. The function doesn't change the output when in `template.php` nor in `button.func.php`. The only way it seems to get the correct results is if I overwrite the function in the base theme. I can't wrap my head around it :/
Comment: You're doing something quite wrong then. I just tested my answer to this question with the latest Drupal 7 / Bootstrap versions. I'll add a short bit to the end of my answer explaining the steps.
Comment: You are correct @bhotel - did a clean installation and it works now. Sigh. No idea what went wrong. Thank you for your answer!

Prevent replacing  with


Key with multiple values

Question: I am doing a college project where I have multiple values with a key. Here is my code
import  java.util.Hashtable;

private Hashtable name2email;
name2email = new Hashtable();

@Override
public void record_user(String name, String email, String address, String phonenumber, double accountnumber, double credit) throws user_exists {
    if (name2email.containsKey(name)||
        name2email.contains(email)||
        name2email.contains(address)||
        name2email.contains(phonenumber)||
        name2email.contains(credit)||
        name2email.contains(accountnumber))
    {
        throw new user_exists();
    }
    name2email.put(name, email,address,accountnumber,phonenumber,credit);
}

I am using a HashTable because of the specs of my assignment. Any suggestions? Yes this is the error I am getting back
 no suitable method found for put(String,String,String,double,String,double)
    method Hashtable.put(Object,Object) is not applicable
      (actual and formal argument lists differ in length)

What should I do ?
Comment: Hashtable is obsolete - you can use a HashMap instead.
Answer: Create a class which contains all these values, instantiate this object and map user name to these "user details" object.
Answer: Create a User class (i.e. a domain object), with:

A field (i.e. member variable) for each data item about a user (name, phone etc.)
An overridden hashCode() method that computes a hash value based on the data items that represent user identity (can two users have the same name? Same phone number?)
An overridden equals() method that implements the same identity-ness as hashCode().

In general, if you're using your own classes as Map keys then you want to consider whether the default (i.e. java.lang.Object) hashcode()/equals() methods do what you want (i.e. define identity) correctly.
Implementing hashCode() and equals() correctly is not trivial - read the java.lang.Object API docs carefully for those methods. A decent IDE will implement hashCode() and equals() for you if you tell it which fields to compute those over, which is usually much safer than rolling your own.
Then use a HashMap to map Users to email addresses. (Why's the email address not a member of User? What if a user has multiple email addresses?)
(Prefer HashMap to Hashtable. If you need a thread-safe Map then use ConcurrentHashMap or Collections.synchronizedMap().)
Answer: Hash table works with key value pair.
clearly
 name2email.put(name, email,address,accountnumber,phonenumber,credit);

violates the Hashtable put syntax. Instead you need to be doing something like this
name2email.put(name,new User(name,email,address,accountnumber,phonenumber,credit);

And your name2email definition should look something like this :
Hashtable<String,User> name2email= new Hashtable<String,User>();

to check if the record exist you need to do :
 User u = name2email.get(name);
 if(u.getName().equals(name) || u.getEmail().equals(email)...(rest of your logic).
  { ...your user exists
  }
  else put(name,new User(name,email,address,accountnumber,phonenumber,credit);

Key with multiple values


Regex: find a variable number sequence

Question: I am looking for a specific sequence of numbers in a line. I can best explain with an example:
00001 # first search criteria - line 1
00010 # second search criteria - line 2

So every line has 5 digits of either 0 or 1. I am looking for the combination of all 0 except for 1 digit that can be a 1. This 1 can be in any position of the 5 digits.
The regex code I have for 5 digits of 0 is
^((0\s*?){5}) # there may be spaces between the numbers

The line 1 case above would be selected with following regex code:
^((0\s*?){4})\s*(1)

My question is how I could write in regex code the changing position of 1 to cover the 5 cases/positions.
Thank you.
Answer: You can use a lookahead based regex for this:
^(?=[0\s]*1[0\s]*$)(?:\s*[01]\s*){5}$

RegEx Demo
Lookahead (?=[0\s]*1[0\s]*$) will enforce only single 1 at any position in input where as (?:\s*[01]\s*){5} will make sure that input has only 0 and 1 with 5 digits length also allowing white-spaces anywhere.
Comment: If there are no spaces between the numbers, this works. How can I adjust to allow for spaces (even tabs), as I mentioned?
Answer: You can use two conditionals.
First one insures 1 is not found again.
Second one insures 1 is found.
(?:((?(1)(?!))1)|0){5}(?(1)|(?!))
Expanded
 (?:
      (                             # (1 start)
           (?(1) (?!) ) 1
      )                             # (1 end)
   |  0
 ){5}
 (?(1) | (?!) )

Regex: find a variable number sequence


private/public ssh keys