Search if a given sub-string is present in a string

Question: I am using this code to find if a substring is present in a string or not. But the result is Present even if the substring is not present in the string. Basically, I am getting Present as the only result.
#include <stdio.h>
#include <string.h>

int main()
{
    int i, la, lb, j, f = 0, found = 0;
    char a[100], b[100];

    printf("Enter a string: ");
    fgets(a, 100, stdin);

    printf("Enter substring: ");
    fgets(b, 100, stdin);

    la = strlen(a);
    lb = strlen(b);

    for (i = 0;i < la - 2; i++) {
        if (a[i] == b[0]) {
            for (j = 0; j < lb - 2; j++) {
                f = 0;
                if (a[i + j] != b[j]) {
                    f = 1;
                    break;
                }
            }
        }
        if (f == 0) {
            found = 1;
            break;
        }
    }

    if (found == 1) {
        printf("Present.");
    } else {
        printf("Not Present.");
    }

    return 0;
}

Comment: I assume `strstr()` is off limits?
Comment: what did you see when you stepped through with your debugger
Comment: Yes it's off limits.
Answer: You should first strip the trailing newlines from the strings entered by the user:
    a[strcspn(a, "\n")] = '\0';
    b[strcspn(b, "\n")] = '\0';

Then you can remove the - 2 adjustments in your for loop tests, which are incorrect as you should only adjust by 1 anyway.
There is a problem with the f variable: you should set it to 0 before the nested loop and test it just after the nested for loop but inside the if body.
Another problem is you should iterate the outer loop only as long as i <= la - lb.
Here is a modified version:
#include <stdio.h>
#include <string.h>

int main() {
    char a[100], b[100];

    printf("Enter a string: ");
    if (!fgets(a, sizeof a, stdin))
        return 1;

    printf("Enter substring: ");
    if (!fgets(b, sizeof b, stdin))
        return 1;

    // compute the lengths without the trailing newlines.
    size_t la = strcspn(a, "\n");
    size_t lb = strcspn(b, "\n");
    int found = 0;

    if (lb == 0) {
        found = 1;
    } else {
        for (size_t i = 0; i + lb <= la; i++) {
            if (a[i] == b[0]) {
                int f = 0;
                for (size_t j = 1; j < lb; j++) {
                    if (a[i + j] != b[j]) {
                        f = 1;
                        break;
                    }
                }
                if (f == 0) {
                    found = 1;
                    break;
                }
            }
        }
    }
    if (found == 1) {
        printf("Present.\n");
    } else {
        printf("Not Present.\n");
    }
    return 0;
}

If the standard string function strcspn() is off limits, you can compute la and lb this way:
    size_t la = 0, lb = 0;
    while (a[la] != '\n' && a[la] != '\0')
        la++;
    while (b[lb] != '\n' && b[lb] != '\0')
        lb++;

Comment: This works perfectly fine. But, is there a way to do it without stripping the trailing newlines.
Comment: @IhaAgrawal: yes, by reducing the lengths appropriately.  Answer updated.
Answer: This is what I saw when I stepped through with mu debugger. Walk through the code with string 1 = "mouse" and second string = "cat"
   for(i=0;i<la-2;i++)
   {
      if(a[i]==b[0]) {    // m == c?, no
         for(j=0;j<lb-2;j++) {
            f=0;
            if(a[i+j]!=b[j]) {
                f=1;
                break;
            }

          }

       }
      if(f==0) { // drop to here, f does == 0, so we are done, found == true
            found=1;
            break;
    }

Comment: It's working fine if both the strings are different. But, it still gives Not Present even if the strings are same.
Comment: @IhaAgrawal your question says that it always says 'present', which is what it does for me


Conexão ao banco de dados - MySQL e Java

Question: Já tenho um servidor local em minha máquina (localhost) com o MySQL funcionando normalmente. A partir daí, gostaria de conectar meu banco de dados com o Java, mas... como eu faço isso? Existe algum componente do Swing que exiba os campos de uma determinada tabela do MySQL?
Estou criando um programa para o desktop de meu parceiro. Ou seja, é outro PC! O banco de dados, mesmo assim, conecta-se? É preciso internet?
Comment: Existe sim, o mais utilizado é o jTable, onde os dados são carregados em uma tabela
Comment: Se o seu amigo quiser conectar no banco de dados que fica na sua maquina acho que a melhor forma é voce criar um ip fixo e configurar a conexão com esse ip
Comment: Valeu! Mas... você poderia me dar um código de exemplo?
Comment: estou fazendo uma explicação, só um momento
Comment: No site do Netbeans tem um breve tutorial ensinando a fazer isso. Tente estuda-lo e faze-lo, caso tenha alguma outra dúvida referente a algum ponto mais específico do tutorial, poste para que possamos ajuda-lo: https://netbeans.org/kb/docs/ide/mysql_pt_BR.html
Answer: Vou tentar dar uma resumida de como começar uma aplicação com banco de dados usando JDBC:
O primeiro passo é criar a classe conexão, podemos cria-la da seguinte forma:
public class Conexao {

    private static final String USUARIO = "root";
    private static final String SENHA = "";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/meubanco";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    // Conectar ao banco
    public static Connection abrir() throws Exception {
        // Registrar o driver
        Class.forName(DRIVER);
        // Capturar a conexão
        Connection conn = DriverManager.getConnection(URL, USUARIO, SENHA);
        // Retorna a conexao aberta
        return conn;

    }

}

O método anterior retorna a conexão aberta, lembrando que é preciso adicionar o Connector/J que é o driver responsável por conectar o java ao Mysql, voce pode baixar o driver nesse LINK. Após baixa-lo vá no seu projeto, clique na pasta Bibliotecas/Adicionar JAR... Procure o seu driver e clique em adicionar, isso no Netbeans. Se estiver utilizando o Eclipse Clique no seu projeto e vá em Build Path/Configure Build Path e em seguida procure pela guia Libraries, clique na opção Add External Jars e selecione o Driver.

2ª Parte:
Vou tentar simplificar ao maximo essa explicação para que não fique muito extensa, caberá a voce estudar mais sobre o assunto depois.
Vamos começar com a Classe Cliente
public class Cliente {

    private Integer codigoCliente;
    private String nomeCliente;
    private Integer idadeCliente;

    public Integer getCodigoCliente() {
        return codigoCliente;
    }

    public void setCodigoCliente(Integer codigoCliente) {
        this.codigoCliente = codigoCliente;
    }

    public String getNomeCliente() {
        return nomeCliente;
    }

    public void setNomeCliente(String nomeCliente) {
        this.nomeCliente = nomeCliente;
    }

    public Integer getIdadeCliente() {
        return idadeCliente;
    }

    public void setIdadeCliente(Integer idadeCliente) {
        this.idadeCliente = idadeCliente;
    }

}

Agora é necessário uma classe que interaja com o Banco de Dados, geralmente essa classe tem atribuído o nome DAO que faz parte do padrão DAO (Data Access Object)
Presumindo que voce já tem informações salvas no banco e quer apenas retorna-las em uma tabela vou apenas fazer o método que faz a pesquisa desses dados:
public class ClienteDAO {

    public List<Cliente> buscar(Cliente c) throws Exception {
        /* Define a SQL */
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT cod_cliente, nome_cliente, idade_cliente ");
        sql.append("FROM tabela_cliente ");
        sql.append("WHERE nome_cliente LIKE ? ");
        sql.append("ORDER BY nome_cliente ");

        /* Abre a conexão que criamos o retorno é armazenado na variavel conn */
        Connection conn = Conexao.abrir();

        /* Mapeamento objeto relacional */
        PreparedStatement comando = conn.prepareStatement(sql.toString());
        comando.setString(1, "%" + c.getNomeCliente()+ "%");

        /* Executa a SQL e captura o resultado da consulta */
        ResultSet resultado = comando.executeQuery();

        /* Cria uma lista para armazenar o resultado da consulta */
        List<Cliente> lista = new ArrayList<Cliente>();

        /* Percorre o resultado armazenando os valores em uma lista */
        while (resultado.next()) {
            /* Cria um objeto para armazenar uma linha da consulta */
            Cliente linha = new Cliente();
            linha.setCodigoCliente(resultado.getInt("cod_cliente"));
            linha.setNomeCliente(resultado.getString("nome_cliente"));
            linha.setIdadeCliente(resultado.getInt("idade_cliente"));
            /* Armazena a linha lida em uma lista */
            lista.add(linha);
        }

        /* Fecha a conexão */
        resultado.close();
        comando.close();
        conn.close();

        /* Retorna a lista contendo o resultado da consulta */
        return lista;
    }

    }

3ª Parte:
Pronto temos o DAO(ClienteDAO) e o MODEL(Cliente) agora na sua view(Tela) vo adiciona um Painel de Rolagem e dentro desse painel voce coloca uma Tabela ficando de tal forma:

Em seguida voce clica com o botão direito na sua tabela, vá em propriedades, procure por Model clique nos ... e Definir Propriedades... selecione Código Personalizado e digite o seguinte código: new ClienteTableModel() e ignore o erro, pois iremos resolver no próximo passo. Exemplo:

4º Passo (Ultimo)
Precisamos de mais uma Classe, essa classe é a mesma que instanciámos em nossa JTable logo acima.
public class ClienteTableModel extends AbstractTableModel {
    /* Lista para armazenar os cabeçalhos da tabela */

    private Vector colunas;

    /* Lista para armazenar os dados da tabela */
    private Vector linhas;

    public ClienteTableModel() {
        /* Definição das colunas da tabela */
        colunas = new Vector();
        colunas.add("Código");
        colunas.add("Nome");
        colunas.add("Idade");

        /* Definição dos dados da tabela */
        linhas = new Vector();
    }

    public int getRowCount() {
        /* Captura o total de linhas da tabela */
        int totalLinhas = linhas.size();

        /* Retorna o total de linhas */
        return totalLinhas;
    }

    public int getColumnCount() {
        /* Captura o total de colunas da tabela */
        int totalColunas = colunas.size();

        /* Retorna o total de colunas */
        return totalColunas;
    }

    public String getColumnName(int coluna) {
        /* Captura o nome da coluna */
        String nomeColuna = (String) colunas.get(coluna);

        /* Retorna o nome da coluna */
        return nomeColuna;
    }

    public Object getValueAt(int linha, int coluna) {
        /* Captura o registro informado */
        Vector registro = (Vector) linhas.get(linha);

        /* Dentro do registro captura a coluna selecionada */
        Object dado = registro.get(coluna);

        /* Retorna o valor capturado */
        return dado;
    }

    public void adicionar(List<Cliente> lista) {
        /* Reinicializa os dados da tabela */
        linhas = new Vector();

        /* Percorre a lista copiando os dados para a tabela */
        for (Cliente d : lista) {
            Funcionario f = new Funcionario();
            /* Cria uma linha da tabela */
            Vector<Object> linha = new Vector();
            linha.add(d.getCodigoCliente());
            linha.add(d.getNomeCliente());
            linha.add(d.getIdadeCliente());
            /* Adiciona a linha a tabela */
            linhas.add(linha);
        }
        /* Atualiza a tabela */
        fireTableDataChanged();
    }

}

Esse código é responsável por preencher a tabela, mas ainda falta um detalhe. Como atualizar a tabela, ou seja, como carregar os dados. Eu faço da seguinte forma:
no começo do código da sua tela, após o construtor adicione um metodo chamado atualizar da seguinte forma:
  public NewJFrame() {
        initComponents();
    }

Após o construtor adicionar:
public void atualizar(){
         try{
             /* Criação do modelo */
            Cliente d = new Cliente();

            /* Criação do DAO */
            ClienteDAO dao = new ClienteDAO();
            List<Cliente> lista = dao.buscar(d);

            /* Captura o modelo da tabela */
            ClienteTableModel modelo = (ClienteTableModel)jTable1.getModel();

            /* Copia os dados da consulta para a tabela */
            modelo.adicionar(lista);

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "Erro ao tentar buscar um Cliente");
        }
    }

