Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

Question: What is the difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?
When is the appropriate time to use each one of these?
Comment: Also see http://stackoverflow.com/questions/1247457/difference-between-rebuild-and-clean-build-in-visual-studio-2008
Comment: Is rebuild the same as clean then build?
Comment: @ColonelPanic yes
Answer:
Build solution will perform an incremental build: if it doesn't think it needs to rebuild a project, it won't. It may also use partially-built bits of the project if they haven't changed (I don't know how far it takes this)
Rebuild solution will clean and then build the solution from scratch, ignoring anything it's done before. The difference between this and "Clean, followed by Build" is that Rebuild will clean-then-build each project, one at a time, rather than cleaning all and then building all.
Clean solution will remove the build artifacts from the previous build. If there are any other files in the build target directories (bin and obj) they may not be removed, but actual build artifacts are. I've seen behaviour for this vary - sometimes deleting fairly thoroughly and sometimes not - but I'll give VS the benefit of the doubt for the moment :)

(The links are to the devenv.exe command line switches, but they do the same as the menu items.)
Comment: I have personally found "Clean Solution" to be more than unhelpful. If I *really* want it clean, manually deleting the bin and obj folders is the way to go.  Have even been caught chasing phantom "errors" - until I did that.  Clean just isn't reliable.
Comment: if artifacts made their way through other means than through build artifacts (say for example a copy from another source integrated as a msbuidltask in the cproj) then clean leaves them be.  Which makes it pretty much useless, I'd even say it is dangerous as it will leave you with a false sense of cleansiness.
Comment: @verdana: For github etc, it's simpler to have a decent `.gitignore` file. But as per the answer, Clean doesn't always do a particularly thorough job in my experience.
Comment: @Tod: I have noticed in the past that Clean+Build works when Rebuild gives me link errors.
Comment: @womp: Not in the project I've just been looking at. It's still got all the assemblies there...
Comment: @Jon - weird.  I don't recall a clean ever not cleaning up those directories.  I'm doing it right now and it's wiping all .dll and .pdb files.  Definitely leaves my ReSharper junk alone though.
Comment: @Chris:
Using tortoise-svn functionality "delete all unversioned files" as a replacement for VS clean works like a charm for me.
Comment: I usually use "Clean" just to clean my project (for reduce size) before copy, archive or upload, or something like Github, etc
Comment: One reason to do a clean is so that COM registrations of the TLBs of DLLs can get unregistered. VS appears to take care of this. If you just delete the bin folder it would leave orphaned information in the registry.
Comment: it's easyer to have a step that destroys the build direcotry .. Clean build now has an Option for Remove all build dirdctories.. other wise clean JUST removes the source.
Comment: @Jon - a Clean does wipe the bin and obj folders in my experience?
Comment: Clean also removes add-in assemblies, registry entries and security settings - According to:  http://msdn.microsoft.com/en-us/library/vstudio/cc442946(v=vs.100).aspx  - cleaning up the project section.
Comment: @happygilmore I am not sure yet why that is. See Shivprasad Koirala for a possible answer. Though I'm not sure if it is the only reason why. I've read that rebuild does not clean the intermediate files, so I'm still confused as to what it does exactly.
Comment: I've found that a Rebuild will often delete PDB files of static immediately after they're created, causing linker warnings.  Clean + Build doesn't suffer from that problem.  This might be because I have a solution where the static library projects are used by more than one executable project.  Perhaps that explains @happygilmore's linker errors.
Answer: Build solution: Compiles code files (DLL and EXE) which are changed.
Rebuild: Deletes all compiled files and compiles them again irrespective if the code has changed or not.
Clean solution: Deletes all compiled files (DLL and EXE file).
You can see this YouTube video (Visual Studio Build vs. Rebuild vs. Clean (C# interview questions with answers)) where I have demonstrated the differences and below are visual representations which will help you to analyze the same in more detail.

The difference between Rebuild vs. (Clean + Build), because there seems to be some confusion around this as well:
The difference is the way the build and clean sequence happens for every project. Let's say your solution has two projects, "proj1" and "proj2". If you do a rebuild it will take "proj1", clean (delete) the compiled files for "proj1" and build it. After that it will take the second project "proj2", clean compiled files for "proj2" and compile "proj2".
But if you do a "clean" and build", it will first delete all compiled files for "proj1" and "proj2" and then it will build "proj1" first followed by "proj2".
Answer: Taken from this link:

Build means compile and link only the source files that have changed
  since the last build, while Rebuild
  means compile and link all source
  files regardless of whether they
  changed or not. Build is the normal
  thing to do and is faster. Sometimes
  the versions of project target
  components can get out of sync and
  rebuild is necessary to make the build
  successful. In practice, you never
  need to Clean.
Comment: "In practice you never need to Clean" <-- I call BS on this one.
Comment: @PaulBinder [You needn't look too far.](https://stackoverflow.com/questions/3095901/difference-between-build-solution-rebuild-solution-and-clean-solution-in-visua?rq=1#comment32042384_17781143)
Comment: Link? I thought the idea of a DLL, aka Dynamic Link Library, was to link at runtime?
Comment: piers7 can you then provide a reason you would need to clean vs rebuild?
Answer: Build Solution - Builds any assemblies which have changed files. If an assembly has no changes, it won't be re-built. Also will not delete any intermediate files.
Used most commonly.
Rebuild Solution - Rebuilds all assemblies regardless of changes but leaves intermediate files.
Used when you notice that Visual Studio didn't incorporate your changes in the latest assembly. Sometimes Visual Studio does make mistakes.
Clean Solution - Delete all intermediate files.
Used when all else fails and you need to clean everything up and start fresh.
Comment: *Used when you notice that Visual Studio didn't incorporate your changes in the latest assembly. Sometimes Visual Studio does make mistakes.* — this is the reason I upvote this answer because no other answer seem to say about it
Comment: What is intermediate files ? Do u mean Dll,pdb's and xml files ?
Answer: I just think of Rebuild as performing the Clean first followed by the Build.
Comment: I don't think it does.  I have a situation where doing a Clean Solution, followed by Build Solution works, but doing a Rebuild Solution fails.  This is on a freshly created solution with 2 projects (one a dependent of the other).
Comment: This had no upvotes (until now) and according to the docs (see the link in Jon's answer) this is exactly right.
Comment: @Cthutu See Shivprasad's answer for the detail that makes the difference here.  Rebuild cleans and then builds each individual project at a time, whereas running Clean first cleans everything out at once, then Build builds it all at once.  I've run across instances where this change in clean/build order makes the difference between compiling and not compiling, too.
Comment: @Sean Maybe it was caused by adding a project in your solution as a `file reference` instead of a `project reference` so the project build order didn't recognize it had to build a certain project before another, and the assembly didn't exist where it should have during the build?
Answer: Build solution will build any projects in the solution that have changed. Rebuild builds all projects no matter what, clean solution removes all temporary files ensuring that the next build is complete.
Answer: The one major thing I think people are leaving out is that Build and Clean are both tasks that are performed based on Visual Studio's knowledge of your Project/Solution.  I see a lot of complaining that Clean doesn't work or leaves leftover files or is not trustworthy, when in fact, the reasons you say it isn't trustworthy actually makes it more trustworthy.
Clean will only remove (clean) files and/or directories that Visual Studio or the compiler themselves have in fact created.  If you copy your own files or files/folder structures get created from an outside tool or source, then Visual Studio doesn't "know they exist" and therefore, should not touch them.
Can you imagine if the Clean operation basically performed a "del *.*" ?  This could be catastrophic.
Build performs a compile on changed or necessary projects.
Rebuild performs a compile regardless of change or what's necessary.
Clean removes files/folders it has created in the past, but leaves anything that it didn't have anything to do with, initially.
I hope this elaborates a bit and helps.
Comment: "Clean removes files/folders it has created in the past, but leaves anything that it didn't have anything to do with, initially."  That's mostly, but not completely true.  For intermediate files, yes, it deletes exactly the set of files that the toolchain produced.  For others, in the build output directory, it uses wildcard patterns, like *.pdb.  This leads to race conditions in Rebuild Solution that don't exist if you do Clean Solution followed by Build Solution.
Answer: Build Solution - Build solution will build your application with building the number of projects which are having any file change. And it does not clear any existing binary files and just replacing updated assemblies in bin or obj folder.
Rebuild Solution - Rebuild solution will build your entire application with building all the projects are available in your solution with cleaning them. Before building it clears all the binary files from bin and obj folder.
Clean Solution - Clean solution is just clears all the binary files from bin and obj folder.
Answer: I have a a blank solution BuildRebuildClean and three class library Models,Repository,Notification.
I use Models and Repository in Notification class library.
Then:

Build solution Incremental build and compiles only the files that are changed. If an assembly has no changes,
it won't be re-built. Also, it will not delete any intermediate files.
If Modify some code in Models library project, then BUILD solution.
In the below screen shot, refer to the time stamp of DLL, EXE is updated in Models and Notification library.

Rebuild solution Deletes all compiled files and compiles all irrespective of changes,
ignoring anything it's done before.
Right click on the solution name BuildRebuildClean. What it does is deletes all the assemblies,
EXEs and referred files to compile again.

Clean Solution Deletes all compiled, intermediate files (i.e., EXEs and DLLs) from the bin/obj directory.
Answer: A two-part question ... but all answers (except from Justin Niessner) only focus on part 1: the difference. The second part is what I find more interesting: "When is the appropriate time to use each one of these?". But let me start with how I think of what each does:
Build: Should and usually does: generate (build) each intermediate and output file that is out-of-date with respect to its source files.
Rebuild: A workaround (hack) that allows you to build when the build command fails due to a bug with out-of-date evaluation.
Clean: A hacky implementation of deleting generated (intermediate and output) files so that a subsequent build might work. Hacky since it often doesn't delete enough. VS designers put all intermediate and output files in separate directories. Why not delete the directories?!?!?! But, I digress.
There is no clean/clear way to know when to use one command vs another. Knowing what each does, does not really inform me about the appropriate situation to use each.
It's more about personality than science. An optimist uses Build most of the time, but resorts to Rebuild if Build fails and they think the issue is wonky behavior of Visual Studio. And if Rebuild fails, then they do Clean and Build. When that fails, they start googling...
More pessimistic folks always use Rebuild since its more reliable even though takes longer when used every time. The most pessimistic always do Clean then Rebuild. They forgot there is a Build command. They also wear a belt and suspenders.
Some might think this is cynical. But, I think not. I think the UX of Visual Studio is bad and that users and the industry have gotten used to it. Worse, many other tools adopted the same UX since VS is ubiquitous.
IMO, Microsoft should: fix Build, fix Clean and eliminate Rebuild
Answer: All I know is a Clean does not do what "make clean" used to do - if I Clean a solution I would expect it delete obj and bin files/folders such that it builds like is was a fresh checkout of the source.  In my experience though I often find times where a Clean and Build or Rebuild still produces strange errors on source that is known to compile and what is required is a manual deletion of the bin/obj folders, then it will build.
Comment: Specially in Xamarin projects I need to delete manually bin and obj folders to solve strange compilation errors
Answer: This is concerning "Build Solution" option only.
I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.
Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:

In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.
Answer: **Build ,Rebuild, Clean Solution**

Clean Solution
: deletes all compiled files (all dll's and exe's ).
Build Solution
: compiles code files (dll and exe) that have changed.
Rebuild Solution
: Deletes all compiled files and Compiles them again regardless of whether or not the code has changed.
Answer: Clean will clean the artifacts in bin/Debug folder. Means deletes all the files in bin/Debug folder.
Build checks the artifacts in bin/Debug folder and if required then creates the artifacts (while checking for build time errors).
Rebuild = Clean + Build in a single go. This will first delete all the files in bin/Debug folder and then create the artifacts again in the bin/Debug folder.
One can confirm these operations by opening and observing the bin/Debug (or Release) folder and then Cleaning, building and rebuilding the project.
Comment: Rebuild does Clean then Build project by project.  If the intermediate or build output directories are shared by multiple projects in the same solution, that's different than Clean on the solution followed by Build on the solution.
Answer: Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
Comment: [Rebuild cleans the projects one at a time which is not the same as `Clean + Build`.](https://stackoverflow.com/a/17781143/6655092)


Prove that a relatively compact subset of $L^p$ is bounded.

Question: Let $p\in [1,\infty)$, $A\subset L^p(\mathbb R^m)$ relatively compact and $\lambda^m$ be the Lebesgue measure on $\mathbb R^m$. Prove:
a) $A$ is bounded.
b) $\lim_{y \to 0}\sup_{f \in A} \int_{\mathbb R^m} |f(x+y)-f(x)|^p d\lambda^m(x)=0$
c) $\lim_{r \to \infty}\sup_{f \in A} \int_{|x|>r} |f(x)|^p d\lambda^m(x)=0$.
I can't get any further:
a): Every relatively compact set in a normed space is totally bounded, which implies boundedness. (Right?)
b), c): Cover A by balls and approximate the centers by simple functions. (How do I do this formally?)
Answer: We can show that b) and c) hold when $A$ is replace by $B$:

