What type of array do I send to constructor?

Question: I am creating a server-chat-client application and have borrowed code. I know how most of the things work except one.
In my Class Server I wait for a socket to be accepted.
public static ArrayList<String> clientUsernameList = new ArrayList<>();

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {

    int port = 8900;    //Port number the ServerSocket is going to use
    ServerSocket myServerSocket = null;  //Serversocket for sockets to connect
    Socket clientSocket = null;    //Listerner for accepted clients
    ClientThread[] clientsConnected = new ClientThread[20]; //Max clients in this server

    try {
        myServerSocket = new ServerSocket(port);
        System.out.println("Server waiting for clients on port:" + port);
    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }

    while (true) {
        try {   //Freezes while-loop untill a socket have been accepted or if some failure occur
            clientSocket = myServerSocket.accept();
            System.out.println("Client have connected from:" + clientSocket.getLocalAddress().getHostName());
        } catch (Exception e) {
            //Print out exception
            System.out.println(e);
        }
        //For-loop that counts every element in Array-clientsConnected
        for (int i = 0; i < clientsConnected.length; i++) {
            //If-statement checks if current element is null
            if(clientsConnected[i] == null){
                //If current element in the Array is null then create a new object from ClientThread class
                //With a socket and the object of itself as parameter.
                (clientsConnected[i] = new ClientThread(clientSocket, clientsConnected)).start();

                //Must have a break otherwise it will create 20 objects (Exit for-loop)
                break;
            }   //Exit if-statement
        }   //Exit for-loop
    }   //Exit while-loop

}

}
So if a socket gets accepted I create a thread class called Class ClientThread
To create a object of this class I need a socket and a array.
This is how my ClientThread class looks like
public class ClientThread extends Thread {

private ClientThread[] clientsConnected;
private Socket SOCKET = null;
private DataInputStream IN = null;
private DataOutputStream OUT = null;
private String userName,zone;
//-------------------------------------------------------
//Constructor
public ClientThread(Socket socket, ClientThread[] clientThread) {
    this.SOCKET = socket;
    this.clientsConnected = clientThread;
}

//Some more code
Now this is where I am lost. Do I send in my whole array? and if I do shouldn't user1 only get an array with 1 user and when user2 connects shouldn't he get an array with 2 users? I am lost. If someone could point me to something that explains this I would be grateful.
Answer:
Your code will serve only 20 requests. For each one it adds new value to clientsContected, once the whole table is full it will just go back to the start of the loop (without closing the accepted connection).
Probably the idea of passing the clientsConnected to the thread, was so it can set the value to null once it stopped working (so that your main code in the loop can assigne a new client to it). GUessin as no code is included). But for that an index inside the array would be useful (so 3 parameters instead of 2) so the ClientThread doesn't have to search the whole array to find object matching this.

I would rather recommend using BlockingQueue (with limited capacity for example 5) to which you will pass accepted connections. Once it is full your main will be forced to wait on it till it has same space to insert new connection so you will stop accepting new sockets. Create the 20 threads, that in a inifinite loop tries to get a socket from that queue and serve it. Once they finish they go back an wait for new request.
So yes you passs the whole array.

Still it doesn't solve the problem of what happens if all are busy, as you keep accepting new clients instead of waiting for free Thread.


What's a useful recurrence relation for $(2n)!$ in terms of $n!$?

Question: I want to make an algorithm for $n!$ which will divide the number in half and call the algorithm again until n is so close to $0$ that a value of $1$ can be safely returned, and use the value of each $\tfrac{n}{2}!$ to compute the value of $n!$ to be returned to the previous call, and so on, without using iterated multiplication. Here is an example of what I don't want to use:$$\begin{align}(2n)!&=\left(\prod_{n+1}^{2n}{k}\right)n!\\&=\binom{2n}{n}(n!)^2\end{align}$$ In fact, I want something that will work on any positive number, not just integers. Is there a recurrence relation that meets my needs in this regard?
Just to be clear, I'm not asking what you think is the most efficient way, as an approximation may be, and I'm not looking for a divide-and-conquer algorithm. I simply want to find a recurrence relation to test my theory with. This question is still open; if you know such a recurrence relation, please share it.
Comment: The reason I mention Gamma is that you want something "that will work on any positive number, not just integers." That is the Gamma function.
Comment: See the [Gamma function](http://en.wikipedia.org/wiki/Gamma_function) which extends factorial to real (and complex) numbers.
Comment: @JohnHabert, I thought I was very specific. I've already seen the formula for $\Gamma(2n)$, and it's a little bit too complicated for my purposes. And I don't want to use an approximation. I want to use an algorithm to build the value.$
Comment: @JohnHabert, that problem will be solved by getting so small the number is almost $0$. $0!=1$ by definition. Then just plug each factorial into the next higher one. In theory, it should work.
Comment: Okay. So let's try $1!$ with your method. We split in half and calculate $\frac{1}{2}!$, which is $\sqrt{\pi} \approx 1.7724$. How are you going to use that to get $1!=1$?
Comment: That's where the illusive recurrence relation comes in; whatever you multiply $\sqrt{\pi}$ by would make it smaller, and besides, the value of $\Gamma(\frac12)$ is actually $(-\frac12)!$. $\frac12!=\tfrac{\sqrt{\pi}}{2}\approx.886227$.
Comment: True enough. Forgot about the shift by $1$. Why not use the integral definition of Gamma and approximate it numerically to the desired precision?
Comment: @JohnHabert, I could do that, but I'm trying to prove that the other way is possible. I know the your way is probably faster, and close enough, but could you please answer the question I did ask, instead of arguing about it?
Comment: Sorry, I think I meant " **e** lusive."
Comment: Do you have any reason to think that such a recursion exists?
Answer: this is not a question of a recurrence relation, instead its  a question of divide and conquer technique to find the factorial, which wont be useful btw, complexity will remain same, as the numbers are eventually have to be multiplied. (This is not the same as merge sort, in merge sort one can gain advantage because of it is easier to sort already sorted lists)
Try asking it in computer programming section.
and yes, Recurrence relation will be used to find the complexity of the program, which should be
$$O(n)$$ even after using D&C.
Comment: This is more of a curiosity exercise than a really efficient solution. Frankly I want to see if it's possible, and I'm not satisfied with the existing algorithms. The way I see it, this is something that has not been tried before, and I'm willing to try it. All I need is some uncomplicated way of computing $(2n)!$ from $n!$.
Comment: Yes its possible to evaluate factorial using divide and conquer, you just need to set the condition if lower bound = upper bound then return that number, and in the function you can multiply those 2 lists. like $$f(0....[n/2]-1)*f([n/2]+1....n)$$, call this recursively. Use integer value of n/2 not real value of it. [x] represents greatest integer function here.
Comment: I'm not interested in lists. My question is essentially mathematical. I want to know a recurrence relation.


using .rodata and -fPIE in compliation

Question: I'm a student currently taking a computer structures course and I have an assignement for writing in aseembly and C. I've found an issue I don't quite understand. We were given a makefile for running the program, and when connecting to our school's servers it works as intended. The issue arises when trying to use the same makefile on my personal machine. One of the assembly files (and likely more as I continue working) utilizes a .rodata section. Attempting to use the makefile as it was given results in the following error:
gcc -g -o a.out main.o run_main.o func_select.o pstring.o
/usr/bin/ld: func_select.o: relocation R_X86_64_32S against `.rodata' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: failed to set dynamic section sizes: bad value
collect2: error: ld returned 1 exit status
make: *** [makefile:2: a.out] Error 1

attempting to add one of the following
-fpie -fPIE or -no-pie
in between
-o
and  a.out
results in the following error
gcc -g -o -fPIE a.out main.o run_main.o func_select.o pstring.o
/usr/bin/ld: cannot find a.out: No such file or directory
collect2: error: ld returned 1 exit status
make: *** [makefile:2: a.out] Error 1

I'm sorry if this is considered a silly question however I can't figuere it out.
The expectation was for the makefile to create all of the .o files and a.out, however the a.out file never works.
In addition writing the following: gcc -g -fPIE -o a.out main.o run_main.o func_select.o pstring.o still creates an error, specifically
gcc -g -fPIE -o a.out main.o run_main.o func_select.o pstring.o
/usr/bin/ld: func_select.o: relocation R_X86_64_32S against `.rodata' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: failed to set dynamic section sizes: bad value
collect2: error: ld returned 1 exit status
make: *** [makefile:2: a.out] Error 1

Comment: That's a misleading suggestion in the error message, it assumes you are using the compiler. Of course those flags have no effect on hand written code. You did not show your program but presumably you have not written it in a position independent way. If you nevertheless want to link it, you should counter-intuitively use `-no-pie`
Comment: That seems to have dont it! I must have failed to try `-no-pie` in that position, now I just have a run-time error for the output file lol. Thank you so much!
Answer: As per man gcc:
gcc [-c|-S|-E] [-std=standard]
           [-g] [-pg] [-Olevel]
           [-Wwarn...] [-Wpedantic]
           [-Idir...] [-Ldir...]
           [-Dmacro[=defn]...] [-Umacro]
           [-foption...] [-mmachine-option...]
           [-o outfile] [@file] infile...

-o requires outfile parameter. This should work:
gcc -g -fPIE -o a.out main.o run_main.o func_select.o pstring.o
Comment: You need to write position independent assembly or use `-no-pie` to link. No compiler flags will fix your code.
Comment: It didn't work for some reason, still says to recompile with -fPIE
Comment: Have you recompiled your object files before running the command I provided? If no: `rm *.o`, and rebuild all from scratch. Otherwise - provide us with exact error message.
Comment: I have done that. Could the other object file commands require the `-fPIE` flag?

using .rodata and -fPIE in compliation


Between a guitar and a ukulele what should one consider when choosing a new instrument to learn?

Question: I really want to learn to play a musical instrument. Ever since my "keyboard" lessons as a kid 3 decades ago - I have been put off.
I learned songs on keyboard by "rote" i.e., the instructor scribbled the notes for me to play and I had to memorize them. Over time I hated my music class. However, a friend recently suggested a stringed instrument such as guitar/ukulele might be something worth looking into as an instrument that does not require mastery of musical theory or reading music to be able to play songs.
I have absolutely abysmal/zero understand of musical theory. E.g.: I don't even know what a "chord" means and how a song is composed of chords (I know the definition of a chord, but don't understand it musically.)
My primary aim is to learn to play songs by ear, strum for fun with friends over or just meditate by playing for myself in a closed room, but being "good enough" at it to keep it interesting. I can set aside up to 3-4 hours a week for musical endeavors so something that's learnable over time within such time frames might fit my needs.
Between Guitar and Ukulele, what are the differences and other considerations that I might want to take into consideration when choosing an instrument to learn to play?
Comment: There's only one legitimate reason to play an instrument: because you want to, because you'd enjoy it. So pick whichever one you **want** to play. You're the only person that can answer that.
Comment: You should pick an instrument for which there is a lot of music played that you **love**. If you love rock or pop or country, then guitar or bass is more likely to thrill you. If you love classical, then you might do best picking your favorite instrument from the orchestra. BTW, it sounds like your early music teacher was not a good one, so I suggest you keep an open mind and try to forget that experience.
Comment: This question is worded too specifically and opinion-oriented. A better angle for this site would be something like "what are the pros and cons of starting with ukulele vs. guitar?"
Comment: Do you plan to sing too, or just play the instrument?
Comment: The answer is of course a matter of opinion, but one thing I have not seen mentioned is that there are a ton more songs/song books out there for guitar than ukulele.
Comment: No singing. Horrible voice for that :)
Comment: One thing to consider.  If you choose to start on a Uke, the Baritone Uke (largest) is typically tuned the same as the top four (treble side) strings of guitar so chords learned can be transferred to guitar should you choose to switch to guitar after starting on Uke.
Comment: I am 40 and I just (and by "just" I mean since the day before yesterday) began learning music on a concert ukulele. Before actually buying it I tried to learn a bit about the instrument itself, which I considered a stepping stone towards the guitar... then I stumbled upon the performances of people like Jake Shimabukuro, James Hill, Manitoba Hal, etc. and I discovered that the ukulele might give you *a lot* of satisfaction by itself. I still do not know how far I will be able to go and I have no experience whatsoever but I now think it is mistake to consider the ukulele as a guitar surrogate.
Answer: They're very similar in terms of technique. Differences:

