Selenium WebDriver_ Acessar a pagina sem abrir navegador

Question: Alguém sabe me informar se é possível acessar a pagina sem abrir navegador? Ou seja, fazer os testes sem abrir o browser.
Tem como? Se tem me deem uma luz.
Estou usando o navegador Firefox
Answer: Sim. basta instalar PhantomJS.
Então você muda o webdrive de:
driver = webdriver.Firefox()

para:
driver = webdriver.PhantomJS()

O resto do código creio que você não precisará alterar.
Comment: Perfeito, mas isso funciona em JAVA certo? e terei que usar outro navegador?
Comment: @ThiagoCosta ele é outro navegador, só que sem interface... faz tudo em background.
Comment: Complementando: dependendo da complexidade do teste, deverá ser tomado alguns cuidados com o phantonjs, ele não aceita download de arquivos como qualquer outro navegador comum e nem executa ou até mesmo reconhece o flash. Sim, são limitações bestas, mas pra testar a disponibilidade de download de um link ou verificar se tal frame que contém um elemento em flash carregou sem erros, o phantonjs não poderá fazer esse trabalho.
Comment: @ThiagoCosta funciona em Java sim.
Answer: Tem uma maneira simples de resolver este problema…
Basta substituir a criação padrão do WebDriver
De:
WebDriver driver = new ChromeDriver();

Para:
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);

Simples assim, espero ter ajudado! Até mais!


Re-setting up a guitar

Question: My new guitar is Yamaha f310.
The original  strings were medium but I changed them to extra light .. because I found them easier to play, and have a brighter sound !
But all I hear is a buzzing sound, terrible music .
 Some people told me I have to have my guitar setup ..but I can't go to a professional guitar expert right now ,  and  every time I ask question I do not find clean short answers :(
