I need help writing the correct boolean function for a circuit

Question: I was given a pre-made circuit. I was tasked with determining the input/output table and also the correct boolean function.
The results of the input/output table is:
~x,~y = 0
~x,y = 0
x,~y = 0
x,y = 1
From the results, I think the boolean function should simply be
f(x,y) = xy
The confusion comes when I analyze the circuit. It gives the formula:
~(~x y + ~(x y))
Am I overthinking things or is there more to boolean function?
Comment: Looks like an **AND** function.
Answer: One thing I would advise is to break yourself of the habit of using
the symbol "$\require{begingroup}
\begingroup=$" to signify a relation between things that are not equal.
Unless you've been told to use "," in "$x,y$" as some sort of operator I've never seen a "," used for,
$x,y$ by itself isn't really a meaningful expression.
If you write it like $\{x,y\}$ you have a set of one or two elements
(only one element if $x = y$);
if you write $(x,y)$ you have an ordered pair of two elements.
Since it makes little sense to write the input to a Boolean function
as a set, you presumably meant to write ordered pairs.
So now it looks like you tried to write $\newcommand{\lsim}{\mathord{\sim}}(\lsim x,\lsim y) = 0$
and $(\lsim x,y) = 0.$
By the transitive and symmetric properties of equality, that means
$(\lsim x,\lsim y) = (\lsim x,y),$ which is never a true statement
for any values of $x$ or $y.$
It was better before (although still wrong) when you were using $1$ and $0$ instead of $x$ and $\lsim x.$
It is still not true that $(0,0) = 0$ and $(0,1) = 0,$ because
$(0,0) \neq (0,1),$
but you could have fixed the equations with just one extra symbol per line:
\begin{align}
f(0,0) &= 0 \\
f(0,1) &= 0 \\
f(1,0) &= 0 \\
f(1,1) &= 1 \\
\end{align}
This says that when we take the two inputs $0$ and $0$ and
apply the Boolean function $f$ to them, the result is $0,$ and so forth
for other possible input values.
I think that's what you meant to write in the first place,
but by not actually writing what you meant (by forgetting to give any
indication that a function was being applied to the two numbers on the
left of each equation), you wrote nonsense,
and confused yourself into writing things like
$f(x,y) = x,y$ which I'm sure is not at all what your circuit was supposed to be about.
To the names of functions when you functions like to something in English while no verbs. (That is, "Neglecting to write the names of functions when you use functions is like trying to explain something in English while using no verbs.")
If we try to write your edited equations as applications of the function $f,$
however, we get things like this:
$$ f(x,y) = 1. $$
What does that mean? We don't usually have a rule that the symbol $x$
always represents a $1$; instead, $x$ might be $1$ or might be $0.$
Likewise, $y$ might be $1$ or might be $0.$
But if $x=0$ and $y=1$ (which is a possible assignment),
you have just asserted that $f(0,1) = 1,$ which I'm fairly sure
is not something your Boolean circuit would agree with.
So yes, there is something more to Boolean functions than
$f(x,y) = x,y.$
For the "correct Boolean function" part of the question, I suppose you were meant to put something on the right-hand side of
$f(x,y) = \ldots$
that would make a true equation for all $x$ and $y.$
It seems that by examining the circuit you have concluded that
$f(x,y) = \lsim((\lsim x) y + \lsim(x y)).$
You can also replace the right-hand side of this equation with
a much simpler expression involving $x$ and $y.$
Possibly you were meant to write the simpler expression,
but we'd have to see exactly how the problem was put and how similar
examples were previously answered in order to say whether the
exercise was to copy the circuit literally or to find the
simplest equivalent form.
Comment: I understand. I'm just writing them how it was shown to me. For instance, I have a sample function that is written out as:  f(x,y,z) = xyz+~xyz+xy~z+~x~y~z  (the "~" being complements)
Comment: Your last edit, $f(x,y)=xy,$ looks OK to me. The sample function in your comment is in disjunctive normal form, and $f(x,y)=xy$ also is in disjunctive normal form and is equivalent to the other formula you got, so I expect that's the intended answer. (The formulas in the "results of the input/output table" still don't make any sense, which was making the question unclear, but that's a separate part of the exercise.)
Comment: I understand. It was a mistake on my part. My main point of confusion was choosing which of the correct answers, were the proper expression. What threw me off was that I had never seen a boolean function that wasn't in the form  of "f(x,y,z) = xyz+x~yxz, etc". So seeing the formula have parentheses, made me think that maybe it was something new that I hadn't learned yet. I've only been learning this class for 2 weeks


How do transitive dependencies work in Python pip?

Question: I have an automated machine build that installs a Python package (Package A) with a ton of dependencies (Packages X, Y, and Z).  Package A doesn't pin the versions of packages X, Y, or Z, so even though I pin the version for package A, there have been a bunch of times when my builds fail because of a breaking update in package X.
To fix this, I was planning on making a requirements.txt file that pinned explicit versions of A, X, Y, and Z (rather than just A, which is what happens now).  This should work assuming pip has proper support for both pinning and transitive dependency resolution.
It seems like this works with my current version of pip, but I've found a lot of conflicting information about how pip handles these things (eg, this thread with 100 comments talking about how pip dependency resolution isn't great).
So my questions:

How does dependency resolution work in pip?  If package A depends on X>=7, and my top-level requirements.txt specifies X==8, is it possible that pip would install X version 9 because it looks at A first and tries to get the most recent version of transitive dependencies?
Is there a canonical / authoritative source describing how dependency resolution works in pip?  The best I've been able to find is this page, but some of the comments I've seen online make it seem like that page isn't 100% correct where transitive dependencies are concerned.

Thanks!
Comment: I'm very interested in finding out more about this as well and will provide some bounty points if necessary.
Answer: pip introduced a new resolver in 20.3 and from 21.0 this is now the default resolver.
The new resolver fixes the inconsistencies outlined in your first question and not only that. When dependency packages are inconsistent (e.g. X>=7 and X==6) it will reject the installation all together.
The new resolver is resolvelib based so you can find details about the algorithm there but pip also updated the docs about dependency resolution with some details like the backtracking they do.


Sort hash elements in-place within an array

Question: I have an array. Some elements are hashes. I want to sort the hashes in-place and leave the array elements in order.
Can I improve this code?
def sort(args)
  args.map! do |arg|
    arg.is_a?(Hash) ? arg.sort : arg
  end
end

For example:
sort [{"b"=>"2", "a"=>"1"}, "x"]
=> [{"a"=>"1", "b"=>"2"}, "x"]

Answer: AFAIU your question is how to sort a hash inplace, since you don't need any modifications to original array but those. To sort a Hash inplace you might use:
hash.keys.sort.each { |k| hash[k] = hash.delete k }

Putting it all together:
def sort args
  args.each { |el|
    el.keys.sort.each {|k|
      el[k] = el.delete k
    } if Hash === el
  }
end

res = sort [{"b"=>"2", "a"=>"1"}, "x"]
puts res
# ⇒ [{"a"=>"1", "b"=>"2"}, "x"]

Hope it helps.


Contador de if em um arquivo de texto

Question: Pessoal estou tentando fazer um programa que conta a quantidade de ifs em qualquer texto, mas por algum motivo ele não conta todos, se puderem me ajudar agradeço
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    FILE *arq;
    char str[24];
    int count = 0;
    arq = fopen("texto.txt","r+");

    while(fgets(str,sizeof(str),arq) != NULL){
        if(strstr(str,"if") != NULL){
            count++;
        }
    }

    fclose(arq);

    printf("Qt : %i",count);
}

Conteudo do "texto.txt"
1 if if if if
2 if if if if if if if if
3 if if if if if if if if if if if if
4 if if if if if if if if if if if if if if if if
total = 40

Quando rodo o programa são exibidos apenas 8.
Comment: Olá, pode compartilhar onde pegou essa lógica? testei seu código e agora lê normalmente, ´mas alterei apenas uma linha e gostaria de entender melhor como esta lógica trabalha.
Comment: Da maneira como declarou sua string `str` você precisa fazer um outro loop para contar em cada string lida. Por exemplo a linha 4 contém 49 caracteres.
Comment: Por acaso a aplicação desse algoritmo seria para se calcular a [complexidade ciclomática](https://pt.wikipedia.org/wiki/Complexidade_ciclom%C3%A1tica) de um determinado código ?
Comment: @anonimo, a resposta para isso é não, vão é necessário.
Comment: @Brewerton: Mas a função `strstr` sempre parte do início da string. No caso do exemplo do post ele conta apenas a primeira ocorrência de cada linha lida, como ele declarou str[24] e existem linhas com mais de 24 caracteres a função `fgets` faz várias leituras de tais linhas. Creio que a função `strtok` é que varia o ponteiro a cada localização.
Answer: Olá, mude o tamanho de str para 4 e o resultado será como esperado.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    FILE *arq;
    char str[4];
    int count = 0;
    arq = fopen("texto.txt","r+");

    while(fgets(str,sizeof(str),arq) != NULL){
        if(strstr(str,"if") != NULL){
            count++;
        }
    }

    fclose(arq);

    printf("Qt : %i",count);
}

Answer: Opção percorrendo a string lida:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {
    FILE *arq;
    char str[255], *p;
    int count = 0;
    arq = fopen("texto.txt","r+");
    while(fgets(str,sizeof(str),arq) != NULL){
        p = str;
        while ((p = strstr(p, "if")) != NULL){
            count++;
            p++;
        }
    }
    fclose(arq);
    printf("Qt : %i",count);
}

Answer: Eu fiz de uma maneira mais performática em relação a memoria, já que as funções da string.h copiam as strings. Em questão de performance não é notório, apenas em arquivos incrivelmente grandes. Eu também não use a lib string.h, segue o código:
#include <stdio.h>

#define MAX_LEN 256

int main() {
    FILE* file;
    char str[256];
    int total = 0;
    const char* strif = "if";

    file = fopen("txt.txt", "r+");

    if (file == NULL) {
        return -1;
    }

    while (fscanf(file, "%s", str) != EOF) {
        if (str[0] == 'i' && str[1] == 'f' && str[3] == '\0') {
            total++;
            continue;
        } else {
            int i;
            for (i = 0; i < MAX_LEN - 1; i++) {
                if(str[i] == '\0'){
                    break;
                }
                if (str[i] == 'i' && str[i + 1] == 'f') {
                    total++;
                }
            }
        }
    }

    printf("Total: %d\n", total);
    fclose(file);
    return 0;
}

Contador de if em um arquivo de texto


Nginx server static files with try_files under location

Question: I have the following nginx configurations:
server {

    listen 80;

    charset     utf-8;
    client_max_body_size 5M;

    location /severbat {

        root /root/severbat/dist;
        try_files $uri /index.html;
    }

    location /swagger {
        root /root/av/swagger-ui-dist;
        try_files $uri /index.html;
    }

}

And I files /root/severbat/dist/index.html and /root/av/swagger-ui-dist/index.html exist. But if I open url http://localhost/severbat I see nginx greetings page instead of index.html
However if I serve files under / it works:
location / {
    root /root/severbat/dist;
    try_files $uri /index.html;
}