Ukulele is 4 strings, meaning it's always pretty easy to fret a chord, since you have one finger for each string. Guitar's 6 strings mean you have to use barre chords for 5- or 6-string chords, and that is always a pain point for beginners.
The ukulele is smaller than guitar, so stretching to reach chords in low positions is easier. But on the other hand, it becomes impractical to play chords up high because the frets get too close together.
Since ukulele has only 4 strings (and in a reentrant tuning), it doesn't have much range. It's harder to be creative and find patterns that aren't just the same chords over and over.

Other differences:

A steel string acoustic guitar is usually much louder than a ukulele.
A steel string guitar will be more uncomfortable to play at first until you build up callouses.
A guitar is a more flexible instrument with a wider range of notes and tones, and you can use the same knowledge to play electric guitar, which has a vast tonal palate. There are electric ukuleles, but they are still not as flexible as electric guitars.
Despite the ukulele's recent popularity, there is still a lot more literature (sheet music, YouTube lessons, magazines, web sites, etc.) available for guitar.
Comment: Naming bar chords as an argument against guitar is a bit strange. It's not like just because the strings are there you must play 5- or 6-string voicings all the time. And lots of stuff can be played with open chords, especially if using a capo.
Comment: bar chords are only a problem at the beginning, with some practice you don't think about it anymore.
Answer: Several questions in one here. Which instrument, to start with. Ask yourself which instrument stands out most in the music you listen to. If in your mind, you imagine yourself on stage at a stadium wielding that guitar, then there's an answer. If you find yourself humming the bass line from pop songs, there's your answer.
Next - do you want to learn to play an instrument, or get deep into music - what makes it all work? We're straying into the 'theory' territory here, but to play an instrument by ear, as probably half (my guess) do, is no bad thing, and a lot of pleasure - for you and your listener - can be realised with little or no deep knowledge of why it all works. Strumming chords and playing riffs on guitar is a lot of fun, and works for many.
However, if you have a desire to understand what's going on, the guitar, although it's almost instant satisfaction (play three chords, and your inventory of songs is in the thousands), it's not the best for explaining on.
Keyboard comes into its own here - graphically set out, easy to see which notes fit with which, but hard(er) than guitar to play convincingly.
Uke. Easier than guitar with only 2/3 of the strings. Easier to take into work for a 10 minute play at lunchtime. Cheaper to buy initially. Quite limited as to the sounds it produces. Maybe harder to find others who play similar instruments. Fewer resources. Playing pop songs lacks that certain something.
And what style of music you see yourself playing will have great bearing on the choice of instrument. Bear in mind there are several kinds of ukes, just as there are guitars.
Your choice in the end. This is just food for thought. Or the food of love. Play on...
Comment: You made some good points in terms of what things to take into consideration as part of the decision.  I see that the question was closed as opinion based (but was still able to upvote your answer) but you and others have added valuable information for those who have a similar dilemma.   I edited the question (to remove opinion) and voted to re-open. Please check my edits and add your vote to reopen if you agree.  Thanks
Comment: @Tim - my imagination almost "always" leads me to a piano. I've always thought it'd be "easier" to learn music - theory and practice, on it. However, owning a piano isn't possible (for me) and not sure how I'd go about practicing it. Perhaps I could buy a decent keyboard.

My goal is to pick up the easiest instrument to learn music with a faster feedback loop to keep me motivated. The flute "blowing practice" was total turn off.
Comment: I won't sing definitely - too hoarse for it. But would love to play music - I enjoy symphonies every once in a while and would love to play some of my favorite songs (by the ear). I don't aim for concert level performance but do aim for "better than average" capability i.e., _if_ someone asks me to play on stage (work event, neighborhood show etc.,) and I ace that, that'd be "good enough" for me. Anything beyond that is a bonus but not aiming for it
Answer: Between ukulele and guitar, ukulele is almost definitely easier, although probably less versatile, but which instrument you learn should depend on your goal.
I love the keyboard/piano as a starting instrument, ESPECIALLY if the goal is to learn more instruments later. There just isn't any way to visual music like the keyboard, and learning piano will drastically improve attempts to learn other instruments later.
Starting on chording instruments like guitar and ukulele leads to much abstraction from the actual music (instead of really understanding chords, many beginner guitarists think of them simply as shapes for the fretboard) which, while not disastrous, definitely makes it harder to learn music.
That being said, if your goal is just to be able to play music, like at a campfire or with friends or whatever, then learn guitar. Super versatile and if you don't plan on having an in depth understanding of music theory, it probably won't impair you too much to lose that keyboard visualization.
Ukulele is also a great choice because of portability and ease of learning, but its use cases are limited by its low volume and, shall I say, specialized sound. (I love the sound of the ukulele, but it isn't for every setting)
Comment: What's the difference between shapes for the fretboard and shapes for the keyboard? I have taken three college level music theory classes, I sight read, I write, etc., and I still view chords as shapes on both keyboards and guitar. To me, that's a **good** thing.
Comment: @ToddWilcox Because on a keyboard all of the notes are laid out in a row, it's easier to think of the different notes of the chords as intervals. Think about how on guitar, most people learn chords by looking at tabs that show pictures of how to play the chord, whereas on piano, at least I was taught by learning the actual structure of, say, a major chord (root, third, fifth) and applying that in whatever key I'm in.
Comment: I just look at it differently from you is all. It's all shapes to me. Shapes that line up in a row are still shapes.
Comment: @ToddWilcox I guess what you mean is that in practice -- like when you're actually playing piano/guitar -- our brains use muscle memory (i.e. shapes) to quickly move to the next chord. I was kind of focusing in on the visualization of the individual parts of a chord. Interesting discussion!
Answer: Between guitar and ukulele, I would recommend the ukulele for you to start with. Here is why:

Ukulele is easier for a beginner. It has fewer strings, making chord shapes easier. Because it is smaller, it is easier to hold. The nylon strings are easier on your fingers than the steel strings of a guitar.
Ukulele is more portable. It is smaller and lighter, and is easier to take with you anywhere you want to go.
Ukuleles are less expensive. Because of their smaller size, you can purchase a good ukulele for less than you could a good guitar.
Ukulele can prepare you for guitar. If you decide in the future you want to "upgrade" to guitar, your time spent with a uke will not be wasted. Chord shapes, strumming rhythms and techniques, and songs are all transferable to the guitar.
Comment: @Tim Not a problem. Age means nothing. If his hands are larger than average, then pick up a concert or tenor uke instead of a soprano.
Comment: OP's in his 40s, probably with quite large fingers. One point against a uke, maybe?
Answer: WOW!  I don't know where your friend got the information.  In my opinion the guitar, and string instruments in general, are pretty difficult to learn.  Keyboard is usually thought of as easier.  I think you had a bad experience and that was unfortunate.
Your goal is not 100% clear.  Do you want to learn a guitar like instrument or learn music?
I would say take vocal lessons.  That will teach you to learn the instrument you were born with while also getting your ear in tune.  Many instrument teachers encourage voice lessons or incorporate voice in their lessons for just this reason.  By rote is an important learning technique because at the end of the day you typically learn by doing and when we learn to speak we learn to imitate.
with all due respect if you are serious I'd find someone to take lessons from, explain your situation and see if you can find someone good.  Video lessons, and self teaching methods, can cause more harm than good since you don't have someone to critique what you are doing.  There are too many opportunities for confusion and misunderstanding.
As for Guitar versus Uke.  Just pick one based on what you see yourself doing in the future.  Which do you want to play?
Comment: I might have to vote to close the question as opinion based because I learned both guitar and piano and guitar was MUCH easier. I've also learned a bit of violin and clarinet and trumpet and the only thing easier than guitar that I've dabbled in was harmonica.
Comment: It depends on what you consider "learning".  I've played violin, classical upright bass, baritone horn, guitar, uke, and a few others.  Violin and bass were considerably harder to learn intonation (being fret-less instruments) but by far Guitar was hardest to develop any real skill on as it is a multi-voice instrument with multiple ways to play a single voicing.  Comparing classical solo guitar to classical solo bass, I'd say guitar was way harder than bass.
Comment: And, I should have mentioned keys.  Again, I think hard vs easy is relative to the performance level you are aiming for.  Key lab is a requirement in most music school programs regardless of your main solo instrument.
Comment: @ToddWilcox Todd you were correct to vote to close the original question as opinion based.  I edited the question and voted to re-open.  Please consider adding your vote.


OpenDialogCommand how to include Buttons in dialog_options

Question: How can I inlcude buttons in OpenDialogCommand?
<code>$options = [
        'dialogClass' => 'my-dialog-class',
        'width' => '700px',
        'buttons' => [
          'text' => 'Continue',
          'class' => 'btn-primary ok-button',
          'click'=> "function() { $(this).dialog('close'); }",
  ],
      ];

      $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
</code>
This seems not to work. The class is set, but no buttons are shown.
Answer: In the $options array the element "buttons" must be a "multiple" array.
For example:
<code>$options = [
  'dialogClass' => 'my-dialog-class',
  'width' => '700px',
  'buttons' => [
    [
      'text' => 'Continue #1',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
    [
      'text' => 'Continue #2',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
  ],
</code>


Trouble understanding/importing packages

Question: I have 2 folders inside myproject directory.
The structure looks like this:
myproject
|
|-- graphs
|     |--------contains Graph1.java, Graph2.java
|
|
|-- gui
      |--------contains GUI things, like MainWindow.java

I'm trying to import the classes in graphs in MainWindow.java. Both Graph1.java and Graph2.java have package graphs; declared at the top of the files. In my MainWindow.java, I'm trying to import Graph1.java and Graph2.java.
When I type import graphs.* in MainWindow.java and try to create new instances of the classes to be imported, it gives me a compile error, saying it cannot find said package/symbol. What am I doing wrong?
EDIT: I try to compile with javac MainWindow.java inside the directory containing MainWindow.java, and it gives me these errors:
error: package graphs does not exist
error: cannot find symbol (for Graph1, Graph2)
Comment: Please post a [mcve], and show how you compile: if you use the commandline: post the commands you used to compile and where relative to these directories.
Comment: See this answer and if it helps. [Where to put packages](https://stackoverflow.com/questions/23759812/where-to-put-java-packages-i-want-to-import)
Answer: the other classes are not in your class path, i.e. the compiler doesn't know they even exist, when you compile you have to specify the class path explicitly.
see: javac : Compiling a .java file which uses other classes in it
that being said I would highly suggest using a proper IDE like eclipse,intellj, VScode and use a build tool like maven. it worth the effort as adding more and more classes and jars that you need will mean bigger class path to manage


Adicionar sub propriedade dinamicamente

Question: class ObjetoSimples{
   var $nome;
   var $cargo;
   var $turno;
}

class ObjetoComposto{
    var $nome;
    var $setor;
    var $equipe;
}

Como adicionar novo nome com turno e cargo na equipe?
Por exemplo:
ObjetoComposto->novo($this->nome,$this->setor,$this->equipe->novo(nome,cargo,turno))

Comment: já vi com uso de arrays, mas estou querendo evitar matrizes multidimensionais, e como estou inciando em orientação à objetos, me vi neste complexo de niveis e subniveis de variaveis. Seria possível atualizar a equipe através do ObjetoComposto sem interferir no seu setor e no seu nome?
Answer: Fazer como um array associativo realmente é uma solução, até porque um objeto não deixa de ser um. Concordo que é uma bela gambiarra e deve ser evitado a não ser quando realmente faça sentido.
Então é só criar o objeto do jeito tradicional. Primeiro cria um objeto auxiliar, aí inicializa cada propriedade, sendo que a que terá um objeto usará este objeto auxiliar. O básico é assim, não tem jeito.
Outra técnica é criar um construtor na classe para facilitar a criação do objeto. Como o construtor padrão do PHP é muito limitado e criaria outros problemas no código eu prefiro (ainda que isto não seria o ideal em outra linguagem) criar funções estáticas que funcionam como construtores, assim libera o construtor sem parâmetros e permite uma espécie de overloading dos construtores.
Então criei um construtor que recebe todos os argumentos necessários para preencher todas as propriedades, inclusive a que é um objeto que será criado nesse "construtor".
Criei um outro construtor que pega só os argumentos para preencher as propriedades e exige que seu código crie uma instância da propriedade que é um objeto. Neste caso, pra facilitar também criei um "construtor" para criar este objeto.
Em outra linguagem isto poderia ser feito de forma mais suave.
Não sei se este é o melhor jeito porque não faço OOP em PHP, mas é o mais óbvio pra mim.
class ObjetoSimples {
    var $nome;
    var $cargo;
    var $turno;
    public static function construtor($nome, $cargo, $turno) {
        $obj = new ObjetoSimples();
        $obj->nome = $nome;
        $obj->cargo = $cargo;
        $obj->turno = $turno;
        return $obj;
    }
}

class ObjetoComposto {
    public static function construtor($nome, $setor, $nome2, $cargo, $turno) {
        $obj = new ObjetoComposto();
        $obj->nome = $nome;
        $obj->setor = $setor;
        $obj->equipe = new ObjetoSimples();
        $obj->equipe->nome = $nome2;
        $obj->equipe->cargo = $cargo;
        $obj->equipe->turno = $turno;
        return $obj;
    }
    public static function construtor2($nome, $setor, $obj2) {
        $obj = new ObjetoComposto();
        $obj->nome = $nome;
        $obj->setor = $setor;
        $obj->equipe = $obj2;
        return $obj;
    }
    var $nome;
    var $setor;
    var $equipe;
}

$obj = new ObjetoSimples();
$obj->nome = "joao";
$obj->cargo = "gerente";
$obj->turno = "noite";
$obj2 = new ObjetoComposto();
$obj2->nome = "maria";
$obj2->setor = "fabrica";
$obj2->equipe = $obj;
$obj3 = ObjetoComposto::construtor("maria", "fabrica", "joao", "gerente", "noite");
$obj4 = ObjetoComposto::construtor2("maria", "fabrica", ObjetoSimples::construtor("joao", "gerente", "noite"));

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Muito obrigado Bigown, o construtor2 foi uma bela solução, não havia cogitado esta ideia, mas é exatamente a estrutura que deve ser aplicada, funcionou perfeitamente!

Adicionar sub propriedade dinamicamente


Querying DynamoDB table by hash and range key

Question: I want to query DynamoDB table by hash and range key, using AWS SDK for Ruby V2. Following code can work.
dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo'],
      comparison_operator: 'EQ'
    }
  }
)

But, I want to set multiple items to range key condition.
Like this:
dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo', 'bar'],
      comparison_operator: 'EQ'
    }
  }
)

