How to teach a Piano Student with Hand Mobility Issues

Question: I have recently started teaching piano to a student.  They had been learning with another instructor and have a few years of experience.
The students parent let me know in advance that they have mobility issues with their right hand. Based on the prior experience and the parents' willingness, I thought it was a workable issue.  I planned to suggest alternate fingerings when applicable.
Now that I have sat with the student through several lessons, the following is clear to me:
This student struggles to play any interval greater than a whole step with fingers 3-5 on the right hand. They also struggle to maintain proper hand posturing, which introduces a number of other issues. I have suggested alternate fingerings (ones that favor the first 3 fingers), but there's no way to accommodate chords.  They struggle to play a major triad.  I suggested dropping one of the notes in the chord.
The issue is that this student does not enjoy entertaining these mitigation strategies.  I think it is because they are uncomfortable discussing their mobility issue.
I am not a physical therapist and can't effectively recommend exercises to improve mobility (not to mention I don't know the precise medical reason, and have no desire to ask). So I feel my options are:

Keep pushing mitigation strategies and hope the student becomes more open to the idea over time.
Let the student play as they prefer (often just hiting the second and fourth notes in addition to the triad), and focus instead on other aspects.
Inform the parents that this is a very prohibitive issue for a piano player and see how they wish to proceed.

I am a relatively new teacher, so feedback on these options or better suggestions is what I'm looking for.
I should also mention that the parents' intention is likely not to turn their child into a concert pianist, but instead to give critical music theory knowledge that may be applied to a different instrument later on. But I feel quite bad watching the student become so frustrated with no way to help!
Comment: If the goal is not to become a pianist, let alone classical pianist, but to get an overview of what happens in music and to get tools for reasoning about music, and maybe to produce music with computers and keyboards etc. then I don't think fingerings and being able to fluently perform given pieces matter pretty much at all.
Comment: @Aaron, Correct on both fronts, mostly:  I only discussed the issue with the father via website chat prior to first lesson, and  'Several' is specifically 4 lessons so far.
Comment: This page is not really well suited for physiotherapeutic advice! Even someone with medical knowledge would most likely not give a lot of advice without knowing any specifics, as that wrong advice could even backfire. Needless to say, if your student has constantly the feeling that he cannot do it he will not have a great time and soon loose motivation. I think it is essential for you to talk with both the parents and the student. You have to be honest with them that this *is* a big limitation when playing piano, and you need to know what's going on to have any chance to make things better.
Comment: Depending on the situation the correct exercises might help the student overcome these issues. Or they might not. And it might just be that the student would invest a lot of time into something that is not suited for him, when he could have spent the time learning something that fits him.
Comment: As a clarification, before taking on the student, you had met and discussed with one or both parents, but you had not encountered student at the piano until the first lesson. Yes? Also, by "several" lessons, less than a dozen, say?
Comment: How old is this student?  A lot of what you're describing can be just a matter of small hands.  They may need to grow into them a bit more.  No child is going to be able to make a full octave stretch at first (let alone longer).
Comment: If the mobility issue is limited to their right hand, introducing them to genres like boogie woogie might be a good idea.
Comment: I think it would help to distinguish between "playing piano" and "playing certain/many piano pieces as written".
Answer:
I should also mention that the parents' intention is likely not to turn their child into a concert pianist, but instead to give critical music theory knowledge that may be applied to a different instrument later on

My advice would be to incorporate as much theory as you can into the lessons, and use the piano playing as a way of exploring musical ideas, rather than as the primary or only goal of the lessons.
It is a feature/bug of a lot of classical music training (especially in the early years) that the student is taught which notes to play, but not why to play those notes. As a result, a lot of musicians can play the pieces they practiced really well, but couldn't improvise or song-write their way out of a paper bag.
So look at this as an opportunity to try and do better. Try to impart as much musical knowledge as you can to this student. Explore different musical genres and styles with them. Improvise with them. Let them accompany you while you sing or play another instrument. Play along to orchestral recordings, or improvise four-hand versions of orchestral music. Let them transcribe music for other instruments to the piano. Incorporate jazz theory into the lessons. Teach them all the things that other students are missing out on, because they're too busy practicing Für Elise for the millionth time. Get them excited about making music in general, instead of forcing them to be excited about playing the piano.
Comment: Good answer. My suggestion is to aim at playing good music on the piano, not necessarily play Schopin. Example is Django Reinhardt, famous guitar player, with three fingers missing after a fire accident.
Answer: Let's interrogate the "third option" you mentioned, and I'll intentionally take it a bit more literally than you truly meant it:

Inform the parents that this is a very prohibitive issue for a piano player and see how they wish to proceed.

I think the word "prohibitive" gets to the heart of the matter, speaking volumes about our assumptions about music-making. As teachers, is it our job to "prohibit"? To be gatekeepers of participation? And what is it that we're participating in?
In Western classical tradition, we do have a lot of boundaries, obstacles, and assessments. We have "the right notes," we have competitions that allow access to opportunities, we have auditions; in music school we even have "juries" that kick you out if you aren't doing enough. (Whereas, in some other traditions, the goal of music-making is simply having fun, and "the right notes" are not set in stone.)
If the student can't play a major triad, they will definitely run afoul of all these classical gatekeeping measures. And yes, your point is not only that the student is unlikely to be a concert pianist, but that these challenges might stand in the way of lesser goals like playing even the simplest works in the standard canon.
But there have been plenty of artists throughout history who have worked around their physical limitations, often by developing a non-standard technique, maybe one that even impacts the shape of the music. Django Reinhardt comes to mind...

... as does Gaelynn Lea:

So you're on the right track to talk about modifications, and other answers have emphasized exploring improvisation or composition, giving the student an opportunity to use their ability as a tool to shape the music, rather than "reshaping" or "reducing" existing music to fit them.
But the biggest issue here is that they're unwilling to take your suggestions. This is a problematic (though common enough) teacher-student dynamic. You're the teacher; they came to you for your advice and help. Unfortunately, it gets complicated: e.g. maybe it's the case that the parents value your advice but the student isn't as convinced of their own need for help. Every student has a different threshold of frustration, a different level of determination, and even a different goal (just to have fun, vs. Rachmaninoff-or-bust). Frankly, four lessons is a short time for you to get a bead on these personal needs, and for the student to build trust in you. Over time, you'll have to find a way to get them to accept your help. This might take some combination of gentle encouragement and patience. Preferably, "encouragement" doesn't mean saying "I'm the teacher, dammit," but gently pointing out that you're there to help, and winning their confidence by steering them into achievable successes. And it might just take patience, watching while they get frustrated, until they're ready to hear you.
Meanwhile, I'd suggest controlling the repertoire. If major triads don't work, don't have them play them! This is a challenge, of course, because you run into chords pretty quickly in beginning methods. If you have time you could write things yourself, and of course you can do a lot (including teach a lot of theory!) by having the student write their own compositions. You might also look to things that are more contrapuntal and less chordal; perhaps some Bach two-part Inventions?
Comment: Excellent advice. Thank you. The other answers were helpful, but this one seems to me the best!
Answer:
Hello , I'm a disabled piano player with only 1 usable hand, and as a child it was SO hard finding a teacher that would even try taking me on as a student, so thank you for at least looking into how to best help!
What my teacher did (which was absolutely genius), was on an electric keyboard, she would press record & I would play one hand's chords, then play back the recording while I played along to it with the other hand's chords. I'm not sure if I'm explaining it very well, or if that would even be helpful for your student's needs, but I figured I would share what helped me. Also, just practice, practice, practice.
Another suggestion is to lookup accessibility tools on Etsy to see if anything there can help. I've been a photographer for over 15 years and always just held the camera awkwardly, but recently I discovered a bunch of cheap and handmade gadgets to help with it. I never knew that market was being realized and the innovation some people have to come up with those useful tools. Piano is amazing for hand mobility therapy and I hope you encourage them the way you would with any other piano player ♡.
I always hated being placated because of my disability... during jump rope for hearts fundraiser events in my schools gym classes, my teacher once told me to just throw a ball against the wall while everyone else participated . I just tied one end of the rope to a door handle and ended up 2nd for most amount of jumps raised. My mom ended up buying me this cool toy that would spin one end of the rope around while you twirl the other in your hand and I wore that thing out lol. My mom was furious when she heard what the gym teacher asked me to do and chewed him out. He never excluded me again, and I was never unable to participate because I'm very creative and an athlete too.
Hope it helps!
Answer: It does beg the question why (and who) chose the piano, given prior knowledge of restrictions. That alone needs answering. How old/mature the student is will also be of interest, along with is there an instrument to practise on at home?
Given that the physical restrictions are serious, and the desire to play piano in particular are too, you and the student will have to adapt just about everything. So not a lot will sound as it was written, but that shouldn't do more than slow progress down, as alternatives are worked out. re-voicing parts, crossing hands, etc. can be incorporated.
If the piano idea was indeed a whim, then there are several other alternatives (which may well not involve you), such as trumpet, trombone, drums, guitar, bass, harmonica to name a few off the cuff.
As already said, if piano is the be-all and end-all, then use it as a theory explaining tool - it's the accepted one for this anyway. Composition, single note soloing, improvisation, will all be possible.
But, bottom line, first it must be established why piano was the chosen instrument, with good reasons, and steer from there.
Answer: With this handicap the child would be able to play e.g. trombone or electric guitar later.
To be not frustrated they should have to play pieces where their issues don't matter. It's your job to choose the right selection. There are surely a lot of pieces of classical music, pop or modern compositions. It might be even possible to overcome their handicap over time.
Comment: Famously, of course, there are Paul Wittgenstein's commissions for left-hand-only piano.
Comment: If it is really a specific issue of finger mobility in the right hand, why not try the violin?
Answer: Have them do practices such as stretching hands (left and/or right).
Do warm ups for them such as playing chords. (This will help in knowing where each chord is)
Have the student play a moving part repeatedly to help them know what to do. For example, moving to a different chord. In this case, have them go back and forth between each chord.


Message box with "Yes", "No" choices in C#?

Question: I want to make a MessageBox confirmation. Here is the message box:
DialogResult dialog = MessageBox.Show("Etes vous sûre de vouloir fermer le programme ?", "Exit",MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
  Application.Exit();
}
else if (dialog == DialogResult.No)
{
    e.Cancel = true;
}

The problem is, when I click the YES Button, the popup does not close automatically. It will be closed after I click 2 times again.
It should be closed from the first time.
It seems pretty easy but I'm not sure where is my mistake;
Comment: from that code, theres no obvious reason - however depending on where that code is, that could be the reason.. in the wrong place it can cause the  event to be triggered more than once
Answer: If it's in main form close method you can use it like this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Really close?", "Exit", MessageBoxButtons.YesNo) ==
        System.Windows.Forms.DialogResult.No)
        e.Cancel = true;
}