E em seguida, clique na sua tela(jFrame) e adicione um evento Window/WindowOpened e dentro desse evento faça o seguinte:
  private void formWindowOpened(java.awt.event.WindowEvent evt) {

        atualizar();

        //Opcional
        setLocationRelativeTo(null);
        setResizable(false);

    }

E pronto, sua aplicação está pronta para carregar os dados do banco em uma tabela. Me desculpe se a explicação não foi muito boa, ou se ficou muito extensa, acho que não tenho muito o "dom" de explicar. Boa sorte com os códigos e estude bastante.
Comment: Estou tendo problemas com esta linha do código: public List buscar(Funcionario f) throws Exception: a IDE diz: type List does not  take paramenters
Comment: @alexjosesilva veja se você fez o import da Lista corretamente. `Java.util.list`
Comment: Fiz tudo como esta aqui escrito...porém o erro continua


Envolvendos divs com uma class dentro de um laço de repetição

Question: Tenho o seguinte código php
for ($i = 0; $i <6; $i++){
    echo '
';
    echo $i;
    echo '
';
    }
?>

Gostaria que as class até a posição 3 fossem envolvidas por uma div, e as duas classes restantes, fosse envolvidas por outra classe, para que o resultado final seja esse abaixo:

0

1

2

3

4

5

Fiz várias tentativas, mas não consegui, a forma que eu estava fazendo tava imprimindo um elemento dentro do outro.
Answer: Dá pra criar uma função e chamar duas vezes:
<?php

function colunaDiv($className, $primeiro, $ultimo) {
    echo '
';

    for($i = $primeiro; $i <= $ultimo; $i++) {
        echo '
';
        echo $i;
        echo '
';
    }

    echo '
';
}

colunaDiv("coluna-1", 0, 4);
colunaDiv("coluna-2", 5, 6);

?>

Comment: Muito obrigado Daniel, deu super certo, só precisei passar mais dois parâmetros que tinha no código e ficou show


Panel Content not displaying correctly after migrating site to new server

Question: This is how it looks like after I migrated the site. I compared the new panelizer and panels folders with a backup folder that I had  to see if there were discrepancies, but the folders had the same files. I also resaved the admin page as suggested in another post, but that didn't do it for me.
I am using D7 by the way.
Comment: Got any missing files among the HTTP requests? Check for 404s in firebug.
Comment: Hi, sorry for the dumb question, but what exactly do you mean by the HTTP requests? Is it an error or folder somewhere
Comment: When you're browser builds the admin page, it makes multiple requests over HTTP to the server to fetch resources, such as css files. If you look over that list, using whatever debugging tools your browser provides, you might be able to find out which file Panels is expecting to be there, but your browser fails to find.
Comment: Thank you so much! It is a problem with the HTTP  requests. When I tried the site in Firefox the panels were back to normal . I would have never thought about the HTTP requests myself. Thanks!
Answer: When you're browser builds the admin page, it makes multiple requests over HTTP to the server to fetch resources, such as css files. If you look over that list, using whatever debugging tools your browser provides, you might be able to find out which file Panels is expecting to be there, but your browser fails to find.


How to validate a dropdown menu in JavaScript?

Question: I am new to Web Design and I did not find a suitable answer for my question in the community. I need to validate a dropdown menu with JavaScript and the button btn1 but my code doesn't work, I'll just include a snippet for simplicity sake. Please help
<form>
Option
        <select id="dropdown1">
            <option value="">--Select an option--</option>
            <option value="option1">1</option>
            <option value="option2">2</option>
        </select>
</form>
 <button type="button" id="btn1" required>Calcular</button>

Here is my js
btn1.addEventListener('click', validate(dropdown1.value))
let dropdown1 = document.getElementById('dropdown1');
function validate(object) {

    if (object.value == "") {

        alert("Select an option")
        return false;
    }

    return true;
}

btn1.addEventListener('click', validate(object))

Comment: Learn about the difference between function invocations and function references. Your event callback expects a callback, i.e. a function reference - but you're invoking the function in situ. The result is the function is called when you bind the event, not when it fires.
Comment: Use change event in place of click.
Answer: When you are setting up an event listener you can either pass it the function name or write an inline function. The problem you were running into was trying to pass it a name and an argument at once. Also you can determine the dropdown element's value in the callback without worrying about passing it in.

const btn1 = document.getElementById('btn1');
const dropdown1 = document.getElementById('dropdown1');
btn1.addEventListener('click', validate);

function validate() {
  const dropdownValue = dropdown1.value;
  if (dropdownValue == "") {

  alert("Select an option")
    return false;
  }
  return true;
}
<form>
Option
        <select id="dropdown1">
            <option value="">--Select an option--</option>
            <option value="option1">1</option>
            <option value="option2">2</option>
        </select>
</form>
 <button type="button" id="btn1" required>Calcular</button>
Comment: thank you so much, I understand now. You helped me a lot.
Comment: No problem, glad to help!


How to make table-responsive in drupal views

Question: I have created the views which renders table. I want to make table responsive without any contrib module. Is it possible?
Comment: http://drupal.stackexchange.com/questions/90309/views-tables-on-responsive-layout
Comment: I set width:100% and width: 100% !important but not working
Answer: Consider the Views Responsive Grid module. Here is a quote about it (from its project page):

... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
Features:

Horizontal or vertical grid layouts
Custom classes for use with responsive themes

Of course, this requires the use of a contributed module (which is something you want to avoid as per the edited version of your question).
Assuming that it's OK to use a contributed "theme", you may should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "is designed from the ground up as a mobile-first responsive theme". However that has like 5 module dependencies ...
For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.
Comment: Sorry i have wrongly typed the question. I want to make table responsive without using contrib module


How do I check if core data class is nil. in SWIFT

Question: I have created an Entity called Status with an attribute called statusUpdate. I want the user to be able to create a status for the first time which would then be saved in core data, then when the status is next updated to save over the old status in core data. Here is what i've done:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as NSManagedObject

var request = NSFetchRequest(entityName: "Status")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: &self.error)

if results?.count > 0 {
    for result: AnyObject in results! {
        if var oldStatus = result.valueForKey("statusUpdate") as? String {
            println("Current User fetched status from Core Data")
            var newStatus = self.updateStatusText.text
            result.setValue(newStatus, forKey: "statusUpdate")
        } else if result.valueForKey("statusUpdate") == nil {
            var newStatus = self.updateStatusText.text
            newUser.setValue(newStatus, forKey: "statusUpdate")
            println("Status uploaded for the first time")
        }
    }
}

context.save(&self.error)

The problem is the else if seems to always run. I want it to basically only run of the Status entity is nil (so it will only run for the first time somebody updates a status) and then when the status is updated after that it will run just the regular if statement.
I'm not sure what i'm doing wrong???
Thanks in advance.
Comment: Why don't you explicitly check if  (var oldStatus = result.valueForKey("statusUpdate") as? String) == nil
Answer: Line 3 of your code inserts a new Status object, so each time this code is executed, you are adding an extra object.  The newly inserted object will have a statusUpdate of nil (most likely).
When you execute the fetch, in line 6, this new Status object will be included in the results, together with any objects you have saved previously. So when you iterate through all the results, there will always be one for which statusUpdate is nil.
I would restructure your code to do the fetch first, establish whether there are any results.  If so, update the statusUpdate; if not, create the new object and set the statusUpdate field.  Something like this:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!

var request = NSFetchRequest(entityName: "Status")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: &self.error)