nginx-acesss.log:
2018/10/03 09:32:44 [debug] 23052#23052: *519 trying to use file: "/swagger" "/root/av/swagger-ui-dist/swagger"
2018/10/03 09:32:44 [debug] 23052#23052: *519 trying to use file: "/index.html" "/root/av/swagger-ui-dist/index.html"
2018/10/03 09:32:44 [debug] 23052#23052: *519 internal redirect: "/index.html?"
2018/10/03 09:32:44 [debug] 23052#23052: *519 rewrite phase: 1
2018/10/03 09:32:44 [debug] 23052#23052: *519 test location: "/severbat"
2018/10/03 09:32:44 [debug] 23052#23052: *519 test location: "/api"
2018/10/03 09:32:44 [debug] 23052#23052: *519 using configuration ""
2018/10/03 09:32:44 [debug] 23052#23052: *519 http cl:-1 max:5242880
...
2018/10/03 09:32:44 [debug] 23052#23052: *519 content phase: 17
2018/10/03 09:32:44 [debug] 23052#23052: *519 http filename: "/usr/share/nginx/html/index.html"

Answer: Hello and welcome to ServerFault.
I think your problem is that NGINX appends the matched location to the specified root, so when you enter, for example, http://localhost/swagger NGINX looks for the directory /root/av/swagger-ui-dist/swagger and doesn't find it.
That's how the root directive works in NGINX
You might want to use the alias directive instead:
location /severbat {
    alias /root/severbat/dist;
    try_files $uri $uri/ index.html;
}

location /swagger {
    alias /root/av/swagger-ui-dist;
    try_files $uri $uri/ index.html;
}

Comment: Nginx respond with 404. If location is `/` configuration `/index.html` doesn't work as well
Comment: @deathangel908 looks like the problem was elsewhere. I've updated my answer accordingly.
Comment: I am having the exact same issue, and switching to `alias` also gives me a 404. Any updates on a solution to this issue?
Comment: This is NOT a valid answer! Look at "Using the try_files $uri directive with alias": https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ As you can see this is not going to work as expected.


(0,1), (0,2) and (0,3) modes of vibration for a timpani