if $B=\{\chi_S\}$ where $S\subset\mathbb R^n$ is an open set of finite measure;
when $B=\{\chi_S\}$ where $S$ is any measurable subset of $\mathbb R^n$ of finite measure;
when $B=\{f_0\}$, where $f_0\in\mathbb L^p$;
when $B$ is finite.

Then conclude by a $2\varepsilon$-argument.


TextInputListener string into Label

Question: I took a look at https://github.com/libgdx/libgdx/wiki/Simple-text-input and what I want is to take the entered text from one of those dialogs into a Label. I got nullpointer with this way :
public class TextInputListener implements Input.TextInputListener {
public String name, year;
@Override
public void input(String text) {
    name = "Enter some text.."+ text ;

}

@Override
public void canceled() {
    name = "canceled by user";

}

}
Then I have a button that opens the dialog :
btnEdit.addListener(new ChangeListener() {

        @Override
        public void changed(ChangeEvent event, Actor actor) {
        TextInputListener listener = new TextInputListener();
            Gdx.input.getTextInput(listener, "Enter information", "Name:");

        }

    });

And then I try to recieve that string into my Label:
    Label nameLabel = new Label(listener.name, labelstyle);

As I said I get nullpointer at that last line saying "Attempt to read from field 'TextInputListener.name' on a null object reference" . But I make sure to type in some text and press enter/ok.
Answer: You never set the name string in the TextInput listener.
Gdx.input.getTextInput(listener, "Enter information", "Name:");

I don't think that is setting the string using the input or it is calling new Label(listener.name, labelstyle); before you the user actually types the input in.
Try changing TextInputListener to
public class TextInputListener implements Input.TextInputListener {
public String name = "Enter some text..";
public String year;
@Override
public void input(String text) {
    name = "Enter some text.."+ text ;

}

@Override
public void canceled() {
    name = "canceled by user";

}

If that doesn't work try checking to see the user has entered the text then call Label nameLabel = new Label(listener.name, labelstyle);
Comment: Hm.. didn´t work either. I noticed though that the error now is "Attempt to read from field xxxx on a null object reference"
Answer: I think there are two problems.
The first is that when you create a Label with an String object the Label will not automatically change when the String value change. At least I didn't got it to work. So you must call the setText(String str) method manually. But to do so, you need access to the Label object.
The second is, that you create the Label with listener.name but you are createing the listener object in the changed(ChangeEvent event, Actor actor) method so if you aren't creating the Label in that method the listener would be null.
So for the code you must set something like this:
public class TextInputListener implements Input.TextInputListener {
    private Label label;

    public TextInputListener(Label targetLabel) {
        label = targetLabel;
    }

    @Override
    public void input(String text) {
        label.setText("Enter some text.."+ text);
    }

    @Override
    public void canceled() {
        label.setText("canceled by user");
    }
}

And somewhere in your GUI creating method:
private TextInputListener listener; // Class field

    ...

    Label nameLabel = new Label("", labelstyle);
    listener = new TextInputListener(nameLabel);

    btnEdit.addListener(new ChangeListener() {

        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.input.getTextInput(listener, "Enter information", "Name:", ""); // My Gdx version needed a third parameter
        }

    });

    ...

Comment: Thanks for good explaining. Though when run with your changes the label doesnt change the text when I press Ok after typing some text into the dialog. I suppose I need to update the screen somehow? Or re-enter or something? Cause the changes wont take place in front of my eyes when pressing enter. Please take a look at this and see if I did wrong somewhere?
Comment: Could you provide some of the relevant code that I can check. Maybe you or I miss something.
Comment: Oh ke thought you would use a Stage for GUI stuff. Are you using multiple Screens? And do you see the "just something.." after start up. Also is that really the code you are executing? Seems like there is something missing.
Comment: I added the label in StoScreen to a stage and draws/act it in render. Yes I use mulitple screens. Also, the "just something" I removed to just empty " "
Comment: If you have a Stage why do you render the label manually in the screen with `labelName.draw(game.batch, 1);` if you add the label to a stage. Here is a code example maybe that clear something up. [Code Example](http://pastebin.com/V34LWd2b) But I also recommend if the project is a little bit bigger to use a Skin from a JSON file [Skin](https://github.com/libgdx/libgdx/wiki/Skin)

TextInputListener string into Label


What if Z value I want isn't in the table?

Question: We have a normal distribution of salary. We are told that 25% of the salary workers earn below 180 000 dollars and 25% percent earn above 320 000 dollars.
I want to find the Z value associated with P( X < 180 000).
I look up the solution and this is what I see:
P( X < 180 000) = 0.25
P( X < $\dfrac{180000- \mu }{\sigma}$) = 0.25
We should then find what is the corresponding value to 0.25 in the Z table. However this value isn't there. My Z table starts with 0.5000. I actually want to find $\dfrac{180000- \mu }{\sigma}$.
What do I do?
Update: In the solution they say that Z = $\dfrac{180000- \mu }{\sigma}$ = -0.675 but I have no idea how it was found because even if it was 0.675 I don't know how it relates to the Z table.
Comment: Consider looking at $0.75$ instead.  How should the value for $0.75$ be related to the value you should have expected for $0.25$?  Should these be equal?  Should these add up to $1$?  Should they be related in some other way?
Comment: I have updated the question to add clarification.
Comment: The first line tells you that $P(X \lt 180\ 000)=0.25$, so you can stop there.
Comment: Yes but no I want to find the value of Z so I can use it to find other probabilities. I've edited the question to reflect this more.
Answer: You are expected to use the fact that the normal distribution is symmetric about the mean.  Because the percentages outside $180000$ and $320000$ are the same, the mean is halfway in between, so $\mu=\frac 12(180000+320000)=200000$  Now we need to evaluate the standard deviation.  The Z-score table in Wikipedia lists the chance a random variable is between the mean and some value above the mean.  The chance the variable is less than the mean is $\frac 12$.  We know that $0.75$ of the area is below $320000$ so we need $0.25$ of the area to be between $200000$ and $320000$.  We look in the body of the table for $0.25$ and find it is between the values for $+0.67\sigma$ and $+0.68 \sigma$, so the value $320000$ is $0.675$ sigma above the mean.  We then have $\sigma\approx \frac {320000-200000}{0.675}\approx 178000.$


Passagem por referêcia de uma estrutura com vetor em C!

Question: Tenho o seguinte codigo:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define TAM 3

    typedef struct{
       char nome[50];
       char musica[50];
       int integrantes;
       int ranking;
    }Banda[TAM];

    void ler(Banda *banda){
       int i=0;
       for(i=0;i<TAM;i++){
           printf("Nome da banda: ");
           fgets(banda[i]->nome,50,stdin);
           fflush(stdin);
           printf("Tipo de musica: ");
           fgets(banda[i]->musica,50,stdin);
           fflush(stdin);
           printf("Numero de integrantes: ");
           scanf("%i",&banda[i]->integrantes);
           fflush(stdin);
           printf("Posicao: ");
           scanf("%i",&banda[i]->ranking);
           fflush(stdin);
           printf("\n\n");
       }
    }

void mostrar(Banda banda){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Banda %i\n\n",i+1);
        printf("Nome da banda: %s\n",banda[i].nome);
        printf("Tipo de musica: %s\n",banda[i].musica);
        printf("Integrantes: %i\n",banda[i].integrantes);
        printf("Posicao: %i\n",banda[i].ranking);
    }
}

int main(){
   Banda banda[TAM];
   ler(&banda);
   mostrar(banda);
   return 0;
}

Consigo ler as 3 posições com a função ler(), porém na hora de escrever com a função mostrar(), só a primeira posição é escrita da maneira correta, as outras duas não,(aparecem letras e números aleatórios).
Agradeço a ajuda.
Answer: A declaração da struct não precisa de um tamanho, como está instanciando um vetor de struct no main, ou métodos ler e escrever devem receber vetores (ponteiros), quando pegar a posição de um vetor/ponteiro, não se usa mais -> e sim ..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TAM 3

typedef struct{
    char nome[50];
    char musica[50];
    int integrantes;
    int ranking;
}Banda;//////////////////////////

/////////////////
void ler(Banda banda[]){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Nome da banda: ");
        scanf("\n%50[^\n]",banda[i].nome);
        printf("Tipo de musica: ");
        scanf("\n%50[^\n]",banda[i].musica);
        printf("Numero de integrantes: ");
        scanf("%i",&banda[i].integrantes);////////
        printf("Posicao: ");
        scanf("%i",&banda[i].ranking);///////
        printf("\n\n");
    }
}

////////////////////////
void mostrar(Banda banda[]){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Banda %i\n\n",i+1);
        printf("Nome da banda: %s\n",banda[i].nome);
        printf("Tipo de musica: %s\n",banda[i].musica);
        printf("Integrantes: %i\n",banda[i].integrantes);
        printf("Posicao: %i\n",banda[i].ranking);
    }
}

int main(){
    Banda banda[TAM];
    /////////////////
    ler(banda);
    mostrar(banda);
    return 0;
}

Deixei uma marca nos lugares onde fiz a correção.
Comment: Este código não funciona http://ideone.com/v51JKC
Comment: eu rodei antes de enviar... O que não funciona? não compila ou da algum erro?
Comment: Está executando aí, é só olhar.
Comment: alterei os métodos de entrada, agora está funcionando, tente evitar usar scanf com gets.


