There exists infinitely many irrationals within a range of reals?

Question: Theorem: There exists infinitely many irrationals in a range of reals.
Proof:
Let the range be $R=(a,b)$ where $a<b$ and $a,b\in\mathbb{R}$
Suppose some numbers $n_1\ldots n_k\in R$ where each number is greater than the one before, then $a<n_1<\cdots<n_k<b$. From this it follows
\begin{align}
a&<n_1\\
n_1&<n_2\\
&\vdots\\
n_{k-1}&<n_k\\
n_k&<b
\end{align}
So
$$
a+\sum\limits_{i=1}^k n_i<b+\sum\limits_{i=1}^k n_i\qquad\therefore a<b
$$
Because $k$ can be arbitrarily big, and the truth values of $a<b$ does not depend on $k$, we can conclude that there are infinitely many numbers on a given range. We will now use the fact that the distance between two numbers -irrationals too- is always finite.
Because there are infinitely many numbers in a range where $a<b$ and infinity can be divided into infinite finite parts, then there must be infinite irrationals in that range. $\blacksquare$

My question is, is this argument valid? Any not-so-right steps?
Comment: **PD:** I would like ti know how the vertical dots should be used in this case with MathJax, as I don't see them right.
Comment: In latex it is \vdots
Comment: @joeb I used them like that, but they are not centered.
Comment: I don't follow the idea of the proof. You seem to be pulling $k$ numbers out of a hat, then somehow "prove" the hypothesis that $a \lt b$.
Comment: $k$ is just the number of numbers between $a$ and $b$. At first finite, but the conclusion is that $k$ can be infinity because it cancels when grouping all the inequalities.
Comment: Yes you do seem to be arguing in the wrong direction. Another thing about your arguement, what happens if one of the $n_i = 0$. Then $a \prod_i n_i < b \prod_i n_i$ does not imply $a < b$. It doesn't matter anyway, because you don't need anything to imply $a<b$, you were given this from the start.
Comment: What you've written makes no sense to me. Nothing in your argument says anything at all about irrational numbers. I suggest you start over. Can you find ONE irrational number between $0$ and $1$? When you have done that, find ONE irrational number between $a$ and $b$. Then think about how you could know you could find more.
Comment: @joeb That shows there are an infinite number of rationals in the interval.  The question was to prove there are an infinite number of **irrationals**.
Comment: @MarkFischler But the fact that the distance between two irrationals is finite and there are infinitely many reals between a range doesn't imply that there are infinitely many irrationals within that range?
Comment: Wouldn't it be easier to, say, construct a bijection (or injections both ways would be sufficient due to Cantor-Schroeder-Bernstein) between an arbitrary range and all of $\mathbb{R}$? That tells you the range is uncountable, and you presumably know that rationals are countable, thus this uncountable set of reals minus a countable set of rationals in the range gives you an uncountable (infinite) set.
Comment: @joeb That is exactly what I've done, just in another words.
Answer: No, your proof misses the point.  Aside from the fact that you start with an assumption about the existence of a set of ordered intermediate values of arbitrary size, and spend most of your time proving that $a<b$, which was already given, the problem is that what you have shown is that there are infinitely many reals between any two unequal reals.  But how do you know that almost all of them aren't rational, leaving only finitely many irrationals?
I would start by proving that between any two rational numbers $q_1$ and $q_2$  with $q_1<q_2$ there exists at least one irrational, by proving that
$q_1+\frac{\sqrt{2}}{2}(q_2-q_1)$ is irrational.  (The proof of that is a lot like the
proof that $\sqrt{2}$ is irrational.)
Then I would use the fact that at least one rational number must exist between any two unequal reals (proved by using a denominator bigger than twice the reciprocal of the distance between the reals).  Apply that to $a$ and $b$, getting a rational $q_x$, and apply it again between $a$ and $q_x$ getting another rational $q_y$.
Now for any given $N$ you can break up the interval between $q_x$ and $q_y$ into $N+2$ rational sub-intervals and by the first part of the proof you can slot $N+1>N$ irrationals, one in each interval.  So for any arbitrary $N$ there are more than $N$ irrationals in the interval.


Excel VBA: Timer prevents drag and drop functionality?

Question: I recently wrote a workbook macro to close the workbook after a certain time.  It has a timer running in the background.  I can enter information into cells normally but if I drag a cell to another location, it just disappears and there is no "undo" option.  If I enter debug mode or stop the macro and restart it, drag and drop functionality works again.  But on normal workbook open, it does not.  Any ideas on how to work around this?
I tried forcing Application.CellDragAndDrop = True but this did not fix the problem.
The only way drag and drop starts working correctly is if I stop the macro, then manually start it.
Code is below.
Private Sub Workbook_Open()
Dim Start, TimeInMinutes, UserAck

TimeInMinutes = 5 'Timer is set for 5 minutes; change as needed.

If UserAck = 0 Then
UserAck = MsgBox("This file will automatically close after " & TimeInMinutes & " minutes.", 0)
End If

Application.CellDragAndDrop = True
Application.DisplayAlerts = True

Start = Timer 'Grab current time stamp
Do While Timer < Start + (TimeInMinutes * 60) - (0.5 * 60)
    DoEvents
    Loop
Application.StatusBar = "File will close in less than 30 seconds. Make sure to save."

Do While Timer < Start + (TimeInMinutes * 60) - (0.333 * 60)
    DoEvents
    Loop
Application.StatusBar = "File will close in less than 20 seconds. Make sure to save."

Do While Timer < Start + (TimeInMinutes * 60) - (0.167 * 60)
    DoEvents
    Loop
Application.StatusBar = "File will close in less than 10 seconds. Make sure to save."

Do While Timer < Start + (TimeInMinutes * 60)
    DoEvents
    Loop

Application.StatusBar = "File closed due to inactivity"
Application.DisplayAlerts = False
ActiveWorkbook.Save
Application.Quit
End Sub

Comment: You might be better off using `Application.OnTime` to schedule the event, rather than a loop.
Answer: The loop in your code blocks a lot. Try something like this instead:
Replace your Workbook_Open with this
Private Sub Workbook_Open()
    ClearStatus
    Application.OnTime Now + TimeValue("0:00:05"), "Warn30"
    Application.OnTime Now + TimeValue("0:00:25"), "Warn10"
End Sub

Put this in a module:
Sub ClearStatus()
    Application.StatusBar = ""
End Sub

Sub Warn30()
    Application.StatusBar = "File will close in less than 30 seconds. Make sure to save."
End Sub

Sub Warn10()
    Application.StatusBar = "File will close in less than 10 seconds. Make sure to save."
End Sub

Obviously not a complete example, but it is a start.


getting pyarrow.lib.ArrowInvalid: CSV parse error: Expected 9 columns, got 1

Question: so I am trying apache arrow for the first time and want to read an entire directory of txt files into a pyarrow datastructure. I am getting

pyarrow.lib.ArrowInvalid: CSV parse error: Expected 9 columns, got 1

when I run the code below? no clue how to debug this. any help appreciated. ALSO if there's a book that covers python and pyarrow happy to read it.

import pyarrow.csv as csv

import pyarrow as pa

l_all_files = ['x08.txt', 'x21.txt', 'x108.txt']

read_options = csv.ReadOptions( column_names= ('Sol' , 'H20', 'H50', 'H100',  'Date', 'Cv', 'Dys', 'Ple' , 'Cl') ,  skip_rows=26)

df_arrow_all = pa.concat_tables(( csv.read_csv(current_filename,read_options=read_options, ) for current_filename in l_all_files))

when the skip_rows = 26 is done this is what the line looks like

$sss        3431    3232    3249  25523  35.66    57  56le   77.73

