How to create a dynamic date format?

Question: I'm fairly new to Drupal and I'm struggling to find where and how I should approach the problem I'm describing below. I suspect I will have to dive in the code but that's ok I'm comfortable with PHP.
I have a content type "Event" with a "Date & Time" field called "Event Start Date". I've configured the Date format to be "l, F d, Y - h:i a", but it's not exactly what I'm looking for.
I need to add a condition to my date format so that it doesn't display :00 when the minutes are at 00.
For example
Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9:00 am

should display
Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9 am

How and where should I be doing this in code?
Preferably, I would like to be able to tell when to apply this rule.
Comment: where do you want to show it?
Comment: On the node page with the other details of the event.
Answer: I think the best solution is used custom field formatter for date type:
/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
      'mymodule_custom_datestamp' => array(
          'label' => t('Custom datestamp formatter'),
          'field types' => array('datestamp'),
      ),
      'mymodule_custom_date' => array(
          'label' => t('Custom date formatter'),
          'field types' => array('date', 'datetime'),
      ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'mymodule_custom_datestamp':
      foreach ($items as $delta => $item) {
        $tmp = (integer)$item['value'];
        $minutes = (integer)date('i', $tmp);
        if(empty($minutes)){ //you'll update only values with :00
          $element[$delta] = array('#markup' => date('l, F d, Y - h a', $tmp));
        }else{
          $element[$delta] = array('#markup' => date('l, F d, Y - h:i a', $tmp));
        }
      }
      break;
    case 'mymodule_custom_date':
          .....
          break;
  }

  return $element;
}

You can use it anywhere and It uses the least resources.
Comment: This is the best answer.  If you also need this in views, you may want a views field plugin to do the same thing.
Answer: You can use the theming of field:
create file into your theme for field "Event Start Date"
field--field-event-start-date.tpl.php
or use function in template.php of your theme (for delete seconds)
 function mytheme_field__field_event_start_date($vars) {
    $value = (integer)$vars['element']['#items'][0]['value'];
    if(empty($value % 100)){ //you'll update only values with :00
       $vars['items'][0]['#markup'] = date('l, F d, Y - h a', $value);
    }

 }

for delete minutes:
function mytheme_field__field_event_start_date($vars) {
  global $language;
  $tmp_date = $vars['items'][0]['#markup'];

  switch ($language->language) {
    case 'fr':
      $vars['items'][0]['#markup'] = str_replace('h 00', 'h', $tmp_date);
      break;

    default:
      $vars['items'][0]['#markup'] = str_replace(':00', '', $tmp_date);
      break;
  }
}

P.S. I could be wrong with variable names
Comment: What does the index [0] represent? Is it possible to have move value?
Comment: @EricB. I'm using a raw value. index [0] for simple value, if multi values need to use foreach. But I had mistake. I was thinking you want to delete seconds, and your solution works no right for that situation. Before, I was wanted to offer it (used function replace).... OK.  BUT you should use the theming of field: my variant executes only when render the field, in your variant - when render any fields. It is more  time on the render of page. Into function you're using your solution.
Comment: @EricB. I added the changes
Comment: Thanks Alex, I'm looking for a more broad approach. With the hook I can target all "datestamp" field not just the one for the "Event" content type.  Anyway I'm still facing an issue with Views and Search API, they don't seem to trigger the hook_field_attach_preprocess_alter/
Comment: Ideally the Date Format should accept a callback function instead of only providing support for PHP format, this would solve a lot of issue.
Answer: Here is the solution I implemented using the hook_field_attach_preprocess_alter hook.
/**
 * Implements hook_field_attach_preprocess_alter
 */
function mymodule_field_attach_preprocess_alter(&$variables, $context) {
  global $language;

  foreach ($variables['content'] as $field_name => $field) {

    // remove minutes formating if at 00 on field type datestamp.
    if (isset($field['#field_type']) && $field['#field_type'] === 'datestamp') {
      $tmp_date = $variables['content'][$field_name][0]['#markup'];

      switch ($language->language) {
        case 'en':
          $variables['content'][$field_name][0]['#markup'] = str_replace(':00', '', $tmp_date);
          break;

        case 'fr':
          $variables['content'][$field_name][0]['#markup'] = str_replace('h 00', 'h', $tmp_date);
          break;

        default:
          break;
      }
    }
  }
}

How to create a dynamic date format?


Função para inverter uma string

Question: Tentei fazer uma função a fim de inverter uma string mas o programa sempre retorna
(null).
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char reverse(char string[])
{
   int length, i;

   length = strlen(string);

   char reverse_string[length];

   for(i=0; i<length; i++)
   {
      reverse_string[i] = string[(length - i) - 1];
   }

   return reverse_string;
}

int main()
{
   char string[50];

   gets(string);

   printf("%s", reverse(string));

   return 0;
}

Pensei que pudesse estar colocando o caractere '\0' na primeira posição de reverse_string, mas eu adicionei o "-1" na operação e mesmo assim o programa sempre retorna (null). Se alguém souber o que está acontecendo e puder dar uma dica, eu agradeço!
Answer: O problema é que a tua função retorna um char mas reverse_string é um vetor, o correto seria retornar char*. Além disso, você esqueceu de marcar o final da string convertida com o terminador nulo '\0'.
char* reverse(const char string[])
{
    int length, i;
    length = strlen(string);
    char *reverse_string = malloc(length + 1); // +1 para o terminador nulo

    for(i = 0; i < length; i++)
    {
        reverse_string[i] = string[(length - i) - 1];
    }
    reverse_string[length] = '\0'; //terminador nulo no fim da string
    return reverse_string;
}

Nota que reverse_string tem que ser dinamicamente alocado. Caso contrário você estaria retornando o endereço para um vetor que já foi destruído. E não se esqueça que tens que libertar a memória.
int main() {
    char string[50];

    gets(string);
    char* reversed = reverse(string);
    printf(reversed);
    free(reversed); //libertar a memória
    return 0;
}

Answer: Há vários problemas no código apresentado:

O tipo de retorno da função reverse() está char. Se pretende
retornar uma string tem de ser char*.
A string reverse_string[] é alocada na pilha dentro da função
reverse(), por isto a string não sobreviverá ao término da execução
da função. O valor de retorno de reverse() será um ponteiro
inválido.
A função strlen() calcula o tamanho da string sem incluir o
terminador '\0'. É preciso adicionar o '\0' após o último
caractere.

Duas alternativas de implementação seriam:

Alocar a string no heap, utilizando malloc() e devolver o ponteiro
para a string. Fazendo isto, a string sobrevive para além do escopo
da função e deve depois ser liberada usando free().
Adicionar um parâmetro na função reverse() e passar para este
parâmetro uma string já alocada para receber a string invertida.
Neste caso a string a ser passada como parâmetro pode ser alocada
normalmente na pilha dentro do main().

A seguir a implementação destas duas variantes, reverse_1() e reverse_2():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* reverse_1(char string[])
{
  // armazena o tamanho da string sem o terminador '\0'
  int length = strlen(string);

  // aloca espaço no heap
  char* reverse_string = malloc((length + 1) * sizeof(char));

  // inverte a string
  for(int i = 0; i < length; i++)
       reverse_string[i] = string[length - i - 1];

  // coloca o terminador '\0'
  reverse_string[length] = '\0';

  return reverse_string;
}

void reverse_2(char string[], char reverse_string[])
{
  // armazena o tamanho da string sem o terminador '\0'
  int length = strlen(string);

  // inverte a string
  for(int i = 0; i < length; i++)
       reverse_string[i] = string[length - i - 1];

  // coloca o terminador '\0'
  reverse_string[length] = '\0';
}

int main()
{
  char s[50];
  gets(s);

  // teste de reverse_1
  char* rs1 = reverse_1(s);
  printf("reverse_1: %s\n", rs1);
  free(rs1);

  // teste de reverse_2
  char rs2[50];
  reverse_2(s, rs2);
  printf("reverse_2: %s\n", rs2);

  return 0;
}

Answer: Você pode inverter uma string inplace sem fazer uso de nenhuma função da biblioteca padrão, fazendo uso apenas de aritmética de ponteiros, veja só:
void reverse( char str[] )
{
    char * ptr = str;

    while( ptr && *ptr )
        ptr++;

    for( ptr--; str < ptr; str++, ptr-- )
    {
        *str = *str ^ *ptr;
        *ptr = *str ^ *ptr;
        *str = *str ^ *ptr;
    }
}

Testando:
#include <stdio.h>  /* printf() */

void reverse( char str[] )
{
    char * ptr = str;

    while( ptr && *ptr )
        ptr++;

    for( ptr--; str < ptr; str++, ptr-- )
    {
        *str = *str ^ *ptr;
        *ptr = *str ^ *ptr;
        *str = *str ^ *ptr;
    }
}

int main( void )
{
    char txt[] = "O rato roeu a roupa do rei de Roma";

    reverse( txt );

    printf("%s\n", txt );

    return 0;
}

Saída:
amoR ed ier od apuor a ueor otar O

Veja funcionando do Ideone
Answer: bom dia,
Exemplo de uma função para inverter uma string:
            string novaStr=string.Empty;
            string strOriginal;
            int i;

            strOriginal = "TesteInverter";

            for (i = strOriginal.Length-1; i >=0; i--)
            {
                novaStr += strOriginal[i];
            }

            Console.WriteLine(novaStr);

Comment: Ricardo, sua resposta não ajuda a resolver o problema específico da pergunta e ainda postou um código em outra linguagem, tente dar uma resposta mais direciona para o problema da pergunta