if let resultsArray = results { // explicitly test for nil results
    if resultsArray.count > 0 {
        // count should be at most one, but just in case we will iterate through:
        for result: AnyObject in resultsArray {
            println("Current User fetched status from Core Data")
            var newStatus = self.updateStatusText.text
            result.setValue(newStatus, forKey: "statusUpdate")
        }
    else { // resultsArray is empty, so insert a new object
        var newStatus = self.updateStatusText.text
        let newUser = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as NSManagedObject
        newUser.setValue(newStatus, forKey: "statusUpdate")
        println("Status uploaded for the first time")
    }
} else { // fetch returned nil, so log an error:
    println("Nil returned by fetch")
}
context.save(&self.error)

Answer:    if (var oldStatus = result.valueForKey("statusUpdate") as? String) != nil{

        println("Current User fetched status from Core Data")
        var newStatus = self.updateStatusText.text
        result.setValue(newStatus, forKey: "statusUpdate")

    }else {

        var newStatus = self.updateStatusText.text
        newUser.setValue(newStatus, forKey: "statusUpdate")
        println("Status uploaded for the first time")
    }


How to setup module install (sub-folder) paths from the *very beginning* (contrib, custom, features etc) - i.e. not move them after the install

Question: I've seen plenty of guides saying why it's a good thing to organise modules in different folders... (and I'd agree) e.g.:

Where to put custom modules?
https://drupal.org/documentation/install/modules-themes/modules-7
http://befused.com/drupal/module-directory-structure (particularly like this guide, more folders and options to choose from)

...and how to move the modules to the new place(s) after installation

How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/*
https://stackoverflow.com/questions/2654720/drupal-moving-module-folder
How to reorganize drupal sites/all/modules structure without symbolic links?

... but these haven't worked for me, perhaps I need to try again. My site broke, even after trying the registry rebuild and clear cache many times.
So my question is this: How can I run the installation of Drupal to set up the modules to be installed in different folders (e.g. like in examples http://befused.com/drupal/module-directory-structure )?
There doesn't seem to be anything out there if you want your module paths (sub-folders) structured in a certain way, right from the beginning. NOT after the fact.
I want the folders to be set up in the first place, right from the beginning. So example, whenever I use drush to download a contrib module, the module is placed in the contrib sub-folder: sites/all/modules/contrib for example.
Some other references:

Can Drupal be configured to find modules in other locations? - this suggests Drupal can just discover the location, I'm not so keen on this, I'd rather Drupal always know where the modules are rather than having to discover where they are.
Is it possible to change the path of modules/themes installed using an installation profile? - I just want to use the plain vanilla Drupal 7 core install. If I was going to use this option, what would be the minimum I would need to provide in a setup to have module sub-folders?
Answer: Actually it seems like all you need to do is just create a folder called contrib in /sites/all/modules
when I issued drush dl views (at the docroot/install top level root of my site), drush put the views module in the contrib folder
as for features - you specify where you want the module to go when you (re)create the Feature (in the Feature section of the Drupal config)
as for custom - I'm hoping that Drupal will discover custom modules here - but is discovering, rather than a setting determining the path, a good thing?
Thought I'd still ask the question even after I'd found an answer, didn't want to waste the effort in making the question - hope someone else finds it useful.
Please provide your own answer or comment to enhance what I found.
Comment: Did you try to rebuild the registry using https://www.drupal.org/project/registry_rebuild? I usually build a site inside a custom installation profile and by using make files specify which folders different modules and themes should go into. I usually place custom modules under /profiles/MYPROFILE/modules/custom and contrib modules goes in /profiles/MYPROFILE/modules/contrib
Comment: +1 Great tips thanks Pontus Nilsson - I did try registry rebuild - I think I'd moved my modules into certain folders, it didn't work out (errors) then moved them back to the original place (still errors) and then tried registry_rebuild to sort it all out, but it wouldn't install. So now when I remember more of what happened, I think what would have worked would be to have installed registry_rebuild *before* attempting to move any modules to other folders.
Comment: That said I prefer the idea of having everything in the certain folders (contrib, custom etc) in the first place so your input on install profiles is something I'd want to explore.
Comment: Be aware that registry_rebuild isn't a module. It's a php script, see the documentation for more info.


How do I determine the SP and Rollup version of an Exchange installation?

Question: How do I determine the SP version number and Rollup version of an Exchange installation?
Comment: http://technet.microsoft.com/en-us/library/hh135098%28v=exchg.150%29.aspx
Answer: Slow method
Open "Programs and Features", select view updates, and search for the relevant Exchange 2010 patch.
Fast method
Run this command in Powershell
 gcm exsetup | %{$_.fileversioninfo}

Then use this URL to decipher the version number:
http://social.technet.microsoft.com/wiki/contents/articles/240.exchange-server-and-update-rollups-build-numbers-en-us.aspx
This site seems to have more versions than the former - my Exchange version, 14.03.0123.004, wasn't listed on the former, but I found it here:
https://technet.microsoft.com/library/hh135098.aspx?f=255&MSPPError=-2147217396
Answer: I created a PowerShell function to retrieve the proper version information for Exchange 2007, 2010 and 2013. My blog post includes the code and some usage examples. Since the function is over 200 lines, I will not include it here. The following is some sample usage and output of the function:
Get Installed Updates (Cumulative and Update Rollups) for a Single Server
[PS] Get-ExchangeServerPlus -cn exch01 | select -ExpandProperty update | ft inst*,upd*,desc* -AutoSize

InstallDate UpdateBuild Description
----------- ----------- -----------
11/11/2012  8.3.279.5   Update Rollup 8-v2 for Exchange Server 2007 Service Pack 3 (KB2756497)
02/18/2013  8.3.298.3   Update Rollup 10 for Exchange Server 2007 Service Pack 3 (KB2788321)

Output All Exchange Server Object Properties with Installed Updates
Get-ExchangeServerPlus | % {"Name`t: $($_.Name)"; "Version`t: $($_.Version)"; "Edition`t: $($_.Edition)"; "Build`t: $($_.Build)"; "Role`t: $($_.Role)"; "OSVer`t: $($_.OSVer)"; "OSSP`t: $($_.OSSP)"; "OSArch`t: $($_.OSArch)"; if ($_.Update) { $_ | select -ExpandProperty update | ft inst*,upd*,desc* -auto } else { [Environment]::NewLine }}

...
Name    : EXCH160-02
Version : 2013
Edition : Enterprise
Build   : 15.0.620.29
Role    : MB,CAS
OSVer   : Microsoft Windows Server 2012 Datacenter
OSSP    : 0
OSArch  : 64-bit

InstallDate UpdateBuild Description
----------- ----------- -----------
04/21/2013  15.0.620.29 Microsoft Exchange Server 2013 Cumulative Update 1
...

Answer: Get-ExchangeServer | ft AdminDisplayVersion

Comment: How does this add to the other answers?  More detail would improve this answer
Comment: This (AdminDisplayVersion) does not reveal what RU has been installed, as explained in http://blogs.technet.com/b/rmilne/archive/2013/10/29/how-to-check-exchange-2010-ru-version.aspx


Badminton Racket Specifications

Question: I've been playing with numerous badminton rackets:

short
long
large blade
long shaft

but are there exact badminton racket specifications regarding length and/or weight?
Answer: On the Badminton World Federation (BWF) website, there are a lot of official documents to be found.
You need to go to the second tab (Organisation) on the main site and choose Law & Regulations.
After that you need to click on Laws of Badminton (circled red):

The document, titled: PART II, SECTION 1 A, LAWS OF BADMINTON, elaborates in chapter 4 on the racket specifications:

4.1
The racket shall be a frame not exceeding 680 mm in overall length and 230
  mm in overall width consisting of the main parts described in Laws 4.1.1 to
  4.1.5 as illustrated in Diagram C.

After that, in paragraph 2 of chapter 4, the following is explicitly mentioned  about the racket:

4.2 The stringed area:
4.2.1
shall not exceed 280 mm in overall length and 220 mm in overall width. However, the strings may extend into an area which otherwise would be the throat, provided that:
22.214.171.124
the width of the extended stringed area does not exceed 35 mm; and
220.127.116.11
the overall length of the stringed area does not then exceed 330 mm

The weight isn't specified, thus out of bounds.
Answer: Badminton Rackets

Modern Badminton Rackets are light in weight and usually below 100
  grams. The frame of the Racket can be made of steel, aluminum, carbon
  fiber, ceramic, boron or a combination of some of these.
It shall not exceed 680mm in overall length and 230 mm in overall
  width.
The weight should not exceed more than 100 grams.
A majority of racket manufacturers use 1U, 2U, 3U, 4U to indicate the
  weight of the racket, 1U being the heaviest and 4U the lightest. The
  weight of high quality rackets range from 83 grams to 100 grams.

2U - 90 to 94g
3U - 85 to 89g
4U - 80 to 84g
The racket head may be either oval or square.
Strings:

Badminton strings are thin, high performing strings in the range of
  about 0.62 to 0.73 mm thickness. Thicker strings are more durable, but
  many players prefer the feel of thinner strings. String tension is
  normally in the range of 80 to 160 N (18 to 36 lbf). Recreational
  players generally string at lower tensions than professionals,
  typically between 80 and 110 N (18 and 25 lbf). Professionals string
  between about 110 and 160 N (25 and 36 lbf). Some string manufacturers
  measure the thickness of their strings under tension so they are
  actually thicker then than specified when slack. Ashaway Micropower is
  actually 0.7mm but Yonex BG-66 is about 0.72mm.

Grip:

There are two main types of grip: replacement grips and overgrips.
  Replacement grips are thicker, and are often used to increase the size
  of the handle. Overgrips are thinner (less than 1 mm), and are often
  used as the final layer. Many players, however, prefer to use
  replacement grips as the final layer.
Most racket manufacturers provide four grip sizes. In Japan, they
  range from G2, G3, G4 to G5 where G2 is the biggest size and G5 is the
  smallest size. In some countries, the opposite applies. Some brands go by small, medium and big sizes.

Hi-Qua / Tactic G2 - 3.25 inches,       Yonex G2 - 4.00 inches
Hi-Qua / Tactic G3 - 3.50 inches,       Yonex G3 - 3.75 inches
Hi-Qua / Tactic G4 - 3.75 inches,       Yonex G4 - 3.50 inches
Hi-Qua / Tactic G5 - 4.00 inches,       Yonex G5 - 3.25 inches
For more info about the terms G and U refer here.
Source : Badminton information.com and Wikipedia.
Comment: -1 Please refrain from copying content wholesale and use (block) quotes when not using your original work. See [this](http://meta.sports.stackexchange.com/a/223/527) for more info.
Comment: Perhaps I should have asked more precise, but I was looking for dimensions, like long, short. Actually the first three sentences would suffice. Can you add specific references for that?
Comment: @JacobJanTuinstra, references were already added in the answer
Comment: You just copied the complete content into this answer. Where is the reference that `It shall not exceed 680mm in overall length and 230 mm in overall width`?

Badminton Racket Specifications


Certificate Information from WCF Service using Transport security mode

Question: Is there any way to pull information about which client certificate was used inside of my web service method when using <security mode="Transport>?  I sifted through OperationContext.Current but couldn't find anything obvious.
My server configuration is as follows:
  <basicHttpBinding>
    <binding name="SecuredBasicBindingCert">
      <security mode="Transport">
        <message clientCredentialType="Certificate" />
      </security>
    </binding>
  </basicHttpBinding>

I'm working with a third party pub/sub system who is unfortunately using DataPower for authentication.  It seems like if I'm using WCF with this configuration, then I'm unable to glean any information about the caller (since no credentials are actually sent).
I somehow need to be able to figure out whose making calls to my service without changing my configuration or asking them to change their payload.
Comment: I'm considering taking advantage of the endpoint's address by simply adding a unique querystring to it.  The QueryString can be read via `((System.ServiceModel.Channels.HttpRequestMessageProperty)System.ServiceModel.OperationContext.Current.IncomingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name]).QueryString`
Answer: Yes, but it's unintuitive.
First, be sure and reference the System.IdentityModel assembly from your service library.
Now, add something similar the following to your service method where you would like to know about the client certificate:
// Find the certificate ClaimSet associated with the client
foreach (ClaimSet claimSet in OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets)
{
    X509CertificateClaimSet certificateClaimSet = claimSet as X509CertificateClaimSet;
    if (certificateClaimSet != null)
    {
        // We found the ClaimSet, now extract the certificate
        X509Certificate2 certificate = certificateClaimSet.X509Certificate;

        // Do something interesting with information contained in the certificate
        Debug.Print("Certificate Subject: " + certificate.Subject);
    }
}

Hope this helps!
Comment: Thanks for the answer, but `OperationContext.Current.ServiceSecurityContext.AuthorizationContext` is empty!  Maybe IIS doesn't provide the certificate to WCF?
Comment: Or perhaps it's only available when ``?
Comment: I don't know, it works for us when using transport level security with the net.tcp binding in a self-hosted scenario. I don't know why the AuthorizationContext would be null in your case.


Interpreting the Chi-square on a multiple group SEM with lavaan

Question: A Chi-square (p-value) of a single group SEM is easy to interpret. It is a measure of exact fit.
When one runs a multiple group, say grouping the data by gender or by the presence of a condition like a disease, lavaan outputs a chi-square, together with the chi-square of the particular groups.
How to interpret that general multigroup chi-square? I have applied a same model to two groups, one with and the other without the diagnosis of schizophrenia. In that case the single non-significant chi-square allows me to say that schizophrenia mediates whatever relation I am evaluating in the path?
I am aware that I have to run invariance tests after the multigroup analysis, but I am curious about the particular interpretation of that Chi-square.
Answer: Ideally, invariance tests would culminate in a model that constrained the path between the "mediating" factor and the outcome factor to equality across groups. Global $\chi^2$ values are used to evaluate relative fit between models representing different levels of invariance.$^1$ Assuming measurement invariance has been established,$^2$ testing for mediation would be accomplished by constraining the relevant structural paths to equality across groups and conducting $\Delta\chi^2$ tests.
$^1$ Cheung and Rensvold (2002) recommend using $\Delta$CFI when testing invariance across groups. $\Delta$CFI values above .01 represent non-trivial group differences.
$^2$ People have different opinions about this. Most would agree that you need to provide evidence of weak (or metric) invariance (same factors and loadings constrained to equality across groups).
Comment: Lovely, Mike. I am so grateful for your answer. Now it is clear to me. One other thing, can I report metric invariance without having reported configural invariance, for example? Or they have to be  all reported in all cases?
Comment: A lot paper have tables that include fit statistics for each model. Some papers make it a footnote. And others just reference that they checked it. I suppose it depends on how important those line of tests are and what the reviewers think.


How can I convert tuple of dictionaries into an organized dataframe?

Question: I am pulling an API that retrieves data in the format below.
     data = ({'2019-12-20': {'SMA': '216.0037'},
              '2019-12-19': {'SMA': '215.4711'},
              '2019-12-18': {'SMA': '214.9335'},
              '2019-12-17': {'SMA': '214.4074'}})

Currently, when I try and run "data = pd.DataFrame(data)", it returns a dataframe with 2 rows that uses each date as a seperate column and gives each row a dictionary as a value (example below).
           2019-12-20       |       2019-12-19     |      2019-12-18
 0  "{ 'SMA' : '216.0037' } |  {'SMA': '215.4710"} | {'SMA': '214.9335'}
 1            NaN           |         NaN          |        NaN

I would like to figure out how to convert this data into a dataframe following the format below.
        date     |   SMA
 ----------------------------
 0  '2019-12-20' | '216.0036'
 1  '2019-12-19' | '215.4711'
 2  '2019-12-18' | '214.9335'
 3  '2019-12-17' | '214.4047'

Any help would be much appreciated!
Answer: IIUC
pd.DataFrame(data).T.reset_index().rename(columns={'index':'date'})
         date       SMA
0  2019-12-20  216.0037
1  2019-12-19  215.4711
2  2019-12-18  214.9335
3  2019-12-17  214.4074

Or from_dict
pd.DataFrame.from_dict(data,'index').reset_index().rename(columns={'index':'date'})
                 SMA
2019-12-17  214.4074
2019-12-18  214.9335
2019-12-19  215.4711
2019-12-20  216.0037

Answer: From your code it looks like data is a dictionary (the outer parenthesis is ignored).
data = ({
    '2019-12-20': {'SMA': '216.0037'},
    '2019-12-19': {'SMA': '215.4711'},
    '2019-12-18': {'SMA': '214.9335'},
    '2019-12-17': {'SMA': '214.4074'}
})
assert isinstance(data, dict)

If that's the case then the dataframe you want can be generated as follows.
pd.DataFrame(
    [(k, v['SMA']) for k, v in data.items()],
    columns=['date', 'SMA']
)

Output:
         date       SMA
0  2019-12-20  216.0037
1  2019-12-19  215.4711
2  2019-12-18  214.9335
3  2019-12-17  214.4074

Answer: You would be able to achieve this using pandas.DataFrame.T

Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method.

df = pd.DataFrame(data).T.reset_index().rename(columns={'index':'date'}) will return:
         date       SMA
0  2019-12-20  216.0037
1  2019-12-19  215.4711
2  2019-12-18  214.9335
3  2019-12-17  214.4074


How do I replace all values in a column with the first value in that columns row?

Question: Let's say I have this dataframe:
df = pd.DataFrame({'A': ['green', 'red', 'blue'],
                   'B': ['orange', 'nan', 'nan']
                   'C': ['yellow', 'cyan', 'purple']})

I want all of column B to equal the 1st row value in column B (orange), without having to type in "orange". How would I go about doing that?
For context, I'm creating many different dataframes, but in one of the columns I only want the single value in the first row of that column, so it's impractical to type it in each time like this:
df[['B']] = "orange"

Thank you!
Answer: I think a slightly cleaner way than the above answer might just be to do:
df['B'] = df['B'][0]
Comment: ahh...very nice, agreed, much cleaner
Comment: Thank you all who contributed! Feels different when you're not doing it in the tutorials!
Answer: Here is one way to do it
df['B'] = [df['B'].iloc[0]] * len(df)
It takes the first row of column B without having to type it


$\lim_{x\to 1^-} \sum_{k=0}^\infty \left( x^{k^2}-x^{(k+\alpha)^2}\right)$

Question: Has anybody seen (or can anybody come up with) a proof that
 $$\lim_{x\to 1^-} \sum_{k=0}^\infty \left( x^{k^2}-x^{(k+\alpha)^2}\right) = \alpha$$
for all $\alpha > 0$?
And also that
 $$\lim_{\alpha\to 0^+} \left[ \lim_{x\to 1^-}\frac{\alpha -  \sum_{k=0}^\infty \left( x^{k^2}-x^{(k+\alpha)^2}\right)}{1-x}
\right]=\frac16$$
I thought I had a proof of the first limit but it was flawed.
EDIT I had written the wrong expression for the second of the limits.  It is now corrected.
Comment: https://en.wikipedia.org/wiki/Hardy%E2%80%93Littlewood_tauberian_theorem
Comment: From $\sum_{n=1}^\infty (n+a)^{-s} \Gamma(s/2) = 2\int_0^\infty x^{s-1} \sum_{n=1}^\infty e^{- (n+a)^2 x^2}dx$ and inverse Mellin/Laplace we get that $\sum_{n=1}^\infty e^{- (n+a)^2 x^2} \sim \frac{\sqrt{\pi}}{x}$ as $x \to 0$ . Otherwise, the Poisson summation applied to $\sum_{n=1}^\infty e^{- (n+a)^2 x}$ should give the same result.
Comment: I don't understand how that helps with the first statement. The exponentiation involved in the question is for a number just below 1 raised to what quickly become high powers, so how is the pole at $x=0$ important?
Answer: If we set $x=e^{-t}$ we have to prove that
$$ \lim_{t\to 0^+}\sum_{k\geq 0}\left(e^{-tk^2}-e^{-t(k+\alpha)^2}\right) = \alpha.$$
As a function of $t$, the above series is regular enough to make us able to state:
$$ \lim_{t\to 0^+}\sum_{k\geq 0}\left(e^{-tk^2}-e^{-t(k+\alpha)^2}\right) = \lim_{m\to +\infty}\int_{0}^{+\infty}me^{-mt}\sum_{k\geq 0}\left(e^{-tk^2}-e^{-t(k+\alpha)^2}\right)\,dt$$
(we use $me^{-mt}$ as an approximation of the Dirac delta distribution) and the original limit is converted into:
$$ \lim_{m\to +\infty}\sum_{k\geq 0}\left(\frac{m}{m+k^2}-\frac{m}{m+(k+\alpha)^2}\right)=\lim_{m\to +\infty}\sum_{k\geq 0}\frac{m(2\alpha k+\alpha^2)}{(m+k^2)(m+(k+\alpha)^2)}$$
Now the last series can be computed through the digamma function and the limit as $m\to +\infty$ is exactly $\alpha$ as wanted, since:
$$\frac{i}{2}\left[\psi(\alpha-im)-\psi(\alpha+im)\right] = \frac{\pi}{2}+\frac{\tfrac{1}{2}-\alpha}{m}+O\left(\frac{1}{m^3}\right). $$
The second question is essentially equivalent to finding an extra term in the previous asymptotic expansion.
Comment: I really like the idea of introducing the approximation-to-the-identity. (+1)
Comment: Nice answer. (+1)
Comment: Happy New Year Jack.  Great solution.  (+1) I took a different approach and applied the Euler-Maclaurin Summation Formula.  -Mark
Comment: I don't see that this gives $\frac16$ for the second limit (but I had written it wrong, so unless you were a mind reader, you probably could not have attacked that part of the problem. At any rate, I would imagine your technique could be brought to bear, but I am not strong enough to see how. I will ask the second part in a separate question.
Answer: From the Euler-Maclaurin Summation Formula, we have
$$\begin{align}
\sum_{k=1}^K (x^{k^2}-x^{(k+\alpha)^2})&=\int_0^K (e^{y^2\log(x)}-e^{(y+\alpha)^2\log(x)})\,dy\\\\
&+\frac{e^{-K^2|\log(x)|}-e^{-(K+\alpha)^2|\log(x)|}-(1-e^{-\alpha^2|\log(x)|})}2  \\\\
&+\log(x)\int_0^K \left(2ye^{-y^2|\log(x)|}-2(y+\alpha)e^{-(y+\alpha)^2|\log(x)|}\right)P_1(y)\,dy \\\\
&=\int_0^\alpha e^{-y^2|\log(x)|}\,dy-\int_K^{K+\alpha}e^{-y^2|\log(x)|}\,dy\\\\
&+\frac{e^{-K^2|\log(x)|}-e^{-(K+\alpha)^2|\log(x)|}-(1-e^{-\alpha^2|\log(x)|})}2  \\\\
&+\log(x)\int_0^K \left(2ye^{-y^2|\log(x)|}-2(y+\alpha)e^{-(y+\alpha)^2|\log(x)|}\right)P_1(y)\,dy \tag 1\\\\
\end{align}$$
Taking the limit as $K\to \infty$ in $(1)$ reveals
$$\begin{align}
\sum_{k=1}^\infty (x^{k^2}-x^{(k+\alpha)^2})&=\int_0^\alpha e^{-y^2|\log(x)|}\,dy
-\frac{1-e^{-\alpha^2|\log(x)|}}2  \\\\
&+\log(x)\int_0^\infty \left(2ye^{-y^2|\log(x)|}-2(y+\alpha)e^{-(y+\alpha)^2|\log(x)|}\right)P_1(y)\,dy  \tag 2
\end{align}$$
Taking the limit as $x\to 1^-$ in $(2)$ yields the coveted result
$$\lim_{x\to ^-1}\sum_{k=0}^\infty (x^{k^2}-x^{(k+\alpha)^2})=\alpha$$
as was to be shown!
Comment: The asymptotical expansion $$\psi(x)=\log(x)-\frac{1}{2x}-\sum_{n=1}^{+\infty}\frac{B_{2n}}{2n x^{2n}}$$ is usually derived from the EMC formula, so I guess our solutions are not that different. (+1) and happy new year.
Comment: I assume here that $P_1(x) = (x-\lfloor x \rfloor) - 1$.  I like this one better than Jack's just because I could not work out his computation of the last series via the digamma function, while I could follow your reasoning.
Comment: @MarkFischler Mark, you are correct regarding $P_1(x)$.  And Happy New Year!  - Mark


How to implement a custom scheduler in Heron?

Question: I have read the Heron Documents about Implementing a Custom Scheduler. And I have known that I should implement some interfaces to implement a Custom Scheduler, such as ILauncher, IPacking, IScheduler and IUploader.
I have realized my CustomScheduler that implemented IScheduler interface, and I want to using LocalLauncher, LocalUploader and default Packing algorithm with my custom scheduler.
What's more, I modified the heron configuration file named scheduler.yaml that located at conf/local/ to use the custom scheduler. At the same time, I added the CustomScheduler.jar to heron-core/lib/scheduler/. However, there is something wrong as logs shows:
[2018-04-15 20:44:27 -0700] [STDERR] stderr: Exception in thread "main"
[2018-04-15 20:44:27 -0700] [STDERR] stderr: com.twitter.heron.spi.scheduler.SchedulerException: Failed to instantiate scheduler using class 'com.zyt.heron.custom.scheduler.CustomScheduler'
[2018-04-15 20:44:27 -0700] [STDERR] stderr:    at com.twitter.heron.scheduler.utils.LauncherUtils.getSchedulerInstance(LauncherUtils.java:120)
[2018-04-15 20:44:27 -0700] [STDERR] stderr:    at com.twitter.heron.scheduler.SchedulerMain.runScheduler(SchedulerMain.java:382)
[2018-04-15 20:44:27 -0700] [STDERR] stderr:    at com.twitter.heron.scheduler.SchedulerMain.main(SchedulerMain.java:218)

what should I do to fix this problem? Thanks for your help!
Answer: The direct reason for your Exception is your custom scheduler is not packaged with the heron release.
To make your custom scheduler work, you can follow the steps below:

add your implementation into the directory heron/schedulers/src/java/com/twitter/heron/scheduler
update the BUILD file at directory heron/schedulers/src/java
add your custom scheduler building target at tools/rules/heron_client.bzl and tools/rules/heron_core.bzl

Here is an example of how local scheduler is packaged: https://github.com/apache/incubator-heron/search?utf8=%E2%9C%93&q=heron-local-scheduler&type=
Answer: The key is to provide your compiled .jar files to heron by copying your jar files into the .heron/lib/ folder.
I want to implement a custom scheduler and packing algorithm without recompiling Heron.
I have a project called "packing" that has the maven dependencies heron.api and heron.spi as requested.
My jar is called "packing-0.0.1-SNAPSHOT-jar-with-dendencies.jar built with maven.
What works for me are the following steps summarized in a small shell-script. I run it from within my packing-project folder to the assembly-command works:
#!/bin/bash
mvn assembly:assembly
cp target/packing-0.0.1-SNAPSHOT-jar-with-dependencies.jar $HOME/.heron/lib/packing/
cp target/packing-0.0.1-SNAPSHOT-jar-with-dependencies.jar $HOME/.heron/lib/scheduler/
echo "updated packing plan and scheduler"

Then, simply add your custom packing or scheduler to your config:
Example from the packing.yaml:
heron.class.packing.algorithm: com.hcep.packing.CustomPacking

with com.hcep.packing being my package structure in my packing-project and CustomPacking my packing class.
Answer: You can develop custom scheduler for Heron - please follow any of the implementations for a scheduler in the code base.
Comment: What should I do to deploy my custom scheduler to Heron? Do I should  upload my customScheduler.jar to heron-core.jar/lib/scheduler/? Is that right?
Comment: I have edited this question with more details. Thanks for you help.


Zone to use to convert UK utm data to longitude, and latitude

Question: I'm currently working on a UK vehicle accident dataframe and I'd like to convert easting and northing utm data to longitude and latitude, and then into regions. I am unsure about which zone to use in the function despite searching the internet.
My current function works but I'm unsure about the zones and further creating a column converting longitude and latitude into regions.
Curent Function:
def rule(row):
    lat, lon = utm.to_latlon(row["location_easting_osgr"], row["location_northing_osgr"], 30, 'U')
    return pd.Series({"lat": lat, "long": lon})
df = df.merge(df_subset.apply(rule, axis=1), left_index= True, right_index= True)

Comment: Are you sure those eastings and northings are UTM, and not the Ordnance Survey National Grid? Using the OSNG would make a lot more sense for the UK, as the UK straddles, if I'm not mistaken, three UTM zones, with a zone boundary running right through Greater London!
Answer: Wikipedia has all the zone information in this image:
(https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#/media/File:Universal_Transverse_Mercator_zones.svg)
Most of the UK is in zone 30U. So it looks like you have it right.
Alternatively you could just use the longitudinal zone and the hemisphere:
lat, lon = utm.to_latlon(row["location_easting_osgr"], row["location_northing_osgr"], 30, northern=FALSE)

Comment: You can inline the image and keep it clickable, if you want: `[![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Universal_Transverse_Mercator_zones.svg/1920px-Universal_Transverse_Mercator_zones.svg.png)](
https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#/media/File:Universal_Transverse_Mercator_zones.svg)` (explanation: `![description](link)` is an image, `[description](link)` is a clickable link, and then `[![](imagelink)](targetlink)` combines the two - description is just left empty here)


Finding where the slope of tangent line is = 1

Question: I am suppose to find the points on the curve $x^2+2y^2 = 1$ where the tangent line has a slope of 1.
I am not sure how to do this but I guessed that if I set it is
$y = \sqrt{\frac{1-x^2}{2}}$ then I can find that derivative and work from there.
I find the derivative as $y = (1-x^2)(\frac{1-x^2}{2})^\frac{3}{2}$
I am not sure how to work from here but just looking at the function it looks like x=1 would make it zero. I have absolutely no idea how to factor that, it just seems like a mess.
Comment: Consider implicit differentiation instead, then using y'=1, you'll have two equations in two unknowns...
Comment: That seems like it would be even more difficult to me, is there no reasonable way to do it my way?
Comment: @Jordan, implicit differentiation is a lot easier: $2x+4yy'=0$
Comment: @Jordan. Yes it's possible. But I'm afraid that you need to "find" the derivative again.
Answer: Your approach should work. We have $y^2=(1/2)(1-x^2)$, and therefore
$$y =\pm \frac{1}{\sqrt{2}}\sqrt{1-x^2}.$$
The plus sign is for the top half of the ellipse, and the minus sign is for the bottom half. If you just stick with the top half, you will only find one point at which the tangent line has slope $1$.  (A quick sketch shows this, and tells you roughly what the answers should be, useful as a check later.)
Let's work with $y =\pm \frac{1}{\sqrt{2}}\sqrt{1-x^2}$, we can deal with the other one later. Now we want  to differentiate. By the Chain Rule, we have
$$\frac{dy}{dx}=\frac{1}{\sqrt{2}}(-2x)(1/2)(1-x^2)^{-1/2}=-\frac{x}{\sqrt{2}}(1-x^2)^{-1/2}.$$
We want the derivative to be $1$. So we want to solve the equation
$$-\frac{x}{\sqrt{2}}(1-x^2)^{-1/2}=1.$$
Note that $x$ needs to be negative. Now square both sides and simplify. You should get something like $x^2=2(1-x^2)$. Solve for $x$, remembering it is negative.
I leave it to you to deal with the other half of the ellipse.
There is a much easier approach, through implicit differentiation. Look at the relationship $x^2+2y^2=1$. Nice formula, don't want to mess it up by taking square roots. Differentiate with respect to $x$ immediately. We get
$$2x+4y\frac{dy}{dx}=0.$$
The slope of the tangent line is $1$, so $\frac{dy}{dx}=1$, and therefore from $2x+4y\frac{dy}{dx}=0$ we conclude that $2x+4y=0$, meaning that $x+2y=0$. But also $x^2+2y^2=1$. Substitute $-2y$ for $x$. We get $6y^2=1$. So $y=\pm\frac{1}{\sqrt{6}}$ and the corresponding $x$ are $x=\mp \frac{2}{\sqrt{6}}$.
Comment: I added a step in the post, hope it takes care of your question.
Comment: I do not follow at all what happened from the implicit part. I see how you got the derivative but what happens after that?
Answer: Another approach would be the following: Let $f(x,y)=x^2+2y^2-1$. The tangent slope is given by: $$\frac{dy}{dx}=-\frac{\frac{\partial f}{\partial x}}{\frac{\partial f}{\partial y}}=1$$   See (here for proof). Using this equation and $f(x,y)=0$ you can find the points where the slope is equal to one.
Answer: Don't solve for $y$ first; use implicit differentiation!
If $x^2+2y^2=1$, then
$$\begin{align*}
\frac{d}{dx}(x^2+2y^2) &= \frac{d}{dx} 1\\
2x + 4y\frac{dy}{dx} &= 0\\
4y\frac{dy}{dx} &= -2x\\
\frac{dy}{dx} &= -\frac{2x}{4y}\\
\frac{dy}{dx} &= -\frac{x}{2y}.
\end{align*}$$
If the tangent has slope $1$, then $\frac{dy}{dx}=1$, so
$$\begin{align*}
1 &= -\frac{x}{2y}\\
-2y &= x.
\end{align*}$$
Plugging into the original equation and solving for $y$, we get:
$$\begin{align*}
x^2 + 2y^2 &= 1\\
(-2y)^2 + 2y^2 &= 1\\
4y^2 + 2y^2 &= 1\\
6y^2 &= 1\\
y^2 &=\frac{1}{6}\\
|y| &=\sqrt{\frac{1}{6}}
\end{align*}$$
giving two values of $y$, and two corresponding values of $x$.


JPA em java web

Question: estou com um projeto em JAVA WEB e estou com problemas com o hibernate. O erro é o seguinte:
Informações:   HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Informações:   HHH000412: Hibernate Core {4.2.2.Final}
Informações:   HHH000206: hibernate.properties not found
Informações:   HHH000021: Bytecode provider name : javassist
Grave:   Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver
Advertência:   StandardWrapperValve[ServeletLogin]: Servlet.service() for servlet ServeletLogin threw exception
java.lang.NullPointerException
at DAOs.LoginDBDAO.selectUsuario(LoginDBDAO.java:35)
at Controllers.ControllerLogin.validaUsuario(ControllerLogin.java:21)
at Servlets.ServeletLogin.doPost(ServeletLogin.java:42)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)....

Procurando pelo google não achei nada. Mas vi pessoas com problemas parecidos E sempre elas colocam imagens da estrutura das paginas então ai vai:
Páginas Web

Bibliotecas

persistence.xml
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" >
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbyclient</artifactId>
            <version>10.4.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>tck-utils-api</artifactId>
            <version>0.9.1</version>
        </dependency>

    <class>Entidades.Usuario</class>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/MackEstagios" />
        <property name="javax.persistence.jdbc.user" value="adm" />
        <property name="javax.persistence.jdbc.password" value="adm" />

                    <property name="hibernate.dialect"  value = "org.hibernate.dialect.DerbyDialect"/>

                    <property name="hibernate.hbm2ddl.auto" value = "update"/>
        <property name="hibernate.show_sql"  value = "true"/>
    </properties>
</persistence-unit>

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
 <session-factory>
    <property name="connection.driver_class">
        org.apache.derby.jdbc.ClientDriver
    </property>
    <property name="connection.url">
        jdbc:derby://localhost:1527/MackEstagios
    </property>
    <property name="connection.username">
        adm
    </property>
    <property name="connection.password">
        adm
    </property>
        <property name="dialect">
        org.hibernate.dialect.DerbyDialect
    </property>
</session-factory>

Creio que o erro esteja na configuração do hibernate e não em sua implementação.
Obrigado!
Comment: `java.lang.NullPointerException
at DAOs.LoginDBDAO.selectUsuario(LoginDBDAO.java:35)`

Consegue nos dar esse método?
Answer: Olá,
Você tem dois problemas:

Relacionar o item Grave:   Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver
java.lang.NullPointerException
at DAOs.LoginDBDAO.selectUsuario(LoginDBDAO.java:35)

Com relação ao problema do item 1, veja esse link com uma dúvida semelhante a sua. Porém, nesse link há uma diferença de projetos, projeto do link referenciado está utilizando um projeto com arquetipo maven.
Com relação ao problema do item 2, você está tentando utilizar um método com uma instancia de objeto null. Entretanto, esse erro também pode ser proveniente do item 1. Então aconselho verifica-lo primeirom antes de ir adiante no seu desenvolvimento.
Aqui você pode ver que há a classe que seu projeto está necessitando, mas esta versão de biblioteca hibernate-core versão 3.6.0.final não esta sendo utilizada no seu proejto o qual é a versão hibernate-core-4.2.2.Final.jar.

JPA em java web


How to use db_select and apply a condition for another table's data?

Question: I know this is probably the dumbest question ever but I'm just not getting warm with SQL.
I am writing this function which loads all users that have a role assigned:
function mymodule_get_users_by_role($rolename) {
  $role = user_role_load_by_name($rolename);
  $uids = db_select('users_roles', 'ur')
      ->fields('ur', array('uid'))
      ->condition('ur.rid', $role->rid, '=')
      // ->leftJoin('users', 'us', '(us.uid = ur.uid AND us.status = 1)')
      ->execute()
      ->fetchCol();
  return user_load_multiple($uids);
}

But I only want those users which's status = 1. I could do it afterwards but I really hope there is a way within the QuerySelect to add this filter beforehands. The commented line just produces a white screen of death so I'ma go with a nope. I dont even know if leftJoin is the right thing to do.
Thanks!
Comment: Are you, basically, asking how to make a [join](https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3Ajoin/7)?
Answer: The following query should be self-explanatory.
$query=db_select('table1','t1');
$query->join('table2','t2','t1.nid = t2.nid');

$query->condition('t1.uid','1')
      ->condition('t2.uid','3')
      ->fields('t1',array('uid','nid'))
      ->fields('t2',array('date'));

Comment: `$query = db_select('users_roles', 't1')
    ->join('users','t2', 't1.uid = t2.uid')
    ;
  $query->condition('t2.status', '1');` creates also a wod


Please review suggested edits!

Question: The Suggested Edits queue is full for at least the second time in 24 hours.  We need people to review edits!  Until some edits are reviewed, no new edits can be suggested:

I will gladly begin reviewing edits myself as soon as my site rep is high enough. In the mean time, there's very little I, personally, can do. So can some of thei higher rep users please step up?
Comment: I will take a look at them if you give me a few up votes ...
Comment: @StrongBad: Can you perhaps take a screen shot showing the empty review queue? This might be a bug that needs to be reported.
Comment: @StrongBad: I think you're over the threshold now :)
Comment: I feel a little dirty now, especially since the edit queue appears empty ...
Comment: @StrongBad: Interesting, really? I know I still have a number of edits awaiting review.
Comment: @Flimzy StrongBad isn't over the threshold for *tag wiki* edits, only for regular edits.
Comment: @GaëlLaurans I didn't realise that all the edits were tag wiki edits. I am no where close to the 1500 threshold.
Answer: Please don't fill up the edit queue ;-) Seriously, we are limited to 20 tag wiki edit reviews per day and per person and I already used up my quota:

Thank you for reviewing 20 suggested edits today; come back in 3 hours to continue reviewing.

Also, only users with more that 1500 rep points can see tag wiki edits and the ones I reviewed still need to be approved by someone else. The only slightly disconcerting thing is that it's not a separate greyed out entry in the review tab, those edits are simply invisible until you reach the threshold but I see them, they are there:

For more: Edit Questions and Answers and Approve Tag Wiki Edits
Comment: We appear to have two users with >1500 rep, so all it needs is our second one to go through and review them to unblock a tiny bit of the queue! (Ideally some proper mods would come through and do the rest....)
Answer: I don't see anything to review

If I go to your profile the suggested edits I see are edits to the tag wiki. If I click on one of them

so apparently tag wiki edits are not reviewable. I wonder if there is a maximum number of edits you can make in a day (or if I need more rep).
Comment: Meta.SO question [here](http://meta.stackexchange.com/q/226744/165502)

Please review suggested edits!


Theming a new Panel Page

Question: I think I am missing something really silly here. I am trying to learn theming in drupal. So I downloaded a "starter" theme called Genesis and installed it. This theme has a barebones header and footer. And in the middle the content area is split into left sidebar, main content and right sidebar.
I created a panel page with 'flexible' layout. It has only one region defined and inside it I placed a custom view I had created earlier. Now when I hit this panel page url, it shows up correctly, but inside the main content area of theme. I mean the header, footer, left and right sidebars are still visible.
My question is: By default do panel pages render inside main content area? How can I customize a panel page such that I can do away with the header, footer or sidebars if I want to?
Appreciate any help!!
Answer:
By default do panel pages render inside main content area?

No, Panels should 'takeover' the page based on your ctools page manager assignments.
See /admin/structure/pages to confirm you have the path set in page manager ("Pages").
Comment: thank you for your answer, I have set the path in page manager for my panel page to 'test-panel'. When I hit the url 'http://localhost/test-panel' I can view the newly created panel page. The only problem is that, as mentioned, before it shows up within the content area with the sidebars and header/footer...not sure what I am missing here..
Answer:
By default do panel pages render inside main content area?

Yes, panel pages are output in the main content region.
Also, there's an option to disable all blocks/regions in your theme under the General settings for your Panel variant. This feature doesn't work for all themes though.

Theming a new Panel Page


When do Inverse Images of Measurable Sets Generate the $\sigma$-algebra?

Question: Just out of curiosity!
Let $(X,\mathcal{M})$ and $(Y,\mathcal{N})$ be measurable spaces and let $f: X\to Y$ be a measurable function. If $\mathcal{N}$ is generated by some collection of sets $\mathcal{E} \subset \mathcal{P}(Y),$ when can we say that $\mathcal{M}$ is generated by $f^{-1}(\mathcal{E}),$ where $f^{-1}(\mathcal{E}) = \left\{f^{-1} (E) \mid E \in \mathcal{E}\right\}?$
Answer: According to this thread, we have
$$\sigma(f^{-1}(\mathcal E))=f^{-1}(\sigma(\mathcal E))=f^{-1}(\mathcal N)\subset \mathcal M,$$
but the inclusion may be strict, for example when $f$ is constant.


Flashlight app not turning off in kitkat device. perfectly working on marshmallow

Question: Here is my code of my flashlight app which is perfectly run on my nougat and marshmallow device. but when i test it to a kitkat device, flashlight turn on perfectly, but not turning off.
Whats wrong i did in this code can you help me to find it please..
I didnt find any solution in the web. please help.
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btnSwitch;
    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Camera.Parameters params;
    MediaPlayer mp;
    private static final String TAG = MainActivity.class.getSimpleName();
    private Camera mCamera;
    private Camera.Parameters parameters;
    private CameraManager camManager;
    private Context context;

    ImageView imageFlashlight;
    private static final int CAMERA_REQUEST = 50;
    private boolean flashLightStatus = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageFlashlight = (ImageView) findViewById(R.id.imageFlashlight);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);

        // First check if device is supporting flashlight or not
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        final boolean hasCameraFlash = getPackageManager().
                hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        boolean isEnabled = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);

        // get the camera

        // displaying button image

        imageFlashlight.setEnabled(isEnabled);

        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);

        imageFlashlight.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (hasCameraFlash) {

                    if (flashLightStatus) {
                        turnOffFlash();
                    } else

                        turnOnFlash();
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }

        });

    }

    @TargetApi(Build.VERSION_CODES.M)
    private void turnOnFlash() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

            try {
                String cameraId = cameraManager.getCameraIdList()[0];
                cameraManager.setTorchMode(cameraId, true);
                flashLightStatus = true;
                imageFlashlight.setImageResource(R.drawable.poweron);
            } catch (CameraAccessException e) {
            }
        } else {

            imageFlashlight.setImageResource(R.drawable.poweron);

            getCamera();
            params = camera.getParameters();
            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;

        }
    }

    // Get the camera
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Camera Error. ", e.getMessage());
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void turnOffFlash() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

            try {
                String cameraId = cameraManager.getCameraIdList()[0];
                cameraManager.setTorchMode(cameraId, false);
                flashLightStatus = false;
                imageFlashlight.setImageResource(R.drawable.poweroff);
            } catch (CameraAccessException e) {
            }
        } else {
getCamera();
            if (flashLightStatus) {
                if (isFlashOn = true) {
                    return;
                }

                params = camera.getParameters();
                params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(params);
                camera.stopPreview();
                isFlashOn = false;
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    imageFlashlight.setEnabled(true);
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

Answer: The issue is with flashLightStatus because you are not setting it inside else part of turnOnFlash method and later inside turnOffFlash,
if (flashLightStatus) {

will never be true hence control will never reach the point to turn off light so do
@TargetApi(Build.VERSION_CODES.M)
private void turnOnFlash() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
            imageFlashlight.setImageResource(R.drawable.poweron);
        } catch (CameraAccessException e) {
        }
    } else {

        imageFlashlight.setImageResource(R.drawable.poweron);

        getCamera();
        params = camera.getParameters();
        params = camera.getParameters();
        params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();

    }
       isFlashOn = true;
       flashLightStatus = true;
}

and also use
if (!isFlashOn) {
     return;
}

instead of
if (isFlashOn = true) {
    return;
}

to return control when flash light is not on
Comment: O god! Thank you so much sir, you just save me. thanks a lot.  One more question please, I added a button on this main activity called red theme (It was blue). when user click the button they will go to another activity, there will be same thing like main activity. just on click color will be change.  i've already done it, activity get change but when i click to flash on button it crashed. do i need to change any method for second activity to turn on flash??
Comment: @Adam just follow the crash `error` details in logcat view (on left bottom) to see the cause and resolve it and to turn on flash in second activity, you need the same setup and probably wants to shut down flash control of previous activity in on pause, rest depends upon the implementation, you can use service etc


DFS Namespace / Windows Server 2008 R2 / Win 8 - missing entries

Question: We have a DFS namespace at \\company.example.org\dfs\ and inside that are entries for half a dozen folders. There is one namespace server, and no replication. The shares are all now on one server. Very basic.
I use Windows 8 Pro as a desktop, with a drive mapped to \\company.example.org\dfs\companyshare\
Suddenly, and arbitrarily, it stops working, with the error "Windows cannot access \\company.example.org\dfs\companyshare\"
I browse to the \dfs\ namespace folder, only one of the endpoint entries is there, the rest are missing. I can ping the namespace server and browse to the share as \server\share.
After a few minutes ... they reappear. Or I reboot, and it works again. This seems to happen on more than one Windows 8 client, but not on Windows 7.
I have run the DFSDiag tests linked, and they all come back fine.
In the properties of the \company.example.org\dfs folder, on the DFS tab, I see one entry in the referral list, which is active and status "Okay".
There are three domain controllers, 2008 R2 twice and 2008. All service packed and updated.
No event log errors that I can find on server or client.
Summary: Win 8 drops most of the DFS endpoints, and then a few minutes later, refreshes them. Nothing else seems to be wrong.
Where can I look for more information?
[Update: So far I have used the dfsutil diagnostics from TheFiddlerWins' answer, and found absolutely nothing. The only progress I've made is realising that the virtual machine in question still had 1 core and 3GB of RAM assigned, and now I've moved lots of roles onto it (printers, several heavy file shares), that was rather underpowered. Since increasing the available CPU and RAM for the machine last week, I haven't noticed this issue occuring again. Too early to say for sure that it's gone, but it might be that simple].
Comment: so the dfs names space is hosted on a w2k8 server not w2k8r2 correct?
Comment: No, sorry, the namespace is on 2008 R2, the 2008 DC shouldn't be involved in DFS, it just exists as a DC. Updated title to reflect this.
Comment: anything in the eventlog on the win8 client?
Comment: Nothing I can find.
Comment: and I bet that you can't make it fail on demand correct?  If you can put netmon on the win8 client and see whats happening.
Answer: DFS (for some ungodly reason) uses NetBIOS style names (DOMAIN instead of domain.com) by default. This document from Microsoft tells you how to fix it. I suspect your issue is that at times it's able to resolve these names (via WINS, broadcasts etc) and other times not.
If that is not it try following this doc on DFS troubleshooting.
Comment: This looks interesting! I can resolve "DOMAIN" when it happens, but I'll work through the troubleshooting doc. For anyone reading, the dfsutil command is in the Remote Server Admin Tools, download links:  [Win8](http://www.microsoft.com/en-us/download/confirmation.aspx?id=28972), [Win7 SP1](http://www.microsoft.com/en-us/download/details.aspx?id=7887), and then needs to be enabled from "turn Windows features on/off" as described [here](http://blogs.technet.com/b/josebda/archive/2010/05/02/where-to-find-dfsutil-exe-for-windows-server-2008-and-windows-server-2008-r2.aspx).
Comment: If you create a new DFS share for testing using FQDN does it work reliably?


Mail caching service?

Question: Right, I'm not too sure if this is possible or even where to look for info, soooo...
What I was hoping to do is setup a linux box with a user "foo"
foo has an email account with gmail
Is it possible for the server to retrieve the users email from gmail using imap so that when they retrieve their email it comes from the local server instead of gmail.
Basicly this is some sort of mail caching service.
Even some info pointing me into the general area of documentation would be great!
Answer: You could use offlineimap to receive the mails from your GMail account.
Also running your own IMAP server and fetching the mail with fetchmail or getmail or generally sync the data with your GMail account (e. g. using imapsync) are viable options. Of course you have to think about syncing the changes back to GMail, e. g. what will happen if you delete a mail in your local IMAP server.
Comment: My progress so far: Using getmail and dovecot it was very simple to setup a multi-user caching server! Thanks, just need to work on that synching method now :(
Comment: Awesome joschi! Thats a great place for me to start!
Comment: Avoid fetchmail.  It has failure modes which lose email.  getmail or offlineimap are good approaches.
Answer: How about configuring some email client like mutt / thunderbird / kmail to retrive emails every 10 minutes from Gmail?
Comment: mutt is designed to look at one folder at a time, so you'd then be looking at scriptinging mutt somehow.  The others are heavy-weight graphical clients.  There are command-line tools which are designed to sync mailboxes and nothing else.

Mail caching service?


How to model distributions which are not normally distributed

Question: I would like to model the performance of a rainwater tank, which has a stochastic input (rainfall). The data are the empty volume in the tank at the end of each day. The values are skewed towards the extremes, and I am not sure how to model this or present it statistically. Reviewing various distributions in Wikipedia, I found that it seems like a Beta Distribution - but I am not sure whether it is one. I need to find a statistical method of representing the 'empty volume'.
One friend suggested that I use binomial distribution of getting probability of tank being 25% empty, 50% empty or 75% empty and find confidence intervals associated with those values.
Here is the distribution of my data:

EDIT - 11 July 7:28 GMT (following comments for clarification)
The inflow into the tank occurs randomly due to the rainfall. There is regular abstraction from the tank if there is stored volume.
I would like to estimate the probability of the empty volume in the tank on any random day in future based on the the historic data, and associated confidence of that probability.
I would then like to use that 'empty volume' figure to estimate how much of a large storm rainfall it can a large number of such tanks hold back and reduce the flash flooding volumes. Possibly may need to present combined probabilities with the storm probability.
Comment: What are you actually trying to accomplish. You say you are trying to model it but do you have a model in mind? I.e., are you trying to predict the amount of rainfall for each day?  Or make inference about the mean amount of rainfall or....?
Comment: Also, based on your graphs I am not convinced this strategy would work but you could always try a transformation of the data and see if that helps alleviate the normality assumption you seem to be hoping for.
Comment: It seems to be that a time series approach would be most useful. Something like a stochastic process with a trend, a normal distributed rain input and structural breaks for the extraction. I do not think you should model this as some sort of distribution. The book for all this is Hamilton (1994). Serial dependence, trends etc. are all issues here. I would not recommend picking a model which starts with the assumption of random picking as some said below, as this is clearly not the case. One input maybe iid, the actual barrel state is not.
Comment: It's *certainly* not binomial, that's for count data. You *might* make an argument for a beta as an approximation, but I doubt that it's actually beta.
Comment: I meant to mention in my previous comment - the observations are going to have serial dependence, which should also not be ignored.
Comment: I am interested in getting the probability and confidence associated with the available tank volumes, which I will use in a different program (hydrological modelling) where I will be using a 'design rainfall for storm events' and use the volume of storage provided by a number of such tanks as detention of the rainfall runoff. Empirical distribution might be a way (as suggested by @willy), and I will look at semi parametric model as suggested by @FrankHarrel (but I guess it will require a lot of reading)
Comment: @Glen_b Just read another posting (http://stats.stackexchange.com/questions/39323/how-to-analyse-a-continuous-response-having-a-bimodal-distribution) on bimodal distribution. That might possibly work?
Comment: If you're asking 'could beta regression work?' then possibly, but the central problem (as with any regression model) is still serial dependence; you might be better modelling the physical circumstances of the process itself and trying to estimate parameters there. @IMA's comment has some useful points in it.
Answer: I would recommend a semiparametric model such as the proportional odds model.  This nicely handles data clumping.  The model will have one intercept per unique $Y$ value, less one.  In two days there will be a major update to the R rms package containing a new ordinal regression modeling function orm that uses sparse matrix algebra to efficiently handle continuous $Y$ (thousands of intercepts).  Chapter 15 of my latest course notes contains a case study - see http://biostat.mc.vanderbilt.ede/rms and click on Course Notes.  orm handles 4 other distribution families besides the logistic.
Comment: The update is now on CRAN for linux, windows, and mac.
Comment: This data looks to be nearly continuous (except near the max and min) based on the QQ plot so you'd probably have to group it before fitting the proportional odds model. How would you suggest doing that?
Comment: What makes you think that any grouping is needed?
Comment: Oops, I did not read your answer carefully enough. I'll be interested to try this when it comes out.
Answer: @COOLSerdash's comment is right on target (+1).  It seems unlikely that your data are actually any of the named distributions, such as beta, and the answer by @Glen_b will provide a nice example of how you might go about exploring your dataset.
The fitdistrplus package in R will provide you with some tools that may be helpful.  For example, if you just want to estimate the parameters of the beta distribution that maximize the likelihood of your data, ?fitdist will help.
Answer: "The data are the empty volume in the tank at the end of each day."

The data are time indexed, you have to take this feature into consideration.
It is likely that the data are dependent. Someone/Something fill up the tank at some time points or when the tank is close to depletion.

I suggest to take a look at Time Series models (e.g. autoregressive models), rather than fitting a distribution to the raw observations, in order to avoid throwing all the features of the data.
The estimation procedures recommended in the other answers do not consider possible dependencies of the data and time indexing.
Comment: Something: the tank is open vertically and there are inputs of rainfall.
Comment: @NickCox Thanks for the clarification. I guess a different something extracts water from the tank.
Comment: Yes, the input is rain from a catchment surface, and abstraction is for use - e.g. gardening, irrigation or other uses.
Answer: I assume you are trying to find some well known distribution to model your data.  If this is the case, then you could do a goodness of fit test.  This is a well known test and there are several methods.  You will be testing many different distributions to see which one best fits.  Then just pick the one that best works for you.
Not sure what you are doing this for, but you could use an empirical distribution, which is basically just the sample itself.
These methods are easy to look up online.
Comment: I'd be surprised if the data would follow any well-known distribution at all. @surgez [This post](http://stats.stackexchange.com/questions/58220/what-distribution-does-my-data-follow) might be of interest too.


java.awt.color.CMMException: LCMS error 12288

Question: ImageIO.read works for most of my images but throwing this exception for a particular jpg image.
im = ImageIO.read(this.getClass().getResourceAsStream("plan3v2.jpg"));

this line throwing exception:
Exception in thread "main" java.awt.color.CMMException: LCMS error 12288
        at sun.java2d.cmm.lcms.LCMS.getProfileData(Native Method)
        at java.awt.color.ICC_Profile.getData(ICC_Profile.java:1310)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.setImageData(JPEGImageReader.java:652)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:593)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:338)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:470)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:586)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1004)
        at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:984)
        at javax.imageio.ImageIO.read(ImageIO.java:1438)
        at javax.imageio.ImageIO.read(ImageIO.java:1342)
        at TestClass.run(TestClass.java:13)
        at TestClass.main(TestClass.java:8)

Not sure what the error "LCMS error 12288" mean.
Is there any alternative api that can read such images?
Thanks in advance.
Answer: The "LCMS error" exception message you see, originates from the LittleCMS color management module, that was introduced first in OpenJDK, but has now replaced KCMS (the original Kodak CMM used by Sun in their Java implementations) in Oracle JDK8.
Assuming the image is the same as referred to from this RedHat bug report (it has the same file name, and causes the same exception), the TwelveMonkeys ImageIO JPEGImageReader plugin can read it*.
The embedded ICC profile in the image is corrupt, so it is simply ignored by my reader, but the image is fully readable and looks okay still.
To use the plugin, you only need to place the plugin with dependencies on class path (see example). Your existing code should then just work as before (without the exception that is). No need to change or recompile anything.

*) I've only tested on JDK 1.6 and OpenJDK 7 on OS X and JDK 7 and 8 on Windows, but it shouldn't matter. :-)
Comment: Well that works in my testcases. But when I deployed my web application in tomcat, getting same LCMS error again. I have verified that JAVA HOME is same in tomcat configuration. Please advise.
Comment: @JitendraChandani If the exception occurs, most likely you haven't installed the plugins correctly, or ImageIO isn't picking them up. Have you read [Deploying the plugins in a web app](https://github.com/haraldk/TwelveMonkeys#deploying-the-plugins-in-a-web-app) and configured your `web.xml` accordingly? You can also use the code from [Installing](https://github.com/haraldk/TwelveMonkeys#installing) in a `Servlet` to verify proper installation.
Answer: What version of jre are you using? It appears this is fixed in 1.7.60.
http://bugs.java.com/view_bug.do?bug_id=6839133
https://bugs.openjdk.java.net/browse/JDK-6839133
Comment: Hi Brett, I am on OpenJDK version "1.6.0_17". Moving to 1.7 is not easier for me at the moment. Application is big enough and have lots of jar dependencies. Thanks.


Dynamically Adding a ViewUserControl in ASP.NET MVC

Question: I am wondering if there are any known issues with adding a ViewUserControl at run time (to a ViewPage). It works fine if I add the control declaritively but not if I add the control programmatically (in the code behind file in this case). I don't get an error, it just does not render the control but stepping through the debugger does confirm that the relevant methods in the page life cycle are being called.
I do realize that it's not quite kosher to use a code behind file with ASP.NET MVC but I do have reasons for wanting to do so.
Answer: Send the list of controls you want to load and pass it to the view model.
Controller action:
var controlsToLoad = new List<string>();
controlsToLoad.Add("foo");

return View(controlsToLoad);

View:
<% foreach (var control in Model as List<string>) { %>
    <% Html.RenderPartial(control); %>
<% } %>

This will keep you out of code behind and still let you dynamically specify in the controller which controls to load in the view.
Comment: Hi John,

Thanks for a quick response. Is this the only way to do it? I'd like to be able to create an arbitrary number of instances of a certain PartialView class, each with different data.
Comment: Create a DTO with two properties: string ControlName and object Data then create the list of those and in the loop use RenderPartial(ControlName, Data); to pass the control-specific data.
Answer: Or you can get slicker and wrap the above suggestion in an extension method to your ViewPage class an extension method if you need other functionality.


Nested loop over combination

Question: Iterating over combinations doesn't give the expected number of iterations. To illustrate my problem:
import itertools

combinations = itertools.combinations(range(10), 1) # The combination has 10 elements

# Test1
count = 0
for c1 in combinations:
    for c2 in combinations:
        count += 1
print("Test1:", count)

# Test2
combinations1 = itertools.combinations(range(10), 1)
combinations2 = itertools.combinations(range(10), 1)

count = 0
for c1 in combinations1:
    for c2 in combinations2:
        count += 1
print("Test2:", count)

# Test3
combinations1 = list(itertools.combinations(range(10), 1))
combinations2 = list(itertools.combinations(range(10), 1))

count = 0
for c1 in combinations1:
    for c2 in combinations2:
        count += 1
print("Test3:", count)

I'm iterating over a combination of 10 elements. With a double nested loop, I would expect 100 iterations (10x10). However, I get the following results:
Test1: 9
Test2: 10
Test3: 100

I can understand that Test1 does not work correctly, since I'm using the same object for both loops. However, I would expect both Test2 and Test3 to yield the same results since the only difference is that I converted the iterator objects to lists first in Test3.
I would really appreciate any explanations regarding this issue. I'm using Python 3.8.2 with Ubuntu 20.04.
Answer: In the second case, you can only iterate combinations2 once. This can be demonstrated by adding some prints in:
count = 0
for c1 in combinations1:
    print("Outer")
    for c2 in combinations2:
        print("inner")
        count += 1
print("Test2:", count)

Outer
inner
inner
inner
inner
inner
inner
inner
inner
inner
inner
Outer
Outer  <-- Noteworthy
Outer
Outer
Outer
Outer
Outer
Outer
Outer
Test2: 10

combinations returns an iterator, and an iterator can only be iterated once. If you try to call next on it after it's exhausted, it'll still be exhausted.
Your third example works because it's lists that are being iterated. When you iterate a list, iter(a_list) is implicitly called, which creates a new iterator each time. Contrast that with iter(an_iterator) that evaluates to itself; not a new iterator.

Nested loop over combination