Customized Paging With Repeater And SQL

Question: I've been looking for a good tutorial to teach me how to make a customized Paging control with a simple DataBound control like Repeater to implement a high performance paging feature.
I've found a lot of articles about that issue, but non of them was a complete answer.

Paging of Large Resultsets in
ASP.NET
This one is awesome, with statistics    and great comparison between the    different methods of doing so, but    the problem is it's too old before    SQL Server had it's new function    ROW_NUMBER()
N-Layered Web Applications with
ASP.NET 3.5 Part 4: Sorting, Paging
and Filtering (The Database Paging
Section and ignore the rest)
This one is almost perfect, but he used the grid's existing paging feature with a customized Method for paging, instead of a repeater.
Custom SEO friendly paging with
ASP.NET Repeater or DataList
control
I think this one is WAY too complicated, and things can get done easier

I'm using SQL, Items Repeater (with direct binding in the code-behind with no datasources used), PageNumbers repeater (which will have a link as an ItemTemplate to pass querystring so the used method could retrieve the next portion of Items), A Label to hold the current page number and title.
I've been trying to implement the example on N-Layered Web Applications with ASP.NET 3.5 Part 4: Sorting, Paging and Filtering (The Database Paging Section and ignore the rest). So far I've created a SQL command in my Data Access Lyaer that looks like this :
WITH Records AS ( SELECT ItemId, ItemName, ROW_NUMBER() OVER (ORDER BY ItemId) AS 'RowNumber' FROM   Items)  SELECT * FROM Records WHERE (RowNumber BETWEEN (@startIndex) AND @startIndex + @pageSize - 1)

but now I'm stuck on how to use it in my presentation layer!
Comment: Looking at your last sample, what issues are you facing implementing it? It needs a method with the id,startindex and pagesize.
Comment: Paging in a repeater is something I've had to teach people in the last 4 job's I've had, there's no good articles on using repeaters, think I'm gonna make it my next blog post.
Comment: @gbs- the repeater which will let me navigate through the pages is my problem. and to be exact I don't know what value should be assigned to the startIndex parameter and how!
Comment: Phill - That would be great! I hope it would be sometime soon and please share it with us when you're done.
Comment: @lKashef - I can't do it till start of feb, got a deadline on a project for feb 1st. Will post a comment here with the link when I've done it.
Comment: @Phill- fair enough =) good luck and waiting for your post.
Answer: You can create a custom method to render your own pagination control. Here is an example:
    ///
    /// Produces html for a pagination control.
    ///
    /// <param name="page">Page number for the current page (1-based index).</param>
    /// <param name="pageSize">Number or items per page.</param>
    /// <param name="totalItems">Total number of items across all pages.</param>
    /// <returns>Html of a pagination control.</returns>
    public string RenderPaginationControl(int page, int pageSize, int totalItems)
    {
        int totalPages = (int)Math.Ceiling((double)totalItems/pageSize);

        // Create pager.
        StringBuilder pagerSb = new StringBuilder();
        for (int i = 1; i <= totalPages; ++i)
        {
            // If it is NOT a link to current page.
            if (i != page) { pagerSb.Append(string.Format("{0}", i)); }
            // If it is the link to current page.
            else { pagerSb.Append(string.Format("{0}", i)); }
        }

        return pagerSb.ToString();
    }

As you can see apart from your sql, you will also need to call
SELECT COUNT(*) FROM Items

and pass that value to totalItems in the RenderPaginationControl.
And as far as the binding to Repeater is concerned - it's pretty straight forward:
this.MyRepeater.DataSource = DAL.GetItems(page, pageSize);
this.MyRepeater.DataBind();

int totalItems = DAL.GetTotalNumberOfItems();
this.PaginationLabel.Text = RenderPaginationControl(page, pageSize, totalItems);

Comment: @niaher- there's a small bug in the code in the GetItems method. It's not taking a parameter to save the startPageIndex...I don't know how to make it clear to you, but what's missing is a variable that will be the new offset (@startIndex) for my sql query to select a new portion of items for another given page
Comment: @niaher- I solved it by add a "start" QueryString argument to the url and added a variable "startIndex" to the method and incremented it by the pageSize (startIndex += pageSize)...but I wonder if the (StringBuilder+Label) as a paging navigator are better than a repeater.   and last question! I want to use Ajax and Anchors won't let me do it, so I need to use a Server Control instead like a LinkButton to cause a postBack and let my Ajax works! any ideas ?...Marked as answer btw, Thank you =D
Comment: I don't really see why you need the "startIndex" parameter inside the GetItems method. You already know which page you will need for any future requests from the "page" parameter inside each link e.g. - data.aspx?page=2.
Comment: As for using AJAX - I am not sure, but you can try to have a  and add controls to it, e.g. - MyPlaceHolder.Controls.Add(new LinkButton(???)).
Comment: @niaher- "WHERE (RowNumber BETWEEN (@startIndex) AND @startIndex + @pageSize - 1)" the query need to know where a given page will start from. for example if the page size is 4, then page one start will be 1 and page 2 start will be 5 and page 3 start will be 9, etc
Comment: You have to calculate startIndex inside the DAL.GetItems method (or even better if you do that inside your stored procedure). Formula is startIndex = page * pageSize + 1.

Customized Paging With Repeater And SQL


How can I get file field url in drupal 7 from views of its content type?

Question: It has been a few days I'm trying to get the uploaded file urls in drupal7 (using default file filed in drupal content type) from a view. I must get this url in page which a view is embedded inside it, this view shows 10 items of its content type per page, how can I get the url of filefield?
should I use preprocess function or any thing else?
I have tried many ways suggested in many websites but I have failed. is there any straight forward solution?
Answer: It's not really clear what you mean by 'access' in this context, but if you're looking to get the details for a file uploaded through a file field:
$node = node_load(1);
if ( ($field_items = field_get_items('node', $node, 'field_file')) ) {
  $file = file_load($field_items[0]['fid']);

  $uri = $file->uri;
  $external_url = file_create_url($uri);
}

Or to grab the external URL directly with an EntityMetadataWrapper:
$node = node_load(1);
$wrapper = entity_metadata_wrapper('node', $node);
$external_url = $wrapper->field_files[0]->file->url->value();

Comment: I'm afraid your deadlines are irrelevant here - this is a Q+A site, the mission is to build a site full of high quality content, not to do people's job for them within a certain time constraint. I disagree that your question is clear; I can't understand it, and I've been developing in Drupal for over 3 years and speaking English for over 30. You haven't describe the context in which you need to 'get' the value, what you need to do with it, or shown that you've made any effort to solve the problem yourself. I'd advise improving the question considerably, but that is your prerogative, of course.
Comment: where should I use this code?
Comment: Wherever you want/need to use it, there's no specific place for it to go
Comment: can I use it in views-view-field template function ?
Comment: Well don't put it in the template file (it'll cause havoc with caching), but in a preprocess function, sure
Comment: what if I don't use node page? I mean I'm trying to get file url in a page which a view is embedded inside it. this view shows 10 items of a certain content type which has file field. then in what preprocess function I must use it?
Comment: Sorry you've lost me, I don't understand what you mean. Your question doesn't mention views at all
Comment: So I edit it, Im trying to get it in views
Comment: Still haven't got a clue what you mean, sorry. As this answers the original question I'll leave it here, might be useful for a future visitor. Please don't edit the question any further, if you need to significantly change the scope of what you're asking, just ask a new question. Thanks
Comment: This is part of my project and I must complete it as soon as possible. the question is clear: I have a content type and one of its fields is File. I created a view of this content type that shows 10 items per page. this view shows some of the fields and one of them is Filefields. now I need to get the filefields url, that's all. thanks for your attention
Comment: I changed the formatter of file to `URL to file` in views administrative menu and then by this code ` strip_tags($fields['field_file']->content);` I got the url.
Comment: From a module I was able to use it but I had to change this line `$external_url = $wrapper->field_files[0]->file->url->value();` to  `$external_url = $wrapper->field_files->file->url->value();`
Answer: change the Formatter of file to URL to file in views administrative menu and then by this code strip_tags($fields['field_file']->content); you will get the url
Comment: This is right. But in order for the 'URL to file' option to appear, you must enable the image_url_formatter module (https://drupal.org/project/image_url_formatter)
Comment: @Druvision I didnt enable this module and it still working
Comment: In the end I did enable this module and it's still not working. Too many modules.


Como chamar um método dentro da classe?

Question: Estou tentando chamar o método que retorna um unsigned char através de outro método da mesma classe, revirei a internet toda mas não entendi como fazer isso.
byte CryrazCore::*ComputeByteArray(byte inputData[], bool decryptMode)
{
    int cs = this->CryrazCore::PushChecksum();
}

O método que estou tentando chamar se chama CryrazCore::PushChecksum(), eis a declaração dele:
// CryrazCore.cpp
byte CryrazCore::PushChecksum()
// CryrazCore.h
byte PushChecksum();

Aqui é o que diz no erro, na linha do primeiro código da pergunta.

'this': can only be referenced inside non-static member functions or non-static data member initializers

Onde estou errando para chamar a função?
Comment: O que seria esse asterisco em `::*`? Se fosse para tornar um ponteiro para `byte` ele não deveria estar junto ao tipo? E se o retorno do método é `byte`, por quê a variável `cs` é do tipo `int`?
Comment: Como disse, sou novo. Não sei de quase nada nessa linguagem, coloquei o `::*` com esperança de ser uma chamada "estática", mas acho que tá tudo errado kkk
Comment: O ponteiro `*byte` seria mesma coisa de `ref byte` em C#, não?
Answer: Esse código nem compila por outros motivos também. Provavelmente ele seria assim:
byte *CryrazCore::ComputeByteArray(byte inputData[], bool decryptMode) {
    int cs = this->PushChecksum();
    //deveria usar os parâmetros
    return alguma coisa que seja um ponteiro para byte;
}

Coloquei no GitHub para referência futura.
Tem que decidir se usa this-> ou CryrazCore::, ambos não dá. O primeiro chama a instância, que parece ser o caso, o segundo chama um membro estático.
Procure fazer exemplos mais simples antes de começar fazer os mais complexos.
Comment: Isso, e qual o problema?
Comment: O retorno de `PushChecksum` é do tipo `byte`, mas `cs` está como `int`. Esse *cast* seria possível? Se sim, seria porquê o tipo `byte` é menor que `int` ou uso não tem relação?
Comment: @AndersonCarlosWoss o retorno é `byte*`, o *cast* é possível, falando de forma geral, C/C++ tem uma especificação complicada para atender todas arquiteturas, mas improvável que seja essa a intenção. O resto ficou sem sentido porque você partiu de uma informação errada. É possível porque na prática um ponteiro geralmente pode ser representado por `int`, embora não valha para todas arquiteturas. O código todo está muito errado e faz pouco sentido.
Comment: O método `ComputeByteArray` retorna o ponteiro, mas `PushChecksum` parece que não. Corrija-me se eu estiver errado, por favor.
Comment: Não sei. É que questionei se o retorno byte poderia ser armazenado no int sem problemas. Você disse que sim, porque geralmente o ponteiro pode ser armazenado no int, mas o retorno é por valor, não um ponteiro. Isso não influencia?
Comment: Isso eu nem sei dizer porque não conheço o tipo `byte` iso deve ser uma definição do código, não faz parte do C++. O retorno deve ser um ponteiro, ele deve ter colocado o ponteiro no lugar errado, geralmente é um ponteiro. Eu imagino que esse `byte` na verdade seja um `char` internamente, e é raro retornar isso. Se nada disso for verdade, o AP tem que dizer. Só ele entende esse código, eu dei a solução para o problema específico, todos os outros problemas depende do que é o código real, esse exige especulação para corrigir. Até tentei. Por isso que eu disse que nem compila por outros motivos.
Comment: O tipo byte é um `using byte = unsigned char;`.

Como chamar um método dentro da classe?


How to compare two files and print matching in 3rd file using Perl

Question: file1.csv
abc,hello
bac,man
cac,tan

file2.csv
cav,
pan,
bac,
and,
Outfile: The out file should have following as this match to file2.csv
bac
Comment: First try yourself and show us your code. Then we will help you.
Answer: #!C:\Perl\perl\bin\perl.exe

use strict;
use warnings;

my $file1 = "file1.csv";
my $file2 = "file2.csv";

my @a_file1 = &sub_read ($file1);
my @a_file2 = &sub_read ($file2);

foreach my $entry1 (@a_file1) {
    foreach my $entry2 (@a_file2) {
        if ($entry1 eq $entry2) {
            print "$entry1\n";
        }
    }
}

sub sub_read {
    my $file = $_[0];
    my @a_file;
    open (READ,"<",$file) or die "$!";
    while (<READ>) {
        chomp ($_);
        my @a_temp = split(/\,/,$_);
        foreach my $a (@a_temp) {
            push (@a_file, $a);
        }
    }
    close (READ);
    return @a_file;
}

I think this shoudl work.
To print the File simply use something like this:
open (WRITE, ">> $outfile");
print WRITE "$entry1\n";
close (WRITE);

There are plenty of possibilities to this (using a hash).
Comment: Using a hash would reduce the cost to O(N+M) from O(N*M)
Answer: open( FILE2, "file2.csv" );
open( FILE1, "file1.csv" );

while (<FILE1>) {
    my $element1 = $_;
    push( @file1, $element1 );
}

while (<FILE2>) {

    my $element2 = $_;

    if ( grep( /^$element2$/, @file1 ) ) {
        print "$element1 exists in file1.csv \n";
    }

}

Comment: This answer would be much improved if it were edited to include the description. As it stands, comments are transient.
Comment: Initially store the first file contents line based in a array and then to compare each line of second file with each element of the array.comaprision is by grep to check whether $element exists in the array @file1.hope this helps.
Comment: alternatives to using grep are

1) if ("$element1" ~ @file1)
2)if ( any(@file1) eq "$element1" )