Como remover ultimo elemento de uma lista encadeada usando posição?

Question: Estou querendo remover o ultimo elemento de uma lista encadeada digitando a posição n:
quando digito 1,2,3,4,5 do e n=2, quero que fique 1,2,3,5 mas esta dando 1,2,3.
import java.io.IOException;
import java.util.Scanner;

class No {
    int val;
    No prox;

    No(int x) {
        val = x;
    }
}

public class Main {
    public static No removeNElementoDoFim(No cabeca, int n) {

        if (cabeca == null) {
            return null;
        } else {
            No ultimoNo = cabeca.prox;
            No penultimoNo = cabeca.prox;
            for (int i = 0; ultimoNo.prox != null && i < n; i++) {
                penultimoNo = ultimoNo;
                ultimoNo = ultimoNo.prox;
            }
            penultimoNo.prox = null;
            return cabeca;
        }

    }

    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        if (input.length() == 0) {
            return new int[0];
        }

        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for (int index = 0; index < parts.length; index++) {
            if (parts[index].trim().length() > 0) {
                String part = parts[index].trim();
                output[index] = Integer.parseInt(part);
            }
        }
        return output;
    }

    public static No stringToNo(String input) {

        int[] nodeValues = stringToIntegerArray(input);

        No root = new No(0);
        No ptr = root;
        for (int item : nodeValues) {
            ptr.prox = new No(item);
            ptr = ptr.prox;
        }
        return root.prox;
    }

    public static String noToString(No no) {
        if (no == null) {
            return "[]";
        }

        String result = "";
        while (no != null) {
            result += Integer.toString(no.val) + ", ";
            no = no.prox;
        }
        return "[" + result.substring(0, result.length() - 2) + "]";
    }

    public static void main(String[] args) throws IOException {
        Scanner scann = new Scanner(System.in);
        String line;
        while (scann.hasNextLine()) {
            line = scann.nextLine();
            No cabeca = stringToNo(line);

            int n = Integer.valueOf(scann.nextLine());

            No ret = removeNElementoDoFim(cabeca, n);

            String out = noToString(ret);

            System.out.print(out);
        }

        scann.close();
    }
}

Answer: Bom, vamos lá. Estou considerando que seja uma lista encadeada simples.
Irei lhe dizer a lógica:
Dentro do método que irá receber um valor n, você irá:
 1. Verificar se a lista não está vazia
 2. Se você tiver feito um atributo para o tamanho da lista, verifique se o valor digitado é menor ou igual o tamanho (considerando que o usuário digite 0 para o primeiro valor).
 3. Se sim, for menor, você irá fazer o seguinte:
 4. Criar um novo ponteiro auxiliar recebendo o inicio (fazemos isso para não ter que alterar o ponteiro início), exemplo:
no *aux = inicio;

int i;
for(i=0;i<posicao-1;i++) {
   aux = aux.prox;
}

Agora, precisaremos atualizar os ponteiros:
aux.next = aux.next.next;
tam--;

Como no java tem "coletor de lixo", não precisaremos excluir o aux que criamos.
Você pode incluir isso no começo:
   if(posicao<tam && posicao>=0){
     if(posicao==0){
         removerinicio();
   }

Caso o usuário digite 0!
Abraços!!!
Answer: Consegui resolver, mas não da maneira correta:
import java.io.IOException;
import java.util.Scanner;

class No {
    int val;
    No prox;

    No(int x) {
        val = x;
    }
}

public class Main {

    public static No removeNElementoDoFim(No cabeca, int n) {

        // Coloque seu código aqui
        No aux = cabeca;
        if (cabeca == null) {
            return null;
        } else {
            for (int i = 0; i < n - 1; i++) {
                aux.prox.prox.prox = aux.prox.prox.prox.prox;
            }

            return aux;
        }
    }

    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        if (input.length() == 0) {
            return new int[0];
        }

        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for (int index = 0; index < parts.length; index++) {
            if (parts[index].trim().length() > 0) {
                String part = parts[index].trim();
                output[index] = Integer.parseInt(part);
            }
        }
        return output;
    }

    public static No stringToNo(String input) {

        int[] nodeValues = stringToIntegerArray(input);

        No root = new No(0);
        No ptr = root;
        for (int item : nodeValues) {
            ptr.prox = new No(item);
            ptr = ptr.prox;
        }
        return root.prox;
    }

    public static String noToString(No no) {
        if (no == null) {
            return "[]";
        }

        String result = "";
        while (no != null) {
            result += Integer.toString(no.val) + ", ";
            no = no.prox;
        }
        return "[" + result.substring(0, result.length() - 2) + "]";
    }

    public static void main(String[] args) throws IOException {
        Scanner scann = new Scanner(System.in);
        String line;
        while (scann.hasNextLine()) {
            line = scann.nextLine();
            No cabeca = stringToNo(line);

            int n = Integer.valueOf(scann.nextLine());

            No ret = removeNElementoDoFim(cabeca, n);

            String out = noToString(ret);

            System.out.print(out);
        }

        scann.close();
    }
}


How to configure access permissions for Cassandra on Linux Ubuntu

Question: Thank-you for reading this. I am stuck at step three on this tutorial pertaining to installing Cassandra: http://wiki.apache.org/cassandra/GettingStarted#Step_3:_Start_Cassandra
I can only run this software as root. (shouting this over fictional helicopter noise) This seem like a terrible way to run the software.
When starting the Cassandra server as my normal user I receive the following errors:
1.) 15:46:00,147 |-ERROR in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - openFile(/var/log/cassandra/system.log,true) call failed. java.io.FileNotFoundException: /var/log/cassandra/system.log (Permission denied)
2.) ERROR 20:46:00 Doesn't have write permissions for /var/lib/cassandra/data directory
I tried changing the permissions several times and nothing has worked. I tried changing the /var/log/cassandra/system.log permissions for read/write for the cassandra group on the operating-system (OS). The command I used to do this was, sudo chmod 664 /var/log/cassandra/system.log. I found this page helpful in determining how to change the permissions:http://www.linux.org/threads/file-permissions-chmod.4094/
Then, I added my user-name to the cassandra group. From my understanding running the /usr/sbin/cassandra -f command as my user should allow me to access the /var/log/cassandra/system.log file, which would solve one of the errors, error number 1 above.
Respectfully,
user
Answer: Give the user you want permissions to the data and commitlog dirs.
sudo chown -R cassandra:cassandra /var/lib/cassandra/data

sudo chown -R cassandra:cassandra /var/lib/cassandra/commitlog

Comment: These things are already owned by `cassandra` user but I am trying to run the cassandra program as the normal user, lets say `foo` on my operating-system. I was looking to change the permissions on the  `/var/log/cassandra/system.log` anyway not the `/var/lib/cassandra/commitlog`.
Comment: Why do you want to run Cassandra as a normal user?
Comment: The user needs access to all the files
Comment: In terms of information-security it is risky to run a server as root.
Comment: The cassandra user is not root.
Comment: the cassandra group and cassandra user has the privileges to read and write on the `system.log` file so I am not sure why it is unable to write to that log when starting the program like so `/usr/sbin/cassandra -f` as a regular non-root operating system user.
Comment: The cassandra user is a regular non root os user, if you start the process as cassandra it will start given what you mentioned about the permissions you have granted. However, your other users may not have the same privileges.
Comment: 'sudo su - cassandra -s /bin/bash' '/usr/bin/cassandra -f'
Comment: Alternatively, just use the DataStax package install that take care of permissions for you and register cassandra as a service. 'sudo service cassandra start'
Comment: I tried the `sudo su - cassandra -s /bin/bash /usr/bin/cassandra -f` command but this did not work. I just received some sort of usage prompt from `su`. Also, maybe I messed up my installation because I did use the DataStax Ubuntu Linux Debian binary and am unable to start Cassandra as a service.
Comment: They are two separate commands one to access the shell as the cassandra user. The next to start the service from that shell.
Comment: I found a solution! I ran `sudo -u cassandra /usr/sbin/cassandra -f` and then ran into problems with the `commitlog` you mentioned in your answer. I then ran your recursive `chown` command and it started up correctly just as would as the `root` user. :D :D :D
Comment: Good deal glad to help
Answer: I found a solution! I ran sudo -u cassandra /usr/sbin/cassandra -f and then ran into problems with the commitlog directory Phact mentions in his answer. I then ran Phact's recursive chown command, sudo chown -R cassandra:cassandra /var/lib/cassandra/commitlog and the Cassandra server started up correctly just as it would if I was running the program as the root user. :D :D :D


OpenVPN server, UDP port no longer accessible

Question: I am having a strange problem with OpenVPN. The server has worked fine and with no modification for a long time, except for updates. It suddenly stopped working and I can't figure out why. I cannot access its UDP port remotely, from the domU, or the local machine. I can reach all other services.
I have tried disabling iptables as an experiment but I still cannot reach the port. I cannot see anything wrong in the OpenVPN config. Running netstat -lp | grep openvpn reveals that the port is listening. Yet I can't even access it from the local machine.
Here is the OpenVPN config: http://pastebin.com/Gq8CDwVK
Here is the output of iptables -nvL: http://pastebin.com/5MCqTWCE
Here is the output of iptables -nvL -t nat: http://pastebin.com/XxFf0Kb4
I think I've eliminated all the other factors it could be. Please help me diagnose this issue further.
This is the log of the service starting...
Tue Apr 28 07:04:39 2015 us=123021 OpenVPN 2.3.6 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [MH] [IPv6] built on Apr 27 2015
Tue Apr 28 07:04:39 2015 us=123031 library versions: OpenSSL 1.0.1l 15 Jan 2015, LZO 2.08
Tue Apr 28 07:04:39 2015 us=127292 Diffie-Hellman initialized with 2048 bit key
Enter Private Key Password:
Tue Apr 28 07:04:47 2015 us=695418 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Tue Apr 28 07:04:47 2015 us=698002 TLS-Auth MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Tue Apr 28 07:04:47 2015 us=698025 Socket Buffers: R=[212992->131072] S=[212992->131072]
Tue Apr 28 07:04:47 2015 us=698114 ROUTE_GATEWAY 184.108.40.206/255.255.255.0 IFACE=eth0 HWADDR=ba:e5:54:4f:ef:d7
Tue Apr 28 07:04:47 2015 us=698259 TUN/TAP device tun0 opened
Tue Apr 28 07:04:47 2015 us=698294 TUN/TAP TX queue length set to 100
Tue Apr 28 07:04:47 2015 us=698317 do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
Tue Apr 28 07:04:47 2015 us=698340 /bin/ifconfig tun0 10.8.0.1 pointopoint 10.8.0.2 mtu 1500
Tue Apr 28 07:04:47 2015 us=699313 /bin/route add -net 10.8.0.0 netmask 255.255.255.0 gw 10.8.0.2
Tue Apr 28 07:04:47 2015 us=699853 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Tue Apr 28 07:04:47 2015 us=700326 GID set to openvpn
Tue Apr 28 07:04:47 2015 us=700368 UID set to openvpn
Tue Apr 28 07:04:47 2015 us=700394 UDPv4 link local (bound): [AF_INET]188.8.131.52:1194
Tue Apr 28 07:04:47 2015 us=700407 UDPv4 link remote: [undef]
Tue Apr 28 07:04:47 2015 us=700422 MULTI: multi_init called, r=256 v=256
Tue Apr 28 07:04:47 2015 us=700460 IFCONFIG POOL: base=10.8.0.4 size=62, ipv6=0
Tue Apr 28 07:04:47 2015 us=700480 ifconfig_pool_read(), in='client-johntate,10.8.0.4', TODO: IPv6
Tue Apr 28 07:04:47 2015 us=700498 succeeded -> ifconfig_pool_set()
Tue Apr 28 07:04:47 2015 us=700511 ifconfig_pool_read(), in='client-lucasmarshall2,10.8.0.8', TODO: IPv6
Tue Apr 28 07:04:47 2015 us=700521 succeeded -> ifconfig_pool_set()
Tue Apr 28 07:04:47 2015 us=700531 ifconfig_pool_read(), in='client-testuser4,10.8.0.12', TODO: IPv6
Tue Apr 28 07:04:47 2015 us=700543 succeeded -> ifconfig_pool_set()
Tue Apr 28 07:04:47 2015 us=700556 IFCONFIG POOL LIST
Tue Apr 28 07:04:47 2015 us=700570 client-obfuscated1,10.8.0.4
Tue Apr 28 07:04:47 2015 us=700582 client-obfuscated2,10.8.0.8
Tue Apr 28 07:04:47 2015 us=700593 client-obfuscated3,10.8.0.12
Tue Apr 28 07:04:47 2015 us=700632 Initialization Sequence Completed

