glBindTexture não aplica textura em GL_QUADS

Question: Problema: glBindTexture não aplica a textura em "GL_QUADS" ao usar OPENGL em C++.
Minha experiência em c++, e principalmente em OPENGL é limitada, porém, me baseei neste código. Fiz alguma poucas modificações para torná-lo compatível com meu projeto. As modificações podem ser observadas na reprodução abaixo.
Ao testar o código original, verifiquei que funciona. Mas esta modificação, fez com que a textura não fosse aplicada. Os "GL_QUADS" são criados, tudo funciona perfeitamente, exceto, a textura.
NOTA: Observei algumas questões relacionadas ao assunto, aqui no "stackoverflow", porém, as repostas não foram suficientes para mim. Ainda segui um tutorial da Nanyang Technological Uuniversity.
Fico agradecido por qualquer ajuda.
bool loadPngImage(char *name, struct pnhImage *img){ //int &outWidth, int &outHeight, bool &outHasAlpha, GLubyte **outData); // TESTADO NO CODIGO ORIGINAL LINK https://gist.github.com/mortennobel/5299151
bool loadTexturePNG(char *filepath, struct pnhImage *img);
void buildQuadradoColorText(char webcolor[7], GLuint tID, float x, float y, float w, float h){;
void desenhar();

bool initGL(int argc, char** argv){
  glutInit(&argc, argv);                              // Initialize GLUT
  glutInitDisplayMode(GLUT_DOUBLE);                   // Set double buffered mode
  glutCreateWindow("OpenGL Setup Test");              // Create a window with the given title
  glutInitWindowSize(Tela.width, Tela.height);        // Set the window's initial width & height
  glutInitWindowPosition(0, 0);                       // Position the window's initial top-left corner
  glutFullScreen();                                   // Exibe em tela cheia
  glutDisplayFunc(desenhar);                          // Register display callback handler for window re-paint
  glutReshapeFunc(winResize);                         // Register callback handler for window re-size event
  glutMouseFunc(mouseEvent);                          // EVENTOS DO MOUSE
  glutMotionFunc(MotionCallback);                     // MONITORA MOVIMENTOS DO MOUSE COM BOTAO ATIVO
  glutPassiveMotionFunc(passiveMotionCallback);       // MONITORA MOVIMENTO DE MOUSE COM BOTAO INATIVO
  glutSpecialFunc(keyPressEspecial);                  // EVENTOS DE TECLAS ESPECIAIS
  glutTimerFunc( refreshFrame, Timer, 0);             // First timer call immediately

  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);               // Black and opaque

  glEnable(GL_DEPTH_TEST);
  // The following two lines enable semi transparent
  glEnable(GL_BLEND);
  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glShadeModel(GL_FLAT);
  glEnable(GL_TEXTURE_2D);

  return true;
}

bool loadTexturePNG(char *filepath, struct pnhImage *img){
  std::cout << "Carregando textura '" << filepath << "' ";

  // CARREGA O TILE DO SOLO
  if (loadPngImage(filepath, img)){
    img->tID = 0;

    glEnable(GL_TEXTURE_2D);

    // CRIA UMA TEXTURA OPEGL
    glGenTextures(1, &img->tID );

    std::cout << ">> tID: '" <tID << "' ";

    // "Bind" a textura recém-criado: todas as funções textura futuras irá modificar esta textura
    glBindTexture(GL_TEXTURE_2D, img->tID);

    // FORNECE A IMAGEM AO OPNGL
    glTexImage2D( GL_TEXTURE_2D,
                  0,
                  img->alpha ? 4 : 3,
                  img->width,
                  img->height,
                  0,
                  img->alpha ? GL_RGBA : GL_RGB,
                  GL_UNSIGNED_BYTE,
                  img->data
    );

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    // Quando Ampliar a Imagem (sem mipmap maior disponível), use filtragem LINEAR
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Quando minifying a imagem, use uma mistura linear de dois mipmaps, cada filtrada linearmente também
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // Gera mipmaps, pelo caminho.
    //glGenerateMipmap(GL_TEXTURE_2D);

    // APAGAMOS/LIBERAMOS A IMAGE QUE JAH FOI CARREGADA PARA O OPENGL
    //SDL_FreeSurface(img->data);

    if (glGetError() != GL_NO_ERROR){
      std::cout << "[FALHA]" << std::endl;
      return false;
    }

    std::cout << "[OK] " << std::endl;

    glBindTexture(GL_TEXTURE_2D, 0);

    return true;
  }else
    std::cout << "[FALHA] " << std::endl;

  return false;
}

// X -> LEFT POINT, Y, TOP POINT, W -> WIDTH, H -> HEIGHT
void buildQuadradoColorText(char webcolor[7], GLuint tID, float x, float y, float w, float h){
  struct rgbColor cor = WebColorTORgb(webcolor); // CONVERT HEX TO INT RGB

  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

  glColor3f (cor.r, cor.g, cor.b); // ISSO FUNCIONA, E A OMISSAO NAO INTERFERE
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, tID);

  // Draw a Red 1x1 Square centered at origin
  glBegin(GL_QUADS);            // Each set of 4 vertices form a quad
    printf("texture id: %d.\n", tID );

    glTexCoord2f(0  , 0);
    glVertex2f( x   , y   );    // x, y

    glTexCoord2f(1, 0);
    glVertex2f( x+w , y   );

    glTexCoord2f(1, 1);
    glVertex2f( x+w , y-h );

    glTexCoord2f(0, 1);
    glVertex2f( x   , y-h );

  glEnd();

  glBindTexture(GL_TEXTURE_2D, 0);
}

void desenhar(){
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     // Clear the color buffer (background)

  glMatrixMode(GL_MODELVIEW);                             // To operate on Model-View matrix
  glLoadIdentity();

  buildQuadradoColorText((char*)"#24a621", tID, -1, 1, 2, 2);

  // MANDA O GRAFICO RENDERIZADO PARA A JANELA
  glutSwapBuffers();
}

Comment: Seria melhor você detalhar o que mudou no código, assim fica difícil saber qual o problema. Dica: Esse código usa o OpenGL versão < 3.1, que ninguém mais recomenda utilizar, se você está só dando manutenção em uma aplicação já existente, tudo bem. Agora se está criando algo novo, recomendo veemente que faça utilizando OpenGL 3.2+, Você pode ter os primeiros passos a partir desse site: http://open.gl
Comment: @paulocanedo , obrigado por sua atenção, estou usando OPENGL 4.5. Relativo a mudança, o que ocorreu foi que o código original texturizava um quadrado diretamente, eu transformei isso em uma função loadTexturePNG, que carrega um PNG e indexa a um índice usando glBindTexture. Isso permite que um mesmo código (função) seja usado para carregar várias texturas distintas (arquivos), e também permite a reutilização da textura com glBindTexture + ID da textura. Foi o que entendo sobre o funcionamento glBindTexture. Portanto, carrego PNGs, vinculando a ID de texturas, e depois as reutilizo.
Comment: @paulocaned O objetivo de criar uma função que carregue e indexe as texturas, é evitar que toda vez que a janela for redesenhada, seja necessário recarregar o aquivo do HD, e ainda transformá-lo em textura. Isso ocuparia processamento desnecessário. Os índices de textura são salvos num vetor de struct, para esta finalidade.
Answer: Descobri a solução, e o problema se encontrava na função loadTexturePNG. Embora eu admita que não entendo realmente o motivo, o teste de compilação verificou que a mudanças corrigiram o problema.
Caso alguém queira complementar explicando o motivo por que esta solução foi bem sucedida, fico agradecido.

Substituir glTexParameteri por glTexParameterf;
Comentar ou exclua a linha:

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

Pronto, a texturização funciona! Veja a função alterada:
/* CARREGA UMA IMAGEM PNG DE TEXTURA PARA O OPENGL */
bool loadTexturePNG(char *filepath, struct pnhImage *img, bool desbind = true){
  std::cout << "Carregando textura '" << filepath << "' ";

  // CARREGA O TILE DO SOLO
  if (loadPngImage(filepath, img)){
    img->tID = 0;

    // CRIA UMA TEXTURA OPEGL
    glGenTextures(1, &img->tID );

    std::cout << ">> tID: '" <tID << "' ";

    // "Bind" a textura recém-criado: todas as funções textura futuras irá modificar esta textura
    glBindTexture(GL_TEXTURE_2D, img->tID);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // FORNECE A IMAGEM AO OPNGL
    glTexImage2D(
                  GL_TEXTURE_2D,
                  0,
                  img->alpha ? 4 : 3,
                  img->width,
                  img->height,
                  0,
                  img->alpha ? GL_RGBA : GL_RGB,
                  GL_UNSIGNED_BYTE,
                  img->data
    );

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);

    // Quando Ampliar a Imagem (sem mipmap maior disponível), use filtragem LINEAR
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    // Quando minifying a imagem, use uma mistura linear de dois mipmaps, cada filtrada linearmente também
    //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    // Gera mipmaps, pelo caminho.
    //glGenerateMipmap(GL_TEXTURE_2D);

    // APAGAMOS/LIBERAMOS A IMAGE QUE JAH FOI CARREGADA PARA O OPENGL
    //SDL_FreeSurface(img->data);

    if (glGetError() != GL_NO_ERROR){
      std::cout << "[FALHA]" << std::endl;
      return false;
    }

    std::cout << "[OK] " << std::endl;

    if (desbind)
      glBindTexture(GL_TEXTURE_2D, 0);

    // LIBERA A IMAGEM DA MEMORIA
    free(img->data);

    return true;
  }else
    std::cout << "[FALHA] " << std::endl;

  return false;
}


Htaccess 301 redirect forum urls

Question: I need to redirect forum and topic links to a new format, without losing there ranking in google.
The situation at this moment:
site.com/forum/32-News  -->forum name
site.com/topic/935-topic-name
How it needs to be:
site.com/board/32-News  -->forum name
site.com/thread/935-topic-name
I searched on this site and google, but did not found anything that matches my issue.
Thanks!
Answer: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteRule ^forum/(.+)$ /board/$1 [L,NC,R=301,NE]

RewriteRule ^topic/(.+)$ /thread/$1 [L,NC,R=301,NE]

Htaccess 301 redirect forum urls


AR(1) Covariance