This code returns lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call': One or more parameter values were invalid: Invalid number of argument(s) for the EQ ComparisonOperator (Aws::DynamoDB::Errors::ValidationException).
I've tried to use IN operator.
dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo', 'bar'],
      comparison_operator: 'IN'
    }
  }
)

It returns lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call': Attempted conditional constraint is not an indexable operation (Aws::DynamoDB::Errors::ValidationException).
How do I query DynamoDB table by one hash key and multiple range keys?
Comment: You can't. `KeyConditions` does not support the `IN` operator. See my answer to [this question](http://stackoverflow.com/q/30589635/627727).
Comment: Thanks a lot. It means that `query` method can't be set multiple range key as query condition?
Answer: The Query operation only allows the following operators on the Range Key:
EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN

For a Query operation, Condition is used for specifying the
  KeyConditions to use when querying a table or an index. For
  KeyConditions, only the following comparison operators are supported:
EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN
Source:
  http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html

You can still meet the requirements by using a FilterExpression :
:filter_expression => "RANGE_KEY_NAME in (:id1, :id2)",{ ":id1" => "hoge",":id2" => "foo"}

However the consumed provisioned throughput will be based on the query returned results rather than filtered result set.
Another option would be to send multiple GetItem requests (each one with a possible Range Key value) via BatchGetItem. The result would contain only the matching records:
resp = dynamodb.batch_get_item(
  # required
  request_items: {
    "TableName" => {
      # required
      keys: [
        {
          "AttributeName" => "value", #<Hash,Array,String,Numeric,Boolean,nil,IO,Set>,
        },
      ],
      attributes_to_get: ["AttributeName", '...'],
      consistent_read: true,
      projection_expression: "ProjectionExpression",
      expression_attribute_names: { "ExpressionAttributeNameVariable" => "AttributeName" },
    },
  },
  return_consumed_capacity: "INDEXES|TOTAL|NONE",
)

Source : http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html
Comment: `batch_get_item` is the solution! Thank you!


Prevent browser URL from changing during page redirect in an SSL configuration using IBM HTTP server

Question: I have installed ibmhttp server as a plugin in websphere application server. I also configured httpd.conf file to allow for ssl connections and this serves the application as expected, however, two issues arise:
I noticed that after entering the URL to launch my app @ https://localhost/application-name, it redirects to the URL specified in the application's configuration. What I want is to have the https://localhost/application-name url, while the content of the application is served without changing the url to the application's configuration URL
I want to be able to type in the browser's URL address bar only the application-name and the URL should change to the localhost
For the httpd.conf file, after enabling the SSL module by uncommenting the  LoadModule ibm_ssl_module modules/mod_ibm_ssl.so and Listen 0.0.0.0:443,
I have the following virtual host declaration
<code>    <VirtualHost *:443>
     SSLEnable
     SSLProtocolDisable SSLv2
    </VirtualHost>

    <VirtualHost localhost:443>
     SSLEnable
     SSLProtocolDisable SSLv2
    </VirtualHost>

    KeyFile "C:/Program Files (x86)/IBM/HTTPServer/ihskey.kdb"
    SSLDisable
</code>
Comment: This is not the part of the configuration that's responsible of your redirect. Find the configuration that does the current redirection. If you can't figure it out by yourself, we could then help you with it.
Answer: When you find the rewrite config then you will need to add the passthrough|PT option to the rewrite rule.
http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule
http://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_pt


Formatar CSS com PHP