If user press "Yes" your form will be closed due to no close cancellation.
If it is not main form close doesn't mean application exit. In this case you can close parent form explicitly after ShowDialog call.
Answer: Below is code to prompt message (Yes/No):
DialogResult dialogResult = MessageBox.Show("Are you sure to delete Yes/No", "Delete", MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)
{
   /// do something here
}

Answer: Call Application.DoEvents() before Application.Exit(). But it is better to close parent form with Close() instead of Application.Exit.
Answer: switch (MessageBox.Show("Etes vous sûre de vouloir fermer le programme ?", "Your_Application_Name", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
        {
            case DialogResult.Yes:
                Application.Exit();
                break;
            case DialogResult.No:
                //Action if No
                break;

        }

Comment: Why should it solve the problem? You only refactored the `if` to a `switch`. There's no other change, or do I miss something?
Comment: Please explain the difference between `No` and `Cancel`.
Comment: i am sorry if it didnt ans ur question. but this is how i use it,, and it wrked for me..

Message box with “Yes”, “No” choices in C#?


403 forbidden issue in Jmeter

Question: I have a JMeter test with the following configuration:
Thread Name: Thread Group 1-1
Sample Start: 2017-08-18 12:45:02 IST
Load time: 304
Connect Time: 0
Latency: 304
Size in bytes: 209
Headers size in bytes: 206
Body size in bytes: 3
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""): text
Response code: 403
Response message: Forbidden

Unfortunately it fails with the following response headers:
HTTP/1.1 403 Forbidden
Content-Type: application/octet-stream
Date: Fri, 18 Aug 2017 07:15:03 GMT
Server: openresty/126.96.36.199
X-Vcap-Request-Id: c9307775-0897-4fbd-5d45-e2e7c11cb1b1
Content-Length: 3

What am I missing? Thanks in advance.
Comment: `HTTP 403 - Forbidden` is returned, when the request is valid, but the caller has no permissions. You probably need to incorporate an authentication header in your request.
Comment: Thanks for your suggestions. Can you please any provide any docs on this sentence structure.
Answer: This issue can have a lot of causes:

missing content-type header
missing authentication token
missing CSRF token
failing authentication before access to url
...

Can you show the request you send ?
Comment: GET https://tix-stage.run.aws-usw02-pr.ice.predix.io/SbomProxyService/api/services/fetchQuoteListDetails?quoteStatus=QUOTED
Comment: Cookie Data:
predix-seed-session=c4krSuplzYEub9i2pRLEAA..|1503044094|xTCnnFanHQ3c5sL9d9Co2A..|amE3p_-6aqrNvZcxEpKQgvRtNSM.

Request Headers:
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Referer: https://tix-stage.run.aws-usw02-pr.ice.predix.io/value-master-list
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Host: tix-stage.run.aws-usw02-pr.ice.predix.io
Comment: Please find above two comments for the request sent.
Answer: I found that OpenResty requires User-Agent header. It will throw 403 Forbidden if User-Agent header doesn't exist.
JMeter do not attach this header automatically like most other apps do hence returning 403 Forbidden.

403 forbidden issue in Jmeter


Count words of a body field using PHP views field

Question: I'm looking for a way to count the amount of words in my body fields, using Views PHP. I am totally new to PHP and this looks so easy, but I must be missing something.
So I have a View for Content, containing a body field (hide display, HTML trimmed) and a Global: PHP field.
I have this in my "Value Code"-field inside the Global: PHP field settings:
$count = print $row->body;
$result = str_word_count("$count");

And this in my Output:
<?php echo $result ?>

Seems I must be missing something, but I get no error, nor any result. Just nothing happens.
Comment: Try this without $count var `$result = str_word_count($row->body);`
Comment: Thanks for your answer. I tried this, but makes no difference. When looking in my dblog, I get this statement: `Notice: Undefined variable: result in __lambda_func() (line 1 of /var/www/clients/client1/web1/web/sites/all/modules/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function).`
Answer: So, after a long research, I stumbled at this issue post. It seems that field data are not present in the result set of Views PHP, so instead of print $row->bodyI needed to use print $data->_field_data['nid']['entity']->body['nl'][0]['value'] to access the data.  This solved my problem.


End-to-Site VPN from IPv4 -Host to IPV6 (only) - Site

Question: I want my IPv4 only Clients to my IPv6 only Site. I have a dualstack Server which I could use as a gateway.
There is a Question somewhat related here:
IPv6-only client to IPv6/IPv4 dual stack server tunnel?
but was asked about 4 years ago.
Is this setup possible:
< Hosts >  --- IPv4 --- < DS GatewayServer > --- IPv6 --- < Site >

Do I have to set up a host to site VPN to the GatewayServer and a Site to Site VPN to the Site? Can this be done? And how would I route beween the two VPNs?
Comment: Which application layer protocols do you need to use? I have implemented [a name based proxy](http://v4-frontend.netiter.com/), which can handle http, https, and smtp (also ssh if you are willing to patch the client).
Comment: I thought of site like in factory not like in website. So I need some kind of VPN proxy. But your proxy might come in handy for other problems - thx
Answer: Sounds like what you need is a 6in4 tunnel. If you have a routed prefix on your dual stack server, then you can set up your own tunnel server. Otherwise you can use one of the many free tunnel providers.
Based on my overall experience with various providers, I recommend Hurricane Electric.
You could replace the 6in4 tunnel with a site-to-site VPN. The difference between 6in4 and VPN is that the VPN provides integrity and encryption on the path between IPv4 site and tunnel server, but this may not add a lot of value for you, as the path between tunnel server and IPv6 site remains unencrypted.
A site-to-site VPN between IPv4 site and IPv6 site might be possible, but this would obviously add another layer of complexity since the VPN would have to run on top of a tunnel, proxy, or NAT.
Comment: Can I find out if I have a routed prefix? Its a rented vServer
Comment: @MaximilianKindshofer The easiest way to find out is by asking the hosting provider.
Answer: You'll need to run a reverse proxy on your dual stack host that acts like a server to the IPv4 clients and as a client to the IPv6 server. Which tools to use depends on the protocol you need to handle. I have used haproxy with good results for TCP based protocols, and it has extra features for HTTP and HTTPS.
Comment: Based on comments, I don't think that is what he wants.


Unable to get pdf file type along with other image types as create a zip file using angular6

Question: Here I am having file types and download collection of file types as a zip file all the image format is working fine except "pdf" file the downloaded file contains "filename.undefined" (pdf file only). other files extension same(filename.jpg, filname.png, filename.gif)

readonly FILE_TYPE = {
    "image/png": "png",
    "image/jpeg": "jpg",
    "image/jpg": "jpg",
    "image/gif": "gif",
    "image/pdf": "pdf"
  };
Is this correct way mentioned pdf file type what I mentioned "image/pdf": "pdf"?
Thanks.
Answer: The MIME media type for pdf is application/pdf and not image/pdf.
See Proper MIME media type for PDF files


Chamar a data que tabela foi criada

Question: Estava vendo este tópico onde ele mostra a última vez que a tabela foi atualizada. Só que eu quero saber quando a tabela foi criada.
Answer: Quase igual, só usa CREATE_TIME ao invés de UPDATE_TIME
SELECT CREATE_TIME
FROM   information_schema.tables
WHERE  TABLE_SCHEMA = 'dbname'
    AND TABLE_NAME = 'tabname'

Referência na documentação do MySQL

Chamar a data que tabela foi criada


Can't understand meaning behind this sentence in Schoenbergs Theory of Harmony

Question:
Hello, the current topic is minor mode. Why can only II degree follow major IV in minor scale? Can't quite figure this one out.
Comment: He keeps saying "at present." I wonder if there are some voice-leading concerns he hasn't addressed yet? IV might not be able to go directly to V so as to prevent parallel perfect fifths, maybe?
Comment: @Richard all of the chords in the example are in root position, so it may be that inversions are not allowed.  But whatever it is, it's clearly some limitation that exists in the context of the rules and techniques that have already been covered in the book, so only someone who knows the book or has access to it will be able to answer.
Comment: Are you able to get hold of the German original? That might shed more light on what exactly he was bringing up there.
Comment: @leftaroundabout Quote: "... Dagegen geht die Verbindung mit der IV. Stufe ganz gut, nur ist sie an eine bestimmte Fortsetzung gebunden, da nach der IV. Stufe vorläufig keine andere wird folgen können, als die II. erhöhte. Glatt erfolgt die Verbindung mit der V. erhöhten, dagegen ist die mit der VI. erhöhten vorläufig unbrauchbar, denn die VI. ist ein verminderter Dreiklang, müßte also durch den Quartensprung des Fundaments aufgelöst werden; das _fis_ des Basses muß aber nach _gis_ gehen (zweiter Wendepunkt), kann also nicht wegspringen."
Answer: Schönberg is treating the minor scale here with the options to raise the sixth or the seventh scale tone, forming a rising and a falling scale. A few pages before this Schönberg postulates four "turning point laws" for the minor scale, which try to keep the tonal character of the minor scale clear. These are:

Erster Wendepunkt gis: gis muß nach a gehen, denn gis ist nur wegen des Leittonschrittes zu nehmen. Keinesfalls darf g oder f gebracht werden, ebensowenig fis (wenigstens vorläufig)
Zweiter Wendepunkt fis: fis muß nach gis, denn es wurde nur wegen des gis gebracht. Keineswegs darf g oder gar f folgen. Aber auch (mindestens vorläufig) nicht e, d, a usw.
Dritter Wendepunkt g: g muß nach f, denn es gehört der fallenden Skala an. Keinesfalls dürfen fis oder gar gis folgen.
Vierter Wendepunkt f: f muß nach e, denn es gehört der fallenden Skala an. Keinesfalls darf fis folgen.

Trans:

First TP g#: g# has to go to a, for g# is only used because of the leading tone interval. In no case may g or f be used, nor  f# (at least for now)
Second TP f#: f# has to go to g#, because we only use it for the g#. By no means may g or even f follow. But also not (at least for now) e, d, a &c.
Third TP g: g has to go to f, because it belongs to the falling scale. In no case may f# or even g# follow.
Fourth TP f: f has to go to e, because it belongs to the falling scale. In no case may f# follow.

So keeping by these rules we see that the f# of the IV# chord may only rise into a g# (or remain on f#).
Furthermore at this point Schönberg is only considering chord changes that share at least one note in common, which he calls harmonisches Band (harmonic bond) (so at this point Schönberg does not consider changes like IV-V. But IV# - V# will actually cause a problem, as f# → g# would require parallel shift of the chord).
But thus the IV# in question has only a limited amount of options:

D → B minor (IV - II)
D → G major (IV - VII)
D → B dim (IV -II)
D → F# dim (IV - VI#)
D → F major (IV - VI)
D → A minor (IV - I)

But if we consider the TP rules (f# may only be followed by g#) only the first options remains:

f# → g is not allowed
f# → g is not allowed
f# → f# would be allowed, but as the last clipped sentence on your pictures says this diminished chord would need to be resolved by a 4th upwards (cf. the early section about the 7th scale degree in major), f# would need to go into b, which is not allowed, as f# → g#.
f# → f is not allowed
f# → e is not allowed

Thus only the given chord change is possible.
Comment: I started to edit this answer because "by no means" requires subject-verb inversion in the clause it introduces (yes, this does happen in English, contrary to popular belief; it needs to be "by no means may one follow x with y").  But then I noticed that the translation changed the subject from the pitches themselves to the impersonal "one," so I decided to change it back.
Comment: Thank you man. I had the pivot rules written down but apparently could not use them correctly, your answer is very clear. Be well.


Is a violin's shape (particularly the f-holes) necessary or is it just for aesthetics?

Question: Violins have a rather beautiful design.
... is such design necessary? Is a violin's natural sound only achieved when it has this specific shape?
I have a particular interest in the f-holes. Are they the way they are because we need it, or is all of this just for aesthetic reasons?
If it is not necessary at all, how differently-shaped could a violin actually be from the normal design?
Answer: The shape also has to do with structural integrity. A violin would be of no use if it were built in a shape that would not support the high tension of the strings, thus causing the violin body to collapse after being used for some length of time. Instruments in the violin family, among all musical instruments, are notoriously durable; there are individual instruments that are 300 years old that are still being played professionally.
The shape of the violin, and any other musical instrument, evolved over time through the trial and error of musical instrument builders. In the last 150 years or so, there have been various attempts to apply the science of physics to instrument building and to refine the design.
The Luis and Clark company makes re-engineered, futuristic carbon-fiber acoustic violin-family instruments. They have a FAQ with a discussion of some of the elements of their design; you might find it interesting.
Comment: [mezzo-forte](http://www.mezzo-forte.de/)'s carbon designs go away even further from the traditional looks – for instance their soundholes are merely slits – yet sound IMO closer to "ordinary" wooden violins than the Luis and Clark models, which probably has to do more with material choice (wooden vs. carbon fingerboard) than with those decorations.
Comment: I have not heard any of these instruments, and I am not good enough to notice the difference, but I see that the Mezzo-Forte carbon violin uses a traditional ebony fingerboard. That probably contributes quite a bit to a more traditional sound.
Comment: @WheatWilliams No, the fingerboard can be any hardwood without affecting the sound significantly. The parts of the violin that vibrate (bridge, sounding board, etc) are far more important to the sound than the rigid parts.
Comment: I know this is a question about shape, and so the point that carbon-fibre violins sometimes are and sometimes are not the same shape is informative, but I did just want to chime in with a note about materials. If you draw a graph that maps density with elasticity or strength (e.g. Figures 1 and 3 in Claire Barlow's 1997 paper "Materials Selection for Musical Instruments" in the Proceedings of the Institute of Acoustics 19/5 pages 916-920 - sorry, I cannot find a free link, just this http://direct.bl.uk/bld/PlaceOrder.do?UIN=038339369&ETOC=RN ) you see that the best material is ... wood.
Answer: The sound variance of violins is surely greater than the difference in their optical appearance, so I assume different shapes are possible. Note, that the viola da gamba family, which also has a soprano member (not sounding sooo different) sports C-shaped holes, and baryton has nearly unregular ones so the effect of hole shape seems very minor.
I found a nice picture illustrating variance in German wikipedia different forms of viola da gamba.  A look-up in a violin makers book (Möckel, Geigenbaukunst) revealed, that of the f-hole the area is important. The violin body mainly needs to support many different resonance frequencies but no overly strong ones. This is most prominently influenced by the thickness of top plate, and (significantly less:) back; the sound post, bridge, type of wood, varnish etc. being less important.
Comment: I don't understand your first sentence: having large changes in sound from small changes in appearance would lead me to think that large changes in appearance would lead to even larger changes in sound; making radically different desgins sound un-violin-like.
Comment: @VruxNix. Actually, yes, and the short title of the book is already mentioned. The full title is Otto Möckel, Geigenbaukunst (Art of Violin Making), 8th edition, revised by Prof. Dr. Fritz Winkel, Technical University Berlin, chapter I/B/2; admittedly the book dates from 1954. I find it plausible, since the bridge is in direct contact with top plate only - lutes may be completelety different. While I'm neither expert physicist nor musician, I'm astonished, that the violin should already have been physically modelled to such a  degree to allow quantitative reponsibilities assigned.
Comment: @Dave: I admit, my argumentation is a bit adventurous: If large changes in sound are hard to catch, the factors influencing the sound must be somewhat hidden. So some optical changes may be possible without effect, if the invisible factors stay the same. I add some further insights to my answer.
Comment: @guidot Can you support your statement that the thickness of the top plate is of more significance than the sounding board? This is contrary to my teaching both in physics and luthiery.
Answer: I asked your question of a couple of players at the local amateur orchestra I'm in who make their own instruments. I know one was also a member of Cambridge University's Dynamics & Vibration Research Group before he retired. I'm not sure I entirely grasped the answer so this is more of a brain dump than a well structured answer - sorry!

The size of the hole affects the pitch and the quality of the sound. If you tap the front of a violin as you make it the tone changes as the whole size changes. It is generally felt that if the area of the f holes is too small the instrument sounds 'flat' or 'pinched'.
For the given area of hole you want the hole cut so that long curves lie with the grain and short sharp curves lie against the grain of the wood to lessen the probability that the wood will fracture. F holes are good in this respect.
You can think of the front of the violin body as two speakers like in hi-fi speaker stands, a larger one for lower sounds below a smaller diameter one fore higher pitches. The small circle and large circle of the violin body top vibrate in complicated ways: sometimes together, sometimes opposite, and sometimes transverse, i.e. sometimes the top needs to vibrate so that the left-right movement of the smaller section is opposite to the left-right movement of the larger section. But the smaller and the larger circles in a violin top are part of a single piece of wood so something needs to be done to weaken the wood joining the two ends. The f holes successfully do that and are an excellent shape for achieving that decoupling of movement without sacrificing strength overall.

Phew. I hope that helps.
Answer: This is an 8 year old dead thread but I had to chime in because all the answers are incorrect. MIT studied this, and holes with more perimeter give more airflow and sound, rather than wide circles (which were used for hundreds of years).
https://news.mit.edu/2015/violin-acoustic-power-0210
Comment: I also feel it necessary to add that the linked page, and others that cite it, make the same mistake that reporting on the sciences often makes, of taking the findings and leaping to causative conclusions with them (often making contextual mistakes in the process). The study focuses on variation among the exact proportions of the f-holes across cremonese makers, not the shift *from* other shapes *to* f-holes. I'd be very interested in that historical question, but...
Comment: ... but I imagine it's more complex than the version [BoingBoing](https://boingboing.net/2015/03/09/why-violin-makers-adopted-the.html) leaves with, getting the impression that Amati "invented" the f-hole. I'm not sure off the top of my head what the earliest iconographic record of the f-hole is, but there are plenty in Praetorius (1614—p 293 [of this pdf](https://s9.imslp.org/files/imglnks/usimg/8/81/IMSLP448854-PMLP138176-praetorioussyntagmamusicumII.pdf).


Symbols no rails

Question: Após criamos um modelo no rails é possível alterar o symbol criado?
Por exemplo criei um modelo chamado transação, o rails cria no plural transaçãos mas gostaria de alterar esse nome  para transações é possível?
Answer: Alterando o arquivo config/initializers/inflections.rb é possível configurar a  pluralização no Rails.
Recomendo dar uma lida na apostila da Caelum para melhor entender.
Apostila ruby on rails - caelum
Answer: É possível você configurar o plural como precisar, alterando o arquivo config/initializers/inflections.rb, que irá refletir em toda sua aplicação.
Vale lembrar, que o Rails é um framework CoC (Convention over configuration), sendo que a convenção é que o código seja escrito em inglês.
Isso significa que quanto mais você codar fora da convenção, mais configurações terá que fazer para obter o mesmo resultado esperado ao final.

Symbols no rails


Solving a Diophantine equation with LTE

Question: Show that only positive integer value of $a$ for which $$4(a^n+1)$$
is a perfect cube for all positive integers $n$, is $1$.
Rewriting the equation we obtain:
$$4(a^n+1)=k^3$$
It is obvious that $k$ is even and that in his prime factorization presents a prime factor $=2$ I proved to solve with LTE and other methods but in vain. How can I solve it?
Edit:
Supposing that a prime factor of $k$ ($k=p_1^{3q}\cdot p_2^{3q}\cdot ....\cdot p_j^{3q}$) is a divisor of $a+1$ (i.e. $p|a+1$) therefore the greatest power of $p$ that divides $a^n+1$ has to be a multiple of $3$: $$\upsilon_p(a+1)+\upsilon(n)=3q$$ but we can note that $3q$ depends not only by $a$ but also by $n$ therefore this isn't possible for hypothesis.
But if $p$ isn't  a divisor of $a+1$, How can I continue?
Comment: Because$\newcommand\nequiv{\not\equiv}$ we're working with cubes and $3\mid7-1$, we might look at it modulo $7$, as cubes are $0$ or $\pm\,1\pmod7$. This already rules out $a\equiv0,2,3,5$ (take $n=1$) and $a\equiv4,6$ (take $n=2$), hence $a\equiv1$. Not sure if it is useful, but $(a+1)(a^2+1)(a^3+1)=a^3+\frac{a^7-1}{a-1}$.
Answer: No need of LTE. Suppose $$4(a^n+1)=k^3 \tag{$\star$}$$ for some $a>1$. Then, since $a^n+1>2$, we must have $$a^n+1=16b$$ $$ a^n=16b-1 \tag{P(n)}$$ for some $b\ge1$ (in fact $b$ is a cube, but it is an unnecessary information for our purposes). However, if $P(n)$ holds, then multiplying both sides by $a$ we see that $P(n+1)$ also holds if and only if there exists a positive integer $c$ such that $a-1=16c$:$$a^{n+1}=16ab-a \\ a^{n+1}=16ab-(a-1)-1 \\ a^{n+1}=16\left(ab-\frac{a-1}{16}\right)-1.$$ But this yields that $P(n)$ is equivalent to $$a^n-1=16b-2 \\ (a-1)\left(a^{n-1}+a^{n-2}+\cdots+1\right)=16b-2 \\ 16c\left(a^{n-1}+a^{n-2}+\cdots+1\right)=16b-2,$$ which is clearly impossible, hence we conclude $a=1$ alone satisfies $(\star)$ for all positive integers $n$.

Solving a Diophantine equation with LTE


Eloquent with(), select() and where() selection

Question: This is my query to fetch data from 2 different table.
$variant = Variant::with(['v_detail' => function($q){
            $q->select('variant_dtl_name');
        }])->where('product_id','=',$productId)->get();

There is output, but v_detail returning empty list
result:
created_at: "2015-11-07 12:37:26"
id: 1
product_id: 30
updated_at: "2015-11-07 12:37:26"
v_detail: []
variant_name: "Pricing"

But with these query:
$variant = Variant::with('v_detail')->where('product_id','=',$productId)->get();

The result is:
created_at: "2015-11-07 12:37:26"
id: 1
product_id: 30
updated_at: "2015-11-07 12:37:26"
v_detail: [{id: 1, variant_id: 1, variant_dtl_name: "Adult", variant_dtl_price: 25,…},…]
0: {id: 1, variant_id: 1, variant_dtl_name: "Adult", variant_dtl_price: 25,…}
1: {id: 2, variant_id: 1, variant_dtl_name: "Senior", variant_dtl_price: 15,…}
2: {id: 3, variant_id: 1, variant_dtl_name: "Children", variant_dtl_price: 8,…}
variant_name: "Pricing"

Now, on the query that work, how can I fetch a specific column names. Thanks!!
Answer: You have this:
$variant = Variant::with(['v_detail' => function($q)
{
    // Either add the related foreign key or select all
    $q->select('related_foreign_key', 'variant_dtl_name');

}])->where('product_id','=',$productId)->get();

Since you are selecting only a single field which is variant_dtl_name then it's not possible to find out the related models because the relation builder foreign key is required. So, you have to select that foreign key as well. Notice the related_foreign_key in sub-query so use the right one, probably that is variant_id but not sure because you didn't mention anything about that.


why setState doesn't rerender React page

Question: I am having some datas from an API GET call,i store them in datas(so it's not longer a string) and i want to delete some of them when the user choose some filters. I see the data change on the console and setState them but the page doesn't update the new data.
const [datas, setData] = useState('');

const handleClick = (event) => {
    console.log("deleting")
    var newdata = datas
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

I used a new variable newdata because i saw that using the same variable data isn't recommended.
`
Comment: You initialize `datas` as a string, and then treat it as an array. Which is it supposed to be?
Comment: @kostaskrav: Then why initialize it to a string in the first place?  Keep your data types consistent.  Otherwise you're just asking for bugs and other unexpected behavior, like what you're seeing now.  If `datas` was a string (which *in the code shown* it is) then the error described wouldn't happen, because assigning it by value to another variable would create a new value.  But since *some other code* is modifying the data type and changing it to a reference to an array, that changes the behavior.
Comment: I would expect an entirely different error from this code.  Namely: *"Uncaught TypeError: newdata.splice is not a function"*  Since `splice()` is a function on arrays, not strings.
Comment: I then use a GET call and make it an array of objects.
Answer: You are mutating the content of the array.
Do this in handleClick instead:
const handleClick = (event) => {
    console.log("deleting")
    // Create a copy of datas, do not modify the original array
    var newdata = [...datas]
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

That would solve it because you're creating a copy of the array with the spread operator ...
As a general rule, I'd always favor immutable array methods over mutable ones. You can check the docs for the methods and if it reads something like "changes the contents of an array", then the method is mutating the original array. Use methods that return a new copy of the array instead.
Comment: Yes i had to wait 10 minutes because you answered before the threshhold i can accept an answer :P


Reducing a non regular graph to a regular one.

Question: I'm not a big expert in graph theory, I know basic algorithms, but I'm not quite familiar with proofs, here. I do wonder about the following (I came up with this problem, and I don't know whether or not is true).
Let $G$ be a connected graph such that $\delta(G) = 5$ and $\Delta(G) = 6$, then there's a spanning subgraph (i.e. obtained only by edge removal), such that it is 3-regular. In general what I've tried is assuming I'm removing an edge, but from there I get confused on what happens with the neighbours. As counter example I'm not able to come up with an example (I really get confused drawing all the lines etc. The question in general is given a graph $G$ such that $\delta(G) = p, \Delta(G) = q$ can $G$ be reduced to a $r-regular$ graph by edge removal only?
Answer: There's an easy way to show this can't be true for your initial case. Take any graph with $\delta(G)=5$, $\Delta(G)=6$ and an odd number of vertices (e.g. $G=K_{5,6}$). Now if we could remove edges to leave a $3$-regular graph we would have a $3$-regular graph with an odd number of vertices, which is impossible by handshaking.
In fact the graph given above, $K_{5,6}$, cannot be reduced to any regular graph by removing edges (except by removing all the edges). This is because any $r$-regular bipartite graph for $r>0$ has the same number of vertices in each part*, but any graph you can get to by removing edges from $K_{5,6}$ is bipartite with a different number of vertices in each part. This generalises to any $p,q,r$ with $p\neq q$.
* is true because if the parts have $a$ and $b$ vertices, the number of edges is $ra$ counting edges leaving the first part, but $rb$ counting the edges entering the second part, so $a=b$ or $r=0$.
Comment: What about if the number of vertices is assumed to be even?
Comment: @user8469759 You can just take two copies of $K_{p,q}$ and that will have an even number of vertices and no way to make it $r$-regular by removing edges. And it's easy to make that connected if you want by taking edges $uv$ in the first copy and $xy$ in the second and replacing them with edges $uy$ and $xv$.
Comment: I'll meditate on your comments and answer, thank you.


What does it mean by "approach the performance of the Bayesian gold standard"?

Question: It is a sentence in Dropout paper(Dropout: A Simple Way to Prevent Neural Networks from Overfitting).
"This can sometimes be approximated quite well for simple or small models, but we would like to approach the performance of the Bayesian gold standard using considerably less computation"
What does it mean by "approach the performance of the Bayesian gold standard" ?
Plus, I don't understand the next sentence too.
"We propose to do this by approximating an equally weighted geometric mean of the predictions of an exponential number of learned models that share parameters"
Answer: The "Bayesian gold standard" is to "regularize" predictions by computing the posterior predictive distribution $P(y|x,D) = \int p(y|x,w) p(w|D) dw$, where $D$ is our dataset and $w$ is the weights in our network. This integral is intractable in most cases.

We propose to do this by approximating an equally weighted geometric
  mean of the predictions of an exponential number of learned models
  that share parameters

The "exponential number of models" is simply all the possible dropout masks which could randomly have been selected. The geometric mean refers to the fact that at test time, you downscale the weights, creating some sort of average of all models.


Joint probability and Gaussian copula

Question: I have $\Pr(A)=29\%$ and $\Pr(B)=10\%$, where $A$ and $B$ are two events which are not independent.
In fact, a correlation measure suggests they're correlated by $\rho=0.8$.
I would like to calculate $\Pr(A \cap B)$, that is the probability both of them occur.
Here is what I've done in R:
<code>prA <- .29
prB <- .1
Sigma <- matrix(.8, 2, 2)
diag(Sigma) <- 1
qA <- qnorm(prA, 0, 1)
qB <- qnorm(prB, 0, 1)
library(mnormt)
pmnorm(x = c(qA, qB), mean = rep(0, 2), varcov = Sigma)
</code>
Is the result of such a code $\Pr(A \cap B)$ I'm looking for?
Comment: What does it mean for _events_ to be correlated? $\text{Pr}(A\cap B)$ can be _any_ number in $[0.0,0.1]$ with the possible exception of $0.29\times 0.1 = 0.029$ which would be the value of $\text{Pr}(A\cap B)$ if $A$ and $B$ were _independent_ events, a possibility that you have excluded.
Comment: If you are looking at $I_A$ the indicator random variable for the event $A$ and similarly $I_B$, then I do not think you can get the correlation between them greater than about $0.5216$, and that happens when $\Pr(A\cap B) = \Pr(B)$.
Answer: If $A$ and $B$ are just two binary random variables with $P(A=1) = p$, $P(B=1) = q$ and $\rho$ their correlation coefficient known, we can easily estimate the full joint distribution of $A$ and $B$.
Let $P(A=1 \cap B = 1) = r$, then $P(A =1, B=0) = p - r$, $P(A =0, B=1) = q - r$, and $P(A = 0, B=0) = 1-p-q+r$. The only unknown is $r$.
Now $r$ can be computed by writing out the expression for the correlation coefficient,
$E[(A-p)(B-q)] = \rho \sqrt{p q (1-p)(1-q)}$
the left hand side of which can be written out in terms of $p$, $q$ and $r$. This equation can be solved to obtain $r$.
Of course, as Henry pointed out above, there may not be a solution for certain combinations of $p$, $q$ and $\rho$,
Comment: I appreciate very much your answers, I'm studying them. Then my question would be: what am I really doing when I follow the steps which I've listed in my R code?
Comment: In fact, since $E[(A-p)(B-q)] = E[AB]-pq =r-pq$, the putative value of $r = P(A=1\cap B=1)$ is $$pq+\rho\sqrt{p(1-p)q(1-q)}=0.029 + 0.13612861565446\rho,$$ putative because the number thus computed might not be in the interval $[0,1]$.  In this instance, since the largest possible value of $r$ is $0.1$, $\rho$ cannot exceed $\approx 0.5216$ as pointed out by Henry. Since the smallest possible value of $r$ is $0$, $\rho$ cannot be smaller than $\approx -0.2130$ either.

Joint probability and Gaussian copula


Does this series over $SL_2(\mathbb{Z})$ converge?

Question: Consider the following series of positive numbers
$$
\sum_{\substack{a,b,c,d \in \mathbb{Z} \\ ad-bc=1}}\frac{1}{((a-b)^2 + (c-d)^2 + 1)^2}
$$
Does it converge? How to prove it?
Comment: Where are you considering $SL_2(\Bbb{Z})$?
Comment: In the "index set". The sum is over matrices $a,b,c,d$ in $SL_2(\mathbb{Z})$.
Answer: The answer to your literal question is "no", but for a reason which may clarify what question you actually intend to ask:
Since $\pmatrix{a & b \cr c & d}\pmatrix{1 \cr -1}=\pmatrix{a-b\cr c-d}$, the expression in the denominator is the fourth power of the length of the latter vector, plus $1$.
A key point is that isotropy/stabilizer subgroups in $SL_2(\mathbb Z)$ of non-zero vectors in $\mathbb Z^2$ are infinite. Here, $\pmatrix{1 & 0 \cr 1 & 1}\pmatrix{1 \cr -1}=\pmatrix{1\cr 0}$, and the isotropy subgroup of the latter vector is recognizable as $\pmatrix{1 & n\cr 0 & 1}$ for $n\in\mathbb Z$.
So at the very least you may want your sum to be not over $SL_2(\mathbb Z)$, but over the coset space $SL_2(\mathbb Z)/H$, where $H$ is the isotropy subgroup of $\pmatrix{1 \cr -1}$ in $SL_2(\mathbb Z)$.
In that case, your sum is a subsum of the sum of $4$th powers of lengths of non-zero vectors in $\mathbb Z^2$. (In particular, it is the sum over vectors $v=(x,y)$ with $x,y$ coprime, but we don't need this.) That is, $\sum_{x,y} {1\over (x^2+y^2)^2}$ with not both $x,y$ being $0$. Fooling around with polar coordinates and/or integral tests shows that this does converge.
EDIT: the revised version of the question is significantly different, even if the formulaic assertion may seem similar. Reformulating it to help explain its meaning, let $\varphi(z,w)=1/(z-\overline{w})^{2k}$. With $2k=2$ this would essentially be a Bergman kernel for the upper half-plane. For $2k>2$, this will wind up to be a reproducing kernel for holomorphic cuspforms (something like this appeared in Petersson 1940). That is,
$$
K(z,w) \;=\; \sum_{\gamma\in SL_2(\mathbb Z)} {1\over (cz+d)^{2k}}\varphi(\gamma z,w)
$$
has the property that (up to a constant)
$$ \int_{\Gamma\backslash\mathfrak H} K(z,w)\,f(w)\;(\Im w)^{2k} {|dw|\over (\Im w)^2} \;\;=\;\; f(z)
$$
where $\Gamma=SL_2(\mathbb Z)$. Summing over integer matrices with determinants $N$, instead, gives the $N$th Hecke operator. (This was also known long ago. S. Lang's "Intro to modular forms" has an appendix by D. Zagier using this to compute traces. In the first edition of the book, there was an error due to the fragility of the convergence of the trace... corrected in a later edition.)
A non-obvious, but conceptually robust and not-so-computational approach to proof of convergence is to "observe" that the given series is a subsum of the pullback of the Siegel-type holomorphic Eisenstein series on the Siegel upper half-space $\mathfrak H_2$ to the diagonally imbedded $\mathfrak H\times \mathfrak H$. (This was discussed in my paper, and H. Klingen's paper, in the 1984 Katata conference volume "Automorphic forms in several variables".) The convergence of those Eisenstein series was proven by H. Braun by 1939. Analogous reproducing kernels for holomorphic cuspforms exist for all the hermitian classical domains.
Of course, none of this is strictly necessary to understand convergence, but it does explain why we might care, and so on.
Comment: Thank you! I see that my question was a bit silly. I actually want to check if $\sum_{\gamma \in SL_2(\mathbb{Z})}(az + b + i(cz+d))^{-4}$ converges absolutely uniformly on the usual fundamental domain in $\mathbb{H}$. Do you have any idea?
Comment: Ah. Ok. Yes, this is a standard object... I will have time to respond a little later, if no one else does. By the way, if you want to google, it is a special value of the _reproducing_kernel_ for weight four level one cuspforms.
Comment: (Still occupied with various things, but hopefully tomorrow I can write something useful, since/if there do not seem to be visible ambient references...)
Comment: I see, that's very interesting! Unfortunately, none of the references I can find discusses convergence. Is there a standard way to estimate the sum I wrote over the whole fundamental domain?
Comment: That's very kind! Don't worry too much about it, though. I think I actually understand it now (but I imagine there are probably better ways of thinking about this).


bastille linux command line pass config file with answers

Question: I have bastille for hardening and Im using it as follows
    /usr/sbin/bastille -c

The above starts it in interactive mode
Is it possible to provide bastille linux set of answers via a file on the command line? If yes, an example would be helpful. Thank You
Answer: According to the fine manual, copying the config you want into /etc/Bastille/config and then running bastille -b should do the trick.
Comment: Thank You womble .... in future ill be sure to RTM carefully before posting qs to the community ... appreciate your help and guidance....


AutoMapper - mapping integers to int array

Question: I'm trying to map integers from a database to an int array, but I'm getting the error:  AutoMapper.AutoMapperConfigurationException: 'Custom configuration for members is only supported for top level individual members on a type.'
This is what I have:
Model:
public class Year
{
    public int[] Months { get; set; } = new int[3];
}

Mapping:
CreateMap<DataRow, Year>()
    .ForMember(dest => dest.Months[0], opt => opt.MapFrom(src => src["Jan"]))
    .ForMember(dest => dest.Months[1], opt => opt.MapFrom(src => src["Feb"]))
    .ForMember(dest => dest.Months[2], opt => opt.MapFrom(src => src["Mar"]))

Anyone know how to get this to work?
Answer: You will need to do something like this
.ForMember(dest => dest.Months, opt => opt.MapFrom(src => MapFromRow(src)))

where you have a method
int[] MapFromRow(DataRow src)
{
    int months = new int[12];

    months[0] = src["Jan"];
    ...
    return months;
}

AutoMapper does not seem to support "dotting" into a property or indexing into an array.
If you want to go fully inline, you can do
.ForMember(dest => dest.Months, opt => opt.MapFrom(src => new int[]
    {
        (int)src["Jan"], (int)src["Feb"], ...
    }))

Comment: I missed the explicit cast. Wasn't in front of a compiler at the time. Try the updated answer.
Comment: Thanks, but for the inline solution it's complaining about src[".."] not able to convert object to int.  src is the DataRow
Comment: Yup I figured, I went with your first solution thanks!


How to Increase the weight for one predictor variable?

Question: Just read this news: "Zuckerberg agreed to increase the weight that Facebook's algorithm gave to NEQ scores to make sure authoritative news appeared more prominently." My question is: how can we increase the weight/importance of a predictor variable to influence the outcome when building a model? Or for this case, is actually NEQ scores a part of the target variable (in other words, the target variable is composed from multiple objectives)?
Answer: Lets say Facebook uses a model which evaluates the importance as following
importance = b_1 x age + b_2 x location + b_3 x NEQ.
b_3 represents the weight that NEQ is assigned. If b_3 is manually increased then it also increase the contribution to the overall importance.


With nginx how do I do a mass redirect of all www sites to non www sites

Question: Something like
<code> server {
   listen 80 default;
   server_name  _ ;
   root /home/drew/sites/$host;
   rewrite ^www(.*) http://$host$1 permanent;
 }
</code>
Answer: <code> server {
   listen 80 default;
   server_name the very first;
   rewrite "^www\.(.*)" http://$1 permanent;
 }
</code>
Then use respective server declarations with their roots
Comment: What does "server the very first" mean?
Comment: It is just important taht this server declaration to be the very first for nginx. Maybe even in nginx.conf or make sites-enabled/000-default. No matter what server name you give to it. Put something nonexistent
Comment: If you mark it as default (or default_server in the stable version which you should be using!) then it doesn't matter where in the config it's located.
Answer: I figured out how to mass redirect www sites to non www
<code> server {
   listen 80 default;
   server_name  _ ;
   if ($host ~ ^(www\.)(?<domain2>.+)$) {
      set $domain2 $2;
      rewrite ^ http://$domain2$request_uri?;
   }
   root /home/drew/sites/$host;
 }
</code>


Test setTimeout with React Native Testing Library and Jest

Question: I have a React Native app with the following Player component that infinitely calls a play() function with a setTimeout. I'm using react-native-testing-library for rendering/testing along with jest.
I am trying to test this setTimeout function. Specifically, I want to spy on the function so that I can expect the setTimeout to have been called any number of times after a given set of seconds. For example, after 3 seconds, the function should have been called 3 times. I am having issues testing this however. My current test looks like this:
fit('displays the content', async () => {
            //jest.useFakeTimers();

            const { debug, toJSON, getByText, getByTestId } = render(
                <Player token={'test-token'} saveToken={saveTokenMock} />
            );
            //jest.runOnlyPendingTimers();
            const data = {"device":{"id":58,"updated_at":"2021-07-05T01:39:53.588Z","events":[{"my data here"}]}]}};
            mock.onPost('https://www.mydomain.io/api/v1/devices/events').reply(200, data);

            await waitFor(() => {
                expect(getByTestId('imageAsset')).toBeTruthy();
                expect(toJSON()).toMatchSnapshot()

            });

})

When I add the jest.useFakeTimers() and jest.runOnlyPendingTimers(), the waitFor function errors with a timeout error. How can I spy on the setTimeout? Here is the general idea of my component:
class Player extends Component {
   componentDidMount(){
       this.play()
    }

   play() {
     //does some things

     setTimeout(play, 1000)
   }
}

Answer: You can advance the time using advanceTimersByTime provided by jest.
In order to check the number of the function calls, use  toHaveBeenCalledTimes.
The provided example in Jest documents is very similar to your component.


Convergence of a Sequence Implies Closed Set

Question:
QUESTION:
I believe the following are equivalent, but I am wanting to show why  $(1)\implies (2)$ in regards to below. I came across a proof on this site as to why accumulation/limit points are related to Hausdorff to try to start the proof, but  I got stuck on the part that discussing $N-1$ elements. After getting stuck, I wasn't sure even if this was an appropriate route to take to prove why $(1)$ implies $(2)$. Any help would be greatly appreciated!

For the following, $X$ is a metric space, $A\subseteq X$, and the notation $\lbrace a_n \rbrace_{n\in \mathbb{N}}\rightarrow x$ denotes the sequence converging to the limit $x\in X$.

$\textbf{(1)}$ $\forall$ sequence $\lbrace a_n \rbrace_{n\in \mathbb{N}}$ that is a subset of $A$, [if $\lbrace a_n \rbrace_{n\in \mathbb{N}}\rightarrow x$, then $x\in A$].
$\textbf{(2)}$ the set $A$ is closed.

I have previously shown the following are equivalent definitions of a closed set concerning the problem.
\begin{align*}
A \text{ is a closed set} &\leftrightarrow X-A \text{ is open }\\
&\leftrightarrow closure(A)=A\\
&\leftrightarrow boundry(A)\subseteq A\\
&\leftrightarrow \forall \text{ limit point } c \text{ of } A, c\in A.\\
\end{align*}
Comment: As its name suggests, a limit point $x$ (in a metric space) is a limit point precisely because there exists a sequence $x_n$ such that $x_n\to x$ as $n\to\infty$. Just think of open balls with radius $1/n$ to construct such a sequence.
Comment: I am using the following as a definition of a limit point:
Comment: Let $A\subseteq X$. Let $b\in X$. We say $b$ is a limit point of $A$ iff $\forall B_x$ (an open ball with center $x$), $(B_x-\lbrace x \rbrace)\cap A \neq \phi$.
Comment: Is that the best way to solve this problem? Could I see more how to solve it then?
Answer: This is true. Let $x$ be a limit point in a metric space $(X,d)$. We claim $X$ is closed if and only if for every convergent sequence, it converges in $X$.
$\Rightarrow$ Assume $X$ is closed, e.g. it contains all of its limit points. Now let $\{x_n\}$ be a convergent sequence contained in $X$ that converges to $x$. Then for any $r>0$, $B_r(x) \cap X \neq \emptyset$, so $x$ is a limit point, therefore it's in $X$.
$\Leftarrow$ Assume for every $\{x_n\}$ be a convergent sequence that is contained in $X$, it converges in $X$. Let $x$ be a limit point, then take $r_n = \frac{1}{n}$ to get a convergent sequence. Then by assumption $x \in X$, so $X$ has all of its limit point, so by def it's closed.
Comment: Can you explain more what you mean by taking $r_n=\frac{1}{n}$ to get a convergent sequence? Reading the first comment, I see you do something with open balls. Is the convergent sequence something like $B(x, r_n)$ (I am not sure)? I see your using the last definition of the closed set to prove this but not sure how you go about finding a convergent sequence.
Comment: To construct a sequence, let $x_1$ in $B_{1}(x) \cap X$ and similarity for $x_n \in B_{1/n}(x) \cap X$
Comment: I just am thinking of the reasons as to why that would be well defined in the first place.Why would $\forall n\in \mathbb{N}$, $x_n \in B_r(x)$ when $r=\frac{1}{n}$ hold true?
Comment: I'm not sure if you are getting it from the limit point definition or what. I appreciate your help.
Comment: It comes from the definition. $x$ is a limit point in $(X,d)$ if and only if for all $r > 0$, $B_r(x) \cap X \neq \emptyset$. Taking $r = \frac{1}{n}$, we see $B_{1/n}(x) \cap X \neq \emptyset$. As it's non-empty, we can choose a point in the ball and choose that to be our $x_n$
Comment: I'm essentially using the definition of a limit point to construct a sequence. What I'm basically saying if for every $n \in \mathbb{N}$ there exists an $x_n$ such that $d(x,x_n) < \frac{1}{n}$. I'm finding this $x_n$ by using the limit point definition. E.g. for $n=1$, by limit point definition, $B_{1}(x) \cap X \neq \emptyset$, so take any point in this intersection to be our $x_1$. Then for $n=2$, by limit point definition, $B_{1/2}(x) \cap X \neq \emptyset$, so take any point in this intersection to be our $x_2$. We may well have $x_1 = x_2$, but that doesn't matter.


Output format is wrong

Question: i submitted this on codeforces
the checker's comment came-'"wrong output format Expected integer, but "Enter" found""
where is the mistake
 #include<iostream>
 using namespace std;

 int main(){
     int n,m,a,i,l = 0,k = 0;

     cout<<"Enter the values of n,m,a";
     cin>>n;
     cout<<"\n";
     cin>>m;
     cout<<"\n";
     cin>>a;

     for(i = a ; i < n ; i = i + a){
         l++;
     }

     for(i = a ; i < m ; i = i + a){
         k++;
     }

     cout<<"The least number of flagstones needed is"<<(l+1)*(k+1);

   return 0;
}

Comment: Are you supposed to output anything except the actual result?
Comment: Are the `for` loops required?  Looks like you could reduce them to one math expression each.
Answer: On competition websites you should not print anything but the expected answer thus all the messages like "Enter the values of n,m,a" and the newlines should not be there. Remove all cout-s and leave only the last one like cout<<(l+1)*(k+1)<<endl; codeforces does not care too much but usually you should have an empty line after your last output line.

Output format is wrong


Gson.toJson()"Exception java.lang.IllegalArgumentException: class java.text.DecimalFormat declares multiple JSON fields named maximumIntegerDigits"

Question: I am trying to make a JSON file to use it as a database. my classes are:
1. Sheep: includes some info about every sheep
2. Farm: includes an array of Sheeps
3. DB: here I am trying to parse the Farm object into JSON
I have already tried to add "transient" to all the fields from the date type but it did not work.
to give you a better idea of what I am trying to do: it is a farm manager where the user can store the data about his sheeps
public class Sheep implements Serializable {

    @SerializedName("localId")
    @Expose
    private int localId;
    @SerializedName("globalId")
    @Expose
    private int globalId;
    @SerializedName("birthDate")
    @Expose
    private transient Date birthDate = null;
    @SerializedName("sellingDate")
    @Expose
    private transient Date sellingDate = null;
    @SerializedName("deathDate")
    @Expose
    private transient Date deathDate = null;
    @SerializedName("lastpregnancyDate")
    @Expose
    private transient Date lastpregnancyDate = null;
    @SerializedName("lastDoctorCheck")
    @Expose
    private transient Date lastDoctorCheck = null;
    @SerializedName("alive")
    @Expose
    private boolean alive;
    @SerializedName("sold")
    @Expose
    private boolean sold;
    @SerializedName("pregnant")
    @Expose
    private boolean pregnant;
    @SerializedName("mother")
    @Expose
    private Sheep mother = null;
    @SerializedName("father")
    @Expose
    private Sheep father = null;
    @SerializedName("allDoctorChecks")
    @Expose
    private transient List<Date> allDoctorChecks = null;
    @SerializedName("allpregnancies")
    @Expose
    private transient List<Date> allpregnancies = null;
    @SerializedName("children")
    @Expose
    private List<Sheep> children = null;
    @SerializedName("allHusbands")
    @Expose
    private List<Sheep> allHusbands = null;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
}

public class Farm implements Serializable {

    @SerializedName("allSheeps")
    @Expose
    private List<Sheep> allSheeps = null;
}

public class DataBase {
    private static Farm farm;

public static void main(String[] args){
        ...

        Gson g = new GsonBuilder().setPrettyPrinting().create();
**/*40*/  String strGsn = g.toJson(farm);/*this is line 40*/**

        FileWriter writer = null;
        try{
            writer = new FileWriter("farm.json");
            writer.write(strGsn);
        }catch (Exception e){
            System.out.println(e.fillInStackTrace());
        }finally {
            if(writer != null)
                try{
                    writer.close();
                }catch (Exception e){
                    System.out.println(e.fillInStackTrace());
                }
        }

    }

}

"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\lib\idea_rt.jar=53834:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\saleh\Desktop\farm\out\production\farm;C:\Users\saleh\.m2\repository\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar com.company.DB.DataBase
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.gson.internal.reflect.UnsafeReflectionAccessor (file:/C:/Users/saleh/.m2/repository/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar) to field java.text.SimpleDateFormat.serialVersionOnStream
WARNING: Please consider reporting this to the maintainers of com.google.gson.internal.reflect.UnsafeReflectionAccessor
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" java.lang.IllegalArgumentException: class java.text.DecimalFormat declares multiple JSON fields named maximumIntegerDigits
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
    at com.google.gson.Gson.getAdapter(Gson.java:458)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:56)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
    at com.google.gson.Gson.toJson(Gson.java:704)
    at com.google.gson.Gson.toJson(Gson.java:683)
    at com.google.gson.Gson.toJson(Gson.java:638)
    at com.google.gson.Gson.toJson(Gson.java:618)
    at com.company.DB.DataBase.main(DataBase.java:40)

Answer: The exception

java.lang.IllegalArgumentException: class java.text.DecimalFormat declares multiple JSON fields named maximumIntegerDigits

is due to the field sdf of Sheep is being serialized. It is questionable on why SimpleDateFormat can not be serialized to json, but to solve the problem, since you are using @Expose annotation to control which field to be serialized, change the line
Gson g = new GsonBuilder().setPrettyPrinting().create();
to
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
in order to avoid sdf to be serialized.


A problem about $-\max$ and $\min$

Question: Suppose $X$ and $Y$ are convex compact subsets in $\mathbb R^n$. Let $\langle.,.\rangle$ be the standard inner product.
Does the following equality
$$\max_{y\in Y} [\langle y, z\rangle- \max_{x\in X}\langle y, x\rangle]=\max_{y\in Y} \min_{x\in X}\langle y, z-x\rangle $$
hold?
I saw the term on the l.h.s. in elemetary convex analysis books but have never seen the term on the r.h.s. in any book. So it makes me unsure about whether this equality is true.
Thanks a lot.
Answer: Notice that $\langle y, z-x\rangle =\langle y,z \rangle-\langle y,x \rangle$. Hence
$$\min_{x \in X} \langle y, z-x\rangle=\min_{x \in X}[\langle y,z \rangle-\langle y,x \rangle]=\langle y,z\rangle -\max_{x \in X}\langle y,x \rangle.$$
Now apply the $\max_{y \in Y}$ on both sides.

A problem about $-\max$ and $\min$


Using CursorLoader with LoaderManager to retrieve images from android apps

Question: At the moment I'm using getContentResolver().query()/managedQuery() to get a cursor to retrieve images from the gallery app. Because the APIs I'm using are partly deprecated I wanted to use CursorLoader with LoaderManager.
/**
 * Creates a cursor to access the content defined by the image uri for API
 * version 11 and newer.
 *
 * @return The created cursor.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private Cursor createCursorHoneycomb() {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);

    return cursor;
}

/**
 * Creates a cursor to access the content defined by the image uri from API
 * version 8 to 10.
 *
 * @return The created cursor.
 */
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.FROYO)
private Cursor createCursorFroyo() {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    Cursor cursor = managedQuery(imageUri, projection, null, null, null);

    return cursor;
}

Since I don't have a ListView I don't use any adapter. I just set an image bitmap for an ImageView.
/**
 * Sets the image bitmap for the image view.
 */
private void setupImageView() {
    String imagePath = getImagePathFromUri(imageUri);
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    ImageView imageView = (ImageView) findViewById(R.id.image_view);

    imageView.setImageBitmap(bitmap);
}

/**
 * Returns an image path created from the supplied image uri.
 *
 * @param imageUri The supplied image uri.
 * @return Returns the created image path.
 */
@SuppressWarnings("deprecation")
private String getImagePathFromUri(Uri imageUri) {
    Cursor cursor = null;
    String imagePath = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        cursor = createCursorHoneycomb();
    } else {
        cursor = createCursorFroyo();
    }

    // if image is loaded from gallery
    if (cursor != null) {
        startManagingCursor(cursor);

        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();
        imagePath = cursor.getString(columnIndex);
    }
    // if image is loaded from file manager
    else {
        imagePath = imageUri.getPath();
    }

    return imagePath;
}

Is it possible to use CursorLoader with LoaderManager to load images from the gallery app or a file manager? I cant't find any solution.
Answer: Start the loader manager by invoking getSupportLoaderManager when it is needed.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            imageUri = data.getData();
            getSupportLoaderManager().initLoader(0, null, this);
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Action canceled.", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "Action failed!", Toast.LENGTH_LONG).show();
        }
    }
}

Then create a cursor loader that is used to retrieve the image path.
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    CursorLoader cursorLoader = new CursorLoader(this, imageUri, projection, null, null, null);

    return cursorLoader;
}

When the cursor loader is finished it uses the retrieved data to update the UI.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null) {
        int columnIndex = data.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        data.moveToFirst();
        imagePath = data.getString(columnIndex);
    } else {
        imagePath = imageUri.getPath();
    }

    setupImageView();
}

It's quite easy to do. But I had to understand how to use onCreateLoader() and onLoadFinished().
Comment: Would it be possible for you to share with me your entire code here? I badly need to do the same thing (but with MediaStore Audio) and no matter what I do, the OnLoadFinished is not called. I thank you in advance for your generosity.
Comment: It's keepsaying to change return type to CursorLoader in public Loader onCreateLoader(int id, Bundle args). Please help me out.
Comment: @dariusiv: You have to start the the loader by `getLoaderManager().initLoader(, , )`, usually `getLoaderManager().initLoader(0, null, this)`.
Answer: You may want to replace this
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
with this
CursorLoader cursorLoader = new CursorLoader(this, imageUri,
projection, null, null, null);
Cursor cursor = CursorLoader.loadInBackground();

Answer:
Is it possible to use CursorLoader with LoaderManager to load images from the gallery app or a file manager?

Only if they publish, document, and support a ContentProvider.
Comment: Thanks for your answer, CommonsWare. For now I have to accept that there is no better solution. I'll try to find a better solution.
Comment: Finally I found a solution. See my answer below.


What does this symbol mean?

Question: I've gotten a new song from my music teacher though, she never mentioned anything about this symbol.

I'm rather new, can anyone explain to me what this represents?
Comment: The Elephant Song! I learned to play it when I was trying to learn Thai, and it's what I play at parties when everybody (me included) is a bit drunk. Meeting it here was an unexpected pleasure. Chaang chaang chaang!
Answer: That's an eighth note (quaver) rest. If you know how to play the quarter note (crotchet) rest in the previous measure, then it's the same thing, just half as long.
I suggest you bookmark the following page for future reference:
Musical symbols.

What does this symbol mean?


Falha ao passar menu do html para o CakePHP

Question: No link abaixo eu tenho um Menu funcionando perfeitamente no Codepen conforme link abaixo:
https://codepen.io/FabricioDev/pen/JOmjEg
Inicio do CSS
#DPrincipais
{
  display: block;
}

#TrabalhoRendimento
{
  display: none;
}
#Referencia
{
  display: none;
}
#Comprovante
{
  display: none;
}
.ContForm
{
  border: 1px solid #98adab !important;
  width: 750px !important;
  margin-left: 0px !important;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: flex-start;
}
.LabelForms
{
  padding-left: 5px;
  padding-right: 5px;
  border-left: 0px;
  border-right: 0px;
  border-top: 0px !important;
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  color: #98adab;
}
.InputForms
{
  border: 0px;
  border-right: 1px solid #98adab !important;
  height: 30px;
  line-height: 30px;
  width: 100% !important;
  font-weight: bold;
  padding-right: 7px;
  padding-left: 7px;
}

Fim do Css
Inicio do Menu

<?= $this->Html->link('> '.__('Student Data'), '#DPrincipais', ['style' => $dataButton]) ?>

> Trabalho Rendimento

<?= $this->Html->link('> '.'Trabalho','#TrabalhoRendimento', ['style' => $matriculaButton]); ?>

Fim do Menu
Inicio do Javascript
const divs = [...document.querySelectorAll('#DPrincipais,#TrabalhoRendimento,#Referencia,#Comprovante')];
const botoes = [...document.querySelectorAll("li")];

for (let i = 0; i < botoes.length; ++i){ //percorrer todos os botoes
  botoes[i].addEventListener("click", function(){ //definir o click para cada um
    divs.forEach(div => div.style.display = "none"); //esconder todos os divs
    divs[i].style.display = "block"; //mostrar o que foi clicado
  });
}

divs.forEach(div => div.style.display = "none"); //iniciar todos escondidos
divs[0].style.display="block"; //Exibe só a primeira div

Fim do Javascript
Inicio do Edite

   <fieldset>
      <legend>
         <?php echo __('Dados Básico') ?>
      </legend>

            Nome

            <?php
            echo $this->Form->control('nome', ['type' => 'text', 'class' => 'InputLabelUnic', 'name'=>'txtNome',
            'label' => false ]); ?>

            Data Cadastro

            <?= date('d/m/Y'); ?>

   </fieldset>

   <fieldset>
      <legend>
         <?php echo 'Trabalho'; ?>
      </legend>

            Atividade principal

            teste 1

            Setor

            teste 2

   </fieldset>

Fim do Edite
Comment: Note que tem um erro no código: ``
Comment: @fabricio_wm Pelo erro da imagem parece exatamente o que eu disse. Tem de especificar mais os `` senão acerta em todos. Experimente com algo como `const botoes = [...document.querySelectorAll(".side-nav li")];`, assumindo que os botões que quer dar a funcionalidade de click são os que estão dentro de ``
Comment: O código JS tem de ser executado apenas depois de a pagina carregar, caso contrário os botões e/ou `` ainda não existirão. Está a fazer isso ? Executando por exemplo no `onload` do `` ou colocando o código no fim do ``
Comment: Cuidado que o `querySelectorAll("li")` apanha todos os `` da página renderizada. Confirme se é isso que pretende, e caso não seja localize mais o seletor adicionando hierarquia
Comment: @ÐvÐ O meu aqui não está com erro.
Não sei o que aconteceu.
Obrigado.
Comment: Na verdade, esse código foi adaptado.
Não sei se fiz certo mas eu troquei o button por um li que é o que eu estou usando, @Isac.
O que vc me recomenda?
Comment: @Isac
O código original é o seu mesmo. rsrs
https://pt.stackoverflow.com/questions/257799/como-manter-uma-div-sempre-ativa/257819#257819
Como vc acha que eu devo fazer?
Comment: https://imgur.com/a/Xixil
Olha esse erro ao inspecionar o código, @Isac
Comment: O erro dá na linha 30 desse `script.js`, qual a instrução que está nessa linha ? Clique no inspecionar nessa linha e mostre aqui para se saber exatamente onde tá a dar o erro
Comment: https://imgur.com/a/iWHMW
Seria nessa aba, @Isac
Comment: Os quatro primeiros link deveriam apontar para a mesma Div mas estão funcionando como se ele pegasse as divs e distribuísse na sequenciaria para os 4 primeiros menus.
Comment: @Isac
Fincionou com:
const botoes = [...document.querySelectorAll(".side-nav li")];
Coloca como resposta para finalizar.
Obrigado.
Answer: O seletor que está a utilizar para construir os botões:
const botoes = [...document.querySelectorAll("li")];

É muito amplo e acaba por acertar em mais elementos que os pretendidos.
Uma forma simples de resolver é acrescentar hierarquia para que acerte apenas nos
 de uma determinada parte do html. Tendo em conta que os
 em causa fazem parte da barra de navegação, a
, pode acrescentar esta classe ao seletor para acertar apenas nos
 que estão lá dentro.
Para isso apenas precisa de trocar o obter dos botões para:
const botoes = [...document.querySelectorAll(".side-nav li")];


Uploading pictures to Facebook using Graph API with Android SDK

Question: I am trying to upload a photo to facebook using graph api and keep getting OutOfMemory exception.
The code for the upload is this:
private void PostPhoto(SessionHandler facebook, Uri photoUri)
{
    Bundle params = new Bundle();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    String realPath = getRealPathFromURI(photoUri);
    Bitmap bitmap = BitmapFactory.decodeFile(realPath);

    bitmap.compress(CompressFormat.JPEG, 100, bos);

    params.putByteArray("picture", bos.toByteArray());

    try
    {
        facebook.mFacebook.request("me/photos", params, "POST");

    } catch (FileNotFoundException fileNotFoundException)
    {

    } catch (MalformedURLException malformedURLException)
    {

    } catch (IOException ioException)
    {

    }

}

The exception raises on the decodeFile function and sometimes in the facebook SDK itself when it calls this line:
return Util.openUrl(url, httpMethod, parameters);

inside the request function.
The app is getting the picture content:// Uri by the ACTION_SEND intent.
getRealPathFromURI() is used to translate the content:// uri to a real sdcard path.
Any ideas?
Comment: can you show the stack trace for the error.
Answer: Try this, it works for me:
byte[] data = null;
try {
    ContentResolver cr = mainActivity.getContentResolver();
    InputStream fis = cr.openInputStream(photoUri);
    Bitmap bi = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    data = baos.toByteArray();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);

This is using the Rest API, the facebook sdk has the method for calling it so just change your request line from:
facebook.mFacebook.request("me/photos", params, "POST");

to:
facebook.mFacebook.request(params);

and hopefully that will solve the problem.
Comment: @Idan - can you post the response your getting from facebook
Comment: looks like this code is not getting the out of memory exception. the code does reach the onComplete of the RequestListener, but the picture does not show in facebook. Tried to change the null in the request to "me/photos" and still nothing in the profile or albums.
Comment: response: Unsupported method, photos.upload
Comment: sorry this is using the legacy Rest API, see my edited answer for details on how to fix it. I'll try and figure out the graph API way to do it and let you know, but it might not be implemented yet!
Comment: By removing the method line the upload was successful but the pictures got in to a new album named after the app name. When getting in it using the web i get a message saying these pictures was uploaded using a different application and that i need to approve them.
Comment: You can add in the parameter "aid" as a string, i think this will set the album name, also add "uid" as an int which is the user id this might get around having to approve them (probably depends on the users privacy settings though)
Comment: added the params. did not helped. still asking me to approve the photos.
Comment: Ok SOLVED. has to add a publish_stream permission. to publish to an existing album i have to use aid/photos in the request path.
Comment: I presumed you already had that! Note to self - never presume anything! lol, glad you got it working. Can you mark the question as answered - ta.
Comment: I have done step by step but Facebook return the message":"Unsupported method, photos.upload.


Backing up a RIAK database data

Question: I'm very new to RIAK. I have a cluster with 5 nodes and I want to backup the data on the cluster. I ran the following command to backup data.
[root@PCPRIAK33 local]# riak-admin backup localhost riak /var/local/temp all

However I am getting the following error.
Attempting to restart script through sudo -H -u riak
{"init terminating in do_boot",{{nocatch,{could_not_reach_node,localhost}},[{riak_kv_backup,ensure_connected,1,[{file,"src/riak_kv_backup.erl"},{line,171}]},{riak_kv_backup,backup,3,[{file,"src/riak_kv_backup.erl"},{line,40}]},{erl_eval,do_apply,6,[{file,"erl_eval.erl"},{line,572}]},{init,start_it,1,[]},{init,start_em,1,[]}]}}
init terminating in do_boot ()

Can you please help me out? :)
Thanks.
Answer: I'll answer your immediate question (how to use riak-admin backup) first, but see the comments on preferred methods of backing up, at the end.
The command is:
riak-admin backup <node name> <erlang cookie> <file name with path> all
The node name you can find in your riak vm.args file (look for the line that looks like -name firstname.lastname@example.com). It'll be of the form email@example.com with the IP address. So, on my local machine, a single node is named email@example.com.
The erlang cookie is also found in the vm.args file, it will most likely be erlang.
The file name parameter should be a fully-qualified path to the actual file name (meaning, you can't give it just a directory name). The filename and extension are arbitrary. So, I would use something like cluster_backup.riak.
So, to put it all together, your backup command should look like:
riak-admin backup riak@<your node ip> riak /var/local/temp/cluster_backup.riak all
Now, having said all that, I don't recommend using the riak-admin backup and restore commands to back up your whole cluster. For several reasons. One, it stores every replica of every object. Meaning, if you're running with the default replica value of n=3, you will be storing 3 copies of each object in your backup file.
Two, the code invoked by that command is single-threaded, and not connection pooled. So all in all, it's going to be SLOW to restore and backup.
Instead, I recommend one of the following approaches:

Take filesystem level snapshots of the data directories of each node. This is the approach currently recommended by Basho, and detailed here: http://docs.basho.com/riak/latest/ops/running/backups/
If you definitely want a "logical" backup (meaning, an export of the objects contained in the cluster), you can use an experimental standalone tool such as the Riak Data Migrator (but see the limitations in the Readme).

I recommend testing out / timing each of these approaches, to see which one is faster for your situation.

Backing up a RIAK database data


Stripe Refunds Error

Question: I am using Stripe Python library version 1.23.0 with Python 2.7. When I try to process a refund using the following code
import stripe
stripe.api_key = <my_api_key>
refund = stripe.Refund.create(
        charge=payment_id.stripe_id
    )

I get an error that

'module' object has no attribute Refund

I have checked the init file and indeed Refund hasn't been imported.
I checked with stripe support and they said

The Refund object was added on the 1.25.0 version of our library

I cant find any documentation on how refunds are processed in library version 1.23
Comment: @Anoop's response is correct, you can call the `refund` method on charge objects. That said, you should be able to upgrade to the latest version of the Stripe Python bindings (1.43.0) without any issues: Stripe increments the major version number when backwards-incompatible changes are introduced.
Answer: Try this,
import stripe
stripe.api_key = <my_api_key>
resp = stripe.Charge.retrieve(charge_id)
resp.refund()

Stripe Refunds Error


Get custom fields from users table in global user object

Question: I've altered users table and added two new fields directly using MySQL workbench

first_name
last_name

If we add new fields by config > people > site information > manage fields, it does not allow adding drop-down list. So, directly added using MySQL workbench.
Now I was able to alter user_register_form and added above two fields with validation.
At the time of creating new user, the values of first_name and last_name gets stored in users table.
Now, how to get those two fields when user logs in?
i've used below code to print user object
global $user;
$user_full = user_load($user->uid);
print_r($user_full);

Any help would be appreciated, thanks !!
Comment: This is not the way to do it ! Use the [entity module](https://www.drupal.org/project/entity) to add field to the user object just like you add field to a content type. When you create your field tick the `"Display on user registration form."` option.
Answer: You can implement the hook_user_load() for this purpose
I have altered the user table with field "fname" , Now you can load this in user object with the help of hook_user_load() func.
function testing_custom_user_load($users) {
  foreach ($users as $record) {
     foreach ($users as $record) {

        $result = db_query("SELECT fname FROM {users} WHERE uid IN ($record->uid)")->fetchAssoc();

        $users[$record->uid]->extra =$result['fname'];
     }
  }

}

Just put this code snippet in any of your custom module file.
Comment: I want those fields in $user object, how it can be done and where should the above code placed ?
Comment: Answer updated, Please check.


propagation of error from product of Taylor Series

Question: Say I have two functions $f(x)$ and $g(x)$, both of which I will be approximating with Taylor series $T_f(x)$ and $T_g(x)$ respectively. Lets say $f(x)$ is order $O(x^{n_1})$ and $T_f(x)$ has error of order $O(x^{m_1})$. Likewise $g(x)$ is order $O(x^{n_2})$ and $T_g(x)$ has error of order $O(x^{m_2})$.
Given that, what is the order of the error for $T_f(x)T_g(x)$?
What I have thought of so far is that $f(x)g(x) = (T_f(x)+E_f(x))(T_g(x)+E_g(x))= T_f(x)T_g(x) + E_f(x)T_g(x) +  E_g(x)T_f(x) + E_f(x)E_g(x)$
and if the orders multiply then $E_{total}=\max\{x^{n_2+m_1},x^{n_1+m_2},x^{m_2+m_1}\}$
But that looks like the error would go down, not up like it should be.
Answer: When you multiply two truncated series you get an approximation of the product function which is as good as the lowest one:
$$
\eqalign{
  & \left( {a_{\,0}  + a_{\,1} x + a_{\,2} x^{\,2}  +  \ldots  + O\left( {x^{\,m} } \right)} \right)\left( {b_{\,0}  + b_{\,1} x + b_{\,2} x^{\,2}  +  \ldots  + O\left( {x^{\,n} } \right)} \right) =   \cr
  &  = c_{\,0}  + c_{\,1} x + c_{\,2} x^{\,2}  +  \ldots  + b_{\,0} O\left( {x^{\,m} } \right) +  \ldots  + a_{\,0} O\left( {x^{\,n} } \right) =   \cr
  &  = c_{\,0}  + c_{\,1} x + c_{\,2} x^{\,2}  +  \ldots  + O\left( {x^{\,\min \,(m,\,n)} } \right) \cr}
$$
Comment: Well, in very simple wording, if the first approximation is correct up to the $m$th term and the second up to the $n$th, then the multiplication - which is a linear combination of terms $j$*$k-j$ - will be correct till $j$ and $k-j$ are less than $min(m,n)$
Comment: That is exactly what I was looking for, thank you. Do you have a simple explanation as to why that is? I don't know why my intuition was off here.
Answer: This is actually very interesting question and even better the answer.
If $m = n = 2$, then
$$f \cdot g = (a_0 + a_1 x + O(x^2)) \cdot (b_0 + b_1 x + O(x^2)) = a_0 b_0 + (a_1 b_0 + a_0 b_1) x + a_1 b_1 x^2 + [(a_0 + b_0) O(x^2) + (a_1 + b_1) x O(x^2) + O(x^2) O(x^2)]$$
The content of $[]$ reduces obviously to $O(x^2)$, so
$$f \cdot g = a_0 b_0 + (a_1 b_0 + a_0 b_1) x + a_1 b_1 x^2 + O(x^2)$$
What is curious here is that the order remains $ O(x^2)$ although an $x^2$ term is present in the expansion. Therefor the degree of the approximating polynomial is 2 but the other is still $O(x^2)$. Bilinear interpolation/approximation is another similar example: there is $xy$ term, so it is not linear, but the error is $O(x^2)$ and  $O(y^2)$ in each of the coordinates.


t-foreach="docs" only takes 80 records, I need all records

Question: When I select all records, in a tree search:
<code>t-foreach="docs" t-as="o"
</code>
It only takes 80 records, but I need to include the rest. ¿How can I do that?
Answer: you can change the number of record to show on the tree view but i don't recommend to do so:

Or use Wizard to search and print the result of search and this is the best solution.
because in more menu the ids that passed to action are those who are selected by the user
Comment: @Jonathan yes it's available in the tree view all you have to do is click on the number that shows how many record are shown per pages. Then this drop down will appear if it didn't may be you are not using an new version of you navigator
Comment: I don't have that dropdown, are you sure it's available on all modules? Do I have to install a specific Addon?
Comment: I see it now, I had to click for it to appear


Require One Post per Category in Wordpress

Question: I have created a website in wordpress... and my requirement is that I need one post per category on homepage..
Below is my Code in PHP:
<code>$args = array('type' => 'post', 'orderby'  => 'name', 'order' => 'ASC', 'number' => '10', 'taxonomy'  => 'category');
$categories = get_categories($args);

foreach($categories as $category) {
   $catquery = new WP_Query( 'cat='.$category->cat_ID.'&order=DESC' );
   while($catquery->have_posts()) : $catquery->the_post();

     echo "Some div & links";

   endwhile;
 }
</code>
The above code give me all post in all category... How to get the only 1 latest post per category..??
Wat should i change in above code..??? Please let me know...
Answer: i have resolved the issue.. please check the below code
<code>$args = array('type' => 'post', 'orderby'  => 'name', 'order' => 'ASC',  'number' => '10', 'taxonomy'  => 'category');
$categories = get_categories($args);

foreach($categories as $category) {
  $catquery = new WP_Query( 'cat='.$category->cat_ID.'&order=DESC' );
  $catquery->the_post();

   echo "Some div & links";
}
</code>
I just removed while loop...:)


Formatting options in Webform Select field

Question: I have a select field on a webform with 20+ options for the user. The default is a long list of options to select from. Is there any way to have the options broken into columns for the user to choose from so the webform doesn't end up an excessively long form?
Answer: Take a look at Chosen module can help you.
Answer: Use CSS. Flex or grid
<code>#edit-field-event-sponsors-und {
   display: flex;
   flex-wrap: wrap;
   justify-content: space-between;
</code>
With grid
<code>.view-events.view-webinars-archive .view-content {
  display: grid;
  grid-template-columns: 1fr;
  grid-column-gap: 2rem;
  grid-row-gap: 3rem;
</code>


base_url in settings.php with mobile version

Question: I've both www.example.com and m.example.com pointing to the same directory in Ubuntu and there was in the settings.php  with this line:
$base_url="www.example.com";

I want to ask what will happen in this case in Drupal where sites are accessed as www. or the m. versions?
In the hook_custom_theme I'm returing a mobile theme whenever the URL is starting with "m.".
I was getting some wierd mix up of mobile and the desktop versions.
I was not able to find any cid with "http://m." URLs in the cache_page mysql table. After I removed this $base_url now  both mobile and the desktop versions seem to be showing fine now and also cache_page table is having rows with cid with "http://m...".
I'm not fully sure this but could $base_url cause this?
Answer: How is your /sites folder structure? You can create subdomain m.example.com, and implement the mobile version in there.
There are different approaches in implementing the subdomains in drupal. it may be multisite and shared database or multisite with different databases and single code and different databases .
what you are looking for is a shared database but different themes (multiple codes), Here is good discussion about this.