Função para inverter uma string


Vector version of Magento Stack Exchange logo

Question: Wondering if it's possible to get a vector version of the logo.  Want to use it in my list of social links.
Answer: The logo on the Stack Exchange is actually a vector (SVG), I've quickly cropped it out the sprite so if you don't receive an official version you should be able to edit this to what you want:
http://codepen.io/BenCrook/pen/KaBgVY?editors=1000
Comment: You sir, are a friggin BEAST.  I'd actually love to get just the glyph though without "Magento" in it....?
Comment: @kalenjordan Check the codepen again ;)


P2P Isolation Prevention

Question: What are the chances of creating a P2P network where a set of peers can get isolated from the rest. Obviously, I don't fully understand P2P, but I would think that you can get a small group of peers that only know about each other when the real main group of peers is somewhere else.
Comment: Indeed, this is very possible. 'Node discovery' is one of the hardest problems in P2P, without a single known set of central servers. Some P2P systems (such as Skype) are a hybrid of P2P and centralised, since the latter has some very definite advantages.
Comment: There is in theory no 'real main group' in a distributed architecture. Anything related to 'main' usually create problem.
Answer: Connecting to a P2P network requires a bootstrap system which can be implemented two ways: i) with central peers (i.e., peers everyone knows about) or ii) by publishing seeds adresses on a know URL for example. This makes sure that all peers are connected transitively.
If method i) is used and all central peers are down, then there is a risk of isolation for sure, especially when alive connections between peers are closing over time.
If method ii) is used, seed addresses can be republished/updated on the URL. The weak link becomes the webserver serving the URL. If it goes down, risk of isolation increases just like in i), when connections are closing.

P2P Isolation Prevention


Throttling C++ threads

Question: I am trying to translate some C# code which creates N threads at a time and runs a function in each thread.
I have two problems:
-How do I limit N threads at a time?
-My linker doesnt appear to be recognising the static ints FastestMemory and SlowestMemory when I refer to them in my main method (when I print the values out at the end).
Could somebody please help?
So far I have:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <vector>
#include <ctime>

using namespace std;

class Test{

public:
    static unsigned int FastestMemory;
    static unsigned int SlowestMemory;

    public:
        Test(unsigned a, unsigned b){
            FastestMemory = a;
            SlowestMemory = b;
        }

    struct thread_data
    {
        int m_id;
        thread_data(int id) : m_id(id) {}
    };

    static DWORD WINAPI thread_func(LPVOID lpParameter)
    {
        thread_data *td = (thread_data*)lpParameter;

        int RepetitionNumber = td->m_id;

        printf("thread with id = " + RepetitionNumber + '\n');

        unsigned int start = clock();

        vector<byte> list1;
        vector<byte> list2;
        vector<byte> list3;

        for(int i=0; i<10000000; i++){
            list1.push_back(57);
        }

        for (int i = 0; i < 20000000; i=i+2)
        {
            list2.push_back(56);
        }

        for (int i = 0; i < 10000000; i++)
        {
            byte temp = list1[i];
            byte temp2 = list2[i];
            list3.push_back(temp);
            list2[i] = temp;
            list1[i] = temp2;
        }

        unsigned int timetaken = clock()-start;
        printf(RepetitionNumber + "  Time taken in millisecs: " + timetaken);

        if(timetaken < FastestMemory){
            FastestMemory = timetaken;
        }
        if(timetaken > SlowestMemory){
            SlowestMemory = timetaken;
        }

        return 0;
    }
};

    int _tmain(int argc, _TCHAR* argv[])
    {

        Test* t = new Test(2000000,0);

        for (int i=0; i< 10; i++)
        {
            CreateThread(NULL, 0, Test::thread_func, new Test::thread_data(i) , 0, 0);
        }

        printf("Fastest iteration:" + Test::FastestMemory + '\n'); //Linker not recognising
        printf("Slowest iteration:" + Test::SlowestMemory + '\n'); //Linker not recognising

        int a;

        cin >> a;
    }

Answer: I'm not sure what you mean about "limit N threads at a time". Do you mean you want (for example) to only use, say, 5 threads to execute the 10 tasks in your question?
If so, you might want to use a thread pool of some sort. Windows has something like three separate thread pool APIs, along with I/O completion ports, which can also act as thread pools. It's also pretty easy to write a thread pool of your own if you find them lacking -- but the structure is quite a bit different from what you've posted.
The static unsigned int FastestMemory; declares but does not define the variable. You need to define it outside of the class definition:
class Test {
    static unsigned int FastestMemory;
    static unsigned int SlowestMemory;
    // ...
};

unsigned int Test::FastestMemory = 0;
unsigned int Test::SlowestMemory = 0;

Comment: Hi Jerry, yes I do mean 5 threads to execute 10 tasks (therefore roughly two iterations of threads executing).
Comment: @user1107474: In that case you want a thread pool. The basic idea would be to create a [thread-safe queue](http://stackoverflow.com/questions/2375132/releasesemaphore-does-not-release-the-semaphore/2375370#2375370). Put your `thread_data` into the queue in main. Your thread function repeatedly retrieves an item from the queue, processes it, then retrieves another (that question has some sample code showing the general idea).
Answer: You are declaring but not defining your static ints.
Try:
class Test{

public:
    static unsigned int FastestMemory;
    static unsigned int SlowestMemory;
    // ...
};

unsigned int Test::FastestMemory = 0;
unsigned int Test::SlowestMemory = 0;

As for defining N threads, looking at what you have so far, try using CreateThread to create individual threads and scale up as needed. Of course just doing this will give you a very basic and probably not very useful threading model. I suggest reading up on thread pools.
Comment: He's really declaring but not defining.
Comment: @Konrad, I am using CreateThread- but I am not sure how I delay the next group of threads to run, until the first has finished?
Comment: Good spot, it has been a long day ;-)

Throttling C++ threads


Why when textarea not fill, doesn't change a style?

Question: When I press the button, I am trying to change styles of the textarea if it is not filled. But It doesn't work. I catch all elements in the form - textarea. But after this code doesn't work and I can't find a mistake.

var btnForm = document.getElementById('btn-form');
btnForm.addEventListener('click', function (){
var form = document.getElementById('form');
var elems = form.elements;
var error=document.getElementById('error');
console.log(elems);

  for (var i=0; i < elems; i++){
      var textarea=elems[i];

      console(textarea);
      if (textarea.value==''){
          console.log('fserf');
        textarea.style.border = '2px solid red';
        error.style.display = "block";
      }
  }
}
);
.form{
    margin-top:30px;
    text-align: center;
}
.form textarea{
    width: 100%;
    margin-top: 10px;
    border: 1px solid #5dc5ef;
    text-align: right;
    padding-right: 10px;
    resize: none;
}
.form button{
    padding: 10px 80px;
}
.form-for-users h5{
    margin-top: 20px;
}
#number-light-blue{
    color:#5dc5ef;
    font-size: 2em;
}
.btn-form{

}
#error{
    display: none;
    color:red;
}
<form class="form" id="form">

                    <textarea type="text" class="form-control">:שם</textarea>
                    <textarea type="text" class="form-control">:מייל</textarea>
                    <textarea type="text" class="form-control">:נושא</textarea>
                    <textarea type="text" class="form-control">:הודעה</textarea>

Please, fill the form!

                </form>
                <button id="btn-form">שליחה</button>