Question: So I'm trying to derive the covariance between $z_t$ and $z_{t-1}$ in the $AR(1)$ model:
$z_t =\phi z_{t-1} + a_t$. Can anyone give me some advice on where to start?
Comment: Have you tried to compute $\mbox{cov}(z_t, z_{t-1})$? What did you get? Where are you stuck?
Comment: The answer is here: http://stats.stackexchange.com/questions/68243/ar1-coefficient-is-correlation/68246#68246
Comment: Hey Quantlbex, at first I wasn't sure where to start, but now this is what I'm getting: $cov(z_t, z_{t-1}) = cov(\phi z_{t-1} + a_t, z_{t-1}) = \phi cov(z_{t-1}, z_{t-1}) + cov (a_t, z_{t-1}) = \phi var(z_{t-1}) + cov(a_t, z_{t-1}) = \phi (\frac{\sigma^2}{1-\phi^2})$. Does that seem correct to you? Would you mind explaining why $cov(a_t, z_{t-1}) = 0$?
Comment: Also, if I was trying to find the $cov(z_t, z_{t-2})$, does this seem correct: $cov(z_t, z_{t-2}) = \phi^2 var(z_{t-2}) + \phi cov(a_{t-1}, z_{t-2}) + cov(a_t, z_{t-2}) = \phi^2 (\frac{\sigma^2}{1-\phi^2})$ ?
Answer: Just write it out the old fashioned way:
$$ Cov(z_t, z_{t-1}) = Cov(\phi z_{t-1}+a_{t-1},z_{t-1})=\phi Cov(z_{t-1},z_{t-1})+Cov(a_{t-1}, z_{t-1})=\phi Var(Z)
$$
The derivation for $Var(Z)$ is a little different but same approach:
$$Var(z_t)=Var(\phi z_{t-1}+a_{t-1})=\sigma_a^2+\phi^2 Var(z_{t-1})
$$
Since $Var(z_t)=Var(z_{t-1})$, you can get that $Var(Z)=\frac{\sigma_a^2}{1-\phi^2}$ for all $t$.
Now plug that back in and you're done.
Comment: Thanks Mike, that is very helpful. Would you mind explaining why $cov(a_t,z_{t-1}) = 0$? Is it because a there can't be a covariance between $z_{t-1}$ and a future error term, $a_t$?
Comment: Also, if I was trying to find the $cov(z_t, z_{t-2})$, does this seem correct: $cov(z_t, z_{t-2}) = \phi^2 var(z_{t-2}) + \phi cov(a_{t-1}, z_{t-2}) + cov(a_t, z_{t-2}) = \phi^2 (\frac{\sigma^2}{1-\phi^2})$ ?
Comment: Ya that does seem right. $Cov(a_t,z_{t-1})=0$ because $a_t$ is i.i.d. noise and it does not appear in $z_{t-1}$, so they are independent.

AR(1) Covariance


How to use multiple cache sink in a single data flow and use outputs of both the sinks in a pipeline?

Question: I am having two cache sinks in a dataflow, when selecting write to activity output for both the sinks throws validation error: Multiple Cache sinks found with output set to 'true'. Output for only one sink is supported.
Is there any workaround / Solution to use output of both the sinks in a single pipeline?
Answer: Only 1 cached sink can send output from a data flow. Would it be possible to combine or union multiple data streams into a single cache sink in your data flow?
Comment: Hi @Mark yes i had to do that because multiple sink was not possible. Thanks


trying to dynamically change drupal commerce order

Question: I am trying to create a pane on the drupal commerce checkout page which will will give the user some options to change which product is in the cart. I want this done with ajax, without leaving the checkout page.
This is the code I have written so far:
  global $user;
  $product_id = 3;
  $order_id = commerce_cart_order_id($user->uid);
  commerce_order_delete($order_id); //delete the present order
  $newOrder = commerce_order_new($user->uid); //and create a new one
  commerce_order_save($newOrder);   //NEED?
  $product = commerce_product_load($product_id);
  $lineItem = commerce_product_line_item_new($product, 1, $newOrder->order_id);
  commerce_line_item_save($lineItem); //NEED?

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($newOrder);
  commerce_cart_order_refresh($newOrder);

  return $form;

However, this code gives me an ajax error

Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://example.com/system/ajax

Am I making a code error? A Commerce error?
Comment: Check your server logs, they will contain a proper error message.
Answer: Going out on a limb a bit...
There's no function called commerce_new_order, you probably mean commerce_order_new()
Same thing with commerce_load_product() and commerce_product_load()
Comment: You're right. I changed that, an now I get a different error pop up: An AJAX HTTP error occured: Debugging information follows. Path /system/ajax StatusText: error ResponseText: EntityMetadataWrapperException: MIssing data values. in EntityMetadataWrapper->value() line 83 etc
Comment: It doesn't look like you've initialised the `$order` variable
Comment: your right, edited that above. But still have the same error.
Comment: You still haven't initialised an `$order` variable. The problems you're having are all to do with incorrectly named variables. Do yourself a favour - delete the code you have, and start again from fresh, paying close attention to the names of the variables you're creating, and how you're then using them
Comment: sorry, did a full edit now. I think it might work, just not sure yet because I think I have some rules set up which are messing with the order as well.
Comment: But is this the correct way of doing things? Is there a way to delete the products inside of an order without actually deleting the order?
Comment: Personally I'd just remove the line item from the existing order, rather than making a whole new order. Have a look at [`commerce_cart_order_empty()`](http://drupalcontrib.org/api/drupal/contributions!commerce!modules!cart!commerce_cart.module/function/commerce_cart_order_empty/7) and [`commerce_cart_order_product_line_item_delete()`](http://drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21cart%21commerce_cart.module/function/commerce_cart_order_product_line_item_delete/7) for some inspiration
Comment: Perfect, thats exactly what I need! One more question: I was trying to copy someone else's example. Would I really need both commerce_line_item_save() and commerce_order_save() if I just update a previous order? Wouldn't the former be enough, since I gave it the order id?
Comment: Saving the order won't save the referenced entities, no (or at least in my experience it doesn't)


While para analisar retorno de Select

Question: boa tarde!
Estou tendo meu primeiro contato com MySQL, antes trabalhava com Oracle, e me deparei com um problema que no Oracle, eu tinha a seguinte estrutura:
for a in (select id, nome, salario from usuario)
loop
/*
  Meu código aqui. Realizar um novo select, insert, update e etc.
*/
end loop;

Com essa estrutura eu conseguia trabalhar linha a linha do retorno do select, mas no MySQL procurei e não encontrei nada parecido, me parece que ele nem implementa o comando for. Gostaria de saber se alguem já precisou de algo parecido e como foi que resolveu o problema, ou mesmo idéias para contornar o problema já facilitaria muito.
Obrigado
Comment: Veja: https://dev.mysql.com/doc/refman/8.0/en/sql-compound-statements.html
Answer: Para iterar sobre um resultado de um SELECT utilize um CURSOR. Aplicado no seu exemplo ficaria assim:
CREATE PROCEDURE curdemo()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE id INT;
  DECLARE nome CHAR(16);
  DECLARE cur CURSOR FOR SELECT id, nome FROM usuario;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur;

  read_loop: LOOP
    FETCH cur INTO id, nome;

    IF done THEN
      LEAVE read_loop;
    END IF;

    // Aqui seu código
  END LOOP;

  CLOSE cur;
END;

CURSORS
MySQL supports cursors inside stored programs. The syntax is as in embedded SQL. Cursors have these properties:
Asensitive: The server may or may not make a copy of its result table
Read only: Not updatable
Nonscrollable: Can be traversed only in one direction and cannot skip rows
Cursor declarations must appear before handler declarations and after variable and condition declarations.

Em tradução livre:

O MySQL suporta cursores dentro de procedimentos armazenados. A sintaxe é como no SQL padrão. Cursores possuem essas propriedades:
Asensitive: O servidor pode ou não pode fazer uma cópia dos resultados da tabela
Read only: Não atualizável
Nonscrollable: Pode ser percorrido em apenas uma direção e não pode pular linhas
A declaração do cursor deve aparecer antes da declação do handler e depois das variáveis e declarações condicionais.

While para analisar retorno de Select


Transmitting the location of Physical process to Application module in Castalia

Question: So when a physical process calculates the return value using the following function:
retVal TargetPhysicalProcess::calculateScenarioReturnValue(const double &x_coo,
                             const double &y_coo, const simtime_t &stime)
along with the value I am also sending the location of physical process taken from current snapshot. When the sensor manager receives the reply it extracts the data from  PhysicalProcessMessage and stores it in a SensorReadingMessage to send to Application module.
So when the data is extracted from PhysicalProcessMessage,I extract the location as well and when I have to store data in SensorReadingMessage, I can't do that because there are no readingMsg->setXcoor and readingMsg->setYcoor functions.
What can be the possible solution?
Comment: I noticed that you are asking a lot of questions on Castalia lately, without studying existing material first. This question for example shows a basic misunderstanding on the model of physical process. Stackoverflow is not a personal tutor, and I cannot keep answering questions that show a lack of effort to learn the basics of Castalia first.
Comment: I have studied the code of physical process and i have modified the calculateScenariofunction.
I am working on my thesis right now, I developed the algorithms first and then studied castalia and that is why I am changing some things according to my algorithm.
Answer: The location you are referring to is already known by the node. It is the location of the node! The various modules within the node already have access to this info (through the MobilityManager).
There is no "location of the physical process". The physical process happens all over the space. It is the node who is asking for a specific value in space and time that it has to provide the location and time moment.
Comment: Since I am working on a target tracking application, I am working on retracing the path at sink node. I have changed the code of calculatescenario function and now its not all over the space.
By location i mean x and y value of a snapshot.
the snapshots are representing the path of target hence I am transmitting x and y values to application module.
Comment: You seem utterly confused about what `x_coo` and `y_coo` are in the function call. I already explained some basics, and the manual also has information on the basics of phy process and overall modelling. Study it. I cannot stress this enough. As a side node, sending back to the node the location of the target seems like a horrible way to simulate any tracking system. If you do not understand this, I suggest you consult with your advisor.


Why does Bach not resolve this chordal seventh down by step?