Edit: I did a further test and it seems the system can't listen on UDP at all. Even with the firewall disabled. This doesn't make any sense at all. To test I used socat to listen to UDP, and hping to test it.
Answer: Is it VPS (OVH) @ Canada? If so then you should contact your support. Your setup looks perfectly normal for me. According to iptables counters dump OS kernel does not receive anything @ openvpn's port (1194/UDP). It smells like connection issues for me. That's why openvpn doesn't work. You can't diagnose it, only your provider can. They usually use complex setup to minimize costs and provide best public IP addresses distribution. It's very easy to do some mistake there.
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   15  3291 ACCEPT     all  --  *      *       10.8.0.0/24          0.0.0.0/0
 217M   74G ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
3155K  189M ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
53874 3814K DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
 357K   12M ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0            icmptype 8 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:1194
 305K   68M UDP        udp  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate NEW
3802K  204M TCP        tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:0x17/0x02 ctstate NEW
 290K   67M REJECT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
 125K 6870K REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-proto-unreachable
    0     0 sshguard   all  --  *      *       0.0.0.0/0            0.0.0.0/0
Can you provide also ifconfig -a output?
You can look at tcpdump/wireshark output as well. It should prove what I say.
You may try to find available udp port in bellow way:

@ server

tshark -i ethX udp or tshark -i ethX -f 'udp' depending on version

@ some client

nmap -sU server's_IP_address -p 1-65535

And observe output @ server. This should tell u what UDP ports are open.
To test OpenVPN u can switch to TCP, it will rule out OpenVPN configuration problems and provide backup connectivity for now.
And good luck!


Increase upload file size by content type

Question: I have worked with our host to increase our upload file size to 2GB.  However, on one page it still states that the files must be less than 3MB.  How do I change that?  I am a Drupal novice so please bear that in mind.
The following is on a content type on our website (classified as a 'story'):

Files must be less than 3 MB. Allowed file types: jpg jpeg gif png txt
  doc xls pdf ppt pps odt ods odp.

So I am trying to increase the size to be 2GB as per what our host is allowing. How do I increase the file size to upload?
Comment: Can you even upload a file that size without a timeout?
Comment: I am not getting and error (not yet anyway).  The following is on a page on our website (classified as a 'story)  "Files must be less than 3 MB.
Allowed file types: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp."  I am trying to increase the size to be 2GB as per what our host is allowing.  How do I increase the file size to upload?  I apologize if I am not clear.  Please let me know if this helps you.  Thank you.
Comment: Kevin,  we have on a different 'page'  at which our limit is 1GB.
Answer: It sounds like the content type "story" has a 3MB limit set on that file field.
You can increase that limit by browsing to "example.com/admin/structure/types" and select the "Manage fields" tab (for the "story" content type). Find the field in question (the file upload field) and edit it. You should find a setting for the maximum upload size there.
If you'd like to learn more about fields, and specifically file fields, check out this Drupal.org resource and and this one as well.
Now, the other thing you will need to review is your .htaccess file. There are a couple of php flags you will want to review:
<code>php_value post_max_size
php_value upload_max_filesize
</code>
Review the .htaccess file first because no matter what setting you set for your file field on the content type "story", it will be overridden by the setting in the .htaccess file.
Comment: Shane et al,  thank you for your responses and assistance in solving this.  And thanks for the education on 'content type', that helps!
Comment: BTW  the .htaccess file does not have anything for max size, this is what it has this:  # Override PHP settings that cannot be changed at runtime.

# PHP 5, Apache 1 and 2.

  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
Comment: Yes, I'm pretty sure the .htaccess change is not required for your issue @javablood , as only one type of content was being affected. Some others may need to use the .htaccess fix for site-wide problems. P.S. please mark this answer as accepted if it fixed your issue. Glad we could help :)
Comment: How do I mark it as answered?  Told you I was a Drupal novice!  :-)  I only see "Answer Your Question" and it did not look like that was it.
Comment: There should be a check mark to the left of this answer that you can check to accept the answer. That's the case for all "Stack Exchange" communities like this one: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: ah, the old check mark routine eh? got it.


How to test if a single proportion is significantly different from zero

Question: I checked a few posts on cv, but couldn't get the exact answer. Which test can I use and test if a single proportion (say proportion of choosing a particular item ) from an AB test is significantly different from zero. Here the hypothesis that I am testing is if significantly more people are choosing from the item, when recommended (the other variant is that they are not offered any items). So, wanted to test significance of that proportion vs. 0.
Can I use a one sample Z test ? with population mean as 0 and the sample standard deviation = standard deviation of the proportion that I wanted to test (against 0)
EDIT: actually the test is an email marketing campaign, one campaign variant which has just the viewed item (left in cart) and other that has 3 recommended items along with the viewed item. I wanted to test if significant proportion of people are clicking or buying the recommended items.
Now given this, how can I calculate the statistically significant number of people clicked and viewed (or bought) the recommended items. Also, should if I am testing the significance of the recommended items bookings or views (if the proportion of people viewed are significantly different from zero), should I calculate my sample size based on this (recommended item's conversion) effect size.
Comment: If anyone chooses the item, the probability of choosing that item is greater than zero, and you reject your null hypothesis with certainty. This fact makes me wonder if you meant to ask a different question. Some of what you're writing makes me think you want to test if two proportions are different. Is that what you want to do?
Comment: I have seen your edit and think you still need to refine your problem. When no recommended products are shown, there's no chance for a person to select a recommended product. When the recommended products are shown, there's a chance that someone will select them. If even one is selected, then you have proof (not evidence, proof) that there's better than zero chance of a recommended item being selected.
Answer: This sounds more like an estimation problem rather than a hypothesis testing problem. As Dave notes, a single selection of the item in the variant group will contradict the hypothesis that the probability of selection is 0 (which is equivalent to saying it is impossible that anyone would select the item when it is recommended, which while physically possible is statistically unlikely).
Let me demonstrate.  The binom library implements several different confidence intervals.  Assuming 1 person in 10,000 buys or selects your product, here would be the confidence intervals:
         method x     n        mean         lower        upper
1  agresti-coull 1 10000 0.000100000 -4.282233e-05 0.0006267439
2     asymptotic 1 10000 0.000100000 -9.598660e-05 0.0002959866
3          bayes 1 10000 0.000149985  1.553338e-07 0.0003907725
4        cloglog 1 10000 0.000100000  1.125906e-05 0.0005843805
5          exact 1 10000 0.000100000  2.531778e-06 0.0005570370
6          logit 1 10000 0.000100000  1.408618e-05 0.0007095439
7         probit 1 10000 0.000100000  1.253757e-05 0.0006322640
8        profile 1 10000 0.000100000  7.735773e-06 0.0004402345
9            lrt 1 10000 0.000100000  1.000000e-04 0.0004388696
10     prop.test 1 10000 0.000100000  5.220037e-06 0.0006492406
11        wilson 1 10000 0.000100000  1.765267e-05 0.0005662689

Note all 11 have a lower bound greater than 0, so you would reject in every case. All it takes is 1 person, which could even be an accident for all you know, to reject your null.  If a test is that fragile, then it isn't worth performing.
I'm not sure what you're interested in, but you could instead just observe how many conversions are made when recommended.  In order to get a confidence interval of radius $r$, you need approximately
$$ n = \left(\dfrac{1}{r}\right)^2 $$
observations.  Frankly, probably fewer than this because conversion is likely very small and so the estimated standard deviation is smaller than 0.5 (an approximation to the true standard deviation which I have made here).
All in all, don't test.  Instead, estimate.
Comment: @tjt This sounds like a classic AB test, so you can search the site for similar questions.  I know I've answered about a dozen or so.
Comment: Thank you Demetri. I have updated my question with details. Sorry for not specifying that earlier


Dynamic pattern validation in Angular 2 and 4

Question: Input validation works fine with a fixed pattern, e.g.
<input type="number"
    [(ngModel)]="info.sortOrder"
    pattern="[0-9][0-9]"
    id="sortOrder" name="sortOrder" #sortOrder="ngModel"/>

When changing the pattern to be evaluated through a function, validation always fails. The function "customPattern()" is called, though.
<input type="number"
    [(ngModel)]="info.sortOrder"
    [pattern]="customPattern()"
    id="sortOrder" name="sortOrder" #sortOrder="ngModel"/>

With
customPattern() { return "[1-9][0-9]"; }

Is this a bug or is this not supposed to work this way?
Comment: this can be easily achieve by switching to model driven form.
Comment: for having dynamic pattern for template driven form, you could create a directive like shown in [this article](http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html)
Answer: I guess you are dong wrong, @black
I would recommend you to use Reactive Forms approach to achieve the desire result.

create a reactive form.
Add the control name for eg('number_validation').
(optional) Register the HTML input element with the formControlName same as above ('number_validation').
create a field 'regex' = '[0-9][0-9]' in the component.ts file.
Bind the [pattern] = regex in the HTML HTML input element tag.
Listen the change and change the regex pattern according to the requirement.

In ts file.
 someForm: FormGroup;

this.someForm= new FormGroup({
        'some_name': new FormControl('', [
          Validators.required])});

regex = /[0-9][0-9]/;

In HTML:
 <input type="number"
    [pattern]=regex
    id="sortOrder"
    formControlName=some_name
    name="sortOrder"/>

Logic :
It depends on the requirement how you are going to change the regex value, dynamically.
eg.
ngAfterViewInit() {
    this.someForm.get('some_name').valueChanges.subscribe(val => {
      if (val === 'anything') {
        this.regex = /change the regex/;
      } else if (val === 'anything_other') {
        this.regex = /change the regex/;
      }
    });
  }

Hope it help you, or other devs! :)
Answer: In reactive forms you could easily do this:
let regPattern = ...; // some logic to determine regex
let lastUsedRegexValidator = Validators.pattern(regPattern);
this.someService.myControl.addValidators(lastUsedRegexValidator)