Ckeditor and IMCE not working with Plupload

Question: When I use IMCE with CKeditor as a WYSIWYG for my website it works fine:

However when I add the Plupload module which would allow me multiple files selection it breaks!

If this can't be fixed, is there any other alternatives similar to Plupload that I can use with CKeditor?
Answer: Use Insert module instead of IMCE

Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.
Comment: I will give it a try - can you upload multiple files with this? If not I can always just continue using IMCE as it has a much nicer UI
Comment: yes you can upload multiple files
Answer: Check the module IMCE Uploader. It depends on IMCE and Plupload.

Besides that, It also provides the Plupload uploader as a plugin (in
  this module) to allow uploading multiple files at a time. If you want
  to use it, just select "IMCE Uploader - Plupload" the module list and
  enable it


If $\sum a_n$ is convergent , then $\sum {a_n}^2$ convergent.

Question: I found proofs telling that if $\sum a_n$ with $a_n>0$ is convergent (hence absolutely), then  $\sum {a_n}^2$ always convergent.
But what happens if we do not suppose that $a_n>0$?
My guess is that as $a_n \to 0$, $\exists n_0$ such that $\forall n \geq n_0, -\frac{1}{2} \leq a_n \leq \frac{1}{2} \implies 0 \leq a_{n}^2 \leq \frac{1}{2}a_n < a_n$ and conclude with comparison test. Is it right ?
Comment: How are you concluding $0\le a_n^2  0^2$.
Comment: A clumsy multiplication, my bad
Answer: counterexample: $a_n=(-1)^n \cdot \frac{1}{\sqrt{n}}$
Answer: In fact, the only functions $f: \mathbb R \to \mathbb R$ such that $\sum_n f(a_n)$ is convergent whenever $\sum_n a_n$ is convergent are those that are linear in a neighbourhood of $0$.  See here
Comment: What do you mean by linear in a neighborhood of 0 ?
Comment: I mean there are some constants $c$ and $\epsilon$ with $\epsilon > 0$, such that $f(x) = c x$ for $-\epsilon < x < \epsilon$.


Criar uma função de repetição usando dois data frames

Question: Preciso da média de cada variável (x1,x2,x3,x4) de acordo com o mês que ela pertença dados1$mes. O valor dessa média será gravado em (y1,y2,y3,y4) de acordo também com o mês pertencente dados2$mes.
Para x1 será gravado em y1, para x2 em y2 e assim por diante.
Gostaria de uma alternativa mais viável, do que a que fiz abaixo.
dados1 <- data.frame(matrix(NA,nrow = 30, ncol = 5))
colnames(dados1) <- c("mes","x1","x2","x3","x4")

dados1$mes <- c(5,9,7,3,8,2,4,1,6,10,2,11,12,10,12,2,8,9,10,7,6,4,5,7,3,1,9,5,2,6)
dados1$x1 <- c(2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60)
dados1$x2 <- c(3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90)
dados1$x3 <- c(4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120)
dados1$x4 <- c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150)

dados2 <- data.frame(matrix(NA,nrow = 12, ncol = 5))
colnames(dados2) <- c("mes","y1","y2","y3","y4")
dados2$mes <- c(1,2,3,4,5,6,7,8,9,10,11,12)

Criei os contadores para todos os meses:
contador_dias_jan <- 0
somatorio_jan <- 0
contador_dias_fev <- 0
somatorio_fev <- 0
contador_dias_mar <- 0
somatorio_mar <- 0
contador_dias_abr <- 0
somatorio_abr <- 0
contador_dias_mai <- 0
somatorio_mai <- 0
contador_dias_jun <- 0
somatorio_jun <- 0
contador_dias_jul <- 0
somatorio_jul <- 0
contador_dias_ago <- 0
somatorio_ago <- 0
contador_dias_set <- 0
somatorio_set <- 0
contador_dias_out <- 0
somatorio_out <- 0
contador_dias_nov <- 0
somatorio_nov <- 0
contador_dias_dez <- 0
somatorio_dez <- 0

Aqui esta somente para janeiro e fevereiro, mas teria o "if else" até dezembro.
for (L in 1:30) {
  #para janeiro
  if (dados1$mes[L] == 1) {
    contador_dias_jan <- contador_dias_jan + 1
    somatorio_jan <- somatorio_jan + dados1$x1[L]
    #para fevereiro
  } if else (dados1$mes[L] == 2) {
    contador_dias_fev <- contador_dias_fev + 1
    somatorio_fev <- somatorio_fev + dados1$x1[L]
  }
}

for (L in 1:12) {
  #para janeiro
  if (L == 1) {
    dados2$y1[L] <- somatorio_jan / contador_dias_jan
    #para fevereiro
  } else if (L == 2) {
    dados2$y1[L] <- somatorio_fev / contador_dias_fev
  }
}

Da forma que está, seria somente para preencher y1. Falta ainda y2, y3 e y4. Alguma sugestão?
Answer: De maneira geral, não é nem necessário nem recomendável usar loops em R; a família apply é mais eficiente. No caso de operações por grupo, combine com o uso de split:
# Separa os dados por mês
dadosL <- split(dados1, dados1$mes)

# Calcula as médias por colunas para todos os elementos da lista:
dadosM <- lapply(dadosL, colMeans)

# Une os elementos da lista de volta em um único data.frame
dadosF <- do.call("rbind", dadosM)

head(dadosF, 4)
#>   mes x1   x2 x3   x4
#> 1   1 34 51.0 68 85.0
#> 2   2 31 46.5 62 77.5
#> 3   3 29 43.5 58 72.5
#> 4   4 29 43.5 58 72.5

Os pacotes dplyr e data.table automatizam operações do tipo split/apply:
dplyr
library(dplyr)

dados1 %>%
  group_by(mes) %>%
  summarise_all(mean)

data.table
library(data.table)

setDT(dados1) # estabelece dados1 como classe data.table

dados1[, lapply(.SD, mean), mes]

Comment: Obrigada pela orientação @Carlos Eduardo Lagosta. Me auxiliou muito! Irei buscar mais por esses pacotes utilizados em sua resposta.


show numbers (mod $p$) are distict and nonzero

Question: Let's start with the nonzero numbers, mod $p$,
$1$, $2$, $\cdots$, $(p-1)$,
and multiply them all by a nonzero $a$ (mod $p$).
Notice that if we multiply again by the inverse of $a$ (mod $p$) we get back the numbers
$1$, $2$, $\cdots$, $(p-1)$.
But my question is how the above process show that the numbers
$a\cdot 1$ mod $p$, $a\cdot 2$ mod $p$, $\cdots$, $a\cdot (p-1)$ mod $p$
are distinct and nonzero?
Thanks in advance.
Comment: Have your proved $\Bbb Z_p$ is a field for $p$ prime? Since $a$ is invertible, in particular it is non-zero. Moreover, since it is invertible you can show the map $x\mapsto ax$ is actually a bijection, in fact, an isomorphism. This is true in general when $a$ is invertible $\mod n$, but $\Bbb Z_p$ is a field only if $p$ is prime.
Comment: The key idea in the **process** is that if $ax=ay$, then also $a^{-1}(ax)=a^{-1}(ay)$. But associativity of multiplication and the fact $a^{-1}a=1$ then imply that $x=y$. So we cannot have $ax=ay$ without $x=y$. Nor can we have $ax=0=a\cdot0$ without $x=0$.
Answer: Suppose that $1\le x\lt y\le p-1$.
If $ax\equiv ay\pmod{p}$ then $p$ divides $a(y-x)$. But $a$ and $p$ are relatively prime. So $p$ divides $y-x$. This is impossible, since $1\le y-x\lt p$.
None of the $ax$ is congruent to $0$ modulo $p$. For if $p$ divides $ax$, then $p$ divides $a$ or $p$ divides $x$. But $p$ does not divide $a$ by the choice of $a$. And $p$ does not divide $x$ since $1\le x\le p-1$.
Remark: Or else one can use multiplication by $a^{-1}$. The $ax$ must be distinct modulo $p$. For if $ax\equiv ay\pmod{p}$ then multiplying by $a^{-1}$ we find that $x\equiv y\pmod{p}$.  Since $x$ and $y$ are between $1$ and $p-1$, it follows that $x=y$.
It is easy to verify that none of the $ax$ is congruent to $0$ modulo $p$, else multiplying by the inverse would yield $0$.
So the $ax$ are distinct non-zero modulo $p$. There are $p-1$ of them. There are also $p-1$ possible values of $x$. So the $ax$ must be, in some order, congruent to all of the objects $1,2,\dots,p-1$.
Comment: But how do you use the process, which did multiplications by a (mod p) and then the inverse of a (mod p)?
Comment: I did not use the inverse of $a$ mod $p$. I thought "above process" referred to the plain multiplication. But multiplication by $a^{-1}$ also works. The $ax$ must be distinct modulo $p$, for multiplying by $a^{-1}$ yields distinct objects modulo $p$. Can add a remark.
Answer: It is important to point out that $\Bbb Z_p$ is  a field if (and only if) $p$ is prime. This means in particular that every element that is not $0$ has an inverse. Since $p\not\mid a$ is equivalent to $a\not\equiv 0\mod p$, $a$ has an inverse $a^{-1}$. But then $$x\equiv y\mod p\iff ax\equiv ay\mod p$$
since we can reverse the equalities by multiplication by $a$ or $a^{-1}$. Moreover, since $p\not\mid a$ and $p\not\mid x$ (by assumption), $p\not\mid ax$, that is $$a\not\equiv 0,x\not\equiv 0\implies ax\not\equiv 0$$
Answer: The set you are considering is really a field: $\mathbb{Z}/p\mathbb{Z}$. Since it is a field, it is closed under multiplication, therefore when you multipliy them by a nonzero element $a$, all of them are distinct and nonzero (but they are somehow permuted)