So , here are my questions : (I'm 100% beginner )
1 - The Neck Relief : Does it mean that it must be dead straight?
2-The saddle ( adjusting the action)
Do I have to lower the saddle or make it higher ?
3- Strings Height : I don't know what the right strings height must be !?
how many mm?
Comment: You may like to edit the question and describe the buzzing a little more - does it happen when a string is played open, does it only happen when playing certain frets, etc. If it is caused by the string rattling against frets, neck relief **may** be the cause (a slight back bow on the neck), otherwise it might be some other cause.
Answer: By changing to lighter strings you reduce the tension on the neck.  The truss rod in your guitar is designed to counter the tension exerted by the strings.  The strings bend it forward (in a concave arc like a smile).  The truss rod bends the neck in the opposite direction - backwards (in a convex arc like a frown).  Too much of a forward bend (smile) will cause the strings near the center of the fret-board to be too far away from the frets and hard to play.  The truss rod is able to decrease the bow in the neck caused by the string tension.
With less string tension countering the action of the truss rod - it is able to cause the neck to bend towards a flat or convex curve (also known as a back-bow) in the neck.  A flat neck or back-bow will cause fret buzz.
Ideally you will want a slight amount of relief in the curve of the neck and the action.  You want the strings exerting more tension than the truss rod to give you a slight forward curve in the neck.  So the string height in the center of the fretboard should be slightly higher off the fretboard than at either end.
You need a certain amount of relief between the strings and frets because when you pluck a string and cause it to vibrate, it does not vibrate only back and forth parallel to the fretboard.  It vibrates all around in a circle.  I call this oscillation.  And like a jump rope, the oscillation will have a wider arc between the anchor points (on an open string the anchor points are the nut and saddle - fretted string = fret and saddle).
If you don't have enough room for the strings to oscillate (vibrate in a circle) they will contact the frets and that is what causes the buzz.
The image below came from an on line tutorial about adjusting your truss rod Guitarbitz tutorial on truss rod adjustment

Two things I recommend.  1) Adjust the truss rod to provide proper relief between strings and fret board with a slight smile curve.  Refer to my answer in your question about saddle height Eva's Question on Saddle Height for a link to a good instructional resource for doing this yourself if you insist.  Just be aware that making adjustments to your truss rod can cause damage to your guitar. Do not attempt to adjust your truss rod if you are the least bit unsure of what you're doing. My recommendation is to take the guitar to a professional luthier or guitar technician for a complete set up.
The other thing you will want to do (#2) is to stretch your new strings in so they stay in tune.  To stabilize your tuning, after all six strings have been brought to proper pitch, go back to the fattest (sixth string) and gently tug on it near the center of its length to "stretch" it. This will tighten up some of the slack where your string is wrapped around the tuning post and firmly seat the ball end in the bridge. You will notice after you do this that it is now out of tune (flat). Turn your tuning key to bring it back into tune. You can even go a tad sharp. Then repeat this process of gently tugging ("stretching" the string til it plays flat) and re-tuning until you can no longer make it play flat by tugging on it. Now the sixth string is nice and tight on the tuning post and will not be as inclined to go out of tune when you start playing.
Do the same thing for each subsequent string. Be especially careful on the skinnier strings not to tug too much or you could actually break the string. Gently tug just enough to make the string play flat.
It is important to get your guitar playing optimally as a beginner in order to maximize the reward of hearing your successful attempts to play the notes and chords you are learning.  Buzzing strings can be just as frustrating as strings that are too difficult to press down.  The good news is - your guitar is adjustable for a reason - and you (or your local guitar tech or friend who does their own set ups) will be able to get it playing the way it is designed to play.
Good luck!
Comment: Thanks for these great information ! but my last question is how much the truss rod adjustment should be ? (degrees )
Comment: @Eva Please read both of the tutorials I linked carefully.  Make very small adjustments (1/4 turn max) at a time and allow the neck to adjust.  Check the relief after 15 minutes and then make another small adjustment if needed.  Continue this process of very very small adjustments and 15 minute pause until you have the desired amount of relief.  There is no way to specify how much your truss rod will need to be adjusted.  You will be loosening the truss rod (decreasing the tension) by turning it counter clockwise ("lefty loosey") if looking at it as if it were a clock right side up.
Answer:
Moving to lighter strings will have reduced the string tension, so this has two direct effects that could cause your buzz:

if you have a tremolo (this guitar dues not, so ignore this section) it will have moved backwards, so on most floating tremolos this means your strings will be closer to the body of the guitar, which will result in buzzing. This is fixed by reducing tremolo tension (usually by removing one of the trem tension springs - usually found under the cover on the back of the guitar)
the lower tension also allows the neck to bend backwards more, which means the middle of the fretboard is effectively closer to the strings, leading to buzzing again. This is usually counteracted by adjusting the truss rod to let the neck curve forward again.

The amount of curve (neck relief) is very small, though, so if you haven't adjusted this before, you should be very careful as you can really upset the balance of the guitar. We have a few questions on here already about adjusting neck relief, so have a browse around. My guidance for you though is really to get it set up professionally - it is not expensive.
As for your other questions:

If all you have done is use different strings, you shouldn't have to change the saddle height.
There is no correct string height. You can set these any way you like. Closer to the fretboard requires less pressure and can be faster and easier to play, but you run a risk of more buzzing than if you have a high action.

Finally - if this all sounds too scary or expensive, just revert to your original strings. Yes, heavier strings require more effort at first, but your fingers will rapidly strengthen.

Re-setting up a guitar


This Python code to check if there is 007 order in a list does not work

Question: a=[1,2,0,0,7,11]
flag=0
flag1=0
for i in range(0,len(a)):
    if a[i]==0:
        flag=1
    elif flag==1 and a[i]==0:
        flag1=1
    elif flag==1 and flag1==1 and a[i]==7:
        print(True)
    else:
        pass

This is one of the problem in udemy. Returns True if there is an order of 007.
MY OUTPUT:
BLANK OUTPUT
Answer: This is because for second 0, the elif flag==1 and a[i]==0: will not be executed but the if a[i]==0: will be executed. So, for first 0, flag will be set to 1 and for the second 0, the if a[i]==0 will again be true. As a result, the flag will be again set to 1 without executing the desired elif block. You may want to change the if block like below -
if flag==0 and a[i]==0:

That way when flag is set to 1 once, the if block will not be executed but the elif will be executed. So, the whole code will be -
for i in range(0,len(a)):
    if flag==0 and a[i]==0:
        flag=1
    elif flag==1 and a[i]==0:
        flag1=1
    elif flag==1 and flag1==1 and a[i]==7:
        print(True)
    else:
        pass

Btw, if your code needs to check if 007 comes in order without any number in between them, then this code will also not work.


Which reading class should I use when I don't know the type of the file?

Question: I'm a newbie so the only ways to read a file in Java I know are:
DataInputStream dis = new DataInputStream(new FileInputStream(<FILE>));

and:
BufferedReader br = new BufferedReader(new FileReader(<FILE>));

And I know that while the first one serves the purpose of handling binary files, the latter is used for character/text files (for my current understanding: such that I can open them with, say, notepad and see something a human can actually read). The problem is: what if the problem does not state whether I'm to deal with a binary or text file? I mean: when I'm to read an object from a file, for example, I know it's the first, but what when I'm only given info like "Your method is to read from the file XYZ which contains names of the students which you are to process (and so on and so on)"?
I've come across some such tasks and was never sure which one to use. Can I use whatever I want if the description doesn't explicitly state the type of the file or is there some convention that if nothing is said, it's safer to assume we're dealing with X?
Answer: You do need to know which type you want to read.
If the spec is unclear, define (and document) it for yourself. If you already have an existing file, you can have a look at it to decide which approach to take - if it is line oriented, with no "unreadable" characters in it, e.g. one name at a line, you would take the text file approach. If it looks strange when opened in a text editor, you can assume a binary file, but in this case you need additional information anyways to be able to correctly read it.
On a file system level, there is no such thing like "binary" or "text" file - it depends on how you interpret it. You can read each file as a binary file (considering the individual bytes - this is what hex editors do), and you can read (almost) each file as text (and most likely end up with something which looks like garbage when you try to print it). (I said "almost" since there are some constraints with multibyte characters, where one character is built from more than one byte. But even these files could still be treated as "extended ASCII" files where each byte maps to exactly one character).
In any case, you should document the file format you expect (even "text" files can have different structures, like fixed line length, variable line length and so on).
Comment: Thank you. I'm asking for my college purposes as the exam is coming and browsing the tasks from past years, I see that this problem is present. I won't be able able to ask any questions during the exam so I'm just thinking about some plan to not be confused when the time comes :)
Answer: "Your method is to read from the file XYZ which contains names of the students which you are to process (and so on and so on)"?
Based on that statement that I've highlighted, I'd be under the impression that the file contains textual based data.
At that point you should read it using a derivative of "Reader".
If the file has a fixed structure, you might consider using InputStream or a derivative of that.
In your case though, it appears to be a simple task of reading character data of student names.


How to ensure throughput from 10GbE network device on ubuntu 20.04 under heavy load

Question: I'm having trouble ensuring a required network throughput on a server connected to a Signal Hound spectrum analyzer via a 10GbE network interface. Basically, I can get good throughput when only the radio capture process is running, but when I run other processes, the throughput starts to drop. I'm using an Aquantia PCIe ethernet adapter with a QNAP SFP+ 10GbE Thunderbolt 3 adapter.
When I'm running a simple python program to poll from the spectrum analyzer API in streaming mode, it all works great at the maximum bandwidth (~800MB/s). When I do
$ stress --cpu 8 --io 8 --vm 8 --hdd 8

side-by-side, it lowers to about 600MB/s and I start dropping a lot of data.
Things I've tried:

Updating drivers
Messing with the coalescing parameters and many ethtool options (MTU, etc)
Turning off hyperthreading and isolating the process to a single core (8 of 8) via cpu affinity pinning

This also involved isolating the networking interrupts to their own core (7 of 8)
I also change the core governor to be "performance" so it's always at maximum freq
I also tried turning off most of the other interrupts for cores 7 and 8 to prevent them from slowing down, verified by a netdata dashboard
I basically tried everything in here

Essentially, I know that it can run in real-time because it works fine when it's by itself confined to 2 cores. But for some reason, even though the other cores don't interfere with the CPU cycles or network IRQs, when cores 1-6 are at heavy load, they slow the main process down greatly.
If it helps, I find that the --vm 4 option for stress causes the most slowdown, so I suspect that it has something to do with memory allocation and perhaps the DRAM interface to the network card.
I'm basically pulling my hair out trying to get every packet from the radio on a (what should be very powerful) Ubuntu 20.04 machine. Does anyone have any experience with applications like this?
EDIT: I copied some of the performance curves here:
Here is the effect I'm seeing
So here's the utilization. Core 6 is at 100% with softirqs both during the high stress period and the "just capturing" period. I've tried splitting the network data onto two cores (5 and 6), but one of them always stays loaded while the other one seems clear, even if they have similar amounts of interrupts.

The actual number of softirqs unfortunately drops on CPU 6 during the period when the stress test is running.

Here is the effect I'm seeing on CPU6 softnet.

Also, the interrupts seem to stay relatively the same, though they get a little less consistent during the high stress period.

Here's the straight network speed, and it looks a little inconsistent as well in both periods.

I was looking pretty closely for anomalies (though there are a lot of plots in netstat), and it looks like there is no interprocess memory during the high stress period. Could this lead to issues?

If anyone needs more plots, let me know. I can't deduce the issue from these, but I hope it's enough information to come up with potential solutions.
Thanks again!
Comment: Brendan Gregg is waiting for you.  Start with his web page https://www.brendangregg.com/, start collecting system performance metrics, look for bottlenecks.
Comment: Thanks Alex for the suggestions! I've edited the original post with more performance curves so that hopefully someone smarter than me can help me figure out what's going on.
Answer: Ok all, I think I've figured out an answer to my problem.
I think the key graph here was the "softirq" graph. Under normal operation, I don't think it should be that high.
I had a little d'oh moment while profiling: basically, since I'm running CUDA and a bunch of other fiddly-install libraries, I was running all of this in a docker container (I know what you're all saying!). Since I didn't mess with the network stuff for the radio in docker, I kind of didn't think about it. And yep, you guessed it, the docker networking added enough processing to push me over the edge into dropping packets. I ended up setting the network_mode to host to use the host networking, and it solved my problem. Hopefully this can be helpful to someone else!
But that's not all--to figure this out, I spent a good bit of time profiling to figure out exactly why I was seeing the effect I was seeing (Thanks to @AlexD for the resources). Here's a flame graph of the pinned CPU 7 that was running the API drivers:

As you can see, it spends a lot of time in page fault memory allocation (which should have been another clue, though I didn't post it here. Minor memory faults were through the roof during capture). That explains why running stress with --vm 4 gave the worst results--It was causing a contention for the memory which slowed down the driver significantly. Also, after testing it a little, I think it needs more than one core anyway (it was dropping packets pinned to core 7 exclusively, but worked pinned to 6 and 7). I was getting better results after overclocking (but still not perfect) and that explains why.
So there you have it: an explanation for why it was all happening the way it was, with graphs to back it up. I have about 60% utilization on two cores for the radio API, and it's pretty stable in getting all the packets (another core handles the softirqs at about 10%, down from 95% that you see in the graph above).
I feel a little dumb for not thinking of docker slowing me down, but much better having figured this all out. Hopefully this post helps someone else!


How to properly record electric guitar?

Question: I want to record my electric guitar for the sake of making covers as well as my own music, however I'm having trouble getting a good tone. I have 3 possible approaches (one of which has worked fairly well)

Plug my guitar into my Scarlett 2i2 and use the amps in Garageband. This has worked decently well for me.
Try to record my amps directly with my microphone. This is what it sounds like. It sounds very... lackluster. I can hear the pick hitting the strings, everything sounds muddy and cheap. For reference, I'm using a Boss GT-6 for effects and a Fender Frontman 25R for the amp.
Plug my Boss GT-6 directly into the interface and record its output directly since it has preamp and speaker simulation built in. Disclaimer: I haven't tried this approach yet.

Option 1 is super easy to set up, I just need my guitar and a cable, and as a bonus I can tweak the sound as much as I want even after having recorded (which is pretty convenient). It's what I currently use and it's not broken by any means, so if that's standard practice then I can keep doing it.
However, I really wanted Option 2 to work though because when practicing you get everything to sound just right to your ears, and it'd be nice to be able to convert that directly to a recording. For instance, I sometimes practice on a mini-amp and I love the lo-fi/garage rock sound, especially when practicing Strokes songs. It sounds perfect to my ears, but I know that if I put the mic to it, it'll sound bad.
Is there a trick I'm missing to recording? Do I need a better quality microphone? How do I get rid of the picking sounds?
Note: I can't really turn the amp up any louder since I have roommates :( so if that's the only solution then I'll just have to stick with the digital methods
Comment: @DataProcessing I looked up the response of the microphone and it's a cardioid, which means even though the microphone _looks_ symmetric, there is indeed a front and a back... oops. I didn't take that into account and just made sure one of the faces was up against the amp. It's entirely possible (and kinda likely) that the mic was facing the wrong way...
Comment: The trick to recording is that it's a skill just as complicated as playing guitar and it takes just as many years of daily practice to learn to do it well. The other trick is that the cheapest gear usually sounds like it's the cheapest.
Comment: You really do need someone in an isolate booth who can hear what's going on as you change mic positions and so on.  Or make notes of several scenarios, record on each, and carefully listen to them all.  There's no advice that will replace a great ear and a WHOLE LOT of experimentation.  Even experts take HOURS and HOURS setting up mics for a recording session.
Comment: In your Option 2, it sounds like the mic is out in the room, not right on the speaker grille, where it should be.  Sounds really boomy and roomy, not tight and focused.  And I'm not hearing any picking sounds, but at 0:11 I do hear what sounds like someone stomping on the footswitch of a pedal.  That shouldn't be audible if your mic placement is right.
Comment: Are you certain you had the front of the mic capsule pointed toward the amp and not backwards?  If you had things set up correctly, there's no way it should sound like your sample.
Comment: Much better; that was definitely the problem in your first recording.  Just wear some decent headphones and gradually move the mic around the front of the speaker until you find where the sweet spots are.  Usually about 1" off the speaker grille and close to the center of the speaker cap is where you'll find some good tones.
Comment: @DataProcessing I actually had the mic right up to the amp, and I put a small fleece blanket around the two (probably not the most insulating, but more than nothing I reckon). As for the sound at 0:11, that was actually me flipping the pickup switch on my guitar. You're right that it overall is boomy+roomy but I'm not sure how to stop that (short of hanging anechoic foam on my walls)
Comment: What exactly is the problem? Can you get a good tone with inside-the-box GarageBand amps? Or you'd like to record the same sound as you're hearing? Then why not start practicing with GarageBand too, so practicing sound is the same as recording sound? What's the thing with the GT-6, is the tone not good enough? Get a better external amp sim?
Comment: @piiperiReinstateMonica I can get good tones out of GarageBand, but it's easier to practice with my real effects board. Practicing with GarageBand seems a bit tedious since I have to create a project and track just to hear the guitar (though this is null if I'm recording a song since I have all this ready anyways). I haven't tried the GT-6 so I'm not sure how it would sound, but the main issue is I want to record what I hear, and switching the GT-6 output from my amp to my laptop seems like it would effect the sound.
Comment: @rcplusplus Did you do another test with the mic oriented the correct way?
Comment: @DataProcessing I found out where the front of the microphone is and then recorded my guitar, [here is the result](https://drive.google.com/file/d/1iwe_fmsSBzTjtOscTh-zUyjgQJwUCB_V/view?usp=sharing). It sounds a lot better I think! I did some EQ-ing in garageband to clean it up a bit, but I think to get it better than this it'll be as ToddWilcox and Bennyboy1973 said: I'm just gonna have to take time and fiddle with everything until the sound is just right!
Answer: Option 2 is the traditional way and would still be considered the "proper" one by many engineers. Obviously though, the Frontman isn't exactly a boutique amp, so you shouldn't be surprised if this doesn't give results that are as good as what you hear on professional records. To go the amp route you should

Have an amp whose sound you really like. Typically that would mean all-tube with a nice cabinet, what exactly depends of course on the genre.
Run it without digital pre-simulation. If you use a digital multi-FX, make sure that it simulates only stuff that could also be done with analogue stompboxes, but in particular no cabinet emulation.
Use a room with good acoustics. Actually this isn't so critical for guitar amp as it is for other situations, but it's important that the room doesn't have weird resonant reflections. What tends to work well is acoustically "dead" rooms, for example a crammed guest bedroom in the attic. Reverb can be added later on.
Turn it up loud. Practice volume is no use here, you want a master volume near the amp's limit to both get the right sound and reduce parasitic noise.Note that it isn't so much the absolute volume that matters but the local volume at the mic'd speaker, and the fact that all parts of the amp are actually driven to near-saturation, to unfold its full sound complexity. That's why very small all-tube amps make a lot of sense for recording.
Mic it well. There's no single right way to do this, but certainly pointing a cardoid mic in the wrong direction is rather questionable...

If you can't achieve all of this, then you're nowadays likely to get better results by digital emulation. That doesn't mean the amp is worthless, but it should be understood as just a monitor to get the playing right with no latency issues. But what you actually record should be the direct guitar signal before amp. You could record through the Boss with cabinet emulation, but I wouldn't recommend it – modern amp-sim DAW plugins are generally better and you have more flexibility tweaking the sound during mixing instead of tracking. So better just split off the signal before the amp with a DI box (make sure it's a high-impedance active one) and record that. Then use amp simulation in the computer to get the final sound.
Answer: All 3 at once.

Mic'd amp because you know how it sounds and what you record is what you get
DI'd signal so you have something to re-amp if you don't like #1
GT-6 because why not?

Then at mix time you can work with a blend of the 3 to achieve whatever you want.
Comment: out of curiosity, is this a common tactic with home recording and/or studio recording? Also, how do I get the signal to go across multiple routes like that? Do I just looks for a signal splitter device?
Comment: I have an interface (stealth pedal) that has two mono instrument inputs. The chain could be: guitar > Y-splitter > one branch off Y to one input on interface; 2nd Y branch to amp with mic > (preamp) > 2nd interface input. Two separate tracks: arm DI on one; arm mic on the other. Hit record.
Answer: There is no such thing as the 'true' sound of an electric guitar.   You've described three valid methods of recording yours.
Direct connection plus Garageband effects gives a pleasing result?  Good.
A cheap microphone that looks designed to flatter close-miced vocals was less successful.  OK.  Maybe it overloaded.  Maybe you should point it at a different part of  of the speaker cone, from a different distance. Maybe you had it pointing the wrong way!   Maybe it's just the wrong mic.  A SM57 is traditional for this job.   Carry on experimenting.
There's a third option that you haven't tried yet.  Exciting!
Obviously if you CAN get a  useful result without deafening the neighbours, that's a plus!   I don't know if there's much point in miking a guitar amp unless it's working pretty hard.

How to properly record electric guitar?


How to add a form as field attribute in a django ModelForm

Question: I have a ModelForm for a Product object set up like this:
class ProductForm(forms.ModelForm):
    compositon_choices = ((2L, u'Calcium (100mg)'), (3L, u'Iron (500mg)'))
        composition_selection = forms.\
              MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                        choices=compositon_choices )

    class Meta:
        model = Product
        fields = [
            'title', 'title_de', 'title_es', 'upc', 'description',
            'description_en_gb', 'description_de',
            'description_es', 'is_discountable', 'structure',
            'unit_type', 'product_concentration',]

        widgets = {
            'structure': forms.HiddenInput()
        }

In the example above I extended the ModelForm with a MultipleChoiceField by adding the composition_selection field (this works):
I would like the composoition_selection to be a form itself and not just a MultipleChoiceField:
class ProductComponentForm(forms.Form):
    component_amount = forms.IntegerField()
    component_name = forms.CharField()

and then extend the ModelForm with this new form like this:
class ProductForm(forms.ModelForm):
        composition_selection = ProductComponentForm()

        class Meta:
            model = Product
            fields = [
                'title', 'title_de', 'title_es', 'upc', 'description',
                'description_en_gb', 'description_de',
                'description_es', 'is_discountable', 'structure',
                'unit_type', 'product_concentration',]

            widgets = {
                'structure': forms.HiddenInput()
            }

But I cannot get this to work. This ProductForm that I want to create never gets rendered,and nothing appears. Am I doing something wrong or missing something? What would be the best way to extend a ModelForm with a SubForm?
Comment: What is the purpose of it? To have `component_amount` and `component_name` in `ProductForm` as two more fields?
Comment: A Product can have various ProductComponents. Every ProductComponent has a name and an amount. My goal would be to render a form where one can select various ProductComponents by checkbox and add the amount in an integer field next to the select box.
Answer: Finally I understand what I did wrong. To make subforms in Django one needs formsets.
In my case i needed two different types of formsets because I had two different relationships that I wanted to change from one form.

one to many relationship
many to many relationship

depending which side of the relationship and which relationship type one wants to edit from within a single form there are different approaches:
There is the inlineformset_factory:
https://docs.djangoproject.com/el/1.10/topics/forms/modelforms/#inline-formsets . This type of formset is used when one wants to edit the many side of a one to many relationship
If one wants to edit the one side of a one to many relationship the
modelformset_factory gets used:
https://docs.djangoproject.com/el/1.10/topics/forms/modelforms/#model-formsets
one can create a model_formset, and then add this formset to the main formset of the main form.
when one wants to edit a many to many relationship within a single form, an inline_formset_factory can be created with the intermediary table of the many to many relationship.
this formset than can be added to main form.
For my use case that I described above I ended up using a model_formset_factory and added that to the main form.


I'd like to use a wildcard with the SET command in Windows Batch so I don't have to know exactly what is in the string in order to match it

Question: I'd like to use a wildcard with the SET command in Windows Batch so I don't have to know exactly what is in the string in order to match it.
Is this possible?
If this has already been asked and answered I apologize, I searched for a good while, but could not find it.
Comment: A sample would be nice, do you want find a regualar expression or what kind of wildcards do you want to use
Comment: +1 Answering your own question definitely shows research effort ;)
Answer: A: Yes. But it is not as powerful as it should be.
But first, let's answer a question that you didn't ask (yet) because it is a natural follow-up question.
Q: Will the question mark match any single character in the batch string search and replace with SET?
   A: No. It is a regular character, and will only match it'self.
The asterisk IS a wildcard and WILL match multiple characters, but will ONLY match everything from the very beginning of the string. Not in the middle, and not from the end.
Useful Searches:
*x
*how are you?

The above two searches CAN be matched. The first will match everything up to and including the first "x" it runs across. The second one will match everything up to and including the first "how are you?" it finds.
Legal, but Unuseful, searches:
x*
Hello*
One*Three

The above three searches can NEVER be matched. Oddly they are also legal, and will cause no errors.
One exception: Hello* and x* WILL match themselves, but only if they are the very beginning of the string. (Thanks Jeb!)
Two examples you can type or paste in at a command prompt:

REM A successful search and replace.
  SET X=Hello my friend. How are you?
  SET X=%X:*.=%
  ECHO Output: "%X%"
  Output: " How are you?"
REM Unexpected action causing an unsuccessful search and replace.
  SET X=Hello my friend. How are you?
  SET X=%X:.*=%
  ECHO Output: "%X%"
  Output: "Hello my friend. How are you?"

Logiclly, .* should match everthing from the period on, resulting in the string
being truncated to "Hello my friend". But since the * only matches from the start
of the string, the .* matches nothing, and so the string was left unchanged.
Comment: `Hello*` can match a string, the asterix is a normal character if it's not the first. `set var=Hello*world` `set var=%var:Hello*=%` will result to `world`
Comment: Oops! Didn't think about that!
Answer: Extremely old, but useful
As an executable set-ast
set string=abc*def*ghi
set-ast string "-dash-"
  :: -> "abc-dash-def-dash-ghi"

Where the arguments are given as set-ast <variable-name> <replacement-string>

replace * with -dash- (one time only)
Note: delayed expansion must be enabled
set string=abc*def
  :: -> "abc*def"
set right=%string:**=%
  :: -> "def"
set left=!string:%right%=!
  :: -> "abc*"
set left=%left:~0,-1%
  :: -> "abc"

set new-string=%left%-dash-%right%
  :: -> "abc-dash-def"


How to obtain raw View result for Drupal 5?

Question: How do I get a raw result from a view similar to this $view->result for Drupal 5 ? I would like to get results from the database and run calculations before displaying to the user. I really need to gain access to the the raw data before it's themed by the Drupal engine.
Comment: By get access you mean outputting them, or altering them in the normal course of rendering? Please clarify a bit if you expect focused answer.
Answer: I think the answer is in here somewhere but I have no way to test it out.
Check out Intro to Views 1 and especially Inserting Views where the views_build_view() function is discussed.  From the discussion there, you should be able to do something like this:
<code>$view = views_get_view('your_view');
$results = views_build_view('items', $view);
</code>
with <code>$results</code> now being "An array of objects containing the results of the query."
Now how you theme this is up to you to decipher :)


How can I estimate the phase difference between two periodic time-series?

Question: I have 2 daily time-series, each 6 years long. While noisy, they are both clearly periodic (with a frequency of ~1 year), but appear to be out of phase. I would like to estimate the phase difference between these time-series.
I've considered fitting curves of the form $a\sin(\frac{2\pi}{365}t - b)$ to each time-series and just comparing the two different values for b, but I suspect there are more elegant (and rigourous!) methods for doing this (perhaps using Fourier transforms?). I would also prefer to have some kind of idea of the uncertainty in my phase difference estimate, if possible.
Update:

The shaded regions are 95% CIs.
Sample crosscorrelation between the two time-series:
Comment: As a very first quick-and-dirty check, have you tried plotting the sample crosscorrelation between the two series and finding the peak? There are some curious discontinuities, e.g., in the first series sometime around Feb 2005 or so.
Comment: A plot would be interesting and, potentially, helpful. How close to sinusoidal are the two series?
Comment: Hi Cardinal. I have a plot, but need 10 reputation points to upload it, unfortunately! I'll do so as soon as that happens. The time-series are related to temperature and vegetation growth, so follow pretty consistent seasonal behaviour, although it is noisy. Without having seen the plots, do you have any thoughts on how to approach this problem?
Comment: Yes. I have a couple ideas, but I'd like to see a plot first to have a better idea of what you're dealing with. if you upload your plot to imgur and edit the post to provide the link, then I can edit it yet again to put the image inline. The rep will come soon enough. Welcome to the site.
Comment: For some reason, maybe my currently-crippled machine, I can't click on a link or see a plot.
Comment: Similar (but not exactly the same) issues are discussed at http://stats.stackexchange.com/questions/7727/how-to-correlate-two-time-series-with-gaps-and-different-time-bases (same problem, but with irregular spacing) and http://stats.stackexchange.com/questions/19459/measuring-synchrony-with-time-series-correlations (different kind of data).
Comment: @jbowman: I'm sure it was my fault. Manually editing from an iPad can be a little cumbersome; I got the link wrong the first two times I tried. Hopefully you can see it now.
Comment: @cardinal, I've plotted the sample crosscorrelation and will post it in the main section above. There appears to be a distinct peak with a ~2 month lag. This agrees with my initial visual estimate and intuition about the data. You mention that it is a quick-and-dirty check -- what are the limitations with this method, and would you recommend anything else?
Comment: Maybe spectral coherency: https://en.wikipedia.org/wiki/Coherence_(signal_processing)
Answer: This is the very problem cross-spectral analysis is good for. Next you have an example of code using consumer prices (in differences) and price of oil, and estimating the coherency (roughly, a squared correlation coefficient broken by frequency band) and phase (lag in radians, again by frequency band).
<code>Crudo <- dget(file="Crudo.dge")
IPC <- dget(file="ipc2001.dge")[,1]
dIPC <- diff(IPC)
datos <- ts.union(dIPC,
           Crudo)
datos <- window(datos,
           start=c(1979,1),
           end=c(2002,1))
sp <- spectrum(datos,
           main="Petróleo e IPC",
           spans=rep(3,5))
par(mfrow=c(2,1))
plot(sp,plot.type="coh")
plot(sp,plot.type="phase")
</code>
These are the graphs produced by the last instructions. You can probably adapt this to your setup.


How to call a function residing in a parent screen within an if statement in a tabNavigator (React Native)

Question: So my problem is this:  Parent Component is a screen in a tab navigator which has another tab navigator nested in it. I am able to pass props down to the child tabs via screenProps. However I am unable to call a function in the parent screen from any of the screens in the child tab navigator. What am i doing wrong?
ParentScreen.js //One of the screens of a parent tab navigator

import React, { Component } from 'react';
import { ChildTabs } from '../navigatation/router.js';

export default class ParentScreen extends Component {
    state = { name: '' }

    componentWillMount() {
        this.parentFxn();
    }

    parentFxn() {
        this.setState({ name: 'Staker' });
    }

    render() {
        screenProps = { parentFxn: this.parentFxn.bind(this) };
        return(
            <ChildTabs  // this is a tab Navigator
                screenProps={screenProps}
            />
        );
    }
}

Now one of the child screens:
ChildScreen.js
//childScreen is one of the screens in the tab navigator

import React, { Component } from 'react';
import {Button} from 'react-native-elements';
import { ChildTabs } from '../navigatation/router.js';

export default class ChildScreen extends Component {

    childFxn() {
        axios.get(someRemoteUrl)
        .then((response) => {
            if (response.status == 200) {
                return this.props.screenProps.parentFxn; //this never gets called
            }
        });
    }

    render() {
        return(
            <Button
                onPress={this.childFxn.bind(this)}
            />
        );
    }
}

Comment: Very nicely asked question. Was searching for this for 2 hours and finally found this. Many thanks!
Answer: Function is not getting called because you are not calling it. It should be called like this
  if (response.status == 200) {
     return this.props.screenProps.parentFxn(); //this always gets called
  }

Comment: Wow. thanks. I totally forgot to add that. Thanks alot.


Split many dataframes by a column, and save as different dataframes

Question: I have many dataframes. I would like to split them based on the values in a column (a factor). Then I would like to store the result of the split in separate data frame that have a specific name.
For the sake of a mrp, consider some generated data,
for (i in 1:10) {
assign(paste("df_",i,sep = ""), data.frame(x = rep(1,12), y  = c(rep("a",4),rep("b",4),rep("c",4))))
}

here we have 10 dfs, df_1, df_2... to df_10. (real data is similar to generated data, but in real data column z is different for each df).
Now, I want to split the dfs by 'y' (column 2).
For 1 df, I can do the following;
splitdf <- split(df_1,df_1$y)
namessplit <- c("a","b","c")
for (i in 1:length(splitdf)) {
  assign(paste("df_1_",namessplit[[i]],sep = ""),splitdf[[i]])
}

While this works for 1 df, how can I do it for all the dfs?
Big thanks in advance!
Comment: [Don't ever create ,`d1` `d2` `d3`, ..., `dn` in the first place. Create a list `d` with `n` elements.](https://stackoverflow.com/a/24376207/1422451).
Answer: It is not recommended to create multiple objects in the global env, but if we want to know how to create the objects from a nested list - Loop over the outer list sequence and then in the inner list sequence, paste the corresponding names to assign the extracted inner list element
lst1 <- lapply(mget(ls(pattern = "^df_\\d+$")), \(x) split(x, x$y))
for(i in seq_along(lst1)) {
   for(j in seq_along(lst1[[i]]))  {
   assign(paste0(names(lst1)[i], "_", names(lst1[[i]][j])), lst1[[i]][[j]])
  }
}

-checking for objects created in the global env
> ls(pattern = "^df_\\d+_[a-z]+$")
 [1] "df_1_a"  "df_1_b"  "df_1_c"  "df_10_a" "df_10_b" "df_10_c" "df_2_a"  "df_2_b"  "df_2_c"  "df_3_a"  "df_3_b"  "df_3_c"  "df_4_a"
[14] "df_4_b"  "df_4_c"  "df_5_a"  "df_5_b"  "df_5_c"  "df_6_a"  "df_6_b"  "df_6_c"  "df_7_a"  "df_7_b"  "df_7_c"  "df_8_a"  "df_8_b"
[27] "df_8_c"  "df_9_a"  "df_9_b"  "df_9_c"

Comment: @NiGS Here, I am assuming that you want to split by column name `y` so I used `x$y` in the first line.  Similarly, as you have created objects in your first assign with `df_1, `df_2`, etc, u used `pattern = '^df_\\d+$'` to load all objects created as `df_` followed by one or more digits.  There is no info in your post about how your real data looks like or the column names
Comment: @NiGS IN that use `lst1 <- lapply(list(bike1 =bike1, dvan1 = dvan1, evan1 = evan1, avsdv1 = avsdv1, avmdv1 = avmdv1), \(x) split(x, x$dbdx))` and the rest of the code is same
Comment: Works, thanks a bunch!
Comment: Thanks, it works great on the mrp! However, could you please the working of the code so I could apply it to my real data?
Comment: You're right Arun, indeed I didn't provide info on my real data. I have 5 dfs - bike1, dvan1, evan1, avsdv1, avmdv1. each have 5 columns and 9 rows. I am afraid the pattern lookup is does not work. the column 'y' in this mrp is 'dbdx' in the real data. Big thanks for your help :)


Importing data from an XML file into R

Question: I want to import an XML file from polarpersonaltrainer.com that stores heartrate data into a R data.frame.
Is there a package that makes importing XML easy or do I have to write my own parser?
Answer: Yes. Use the XML package. There's a function called xmlToDataFrame which will make your life easy.
Answer: You might find RSXML useful. It's also in CRAN.
Comment: No, RSXML is precursors to XML, and only on Omegahat. You really want XML as Shane said.
Comment: Why does the XML entry on CRAN link to the RSXML website? http://cran.r-project.org/web/packages/XML/

Importing data from an XML file into R


lm.removeUpdate(ll); not releasing updates

Question: I have been working for 2 days looking for this bug.  I have searched stackoverflow and Android documentation with no luck.
My onLocationChanged code has a counter in it that counts how many times it has been called and if I back arrow out of the activity screen on the phone and return, the counter will go up by 2 for each update. If I  back arrowing out and update the GPS, the counter records that onLocationChanged is still getting called even though the screen is in the background and onPause has been called. If I go in and out of the activity with the backarrow, I can get more than two updates per GPS input send depending on how many times the activity screen is entered.
All the GPS code works but these multiple instances can't be good and they mess up other things I am trying to do, like distance traveled between two updates.
Here is what I think is the relevant parts of my code.  Obviously I left out the main part but the point is that after returning to this screen after back-arrowing out then a single send of a GPS data point increments the n variable by more than one depending on how many times I have returned to the screen.
I must be doing something obvious but I can't find it.
public class Data extends Activity {

protected LocationListener ll;
protected LocationManager lm;
static int n = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data);
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

    class mylocationlistener implements LocationListener{
        @Override
        public void onLocationChanged(Location location) {
            if (location != null){
                n = n + 1;
                                    textData.setText("\n" + n);
                            }
     }

and
        @Override
    protected void onPause() {
        if(lm != null) {
            lm.removeUpdates(ll);
        }
        ll = null;
        lm = null;
        super.onPause();
    }

The only clue I have is that if I take the lm.removeUpdates(ll) out of the if(lm != null) then the code crashes which makes me think that lm must be null and that lm.removeUpdates(ll) must not be correct but it matches the all the examples I could find as well as the Android documentation as far as I can tell.
Please help.
Answer:   LocationListener ll = new mylocationlistener();

This LocationListener is local to your method onCreate().So is your LocationManager lm.So when you are removing updates its not working with the manager and listener that you declared as the class variable.
Just write as
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener(); in your onCreate().

Comment: Thank you.  That is so obvious once you pointed it out.  You have fixed my problem!


How to alter user's input?

Question: I have a form to get some user input in Drupal. I want to add some prefix to the user input.
For example, the user enters "Laptop"; I want to save it in the database as resource_Laptop. I want to add the prefix before the validation is done, to avoid it fails.
How do I do this? Will hook_form_alter() help me here?
I have used this method, but not satisfied with this hack.
function mymodule_form_alter(){
  drupal_add_js("
    (function ($) {
      $(document).ready(function() {
        $('.field-suffix').hide();
        $('#edit-submit').click(function(){
        var s = $('#edit-machine-name').val();

        if (s.indexOf('_resources') == −1) {
          $('#edit-machine-name').val($('#edit-machine-name').val() + '_resources');
        }
      });
    })(jQuery);", 'inline');
}

Comment: The validate handlers are the first to be called by FAPI after a submit. So it will be difficult to have the prefix added beforhand. May be you want explain why you want to validate something you are adding as a post process and is not entered by the user anyway. If you want to make sure your prefixing code works corrent it would be better to think about writing a simple test.
Comment: Since your db table already has a column for resources, why do you need to prepend 'resource_' to the content?
Comment: @paul-m... actually I am adding some data in taxonomy table and want to make my data unique by adding resources_ prefix to taxonomy vocabulary. It gives me error for machine-name already exist and which is actually added vocabulary by taxonomy so in my module as I am using the same taxonomy tables to save my data.
Comment: What form are you altering? Why are you altering an existing form, rather than using your own form?
Comment: This whole thing seems like a really bad idea and bad way of implementing. If your only worry is passing validation, then why does it matter whether a string has `resource_` prepended or not? It should still be possible to write a validation for that. Best place to add this, and alter input is in a submit handler. Also don't use `#edit-machine-name` as this can become `#edit-machine-name--2` or `#edit-machine-name--3`. Use a class selector, or add a class through that hook_form_alter
Comment: Just don't do this with javascript. You'd be asking for trouble in my opinion. Investigate form validation callbacks. Make yours run first. Make it change the value.
Comment: As others noted, this approach just leads to bad times. It sounds like you should be asking for an entity reference select list or something concrete in your system.
Answer: Use the hook_form_FORM_ID_alter and add a custom submit handler.
function example_form_form_id_alter(&$form, &$form_state,$form_id){
  $form['#submit'][] = 'example_form_id_submit',
}

function example_form_id_submit(&$form,&$form_state){
  $form_state['values']['resource_name'] = 'resource_' . $form_state['values']['resource_name'];
}

Comment: This will come to late, since op want's to have the prefix added before validation. Validation handlers are called prior to the submit handlers.
Comment: @karthik... this will still fail my validation. I want to add prefix before validation call. does form_set_value help me here?
Comment: @Umar: how about doing the above in the validation instead of during submit, i.e. ```$form['#validate'][] = 'example_form_id_validate'```, you just have to make sure this validation runs before the rest ..
Comment: @Karthik... Nikhil suggested me same and I tried check my response on his comment.
Comment: can you confirm, the validate function does a call by reference and not by value? If you did a call by reference and doesn't work, you might have to stick to your js hack.
Answer: Add one more validation callback handler by giving it the priority(executed first) in $form['#validate'] and change the values in $form_state.

How to alter user's input?


If I have an $n$-gon, for odd $n\geq5$ with all angles equal to the angles of the regular $n$-gon, is my $n$-gon necessarily regular?

Question: To paraphrase the title, is there such thing as an odd-sided (with at least 5 equal sides) non-regular polygon with all equal interior angles?
So for example, if I have a pentagon with all angles being $108^\circ$, then is it necessarily a regular pentagon?
I have constructed an example that I think works, but I just want to be sure.
The example I constructed is below, where you cut the red strip away from the regular pentagon and glue the halves together. The mid-line of the strip is concurrent to the line connecting the vertex to the mid-point of the opposite side.
Comment: Your construction is fine, but one can do more: translating any side of the $n$-gon parallel to itself does not change the angles.
Comment: Sorry, I have just added conditions on $n$ to avoid that, as I forgot to do so initially.
Comment: What example did you construct?
Comment: hexagons can have external angles all $60$ degrees but different side lengths.
Comment: I observed that the result was trivial for even $n$, which was why I had $n$ being odd in the title.
Comment: I think your example is a good one.
Comment: Are there any other such constructions (of an example/counter example), or is this the only one?
Comment: Are you sure about that one @Aretino? If you drag the base side of the pentagon to the side, would that not change some of the angles? I can imagine if I drag it far to the right, it would even make one of the angles acute!
Comment: I mean: you can translate any line to which a side belongs, along a direction perpendicular to it, and the $n$-gon formed by the translated lines will have the same angles as before.
Comment: I'm not quite following unfortunately. If you have a quick diagram and attach it as an answer, I'd be happy to tick it off.
Comment: It's basically this one: https://www.mathsisfun.com/geometry/parallel-lines.html (same corresponding angles)
Answer: Here's an example of what I wrote in the above comment.
Comment: Would never have thought of this. I think this is a much better counter example than my one, which I felt was 'cheat'-ish.


Pain at base of left thumb after playing stride piano

Question: I am an experienced piano player. I played for 20-something years starting in my childhood, and even studied classical piano at the university level. At my peak I was practicing and playing from 4-8 hours per day, or so. I would sometimes get some minor pain in my forearms that would subside within a week, but never had any serious issues beyond that.
I'm now in my late 40s and have started playing again after a 15-20 year hiatus. I'm currently practicing 2 pieces that involve a lot of left-hand motion - Scott Joplin's Maple Leaf Rag and Maxence Cyrin's piano arrangement of The Pixies' Where Is My Mind. I have played Maple Leaf Rag before and did not experience any pain. The left hand involves moving from octaves to chords on every beat. For Where Is My Mind, there are 2 sections where the left hand is arpeggiating a chord from the root to the 10th, so it's a bit of a stretch. I suspect this may be what's causing the pain.
The pain is at the base of my left thumb extending towards my wrist. When it first happened about a week and a half ago, I took some anti-inflammatory meds and stopped playing for about 5 days. It got significantly better. However, I still notice that every now and then, I'll turn it a certain way, or hold an object a certain way and it will return.
Given that it's subsiding, I don't think it's serious. However, I'm curious if I did something wrong that caused it to happen, or if it's just from having been away from the instrument for so long? Are there exercises I could do to get me more in shape for playing again? (I am doing technique exercises from the Hanon series, but I'm not sure if that's helping or hurting my hand.)
Comment: if you have pain from playing piano, you're not playing correctly.  regardless of how many years you've played piano.  Your piano teacher will help you with this.  But it boils down to...  Play in a more relaxed stress free fashion.  You should be able to play for hours if you aren't stressing your tendons.  If you continue to notice stress, slowwwwwww down until you CAN play for hours.  Then once you can, add the speed back slowly.
Comment: Well, @StephenHazel may be a bit optimistic to say that if you have pain you're doing it wrong... but, still, yes, that is a big part of a potential problem, and many changes are available to make things better. Some of them are not obvious, etc.
Answer: I would avoid treating SYMPTOMS.  If you have a nail in your shoe and it is impaling your foot, you can take the shoe off for a few weeks, take anti-inflammatory drugs and put a bandage on it.  All these actions treat the symptom.  The problem is when you put the shoe back on you still have a nail in your shoe.  Take out the nail and the symptoms go away. Problems with ergonomic issues in your playing are exactly the same.
I'd have to watch you play to tell what you are doing wrong.  What you do wrong  can cause these SYMPTOMS. YOU are not broken.  Your technique is.
Some of the many thumb problems you may have:  Pressing into the keybed.  Once you hit the "point of sound," pressing into the keybed only causes strain to the tendons.  Remember HS physics, when you press into an immovable object, it is pressing with just as much force back into you.  You will break, not it. Remember, the piano is stronger than you.
The muscle most pianists incorrectly use to play the thumb is the thumb's abductor.  The abductor is a weak, slow and fatigable muscle.  It is designed for gripping and holding, not playing down.  A better muscle to use would be the pronator in combination with arm weight, up/down and a slight forward shift from the elbow/shoulder.  Used simultaneously, this completely frees the thumb and provides a nice rotation for the rest of the hand (what the fingers are connected to) to get where it needs to go next and, facilitates the grouping of fingering.
Another error pianists make is crossing the thumb under the palm.  The thenar and  index tendons intersect.  When you cross the thumb under, they grind together.  That can't be good over time.  To get around this, using the pronator, supinator and elbow will not only give you tremendous speed in scales and arpeggios but, will make the thumb feel effortless and powerful.  The same is true with the pinky and ring fingers.  They are not weak nor incoordinate, we just fail to adjust the forearm alignment from the shoulder and elbow.
Abducting all your fingers and stretching out your thumb's extensor (spreading out for an octave) creates a ton of muscular pulls and vector forces.  This is the foundation for most injuries, uneven playing and mistakes.  The arm can only move in one direction at a time.  When we play from the fingers, we attempt to drag the arm and that creates tension in the fingers and tries to pull the arm where we don't want to go.
Of course I suggest seeing a doctor but most doctors treat symptoms and not the problem.  A really good doctor will send you to a movement specialist who treats injured pianists and will fix your errors in movement and the symptoms will disappear.
This is the state of our pedagogy right now.  A student experiences pain, fatigue, tension or cramps and a teacher will suggest they relax the hand or build up strength and endurance.  All those answers are incorrect.  It is the arm that plays the fingers.  Your fingers have no muscles.  A forearm muscle flexes, it pulls a tendon, your bones bend. When we play from the fingers, we strain the tendon caught between the bone and muscle.  When a student experiences cramps from using the wrong muscles, the teacher suggests to relax but, they are relaxing the same muscles they are trying to play from. When we play properly from the arm, indeed, the fingers are relaxed. If a teacher says "relax," you should then ask, Okay, what do I use instead?
The solution is to take a lesson from HS physics and use the muscles and bones designed to move the fingers.  If you must treat your symptoms, I suggest a contrast bath four times a day.  Fill one large plastic trash pail with ice cold water, the other with hot as you can tolerate hot.  Plunge both arms into each pail all the way up to the elbows for one minute. Then switch.  Do this five or six times.  The cold reduces inflammation and the hot increases circulation.  End in hot. But, if you continue you play improperly, you achieve nothing. Our body does most of its maintenance and repair when we sleep.  Make sure you get plenty of it.
Ultimately, just find a teacher who knows what a pronator and abductor is. They will fix you right up.
Comment: Given that finding a good teacher is the best way to learn good, healthy technique, can you say anything more about  forearm alignment for optimizing the use of the pronator, supinator and elbow? And how can one play scales without crossing the thumb under the palm?
Comment: Thank you for this in-depth explanation! I'm wondering if you (or anyone here) knows of a good video that would show the difference between "playing with the fingers" and "playing with the arms"?
Comment: I have created several videos but I STRONGLY URGE YOU NOT TO TRY THEM AT HOME.  All the muscles, fulcrum, weight, gravity and torque must come from the arm simultaneously.  That means you need to know it all at once.  If you isolate a single movement and there is an error elsewhere, you can cause strain or injury.  An analogy would be driving with your parking brake on, or never changing your oil.  You can do it but you shouldn't.
Comment: Oops, I wasn't finished.  Who knew that hitting "enter" would send the comment.  So, there are proper movements and improper ones. Many of us do not execute the proper movements much and most of us do the improper ones.  One of the improper ones is abducting the fingers.  With all five fingers together, gently wave bye-bye. Now abduct them all (spread them out) then wave bye-bye.   Feel the strain?  That is you using two muscles to pull one bone in two directions resulting in strain and an imbalanced hand.  To be continued . . .
Comment: Your bone can only go in one direction at a time and if two muscles pull in two directions, the tendon gets micro tears or strain because it is caught between the two forces.  Consequently most of us are told to "build strength and endurance" or relax or practice more.  All answers are wrong.  The answer is to stop abducting.    I have created a couple of videos on the topic but again, I urge you to work on this with a teacher.  Breaking bad muscle memory habits can be long and hard.

https://youtu.be/pGytHIwDrms
https://youtu.be/1f6zvTy_LhI
Answer: Be very aware of tension. I am a pianist also, and sometimes my worst issues come from things that have nothing to do with playing. For example, driving can cause great tension in my shoulders and arms due to the way I hold the steering wheel. Also, the way the arm rests are located, if I place my elbows on them they cause my shoulders to go up and my elbows to push down hard into the arm rests. I am often better off not using them.
Other times, I will find myself holding a cup of coffee in a weird way (especially to-go cups), and my thumb will be literally pressing into the side of the cup. Why? I do not know. But at times I have even caused my thumb to fall asleep just by holding the coffee cup weird.
So whenever I have a pain or tingling or other strange feeling in my arms/shoulders/wrists/hands, I try to figure out where that is coming from. I ask myself "what is my exact posture right now?" and see if I can find the source of tension. Releasing that tension usually resolves the problem. If I have been doing this repeatedly for a long time, it may take longer for the problem to go away, but it does.
Another time to consider arm and shoulder posture is when falling asleep. I sleep on my side and sometimes my shoulder on the side facing up will fall forward and droop down in front of me. This causes tension because it ends up pulling through the shoulder and upper back. So, I try to at least start off my sleeping with my upper arm resting on my body in a relaxed fashion.
Also be aware of what you are lifting throughout the day and how you hold you arms and shoulders while sitting at the computer.
The reason I bring up these non-playing issues is because the tension can build up elsewhere but become a real problem while playing. It just may not be the playing that is causing the problem. I had a student that was having some wrist issues and they hurt while she was playing. I could not see what she was doing wrong at the keyboard and in conversation learned that she was doing some Yoga postures that I suspected were straining her wrists. She just wasn't holding that posture long enough during Yoga to notice. But sitting down to practice for a length of time aggravated it.
I use Hanon exercises as well, but I have realized that the admonishment to lift the fingers high may not be too helpful. It is important that they move independently, but I have found more usefulness in practicing my scales and Hanon exercises with all my fingertips resting on the keys at all times and gliding my whole hand up and down the keyboard as necessary. Also make sure your piano bench is at the right height. An inch or two in the wrong direction can make a huge difference!
If self-care doesn't help, I suggest seeing a physical therapist.
Comment: Thank you! I actually have noticed some things like you mention - like when sleeping, and also when running at the gym, I sometimes get some shoulder issues. So I'll keep an eye out for when it happens and see if I can figure out what's causing it.
Comment: Since you mentioned the gym, if you are lifting weights, be careful to lift the right amount for you and to do it with proper form, and STRETCH. I have been going to the gym quite a bit myself lately and my muscles definitely have more tension because I have been purposefully stressing them. So I have to be careful to also stretch and be careful not to overdo it.  And with running  - yes, how are you holding your hands? Do you ever make a fist and pull your thumb into the middle of it? I do that sometimes and catch myself and wonder "why am I doing that?"
Comment: I usually run with my elbows bent, and my arms swinging in time to my stride. I don't think I'm clutching my hands tightly, but I feel like sometimes my shoulders start creeping upwards towards my ears, and I have to think about relaxing them. I'm sure I'm doing similar stuff in my playing and don't realize it. I definitely need to look out for it, though!
Answer: I've had that kind of pain, and I know it's frustrating. I've had it as a piano player and from painting my house. For me it goes away eventually, and I haven't always had to stop the activity before it gets better.
It might be from tightness due to stress. You probably had less stress when you were in college than you do now. Try feeling where you're holding tension when you play and then practice letting the tension go. It might not be just in your hand, but could be in your arm, neck or back, too. Let your body relax so that it can be flexible and strong in it's natural way and have the best chance to adapt to what you're doing with it. Meditation, Hatha Yoga, sleeping and exercise are great ways I know of to release stress and relax the whole body.
This is from personal experience, not medical knowledge, and of course, if it gets worse, stop and/or see a doctor.
Comment: Thank you! I have been thinking about getting into meditation anyway, so I guess this is as good an excuse as any. :-)


Relation of Score function of a normal pdf and the z-score?

Question: Suppose we have a density function $f \sim N(\mu, \sigma^2)$. Then, the score function is defined to be:
$$
\frac{d}{d\mu}\log f\left(x;\mu,\sigma^2\right)
$$
The answer to this for the normal is:
$$
\frac{d}{d\mu}\log f\left(x;\mu,\sigma^2\right) = \frac{x-\mu}{\sigma^2}
$$
which looks uncannily like the z-score. Is there a deeper relation here? Thanks!
Comment: Could you elaborate on what you mean by "deeper relation"?  The score functions give first-order differential equations for the densities, thereby defining the family of distributions.  Thus, different distributions will give rise to different score functions and *vice versa*.  Consequently, the meaning of your question seems to rest on how we are supposed to interpret "uncannily."
Answer: There is a set of tests based on the score function. For a normal distribution, it gives the standard z-test. I think with parametric tests for normal distributions you always going to end up with the same test, it's fundamentally the only reasonable thing to do (without going non-parametric).


How do I package a Go program so that it is self sufficient?

Question: I have a Go Program and I want to run it on a switch. Since I cannot install Go on the switch itself, I just copy the executable and try to run. But I get the following error.
runtime: panic before malloc heap initialized
fatal error: runtime: cannot reserve arena virtual address space

runtime stack:
runtime.throw(0x8149b8b)
        /usr/local/go/src/pkg/runtime/panic.c:520 +0x71
runtime.mallocinit()
        /usr/local/go/src/pkg/runtime/malloc.goc:552 +0xf2
runtime.schedinit()
        /usr/local/go/src/pkg/runtime/proc.c:150 +0x3a
_rt0_go()
        /usr/local/go/src/pkg/runtime/asm_386.s:95 +0xf6`

How do I package the Go executable with all it's dependencies?
EDIT 1: Here is the ulimit -a dump.
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 40960
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1024
virtual memory          (kbytes, -v) 395067
file locks                      (-x) unlimited

Comment: run `ulimit -a` on the switch and see if there's any restriction on the virtual memory, max memory or data seg
Answer: TL;DR
Your Go app is not being able to allocate virtual memory to run. I've never developed for a switch before but if it's running linux or a unix variant, check group/user permissions and ulimit values to check if that user has any kind of restriction. Maybe this question might be of help
Longer version
So, your problem here is not go not being able to run without the go development environment because you really don't need it. Go is known for generating static binaries that by definition are self contained and don't depend on other libraries to run.
If you take a better look at your error message, you'll notice that it says:
"cannot reserve arena virtual address space"
You might be asking yourself "what is this arena?"
I quick look at malloc's source code gives us a hint:

Set up the allocation arena, a contiguous area of memory where
  allocated data will be found.  The arena begins with a bitmap large
  enough to hold 4 bits per allocated word.

If you go through that source code you'll find your error message around here.
The runtime·SysReserve C function is the one that actually tries to reserve the virtual address space for the arena. If it can't allocate that, it will throw that error.
You can find code for the Linux implementation of it here.
As go normally tries to avoid big allocations as the might fail right away, if your user can't allocate something as small as 64K, it means your user has tight restrictions. As I have no idea which OS your switch is running and have no experience developing for them I can't go any further than this.
If you can provide more information, I can try to update this answer accordingly.
Comment: Good digging, interesting situation.
Comment: @dallarosa That was detailed! Thanks :)
Here are the values set:
    **ulimit = unlimited** and
    **ulimit -v = 395067**

I am developing for Cisco's NXOS platform. Any more information would really help!
Comment: Write that number down and set the virtual memory to unlimited.
Comment: But 395 MB should be enough to run a simple 'Hello world' program right?
Comment: @Rahul I'm digging on how process memory is allocated and what kind of things could be interfering with your process. It may take some time but I'll update this answer when I have more information!


How to use node reference to link images of referenced node?

Question: I created a blog content type. In this content type I added a field "blog detail". I have a custom module to fetch data using node_load() in blog page. Now I want, when I click on a particular image, that this image's basic page would open using node_reference().
How can I do it?
Answer: I'ld suggest you use References. Add a node reference field into your blog content type. Finally when creating a blog node you'll reference a basic page (the one with your image).
Then check the display settings of your node reference field. Check the field formatters where you can choose

Title (linked)
Rendered Node
NID
etc...

Exactly there you have to add a field formatter now. Best by writing a small custom module. You may take the following code as a starting point:
/**
* Implements hook_field_formatter_info().
*/
function MY_MODULE_field_formatter_info() {
  $info = array(
    'linked_image' => array( // Machine name of the formatter
      'label' => t('Image (linked)'),
      'field types' => array('node_reference'), // Scope (this one will only be available to node reference fields)
      'description' => t('Display linked image if available'),
    ),
  );
  return $info;
}

/**
* Implements hook_field_formatter_view().
*/
function MY_MODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
    foreach ($items as $delta => $item) {
      // get the nid,
      // do a node_load(),
      // get your image,
      // rework it
      // $linked_image = what ever you got
      $element[$delta]['#markup'] = $linked_image;
    }
  return $element;
}

Comment: hey, can you just provide the briefly code? I will try but I didn't understand after foreach
Comment: @priyank - Sure, if you hire me ;)
Comment: please help me bro.
Comment: @priyank - Don't you think I already helped you lot? Now go on and help yourself. It will pay off a thousand times if you figure out to walk the last few meters by yourself. Or simply ask a new question and let's see where your exact problem is with that code.
Comment: @priyank : I think you should consider marking this anwers as accepted ... Moreover, and sorry for asking, but since you don't seem to have any question marked as accepted, I wonder if you're familar with [this]( http://drupal.stackexchange.com/help/someone-answers)?


Job for httpd.service failed

Question: after following this tutorial :https://www.digitalocean.com/community/tutorials/how-to-create-an-ssl-certificate-on-apache-for-centos-7
I have tried everything I possibly can to fix the error I have gone through the steps to ensure I correctly entered the details
I got to this point:
sudo apachectl restart

I keep getting this error.
Job for httpd.service failed. See 'systemctl status httpd.service' and 'journalctl -xn' for details.

I have tried restarting httpd service but that get's the same error
after executing systemctl status httpd.service I got :
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
   Active: failed (Result: exit-code) since Thu 2015-04-30 13:54:04 EDT; 2min 7s ago
  Process: 30331 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 29403 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)
  Process: 30330 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 30330 (code=exited, status=1/FAILURE)

for the second command journalctl -xn I get :
   -- Logs begin at Thu 2015-04-30 07:01:51 EDT, end at Thu 2015-04-30 13:57:37 EDT. --
Apr 30 13:54:04 user sudo[30325]: user : TTY=pts/0 ; PWD=/home/user; USER=root ; COMMAND=/sbin/apachectl restart
Apr 30 13:54:04 user systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun with start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Apr 30 13:54:04 user httpd[30330]: AH00526: Syntax error on line 100 of /etc/httpd/conf.d/ssl.conf:
Apr 30 13:54:04 user httpd[30330]: SSLCertificateFile: file '/etc/httpd/ssl/apache.srt' does not exist or is empty
Apr 30 13:54:04 user systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Apr 30 13:54:04 user kill[30331]: kill: cannot find process ""
Apr 30 13:54:04 user systemd[1]: httpd.service: control process exited, code=exited status=1
Apr 30 13:54:04 user systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Apr 30 13:54:04 user systemd[1]: Unit httpd.service entered failed state.
Apr 30 13:57:37 user sudo[30336]: user: TTY=pts/0 ; PWD=/home/user; USER=root ; COMMAND=/bin/journalctl -xn
-- Logs begin at Thu 2015-04-30 07:01:51 EDT, end at Thu 2015-04-30 13:57:37 EDT. --
Apr 30 13:54:04 user sudo[30325]: user: TTY=pts/0 ; PWD=/home/user; USER=root ; COMMAND=/sbin/apachectl restart
Apr 30 13:54:04 user systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun with start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Apr 30 13:54:04 user httpd[30330]: AH00526: Syntax error on line 100 of /etc/httpd/conf.d/ssl.conf:
Apr 30 13:54:04 user httpd[30330]: SSLCertificateFile: file '/etc/httpd/ssl/apache.srt' does not exist or is empty
Apr 30 13:54:04 user systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Apr 30 13:54:04 user kill[30331]: kill: cannot find process ""
Apr 30 13:54:04 user systemd[1]: httpd.service: control process exited, code=exited status=1
Apr 30 13:54:04 user systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Apr 30 13:54:04 user systemd[1]: Unit httpd.service entered failed state.
Apr 30 13:57:37 user sudo[30336]: user: TTY=pts/0 ; PWD=/home/user; USER=root ; COMMAND=/bin/journalctl -xn
...skipping...
-- Logs begin at Thu 2015-04-30 07:01:51 EDT, end at Thu 2015-04-30 13:57:37 EDT. --
Apr 30 13:54:04 user sudo[30325]: user: TTY=pts/0 ; PWD=/home/user; USER=root ; COMMAND=/sbin/apachectl restart
Apr 30 13:54:04 user systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun with start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Apr 30 13:54:04 user httpd[30330]: AH00526: Syntax error on line 100 of /etc/httpd/conf.d/ssl.conf:
Apr 30 13:54:04 user httpd[30330]: SSLCertificateFile: file '/etc/httpd/ssl/apache.srt' does not exist or is empty
Apr 30 13:54:04 user systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Apr 30 13:54:04 user kill[30331]: kill: cannot find process ""
Apr 30 13:54:04 user systemd[1]: httpd.service: control process exited, code=exited status=1
Apr 30 13:54:04 user systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Apr 30 13:54:04 user systemd[1]: Unit httpd.service entered failed state.
Apr 30 13:57:37 user sudo[30336]: user: TTY=pts/0 ; PWD=/home/user ; USER=root ; COMMAND=/bin/journalctl -xn

IT says the files do no exist etc/httpd/conf.d/ssl.conf and .key but they do :/
Answer: The key error message appears to be:

SSLCertificateFile: file '/etc/httpd/ssl/apache.srt' does not exist or is empty

Which is likely a small typo in /etc/httpd/conf.d/ssl.conf in the name of the SSL public key component of your certificate, most likely it should be apache.crt instead of apache.srt
Comment: @HBruijin Hi, my friend, I got a similiar error, can you take a look with that? https://stackoverflow.com/questions/44280173/job-for-httpd-service-failed-because-the-control-process-exited-with-error-code

Job for httpd.service failed


Como fazer essa função retornar somente o valor desejado ao mesmo tempo em que recebe ponteiros como argumento?

Question: Estou tentando construir uma função que realize uma busca em um vetor de forma binária, mas quero que ela retorne -1 quando o elemento não for encontrado, e quando o elemento for encontrado ela devolva a posição do elemento no vetor, e a quantidade de comparações necessárias para verificar se o elemento está ou não no vetor.
O que está acontecendo: se eu deixo a função com retorno, ela nunca me dá resposta positiva, mesmo quando o elemento está no vetor. Já tentei deixar ela sem retorno, e nesse caso ela devolve para o endereço comparação o numero de comparações e para o endereço chave a posição da chave, mas fica sem a possibilidade de devolver resultado negativo. Já tentei usar a própria chave como ponteiro para fazer essa função de devolver verdadeiro ou falso, mas nesse caso também só devolve resultado negativo.
Já tentei também deixar com dois retornos, um para o caso de resultado falso e outro para o caso de resultado positivo, e funciona a verificação, mas não devolve a quantidade de comparações.
<code>int busca_binaria(int v[], int tamanho, int* chave, int* comparacoes) {

    int meio, inicio = 0, fim = tamanho - 1, posicao_chave, quantidade_comparacoes = 0;

    while (inicio <= fim) {
        meio = (fim + inicio) / 2;
        if (*chave == v[meio]) {
            posicao_chave = meio;
        }
        if (*chave > v[meio]) {
            inicio = meio + 1;
        }
        else {
            fim = meio - 1;
        }
        quantidade_comparacoes++;
    }
    *chave = posicao_chave;
    *comparacoes = quantidade_comparacoes;
    return -1;
}
</code>
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Veja abaixo seu código revisado e comentado que realiza suas exigências quanto ao algoritmo:
<code>/**
 * BUSCA BINÁRIA em vetor ordenado
 * @return se o elemento 'chave' for encontrado no vetor, a funcao retorna usa posição, caso contrário é retornado -1
 * @param comparacoes é um ponteiro para uma variavel no escopo em que busca_binaria foi instanciada, e guarda a quantidade
 * de iterações/comparacoes executadas durante a busca
**/
int busca_binaria(int v[], int tamanho, int* chave, int* comparacoes) {

    int meio, inicio = 0, fim = tamanho - 1;

    *comparacoes = 1; // Usa o próprio ponteiro como contador, ao invés de criar a variável quantidade_comparacoes para isso
                      /* Perceba que ele começa com 1, ao invés de zero, isso porque mesmo no melhor caso (quando o elemento procurado estiver no meio)
                       * ainda assim será necessário ao menos uma comparação para validação da igualdade
                       */

    while (inicio <= fim) {
        meio = (fim + inicio) / 2;
        if (*chave == v[meio]) {
            return meio; // Quando encontrado, retorna um valor não negativo (maior ou igual a 0) indicando a posição do elemento
        }
        if (*chave > v[meio]) {
            inicio = meio + 1;
        }
        else {
            fim = meio - 1;
        }
        (*comparacoes)++; // Incrementando o conteúdo do ponteiro
    }

    return -1;
}
</code>


Android Lifecycle - ActivityManager kills process -> Exception when returning from background

Question: I'm having a very boring problem. When my app goes to background, sometimes the process is killed as the LogCat shows:
<code>INFO/ActivityManager(187): Low Memory: No more background processes.
INFO/ActivityManager(187): Process com.app.myapp (pid 20681) has died.
INFO/WindowManager(187): WIN DEATH: Window{40592708 com.app.myapp/app.myapp.dashboard.Dashboard paused=false}
ERROR/InputDispatcher(187): channel '408b1d40 app.myapp/app.myapp.menus.products.Promotions (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
ERROR/InputDispatcher(187): channel '408b1d40 app.myapp/app.myapp.menus.products.Promotions (server)' ~ Channel is unrecoverably broken and will be disposed!
INFO/WindowManager(187): WIN DEATH: Window{408b1d40 app.myapp/app.myapp.menus.products.Promotions paused=false}
INFO/ActivityManager(187): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10100000 cmp=app.myapp/.Main } from pid 187
INFO/ActivityManager(187): Start proc app.myapp for activity app.myapp/.menus.products.Promotions: pid=20721 uid=10062 gids={3003, 1015}
</code>
When i then try to return to the app, via task switcher (long press home) it tries to return to the last opened activity... and crashes.
Why doesn't it open from scratch, opening Main as the whole app was closed?
The ERROR/InputDispatcher erros do not always appear.
UPDATE:
The problem is... the Application is restored, but the objects in it that were downloaded (as a hashmap) aren't... so when i access them.... i have "problems"...
UPDATE 2:
I've manage to fix the problem by verifing on onCreate on BaseActivity (that is extended by every other) if the Application contains the data I need or if it's null (in this case it restarts the app).
Is there a more elegant solution, or at least a way to say to the device that if the application is killed, i want the application to be restarted?
This links helped understand the problem... and knowing there is no clear answer for how to store the data from Application: How to declare global variables in Android?
UPDATE 3:
So I asked a question specifically of how to save Application data correctly. This may help those with the same question: Android: Best way to save data stored in Application Singleton Class
Comment: http://stackoverflow.com/questions/6025554/android-application-loses-state-after-launching-another-intent/6025590#6025590
Comment: That link ALMOST answers my question.. the problem is that i have data stored in Application class.. that when the Application class is restored are not.
Comment: This was also useful, but it didn't take my doubt about what method to use: http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables
Answer: As far as I ubderstand it goes back because the user didn't close the application. A though: are you accessing bundle data in that activity that's passed from the opening activity? If so you may want to look into the bundle instance saving and restoration functions that you can implement to solve the app coming back into the foreground in am invalid state.
Edit for clarity: the application is restored to its previous state because it was killed by the OS due to low memory while it's in the background. Upon task switching back it's restored to that previous state and invalid / non-existent bundle data may be causing the crash when that activity is resumed.
Comment: But what about activity stack history? If i press back after that, even if it doesnt crashes.. it will close right? As it is the only activity opened? Or am i wrong?
Comment: Edited question to address your answer.
Comment: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState read that. It talks about onSaveInstanceState and pausing your app. That's the elegant solution. Detect the pause, save our state. And on resume you have a chance to reinitialize without reloading completely. I'm unsure about the activity history part of your comment. You'd have to try it out
Comment: The problem is.. if you have data that is shared by multiple activities. Then what, save in each the data? That kind of defeats the purpose of using the less memory we can. That's why i store some stuff on the Application, so that every activity can use the data, which is shared.
Comment: In your state bundle you only save what you need. It's temporary memory. Just a point in time. Once you resume the app that memory is thrown away after the lifetime of the activity and you can go back to using your shared settings values on other activities. Think of these state bundles like an emergency snapshot of data only to get the application back into a useable state when resuming.
Comment: ok, then for each activity i'm supposed to use state bundles to each object on the Application? Am I wrong or are they called everytime the activity stops?
Comment: Just throw into the bundle what you need before you app is paused / destroyed for memory. It helps if you extend Activity with your own Activity (e.g. "MyApplicationActivity") and then use that for all other activities. Then you can implement cleanup and init methods for data that's shared across different activities. You should only have data active for that activity or in a thread/service. These need to be shut down if you're leaving the app. Most of this is explained in the Activity reference page.
Comment: ok thanks. I'll have to see that question about the stack of activities after the kill...


How do I prove the minimum for given trigonometric expression of two angles

Question: Given the expression defined for $x,y \in {[}0,2\pi{)} $
$$\begin{align} E(x,y)&=\cos(2x)+\cos(2y)+\cos(2x+2y) \\
&+4\cos{x}+4\cos y+4\cos(x+y)\\
&-2\cos(x-y)-2\cos(2x+y)-2\cos(2y+x)
\end{align}$$
Wolfram-Alpha tells me that the minimum of this multivariable expression is $-\frac{27}{2}$, for $x=y=\frac{2\pi}{3}$.
How can this be proved (easily)?
I've tried using multivariable calculus but the calculations are really "messy". Using formulae that transform sums of trigonometric functions to products did not help either, in my case.
Answer: It may not be very simple but i'll try. First observe that it's a continuous function and it should have minimum and maximum on a closed interval. Next, observe that the function is symmetrical relative to $x$ and $y$ so if there is a minimum inside of the interval it will be achieved at some point $(a,a)$ because partial derivatives will be symmetrical as well. So we just need to find minimum of $$f(x)=E(x,x)=\cos 4x-4\cos 3x+6\cos 2x+8\cos x-2$$ Using multiple angle formulas, we can write this function as a polynomial of $\cos x$: $$f(x)=8\cos^4x-16\cos^3x+4\cos^2x+20\cos x-7$$ Let's find derivative $f'(x)=-\sin x \cdot (32\cos^3x-48\cos^2x+8\cos x+20)$ or $f'(x)=-4\sin x \cdot(2\cos x+1)(4\cos^2x-8\cos x+5)$. We have two critical points to check: $x=0$ and $\cos x=-0.5$ ((plus the boundaries).$f(0)=f(2\pi)=9$, when $x_m=\frac{2\pi}{3}$ we have our minimum $f(x_m)=-\frac{27}{2}$
Comment: Thank you very much for this, however I don't completely understand the reasoning behind the fact that $x=y$, can't the partial derivative be $0$ (condition for maximum or minimum) in a point where $x \ne y$, for example $(x,y)$ - and then the partial derivative will be $0$ for the point at $(y,x)$ too. Could you help me clear that out?
Comment: @ParallelismAlert: This is a very good and a valid point and there is no easy answer. If you want to learn more, look up Purkiss Principle and these references: https://math.stackexchange.com/questions/681153/how-to-find-the-minimum-value-of-this-function/684155#684155 https://mathoverflow.net/questions/58721/when-does-symmetry-in-an-optimization-problem-imply-that-all-variables-are-equal In this particular case the function is convex, that's the key point here.


Show View When Empty and Hide View When Not Empty!

Question: I have a webform as a block which sets a value connected to the logged in user. I want to display the webform if it hasn't been filled in yet by authenticated users, and hide it when it has (based on whether the value has been set or not).
I thought I could do it by using views with the Views Block Area to display the webform as a block when there is no result. But I want to hide the view when there is a result, which seems impossible?
If anyone can suggest how I might be able to achieve this, not necessarily using views.
Comment: Possible duplicate of https://drupal.stackexchange.com/questions/200595/how-to-hide-webform-block-for-users-who-submitted-the-form-already
Comment: Thanks for pointing out the duplicate. I have used Rules Block Visibility before but was hoping to find an alternative. May just need to find a way to code it I guess.
Answer: Limit submissions to "1 ever" when you configure the Webform. I'm not sure if Webform Block module would automatically hide the block if the form is not shown, but it should. Webform will not show the form if it cannot be submitted.
Comment: Many thanks for your answer. I had ended up using code (I gave this as an answer) but yours would have been a much easier way of solving it! I was thinking there must have been an easier way :)
Answer: In the end I used code in the block page visibility settings to only show the block based on whether users had set a value in their CiviCRM profile (a Drupal module). I am posting the code in case it helps others:
<code><?php

    civicrm_initialize( );

  //variable used to set if block should be displayed or not - default to not
    $show = 0;

    //get current logged in user civi id
    $contact = CRM_Core_Session::singleton()->getLoggedInContactID();

    //get employer id
    $org = civicrm_api3('Relationship', 'get', [
        'sequential' => 1,
        'return' => ["contact_id_b"],
        'relationship_type_id' => 5,
        'contact_id_a' => $contact,
    ]);

    if(isset($org['values'][0]['contact_id_b'])) {

        //get field value
        $result = civicrm_api3('Contact', 'get', [
            'sequential' => 1,
            'return' => ["custom_958"],
            'id' => $org['values'][0]['contact_id_b'],
        ]);

        // only show on the members home page
        if(drupal_get_path_alias() == 'members/organisation-profile') {
            $show = 1;
        }

        // don't show if they have set a value
        if(isset($result['values'][0]['custom_958'])) {
            $show = 0;
        }

        // do show if the value is ''
        if($result['values'][0]['custom_958'] == '') {
            $show = 1;
        }
    }

    return $show;

?>
</code>


Whether $\sum_{i=1}^k\frac{\prod_{j\neq i}(\alpha_j-\beta)}{\prod_{j\neq i}(\alpha_j-\alpha_i)}=1$ is true

Question: Suppose we have k positive numbers: $\alpha_1, \alpha_2, ..., \alpha_k$, for any number $\beta>0$, is
$$\sum_{i=1}^k\frac{\prod_{j\neq i}(\alpha_j-\beta)}{\prod_{j\neq i}(\alpha_j-\alpha_i)}=1$$
true? If so, how to prove it?
Answer: Use the formula for the Lagrange interpolation polynomial
$$L(\beta)=\sum_{i=1}^{k} f_i\prod_{j\neq i}^{k}\frac{\alpha_j-\beta}{\alpha_j-\alpha_i}.\tag{1}$$
This is the unique $(k-1)$th degree polynomial passing through $k$ points
$(\alpha_i,f_i)$, with $i=1,\ldots, k$. In your case all $f_i$'s are equal to $1$, and therefore $L(\beta)=1$.
Comment: Yes. Thank you for the right answer.
Answer: The sum is a polynomial with respect to $\beta$. Evaluate the polynomial at the points $\alpha_i$. Use the degree of the polynomial to conclude.
Answer: This is a degree $k-1$ polynomial in $\beta$ which is equal to $1$ at the $k$ points $\alpha_1,\ldots, \alpha_k$, and is thus $1$ everywhere.
This follows from the result that a nonzero polynomial of degree $n$ cannot have $n+1$ roots.


Should I take the weather into account when I replace guitar strings?

Question: I have been told that the strings in a guitar should be replaced at least every six months (I know this can be subjective).
I have a classical guitar which has been several years with the same strings, and plan to replace them.
My question is if it matters the kind of weather/temperature of the day (hot or cold), when replacing the strings, like for instance affecting the tension, or not settling as fast as with a different temperature?
Answer: Not really, good strings will sound good at any (reasonable) temperature. If you go outside with the guitar (where it's cold), you might need to tune it again, because the temperature affects the tension of the strings.
You might also need to adjust your neck, depending on the moisture level (this is typically done twice a year) to maintain proper string action.