and in .HTML to check whether we have error:

Pattern error occurred.

Make sure to remove validators when you don't need them anymore before adding new ones, so you don't end up in a situation with a lot of unneeded validators being added.
this.someService.myControl.removeValidators(this.lastUsedRegexValidator)

// for some reason removing like this is not working
this.someService.myControl.removeValidators(Validators.pattern(regPattern))

Answer: In you component, simply define a member variable like this:
export class AppComponent {
 customPattern = '[1-9][0-9]';

In your html, use interpolation like this:
pattern = "{{customPattern}}"

That should work.
Comment: Tell me what is the reason to use string interpolation here? we don't need to show the pattern on DOM?


Can node reference be altered to include views pages?

Question: I have a site where 'related pages' is a node reference CCK field for a node. Authors can add related pages (1 or more) to a node with the autocomplete functionality of node reference.
My question is the following: is it possible to extend the CCK node reference field to include non nodes, e.g. views pages, in this case?
Answer: You could use a separate viewfield for the related views, and theme it so that the nodereferences and viewfields appear in the same list.
You could also use a link and use a custom widget if you don't wanna type the full path every time.
On a couple of sites I ended up never (or very rarely) using a view's page display. Instead I attached the view to a node, and always referred to the view via its node. This was because my advert banner system was based on nodereferences. It's not the most extensible approach, but it worked for those sites.
Answer: There are some major differences between a node and a view. The node is some pieces of data (title, CCK, etc), while the view is constructed by querying the database.
That said it would be possible to make a reference to views. I don't think the approach would be to try to extend the node reference field. Instead you would need to create your own type of CCK field. Unless you know your way around CCK, this could very well be a lot more work than you would like.
You also need to note, that views are more complex than nodes, as they have more viewing possibilities. A view can have an endless amount of different displays, so you would need to not only save the view name but also the display.
The solution would probably end up being so technical, that only expert users would be able to use it. Though I'm against using PHP filter in node, an easier solution would be to create a field, where you could put in a PHP snippet to embed the view you want. views_embed_view I believe it's called, this is what you would have needed in your cck field formatter anyways.
Comment: I agree. Altering the module to include also views is quite difficult; a node reference uses the node ID as reference, while a view reference cannot generally contain a node ID.
Answer: Just adding another solution as @wiifm was looking to only use the nodereferences as hyperlinks. Linkit module + Links + Linkit Views gives a field with a pretty little search widget as well as a WYSIWYG button + IMCE integration.
One config thing to check in my answer re Views Links (to my own question) on configuration.


Some files are deleted from the files table after CRON execution

Question: I am using hook_form_alter() to add a file upload field to the taxonomy term form.
The form itself and the submit are working well. From the submit callback i save the uploaded file using file_save_upload(). This also works well, the is saved in sites/default/files and in the files database. I have noticed that when Drupal CRON is executed the files i saved are deleted, but the other files (from CCK for example) remains in the table. Files are also deleted from the sites/default/files directory.
Here is my code :
/**
 * Implementation of hook_form_alter()
 */
function community_form_alter($form, $form_state, $form_id) {
  switch($form_id) {
    case 'taxonomy_form_term':
      // get the current image if any
      $image = variable_get('community_term_image_'.$form['tid']['#value'], '');
      // load file
      if($image) $image = field_file_load($image);
      $form['identification']['image_preview'] = array(
        '#type' => 'markup',
        '#value' => $image ? theme_imagecache('community-section-title', $image['filepath']) : '',
      );
      $form['identification']['image'] = array(
        '#title' => t('Category image'),
        '#type' => 'file',
      );
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['#submit'][] = 'community_term_form_image_submit';
    break;
  }
}

function community_term_form_image_submit($form, &$form_state) {
  $dir = variable_get('file_directory_path', 'files');
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    // If the term currently contains a picture, we remove it prior to saving
    // the new one
    $current_image = variable_get('community_term_image_'.$form_state['values']['tid'], '');
    if($current_image) {
      $current_image = field_file_load($current_image);
      db_query('DELETE FROM {files} WHERE fid = %d', $current_image['fid']);
      file_delete($current_image['filepath']);
    }
    variable_set('community_term_image_'.$form_state['values']['tid'], $save->fid);
  }
}

Answer: file_save_upload():

The source file is validated as a proper upload and handled as such.
  The file will be added to the files table as a temporary file.
  Temporary files are periodically cleaned. To make the file permanent
  file call file_set_status() to change its status.

You need to use file_set_status() to change the status of the file.
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    file_set_status($save,FILE_STATUS_PERMANENT);
    ...


How to upgrade outdated Drupal 7 version

Question: I'm using Drupal 7.10 which is an outdated version. Is it safe to just upgrade to the latest version or should I upgrade version by version from 7.11 until the latest version 7.21?
Comment: If you have drush installed, you can simply do `drush up drupal` and your update is done! Don't forget to run the database updates after you do this.
Answer: You can upgrade directly to the new version as it contains all the previous changes as well. But don't forget to follow the backup instructions...
Answer: just go to your command prompt , switch to your site folder and use the command "drush pm-update drupal"
this ll help you out ..:)
in an easy way..
happy coading :)
Comment: Thank you for the advise. The drush tool is helpful indeed.


How to create a sql query get the 2nd to Max result in table?

Question: I have a table in snowflake and I want to see the results for the max date and 2nd to Max date. I wrote a query below which gives the results for max date
SELECT MAX(FILE_DATE)  "MAX_DATE"
    ,UPPER(RETAIL)  "SHOP"
FROM PRODUCTS
GROUP BY UPPER(RETAIL)

the results are something like this
MAX_DATE   SHOP
2022-09-27 SHOP1
2022-08-01 SHOP2

I am looking for
2nd_MAX_DATE MAX_DATE   SHOP
2022-08-27   2022-09-27 SHOP1
2022-07-01   2022-08-01 SHOP2

I tried something with where clause WHERE FILE_DATE < ( SELECT MAX(FILE_DATE) FROM "PRODUCTS" GROUP BY UPPER(RETAILER)) but this isn't working
Comment: how many distinct shops in your table?
Answer: One way is to use a cross join.
Here's a full sample roughly altered to your schema using SQL Server syntax.
CREATE TABLE Products (
  Id INT PRIMARY KEY,
  Retail VARCHAR(100),
  FileDate DATETIME
);

INSERT INTO Products (Id, Retail, FileDate)
VALUES (1, 'shop 1', '2022-09-01'),
       (2, 'shop 1', '2022-09-01'),
       (3, 'shop 1', '2022-09-01'),
       (4, 'shop 2', '2022-09-01'),
       (5, 'shop 2', '2022-09-01'),
       (6, 'shop 2', '2022-09-30'),
       (7, 'shop 3', '2022-09-01'),
       (8, 'shop 3', '2022-09-01'),
       (9, 'shop 3', '2022-09-20');

SELECT DISTINCT
    MAX(p1.FileDate) "MAX_DATE",
    UPPER(p1.Retail) "SHOP"
FROM Products p1
    CROSS JOIN Products p2
WHERE
    p1.FileDate > p2.FileDate
GROUP BY
    p1.Retail,
    p2.Retail

Output
2022-09-30|SHOP 2
2022-09-20|SHOP 3

Answer: As you want the latest two file_dates for every shop, you can use WINDOW function
WITH CTE as(
SELECT FILE_DATE
    ,UPPER(RETAIL)  "SHOP"
    , ROW_NUMBER() OVER(PARTITION BY UPPER(RETAIL) ORDER BY FILE_DATE DESC) rn
FROM PRODUCTS
)
SELECT "SHOP",MIN(FILE_DATE) second_date, MAX(FILE_DATE) first_date
FROM CTE
WHERE rn < 3
GROUP BY "SHOP"

Answer:
create or replace TABLE SNOWPARK_QUICKSTART.TELCO.Products (
ID INT,
FileDate TIMESTAMP,
Retail VARCHAR(16777216)
);
INSERT INTO Products (Id, Retail, FileDate)
VALUES (1, 'shop 1', '2022-09-01'),
   (2, 'shop 1', '2022-09-01'),
   (3, 'shop 1', '2022-09-01'),
   (4, 'shop 2', '2022-09-01'),
   (5, 'shop 2', '2022-09-01'),
   (6, 'shop 2', '2022-09-30'),
   (7, 'shop 3', '2022-09-01'),
   (8, 'shop 3', '2022-09-01'),
   (9, 'shop 3', '2022-09-20');

SELECT RETAIL
      ,FILEDATE
      ,IFF(RANK()OVER(PARTITION BY RETAIL ORDER BY FILEDATE DESC)=2,'SECOND MAX DATE','MAX DATE') DAY_DESC
FROM
    Products
GROUP BY
    RETAIL,FILEDATE
QUALIFY
    RANK()OVER(PARTITION BY RETAIL ORDER BY FILEDATE DESC)<3

Comment: You could easily PIVOT this to put Max and Second Max dates on the same row.
Answer: Using the data provided PeteGo as a CTE:
with Products (Id, Retail, FileDate) as
(
    select * from values
        (1, 'shop 1', '2022-09-01'::date),
        (2, 'shop 1', '2022-09-01'::date),
        (3, 'shop 1', '2022-09-01'::date),
        (4, 'shop 2', '2022-09-01'::date),
        (5, 'shop 2', '2022-09-01'::date),
        (6, 'shop 2', '2022-09-30'::date),
        (7, 'shop 3', '2022-09-01'::date),
        (8, 'shop 3', '2022-09-01'::date),
        (9, 'shop 3', '2022-09-20'::date)
)

you can use the window function NTH_VALUE and then combine with DISTINCT to de-dup:
select distinct
    Retail
    ,nth_value(FileDate, 1) over(partition by retail order by filedate desc) as "1st_MAX_DATE"
    ,nth_value(FileDate, 2) over(partition by retail order by filedate desc) as "2nd_MAX_DATE"
from products

gives:

RETAIL
1st_MAX_DATE
2nd_MAX_DATE

shop 1
2022-09-01
2022-09-01

shop 2
2022-09-30
2022-09-01

shop 3
2022-09-20
2022-09-01

But you can see the two values of 2022-09-01 for shop 1 are getting picked.
and can be shown if you also pick the id's:
select distinct
    Retail
    ,nth_value(FileDate, 1) over(partition by retail order by filedate, id desc) as "1st_MAX_DATE"
    ,nth_value(FileDate, 2) over(partition by retail order by filedate, id desc) as "2nd_MAX_DATE"
    ,nth_value(id, 1) over(partition by retail order by filedate, id desc) as "1st_id"
    ,nth_value(id, 2) over(partition by retail order by filedate, id desc) as "2nd_id"
from products