Ambigous use of 'init(CIImage:)'

Question: I have an error - Ambigous use of 'init(CIImage:)' on the last line. Can anyone help me fix it?
let origImage = CIImage(image: img)
let filter = CIFilter(name: "CIColorInvert")
filter?.setValue(origImage, forKey: kCIInputImageKey)
let invertedImage = UIImage(CIImage: (filter?.outputImage)!)

Comment: possible duplicate of https://stackoverflow.com/q/43528115/2303865
Answer: In Swift 3, UIImage(CIImage: ...) constructor was renamed to:
let invertedImage = UIImage(ciImage: ...)

Ambigous use of 'init(CIImage:)'


Does using count data as independent variable violate any of GLM assumptions?

Question: I would like to employ count data as covariates while fitting a logistic
regression model. My question is:

Do I violate any assumption of the logistic (and, more in general, of the
generalized linear) models by employing count, non-negative integer
variables as independent variables?

I found a lot of references in the literature regarding hot to use count
data as outcome, but not as covariates; see for example the very clear
paper: "N E Breslow (1996) Generalized Linear Models: Checking Assumptions
and Strengthening Conclusions, Congresso Nazionale Societa Italiana di
Biometria, Cortona June 1995", available at
http://biostat.georgiahealth.edu/~dryu/course/stat9110spring12/land16_ref.pdf.
Loosely speaking, it seems that glm assumptions may be expressed as follows:

iid residuals;
the link function must correctly represent the relationship among dependent
and independent variables;
absence of outliers

Does everybody know whether there exists any other assumption/technical
problem that may suggest to use some other type of models for dealing with
count covariates?
Finally, please notice that my data contain relatively few samples (<100)
and that count variables' ranges can vary within 3-4 order of magnitude
(i.e. some variables has value in the range 0-10, while other variables may
have values within 0-10000).
A simple R example code follows:
\###########################################################

\#generating simulated data

var1 <- sample(0:10, 100, replace = TRUE);
var2 <- sample(0:1000, 100, replace = TRUE);
var3 <- sample(0:100000, 100, replace = TRUE);
outcome <- sample(0:1, 100, replace = TRUE);
dataset <- data.frame(outcome, var1, var2, var3);

\#fitting the model

model <- glm(outcome ~ ., family=binomial, data = dataset)

\#inspecting the model

print(model)

\###########################################################

Comment: usually, in GLM models, the predictor ("independent") variables are just supposed to be some known constants, there are __NO__ distributional assumptions about them! So there is nothing wrong in using count data as predictors.
Comment: They are "constants" in the sense that theyb are not random: no distribution. They are "known" in the sense that they are assumed to be measured without error, so the measured value is the one that actually was working in the data generation mechanism. The GLM model assumes that all randomness is in the response mechanism, that is often dubious!
Comment: kjetil That's correct--and a good answer to the question. Yet, with the extreme ranges of IVs described here, one would be wise to evaluate the influence of the data, check goodness of fit, and particularly assess the potential for a nonlinear relationship. This would be done in the hope that the relationship actually *is* nonlinear and that a re-expression of the IVs, such as a root or log, will linearize it, thereby simultaneously relieving some of the influence problems. This is probably what @user14583 is trying to indicate in their answer.
Comment: Welcome to the site! One remark: if you want to sign your posts, use your profile (especially the about me box).
Comment: @kjetilbhalvorsen - I agree on "no distributional assumptions," but I don't think you meant to say "known" or "constants," as neither of those words fits.
Answer: There are some nuances at play here, and they may be creating some confusion.
You state that you understand the assumptions of a logistic regression include "iid residuals... ".  I would argue that this is not quite correct.  We generally do say that about the General Linear Model (i.e., regression), but in that case it means that the residuals are independent of each other, with the same distribution (typically normal) having the same mean (0), and variance (i.e., constant variance: homogeneity of variance / homoscedasticity).  Note however that for the Bernoulli distribution and the Binomial distribution, the variance is a function of the mean.  Thus, the variance couldn't be constant, unless the covariate were perfectly unrelated to the response.  That would be an assumption so restrictive as to render logistic regression worthless.  I note that in the abstract of the pdf you cite, it lists the assumptions starting with "the statistical independence of the observations", which we might call i-but-not-id (without meaning to be too cute about it).
Next, as @kjetilbhalvorsen notes in the comment above, covariate values (i.e., your independent variables) are assumed to be fixed in the Generalized Linear Model.  That is, no particular distributional assumptions are made.  Thus, it does not matter if they are counts or not, nor if they range from 0 to 10, from 1 to 10000, or from -3.1415927 to -2.718281828.
One thing to consider, however, as @whuber notes, if you have a small number of data that are very extreme on one of the covariate dimensions, those points could have a great deal of influence over the results of your analysis.  That is, you might get a certain result only because of those points.  One way to think about this is to do a kind of sensitivity analysis by fitting your model both with and without those data included.  You may believe it is safer or more appropriate to drop those observations, use some form of robust statistical analysis, or to transform those covariates so as to minimize the extreme leverage those points would have.  I would not characterize these considerations as "assumptions", but they are certainly important considerations in developing an appropriate model.
Answer: One thing I would definitely check is the distributional properties of your independent variables. Very often with count data, you'll see some moderate to severe right-skew. In that case, you will likely want to transform your data, as you'll lose the log-linear relationship. But no, using a logistic (or other GLM) model is fine.
Comment: How does right skew lose 'the log-linear relationship'?
Comment: This comment seems incorrect to me. Like @Glen_b, I don't see how this would necessarily lose the log-linear relationship. In any case, it would be better to examine the relationship directly (through plotting, for instance).
Comment: A nonlinear transformation of an IV will definitely change the log-linear relationship to something else, @Peter. This answer seems basically correct to me.
Comment: @whuber I agree that a nonlinear transform of one variable will change the relationship between it and another variable. That seems pretty clear.

But from what sort of relationship to what sort? Why not examine the relationship directly instead of assuming how it will be changed?

Also, the answer seems to say that the person *wants* to lose the log linear relationship.
Comment: That's a good point @Peter. Yet some people *do* want to change the relationship; that's not necessarily a mistaken notion.  I agree that a direct examination is the right procedure: it will suggest how to re-express the IV(s) involved in order to create linear relationships.


Convert Autograd ArrayBox to BigFloat

Question: As said in the title, I want to convert from Autograd ArrayBox to BigFloat.
My function is simple:
def fun(mean, variance, bin_mean, bin_variance):

    first = np.float(bf.sqrt(1.0 * bin_variance / (bin_variance + variance)))

    second_numerator = (bin_mean - mean)**2
    second_denominator = 2*(bin_variance + variance)
    second = np.float(bf.exp(-second_numerator/second_denominator))

    return first * second

and I need high precision and hence I want to use bigfloat package. Now, this function is part of a more complex one for which I'm using scipy.optimize.minimize function for finding the minimum of the function while also using autograd to approximate Jacobian and Hessian matrices.
The error I'm getting when I run my code is
TypeError: Unable to convert argument Autograd ArrayBox with value 0.01297563222656762 of type <class 'autograd.numpy.numpy_boxes.ArrayBox'> to BigFloat

So my question is: how to convert from Autograd's ArrayBox to BigFloat? How to even properly extract the value inside the ArrayBox?
Answer: I did:
myvariable._value
and I got an array with the values inside the ArrayBox, which then I could manipulate.
I figured it out after checking the  attributes of the ArrayBox using call(myvariable). Looks it is not documented anywhere.
Hope it helps

Convert Autograd ArrayBox to BigFloat


Locate rogue DHCP server

Question:
Possible Duplicate:
How do I find if there is a rogue DHCP server on my Network?

I know this is a serious long shot, but here we go.
In the past week or so, for users connected to a particular switch in our network (there are four dumb switches all connected, and it only affects SOME, not all, users on the one switch) are getting DHCP addresses from a rogue DHCP server.
I have physically checked every cable plugged into the switch in question to make sure that none of them have a router or wifi point attached to it. I know the IP of the DHCP server, but I cannot ping it, and it does not have a web interface.
Does anyone have any suggestions on what I can do to locate it or shut it down? Unfortuantely all the switches are unmanaged, and as mentioned, there's no physical device (that I can find) plugged in to anything.
It's getting critical, because it's screwing up the PXE boot of a whole bunch of thin clients.
Comment: Love the tag. :)
Comment: As a side note, DHCP Explorer purports to be able to find rogue DHCP servers: http://www.networksecurityhome.com/network_tools/dhcp_discovery/dhcp_discovery.html
Comment: Interesting. I wish I had known about all these tools days ago! I should have come here first!
Comment: There are very affordable switches around that have a built in rogue DHCP server filter configurable per port. The less than 250 Euro that eg a GS-1224 (The Lancom one, not D-Link) will cost you are probably less than the cost you in the end summed up chasing that rogue down...
Comment: On a different note: There are also some models of LAN print servers that can function as a rogue DHCP, in case somebody finds that question with the same problem in the future...
Answer: Try to nmap it using the -O  to detect the operating system, may give you a better idea of what server it is?  Also running a standard port scan might help figure out what it is
Comment: Ahah! It was a Virtual Machine someone was running on their development machine. nmap had the info I needed in seconds. Brilliant!
Comment: looking at the MAC address to figure out the vendor would also have been a good way of knowing it was a virtual machine.  Glad you got to the bottom of it :D
Comment: The only port open is 67 (or responding at least) :( I hadn't thought of nmap -O though! I'll give it a go
Comment: Wow, how fricking annoying is that. Completely unfindable.
Answer: The fact that you can't ping it isn't a problem.
(This procedure is mostly for managed switches, in the case of your dumb switches, it isn't as helpful, since you can't inspect the cam table... but anyway.)

run ipconfig /all(or look at syslog), note the IP address listed for "DHCP Server".  Generally this is the same as the default gateway.
attempt to ping this ip address, ignore the result.
run arp -a.  The mac address listed for the IP is your rogue DHCP server.

So, in your case, you can't follow this up with locating the switchport and disabling it, but you could have at least looked up the mac address vendor and would have found that the vendor was something like vmware or virtualbox.
If you have a box lying around, you can install https://roguedetect.bountysource.com/ on it, which will notify you if a problem like this occurs in the future.
Comment: Interesting tool. We've got a VMWare ESXi blade centre so I can deploy it on there with little system cost, which would certainly catch this in future. Thanks. (p.s. that site's certificate is expired)
Answer: Well, you can always try to ping the crap out of it and check the blinky lights on the routers. =P
Does traceroute show you anything?
Comment: Hey there's another idea I hadn't thought of. This is why I love ServerFault. Nothing in traceroute as it's all all on the one switched network.
Answer: I know this has already been solved but another means, when you really can't find the machine (knowing it's a VM doesn't tell you what host it's on) is to keep sending it DHCP requests and unplug each cable in turn till it shuts up. Sometimes you just have to get back to crude basics.
Answer: Run Wireshark to get the MAC address of the server. It should at least tell you the manufacturer (MAC addresses are centrally allocated and each manufacturer is allocated a set of addresses).