Question: I was reading this chorale by Bach (#130, "Meine Seele erhebet den Herrn", BWV 324)  and discovered something curious. It starts in Em and modulates to G. In the last beat of the third bar, he plays a sixth chord in the key of G, with a 7th. Em7.
Interestingly, this seventh (D) doesn't resolve downwards but actually goes up to an E in the next bar. I don't understand why Bach does this here. Why does he include the seventh of the chord, to then avoid resolving it?
Any wisdom on this is appreciated!
Answer: The D on the fourth beat in the alto is an error.  It should be an E.  You can compare editions at IMSLP.  Both the original edition of the 1780s and the second engraving of 1831 have the E; the D was introduced in the 1870s engraving.  The Neue Bach Ausgabe has the E.
Answer: Another comment mentioned that there was an engraving error.
Aside from this, I would also note that it is possible to resolve a dissonance by switching the resolving note with another from the same chord. Beethoven calls this a "permutation of resolution."
In the first example he gives, the upper F and bass B, which normally resolve to E and C, respectively, instead resolve to C and E.

Louis Van Beethoven's Studies in Thorough-bass, Counterpoint and the Art of Scientific Composition,
Comment: Interesting.  I don't suppose this possibility actually applies in Bach's style, but one can imagine that an engraver in the 1870s might not be aware of that, making it rather less surprising for the engraver to overlook the voice leading error.


Retrieve an element from a given index in the biggest list value of a JSON

Question: Here are the instructions:

Giving a randomly-generated JSON string. Find the longest list and
return its key, followed by a dash ('-'), followed by the element at
index 1
{
  "agistment": "nonpromulgation",
  "gastroparietal": 4599,
  "ryotwar": [
    "mealies",
    "sophistress",
    "money",
    "astraeid"
  ],
  "pranava": [
    "rosinesses",
    "basis"
  ],
  "loomer": 581.6,
  "bangalay": "orthopnea",
  "inflexive": 3367,
  "spinelles": [
    "druith",
    "pseudomonades",
    "nonrhythmically",
    "ischiocavernosus",
    "operettist"
  ],
  "articulator": 2805.3,
  "preempted": [
    "equvalent",
    "mesoderms",
    "idlers"
  ],
  "unfractiously": [
    "semitextural",
    "stilyaga",
    "coddle",
    "identism"
  ],
  "synkinesia": 4993,
  "linoleum": "overcram",
  "nations": "colleagueship",
  "lithonephria": "presoaked",
  "subpartitioned": "tiresomeness",
  "triternately": [
    "postaxial",
    "nonimmune",
    "eopaleozoic",
    "maledict",
    "ritzily",
    "whisperation"
  ],
  "etoile": "nonvesting",
  "decussorium": [
    "tocusso",
    "butterfingered",
    "sizeman",
    "duetted",
    "misthrew",
    "untextually",
    "splenotyphoid",
    "acmispon"
  ],
  "novelties": "hypersthenite",
  "aesop": [
    "sabadinine",
    "tangency"
  ],
  "potlatching": [
    "lucrific",
    "tupaia",
    "dedenda",
    "burglarise",
    "tanagroid",
    "grewsomely",
    "lipotype",
    "squarable",
    "withholdal",
    "antidotes"
  ],
  "preformistic": "broadsiding",
  "papovavirus": 3917,
  "hurri": [
    "catcall"
  ]
}

Note : the index and JSON is randomly generated each time I do the lab, so I have to write generalized code. Here's what I came with first :
ind = 1 #raw data for better understanding

json_data = json.loads(challenge_input) #challenge_input is the json above sent in the lab

biggest_length = 0 #will store the biggest length of the list of a value in the JSON

for key, value in json_data.items():
    if type(value) == list: # check if the value of the key is a list
        list_length = len(value) # store the length
        if list_length > biggest_length: # check if the list is bigger than the existent biggest list
            biggest_length=list_length # store the biggest list length
            list_value = value # store the value from the json into a variable
            list_key = key # stoer the value of the key from the json into a variable

result=list_key + "-" + list_value[ind] #output

# {} =
send_data_to_server(client_socket, result) #send the result to the server to validate the lab

Here's the output of my code :
Your answer was on time but incorrect: - Your answer was "potlatching-tupaia", the expected answer was "potlatching-"tupaia""

My first idea was that my JSON value was maybe parsed to a string or given a bad format. I've tried to "bypass" this, by manually adding --> ". As you would expect, didn't work. :
result=f'"{list_key}-"{res[ind]}""'

Output:
Your answer was on time but incorrect: - Your answer was "ultralegality-"reservoired"", the expected answer was "ultralegality-"reservoired""

As you see, bypassing doesn't work.
I don't know what's wrong. Is it the way I retrieve the data in the JSON, which leads it to being in another format ? (like string format?) Is is the way that I display my data ? The Lab seems to check the data and the type, but I don't know any more solutions. I've tried almost every way of display the data (str(), f"{}", ...)
Answer: Try f'{list_key}-{json.dumps(res[ind])}'. This should handle the data types as expected, wrapping strings in quotation marks but not ints, and handling arbitrary elements like lists or dicts.
Comment: Working perfectly, thanks a lot


Piano practice log : are "categories" important?

Question: I just started logging my practice activities in a journal. My main purpose is to keep my mind dedicated in order to make the best use of my time.
I wonder whether/which categories are important : today I practiced sight reading for 15 minutes and a piece for 30 minutes. I started logging this, but working the piece meant mainly working on polyrythm, so I wonder whether I should count it as "piece" or "technique/rythm".
For those who keep a journal, do you use categories? Which are they? Should the "technique" category used only for "out of context" work? Does it really matter, after all?
Thanks.
Answer: Categories are important, but they should allow for flexibility.  If you are filling out the same forms every day, it will quickly become monotonous and you won't continue with it.  Everyone does journals differently - some people only write the bare essentials while other people like to / need to verbalize their thoughts with paragraphs.
It's a good idea to frame out parts of your practice session - sight-reading, technique, repertoire, and improvisation.  But really, there are two basic parts to your journal (if you include nothing else): what you worked on that day and what you want to work on next time.
It's important to include goals for the next practice session so that you have a plan of attack.
Honestly, I wouldn't worry about the semantics of how you label things - the practice journal is for you to organize your goals, so as long as you understand what's going on, that's all that really matters.


Dependency injection to load node data

Question: When I checked the code I wrote with phpcs --standard=DrupalPractice /path/to/myController, I got the following warning.

WARNING | Node::load calls should be avoided in classes, use dependency injection instead.

The code I use to load the node is the following.
use Drupal\node\Entity\Node;

public function content_load($node = NULL) {
 $noad_data = Node::load($node, NULL, TRUE);
}

How should I use dependency injection to load a node?
Answer: The controller base class provides the method entityTypeManager() which gets the service with the same name from the container the first time you use it. You can use this service to get the node storage:
  $node_storage = $this->entityTypeManager()->getStorage('node');

and then load the node:
  $node = $node_storage->load($nid);

Comment: No, not if you use the utility base class for thin controllers [ControllerBase](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Controller%21ControllerBase.php/class/ControllerBase/8.7.x). This class exists so that the average user doesn't need to write that ugly pair of factory method and constructor, which you can avoid also by simply putting the controller method in a normal service and inject via container arguments.
Comment: @FreeRadical, the answer begins with *The controller base class provides ...*, which in Drupal 10 still provides this method.
Comment: Shouldn't this be `$node_storage = $this->entityTypeManager->getStorage('node');`? Without the parenthesis after `entityTypeManager`?
Comment: @leymannx, and 4k4 I was just going insane why my code was not working in form, which was working in controller thanks for the clarification .
Comment: I can't get this accepted answer to work with Drupal 10. I've posted a [new question](https://drupal.stackexchange.com/q/315798/12076) about how to do this with Drupal 10.
Comment: @4uk4 Yes, and I am trying to use this code in a controller class. What is missing from the accepted answer is how to make the entityTypeManager service available (i.e. not  NULL) inside my class. This does not happen by default - something more has to be added to make this happen.
Comment: @FreeRadical, my answer is not trying to replace the official docs. Start with the controller example from here https://www.drupal.org/docs/drupal-apis/routing-system/introductory-drupal-routes-and-controllers-example#s-building-a-page-controller
Answer: This is how I injected the entity type manager to load nodes into a block (where the nodes to load didn't come from the block context):
<?php

namespace Drupal\MYMODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Provides a 'My Block' Block.
 *
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new MyBlock.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $node_storage = $this->entityTypeManager->getStorage('node');

    $node = $node_storage->load(1);

    return [
      '#markup' => $node->getTitle(),
    ];
  }

}

Comment: While the context is slightly different, the answer still shows how to load an entity using dependency injection without using a static method of a class. This answer is not about block context. I take it as saying _I would do it in the same way I would do it in a block plugin._
Comment: @ssibal – Normally, in a block, you can simply get the current node from the block context. In my case, I got some entity IDs from a database query, and then needed to load them. No context. That's why I called in entityTypeManager. `->load(1)` is a placeholder. How you get your entity IDs depends on your own logic. I just extended the accepted answer to have a fully working code snippet. How would you have solved that challenge? What's your fully working code answer to the asked question?
Comment: I don't really see how it's relevant to the original question:
- why context should provide nodes? And what does it have to do that you then loaded node id:1?
- Mentioning ContainerFactoryPluginInterface in general has nothing to do that you should always use storage injection loading entities. It's a different topic.

Dependency injection to load node data


Notation $2^T$ for the operator T of the Hilbert space

Question: I came across an unknown to me notation $2^T, 2^{-T}$ for a positive operator $T$ on a Hilbert space (more precisely, in $\mathbb{C}^n$).
What does this mean? I can't find it anywhere. Is it the image and the kernel?
Comment: Might $2^T$ just mean $\exp(\log(2) T) = \sum_{n \geq 0} \frac{\log(2)^n}{n!} T^n$?
Comment: It would help if you gave the source. diracdeltafunk's suggestion is my first guess but it seems like a very bizarre thing to write down so I don't know.
Comment: It is not a standard notation for an operator.
Comment: Unfortunately, there is no source. It was in the task next to the calculation of the norm and square root and finding the spectral decomposition, so you may be right. Thank you!
Comment: You have to read spectral theory to find out how to define functions of an operator.
Answer: For a positive (more generally, normal) operator $T$ on a Hilbert space $H$, there is a unique unital *-homomorphism (a linear map that preserves products and involutions) from $C(\sigma(T))$ to $B(H)$ that maps $\operatorname{id}$ to $T$, where $\operatorname{id}$ is the map $C(\sigma(T))\to \mathbb{C}, z\mapsto z$.
For a continuous function $f$ on the spectrum $\sigma(T)$ of $T$, $f(T)$ means the image of $f$ under the unique *-homomorphism.
For example, let $p(x)=x^2+2x+1$,  you can check $p(T)=T^2+2T+e$ where $e$ is the  identity of $B(H)$.
For $f(x)=2^x$, it can be approximated by polynomials $p_N(x)=\sum_{n=0}^N\frac{(\ln 2)^n}{n!}x^n$ with respect to the uniform norm. $f(T)$ can be proved to be the limit of $p_N(T)$.
Answer: Since $T$ is a positive operator, it is a normal operator and we can consider the continuous functional calculus
$$C(\sigma(T)) \to  B(\mathbb{C}^n) \cong M_n(\mathbb{C})$$
Then $2^T$ is the operator obtained as the image of $\sigma(T)\ni x \mapsto 2^x$ under the above map.
In some sense, it is unnatural to consider the operator $2^T$ since $\sigma(T)$ is a finite space, but I think it suffices for your purposes.


Integrating with considering two indicator function

Question: Consider exponential random variables $X$, $Y$, and $Z$ with $\lambda_x$, $\lambda_y$, and $\lambda_z$, respectively. Now I want to calculate the following integration:
$$E[X1_{\{X<Y\}}1_{\{X<Z\}}]=\int_{0}^{\infty}X1_{\{X<Y\}}1_{\{X<Z\}}f_X(x)=?$$
any hint, please
I know that there is a very simple solution for this expectation, but I want to calculate such integration.
Comment: The expectation is incorrectly expressed.  The expectation is a *triple* integral, $$E\left[X1_{X\lt Y}1_{X\lt Z}\right] = \int_0^\infty \int_0^\infty \int_0^\infty x 1_{x\lt y} 1_{x \lt z} f_{X,Y,Z}(x,y,z)\,\mathrm{d}x\mathrm{d}y\mathrm{d}z.$$ You can easily evaluate it by assuming $X,Y,Z$ are *independent.*
Comment: Notice that $\mathbb{I}_{X<Y}\mathbb{I}_{X<Z}$ is non zero if $X<min(Z,Y)$
Comment: Thanks, I actually know this, but I want to solve this directly by specifying integral intervals.
Comment: @whuber, Thanks, can you explain to me in more detail? If it is in the form of an answer, I would be very grateful.
Answer: To continue Whubers answer, based on independence assumption between the random variables $X, Y, Z$.
$$\mathbb{E}[X\mathbb{I}_{X<Y}\mathbb{I}_{X<Z}] = \int_{0}^{\infty}\int_{0}^{\infty}\int_{0}^{\infty}x \mathbb{I}_{x<y} \mathbb{I}_{x<z}f_{X}(x)f_{Y}(y)f_{Z}(z)dzdydx$$
$$=\int_{0}^{\infty}\int_{0}^{\infty}x\mathbb{I}_{x<y}f_{X}(x)f_{Y}(y)\int_{x}^{\infty}f_{Z}(z)dz \ dydx$$
For exponential distributions with parameter $\lambda_{z}$ it holds that $F(Z>x) = \int_{x}^{\infty}f_{Z}(z)dz = e^{-\lambda_{z}x}$
$$=\int_{0}^{\infty}\int_{0}^{\infty}x\mathbb{I}_{x<y}f_{X}(x)f_{Y}(y) e^{-\lambda_{z}x} \ dydx$$
$$= \int_{0}^{\infty}xe^{-\lambda_{z}x}f_{X}(x) \int_{x}^{\infty}f_{Y}(y)dy \ dx$$
$$ = \int_{0}^{\infty}xe^{-(\lambda_{z}+\lambda_{y})x} f_{X}(x)dx$$
Now using Integration by parts we have
$$= -\frac{\lambda_{x}}{\lambda_{z}+\lambda_{y}+\lambda_{x}}\int_{0}^{\infty}x(e^{-(\lambda_{z}+\lambda_{y}+\lambda_{x})x})^{'}dx = -\frac{\lambda_{x}}{\lambda_{z}+\lambda_{y}+\lambda_{x}} (0 - \int_{0}^{\infty}e^{-(\lambda_{z}+\lambda_{y}+\lambda_{x})x}dx ) = \frac{\lambda_{x}}{(\lambda_{z}+\lambda_{y}+\lambda_{x})^{2}}$$
Comment: Yes: the result looks like it must be related to the distribution of $\min(X,Y,Z).$  That distribution is easy to work out.  Compare the answer to yours--or better, compare it to what you obtain upon permuting the roles of $X,$ $Y,$ and $Z.$ That will bring to your attention the perhaps not so obvious relation $$\min(X,Y,Z) = X1_{X\lt Y}1_{X\lt Z}+Y1_{Y\lt Z1}1_{Y\lt X}+Z1_{Z\lt X}1_{Z\lt X}.$$ Then, remembering the relationship between Poisson processes and exponential random variables, ponder the illustrations I posted at https://stats.stackexchange.com/a/429589/919 for intuition.
Comment: Yes, this is one way to do it.  However, you lost $\lambda_x$ near the end of your calculations and the integration was incorrectly performed.  This is easy to see without any calculation: since you have taken the $\lambda_{*}$ to be rates, the result should be inversely proportional to them--but not inversely proportional to their squares.
Comment: @whuber ooops I'll correct it right away!
Comment: @whuber Does the square on the denominator should disappear because based on my calculations it doesnt?
Comment: Yes, now it looks good.  Notice that your new answer includes $\lambda_x$ and is inversely proportional to it.
Comment: @whuber Is it possible to intuitively interpret this result?? The expected value of $X$ when it is less from both $Y$ and $Z$ ?
Comment: Interesting point! Also, the results of the integral is like $\frac{Var(min(X,Y,Z))}{\mathbb{E}[X]}$ restricting that $X$ has to be the minimum. Then I assume restricting that any of the other two random variables is the minimum we would have $\frac{Var(min(X,Y,Z))}{\mathbb{E}[Y]}$, $\frac{Var(min(X,Y,Z))}{\mathbb{E}[Z]}$ respectively
Comment: Thanks a lot for your clear answer


Countable product of $\mathbb{R}$ is not connected with respect to box topology

Question: From the book Topology, by James Munkres, I am trying to understand that $\mathbb{R}^\omega$ is not connected with respect to box topology. It is written that,
We can write $\mathbb{R}^\omega$ as the union of the set $A$ consisting of all bounded sequences of real numbers, and the set $B$ of all unbounded sequences. These sets are disjoint, and each is open in the box topology. For if $a$ is a point of $\mathbb{R}^\omega,$ the open set
$$U=(a_1-1,a_1+1)\times (a_2-1,a_2+1)\times...$$
consists entirely of bounded sequences if $a$ is bounded, and of unbounded sequences if $a$ is unbounded....
I do not realise that, how the open set
$$U=(a_1-1,a_1+1)\times (a_2-1,a_2+1)\times...$$ can contain all the bounded sequences of $\mathbb{R}?$ If I choose $a=(1,\frac{1}{2},\frac{1}{3},...) \in \mathbb{R}^\omega,$ then $a$ is a bounded sequence of $\mathbb{R}$. Therefore,
$$U=(1-1,1+1)\times (\frac{1}{2}-1,\frac{1}{2}+1)\times...,$$
which implies that,
$$U=(0,2)\times (-\frac{1}{2},\frac{3}{2})\times...,$$
Now, if I consider the bounded sequence $b=(5,5,...)\in \mathbb{R}^\omega,$ then how $b$ can be contained in $U?$
Surely I am missing something, please help me to figure out the concept.
Thanks in advance.
Comment: The set $U$ for a particular sequence $a$ will not contain *all* bounded sequences nor all the unbounded sequences either. But, it is a neighborhood of $a$ which is completely contained in one of the two sets of sequences (the bounded sequences or the unbounded sequences). This shows that both sets that make up the separation are open.
Comment: Thank you. Now it's clear.
Comment: @shoteyes Should probably convert that to an answer so the OP can accept it
Comment: @Alan I did something like that earlier today.
Answer: The set $U$ only contains bounded sequences if $(a_n)$ is bounded, so is a subset of $A$, and that's all you need because it shows that any bounded sequence is an interior point of $A$. We don't need it to contain all bounded sequences: just an open set around $(a_n)$ inside $A$.
The same holds for $B$: if $(a_n)$ is unbounded, the defined $U$ also contains only unbounded sequences as well, so $U \subseteq B$ and the sequence is an interior point of $B$.
So $A$ and $B$ only have interior points so both are open, and as $A \cup B = \Bbb R^\omega$, both are closed too, and we have a disconnection.
Comment: Thank you for the explanation.
Comment: @user490489 you're welcome.


file_managed not working when i try to save permanently

Question: First of all, i want to say that i tried everything, i have coded since 10:30 am and i cannot get the solution, i looked in forums, combined code and many other things and nothing seems to work. What i want to achieve is to save permanently an uploaded image to a carrousel but in one minute (default is six hours but i changed it) the image dissapear. I would appreciate any help you can do.
This is the code.
function participacionciudadana_form_system_theme_settings_alter(&$form, &$form_state) {
  $form['participacionciudadana_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('participacionciudadana Theme Settings'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['show_front_content'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show content and sidebar on front page'),
    '#default_value' => theme_get_setting('show_front_content','participacionciudadana'),
    '#description' => t('Check this option to show content and sidebar on the front page.'),
  );
  $form['participacionciudadana_settings']['breadcrumbs'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show breadcrumbs in a page'),
    '#default_value' => theme_get_setting('breadcrumbs','participacionciudadana'),
    '#description'   => t("Check this option to show breadcrumbs in page. Uncheck to hide."),
  );
  $form['participacionciudadana_settings']['slideshow'] = array(
    '#type' => 'fieldset',
    '#title' => t('Front Page Slideshow'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['slideshow']['slideshow_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show slideshow'),
    '#default_value' => theme_get_setting('slideshow_display','participacionciudadana'),
    '#description'   => t("Check this option to show Slideshow in front page. Uncheck to hide."),
  );
    $form['participacionciudadana_settings']['slideshow']['slide'] = array(
    '#markup' => t('You can change the description and URL of each slide in the following Slide Setting fieldsets.'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 1'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide1']['slide1_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide1_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide1']['slide1_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide1_url'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

  $form['participacionciudadana_settings']['slideshow']['slide2'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 2'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide2']['slide2_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide2_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide2']['slide2_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide2_url'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

  $form['participacionciudadana_settings']['slideshow']['slide3'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 3'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide3']['slide3_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide3_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide3']['slide3_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide3_url','participacionciudadana'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

    $form['participacionciudadana_settings']['slideshow']['slideimage'] = array(
    '#markup' => t('Los nombres tienen que ser foto1, foto2 y foto3 sino no funcionará. Las medidas tienen que ser 930 x 320'),
  );
  $form['participacionciudadana_settings']['footer'] = array(
    '#type' => 'fieldset',
    '#title' => t('Footer'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['footer']['footer_copyright'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show copyright text in footer'),
    '#default_value' => theme_get_setting('footer_copyright','participacionciudadana'),
    '#description'   => t("Check this option to show copyright text in footer. Uncheck to hide."),
  );
  $form['participacionciudadana_settings']['footer']['footer_credits'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show theme credits in footer'),
    '#default_value' => theme_get_setting('footer_credits','participacionciudadana'),
    '#description'   => t("Check this option to show copyright text in footer. Uncheck to hide."),
  );

$form['#submit'][] = 'participacionciudadana_form_system_theme_settings_submit';

}

function participacionciudadana_form_system_theme_settings_submit(&$form, &$form_state) {
      $image_fid = $form_state['values']['slide3_url'];
      $image = file_load($image_fid);
      if (is_object($image)) {
      // Check to make sure that the file is set to be permanent.
      if ($image->status == 0) {
      // Update the status.
      $image->status = FILE_STATUS_PERMANENT;
      // Save the update.
      file_save($image);
      // Add a reference to prevent warnings.
      file_usage_add($image, 'participacionciudadana', 'slide3_url', 1);
     }
  }
}

Answer: Your code is specifically deleting the file after it has been uploaded.
A good example to follow is the image example. Check out the form and submit functions of that.
You start of the same where you load the image, set it to permanent and then save it, although maybe
    if ($image->status != FILE_STATUS_PERMANENT) {

would be better than
    if ($image->status == 0) {

Then you add file usage, which is also good.
But then you remove the file usage and delete the file.
I'm not sure why seeing as that kind of defeats the purpose of uploading it in the first place.
I would say that is your problem. Try not deleting it.
Edit:
Oh I see another issue.
Your use of
$image_fid = $form_state['slideshow']['slide3']['slide3_url'];

seems wrong.
If you interrogate the $form_state array and reference with the image example you can see there is a $form_state['values'], which is where you should be getting your image fid from.
It probably should be this:
   $image_fid = $form_state['values']['slide3_url'];

Comment: Thank you for you reply, i have made all the changes you posted but the problem persist. I don't know what is causing this yet.
Comment: I added some more info.
Comment: I noticed that i put the function submit inside the alter function, i put the two functions separate but it's not working either...


How do we Get keyboard idle time in delphi

Question: The following code can get the system idle time.
<code>function IdleTime: DWord;
var
  LastInput: TLastInputInfo;
begin
  LastInput.cbSize := SizeOf(TLastInputInfo);
  GetLastInputInfo(LastInput);
  Result := (GetTickCount - LastInput.dwTime) DIV 1000;
end;
</code>
Is it possible to get keyboard idle time alone? Let the user move his/her mouse-it doesn't matter. Is it possible to determine, how long the keyboard has been idle?
Comment: Create a keyboard hook and keep your own timer going
Comment: The OS does not provide the info you are looking for, so you have to hook the keyboard manually.
Comment: Maybe the [CallNtPowerInformation()](http://msdn.microsoft.com/en-us/library/aa372675%28VS.85%29.aspx) can be of any help?
Comment: Keyboard hook sounds like a key-logger. So i prefer to go with some other alternatives!
Comment: Well same concept no matter what it's being used for.
Answer: You have to hook to Keyboard event. Check the Keyboard or mouse hooking in Delphi at
http://delphi.about.com/od/kbwinshell/a/delphi_hook.htm
and
http://delphi.about.com/od/windowsshellapi/a/delphi-hooks.htm
You can build your logic over this.


Bash script to configure IPTABLES

Question: I am beginner at BASH scripting, I'm trying to write script to configure iptables but it seems something wrong in the first block, Please advise
#!/bin/bash
echo "IPTABLE ASSIGNMEN"
echo -e "1.Reject all except one IP\n2.Flush iptables (*Use Carefully_it will remove all the rules from iptables*)\n"
echo -e "Select Number"
read number;
if [[$number == "1"]]; then
        echo "Insert IP\n"
        read ip;
        iptables -A INPUT -s $ip -j ACCEPT
        iptables -A OUTPUT -d $ip -j ACCEPT
        iptables -P INPUT DROP
        iptables -P OUTPUT DROP
fi

Comment: the iptables.service now can save settings, on CentOS it is saved on `/etc/sysconfig/iptables`. Every time you return `systemctl restart iptables` it will go there to load all the settings.
Answer: Your equality test is incorrect
if [ $number == "1" ]; then

You need single square braces with spaces around them.
Double square braces do something a bit different.
Also ...
Get into the habit of using single quotes wherever you can.
Linux applies expansion rules to literals in double quotes.
ip=127.0.0.1

echo '$ip'
$ip

echo "$ip"
127.0.0.1

If you don't want/need this, use single quotes to make this clear.
Since you're probably going to add more options, look into the case statement.
case $number in
'1' :
  ;;
'2' :
  ;;
esac

Comment: Actually, `[` is an external command (`test`), and `[[` is a `bash` builtin. It can be used for testing conditions, and does not require calling an external program, so it is (in my opinion) a better choice. Also, `case` patterns need to be terminated with `)`, not `:`.
Comment: Thank you Phill for your clarification, and thank you Lacek for your suggestion, I used case statement and its working well.
Answer: Thank you all for your support, Actually as you mentioned, I used case statement, also due to the error $'\r': command not found , which caused by editor style, I used "dos2unix filename.sh" to solve it and run the script "sudo bash filename.sh" which worked properly.
!/bin/bash
echo "IPTABLE ASSIGNMEN"
echo -e "1.Reject all except one IP\n2.Flush iptables (*Use Carefully_>
echo -e "Select Number\n"
read x;
case  $x in
        "1" )
        echo "Insert IP\n"
        read ip;
        iptables -A INPUT -s $ip -j ACCEPT
        iptables -A OUTPUT -d $ip -j ACCEPT
        iptables -P INPUT DROP
        iptables -P OUTPUT DROP
                ;;
        "2" )
                iptables -F
                iptables -X
                iptables -P INPUT ACCEPT
                iptables -P FORWARD ACCEPT
                iptables -P OUTPUT ACCEPT
                ;;
        * )
        echo "Try Again"
                ;;
esac

Bash script to configure IPTABLES


How to generate these two reports with MySQL?

Question: My Schema
I have the following tables
table             notes/example values
------------------------------------------------
users (
  id
  email           # "firstname.lastname@example.com"
)

games (
  id
  name            # "Space Invaders", "Asteroids", "Centipede"
)

players (
  id
  name            # "uber dude"
  user_id         # player belongs to user
  game_id         # player belongs to game
)

scores (
  id
  player_id       # belongs to one player
  value           # 50
  created_at      # "2010-09-10",   "2010-08-05"
  month           # "2010-09",      "2010-08"
)

I need to create two reports.
1) Top players
Best performing players (sum all scores for each player) for the most recent
4 months. Show top 10 for each month.
    2010-07         2010-08           2010-09    2010-10
 1  plyA 5,000 pts  plyB  9,400 pts   ...        ...
    Centipede       Solitaire

 2  plyB 3,600 pts  plyC  8,200 pts   ...        ...
    Asteroids       Centipede

 3  plyC 2,900 pts  plyA  7,000 pts   ...        ...
    Centipede       Centipede

 4  ...             ...               ...        ...
 5  ...             ...               ...        ...
 6  ...             ...               ...        ...
 7  ...             ...               ...        ...
 8  ...             ...               ...        ...
 9  ...             ...               ...        ...
10  ...             ...               ...        ...

2) Top Users:
Best performing users (sum all scores for each players for each user) for the
most recent 4 months. Show top 10 for each month.
    2010-07           2010-08             2010-09    2010-10
 1  userA 50,000 pts  userB 51,400 pts    ...        ...
 2  userB 40,500 pts  userA 39,300 pts    ...        ...
 3  userC 40,200 pts  userC 37,000 pts    ...        ...
 4  ...               ...                 ...        ...
 5  ...               ...                 ...        ...
 6  ...               ...                 ...        ...
 7  ...               ...                 ...        ...
 8  ...               ...                 ...        ...
 9  ...               ...                 ...        ...
10  ...               ...                 ...        ...

MySQL View helper
For joining purposes, I have a stored view to help query the months for the reports. It will always return the most recent 4 months.
report_months (
  month
)

SELECT * FROM report_months;

2010-07
2010-08
2010-09
2010-10

The Problem
In report #1, for example, I can get the sums pretty easily.
select
  p.name        as player_name,
  g.name        as game_name,
  s.month       as month,
  sum(s.score)  as sum_score

from players  as p

join games    as g
  on g.id = p.game_id

join scores   as s
  on s.player_id = p.id

join report_months as rm  -- handy view helper
  on rm.month = s.month

group by
  p.name, g.name

order by
  sum(s.score) desc

-- I can't do this :(
-- limit 0, 40

However, I can't simply fetch the top 40 results and spread them across 4 months as this wouldn't guarantee me 10 for each month.
The Question
How can I modify my query to ensure that I'd get 10 for each month?
Comment: A query for each month and union them.
Answer: I wouldn't try to make an SQL query that tabulates by month as you have shown.
Instead, query the top 10 players per month as rows, not as columns:
Month    Rank  Player  TotalScore  Game
2010-07     1    plyA   5,000 pts  Centipede
2010-07     2    plyB   3,600 pts  Asteroids
2010-07     3    plyC   2,900 pts  Centipede
...
2010-08     1    plyB   9,400 pts  Solitaire
2010-08     2    plyC   8,200 pts  Centipede
2010-08     3    plyA   7,000 pts  Centipede
...

This becomes a greatest-n-per-group problem, where n is 10.
CREATE VIEW PlayerScoresByMonth AS
  SELECT month, player_id, SUM(value) AS score
  FROM scores
  GROUP BY month, player_id;

SELECT s1.month, COUNT(s2.month)+1 AS Rank, s1.player_id, s1.score AS TotalScore
FROM PlayerScoresByMonth s1
LEFT OUTER JOIN PlayerScoresByMonth s2 ON s1.month = s2.month
  AND (s1.score < s2.score OR s1.score = s2.score AND s1.player_id < s2.player_id)
GROUP BY s1.month, s1.player_id
HAVING COUNT(*) < 10
ORDER BY s1.month, Rank;

(that's untested but should get you started)
Then you need to write some application code to fetch the results of this query and separate the lists by month, and present the data however you were going to do that.
Comment: @Bill Karwin, this is incredible. It is exactly what I was looking for. Thank you so much :)
Comment: **note:** In the view, I added `JOIN report_months AS rm ON rm.month = scores.month` to limit the rows returned in the view.
Comment: Great, I'm glad I could help.  And that join to report_months is a fine thing to do.
Comment: @Bill Karwin, do MySQL views use indexes? If I were to cache the `PlayerScoresByMonth` in a table instead of a view, what indexes would I want to add to speed up the `LEFT OUTER JOIN` you're using?
Comment: You can't create an index on a view, but the view gets translated into a query against the base table(s), so it makes use of an applicable index on the base table.  See http://dev.mysql.com/doc/refman/5.1/en/view-restrictions.html
Comment: @Bill Karwin, very awesome; I did not know that. What indexes should I have on my `scores` table to make this the most efficient?
Comment: First I'd try a composite index over `(month, score, player_id)` but as I say in the slides, be sure to use EXPLAIN and profiling to make sure any index is being used.


LLVM Insert function call into another function

Question: I am trying to insert function call inside a main function, so then when i run generated binary file, function will be executed automatically. Since language i am trying to "compile" looks like a "scripted" language  :
function foo () begin 3 end;
function boo () begin 4 end;

writeln (foo()+boo()) ;
writeln (8) ;
writeln (9) ;

where writeln is a function available by default, and after executing binary i expect to see 7 8 9. Is there a way to insert last function call right before return statement of a main function ?
Right now I have
define i32 @main() {
entry:
  ret i32 0
}

and i want to have something like
define i32 @main() {
entry:
  %calltmp = call double @writeln(double 7.000000e+00)
  %calltmp = call double @writeln(double 8.000000e+00)
  %calltmp = call double @writeln(double 9.000000e+00)
  ret i32 0
}

editing IR file manually and compile it afterwards works, but i want to do it in codegen part of my code.
edit
what i generate right now is
define double @__anon_expr() {
entry:
  %main = call double @writeln(double 3.000000e+00)
  ret double %main
}

define i32 @main() {
entry:
  ret i32 0
}

so when i execute binary - nothing happens
Comment: How is this related to `c++`?
Comment: @super I am writing frontend of llvm in c++
Comment: It's not quite clear what you're trying to do. If it is the IR you're generating anyway, you can do whatever you like. If you want to modify some existing IR - that's probably not what you should be doing. If you still insist, then just write a function pass and run it with `opt`.
Comment: @SK-logic I am generating IR, but i don't know how to add function calls inside a main function. Right now the look like this
```
define double @__anon_expr() {
entry:
  %main = call double @writeln(double 3.000000e+00)
  ret double %main
}
define i32 @main() {
entry:
  ret i32 0
}
```
so nothing is executed
Answer: feel free to source your inspiration from here
Type * returnType = Type::getInt32Ty(TheContext);
std::vector<Type *> argTypes;
FunctionType * functionType = FunctionType::get(returnType, argTypes, false);
Function * function = Function::Create(functionType, Function::ExternalLinkage, "main", TheModule.get());

    BasicBlock * BB = BasicBlock::Create(TheContext, "entry", function);
    Builder.SetInsertPoint(BB);
    vector<Value *> args;
    args.push_back(ConstantFP::get(TheContext, APFloat(4.0)));
    Builder.CreateCall(getFunction("writeln"), args, "call");
    Value * returnValue = Builder.getInt32(0);
    Builder.CreateRet(returnValue);


Ajuda com organização de função

Question: Estou desenvolvendo uma calculadora IP, e agora preciso achar o primeiro IP válido da rede original digitada. Eu separei meu código em funções, o que acho que ao em vez de ajudar, atrapalhou. Meu problema é o seguinte: Eu tenho uma função que exibe máscara e nessa função eu tenho os octetos digitados e separados (cada octeto é uma string). Eu tenho uma função que calcula o ID da rede, porém, essa função é chamada fora das funções, pois preciso passar por parâmetro a máscara e o endereço ip. A função que exibe a máscara retorna a máscara e a função que exibe o endereço retorna o endereço, então pego esses valores em duas variáveis e passo quando chamo a função ID. Agora, pra calcular o primeiro IP válido, eu preciso do último octeto (está na função máscara), mas também preciso dos parâmetros máscara e endereço, pois o primeiro IP válido é o endereço de ID + 1 (somando isso no último octeto). O problema está na hora de pegar esses valores, uma vez que os octetos estão na função máscara.
Minha função máscara
       function exibe_mascara() { //função pra exibir informações da máscara original da rede
        $mascara_bin = array("", "", "", ""); //array pra máscara em binário
        $conta_octeto = 0; //variável para contar os octetos da máscara
        $conta_bit = 0; // variável pra contar os bits da máscara
        $stringMascaraBin = null; //inicializa a variavel de string da mascara binario

        if ($_POST["mascara"] >= 8 && $_POST["mascara"] <= 30 || valida_mascara_decimal()) { //condição pra validar o que o cara digitou
            if ($_POST["mascara"] >= 8 && $_POST["mascara"] <= 30) { //condição p testar se a máscara está em notação CIDR
                for ($j = 0; $j < $_POST["mascara"]; $j++) { //laço para acrescentar "1" na máscara de acordo com a máscara CIDR
                    $mascara_bin[$conta_octeto] = $mascara_bin[$conta_octeto] . "1";
                    $conta_bit++;
                    if ($conta_bit == 8 || $conta_bit == 16 || $conta_bit == 24) {//condição pra incrementar o octeto
                        $conta_octeto++;
                    }
                }

                $limite = 32 - $_POST["mascara"]; //conta pra saber quantos bits sobraram pra host
                for ($i = 0; $i < $limite; $i++) { //laço para acrescentar os bits de host, os zero's.
                    $mascara_bin[$conta_octeto] = $mascara_bin[$conta_octeto] . "0";
                    $conta_bit++;
                    if ($conta_bit == 8 || $conta_bit == 16 || $conta_bit == 24) {//condição pra incrementar o octeto
                        $conta_octeto++;
                    }
                }
                echo"
";
                echo"Máscara em binário:  ";

                for ($i = 0; $i < count($mascara_bin); $i++) {//exibir a máscara em binário
                    echo $mascara_bin[$i];
                }

                echo"
";
                echo"Máscara em notação CIDR:  /" . $_POST["mascara"] . "
";
                echo"Máscara em decimal:  ";
                $mascara_decimal = array("", "", "", ""); //array pra máscara em decimal
                for ($i = 0; $i < 4; $i++) {//laço pra exibir a máscara em decimal
                    echo bindec($mascara_bin[$i]);
                    $mascara_decimal[$i] = bindec($mascara_bin[$i]);
                    if ($i < 3) {
                        echo".";
                    }
                }
                //separa os octetos em arrays
                $octeto1 = str_split($mascara_bin[0]);
                $octeto2 = str_split($mascara_bin[1]);
                $octeto3 = str_split($mascara_bin[2]);
                $octeto4 = str_split($mascara_bin[3]);

                //chamada da função wildcard
                echo "
 Wildcard binário:  ";
                $octeto1_wil = wildcard($octeto1);
                echo ".";
                $octeto2_wil = wildcard($octeto2);
                echo ".";
                $octeto3_wil = wildcard($octeto3);
                echo ".";
                $octeto4_wil = wildcard($octeto4);
                echo "
";

                //inicializando as strings para os octetos
                $stringArrayF1 = null;
                $stringArrayF2 = null;
                $stringArrayF3 = null;
                $stringArrayF4 = null;

                //transformando os arrays de octetos wildcard em strings
                foreach ($octeto1_wil as $stringArray1) {
                    $stringArrayF1 = $stringArrayF1 . $stringArray1;
                }

                foreach ($octeto2_wil as $stringArray2) {
                    $stringArrayF2 = $stringArrayF2 . $stringArray2;
                }

                foreach ($octeto3_wil as $stringArray3) {
                    $stringArrayF3 = $stringArrayF3 . $stringArray3;
                }

                foreach ($octeto4_wil as $stringArray4) {
                    $stringArrayF4 = $stringArrayF4 . $stringArray4;
                }

                $aux = 0; //variável pra mudar a posição do vetor endereço
                $endereco_ip = explode(".", $_POST["endereco"]); //tirar os pontos do endereço digitado
                echo "Endereço de Broadcast:  ";
                //chamada da função de broadcast
                broadcast($stringArrayF1, $endereco_ip, $aux);
                $aux++;
                broadcast($stringArrayF2, $endereco_ip, $aux);
                $aux++;
                broadcast($stringArrayF3, $endereco_ip, $aux);
                $aux++;
                $ultimo_octeto = broadcast($stringArrayF4, $endereco_ip, $aux); //armazena o ultimo octeto de broadcast numa variavel

                echo "
Último IP válido:  ";
                $aux = 0;

                //chamada da função de ultimo ip valido
                UltimoIpValido($stringArrayF1, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF2, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF3, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF4, $endereco_ip, $aux, $ultimo_octeto);

                foreach ($mascara_bin as $stringMascara) { //transforma em string o array de mascara binario
                    $stringMascaraBin = $stringMascaraBin . $stringMascara;
                }

                return $stringMascaraBin; //retorna a string da mascara em binario
            }

            if (valida_mascara_decimal()) { //chama a função de validar pra saber se está no formato correto
                $mascara_decimal = array("", "", "", ""); //array pra mascara em decimal
                $mascara_decimal = explode(".", $_POST["mascara"]); //adicionando a máscara digitada ao array de mascara decimal sem os pontos
                $mascara_binario = array("", "", "", ""); //cria array pra mascara em binario
                echo "Máscara em decimal: ";
                echo $_POST["mascara"] . "
"; //exibe a mascara em decimal
                echo "Máscara em binário: ";
                for ($i = 0; $i < 4; $i++) {//laço pra transformar de decimal pra binario e armazenar no array mascara binario
                    $mascara_binario[$i] = str_pad(decbin($mascara_decimal[$i]), 8, "0", STR_PAD_LEFT); //transforma a posição i da mascara em decimal em binario e armazena na posição i da mascara em binário e adiciona 0 a esquerda caso o numero em binario n tenha preenchido  bits
                    if ($i < 4 && $i > 0) {
                        echo"."; //coloca os pontos nos octetos
                    }
                    echo $mascara_binario[$i]; //exibe a mascara binario
                }

                //separa os octetos em arrays
                $octeto1 = str_split($mascara_binario[0]);
                $octeto2 = str_split($mascara_binario[1]);
                $octeto3 = str_split($mascara_binario[2]);
                $octeto4 = str_split($mascara_binario[3]);

                //chama função pra saber quais bits estão setados
                $bit_setado_octeto1 = verificarBit($octeto1);
                $bit_setado_octeto2 = verificarBit($octeto2);
                $bit_setado_octeto3 = verificarBit($octeto3);
                $bit_setado_octeto4 = verificarBit($octeto4);

                //chama a função wildcard e adiciona o retorno numa variável
                echo "
 Wildcard binário:  ";
                $octeto1_wil = wildcard($octeto1);
                echo ".";
                $octeto2_wil = wildcard($octeto2);
                echo ".";
                $octeto3_wil = wildcard($octeto3);
                echo ".";
                $octeto4_wil = wildcard($octeto4);

                //inicializa as strings com null
                $stringArrayF1 = null;
                $stringArrayF2 = null;
                $stringArrayF3 = null;
                $stringArrayF4 = null;

                //transforma os arrays dos octetos em strings
                foreach ($octeto1_wil as $stringArray1) {
                    $stringArrayF1 = $stringArrayF1 . $stringArray1;
                }

                foreach ($octeto2_wil as $stringArray2) {
                    $stringArrayF2 = $stringArrayF2 . $stringArray2;
                }

                foreach ($octeto3_wil as $stringArray3) {
                    $stringArrayF3 = $stringArrayF3 . $stringArray3;
                }

                foreach ($octeto4_wil as $stringArray4) {
                    $stringArrayF4 = $stringArrayF4 . $stringArray4;
                }

                echo "
";
                $aux = 0;
                $endereco_ip = explode(".", $_POST["endereco"]); //armazena na variavel endereço ip o que foi digitado pra usar na função broadcast
                echo "Endereço de Broadcast:  ";

                //chama a função broadcast passando os parâmetros pedidos
                broadcast($stringArrayF1, $endereco_ip, $aux);
                $aux++;
                broadcast($stringArrayF2, $endereco_ip, $aux);
                $aux++;
                broadcast($stringArrayF3, $endereco_ip, $aux);
                $aux++;
                $ultimo_octeto = broadcast($stringArrayF4, $endereco_ip, $aux); //armazena o último octeto em broadcast numa variavel ultimo octeto

                echo "
Último IP válido:  ";

                //chama a função de ultimo ip valido
                $aux = 0;
                UltimoIpValido($stringArrayF1, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF2, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF3, $endereco_ip, $aux, $ultimo_octeto);
                $aux++;
                UltimoIpValido($stringArrayF4, $endereco_ip, $aux, $ultimo_octeto);

                //soma a quantidade de bit setado de cada octeto pra mostrar a mascara em notação CIDR
                $cidr = $bit_setado_octeto1 + $bit_setado_octeto2 + $bit_setado_octeto3 + $bit_setado_octeto4;
                echo "
Máscara em notação CIDR:  " . $cidr;

                foreach ($mascara_binario as $stringMascara) { //transforma em string o array de mascara binario
                    $stringMascaraBin = $stringMascaraBin . $stringMascara;
                }

                return $stringMascaraBin; //retorna a string da mascara em binario
            }
        } else {
            echo "Formato de máscara inválido!";
        }
    }

A função de ID
 function id_rede_original($ip_bin, $mascara_bin) {
        echo "ID rede original em decimal:  ";
        $id_original = $ip_bin & $mascara_bin;
        $decimal_id = long2ip(bindec($id_original));
        echo $decimal_id;
        echo "
";
        echo "ID rede original em binário:  ";
        echo $id_original;
    }

e Onde eu chamo a função ID e a máscara
 if ($metodo == "POST") {
        if (isset($_POST["calcula"])) {

            if (valida_endereco()) {
                $endereco_original_binario = exibe_endereco();
                echo "
";
                ?>

                <?php
                $mascara_original_binario = exibe_mascara();
                echo"
";
                classe();
                echo"
";
                id_rede_original($endereco_original_binario, $mascara_original_binario);

Answer: Algumas dicas que podem lhe ajudar:

Observe o seu problema, e quebre a solução abstraindo de grosso modo o fluxo dos dados.

Crie uma função responsavel por tratar e adaptar para o seu sistema as variaveis passadas por GET e POSTS.
Separe a parte lógica do seu sistema.
Separe a parte de exibição do sistema.

Nota: Você pode criar 3 classes para separar melhor esses processos, ex de fluxo:
$requisicao = new prepararRequisicao();

$calculadora = new calculadora();
$calculadora->validaEndereco($requisicao);
echo json_encode($calculadora->pegarResposta());

Sempre quando notar que existe uma função complexa, abstraia para um metodo.

Ex:
if ($_POST["mascara"] >= 8 && $_POST["mascara"] <= 30) {
    // Faça alguma coisa...
}

Poderia virar:
public function checarNotacaoCIDR($mascara) {
    if ($mascara >= 8 && $mascara <= 30) {
        // Faça alguma coisa...
    }
}

Alguns programadores acreditam que repetir o mesmo código por mais de duas vezes no mesmo local é sinonimo de coisa errada. Então evite fazer isso:
$octeto1 = str_split($mascara_bin[0]);
$octeto2 = str_split($mascara_bin[1]);
$octeto3 = str_split($mascara_bin[2]);
$octeto4 = str_split($mascara_bin[3]);

$bit_setado_octeto1 = verificarBit($octeto1);
$bit_setado_octeto2 = verificarBit($octeto2);
$bit_setado_octeto3 = verificarBit($octeto3);
$bit_setado_octeto4 = verificarBit($octeto4);

Pode ser facilmente substituido por:
foreach ($mascara_bin as $key => $value) {
    $octeto[$key] = str_split($value);
    $bitSetadoOcteto = verificarBit($octeto[$key]);
}

Espero que tenha ajudado ;)

Ajuda com organização de função


jQuery, if "a" tag has class or not

Question: Im trying to get a popup open when I'm pressing a a tag with class: "disable".
This is what i have right now: When I'm clicking on "tab-link" that has class "disable" I get an alert saying "yes",
but when I'm clicking on "tab-link"  that do not have disable i still get a message saying "Yes".

$(".tab-link").click(function() {
  if ($(".tab-link").hasClass("disable")) {
    alert("Yes");
  } else if (!$(".tab-link").hasClass("disable")) {
    alert("No");
  }
});
a{
  display: block;
}

  today
  today
  today
  Home

  rocket_fill
  rocket_fill
  Games

  layers_alt_fill
  layers_alt_fill
  Todo

  download_fill
  download_fill
  Download

  search
  search
  search
  Search

Answer: $(".tab-link") always points to the first matched element in the document.
Try with this to refer the currently clicked element like the following way:
$(".tab-link").click(function() {
  if ($(this).hasClass("disable")) {
    alert("Yes");
  } else{
    alert("No");
  }
});

$(".tab-link").click(function() {
  if ($(this).hasClass("disable")) {
    alert("Yes");
  } else{
    alert("No");
  }
});

function loadFirebase(){}
a{
  display: block;
}

  today
  today
  today
  Home

  rocket_fill
  rocket_fill
  Games

  layers_alt_fill
  layers_alt_fill
  Todo

  download_fill
  download_fill
  Download

  search
  search
  search
  Search

Comment: That works on the PC but on the webapp on my phone i got No on every click

jQuery, if "a" tag has class or not


Auto-include version of program based on date of git push

Question: I am developing a program in C that needs to include the date and the time of the last push performed in a given branch in the git repository in order to version it.
I know how I can get the data from git and use it to generate a version number in the format I want.
(https://stackoverflow.com/a/51403241/7114946)
The problem is I don't know how to include this within the code of the program because it ultimately needs to "printf" this info during the starting of the app.
I have found the preprocessor macros __TIME__ and __DATE__. I wonder if there are other similar macros to include some given string/data.
Thanks
edit: I need to include this info in compilation time, not when the code is uploaded into git.
Answer: You can define macros on the command line:
gcc -DFOO=BAR -c prog.c

acts like #define FOO BAR in prog.c.
You can combine this with shell command interpolation to get the output of an external program in there:
gcc -DGIT_TIMESTAMP="\"$(git whateveryourcommandis)\"" prog.c

(The escaped quotes are there to make the macro expand to a string literal.)
And then prog.c can do e.g.:
printf("my git timestamp is %s\n", GIT_TIMESTAMP);

Comment: I am just lurking but that is slick.
Comment: That is exactly what i was searching for

Precise, concise and clean.

Thank you!


Cast Eigen::MatrixXd to Eigen::MatrixXf

Question: I am using Eigen on a C++ program.
I wonder if there is a way to cast from Eigen::MatrixXd to Eigen::MatrixXf.
static_cast <Eigen::MatrixXf> doesn't seem to work and neither A.cast<MatrixXf> (this is the cast method from Eigen).
Any solution for this type of cast?
Answer: Try this:
Eigen::MatrixXd d;                       // Matrix of doubles.
Eigen::MatrixXf f = d.cast <float> ();   // Matrix of floats.

Comment: I made a confusion in my description since I am trying to cast MatrixXd to MatrixXf (and not has I described first). Following your sugestion I've used .cast() and it did the trick. (I was missing the () in the end.)

Cast Eigen::MatrixXd to Eigen::MatrixXf


Hand generate views relationship

Question: Here's the setup: the previous site builder linked a large quantity of assets to particular nodes.  Now that I'm on board, we want to expand those nodes into larger sections, but we need the linked assets to show up on all the pages.
Right now we have a view that uses a contextual filter to look at the NID.  Then, it refers to a relationship to see what assets are related to that NID.  Then, the view is filtered and displayed.
I need to come up with a way to display that same view on different pages that obviously don't share the same NID.  I've tagged all the pages within a section with the same taxonomy term.  I'd like to create a custom relationship that runs an equation that converts tid to nid.

tid 62 = nid 15
  tid 63 = nid 47
  tid 64 = nid 153

I think you get the picture.  Any help?  If you have a better idea please let me know, thanks!
-JB
Answer: Here are a couple of ideas for you:
1) If there aren't too many nodes with assets - you could remove the contextual filter and create an "Or" Filter Group in the regular filter section of the view (based on NID). Then just list all of the NID's you want to filter by (NID 15 Or NID 47 Or NID153). That should pull in all of the assets from each of the Nodes without having to change the view much.
2) If you tagged the nodes containing the assets with taxonomy terms - you should also be able to use a regular taxonomy term filter instead of the contextual filter. I think in that case you would just need to add a Content: Taxonomy terms on node relationship to the view. That should open up a bunch of new taxonomy filter options in the regular filter section of views. You could then filter by term id or name.
You would just have to make sure you apply the Content: Taxonomy terms on node relationship to the term id filter when you set it up.

Hand generate views relationship


Create function to loop through a pandas dataframe

Question: I have a dataframe that looks like this.
Now i want to create a function to get the sum of the 'Total' column for each of the name 'ABC','XYZ'... with a pre-defined condition of the Currency.
In other words, i want my output to be the same as the following
Name_list = list(df['Name'])
Currency_list = list(df['Currency'])

def Calculation(a,b):
    for a in Name_list:
        for b in Currency_list:
            return df['Total'].sum()

result = Calculation('ABC','VND')
print(result)

So far what I have got is just the sum of the whole column 'Total'. Anyone has ideas how to get the desired result for this?
Answer: I think pandas' groupby method may help you here:
df.groupby(['Currency', 'Name'])['Total'].sum()

Link to official docs:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html
Answer: In your code there is actually nothing that force the function to use only the lines you want to select in your dataframe.
This can be done by using the loc function to locate the lines you want to sum on.
In your example, if you replace le the line return df['Total'].sum() by this one :
return df.loc[(df['Name'] == a) & (df['Currency'] == b), 'Total').apply(numpy.sum)
It should return what you want.
Comment: I tried your suggestion. However, it only returns a fixed value, even though I have tried to insert different arguments to the function.
Comment: I edited my answer, I think it will work with this line (you need to import numpy though).


Is there a way to selectively export specific relevant configuration into custom modules?

Question: I'm learning D8 and gaining familiarity with the configuration management aspects of drush.
All my configuration is exported into my config/sync directory and I cherry picked the relevant files and moved them into a config/install under my custom modules.
However, I'm having trouble when I had to rebuild my site due to some vagrant issues and I came across the following type of errors:

Unable to install Questions due to unmet dependencies: field.field.node.quiz.field_questions (node.type.quiz), views.view.quizes (node.type.quiz, rest, serialization)

Is there a way to selectively export specific relevant configuration into my custom modules directly?
Comment: See https://drupal.stackexchange.com/a/283268/47547
Answer: I would use the awesome features module as a base to export complex configurations that contain multiple dependencies as a base of my new module and then start building my custom functionality. All major distributions are using features module as it saves a lot of time and it is very reliable.


What are the key things I need to work on for writing rhythmic notation?

Question: I want to learn how to write music notation, but first I want to learn the rhythmic aspect of it so I'm only trying to work out rhythms on single staves.
What are the key things I need to work on?
Some things I've already thought of are:

Learning how to write note and rest values, which I already understand pretty well.
How to properly count — I'm having trouble with this one beyond 16th notes. I'm thinking that this is the reason it is hard for me to comprehend how to write the rests.

I was thinking to buy some books on drum notation and work on counting those, but I'm not sure that'll even help without first understanding how to count, more specifically, how to count the past 16ths and the rests. I understand up to sixteenth 1 e + a but I never learned past sixteenth.
Essentially, my current goal is to translate my rhythmic ideas onto paper.
Comment: Quick point: If you find yourself writing an unreasonable number of triplets,  you may be in the wrong time signature When Pete Seeger transcribed _Minuit_, he did so in 4/4 and it's quite hard to read. Rewriting it as 12/8 makes it _much_ easier to understand.
Answer: The thing about music and rhythm and the connection to writing is that most musicians, amateur to pro have an innate sense of rhythm and are able to conceptualize, copy and create things that are very complex. What a lot of musicians can't do is bridge the gap between being able to hear, feel and play something and explain it in concrete terms like music notation. This seems to be what you are trying to do.
For now I would put a limit on subdivisions at 16th notes until you have a strong grasp of the rhythms that can be created using whole, half, quarter, eighth, sixteenth notes and their triplets. Anything beyond those basically uses the same concepts and is just simple math with smaller fractions.
Writing is not a one way street. You need to be able to read and understand rhythm and written notation in order to be able to write your own ideas so yes, get yourself some books, preferably accompanied by audio examples. You may want to start with a book that only teaches rhythm and is not necessarily drum specific. Read and play rhythms. This will give you a lot of insight on how to write what you hear.
Once you start writing, the things you need to focus on are:
Accuracy: Make sure you are presenting the rhythmic notation in a way that represents exactly the notes you want to hear and when they are played.
Clarity: This includes neatness. Make sure your notes are grouped and beamed together properly. Use imaginary par lines. In 4/4 time that means on beat 3 for eighth notes or on every beat for 16th notes. Space your notes so that they are representative of their appropriate value in relation to other notes within each bar.
Simplicity: This goes hand in hand with clarity. Basically if there are two or three ways to write something, pick the way that is the easiest to digest quickly. Imagine you are writing for someone who is sight reading and want to make it as easy as possible for them.
Transcribing is also a great tool to help you understand and assimilate rhythms, start with simple 8th note music and move up from there. It can be any instrument, not just drums. You can transcribe the rhythm of a melody, guitar, bass, horn parts, etc. If you can't write it out right away at least try and be able to play it and it will start sinking in over time.
Answer: It can be tricky to know exactly what your rhythm "sounds like," but to figure out how it's written. I'd suggest letting some technology help. If you can sing or clap or tap your rhythm, then record it (preferably while running a metronome so it stays stable). So first of all, this prevents you from forgetting or altering it while you work on transcribing it. Then, you can use various tools to slow the recording down, so you can hear and think about it better. You can count aloud, "1 e & a" or etc., and notice how the recorded values align with what you count.
For small note values, try "doubling" everything in your mind. For instance, there's no real difference in the way these two things sound:

With the metronome set to 60 for the first example and 120 for the second, these notes go by at the same rate. The only difference is how "big" a note you "feel" to be the beat—or in other words, what the metronome is doing. (This raises the question, which one is the "right" choice? That's not an easy question, and has been covered elsewhere here. It comes down to what you like and what's practical.) But even if the first version is what you choose to go with, sometimes for small note values it helps to "pretend" for a little bit that a smaller note value is in fact the beat. (Helps when reading them, too!)
Answer: 1e&a is fairly safe.  But the trouble with mnemonics is that they aren't as 'intuitive' as we like to think.  For instance, these two readings of 'Elephant' are equally possible and equally learnable.  But you HAVE to learn them!  Invent anything you like, but don't kid yourself they'll be 'standard' or 'intuitive'.
Comment: In my teaching experience, every time anyone encounters the concept of triplets for the very first time, what comes out is the second example. "Oh, easy! One two threee, one two threee!" (Which reminds me of the joke "Maestro, do you find it difficult to conduct in seven?" "Certainly not! One, two, three, four, five, six, sev, en.")
Answer: For notes "smaller" than sixteenths, there's no standard counting mnemonic. The best option I've found is to change the beat note and then divide the count accordingly.
For example, consider a piece in 4/4 time with a 32nd-note passage. I would count as though the piece were in 8/8 (i.e., eighth-note beats) and then use the 1-e-&-a (or other) counting method for the 32nds.

Triplets are typically 1-&-a or tri-pl-et or el-e-phant or ta-ki-da or ....
Comment: Glad to see el-e-phant is far more universal than I would have imagined! Trying to find a French equivalent right now.
Answer: Can't speak for everyone, but I'd split each crotchet (say) into two, and count 1e&a for each quaver. Don't think there's an 'industry standard' for those, but each would have their own trick.
Triplets - 1-trip-let, 2-trip-let, etc works well. Kids like el-e-phant el-e-phant too!
Answer: One help could be a good note writing program on your computer. The note program will always fill a bar with notes + rests and notates complicated rythms correctly. It will allow you to see the notes and playback the rythm. Dorico SE is free to use is one example of a program as there are other programs (some programs will allow you to write free from the limitations of standardized note writing, ie having to many or to few beats in a bar, maybe best to avoid at the stage you are right now).
Comment: @nuggethead - as I wrote programs differ. Which program is your experience from? If the answer is FInale then it generally does not nudge you towards using correct notation as it is designed to allow you to do what you want (not what the program wants).. My experience is from Dorico where you can force it to not follow the standard notation rules , but it takes some special steps..
Comment: Yup wrote, "The note program will always fill a bar with notes + rests and notates complicated rythms correctly."  This has not been my experience.  They frequently do not notate things correctly, but we tend to trust the computer and so we don't notice the mistake and then learn it wrong.
Comment: Awesome! Thanks for this suggestion I didn't even think about it. What do you think about Sibelius and the rest of the avid notation applications? The first thing that stuck out to me is that I can use Sibelius on my iPhone but not Dorico (I don't have an iPad and would rather not buy one right now).