RETAIL
1st_MAX_DATE
2nd_MAX_DATE
1st_id
2nd_id

shop 1
2022-09-01
2022-09-01
3
2

shop 2
2022-09-01
2022-09-01
5
4

shop 3
2022-09-01
2022-09-01
8
7

you can therefore de-dup the shops/dates:
select distinct
    Retail
    ,nth_value(FileDate, 1) over(partition by retail order by filedate desc) as "1st_MAX_DATE"
    ,nth_value(FileDate, 2) over(partition by retail order by filedate desc) as "2nd_MAX_DATE"
from (
    select distinct Retail, FileDate from products
)

now gives a null as I originally expected:

RETAIL
1st_MAX_DATE
2nd_MAX_DATE

shop 1
2022-09-01
null

shop 2
2022-09-30
2022-09-01

shop 3
2022-09-20
2022-09-01


Is there a way to backup logs to tape without mounting a NAS?

Question: The traditional way to send logs to tape backup as I understand it is to mount a NAS which has the ability to do tape backups (or maybe send to a syslog server which in turn mounts a NAS).
Is there a way to backup to tape without mounting a NAS? (Which makes sense in an enterprise environment).
Answer: A NAS is is a fileserver. Period.
To reduce shoe-shining, backup systems frequently back up data to a disk pool first, and then when they have enough data accumulated to fill a tape, they'll relocate that backup job to tape all in one session. The disk pool could be a NAS, or it could be a dedicated array of disks connected to a backup server.
This is not specific to logs, but to any type of data you're backing up.
Hopefully this answers your question. If it doesn't please specify exactly what you are trying to accomplish here, without letting extraneous details get in the way and confuse things.
Edit:
For web logs, two mechanisms come to mind to back them up.

Centralized logging. You should have centralized logging in place anyway. Just configure apache to log via syslog and then you have one server which you back up all of your logs on.
Logstash/Elasticsearch - this is becoming more of a frequent use pattern. Run logstash on your webserver, which ingests your access logs, and then ships them off to an Elasticsearch instance for long-term storage and search.
Comment: @David Please see my edit.
Comment: My perception is that mounting network storage on all of your servers is a messy set up, so I'm trying to get a feel of what the best practice out there is for archiving logs, specifically in the context of Apache logs. Sorry for the ambiguity.
Answer: For example:
<code>ssh www tar c /var/log > /dev/st0
</code>
Or use Bacula (or some other full featured backup software), which is very convenient later, but it takes a considerable time to learn. Setting up the client software on a single machine however is less than a minute if it is packaged for your OS.


Transformar labels de uma CheckBoxList em strings

Question: Tenho um checkboxlist com alguns itens e o nome deles são os diretórios para eu poder salvar o arquivo. Gostaria de saber como eu pego o nome de cada label selecionado do checkboxlist e transformá-lo em uma string. Gostaria de saber uma maneira para que ele salvasse vários arquivos de vez, que são os que estão na checkboxlist.
private void bt_salvar_Click(object sender, EventArgs e)
{
    clsMCI clsmci = new clsMCI();
    string ArtistaDoAlbum;
    string Artista;
    TagLib.File tagFile = TagLib.File.Create(aqui onde gostaria que o nome da label selecionada estivesse);
    tagFile.Tag.Title = tx_titulo.Text;
    tagFile.Save();
}

Answer: Segue alguns exemplos de como capturar o texto de um CheckBoxList
string ex1 = chkLista.SelectedItem.Text;
string ex2 = chkLista.Items[0].Text;

Para salvar um registro para cada item acredito que a melhor maneira é você fazer um foreach, caso tenha entendido errado favor detalhar melhor o problema.
OBS: chkLista = ID DO SEU OBJETO
Comment: eu tentei usar a classe ListItem, só que eu não conseguir adicionar esse classe ao visual studio.


How can I install H5P SCORM libraries?

Question: The subject says it all. I am attempting to install H5P SCORM libraries in an install of Drupal 7.59 and running into a roadblock: None of what I am reading—or understanding—is clear about how to install the libraries. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10). Apache permissions are fine as far as I can see, FWIW and other temp files and uploads work fine on this setup.
I have installed the following two modules in Drupal:

H5P: The core H5P module.
H5P SCORM/xAPI: The H5P SCORM API.

And on the module's install page I have activated all three modules connected to them:

H5P (7.x-1.35)
H5P Editor (7.x-1.35)
H5P SCORM (7.x-2.4)

But when I go to install the libraries… I just can't seem to get them to upload without some error happening such as a problem expanding the archive into the temp/ directory and such. The weird thing is temp direcroures are clearly created, but there is no content in them.
I have even followed the "Better Install Instructions" that appear here as a contributed "issue" but with no luck.
The libraries in question are as follows:

H5PEditor SCORM
H5P SCORM/xAPI