Comment: There are no commas in the data. It's probably read as single column. Try `df_arrow_all = pa.concat_tables(( csv.read_csv(current_filename,read_options=read_options,parse_options=csv.ParseOptions(delimiter='\t' ) for current_filename in l_all_files)) `
Comment: Are the csv files properly formatted?  Are there commas in the first row? Is the entire header row quoted?
Comment: I don't see a whitepsace option for pyarrow: https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html. You may need to load and resave the data using the csv module so the file has commas.
Comment: hi @Mike67  updated the question to show an example row. I thought csv.read_csv was smart enough to handle space separation instead of comma's. Also I thought by providing the column names there would be no need for headings inside the files.
Comment: I agree it's reading it as a single column. running  pandas against it works fine using  delim_whitespace=True,  Can't seem to figure out how to do same in pyarrow.
Comment: AND tried delimiter='\t' no luck.  This is a white space problem. I need to find out how to remove all spurious white space from the data. I would have thought Pyarrow CSV would have something like that but I can't find anything in the docs?
Comment: Hi @Mike67 thanks so much for trying to help. I can't see that the whitespace option either. I think I'll just continue to use pd.read_table instead as it works on this dataset right out of the box. I wanted to try Arrow ready for my move to julia but this is TOO hard :-) thanks again.
Comment: I opened https://issues.apache.org/jira/browse/ARROW-10432 for supporting a general whitespace delimiter
Answer: delmt = '\t'
df = csv.read_csv(current_filename
                 ,read_options=read_options
                 ,parse_options=csv.ParseOptions(delimiter=delmt)

This worked for me!
credit: @Mike67


Google fit API script needs constant authorisation when trying to run automatically & how to extract additional info

Question: I have a script that exports data from the Google Fit API to Google Spreadsheets. The script was found here - https://ithoughthecamewithyou.com/post/export-google-fit-daily-steps-to-a-google-sheet and works.
When I run the script daily manually, it works. However, when I have it set up to run automatically and scrape the data each morning, I get an email saying that it failed to run as authorisation was required.
I'm sure it's something simple, but how can I have it set up so that authorisation isn't required?
Additionally, the ultimate goal is to build some form of dashboard from the data stored on that spreadsheet. Is it possible to scrape additional information, such as what the exercise was? I know that info is stored there, but I'm just not sure how to access it.
For example, I'd like to scrape the data that has been identified as a run on Google Fit.
Answer: Google fit Access OAuth token are process short-lived, and they do not last for long period. So you will be required to identify yourself with credentials on every instance request or after 60 mins per documentation for security reasons.


Oracle query fails by to_date function

Question: Using dapper ORM and running this query;
string transDate ="to_date('8/4/2023','MM/dd/yyyy')";
string customerProfileId = "5464232";

string query = " update customer_bundle set modified_date = sysdate where cust_prof_id = :customerProfileId and trunc(trans_date) = trunc(:transDate)";

            using (OracleConnection dbConn = new OracleConnection("..."))
            {
                DefaultTypeMap.MatchNamesWithUnderscores = true;
                dbConn.Open();
                dbConn.Execute(query, new { customerProfileId, transDate});
            }

it works fine if I remove the "to_date" param from query.
but with date param added, Oracle.ManagedDataAccess.Client.OracleException throws exception like this;

Oracle.ManagedDataAccess.Client.OracleException: 'ORA-00932:
inconsistent datatypes: expected DATE got NUMBER'

I know somehow this "to_date()" part mapped incorrectly and caused this issue
What's causing this? and how can I fix it? And I am using Dbeaver is there any profiler that I can trace incoming queries from the app? QueryManager doesn't contains external queries..
Answer: The parameters given are not inserted as strings into the sql statement; instead, their value is directly used for the query. Therefore, you cannot use the to_date function as part of the date literal. Instead, if you want to use to_date, you must put it into the sql query instead.
string transDate ="8/4/2023";
string customerProfileId = "5464232";

string query = " update customer_bundle set modified_date = sysdate where cust_prof_id = :customerProfileId and trunc(trans_date) = trunc(to_date(:transDate,'MM/dd/yyyy'))";

            using (OracleConnection dbConn = new OracleConnection("..."))
            {
                DefaultTypeMap.MatchNamesWithUnderscores = true;
                dbConn.Open();
                dbConn.Execute(query, new { customerProfileId, transDate});
            }

Oracle query fails by to_date function


C# how to save userinput in windows form

Question: I'm currently trying to make a small program that store the input by the user in the textbox to a file but somehow I couldn't save the input to the file this is what I have done so far:
First Class:
class Name
{
    private string SongName;
    private string ArtistName;

    //Constructor
    public Name(string SongName, string ArtistName)
    {
        this.ArtistName = ArtistName;
        this.SongName = SongName;
    }

    //Properties for SongName
    public string songName
    {
        get { return SongName; }
        set { SongName = value; }
    }

    //Properties for ArtistName
    public string artistName
    {
        get { return ArtistName; }
        set { ArtistName = value; }
    }
}

And here is the Form1 code:
    public Form1()
    {
        InitializeComponent();
    }

    private string SongName, ArtistName;

    public void Registry()
    {
        List<Name> MusicList = new List<Name>();
        MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass

        //Save the list
        StreamWriter FileSaving = new StreamWriter("MusicList");
        for (int i = 0; i < MusicList.Count; i++)
        {
            string sName = MusicList[i].songName;
            string aName = MusicList[i].artistName;
        }
        FileSaving.Close();
    }

    private void btnEnter_Click(object sender, EventArgs e)
    {
        Registry();
        //Set the textbox to emty so the user can enter new data
        txtArtistName.Text = "";
        txtSongName.Text = "";
    }

Comment: your not doing anything with the streamwriter just opening it `filesaving.writeline`
Comment: your code does `NOTHING` also what's up with this line  string sName = MusicList[i].songName;
            string aName = MusicList[i].artistName; you are not writing anything to the file i would also read up on how to use properties..
Comment: Pretty simple issue here if you just look at your code and consider what is missing. Good luck
Comment: Always search for examples, you will learn a great deal. In cases like this you should go line by line and just comment what each line does. This will help you understand what is happening. You would have realized you never commented about anything writing to a file.
Comment: Not entirely sure why you did, but please do not strike out your question content.
Answer: ....You never write anything to the file.....
A quick Google got me this
Notice the call to file.WriteLine(line); also...you realize you are not creating your file with an extension, also?
Comment: @JeremyK I hope you are kidding? Being a beginner does not excuse you from knowing how to google.
Comment: There is nothing wrong with you pointing that out. Just saying you are pretty harsh on your tone and I wouldn't be surprised if this person is very very new to programming or even young. Just no need for falling asleep on the . key :)
Comment: And his lack of google skills won't make up for his lack of understanding on programming. His question does not belong here as he clearly needs someone to coach him.
Answer: In your for loop you need to actually write the values to the stream.
for (int i = 0; i < MusicList.Count i++)
{
    string sName = MusicList[i].songName;
    string aName = MusicList[i].artistName;
    FileSaving.WriteLine(sName + ' ' + aName);
}

Answer: Here you are creating the StreamWriter but never using it:
StreamWriter FileSaving = new StreamWriter("MusicList");
for (int i = 0; i < MusicList.Count; i++)
{
    string sName = MusicList[i].songName;
    string aName = MusicList[i].artistName;
}
FileSaving.Close();

strings aName and sName are assigned to but never saved.
See example here on using StreamWriter:
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
Answer: using (StreamWriter writer = new StreamWriter(filePath))
{
        for (int i = 0; i < MusicList.Count; i++)
        {
            writer.WriteLine(MusicList[i].songName + " , " + MusicList[i].artistName);
        }
}

Answer: I my opinion You should use XML Serialization
here is my serialization generic class
public static class Serializer<T>
{
    public static T Deserialize(string path)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

        System.IO.FileStream stream = null;

        try
        {
            stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

            return (T)serializer.Deserialize(stream);
        }
        finally
        {
            if (stream != null)
            {
                stream.Close();
                stream.Dispose();
            }
        }
    }

    public static void Serialize(string path, T obj, bool createFolder = false)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

        if (createFolder)
        {
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
        }

        using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(path, System.Text.Encoding.Unicode))
        {
            xmlWriter.Formatting = System.Xml.Formatting.Indented;

            serializer.Serialize(xmlWriter, obj);

            xmlWriter.Flush();
            xmlWriter.Close();
        }
    }
}

Then in Registy Method
    public void Registry()
    {
        List<Name> MusicList = new List<Name>();
        MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass

        Serializer<List<Name>>.Serialize(@"C:\saved.xml", MusicList);
    }

note that you must add default constructor in class Name


Finding the function $f(x)$ through the given set of conditions

Question: I got terribly stuck while solving this question recently
Let $f(x)$ be a real valued function such that $$f(0)=\frac{1}{2}; \quad f(x+y) =f(x) f(a-y) +f(y) f(a-x).$$
I do not want the rigorous solution to this problem. I want a possible approach that can be used.
I tried plugging in the values of $0$, $a$, etc but couldn't find the function anyway.
How do I proceed?
EDIT:
a is a constant
Comment: This is a functional equation. In particular one which is similar to the functional equation of the _sine addition formula_.
Comment: Is $a$ arbitrary or is it fixed?
Comment: a is fixed,i.e it is a constant
Comment: @JensSchwaiger Yes it sure does. But how do manipulate it? a is present here....
Answer: Hint:
Assuming $a$ is fixed. Set $x=y=0$, to get
$$f(0)=2f(0)f(a).$$
This implies $f(a)=1/2$.
Now just set $y=0$, to get
$$f(x)=f(x)f(a)+f(0)f(a-x) \implies f(x)=f(a-x).$$
Can you take it from here?
Comment: Yes thanks. However how do i find a trigonometric function by continuing this solution?
Comment: @VAMSIKRISHNACHILAKAMARRI i thought you only want a hint not a "rigorous" solution. Without additional conditions, you cannot say that it has to be a trigonometric solution. Though it certainly is one of the solutions. For example, a constant function $f(x)=1/2$ is also a solution.
Comment: yes i do not want the rigorous solution. I just want to know how to relate from this equation to a trigonometric solution.(which is a possible solution). So I just relate the formulae of addition of sine and cosine functions and see what matches?
Comment: @VamsiKrishna I don't see any direct relation to trigonometric function. By the way, the [answer](https://math.stackexchange.com/a/3677709/229831) by [Jens Schwaiger](https://math.stackexchange.com/users/532419/jens-schwaiger) shows that $ f $ must be constant; i.e. $ f ( x ) = \frac 1 2 $ for all $ x \in \mathbb R $.
Answer: Using $f(x-y)=f(x)$ in the original equation results in  $f(x+y)=2f(x)f(y)$ or $m(x+y)=m(x)m(y)$ for $m:=2f$. Because of $m(a-x)=m(x)$ (a result contained in the answer by Anurag A) and $m(a)=1$ we get $m(2x)=m(x)^2=1$. What does this imply for $f$?


Diferença entre Pipes, Fork e Threads

Question: A partir dessa pergunta, me veio a curiosidade de querer aprender mais sobre o assunto, então pesquisando mais a fundo, acabei me deparando com mais dúvida sobre o assunto. Pois vi que existe uma cadeia de formas de utilizar Threads.
Podemos ver as threads como pequenos processos.
A grande diferença das threads é que elas compartilham os mesmos recursos e endereçamento de memória. Ou seja, é como se tivéssemos um processo que dividido em processos menores, onde há um chaveamento entre eles, cada um executando um pouco (como ocorre nos processos), mas agora eles compartilham os mesmos dados e recursos, e tem um mesmo objetivo, trabalham juntos. E achei curioso, já que as vezes tive que apanhar bastante para melhorar o desempenho de sistemas complexos que ainda estão muito lentos, e que precisam utilizar sub sistemas para melhorar sua performance.
Considerando o meu caso, numa implementação futura, gostaria de saber o que exatamente muda entre os três exemplos abaixo, e quando devo usar um ou outro e vise-versa:
Exemplo de Fork:
$pid = pcntl_fork();

