Tease out extensionAttribute5 with get-mguser

Question: Trying to force myself to start using graph thru powershell since it looks like the AzureAD powershell commandlets are going the way of the dodo at some point. Wondering if there is a way to use get-mguser to grab extensionAttribute5.
I know you have to use expandedproperties to get to the onpremextensions. You also have to use the beta schema to see the extension attributes in place. Where I'm lost is exactly HOW to tease out a single property (if you even can).
For instance, (get-azureaduser -SearchString "NAME").objectID would return the azureobjectID for the user being gotten. I'm looking for something similar to that for extension attributes with get-mguser.
Been googling so much at this point that I think I might be thinking about this wrong. Sorry! Any help or pointers would be beyond appreciated.
Answer: Late answer, but you will need to use onPremisesExtensionAttributes to fetch all the extension attributes.
This works for me :
Get-MgUser -UserId 7049a62d-0091-4ddb-9e2a-e02ac57f489a -Property onPremisesExtensionAttributes | select -ExpandProperty onPremisesExtensionAttributes | select -ExpandProperty ExtensionAttribute5


writing a linked list queue class, but for some reason my head pointer reverts to garbage in my destructor when exiting the copy constructor

Question: for some reason my program breaks after setting up debugging in the destructor after finishing its copy constructor test. I debugged through it and found out that for some reason the head pointer reverts to garbage as soon as it enters the destructor, even though the head pointer points correctly to the first node right as its exiting the copy constructor, and thus causes the assignment of the first link field in my destructor to fail.
when I ran the exam stub, it passed the heap test, and the copy constructor test right before breaking at destructor, why could this possibly be? btw i didnt include all of my code because I dont want a simple paste of fixed code, i just want to know why this is happening so I can learn.. I really didn't want to have to revert posting this question but i've been trying to figure out why this thing is acting this way and its driving me nuts..
here is my destructor with the point of break
PriorityQueue::~PriorityQueue( )
{
        Node *nodeptr, *nextnode=NULL;
        nodeptr = head_ptr;                     // CONTAINS GARBAGE AT POINT OF BREAK
        while ( nodeptr != NULL)
        {
                nextnode = nodeptr->link;  // THIS IS WHERE IT BREAKS,
                delete nodeptr;             //BECAUSE ITS ASSIGNING GARBAGE FROM HEAD POINTER
                nodeptr = nextnode;
        }
        many_nodes = 0;
        head_ptr = NULL;
}

and here is my copy constructor
PriorityQueue::PriorityQueue(const PriorityQueue& source)
{
    many_nodes = source.many_nodes;         // copy node count

    Node * node1 = NULL;                    // declare node pointer
    Node * precursor = NULL;                // declare precursor for new list
    Node * copycursor = NULL;               // declare cursor for copy list

    copycursor = source.head_ptr;           // set copy cursor to source head

    int x = 0;
    while(x < many_nodes)               // start a loop for num of nodes
    {
        node1 = new Node;               // point node1 to a new allocated node

        node1->data = copycursor->data;         // copy over data to that node
        node1->priority = copycursor->priority;

        if (copycursor == source.head_ptr)      // if we're at the head
            head_ptr = node1;               // set new head to copy head

        if(precursor != NULL)               // if this isn't the first iteration
            precursor->link = node1;            // link the last node to this new node

        precursor = node1;              // precursor is now on this node
        copycursor = copycursor->link;          // copy cursor is now advanced

        x++;
    }
}

I also added a picture of my point where it breaks in the destructor to show the values easier
Comment: Check your debugger documentation to see how to set a write breakpoint. But note also that `many_nodes` is zero, and you don't handle that case properly in your copy constructor. That's why I'm suspicious of your claim that everything is correct on exit from the copy constructor.
Comment: The constructor for `Node` is rather important here, as it should be defaulting its `link` to `nullptr`, and for that matter, should have a constructor that takes a data value *and* initializes `link` to `nullptr`; both in the initializer list of the ctor. And note: your list-copy is considerably more dense than it needs to be. A single pointer-to-pointer will clean that thing up substantially if you're interested.
Comment: Set a write breakpoint to see who is modifying it. Note that if `many_nodes` is zero (as it is in your screenshot), then `head_ptr` is uninitialized. Are you sure it's set correctly on exit from the copy constructor?
Comment: the specification doesn't require me to create a constructor for node though.. just to implement the methods already in the header..
Comment: whats a write breakpoint? im googling it..
Comment: Your specification may not *require* initializing your members on construction, but this is C++, and touting around indeterminate pointers is *never* a grand idea. By not doing it in the constructors you're automatically taking on the responsibility of doing it manually *everywhere else*. I advise against that approach, sincerely.
Comment: @RaymondChen I don't recognize that fill-pattern at all, its not in any of the tables I regularly reference when seeing what appears to be pattern fills from the CRT, Win32, or .NET. Do you recognize it from anywhere? If not, I suspect as you it is quite-possibly an overwrite, but it would be a rather odd one.
Comment: @WhozCraig It may be a custom fill pattern provided by the instructor to catch exactly this bug.
Comment: interesting, I added
if(many_nodes == 0)
 {
  head_ptr = NULL;
  return;
 }
before the while loop in the copy constructor, and it caused it to get to the next test without breaking, then i had to do it for the assignment operator, but it fails the assignment operator test.. ill post its code up now
Comment: Please do not morph questions. One problem per question. Morphing the question invalidates previous answers and makes them nonsensical to future visitors. You may not realize it, but this Web site exists to be a resource for future visitors. That it also solves your problem is a side effect. Don't be selfish and treat it as your personal "help me" site.
Comment: Also, remember to cite this Web page when you submit your assignment. Claiming the work of others as your own is academically dishonest. Debugging is part of the essential work of programming.
Comment: I didn't morph the question, I left the original question the way it was, but left out the source code because I don't want everyone else who is taking the same class as me to copy the entire implementation. no where is the original "question" being morphed. All I did was remove the source code, and then under it, added an additional problem that arose. I left the question and the answer still makes sense, it tells people to never forget to check for the many_nodes = 0 case.
Comment: You changed the question by removing the original, important information and adding a new question. Don't do that. I've rolled your edit back.
Answer: The bug is in your copy constructor. If many_nodes is zero, then head_ptr is uninitialized. This is confirmed in in the screen shot: At the time of the crash, many_nodes is zero. (This means that your claim that "the head pointer points correctly to the first node right as its exiting the copy constructor" is incorrect. The head pointer did not revert to garbage. It was already garbage. That's probably what prevented people from diagnosing the real problem.)
Update: Well now you edited your question so it is now a completely unrelated question, so this answer and john's answer make no sense. This question is now useless to future visitors to the site, who will read the question and the answers and say "This is complete nonsense."
Comment: my claim was true that it was correctly pointing to the right head, when i stepped through in visual studio the watch window confirmed that it pointed to a linked list of 4 nodes, then once it entered the distructor, it reverted to 0 nodes and a garbage list. why do you have to act like you're attacking me? just because I deleted my code? I want to help everyone else in my class learn by not leaving the entire solution to the assignment up but i still left the question without the syntax up, it is still useful. sorry if I made you feel like i was misusing your help, you don't have to get
Comment: personal about it, and johns answer still makes sense without my code, but it isn't right anyway.
Comment: in case anyone cares... i sorta found a way around the stupid bug. i wrote
if(many_nodes == 0)
 {
  head_ptr = NULL;
  return;
 }
at the begining of the destructor, seems like it would have been obvious since it breaks in the destructor, yet it passes the assignment operator test without the destructor!
Answer: it turns out adding the test for 0 many_nodes in the destructor takes care of both the copy constructor and assignment operator from crashing, and the copy constructor and assignment operator still do their job as they meant to. this is confirmed with the screenshot here. credit to Ray for pointing out the 0 case. Now everyone reading this thread knows, how to write a well rounded destructor and copy constructor for a linked list class..
if(many_nodes == 0)
{
    head_ptr = NULL;
    return;
}

Answer: You need to change this
    node1->data = copycursor->data;         // copy over data to that node
    node1->priority = copycursor->priority;

to this
    node1->data = copycursor->data;         // copy over data to that node
    node1->priority = copycursor->priority;
    node1->link = NULL;

The problem you have is that the last node in your list is not getting it's link field set to NULL (I am assuming that the Node constructor doesn't do that).
Comment: @JL OK, well I think a complete program is going to be necessary to make any progress. Try and trim down the code as much as possible, but so that it is still showing this error, and then post all the code here.


If A is dense in (X,T) and A = the countable intersection of open sets in X, then each open set is dense

Question: If $A$ is dense in $(X,T)$ and $A$ is an $G_{\delta}$ set $A$ $= \bigcap _{n=1}^{\infty} B_n $ such that $B_n \in T$ $\Rightarrow B_n$ for each n is dense in $(X,T)$.
I have: $A$ $= \bigcap _{n=1}^{\infty} B_n $ $\Rightarrow$ $A$ $\subseteq \bigcap _{n=1}^{\infty} B_n $ $\Rightarrow \forall n \in \Bbb N, A \subseteq B_n$.
And any subset that contains a dense subset in X is dense in X.
I feel like I'm skipping something between the subset and the for all statements.  Does this proof make sense or should I have more between the two statements?
Comment: It really is that easy. To say it a little more concisely, you need only observe that if $U$ is a non-empty open set, then for each $n\in\Bbb N$ we have $U\cap B_n\supseteq U\cap A\ne\varnothing$, so $B_n$ is dense in $X$.
Answer: You can conclude directly from $A = \bigcap_{n=1}^\infty B_n$ that $A \subseteq B_n$ for all $n$.
And so $X = \overline{A} \subseteq \overline{B_n} \subseteq X$ so $B_n$ is dense (expanding the comment about "any subset that contains a dense subset of $X$ is dense in $X$").
It really is that simple.


Minha JTable não atualiza quando adiciono uma row [Resolvido]

Question: Eu tenho uma JTable na minha MainForm que recebe os dados de um form em outra janela só que depois de receber os dados a JTable não atualiza.
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement psm = null;
String cod = txtCod.getText();
String sql = "SELECT * FROM produtos WHERE cod = "+cod;
String nome = null;
float valor = 0;
String desc = null;
try{
    conn = DatabaseConnection.MysqlConnection();
    psm = conn.prepareStatement(sql);
    psm.execute();

    ResultSet result = psm.executeQuery(sql);

    while(result.next()){
        nome = result.getString("nome");
        valor = result.getFloat("valor_m2");
        desc = result.getString("descricao");
    }
    if(txtHeight.getText().equals("") && txtWidth.getText().equals("")){
        float a2 = Float.parseFloat(JOptionPane.showInputDialog(rootPane, "Por favor insira a área da peça", "Área", HEIGHT));

        float valorm = a2 * valor;

        MainForm mf = new MainForm();
        mf.addInTable(cod, nome, a2, valor, valorm);

        this.setVisible(false);
        psm.close();
        conn.close();
    }
    else{
        float alt = Float.parseFloat(txtHeight.getText());
        float lag = Float.parseFloat(txtWidth.getText());

        float area = alt * lag;
        float valorm = area * valor;

        MainForm mf = new MainForm();
        mf.addInTable(cod, nome, area, valor, valorm);

        this.setVisible(false);
        psm.close();
        conn.close();
    }
}
catch(Exception ex){
    System.out.println(ex);;
}