Do the decompressed files need to have a directory name such as H5PEditor.ScormFile.h5p or H5P.Scorm.h5p? Because if I simply rename the files, the created directory is still h5p-editor-scorm-master and h5p-scorm-master.
The tangential question is… Is there simply a way I can just physically place files in the correct directory structure user libraries/? Or must it be installed via the administration interface? It seems to me if I could just drop those files in, Drupal—and the H5P modules—should be able to see them, right?
Answer: See this page about how to manually construct H5P packages and follow the same process for each repo.
You need to download the repo Zip file. Decompress into a temp directory. Delete the LICENSE, README.md, and .gitignore files
Create a new folder to hold the rest of the files like library.json, CSS, JS For the H5P editor, name it H5PEditor.ScormFile. For the h5p-scorm-master, use H5P.Scorm:
Outside of the new folder, create an h5p.json file.
For the H5PEditor.ScormFile, use this:
{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5PEditor.ScormFile", "majorVersion": 1, "minorVersion": 0,"patchVersion": 8, }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}

for the H5P.Scorm, use:
{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5P.Scorm", "majorVersion": 1, "minorVersion": 1, "patchVersion": 16, }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": ["div"]
}

Now Zip up the right h5p.json folder and the H5PEditor.Scormfile or and the other with H5P.Scorm directory. Zip compress each, naming the editor file H5PEditor.ScormFile.h5p and the second library H5P.Scorm.h5p.
Creating H5PEditor.ScormFile.h5p.
So create Zip file renamed to H5PEditor.ScormFile.h5p. Inside of that you have a folder named H5PEditor.ScormFile with contents of the Git repo, https://github.com/pavloshevchuk/h5p-editor-scorm, specified files removed. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5PEditor.ScormFile directory.
H5PEditor.ScormFile.h5p
├── H5PEditor.ScormFile
│   ├── library.json
│   ├── scripts
│   │   ├── scormFile.js
│   │   └── scormFileUploader.js
│   └── styles
│       └── scormFile.css
├── H5PEditor.ScormFile.h5p

Creating H5P.Scorm.h5p.
Create a second Zip file renamed to H5P.Scorm.h5p. Inside of that you have a folder named H5P.Scorm with contents of the Git repo: https://github.com/pavloshevchuk/h5p-scorm, specified files deleted. Place the icon.svg file in a directory called content, inside the Zip file. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5P.Scorm directory. The Zip file contains this structure:
H5P.Scorm.h5p
├── content
│   └── icon.svg
├── h5p.json
├── H5P.Scorm
│   ├── css
│   │   └── scorm.css
│   ├── js
│   │   ├── api
│   │   │   ├── api_1_2.js
│   │   │   ├── api_2004.js
│   │   │   ├── datamodel.js
│   │   │   ├── debug.js
│   │   │   └── flash_detect.js
│   │   └── scorm.js
│   ├── library.json
│   └── semantics.json

You should now have two H5P files and you will now be able to update them at the H5P admin libraries page:
admin/content/h5p

Here's a repo containing the files I made following these instructions:
https://github.com/jackrabbithanna/h5p-scorm-libraries
Comment: @JakeGould I cleaned up a bunch of comments.  Continuing to add to your question after answers have come isn't a great for for any SE site.  https://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions is a starting point for the reasoning behind this.
Comment: I provided the answer for the original question, now you ask a new one. Should be a separate post
Comment: Fantastic! I must have already had the font awesome library from other H5P content types I had installed. Would you like to fork my github repo of the h5p files and make a PR, adding your font awesome library, so that people in the future can just get down to business?
Comment: I know I tried a couple of times before I got it right and didn't get that error. You could look in the site's public files directory and see if a file H5P.Scorm.h5p already exists there, and the delete it, then try the upload again
Comment: If there's an entry in the file_managed database table with a value for the uri column that contains the file name for the .h5p file, try deleting that row in the database.
Comment: Okay, this has been solved on my side. [Details here on the other question](https://drupal.stackexchange.com/a/263273/36892), but on a clean install of Drupal 7.59 I was able to track down the issue being connected to a missing Font Awesome h5p specific library. Once I rolled my own H5P module for Font Awesome and get that installed, everything else worked fine. Thanks for the help and patience on this!
Comment: @jackrabbithanna Feel free to add it on your own. I'm happy you have helped. The reason I won't do a pull request is that my Github profiles is far more public and directly connected to me than my login here. So I don't want to mix the two; I like to divide things that way. So feel free to credit "JakeGould on Stack Exchange" if you wish. Also, [check the bottom of my answer on that other question for a Bash script I quickly put together](https://drupal.stackexchange.com/a/263273/36892) to make life easier getting this stuff setup.

How can I install H5P SCORM libraries?


How to determine which sets are open in a topology?

Question: Given $A_n = \{n, n+1, \dots\} , n \in \mathbb{N} $ and $\tau = \{ \emptyset, A_1, A_2, \dots \} $, I would like to determine which sets are open in $(\mathbb{N}, \tau) $
By definition: $A_n$ is open and any intersection/union of finitely/infinitely many $A_n$ is also open. Furthermore: $A_n$ is infinite, ${A_n}^C$ is finite.
However this does not tell or really help me deciding, what are any other open/closed sets regarding this topology? For example: Is set of odd/even numbers open? What about an arbitrary set? etc.
It seems I am missing a very basic property of topologies. Therefore how does one approach above problem? What am I missing?
Answer: $\tau$ is already a topology on $\mathbb{N}$. The open sets are precisely $\emptyset$ and $A_n$ for $n \in \mathbb{N}$.
Perhaps you meant to ask how to verify that $\tau$ is a topology.
Notice that $A_{n+1} \subseteq A_n$ for all $n \in \mathbb{N}$.
Therefore, $$\bigcup_{i \in S} A_i = A_{\min S} \in \tau$$
for every $S \subseteq \mathbb{N}$.
Also, $$\bigcap_{i=1}^n A_{i} = A_n \in \tau$$
for every $n \in \mathbb{N}$.
We have $\phi \in \tau$ and $\mathbb{N} = A_1 \in \tau$. We conclude that $\tau$ is a topology.
Answer: The meaning of the word 'topology' is the collection of all open sets. Therefore, if someone tells you that the topology is
$$\tau=\{\emptyset, A_1,A_2,\dots\}$$
then this is precisely the collection of all open sets. There are no others. You can check that this is indeed a topology, i.e., the union open sets is open (that is, a member of the set $\tau$), etc.
Answer: EDIT: This answer is based on a misreading of the question. I read the question as asking about the topology generated by $\{A_n: n\in\mathbb{N}\}\cup\{\emptyset\}$ - equivalently, asking to prove that that that set is already a topology.
As noted above, given that the OP already is told that $\{A_n: n\in\mathbb{N}\}\cup\{\emptyset\}$ is a topology, their question does boil down to just understanding how a topology describes open sets (namely, that the topology is exactly the set of open sets).
However, I suspect that the OP may be confused about why this family is a topology on $\mathbb{N}$. Since I think my (misinformed) answer may be useful to them with respect to this, I've left it up (with minor changes).

A set with the property that its complement is finite is called cofinite. For example, all the $A_i$s above are cofinite.
Here are a couple hints towards showing that the set of even numbers is not open in the above sense:

Show that the union of aritrarily many cofinite sets is cofinite. (HINT: any set containing a cofinite set is cofinite ...)
Show that the intersection of finitely many cofinite sets is cofinite. (HINT: think about the complement of a finite intersection of cofinite sets - remember that the complement of an intersection is the union of the complements ...)
Conclude that every open set (in the sense above) is cofinite.

Note that the above does not fully characterize the open sets (again, in the sense of your question). For example, the set of all numbers except $3$ and $17$ is cofinite; is it open?

Show that if $B$ is open in the sense above, and $b\in B$ and $c>b$, then $c\in B$.
Use the above to give a complete characterization of the open sets in the sense above.


Two-column text layout with irregular inset

Question: One picture worth a thousand words:

How to implement this layout? I want text to flow freely from Column-1 to Column-2.
Note that inset width is greater than column width, so it "pushes" text in Column-1 a bit. Below inset Column-1 returns to normal width.
I want compatibility with latest releases of modern browsers (Chrome, FF). No IE is OK. Safari, Mobile Safari, Opera are desirable.
JS is OK, but I'd prefer a solution without it.

Update about known dimensions:

I know width and height of whole "page".
I know width and height of image.
I know width of inset, but not its height (since there is additional caption text there).

Update:
Below is my test code. If I move inset out of columns div, it is displayed as "third column".
If inset is in front of the text, it is displayed in the left column at the top, clipped from the left side to the column width.
If inset is in end of the text, it is displayed in the right column at the bottom, clipped from the left side to the column width in Chrome, and overflowing to the left column in FF (without pushing its text).
I must be missing something... :-(
<!DOCTYPE html>

<meta charset="utf-8">

<title>Column test</title>

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc neque elit, mollis a vulputate ac, mollis vitae augue. Sed augue enim, congue ac laoreet hendrerit, ultricies a sem. Integer dignissim molestie erat quis lacinia.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc neque elit, mollis a vulputate ac, mollis vitae augue. Sed augue enim, congue ac laoreet hendrerit, ultricies a sem. Integer dignissim molestie erat quis lacinia. Nulla pellentesque sodales dolor, et egestas tortor ultricies et. In hac habitasse platea dictumst. Nunc semper dui sit amet sem condimentum vitae molestie arcu cursus. Morbi rhoncus posuere gravida. Sed bibendum ullamcorper lectus, id mollis nulla pulvinar hendrerit. Mauris id est nulla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam tempor venenatis vehicula. Nam a enim justo, nec viverra sem. Vivamus faucibus ullamcorper lobortis.

Cras nulla ante, tincidunt non accumsan nec, adipiscing eget odio. Nam gravida ligula at elit interdum lacinia. Mauris condimentum justo venenatis mauris condimentum eu fringilla augue hendrerit. Duis eget enim et erat faucibus blandit et lobortis ligula. Integer felis justo, feugiat et scelerisque non, vehicula in urna. Aliquam dignissim tristique ornare. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam volutpat ullamcorper purus, ut auctor magna consectetur at. Aliquam vitae odio in lectus lobortis fermentum. Nunc tortor quam, luctus et consequat vel, fringilla at lorem. Cras ut molestie diam. In aliquet purus sed massa sagittis id dapibus est ultricies. Mauris sed laoreet est.

In hac habitasse platea dictumst. Integer mollis dapibus tellus, at venenatis mi euismod quis. Donec quis ullamcorper nulla. Maecenas semper porttitor nibh, et porttitor ipsum convallis eget. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec est turpis, faucibus id venenatis ac, mollis ut risus. Nam tincidunt scelerisque lectus.

Donec euismod neque id est accumsan eu egestas tortor adipiscing. Curabitur tortor ante, mattis at ultrices vel, facilisis eu sapien. Nullam congue ipsum vel nisi condimentum quis condimentum turpis pretium. In aliquet imperdiet ligula, ut dictum lorem ultrices at. Quisque ac nunc arcu. Pellentesque egestas venenatis urna, in blandit purus ullamcorper at. Ut lobortis, nisi at pharetra consequat, est nibh interdum est, vitae tempor felis magna sed erat. In hac habitasse platea dictumst.

Sed ligula felis, volutpat ac pulvinar a, porta sed felis. Aenean eu turpis nec magna mollis tincidunt quis vitae massa. Praesent faucibus nisl in leo rutrum gravida. Donec aliquet interdum vestibulum. Aenean faucibus posuere ornare. Donec sed velit id sem pulvinar faucibus ut tempor tellus. Donec ante justo, egestas eget venenatis vitae, tempor et nulla. Suspendisse dapibus pellentesque nulla sit amet tempor. Curabitur auctor, sem id ullamcorper ultricies, nisl tortor rhoncus lorem, eleifend ornare tortor ante vel lectus. Nunc lectus sem, ullamcorper vitae aliquam sed, volutpat eu justo. Nam et nisl est, dictum vestibulum dolor. Cras ipsum orci, vestibulum ac convallis a, laoreet in lorem. Aliquam at adipiscing lacus. Donec quis dui sed felis sollicitudin ultricies in vel libero. Donec tincidunt felis et metus mollis at congue elit molestie.

Ut posuere lobortis est, sit amet adipiscing neque vehicula eu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam id fermentum felis. Aenean nunc neque, faucibus vel consectetur eget, ullamcorper ac est. Nulla sit amet metus sed erat fringilla lacinia. In at pulvinar sapien. Mauris volutpat scelerisque elit, quis lobortis orci imperdiet pretium. Ut facilisis interdum dapibus. Sed luctus dignissim blandit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin ultricies tortor nec rutrum.

Quisque sed sollicitudin lacus. Quisque egestas interdum dui, eget gravida sem convallis in. Sed auctor justo et urna gravida tincidunt. Proin erat nibh, euismod et varius at, aliquam in diam. Nullam condimentum libero id libero pretium ac ullamcorper arcu luctus. Sed gravida mattis tortor sit amet accumsan. Etiam vitae consequat dolor.

Answer: How about making the image with its caption in a separate CSS layer and "pinning" it into the right position, coupled with some DIV's underneath which take care of pushing the content out from under it?  Something like this:
In CSS:
#column1 {
    color: white;
    width: 200px;
    background: #444;
    height: 300px;
    float: left;
    margin-right: 5px;
}
#column1-spacer {
    float: right;
    width: 45px;
    height: 170px;
}
#column2 {
    color: white;
    width: 200px;
    height: 300px;
    background: #444;
    float: left;
    margin-left: 5px;
}
#column2-spacer {
    height: 175px;
}
#imageWrapper {
    background: white;
    position: absolute;
    left: 170px;
    width: 250px;
    height: 170px;
}
#image {
    margin-left: 10px;
    width: 240px;
    height: 125px;
    background: #888;
}
#caption {
    font-size: 0.85em;
    margin-left: 10px;
}

And in HTML:

    Column 1

    Column 2

Image

        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Maecenas vel vulputate justo.

In my Firefox, it produces this:
Comment: You split columns into two divs. This wouldn't do for me, unfortunately. I need text to flow freely from one column to another.
Answer: curtisdf has answered the issue of the image placement but as far as flowing text freely from column 1 to column 2 the easiest way would be to use CSS 3 columns. You can make CSS 3 columns work in browsers that don't support CSS 3 by adding modernizer to your site.
Modernizer: http://www.modernizr.com/
CSS 3 Columns: http://www.w3.org/TR/css3-multicol/
Comment: I was not able to do this with CSS3 columns — inset gets clipped by column width. Can you please provide a simple example?
Comment: Also, unless I'm missing something, Modernizr only informs me about feature support, it does not implement the missing features, so it is of little help here (unless I know how to implement the columns, which I obviously don't).


Windows 7 Slipstream will not enter Audit Mode

Question: I have two sets of Dell Laptops that I'm trying to install Windows 7 x64 on. I downloaded the driver packs from Dell's Enterprise site, and slipstreamed them into my install.wim file. On one notebook, it works perfectly fine, and I can enter Audit mode. On the other, I press Ctrl+Shift+F3, and am presented with a black screen with the mouse cursor. Nothing happens, I can't bring up any tools (i.e. Task Manager, UtilMan, etc). All I can do is restart.
I tried to kill the OOBE on the reboot, but then I was left without an account to use to log in. If I use the UtilMan-CMD hack, I can use the Administrator profile, but sysprep.exe will not load - It claims Windows Updates are requiring a reboot, and to try again. Even after rebooting, no change.
How can I get into Audit Mode on this second model? I have tried waiting over an hour to see if it will do its automatic reboot to enter Audit mode, but it never does.
Answer: Core issue unknown, but it's solved.
After attempting to log in to Audit mode, I tried rebooting into Safe Mode. It brought up the message that you can't complete setup in Safe Mode, then it restarted in Audit Mode automatically after rebooting.
If anyone knows why this would happen, please feel free to edit.


Are $S^1$ and $O_2(\mathbb{R})$ isomorphic?

Question: Let $S^1 = \{z \in \mathbb{C} | |z| = 1\}$ and $O_2(\mathbb{R}) = \{A \in GL_2(\mathbb{R})|A^TA = I_2 \}$. Is the group $(S^1, \cdot)$ isomorphic to $(O_2(\mathbb{R}), \cdot)$? Prove it.
This is a question from "Prova Extramuros (2013)", a exam from Brazil. This question asks which of the options are isomorphisms. I easily found the correct option, but in this one I had a little trouble in proving that there was no isomorphism. I interpreted $(S^1, \cdot)$ as a rotation group and $(O_2(\mathbb{R}),\cdot)$ as a rotation and reflection group, so they could not be isomorphic. Is this reasoning correct? Is there a way to prove it more rigorously?
Comment: What have you tried?
Comment: What have you tried? Alternatively, what is the context behind this problem; where did you find it, and what relevant knowledge do you have? I suggest you read [this post](https://math.meta.stackexchange.com/q/9959) about what you are expected to do when you ask a question on this site. Questions that offer no context or work shown tend to get downvoted and closed, which I imagine you would like to avoid.
Comment: @Bernardo $S^1$ is abelian but $O_2(\Bbb R)$ is not, so the two groups are not isomorphic.
Comment: @Bernardo Your statement "one is a rotation group and the other is a rotation and reflection group" is not enough justification. You have only stated that the groups are superficially different, but not that they have enough of a difference for us to know that they are not isomorphic.
Comment: Hint: orthogonal matrices can be written in a certain form.
Answer: $S^1$ has exactly one element of order $2$: namely $-1$.
$O_2(\Bbb R)$ has at least three: $-I$ and two others formed by changing the sign of exactly one diagonal entry.
Since an isomorphism preserves orders, the two cannot be isomorphic.


Logistic regression and scaling of features

Question: I was under the belief that scaling of features should not affect the result of logistic regression. However, in the example below, when I scale the second feature by uncommenting the commented line, the AUC changes substantially (from 0.970 to 0.520):
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics

cancer = load_breast_cancer()
X = cancer.data[:,0:2] # Only use two of the features
#X[:,1] = X[:,1]*10000 # Scaling
y = cancer.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)