Locate rogue DHCP server


Is there existing integration between the Salesforce and Location modules?

Question: I'm using the Salesforce module in Drupal 7 and am attempting to create a mapping to one of my content types that contains a Location module field. After looking at both modules, I don't see an existing integration for them.
I tried adding a field mapping for just the street address (the only method available was using a token, so I selected [node:location:street]).  When I kick off the import of salesforce data, I get the following error:
WD Salesforce Pull: Unknown data property [node. Processing failed for entity XXXXXXXXXX
associated with Salesforce Object ID: XXXXXXXXXXXXX

I tried other variations of the token, too, including:
[node:location:street:0]
[node:location:street:?]
Both gave me the same error.
Answer: It's difficult to say what's the exact problem, but I think you could have unmapped property in your configuration.
So please go to /admin/structure/salesforce/mappings and verify all the objects that have the properly set mappings and the tokens are valid.
If this doesn't help, try the following options:

Clear the cache (including memcached).
Check watchdog logs for further info.
Double check your Salesforce mappings again if you didn't miss anything.
Upgrade your Location and Salesforce module to development version just to test.
Look for any existing issues.
Debug the code using xdebug.
Report the issue or bug report on Drupal site against the right module.

You may also try the following related links:

Location - Select User Primary
Support Salesforce attachment sync


Android ad hoc wifi connection but keep internet connection

Question: My application creates a Wi-Fi connection to a sensor but this means that the user will have no connection to the Internet as long as he is connected to this peripheral.
I've already read that it is not possible to have two wifi connection without rooting the device.
I guess I've already read all posts on stack overflow concerning this topic but all of them are quite old.
It would be ok if I could use at least the mobile network for Internet so that the user is able to use the browser or other applications while connected.
I tried to set the preferred network but this is not working.
<code>  try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (forceMobile) {
            connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
        } else {
            connectivityManager.setNetworkPreference(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
        }
    } catch (Exception exc) {

    }
</code>
Answer: If connected to another sensor over wifi . You still wont be able to connect to internet through mobile data as at a time only one of the two interfaces can be connected in most of devices(There  might be some exceptions). The best way to achieve this if you could connect to the sensor using bluetooth and stay connected to internet over wifi or mobile data .Since bluetooth and mobile data or Wifi can stay connected in parallel.


Drag and drop a view

Question: I am trying to drag and drop a button on the screen.i can drag but when i drop the following error takes place.
Logcat:
12-05 15:03:00.905: E/AndroidRuntime(1009): java.lang.IllegalArgumentException: Given view not a child of com.avigma.learning.DragLayer@44f5eda0
12-05 15:03:00.905: E/AndroidRuntime(1009):     at android.view.ViewGroup.updateViewLayout(ViewGroup.java:1876)
12-05 15:03:00.905: E/AndroidRuntime(1009):     at com.avigma.learning.DragLayer.onDrop(DragLayer.java:131)
12-05 15:03:00.905: E/AndroidRuntime(1009):     at com.avigma.learning.DragController.drop(DragController.java:447)
12-05 15:03:00.905: E/AndroidRuntime(1009):     at com.avigma.learning.DragController.onTouchEvent(DragController.java:424)
12-05 15:03:00.905: E/AndroidRuntime(1009):     at com.avigma.learning.DragLayer.onTouchEvent(DragLayer.java:69)

xml:-
<?xml version="1.0" encoding="utf-8"?>
<com.avigma.learning.DragLayer
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:launcher="http://schemas.android.com/apk/res/com.android.launcher"

    android:id="@+id/drag_layer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

  <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
       android:src="@drawable/b" />

  <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_x="-4dp"
      android:layout_y="2dp" >

      <AbsoluteLayout
          android:id="@+id/ll"
          android:layout_width="match_parent"
          android:layout_height="match_parent" >

   //This button i am dragging and dropping
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="84dp"
    android:layout_y="90dp"
    android:background="@null"
    android:text="B"
    android:textColor="#000000"
    android:textSize="35dp"
    android:textStyle="bold"
    android:typeface="serif" />

</AbsoluteLayout>

  </ScrollView>

</AbsoluteLayout>
</com.avigma.learning.DragLayer>

I think i have to update the current view of movable object bcoz its refrencing drag layer its parent view but in my xml button current view is absolute layout.this error is in onDrop().I am providing its code:-
 private boolean drop(float x, float y) {

    final int[] coordinates = mCoordinatesTemp;
    DropTarget dropTarget = findDropTarget((int) x, (int) y, coordinates);

    if (dropTarget != null) {
        dropTarget.onDragExit(mDragSource, coordinates[0], coordinates[1],
                (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
        if (dropTarget.acceptDrop(mDragSource, coordinates[0], coordinates[1],
                (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo)) {

            dropTarget.onDrop(mDragSource, coordinates[0], coordinates[1],
                    (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
            mDragSource.onDropCompleted((View) dropTarget, true);
            return true;
        } else {
            mDragSource.onDropCompleted((View) dropTarget, false);
            return true;
        }
    }
    return false;
}

please help that what should i do to overcome this issue..or how to handle that button should not refrence drag layer its current parent view but absolute layout..I know whats the problem that either(1) move everything under one ViewGroup so all the movable views have the same parent view; (2) arrange to change the parent view of the view being moved when that view is dropped. But today I think I'd try what I suggested above: (3) in the view that is accepting the drop, make a copy of the view being dragged. Attach the copy as a child of that view. Go back to the original view and remove it from its parent.But how to code that to fix it please assist me...thanx..
Answer: Simply use this method:
public interface DropListener {

/**
 * Called when an item is to be dropped.
 * @param from - index item started at.
 * @param to - index to place item at.
 */
void onDrop(int from, int to);
}

You can see here. And, let you can know more detail.

Drag and drop a view


Hibernate Select query with a critera

Question: Here i am creating a hibernate query. The query is for selection of some ID form a table, as i want to add the criteria that have a not equal to and a equal to condition.The given query always return a unique value..
        how can i build the query in hibernate using criteria
ID | ST_NAME| EDU_ID
 1 STD E1

 2 STU E1

 3 STD E2

 4 STV E2

select ID from Table where EDU_ID = E1 and ST_NAME <>STD;

how can i make the query in hibernate?
Result i want is 2
Answer: First of all you need to create the Entity student. Then you can use the entity in Criteria API to get the desired results
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.eq("eduId", "E1");
criteria.add(Restrictions.ne("name", "STD");
Student result = criteria.uniqueResult();

Answer: With HQL: query seems like this:
select s.id from Student s where s.name!=? and s.edu=?

You have to pass student name and edu as parameter. If you are using Criteria API, Pratik's answer seems right.
Comment: select s.ID from table  where ug.testID =:testID and checkID !=checkID its not working properly.could u plz check with my query
Answer: I got the result at last. its working perfectly with not equal to checking
select stuID from Table T where T.eduID =:eduID and stuName !=:stuName

Hibernate Select query with a critera


Recebendo Json array em PHP

Question: Estou com o seguinte código no lado da aplicação:
function enviaMensagem() {
    var send = "http://appchat.host56.com/mensagem.php?jsoncallback=?";
$.post( send, {"table": [{"d":1, "p":1, "m": "1"},{"d":2, "p":2, "m": "2"},{"d":3, "p":3, "m": "3"}]}, function( data ) {}, "json");

}

No lado do servidor eu tenho o seguinte código:
$jsonObj = json_decode($json, true);
$table = $jsonObj->table;
foreach ( $table as $e ) {
\\aqui eu gravo o resultado em um BD
}

Quando eu passo apenas uma cadeia de dados, sem ter um table, eu consigo manipular ex:
 $.post( send, {"d":1, "p":1, "m": "1"}, function( data ) {}, "json");, mas passando um table não.
Como faço para pegar os dados table[0]['d']?

Lado da aplicação

Recebendo Json array em PHP


How to add a javascript function after uploading file

Question: I make a form using FAPI, and this form contains a file managed field. I want to show an alert after uploading the file ("uploaded successfully"), and a confirmation ("Are you sure you want to delete file") when deleting the file.
This my code.
$form['my_file_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Files'),
  '#default_value' => variable_get('my_file_fid', ''),
  '#upload_location' => 'public://',
);

I tried to add #file_value_callbacks, but I don't know how to use it.
I tried to make a javascript just to alert when I click upload,remove button but it doen not work I tried to make it general to all input to check that js is correct now all inputs are clickable but upload and remove button not
jQuery(document).ready(function() {
         jQuery('input').bind('click',function() { alert("hi") });
 });

I make this js to check jquery ajaxSuccess function
Answer: You could just bind something to the jQuery ajax success event on the page where your form is displayed.
You can bind ajaxSuccess to any jQuery object, try something like this if you're experimenting:

Comment: I don't know how,file_manged field have upload button by default and its have ajax function how can I bind something to it and i don't know where the success function
Comment: I can't teach you how to use jQuery and bind functions to events in javascript but the documentation for the function I'm talking about is here - http://api.jquery.com/ajaxSuccess/
Comment: it is not a problem to bind jQuery event to a control I tried bind click to upload button but it does not accept any thing i tried this jQuery(document).ready(function() {
  jQuery('input').bind('click',function() {
  alert("hi")
 });
}); all input in the form have alert except the upload and remove button
Comment: @Ahmed Try editing your question with the jquery that you tried. It will add some clarification to some of the things you have done in search of the answer. It will also bump up your question giving it a better chance to be answered.
Comment: The upload form is being changed via AJAX isn't it? That means if you bind an event to that element, you lose the binding when the element is overwritten. I'm suggesting that you bind something to the ajaxSuccess event which happens for the whole document. I'll update my response with an example.
Comment: @Mr.Black please don't edit the source code in question. Comment or answer instead.
Answer: Hope this will help, use hook_file_presave inside that you can use drupal set message.
/**
 * implementing hook_node_presave
 */
function mymodule_file_presave($file) {
//dpm($file);
//
 if (isset($file->source) && $file->source=='field_preview_image_file_und_0')//make condition like this for ur file
{
//use the drupal set message or java script alert  on successful upload
drupal_add_js(drupal_get_path('module','mymodule') . '/test.js');
}
}

create a js file on same module folder as test.js
(function ($) {
$(document).ready(function(){
alert('this is alert message');
});
})(jQuery);


Como posso melhorar esse código?

Question: Estou apredendo java e encontrei esse desafio porem ao terminar achei que o código ficou muito poluido porem não consigo pensar no modo de melhorar, acredito que usando POO seria bem mais fácil porem não posso usar. Como posso deixar esse código mais "limpo"?
/*Uma academia deseja fazer um senso entre seus clientes para descobrir o mais alto, o mais baixo, a mais gordo e o mais magro, para isto você deve fazer um programa quepergunte
a cada um dos clientes da academia seu código, sua altura e seu peso. O final da digitação de dados deve ser dada quando o usuário digitar 0 (zero) no campo código. Ao encerrar
o programa também deve ser informados os códigos e valores do clente mais alto, do mais baixo, do mais gordo e do mais magro, além da média das alturas e dos pesos dos clientes*/

package Exercício062;

import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);

        //Varaáveis
        int id = 0;
        double altura = 0;
        double peso = 0;

        //Primeiros valores
        //ID
        System.out.printf("ID: ");
        id = read.nextInt();
        //Altura
        System.out.printf("Altura: ");
        altura = read.nextDouble();
        //Peso
        System.out.printf("Peso: ");
        peso = read.nextDouble();

        //Colocações
        int id_gordo, id_magro, id_alto, id_baixo;
        id_gordo = id_magro = id_alto = id_baixo = id;
        double peso_gordo = peso;
        double peso_magro = peso;
        double alt_alto = altura;
        double alt_baixo = altura;

        while(id != 0){
            System.out.printf("ID: ");
            id = read.nextInt();
            if(id == 0){
                break;
            }
            System.out.printf("Altura: ");
            altura = read.nextDouble();
            System.out.printf("Peso: ");
            peso = read.nextDouble();

            if(peso > peso_gordo){
                id_gordo = id;
                peso_gordo = peso;
            }
            if(peso < peso_magro){
                id_magro = id;
                peso_magro = peso;
            }
            if(altura > alt_alto){
                id_alto = id;
                alt_alto = altura;
            }
            if(altura < alt_baixo){
                id_baixo = id;
                alt_baixo = altura;
            }
        }

        System.out.printf("O mais gordo é o: " + id_gordo + "\nO mais leve é o: " + id_magro + "\nO mais alto é o: " + id_alto + "\nO mais baixo é o: " + id_baixo);
    }
}

Comment: Para um exercício está bom, para um caso real precisaria de muito mais informação para dizer o que pode ser melhor. O resto é praticamente questão de estilo e detalhes pouco importantes para o estágio atual de aprendizado.
Comment: @hkotsubo desculpe, estou conhecendo o stack agora, marquei como correta novamente, extremamente interessante essa função MAX e MIN_VALUE, sua resposta me ajudou muito e entendi muito bem a logica do código e as dicas, obrigado
Answer: Sem saber os requisitos é difícil afirmar o que seria o "certo" ou mais adequado, mas em linhas gerais, dá para sugerir algumas coisas.

Se vc faz o break quando o id for zero, não precisa testar essa condição novamente no while (pois break interrompe o loop imediatamente), então poderia fazer while (true).
Além disso, não precisa repetir a leitura dos dados antes do loop e dentro dele. Talvez você tenha feito isso para iniciar o loop com as variáveis que guardam os valores mínimos e máximos, mas não precisa disso. Uma opção é inicializar o valor mínimo com o maior valor possível (pois assim qualquer coisa que for digitada será menor que ele), e o máximo com o menor valor possível.
E se está usando printf, aproveite as opções de formatação que este método disponibiliza, em vez de concatenar strings. E onde não precisa imprimir variáveis, pode usar simplesmente print, que não pula a linha ao final.
Por fim, a convenção de nomenclatura em Java não recomenda o snake_case para nomes de variáveis, e sim o camelCase:
Scanner read = new Scanner(System.in);

int idGordo, idMagro, idAlto, idBaixo;
idGordo = idMagro = idAlto = idBaixo = 0;
double pesoGordo = Double.MIN_VALUE;
double pesoMagro = Double.MAX_VALUE;
double altAlto = Double.MIN_VALUE;
double altBaixo = Double.MAX_VALUE;

while (true) {
    System.out.print("ID: ");
    int id = read.nextInt();
    if (id == 0) {
        break;
    }
    System.out.print("Altura: ");
    double altura = read.nextDouble();
    System.out.print("Peso: ");
    double peso = read.nextDouble();

    if (peso > pesoGordo) {
        idGordo = id;
        pesoGordo = peso;
    }
    if (peso < pesoMagro) {
        idMagro = id;
        pesoMagro = peso;
    }
    if (altura > altAlto) {
        idAlto = id;
        altAlto = altura;
    }
    if (altura < altBaixo) {
        idBaixo = id;
        altBaixo = altura;
    }
}
System.out.printf("O mais gordo é o: %d\nO mais leve é o : %d \nO mais alto é o: %d\nO mais baixo é o: %d\n", idGordo, idMagro, idAlto, idBaixo);

Claro que sempre dá para melhorar mais, como por exemplo verificar se o id se repete (pode? não pode?), se os valores digitados são números válidos (se não digitar um número, dará erro, e Scanner tem algumas pegadinhas que podem acontecer), verificar faixas de valores (entendo que peso e altura não podem ser negativos, por exemplo), e por aí vai. Se os valores serão usados posteriormente, poderia usar uma estrutura (array ou List, por exemplo), etc.
A outra resposta (que foi apagada) chegou a sugerir recursão, mas sinceramente, não faz o menor sentido para esse caso. Se quiser entender melhor, leia aqui, aqui e aqui.

Como posso melhorar esse código?


iOS: Referencing Core icons ex: search magnifying glass?

Question: Is it possible to reference the iOS core icons? For example, I want to place an Image View that has the search magnifying glass in it.
Answer: You cannot reference them directly, but you can extract the graphics from the simulator and use them in your app. See the UIKit Artwork Extractor on github. Run the app in both retina and non-retina simulators and dump out all the iOS graphic files.


Concatenação em função verifica

Question: $linkBloquear = '
  getIdProdutos() . '"
      onclick="return verifica(' . $mensagemBloquear . ');"
   >
' . $imagemBloquear . '
';

Postei dessa forma para que facilite a visualização.
Estou co,m problemas na função verifica
Da forma que está
(' . $mensagemBloquear . ')

Vai sair algo como:
return verfica (Tem mesmo que verificar?)

E vai dar erro;
Tentei:
(\"' . $mensagemBloquear . '\")

e sai algo como:
return verfica (\Tem mesmo que verificar?\)

Como corrijo isso?
Answer: Em JavaScript tens 3 marcadores de String, usa string template "`".
onclick="return verifica(`' . $mensagemBloquear . '`);"

Answer:
Use algo do tipo, use essa forma de concatenar.

$linkBloquear = "Teste";

Answer: O problema estava na colocação das aspas aqui:
onclick="return verifica(\'' . $mensagemBloquear . '\');"

Ao invés de colocar aspas simples escapadas estava colocando aspas duplas:
onclick="return verifica(\"' . $mensagemBloquear . '\");"

Concatenação em função verifica


Entity Framework + Fluent API + Web API?

Question: Estou com problemas para mapear a categoria dentro de um produto, quando listo os produtos a categoria (virtual class) vem vazia, mesmo com CategoryId preenchido.
Product
public class Product
{
    public Product()
    {
        this.LastUpdate = DateTime.Now;
    }

    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
    public DateTime LastUpdate { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    public override string ToString()
    {
        return this.Title;
    }
}

Product Map
public class ProductMap : EntityTypeConfiguration<Product>
{

    public ProductMap()
    {
        ToTable("Product");
        HasKey(x => x.Id);
        Property(x => x.Title).HasMaxLength(160).IsRequired();
        Property(x => x.Price).IsRequired();
        Property(x => x.LastUpdate).IsRequired();

        HasRequired(x => x.Category);

    }
}

Category
public class Category
{
    public int Id { get; set; }
    public string Title { get; set; }

    public ICollection<Product> Products { get; set; }

    public override string ToString()
    {
        return this.Title;
    }
}

Category Map
public class CategoryMap : EntityTypeConfiguration<Category>
{
    public CategoryMap()
    {
        ToTable("Category");
        HasKey(x => x.Id);
        Property(x => x.Title).HasMaxLength(60).IsRequired();

        HasMany<Product>(x => x.Products).WithRequired(c => c.Category);
    }
}

GetProducts
// GET: api/Product
public IQueryable<Product> GetProducts()
{
    db.Configuration.ProxyCreationEnabled = false;
    return db.Products;
}

Retorno
{
    "Id": 1,
    "Title": "Produto Eletrônico",
    "Price": 10010,
    "LastUpdate": "2015-10-29T18:28:19.547",
    "CategoryId": 1,
    "Category": null
}

Comment: Em CategoryMap, retire  o HasMany e no productMap, mude para HasRequired(x => x.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
Comment: Resolvido o problema?
Answer: Tente alterar o seu método com:
public IQueryable<Product> GetProducts()
{
    db.Configuration.ProxyCreationEnabled = false;
    var query = from r in db.Products.Include("Category") select r;
    return query;
}


What timing is the access log writtien to

Question: Looking at the access log using "tail". At what point does the log get written to by httpd (I'm on CentOS6.3 if it makes a difference) ?
e.g. When the URL is accessed?, when process is finished and the page delivered? Some other timing?
Comment: Run `tail -f` on the log file and make a request. You'll have your answer fairly quickly.
Answer: Would it be that hard to check? The log entry can't be written until the request completes (since it includes the status, size of response and may include time taken to handle the request).
If the timestamp is when the request starts and you've got requests taking different times to complete, then the times would be out of sequence.
Comment: Snarkiness isn't really required. It really isn't so easy to check as requests come in over the mobile network and I don't know where the delay is.  So the log is written to after the request is completed. Thank you.


jQuery - Alternar background-image de um elemento

Question: Tenho um elemento figure com uma série de imagens dentro:

Obs: As imagens estão com display:none.
Quero recuperar o caminho de cada imagem e atribuir ao background do elemento figure a cada 3 segundos. Para isso fiz esse script:
var imgs = $(".MiniModImgSlider img").map(function()
{
  return $(this).attr('src');
});

for (var i = 0; i <= imgs.length; i++)
{
  setInterval(function()
  {
    $(".MiniModImgSlider").css('background-image', 'url('+imgs[i]+')');
  },1000);
}

Só que ao invés de atribuir o caminho da imagem o script retorna undefined!
Como posso resolver isso?
Código no JSFiddle
Answer: Um problema é que você está definindo vários setInterval, um para cada imagem, o que faz com que existam um monte de timers concorrendo para fazer alteração da imagem sendo exibida.
Você não precisa de um for, mas sim, somente de um setInterval com uma variável de controle definida em algum lugar, de forma a saber qual é a próxima imagem a ser exibida.
Exemplo no jsfiddle
var imgs = $(".MiniModImgSlider img")
.map(function()
     {
         return $(this).attr('src');
     });

var imgIndex = 0;
setInterval(function()
            {
                var url = imgs[imgIndex++ % imgs.length];
                $(".MiniModImgSlider")
                .css('background-image', 'url('+url+')');
            },1000);

Comment: Obrigado! Resolveu aqui.
Answer: No metodo .MAP() você deve passar um parâmento antes de function() Com algumas informação,por exeplo o alt, como uma array com todas as informações que você deseja manipular.
De acordo com a documentação do Jquery.
Ex:
var arr = [1,2,3,4,5];
var imgs = $(".MiniModImgSlider img").map(arr,function(){
    FAZ ALGUMA COISA
};


"Missing closing parenthesis" MySQL error

Question: I am trying to run a query that will show the rounded average to two decimal places. This is my code and I don't know why I keep getting the error.
SELECT
    ROUND(AVG (Scholarship, 2)) AS 'Average Scholarships'
FROM
    student;

Answer: You are passing Scholarship, 2 to the AVG function, which only expects one argument.
What you meant to do was pass AVG (Scholarship) and 2 to ROUND, like this:
SELECT ROUND(AVG (Scholarship), 2) AS 'Average Scholarships' FROM student;

Answer: SELECT ROUND(AVG (Scholarship), 2) AS 'Average Scholarships' FROM student;


passing a user id to user_is_logged_in function

Question: I want to use the user_is_logged_in function to determine if a user is logged in but i want to determine if that user is logged in from a cron job/ module.
Essentially i have an array of user id's that i want to loop through to see if the corresponding user is logged in and if so execute some code.
My question is how does one pass an integer to the function to get a true or false from the function? all examples i have seen use the function on a page where the user is viewing to show them content or send message to them. Nothing i can see shows how to use it from a script.
Hope this makes sense.
Madmilner
Answer: If you look at the docs you'll see the function comment:

Determines if the current user is logged in.

Emphasis mine.
So the function simply isn't supposed to do what you want to use it for, you'll need to write something custom
It's pretty easy though, see Get all logged in users in Drupal for some inspiration.


how to get current PAM user in pam_ldap?

Question: how can I get the user name that auth by pam_ldap in C/c++?
I found "pam_get_user" API, but how can I get the pam_handle_t for this function?
Thanks
Dma
Answer: You get the handle by calling:
int pam_start(const char *service_name, const char *user,
              const struct pam_conv *pam_conversation, pam_handle_t **pamh);

pamh - is an output parameter in above api.
Check more details here.
Comment: if I login through pam_ldap, how I can get current user info in a program? I don't know the paramater for pam_start.


Integrate $ \int_0^\infty \frac{ \ln^2(1+x)}{x^{3/2}} dx=8\pi \ln 2$

Question: I am trying to evaluate this integral.
$$
I=\int_0^\infty \frac{ \ln^2(1+x)}{x^{3/2}} dx=8\pi \ln 2
$$  Note $$
\ln(1+x)=\sum_{n=1}^\infty \frac{(-1)^{n+1}x^n}{n}, \ |x| < 1.
$$
I was trying to do use this series expansion but wasn't sure how to go about it because of the square of the logarithm.  And also it seems than we then will have $I\propto \int_0^\infty x^{n-3/2}dx$ which will diverge. Thanks
Comment: I'd guess that the best way to proceed is to find an appropriate contour in the complex plane and integrate using residues.
Comment: @T.Bongers I am looking for a solution, thanks though.
Answer: Integrating by parts,
$$ \begin{align} \int_{0}^{\infty} \frac{\ln^{2}(1+x)}{x^{3/2}} \ dx &= - \frac{2 \ln^{2}(1+x)}{\sqrt{x}} \Bigg|^{\infty}_{0} + 4 \int_{0}^{\infty} \frac{\ln (1+x)}{(1+x) \sqrt{x}} \ dx \\ &=4 \int_{0}^{\infty} \frac{\ln (1+x)}{(1+x) \sqrt{x}} \ dx . \end{align} $$
Now let $x = u^{2}$.
Then
$$\begin{align} \int_{0}^{\infty} \frac{\ln^{2}(1+x)}{x^{3/2}} \ dx &= 8 \int_{0}^{\infty} \frac{\ln (1+u^{2})}{1+u^{2}} \ du \\ &= 8 (\pi \ln 2) \tag{1} \\ &= 8 \pi \ln 2. \end{align}$$
$(1)$ Evaluating $\int_0^{\infty}\frac{\ln(x^2+1)}{x^2+1}dx$
Comment: Thanks, very clear.  No questions.  +10
Comment: Your editing makes this problem active and also makes me reminisce that this is the first problem I answered on Math SE. Thanks. $\ddot\smile$
Comment: @Tunk-Fey Since I just linked to this question, I thought I'd improve the formatting of my answer. Sometimes I wish you could make minor edits to an answer without bumping the question.
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{\int_{0}^{\infty}{\ln^{2}\pars{1 + x} \over x^{3/2}}\,\dd x = 8\pi\ln\pars{2}:
     \ {\large ?}}$

With $\ds{t \equiv {1 \over x + 1}\quad\iff\quad x = {1 \over t} - 1}$:
  \begin{align}
&\color{#00f}{\large\int_{0}^{\infty}{\ln^{2}\pars{1 + x} \over x^{3/2}}\,\dd x}=
-2\int_{x = 0}^{x \to \infty}\ln^{2}\pars{1 + x}\,\dd\pars{x^{-1/2}}
\\[3mm]&=2\int_{0}^{\infty}x^{-1/2}\bracks{2\ln\pars{1 + x}\,{1 \over 1 + x}}\,\dd x
=4\int_{1}^{0}\pars{1 - t \over t}^{-1/2}\ln\pars{1 \over t}t
\pars{-\,{\dd t \over t^{2}}}
\\[3mm]&=-4\int_{0}^{1}\ln\pars{t}t^{-1/2}\pars{1 - t}^{-1/2}\,\dd t
=-4\lim_{\mu \to -1/2}\totald{}{\mu}\int_{0}^{1}t^{\mu}\pars{1 - t}^{-1/2}\,\dd t
\\[3mm]&=-4\lim_{\mu \to -1/2}\totald{{\rm B}\pars{\mu + 1,1/2}}{\mu}
-4\lim_{\mu \to -1/2}\totald{}{\mu}
\bracks{\Gamma\pars{\mu + 1}\Gamma\pars{1/2} \over \Gamma\pars{\mu + 3/2}}
\\[3mm]&=-4\Gamma\pars{\half}\lim_{\mu \to -1/2}\braces{%
{\Gamma\pars{\mu + 1} \over \Gamma\pars{\mu + 3/2}}\,\bracks{\Psi\pars{\mu + 1} - \Psi\pars{\mu + {3 \over 2}}}}
\\[3mm]&=-4\Gamma^{2}\pars{\half}\,
{\Psi\pars{1/2} - \Psi\pars{1} \over \Gamma\pars{1}}
=-4\pars{\root{\pi}}^{2}\,{\bracks{-2\ln\pars{2} - \gamma} -\pars{-\gamma} \over 1}
\\[3mm]&=\color{#00f}{\large 8\pi\ln\pars{2}}
\end{align}
Comment: You always have nice solutions with $\partial_\mu$ or $\partial_\nu$ with these special functions.  Very helpful to me....Thanks a lot!!!!
Comment: @Jeff They are very useful. Thanks.
Comment: You are an expert on special functions!
Comment: @xpaul Thanks. They are quite useful. For that reasons people call them 'specials'.
Answer: Using Richard Feynman's favorite method, the method of differentiation under the integral sign.
$$
\begin{align}
I(\alpha)&=\int_0^\infty\frac{\ln^2(1+\alpha x)}{x^{\frac{3}{2}}}dx\\
\frac{dI(\alpha)}{d\alpha}&=\int_0^\infty\frac{2x\ln(1+\alpha x)}{x^{\frac{3}{2}}(1+\alpha x)}dx\\
I'(\alpha)&=2\int_0^\infty\frac{\ln(1+\alpha x)}{\sqrt{x}(1+\alpha x)}dx.
\end{align}
$$
Let $\,x=t^2\;\Rightarrow\;dx=2t\,dt$, then
$$
\begin{align}
I'(\alpha)&=2\int_0^\infty\frac{\ln(1+\alpha t^2)}{t(1+\alpha t^2)}\cdot2t\,dt\\
&=4\int_0^\infty\frac{\ln(1+\alpha t^2)}{(1+\alpha t^2)}dt.
\end{align}
$$
To solve the integral part, again we use the method of differentiation under the integral sign.
$$
\begin{align}
I(\beta)&=\int_0^\infty\frac{\ln(1+\alpha\beta t^2)}{(1+\alpha t^2)}dt\\
\frac{dI(\beta)}{d\beta}&=\int_0^\infty\frac{\alpha t^2}{(1+\alpha\beta t^2)(1+\alpha t^2)}dt\\
I'(\beta)&=\int_0^\infty\left[\frac{1}{(\beta-1)(1+\alpha t^2)}-\frac{1}{(\beta-1)(1+\alpha\beta t^2)}\right]dt\\
&=\frac{1}{\beta-1}\int_0^\infty\left[\frac{1}{1+\alpha t^2}-\frac{1}{1+\alpha\beta t^2}\right]dt.
\end{align}
$$
Note that
$$
\int_0^\infty\frac{1}{1+k y^2}dy=\frac{\pi}{2\sqrt{k}}.
$$
Therefore
$$
\begin{align}
I'(\beta)&=\frac{1}{\beta-1}\left(\frac{\pi}{2\sqrt{\alpha}}-\frac{\pi}{2\sqrt{\alpha\beta}}\right)\\
&=\frac{\pi}{2\sqrt{\alpha}}\left(\frac{\sqrt{\beta}-1}{\sqrt{\beta}(\beta-1)}\right)\\
&=\frac{\pi}{2\sqrt{\alpha}}\left(\frac{\left(\sqrt{\beta}-1\right)}{\sqrt{\beta}(\beta-1)}\cdot\frac{\left(\sqrt{\beta}+1\right)}{\left(\sqrt{\beta}+1\right)}\right)\\
&=\frac{\pi}{2\sqrt{\alpha}}\left(\frac{1}{\sqrt{\beta}\left(\sqrt{\beta}+1\right)}\right)\\
\frac{dI(\beta)}{d\beta}&=\frac{\pi}{2\sqrt{\alpha}}\left(\frac{1}{\sqrt{\beta}}-\frac{1}{\sqrt{\beta}+1}\right)\\
I(\beta)&=\frac{\pi}{2\sqrt{\alpha}}\int\left(\frac{1}{\sqrt{\beta}}-\frac{1}{\sqrt{\beta}+1}\right)d\beta\\
&=\frac{\pi}{2\sqrt{\alpha}}\left(2\sqrt{\beta}-2\sqrt{\beta}+2\ln\left(\sqrt{\beta}+1\right)+\text{C}_1\right)\\
&=\frac{\pi}{2\sqrt{\alpha}}\left(2\ln\left(\sqrt{\beta}+1\right)+\text{C}_1\right).\\
\end{align}
$$
For $\beta=0$ implying $I_\beta(0)=0$, then $\text{C}_1=0$ and
$$
I_\beta(1)=\int_0^\infty\frac{\ln(1+\alpha t^2)}{(1+\alpha t^2)}dt=\frac{\pi\ln 2}{\sqrt{\alpha}}.
$$
Now, plug in $I_\beta(1)$ to $I'(\alpha)$.
$$
\begin{align}
I'(\alpha)&=4\cdot\frac{\pi\ln 2}{\sqrt{\alpha}}\\
\frac{dI(\alpha)}{d\alpha}&=4\pi\ln 2\cdot\alpha^{-\frac{1}{2}}\\
I(\alpha)&=4\pi\ln 2\int\alpha^{-\frac{1}{2}}\,d\alpha\\
&=(4\pi\ln 2)\left(2\alpha^{\frac{1}{2}}+\text{C}_2\right)
\end{align}
$$
For $\alpha=0$ implying $I_\alpha(0)=0$, then $\text{C}_2=0$. Thus
$$
I_\alpha(1)=\int_0^\infty\frac{\ln^2(1+x)}{x^{\frac{3}{2}}}dx=\boxed{\color{blue}{\large8\pi\ln 2}}
$$
$$$$

$$\Large\color{blue}{\text{# }\mathbb{Q.E.D.}\text{ #}}$$
Comment: clever solution.  Thanks for the new approach.
Comment: @Jeff You're welcome. Unfortunately, I failed to earn my first bounty.
Answer: There is another way to solve. Let
$$ I(\alpha,\beta)=\int_0^\infty\frac{\ln(1+\alpha x)\ln(1+\beta x)}{x^{\frac{3}{2}}}dx. $$
Note $I=I(1,1)$. It is easy to see that
$$ \frac{\partial^2I(\alpha,\beta)}{\partial\alpha\partial\beta}=\int_0^\infty\frac{\sqrt{x}}{(1+\alpha x)(1+\beta x)}dx=\frac{\pi}{\alpha\sqrt{\beta}+\sqrt{\alpha}\beta}  $$
and hence
$$ \frac{\partial I(\alpha,1)}{\partial\alpha}=\int_0^1 \frac{\pi}{\alpha\sqrt{\beta}+\sqrt{\alpha}\beta}d\beta=2\pi\frac{\log(1+\frac{1}{\sqrt{\alpha}})}{\sqrt{\alpha}} $$
and
$$ I(1,1)=\frac{\partial I(\alpha,1)}{\partial\alpha}=2\pi\int_0^1\frac{\log(1+\frac{1}{\sqrt{\alpha}})}{\sqrt{\alpha}}d\alpha=8\pi\ln 2. $$


Fixed div on left of container, full height of container (but not of page) using CSS

Question: I want the following layout in my page:

The header and footer are always visible. The gray area is an article tag. The green and dark red areas are both inside a nav tag. The dark red has a fixed width, and is going to be used as a handle to resize the green navigation panel (it will be very narrow, of course, and I'll use JavaScript for the resizing). Both the gray and green areas must have their own scrollbars.
That's the HTML:
<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS template</title>

Header

nav1

nav2 with longer line just to make sure if everything is working as intended

Handle

Article

Footer

That's the CSS:
html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#C0C0C0;
    width:80%;
    overflow:auto;
    padding:10px;
}
nav {
    width:20%;
    height:auto;
    overflow:hidden;
}
.navcont {
    background:#00FF00;
    width:auto;
}
.handle {
    background:#800000;
    float:right;
    width:30px;
}
footer {
    text-align:center;
}

And a running example: https://jsfiddle.net/etwphhc8/
I tried many different solutions, from many different questions/answers here, but still haven't make it work as intended. So, how can I achieve the wanted layout using CSS?
Comment: like this? https://jsfiddle.net/etwphhc8/2/
Comment: Yes, @MichaelCoker, of course! That's what we get for copying solutions, instead of thoroughly learning CSS. Thank you!
Answer: Add flex with the direction set to row in nav:
nav {
  width:20%;
  height:auto;
  overflow:hidden;
  display:flex;
}

Comment: The flex-direction doesn't seem necessary. Thank you!
Comment: I forgot that flex-direction is row by default.  I removed it.
Answer: Try to write:
  .navcont {
      background:#00FF00;
      width:auto;
      height: 100%;
}

Comment: I tried this, but then the footer disappeared from the page.


iOS first time user tutorial

Question: I'm building an iPhone app and want to create a 1st time use tutorial for the user. I've seen some other apps use popover style baloons to guide the user through the UI and I'd like to do that as well. I have a popover library. What's the best way to create and track the steps of the tutorial?
Answer: I would go with NSUserDefaults.  Just trigger some BOOL-ean values to change as each part finishes.  I assume you want to continue the tutorial if the user quits the app, so this would be your best and easiest bet.
Answer: BOOLs for each dialog? Persisted however you want - NSUserDefaults or plist, json file, xml, whatever.
Answer: You can also use NSUbiquitousKeyValueStore if you want to setting to sync across devices using iCloud. If the user doesn't have iCloud configured it will just store it locally.

iOS first time user tutorial


Correct way to change the active Drupal theme programmatically?

Question: What is the correct way to change the active Drupal theme programmatically?
Answer: Drupal 6 solution:
You want to make sure you change the global $custom_theme variable fairly early in page execution.
global $custom_theme;
$custom_theme = 'garland';

Comment: Please, mention `hook_custom_theme` http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_custom_theme/7
Comment: Could not reproduce the success. :<
Comment: where is `$custom_theme` defined? is it enough for changing theme?
Comment: A couple of hooks to try that are very early in page execution (if you're using a custom module) are hook_boot() and hook_init().
Comment: Worked for me.  I added it in [hook_boot()](https://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_boot/6)
Comment: It also works at the top of a page callback function - at least some of the time.
Answer: I know you asked how to do it programattically, but in case that's your solution, not the actual problem, you can also use the ThemeKey module. This allows you to set conditions which, when met, changes the theme. You can make conditions based on paths, taxonomy, content type, create or edit date and more. You can also add in the Themekey Properties module module to get even more options.
Again, I know this isn't programmattically, but I'm not sure if the real question behind your question is how to change themes based on conditions.
Comment: Yeah if you want to manage this through the UI, I'd recommend ThemeKey.
Comment: Or at least checkout http://drupalcode.org/project/themekey.git/blob/refs/heads/7.x-2.x:/themekey.module#l114 where ThemeKey does its magic
Comment: @Chaulky is right : I'm using ThemeKey since a while, it is the easiest way to manage theming customisations upon user name, role, page, whatever you want. I recommend it.
Answer: The best way to do this is to create an update hook in a module:
function yourmodule_update_N() {
  variable_set('theme_default','yourtheme');
}

Comment: This should be the correct answer..
Comment: This would only be correct if you wanted to change the theme globally. I had assumed from the question that the OP wanted to change the theme on a particular page, or in a particular context.
Answer: Changing the active theme via Drush
drush vset theme_default garland
drush vset admin_theme garland
drush cc all

Changing the active theme via a module
The basics of changing the default theme and administration theme:
// Changes the theme to Garland
variable_set('theme_default', $theme_default);
// Changes the administration theme to Garland
variable_set('admin_theme', $admin_theme);

Here's a small function to set back the themes safely to default Drupal themes like Bartik or Garland (tested in Drupal 6 and 7):
/**
 * Set the active Drupal themes (the default and the administration theme) to default ones.
 * Tested in Drupal 6, 7 (but possibly working in version 8 too according to the documentations [some similarities between 7 and 8]).
 */
function TESTMODULE_set_active_theme_to_default($affect_admin_theme = TRUE) {

  // Provides a list of currently available themes.
  $list_themes = list_themes(TRUE);
  // 6, 7, 8, etc.
  $major_version = (int)VERSION;

  $theme_default = isset($list_themes['bartik']) ? 'bartik' : 'garland';
  $admin_theme   = isset($list_themes['seven']) ? 'seven' : 'garland';

  // Changes the theme to Garland
  variable_set('theme_default', $theme_default);

  // Changes the administration theme to Garland if argument is TRUE
  if($affect_admin_theme){
    variable_set('admin_theme', $admin_theme);
  }

  // if Switchtheme module (https://drupal.org/project/switchtheme) is enabled, use it
  if (module_exists('switchtheme')) {
    if (empty($_GET['theme']) || $_GET['theme'] !== $theme_default) {
      $query = array(
        'theme' => $theme_default
      );
      // in D6, drupal_goto's second argument is the query string,
      // in >=D7, a more general $options array is used
      if($major_version < 7){
        $options = $query;
      }
      else{
        $options = array('query' => $query);
      }

      drupal_goto($_GET['q'], $options);
    }
  }

  drupal_set_message(t('Default theme has been changed to %theme_default, administration theme has been changed to %admin_theme.', array(
    '%theme_default' => $theme_default,
    '%admin_theme' => $admin_theme
  )));

}

You can call it in a hook_init() implementation (comment it out after it's not needed):
/**
 * Implements hook_init()
 */
function TESTMODULE_init() {
  // ATTENTION! Comment out the following line if it's not needed anymore!
  TESTMODULE_set_active_theme_to_default();
}

Comment: This is also the method you would use when enabling a theme in an install profile `variable_set('theme_default','yourtheme');`
Answer: In Drupal 7, use hook_custom_theme():
/**
 * Implements hook_custom_theme()
 * Switch theme for a mobile browser
 * @return string The theme to use
 */
function mymodule_custom_theme()  {
    //dpm($_SERVER['HTTP_USER_AGENT']);
    $theme = 'bartik'; // core theme, used as fallback
    $themes_available = list_themes(); // get available themes
    if (preg_match("/Mobile|Android|BlackBerry|iPhone|Windows Phone/", $_SERVER['HTTP_USER_AGENT'])) {
        if (array_key_exists('custommobiletheme', $themes_available)) $theme = 'custommobiletheme';
        else { drupal_set_message("Unable to switch to mobile theme, because it is not installed.", 'warning'); }
    }
    else if (array_key_exists('nonmobiletheme', $themes_available)) $theme = 'nonmobiletheme';
    // else, fall back to bartik

    return $theme;
}

Adapted from <emoticode />
Return the machine-readable name of the theme to use for the current page.
The comments for this function may be worth reading:

This hook can be used to dynamically set the theme for the current
  page request. It should be used by modules which need to override the
  theme based on dynamic conditions (for example, a module which allows
  the theme to be set based on the current user's role). The return
  value of this hook will be used on all pages except those which have a
  valid per-page or per-section theme set via a theme callback function
  in hook_menu(); the themes on those pages can only be overridden using
  hook_menu_alter().
Note that returning different themes for the same path may not work
  with page caching. This is most likely to be a problem if an anonymous
  user on a given path could have different themes returned under
  different conditions.
Since only one theme can be used at a time, the last (i.e., highest
  weighted) module which returns a valid theme name from this hook will
  prevail.
Answer: For Drupal 8:
In settings.php
$config['system.theme']['default'] = 'my_custom_theme';

Update config programatically:
\Drupal::configFactory()
->getEditable('system.theme')
->set('default', 'my_custom_theme')
->save();

Comment: Thanks past me!


How to use the getColor method from cwac's ColorMixer?

Question: I am trying to implement the get color method for the cwac color mixer( https://github.com/commonsguy/cwac-colormixer), but every time this code runs I get a NullPointerException:
int color = 1;

public void openColor(){
ColorMixer mixer = (ColorMixer)findViewById(R.id.mixer);
  if (color!=1){
    mixer.setColor(color);
  }
  color = mixer.getColor();
}

The color = mixer.getColor();     is the line that crashes.
Comment: You're most likely not searching for the `ColorMixer` in the right place(or your layout doesn't have a `ColorMixer` element with the id `R.id.mixer`).
Comment: Thank you luksprog - it turned out it was crashing because I was trying to run the openColor method within a pop up window, and what I needed to do was not use a separate method and instead put the name of my pop up window (see http://stackoverflow.com/questions/8595427/android-popup-and-button-to-dismiss-doesnt-work) - I will add this as an answer as soon as I can (people like me who can't answer any questions can't post an answer within 8 hours)
Answer: I haven't ever used this Commonsware component before, but from looking at the source code, it appears all you need to do is set up a listener/callback. This mechanism will allow you to get notified of any changes in the color picking.
First, have your class implement the following listener interface:
public interface OnColorChangedListener {
    public void onColorChange(int argb);
}

Then set the listener on the ColorMixer using:
public void setOnColorChangedListener(OnColorChangedListener listener) {
    this.listener=listener;
}

If you do it all inline, it will look somewhat like this:
mixer.setOnColorChangeListener(new ColorMixer.OnColorChangeListener() {
    @Override public void onColorChange(int argb) {
        //... get the color here; e.g.
        color = argb;
    }
});

Comment: Sorry for wasting your time - found the answer, just have to wait 8 hours before answering my own question
Answer: Thank you luksprog - it turned out it was crashing because I was trying to run the openColor method within a pop up window, and what I needed to do was not use a separate method and instead put the name of my pop up window (see Android: popUp and button to dismiss doesnt work)


Como separar imagens parecidas (Pyhton / Aprendizagem de máquina)

Question: Objetivo: Separar imagens com características iguais de uma pasta com diversas imagens
(exp: foto1, foto2, foto3, foto4, foto5 >>> foto1.Copo1 foto2.Copo2 foto3.Copo3; foto4.Cachorro1,foto5.Cachorro2...)
Gostaria de uma luz no assunto, mas na parte que eu estudei, acredito que seria algo no estilo : Aprendizagem de máquina -> Não supervisionada -> Agrupamento.
Answer: Sua pergunta é muito genérica, não há como responder especificamente.
Uma coisa que você pode fazer é usar k-means para clusterizar por algum critério de semelhança.  Você decide o critério:
1) Pode clusterizar por cor, por exemplo;
2) Se as imagens são normalizadas, você pode usar SIFT e definir como critério quantos keypoints são inliers.
Estou assumindo que você não tem nenhuma informação de categoria das imagens, uma vez que você mencionou aprendizado não-supervisionado. Se tiver qualquer informação de categoria, os resultados são melhores.
Comment: a questão é bem ampla, mas infelizmente n dá para dividir por cor.
O problema: tenho +7000 imagens, e tenho q separar elas por semelhança , como por exemplo, separar todas as imagens que contem um poste.
Comment: Eu tentei explicitar melhor o que queria dizer.
Comment: Obrigado @fredguth , vou dar uma estudada nesse caminho.
Answer: Primeiramente eu aconselharia a reduzir as dimensões dessas imagens.
Pois se for aplicar um K-means pode acontecer o problema de Course Of dimensionality que faz com algoritmos que usam distâncias entre um ponto e outro percam precisão.
Porem não digo literalmente reduzir o tamanho da imagem mas sim utilizar um PCA ou SVD para isso pois irá conservar informações relevantes da imagem.
Existem outras formas de clusters como hierarchical clustering e Autoencouders que podem ser uteis também.
Outro ponto importante é a memória necessária para lidar com essa quantidade de imagens. dependendo do algoritmo e da quantidade de memoria de seu computador você pode trava-lo.
Existem métodos mais diretos como comparação de pedações da imagem A com a imagem B.(mas não acredito que seja muito bom.)
Emfim existem várias formas de se fazer esse tipo de clusterização.


Maximum of a function of two variables

Question: Let $f : X(\subseteq \mathbb{R}^2) \to \mathbb{R}$ by the function $f(x,y) = x^ny^m,$ where $D = \{ (x,y) \ \vert \ x^2+ y^2 <1 \}$ and $n \in \mathbb{Z}_{\geq 1}$. I want to determine the supremum of $f$.
We can compute the partials, $$\frac{\partial f}{\partial x} = ny^mx^{n-1}$$ and $$\frac{\partial f}{\partial y} = mx^ny^{m-1}$$ which gives a critical point at $(0,0)$. This looks like a minimum since $f(0,0)=0$.
To determine the supremum, we would need to look on the bound of $D$. This gives us $$f(x) = x^n (1-x^2)^{m/2}.$$ Calculating the derivative of this, $$f'(x) = nx^{n-1}(1-x^2)^{m/2} - mx^{n+1}(1-x^2)^{(m-2)/2} =0 \\
= x^{n-1}(1-x^2)^{\frac{m}{2}-1}[n(1-x^2)-mx^2] =0 \ \ $$ which says that $x=0$, $1-x^2 =0$ or $$n(1-x^2)-mx^2=0 \implies n-(m+n)x^2=0 \implies x = \pm \sqrt{\frac{n}{n+m}}.$$ Can we then assert that the supremum occurs at $$\left(\pm \sqrt{\frac{n}{m+n}}, \pm \sqrt{\frac{m}{m+n}} \right)$$ and the supremum is $$f\left(\pm \sqrt{\frac{n}{m+n}}, \pm \sqrt{\frac{m}{m+n}} \right)=\frac{n^nm^m}{(m+n)^{m+n}}?$$
Comment: For completeness, you should add the reasons why the $x=0$ and $1+x^2=0$ cases do not lead to a supremum, but other than that, it looks good to me.
Comment: $f(0,0)$ is not the minimum value if $m+n$ is odd.
Answer: HINT: with $AM-GM$ we get for $$x\geq 0,y\geq 0$$
$$(xy)^n\le \left(\frac{x^2+y^2}{2}\right)^n<\frac{1}{2^n}$$ for $$x^2+y^2<1$$
Comment: I have edited the question, I want to investigate the behaviour of a function a little more complex.
Answer: You have to determine the points $(x,y)\in\partial D$ where $(xy)^n$ is maximal. To this end consider the pullback
$$\hat f(\phi)=(\cos\phi\sin\phi)^n=2^{-n}\sin^n(2\phi)\qquad(\phi\in{\mathbb R})\ .$$
If $n\geq1$ is even then $\hat f$ assumes values between $0$ and $2^{-n}$, and if $n$ is odd then $\hat f$ assumes values between $-2^{-n}$ and $2^{-n}$.
If $n$ is even then the critical point $(0,0)$ is a local minimum, and if $n$ is odd then this point  is a saddle point.
In all we can say that $\sup_{(x,y)\in D} f(x,y)=2^{-n}$.
Note that there is an error in your calculation: Replace $\left({1\over\sqrt{2}},{1\over2}\right)$ by $\left(\pm{1\over\sqrt{2}},\pm{1\over\sqrt{2}}\right)$.
Comment: I have edited the question, I want to investigate the behaviour of a function a little more complex

Maximum of a function of two variables


AWE turned on but still not using memory

Question: I do have a server 2008 64 running a SQL server 2005. I do have 8GB on the server and I want SQL to use most of the memory on that server. I have turned the page-locking on for the account and also turned AWE on. See the result below:

Configuration option 'min server memory (MB)' changed from 0 to 1024. Run the RECONFIGURE statement to install.
Configuration option 'max server memory (MB)' changed from 5113 to 6144. Run the RECONFIGURE statement to install.

However it does not seem that SQL server is loading the memory. Not sure what I am missing.
I would appreciate if someone could lead me on the right direction.
Answer: 64-bit versions of Windows don't support AWE. "AWE is not required and cannot be configured on 64-bit operating systems."
Comment: As @DavidSchwartz said try upgrading to x64 of SQL Server.
Comment: Then how could I make my SQL server 2005 use more memory?
Comment: Install the [64-bit version of SQL server 2005](http://www.microsoft.com/sqlserver/2005/en/us/64-bit.aspx).
Comment: I agree with David. What edition SQL Server are you running? Can you post back the result of this query: SELECT  SERVERPROPERTY('Edition') AS 'Edition'
Comment: `Play_demo 204.992187
SmarterTrack 4.312500
EasyLoanChoice 2.109375
BugTracker2 0.671875
HotBargainHunter 0.500000`

As you see not using almost any memory at all.
I am using a 2005 Enterprise x86 version.
I do have the same thing on another server running Windows 2003 but in there SQL server takes all the memory that is assigned.
Not sure what else to do to SQL server 2005 x86 or to Windows 2008 x64.
Answer: Try running this below query (by Glen Berry); and see "how much memory (in the buffer pool) is being used by each database on the instance"
<code>SELECT  DB_NAME(database_id) AS [Database Name] ,
        COUNT(*) * 8 / 1024.0 AS [Cached Size (MB)]
FROM    sys.dm_os_buffer_descriptors
WHERE   database_id > 4 -- system databases
        AND database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id)
ORDER BY [Cached Size (MB)] DESC
OPTION  ( RECOMPILE ) ;
</code>
The min and max memory allocation depends on your workload; Read Effects of min and max server memory for more detail


drop down - use jquery in mvc

Question: I am trying to fill up the state ddl on selection of a country from a dropown. I am able to get the filter result based on countryname criteria in stateList function. But when it returns to view, it shows all the states list. Can you tell me where it went wrong.
Thanks in advance.
//This is my controller class
public ActionResult  Country()
{
    Country country = new Country();
    ListCountry objCountry = new ListCountry(country);
    return View(country);
}

//This method calls  on selection of countryanem
public ActionResult stateList()
{
    Country country = new Country();
    var state = Request.Form["_countryId"];
    country.CountryId = _countryId;
    ListCountry objCountry = new ListCountry(country);
    return View(country);
}
}

//This  is model class
public partial class Country
{
    public SelectList countryList { get; set; }
    public SelectList stateList { get; set; }
}

public partial class ListCountry
{
    Entities db = new Entities();

    //This constructorof Listcounty  populate the country and state ddl
    public ListCountry(Country country)
    {
        string cntId1    = country.countryId;
        int id = Convert.ToInt32(cntId1);
        country.countryList = new SelectList(db.Countries.ToList(), "CountryId", "CountryName");
        if (id > 0 )
        {
            List <State> list = db.States.Where(p => p.countryId == id).ToList();
            country.stateList = new SelectList(list, "StateID", "StateName");
        }
        else
        {
            country.stateList = new SelectList(db.States.ToList(), "StateID", "StateName");
        }
    }

Comment: Have you debugged to see what code path is executing? I would assume you're getting back all  the states because `id` is not greater than zero. How is the `stateList` action being called? If it's jQuery, can you post that code? Also, what does stateList.cshtml look like?
Answer: Couple of things:

From your description it looks as though you are calling stateList when you first load. Are you including the Country in your call? If you do not it will always give you all the states lists as it needs a country.countryId in your query.
I don't recommend declaring SelectList in your model. MVC is supposed to separate those two concerns. What would happen if all the sudden you decide not use a select? This should only concern the View.

drop down - use jquery in mvc