Aqui ele vai criar a pesquisa e mandar para a JTable no MainForm
public void addInTable(String cod, String prod, float area, float prec, float precTot){
String nom = prod;
String con = cod;
String are = Float.toString(area);
String pre = Float.toString(prec);
String tot = Float.toString(precTot);

DefaultTableModel model = (DefaultTableModel) tblMain.getModel();
model.addRow(new Object[]{con, nom, are, pre, tot});

float total = 0;
total = total + precTot;

lblTrue.setText(Float.toString(total));

E aqui ele adiciona os dados na JTable. Só que como eu disse ele não atualiza a tabela e não mostra os dados.
Answer: Cada vez que entra nesses laços condicionais da sua classe DAO ele cria uma nova instancia de MainForm e manda os dados por isso não da certo.
Tente criar uma classe que tenha todos esses atributos que você deseja retornar e então na sua classe DAO crie um método como por exemplo:
public List<EssaClasseVolta> findAll(){
}

e lá no seu mainFrame você cria uma lista e da um get nesse metodo.
Logo depois é só popular usando for para percorrer a lista.
Comment: o problema não e popular a tabela e sim adicionar na tabela meu amigo me apontou o mesmo fato do mainForm criar uma nova instancia. Mas eu já consegui arrumar, mas mesmo assim muito obrigado pela sua ajuda.


Domino Server Incoming Mail Mime Encoding

Question: I recently installed FP10 to the Domino 9 server and made changes to http.cnf to AddType image/svg+xml .svg
I am not running IHS.  Incoming mail however now has encoded Subject:
=?UTF-8?Q?Breaking_News_-_LeBron:_Trump_is_u?= =?UTF-8?Q?sing_sports_to_=E2=80=98divide=E2=80=99_the_country?=

This only happens to some incoming messages.  What has happened?  Did I change something else, too?
Answer: You need to install interim fix 1 or 2 as this fixes the bug.
Comment: That did it.  FP10 was fine until I added the extra SVG+XML to http.cnf.  This is the only occurrence out of several servers running FP10.  Thanks.


Handling tie with partially matching notes

Question:
Suppose I play this section on a piano.
Should C4 be pressed down 2 separate times?
Or should I just hold it until the end (pressing keys C4GAC5, then ONLY F)?
Thanks a lot!
* For the context, it's from Chopin's Etudes No. 10 Op. 12. Here is one whole line of the sheet:
Comment: I don't know either, Chopin once decided to put it there
Comment: The fifth and the flat sixth just sound horrific when played together. I have no idea why you would want to play them at the same time.
Answer: Both the Ab and the C stay held for the whole bar. The G changes to F half way through.The top C is held for only 3 beats, but since it's the top voice, with up tail, it really needs a crotchet rest after the second chord. A tie will only join two (or more) notes that are the same. So it won't join anything except the two Cs. Afraid it's not very well written at all!
Comment: Your question shows that you recognize it as a tie, so you know the answer.  It's a peculiar way to write it though, when one voice already uses a whole note.  Why not that voice too?  Perhaps there is context that you haven't mentioned?
Comment: @LaurencePayne Thanks for the response! For the context, this is from Chopin's Étude Op. 10, No. 12. As for the question, I wasn't sure how strong is tie notation acting on notes. I tried to look up the definition first but I didn't find one that is specific enough to solve my problem. It would be great if you could let me know anything that I can refer to.
Comment: Will Wikipedia do?  In this case it offers a concise and correct definition:

"In music notation, a tie is a curved line connecting the heads of two notes of the same pitch and name, indicating that they are to be played as a single note with a duration equal to the sum of the individual notes' values. A tie is similar in appearance to a slur, however slurs join notes of different pitches which need to be played independently, but seamlessly."

https://en.wikipedia.org/wiki/Tie_(music)
Comment: @LaurencePayne - the OP, probably a beginner, obviously wondered whether the dots on the down stem were tied together. Let's face it, it could be written far better, anyway. The Ab is a semibreve, and the low C could be also. There would be no doubt as to which voice it is, being the lowest note. Maybe if the OP had seen Wiki. the question wouldn't have been posed. It's so with quite  a few.
Comment: Hi @LaurencePayne, I checked WikiPedia in the first place. However because I learnt to play the piano in a language other than English in the very first place, I wasn't sure even after reading it, that whether under a tie notation the pitches are bounded together. I don't have my mentor around me so I decided to post a question here. Thanks for the help anyways.
Comment: OK.  Well, @Phoebus, if you find anything clearer than "...a tie is a curved line connecting the heads of two notes of the same pitch and name, indicating that they are to be played as a single note..." let us know!
I can sort of see a reason for that notation, now you show us the context, if Chopin wanted the Ab to act as a pedal note through the changing harmony...  but probably I'm merely trying to justify a music engraver's whim after the fact!
Answer: The OP's notation seems to be based on what was in the first edition, which apparently has a couple of typos in that bar - the Ab whole note is in a strange place, and the top C at the start of the bar doesn't have a dot.

Most later editions have rewritten this with the bottom C as a whole note:

It has always been a challenge for engravers to lay out keyboard music of this complexity so it is "easy to read", and different publishers often come up with different solutions. Also note the variety of "creative interpretations" added to Chopin's simple directions of "pp" and "Poco rall"!
IMSLP is a great resource for comparing different editions of standard works like this - unless you are required to use a specified edition for an exam or a competition, look at everything available and make up your own mind how you want to play the piece.
Comment: May I know where did you find the version with ped notations? I have been gussing them myself this whole time. Thanks :D
Comment: In the first example, the Ab semibreve is correctly placed -- according to engraving standards of the time. (French, anyway -- I'm not sure about elsewhere -- Artaria placed them at the left.)  There was a convention that a note that fills a bar may be placed further to the right -- even about halfway across the bar! All the above applies when there are also shorter-duration notes at the start of the bar -- if all the bar's notes fill it, the issue doesn't arise, and, even nowadays, the notes may be put further away from the preceding bar line than is usual when there are shorter notes.
Comment: @RosieF: A whole note or vertical stack of whole notes may sensibly appear centered in a bar that's as wide as one containing two half notes, but it seems weird that that principle would override the principle that simultaneous notes should be vertically aligned, at least with any single staff.


Nullary and unary operations defined on a uniquely complemented lattice?

Question: A lattice is a set $L$ with two binary operations, $\lor$ "join" and $\land$ "meet". In a complemented lattice, for every element $a$ there exists an element $a^{\perp}$ such that $a \lor a^\perp=1$ and $a \land a^\perp=0$. Note this "complement" element need not be unique. But if it is unique, as is true in distributive lattices, the lattice is called a uniquely complemented lattice.
It seems to me that in a uniquely complemented lattice, each element having a unique "complement" element could define a unary operation $\perp: L \to L$ defined by $\perp(a)=a^\perp$. But I have never seen it developed this way (the way the additive inverse is defined as unary operation in a group or the multiplicative inverse is defined as a unary operation in a field). Is there a problem with defining a uniquely complemented lattice this way: that is, a lattice with a unary operation $\perp$ in addition to its two binary operations $\lor$ and $\land$?
Along the same lines, is it OK to define $0$ and $1$ as nullary operations on the lattice, the same way $0$ and $1$ are considered nullary operations on a ring? Although it seems correct to me, I could be missing something. Have nullary and unary operations been described this way in lattice theory before? Thanks for reading!
Answer: Nullary (constants) and unary operations are perfectly fine in universal algebra. And indeed, top and bottom elements in a bounded lattice are defined using constants. It's a little bit surprising that you didn't meet that definition yet; actually the phrase "in the language of bounded lattices" implicitly says that you have both 0 and 1 in your signature.
I don't exactly remember the treatment there, but it is for sure that in B&S A Course in Universal Algebra this is explained this way.
Comment: Thanks for your answer, Pedro! And thanks for the book you referenced - it looks like a great resource!


Learning the piano strictly by learning chords...and saving scales and complex fingerings for later...

Question: I studied piano for a couple years as a young adult.  I enjoyed it, but got busy with school/activities/other instruments and it fell by the wayside.
I've been interested in picking it up again and have read some FAQs on the web that suggest a different way of learning than I've been exposed to...basically foregoing scales, individual notes, and complex fingerings, and focusing on learning chords (and patterns) to play full songs.  This is interesting because it would allow me to play full songs pretty quickly.
Despite the more traditional concerns, is this a valid way to learn Piano?  Has anyone done this with much success?  And if so, any suggestions on how to do about doing this (i.e. take an online course, get a teacher, etc...)?
Comment: I can't speak from experience, but you can definitely learn with this.  A lot of synth/keyboard players start out this way.  Songs where the focus is more on the vocals and the melody is uncomplicated are a good choice, since glossing over the melody won't be noticed or can simply provide a different feel to the song.  I'm not a strong sight reader so being able to just play chords when I need to pick up and play a new song in a pinch is very useful.
Comment: The newest versions of GarageBand for Mac (not the iPad version) include video lessons for piano and guitar.  To a certain extent, the emphasis in the piano lessons is slightly towards chords.  Especially in the "master class" segments of learning to play pop songs from the artists themselves.
Answer: Depends on your goals.  A comprehensive mix of reading, playing by ear, improvisation and theory will take you the farthest but chords are a fun shortcut to good times jamming with friends or self-accompanying singing.
Answer: Learning chords before mastering scales can be a fast jump start because many songs only use 3 or 4 chords. Then, once you gain some confidence, you could consider learning scales one by one - ie. not all 12 at once. You would probably have mastered C, and perhaps F and G as well, so reviewing might be much easier than it seems. Try not to rush the process, enjoy learning one new scale each time until you feel comfortable playing in that key, then move on to another key... This way you would be able not only to jam, but also to solo.
After you master the keys of C, F and G, you might want to learn (or review, if you have learned it before), how to modulate from F to G. I have had a considerable success learning this way, and indeed, that modulation sounds exciting! It boosts my confidence and desire to learn more. Video lessons are widely available in YouTube if you find them helpful.
Answer: I'm just starting to learn as well I think it's a good idea to make sure you get to play stuff you enjoy. Although learning your scales is important, I found it fun to look up the chords to songs I like and learn how to play them as well.
Answer: Most people who play piano/keyboards strictly in a popular setting (jazz, rock, country, Latin, etc) learn it exactly how you're describing: learn chords and chord voicings first. The only people who don't do it this way are the classical students (they learn scales and arpeggios.) But in my opinion the only thing useful about practicing scales is to improve your finger coordination and dexterity. It does little to help you learn how to make music, improvise, play with a band, etc. so it basically depends on what kind of music you want to play and in what type of setting. Also you should note that if you learn chords first, then you eventually pick up the right notes in the scales anyway, because the chord progressions tend to cover all the possible notes in the key. In other words, if you learn the chords and melody to some songs in the key of C, then you'll learn the C major scale without even trying.
Answer: That's how I was taught chords as a child. I did allow me to progress more rapidly and I learned how to play pop songs and accompany singers fairly quickly.
However, I'm now struggling to learn the more complex/alternate fingerings as reflected in my question here: Tricks to unlearn chords learned by shape on the piano
It all depends on how far you want to get and whether you'll be more encouraged by seeing progress faster or discouraged if you hit a wall later.


How to obtain this result using Ito's Lemma?

Question: My book writes that when:

$dx = a(x,t)dt + b(x,t)dz$
$x' := x + dx$

Then using Ito's lemma:
$E[F[x+ \Delta x, t + \Delta t \mid x)] = F(x,t) + [F_t(x,t) + a F_x + \frac{1}{2} b^2 F_{xx}] \Delta t + o(\Delta t)$.
Now I am not sure about two things:

How can Ito's lemma be used to say something about expectations - I thought it was just for functions

Where does the first term [$F(x,t)$] come from? I don't see it in Ito's lemma.

Thanks in advance!
Comment: Is $z$ a Brownian motion ?
Comment: @Tom-Tom Yes, correct.
Answer: It's simpler than you think. The expectation $\mathbb{E}\left[F(x+\Delta x,t+\Delta t)|x,t\right]$ is an expectation over all possible Brownian motions $z$. It will not depend on $z$ since we average over it realizations during the time $\Delta t$. So it should only depend on $\Delta t$. To obtain it, one has to expand $F$ to first order in time and to the second order in space. Taylor expansion yields, for any $\delta x$, $\delta t$
$$F(x+\delta x, t+\delta t)=F(x,t)+\partial_tF(x,t)\delta t+\partial_xF(x,t)\delta x+\frac12\partial_x^2F(x,t)\delta x^2+o(\delta t)+o(\delta x^2).$$
Now plug the $\Delta x$ obtained from the equation and compute the expectation.
We have $\mathbb{E}[\Delta z]=0$ because $z$ is a Brownian motion. for the same reason $\mathbb{E}[(\Delta z)^2]=\Delta t$. Using $\Delta x=a \Delta t+b\Delta z$, you get the desired result. The $F(x,t)$ remains in first position because it is a constant with respect to $z$ so its average is equal to $F(x,t)$. The $(\Delta t)^2$ coming from $(\Delta x)^2$ is absorbed in the $o(\Delta t)$.
Comment: Thank you - this answer was the easiest for me to understand.
Comment: @tom-tom Just curious ... why did you not include the $o(\Delta t)$ term when writing $E(\Delta z)^2=\Delta t$ as you had suggested in your comment?
Comment: @Dr.MV Because there is no need. $E[(\Delta z)^2]=\Delta t$ is exact. But $E[(\Delta x)^2]=a^2(\Delta t)^2+2abE[\Delta z]\Delta t+b^2E[(\Delta z)^2]$.
Answer: Ito's Lemma states
$$dF(x,t)=\frac{\partial F}{\partial t}dt+\frac{\partial F}{\partial x}dx+\frac12 \frac{\partial^2 F}{\partial x^2}(dx)^2$$
We can write the increment of $F$ as
$$\Delta F=F(x+\Delta x,t+\Delta t)-F(x,t)=\frac{\partial F}{\partial t}dt+\frac{\partial F}{\partial x}dx+\frac12 \frac{\partial^2 F}{\partial x^2}(dx)^2+o(\Delta t) \tag 1$$
Using $E\left(dx\right)=a(x,t)dt$ and $E\left((dx)^2\right)=b^2(x,t)dt+O(\Delta t)^{2}$ in $(1)$ gives
$$\begin{align}
E\left(F(x+\Delta x,t+\Delta t)\right)&=E\left(F(x,t)\right)+E\left(\frac{\partial F}{\partial t}dt+\frac{\partial F}{\partial x}dx+\frac12 \frac{\partial^2 F}{\partial x^2}(dx)^2+o(\Delta t)\right)\\\\
&=F(x,t)+\frac{\partial F}{\partial t}dt+a(x,t)\frac{\partial F}{\partial x}+\frac12 b^2(x,t)\frac{\partial^2 F}{\partial x^2}+o(\Delta t)
\end{align}$$
as was to be shown!
Comment: @dreamer You're welcome!  My pleasure.  The second equality in $(1)$ is effectively the Fundamental Increment Formula/definition of the total differential from calculus.
Comment: Thanks a lot! That helps. Only thing I'm not sure about is the second equality in (1). Why is that so?
Comment: I have been too slow... Note that you should correct some point : $E((dx)^2)=b(x,t)^2 \,dt\color{red}{+o(dt)}$.
Comment: Have accepted the other answer (but have upvoted yours) as it was slightly easier for me undertand, though I appreciate your help very much (but can unfortunately only accept one). Hope you understand!


c legacy code gives me pointer on left; needs integral value on right error

Question: i try to compile lagecy code in visual studio 2013
in some part of the code i have this section which gives me compilation error which i dont understand :
{

    const char* str ="111";
        const char* str1 = "TTTTTT";
        str -= str1;
...
...
}

 \example\example.c(170): error C2297: '-=' : illegal, right operand has type 'const char *'
 \example\example.c(170): error C2114: '-=' : pointer on left; needs integral value on right

what is wrong here ?
Comment: This code is invalid in C and C++. What do you expect the result should be?
Comment: What is the result which you want?
Comment: Effectively, that's the same as `str = str - str1;` Pointer subtraction is only valid if the two pointers are pointing to elements within (or just past the last element) of the same array. The result is an integer (of type `ptrdiff_t`) and you're trying to convert the integer back to a pointer without a cast. Not that the code makes much sense anyway! `str -= str1` is even more illegal than `str = str - str1` and is not allowed at all by the C standard.
Answer: This code looks terrible. It's not valid C or C++. We can only guess what it meant to do. Perhaps you could replace the last line with the following:
str = (void*)(str - str1);

but there's no guarantee it will work correctly.
Answer: I believe the error description is quite self-explanatory. You can't have const char* on the right if you've got pointer on the left. Such arithmetics are only possible using integers.


Colocar font externa em site

Question: Eu tenho uma font que preciso de pôr no site (edosz.ttf), estive a pesquisar e acabei com este código:
@font-face{
  font-family: "edosz";
  src: url('edosz.ttf');
}

mas não dá! Alguém me podia ajudar?
Answer: Para adicionar uma fonte ao seu site você utilizará a regra do css chamada @font-face.
Suporte dos navegadores para: @font-face.
@font-face{
    font-family: NomeDaFonte;

    /*Caso a fonte esteja na mesma pasta*/
    src: url("ArquivoDaFonte.eot");
}

Lembrando que o caminho depende do local do arquivo.
 @font-face{
    /*Caso a fonte esteja dentro de uma pasta*/
     src: url("/pasta/ArquivoDaFonte.eot");

    /*Caso a fonte esteja na pasta anterior*/
     src: url("../ArquivoDaFonte.eot");
}

Caso queira checar se o usuário possui a fonte instalada em seu sistema:
@font-face {
    src: local(ArquivoDaFonte.eot), url(ArquivoDaFonte.eot);
}

As fontes possuem alguns formatos.
TrueType - .ttf
format('embedded-opentype')

OpenType - .ttf, .otf
format('embedded-opentype')
Suporte dos navegadores para: TTF/OTF.

TrueType with Apple Advanced Typography extensions - .ttf
format('embedded-opentype')

Embedded OpenType - .eot
format('embedded-opentype')
É o formato que deixa o @font-face compatível com  o IE7/8/9.
Suporte dos navegadores para: EOT.

SVG Font - .svg, .sgvz
format('embedded-opentype')
Suporte dos navegadores para: SVG.

WOFF2 - .woff2
format('woff2')
Traz uma redução de aproximadamente 30% do tamanho do arquivo.
Suporte dos navegadores para: WOFF2.

Caso precise de um conversor eu utilizo este aqui: Everything Fonts
Exemplo de suporte mais intenso aos browsers.
@font-face {
    font-family: 'NomeDaFonte';
    src: url('ArquivoDaFonte.eot'); /* IE9 */
    src: url('ArquivoDaFonte.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
        url('ArquivoDaFonte.woff2') format('woff2'), /* Browsers de ponta */
        url('ArquivoDaFonte.woff') format('woff'), /* Browsers atualizados */
        url('ArquivoDaFonte.ttf')  format('truetype'), /* Safari, Android, iOS */
        url('ArquivoDaFonte.svg#NomeDaFonte') format('svg'); /* iOS */
}

Answer: Para o código abaixo, a fonte deve estar na mesma pasta do arquivo CSS, caso esteja em um diretório diferente é necessário referência-lo corretamente.
@font-face{
  font-family: "edosz";
  src: url('edosz.ttf') format('truetype');
}

Answer: Alem do código do font-face é necessário você atribui-lo a algum seletor no css como:
Seu @font-face
@font-face{
  font-family: "edosz";
  src: url('edosz.ttf');
}

Atribuindo a nova fonte a um elemento da página:
body {
    font-family: edosz;
}

Colocar font externa em site


How do i store address in a register on x86

Question: I have a piece of code as below:
<code>    .section .data
    myvar:
    .long 4,3,2,1

    .section .text
    .globl _start
    _start:
     movl $0, %edi
     movl myvar(,%ed1,4), %eax
     movl $0, %ebx
</code>
I would like to store address of last element of my array "myvar" in ebx (which is 1),  How do i do that ?
Answer: My mental compiler outputs Intel syntax, not AT&T's, but you should get the idea:
<code>lea eax, myvar + 12
</code>
eax now has the address of the '1' value.
Comment: thanks, need to check what's the equivalent of lea in AT&T syntax, i guess it's movl but not sure
Comment: lea is supported in at&t syntax as well - that I do know :)
Answer: Okay i got it, we can use $myvar + N
example:
<code>     .section .data
      myvar: .long 4,3,2,1
     .section .text
     .globl _start
      _start:
     movl $0, %edi
     movl $myvar+0, %eax
     movl $myvar+4, %ebx
     movl $myvar+8, %ecx
     movl $myvar+12, %edx
     movl $myvar+16, %edi
     movl $1, %ebx
     movl $1, %eax
     int $0x80
</code>


Preferred methods for graphing time-series data to present "averages"?

Question: I have data from a load test of a web site with several thousand data points spread out over roughly 30 minutes (the values are the response time of the site in milliseconds). The values are spread out among the 30 minute range, but not at a constant rate (i.e. there may be a few milliseconds between some points, other points maybe at the same timestamp, etc).
I'd like to present this data visually and chart it, but I'm not sure of the best method for doing so - there is a good amount of variance around any sort of concept of average values or a trend line.
Is there any generally accepted best practices for methods on how to graph data of this type? I'm concerned about choosing a poor method for averaging/smoothing out the data and misrepresenting the data - such as underweighting some outlier values.
I've played around with a line chart with the timestamps on the x-axis and the average of samples in the same minute on the y-axis. I'd also like to consider graphing a moving average of the data, but I'm unsure if I should be averaging datapoints in the same N minutes or a window of the last N points.
I'd like to make sure that whatever choice I make would appear to be a rigorous representation of the data and not too amateur-ish.
Update: below is a sample of what I have produced so far, each point on the chart is taken as the mean/median of all of the samples within the same minute (i.e. within 11:12:00.000 and 11:12:59.999). I included the number of samples per minute as a bar chart in the second half of the image to be able to show if any single points in the line chart look as outliers due to a small amount of samples, although aesthetically speaking I think the bar chart takes up way too much real estate for the amount of information it gives.
Answer: I suggest adding an example or two of what you are presently doing so we can better see what you are dealing with.
What you are concerned with is an important issue: how do you convey the "overall" pattern in the time series data while also not misleading viewers by showing just average values? One way I have dealt with this situation is plotting an average or median line along with surrounding quantile bands. For example,

Here, the time series data are from a bootstrap-based simulation so there are hundreds of values associated with each time point. The actual data are plotted in the black line with colored bands showing the variability of values from the simulation. This particular plot is maybe not the best example to show, but you can see that some points have much more variability than others, and you can also assess how the variability is skewed above/below the actual values depending on the position in the series.
UPDATE:
Given your update here are some additional questions and thoughts... What decisions, if any, are made from this visualization? For example, are you looking for specific points in time where there is very slow response time, perhaps above a specific threshold? If so, it may be better to simply plot all of the points as a scatter plot, and then also plot a time series line showing the average value, as well as some lines delineating the bounds you are concerned about. This recommendation is not appropriate if you have numerous observations at some time points (too much clutter), or if your time measurement is not sufficiently coarse (in which case you can bin response data into minute-wide time of day intervals). But the visualization recommendation will certainly be affected by what decision(s) will be supported with it. In my example, I was looking at such plots side by side, one from one simulation and the other from another simulation (each simulation using different parameters) so I could assess the variability of the underlying model due to sampling error.
Comment: Another possibility would be to plot density strips for each time period as opposed to discrete colors for quantiles, see this article in the American Statistician for examples http://dx.doi.org/10.1198/000313008X370843 . The graph posted seems pretty informative as is though (+1)
Comment: @matt b, I just found an ungated version of the [paper](http://www.mrc-bsu.cam.ac.uk/personal/chris/papers/denstrip.pdf). Also check out the R package [denstrip](http://cran.r-project.org/web/packages/denstrip/index.html). In retrospect though I think the suggestion may be overkill, you will only have slight gains over just plotting the quantiles of interest and it will be much more computationally expensive (hence reducing its utility as an exploratory tool).
Comment: Thanks, I like this idea a lot. I also updated my main question with an example of what I've done so far as requested. Is it fair of me to average the data points into minute buckets, when each bucket may not have the same amount of samples in it?
Comment: @Andy W, do you happen to have an example image of that method? It seems like I can only read the abstract of that article without a login.
Answer: Have you considered a scatterplot of the data themselves?  That's an approach I really like.  It lets the viewer make their own conclusions about the presence and significance of trends, and it doesn't conceal variability or outliers.  Alpha-blending the points will help if you have serious overplotting (which it sounds like you might).  You can also overlay whatever trend you like and take comfort in knowing that the data are still present to speak for themselves.
Comment: @matt  That's a classic case for alpha-blending (see the image in the comment above).  It requires some experimentation with the level of transparency, but you'll likely be able to find something that works.  It still won't be perfectly clear how many points are at each spot on the axis, but it gives the viewer a sense of density that lines don't.
Comment: Matt, just to clarify on the "alpha-blending" comment: I assume you mean setting the alpha channel of the graphics to allow for some level of transparency in displayed graphical elements?
Comment: I did attempt a scatterplot, but I found that I had such tight clustering of the datapoints for each x-value that it's a bit hard to tell, personally, just how many values appear at certain levels - see http://i.imgur.com/FsNC1.png for example. I'm nervous that a chart like this doesn't make it obvious just how many points appear in the cluster around the y=0 line
Comment: I think this may be a good approach for visualizing outliers, I'm not so sure it is a great idea for the whole distribution though. Also as a note in regards to your linked question, Tufte has an example in his Visual Display of Quantitative Information where plotting the lines between the temporal dimension (similar to your chart 1 on the linked question) shows an obvious periodic pattern, whereas it is much more difficult to discern with just the scatterplot without the lines.
Comment: @Josh  Right - as in [this image](http://had.co.nz/stat405/resources/drills/plot-drills/ggplots/soheight14.png)
Comment: @Andy It all depends on the purpose of the plot, as Josh mentions.  The scatterplot that matt posted seems a bit more informative than the line plot to me (especially the spikes after 14:07), but I don't know what the context is (and I've been obsessing over fat-tailed distributions lately).  As far as the linked question goes: do you mean connecting the dots?  I'll definitely try that out when I finally have time to get back to that dataset.  It's a very seasonal process, actually, and you can barely tell from that scatterplot.  Thanks for the tip.


Avoiding false sharing of SPSC queue indices

Question: Let's imagine a lock-free concurrent SPSC (single-producer / single-consumer) queue.

The producer thread reads head, tail, cached_tail and writes head, cached_tail.
The consumer thread reads head, tail, cached_head and writes tail, cached head.

Note, that cached_tail is accessed only by the producer thread, just like cached_head is accessed only by the consumer thread. They can be thought as private thread local variables, so they are unsynchronized, thus not defined as atomic.
The data layout of the queue is the following:
#include <atomic>
#include <cstddef>
#include <thread>

struct spsc_queue
{
    /// ...

    // Producer variables
    alignas(std::hardware_destructive_interference_size) std::atomic<size_t> head; // shared
    size_t cached_tail; // non-shared

    // Consumer variables
    alignas(std::hardware_destructive_interference_size) std::atomic<size_t> tail; // shared
    size_t cached_head; // non-shared

    std::byte padding[std::hardware_destructive_interference_size - sizeof(tail) - sizeof(cached_head)];
};

Since I want to avoid false sharing, I aligned head and tail to the L1 cache line size.
The pseudo-code-ish implementation of the push/pop operations is the following:
bool push(const void* elems, size_t n)
{
    size_t h = atomic_load(head, relaxed);

    if (num_remaining_storage(h, cached_tail) < n)
    {
        cached_tail = atomic_load(tail, acquire);

        if (num_remaining_storage(h, cached_tail) < n)
            return false;
    }

    // write from elems

    atomic_store(head, h + n, release);
    return true;
}

bool pop(void* elems, size_t n)
{
    size_t t = atomic_load(tail, relaxed);

    if (num_stored_elements(cached_head, t) < n)
    {
        cached_head = atomic_load(head, acquire);

        if (num_stored_elements(cached_head, t) < n)
            return false;
    }

    // read to elems

    atomic_store(tail, t + n, release);
    return true;
}

void wait_and_push(const void* elems, size_t n)
{
    size_t h = atomic_load(head, relaxed);

    while (num_remaining_storage(h, cached_tail) < n)
        cached_tail = atomic_load(tail, acquire);

    // write from elems

    atomic_store(head, h + n, release);
}

void wait_and_pop(void* elems, size_t n)
{
    size_t t = atomic_load(tail, relaxed);

    while (num_stored_elements(cached_head, t) < n)
        cached_head = atomic_load(head, acquire);

    // write to elems

    atomic_store(tail, t + n, release);
}

At initialization (not listed here), all the indices are set to 0.
The functions num_remaining_storage and num_stored_elements are const functions performing simple calculations based on the passed arguments and the immutable queue capacity - they do not perform any atomic reads or writes.
Now the question is: do I need to align cached_tail and cached_head as well to completely avoid false sharing any of the indices, or it is okay as it is. Since cached_tail is producer private, and cached_head is consumer private, I think cached_tail can be in the same cache line as head (producer cache line), just like cached_head in the same cache line as tail (consumer cache line) without false sharing to ever happen.
Am I missing something?
Comment: FWIW, I'm pretty sure you don't need to align the cached values, but didn't get enough conviction yet.
Comment: You're probably going to want 3 cache lines: writer-only, reader-only, and stuff accessed by both.  Ideally you can avoid having both threads write the shared line frequently.  Even one writing and the other reading keeps flipping it from Modified to Shared and requiring the thread doing a store to do an RFO to regain exclusive ownership.  But having the non-shared vars in separate cache lines could allow a bit more progress to be made / in-flight while waiting on those share requests or RFOs.
Comment: @PeterCordes I don't entirely understand your comment. Do you suggest to put both `cached_tail` and `cached_head` into a common, but third cache line? Even if they are not shared across threads, they are handled by different threads (`cached_tail` by the producer, `cached_head` by the consumer). Look at the beginning of my question at the access patterns.
Comment: I should have said "producer only" / "consumer only" / stuff accessed by both. Obviously variables that are only accessed by one of the threads should go in a cache line that the other thread never touches. IDK if you thought I was saying to break it down by write-only vs. read-only data?  No, I meant writer = producer. Anyway, the hard question is how to split up other variables that are actually shared, and whether there's anything to gain or lose from having more lines so you can have vars that only the producer writes (read by consumer) in a line that the producer can always at least read.
Comment: @PeterCordes Ah, okay, it's clear now. Well, `head` and `cached_tail` are always updated together in `push()` - just like `tail` and `cache_head` in `pop()`. But `head` and `tail` are accessed by both threads. At the worst case I can use four cache lines, one for each. According to your suggestion `head` and `tail` should go to the same cache line, since they are accessed by both threads. That would definitely cause false sharing. I don't think it is a good idea, also all lock-free implementation I've seen put them (`head` and `tail`) into separate cache lines.
Comment: @PeterCordes What's the problem with the current 2 cache lines version?
Comment: `push` has to *modify* `cached_tail`, but `pop` will sometimes read `head` in that same line, taking it out of MESI Modified state.  Your caching strategy makes that infrequent so it may be fine or at least not worth another extra cache line.  Re: `head` and `tail` in the same line: I didn't think that through fully, or I was for some reason thinking of a linked-list implementation where pop detects empty via a NULL pointer in a node instead of by looking at the producer's state.  So yes, as I eventually got to saying, it's a question of how to split up the vars that both threads R and/or W.
Comment: Oh, and in the fast path `push` only reads `cached_tail`, and that's still fast with the line in MESI Shared state.  So yes this is probably good.  If the queue is near-empty most of the time then contention is unavoidable and separate cache lines for the fully private `cached_tail` and `cached_head` are unlikely to help.  Although they *might*?  Also if we're lucky, the compiler can keep the cached head / tail in a register if called inside a fairly tight loop that doesn't inline too much other stuff.
Comment: @PeterCordes Haha, that was a typo. Fixed now.
Answer: Thank you for providing the pseudocode - it is still lacking some details, but I think I get the basic idea. You have a bounded SPSC queue where the indexes can wrap around, and you use the cached_tail variable in push to check if there are free slots, so you can avoid loading tail from a potentially invalidated cache line (and vice versa for pop).
I would suggest to put head and cached_tail next to each other (i.e., on the same cache line), and tail and cached_head on a different one. push always reads both variables - head and cached_tail, so it makes sense to have them close together. cached_tail is only updated if there are no more free slots and we have to reload tail.
Your code is a bit thin on details, but it seems that there is some room for optimization:
bool push(const void* elems, size_t n)
{
    size_t h = atomic_load(head);

    if (num_remaining_storage(h, cached_tail) < n)
    {
        auto t = atomic_load(tail);
        if (t == cached_tail)
          return false;

       // we only have to update our cached_tail if the reloaded value
       // is different - and in this case it is guaranteed that there
       // is a free slot, so we don't have to perform a recheck.
        cached_tail = t;
    }

    // write from elems

    atomic_store(head, h + n);
    return true;
}

That way cached_tail is only ever updated when head is also updated, so this is another reason for them to be on the same cache line. Of course the same kind of optimization can be applied to pop as well.
That is exactly why I wanted to see some code, because the access pattern is crucial to determine which variables should share a cache line and which should not.
Comment: Good idea with delaying update of `cached_tail` or `cached_head`.  That removes any possible benefit to having 4 separate cache lines.  (Without that I was wondering if it made any sense to split them up so spinning on a retry of push or pop isn't writing the line the other thread needs to write.  In a full or empty queue situation.)  Even then I'm not sure it's significant.  If the line is in Shared state the other thread could read it more easily, but would still have to RFO on the store anyway, whether we invalidate it again after their read or not.
Comment: (I think that same optimization can work for `pop`, or at least a similar one.)
Comment: @PeterCordes yes, of course the same optimization can be applied for `pop` too. I did want to mentioned that, but apparently forgot. Thanks for the note, I have updated my answer.
Comment: Ah, yes you can of course avoid repeated writes to the cached values. In fact I would use a local variable to track the index and only write to the cached variable just once when there is enough space to proceed s Peter Codes already suggested.
Comment: Great answer and idea on the further optimization! I updated my answer with some more details, including memory ordering and waiting versions of `push` and `pop` (`wait_and_push`, `wait_and_pop`). If you have any more suggestions about them, don't hesitate to share with me. ;]
Comment: I think I could use the same optimization you suggested to the spinwait versions as well.
Comment: "we only have to update our cached_tail if the reloaded value is different" - this is only true when `n == 1`, otherwise it only means that there is more space, but after the re-load it can be still not enough for `n`, so re-testing the condition `num_remaining_storage(h, cached_tail) < n` is required if `n > 1`. Still, it is a great optimization when `n == 1`. I have separate functions for batch (bulk) and single-value operations so there is no need for extra branches.
Comment: Yes you are right, I did not realize from your pseudocode that you want to perform bulk operations. However, I don't think that this optimization works for the blocking functions, since you are actually waiting for head/tail to be updated. FWIW: the memory orderings look fine.
Comment: @mpoeter There is a short chat about the blocking functions here, if you are interested (the point is that the delayed assignment of the cached indices is still advantageous in this case): https://chat.stackoverflow.com/rooms/212865/room-for-plasmacel-and-peter-cordes


Como direciono o link para a âncora e fecho o modal ao mesmo tempo?

Question: Tenho alguns links num modal feito em React que vão para âncoras da página que o modal foi aberto. Estou usando href para a âncora e o evento onClick para fechar o modal. Exemplo:

Porém, um anula o outro. Quando tenho o evento, a âncora não funciona, quando tiro o onClick, a âncora funciona, porém o modal não fecha.
Programação do modal:
const MyOwnModal = (props) => {
return (
    <Modal
    {...props}
    size="lg"
    dialogClassName="modal-90w"
    aria-labelledby="contained-modal-title-vcenter"
    centered
  >
    <Modal.Header closeButton>
      <Modal.Title id="contained-modal-title-vcenter">
        POLITICA DE PRIVACIDADE
      </Modal.Title>
    </Modal.Header>
    <Modal.Body>

Programação do onHide:
<MyOwnModal
            show={modalShow}
            onHide={() => {
              if(window.location.hash){
                setModalShow(false);
            }}}
          />

Anteriormente, eu não tinha adicionado este if no onHide. O adicionei buscando informações na internet, mas não ajudou muito. Com ele, o modal só fecha direcionando para a âncora na primeira vez.
Alguém pode ajudar?
Answer: Se você está usando diretamente o window.location (nem sempre comum num app react), você pode navegar para uma âncora usando diretamente
window.location = '#some-hash'

O modal pode receber um onSectionSelected, que fecha o modal e devolve um section/hash para então navegar.


Consistency of Norm

Question: Definition: Norm $p$ on $\mathbb C^{n\times n}$ is consistent if $p(AB)\leq p(A)p(B)$ for all $A,B\in \mathbb C^{n\times n}$.
I want to show
$p(C)=\max_i \sum_j |c_{ij}|$ is consistent, where $C\in \mathbb C^{n\times n}$.
By verifying the definition directly, I got a page of messy expressions, which did not lead me to anywhere. Also, Cauchy-Schwarz does not work well here. Any hint will be appreciated.
Comment: Can you show that $p(C)=\max\{\|Cx\|_\infty:\|x\|_\infty=1\}$, where $\|x\|_\infty=\max_i|x_i|$?  If so, this is a one-line proof.
Comment: In $\max\{\|Cx\|_\infty:\|x\|_\infty=1\}$, the $x$ is a vector in $\mathbb C^n$.  Sorry for the confusion.
Comment: @Aweygan I managed to show that $p(C)\geq \max\{||Cx||_{\infty} \colon ||x||_{\infty}=1\}$, by Cauchy-Schwarz. Also, $||\cdot||_{\infty}$ itself is not consistent.
Answer: Let's write $q(C)=\max\{\|Cx\|_\infty:x\in\mathbb C^n,\|x\|_\infty=1\}$. I will show that $q(C)=p(C)$.
If $x\in\mathbb C^n$ and $\|x\|_\infty=1$, we have
$$\|Cx\|_\infty=\max_i\left|\sum_jc_{ij}x_j\right|\leq\max_i\sum_j|c_{ij}||x_j|\leq\max_i\sum_j|c_{ij}|\cdot\|x\|_\infty=p(C).$$
Taking the supremum over such $x$ yields $q(C)\leq p(C)$.
Now choose $i$ so that $p(C)=\sum_j|c_{ij}|$, and consider the vector $x=(e^{-i\arg(c_{i1})},\ldots,e^{-i\arg(c_{in})})\in\mathbb C^n$.  Then $\|x\|_\infty=1$, and
$$p(C)=\sum_j|c_{ij}|=\sum_jc_{ij}e^{-i\arg(c_{ij})}=\left|\sum_jc_{ij}x_j\right|\leq\|Cx\|_\infty\leq q(C).$$
Therefore $p(C)=q(C)$.
Now it's easy to see the norm $q$ is, as you say, consistent.  For if $x\in\mathbb C^n$ and $\|x\|_\infty=1$, then
$$\|ABx\|_\infty\leq q(A)\|Bx\|_\infty\leq q(A)q(B)\|x\|_\infty=q(A)q(B),$$
and taking the supremum over $x$ yields $q(AB)\leq q(A)q(B)$.

Consistency of Norm


Linear combination with an orthonormal basis

Question: Using $W = $ {$(x, y) | x, y ∈ R)$} Let $u = (1,3)$ and $v = (2, 1)$ defined by the inner product
$<u, v> = 2v_1u_1 - v_1u_2 - v_2u_1 + v_2u_2$
Find an orthonormal basis and express the vector $w = (1,1)$ as a linear combination with the obtained orthonormal basis.
As the vectors are orthogonal by the definition and equaling $0$, I normalised the vectors with the definition to obtain:
$u = \left(\frac{1}{\sqrt 65}, \frac{3}{\sqrt 65}\right)$ and $v = \left(\frac{1}{2}, \frac{1}{4}\right)$
Assuming this is correct, as it may not be, then normally a linear combination would be formed by
$(1, 1) = c_1\left(\frac{1}{\sqrt 65}, \frac{3}{\sqrt 65}\right) + c_2\left(\frac{1}{2}, \frac{1}{4}\right)$
How do you apply the definition to the linear combination? Anything I try seems awfully messy. Again, perhaps my calculations were wrong but I'm not sure how.
Comment: $u$ and $v$ are already orthogonal wrt your inner product, so you need only to normalize them. When do that the components of $w$ wrt the normalized $\hat u$ and $\hat v$ are simply $\langle \hat u,w \rangle$ and $\langle \hat v,w \rangle$ respectively. That is $w = \langle \hat u,w \rangle \hat u + \langle \hat v,w \rangle \hat v$
Answer: I can't see where you did get $\;\sqrt{65}\;$ for  $\;u\;$ :
$$\begin{cases}\left\|u\right\|=\sqrt{2\cdot1\cdot1-1\cdot3-3\cdot1+3\cdot3}=\sqrt5\\{}\\
\left\|v\right\|=\sqrt{2\cdot2\cdot2-2\cdot1-1\cdot2+1\cdot1}=\sqrt5\end{cases}\,\implies$$
$$ w_1:=\frac u{\left\|=\right\|}=\frac1{\sqrt5}(1,3)\,,\;\;w_2:=\frac v{\left\|v\right\|}=\frac1{\sqrt5}(2,1)$$
And now: since we have already an orthonormal basis, expressing any vector as a linear combination of it is pretty simple:
$$(1,1)=\left\langle (1,1),\,w_1\right\rangle\,w_1 +\langle (1,1),\,w_2\rangle w_2$$
where we used $\;\langle,\rangle\;$ to denote the inner product defined by your function
Comment: I thought the numbers for the normalisation process had to be squared so that it is the square root of $2 - 3^2 - 3^2 + 9^2$ which is how I got 65. Are you saying the definition negates the squaring function?
Comment: Ok, so Gaussian elimination is not required for finding linear combinations with orthonormal bases?
Comment: @DuncanK3 I don't understand what "squaring" are you talking about...Isn't what I wrote clear?
Comment: Yes what you wrote is great, thanks! I just thought finding the norm involved squaring the components before taking the square root.


normalize a matrix along one specific dimension

Question: I have a matrix of shape [1000,500], and I would like to normalize the matrix along the second dimension. Is the following implementation right?
def norm(x):
    return (x - np.mean(x)) / (np.std(x) + 1e-7)

for row_id in range(datamatrix.shape[0]):
    datamatrix[row_id,:] = norm(datamatrix[row_id,:])

Answer: Your implementation would indeed normalize along the row-axis (I'm not sure what you mean by second dimension as rows are usually the first dimension of matrices, and numpy starts with dimension 0). You don't need to include the colon as it's implicit that you want all the rows.
Do remember to use the float32 dtype in your datamatrix as opposed to a integer dtype as it doesn't do automatic typecasting.
A more efficient, or clean implementation might be to use sklearn.preprocessing.normalize.
But be aware that you're using standard score normalization which assumes your dataset is normally distributed.
Comment: Hi Kasper, thanks. If the data set is not normally distributed, what are other options. Generally, when building machine learning models, we usually normalize them before feeding them to the model.
Comment: @user288609 That depends on how your data is distributed. It's sometimes possible to transform the data to become normally distributed.


Consultar dados em um arquivo txt com python tkinter

Question: Estou criando um sistema simples para consultar dados dos empregados armazenados em um arquivo txt.
def read_from_file():
    with open('dados.txt') as file:
        for line in file:
            line = line.rstrip('\n')
            nome, matricula, supervisor, email, chave, local, centrodecusto = line.split('/')
            base_dados[nome] = matricula, supervisor, email, chave, local, centrodecusto

def write_to_file(nome_data, matricula_data, supervisor_data, email_data, chave_data, local_data, centrodecusto_data):
    with open('dados.txt') as file:
        file.write('\n' + nome_data + '/' + matricula_data + '/' + supervisor_data + '/' + email_data + '/' + chave_data + '/' +  local_data + '/' + centrodecusto_data )

read_from_file()
while True:
    query_nome = simpledialog.askstring('Dados empregados', 'Digite o nome do empregado: ')
    if query_nome in base_dados:
        result = base_dados[query_nome]
        messagebox.showinfo ('Answer',
                             'teste' + query_nome + 'teste' + result + 'teste')

root.mainloop()

Porém código me retorna o seguinte erro:

File "path", line 24, in
      'teste' + query_nome + 'teste' + result + 'teste')   TypeError: must be str, not tuple

Poderiam me ajudar?
Comment: `result = base_dados[query_nome]` está retornando uma tupla.
Answer: A mensagem de erro está sendo bem específica, você está concatenando uma tupla (tuple) em uma string, isso não é possível.

Para corrigir isso de forma bem pontual, você pode transforma a sua tupla em uma string, basta chamar a função str com a tupla como parâmetro:
messagebox.showinfo ('Answer','teste' + query_nome + 'teste' + str(result) + 'teste')

Dessa forma os dados da sua tupla são convertidos para string, sendo exibidos entre parenteses e separados por vírgula, algo semelhante a isso:
('000001', 'Daniel', 'email@example.com', '000001', 'São Paulo', '000001')

Abaixo o seu exemplo com as alterações para que os dados sejam exibidos sem gerar exceção:
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox

base_dados = {}

def read_from_file():
    with open('dados.txt') as file:
        for line in file:
            line = line.rstrip('\n')
            nome, matricula, supervisor, email, chave, local, centrodecusto = line.split('/')
            base_dados[nome] = matricula, supervisor, email, chave, local, centrodecusto

def write_to_file(nome_data, matricula_data, supervisor_data, email_data, chave_data, local_data, centrodecusto_data):
    with open('dados.txt') as file:
        file.write('\n' + nome_data + '/' + matricula_data + '/' + supervisor_data + '/' + email_data + '/' + chave_data + '/' +  local_data + '/' + centrodecusto_data )

root = tk.Tk()
read_from_file()

while True:
    query_nome = tk.simpledialog.askstring(parent=root, title='Dados empregados', prompt='Digite o nome do empregado: ')

    if not query_nome:
        break

    if query_nome in base_dados:
        result = base_dados[query_nome]
        messagebox.showinfo ('Answer',
                            'Nome: ' + query_nome + ' - Dados: ' + str(result) + '.')

root.mainloop()

Comment: Muito Obrigado!!


Run-time analysis of common machine learning algorithms

Question: Does anyone have reference to a summary of run-time analyses for common machine learning algorithms (different flavors of NN, SVMs, etc)?
Answer: Here are some superficial tables:

The Computational Mathematics of Statistical Data Mining. PPT

Table 1 in:

Chu, C. T., Kim, S. K., Lin, Y. A., Yu, Y., Bradski,
G. R., Ng, A. Y., & Olukotun, K. (2006). Mapreduce for machine learning on multicore. Neural
Information Processing Systems (pp. 281–288). PDF
Comment: First link is dead.
Comment: Fixed broken link based on google search. However, there are multiple versions of the relevant presentation online, so this might not be an exact duplicate of the original one.
Answer: I wrote the following article: computational complexity of machine learning algorithms where I keep track of the (theoretical) complexity of learning algorithms and run time analysis based on log-log regressions.


Filling in an ANOVA table

Question: I am given the following table
Source of variation ___ sum of squares __ degrees of freedom __ mean squares __ test statistic __ p
Among or between  ____1874_______________ ----______________-----___________------____0.009
Within groups/error_____16580_____________----_______________-----___________
total_________________-----_______________----
There are 5 groups which 25 plants are separated into.
My attempt at filling in the table:
Source of variation ___ sum of squares __ degrees of freedom __ mean squares __ test statistic __ p
Among or between  ___1874____________5-1________________1874/4_________ (1874/4)/(16580/20) ____0.009
Within groups/error___16580___________25-5_______________16580/20___________
total_______________1874+1650 ______ 25-1
This division of two divisions belong under test statistic and 0.0009 belongs under p
I opted for showing the equations rather than the answer to show where I got the values from. Please do excuse me for the formatting of the tables.
How did I do? Also with a p-value < 0.05 I can reject the null hypothesis correct?
Answer: As far as I can see your table is correct. Well, nearly SST should be 1874+16580
If you set alpha to 0.05 you can reject the null hypothesis of the ANOVA.
Remark: since this is not a concrete problem but you are rather learning about ANOVA in general, please add the self-study tag to your question.

Filling in an ANOVA table


Show that $g'(0)\neq \lim_{x\to 0} g'(x)$

Question: Use the limit definition to show that $g'(0)$ exists but  $g'(0)\neq \lim_{x\to 0} g'(x)$, where
$$g(x)=\begin{cases}x^2\sin\frac1x,&\text{when }x\neq0\\\\
0,&\text{when }x=0\end{cases}$$
I find that when $x\neq 0$, $g'(x)=2x \sin\dfrac1x-\cos\dfrac1x$.
My problem is that when I can't compute
$$\lim_{x\to0}g'(x)=2\lim_{x\to0}x \sin\frac1x-\lim_{x\to0}\cos\frac1x$$
question from Rogawski, Jon. Calculus Single Variable. 2nd ed. New York: W.H. Freeman, 2012. Print.
Comment: I think a mistake I made is I didn't use the limit definition yet, rather I directly computed g'(x) at $x\neq0$.
Comment: I'm pretty sure that you're expected to use ordinary differentiation formulas to handle $g'(x)$ for non-zero $x$; it's only at $0$ that you need the limit definition. But for that you will have to go back to the difference quotient at $0$: $$g'(0)=\lim_{h\to 0}\frac{g(0+h)-g(0)}h\;.$$
Comment: Information on $lim_{x\to0}g'(x)$ http://www.wolframalpha.com/input/?i=limit+2xsin(1%2fx)-cos(1%2fx)
Comment: Using Brian's equation, I find $lim_{x\to0}g'(x)=0$
Comment: Yes: $h\to 0$, and $\sin\frac1h$ is bounded, so the product $\to0$.
Comment: If $lim_{x\to0}g'(x)=0$ and $g'(0)=0$, how could $g'(0)\neq \lim_{x\to 0} g'(x)$?
Comment: Sorry: I misread what you wrote in your previous comment. Everything that I've written has been aimed at the problem of showing that $g'(0)$ exists (and in fact is $0$); I've said nothing about $\lim\limits_{x\to 0}g'(x)$. *That* doesn't exist.
Answer: Assume by contradiction that $\lim_{x \to 0} g'(x)$ exists. Then
$$\lim_{x\to0}g'(x)-2\lim_{x\to0}x \sin(1/x)$$
also exists, thus $\lim_{x \to 0} \cos(\frac{1}{x})$ exists.
Alternatelly, find two different sequences, $x_n, y_n$ so that
$$ \lim_n g'(x_n)=0$$
$$\lim_n g'(y_n)=1$$
Answer: Here's a pretty large for showing that $g'(0)$ exists. By definition
$$g'(0)=\lim_{h\to 0}\frac{g(0+h)-g(0)}h=\lim_{h\to0}\frac{g(h)}h=\lim_{h\to 0}\frac{h^2\sin\frac1h}h=\lim_{h\to 0}h\sin\frac1h\;;\tag{1}$$
can you evaluate that last limit?
For the rest, you already have
$$\lim_{x\to0}g'(x)=2\lim_{x\to0}x \sin\frac1x-\lim_{x\to0}\cos\frac1x\;.$$
The first limit on the righthand side is the same as the limit in $(1)$, and since $\cos\frac1x$ oscillates between $1$ and $-1$ infinitely often as $x\to 0$, the second limit on the righthand side doesn't exist. But as N.S. already pointed out, if $\lim_{x\to0}g'(x)$ existed, so would
$$\lim_{x\to0}\cos\frac1x=2\lim_{x\to0}x \sin\frac1x-\lim_{x\to0}g'(x)\;;$$
since it doesn't, neither does $\lim_{x\to0}g'(x)t$.
Comment: @Raindrop: Now you've got it. And in case you were wondering, the point of this problem is that even though $g'(x)$ exists everywhere, it's not continuous at $x=0$. This is an example of a function that is differentiable, but not *continuously* differentiable.
Comment: yeah it's 0.http://www.wolframalpha.com/input/?i=limit+h+sin+1%2Fh
Comment: It seems to me that $g'(0)=\lim_{x\to 0} g'(x)$ so I can't prove  $g'(0)\neq \lim_{x\to 0} g'(x)$
Comment: @Raindrop: How can they be equal when one of them is $0$ and the other **doesn't exist**?
Comment: The limit $\lim_{x\to0}g'(x)=2\lim_{x\to0}x \sin\frac1x-\lim_{x\to0}\cos\frac1x$ doesn't exist but the limit $g'(0)=\lim_{h\to 0}\frac{g(0+h)-g(0)}h=\lim_{h\to0}\frac{g(h)}h=\lim_{h\to 0}\frac{h^2\sin\frac1h}h=\lim_{h\to 0}h\sin\frac1h\;;\tag{1}$ exists
Comment: There's a chance that the question is incorrect because the  textbook has a typo
Comment: @Raindrop: No, there isn't: the question is correct. And your previous comment is exactly the point: $g'(0)$ exists and is $0$, but $\lim_{x\to0}g'(x)$ does not exist. Therefore they aren't equal.
Comment: Thanks! When finding the limit, we use the equation of $g(x)$ for $x\neq0$ but when using limit definition, we use $g(0)=0$ while computing $g'(0)$.


Peano's Existence Theorem - Constructing Maximum and Minimum Solutions

Question: Suppose that $D=[a, b] \times \mathbb{R}$ is a strip in $\mathbb{R}^2$, and that $f(x, y)$ is continuous and bounded on $D$. Let $(x_0, y_0)$ be an interior point of $D$ (i.e. $a< x_0 <b$).
Prove that there are two integral curves $y=\phi_1 (x)$ and $y=\phi_2 (x)$, i.e. the maximum and the minimum solutions to the equation $\frac{dy}{dx}=f(x, y)$, such that
(1). $\phi_1 (x_0)=\phi_2 (x_0)=y_0$ and $\phi_1 (x)\geq \phi_2 (x), \forall x\in [a, b]$;
(2). the region $\{(x, y)\in \mathbb{R}^2 | a\leq x \leq b, \phi_2 (x)\leq y\leq \phi_1 (x)\}$ can be completely filled by integral curves passing through $(x_0, y_0)$;
(3). There are no solutions (integral curves) to $\frac{dy}{dx}=f(x, y)$ passing through $(x_0, y_0)$ that lies outside the region in (2).
Below is a sketch of solution given by my TA.
By Peano's existence theorem, since $f$ is continuous and bounded on $D$, there exists, in a neighborhood of $x_0$, some function $y=y(x)$ such that $\frac{dy}{dx}=f(x, y)$ and that $y(x_0)=y_0$.
By fundamental theorem of calculus, we have that
$$y'=f, y(x_0)=y_0 \iff y(x)=y_0+\int_{x_0}^{x} f(t, y(t))dt$$
Let $y_{max}$ be the largest integral curve and $y_{min}$ the smallest. Then
$$y_{max}-y_{min}=\int_{x_0}^{x} \Big[f(t, y_{max}(t))-f(t, y_{min}(t))\Big] dt\geq 0$$
These may be constructed using an Euler approximation on the integral to recursively build the max and the min. Any integral curve in-between may also be created since we may take any value between the max and the min in the recursion.
The idea he presented is very natural, but what is confusing me is the bolded part. I really have no idea how to build the max and the min recursively. Can anyone explain how to proceed? Any help is appreciated!
Answer: The sentence in bold is correct and means the following:
At each step of the subdivision always take the maximum or always take the minimum of the possible derivatives on the corresponding interval. Each of the constructions will converge uniformly to solutions, indeed the maximal and minimal solutions (although one should point out that these claims are not obvious).
Comment: @Peter A rough idea is that by selecting at each step values of $f$ that are between the smallest and largest values you can reach $\delta$-near any point of the area in between. Then you need to use a density argument by letting $\delta\to0$ (assume on the contrary that there is a gap at some time $x$, and make sure that you construct a sequence of approximations always with $\delta$ smaller than the size of the gap).
Comment: As you wrote: the idea is to use the "Euler approximation", not to solve the equation explicitly. And yes, for example $y(x)=0$ is also a solution.
Comment: If I understand correctly, the idea is to take small $\epsilon$ and take the largest value of $f$ on each $\epsilon$ interval to construct $y_{max}$ (and then take the smallest value of $f$ for $y_{min}$) as a limit of these curves as $\epsilon$ approaches $0$. Then I suppose it is obvious that $y_{max}$ is greater than $y_{min}$ and also that they intersect at $(x_0,y_0)$. Furthermore, it is pretty clear that no solution passing through that point can be outside the area. But how do you show that the area between the min and max functions is "filled in"?
Comment: Thank you. I'm still a little bit confused. So suppose we take $[a, b]=[-1, 2]$ and $(x_0, y_0)=(0,0)$. Assume that $f(x, y)=\sqrt{|y|}$, then $y(x)=\frac{x^2}{4}$ if $x\geq 0$ and $0$ if $x<0$, is a solution to $y'=f$. In this case, what is $y_{max}$ and what is $y_{min}$? Sorry but I mean isn't the 'possible derivative' just $f$?
Comment: Oh I think I got it. So we are dealing with the slopes of the linear approximations (tangent lines). Suppose we have our $y$. The tangent line at $x_1=x_0+\epsilon$ takes the value $y_0+\epsilon f(x_0, y_0)$. And by always maximizing (or minimizing) $\epsilon$, we obtain the optimized approximation. Is it correct?
Comment: Precisely !  :-)


How to prove that the ellipse is a periodic orbit knowing that the orbital derivative of a function V is zero on there

Question: The question is as follows:
Show that the orbital derivative of the function $V=(1-x^2-2y^2)^2$ is zero on the ellipse $x^2+2y^2=1$, and explain why you can deduce that the ellipse is a periodic orbit.
So I've proved the first part:
$$V'=2(1-x^2-2y^2)(-2xx'-4yy')$$ ($V'$ denotes the orbital derivative and $x'$ and $y'$ are the derivatives of $x$ and $y$ respectively)
Now taking the orbit: $2y^2=1-x^2$ and substituting on $V'$, we get zero.
My question is that now I don't know how to proceed to show that it is periodic...
Thank you
Comment: You want the ellipse to be a periodic orbit of which equation?
Comment: @Jonas I have a dynamical system:

x' = x*(1-x^2-2*y^2) - 2*y*(1+y) ;
y' = y*(1-x^2-2*y^2) + x*(1+y)

and I've calculated its fixed points and stability (the only fixed point is (0,0) which is unstable)

So now,  I've been given that function, V, and I need to show that the ellipse is a periodic orbit (knowing that  the orbital derivative of V is zero on the ellipse)

Thanks for answer
Comment: @Jonas sorry I was editing it
Answer: Since
$$
x' = x(1-x^2-2y^2) - 2y(1+y),\quad
y' = y(1-x^2-2y^2) + x(1+y),
$$
you have
$$
xx'+2yy'=(x^2+2y^2)(1-x^2-2y^2)
$$
and so
$$
V'=-4(1-x^2-2y^2)^2(x^2+2y^2).
$$
Hence, for points close to the ellipse but outside the ellipse you have $V'<0$.
This implies that the ellipse is a periodic orbit since we know how the orbits behave in its neighborhood (just draw it).
Comment: Thank you. Just one more question:  How should I proceed now to determine whether this periodic orbit is stable or unstable? I know that the only fixed point of the dynamical system is unstable (eigenvalues have real part positive) and since we have that expression of V we can easily check that it's a Lyapunov function...
Comment: The orbit is unstable, because orbits "inside" go away from the orbit (because $V'<0$).


Digital piano sound fonts

Question: I have a Yamaha YDP-142 and the piano sounds great on it, but it only lets me download MIDI files that I have recorded, and I can't find any piano soundfonts that sound like the piano itself to play back on computer.
The biggest problem in the soundfonts I have found is that they don't effectively hold the sustain on the notes.
Is there any way to get the soundfonts off of the piano?  Surely if they sell it as having a Record function it is reasonable to expect to be able to recreate the sound?
Comment: Can you play back the midi file through the Yamaha?
Comment: I presume that this is what the piano does.  There are headphone jacks, so I could record the output, but I like the idea of having the midi file to play with I just want to be able to mimic the piano sound on my PC.
Comment: I mean - http://download.yamaha.com/api/asset/file/?language=nl&site=nl.yamaha.com&asset_id=59451, top of page 6 : "Playing Back Songs on a Computer via the Instrument Sounds". Is that an option for you?
Comment: I'm personally pretty happy with Garritan CFX.
Answer: A good piano synthesizer (as in the engine of a digital piano) should do more than just play back samples such as panning the notes according to pitch and adding sympathetic resonance for strings not being directly played. A simple MIDI player with sound fonts is unlikely to get the dynamics working as well as a dedicated piano synthesizer. If possible set the computer to route the midi track to play back through your digital piano as mentioned in Topo Morto's comment. If your computer can't always be connected to your instrument you could try using a piano softsynth such as True Pianos or Pianoteq.
Comment: I think all the answers here have helped me, but this one linked the two options - buy some high end software, which is a bit beyond my budget as a hobbyist. Or playback via the piano (ref. @topo  morto link) and then record via headphones for final playable track, I'll experiment further.
Comment: I don't know what the price and performance of all the current virtual pianos is like but I think some of them do give you a free trial period which may be useful to you.
Answer: In principle you could make your own soundfont, by recording single notes (preferably using a MIDI file to "play" the piano, so you get consistent note-on velocity etc) and using soundfont editor. But the results are unlikely to sound as good as the piano, because you will lose the interaction between sound of different notes played together. Good quality sampled pianos use huge sample sets - for example this one http://www.garritan.com/products/cfx-concert-grand-virtual-piano/, recorded from an acoustic Yamaha concert grand piano, has about 120Gb of samples (and even the "lite" version is about 20Gb).
Note, making a soundfont this way may not be legal - check what the user licence agreement for your Yamaha says about "reverse engineering."
A different computer simulation method creates a mathematical model of how the piano actually "works", rather than attempting to recording every possible sound it can make. Software like https://www.pianoteq.com/, which uses this "physical modelling" approach, needs much less memory and disk space than a sample library, but uses more CPU power to generate the audio in real time as you play. Any modern computer (including laptops) should be powerful enough to run it.
Answer: "Soundfonts" are pretty old technology!  But there's a wide choice of "virtual pianos" that work on any reasonably modern computer.  Here's one supplier:
http://synthogy.com/index.php/products/software-products/ivory-2-grand-pianos
Comment: Thanks, I was surprised by your comment that Soundfonts are old technology as that is all I've come across when googling, what would be considered new technology?
Answer: I use Addictive Keys as in a DAW as an add on to play back my midi files and I like the sound better than the Yamaha. I got a free copy with 1 piano type enabled when I bought my USB interface. You can change loads of parameters such as the room dynamics to get a load of sounds.

Digital piano sound fonts


String to array nodejs

Question: I format a string (I can format the string in any way)
e.g
   id1:234,id2:4566,id3:3000

then encrypt it and pass via query string
   ?qs=djdjdjfjf57577574h33h3h3hh3h3

then decrypt it on node
   id1:234,id2:4566,id3:3000

which is the best method to format the string and then turn it into an array in node
    arr[id1] = "234";
    arr[id2] = "4566";
    arr[id3] = "3000";

Comment: can I ask what is the context for this solution? What are you doing with it?
Comment: That example is so close to JSON that for me is the obvious next step to achieve what you want.
Comment: pass argument from php site to a node soket
Comment: What are `id1`, `id2` and `id3` supposed to be in your example? They are not variables, but string literals right?
Comment: yes because I encrypt and decript a string for security,I do not want to pass values that can be haked
Answer: I think you would like to use hashmap (object) instead of array:
var obj = {}
then try:
"id1:234,id2:4566,id3:3000".split(",").forEach(function(e){
    var record = e.split(":");
    obj[record[0]] = record[1];
})

which give you:
{id1: "234", id2: "4566", id3: "3000"}
Comment: There is no `each` function. You can use `forEach`, but this is not supported for <IE8.
Comment: It will be on NodeJS side, I assumed there is `"each"` since on Chrome there is :)
Comment: There is no `each` function as far as I can tell
Comment: @Amberlamps edited, thanks (seems to site on which I ran console has that method in array).
Answer: Firstly, what you have as your object model is more of a hash like object or simply a JavaScript object with keys and values, so the best way to do that is simply using JSON.parse.
So if you can do it as you said: I can format the string in any way, you better first change your formatting to have something like:
'{"id1":234,"id2":4566,"id3":3000}'

instead of :
id1:234,id2:4566,id3:3000

you can do it using JSON.stringify on the client side JavaScript using a JavaScript object without you needing to deal with string formatting:
//on the client side
var myObj = {};
myObj.id1 = 234;
myObj.id2 = 4566;
myObj.id3 = 3000;
var objStr = JSON.stringify(myObj);

let's say you encrypt your string using a function named encrypt:
var encryptedStr = encrypt(objStr);
//so now you should use encodeURI to be able to put it in the queryString
var queryStringParam = encodeURI(encryptedStr);

now you put the queryStringParam in the queryString.
Then on the node.js side, all you should do is parsing it as a JSON object. The other important point that you probably have considered doing it is using decodeURI. For the last step, let's say you are using e function named decrypt:
//the server-side code
var decryptedStr = decrypt(decodeURI(yourQueryString));
var obj = JSON.parse(decryptedStr);

Now obj is exactly what you want.
Comment: thanks It works! but if i put the client side part is useless to encrypt the string ;)

String to array nodejs


What is the Drupal 7 bookmarking module (a la delicious.com) that is equivalent to userlink in Drupal 6?

Question: I am using the Web Links in Drupal 6, and I would like to use its equivalent in Drupal 7. It doesn't appear to be a clear direction, according to Comparison of Links Page modules.
Answer: For Drupal 7, I am using the Link module. It defines simple link field types.


Fallback between datacenters

Question: What is the best way to do a fallback between datacenters. We have a dedicated server in one of the data centers and as our traffic increased i wanted to add more then backup i wanted redundancy and load balancing.
The thing that happened in the meantime is our hosting provider got hit with some DDOS attacks. We were not the target, somebody else was but the attackers managed to make anybody available on that hosting provider. After 2 od those DDOS attacks, the past behind particularly bad i leaved a bad taste in my mouth. I want the redundancy from two different data centers and two different hosting providers.
The only thing that i can think of is DNS fallback, but we have also non HTTP traffic.
I wanted to put something in front of everything that would route/proxy that traffic but then i have also create a redundancy for that
PS. im in europe and have to have the servers in my country because of latency.
Comment: Is your question about DDoS or about a second datacenter?
Comment: If your DNS provider supports health checks you should be able to dynamically alter the hostname->IP matching.  This need not be limited to HTTP.  Any well-written application should recheck DNS periodically.
Comment: im thinking about that. the problem is that i have some services where they ask me to give them my ip address. how can i work with that ?
Answer: Having been in the DDoS defense industry, this is commonly referred to as 'collateral damage' when unintended targets at the same data center gets taken down. A good datacenter operator will automatically kick in protective mechanisms like blackholing routes for the intended target in order to save everyone else hosted at the datacenter, but you'll be surprised how slowly many operators react to such attacks.
Sounds like you're already hosted in multiple datacenters, so a GSLB (global server load balancing) service that operates on dynamic DNS, and directs traffic on the fly based on application health checks, datacenter reachability, and where the user is coming from would have helped you. Since it's DNS, it would work for anything that needs a name resolutions, and not just for HTTP. Companies like Dyn and Akamai have monthly services that can do this for you.
Answer: You simply need DDoS protection from ISP. This is an optional service, by which the ISP tries to monitor attacks and re-route any DDoS to blackhole.
Another datacenter cannot protect you from DDoS that is targeted at your service.
Comment: in first post i wrote that the whole hosting provider whas down when somebody attacked somebody. i dont trust that they have a service where they can protect me if they cannot protect themself.

Fallback between datacenters


DRUPAL_ROOT undefined on module installation

Question: I try to install the live_agent module. When I go to enable the module, I get the following errors:

Notice: Use of undefined constant DRUPAL_ROOT - assumed 'DRUPAL_ROOT' in /sites/all/modules/live_agent/live_agent.module on line 319
Warning: require_once(DRUPAL_ROOT/includes/errors.inc) [function.require-once]: failed to open stream: No such file or directory in /sites/all/modules/live_agent/live_agent.module on line 319
Fatal error: require_once() [function.require]: Failed opening required 'DRUPAL_ROOT/includes/errors.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /sites/all/modules/live_agent/live_agent.module on line 319

The code causing the error is the following one.
 /* 318 */ function live_agent_buttons_form(&$form_state) {
 /* 319 */   global $base_url;
 /* 320 */
 /* 321 */   $settings = new liveagent_Settings();
 /* 322 */   $la_buttons_grid = $settings->getButtonsGridRecordset();
 /* 323 */   $recordset = $la_buttons_grid->toArray();
 /* 324 */
             // ...
 /* 373 */ }

Any help on debugging this would be greatly appreciated.
Comment: Hello, and welcome to DA! If you read the code and the error message, you'll see that line 319 is _not_ a `require_once` as the error message states, so you appear to have pasted the wrong code. Bugs in modules a considered off-topic for this site.
Comment: @Letharion I pasted [the code that is at line 319 of the module file](http://drupalcode.org/project/live_agent.git/blob/refs/heads/7.x-1.x:/live_agent.module).
Comment: Do you have APC enabled?  If so, try disabling it temporarily.
Comment: @kiamlaluno I see. Well, that combination of code and error message still doesn't seem to make sense to me. :)
Comment: @Letharion The errors seem caused from the autoload function, but I don't know why the error is for that line.
Answer: The error about the undefined constant DRUPAL_ROOT could be caused from the index.php file that is corrupted, or that is returned corrupted from APC, or similar extension. DRUPAL_ROOT is always defined when Drupal bootstraps.
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

As for why the error message is reported for that module when a function that doesn't contain any reference to the constant is executed, I think that is caused from the autoload function Drupal registers, drupal_autoload_class(), which is trying to load the file containing the class.
Answer: Check your settings.php file. You might have either.
You set the wrong base URL, or maybe you did not set one and this module requires it.


How to set file-path in ViewController?

Question: This is my project structure:

I have 2 different View Controllers (GameViewController, TaskViewController). Both of them should be able to show a web view to the user.

The web view for GameViewController should load the file www/game/index.html
The web view for TaskViewController should load the file www/task/index.html

Adding the web view is quiet easy. But how can I specific the right path?
This was what I've tried inside the GameViewController:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www/game") // not working

let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "game") // not working

let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "myApplication/www/game") // not working

How can I set the path for the files (with the same names [index.html] ) the right way?
Any help would be very appreciated. Thanks.
Comment: You have to add the HTML files as "folder references" to your project, otherwise all files will be copied to the same directory in the application bundle. See for example https://stackoverflow.com/questions/6420925/load-resources-from-relative-path-using-local-html-in-uiwebview.
Answer: Try to add the files with references selected , suppose I have a folder named pp inside it there is a premium.txt when I drag it to Xcode selected create folder references and reference it easily with subdirectory, the folder will have a blue color
Comment: I've deleted my html-files and dragged them again into the folders. I've also enabled "create folder reference" but using this code: `let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "game")` will not work either.
Comment: game folder must contain index.html directly without inner subdirectories before you drag the folder to Xcode ????

How to set file-path in ViewController?


What's the best way to put in a link to a translated node in a D8 template?

Question: There just has to be a better way to insert a link to an alternative translation than this:
function THEME_preprocess_node(&$variables) {

  $node = &$variables['node'];

  // Current language
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['current_language'] = $current_language;
  $variables['current_language_url'] = $node->toUrl()->toString();

  // If this is a multi-lingual node, get links to alternative language.
  $languages = $node->getTranslationLanguages();
  foreach ($languages AS $langcode => $language) {
    $node_ja = ($langcode == 'ja') ? $node->getTranslation('ja') : null;
    if ($node_ja && is_object($node_ja) && $current_language == 'en') {
      $node_url = $node_ja->toUrl()->toString();
      $variables['node_url_ja'] = $node_url;
      $variables['node_url_ja_translation'] = 'Japanese';
    }

    $node_en = ($langcode == 'en') ? $node->getTranslation('en') : null;
    if ($node_en && is_object($node_en) && $current_language == 'ja') {
      $node_url = $node_en->toUrl()->toString();
      $variables['node_url_en'] = $node_url;
      $variables['node_url_en_translation'] = 'English';
    }

  }

  // Display link to alternate translation.
  $variables['node_url_translation'] = ($current_language == 'en') ? $variables['node_url_ja_translation'] : $variables['node_url_en_translation'];

}

It works, but it's just not at all graceful. How should this be written?  I just want to put in a link like this into a templates/node.html.twig file:
{{ node_url_translation|raw }}

Comment: I'm voting to keep it open, because it's clear to me what @MikeGifford is looking for and I think it's a good question. That said, it would help if the question was rephrased in more objective words, providing measurable criteria that answers should meet.
Comment: It's best practice to not use the `|raw` filter. See [How do I get the raw field value in a template?](https://drupal.stackexchange.com/questions/228388/how-do-i-get-the-raw-field-value-in-a-template/228393#228393)
Comment: Also, it's best practice to create a link using the Drupal API's link class. See [How do I create a link?](https://drupal.stackexchange.com/questions/144992/how-do-i-create-a-link)
Comment: I'm voting to close this question, as it is primarily opinion based. Drupal has many ways to achieve your solution. And possibly every member of Drupal Answers would have done it in a different way. So there is no chance of giving you a dedicated answer to "How should this be written?".
Comment: It's a lot more than just adding the |raw filter. More logic is needed.

I'm asking this question as it's going to be a common problem in multilingual sites. I was frustrated at how long it took me to build this logic in D8.

I'm fine with re-phrasing it. I guess I'm looking for best practices for creating links to jump back/forth between multi-lingual content from within a theme.
Comment: @MikeGifford: There you go. I added a more generic answer, that hopefully has some valuable information for you.
Answer: The easiest method of providing language switching links would be using the language manager's getLanguageSwitchLinks() method. However, this might - depending on your language settings - also provide fallback links, if the node is not translated to the target language. An abstract example:
use Drupal\Core\Language\LanguageInterface;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();
  $links = $language_manager->getLanguageSwitchLinks(LanguageInterface::TYPE_CONTENT, $node->toUrl());

  $variables['current_language'] = $current_language;
  $variables['translations'] = [
    '#theme' => 'links',
    '#links' => $links,
    '#set_active_class' => TRUE,
  ];
}

For your use case - to show links to translated content only -, your approach to using getTranslationLanguages() of the TranslatableInterface is on the right track.
But be aware, that it will return entity translation instances also for non-published - or otherwise limited - content translations, to which the current user may not have view access to. Hence, he will get an "Access denied" error after clicking the links.
Additionally, the code should be generic enough to allow for further languages being added using the admin UI in a later stage of the application's life-cycle, without having to touch your preprocessing/templates anymore.
Therefore some suggested improvements for your solution:

Check, whether the current user has access to the translation.
Avoid using hard-coded language identifiers. As I suppose you did so to not add further links for the current language, you should use your $current_language variable to do the checks.
Avoid using hard-coded language link labels. Consider using \Drupal\Core\Language::getName() instead.
Use a list of language links instead of a dedicated variable for each language, and pass that list to the template. This way you can just iterate over the links.
Don't return markup (the links) from within your preprocess hook, but allow creating the links within the templates.

This sums up to something like this:
use Drupal\Core\Template\Attribute;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();

  $links = [];
  foreach ($node->getTranslationLanguages() as $langcode => $language) {
    // Skip any translation that cannot be viewed.
    $translation = $node->getTranslation($langcode);
    if (!$translation->access('view', NULL, TRUE)->isAllowed()) {
      continue;
    }
    // Get URL of the translation.
    $url = $node->toUrl('canonical')
      ->setOption('language', $language)
      ->setAbsolute()
      ->toString();
    // Optionally provide an 'active' class.
    $classes = [];
    if ($langcode == $current_language) {
      $classes[] = 'active';
    }
    // Construct information for a link.
    $link = [
      'language' => $langcode,
      'is_current' => $langcode == $current_language,
      'url' => $url,
      'title' => $language->getName(),
      'attributes' => new Attribute(['class' => $classes]),
    ];
    $links[] = $link;
  }

  $variables['current_language'] = $current_language;
  $variables['translations'] = $links;
}

In your template, you can then create the links like this:
{% if translations %}
  {% for item in translations %}
    {# Optionally skip current language #}
    {% if not item.is_current %}
      {{ item.title }}
    {% endif %}
  {% endfor %}
{% endif %}