fpr, tpr, _ = metrics.roc_curve(y_test, log_reg.predict_proba(X_test)[:,1])
auc = metrics.auc(fpr, tpr)
auc

I believe this has to do with regularization (which is a topic I haven't studied in detail). If so, is there a best practice to normalize the features when doing logistic regression with regularization? Also, is there a way to turn off regularization when doing logistic regression in scikit-learn
Answer:
I was under the belief that scaling of features should not affect the result of logistic regression. However, in the example below, when I scale the second feature by uncommenting the commented line, the AUC changes substantially (from 0.970 to 0.520) ... I believe this has to do with regularization

That is a good guess. If you look at the documentation for sklearn.linear_model.LogisticRegression, you can see the first parameter is:

penalty : str, 'l1' or 'l2', default: 'l2' - Used to specify the norm used in the penalization. The 'newton-cg', 'sag' and 'lbfgs' solvers support only l2 penalties.

Regularization makes the predictor dependent on the scale of the features.

If so, is there a best practice to normalize the features when doing logistic regression with regularization?

Yes. The authors of Elements of Statistical Learning recommend doing so. In sklearn, use sklearn.preprocessing.StandardScaler.
Comment: @se7entyse7en In the 2nd edition, it is in Secion 3.4 (Shrinkage Methods), on the penultimate paragraph of page 63: "The ridge solutions are not equivariant under scaling of the inputs, and so one normally standardizes the inputs before solving...".
Comment: @matthiash Great! However, I strongly encourage you to read up on sklearn pipelines. They will allow you to do this right also on cross validations on stuff. Pipelines are a cornerstone of sklearn, IMHO.
Comment: @AmiTavory can you please specify where the authors of ESL states that features normalization is recommended?
Comment: Perfect! `from sklearn.preprocessing import StandardScaler; X_train, X_test, y_train, y_test = train_test_split(StandardScaler().fit_transform(X), y, test_size=0.33, random_state=42)` gives an AUC of 0.972, greater than in both of the earlier cases.
Comment: Are there any arguments in favour of generally using standard scaling over min-max scaling?
Comment: I was curious about this as well, but I tried setting the `penalty=None` and I found equivalent results.  The solver was `libfgs` which should be "robust to unscaled datasets according to [this table](https://scikit-learn.org/stable/modules/linear_model.html#solvers), but unless I'm missing something this isn't the case...


How to use Model.query() with promises in SailsJS/Waterline?

Question: I'm having issues with Sails.JS 0.9.8.
I would like to use promises with the Model.query() function (I use sails-mysql adapter).
This code will work :
User.findOne({ email: email })
.then(function(user) {
  console.log(user);
});

but this one won't
User.query("SELECT email FROM user WHERE email = ?", [ email ]))
.then(function(err, rows) {
  console.log(rows);
})

I get undefined for both 'err' and 'rows'.
Is it just not implemented or I am doing something wrong ?
If not implemented, is there any alternative to use promises with .query() ?
Thank you in advance
Answer: You can promisify(User.query) yourself, just like you'd do for any other callback-based API, like:
var Promise = require('bluebird');

....
var userQueryAsync = Promise.promisify(User.query);
userQueryAsync("SELECT email FROM user WHERE email = ?", [ email ])
.then(function(user) {
    console.log(user);
});

Comment: Very nice-- we're now linking here from the reference page from `.query()` in the sails docs.
Comment: I get only
node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:77
        throw err; // Rethrow non-MySQL errors
        ^

RangeError: Offset is out of bounds
Answer: As a hack you can monkeypatch all your models in bootstrap like this
module.exports.bootstrap = function(cb) {
    var Promise = require('bluebird');

    Object.keys(sails.models).forEach(function (key) {
        if (sails.models[key].query) {
            sails.models[key].query = Promise.promisify(sails.models[key].query);
        }
    });

    cb();
};

Answer: The query method is specific to sails-mysql, and doesn't support deferred objects the way that the more general Waterline adapter methods (e.g. findOne, find, create, etc) do.  You'll have to supply a callback as the second argument.
Answer: In case you do not want to use promisify but do want SailsModel.query to
return a promise.
/**
 * @param {Model} model - an instance of a sails model
 * @param {string} sql - a sql string
 * @param {*[]} values - used to interpolate the string's ?
 *
 * @returns {Promise} which resolves to the succesfully queried strings
 */
function query(model, sql, values) {
  values = values || [];

  return new Promise((resolve, reject) => {

    model.query(sql, values, (err, results) => {
      if (err) {
        return reject(err);
      }

      resolve(results);
    });
  });
}

// and use it like this
query(User, 'SELECT * FROM user WHERE id = ?', [1]).then(console.log);


Real Analysis, Folland problem 3.5.27 Functions of Bounded Variation

Question: Background Information:
If $F:\mathbb{R}\rightarrow \mathbb{C}$ and $x\in\mathbb{R}$, we define $$T_{F}(x) = \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1})|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}$$ $T_F$ is called the total variation of $F$. We observe that the sums in the definition of $T_F$ are made bigger if the additional subdivision points $x_j$ are added. Hence, if $a<b$, the definition of $T_F(b)$ is unaffected if we assume that $a$ is always one of the subdivision points. It follows that $$T_F(b) = T_F(a) + \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1})|:n\in\mathbb{N},a=x_0<\ldots<x_n = b\}$$  Thus $T_F$ is an increasing function with values $[0,\infty]$. If $T_F(\infty) = \lim_{x\rightarrow\infty}T_F(x)$ is finite, we say that $F$ is of bounded variation on $\mathbb{R}$, and we denote the space of all such $F$ by $BV$.
Problem 27:
a.) If $F:\mathbb{R}\rightarrow \mathbb{R}$ is bounded and increasing, then $F\in BV$ (in fact, $T_F(x) = F(x) - F(-\infty)$).
b.) If $F,G\in BV$ and $a,b\in\mathbb{C}$, then $aF + bG\in BV$.
c.) If $F$ is differentiable on $\mathbb{R}$ and $F'$ is bounded, then $F\in BV([a,b])$ for $-\infty < a < b < \infty$(by MVT).
d.) If $F(x) = \sin x$, then $F\in BV([a,b])$ for $-\infty < a < b < \infty$, but $F\notin BV$.
e.) If $F(x) = x\sin(x^{-1})$ for $x\neq 0$ and $F(0) = 0$, then $F\notin BV([a,b])$ for $a\leq 0 < b$ or $a < 0\leq b$.
Attempted proof a.) If $F:\mathbb{R} \rightarrow\mathbb{R}$ and $x\in\mathbb{R}$, then $$T_F(x) = \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1}|):n\in\mathbb{N}, -\infty < x_0 < \ldots < x_n = x \}$$
Since $F$ is increasing, the intervals $(F(x^-),F(x^+) (x\in\mathbb{R})$ are disjoint, and for $|x| < N$ they lie in the interval $(F(-N),F(N))$. Hence $$\sum_{|x| < N}|F(x^{+} - F(x^{-1}| \leq F(N) - F(-N) < \infty$$
so now we know $F$ is finite, therefore the total variation of $F$ is also finite, therefore $$\lim\limits_{x\rightarrow \infty}T_F(x) = T_F(\infty)\Rightarrow F\in BV$$
Attempted proof b.) Since $F,G\in BV \Rightarrow \lim_{x\rightarrow \infty}T_F(x) = T_F(\infty)$ and $\lim_{x\rightarrow \infty}T_G(x) = T_G(\infty)$ since $a,b$ are just scalars it follows that $$\lim_{x\rightarrow \infty} aT_F(x) + bT_G(x) = aT_F(\infty) + bT_G(\infty) \Rightarrow aF + bG\in BV$$
Attempted proof c.) Not sure
Attempted proof d.) Not sure
Attempted proof e.) Not sure
I just want to know if my two proofs are correct or not and what suggestions or hints that I could be provided for proving c,d,and e.
Comment: A good place to start would have been to define $BV([a,b])$ since I don't see a definition in your question ; you only defined $BV(\mathbb R)$, so to speak.
Answer: Hints:
b) is quite easy so no hint (except telling you it's easy is a hint).
c) $\sum_{1}^{n}|F(x_j) - F(x_{j-1})| = \sum_{1}^{n}|f'(c_j)(x_j - x_{j-1})|.$
d) Consider $\sum_{k=1}^{n} |F (\pi/2 + 2k\pi) - F (2k\pi)|.$
e) Let $y_k=1/(\pi/2 + 2k\pi), x_k = 1/( 2k\pi).$ Consider $\sum_{k=1}^{n} |F( y_k) - F(x_k)|.$
Answer: a). Your proof is correct.
b). Your proof is ok. You can also prove it by using the fact that
$$
|aF(x_i)+bG(x_i)-(aF(x_{i-1})+bG(x_{i-1}))|\leqslant|a||F(x_i)-F(x_{i-1})|+|b||G(x_i)-G(x_{i-1})|
$$
So
\begin{align}
T_{aF+bG}&=\sup(\sum_{i=1}^n|aF(x_i)+bG(x_i)-(aF(x_{i-1})+bG(x_{i-1}))|)
\\
&\leqslant|a|\sup(\sum_{i=1}^n|F(x_i)-F(x_{i-1})|)+|b|\sup(\sum_{i=1}^n|G(x_i)-G(x_{i-1})|)
\\
&<\infty
\end{align}
c). By MVT
$$
T_F=\sup(\sum_{i=1}^n|F(x_i)-F(x_{i-1})|)=\sup(\sum_{i=1}^n|F'(\xi_i)(x_i-x_{i-1})|)\leqslant M(b-a)
$$
where $|F'(x)|<M$ and $x_i>x_{i-1}$.
d). On $[a,b]$, since $F'(x)=\cos x$, by c) $F$ is of bounded variation. On $(-\infty, \infty)$, let $x_{2n}=2n\pi+\pi/2$ and $x_{2n-1}=2n\pi-\pi/2$. Then
$$
T_F=\sup(\sum_{n=1}^{\infty}|F(x_n)-F(x_{n-1})|)=\infty
$$
e). Note that on any $(0,\epsilon)$, $F(x)=x\sin {\frac1{x}}$ has infinite $0$. Let $x_{2n}=\frac1{2n\pi+\pi/2}$ and $x_{2n+1}=\frac1{2n\pi+\pi}$. Then
$$
T_F=\sup(\sum_{n=1}^{\infty}\frac1{2n\pi+\pi/2})=\infty
$$