if ($pid == -1) {
     die('Erro ao lançar thread');
} else if ($pid) {
     // thread principal
     //aguardamos a thread child terminar
     pcntl_wait($status);
     echo "Processo child terminado\n";
     exit(0);

} else {
     //thread secundario
     //mudamos para um usuário não privilegiado
     posix_setuid(1000);
     posix_setgid(1000);
     //colocamos a thread para fazer algo,
     //ate que uma condição seja satisfeita e ela termine
    $i=0;
    while(true){

           if (file_exists('/tmp/stop')){
        echo "Terminado thread";
        exit(0);
       }
       echo "Iteração : ". ++$i . "\n";
       sleep(2);
    }
}

Exemplo de Thread:
// Classe que aguarda um tempo aleatorio e depois imprime algo na tela
class AguardaRand extends Thread {

    // ID da thread (usado para identificar a ordem que as threads terminaram)
    protected $id;

    // Construtor que apenas atribui um ID para identificar a thread
    public function __construct($id) {
        $this->id = $id;
    }

    // Metodo principal da thread, que sera acionado quando chamarmos "start"
    public function run() {
        // Sortear um numero entre 1 e 4
        $tempo_rand = mt_rand(1, 4);

        // Aguardar o tempo sorteado
        sleep($tempo_rand);

        // Imprimir quem e' a thread e quanto tempo ela aguardou
        printf(
            "Sou a thread %d e aguardei %d segundos\n",
            $this->id,
            $tempo_rand
        );
    }
}

//Execucao do codigo

// Criar um vetor com 10 threads do mesmo tipo
$vetor = array();
for ($id = 0; $id < 10; $id++) {
    $vetor[] = new AguardaRand($id);
}

// Iniciar a execucao das threads
foreach ($vetor as $thread) {
    $thread->start();
}

// Encerrar o script
exit(0);

Exemplo de Pipe:
for ($i=0; $i<10; $i++) {
    // abre 10 processos
    for ($j=0; $j<10; $j++) {
        $pipe[$j] = popen('script2.php', 'w');
    }

    // espera a finalização do processo
    for ($j=0; $j<10; ++$j) {
        pclose($pipe[$j]);
    }
}

Answer: Fork
Efetivamente, você copia toda a stack de memória do programa, criando dois processos distintos. O código passa a ser executado na linha seguinte a execução do comando que criou o fork.
Normalmente, forks são utilizados quando a comunicação entre as execuções não são tão frequentes, já que a comunicação entre tais processos só pode ocorrer mediante a modos de comunicação entre processos.
Threads
Todo o stack da execução do programa até o momento de criação das threads são compartilhados.
Isso facilita a comunicação entre as threads, porém torna necessário o uso de mecanismos de exclusão mútua (mutex) em alguns casos.
Pipes
Na verdade são forks, com uma única diferença: Ele permite a comunicação entre os processos com o STDIN / STDOUT. *Nota:: Essa diferença só existe no PHP, já que pipes na verdade são um método de comunicação entre processos.

Em relação aos códigos, não é possível comparar eles, já que os 3 são completamente diferentes!
Se reescrever eles para que os tornem com o mesmo objetivo (Dormir um tempo aleatório, então fechar), aí sim será possível.
Fork
$pid = pcntl_fork();
$pid2 = pcntl_fork();

if ($pid == -1) {
    die('Error.');
} else if ($pid) {
    pcntl_wait($status);
    printf("Processo child terminado (PID: %d, PID2: %d)\n", $pid, $pid2);
    exit(0);
} else {
    // Processo filho
    posix_setuid(1000); // Diminui as permissões do processo
    posix_setgid(1000);

    $sleep_timer = mt_rand(1, 4);
    sleep($sleep_timer);

    printf("Pronto... (PID: %d, PID2: %d) - Dormi: %d\n", $pid, $pid2, $sleep_timer);
}

Thread
class AguardaRand extends Thread {
    protected $id;

    public function __construct($id) {
        $this->id = $id;
    }

    public function run() {
        $sleep_timer = mt_rand(1, 4);
        sleep($sleep_timer);

        printf("Pronto... - Dormi: %d", $sleep_timer);
    }
}

$vetor = array();
for ($id = 0; $id < 4; $id++) {
    $vetor[] = new AguardaRand($id);
}

foreach ($vetor as $thread) {
    $thread->start();
}

exit(0);

Pipe
dorme_nenem.php
$sleep_timer = mt_rand(1, 4);
sleep($sleep_timer);

printf("Pronto... - Dormi: %d\n", $sleep_timer);

que_a_cuca_ja_vem.php
for ($j=0; $j<4; $j++) {
    $pipe[$j] = popen('php dorme_nenem.php', 'w');
}

for ($j=0; $j<4; ++$j) {
    pclose($pipe[$j]);
}

Agora que tem os códigos iguais, dá para comparar as diferenças.

Os stacks de memória são diferentes. Nos três:

No primeiro caso (Fork), a stack é copiada por inteira.
No segundo caso (Thread), o stack é compartilhado, a única coisa que não é compartilhado e é próprio de cada execução é a variável $sleep_timer.
No terceiro caso (Pipes), cada processo tem uma stack de memória inteiramente nova.

O thread executa a partir do local indicado para rodar, (função "run()"), já no fork ele executa no comando seguinte ao comando do fork, no pipe no começo do arquivo.

Em relação ao uso:
Não existem "indicações" para quando usar um e quando usar o outro. Antes, quando os processos eram tratados diferentes de threads pelo SO, até poderia ter, mas hoje em dia não há.
A recomendação geral é: Precisa de ter comunicação entre os códigos? Threads. Não precisa? Fork ou Threads.
A única nota que preciso deixar é: Não misture os dois. Se você fizer threads, depois fork, o fork irá copiar coisas do thread que não deveriam ser copiadas e em quase todas as linguagens dá pau.
Comment: fork cria outro processo, thread cria uma thread, pipes cria um processo epermite a comunicação entre eles, certo? porém você diz que os SOs já não fazem muita distinção entre thread e processos, é isso?
Comment: Exato @danilo! Foco no não fazem *muita* distinção, mas existe uma diferença absurda.
Se formos entrar em detalhes, a maior parte dos SO hoje em dia trata forks como outros processos separados (ou subprocessos) - o que pode ser visto facilmente no "Task Manager", enquanto threads a maior parte das vezes não é nem mostrado diretamente

Diferença entre Pipes, Fork e Threads


iOS Facebook SDK - FBLoginView

Question: For some reason I cannot get this code to work:
// Create Login View so that the app will be granted "status_update" permission.
FBLoginView *loginview = [[FBLoginView alloc] init];

loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;

[self.view addSubview:loginview];

[loginview sizeToFit];

I call it in the viewdidload of my ViewController.
I have :
#import <Social/Social.h>
#import <FacebookSDK/FacebookSDK.h>
#import <Accounts/Accounts.h>
#import <AdSupport/AdSupport.h>

And :
@interface FacebookVCViewController : UIViewController <FBLoginViewDelegate> {

The loginView is simply not showing up. What did I do wrong?
Comment: check it if loginview have UIView class type and also check rect of loginview
Comment: yeah its a uiview subclass.. and the origin x, y are : 50.000000 300.000000

    loginview.frame = CGRectMake(50, 300, 50, 50); doesnt change anything
Answer: Solution:
adding the FacebookSDKResources.bundle file to the project (making sure it copies it and adds to target) solves the problem.
FacebookSDKResources.bundle is located in:
 FacebookSDK/FacebookSDK.framework/Resources/FacebookSDKResources.bundle

Answer: Call this code inside of viewDidApear method hopefully it will work
Answer: This worked for me..
In interface Builder (Size Inspector) look for autosizing option.. REMOVE arrows in middle of box.. :) . No need to tweak with bundles or frameworks

iOS Facebook SDK - FBLoginView


How to efficiently do a sweep of many parameters to run a script in R?

Question: I have a script in R and it has 4 parameters that can be varied. I want to run a sweep with a few combinations of these parameters, and time these runs to compare them afterwards. Something like this:
dim_map = c(10,40,80,120)
epochs = c(200,600,1000)
dim_input = c(3,80,400,1000,3000)
datapoints = c(15000,50000,100000)
results = data.frame(dim_map = c(),
                     epochs = c(),
                     dim_input = c(),
                     datapoints = c(),
                     time = c()
)

for(dim in dim_map){
  for (epoch in epochs){
    for (m in dim_input){
      for (n in datapoints){

        t = Sys.time() # Start time

        ## Run some script

        elapsed_time = as.numeric(Sys.time() - t, units = 'secs')

        results[nrow(results)+1,] = c(dim, epoch, m, n, elapsed_time)
      }
    }
  }
}

Is there a way to do this avoiding loops? I feel like these nested loops are slowing down the sweep, but I don't know if this is just my imagination. Or maybe a better way to time the script with these parameter variation?
Comment: The number of combinations is 4x3x5x3 or 180 iterations, depending on the complexity of your script, could have a minimal impact.  I recommend checking out the microbenchmark package for more accurate timing.
Answer: I think one of the easiest ways to do this kind of thing is to combine pmap and cross_df from purrr. We can easily create all the combinations of parameters and then run our code for each of them, storing the results in a new column:
library(tidyverse)

params <-  cross_df(list(
  dim_map = c(10,40,80,120),
  epochs = c(200,600,1000),
  dim_input = c(3,80,400,1000,3000),
  datapoints = c(15000,50000,100000)
))

timer <- function(dim_map, epochs, dim_input, datapoints){
  start_time = Sys.time()
  Sys.sleep(0.01) # your code to time here
  end_time = Sys.time()

  return(end_time - start_time)
}

params %>%
  mutate(time = pmap_dbl(., timer))
#> # A tibble: 180 x 5
#>    dim_map epochs dim_input datapoints   time
#>      <dbl>  <dbl>     <dbl>      <dbl>  <dbl>
#>  1      10    200         3      15000 0.0110
#>  2      40    200         3      15000 0.0110
#>  3      80    200         3      15000 0.0110
#>  4     120    200         3      15000 0.0110
#>  5      10    600         3      15000 0.0110
#>  6      40    600         3      15000 0.0110
#>  7      80    600         3      15000 0.0110
#>  8     120    600         3      15000 0.0109
#>  9      10   1000         3      15000 0.0110
#> 10      40   1000         3      15000 0.0110
#> # ... with 170 more rows