Question: Olá
Eu estou exibindo um conteudo HTML com formatação em CSS utilizando o print_r do PHP, mas estou com duvida quando as aspas simples, eu abri o STYLE com aspas simples, mas dentro da seleção da imagem tem 2 aspas simples tambem, mas não esta funcionando, como eu formato isso corretamente ?
<?php print_r("

"); ?>

Comment: tenta usar echo em vez de print_r
Answer: Neste caso não é necessário colocar o caminho url com aspas pode ficar simplesmente url(../img/banner-product.png), ficando:
print_r("

");

outra forma, também poderia ser:
print_r('

');

Mas também se pode escapar as aspas da seguinte forma, \" ou \', dependo de como se envolve a string, o seja se é com aspas duplas ou simples.
Exemplo:
print_r("

");

Answer: Não seria algo com \" ?
<?php print_r("

"); ?>

Answer: Tente usar o caractere de scape: \'
Use o seguinte código:
<?php echo '

'; ?>

Formatar CSS com PHP


OpenCL: offset for accessing float2*/float4*/... elements

Question: I currently have something like this in my kernel code:
func(__global float2 *array, __global float *buffer) {
    float *vector[2];
    vector[0] = array.s0;
    vector[1] = array.s1;

So I can do something like this later in the code:
vector[vec_off][index] = buffer[i];

Basically, I want to be able to access the elements of a float2 in my code based on a calculated index. The point is to be able to easily expand it to a float4/float16 vector later on.

Currently I get a (-11) error (CL_BUILD_PROGRAM_FAILURE) when I try to do vector[0] = array.x; Which I guess means I'm not allowed to write it (like that?) in OpenCL.
If it's not just a syntax error, I should be able to do this by accessing each element of array using an offset, so I would have:
array.s0 = array
array.s1 = array + offset
...
array.sf = array + 15 * offset

I do not know however how a floatn is stored in memory. Is the .s1 part stored right after the .s0? Is that is the case, then offset would just be the size of array.s0, right?

Thank you.
Answer: To be able to use calculated index to access float2 elements you can use union or cast directly to float*:
1. Using union
Define the following union:
union float_type
{
    float2 data2;
    float data[2];
};

and then cast float2 array on the fly and access elements using calculated index:
func(__global float2 *array, __global float *buffer) {
     float foo = ((__global union float_type*)array)[1].data[1];
}

2. cast to float*
func(__global float2 *array, __global float *buffer) {
     float foo = ((__global float*)&array[1])[1];
}

Comment: @MaiLongdong can you elaborate?
Comment: Devs tend to use `union` approach (I think for better readability) but casting directly works fine too.
Comment: Thanks. Do you know why the way I did it in the question works in C but not in OpenCL?
Comment: `Currently I get a (-11) error (CL_BUILD_PROGRAM_FAILURE) when I try to do vector[0] = array.x;` - this is failing because you are trying to assign a value to a pointer. Even if you would change it to `vector[0] = &array.x` this will still fail but on an attempt to get an address of vector element.


Mis-typed crontab line caused strange operation

Question: So, I meant to put in the following entry in my crontab:
<code>*/5 * * * * /command/to/run/every/5/minutes
</code>
but accidentally typed
<code>**/5 * * * * /command/to/run/5/times/a/minute
</code>
So, the command ran 5 times in immediate succession. Is this an unexpected behavior, or some poorly documented way to run things multiple times.
I am running Centos 6 and cronie-1.4.4-7.el6.x86_64
Comment: The RPM is for CentOS 6 but you said you are on CentOS 5. Can you double check what you wrote and maybe edit your question with the correct detail.
Comment: Could you let us know what your distribution and cron version are?
Comment: I am using Centos5 and running cronie-1.4.4-7.el6.x86_64
Answer: For what it's worth, I do not observe this behavior on CentOS 6. What I do see is that the job runs every minute, which is what you would expect.
The fields are a sequence of ranges or values. The double asterisk is obviously a typo, but according to the man page, the asterisk is a replacement for the "first-last" range. So you have two ranges there. "0-59" (every minute) and "0-59/5" (once every five minutes). The union of these is "every minute" which is what I am seeing.
If your job ran 5 times in rapid succession (i.e. more than once a minute) you should look elsewhere for the reason. It is not the crontab line.
Comment: Strange thing is, when I corrected the typo, it was only running once per 5 minutes.
Comment: Once per five minutes is the expected behavior of `*/5`.
Comment: I understand that its the expected behavior. What I meant was that if the file was running multiple times because of some non-cron behavior, that it stopped when the typo was fixed in the cron.


Is it possible to change method function handlers in MATLAB classdef

Question: I'm trying to use MATLAB OOP. I would like to change the class method handler in the class constructor.
For example, I have a class test where a class method uses one of methods depending on the variablenumber in class properties:
mytest = test(2);
mytest.somemethod();

classdef test < handle
  properties
    number
  end
  methods
    function obj = test(number)
      obj.number = number;
    end
    function obj = somemethod(obj)
      switch obj.number
        case 1
          obj.somemethod1();
        case 2
          obj.somemethod2();
        case 3
          obj.somemethod3();
      end
    end
    function obj = somemethod1(obj)
      fprintf('1')
    end
    function obj = somemethod2(obj)
      fprintf('2')
    end
    function obj = somemethod3(obj)
      fprintf('3')
    end
  end
end

Here the switch operator is used whenever test.somemethod() is called. Can I use switch once only at the time of initialization in the class constructor (ie change the method handler) as follows:
classdef test < handle
  properties
    number
    somemethod %<--
  end
  methods
    % function obj = somemethod(obj,number) % my mistake: I meant the constructor
    function obj = test(number)
      obj.number = number;
      switch number
        case 1
          obj.somemethod = @(obj) obj.somemethod1(obj);
        case 2
          obj.somemethod = @(obj) obj.somemethod2(obj);
        case 3
          obj.somemethod = @(obj) obj.somemethod3(obj);
      end
    end
    function obj = somemethod1(obj)
      fprintf('1')
    end
    function obj = somemethod2(obj)
      fprintf('2')
    end
    function obj = somemethod3(obj)
      fprintf('3')
    end
  end
end

This second implementation of the test class does not work.
For S = test(2); S.somemethod(), there is an error:
Error using test>@(obj)obj.somemethod2(obj) (line ...)
Not enough input arguments.
What's wrong?
Answer: First of all, you can't have somemethod as a method and a property. You can get rid of the method and assign a function handle to the property in your constructor.
function self = test(number)
    self.number = number;
    switch self.number
        case 1
            self.somemethod = @(obj)somemethod1(obj)
    %....
    end
end

Also, your current anonymous functions you've passed two copies of the object to the method:

obj.method implicitly passes obj as the first input
obj.method(obj) passes a second copy of obj as the second input

You want to update your object handles to something like the following which will pass a single copy of obj to the method.
obj.somemethod = @obj.somemethod3

Also, when using your class, you'll have to execute somemethod using dot notation since it's a property and not a "real" method
S = test()
S.somemethod()

Comment: About the same name in properties and methods it is my typemistake (I meant initialization in the constructor). But 'S = test(2); S.somemethod()' generates the error: "Error using test>@(obj)obj.somemethod2(obj) Not enough input arguments."
Comment: @AlexanderKorovin sorry I mistyped that. Should be working now
Comment: Thank you! Unfortunately, I found that this implementation (`obj.somemethod = @ obj.somemethod3`) is about two times slower than when using `switch`!


entire function Res(1/f)

Question: Let $f$ be an entire function and let $a_1, \dots , a_n$ be all zeros of $f$ in $\mathbb{C}$. Suppose that there exists real numbers $r>0$ and $t>1$ such that $|f(z)| \geq |z|^t$ for all $|z| \geq r$. Prove that
$$\sum Res(1/f,a_j)=0$$
I want to say something about the boundedness tell's us about the symmetry of the Residues but I'm unsure. Perhaps taking the Taylor expansion?
Answer: Pick a large circle around the origin containing all the zero's. Then your sum equals to $\frac{1}{2\pi i} \int_{|z|=R} \frac{1}{f}$  by residue theorem. Now apply ML inequality to see that the integral tends to zero as you enlarge your circle.
Comment: could you add a little more detail?
Comment: @az89 this appears to be sufficient. Try working the details on your own, first.

entire function Res(1/f)


Substitution is Pullback

Question: I've read here,
here
and here about how to interpret pullbacks as the substitution of a term into a predicate or dependent type, such as $y:C⊢B(f(y)):Type$ being the pullback of the function $y:C⊢f(y):A$ and predicate $x:A⊢B(x): Type$.
What I do not understand is that all interpretations require two different "kinds" of arrows: one is a vanilla function, the other a predicate/dependent type. When I look at the starting diagram $A \rightarrow_f C \leftarrow_g B$ for a pullback, I just see two arrows $f$ and $g$.
I initially thought that functions and predicates/dependent types are actually interchangeable. For example, $y:Nat⊢Vector(y):Type$ is equivalent to $y:Vector⊢length(y):Nat$.
My issue then is that a pullback can be expressed in two ways; to re-use the above example, the pullback is both $y:C⊢B(f(y)):Type$ and $y:B⊢C(g(y)):Type$ (where $g$ is defined in the equivalence $x:A⊢B(x): Type \equiv x:B⊢g(x):A$). How to reconcile these two and prove equality?
Thanks
Comment: Why would you think $y:Nat\vdash Vector(y):Type$ is "equivalent" to $y:Vector\vdash length(y):Nat$? The first judgment states that $Vector : Nat\to Type$, while the second judgment simply states that $length : Vector \to Nat$. These not only aren't saying the same thing, they can't both hold as the second judgment requires $Vector : Type$ which is contradicted by the first judgment.
Answer: I think you are a bit confused about the whole interpretation of judgments as objects and arrows. Let me try to make it clearer.
Suppose $\vdash C : \mathit{Type}$ and $\vdash A : \mathit{Type}$ are valid judgments. Their interpretations are respectively the objects $C$ and $A$.
Then we can form the judgment $y : C \vdash A : \mathit{Type}$. Since the context contains the variable $y : C$, its interpretation is an arrow with codomain $C$. The domain is the object that corresponds to the judgment $\vdash \Sigma_{y : C}\, A : \mathit{Type}$, i.e. the product $C \times A$. Therefore the interpretation is the projection $\pi_1\colon C \times A \to C$. Of course, we also have the projection $\pi_2 \colon C \times A \to A$.
Then, we suppose $y : C \vdash f(y) : A$ is a valid judgment. Its interpretation is an arrow $f \colon C \to C \times A$ that is a section of $\pi_1 \colon C \times A \to C$, i.e. $\pi_1 \, f = 1_C$.
Finally, suppose $x : A \vdash B(x) : \mathit{Type}$ is a valid judgment. Since the context contains the variable $x : A$, its interpretation is an arrow with codomain $A$. The domain is the object that corresponds to the judgment $\vdash \Sigma_{x : A}\, B(x) : \mathit{Type}$, that we shall denote by $\Sigma_A\, B$. Then the interpretation is the projection $\pi_1 \colon \Sigma_A\, B \to A$.
Now, we are interested in the arrows $\pi_2 \, f \colon C \to A$ and $\pi_1 \colon \Sigma_A\, B \to A$. If we form the pullback of these two arrows we get an object $\Sigma_C\, f^* B$ together with two morphisms $\pi_1\colon \Sigma_C\, f^* B \to C$ and $h\colon \Sigma_C\, f^* B \to \Sigma_A\, B$ satisfying the universal property.
$\pi_1\colon \Sigma_C\, f^* B \to C$ corresponds to the judgment $y : C \vdash B(f(y)) : \mathit{Type}$. It is the pullback of $\pi_1 \colon \Sigma_A\, B \to A$ along $\pi_2\, f$ and indeed it corresponds to the substitution into $x: A \vdash B(x) : \mathit{Type}$.
$h\colon \Sigma_C\, f^* B \to \Sigma_A\, B$ corresponds to the judgment $z : \Sigma_{y: C}\, B(f(y)) \vdash \langle f(\pi_1(z)), \pi_2(z)) \rangle : \Sigma_{x: A}\, B(x)$. It is the pullback of $\pi_2\, f$ along $\pi_1$ and indeed it corresponds to the weakening of the judgment $y : C \vdash f(y) : A$ with respect to the judgment $x : A \vdash B(x) : \mathit{Type}$, since it contains the void information that if $z : \Sigma_{y: C}\, B(f(y))$ then $\pi_2 (z) : B(f(\pi_1(z)))$.
Comment: I'm still digesting but in the meanwhile can you confirm what you mean by the projection $\pi_1 \colon \Sigma_A\, B \to A$ in context of $\Sigma_A\, B$? Is $\Sigma_A\, B$ just $A \times B$? Are you referring to the product projection?
Comment: I called it "projection" because one thinks of it as the map sending $\langle a, b \rangle : \Sigma_A\, B$ to $a : A$. But in this situation $\pi_1$ is just the intepretation of the judgment $x : A \vdash B(x) : \mathit{Type}$, we don't know anything else about it. Notice that here we suppose that we already know the interpretations of $\vdash C : \mathit{Type}$, $\vdash A : \mathit{Type}$, $y : C \vdash f(y) : A$ and $x : A \vdash B(x) : \mathit{Type}$, and what we want to find out is the interpretation of $y : C \vdash B(f(y)) : \mathit{Type}$.
Comment: $\Sigma_A\, B$ is not the product $A \times B$, because there is no object corresponding to $B$. Indeed, $B$ is a dependent type, so again, the interpretation of $x : A \vdash B(x) : \mathit{Type}$ is an arrow (having as codomain the interpretation of $A$, which is a simple type), not an object. If $B$ does not depend on $A$ (i.e. $\vdash B : \mathit{Type}$ is valid, and so $x : A \vdash B : \mathit{Type}$ is valid), then what I called $\Sigma_A\, B$ would be the product $A \times B$, just as we formed the product $C \times A$ for the judgment $y : C \vdash A : \mathit{Type}$.

Substitution is Pullback


Abrir página depois do carregamento

Question: Estou pensando em fazer isto utilizando jQuery e utilizei alguns métodos já disponíveis na internet mas não estão funcionando. Tentei modificá-lo mais acho que estou fazendo isto da maneira errada.
O que eu estou querendo fazer: a página deve abrir depois de carregar totalmente, para que ao abrir uma página qualquer tenha todo o conteúdo já disponível após o seu carregamento.
O código:
  body{overflow-x:hidden;overflow-y:hidden;}

    function liberar(){
        document.getElementById('bloquear').style.display='none';
        document.body.style.overflow='scroll';
    }

Comment: Não deu pra entender o que é "isto" que você está tentando fazer.
Comment: @bfavaretto desculpe se não expliquei do modo correto, o que eu estou querendo fazer: a página deve abrir depois de carregar totalmente, para que ao abrir uma página qualquer tenha todo o conteúdo já disponível após o seu carregamento.
Comment: the flash, por favor, prefira editar a pergunta em vez de esclarecer nos comentários.
Comment: @brasofilo ok,desculpe.
Answer: Aqui fica uma resposta tardia pois a resposta aceite não explica qual o problema que tinha no seu código e acrescenta jQuery quando a solução não é necessáriamente essa.
Tem alguns problemas no seu código:
O primeiro é que CSS e JavaScript precisam de tags de HTML para o browser conseguir interpretar esse código como o que ele é e não HTML. Ou seja, em vez deste pedaço:
body{overflow-x:hidden;overflow-y:hidden;}

function liberar(){
    document.getElementById('bloquear').style.display='none';
    document.body.style.overflow='scroll';
}

deve ter assim: (com o javascript dentro de tags

Outro problema é que a declaração do inicio do body ocerre depois de já ter aparecido HTML na página. Isto é inválido. A tag  diz ao browser que alí começa o corpo da págna e não pode haver HTML fora do body. Assim esta linha:

deve ser inserida depois da tag
Outro problema é que a função liberar não vai ser corrida se não acrescentar () no fim. Ou seja . Dê uma olhada aqui (http://jsfiddle.net/sFms7/) teste retirar os () e carregue em "Run", vai ver que a função não corre. Isto porque JavaScript dentro de HTML comporta-se de maneira diferente. Esse ponteiro para a função só vai ser lido/parsed quando o onload fôr chamado.
O ultimo problema é o posicionamento da função liberar. Aqui tem duas opções. Ou coloca dentro da tag  (que falta no seu código) juntamente com o

AQUI O QUE APARECE ENQUANTO NÃO CARREGOU

SEU CONTEUDO AQUI DENTRO!!!

Ele só carrega a página depois de carregar todos os scripts (menos imagens).
Ele não é muito funcional...
Você também pode usar o load ao invés do ready!
Comment: coloquei um outro exemplo...mas depende de como o CSS dele estiver, no exemplo que ele colocou tá muito confuso..
Comment: @user3230262 aqui está uma página onde será utilizada este método de carregamento: http://codepen.io/flashpremium/pen/DHctJ
Comment: @theflash fiz a correção no seu código, espero que seja isso...
Comment: obrigado, apenas não entendi um ponto se eu estiver com uma única div "wrapper" que seria a div pai, o que devo fazer para esconder e demostrar todo conteúdo apenas após o carregamento de uma página, tudo isto de uma só vez?
Comment: você precisa criar a div que vai aparecer enquanto a página não é carregada e deixar a div "wrapper" com display:none para ela aparecer somente quando a página estiver carregada, é exatamente a resposta que eu postei, só falta vc modificar para suas preferencias, lembrando que ele não espera as imagens carregarem, somente os scripts...
Comment: isto esclarece a minha dúvida. obrigado.

Abrir página depois do carregamento


Properties of the indices of the Kronecker product

Question: I am working with function (and their derivatives) of matrices, in particular of symmetric and positive definite (SPD) matrices. I am interested in keeping a matrix notation as long as possible, instead of using vectorization.
The specific problem that I am facing now is with the Kronecker product and how to manage the object that it produces. Specifically, I obtained (some context will be provided below) this product (note the explicit indexes):
$$ A_{ik}A_{jl} - B_{ik}A_{jl} - B_{il}A_{jk} $$
where $A$ and $B$ are squared, with the same dimension $p$ and SPD matrices. My question is: can I rewrite this object as a Kronecker product? If yes, it exists some way to clean up the two second terms? At the first question, I would be tempted to write something along
$$ (A \otimes A + B \otimes A)_{p(i-1)+j, p(k-1)+l} - (B \otimes A)_{p(i-1)+j, p(l-1)+k}$$
(I am following the wikipedia page here).
Is it possible to obtain a cleaner expression?
Context:
What I am trying to do is to obtain the Hessian of the Loglikelihood for a Multivariate Normal distribution. This in practice requires to compute the derivatives of:
$$ l = -\frac{n}{2}\log\det\left|\Sigma\right| - \frac{1}{2}\text{Tr}\left[S\Sigma^{-1}\right] $$
with $S=XX^\top$ a symmetric matrix obtained from the data (in this setting I am considering the mean equal to $0$) and $\Sigma$ the covariance matrix.
I have to compute $\partial l/\partial\Sigma$ and then $\partial^2l/(\partial\Sigma\partial\Sigma)$. If I have not made mistakes, they are:
$$ \frac{\partial l}{\partial\Sigma} = -\frac{n}{2}\Sigma^{-1} + \frac{1}{2}\Sigma^{-1}S\Sigma^{-1}$$
and
$$ \frac{\partial^2 l}{\partial\Sigma_{ij}\partial\Sigma_{kl}} = \Sigma^{-1}_{ik}\Sigma^{-1}_{jl} - (\Sigma^{-1}S\Sigma^{-1})_{ik}\Sigma^{-1}_{jl} - (\Sigma^{-1}S\Sigma^{-1})_{il}\Sigma^{-1}_{jk}$$ which is the expression that I wrote at the beginning of the question (with $A=\Sigma^{-1}$ and $B=\Sigma^{-1}S\Sigma^{-1}$).
Thus, if you notice some error here that could save my day! :D
Disclaimer
I know that what I am trying to do can be obtained more easily by using the vec and vech operators to work with standard vectors, but I would really prefer to keep the matrix notation for as long as possible. If that was not possible, I will be forced to transform the matrices (and I mostly know how to do it, but in any case that would be another question), but I hope to avoid it.
Thank y'all for the help!
Comment: Thank you, of course I would randomly miss it! :(
Answer: For ease of typing, define
$$\eqalign{
M &= \Sigma^{-1} \;\implies\; dM = -M\,d\Sigma\,M
}$$
Your gradient is correct, so let's start with that and find its differential.
$$\eqalign{
G &= -\tfrac{1}{2} (nM-MSM) \\
dG
 &= -\tfrac{1}{2} (n\,dM-dM\,SM-MS\,dM) \\
 &= +\tfrac{1}{2} (n\,M\,d\Sigma\,M-M\,d\Sigma\,M\,SM-MSM\,d\Sigma\,M) \\
 &= +\tfrac{1}{2} (n\,M\,d\Sigma\,M-M\,d\Sigma\,(2G+nM)-(2G+nM)\,d\Sigma\,M) \\
 &= -\tfrac{1}{2} (n\,M\,d\Sigma\,M+2M\,d\Sigma\,G+2G\,d\Sigma\,M) \\
}$$
At this point, we'd normally use vec/vech operations, but you don't want to do that.
So let's introduce the double-dot product between tensors
$$\eqalign{
A={\cal B}:C \;\implies\; A_{ij}= \sum_{k,l} {\cal B}_{ijkl}C_{kl} \\
}$$
Let's also introduce the 4th order isotropic tensor ${\cal E}$ with components
${\cal E}_{ijkl} = \delta_{ik}\delta_{jl}$
This tensor is the identity for the double-dot product, i.e.
$\;A:{\cal E}= A = {\cal E}:A$
Another useful property is untangling matrix products
$\implies A\,dX\,B = A{\cal E}B^T:dX$
Continuing from before
$$\eqalign{
dG &= -\tfrac{1}{2} \big(n\,M{\cal E}M+2M{\cal E}G+2G{\cal E}M\big):d\Sigma \\
{\cal H} = \frac{\partial G}{\partial \Sigma}
 &= -\tfrac{1}{2} \big(n\,M{\cal E}M+2M{\cal E}G+2G{\cal E}M\big) \\
{\cal H}_{ijkl} = \frac{\partial G_{ij}}{\partial \Sigma_{kl}}
 &= -\tfrac{1}{2} \big(n\,M_{ip}{\cal E}_{pjkq}M_{ql}
 + 2M_{ip}{\cal E}_{pjkq}G_{ql}
 + 2G_{ip}{\cal E}_{pjkq}M_{ql}\big) \\
 &= -\tfrac{n}{2}M_{ik}M_{jl} -M_{ik}G_{jl} -G_{ik}M_{jl} \\
}$$
I think it looks better with the $G$'s but you can eliminate them in favor of $S,M,\pm$ signs, and more indices.
$$\eqalign{
{\cal H}_{ijkl}
 &= \tfrac{1}{2} \big(
n\,M_{ik}M_{jl}
 - M_{ik}M_{jp}S_{pq}M_{ql}
 - M_{ip}S_{pq}M_{qk}M_{jl}\big)
\\
 &= \tfrac{1}{2} \big(
n\,M_{ik}M_{jl}
 - M_{ik}(MSM)_{jl}
 - (MSM)_{ik}M_{jl}\big)
\\
}$$
Comment: Thank you for your help! Can you suggest a reference for some introduction to tensor algebra? Because I found at least two different definitions of the double-dot product and neither is similar to yours! :(
I found one answer [here](https://math.stackexchange.com/questions/348739/double-dot-product-vs-double-inner-product) that gives some sort of insight, but also there they didn't provide references.
Comment: Almost any textbook on _Continuum Mechanics_ will cover tensor algebra and tensor calculus. I believe Dover publications has a couple of good ones in their catalog.


Como fazer um reset na senha do bash Ubuntu do windows 10?

Question: Não me recordo da senha do meu usuário do bash do Ubuntu no Windows 10 como faço para criar uma nova senha para meu usuário?
Comment: Se você acha que está dentro do escopo, existe o botão **reabrir** logo abaixo da pergunta. Se mais 4 pessoas concordarem, a pergunta será reaberta. Se você acha que esta outra que citou também estaria fora do escopo, para isso há o botão **sinalizar** e, da mesma forma, se outros usuários concordarem, será fechada. É assim que funciona a comunidade.
Comment: Não entendi porque vocês acharam fora de escopo. Saber fazer um reset de senha do meu usuário do bash do Ubuntu do Windows-10 me parece um conhecimento não só útil como relacionado ao tema de programação. Vocês podem ser um pouco mais específicos porque fora do escopo?
Comment: Para mim entra em _Ferramentas normalmente usadas por desenvolvedores exercendo sua função programando, depurando, preparando ou implantando softwares e controlando o processo._

Tem essa pergunta que acho que se a minha é fora de escopo está também é [https://pt.stackoverflow.com/questions/91887/como-posso-encontrar-o-utilizador-no-ubuntu-shell-bash?rq=1](https://pt.stackoverflow.com/questions/91887/como-posso-encontrar-o-utilizador-no-ubuntu-shell-bash?rq=1)
Comment: obrigado pela resposta Anderson
Answer: Se possível, tente desinstalar o Ubuntu, e então reinstale, então ele pedirá novamente os dados para criar o usuário.
<code>lxrun /uninstall /full

lxrun /install
</code>
Fonte: https://superuser.com/a/1065579/274615
Comment: A pergunta não é sobre uma ferramenta. Tanto que foi fechada como fora do escopo.
Comment: @Tony ela foi fechada, basta conferir la em cima.
Comment: Acredito que o downvote tem a ver com a pergunta ser offtopic, só a fonte que voce achou ja comprovaria isso.
Comment: Quem deu downvote provavelmente não examinou a fundo as opções possíveis.
Comment: Não é off-topic, pois o StackOverflow também engloba o uso das ferramentas usadas na programação.
Comment: O WSL não é uma ferramenta de programação?
Comment: porque não pode ter perguntas sobre ferramentas de programação? Qual o objetivo disso?
Comment: @RobertoLeitedeMoraes https://pt.meta.stackoverflow.com/q/264/28595
Comment: Lá consta "Ferramentas normalmente usadas por desenvolvedores exercendo sua função programando, depurando, preparando ou implantando softwares e controlando o processo."
Comment: Mesmo que a pergunta fosse fora do tópico, o mais correto e gentil seria comentar, movê-la, ou fechá-la.
Comment: Fechada indevidamente, pois o WSL é uma ferramenta de programação, é o bash Linux no Windows.
Comment: como comentei na pergunta acho que com esse critério tem outras perguntas que tem que ser removidas também por ser fora de escopo como: [https://pt.stackoverflow.com/questions/91887/como-posso-encontrar-o-utilizador-no-ubuntu-shell-bash?rq=1](https://pt.stackoverflow.com/questions/91887/como-posso-encontrar-o-utilizador-no-ubuntu-shell-bash?rq=1)
Comment: @Tony achei uma resposta que gostei mais do que a sua [https://askubuntu.com/questions/772050/reset-the-password-in-linux-bash-in-windows?newreg=9963e4af5b164a05acd2e6d7b072d874](https://askubuntu.com/questions/772050/reset-the-password-in-linux-bash-in-windows?newreg=9963e4af5b164a05acd2e6d7b072d874)
Comment: OK, após rodar estes comandos do link que você achou (eu também havia visto esta antes, mas achei mais complicada), me diga se esta funcionou para você.
Comment: a outra que eu encontrei funcionou, vou testar a sua também
Comment: @Tony acabei de fazer a sua sugestão. realmente parece mais fácil, são dois comandos, mas na hora de executar demora muito mais, tem que re-iniciar a máquina, e depois fazer a configuração do bash, resumindo. tem uma vantagem que com a nova configuração você tem um controle maior do que você fez, mas no final o outra achei menos complicado e muito mais rápido.
Comment: OK, você pode responder sua própria pergunta e marcar como resposta, para ajudar os outros que buscarem por isto. Pode dar um +1 na minha resposta também.
Comment: @Tony assim que tiver pontuação suficiente vou fazer isso, obrigado por compartilhar seu conhecimento.


Do different modes have the same cadence structure?

Question: In major and minor keys, the perfect cadence is V to I
Will this structure remain the same in a different mode?
I.e. E Phrygian Mode in the key of C (E F G A B C D), the tonic chord is the  iii of the key of C major. So, the scale would be iii IV V vi viio I ii iii (expressed relative to C major). So would viio to iii be a perfect cadence?
Comment: It getting really tiresome chasing down all the places where @MaikaSakuranomiya keeps posting this erroneous list of "modal cadences." That is one person's invention and not remotely common for modal harmony.
Answer: Keys use tonal approaches by using functional harmony.  The two main types of final cadences in tonal music are known as authentic and plagal.

Authentic cadence in major key: V-I (Ex. G-C)

Authentic cadence in minor key: V-i (Ex. E-Am) (or sometimes v-i (Ex. Em-Am) but very rare.)

Plagal cadence in major key: IV-I (Ex. F-C)

Plagal cadence in minor key: iv-i (Ex. Dm-Am)

Modes use modal approaches by character emphasis.  In fact, if you want to give a more modal approach, no V-I, IV-I, V-i, iv-i, or v-i is appropriate here.
So the answer is: a big NO.

If you want to write a modal cadence, follow the requirements below:

No tritone in any chord. (It sounds more tonal.)

No leading tone should be used. (It also sounds more tonal.)

Keep the character of the mode. (Use the characteristic tone in the first chord of the cadence.)

No V-I, IV-I, V-i, iv-i, or v-i. (Mentioned above.)

The notes (scale degrees) of each of the seven modes are: (Bold: characteristic tone)

Ionian: P1-M2-M3-P4-P5-M6-M7-P8

Dorian: P1-M2-m3-P4-P5-M6-m7-P8

Phrygian: P1-m2-m3-P4-P5-m6-m7-P8

Lydian: P1-M2-M3-A4-P5-M6-M7-P8

Mixolydian: P1-M2-M3-P4-P5-M6-m7-P8

Aeolian: P1-M2-m3-P4-P5-m6-m7-P8

Locrian: P1-m2-m3-P4-d5-m6-m7-P8

The diatonic chords are: (Bold: characteristic chords, containing the characteristic tone)

Ionian: I ii iii IV V vi viio I

Dorian: i ii III IV v vio VII i

Phrygian: i II III iv vo VI vii i

Lydian: I II iii ivo V vi vii I

Mixolydian: I ii iiio IV v vi VII I

Aeolian: i iio III iv v VI VII i

Locrian: io II iii iv V VI vii io

Notice how all seven modes contain three characteristic chords - one major, one minor, and one diminished.  However, that doesn't mean every chord is useful; we should avoid using the following:

Ionian: IV, viio

Dorian: IV, vio

Phrygian: vo

Lydian: ivo, vii

Mixolydian: iiio, v

Aeolian: iio, iv

Locrian: io (Truncate this chord to just root and third.), V

Imagine one writes V-I or IV-I in Ionian.  Is this viewed as modal?  No.  Modal cadences would meet the requirements that I've listed above.  They are not to set up a strong resolution to the tonic chord like how tonal cadences would, but to show the character of the mode.

So ii6(5)-I in Ionian (Ex. Dm(7)/F-C) would be viewed as a more modal cadence.

In Dorian, you would use ii6(5)-i. (Ex. Em(7)/G-Dm)

In Phrygian, you would use II (or vii6) -i. (Ex. F (or Dm/F) -Em)

In Lydian, you would use II6-I. (Ex. G/B-F)

In Mixolydian, you would use VII-I. (Ex. F-G)

In Aeolian, you would use VI-i. (Ex. F-Am)

In Locrian, you would use iii6-i(no5). (Ex. Dm/F-Bm(no5))

Notice how all modes use their characteristic chords as the first chord of their cadences and the tonic triads as the second.  Also, realize how they have their characteristic tones as the bass of the first chords, except for Dorian, which rather has it on either the soprano or the inner voice.

If you want to read further, see Cadences for Modes.
Answer:
Do different modes have the same cadence structure?

No

In major and minor keys, the perfect cadence is V to I

Correct. For minor keys some write the Roman numerals V i with  lower case for the minor tonic. Keep in mind that the dominant triad must be major for a major/minor key perfect cadence.

Will this structure remain the same in a different mode?

Yes and no. It depends on the harmonic style and whether the cadence is kept purely diatonic or is chromatically altered.
As you rotate the diatonic triads through the various modes the triad build on the dominant will change through the three different chord qualities: major, minor, diminished. Only those modes with a major dominant will have the perfect cadence available as a diatonic option: Ionian and Lydian.
However, in Medieval modal style musica ficta is used to add accidentals to the ^7 scale degree in the other modes to create a proper cadence, a clausula vera. A clausula vera is not exactly the same as a perfect cadence, because it doesn't have the descending fifth in the bass, but it is essentially the same major dominant to tonic harmony.
In modal folk music the bVII chord is often used as a kind of substitute dominant in cadences like bVII i. Obviously that isn't a perfect cadence, there isn't a V chord. I think the common use of the bVII i cadence is harmonizing a phrase ending ^2 ^1, from that melodic perspective it is serving a similar purpose as the V i perfect cadence, but with a substitute chord.

E Phrygian Mode in the key of C (E F G A B C D) ...the scale would be iii IV V vi viio I ii iii (expressed relative to C major).

You should use the Roman numerals to start on the tonic so the E minor chord is i and the full list of chords is i bII III iv vo VI vii, the dominant triad is diminished and the seventh degree triad is minor.

So would viio to iii be a perfect cadence?

No. Let's re-label that to vo i. It's not a perfect cadence, because the dominant isn't major.
The clausula vera for Phrygian would be vii6 i.
The folk cadence (for lack of a better term) would be II i or to make the Phrygian quality clear use a flat sign bII i.

Some answered questions posted after this one cover many of these point separately:

https://music.stackexchange.com/a/58129/23919
https://music.stackexchange.com/a/23610/23919
https://music.stackexchange.com/a/86062/23919
Comment: Nice answer! I've mentioned this question and your answer (and comment) [in the chatroom](https://chat.stackexchange.com/transcript/message/50800628#50800628).
Answer: A couple comments may help.
A perfect cadence is distinguished from an imperfect cadence by its dominant->tonic motion in the melody, not necessarily in the harmony.
When describing the harmonic properties of the mode, it's simpler to consider the example to be in the key of the mode itself, not the relative ionian scale. So E-phrygian is harmonized
i ♭II ♭III iv vø ♭VI ♭vii.
So, you really can't form a perfect cadence in E-phrygian because there's no D♯ to put in the melody. vø->i might be the closest you can get without altering the scale to create a secondary dominant. Diminished->tonic, even a minor tonic, gives a strong resolution. Or ♭II->i is quite dramatic, too.
Please also see Maika-san's answer which is much more comprehensive.
Answer: Perfect cadences are all about functional harmony.  Harmony with dominant seventh chords that include nice sharp leading notes itching to resolve to the tonic.
Modes need a different language and a different approach.
Answer: With respect to your second question, I would say in this case yes, it would be a perfect cadence.  B --> E is V --> I (key of Emin in this example). This is the same as representing B as the viii(dim) and E as the iii in the key of Cmaj.


SQL Code to Select to select unique column and match with row on another column

Question:
Not even how to word this question:  I have a table that looks like this:

select * from tblServiceUsers
ORDER By ServiceID

0   B88230BB-4943-4C10-AB0E-8ABB88A357A3
0   5653C943-7F9A-4746-B2A3-1160E9204A7E
0   08678EE7-49A7-4F63-BC39-CFCCE2C9AD65
1   B88230BB-4943-4C10-AB0E-8ABB88A357A3
1   5653C943-7F9A-4746-B2A3-1160E9204A7E
2   B88230BB-4943-4C10-AB0E-8ABB88A357A3
2   5653C943-7F9A-4746-B2A3-1160E9204A7E

And I need a query that only returns the top (or first) userid that matches a serviceID.
For example, I just want 1 UserID to be displayed for each ServiceID.  Such as the following:
0   B88230BB-4943-4C10-AB0E-8ABB88A357A3
1   B88230BB-4943-4C10-AB0E-8ABB88A357A3
2   B88230BB-4943-4C10-AB0E-8ABB88A357A3

Comment: Please try to format this legibly, using the code formatter.
Answer: You don't say which version of SQL server it is, but for MS SQL Server 2005 onwards you can do something like :
 Select SecID, ServiceID, UserID from
 (
    select ROW_NUMBER() OVER (PARTITION BY ServiceID ORDER BY Secid) AS row_number,
    SecID,
    ServiceID,
    UserID
    From tblSecServiceUsers
 )
 tempTable
 where row_number = 1

Comment: Yes, it's 2005.  I tried this out and it works great!  Thanks.
Answer: Why not use TOP 1 and an ORDER BY clause?
Comment: top 1 will only return 1 row. I have columns ServiceID, and UserID. There are some ServiceID's that have up to 5 userid's, but I only want to display one userid per unique serviceid.
Answer: You sound like you're not too bothered which UserId you just want any one? If so this would work.
SELECT MAX(UserID) AS UserID, ServiceID
 FROM tblServiceUsers
GROUP BY ServiceID
ORDER BY ServiceID


formbuilder choose to not show a field in symfony

Question: I'm building a questionnaire that is  shown in two templates but I need to not show some filed in one of the templates
 $builder
            ->add('acceptConsent', CheckboxType::class, [
                'label_attr' => [
                    'class' => 'font-weight-bold'
                ],
                'required' => true,
                'constraints' => new NotBlank(),
                'disabled' => $readOnly,
            ])

there is any way to set  the form to not render a field?
Comment: Could you add your twig in order to understand better the issue ?
Answer: You may "just" not render your form_row or form_widget
And close your form this way {{ form_end(form, {'render_rest': false}) }}
So that unrendered fields a not rendered.
Have a look here for more infos:
https://symfony.com/doc/current/form/form_customization.html


Definir a obrigatoriedade de campos na aplicação em vez do banco de dados é viável?

Question: Me deparei com um sistema em que a maior parte das regras de obrigatoriedade de campos é feita na aplicação e não no banco de dados (com exceção da chave primária).
Como não tenho experiência com muitos sistemas, gostaria de saber se isso é comum e traz alguma vantagem ou se é inviável.
Answer: O melhor seria primeiramente garantir as Regras de Integridade (RIE e RIR) no próprio banco de dados, para manter a consistência deste. Isso garante que mesmo se a sua aplicação for alterada ou substituída, seus dados estarão protegidos e consistentes.
Quando o assunto são regras de negócio, muitos preferem inseri-las na aplicação.
Tem uma publicação muito interessante sobre esse assunto no seguinte link:
A Arte do Software: Regras de negócio na aplicação
Answer: Esse é um assunto bem controverso, especialmente entre o pessoal que desenvolve software para web. Uns preferem deixar tudo na aplicação, outros dividir a responsabilidade.
Pessoalmente acredito que quanto menos "pontas soltas" você deixar melhor. Dessa forma, acredito que valha a pena, se sua aplicação for grande o suficiente, fazer a validação de consistência nas duas pontas.
A aplicação cuida da parte dela validando tudo o que é necessário antes de inserir no banco de dados (nunca confie nos dados que os usuários enviam) e o banco de dados mantém suas chaves estrangeiras e correlatos.
Como desenvolvedor, com alguma frequência quebro a consistência entre aplicação e banco quando trabalho sozinho num projeto. E tenho certeza de que as coisas tendem a quebrar mais quando mais pessoas trabalham juntas num projeto, ou mesmo quando mais de um projeto precisa acessar dados do mesmo banco de dados.
Comment: Falando exclusivamente de obrigatoriedade de campo não vejo o motivo de um NOT NULL ser motivo de discussão.
Comment: `NOT NULL` não é motivo de discussão nunca. se o campo é obrigatório, ele deve estar presente, se não é obrigatório, o campo não deveria nem estar na mesma tabela e e sim numa outra tabela auxiliar.
Answer: Mantenha em ambos.
A coisa que mais vejo, atualmente, são sistemas onde as regras ficam apenas na aplicação, já que atualmente saber o mínimo de base de dados parece ser uma grande exigência.
O que acontece? No melhor dos cenários, onde apenas sua aplicação usa o banco: algum usuário vai lá diretamente no SGBD e apaga algum dado. Como não existe nem foreign_keys, pronto: agora os dados estão inconsistentes. E vejo isso com uma frequência assustadora.
No pior cenário, vários aplicativos terão acesso ao mesmo banco.
Então, no mínimo, mantenha também no banco os campos que são obrigatórios (definidos como NOT NULL), as chaves estrangeiras, e use restrições para valores, como o ENUM no MySQL (ou CHECK do Oracle) quando possível.
A validação (ao menos de campos obrigatórios) e constraints (como as foreign_keys) no banco são como cinto de segurança: você vai achar que nunca precisa deles, até que um acidente aconteça.
Answer: Cara isso vai depender da sua necessidade, tanto de negócio quanto de consistência.
Haverá casos que você irá precisar garantir no banco de dados que o valor do campo não poder ser null, te darei um exemplo, você tem uma tabela Produto que se relaciona com Plano, nessa tabela Produto você tem o valor do produto, se no banco de dados você não deixar ele como obrigatório você poderá incluir um produto via insert no banco sem esse valor, mas se por exemplo, você fizer isso, e na camada de negócios da sua linguagem de programação que você estiver usando ser de fatal necessidade você ter esse valor pra vender algum Plano desse Produto, você começaria a ter uma falta de consistência muito grande nos seus dados a ponto de não ser possível realizar a venda.
Mas como a grande maioria dos fatores na área de desenvolvimento de software, deverá sempre haver uma analise, até quando você precisa desses dados concisos no DB e até quando não. Feito isso implemente da forma que você conclui melhor pra cada caso.
Answer: Quando possível prefiro ter a garantia das constraints no BD, nem sempre é pois existem pacotes comercializados em diversos Bds e pode ficar inviável administrar Bds diferentes.
Gosto também de Triggers de validação de Regras de Negócio sendo que cabe as mesmas observações já ditas.


PDF mimetype, is this a bug?

Question: I'm uploading a pdf via a ASP.NET web form and checking it's MIME. Sometimes the MIME is reported as applicaton/pdf, not application/pdf. Is this a browser bug?  Why would application be spelled wrong?
Answer: This seems to be a browser bug. Never rely on the data the client sends you - better call a local code that finds out the mime type for you.
Answer: It's clearly a bug somewhere.  applicaton is not a valid IANA-listed mime directory.

PDF mimetype, is this a bug?


partial differential equation with polar coordinate

Question: i have difficultises to resolve the following problem. Thank you for the help.
We consider the heat equation
$$
\dfrac{\partial u}{\partial t}= c^2 (\dfrac{\partial^2 u}{\partial x^2}+ \dfrac{\partial^2 u}{\partial y^2})
$$
1. Write this equation using the polar coordinate.
2. We put $u(r,\theta,t)= R(r) \Theta(\theta) T(t)$. Gives the differential equations satisfied by $R, \Theta, T$.
Comment: Are you sure this question is written down correctly ? $(\frac{u}{\partial x^2}+ \frac{\partial u}{\partial y^2})$ doesn't really make sense.
Comment: https://www.math.ucdavis.edu/~saito/courses/21C.w11/polar-lap.pdf
Comment: Thank you so much Tucker. Please, ii don't understant how we fount the differential equations satisfied by $R, \Theta$ and $T$ if we put $u(r,\theta,t)=R(t)\Theta(\theta)T(t)$. Can you help me please
Answer: The first question boils down to express the laplacian in polar coordinates:
$$\triangle=\frac{\partial^2}{\partial r^2}+\frac{1}{r}\frac{\partial}{\partial r}+\frac{1}{r^2}\frac{\partial^2}{\partial\theta^2}.$$
In order to establish that simply recall that the change of variable is the following:
$$(r,\theta)\mapsto (r\cos(\theta),r\sin(\theta)).$$
Hence, one has:
$$\begin{align}\frac{\partial}{\partial r}&=\cos(\theta)\frac{\partial}{\partial x}+\sin(\theta)\frac{\partial}{\partial y}\\\frac{\partial}{\partial\theta}&=r\cos(\theta)\frac{\partial}{\partial y}-r\sin(\theta)\frac{\partial}{\partial y}\end{align}.$$
From there express $\displaystyle\frac{\partial}{\partial x}$ and $\displaystyle\frac{\partial}{\partial y}$, then take again the partial derivatives.
The second question simply consists in taking the partial derivatives of this special form of $u$ to get:
$$\frac{\dot{T}(t)}{T(t)}=\frac{r^2R''(r)\Theta(\theta)+rR'(r)\Theta(\theta)+R(r)\Theta''(\theta)}{r^2R(r)\Theta(\theta)}.$$
I just isolated $t$ from the other variables and multiply by $r^2$ the right term. One has a function of $t$ which is equal to a function of $(r,\theta)$, hence they are equal and constant. Therefore, there exists $k$ such that:
$$\begin{align}\dot{T}(t)&=kT(t)\\r^2R''(r)\Theta(\theta)+rR'(r)\Theta(\theta)+R(r)\Theta''(\theta)&=kr^2R(r)\Theta(\theta)\end{align}.$$
Once again isolates the variables in the last equation to get:
$$\frac{\Theta''(\theta)}{\Theta(\theta)}=\frac{kr^2R(r)-r^2R''(r)-rR'(r)}{R(r)}.$$
One has a function of $r$ is equal to a function of $\theta$, hence they are equal and constant. Therefore, there exists $\ell$ such that:
$$\begin{align}\Theta''(\theta)&=\ell\Theta(\theta)\\r^2R''(r)+rR'(r)+(\ell-kr^2)R(r)&=0\end{align}.$$
Finally, the differential equations satisfied by $R,\Theta,T$ are:
$$\begin{align}\dot{T}(t)&=kT(t)\\\Theta''(\theta)&=\ell\Theta(\theta)\\r^2R''(r)+rR'(r)+(\ell-kr^2)R(r)&=0\end{align}.$$
Only the last equation requires some tricks to be solved, it is almost a Bessel's equation.
Remark. Some signs can be wrong, it is your duty to be careful and check my computations. I have also set $c=1$, they were already enough constant!
Comment: I understand the all. Thank you so much.
Comment: Thank you so much. So the equation is: $$\dfrac{\partial u}{\partial t}= \dfrac{\partial^2 u}{\partial r^2}+ \dfrac{1}{r} \dfrac{\partial u}{\partial r} + \dfrac{1}{r^2} \dfrac{\partial^2 u}{\partial \theta^2}$$. Please, if we put $u(r,\theta,t)=R(r) \Theta(\theta)T(t)$, how we found the differential equation satisfied by $R, \Theta, T$?
Comment: Yes, that what it is. Regarding the last point, see my edit.


UIEvent timestamp

Question: When handling a UIButton touch, you are given a UIEvent object.  The UIEvent object has a timestamp which the Apple documentation states as being "the time that the event was created" (UIEvent Class Reference). In the documentation on the Main Event Loop, it states that: "The application object obtains the topmost object in the event queue, converts it to an event object (UIEvent) ..."
Does [UIEvent timestamp] refer to the time at which the UIEvent object is created (i.e. after processing the touch event off of the main run loop and hance not remotely real-time) or does it refer to the time that the underlying touch object was created (and hence as close as possible to representing the actual time of the user touch9?
Comment: In what situation would the distinction be important? Note that the time differential between the two is probably no more than a few milliseconds.
Comment: Arguably humans aren't able to distinguish the difference between 0ms of delay and 20ms of delay.
Comment: It is the few milliseconds that I am concerned about. I need to time the actual touch relative to a musical sequence that is playing. The shortest period between notes is 20ms so a 2ms lag will give me a 10% error which is no good.  Further, as you imply with the word 'probably', the time difference is indeterminate - it could be a lot bigger than 2ms.  It is OK if I process the event after a delay but I do need to know as accurately as possible when the event actually occured (relative to the system clock)
Answer: If you want to check, setup a view to log the timestamps of the touches, and then configure a button to lock the main thread for a few seconds (get a for loop to count to a 100 million).
While the main thread is spinning, tap your logging view, then examine the timestamps- if they're evenly spaced the OS does the timestamp, and it's accurate.

UIEvent timestamp


Can I include individuals with a single data point in a growth curve model?

Question: I read that one of the main advantages of using a growth curve model is that it can handle missing data. Some of the participants in my study have data for only one time point, while most have data across several time points.
Can I include the former in a linear growth curve model? If yes, how will individual trajectories be computed for individuals with a single time point?
Comment: @Aksakal would you mind elaborating on why this isn't a good idea?
Comment: you can but shouldn't
Comment: In a parametric individuals with only one data point still contribute information about the general *level*, but not about the shape of the curve, so you can include them.
Comment: @kjetilbhalvorsen My concern then, is how the random slope will be generated for these individuals
Comment: You didn't specify a model, so I thought about a random intercept. For a random slope, the model would just give the expected slope for that model. It shouldn't be taken too serious by itself,but it does no damage to the model.
Answer: You can include individuals with only one observation in a growth model. This individuals will not contribute information about the shape of the growth curve (such as slope), only about the general level. That could still be useful information though, and omitting data could bias the results.
I will illustrate using a data set from the R package nlme:
mydat <- nlme::Oxboys

ind1 <- c( (0:6)*9 + 1, 64:234)
mydat1 <- mydat[ind1, ]

The data frame mydat1 have eliminated all but one of the observations from a subset of the Subjects. First let us look at a plot:

Then we fit simple linear growth models on the complete and subsetted data:
library(ggplot2, lme4)
mod <- lme4::lmer( height ~ age  +  (1 | Subject), data=mydat)
mod1 <- lme4::lmer( height ~ age  +  (1 | Subject), data=mydat1)

### Predict with model for reduced data set,  but for the full data:

newvals <-  predict(mod1, newdata=mydat)

newframe <- data.frame(mydat, newvals)

The fitted models are quite similar:
 summary(mod)
Linear mixed model fit by REML ['lmerMod']
Formula: height ~ age + (1 | Subject)
   Data: mydat

REML criterion at convergence: 940

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.1857 -0.6350 -0.1339  0.6252  2.5357

Random effects:
 Groups   Name        Variance Std.Dev.
 Subject  (Intercept) 65.555   8.097
 Residual              1.718   1.311
Number of obs: 234, groups:  Subject, 26

Fixed effects:
            Estimate Std. Error t value
(Intercept) 149.3717     1.5902   93.93
age           6.5239     0.1325   49.23

Correlation of Fixed Effects:
    (Intr)
age -0.002
  summary(mod1)
Linear mixed model fit by REML ['lmerMod']
Formula: height ~ age + (1 | Subject)
   Data: mydat1

REML criterion at convergence: 732.6

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.0938 -0.5864 -0.1144  0.5203  2.4063

Random effects:
 Groups   Name        Variance Std.Dev.
 Subject  (Intercept) 62.238   7.889
 Residual              1.703   1.305
Number of obs: 178, groups:  Subject, 26

Fixed effects:
            Estimate Std. Error t value
(Intercept) 149.4966     1.5550   96.14
age           6.7146     0.1542   43.55

Correlation of Fixed Effects:
    (Intr)
age 0.025

Finally, have a look at the predictions for the reduced data model, but calculated for the full data set:

Since this is a linear model with random intercepts only, we see of course parallel lines. But everything works exactly the same way if we include a random slope, as we can with
mod.rs <- lme4::lmer( height ~ age  +  (1 + age | Subject), data=mydat)

but I leave that as an exercise.  And, this was a linear growth model, but the same will apply for a nonlinear growth model.


Recover from hosed server that was the sole DHCP Server

Question: One of my Windows Server 2003 Domain Controller seems to have died this morning.  This was the only DHCP server for this particular office.  I have another DC in this office.
If I set up a new DHCP server on this other DC:

Will it know the leases? (Maybe the information is stored in AD?)
Am I going to have to make
everyone reboot so there are no
conflicts?
Anything else I should consider?
Answer:
If I set up a new DHCP server on this
  other DC:
<code>* Will it know the leases? (Maybe the information is stored in AD?)
</code>

The lease are stored in  %systemroot%\system32\dhcp as dhcp.mdb and temp.mdb. (Reference)  They are not stored in AD, and will not be replicated.

<code>* Am I going to have to make everyone reboot so there are no conflicts?
</code>

No need.  Just configure Windows DHCP to check for an existing client on that IP (right click on the server in the DHCP tool, there is an option to have Windows DHCP check up to 5 IP's before handing one out).

<code>* Anything else I should consider?
</code>

Configure a secondary backup DHCP server using the 80/20 rule.  Printers should have their IP's statically assigned (now is a great time to check!), as should other essential system hardware (routers, WAP's, etc).
Comment: like your second point
Comment: Due to how Windows DHCP server works -- you are likely to get clients who will fail to retrieve an IP address due to the reserveration checking.  I believe Windows is stupid and will check 5 sequential IP's, which might all be in use.  If you have users who "can't get an IP", have them reboot (or, alternatively, issue a ipconfig /renew *all* on their machine) so Windows will re-query your DHCP server for another IP.  This might happen a couple of times depending on the size of your network until Windows has a good list of in-use IP addresses.
Comment: Anyone know if a recovery (windows recovery console) would overwrite the dhcp file?
Comment: Any when you say check 'on that IP', that means I can only set 5 ip address to check first?  Or does it mean it will always check an ip before handing it out ...
Comment: Kyle, I'd say that recovery would leave it in place myself, besides even if it doesn't you're no further back, give it a try - how dead is the server?
Comment: +1 for the check 5 IP's.  Didn't know that one myself.
Comment: Chopper: Very dead, it was a VM, just going to create a new one with a scope that isn't being used.  Thanks everyone!
Answer: I'm pretty sure the scopes aren't stored in AD sorry but if you can duplicate them quickly and accurately enough then you shouldn't need to force any reboots/manual-DHCP-renews on your users. The main thing I'd consider is whether there were any reservations in place as they'll screw you over if they're for servers/printers/other-important-devices; which they often are.
I'll try to add some more information to this answer in the next few minutes, just didn't want to leave you panicking :)
Just found that the data is stored at %systemroot%\system32\dhcp\dhcp.mdb, might you have a backup?
Comment: Ya, I *think* I remember where the reservation cut off was.  But won't I get DHCP conflicts?  Since users already have reservations.  If user A doesn't restart and user B does, what stops user B from getting user A's IP.  I didn't think DHCP checked first ... but maybe windows dhcp does?
Comment: No backup for this one.
Comment: good point, if you have a wide enough IP range (say 200 IPs for 100 clients) then you could start the new scope at 101 assuming that the existing users are 1-100 and when everyone's within 101-200 then open up the scope back to 1-200 and they'll migrate to the larger scope. Of course if you're tight on IP addresses that's of no use sorry.
Answer: if you get bad addresses coming up, these are just because the dhcp server has detected a conflict (because it previously didn't know the address was already allocated). this is normal, they will disappear as those machines connect up and re-request their current IP.
You might get some lingering bad addresses from machines that don't rerequest their IP, in this case after a few days, just delete the other bad addresses