Answer: You're trying to compare a number to an array:
for (var i=0; i < elems; i++){
Instead you're looking for:
for (var i=0; i < elems.length; i++){


Cleaning the String in java

Question: Is there any function or library which can be used to clean the user input. Like for example if the user input a text called baily's then i should escape the ' before sending it to mysql query. Similarly i should be able to filter null characters and \n, \t, \r etc.. Like in PHP we have mysql_real_escape_string($input) is there anything in Java to do this ?
Comment: **Also See :** [`JDBC - how to escape user-supplied parameters with a sql query`](http://stackoverflow.com/questions/4954002/jdbc-how-to-escape-user-supplied-parameters-with-a-sql-query)
Comment: If you use an ORM layer (which is common practice in Java) or even just Statements with named or enumerated parameters then the escaping of SQL parameters will be done automatically for you.  So long as you're not manually concatenating strings together to build your queries, you should be safe.
Answer: In Java, you don't usually do this by hand.
Instead you'll use a PreparedStatement and pass in any arguments to your SQL statement via explicit setString() or setObject() methods.
This way the JDBC driver will handle it (either by doing the necessary escaping or by sending the SQL statement separately form the arguments, depending on the DB).
For example, your code could look like that (using prepareStatement()):
Connection c = ...; // get Connection from somehwere
PreparedStatement stmt = c.prepareStatement("SELECT * FROM BOOKS WHERE TITLE = ?");
stmt.setString(1, userInput);
ResultSet result = stmt.executeQuery();

Answer: You use prepared statements with placeholders for this. See http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Just like you should in PHP: http://php.net/manual/en/pdo.prepared-statements.php
I mean no offense when i say that only idiots would use mysql_real_escape_string in favor of prepared statements with placeholders.
Answer: You should use PreparedStatement and set the values of $input using the setString function.
The reason for using PreparedStatement is a each database may need to escape different things. This complexity is hidden in the concrete implementation of PreparedStatement provided by the database vendor.
Answer: Short answer, no, except for very specific definitions of "clean".  Right now you have to use a language specific solution -- for SQL, just use a prepared statement.
Longer answer, there has been recent work on automatic string sanitizers that figure out how to incorporate plain text content safely & correctly into content in other languages.
Automatic contextual auto-escapers exist for HTML in template languages like Soy, Go, a variant of jQuery, cTemplates, clearsilver and hopefully others soon.
There is research happening on generalizing this so that it can easily be extended to other languages.  One idea that I'm working on is taking an annotated grammar that describes a target language like SQL and figure out what escaping needs to be done for holes that can be filled with user data.
Given a grammar like the below which includes annotations that show how the structure of data maps to substrings within the language:
JSONValue            := JSONNullLiteral
                      | JSONBooleanLiteral
                      | JSONObject
                      | JSONArray
                      | JSONString
                      | JSONNumber                                    ;
JSONObject           := @KeyValueMap ([{] JSONMemberList? [}])        ;
JSONMemberList       := JSONMember ([,] JSONMemberList)?              ;
JSONMember           := @Key JSONString [:] @Value JSONValue          ;
JSONNullLiteral      := @ValueNull "null"                             ;
JSONBooleanLiteral   := @ValueFalse "false" | @ValueTrue "true"       ;
JSONArray            := @List("[" (JSONValue ([,] JSONValue)*)? "]")  ;
JSONString           := @String ([\"] JSONStringCharacters? [\"])     ;
JSONNumber           := @Number (Sign? (Mantissa Exponent? | Hex))    ;
JSONStringCharacters := JSONStringCharacter JSONStringCharacters?     ;
JSONStringCharacter  := @Char ([^\"\\\x00-\x1f])
                      | JSONEscapeSequence                            ;
JSONEscapeSequence   := "\\" @Char [/\\\"]
                      | @Char{[\x08]} "\\b"
                      | @Char{[\x0c]} "\\f"
                      | @Char{[\x0a]} "\\n"
                      | @Char{[\x0d]} "\\r"
                      | @Char{[\x09]} "\\t"
                      | @Char ("\\u" @Scalar (hex hex hex hex))       ;
Mantissa             := (Integer ([.] Fraction?) | [.] Fraction)      ;
Exponent             := [Ee] Sign? decimal+                           ;
Integer              := [0] | [1-9] [0=9]*                            ;
Fraction             := [0-9]+                                        ;
Hex                  := [0] [Xx] hex+                                 ;
Sign                 := [+\-]                                         ;

we can build a state machine like the below:

which converts sequences of events (start, start_object, start_key, character 'x', ...) into instructions that encode characters onto a buffer.
From that state machine we can also generate generic traces of instructions to use to generate efficient code for encoders, and hopefully the context analysis algorithms that figure out which encoders to apply when.
If this works, it would make it easy to incorporate into general-purpose programming languages, mechanisms for automatically & securely composing content in languages like SQL, HTML, etc.  With tweaks to language definitions to allow execute_query to find the boundaries between programmer-specified-content and injected content in execute_query("SELECT * FROM Table WHERE ID=$ID") and use those to automatically escape the injected content, we can make that idiom just work as the programmer intends.
Answer: The escaping you use is specific for the system you want to use the string for. If you use MySQL, you have to do different escaping than if you want to use the string in a piece of Javascript.
So to answer your question, we need to know how you want to escape your string. Chances are you don't need to escape the string before you use it in a database context. For example, if you use prepared queries, you don't need to escape your values.

Cleaning the String in java


Assigning (adding) an entity reference when an Order process is completed

Question: In Drupal 8, I am needing to know how to assign/add an entity reference of an e-book to an multivalue entity reference field of the user when an order with the e-book is placed. This will allow the user to then access only the e-books attached to his user account.
What hook do I use? how do I know if there is a product in the order that have field_ebook=true? Then how do add it to the list of entity references?
Answer: Not a hook but an event.
Orders have an attached workflow. You can listen to the event of an order being placed, see the state_machine module for documentation on this. Basically, you need to define an event subscriber service, subscribe to the event commerce_order.place.post_transition, then check if order is an ebook and if so act based on the order customer ID.
The subscriber method needs like this:
public function orderStateChange(WorkflowTransitionEvent $transition_event) {
  $entity = $transition_event->getEntity();
  // Check the transition id and whetever else you need on the order and then do your thing.
  if ($transition_event->getToState()->getId() == 'completed' && ...) {

  }
}


Confidence interval with ols and hac

Question: I have to build a confidence interval using OLS and one using HAC (heteroskedasticity and autocorrelation consistent). Which of the 2 ignores the auto-correlation between the errors?
Answer: I assume you're talking about computing a confidence interval using (1) the "standard" variance/covariance estimator,
$\sigma^2 (X^T X)^{-1}$
and, alternatively, using (2) a HAC estimator such as the Newey-West estimator, whose form is a little baroque, and which I'm not going to attempt to write down.
Under the assumptions of the classical linear regression model, the "standard" estimator is a consistent estimator of $Var(\hat{\beta})$, but if the errors are heteroskedastic or serially correlated, it is inconsistent.  Meanwhile, if the errors are heteroskedastic and serially correlated, a HAC estimator is consistent--that's what "HAC" means.  Obviously, then, the "standard" estimator, presumably what you call the "OLS" estimator, is the one that "ignores" the auto-correlation between the errors.

Confidence interval with ols and hac


Recurrence relation for the number of ternary strings containing 2 consecutive zeros vs not containing

Question:
Find a recurrence relation for the number of ternary strings of length $n$
  that contain a pair of consecutive $0$s

The answer to this can be found quite easily to be:
$$a_n=2a_{n-1}+2a_{n-2}+3^{n-2}\;.$$
Now I came across a similar question which asked this:

Find a recurrence relation for the number of ternary strings of length $n$
  that do NOT contain a pair of consecutive $0$s

I supposed that the answer would be the above answer subtracted from the total number os strings i.e $3^n$. But here on Pg 13 they're ending up with the same answer! They do start with an intuitive statement but they disregard it later.
What am I missing here?
Comment: It might be worth checking a few small values of $n$ to see whether the solution given is correct.
Answer: Peter Capello lost track of what he was doing when he wrote up Exercise 30. Despite the wording of Exercise 30(a) and the first sentence of its 'solution', he actually solves the problem of finding a recurrence for the number of ternary strings of length $n$ that do contain the substring $00$. He continues this in Exercises 30(b) and 30(c).
The number $b_n$ of ternary strings of length $n$ that do not contain the substring $00$ is actually
$$\begin{align*}
b_n&=3^n-a_n\\
&=3^n-\left(2a_{n-1}+2a_{n-2}+3^{n-2}\right)\\
&=3^n-\left(2\left(3^{n-1}-b_{n-1}\right)+2\left(3^{n-2}-b_{n-2}\right)+3^{n-2}\right)\\
&=3^n-\left(2\cdot3^{n-1}+3\cdot3^{n-2}-2b_{n-1}-2b_{n-2}\right)\\
&=2b_{n-1}+2b_{n-2}\;.
\end{align*}$$
This recurrence is easily verified combinatorially: if $n\ge 2$, each string of length $n$ without $00$ is either such a string of length $n-1$ followed by a $1$ or $2$, or such a string of length $n-2$ followed by $10$ or $20$.
Added: By the way, the numbers $b_n$ have the closed form
$$a_n=\frac1{4\sqrt3}\left(\left(1+\sqrt3\right)^{n+2}-\left(1-\sqrt3\right)^{n+2}\right)\;.$$
This is easily derived by the usual methods, or one can simply consult OEIS A028859. The entry for the $a_n$ is OEIS A186244.
Comment: @Alan: There are several techniques; perhaps the most elementary is explained in [this PDF](http://pages.pacificcoast.net/~cazelais/222/rec.pdf). It can also be done straightforwardly with generating functions, but they require a little more background machinery.
Comment: @Alan: Take a string of length $n$ with no $00$ substring. If it ends in $1$ or $2$, the first $n-1$ digits must be good (i.e., not containing $00$) strings of length $n-1$. If it ends in $0$, the previous digit cannot be $0$, so it must end in $10$ or $20$, and what precedes that can be any good string of length $n-2$.
Comment: How do you obtain the closed form without OEIS?
Comment: If you don't mind, could you clarify or, rather, elaborate on your explanation after the equalities?
Comment: @Alan: You mean to deduce the recurrence from the problem statement? It's a bit of an art, though practice certainly does help to get you pointed in the right direction. With string problems you should generally try to see how a good string (whatever that means in any given problem) of length $n$ can be formed from shorter good strings. More generally, you try to derive the stage $n$ objects in some natural way from objects at earlier stages, where *natural way* basically just means that you can count how many stage $n$ objects arise in that way from the stage *whatever* objects.
Answer: "the above answer subtracted from the total number of strings" doesn't make sense, since "the above answer" is an equation, and the number of strings is a number, and you can't subtract an equation from a number. Maybe what you mean is that if you let $b_n$ be the number of strings with no consecutive zeros then $b_n=3^n-a_n$. That is certainly true, and you can use it to get a recurrence. You have $a_n=3^n-b_n$, $a_{n-1}=3^{n-1}-b_{n-1}$, and $a_{n-2}=3^{n-2}-b_{n-2}$, so $$3^n-b_n=2(3^{n-1}-b_{n-1})+2(3^{n-2}-b_{n-2})+3^{n-2}$$ Hit this with lots of algebra to get $$b_n=2b_{n-1}+2b_{n-2}+3^n-2\cdot3^{n-1}-2\cdot3^{n-2}-3^{n-2}$$ and now see what you can do with those powers of $3$.


Android. Have scrollbar only visible if ScrollView is scrollable

Question: Is there a simple way to have the scrollbar in ScrollView only visible if the view is scrollable?
I know it's possible to achieve this by comparing the height of the ScrollView and the ViewGroup inside it and then calling ScrollView.setScrollbarFadingEnabled(false);
but it's a lot of overhead and i feel like there should be a simpler and cleaner way.
Answer: You are describing the normal behaviour of a ScrollView. If the ScrollView is not scrollable the ScrollBar won't appear. Even  android:fadeScrollbars="false" won't take any effect if the view isn't scrollable.
Maybe the only child of the ScrollView itself is to big to fit in the viewport (or the ScrollView container) In your case the ScrollView seems  to have always a scrollbar. You could test it by putting a simple TextView as a child in the ScrollView and adjusting the height.
Answer: Use a ViewTreeObserver to get the heights, because it will be called at the moment the layout / view is changing the visibility, otherwise the heights could be 0.
ScrollView scrollView = (ScrollView)findViewById(R.id...);
ViewTreeObserver observer = scrollView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int viewHeight = scrollView.getMeasuredHeight();
        int contentHeight = scrollView.getChildAt(0).getHeight();
        if(viewHeight - contentHeight < 0) {
           ScrollView.setVerticalScrollBarEnabled(false);
        }
    }
});

This is a clean solution IMO and there is no easier way than this.


Spring boot @Getmapping redirection error

Question: In my application I wanted to use get mapping to redirect me to topicform.html file. I do not know why this specific situation is not working. In other mappings it works fine.
<code>@Controller
@SessionAttributes("newTopic")
@RequestMapping("/forum")
public class TopicsController {

...

  @GetMapping("topicform")
    public String newTopic(Principal principal, Model model){
    ...
    }

   @GetMapping("topic/{id}")
    public String showTopic(@PathVariable Long id, Model model){
    ...
    }
...
}
</code>
Topicform is not working but when I want to redirect to the topic it works fine.
Intelij even not mapping me it.
Html files directory looks like this:
Comment: Missing "/" before topicform? You can try in your browser. You pfobably using "/forumtopicform" as endpoint.
Comment: Post all the code.  Also what does "not working" mean?
Answer: Try this :
<code>@GetMapping("/topicform")
public String newTopic(Principal principal, Model model){
...
}

@GetMapping("/topic/{id}")
public String showTopic(@PathVariable Long id, Model model){
...
}
</code>
Comment: @ProGramer no, it is not working. The funny thing is that "topic/{id}" section works fine and many others but only topicform is not.
Comment: I solve that. It should be added to the dictionary.


Comparing vectors when element close to zero

Question: I would like to compare element wise between two vectors, but when the component is close to zero to get different what I expected.
Here is the code:
m <- rbind(c(-2.138697227039309,2.02792645210313,-0.0446693398025567)
            ,c(-1.963333204136506,2.50000000000000,-0.5366667958634941)
            ,c(-2.292730243327192,2.50000000000000,-0.2072697566728089)
            ,c(-2.525115170624692,2.43589709931669,0.0892180713080040)
            ,c(-0.736143506893788,2.50000000000000,-1.7638564931062122)
            ,c(-2.299960100106132,2.50000000000000,-0.2000398998938679)
            )
s <- matrix(c(0,5),nrow = 2)
A <- matrix(c(1,1,1,-1,1,-1),nrow = 2,byrow = TRUE)

for(i in 1:nrow(m)){
  cat("\niter #:",i,"\n")
  a <- A%*%m[i,]
  print(a)
  print(a <= s)
}

I get the following the output:
iter #: 1
           [,1]
[1,] -0.1554401
[2,]  4.2112930
     [,1]
[1,] TRUE
[2,] TRUE

iter #: 2
     [,1]
[1,]    0
[2,]    5
     [,1]
[1,] TRUE
[2,] TRUE

iter #: 3
              [,1]
[1,] -7.771561e-16
[2,]  5.000000e+00
      [,1]
[1,]  TRUE
[2,] FALSE

iter #: 4
             [,1]
[1,] 2.026157e-15
[2,] 4.871794e+00
      [,1]
[1,] FALSE
[2,]  TRUE

iter #: 5
              [,1]
[1,] -2.220446e-16
[2,]  5.000000e+00
     [,1]
[1,] TRUE
[2,] TRUE

iter #: 6
             [,1]
[1,] 2.775558e-16
[2,] 5.000000e+00
      [,1]
[1,] FALSE
[2,]  TRUE

I expected different result in iterations 3,4 and 6.  Is there a better way to compare these vectors.
Here what I would like to have TRUE instead of FALSE
iter #: 3
              [,1]
[1,] -7.771561e-16
[2,]  5.000000e+00
      [,1]
[1,]  TRUE
[2,]  TRUE

iter #: 4
             [,1]
[1,] 2.026157e-15
[2,] 4.871794e+00
      [,1]
[1,]  TRUE
[2,]  TRUE

iter #: 6
             [,1]
[1,] 2.775558e-16
[2,] 5.000000e+00
      [,1]
[1,]  TRUE
[2,]  TRUE

Thanks
Comment: Can you show the expected output?  do you need `lapply(seq_len(nrow(m)), function(i) pmax(A %*%m[i,], 0))`
Comment: @akrun, thank you but this is not what I am looking for. I would like when the value of the A%*%m[i,] close enough to (0,5) to return TRUE instead of FALSE
Comment: Close enough means to `.Machine$double.eps`
Comment: the difference is still greater than `.Machine$double.eps`.  May be you need a different threshold
Comment: @akrun close enough to .Machine$double.eps or little smaller
Comment: How about `lapply(seq_len(nrow(m)), function(i) {a <- A %*%m[i,]; (a -s) <= (10 *.Machine$double.eps)})`
Comment: Possibly related (second part of answer): https://stackoverflow.com/a/48367150/6574038
Answer: We can check whether the difference between 'a' and 's' is less than or equal to a multipliper of .Machine$double.eps
for(i in seq_len(nrow(m))){
   cat("\niter #:",i,"\n")
    a <- A%*%m[i,]
    print(a)
    print( (a -s) <= (10 *.Machine$double.eps))
}

Comment: what if I want to change the inequality to equality to check for the difference. How I would deal with values very close to zero, as such
 for(i in seq_len(nrow(m))){
   cat("\niter #:",i,"\n")
    a <- A%*%m[i,]
    print(a)
    print( (a -s) == (10 *.Machine$double.eps))
}
Comment: @OlelDias  It can never be equal because they are floating numbers


REST URI design for tree structures

Question: There is a lot of discussions out there about REST URI design, but none replied precisely to my question.
Let's say I have some lists that contains tasks and / or other lists (list = node and task = leaf).
We can have something like
/lists/{id_list1}/lists/{id_list2}/lists/{id_list3}/tasks/{id_task1}

or maybe a shorter version :
/lists/{id_list1}/{id_list2}/{id_list3}/{id_task1}

But what about really deep trees ?
I was also thinking about the parent/child relation which could be translated like
/lists/{id_list_parent}/{id_list_or_task_child}

but I feel like something's missing...
What would be a smart design for REST URI trees ?
EDIT
Sorry for my late answer !
So I think I was mixing 2 needs : API URIs and browser URIs.
Here's how I see things :
On the API side, I'll have only those URIs for both write and read methods (the '/id' at the end is not required, for create for instance) :
/lists/id
/tasks/id

On my browser however, I'll have something like this :
/lists/id/lists/id/tasks/

Only the first part (/lists/id) will be interpreted by the server, the second part (lists/id/tasks/) will be used by my client side javascript to find the tasks of the sublist of the list received from the server.
What do you think of this approach, does something feel wrong in it ?
Comment: URI is not part of the REST API. REST is about content, not URIs. This should let you free to choose one URI organisation, and change it later on. Anyway : why do you need /lists/{id_list1}/lists/{id_list2}/lists/{id_list3}/tasks/{id_task1}? This seem to lead to task with id 3, so couldn't this be reduced to /lists/{id_list3}/tasks to have the list of tasks, and /tasks/{id_task1} for the task within the list?
Comment: Have a look at the url on Git Hub https://github.com/twitter/bootstrap/tree/master/docs/templates folders are nodes and files are leafs. I think it works well!
Comment: Thanks for your reply but my question was not exact, see my edit above.
Answer: Is there any need to represent the tree via the URIs? When they can simply be references to the nodes themselves and the relationships are modeled via links in the hypermedia type.
Other than that, I think something like:
/lists/{nodeId}/children

and it can return a list of the direct children to the parent.
You can also do something like:
/lists/{nodeId}/children?depth=3

and return the next three levels of the tree in your result.
/lists/{nodeId}/children?depth=infinite

can return the entire branch from that node.
Answer: Using the URI to enforce this constraint doesn't seem correct. I would accept a PUT request that has some kind of payload (JSON, XML, etc.).
PUT /tasklist
lists: [{
   id: 1234,
   id: 12345,
   tasks: [{
      id: foo,
      id: bar,
      id: baz
   }]
}]

The URL seems to indicate that you are trying to do too much here (IMHO). Typically, you would be interacting with a single resource, while your use case implies that you are operating on several contextually tiered resources at one time.

REST URI design for tree structures


Tuning a tuning fork?

Question: I just purchased a new 440 Hz tuning fork.  But several different computer, iPad and iPhone tuners say it's almost half a percent sharp (around 442) of Concert A.
Is there any way to adjust the frequency of a tuning fork?
Comment: There should be a frequency marked on the tuning fork itself. Trust that, not the box.
Comment: Are you sure it's a 440 fork? It is not uncommon to find one pitched at 442. And I'm curious what others have to say, but I don't think it's possible to tune a tuning fork.
Comment: The package said 440, which is what I wanted.  I wonder if someone put a fork for a European tuning or something in the wrong box?
Comment: personally, computer/mobile/tablets tuners have never accurate for me. have you try on the actual tuner?
Comment: What iPhone tuner app did you use?
Comment: Certainly possible the wrong fork got in the wrong box.  Or, manufacturing wasn't calibrated properly.  Any number of human factors could have led to a improperly boxed fork or a bad batch.
Comment: But how to quickly check (or re-tune) all those electronic tuners?  By using a well calibrated fork!  A whole bunch of those tuner apps do not work well.  I wanted to make sure my iOS app is accurate by testing against a good non-electronic standard.
Comment: Most seemed to manage being in tune (by themselves, or with each other) decades ago, so why does everybody rely so heavily on tuners like they do? there are many situations where a tuner won't actually help a lot. Imagine a band being at a gig where the acoustic piano is down a fraction. Used to happen a lot. Then the guitarists would have a problem - actually having to tune to real notes instead of  flashing lights...
Comment: @idober : I used multiple tuner apps, including the Peterson strobe tuner, ClearTune, plus (shameless advertisement) my own inTuna and iChromatic Strobe Tuners, and on three different iOS device models (in case the audio sample rate clock was way off on one of them). They all said 8 cents sharp, +- 1 cent.  (I also calibrate my own apps against WWV.)
Comment: Just a question here: If the tuning fork is out and the electronic tuners are proving that...why in the heck worry about trying to bring the darn fork into pitch. Just use the electronic tuner like everyone else does.
The real question should be this: "how do you properly attache a tuning fork to your headstock while you play"?
Comment: @Tim There's a function on the tuner for exactly that. So they'd just calibrate the reference pitch, push push done, and then proceed as usual. No problem at all.
Comment: @Divizna - I have several different tuners, ironically not relying on any very often - only in crowded gigs or those where I must tune silently. None of them have that facility.
Comment: If you have a tuning app on your phone that you find trustworthy, why not just use that rather than trying to get a tuning fork to match it?
Answer: OK.  I found a quick-and-dirty temporary solution.
As an online education forum suggested, a interesting school science experiment might be to see if adding weights and changing their position on a tuning fork will change the frequency of the fork.  So I played science student, and tried the experiment.
Two big rubber bands on the tines clearly lowered the frequency... by way too much.  Next I tried a couple strips of masking tape wrapped around the very end of the each tuning fork tine.  That also lowered the frequency, by only a bit too much, to 20 cents flat.  So I removed those pieces of tape and carefully measured them.  Then I cut some tape strips about 9/29ths as long (actually a few mm longer).  Wrapped the new lengths of tape on the fork tines, and the fork rang 3 cents flat.  A little more fine trimming of the length of the tape with some sharp scissors, and I got the fork to measure within +-1 cent of 440 Hz, as measured against several calibrated iPhone tuners (both dial and strobe).  The fork also now sounds good when played simultaneously with an mp3 of a 440 Hz tone to check for beats.
The tone probably isn't as pure, and tape will eventually age and wear, but this quick fix should work well enough until my next trip to a good music store for a better quality tuning fork.
Comment: The position of the tape along the tines should also affect the pitch. They make adjustable tuning forks using this principle. http://www.fishersci.com/ecomm/servlet/fsproductdetail_10652_1618854__-1_0
Answer: You could tune it up if you have precision tools that can grind off just the right amount of metal from each tine (this would increase the frequency; to decrease the frequency you would need to add metal!) - but practically speaking that means no, you can't do it.
Does it look damaged? If not it is probably supposed to be a 442 tuning fork. If you need a 440 you'll need to just buy one.
Update based on the comment that you had bought a 440 fork:
Take it back to the shop, get them to check it. If their check shows it is a 442 then they can replace it. If they show it to be a 440 then maybe your tuners are out.
Comment: [OP's comment](http://music.stackexchange.com/questions/6336/tuning-a-tuning-fork#comment8552_6336) from about a minute after you posted your answer: "*The package said 440, which is what I wanted.*"
Answer: It is defective. Return it for a refund. There is no practical way to recalibrate it. The reason people purchase a tuning fork in the first place is to get something that is exactly calibrated already.
Answer: Interesting question! No-one's mentioned temperature, so far. I'm off to put one in the freezer and another in the oven! I'll report back!

Just got back from hospital with frostbite on one hand and burns to the other... but surprisingly the tuning fork stayed in pitch! My theory stemmed from the British Yard which lives in London. It is exactly a yard long at a given temperature. Longer tuning fork = lower note, shorter = higher, surely?
Comment: LOL :D Did it damage the forks or alter the pitch?
Comment: Changing the temperature of the fork also changes its elasticity, I expect, which would change its pitch, too.  The colder the stiffer, raising the frequency.  Perhaps this counteracts the change in length.  Or, perhaps more likely, the effects of both changes are imperceptible.
Comment: @phoog - colder would also make the tines shorter, thus *raising* the frequency. So, shorter rather than stiffer? Why the dv?
Answer: As someone else stated, grinding off material from the end of the tines will increase the pitch.
However, grinding material off at the base bend of the fork will lower the pitch: there the material contributes much more to the fork's stiffness than to its inertia.
But it may well affect the purity of tone.
Answer: I had a cheap allegedly A440 fork that showed sharp on all tuners, and for reference, a better-quality fork showed exactly A.  By filing a small amount from the outside of each tine near the join, and checking several times, it is now quite exact.
Comment: Did the forks disagree when you sounded then simultaneously?
Answer: Just adjusted two A tuning forks I had to A#/Bb for my trumpet. Just got my guitar chromatic tuning meter and used my bench grinder to take equal amounts off the tines' ends a bit at a  time until the frequency was right.
It's not rocket science or even heavy engineering. Just do it a bit at a time. It wasn't touchy either, it's not critically minute amounts taking off, just don't go daft. I was easy to keep both tines the same length by eye and the sustain on both seems the same as it was before. It's certainly not changed it noticeably. For the final tuning, I did let it cool down between grinds and checks just in case the temperature had a significant effect.
Regarding how accurate are digital tuners, they are based on quartz crystal oscillators that usually are easily accurate to 50 parts per million so, essentially, they are very accurate. Can't guarantee the same for the apps on phones though as they are often software solutions based on general phones so it depends on how the software has been written.
Answer: CHeap Chinese tuning forks (as of 2023) advertised as 440Hz are simply not that. DO NOT BUY. I have bought 4 from various sources, they produced sounds ranging from G to Bb. One was modifiable, by filing it down, the others - I sent back.
Answer: A bit of solder at the tip would lower the frequency.  But to get both tines exactly right, that's tricky to do.
Comment: This is rather impracticable. First, few people have the resources to solder. Second, just getting that little bit soldered would cost way more than it's worth, and third, filing it down to the right amount would take forever. If you look at hotpaw2's answer, you can see how little needs to be added.
Comment: Memories of tuning a Wurlitzer electric piano!   I had a soldering iron. and filing it down didn't really take long.   Solder's soft.
Answer: You can slowly grind it down to 440. Just make sure to cool it down each time before you check it.
Aside from that 442 is MUCH better than 440 IMHO. I've been tuning all of instruments to 442 for the last couple years and have noticed a drastic improvement on not only my playing but also my health. Kid you not! Most of the really good musicians tune down half a step anyway, which is, surpise... 442!
I know this is an old thread and all but I actually have a 440 tuning fork I would totally trade you. I don't really use tuning forks but I may grind it down anyway as the 440 bugs me something fierce.
Comment: Grinding it down would *increase* the frequency.
Comment: Moreover, 442 is nowhere near half step down. It's a very slightly higher pitch than 440.
Comment: @user1079505 442 isn't down at all!  I realize your comment acknowledges this but it deserves to be called out more prominently.  Most period-instrument baroque music is performed at A=415 Hz, a standard that was chosen because it _is_ a half step down.  442 is around 1/13 of a half step above 440, 7.85 cents.

Tuning a tuning fork?


Is Mikrokosmos technical enough?

Question: I'm an aspiring Jazz piano beginner but decided to quit using Czerny and Hanon for obvious reasons-hanon especially, because it might ruin my touch, and particularly because nearly everyone in my country adores(do they?) playing Czerny and Hanon.
So, I picked up Mikrokosmos by Bela Bartok. It seems a nice book to practice with all those zero point to advancement the book suggests.
But is Mikrokosmos enough for playing Jazz in the regard of technicality? I don't know about technicality but it seems that at least you get to be familiar with the church modal scales.
If this question is too subjective and inappropriate, tell me so that I can edit or delete my question.
Comment: What exactly do you mean by 'Czerny/Hanon might ruin your touch'?
Comment: If your fingers get insensitive, it's not the fault of the exercises but how you are playing them.  Hanon is famous for good reasons.  Don't abandon it.
Comment: Oh! I meant Hanon only. Some say that Hanon makes your fingers insensitive
Answer: Probably no one source is "enough" for playing jazz. Microkosmos, IMO, will do you no harm, but there's plenty more out there that might be more apropos. For example, I have found a lot to learn in Oscar Peterson's collection of jazz studies, and of course you couldn't go wrong learning some Joplin and some Professor Longhair stuff both for historical context and for some of the rhythmic independence of left and right hands that seems to underlie a lot of the great players' technique.
Obviously, these are just a few examples that come to mind, and many more could be added, but you get the point: Mikrokosmos will be useful, but not "enough".
(obviously, this is a highly opinionated answer to a question that seems to demand opinionation)
Links to some recommended study material:

https://www.amazon.com/Oscar-Peterson-Exercises-Minuets-Etudes/dp/0634099795/
https://www.amazon.com/Professor-Longhair-Collection/dp/0793593344/
https://www.amazon.com/Joplin-Complete-Schirmers-Library-Classics/dp/0793567734/
https://www.amazon.com/Jazz-Piano-Book-Mark-Levine/dp/0961470151/
Comment: @Victoria I've added in some links to give you more specific guidance on my (still opinionated :) ) suggestions
Comment: Opps....I'm sorry. It's hard to combine facts(which this site urges to everyone) and questions that I want to know.. I may have to be prepared for deletion. Anyway, thank you  for your reply and I'm a tremendous fan of Scott Joplin's ragtimes, just as you mentioned.

Is Mikrokosmos technical enough?


Form fechando sem close()

Question: Caros amigos, tenho um form bem simples que está fechando após clicar OK no MessageBox. Já revisei tudo, comparei com outros forms que tenho e não encontrei a solução. Se alguem puder me dar uma ajuda, agraço.
namespace menu
{
    public partial class frmFinanceiroDocumentosVencidosGrid : Form
    {
        public frmFinanceiroDocumentosVencidosGrid()
        {
            InitializeComponent();
        }

        public int codigo { get; set; }

        private void frmFinanceiroDocumentosVencidosGrid_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ClienteBLL.verificaParcelasVencidas(codigo);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnVisualizar_documento_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                int codigo = (int)dataGridView1.CurrentRow.Cells[0].Value;
                Financeiro fin = FinanceiroBLL.pesquisaFinanceiroCodigo(codigo);
                if (fin.nota_fiscal_id != null)
                {
                    int nota_codigo = (int)fin.nota_fiscal_id;
                    using (frmNotaFiscalVisualizar ver = new frmNotaFiscalVisualizar())
                    {
                        ver.codigo = nota_codigo;
                        ver.ShowDialog();
                    }
                }
                else
                {
                    MessageBox.Show("Não há notas fiscais vinculadas à este documento.");
                }
            }
        }

        private void btnFechar_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Comment: Qual é código do formulário `frmNotaFiscalVisualizar`?
Comment: O que está chamando esse `Form`?
Answer: Cheque qual o valor da propriedade DialogResult do botão, ela deve ter como valor  DialogResult.None.
Um outro detalhe, o formulário tem duas propriedades AcceptButton e CancelButton verifique se o botão a qual você está clicando não está selecionado nestas propriedades.
Answer: pode ser que esteja acontecendo algum erro ou exception não tratada, vc pode experimentar colocar um try / catch para testar
private void btnVisualizar_documento_Click(object sender, EventArgs e)
{
    try
    {
        if (dataGridView1.Rows.Count > 0)
        {
            int codigo = (int)dataGridView1.CurrentRow.Cells[0].Value;
            Financeiro fin = FinanceiroBLL.pesquisaFinanceiroCodigo(codigo);
            if (fin.nota_fiscal_id != null)
            {
                int nota_codigo = (int)fin.nota_fiscal_id;
                using (frmNotaFiscalVisualizar ver = new frmNotaFiscalVisualizar())
                {
                    ver.codigo = nota_codigo;
                    ver.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("Não há notas fiscais vinculadas à este documento.");
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Form fechando sem close()


Installing package from PPA using Puppet

Question: I'm trying to automatically provision VMs with docker pre-installed.
My default init.pp looks like:
class { 'apt':
 always_apt_update    => true,
}

package { [
    #'build-essential',
    #'vim',
    #'curl',
    #'zsh',
    #'git-core',
    #'htop',
    #'wget',
    #'linux-image-generic-lts-raring',
    'python-software-properties'
    #'lxc-docker'
  ]:
  ensure  => 'installed',
}

apt::ppa { 'ppa:dotcloud/lxc-docker':}

# refresh apt source
exec { "apt-update":
  command => "/usr/bin/apt-get update && apt-get install lxc-docker --force-yes",
  returns => 100
}

The last exec command returns (return 100 is default for a successful apt-get update I think):

info:
  /Stage[main]//Apt::Ppa[ppa:dotcloud/lxc-docker]/Exec[add-apt-repository-ppa:dotcloud/lxc-docker]:
  Scheduling refresh of Exec[apt_update] notice:
  /Stage[main]/Apt::Update/Exec[apt_update]/returns: executed
  successfully notice: /Stage[main]/Apt::Update/Exec[apt_update]:
  Triggered 'refresh' from 1 events

However when I ssh into the box docker is not installed and running apt-get install lxc-docker I can then install it. What am I doing wrong? I can't seem to get it working with a multitude of different configurations.
Answer: apt-get returns 0 on success and 100 on error, as you can easily see from the apt-get man page. So you've got that backwards. You are combining two commands using &&, which means the second command is only run when the first completes successfully (returning 0). So if apt-get update were to return "100", as you wrongly expect, the second command wouldn't even run.
And if you read the log message carefully you'll see that the Exec resource applied is named "apt_update" and not "apt-update". The former is defined in the apt class and run when the apt::ppa resource is applied. The latter is your own Exec resource, which would also appear in the log output, but as Exec[apt-update]. Look for that.
In any case, what you constructed here does not work because you are trying to use Puppet as a glorified Shell script and doing it wrong. Puppet ignores the order in which you specify resources in the manifest and instead applies them in the way it sees fit. So to make sure the lxc-docker package get installed from the specified PPA you need to make sure the PPA resource is applied before the package resource.
There are a few ways to do that, all of them involving that you specify relationships or dependencies. Here's one way, using chaining arrows:
class { 'apt':
 always_apt_update => true,
}

apt::ppa { 'ppa:dotcloud/lxc-docker':}

# Your regular packages don't know or care about the PPA
package { [
    'build-essential',
    'vim',
    'curl',
    'zsh',
    'git-core',
    'htop',
    'wget',
    'linux-image-generic-lts-raring',
    'python-software-properties'
  ]:
  ensure  => 'installed',
}

# We single lxc-docker out to be able to specify
# the relationship to Apt::Ppa properly
package { 'lxc-docker':
  ensure => 'installed'
}

Apt::Ppa['ppa:dotcloud/lxc-docker'] ->
Package['lxc-docker']

This means that the lxc-docker package resource will be applied after the apt::ppa resource for the PPA "ppa:dotcloud/lxc-docker" has been applied. As explained the apt::ppa resource already takes care of updating the APT cache after adding a PPA, so there is no need for explicitly calling apt-get update anywhere.
Comment: You still need to require `Exec['apt_update']` on your packages installed from a PPA. Requiring the PPA before the Package doesn't enforce the relationship between the Exec and the Package.
Answer: And here is an alternative, idiomatic answer using require:
class { 'apt':
 always_apt_update => true,
}

apt::ppa { 'ppa:dotcloud/lxc-docker':}

package { [others]: }

package { 'lxc-docker':
  ensure  => 'installed',
  require => Apt::Ppa['ppa:dotcloud/lxc-docker']
}


Movendo uma Div

Question: Estou com um problema que não estou entendendo as soluções que estou procurando.
Sou iniciante na programação, com apenas 4 dias e estou tentando entender sobre movimentos das divs. Tentei mover as divs por display e position mas não consigo centralizar ela ao meio da tela.
Tentando de algumas maneiras, sua maioria apenas tentativa, e realizando algumas pesquisas não entendi bem como faria.
Vou deixar o código abaixo, e se alguém puder me ajudar, serei grato.

* {
    font-family:'Work Sans', sans-serif;
}
body {
    background:linear-gradient(-45deg, #141f31, #19273c, #1d2f46, #223852);
    display:flex;
    justify-content:center;
}
.container {
    display:flex;
    align-items:center;
    justify-content: center;
    max-width:800px;
    height:auto;
}
.container_tower {
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    width:350px;
    height:300px;
    border:none;
    background-color:#0c131d;
    text-align:center;
    border-radius:20px;
}
.container_tower h1 {
    text-align:center;
    color:#fff;
}
.container_tower input {
    background-color:transparent;
    padding:10px;
    margin-bottom:30px;
    border:none;
    border-bottom:1px solid #fff;
    color:#fff;
    /*Esse outline tira as bordas externa do input*/
    outline:0;
}
.container_tower input:hover {
    text-shadow:0px 0px 1px #ec3535;
}
.container_tower .submit button {
    padding:10px;
    background-color:transparent;
    border:none;
    color:#fff;
    font-size: 16px;
    outline:0;
}
.container_tower button:hover {
    border:1px solid #223852;
    box-shadow:0px 0px 10px #00ffff;
    border-radius:10px;
}
<!DOCTYPE html>

        <title>Opening</title>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, user-scalable=1.0"/>
        <link rel="stylesheet" type="text/css" href="../css/style.css"/>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@300&display=swap" rel="stylesheet">

Opening

                <form method="GET">
                    <input type="email" name="email" placeholder="Username" autocomplete="off" autofocus/>
                    <input type="password" name="pwd" placeholder="Password" autocomplete="off" />
                </form>
                <di class="submit">
                <button>login</button>
                </di>

Comment: Poderia [edit] a pergunta e explicar com mais detalhes o que quer dizer com movimentos das divs? Acredito que queira posicionar elementos, mas posso estar enganado.
Comment: Centralizar verticalmente ou horizontalmente? Além disso, qual(is) div(s) aparece(m) para você sem centralizar? Rodei esse código no widget daqui do Stack Overflow, clicando no botão "Executar", e todos os elementos do formulário apareceram centralizados (exceto os placeholders das caixas de texto (isto é, o texto interno da caixa de texto que fica aparecendo enquanto ninguém digita nada), "Username" e "Password", que apareceram alinhados à esquerda).
Comment: Fala galera! Quando falo em movimentar as divs é como o Augusto falou, quero entender como posicioná-las. No meu navegador ela aparece toda bugada, ou seja, nada está centralizado. Até reinstalei o meu vscode, mas não tive sucesso. Não pensei em recriar até porque, preciso entender o que estou fazendo. Se puderem me indicar algum livro ou vídeo para que eu possa estudar melhor e dá próxima vez vir com uma questão mais concreta e clara, serei eternamente grato. PS: Sou novato me programação, mesmo que seja de estruturação de site, que é  o meu caso. Iniciei no html5 e css3. Curso.
Answer: Olá, boa tarde! Tente colocar:
.container {
display:flex;
align-items:center;
justify-content: center;
max-width:800px;
height:auto;
margin: 170px auto;}

Movendo uma Div


Deslizar item para incrementar TextView

Question: Existe algum componente que, ao deslizar um item de uma ListView, ele incrementa um TextView no próprio item?
Como na imagem abaixo:
Deslizando para a direita, incrementa de acordo com o valor que aparece o TextView da esquerda. O inverso acontece quando deslizamos para a direita.
Answer: Não sei se este tipo de pergunta é válida aqui no SO, uma vez que é sobre "pesquisa" de componente, e não dúvida de programação rs. Mas de qualquer maneira, segue resposta tirada do SO em inglês:

Este componente faz o que você precisa.

Exemplo de declaração na própia documentação do componente:
<com.fortysevendeg.swipelistview.SwipeListView
        xmlns:swipe="http://schemas.android.com/apk/res-auto"
        android:id="@+id/example_lv_list"
        android:listSelector="#00000000"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        swipe:swipeFrontView="@+id/front"
        swipe:swipeBackView="@+id/back"
        swipe:swipeActionLeft="[reveal | dismiss]"
        swipe:swipeActionRight="[reveal | dismiss]"
        swipe:swipeMode="[none | both | right | left]"
        swipe:swipeCloseAllItemsWhenMoveList="[true | false]"
        swipe:swipeOpenOnLongPress="[true | false]"
        swipe:swipeAnimationTime="[miliseconds]"
        swipe:swipeOffsetLeft="[dimension]"
        swipe:swipeOffsetRight="[dimension]"
/>

sendo que:

swipeFrontView - requerido - view frontal
swipeBackView - requerido - view de fundo

Respota original no SO em inglês
Comment: Já testei este componente e já tentei implementar minhas necessidades, mas não serviu. Na verdade o que preciso é conforme arrasto o item e conforme o número aparece o textview do item recebe o valor. No caso eu não clico em nenhum botão, apenas o deslizar do item define o valor. Talvez você tenha alguma ideia de como implementar neste exemplo que você enviou
Comment: Você quer por exemplo, um wheel spinner no backView ? ai conforme o valor selecionado, ele mando para o frontView ? Se não for isso, edite sua pergunta colocando imagens para deixar mais claro. Mesmo eu não sabendo como, pode aparecer outra pessoa que saiba como :)
Comment: Mas tem uma imagem do componente com o item sendo arrastado...
Comment: Pra mim pelo menos não está claro, não tem como você explicar melhor o que você precisa ? e por acaso, o item da backView que você está querendo dizer, seria um tipo de whell spiner ?
Comment: Não, nada haver. Vou explicar a imagem: Tem um listview, onde cada item tem um jogo. Repare que um dos itens foi deslizado para a direta (jogo da Espanha) e por baixo do item aparecem os números 0, 1, 2. No caso se o usuário desliza o item o suficiente para apenas aparecer o item 0 então o TextView correspondente a Espanha vai receber o valor 0. Caso deslize até o valor 2, então o TextBox correspondente da Espanha vai receber o valor 2. É isso que preciso. A imagem eu extrai do aplicativo Palpiteros que tem na play Store caso tenha interface de conhecer o listview que necessito.
Comment: Agora entendi. Eu não conheço nenhum componente que faça isso, e pelo que li nos fontes deste, ele também parece não fazer. Mas fiquei curioso para saber qual seria o comportamento do componente no caso de um palpite de 7x1 (tipo alemanha x brasil, corinthians x santos) rs.
Comment: No caso se você arrastar a lista até o fim aparece um popup para você digitar o valor.

Deslizar item para incrementar TextView


What is the meaning of this tempo marking?

Question: I came across this in a piece for piano four hands (title and composer are unknown; as pointed out in the comments, it might also be a part of a longer piece). Here's the beginning of the upper part (primo):

What does it mean?

"♫=♫" - does this indicate straight (as opposed to swing) rhythm?
"4T. = 4s." - I don't recognize this at all.
"63 ." - is this equivalent to ". = 63", i. e., 63 measures (in 3-4 time) per minute?

More information on the piece:

It has 67 measures; measure numbering starts at 1
It is printed on two pages per part (upper and lower)
No title or composer is given on the first page
It appears to be from a book, with the first page of the lower part starting on page number 128
It has sections A, B, and C (circled letter, section A starting at measure 9 as shown)
It has a coda (starting with a coda sign, ) that ends with a final bar line (thin and thick vertical line)
The last measure before the final bar line is a whole rest in all four hands
Comment: The first one could mean "straight", but it might also means something like "L'istesso tempo", so the eigths should have the same tempo as in the previous case. "4 T. = 4 s." might mean something like "4 measures = 4 seconds" (many languages derive their word for "measure" from latin "tactus"), which would coincide with "2. = 63".
Comment: Is that a common way of specifying the tempo? I've never encountered it (but I'm not particularly well-versed in musical literature). Also, why would one specify "4 measures = 4 seconds" rather than "1 measure = 1 second"?
Comment: I added a longer excerpt and some more details. The fact that there is no title on the first page does suggest that this might not be the beginning of the piece; the whole rest at the end might suggest that this isn't the end either.
But is it common to start measure numbers at 1 after a rehearsal mark? And would we expect a final barline at the end of the coda in this case?
Comment: Curious - by any chance, do you have Piece #40 or #42 in the series? It looks like you have Piece #41.
Comment: Unfortunately, no. I got this from a friend who is currently trying to find out the origin of the piece, and I will update the question if they find it.
Comment: @Lazy Precisely my thought, and likely that "T." is the German "Takt(e)," for measure(s). You should turn this into an answer!
Comment: In short no, there's nothing standard about this. The usual way to indicate tempo is in beats per minute. We also see notations that show note values at changes of tempo or meter *within* a piece. Do we know for sure that this is the beginning? Could that be a rehearsal number 41? Can you edit to give anything more than the present snippet?
Comment: I second the suggestion that the first bit is referencing the previous section.  The "41" could be a rehearsal location number rather than the 41st piece (or movement) in a suite.
Answer: Let's talk at least about what we can know. First of all: The standard way of indicating a tempo is in bpm, with an indication of what kind of note value that bpm pulse measures. For instance, ♩ = 120 m.m. (The "m.m." stands, not for "metronome marking," but for "Maelzel's metronome").
There seems to be some ambiguity about the time signature and the pulse. The mention of a dotted half note and 63 seems to mean that you might choose to feel the pulse "in 1," counting only the downbeats (thus, a dotted-half at a time), and that this pulse would be at 63 bpm. This seems reasonable, since a quarter note pulse at that speed is 189, which is not crazy but perhaps a bit hectic to "feel" as the main pulse.
Next: When we see "[note value] [equals sign] [some other note value]", that tends to tell us something about how to handle a transition in tempo or meter. For example:

... This is telling us that the quarter note pulse of the new 3/4 meter continues at the same tempo as the dotted quarter of the 6/8. So the "eighth notes equals eighth notes" in the mystery notation might relate to material that came before. Even if this is the start of a piece (and the measure number on the second system says it is), perhaps it's "piece number 41," and continued attacca from #40.
The music itself shows some metric ambiguity. It settled on 3/4, and the second measure reinforces that with three big quarter notes, but the first measure subverts it with an accent in the middle of the bar. Combined with the possibility of feeling "in 1," it might shift in and out of subdividing as either three groups of two or two groups of three. I have wondered whether the "s" in "4 s." is sextuplet, or whether " 4 t." is some kind of indication of "4-tuplet," but these theories don't add up to something clear. At any rate, the equals sign seems to suggest that "4t. = 4s." is continuing to talk about the relationship of this section to what came before.
Comment: @Martin True, though I've been debating with myself about whether we're looking at something handwritten or typeset, and leaning toward handwritten. The treble clefs appear identical, but that could just be manuscript paper. The time signature characters look different between the two staves; the "f" in "mf" is different than "f"; the "8"s are different. These could all be artifacts of a scanning process, but maybe not. So anyway, it might just be that the "s" is a capital and has been written smaller... Though otoh, the handwriting *is* meticulously detailed.
Comment: In my experience it's M.M. ♩ = 120 or ♩ = 120 b.p.m.
Comment: Note that in the original "4T. = 4s." it's a capital T, but a small s.


Activity Life Cycle Methods and Saving State

Question: I started reading around about the activity life cycle callbacks and saving state and there are quite a few things I don't understand - I'm writing an android app but I want to ask more general questions than how to do it specifically for the few activities etc I have at the moment, I would like to have a better overall view of how this works!
There are two groups of methods I have seen being used (I have seen one or two others but don't want to confuse myself even further...)

onPause, onResume etc,
and then the onSaveInstanceState ones.

What is the difference between them and the circumstances we should be looking to use them? I have seen some questions where a poster is using one of the normal life cycle callbacks, and is told to use onSaveInstanceState instead, so when should we be implementing onPause rather than onSaveInstanceState and so on. Some posts mentioned about methods being used for transient state only, could someone expand on that?
I have seen state being used to mean slightly different things - UI/View state and Activity state, what is the difference between the two?
I am also a bit unsure with what they mean by state, when we are saving state what kind of things are we saving exactly, could anyone give some quick examples (I don't mean actual code)? The android developer guides say that the android system automatically takes care of some of this, so what should we be concerned with? Bundle objects used by onCreate and onSaveInstanceState only store simple values, so what about more complex objects and arrays.
Thanks
Answer: protected void onPause ()
protected void onSaveInstanceState (Bundle outState)

Just by looking at it, onSaveInstanceState  has an Bundle you can put your things you need to save in it. And get it back in onCreate(Bundle) or onRestoreInstanceState(Bundle);
Some important lines in the document:

This method is called before an activity may be killed so that when it
  comes back some time in the future it can restore its state. Do not
  confuse this method with activity lifecycle callbacks such as
  onPause(), which is always called when an activity is being placed in
  the background or on its way to destruction, or onStop() which is
  called before destruction.
Answer: try to use this code to save state
@Override
protected void onSaveInstanceState(Bundle outState) {
  State s = new State(yourTextView.getText().toString());
  outState.putSerializable(State.STATE, s);
  super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  State s = (State) savedInstanceState.getSerializable(State.STATE);
  yourTextView.setText(s.getYourTextViewText());
}

Answer: Android can destroy your activity or even kill your process at any given time (not likely when it is visible to the user though :-)). When the user navigates back to the activity, the data/info that was shown on the screen before he or she left it should be shown again.
The onSaveInstanceState callback allows you to do this.
Most of the Views already do this for you automatically. E.g. the current text in an EditText, the current scroll position of a ListView, etc. are all automatically saved for you.
However, there are some things that are not automatically saved for you. E.g. the current text in a TextView, the (changed) background drawable of a particular View.
Say, you show an error message after a user action fails. The error message is then shown in a TextField and this TextField's background becomes red (i'm just making this up here :-)). When the user leaves the activity while this error is shown (e.g. presses Home button), the activity is destroyed, the error message and the red background won't be shown again when the user comes back to the activity.
This is where onSaveInstanceState comes to the rescue.
You can save a String in there that containts the error message. Then when the activity is re-created, the Bundle savedInstanceState of the onCreate is not null and you can query it for the error message. If this message is not null/empty, call setText on the TextView for the error message and make that TextView's background red.
Comment: In the error message example, does it not get saved because it wasn't part of the initial ui added during onCreate? So any changes to the ui because of user interaction (or whatever) doesn't get saved automatically?
Comment: Yes, exactly. Some changes to the ui because of user interaction will get saved automatically (e.g. typing text into an EditText). But calling setText on a TextView won't get saved, and calling setBackgroundxxx() on a View won't get saved either. That's where you can use the saved-instance-state to 'fix' this.


Extract a value between semicolons that has a word you want in regex

Question: How can I use regex to pull a the following column titles out of a header list?
Case 1 - ;CASE_NUMBER;CASE_STATUS;CASE_SUBMITTED;... -> CASE_STATUS
Case 2 - ;LCA_CASE_NUMBER;STATUS;LCA_CASE_SUBMIT;... -> STATUS
Here is what I've tried:

(?<=;)STATUS;

Positive Lookbehind (?<=;)
Assert that the Regex below matches
; matches the character ; literally (case sensitive)
STATUS; matches the characters STATUS; literally (case sensitive)

(?<=;).*STATUS;

I added to include characters in between the ; and the word STATUS. I realize the current notation is "greedy", so I finally tried the next option.

(?<=;).*?STATUS;

This is supposed be "lazy", meaning it should only grab everything after the first ; it encounters before STATUS. However, I am getting the same results when using 2 and 3 as a regex and both capture the words starting at the initial semi colon.
How do I extract the letters from the first semicolon behind STATUS to the first semi colon after STATUS?
Answer: However lazy the .*? pattern is, the . can match any char (usually all but line break chars) including ; if the patterns after .*? can appear after a ;.
You may use
[^;]*STATUS[^;]*

See the regex demo
Details

[^;]* - 0+ chars other than ;
STATUS - your word
[^;]* - 0+ chars other than ;.


Getting results from multiple types of data

Question: I'm trying to isolate data as separate values as i get it in. I'm using Python for my code.
Values i could see is:
30/30
30"/32"
XXL
XS/30
XS/30"
30-30
32-32

Everytime there is a second value (/30, -32 etc.) i want to be able to get it in its own group, while the first value (30,XXL,XS,32) should be placed in another group.
End results being:
30/30 = First value "30" Second value "30"
30"/32" = First value "30" Second value "32"
XXL = First value "XXL" Second value null
XS/30 = First value "XS" Second value "30"
XS/30" = First value "XS" Second value "30"
30-30 = First value "30" Second value "30"
32-32 = First value "32" Second value "32"

Been trying for hours to get the regex correct, however i'm not nearly close to any correct result!
Anyone able to help me on the right track here?
EDIT:
My current regex
(?:(?=\d+))(\d+\.?\,?\d+?|[a-zA-Z]+)
I can isolate 30/32, but cant seem to make it grab the text variants (XXL, XS and so on)
Comment: show us your regex
Answer: You can use
([A-Za-z0-9]+)(?:[^A-Za-z0-9]+([A-Za-z0-9]+))?

See the regex demo.
Details:

([A-Za-z0-9]+) - Group 1: one or more alphanumeric chars
(?:[^A-Za-z0-9]+([A-Za-z0-9]+))? - an optional group matching zero or more chars other than alphanumeric chars, and then capturing into Group 2 any one oe more alphanumeric chars.
Comment: @SteffenMandrup Note the `\n` in the negated character class in the regex used inside the demo, it is used to avoid matching across lines. If you run the regex against a multiline text, you might need to use it in the final solution, `([A-Za-z0-9]+)(?:[^\nA-Za-z0-9]+([A-Za-z0-9]+))?`
Comment: Thank you - i knew it was simple, but i couldnt get my head around it :P


best way to sync admin and client time in php

Question: I am not sure if this is hard question or not, but I cannot figure out what is the best way or approach for this case.
I want to synchronize the time of my admin account of the system I am working now, to see the client time base on their time zone. And I has to be ALL the times. for instance I have an admin time of 1:20am in America/New_York time zone, and I will be viewing my client depending on their time zone, like 'Asia/Singapore' will be 1:20pm.
So 1:20am for admin, but admin viewing client will be 1:20pm.
What is the best way to convert those time depending on time zones, and sync it to client depending on client`s time zone.
I have sorted this out by making my function to convert it to client, BUT I will have to use that function to every datetime of my database.
What is the best way to do that?
Answer: The safest way is to ask for user to input his timezone (for example when he registers to your site). If timezone is critical for your service you have to make sure that the client defines his timezone himself, and he accepts all damages may arise by failing to set his timezone by checking a checkbox or something.
If you dont want to ask the client for his timezone you can try to guess his timezone based on his ip using
via php: https://github.com/maxmind/GeoIP2-php
via js: https://bitbucket.org/pellepim/jstimezonedetect
In my experience, the safest way is to ask the user. Depending of the service you provide to the client, the desirable timezone isnt always the timezone of current location of the user.
For example, if i use a remote surveillance system, i could be in japan but i want to check my security cameras on my multibillionaire mansion in USA. So i need the service's time to know what time is in usa, not my time in japan.
Comment: yes I have already time zone for each users. My problem now is what is the best way to convert that to my time as admin when i`m viewing them.
Answer: Not sure how your server is setup.
If you use MYSQL, use TIMESTAMP type to collect date/time data.
MySQL will record standard timestamp to database (regardless to the timezone as the world have one reference).
When query data, MySQL will automatically convert that data to server timezone before presenting you (Just the core setting when database server is setup).
you can try SET time_zone = timezone; function.
MySQL will temporary map new timezone based on your database connection session when you do another query. (e.g. single web page request)
For example, if you run the query immediately after open the database connection.
SET time_zone = 'Australia/Sydney';

All the SELECTED timestamp fields will be converted to Sydney timezone when you do the another query.(It will not effect another session even it's run at the same time. E.g. another PHP file without MySQL set_time_zone query)
Please note that it will not modify your field or core MySQL settings because it's will be real-time conversion based on session only.
================= EXAMPLE ===================
CREATE TABLE test_time (
  user_id varchar(50) NOT NULL,
  register_time timestamp NULL DEFAULT NULL,
  PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO test_time VALUES ('user1','2014-03-16 13:00:00'),('user2','2014-03-16 21:00:00');

In sydney.php
SET time_zone = 'Australia/Sydney';
SELECT * FROM test_time;

In singapore.php
SET time_zone = 'Asia/Singapore';
SELECT * FROM test_time;

In ny.php
SET time_zone = 'America/New_York';
SELECT * FROM test_time;

Comment: I am having the grasp of your sql.. can you give me an mysql query exam for that? that you can set time zone when querying real time?
Comment: @JustIgnite I edited the answer. You can play around with that.