Created on 2018-09-21 by the reprex package (v0.2.0).


How to affect kernel request hostname when bootstrapping from custom PHP script

Question: I'm bootstraping from a custom PHP script using:
$autoloader = require_once 'web/autoload.php';
$request = Request::create('/');
// $_SERVER['SERVER_NAME'] = 'whatever';
// $request->server->set('SERVER_NAME', 'whatever');
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
$this->kernel->prepareLegacyRequest($request);

When rendering a URL from that bootstrapped Drupal, via $item->link->getUrlObject()->toString(), it has a localhost hostname:
http://localhost/sites/default/files/styles/large/public/images/pages/1.JPG?itok=gSuAsMq-

I want to change that to whatever and I've tried what is commented out in the initial block which doesn't work. I've confirmed that the $request->server->set(..., ...); does set the value though.
Any idea on how to solve this?
Answer: You need to use the HTTP_HOST instead the SERVER_NAME, also you can pass it as $server param to the Request::create()
$autoloader = require_once 'web/autoload.php';
$request = Request::create('/', 'GET', [], [], [], ["HTTP_HOST" => 'whatever']);
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
$this->kernel->prepareLegacyRequest($request);

Remember to add the hostname to $settings['trusted_host_patterns']


What's the difference between global.css and default.css files in Omega theme?

Question: I´m still testing the Omega theme, and trying to get its templates and css files to work out for me. I´ve already read at the documentation and issues´ replies at Drupal forums.
They say:

Think of global as the 'mobile first' template and this this is where
  most of your css will go.

Ok, so for mobile I use only global.css and for other resolutions I use all the other templates.

The default template is for desktop resolutions where the css is
  different for that of mobile. The remaining templates are really just
  for exceptions and other values to address scaling up to wider
  resolutions.

This is what confuses me, because the other css files are narrow, normal and wide. So I think narrow should be for 7" screens, normal for 10" screens and wide for all the other, bigger screens (usually the desktop). So where fits default template?

Try resizing your browser window to see the changes between layouts.

I´ve tried that, setting just a line of code in every css file, determinig different body background colors for each case.
global.css showed on the mobile screen.
global.css showed on the 7" tablet on portrait mode.
narrow.css showed on the 7" tablet in landscape mode.
normal.css showed on the 10" netbook.
wide.css showed on the 19" desktop screen.
The color that I´ve set at the default.css file didn´t showed. I´ve took mozilla firefox and resized the browser manually, and all the other templates showed just fine, but default settings never appeared.
I´ve asked this at Drupal community forums, but I would like to know what you think about this. Thanks!
Answer: Ok, this is really one of the confusing aspects of Omega.  Once you grasp it, though, it does make life easier.
The full explanation is found in the Omega Theme Documentation Handbook under How CSS works in Omega - "Ogres are like Onions... They have LAYERS".
global.css applies to all layouts (hence the name).  Since they apply to all layouts, this is the mobile-first sheet.
mytheme-alpha-default.css applies to all of the non-mobile layouts, which is when the grids kick in.
Then the narrow, normal, and wide sheets stack depending on which breakpoint you are on.
So if you are mobile, you just get global.css
Narrow, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css
Normal, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css
Wide, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css + mytheme-alpha-wide.css
The best way to think about this is (in order):

How does my site need to look on mobile?  Make global.css
How do things change when the grid system kicks in?  Make mytheme-alpha-default.css
How does my site look when I am on a portrait table?  Make mytheme-alpha-narrow.css
How do things change when I am on a normal desktop?  Make mytheme-alpha-normal.css
How do things change when I am on a widescreen monitor?  Make mytheme-alpha-wide.css

In other words, don't think of this as four different layouts; think of it as a base layout that you apply changes to as you get wider.
Comment: Very well explained. It took me a while to bend my head round the whole mobile-first principle at first too, but as you say...once you do it does make life a lot easier


Elman networks Training algorithm