Question: For a timpani, when hitting it in the center, how do you produce these three modes of vibration? Second mode has a higher frequency than the first, does that imply do you hit the timpani harder?
Thank you!
Answer: Some information for this answer taken from The Well Tempered Timpani.
Since a real world timpani is not perfectly shaped and can never be perfectly struck in the center, any time you strike a timpani, you will always activate multiple vibration modes.
Also, timpani membranes are two dimensional, so the numbering of the modes is more complicated. I'm going to assume the modes you are talking about are the (0,1) mode ("first"), the (1,1) mode ("second"), and the (2,1) mode ("third"). When a timpani is actually played, the preferred modes that are emphasized are actually (1,1), (2,1), (3,1), (4,1), and (5,1), and sometimes (6,1). The (0,1) mode is inharmonic with the other modes, so it is generally avoided to make sure the timpani is playing a note.
By striking a timpani as close as possible to the exact center, you will activate many vibration modes, but the "first" mode, (0,1) will be the loudest. So striking firmly in the exact center is how to hear the first mode. This might not sound like normal timpani playing, since normally they are played closer to the edge, and should come across a bit boomy. More like a bass drum.
To hear the "second" mode, (1,1) best, you have to both strike the timpani in a way to make the second mode louder and also damp the timpani to make the first mode more quiet. To emphasize the second mode, strike the timpani about 1/3 of the way along a diameter of the timpani. Another way to say that is to strike it about 2/3 of the way from the edge to the exact center. Also while you are striking the timpani, gently place at least one finger in the exact center of the timpani. You may get better results by trying to make a line with your fingers that goes through the middle of the timpani and make sure the line is perpendicular to the line from the edge to the center that you are striking along. You might have to adjust the strike point slightly somewhere between 1/2 to 2/3 the distance from the edge to the center (closer to the center). I may edit in a picture or diagram later if I can, since that would be clearer.
If you succeed in activating the second mode, it should sound like it's an octave higher than the first mode. Resist the temptation to strike a lot harder, a firm strike is what you want. It's the position and damping that controls the vibration, not the hardness of the strike (too soft or too hard will change the vibration modes, but in a more uncontrolled way).
Each higher mode is harder to isolate, so the "third", (2,1) might require a lot more practice. I'm actually not sure how to activate the third, but I have an educated guess. Again you want to place your finger in the center of the timpani, and ideally you would damp in two perpendicular lines going through the center of the head. Then you would hit inside one of the four quarters of the head created by the two lines, close to the middle of the quarter, and slightly towards the overall center of the head.
Comment: Thanks a lot! This is very useful information. However, sorry I didn't specify but when referring to the different modes of vibration for a hit in the center, I actually meant (0,1), (0,2) and (0,3). I apologise for not specifying. So, the timpani is still struckin the same spot at the centre but there are different modes of vibration. I'm still unsure how to achieve the different modes. This is still very insightful though! Also, I think I might try to propose a theoretical situation where everything is perfect.
Comment: @KevinNguyen Since the (0,2) and (0,3) modes have concentric nodes, it's next to impossible to isolate them. You would have to somehow create a very thin damping ring of the right circumference and place it in the right place on the head and then strike the head in the middle to get those.
Comment: @KevinNguyen Also, (0,1), (0,2) and (0,3) modes are generally called the "first", "fourth", and "ninth" modes. You might edit your question to use those words or the specific numbers if you think someone else might have better information than mine about those modes.
Comment: In summary, :-) ,  strike the surface at a point which will be a maximum for the desired mode, and preferably also a minimum for the undesired modes.  If it were possible to adjust the Fourier composition of the "impulse" blow to match the desired modes' frequencies, that would be great -- not practical in the real world.
Comment: @CarlWitthoft Sort of, but for all modes where the first number is 0 beyond (0,1), that is, for modes (0,2), (0,3)... (0,n) with n>1, it's essentially impossible to make that the loudest mode by striking alone. Damping at nodes would also be required, but those modes all have concentric circular nodes, so that's a real damping challenge.
Answer: Without being a timpanist, I will hazard a guess.
First, you will know when you have hit the higher modes because the tone changes as you would expect.
I suggest gently touching the surface of the timpani with one finger as you play it.  The exact location where you touch it will determine whether your finger simply dampens the sound or dampens only some modes of vibration.
The round surface is symmetric in rotation (even if the modes of vibration aren't), so you can find out where to touch the surface just by testing from the outer rim to the center (like a needle following the groove on a record) and by testing sets of points ( for ( >0 , _ ) modes) that start at any arbitrary "cardinal direction" ...you don't need to explore the entire surface.
Comment: Not all modes are circumferentially symmetric (nor do all modes have an axis of symmetry either!) .  Over in optics-land, we often use the Zernicke decomposition in a circular aperture -- which is what the drum head is.
Comment: Do you think changing the modes have anything to do with the pedal? Since the pedal changes the tone, allowing it to play higher or lower notes.
Comment: If I understand the instrument right, the pedal increases the tension on the skin, changing the fundamental frequency but not switching the mode of vibration.  I think if you find a place to touch the instrument and change the mode of vibration, that place will be the same however you adjust the pedal.
Comment: After some research, apparently if the fundamental frequency is changed then mode of vibration should also change. Refer to the frequency differences between (0,1) and (0,2) http://www.acs.psu.edu/drussell/demos/membranecircle/circle.html
Comment: Great link!  I don't think you're following me regarding the pedal, though.  The different modes all have their associated frequency, but what I call the "fundamental frequency" is a function of the tension of the skin, its weight, and its size: not the mode of vibration.
Comment: Ah I see, sorry for my ignorance. I don't do physics nor music :(, this was initially a maths paper but I'm trying to incorporate some music/physics inside it to make it interesting and practical.
Comment: @KevinNguyen If you look at the link in my answer, you'll find a lot more information about how timpani vibrate. Like all vibrating membranes, the vibration is two dimensional, so it's a lot more complicated than a vibrating string.
Comment: OK, great point... I made a change to my third paragraph that I think addresses this.


Manually limiting Graql query results iterator

Question: If I take a simple query, such as match $x isa dog; limit 5; get; then no matter how many dogs are stored in Grakn, I get 5 results back. This is fine, but what if I don't know how many dogs I want when I make the query and want to limit the number I retrieve later on in my code?
Here's my idea using the Python client:
import grakn
client = grakn.Grakn(uri="localhost:48555")
session = client.session(keyspace="dogs_keyspace")
tx = session.transaction(grakn.TxType.WRITE)

results = tx.query('match $x isa dog; get;')  # I don't limit now, so I can do it later

results is an iterator, so I can't do this:
limited_results = list(results)[:5]

because if I do then all dogs will be put into the list, and then I'll take the first 5, which is really inefficient if I have 1,000,000 dogs in the knowledge graph.
But I can say:
limited_results = list(itertools.islice(results, 5))

and I should get just the first 5 dogs without touching the other 999,995 dogs.
But my question is: is there any reason this approach would be slower than providing the limit 5 in the query like match $x isa dog; limit 5; get;?
Answer: If you don't want Grakn to retrieve all the dogs that are in the graph and only access the first 5, both your approaches are valid as they both use lazy iterators, meaning that no retrieval is attempted until you explicitly ask for the next result.
If you issue directly the query match $x isa dog; limit 5; get;, Grakn will build an iterator and it will iterate over it just 5 times and return the result to the client.


Banco de Dados e Listview não funcionam

Question: Estou tentando criar um aplicativo que grave dados e os exiba em um Listview, pra depois ir sofisticando o app pouco a pouco, mas na hora de salvar os dados no Banco de Dados ele não salva. No Debug ele roda tudo certinho, na última linha, como está na imagem abaixo, do nada ele retorna "false". O mais estranho é que ele parece estar buscando os dados. E o id sempre retorna "0" não entendo o porque.

Então descobri também que o meu ArrayList parece não funcionar também. Toda vez que vou na parte do meu app de mostrar os dados gravados (O fragment que corresponde ao Listview) o app fecha sozinho. Usando o Debug descobri dois detalhes, um na DataSource e outro no fragment onde programo para aparecer os dados que são salvos. Normalmente eu pensaria que, como não existe nenhum dado gravado, então ele não vai funcionar. Mas acho que o app não deveria fechar sozinho, no máximo só deveria mostrar uma tela em branco.

O mais estranho é que eu já trabalhei com outro aplicativo usando praticamente os mesmos modelos de códigos, então não entendo porque tantos problemas.
Comment: Mostre o código do insert.
Comment: public boolean insert(String tabela, ContentValues dados) {

        boolean sucesso = true;

        try {

            sucesso = db.insert(tabela, null, dados) > 0;

        } catch (Exception e) {

            sucesso = false;
        }

        return sucesso;
    }
Answer: Tente esse código ele coloca a operação de inserção dentro de um contexto transação de dados que é aberto com o método beginTransaction() é os dados são passado para o banco de dados pelo método setTransactionSuccessful() e o contexto de transação é fechado pelo método endTransaction()
public boolean insert(String tabela, ContentValues dados) {
   boolean sucesso = true;
   //Abre um contexto de transação.
   db.beginTransaction();
   try {
         // >= pois a tabela pode estar vazia e rowID pode ser 0;
         sucesso = db.insert(tabela, null, dados) >= 0;
         // Valida o contexto de transação.
         db.setTransactionSuccessful();
   } catch (Exception e) {
         //  Seria interessante fazer um log dessa exceção
         //para saber se está havendo erro de comunicação com o banco de dados
         sucesso = false;
   } finally {
     // Finaliza o contexto de transação.
     db.endTransaction();
   }
   return sucesso;
}

Comment: O erro persiste. Acho que vou refazer todo o MVC dando Ctrl C no outro projeto que fiz que deu certo e + Ctrl V nesse pra ver se vai funcionar, trocando só os gets e sets e os atributos da tabela. Pq não tem sentido, não estou vendo nada de errado no código. Já aconteceu de no curso eu copiar o mesmo código do mesmo projeto (uma versão do professor e a outra minha) e dar erro com os códigos iguaizinhos. Aí quando eu dei Ctrl C no projeto dele e + Ctrl V, funcionou. Até hj não entendi porquê.

Banco de Dados e Listview não funcionam


Selecionando um item do SELECT HTML

Question: Estou tentando deixa o item selecionado o que tem o id igual ao do $_REQUEST
$combo .= "<option value='".$row_area->area_id."' ".if($id == $row_area->area_id) { echo "selected"; } .">".$row_area->are_descricao."</option>";

Mas só que esta exibindo esse erro:
Parse error: syntax error, unexpected 'if' (T_IF), o código completo está assim:
for($j = 0; $j < $table_area->RowCount(); $j++) {
    $row_area = $table_area->getRow($j);
    $combo .= "<option value='".$row_area->area_id."' ".if($id == $row_area->area_id) { echo "selected"; } .">".$row_area->are_descricao."</option>";
}

Answer: Faz isso com um ternário, senão estás a colocar um echo dentro de uma concatenação de string e o echo vai sair primeiro, sozinho. Na verdade acho que essa sintaxe nem iria passar mas de qq maneira a maneira correta seria:
$selected = $id == $row_area->area_id ? "selected" : "";
$combo .= "<option value='".$row_area->area_id."' ".$selected.">".$row_area->are_descricao."</option>";

Outra variante, correta mas no meu ver menos limpa:
$combo .= "<option value='".$row_area->area_id."' ".($id == $row_area->area_id ? "selected" : "").">".$row_area->are_descricao."</option>";

Selecionando um item do SELECT HTML


Exclude node from search API results based on values in existing fields

Question: My content node includes a verified checkbox that's marked by a human reviewer who then also enters a date. The node is verified only when the box is checked and the date is entered. A content node may be published before it is verified.
How can I keep an unverified content node from appearing in search API results?
One solution is to add a search API exclude entity field to the content node and to set the value of the exclude field in a presave hook based on the verified checkbox and date. This isn't difficult, but it seems there should be a more straightforward way of accomplishing what's needed.
I've looked at modules, but those I've seen don't seem to fit the need. I imagine I'm just missing something obvious, but what is it?
I don't think it's relevant, but I'll mention that I'm using Solr search.
Answer: Given no alternative answers, I solved this problem by

installing the Search API Exclude Entity module
adding a field of type Search API Exclude Entity named search_exclude to the content node
adding the following to my custom rsc module
function rsc_node_presave(EntityInterface $node) {
  switch ($node->getType()) {
    case 'content':
      $node->field_search_exclude->value = <conditions to exclude node>;
      break;
  }
}

going to /admin/config/search/search-api/index/default_solr_index/processors
checking the Search API Exclude Entity box
selecting the Search API Exclude Entity tab at the bottom of the page
checking the field_search_exclude (content) box
reindexing the content

Seems to be working well. When unverified nodes are saved, the search_exclude field is set and that keeps the nodes out of the search results.


PHP - Creating a custom templatesystem?

Question: I've already searched here and surprisingly i didn't find the answer. I found one similar thread, but no real solution there. The complicated part is the loop, if i didn't need the loop i could just do a regular replace.
So, i have a .html file with some markup, like this:

    {{startloop}}

        {{imgname}}

    {{endLoop}}

What i want to do is replace {{filename}} and {{imgname}} with something else. I know how to do that, but the thing is, i want it inside a loop. So for each looped item {{filename}} and {{imgname}} will be different. If i have two "items", it'll look like this (just an example):

        Test name 1

        Test name 2

Any suggestions?
Comment: Did you notice that this "template engine" only replaces `` into `}}`? You're just creating dozens of new problems rather solving any.
Comment: As long as you have to ask such questions, you shouldn't go into designing your own templating system, but reuse some of the existing ones which were built by experienced developers.
Comment: have you tried some code already? please add sample code and output.
Comment: PHP is a template system. Use PHP. You cannot write a better template system in PHP than PHP itself.
Answer: I was a big fan of "smarty" template engine for a long time until the moment I realised I don't need it at all :) It's much better and faster to user straight inline php tags.
just put you html+php_tags into 'some_template.inc' file instead of html file.
then show this template by "include('template.inc');"
example of 'template.inc':

    <?foreach ($items as $item){?>

        <img src="/album/<?=$item[filename]?>" alt="">
        <?=$item[imgname]?>

    <?}?>

Comment: designers aren't as good with this. why trust them with PHP code?! by far and away, my advice is to always *always* use **PLAIN TEXT** templates.
Comment: On the other hand - smarty template engine was made to simplify designer's life. But its tags {foreach from=... item=...} aren't much more easier than  So why use smarty or any other template engine? I suppose designers aren't so dumb to be not able to learn some main php tags :) What do you mean by PLAIN TEXT templates?
Answer: Don't create a parser as its totally pointless, PHP is already a template engine, all you want to do is extend its capabilities with encapsulated template system.
The method below is the way I always create my template engine, its very lose, and can be extended with template helpers as such.
a good thing about my template system is that you don't have to waste your resources creating a cache system for your compiled templates as there already in a compiled state, comparing to engines like smarty.
Firstly we want to create a the main template class which would be used for setting data, and selecting the template etc.
So lets get started with this:
class Template
{
    private $__data = array();

    public function __construct(){/*Set up template root here*/}

    public function __set($key,$val)
    {
        $this->__data[$key] => $val;
    }

    public function __get($key)
    {
        return $this->__data[$key];
    }

    public function Display($Template)
    {
        new TemplatePage($Template,$this->__data); //Send data and template name to encapsulated object
    }
}

this is a very basic class that will allow is do do something like
$Template = new Template();

$Template->Userdata = $User->GetUserData();

$Template->Display("frontend/index");

Ok now you might have noticed the class above called TemplatePage, this is the class that loads the actual file template, and within the actual template you would be in the scope of the TemplatePage scope.
This will will allow you to have methods to get your template data and also access helpers, below is an example of a TemplatePage
class TemplatePage
{
    private $__data = array();

    public function __construct($template,$data)
    {
        $this->__data = $data;
        unset($data);

        //Load the templates
        if(file_exists(TEMPLATE_PATH . "/" . $template . ".php"))
        {
            require_once TEMPLATE_PATH . "/" . $template . ".php";
            return;
        }
        trigger_error("Template does not exists",E_USER_ERROR);
    }

    public function __get($key)
    {
        return $this->__data[$key];
    }

    public function require($template)
    {
        if(file_exists(TEMPLATE_PATH . "/" . $template . ".php"))
        {
            require_once TEMPLATE_PATH . "/" . $template . ".php";
            return;
        }
        trigger_error("Template does not exists",E_USER_NOTICE);
    }

    public function link($link,$title)
    {
        return sprintf('%s',$link,$title);
    }
}

So now as the template is loaded within the scope of the class you can extend the methods such as link and require to have a fully function template tool-kit
Example of template:
<?php $this->require("folder/js_modules") ?>

    <?php foreach ($this->photos as $photo): ?>

        <?php echo $this->link($photo->link,"click to view") ?>
        <?php echo $photo->image_name?>

    <?php endforeach; ?>

<?php $this->require("folder/footer") ?>

Comment: +1 for "use PHP". Also, don't use a double underscore prefix for your names. They're reserved for PHP.
Comment: @Meagar, Firstly that's for the up vote, and using double underscores would have no effect here because firstly there variables, and i dont think PHP Has any magic vars, secondly im specifically looking in the object scope, i.e `$this->`, the reason for the underscores is because as there's a magic method for setting data to the array I don't want the user to set content called data as it would override the container.
Answer: Is there any reason you're making your own templates system? I'd recommend using Smarty http://www.smarty.net/
It has this functionality already as well as a lot more, such as caching etc.
Comment: I want to create everything myself in this project, and this shouldn't really be that hard, right? I mean, it doesn't look very complicated - it's just a matter of finding a way to do it. It also feels kind of unnecessary to use a template engine like smarty for my project. It's unnecessarily big for what i need it for.
Comment: @ajreal Django templates, Mustache and several other templating systems use the double curly brace syntax, as well.
Comment: @asdf: "this shouldn't really be that hard" is overly optimistic, if not shortsighted. you're not into conditionals and other types of loops yet.
Comment: @stillstanding: Being optimistic is good. And i still believe it isn't that hard, there's probably a ton of different solutions for this, and some of them will be simple. @ajreal: I have a good reason for using it. So you're saying people can't ask simple questions?
Comment: @asdf go for it, it's a great exercise. how hard it is depends on features. but don't think supporting expressions is an easy task - quite nontrivial. especially without using PHP/eval.
Comment: thing is, (without sounding too cliché) - you don't want to re-invent the wheel. You should make use of what someone has already done well, so you can focus on your requirements
Answer: Maybe the better thing to do here is to use the MVC/MVVVM patterns and then you get this for free along with a very structured and organized code project.
Take a look at this page from Rasmus' blog as a primer to this workflow:
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
If you are willing to let go of the reigns a bit, Zend is very good as a framework and can help you get your site done pretty quickly. It will save you having to rewrite a lot of code yourself and give you some advanced features you probably wouldn't want to have to write on your own anyway.
I wholeheartedly agree with you about the size of some frameworks, and you can do this without them. The trade-off is time. Time spent coding and time spent debugging. Like I said, if you're willing to let go of some control you can breeze through your project only having to deal with debugging the 'business logic' of your site and not having to reinvent a lot of already existing code.
Hope this is helpful.
Answer: The only way to create a superfast template system is to rely on PHP as a parser, or through the use of an extension coded in C. Furthermore, there's probably no reason to attempt this in any case, as it's already been done a thousand times. There's lots of big winners out there like Smarty, though performance isn't stellar. The template system in PHPBB is also pretty good (using pre-parse and cached PHP). Avoid re-inventing a wheel here.
If performance is a major concern, I highly recommend Blitz.
Borrowing from PHPBB is another route. If you don't have access to extend PHP on your server, and Smarty isn't your cup of tea on format of performance, and would like all the bare-metal code, you could do like me and rip out what's in PHPBB. It isn't the end-all solution, and full of particulars, but it's quite good -- and with the source, you can customize it to taste. It eval's to code so supports some level of expressions, and supports HTML comment tags as the template escapes/markers that are user-friendly for less techie graphic designers.
Answer: Replace your {{tags}} with chunks of php code (foreach in this case) and then eval the result. This is how php template engines work.
example:
$template = "
Hello {{name}}
";
$name = "Joe";

$compiled_template = preg_replace(
    '~{{(.+?)}}~',
    '<?php echo $$1 ?>',
    $template);

eval('?>' . $compiled_template);

prints
Hello Joe

A more advanced example, involving arrays and loops
$template = "
    {{each user}}
        {{name}} {{age}}

    {{end}}
";

$user = array(
    array('name' => 'Joe', 'age' => 20),
    array('name' => 'Bill', 'age' => 30),
    array('name' => 'Linda', 'age' => 40),
);

$t = $template;

$t = preg_replace(
    '~{{each (\w+)}}~',
    '<?php foreach($$1 as $item) { ?>',
    $t);

$t = preg_replace(
    '~{{end}}~',
    '<?php } ?>',
    $t);

$t = preg_replace(
    '~{{(\w+)}}~',
    '<?php echo htmlspecialchars($item["$1"]) ?>',
    $t);

eval('?>' . $t);

In response to other comments, telling me that "php is a template engine" and "eval is evil" - people, don't repeat stupid mantras you've heard somewhere. Try to think on your own.
Comment: Downvote for crazy idea of compiling template each time and using `eval()`.
Comment: @stereofrog, that does work. But in your first post you suggested me to add chunks of php code (like ), and then evaluate it. After editing your post you just replaced {{name}} with $name. As i said before, the complex part about this is making it run a loop. Could you give me better example of running a loop and echoing out an array? Thanks a lot! @Col; You often comment on other peoples suggestions, but you never help. Why is that?
Comment: OMG, who would do such a thing :(, this should never be used, especially in template systems.. **-1**
Comment: I thought of something like that, but i didn't manage to eval() it because of the html code around it. How would that work? Example?
Comment: "eval is evil" only if it affects performance and input is from end-user. obviously, templates are not end-user provided.
Comment: regardless, there a large entity in a framework, and should be treated as top priority as compilation of output can take a lot of resources.

PHP - Creating a custom templatesystem?


Drupal Taxonomy in D6 vs D7

Question: I'm building two very big sites using Drupal. Both will have plenty of vocabularies with up to 6-7 levels deep like this:
State->District->City->Area->office name->department
The taxonomy will have multiple parents from across vocabularies.
I'm working on D6 sites and managing taxonomy hierarchy isn't easy and is bit cumbersome with D6.
I want to know if it'd be easier with D7 especially when it comes to managing terms with multiple parents.
Any idea?
Comment: Perhaps a clarification would help, in what way is it cumbersome, and what is the desired, not-cumbersome behavior?
Comment: Too much of scrolling for selecting terms in case of multiple parents, navigating multiple pages for long list of terms etc
Answer: The UI for dealing with taxonomy term relationships hasn't changed much in Drupal 7 I think.
However, you might want to look into some contributed projects, for example Taxonomy manager, which exist for both D6 and D7. I don't know if it provides a solution for this, however.

Drupal Taxonomy in D6 vs D7


Calculate $\begin{Vmatrix}1&2\\2&4\end{Vmatrix}$

Question: With $$\left\Vert A \right\Vert=\max_{\mathbf{x}\ne 0}\frac{\left\Vert A\mathbf{x}\right\Vert }{\left\Vert \mathbf{x}\right\Vert }$$ and $$A=\begin{bmatrix}1 & 2\\
2 & 4
\end{bmatrix}
 $$
Calculate $\Vert A \Vert$.
Not exactly homework, but an exercise from some notes on applied linear algebra that I am trying to work though. I am given the following hint:

Hint: note that $\begin{bmatrix}1 & 2\\
2 & 4
\end{bmatrix}=\begin{bmatrix}1\\
2
\end{bmatrix}\begin{bmatrix}1 & 2\end{bmatrix}
 $

I've used the hint to obtain an upper bound on $\frac{\left\Vert A\mathbf{x}\right\Vert }{\left\Vert \mathbf{x}\right\Vert }$:$$\frac{\left\Vert A\mathbf{x}\right\Vert }{\left\Vert \mathbf{x}\right\Vert } = \frac{\left\Vert \begin{bmatrix}1 & 2\\
2 & 4
\end{bmatrix}\begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }{\left\Vert \begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }
 = \frac{\left\Vert \begin{bmatrix}1\\
2
\end{bmatrix}\begin{bmatrix}1 & 2\end{bmatrix}\begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }{\left\Vert \begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }
 = \frac{\left(\begin{bmatrix}1\\
2
\end{bmatrix}\cdot\begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right)\left\Vert \begin{bmatrix}1\\
2
\end{bmatrix}\right\Vert }{\left\Vert \begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }
 \leq \frac{\left\Vert \begin{bmatrix}1\\
2
\end{bmatrix}\right\Vert \left\Vert \begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert \left\Vert \begin{bmatrix}1\\
2
\end{bmatrix}\right\Vert }{\left\Vert \begin{bmatrix}x_{1}\\
x_{2}
\end{bmatrix}\right\Vert }
 = \left\Vert \begin{bmatrix}1\\
2
\end{bmatrix}\right\Vert ^{2}
 = 5
 $$
I believe that I am headed in the right direction here but I'm rather stuck with where to go next. I suppose I need to solve $$\frac{\left\Vert A\mathbf{x}\right\Vert }{\left\Vert \mathbf{x}\right\Vert }=5$$but after some struggle, I can't figure out how to solve this equation. I tried following the through component-wise to get $$|x_1 + 2x_2|^2 + |2x_1+4x_2|^2=25[|x_1|^2+|x_2|^2]$$ but that seems no closer to what I need.
Does anyone see where I should go from here?
Comment: The eigenvalues are $0$ and $5$. Since the matrix is symmetric the norm equals the largest eigenvalue.
Comment: Do you know the precise equality condition for your $\le$?
Comment: Here is a [related problem](http://math.stackexchange.com/questions/249047/i-am-not-sure-how-to-calculate-this-norm/249068#249068).
Comment: @PantelisDamianou ah I did not know that. That's I guess a good thing to know. If the matrix was not symmetric then this would not necessarily be the case? I guess the matrix norm by definition must at least be greater than or equal to the largest eigenvalue?
Comment: No, this is a feature specific to symmetric (or skew-symmetric, or, more generally, normal) matrices. Another good thing to know is that for any matrix $\Vert A \Vert^2 = \Vert A A^T \Vert = \Vert A^T A \Vert$, and since the latter two matrices are symmetric, their norm can be computed via eigenvalues. If the scalars are complex, the transpose should be replaced by conjugate transpose.
Comment: Yes. Alexander is correct!
Answer: You have shown that
$$\max \dfrac{\Vert Ax \Vert}{\Vert x \Vert} \leq 5$$
To show that equality is attained, choose $x = \begin{bmatrix} 1\\ 2\end{bmatrix}$. We have $$Ax = \begin{bmatrix} 1 & 2\\ 2 & 4\end{bmatrix} \begin{bmatrix}1\\2 \end{bmatrix} = \begin{bmatrix} 5 \\ 10\end{bmatrix} = 5x$$
Hence, $$\dfrac{\Vert Ax \Vert}{\Vert x \Vert} = 5$$
In general, note that if $A = uu^T$, then the reduced SVD of $A$ is $$A = \Vert u \Vert_2^2 \left(\dfrac{u}{\Vert u \Vert_2} \right) \left(\dfrac{u}{\Vert u \Vert_2} \right)^T$$ Hence, $\Vert A \Vert_2 = \Vert u \Vert_2^2$. In your case, $$A = \begin{bmatrix} 1\\ 2\end{bmatrix} \begin{bmatrix} 1 & 2\end{bmatrix}$$ Hence, $u = \begin{bmatrix} 1\\ 2\end{bmatrix}$ and thereby $$\Vert A \Vert_2 = \Vert u \Vert_2^2 = 1^2 + 2^2 = 5$$
Answer: Consider the vector (1,2) again...
Comment: Wow. I feel pretty stupid. I *did* that, and ended up finding that $\begin{bmatrix}1 & 2\\
2 & 4
\end{bmatrix}\begin{bmatrix}1\\
2
\end{bmatrix}=\begin{bmatrix}5\\
8
\end{bmatrix}$. That's not correct, is it.
Comment: @crf: Indeed, the $8$ should be a $10$. Observe $\|Ax\|/\|x\|$ is the same as $\|Au\|=\|(1,2)\|\cdot|(1,2)\cdot u|$ where $u=x/\|x\|$: if $\theta$ is the angle between $u$ and $(1,2)$, then this is $5\cos\theta$ due to the formula $u\cdot v=\|u\|\|v\|\cos\theta$. This is maximized when $\theta=0$, in other words when $u$ is in the same direction as $(1,2)$, in which case we can take $x=(1,2)$.


How to send a notification to admin on profile picture change?

Question: I want the new uploaded pictures to be sent (notification) to me (admin) for review and approval just to be sure they are in line with the terms and conditions of the webpage. Naked or semi-naked pictures are strictly forbidden.
How can I achieve this?
Answer: I suggest you try to use a combination of 2 approaches, as further detailed below.
Approach 1 - Prior approval required
If you'd use the the Profile 2 module, then the Profile 2 Moderation module, which depends on the Profile 2 module, enables moderation on user profiles. Here is a (self explaining?) screenprint from its project page.

Be aware however that, as mentioned on the project page, it requires a Profile revisions patch.
Approach 2 - After the facts
Use the Rules module to be informed about all sorts of updates that you're interested in, similar to what's detailed in my answer to "How to send an eMail notification when a specific field of a node or user has been changed?".
With this approach, and as per all the great things you can do with this module, your options are virtually unlimited. This approach also allows you to implement this type of moderation using a granular approach: start small, maybe only using a few custom rules, and keep refining them and continue adding new ones.
Not to forget all the available integrations with tons of other modules, of which the Flag module is probably your very first priority to also add that module for what you're trying to implement. Just a basic usecase about this:

Use Rules to flag any user for which some profile update happened.
Use Views to build a list of such flagged users.

If you'd only implement these 2 bullets of this approach (a matter of minutes, say an hour at max), you'd already have a Version 1.0 of your User Profile Moderation Dashboard (call it your MVP if you prefer ...).
If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.
Answer: avatar approval this module worked great for me.


getting started with apache mod_rewrite on a virtual host

Question: hey SO I am attempting to use apache's  mod_rewrite module to do some basic rewrting of url on my website so they become a little more seo friendly
basically I have a virtual host file that look like this
    <VirtualHost *:80>
        ServerAdmin firstname.lastname@example.com
        ServerName mind-knowledge.com
        ServerAlias www.mind-knowledge.com

        DocumentRoot /var/www/tagmenu
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        <Directory /var/www/tagmenu>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                <IfModule mod_rewrite.c>
                        RewriteEngine on
                        RewriteRule /video/([0-9]+) /PlayVideo/index.php?videoID=13424
                </IfModule>
        </Directory>
</VirtualHost>

now from what I understand the rewrite rule should allow  http://www.mind-knowledge.com/PlayVideo/13424/  to be rendered as the page http://www.mind-knowledge.com/PlayVideo/index.php?videoID=13424 is this correct?
As currently I get  404 , and i have run sudo a2enmod rewrite and reloaded apache.
Can anyone help me in what I am doing wrong or suggest some ways to troubleshoot the problem
thanks in advance.
brendan
Comment: @EEAA not entirely a duplicate although this is a handy reference it doesnt quite answer my question on why my rule is not working
Comment: @Mxx same person same question
Answer: You want /PlayVideo/13424/ to work but the first part of your rewrite rule is /video/.
You also don't use the numbers matched in the first part in the second part, meaning that everyone will always watch the same video, no matter what the number in their URL.
Change it to this to fix both those problems:
RewriteRule /PlayVideo/([0-9]+) /PlayVideo/index.php?videoID=$1

I should have noticed this before but there are potentially two other issues.  The first is that your rewrite rules are inside a <Directory> block and this changes how they work.  The simple way of explaining this is that the leading slash is removed.
The more technically accurate description is that the path that is passed in to the rewrite rule to be matched is a filesystem path rather than a URI and it has the directory removed from the start of it.
So inside a <Directory> block, you should use:
RewriteRule PlayVideo/([0-9]+) PlayVideo/index.php?videoID=$1

The other thing is minor but I prefer not to have an <IfModule> block at all.  These are handy for package maintainers whose configs are going to be deployed in thousands of different machines by people of all competence levels but for a single deployment with (probably) a single admin, all they do is hide other mistakes.  If you forgot to load the rewrite module (commented out the line, deleted the symlink, whatever) Apache will still start up just fine and throw no errors but the rerwrite module won't work and URIs that rely on it will result in a 404, just like you're seeing.  Without the <IfModule> block, that same mistake would cause Apache to fail to start up and would result in a useful error message.
Comment: hey sorry about this ... although you are correct that i want PlayVideo I have actually been testing with video. as for the static number this was just for testing . However using the rule you have scpecified i still get a 404 any idea how to debug this
Comment: Oh yes, I can see another issue.  Updated the answer.
Comment: ahh okay thank you it works! now just to clarrify if the block was not inside the `` tag but rather just inside the `` tag I would need the `/` before the `PlayVideo` and the rule would work an all directories not just /var/www/tagmenu is this correct?
Comment: Yes, that's correct.  Also, in case it bites you in the future, a `.htaccess` file is implicitly in a `` context because it's always in a directory.
Comment: Could you help answer a similar question: https://stackoverflow.com/questions/58853639/unable-to-forward-the-query-parameters-submitted-by-the-user?noredirect=1#comment103999680_58853639 @Ladadadada
Answer: While its possible to match that way, My brain doesn't do regex well so I tend to split things up more. While, it is slower on the apache side, I prefer something more along the lines of:

RewriteBase /PlayVideo
RewriteCond %{REQUEST_URI} ^/([0-9]+)$
RewriteRule ^(.*) index.php?video=$1  [L,QSA]

QSA is not neccessary but you may wish to pass more query strings in the future. This gives you that ability.
Also if you have access to the logs, set the following (while debugging only!):
RewriteLogLevel 4
Then step through the logs to see at what point did the rewrite rule do something different than what you expected.


Cannot login to RHEL6 server as any user except root - Says home directory cannot be found and shell permission is denied

Question: As the question above states, I have a RHEL 6 server that is designed for SSH access, with root unable to login through SSH by design. When I am at the server locally I can login as root, but only as root.
If I try to log in as a user the screen quickly flashes a message reading:
Last Login: Mon Aug 24 08:24:52 on tty1
no directory: /home/user1!
logging in with home="/"
login: no shell: Permission denied

I am getting the no shell because there is no shell in /.
Now what is really confusing to me though is that the home directory does indeed exist, and contains a valid shell, and is permissioned right from what I can tell (755). This is common for all users that existed and have been created on this server instance. It seems to matter not if I define a path to the home directory when I make a user or let the default take charge and assign it automatically.
I have not found anything strange in the Secure log or messages log, only that the user successfully logged in (which they have, but can't do anything without a shell)
I am hoping to not need to reinstall at this point, but there is almost no data on the server that would be lost if that is the only option.
Any help would be very much appreciated as I have searched and tried for a week now with no luck.
Edit:
I used the useradd user1 command to originally add the user, when that resulted in the problems above I used
mkdir /home/user1 && useradd user1 -d /home/user1 && chown -R user:user1 /home/user

When I run the cat /etc/passwd | grep user1 command I get:
user1:x:513:517::/home/user1:bin/bash

and when I run the ls -l /home command the entry for that user is:
drwxr-xr-x. 4 user1 user1 4096 Aug 19 17:03 user1

Comment: If you provide the output of 'cat /etc/passwd | grep user1' and 'ls -l /home' someone here will be able to help.
Comment: Why do you think `/` or your home directory need to "contain a shell"? The shell defined in `/etc/passwd` for your user (most likely `/bin/bash`) needs to be existing and executable.
Comment: What commands did you use to add users?
Comment: Sven, I understand that the shell is defined in `/etc/passwd`, however I think the root problem that I am having is that the OS seems to not be able to find the home directory even though it exists and the user has permission to access it, as well as `/bin/bash` as is listed in the `/etc/passwd` file
Comment: Check your `/var/log/audit/audit.log`.
Answer: I was able to fix the problem by running the command
for p in $(rpm -qa); do rpm --setperms $p; done

and restarting the server. Once it restarted not only was I able to log in as any user that had been created I was able to again use the GUI as well. This points to corrupted file permissions somewhere on the system. How they became corrupted I do not know, but it all now works.
Answer: The only issue I can see with your setup is in your passwd file. Try changing
user1:x:513:517::/home/user1:bin/bash
to
user1:x:513:517::/home/user1:/bin/bash.
Comment: I fixed that and it still shows the same symptoms, root can log on and no one else can get a shell to open.
Comment: Does `/bin/bash` exist? Try running `su user1 -c /bin/bash` and `su user1 -c /bin/sh`.
Comment: `/bin/bash` does exist, when I run the `su user1 -c .bin/bash` I get the following: `su: /bin/bash: Permission denied`
It may be of interest that the permission on `/bin/bash` are:
`-rwxr-x-r-x. 1 root root 938736 Apr 23 2012 bash`
Comment: I just saw your comment about powering it off. If that's all you did and it's not working now, then it might be because of corrupted files on the drive. There's an article (http://www.tldp.org/LDP/LG/issue52/okopnik.html) in which the author uses `strace` to try to track down issues, but at that point it may be faster to just reinstall since you don't have much data on the server.
Comment: That is kind of where I was thinking the problem lies, but I wanted to ask for some advice from the more experienced out there before I go to management and tell them I need access to the License information again as that is somewhat a pain
Comment: Ah, I was thinking it would be just an easy reinstall. But yeah, generally if you didn't update or modify any of the software `power off -> power on -> something's broken` means a hardware issue.
Comment: The link you posted helped to point me in the right direction of corrupted file permissions. However not wanting to spend hours upon hours manually pouring through the permissions and comparing them I was able to find a small script that sets the permissions to what is in RPM, which was able to fix my problem.
Answer: The useradd should create the home directory when correct option is passed and you don't (or shouldn't) have to create them manually. I suggest you execute the following (in the order listed) to remove and recreate your user properly.
userdel -f -r user1
useradd -m user1

NOTE: you don't have to pass the -d option since the default will be /home/user1 in this case.
Comment: This is how I originally added the users to the server, and it was working fine for a while (a few months). It is only recently after powering off the server, racking it in a different location, and powering it back on, that I am having these problems.
Answer: I just had this same issue on a CentOS 6 machine.  This was an issue with files in /home having mislabeled SELinux security contexts.  One of the commenters above, Michael Hampton, who said to check /var/log/audit/audit log was spot on.  I followed his advice and noticed that there was an SELinux issue going on here.  The solution that fixed it for me was:
sudo restorecon -Rv /home

That will recursively restore default security context labels on all files in the home directory. After that, ssh access via publickey was restored.


Vetor não imprime corretamente

Question:
Crie um programa em C++. Peça que que um vetor de inteiros de 10 posições seja preenchido pelo usuário. Imprima a soma das componentes deste vetor.

Fiz o código abaixo mas ele não imprime os valores do vetores.
<code>#include <iostream>
using namespace std;
#define SIZE 10
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
    int valor[SIZE];
    int total, i, a;

//  a = sizeof(valor)/ sizeof(valor[0]);

    for (i = 1; i <= sizeof(valor)/ sizeof(valor[0]); i++)
    {
        cout<<"Digite o valor: ";
        cin>>valor[i];
    }

    for ( i = 0; i < 10; i++)
    {
        cout<< valor[i];
    }

    for ( i = 1; i < 10; i++)
    {
        a = a + valor[i];
    }
    cout<< a;

    return 0;
}
</code>
Comment: Qual o motivo de usar `sizeof(valor)/ sizeof(valor[0])` e não simplesmente `SIZE`? Se a variável `a` é um acumulador então você precisa inicializa-la com 0 e o índice `i` partir de 0, ou fazer `a = valor[0];` já que seu loop parte do índice 1.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Comment: Como o @Maniero demonstrou, se você sabe o tamanho do array previamente, use isto. Pra começo, em **C++**, se você não sabe o que está fazendo (ou o porquê), na prática talvez deva estar usando **std::vector** ao invés de fazer arrays "na mão". Em **C**, a história é outra. C/C++, diferente de outras linguagens mainstream (PHP, Python, Ruby, etc...), você _deve_ saber o tamanho daquilo com o que está lidando, a menos que _precise_ ser dinâmico. Ou seja, se o seu array _não precisa ser dinâmico_, assuma que seu tamanho é estático e use isto a seu favor.
Answer: O maior problema é que não está lendo a quantidade dados que acha que está. Está começando ler os dados e armazenando na posição 1 do array, sendo que o array começa na posição 0. Então já terá um lixo nessa posição e fará o resultado ser errado ou certo só por coincidência. Não entendi bem a conta que fez para ir até o final. Essa técnica é usada para outra coisa. Você já sabe o tamanho do array, porque não usar isso?
E por que não usar o vetor do C++ que é bem melhor? Não acho que deveria misturar C com C++.
Tem outras coisas que podem ser melhores, como ter um só laço para somar e imprimir. Organizando o código ficaria assim:
<code>#include <iostream>
using namespace std;
#define SIZE 10

int main() {
    int valor[SIZE];
    for (int i = 0; i < SIZE; i++) {
        cout << "Digite o valor: ";
        cin >> valor[i];
    }
    int total = 0;
    for (int i = 0; i < SIZE; i++) {
        cout << valor[i] << endl;
        total += valor[i];
    }
    cout << total;
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Vetor não imprime corretamente


combining a php variable within html footer

Question: I have a php variable in my web application that is $companyname, this comes from a session variable elsewhere in the code which I know works by testing with a simple echo.
I have written my footer in HTML which is as follows:
<!DOCTYPE html>

This information belongs to . $companyname . if you are not the intended recipient please contact the owner or send us an  email

All rights reserved 2015

I have never combined a variable within a html footer before, normally just use plain text with a hyperlink.  Obviously this isnt working because I dont know how I am doing this and have googled it without much success.
Can someone please tell me how to get the $companyname to actually display as a variable rather than the text, see picture here.
Also if its not too much trouble, I would like the $companyname to be in bold
Comment:
Answer: You can use HTML outside <?php ... ?> blocks. So basically outputting php variable in HTML would be:
<!DOCTYPE html>

This information belongs to <?php echo $companyname; ?> if you are not the intended recipient please contact the owner or send us an  email

All rights reserved 2015

However You did not provide information how HTML is generated, so can't help here anymore.
Comment: Thanks thats worked, now looks like This information belongs to , if you are not the...  However can someone tell me how to get the echo in bold please
Comment: bold is HTML tag, not php. `This information belongs to , if you are not the...`
Comment: Thanks, this did the trick ".$_SESSION["companyname"] ?>,
Comment: Ok one small problem, everything after the php variable is now bold, using  This information belongs to ".$_SESSION["companyname"] ?>, if you are not the intended recipient please contact the owner or send us an  email


Models to use Predict time till next purchase

Question: I have the transaction history of users from 12 years. I want to predict the time till next purchase in R. Can we use Regression models to predict this continuous value (in terms of months). If so, what would the target variable be ? I have the frequency and recency of purchase for each customer.
Appreciate any suggestions or references.
Answer: The basic strategy would be to assume that the activity is distributed according to some family of distributions, and then estimate the parameters based on the data. This wouldn't really be regression, since the feature variables and the response variables are basically the same. Also, the really basic analysis would base the estimate for each customer only on that customer's activity, although a more advanced analysis might adjust what family of distributions is expected, or weight towards an expectation of the parameters based on what the average customer is doing.
If you have other variables, such as the dollar amounts of the transactions, or if you don't assume independence (perhaps people who buy a lot on the weekend have behavior that's different from other people, for example), then you can do regression analysis between those factors and the parameters.
Answer: It depends on what you want to use and what assumptions you want to make. If you assume that the purchases are stochastically independent then you're looking for the the Poisson Point Process. An accessible introduction can be found here.
More generally, the Exponential Distribution predicts the time between successive events. You can use Exponential Regression if you have insight into what the variables that determine the time intervals are (thanks comment!)
If you don't have any insights to the data to allow you to use exponential regression or the Poisson Point Process, you might be able to build a ML algorithm that simulates the purchasing behavior of your clientele and then you can study the simulation to determine the answer.
Comment: The exponential distribution is the best tip among the answers so far. If you have any information that might drive the inter-purchase intervals (e.g., if customers just bought a large amount, this may last them a while so they won't be buying anew soon; or with a price reduction, they might buy sooner), you can run an exponential regression - [see here](https://stats.stackexchange.com/q/51347/1352.)
Answer: This is an example of Survival Analysis, and yes, that can be done with regression. You can start at Wikipedia. Start with figuring out how to create a Kaplan Meier curve, maybe compare it for some subgroups, if you've never heard of this area.
Answer: This is point process modeling. One simple way to use regression is to regress the next interval of purchase as a function of history and other covariates. In general, you can fit a parametric form of conditional intensity function. A popular choice in neuroscience is to use a linear-nonlinear functional form.


Is it possible to check sqlite values without a cursor? - Android

Question: I'm trying to stop the user from entering the same string value for the "title" field in an appointment creation app in a calendar, as homework.
Here is what I thought of so far:
private static String[] CHECK = {TITLE};
    private Cursor addAppointment(String title, String time, String details){
        calendarData = new CalendarData(this);
        SQLiteDatabase db1 = calendarData.getReadableDatabase();
        SQLiteDatabase db = calendarData.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DATE, calendar.getDate());
        values.put(TITLE, title);
        values.put(TIME, time);
        values.put(DETAILS, details);
        db.insertOrThrow(TABLE_NAME, null, values);
        Cursor titleCursor = db1.query(TABLE_NAME, CHECK, TITLE+" = "+appointmentTitle.getText().toString(), null, null, null, null);
        if(titleCursor.getString(0) != null){//MEANING THERE IS A DUPLICATE
            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setMessage("You've entered a duplicate title field, please rename.");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {

                   alertDialog.dismiss();

                } });
            alertDialog.show();
        }
        return titleCursor;
    }

But I don't like the idea of having everything in my addAppointments method, I'd rather leave it clean and simple.
I tried doing the following as an alternative:
private static String[] CHECK = {TITLE};
    private void addAppointment(String title, String time, String details){
        calendarData = new CalendarData(this);
        SQLiteDatabase db1 = calendarData.getReadableDatabase();
        SQLiteDatabase db = calendarData.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DATE, calendar.getDate());
        values.put(TITLE, title);
        values.put(TIME, time);
        values.put(DETAILS, details);
        db.insertOrThrow(TABLE_NAME, null, values);
    }

    private Cursor checkTitle(){
        calendarData = new CalendarData(this);
        SQLiteDatabase db1 = calendarData.getReadableDatabase();

        Cursor titleCursor = db1.query(TABLE_NAME, CHECK, TITLE+" = "+appointmentTitle.getText().toString(), null, null, null, null);

        startManagingCursor(titleCursor);
        return titleCursor;
    }

    private void showTitleError(Cursor cursor){
        if(cursor.getString(0) != null){//MEANING THERE IS A DUPLICATE
            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setMessage("You've entered a duplicate title field, please rename.");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {

                   alertDialog.dismiss();

                } });
            alertDialog.show();
        }
    }

but I get this error in both cases: 04-24 17:56:51.263: E/AndroidRuntime(17856): android.database.sqlite.SQLiteException: no such column: hello: , while compiling: SELECT title FROM appointments WHERE title = hello
Please if you have any advice please share, thank you.
Comment: *Read* the error message closely. Note how it has *nothing* to do with the title. -1 (for lack of problem/issue refinement and grossly incorrect title) and a "too localized".
Answer: If you want it injection safe use it that way
Cursor titleCursor = db1.query(TABLE_NAME, CHECK, TITLE+" = ?",
        new String[]{ appointmentTitle.getText().toString() }, null, null, null);

the ? is replaced by '-quoted and escaped data from the next argument.
Hint: if you want to enforce a unique title, then make the database column UNIQUE. That way you will get an SQLiteException when you insert data that has a title that is already present. Instead of an expection you could also make the column UNIQUE ON CONFLICT IGNORE which means that it simply does not insert the data and does not throw an error.
Comment: that makes sense, I will look into making the column unique, that way I don't have to implement an alert dialog as it will stop the user completely from entering the same title. thanks
Answer: You need to wrap appointmentTitle.getText().toString() in single quotes:
db1.query(TABLE_NAME, CHECK, TITLE+" = '"+appointmentTitle.getText().toString() + "'", null, null, null, null);

That way your assembled query looks like:
SELECT title FROM appointments WHERE title = 'hello'

As other posters have courteously noted, however, this can cause an SQL injection issue if your query here takes User input.  Adapting to a parameterized approach is the better way.
Comment: Did Android *really* re-introduce SQL Injection? I am impressed... but not by this answer (-1 [see the API](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html) for a better way).
Comment: @pst Well better obviously is to parameterize the query instead - but as for why it was breaking. I would also say that android helps you avoid SQL injection, but it doesn't make you
Comment: Is this the right way to check if the value in the database and the one entered by the user are the same? if(cursor != null)? Because every time I try to add a new title it gives me the alert dialog which is not suppose to happen
Comment: @AZ1 I would check the number of rows returned instead:
`if(cursor.getCount > 0)`


On-the-fly changes in ice hockey

Question: During an on-the-fly player change, it is generally acceptable for the replacement player to step on the ice a second or two before the player he is replacing steps off the ice, if such a change doesn't impact the play of the game. In this case, does the time when both players are on the ice count towards the time-on-ice stat for both players?
Also, how is the +/- stat counted for the two players if a goal is scored during those couple of seconds when both players are on the ice?
Answer: My feeling is there is no complete answer for this question unfortunately - that it's just up to the scorer.
For exapmle, on Saturday the Blackhawks and Blues played.  Adding up the TOI for the blackhawks comes to 288:56, which is 11:04 short of a full game (of 300).  However, there were 12 minutes shorthanded plus 2 minutes of 4 on 4 in that game (Kane/Pietrangelo unsportsmanlikes), for a total of 14 minutes of time that's not accounted for; meaning that you're 2:56 over the amount of time that should be accounted for.  As Kevin points out in comments, those can be accounted for by looking at when the StL PP goal was scored - and the last minor was with only :04 left in the game.  So the ToI does look like it adds up.
Looking at the shift chart for the game, I don't see any overlaps at all in the shift changes; they all have a corresponding off/on pair.  But whether the TOI stat comes from the same place as the shift chart, I don't know.
As far as +/-, again I don't think it's explicit anywhere; it would be up to the scorer to determine exactly who was officially on the ice when it occurred.  Typically when I've seen it, the player getting on the ice is credited so long as they're fully on the ice - the player leaving is more or less 'out of it' once that's happened.
Comment: I just had a look at the boxscore, you are right Chicago had 7 minors, but they were scored on one of them, at exactly 1 minute in.  Plus their last minor was with only 4 seconds left in the game.  So that exactly accounts for the missing 2:56 you mentioned.
Comment: Note there are other weird cases to account for when it would be hard for the scorer to make everything add up.  E.g. what happens with a too-many-men penalty?  Also sometimes they add some time to the clock near the end of a period if the clock runs a little long after a whistle.  Then other times I think the clock can be reset quite a bit if it is determined a goal was scored, but it was missed and play had continued.
Comment: @Kevin Hmm, good points - I'll add that to the answer.
Answer: I am not an expert, merely a viewer. But as far as I understand - as soon as the replacement player touches the ice, he is "in" and the other player is "out" even if he still touches the ice.
When the replacement player jumps on, the leaving player may not touch the puck or otherwise participate in the game as this will be called "too many men on ice" and will be penalized. That is why I believe he is counted out of the game immediately as the replacement is on ice and thus the replacement would get counted in statistics for time on ice and +/-.
Comment: This would be much improved by replacing the qualifiers of opinion with reference to fact and credible sources. Many people have an ostensibly reasonable understanding of many sports, but in a lot of cases they are also entirely wrong due to technical implications.

On-the-fly changes in ice hockey


Como exibir/esconder texto usando uma imagem como botão?

Question: Oi, eu estou montando um pequeno site onde eu queria usar varias imagens como botão que ao clicar cada um exibisse um texto diferente, como eu posso fazer isso?
Eu testei esse aqui mas ele não fecha o primeiro texto ao abrir o segundo, fica tudo misturado no mesmo espaço.

<input type="image" src="IMAGEM AQUI" onclick="if (this.parentNode.nextSibling.childNodes[0].style.display != '') { this.parentNode.nextSibling.childNodes[0].style.display = ''; this.value = 'Ocultar'; } else { this.parentNode.nextSibling.childNodes[0].style.display = 'none'; this.value = 'Mostrar'; }" />

TEXTOOOOOO

Comment: " fecha o primeiro texto ao abrir o segundo" onde está o segundo texto ? Só vejo um na pergunta
Comment: Use jquery para facilitar, vocë pode aprender mais no w3schools.
pesquise sobre seletores [aqui](https://www.w3schools.com/jquery/jquery_selectors.asp) e sobre eventos [aqui](https://www.w3schools.com/jquery/jquery_events.asp)
Comment: Opa eu hospedei o site pra vocês verem como esta http://digimonworld1.000webhostapp.com/ os botoes que fiz ate agora são os dois primeiros bichinhos da coluna rosa, eu queria que o texto sumisse ao clicar em qualquer outro lugar da pagina, sem ter que clicar no bichinho de novo.
Comment: Sugiro que tente reproduzir o mesmo problema aqui reduzindo ao minimo necessário, porque o que tem na pergunta parece-me um pouco diferente do que está no seu site
Answer: Um Exemplo que pode ajudar

//array de objetos que armazena o link das imagens e o texto de cada imagem,
        //pode ser um arquivo JSON externo
        var imgTexto = [
          {"img":"https://i.pinimg.com/736x/ae/d7/bc/aed7bcbe347a262f89cc3867cdce54c2--cutest-kittens-ever-cute-baby-animals.jpg",
          "txt":"Texto da Imagem 1"},
          {"img":"https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg",
          "txt":"Texto da Imagem 2"}
        ];

        //variavel img armazena as strings das tags  ja prontas para inserir no HTML
        // geradas pelo for que vem a seguir
        var img = "";

        //for percorre o array de objetos e cria tags formatadas para inserir no HTML
        for(var key in imgTexto) {
          img += "";
        }

        //insere tags  com todas as imagems do array na div com id="imgs"
        document.getElementById("imgs").innerHTML = img;

        //função que mostra o texto referte a imagem que possui a msm key
        function mostraTexto(key) {

          document.getElementById("texto").innerHTML = imgTexto[key].txt;
        }
img {
        border: 10px solid white;
        outline: 1px solid black;
        width: 150px;
        height: 150px;
      }

Tentei deixar bem comentado para ajudar a compreensão. Clique em executar para ver funcionando. pelo que entendi é isso que está tentando fazer.


Janela modal não funciona corretamente ao clicar em YES

Question: Estou a ter algma dificuldade com o seguinte código Jquery:
JQUERY
$(document).ready(function(){
     $('#modalLogout').click(function(){
          $('#yes').click(function(){

              function time()
              {
                 $(location).attr('href',"destroy.php");
              }

              /*set 1s after ckick in yes, after that redirect to index*/
              setTimeout(function(){time()},1000);
              /*table fadeout effect*/
              $(".row").hide("slow");
        });
     });
});

O que se passa é que ao abrir uma janela modal de confirmação se tem a certeza se quer continuar ou terminar a sessão, quando eu clico em YES ele não faz nada na primeira vez, eu tenho de abrir de novo a janela e clicar em YES para a funcão time() ser executada. Já quando clico em NO funciona corretamente, ou seja fecha a janela e permanece na sessão iniciada. Como poderia alterar este estranho comportamento e melhorar o código?
Answer: Você só define o que precisa ser feito no click do YES quando clicar no #modalLogout. Não entendi bem a intenção dessa parte "de fora" do código, pelo visto bastaria definir o click do YES separadamente:
$(document).ready(function(){
     $('#yes').click(function(){

          function time()
          {
             $(location).attr('href',"destroy.php");
          }

          /*set 1s after ckick in yes, after that redirect to index*/
          setTimeout(time, 1000);
          /*table fadeout effect*/
          $(".row").hide("slow");
    });
});

Repare que também simplifiquei sua chamada ao setTimeout.
Comment: Resolveu o problema, agora o comportamento é o correto!
Answer: Se sua intenção era atribuir o evento click para o elemento #yes filho do elemento #modalLogout então a alteração que deve ser feita no seu código é a seguinte:
function time() {
    $(location).attr('href',"destroy.php");
}

$(document).ready(function() {
    $('#modalLogout #yes').click(function(){
        setTimeout(time, 1000);

        $(".row").hide("slow");
    });
});

Comment: O código de cima funcionou como eu queria, mas o seu vai mais de encontro ao que eu estava a programar e funciona também.


Dynamic TypeScript types - svelte and d3

Question: I have this problem regarding types in TypeScript: I am creating a svelte component for the x-axis for d3 visualization, where I pass the xScale as a property from the parent component as
<XAix {xScale}/>

In the parent element, where xScale is defined, TypeScript assigns a type for xScale based on the initialization of xScale, which looks something like
const xScale = d3.scaleBand().domain([/*string array*/]).range([/*numeric array*/]).padding();

and in the XAxis.svelte I annotate the xScale prop manually based on my definition of xScale. However, I would like to be able to dynamically annotate xScale inside XAxis.svelte, because I want to make XAxis.svelte a reusable component for other visualizations, and sometimes the x-axis scale is defined with another d3 scale, such as
const xScale = d3.scaleLinear().domain([/*numeric array*/]).range([/*numeric array*/])

What I am thinking is after I define the xScale in the parent element, I extract the type and store it somewhere, and then import it in the XAxis.svelte. Is this the way to go for this issue? If yes, how can I implement it? If no, what's the correct way?
Answer: Think the other way around: The Svelte component defines an API and tells its users what can be put into it. So type-wise you also need to define in advance what types it expects. I don't know much about d3 but depending on your use case you could create a type that satisfies all possible use cases, like export let xScal: number[] | number | SomethingElse;.
Answer: By building pieces of your chart with svelte components you increase the complexity through depending on order of creation of svelte components, life cycle methods and passing data between components.
I highly recommend to keep your d3 graph as a single svelte component within your svelte code and separating different pieces of your chart into TypeScript classes and functions. Then you can build your chart by using those classes and functions.
Make those classes and functions (if possible) stateless and keep the ground truth of your state at the root of the d3 svelte component.
Then you can react to events and life cycle methods in that single svelte component and update your chart accordingly.


Como fazer um loop foreach com limite em c#?

Question: Como posso fazer um loop foreach com limite, por exemplo eu tenho um dicionario com 100 itens e quero fazer um loop do item 20 até o 50 como posso fazer isso no c#.
Answer: Simples,tente os seguinte códigos como exemplos :
Foreach exemplo 1 :
foreach(ListViewItem lvi in listView.Items.Skip(20))
{
   //faça algo
   if (++itens == 50) break;
}

Foreach exemplo 2 :
foreach(var itens in dicionario.Items.Skip(20).Take(50))

For :
for(int itens = 20; i <= 50 && i < dicionario.Items.Count; i++)
{
    ListViewItem lvi = dicionario.Items[i];
}

LINQ :
foreach( ListViewItem lvi in dicionario.Items.Cast<ListViewItem>().Skip(20).Take(50))
{
    //faça algo
}

Para melhores esclarecimentos,dê uma olhada na documentação do foreach aqui e do for aqui.
E para melhor entendimento dos métodos Skip() e Take() dê uma olhada aqui.


Relacionamento entre as tabelas

Question: Tenho as seguintes tabelas:
TB_ESTOQUE
|COD_PRODUTO|QT_DISPONIVEL|COD_FILIAL|
|  0856322  |      5      |    41    |
|  0856351  |      2      |    41    |
|  0856322  |      9      |    114   |
|  0856720  |      3      |    20    |
|  0856322  |      8      |    128   |
|  0856322  |      12     |     35   |
|  0856322  |      4      |     9    |

TB_FILIAL
|COD_FILIAL|COD_LOCALADM|
|    41    |    114     |
|    128   |    114     |
|    114   |    114     |
|    10    |    156     |
|    56    |     12     |
|    35    |     12     |
|    9     |     12     |

TB_PRODUTO
|COD_PRODUTO|DESC_PRODUTO|
|  0856322  | CALCARIO   |
|  0856351  | ZINCO      |
|  0856321  | SEMENTE    |
|  0856720  | INSETICIDA |
|  0856752  | STE SOJA   |

Tabela desejada:
|COD_PRODUTO|DESC_PRODUTO|QT_DISPONIVEL|COD_FILIAL|
|  0856322  |   CALCARIO |       5     |    41    |
|  0856322  |   CALCARIO |       9     |    114   |
|  0856322  |   CALCARIO |       8     |    128   |

Estou executando o seguinte SQL:
SELECT
E.COD_PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_ESTOQUE E
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE
E.COD_PRODUTO = 856322
ORDER BY
P.DESC_PRODUTO

Como eu relaciono no SQL a tabela TB_FILIAL, filtrando pelo código COD_LOCALADM?
Exemplo:
... WHERE
    E.COD_PRODUTO = 856322 AND
    TB_FILIAL.COD_LOCALADM = 114

Answer: Não existe COD_PRODUTO na tabela TB_ESTOQUE segundo o seu exemplo.
Experimente:
SELECT
E.PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_ESTOQUE E, TB_FILIAL F
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.PRODUTO
WHERE
F.COD_FILIAL = E.COD_FILIAL AND
F.COD_LOCALADM = 114 AND
E.PRODUTO = 856322
ORDER BY
P.DESC_PRODUTO

Comment: Na verdade existe, eu que coloquei errado.
Comment: A coluna não existe, a coluna que queria era PRODUTO e essa sim existe. Caso eu o tenha ajudado por favor marque a minha resposta como a solução.
Comment: Não ajudou, pois a coluna existe. Vou reformular a minha pergunta.
Comment: A coluna não existe, segundo o que você colocou como exemplo de tabela não existe coluna cod_produto mas sim apenas coluna produto na tabela estoque. Editar a pergunta para corrigir um erro seu no exemplo e dizer que não foi ajudado é incrível. Pessoas como você fazem me deixar de comentar neste site, pedem ajuda, são ajudadas, respondem mal e ainda editam a pergunta. Enfim...
Answer: Basta adicionar a tabela de filial na clausula FROM e adicionar os parâmetros para filtragem no WHERE, sem muita complicação:
SELECT
E.COD_PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_FILIAL F,
TB_ESTOQUE E
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE
E.COD_PRODUTO = 856322
AND E.COD_FILIAL = F.COD_FILIAL
AND F.COD_LOCALADM = 114
ORDER BY
P.DESC_PRODUTO

Answer: Pode usar o código abaixo, pois acho que não haverá um cenário onde você guarda apenas uma filial no estoque sem produto, ou um produto sem uma filial.
Para o WHERE funcionar, basta apenas colocar as junções, e depois ir chamando Tabela.Campo de acordo com a necessidade.
SELECT
  P.COD_PRODUTO,
  P.DESC_PRODUTO,
  E.QT_DISPONIVEL,
  F.COD_FILIAL
FROM TB_ESTOQUE E
INNER JOIN TB_FILIAL F
  ON F.COD_FILIAL = E.COD_FILIAL
INNER JOIN TB_PRODUTO P
  ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE P.COD_PRODUTO = 856322
  AND F.COD_FILIAL = 114
ORDER BY
  P.DESC_PRODUTO

Relacionamento entre as tabelas


How to prove that the only curve that minimises the distance between two points in Euclidean space is a straight line?

Question: I am able to prove that one curve in $C^1([0,1], \mathbb{R})$, $r$, that has minimal length connecting two points is a straight line. If these points are $p, q \in \mathbb{R}^n$, then the distance is $|q-p|$. I am, however, struggling to prove that no curves other than a straight line have length $|q-p|$ and have no idea where to start.
For a parameterised curve, $r \in C^1([0,1], \mathbb{R})$, I am finding the length via $\ell(r) = \int_0^1 |\dot{r}(t)|dt$.
Comment: I suspect you could probably prove it without the calculus of variations by making the argument that you can approximate any curve in $C^1([0,1],]\mathbb{R})$ by a curve which is piecewise linear.  Then apply the triangle inequality recursively to show that you can eliminate any "middle point" on this line and decrease the distance.
Comment: Please edit the question to add your working definition of a _curve_. (Particularly, is a _curve_ continuously differentiable?)
Comment: The traditional proof uses the [calculus of variations](https://en.wikipedia.org/wiki/Calculus_of_variations) on the functional $\ell(r)$.  (It actually happens to be easier to use the integral of $|\dot{r}|^2$, but it works either way.)  Basically the calculus of variations lets you consider, for every possible curve, the space of all nearby curves.  Then you show that the straight line is the only local minimum of this space.  This is probably enough to satisfy most students, though of course a rigorous proof involves filling in some more details.
Answer: If $s\in [0,1]$ such that $r(s)$ does not lie on the line segment connecting $r(0)$ and $r(1)$, then by the triangle inequality and the fundamental theorem of calculus we have
\begin{align*}
\ell(r) &= \int_0^1 |\dot{r}(t)|dt= \int_0^s |\dot{r}(t)|dt + \int_s^1 |\dot{r}(t)|dt\\
 &\geq \left|\int_0^s \dot{r}(t)dt\right| + \left|\int_s^1 \dot{r}(t)dt\right| \\
&= |r(s)-r(0)|+|r(1)-r(s)|>|r(1)-r(0)|.
\end{align*}
Remark
Another way to see this is that once we have a definition of length that always satisfies $\ell(r)\geq |r(b)-r(a)|$ for a curve parametrized by $[a,b]$ (which you have already shown apparently, presumably using the fundamental theorem), and satisfies $$\ell(r|_{[a,c]})+\ell(r|_{[c,b]})=\ell(r)$$ for $a<c<b$, then we are done, since if $r(c)$ is not on a line segment with $r(a)$ and $r(b)$ then we have
\begin{align*}
\ell(r) &= \ell(r|_{[a,c]})+\ell(r|_{[c,b]})\\
 &\geq |r(c)-r(a)|+ |r(b)-r(c)|\\
&>|r(b)-r(a)|.
\end{align*}
This is useful to keep in mind when considering curves not parametrized smoothly, using more general definitions of arc-length.


Can't score test set using zero inflated Poisson regression model in SAS

Question: I've run a zero-inflated Poisson model using proc genmod and I'm trying to score my test data set using Proc PLM but it's giving me this error:
proc genmod data = train2;
class region  / param=glm;
model response = var1 var2 var3 var4 var5
                    / dist=zip;
                    zeromodel;
output out = zeropoisson_output predicted= estprobzip;
store zero_poisson;
run;

proc plm source=zero_poisson;
  score data = test2 out= pred_zip;
run;

ERROR: Scoring zero-inflated models is not supported in this release of the PLM procedure.
any ideas of how to get around this?
Comment: Specifically, what version of SAS/STAT? (Starting after SAS 9.22, they began issuing separate release numbers, which would begin with 12.1, which came out with SAS 9.3).
Comment: I'm using SAS EG 4.3
but SAS Base is 9.3 - I'm not sure how to get additional version info or if there is any?
Comment: You can look at the Server (commonly Local Server if you are doing this on your desktop, otherwise pick the server), right click, select Properties, then select "View initialization log", which will include information about your version, including SAS/STAT version.
Comment: It looks like SAS/STAT 13.1 (base 9.4) is where they added the Zero Inflated method scoring to PLM, see [this page](http://support.sas.com/documentation/cdl/en/statug/66859/HTML/default/viewer.htm#statug_plm_details03.htm) and contrast with [this page from 9.3/12.1](http://support.sas.com/documentation/cdl/en/statug/65328/HTML/default/viewer.htm#statug_plm_details02.htm) which doesn't have an entry for the 9.4 page on its left bar.
Comment: ah...any ideas how i could perhaps score it up manually? if it were a normal logit/poisson model then i could start manually scoring it using variable coefficients but with a zero inflated model i'm a little confused as to how i would go about this?
Answer: It will take considerably more effort, but you could always use the ODS output option to get the Parameter Estimates and parse through the data from there. I grabbed some example data from a SAS example on genmod and have demonstrated the concept of saving the coefficients and parsing through them below. The output is a .sas file that can be %included in any data step to score a validation sample.
data drug;
   input drug$ x r n @@;
   datalines;
    A  .1   1  10   A  .23  2  12   A  .67  1   9
    B  .2   3  13   B  .3   4  15   B  .45  5  16   B  .78  5  13
    C  .04  0  10   C  .15  0  11   C  .56  1  12   C  .7   2  12
    D  .34  5  10   D  .6   5   9   D  .7   8  10
    E  .2  12  20   E  .34 15  20   E  .56 13  15   E  .8  17  20
    ;
run;

ods output ParameterEstimates = ZIP_COEFF_EST;
proc genmod data=drug;
      class drug;
      model r/n = x drug / dist = zip;
      zeromodel;
run;
ods output close;

data ZIP_COEFF_EST_Parsed;
    length equation $ 2500;
    set ZIP_COEFF_EST (rename=(estimate=coefficient)) end=last;
    where coefficient ne .;
    if upcase(Parameter) = "INTERCEPT" then do;
        equation = " = " || trim(left(put(coefficient,20.10)));
        output;
    end;
    else if LEVEL1 ne '' then do;
        equation = " + (" || trim(left(Parameter)) || " = '" || trim(left(LEVEL1)) || "') * (" || trim(left(put(coefficient,20.10))) || ")";
        output;
    end;
    else do;
        equation = " + " || trim(left(Parameter)) || " * (" || trim(left(put(coefficient,20.10))) || ")";
        output;
    end;
    if last then do;
        equation=';';
        output;
    end;
    keep equation;
run;

data _null_;
    set ZIP_COEFF_EST_Parsed;
    FILE  "C:/estimate_file.sas";;
    PUT equation;
run;


Let $A$ be a square matrix such that $A_10=0$ while $A_9≠0$. Let $V$ be the space of all polynomials of $A$. Find the dimension of $V$.

Question: Let $A$ be a square matrix such that $A^{10}=0$ while $A^9≠0$. Let $V$ be the space of all polynomials of $A$. Find the dimension of $V$.
The part that is really throwing me off is that $A_9≠0$. This is throwing me off to find the dimension of $V$.
Comment: Could you explain your notation?
Comment: Maybe $A^{10}$ and $A^9$? @msm
Answer: If $A^{10} =0$ then any polynomial in A is a linear combination of $I,A,A^{2},... , A^{9}$ (because, $A^{10},A^{11},A^{12},..$ are all 0. Now let us show that $I,A,A^{2},...,A^{9}$ are linearly independent. Suppose $\sum_0 ^{9} a_i A^{i} =0$. Multiply both sides by $A^{9}$ to see that $a_1 =0$. Then multiply by $A^{8}$ to get $a_2 =0$ etc. In 10 steps you get $a_i =0$ for $0 \leq i \leq 9$. Hence $I,A,A^{2},...,A^{9}$ form a basis for V and the dimension is 10.
Comment: Huh, this kinda makes sense.


Analysis of multiple response/check all that apply survey data

Question: I am helping to review a manuscript and suffering from mental block on some data analysis. The data in question is from a cross-sectional survey, a health care provider KAP (knowledge, attitudes, and practices) on vector borne diseases (Zika, Chikungunya, Dengue, and West Nile Virus).
The question I am stuck on is formatted like so:
An image of the survey question that I am referencing, for clarity.

Which of the following do you associate with illness caused by each virus? Check all that apply.
<code>                     Dengue   Chikun    Zika    WNV    Don't know
Rash
Fever
Cough
Arthralgia
Conjunctivitis
Myalgia
Retro-orbital pain
Headache
Hemorrhage
Altered mental status
</code>
For each disease and symptom, the author has coded a 1 for correct response, and 0 for incorrect response. Not all symptoms present with each disease, and thus leaving the check box empty is considered the correct response in these cases. The primary author is then computing a total correct for each participant (out of 10 possible correctly identified symptoms for each disease). Using the total correct scores, the author is running within-subjects ANOVA on mean correct scores for each disease group in order to identify any differences in levels of knowledge among the different diseases, and then running post-hoc paired t-tests.
In terms of hypothesis, it would be structured like this:
Ho: There are no significant differences in the average number of correctly identified symptoms/illnesses between selected vector borne diseases.
Ha: There is a significant difference in the average number of correctly identified symptoms/illnesses between selected vector borne diseases.
Post-hoc: If there are sig. difference, which diseases have significantly different scores?
I am hoping for your advice on how to best analyze this data as I am quite stumped. My initial thoughts were to code each response (0 - incorrect, 1 - correct) and create contingency tables for each symptom, and analyze with chi-square tests. Although I'm not sure how I would then locate potential differences between each disease.
I should note that the goal is to determine if any differences exist between diseases, not symptoms. Whether it is cumulative or individual to each symptom is not specified.
Is the author correct in running a within-subjects ANOVA, and simply needs to adjust to the proper post hoc test (Tukey?) to identify the differences in diseases?
I should also note that the author is using SPSS for analysis.
Unfortunately, I don't have access to the data at this time to run anything on my end. Any input and feedback is greatly appreciated!
Comment: With no clue what the authors' purpose is and no idea what data are going into their ANOVA it is difficult for me to imagine helpful advice coming from this question. For now, I'm voting 'unclear what you're asking' and hoping for some clarification.
Comment: Thanks for the response @BruceET. I added an image of the question from the survey that should hopefully provide some clarity on the data received (I couldn't think of a good way to format a check box/bubble). I have also added in more detail on the author's purpose, as well as a null and alt hypothesis. If you are able to revisit, that would be awesome. Thanks again.
Answer: If I am understanding this correctly, the goal is to compare the degree of knowledge of different diseases. Rather than ANOVA, I would use a count regression model, as each disease can only get integer values from 0 to 10 - with, hopefully, no 0s.
You could try Poisson regression to start, but negative binomial might be needed.
The "check all that apply" issue is removed by using the total correct.
Comment: Thank you for the response Peter. I can see that count regression would be useful here, though I hadn't thought of it previously. I will suggest to the author, but I fear that modeling may be beyond the scope of his paper and statistical ability (health promotion student).
Comment: Yeah ..... that happens a lot. He might have to hire a consultant, but he probably won't want to.