Question: What is the algorithm that is used to train an Elman Neural Network? and how it works?
And what is the role of the context layer in the Elman model?
Thank you.
Comment: [backpropagation through time](https://en.wikipedia.org/wiki/Backpropagation_through_time)
Answer: Backpropagation through time BPTT is the algorithm that is used to update the weights in the recurrent neural network. One of the common examples of a recurrent neural network is LSTM, Elman or Jordan nets. Backpropagation is an essential skill that you should know if you want to effectively frame sequence prediction problems for the recurrent neural network. You should also be aware of the effects of the Backpropagation Through time on the stability, the speed of the system while training the system. for more information visite
Backpropagation through time definition in Wikipedia
Comment: Done, the explanations has been added.

Elman networks Training algorithm


Group vs role (Any real difference?)

Question: Can anyone tell me, what's the real difference between group and role? I've been trying to figure this out for some time now and the more information I read, the more I get the sense that this is brought up just to confuse people and there is no real difference. Both can do the other's job. I've always used a group to manage users and their access rights.
Recently, I've come across an administration software, where is a bunch of users. Each user can have assigned a module (whole system is split into a few parts called modules ie. Administration module, Survey module, Orders module, Customer module). On top of it, each module have a list of functionalities, that can be allowed or denied for each user. So let's say, a user John Smith can access module Orders and can edit any order, but haven't given a right to delete any of them.
If there was more users with the same competency, I would use a group to manage that. I would aggregate such users into the same group and assign access rights to modules and their functions to the group. All users in the same group would have the same access rights.
Why call it a group and not role? I don't know, I just feel it that way. It seems to me that simply it doesn't really matter :] But I still would like to know the real difference.
Any suggestions why this should be rather called role than group or the other way round?
Comment: I disagree with @FastAl, I found the answers to this question better than those of the duplicate.
Comment: possible duplicate of [What's the difference between groups and roles?](http://stackoverflow.com/questions/3784990/whats-the-difference-between-groups-and-roles)
Comment: SEE THE DUPLICATE mentioned above. its top two short answers are both better than any of the ones here. (+technically groups and roles work the same its how they're used)
Answer: The divide between role and group comes from concepts of computer security (as opposed to simply resource management). Prof. Ravi Sandhu provides a seminal coverage of the semantic difference between roles and groups.
http://profsandhu.com/workshop/role-group.pdf
A group is a collection of users with a given set of permissions assigned to the group (and transitively, to the users). A role is a collection of permissions, and a user effectively inherits those permissions when he acts under that role.
Typically your group membership remains during the duration of your login. A role, on the other hand, can be activated according to specific conditions. If your current role is 'medical-staff' you might be able to see some of the medical records for a given patient. If, however, your role is also 'physician', you might be able to see additional medical information beyond what a person with just a role of 'medical-staff' can see.
Roles can be activated by time of day, location of access. Roles can also be enhanced/associated with attributes. You might be operating as 'physician', but if you do not have a 'primary physician' attribute or relation with me (a user with 'patient' role), then you cannot see my entirety of medical history.
You could do all that with groups, but again, groups tend to focus on identity, not role or activity. And the type of security aspects just described tend to align themselves better with the later than with the former.
For many cases, for the usage of classifying things together (and nothing more), groups and roles function just the same. Groups, however, are based on identity, whereas roles are meant to demarcate activity. Unfortunately, operating systems tend to blur the distinction, treating roles as groups.
You see a much clearer distinction with application or system-level roles - carrying application or system-specific semantics (like in Oracle roles) -  as opposed to 'roles' implemented at the OS level (which are typically synonymous to groups.)
There can be limitations to roles and role-based access control models (like with anything of course):
http://www.lhotka.net/weblog/CommentView,guid,9efcafc7-68a2-4f8f-bc64-66174453adfd.aspx
About a decade ago I saw some research on attribute-based and relationship-based access control which provide much better granularity than role-based access control. Unfortunately, I haven't seen much activity on that realm in years.
The most important difference between roles and groups is that roles typically implement a mandatory access control (MAC) mechanism. You do not get to assign yourself (or others) to roles. A role admin or role engineer does that.
This is superficially similar to UNIX groups where a user can/might be able to assign himself to a group (via sudo of course.) When groups are assigned according to a security engineering process, the distinction blurs a bit, however.
Another important characteristic is that true RBAC models can provide the concept of mutually exclusive roles. In contrast, identity-based groups are additive - a principal's identity is the sum (or conjunction) of the groups.
Another characteristic of a true-RBAC based security model is that elements created for a particular role typically cannot be transitively accessed by someone who does not act under that role.
On the other hand, under a discretionary access control (DAC) model (the default model in Unix), you cannot get that type of guarantee with groups alone. BTW, this is not a limitation of groups or Unix, but a limitation of DAC models based on identity (and transitively, with identity-based groups.)
Hope it helps.
=======================
Adding some more after seeing Simon's well-put response. Roles help you manage permissions. Groups help you manage objects and subjects. Moreover, one could think of roles as 'contexts'. A role 'X' can describe a security context that rule how subject Y access (or does not access) object Z.
Another important distinction (or ideal) is that there is a role engineer, a person that engineers the roles, the contexts, that are necessary and/or evident in an application, system or OS. A role engineer typically is (but does not have to be) also a role admin (or sysadmin). Moreover, the true role (no pun intended) of a role engineer is in the realm of security engineering, not administration.
This is a novel group formalized by RBAC (even if it seldom gets used), one which has typically not been present with group-capable systems.
Comment: Basically what you are saying is that: If you get the permissions list of a group you are looking at the role and if you get the users list of a roles, you are looking at a group.
Comment: Analogically, can we say that groups are like tree and roles are like tags ?
Comment: @ton - interesting analogy, and I never thought about it like that. I got to sit down and think about it. Thanks for the thought-provoking comment!
Comment: No. What happens is that many systems implement roles as groups (or worse, call groups "roles".) When that happen, you see the equivalence you just describe. Let me see if I can explain this better with a follow up reply.
Comment: One of the main differences is that group membership remains independently of your session (your logging session.) Your membership to a group changes only when someone (your or someone with enough privilege) changes it.
Comment: A role, not a group notion sold as a "role", but a true role, that role gets associated to the principal (aka "the role being active") when the principal starts a session (login session or app-specific session) **under that role.**
Comment: For example (a realistic example), I work in  a clinic in South Florida that is part of a chain of clinics. My unix id belongs to a group, say "fl-clinic", which gives me access to a variety of resources in the network that supports that clinic. Whether I'm logged in or not, I am a member of that group until someone with enough privileges changes that.
Comment: Now, I work not only in that clinic, but I'm a physician. So when I log in into  the medical systems at that facility, I'm automatically under the role of physician. But it just so happens that I also have access as manager or lead of other physicians or nurses, so I can 1) log out, thus de-activating my role of physician,and 2) logging back in as an "application admin".
Comment: My role as either is only "realized" when I'm logged in, independently of my membership to group "fl-clinic".
Comment: Moreover, and differently from groups, true roles can inherit from others (say, an "app admin" inherit capabilities present in an "physician" role, thus activating the former automatically activate the later.) Or they can be mutually exclusive (at any given login session, I can be one or the other, but not both.)
Comment: Groups, on the other hand, they have no such notions. Your group membership is the conjunction (the union set) of all groups that you belong to. Any notion of inheritance or mutual exclusion must be handled manually by someone with enough privileges to manage group membership. I hope this explains it better.
Comment: @luis.espinal, "- a principal's identity is the sum (or conjunction) of the groups."   Should this be "disjunction" as opposed to "conjunction"?  Conjunction is intersection and disjunction is union.
Answer: A group is a means of organising users, whereas a role is usually a means of organising rights.
This can be useful in a number of ways. For example, a set of permissions grouped into a role could be assigned to a set of groups, or a set of users independently of their group.
For example, a CMS might have some permissions like Read post, Create post, Edit post. An Editor role might be able to Read and Edit, but not create (don't know why!). A post might be able to Create and Read etc. A group of managers might have the editor role, while a user in IT, who is not in the managers group, may also have the editor role, even though the rest of his or her group does not.
So while in a simple system groups and roles are often closely aligned, this is not always the case.
Comment: So If I understand it right, you cant assign users to roles, but can assign users to groups. After that, you can assign roles to the group of users.
Comment: Not necessarily Ondrej. An application, system or OS *can* implement a mechanism for assigning a user to a role (it can get hairy very quickly, though). Simon's answer is spot on with roles as means to manage permissions (as opposed to groups as means to manage subjects and objects.)
Comment: Thank you guys, it's much more clear to me now. In the system described above, Ive just noticed, there is another mechanism to distinguish users. Each user assigned to any module can be more distinguished by its competency as a USER, SUPERVISOR and ADMINISTRATOR, which I guess, this is ROLE system :] So once more again, thanks both of you! ;)
Comment: i like your explanation, but for some reason no one here wrote about the possibility of a user belonging to more than one group... isn't it also possible for groups to belong to other groups and roles that allow assigning roles, and what about resources? can't resources also belong to groups? can't resources have roles?
Answer: A "group" is a collection of users. A "role" is a collection of permissions. That means that when group alpha includes group beta, alpha receives all the users from beta and beta receives all the permissions from alpha. Conversely, you could say role beta includes role alpha and the same conclusions would apply.
A concrete example makes things more clear.  Consider "customer support" and "senior customer support". If you think of those collections as groups, then it is clear that customer support users "includes" senior customer support users.  However, if you look at them as roles, then it is clear that senior customer support permissions "includes" customer support permissions.
In theory, you could simply have one collection type. However, it would be ambiguous if you were to say that "collection alpha includes collection beta". In that case, you can't tell if the users in alpha are in beta (like a role) or the users in beta are in alpha (like a group). In order to make terminology like "includes" and visual elements like tree views unambiguous, most rbac systems require you to specify whether the collection at issue is a "group" or a "role" at least for the sake of discussion.
Some analogies might help. Framed in terms of set theory, when group alpha is a subset of group beta, then permissions alpha are a superset of permissions beta. Compared to genealogy, if groups are like a tree of descendants, then roles are like a tree of ancestors.
Comment: Actually we can treat groups as roles (as [Mileta Cekovic says](https://stackoverflow.com/questions/7770728/group-vs-role-any-real-difference#answer-12332059)). For example, we can just assign a unique role for each group (1:1 relationship).
But we can't interpret relations between groups as relations between corresponding roles.
For example, if **group** "customer support" _includes_ **group** "senior customer support"
— it doesn't mean that **role** "customer support" _includes_ **role** "senior customer support".
Comment: Your explanation covers exactly why we can't just treat groups as roles (as Mileta answer suggests). Perfect example.
Answer: Although there is  semantic difference between Roles and Groups (as described above by other answers), technically Roles and Groups seems to be the same.
Nothing prevents you to assign Permissions directly to Users and Groups (this can be considered as a fine-tuning access control).
Equivalently, when User is assigned a Role, it can be considered a role Member, in the same sense when user becomes Member of a Group.
So we can end up with no real difference between Roles and Groups. Both can be considered for grouping Users AND/OR Permissions.
Thus difference is only semantic:
 — if it is semantically used for grouping Permissions, it is then a Role;
 — if it is semantically used for grouping Users, it is then a Group.
Technically, there is no difference.
Comment: If you add a group as a member of another group and both have associated permissions, additive permissions would work fine. That's how NTFS works. However, when we talk about systems I believe users think in terms of "let me logon as Financial", "let me logon as Guest", and in that case I think hierarchical roles would be confusing. I wouldn't allow anything but top-level groups to have associated permissions.
Answer: NOTE - the following ramblings only makes sense if one is trying to impose security within an organization - that is to say, trying to limit the access to information...
Groups are empirical - they answer the question of "what". They are the "is" in the sense they reflect the existing reality of access. IT people love groups - they are very literal and easy to define.  Eventually, all access control ultimately devolves (as we all learned back in middle school...) to answering the question "To what group do you belong?"
Roles, however, are more normative - they guide what "should be". Good managers and HR love "roles" - they don't answer - they ask the question of "Why?" Unfortunately, roles can also be vague and that "fuzziness" can drive (IT) people nuts.
To use the medical example above, if the role of "primary care physician" has more rights (i.e. access to more groups) than the role of an "x-ray technician", this is because people (managers and HR) decided why that needed to happen. In that sense they are "the collective wisdom" of an organization.
Let's say a doctor is given access (membership to a group with access) to financial records of patients. This is normally outside the "role" of a doctor and should be debated. So, no one (no matter how qualified) should have full access to all groups - it invites abuses to power. This is why "role engineering" is so important - without it, you just have group access handed out like so much candy. People will collect (and sometimes horde) group access with no discussion as to the dangers of too much power.
To conclude, the wisdom of well-defined roles helps moderate the dangers of runaway group access. Anyone in an organization can argue for access to a particular group. But once that access is provided, it's rarely given up. Role engineering (along with best-practices like well-defined group descriptions and empowered group access managers) can limit conflicts of interest within an organization, decentralize decision-making and help make security management more rational.
Answer: The previous answers are all wonderful.  As was stated, the concept of Group vs Role is more conceptual than technical.  We have taken the stance that Groups are used for containing users (a user can be in more than one group: i.e. Joe is in the Managers group as well as the IT group [he is a manager in IT]) and for assigning broad privileges (i.e. Our mag card system allows all users in the IT group access to the server room).  Roles were used to now add privileges to specific users (i.e. people in the IT group can RDP to servers but cannot assign users or change permissions, people in the IT group with the Admin role can assign users and change permissions).  Roles can be made up of other roles as well (Joe has Admin role to add users/privileges and also has DBA role to do database changes to the DBMS on the server).  Roles can be very specific as well in that we can make individual user Roles (i.e. JoesRole) that can be very specific for a user.  So, to recap, we use Groups to manage users and assign general Roles and Roles to manage privileges.  This is also cumulative. The Group the user is in may have Roles assigned (or a list of available Roles) that will give very general privileges (i.e. IT group users have the role ServerRDP that lets them log onto the servers) so that is assigned to the user.  Then any Roles the user belongs in will be added in the order they are defined with the last Role having the final say (Roles can Allow, Deny or not apply privileges so that as each Role is applied it will either override previous settings for a privilege or not change it).  Once all the Group level Roles and User level Roles have been applied, a distinct security model is created for the user that can be used throughout our systems to determine access and capabilities.
Comment: +1 for providing a very real  example, since the overlapping of these concepts means there is no real difference except in specific implementations. However, it doesn't make very clear the advantages you gained adding roles:
Your example of IT Users with the Admin role could just as easily be done by putting users in the IT Users and Admin _groups_. There's no real distinction between the implicit "permission" "allowed to RDP to" and the "role" : "can assign users".

Also you say that Roles can be made of other roles, but your example is Joe who has 2 roles, not a role that combines others
Answer: Users are assigned to Roles based on the responsibility they play in any system. For example users in role Sales Manager can perform certain actions such as provide additional discount for a product.
Groups are used to 'group' users or roles in a system for easy management of security. For example a group named "Leadership Group" can have its members from roles Managers, Directors & Architects and individual users who are out of these roles as well. Now you should be able to assign certain privileges to this group.
Answer: Purpose of Groups and Roles vary in applications, but mainly what i understood is as follow,
Groups(set of users) are static while Roles(set of permissions) are dynamic with policies, for example based on time from (9 to 6) a group or user may have this role but not that.
Answer: You can assign a role to group.  You can assign user to group and you can assign role to individual user in any role user.  Meaning.  Jean Doe can be in Group of SalesDeptartment with role off ReportWritter which allows to print our reports from SharePoint, but in SalesDepartment group, others may not have role of ReportWritter. - In other words, roles are special privileges withing assigned groups.  Hope this makes any scenes.
Cheers!!!
Answer: This works for us:

Manage user policies through groups (occasionally add additional policies manually to individual users)
Manage service policies through roles (for example a microservice might need access to S3 and it will be granted permissions via a role)
Answer: Besides all the good answers that explain what <code>Groups</code> and <code>Roles</code> are, one good reason I would consider using <code>Groups</code> instead of directly assigning <code>Roles</code> to <code>Users</code> is the ease of updating <code>Roles</code> if required as the software evolves.
It will be easier to update <code>Roles</code> of <code>Groups</code> as compared to doing the same for each user individually.

Group vs role (Any real difference?)


How to delete all Lines not starting with.. [Notepad++]

Question: I've got a rather large file (Over 1GB) which I'm trying to filter out the mass of.  I'd like to delete all lines not containing a specific url in them.
I'm unsure how I'd do this and am not familiar with expressions in Notepad++ so as basic of an answer as possible would be great.
Edit:  I'd like to do this for multiple files at once so if possible using the find in files tab would be best.
Answer: You could do:

Search the lines that contain the url:
in the search box, give your url and in the tab "marks" click on Mark lines then search all
Then in menu Search > Bookmark > invert bookmarks
Then in menu Search > Bookmark > Remove bookmarked lines.

I haven't an english version of Noptepad++ so the name of functions could be a little bit different.
Comment: @Mawg: That's what  said, I wrote "click on Mark lines" , I guess it is the same as "bookmark line". As I said I haven't English version of Npp.
Comment: @Mawg: Don't worry ;)
Comment: In English version it is `Search -> Bookmark -> Remove bookmarked lines`
Comment: I was going to suggest F3 followed by +L, but I like this answer better! Especially the "Marks" tab in the search, never knew what it was for...
Comment: Please note that this only works if you check the "bookmark line" option on the Mark tab. As described, it will not.
Comment: My apologies, I am feeling a little "Monday morning" :-)


$105$ games were played in a chess tournament, every player played with every other player, how many players participated?

Question: $105$ total games
$12$, $13$, $14$, $15$ or $53$ players?
Comment: $\large 29$ players.
Comment: @FelixMarin Where do you get this answer from? It's not even one of the given options.
Comment: @Dre Sorry. I was a mistake. It should be
$\large{1 + \sqrt{\vphantom{\Large A}841\,} \over 2} = 15$. The $\large 29$ in my mistake came from $\large\sqrt{\vphantom{\Large A}841\,} = 29$. See ${\tt @some1.new4u}$ answer. Thanks.
Answer: Let $n$ be the number of players. There was a game for every pair of players, so there must be $105$ pairs of players. An $n$-element set has $\binom{n}2=\frac{n(n-1)}2$ $2$-element subsets, so
$$\frac{n(n-1)}2=105\;.$$
You should be able to solve that for $n$ with little difficulty. Or you could simply test each of the choices to see which one satisfies the equation.
Answer: Hint: if there are $n$ players, each will play $n-1$ games, but each game will be counted twice.
Comment: so the answer is 15?
Comment: Yes, since $15\cdot14 = 2\cdot 105$.
Answer: Well, I don't know about chess, but sometimes it depends on the game you're playing. For example in a football(soccer) match, because we have home-away system, sometimes it's different that $A$ plays against $B$ or $B$ plays against $A$. In that case, the order matters, and if $m$ games are played, then the number of teams participating in the tournament is $n(n-1)=m$ because we can choose $n$ teams at first, and then we have to choose from the $n-1$ teams left, because a team can not play with itself. But if there is no home-away system, then each match is counted twice because the order doesn't matter and $A$ plays against $B$ is the same as $B$ plays against $A$, so the answer is $\displaystyle \frac{n(n-1)}{2}=m$ which is the same as the number of ways you can choose $2$ teams/players from $n$ teams/players to play against each other.
I believe chess doesn't have home-away matches and two individuals play against each other only once, so it must be $\displaystyle \frac{n(n-1)}{2}=105$:
$$ \frac{n(n-1)}{2}=105 \implies n(n-1)=210 \implies n^2-n-210=0$$
$$ \implies (n-15)(n+14)=0 \implies n=15.$$
Comment: good answer man
Comment: @user2635236 Thank you for your kindness.


Open login form in popup iframe? Using Colobox module?

Question: I have the login form block in my header. I removed it and in its place to put a 'login' link.
When clicking the link I'd like a popup (iframe or inline content) to show up. When the form is submitted the popup should close and then return and refresh the parent page.
I think the colorbox module is the right module to do this but I think that my request must be a frequently request and maybe there is an easier way to do this?
Thanks
Answer: I can confirm that the http://drupal.org/project/colorbox module is one of the easiest (and most supported) ways to have a lightbox for the login form.
There is also other benefits like being able to load AJAX content in the lightbox as well using 'colorbox-load'
Comment: Don't suppose you have read the README file - there is excellent documentation in there - http://drupalcode.org/project/colorbox.git/blob_plain/refs/heads/7.x-1.x:/README.txt
Comment: Can you please show me how to do it with colorbox?
Comment: I did it. I just included a hard code line: `LOGIN. The colobox popup shows up correctly, but with an error message: 'Request unsuccessful: Not Found'. I'm using Drupal 6.
Comment: I don't suppose you have done all the required installation steps, e.g. enable the module, and download the colorbox plugin, and then enable the "Enable Colorbox load" functionality in the configuration for the module? The 6.x README is here http://drupalcode.org/project/colorbox.git/blob_plain/refs/heads/6.x-1.x:/README.txt
Comment: Thats working fine
Comment: It used to work in the past indeed, but the current Colorbox module does not support login links any more -- see this post: https://www.drupal.org/node/883210#comment-6135172
Answer: You must try the Popups API (Ajax Dialogs) module.

API for building modal ajax dialogs. Its focus is on putting forms inside of ajax popup dialogs.
  Current example can present pages as popups (of the lightbox type). This is amazingly useful for things like confirmation pages. And the best part is it can be applied retroactively to a page without needing to modify the generating module, and (of course) it degrades gracefully.
Comment: thanks. Almost done. I installed the module, I set checked: "Scan all pages for popups links" and  add the class to the link to the form. Then I get the popup working fine. But I can't get the popup to get close and refresh parent page.

Here are the classes for the link that you can use:(I tried them all...) popups , popups-form , popups-form-reload, popups-form-noupdate.
Answer: There is nice Ajax Login/Register module, which demo site is here: http://ajax-register.drupalace.ru/
In the demo Ajax Login/Register uses standard Ctools modal theme but you can customize it as you want.
Answer: if people are going to carry on reading this this link appears to be worth a look:
Is loading an OpenID Provider in an iframe a bad idea if the provider and RP are on the same domain?
Comment: Hello, and welcome on Drupal Answers. May you expand your answer with a summary of what the linked page says? Answers that are merely a link to external sources are not considered answers, on Drupal Answers.
Answer: Recommending Modal Forms -- it only depends on CTools, and it's a pretty popular module.


how to redirect www.example.com to example.com via htaccess while on zend framework

Question: as you may know zend framework uses .htaccess for redirection purposes
so when I tried to follow this advice: http://techpp.com/2010/06/28/how-to-redirect-www-urls-to-non-www-urls-and-non-www-to-www/
in conjuction with the necessary .htaccess code for zend framework, the redirection works fine, but zend stopped working properly...
does anyone know how to achieve this task without messing up zend framework
current rules:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Comment: Can you post your current rewrite rules?
Answer: I have something similar in a project of mine. The following redirects a non-www requests to a www request:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

A similar thing should work for redirection from www to non-www:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule (.*) http://example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Comment: Thanks! I'd been searching for this all morning. Works perfectly.


Como usar o time_format() no MySQL?

Question: Fiz uma tabela assim:
create table tabela (
hora time not null
);
Essa tabela me retorna hora, minuto e segundo. Como fica a tabela com o time_format()? Quero deixá-la só com a hora e o segundo. Minha dúvida é na sintaxe (maneira de montar o time).
Valor retornado: 00:00:00.
Valor que eu quero que retorne: 00:00.
Motivo: eu tô capturando o horário de um formulário HTML (00:00) e salvando no banco de dados. Quando o horário é enviado do formulário para o banco de dados, o banco de dados o armazena assim: 00:00:00. Por isso eu quero que, na hora da criação da tabela, o time aceite este formato: 00:00.
Comment: Hora e segundo mesmo? ou seria hora e minuto?
Comment: Quero somente a hora e o minuto.
Answer: O time_format() recebe primeiro o campo e depois os parâmetros de formatação, para exibir hora e segundo ficaria assim:
select TIME_FORMAT(hora, '%H:%s') from tabela

Por via das dúvidas, segue também como exibir hora e minutos:
select TIME_FORMAT(hora, '%H:%i') from tabela

Coloquei no SQLFiddle para referencia futura
Comment: Dúvido que seja Hora:Segundo :)
Comment: Também acho, coloquei os dois formatos para garantir
Comment: Mas eu não quero o select, quero a sintaxe quando se cria na tabela.
Comment: @WillBill, desculpa, não ficou claro qual sua dúvida quanto a montar a tabela, o tipo `time` já é hora, minuto e segundo
Comment: @Barbetta, pois é, eu quero que o time seja só hora e minuto. Não quero no select, e sim quando se cria o time na tabela.
Comment: pelo que entendi você deseja que a tabela seja apenas hora e minuto(00:00), a primeiro momento, o que me vem a cabeça é salvar o campo como `varchar`.
Comment: Mas será que não tem como tirar os segundos na hora da criação?
Comment: Fiz uma pesquisa rápida aqui e não achei nada indicando que é possível fazer isso, talvez esse [link](http://www.mysqltutorial.org/mysql-time/) e esse outro [link](https://dev.mysql.com/doc/refman/8.0/en/time.html)  possam te ajudar

Como usar o time_format() no MySQL?


FileSystemWatcher on separate thread

Question: I have to create script which will push some files into provided location and grab the output generated by other script.

Copy files to location.
Other script will grab the files and process them.
Wait for all results.
Get data from files, remove files.
Repeat steps for next stack of files.

On my PC everything works fine but when I run my script on the machine where Windows Server 2016 is running some error pop-up:

So I created a SystemWatcher which is monitoring a provided location
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private void RunWatcher(string location)
    {
        // Create a new FileSystemWatcher and set its properties.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = location;

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                | NotifyFilters.LastWrite
                                | NotifyFilters.FileName
                                | NotifyFilters.DirectoryName;

            watcher.Filter = "*";

            // Add event handlers.
            watcher.Created += OnCreate;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // quit the program.
            while (!endWatcher);
        }
    }
    private void OnCreate(object source, FileSystemEventArgs e)
    {
        string fileExtension = Path.GetExtension(e.FullPath);
        if (extensionWatch.Contains(fileExtension))
        {
            SaveFileData(fileExtension, e.FullPath);
        }
    }

The watcher is created on separate thread. Then a "while" loop inside the "for" is checking if all files has been created or if the "Abandon time" has been exceeded.
    private void PushFiles(string destinationPath, int timeAbandon, BackgroundWorker worker)
    {
        Console.WriteLine("Before start watcher");
        Task.Run(() =>
        {
            RunWatcher(destinationPath);
        });
        Console.WriteLine("After start watcher");
        timeAbandon *= 60; // to sec

        for (int i = 0; i < fileCollect.Count; i++)
        {
            double timeDiff;
            start = DateTime.UtcNow;
            currentListIdx = i;
            CopyPtx(fileCollect[i], destinationPath);
            while (!CheckIfDone(i))
            {
                timeDiff = (DateTime.UtcNow - start).TotalSeconds;
                if (timeDiff > timeAbandon)
                {
                    break;
                }
                Thread.Sleep(1000);
                Console.WriteLine("Waiting for results...");
            }
            CopyAndRemoveFiles(fileCollect[i], destinationPath);
            worker.ReportProgress(1);
        }
        endWatcher = true;
    }

    private bool CheckIfDone(int stackId)
    {
        bool isDone = true;
        foreach (var file in fileCollect[stackId])
        {
            if (file["finished"] == "false")
            {
                isDone = false;
            }
        }
        if (isDone)
        {
            return true;
        }
        return false;
    }

I did have a look on Just-In-Time settings and "Managed, Native, Script" are selected. Also I use .net Core as I can't install any dependencies on the server machine.
To run the script on the server I do publish the script first with a following settings:

I tried to change the Configuration setting to "Debug|AnyCPU" but it didn't help.
Can anyone help me to get more information about the error? Or possible solution to my problem?
Comment: Did you try to attach a debugger to the program? Instead, add logging to investigate the actual error. I _bet_ it's an access denied issue.
Comment: `while (!endWatcher);` - **why??** No... You absolutely do not need this!
Comment: Unrelated: `string fileExtension = Path.GetExtension(e.FullPath);  if (extensionWatch.Contains(fileExtension))` - why not set the filter correctly, instead?
Comment: I think you really should try a deep dive into [DataFlow](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library).
Comment: @Fildor Thanks for your comments, I found a problem and it's related to one of my functions inside function SaveFileData so I don't think that this is related to the threads (I will post answer later). About filters. I need multiple filters and the answer for [link](https://stackoverflow.com/questions/6965184/how-to-set-filter-for-filesystemwatcher-for-multiple-file-types) didn't work form me.  Without    while (!endWatcher); loop my watcher is terminated even before my script copy the files.
Comment: _" Without while (!endWatcher); loop my watcher is terminated even before my script copy the files."_ - that's because you `use` it. Which you shouldn't. Create it and keep it until you exit your program without `use` and spin.
Answer: There was en error in function SaveFileData(fileExtension, e.FullPath);. The error appeard because I was trying to read file before saving into file was finished. So The title of this post is not correct.
To solve the problem with access to file I used a following code.
    protected virtual bool IgnoreErrorMsg(FileInfo file, string ignoreMsg)
    {
        bool isAccess = false;

        while (!isAccess)
        {
            try
            {
                using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    //if file can be read, then read it
                    if (stream.CanRead)
                    {
                        byte[] buffer = new byte[stream.Length];
                        int bytesRead = stream.Read(buffer, 0, buffer.Length);
                        string errorString = Encoding.ASCII.GetString(buffer, 0, bytesRead);

                        if (errorString.Contains(ignoreMsg))
                        {
                            return true;
                        }
                        // access has been granted so loop can be exit
                        isAccess = true;
                    }
                    stream.Close();
                }
            }
            catch (IOException e)
            {
                //the loop will continue as long as "cannot access" error appear
                isAccess = false;
            }
            Thread.Sleep(500);
        }
        //if return false, then script will wait for optimisation unitil AbandonTime
        return false;
    }

In that case the title of the post is not correct because it's not related to multithreading.

FileSystemWatcher on separate thread


How do you protect controller actions with Devise?

Question: I'm using Devise and a user can either be an admin or not (true, false).
Can someone help me figure out how to protect a controller action such as:
  def new
    @post = Post.new
  end

I know Devise lets you call administrators by using in views but can this be used in controllers?:
if current_user.admin?

Thanks in advance.
Comment: Is this a good way to go?

In my controller add a before filter

    before_filter :if_admin, :only => [:new, :edit, :create, :destroy]

and add a private method?
Answer: You can simply add a filter, this way:
class YourController < ApplicationController
  before_filter :check_access, :only => :new

  ...

  def new
    @post = Post.new
  end

  protected
  def check_access
    redirect_to <whatever> and return unless current_user.admin?
  end
end

or use CanCan or something like that, to hold restrictions nicely
Comment: in case of protected you will be able to use this filter in child controller, and in private case it can be accessed only from current controller
Comment: Your return is redundant as `check_access` is method and it is always return last operation result.
Comment: @alony that's not what protected vs private means in ruby. Check http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby
Comment: Thanks Alony, I was just thinking along the same lines. Why would one use "protected" and "private"
Comment: in case if the default route (match ':controller(/:action(/:id(.:format)))') is defined, protected/private clause would prevent user from accessing the filter as a normal action
Comment: @grzuy, I know what it means in Ruby, thanks :) I was talking about the effect it has while applied to controllers
Comment: @alony Still, the same rule applies for rails controllers.
Comment: +1. Have read it more thoroughly, yes, you're right. So neither protected nor private will be visible for routing from both parent and child controllers. Thank you, @grzuy


Aonde está localizado o código fonte dos comandos do Python3?

Question: Aonde fica o código fonte dos comandos do Python3? Quero ver o código fonte de comandos como len(), count(), find(), etc etc.
Eu uso Linux Mint, já olhei e olhei, mas não acho...
Quem puder ajudar agradeço!
Answer: O código fonte do CPython 3 fica nesse repositório. Você provavelmente não consegue achar porque tem instalado só o Python compilado, que não inclui o código fonte (o CPython, interpretador principal, é escrito em C).
Pros objetos built-in, funções como len são definidas no código em C. Por exemplo, dê um Ctrl + F procurando por "list_length" na fonte de uma lista.
Se você tem uma classe em Python que define a função __len__, então essa será a função utilizada pelo Python pra descobrir o tamanho do objeto, mas esse não é o caso pros built-ins escritos em C.


Yum, always install both 32 and 64 bit when available

Question: When using yum, is there a way to have both 32 and 64 bit packages installed whenever both are available?
I know I can specify *.i686 for individual packages... But I have a lot of errors that revolve around a missing 32bit package.
Answer: In /etc/yum.conf add:
<code>multilib_policy=all
</code>


Implications of running out of RAM on production server?

Question: We have a production server with 4GB of RAM running Debian with webserver and various other applications. Checking from the command line using htop, about 3.7-3.8GB of the RAM is used at any given time.
The server is not showing signs of slowness or unresponsiveness. Is it fine to run a server like this at near 100% RAM utilization, or can some problems arise in the future?
Output of free:
              total        used        free      shared  buff/cache   available
Mem:        3957164     3108136      189128       22348      659900      567960
Swap:       4108284      143104     3965180

Here's a screenshot of the htop output:
HTOP
(usually RAM usage is higher, the server was rebooted recently)
Comment: Does that include the memory used for cache? You should edit your question to include the output of htop. If you're actually using 95% of your RAM that gives you less of a buffer for sudden demands and reduces the file caching you can do. If you're actually using 2GB and 1.8GB is used as a file cache, you're fine, as the cache can be dropped any time memory is needed.
Comment: https://serverfault.com/questions/449296/why-is-linux-reporting-free-memory-strangely
Comment: Thanks Tim, I added the htop screenshot
Comment: Please run "free" and edit your question to include the output - suggest as text rather than screenshot.
Comment: If a server in the future needs more then 4G it will start to swapping. This will cause lower performance. If you don't have enough swap memory OOM killer will start to killing processes to free memory and to keep a system up.
Comment: Added "free" to the original question. Thanks again, Tim.
Answer: Approaching 0% available memory, the kernel will try increasingly drastic things to ensure some is available. Rapid paging out of RAM to storage can cause drastic slowdowns. The OOM killer reduces performance to zero when it kills processes. Still better than panicing and rebooting.
The key word is available memory. Linux will use any free memory it can for caches, which are automatically made available for allocation. Obligatory citation of the canonical FAQ: https://www.linuxatemyram.com/
htop there is reporting about 77% utilization and 1% page space use. Nice fully utilizing it, but the free output shows a few percent higher and its starting to swap.  A couple GB more RAM, up to 6 or 8 GB maybe, would be a nice buffer. Especially if it is one your production boxes.


Can't see IBOUTLETs when using StoryBoard with ZBARReaderView

Question: I am trying to write the embedded reader example in ZBar SDK using a story board and not NIB files.  I Declare my IBOutlets as so:
@interface MYQViewController : UIViewController < ZBarReaderViewDelegate >
{
    ZBarReaderView *readerView;
    UITextView *resultText;
}
@property (strong, nonatomic) IBOutlet ZBarReaderView *readerView;
@property (strong, nonatomic) IBOutlet UITextView *resultText;
@end

However when I create a ZBarReaderView View Controller on the main UIView and try click and drag to connect readerView as a referencing outlet, I just can't figure out how to connect it.  All I get from the primary ViewController is an option to select view.
Answer: Add a UIViewController to your Storyboard.
Add a UIView to the UIViewController, now you will have a UINavigationController > UIView > UIView. Give the child UIView the size you expect the reader area to be.
Create a class of type UINavigationController and add the following code to the interface.
@property (nonatomic, strong) ZBarReaderView* readerView;
@property (nonatomic, strong) IBOutlet UIView* skeletonView;

Add the following code to the implementation.
@synthesize skeletonView;
@synthesize readerView;

- (void)viewDidLoad {

    self.readerView = [ZBarReaderView new];
    self.readerView.readerDelegate = self;
    self.readerView.zoom = 1;

    self.readerView.frame = CGRectMake(0, 0, self.skeletonView.frame.size.width, self.skeletonView.frame.size.height);
    [self.skeletonView addSubview:readerView];
    [self.skeletonView sendSubviewToBack:readerView];
    [self.readerView start];

}

Set the UINavigationController class to the class that you have created.
Connect the child UIView to the UIView IBOutlet.
You are read to go and by doing that you don't need to hack anything and you can customize the child view with buttons and messages.


Markov Model for coin flips

Question: Suppose that we flip a fair coin and we win when we get for a first time HTH.Is there a way that we can construct a markov model with 4 states ??
Comment: Depending on what you intend to model (not clear to me) I presume the states keep track of how much of $HTH$ you have built up.  Thus the states are attached to $\emptyset, H,HT,HTH$.
Comment: Can you do the problem with more than 4 states? For instance, there's a reasonably straightforward Markov model with 8 states.
Comment: We can do it with $\left \{ H,T \right \}^{3}$.But I can't really see how we can reduce them to 4.
Comment: A markov model for what?  You get to flip forever until $HTH$ occurs?  That will happen with probability $1$ eventually.
Comment: Yes we get to flip until we get for a first time HTH.We may have infinite flips but we only take into account the last three flips.
Comment: I gave you the state space of size $4$.
Comment: Sorry I wrote it a little bit late , but thank you very much.
Answer: Let the set of states be $\{I,H, HT, W\}$. The transitions are as follows:

And the system starts in $I$.
This is a deterministic machine if we don't consider that the inputs are heads and tails with equal probability. Taking this into account then we can tell that every state transition takes place with probability $\frac12, \frac12$ from the actual state to the two allowed next states. Based on this the state transition probability matrix can be written up.
Comment: Also if I'm correct the initial distribution $\pi_{0}=(1,0,0,0)$ because we necessary start at I ?
Comment: Yes, that is the initial distribution.

Markov Model for coin flips


Matching algorithm for similarities

Question: I'm searching for algorithm, articles, books or whatever, about matching process. So currently I'm writing something like a DatingApp and I calculate a lot of matches.
So I search for an method which solves this issue
Thanks for any hint
Answer: I asked a similar question of the CS stack exchange and the top answer starts

The search terms you're probably looking for are "similarity measure", "dissimilarity", "distance function", or "metric"... applied to trees.
Comment: OK. Interesting would be also methods which operates on databases, which are regular not trees ;)
Comment: Yeah - I happened to be interested in trees, but only because you have some trees which share some branches, and other parts which differ. So you get this alike-but-not-the-same property...

Matching algorithm for similarities


Why does the quality of the sound of guitar strings decay over time?

Question: Particularly, on classical guitars, strings 4, 5 and 6.
At the beginning, the sound is very metallic. After a few weeks, it's like playing on coton.
Comment: Wash your hands before playing. Afterwards wipe the string with a towel. I can easily make my strings last a year that way.
Comment: Simple but, I think, efficient suggestion.
Answer: Your hands are dirty and sweaty.  The dirt is likely to stick in the grooves of the wound strings.  Sweat will coat the strings, and over time you can see they start to rust (or other similar processes).  One way to tackle this issue is to wipe off the strings with a towel after you have played.  It is also the reason why some bass players cook their strings, to clean them to make them last longer.
Another approach is to use coated strings (e.g. Elixir, but other brands also exist), which have a layer of plastic(?) coating to protect the strings.  I find that coated strings sound a tad bit brighter than non-coated, but that might just be me.  In my experience they do last a fair amount longer, so I use them on guitars I don't play too often where string changes are rare.
Comment: @Skippy - no, they rust. You can make them last longer by following morten's advice, but they will not get back to sounding anywhere near as good as new.
Comment: @DrMayhem : the only option would maybe be to play in a helium atmosphere ? :)
Comment: So in theory, after a careful cleanup, the sound quality would nearly be as good as at the beginning ?
Comment: Well, I cannot vouch for acoustic guitar strings, but in my youth (admittedly more than 30 years ago) in Germany I was pissed that the Fender electric guitar strings came pre-rusted.  Maybe from shipping, no idea.  I once substituted, uh, Musicman? strings which were bright and shiny and new.  Next time, returned to the pre-rusted Fender strings.  No real comparison.  So I'm not sure how good an indicator corrosion is, at least not when we are talking about non-human-related corrosion.
Answer: In addition to Morten's answer, there are a few other things that contribute to strings wearing out:

Strings, particularly the wound strings, develop dents or pits at the spot where they vibrate against the fret. This causes them to sound dead, and also contributes to intonation problems
Strings lose their elasticity over time. Tuning and retuning places strain on the string, and can cause it to wear out or break
The unwound strings will corrode as a reaction to the residue left behind by your hands
If you play with a pick, the pick will chew away at the windings on the wound strings

Tone Gear makes a little gizmo you can clamp on to your strings and run up and down the fretboard a few times to clean the strings. It does a good job of degunking strings, and can help you get more life out of them.
Comment: They will sound better, your sustain will be better, and the intonation will be better, but they'll never sound quite like they sound when they're new.
Comment: Would cleaning and degunking the strings make them sound as fresh as they do when they're new?
Comment: That makes sense; I've never cleaned my guitar strings. I'm going to give it a try.


Como eu acho menor ciclo de um grafo não dirigido?

Question: Eu consigo achar um ciclo em um grafo não dirigido. Mas eu não consigo pensar em um jeito de listar os vértices de cada ciclo, e nem achar o menor ciclo. Como eu faço isso?
Comment: Já fez alguma coisa? Pode especificar melhor sua duvida, o que você está tentando?
Comment: Estou tentando acabar o algoritmo para verificar se existe um ciclo no grafo. Eu queria listar todos os ciclos de um grafo não dirigido. E queria achar o menor ciclo desse grafo.
Comment: Posso te indicar onde procurar, o livro fundamentos matemáticos para ciência da computação, Judith L Gersting.
Comment: Se bem que tenho quase certeza que é um problema NP, por que o número de caminhos é fatorial se for um grafo completo.
Comment: Valeu cara, vou dar uma olhada!
Comment: É realmente um problema NP, acredito.
Comment: Olhe também este [tópico](http://pt.stackoverflow.com/questions/22245/o-que-%C3%A9-%C3%A1rvore-geradora-m%C3%ADnima), para ver se não ajuda na dúvida.
Answer: Existem diversos algoritmos, para grafos valorados, ou seja, onde cada aresta tem um peso, exemplos: Algoritmo de Dijkstra, Algoritmo de Bellman-Ford, Algoritmo A*, Algoritmo de Floyd-Warshall, Algoritmo de Johnson.
Porém como o encontro do menor caminho é um problema NP completo, as soluções são ineficientes, ou até matematicamente incalculáveis em números nem tão grandes. Se não me engano para grafos direcionados usava o algoritmo de Floyd-Warshall.
Answer: Primeiramente você deve dar peso 1 a todas as arestas existentes de seu grafo e peso INFINITO às arestas grafo[i][i] para todo vértice i. Também torne seu grafo pseudo-direcionado:
grafo[i][j] = 1
grafo[j][i] = 1

para quaisquer vértices i e j que estiverem conectados.
Geralmente, o peso na aresta grafo[i][i] é de 0, o que faz sentido quando você procura o caminho mais curto, já que não custa nada não se mover no grafo, mas se você mantiver dessa forma e executar os algoritmos abaixo, seu resultado final será apenas 0, já que o menor ciclo de um vértice até si mesmo vai ser sempre o caminho vértice i -> vértice i, ou seja, não se movimentar no grafo.
Dito isso, você pode executar o Algoritmo de Dijkstra para todo vértice i, usando i como o vértice inicial e final do algoritmo, ou seja, quanto custa chegar até o vértice i a partir do próprio vértice i (lembrando que a resposta não vai ser 0 porque você definiu que grafo[i][i] = INFINITO). E como os pesos das arestas são todos 1, o menor caminho lhe dará também o ciclo de menor distância. Executando esse algoritmo para todos os vértices você terá que grafo[i][i] vai ser o custo do menor ciclo no qual o vértice i está envolvido, para todo vértice i. Complexidade final O(n^3):
Dijkstra: O(n^2)
Executado n vezes, onde n é a quantidade de vértices no grafo.
Final: O(n^2) * n --> O(n^3)

Para achar o menor ciclo no grafo inteiro, execute o algoritmo acima e depois pegue min(grafo[i][i]) para todo vértice i, ou seja: pegando todos os ciclos no qual os vértices estão envolvidos, qual deles é o menor?!
E, finalmente, para listar os vértices envolvidos no menor ciclo, adicione ao algoritmo uma lista dos vértices anteriormente visitados no menor caminho (menor ciclo, nesse caso) entre quaisquer vértices i e j e retorne a lista do vértice i que fizer parte do menor ciclo encontrado por min(grafo[i][i]), como discutido acima. exemplo en.