Tips on buying an electric guitar for a beginner

Question: I know there is another question similar to this one but it didn't answer all my questions.
I am just a beginner and I want to buy an electric guitar. First of all I have heard that you should start with an acoustic but I don't like acoustic in general. Is this true??
Next, I should look at the quality of the guitar especially the neck, fingerboard and the frets right?? The knobs and switches should also be good??
Any specific things I should notice?? Can anyone recommend a simple tune or chord that I can play to compare tone and quality of pickups?? What does intonation mean and how can I check it?? Last question, How should I get my guitar set up for easy playing??
Comment: I just found your other question. If you like the HSS Squire then there's no reason not to buy it. It should be set up from the factory. I wouldn't worry about buying a more expensive model - again, you just won't notice the difference yet. I would force yourself to learn on the cheap guitar until you can play pretty well and have saved up enough for the USD 1500+ market (Fender American Standard or Gibson USA brands, etc.) At that point you'll know what to look for. If you want a humbucker, buy a guitar with one, don't try to retrofit.
Comment: Thanks a lot for the advice. I was breaking my head then I realized I might get a better guitar later anyway.
Answer: First, I completely disagree that beginners should start with acoustics. I'm not sure where that idea came from, it makes no sense to me. I learned on electrics and to this day I rarely play acoustic, which leads to the advice I give my students on electric vs. acoustic: buy the one you want to play, based on the genre/style(s) you want to play. If your ultimate goal is to master all of James Taylor's songs, then buy an acoustic and get started right away. If you are obsessed with Rage Against The Machine and want to learn to create all kinds of crazy noises on your guitar, start with an electric.
For the rest of your questions, here's the problem: There's a lot to know about buying a high quality guitar to be able to assess whether it's a great guitar or a ripoff. We can't transmit all the knowledge you need over the internet in a few paragraphs on a web site. It's just not possible to summarize all the things to check and how to check for them.
So what do you do? Buy an inexpensive guitar to start out. You won't notice the difference between a USD 150 and USD 1500 guitar at first - you'll be a beginner on both of them, so don't even bother looking at the midrange or high end models.
Computer controlled milling have made it possible for guitar makers to produce extremely consistent and highly playable guitars for very little money. Gibson Epiphone guitars made in Korea and Fender Squire guitars made in Mexico are both examples of this - with the Fenders being widely seen as some of the best value for the money available anywhere.
Same goes with amplifiers. You just don't know what you want yet. You definitely want to get an amplifier as soon as you can afford one, but again, don't spend more than USD 100 - 200, if that. I see nothing wrong with beginners getting those all-in-one boxes that have a budget guitar, amp, cable, strap, and other doo-dads.
One thing you definitely need is a tuner. You can get an app for your smart phone, but having an inexpensive guitar tuner that you can plug the guitar into will be a little easier to use than an app and your phone's microphone.
The other thing you will need is to know how to tune it. Back in my day, of course, our only option was to buy a book for beginner guitarists. Now, you can just find a web site or YouTube video. Tune the guitar every time you play it. It will be annoying at first, but you will learn to tune the same way you learn to play, and being in tune will make a big difference as you learn.
Regarding amps, ignore the wattage. It doesn't matter at all. If you have a chance to play each amp, buy the one you think sounds better. Or have a person at a music shop play for you so you can hear the difference. But really, it doesn't matter that much. You just need to get playing and saving your money so when you're ready, you can buy midrange quality gear that you know you love because you've learned enough to be able to tell.
Comment: I am sure about Fender design and sound so I am going for the Squier Affinity Strat HSS. Also I have sort of learned all there is to learn in keyboard so I am no novice to music. I can hear the differences between the guitars in the store with a 100W amp, but I am not going to confuse myself more. About the tuner??? Is it possible to play the note on my keyboard and just tune it with my ear??? I do this for my violins and it turns out very well.
Comment: @Tarun Yes, if you already know how to tune a violin then you'll be fine with a guitar. You may feel like an electronic tuner is "cheating" but as someone who plays several instruments I love the fact that the electric guitar I can just tune precisely in a few seconds with a plug-in tuner that eliminates noise and uncertainty. If you already know a bit about music, then my advice is a little off, but one thing stands: Below USD 1000 - 2000, it's all budget stuff that is usually just going to be for learning. Don't stress about it.
Comment: Ok thx a lot. 10W Practice Amp it is...
Comment: @Tim: Someone without a tuner will need to play loudly enough to hear what they're doing.  This may be difficult in a noisy environment, or disruptive in a quieter one.  Using a neck-mounted or pickup-fed tuner will ease both of those problems.
Comment: get a tuner app for your phone. or if your ear is good that is fine as well. get a metronome app too. lots of good free options. Look for used amps. you may get more quality for cheaper and a banged up amp will sound fine if it is in good working condition and this can save you some money. buying a used guitar can have all sorts of problems but not as much of an issue with an amp. if you can't really play and want to get a sense of what it will sound like ask the sales person to play for you.  you should still "play it" to see how it feels in your hands but that may help.
Comment: I know it sounds glib, but for the last few years I've been playing mostly (5 and 6 string) bass. I carry a tuner, but always tune by ear off someone else, using harmonics after a ref. note. Works for me. Sorry, but I'm a luddite, and won't rely on a little box with flashing lights or letters keep me in tune. In principle, if I can't do it properly without that, I shouldn't be playing! No absolute pitch, just experienced ears!
Comment: On the odd occasions a string is out, if I can't put it right on the fly, I really shouldn't be there! No, I don't stop playing and tune up - as a lot do, by turning on the tuner. Of course this is all before the gig starts - initial tuning. The idea is everyone else tunes (yes, with the magic boxes) then I tune to them, from a single reference note, then using harmonics, do the rest.
Comment: Re: acoustic guitars for beginners, another reason to avoid them and to go with an electric is that the setup for an acoustic guitar is *completely* different from an electric, and is probably not something a beginner can reasonably handle. Whereas most adjustment on an electric uses small Phillips or hex key screws and can be learned from a YouTube tutorial. Just follow the cardinal rule: don't force it.
Comment: So even for an amp I should just pick something decent and go with it for now???
Comment: Whilst reluctantly agreeing that a tuner is probably a good idea, I honestly feel that a guitarist should be able to tune his own guitar without the crutch. I really feel I'm playing with an amateur who can't tune his guitar, 'cos the battery's gone in his tuner...
Comment: @supercat - aw, come on. If I'm not playing loud enough to hear me in the mix, I'm going home anyway!
Comment: I do sing. harmony, which usually takes me to both edges of my range. But singing lead at the very edge is something I wouldn't recommend. And tuning to A=440 is no big deal for the rest. When they're all happy, a reference note is good for me, then the whole instrument is done. If someone wanted to tune my guitar or bass for me, I'd consider it pretty unprofessional. Brought up in the days when electronic tuners weren't even a dream.
Comment: Let us not [continue this discussion in chat](https://chat.stackexchange.com/rooms/81297/discussion-between-todd-wilcox-and-tim). and instead just drop it since you're being contrary and not helpful to the asker.
Comment: Thanks a lot for all the comments. I think I will get a tuner but before I use it I will try with my ear and keyboard. As for phone apps, tuners are okay but they are not as accurate as real tuners more so because my phone's microphone is very bad. @GalacticCowboy If setup just involves a few screw then count me in. After changing strings on cheap Chinese violins and sanding wooden bridges to right shape by hand this will be no chore.
Answer: First of all I have heard that you should start with an acoustic but I don't like acoustic in general. Is this true??
If the music you want to make is electric, you will never get there and love music with an acoustic. If the music you want to make is acoustic, you will never get there and love music with an electric. I own both. I love both. I prefer the electric.
Last question, How should I get my guitar set up for easy playing??
Reordered because this gets deeper.
"Easy playing" depends a lot on the kind of playing you want to do. If you want to play lead guitar, like Angus Young of AC/DC, you would want a flatter neck and lower action, which allows you the ability to bend more. If you want to play rhythm guitar, like Malcolm Young of AC/DC, you would want a little more bow in the neck and higher action, so the strings can ring freely without clanging on frets.
I recommend medium picks and strings (.010 sets) until you can express a need for either heavier (I want to detune and djent, or be cool like SRV) or lighter (I want easy bends for country or blues, or be cool like Billy Gibbons).
Doing a setup is fairly easy, and there are guides available online, but if you're getting a pro setup, explain the kind of playing you expect and they should be able to make it work.
A setup is, more or less: truss rod > new strings > string height > intonation. The scariest is adjusting the truss rod, but if you do quarter turns and give it time, even that shouldn't be too bad. And, esp. if you stick with the same gauge of strings, you shouldn't have to redo it when changing strings.
What does intonation mean and how can I check it??
Intonation means how close the note you're intending to play is to the note you're actually playing. If you play slide, or steel guitar, or fretless, or violin, or most other instruments, this means training your ears and hands. If you play guitar, it is a mechanical process.
We guitarists mostly mean that the octave note at the 12th fret is the same note as the octave note at the harmonic at the 12th fret. With the electric, this involves pulling out a screwdriver and an electric tuner. With an acoustic, this involves choosing the right strings, maybe cutting a new bridge, and eventually just saying "this is close enough".
Either way, you can't fully tune a guitar. Between physics and even temperament, it just isn't going to work. But you can get close enough.
Next, I should look at the quality of the guitar especially the neck, fingerboard and the frets right?? The knobs and switches should also be good?? Any specific things I should notice?? Can anyone recommend a simple tune or chord that I can play to compare tone and quality of pickups??
Plug it into an amp and move the switches and pots to every position. (Terminology break: the knob is the thing that you touch, but the potentiometer, or pot, is the thing that is part of the circuit.) An older pot may have dirt and cruft in it, and be scratchy. There is electronics cleaner that can help, and new pots are like $4 and some soldering, but if you don't want to do that, don't buy that guitar.
For the neck, the biggest watch-out I can think of is a dried-out fretboard, which will shrink some and have sharp annoying ends of frets sticking out the side. Some time and a file will rectify that, but again, if you don't want to do that, don't buy that guitar. You can get perfectly acceptable $100 guitars these days, a gift from Free Trade and the CNC gods, so there's no good reason to get started with a fixer-upper.
If you're learning, you don't have the trained ear yet to tell good tone and pickup quality. Don't stress on tone just yet. And best of luck.
Comment: There *should* be lots about playing harmonics, both on this site and on the net. In short, if you touch the string right at the 12th fret, it should ring out, quieter than an open string but one octave higher, which should be the note at the 12th fret.
Comment: Thanks a lot solved most of my problems but what is the octave note at the 12th fret and the octave note at harmonic at the 12th fret. I know basic theory but not harmonics. Could you explain??
Comment: Ok that seems simple. I'll do this for every string when I buy the guitar next week.
Answer: All depends on what you want to play.
Starting out on an acoustic is not a terrible idea when you are new to the guitar, having an instrument with a wide fingerboard is very forgiving for newbies. It has a purer tone which is great for learning the basics.
Yes, when you get some experience under your belt and you decide on what specific genre you want to play, then sure buy the instrument suited for that genre.
A cheap nylon is a gateway guitar. That being said if you know from the outset all you ever want to be is a jazz guitarist, then don't buy a nylon. Buy some sort of jazz guitar but for a new player who wants to dabble in a few genres before making a hard commit, the nylon will be a great intro guitar.
Yamaha makes great entry-level nylon guitars which have staggering amounts of value for money. You can buy a 300-500$ Yamaha that is a great instrument that will keep you occupied for many years while you are still developing chops.
As for the setup, typically you will not have to worry about that. Any new instrument should be sold with a setup done from the shop that sells you the instrument. That simply put is just an industry standard.
Comment: Lots of jazz is played on nylon strings, especially after the rise of Brazilian jazz.
Comment: Thanks for the advice but I am sure I don't want to play calmer types of music that require acoustic guitars. I am not sure on a particular genre yet but I think that is because I am sort of between Pop, rock, classical rock and hard rock. Not much metal but I want to learn some jazz as well. I don't think I will ever be playing one type of music over another for long.
Answer: Get a guitar with the lowest action you can afford.  That is what will make you play better and you will enjoy it more.  The more expensive the instrument, the lower the action will be, as a rule. Get some decent pickups because that makes a big difference.  Everything else is marginal for the most part as far as playability and sound goes and are even pretty good on the cheapest Chinese guitars.
Comment: I prefer low action but that isn't the be-all and end-all of better playability. A good setup for better sustain, no buzzing, polished frets and fret-ends, good intonation, and staying in tune are just as important. Sometime people might prefer a slightly higher action so they can dig in but it does seem like a good idea to get it al low as you can for your preference and your picking style. This ensures that you don't  hold down notes notes so far they go out of tune.


Efficient way to keep Drupal 7 session alive from another web app?

Question: Is there a simple PHP file I could create which, when called by an authenticated user, will keep their Drupal session alive?
I don't want to do an AJAX call to /index.php as this will cause unnecessary overhead. I just need a way to keep the session alive from another app.
Could I use the bootstrap method below, rather than instantiating the whole stack?
<code><?php
    define('DRUPAL_ROOT', '/my/local/root');
    include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
?>
</code>
Answer: If you're worried about unnecessary overhead, why not check out the High-performance JavaScript callback handler module.
It allows you to control what exactly gets loaded during the Drupal bootstrapping process, so that you would only spin up the bare essentials to keep your session alive from another app.
Check out this blog post for a good breakdown of how you implement this module:
High performance AJAX callbacks with Drupal 7 and the JS module
Comment: Thanks for the clarification and link to more info. The article is really helpful. Cheers.
Comment: No problem, glad I could help out.


Strange exception on jbooss 5.1 javax.ejb.EJBTransactionRolledbackException

Question: In one of our client deployments of jboss5.1 mysql and an JSF application we get this one line error
<code>16:46:08,970 ERROR [org.jboss.aspects.tx.TxPolicy] [] - [] (WorkManager(2)-17)  javax.ejb.EJBTransactionRolledbackException
</code>
it happens every 15 seconds eaven if we dont have any chron jobs on that time scale.
We have two ears deployed on the server and if I undeploy one of them the error stops. So it must be something related to the aplication. The strange thing is that we have not touched that ear for a long time and this error started to appear withowt redeploy or any code change.
Any hints on how can I dig furthure to resolve this strange error?
Comment: Do you get any exception stack trace along with this?
Comment: no thee given line is the onliy line about this in the log so no aditional stack trace
Answer: go look at the following link
https://community.jboss.org/message/830295
https://community.jboss.org/message/635405?_sscc=t


Unable to write file after making exe file

Question: I have written the following python code in the jupyter notebook as:
import pandas as pd
import time
from datetime import datetime
import os

PATH="C:\\Users\\ankit19.gupta\\Desktop\\test1"
data = [['Ankit', 28], ['Akshat', 28]]
data = pd.DataFrame(data, columns=['Name', 'Age'])
os.chdir("C://Users//ankit19.gupta//Desktop//test1")
print(os.getcwd())
PATH="C:\\Users\\ankit19.gupta\\Desktop\\test1"
xlsx_file1 = str(datetime.now().strftime('%d_%m_%Y_')) + 'Test' + '.xlsx'
out_path1 = PATH+ "/Generated_Data/"+xlsx_file1

print("Writing excel file") # Till now code is executed successfully

writer1 = pd.ExcelWriter(out_path1, engine='xlsxwriter')

print("Used ExcelWriter") # Don't get this print statement

data.to_excel(writer1,index=False)
print("File is written")
writer1.save()
print("Completed")

I have created a pandas dataframe and store the data of this dataframe in an excel file and writing it on the disk. It executed successfully when I run it on jupyter notebook but when I convert it into an .py file using !jupyter nbconvert --to script test1.ipynb and get .exe file from .py file using !pyinstaller test1.py then when I open the .exe file from the directory \test1\dist\test1 then console gets open and show the print statement as Writing excel file and then console gets closed and I don't get the statement Used ExcelWriter from the print() function.
I don't know why it is happening while using executable file though I have changed the current working directory. Can anyone please help me ? Any help would be appreciated.
Comment: Have it printed out any error messeges?
Comment: No. Console automatically closed without showing any error message. I have written print statements to detect which statement is not executing. Without making exe, it run successfully on jupyter notebook  @AnhPC03
Comment: Add, or modify, a print statement to print `outpath1` to ensure the file is going to where you think it is going.
Answer: You ran your code on Windows, then os.chdir with linux template is wrong. Otherwise, your destination directory must be existed before you write to
import pandas as pd
import time
from datetime import datetime
import os

PATH="C:\\Users\\ankit19.gupta\\Desktop\\test1"
data = [['Ankit', 28], ['Akshat', 28]]
data = pd.DataFrame(data, columns=['Name', 'Age'])
os.chdir("C:\\Users\\ankit19.gupta\\Desktop\\test1")
print(os.getcwd())
xlsx_file1 = str(datetime.now().strftime('%d_%m_%Y_')) + 'Test' + '.xlsx'
out_path1 = PATH+ "\\Generated_Data\\"

# make sure path existed
os.makedirs(out_path1, exist_ok = True)

out_file = PATH+ "\\Generated_Data\\" + xlsx_file1

print("Writing excel file") # Till now code is executed successfully

writer1 = pd.ExcelWriter(out_file, engine='xlsxwriter')

print("Used ExcelWriter") # Don't get this print statement

data.to_excel(writer1,index=False)
print("File is written")
writer1.save()
print("Completed")

Comment: Path is correct.
Comment: @ankit Have you added this line `os.makedirs(out_path1, exist_ok = True)` and try again?
Comment: I have tried it but now `Writing excel file` is also not showing.
Comment: @ankit I've updated my code, check and try it again
Comment: Still getting same as I got initially. It is showing statement "Writing excel file" and then console gets closed. @AnhPC03
Comment: @ankit sorry about last update, I put my PC path. I've updated my code, check and try it again
Comment: No, I had changed that PATH according to my system otherwise I get error. Could you please tell me whether this code is working for you or not after converting it into exe and then run that exe file ?
Comment: Because your code did not check if the path existed or not, so it would throw FileNotFound exception


Let X and Y be jointly normal random variables with $X,Y \sim N(0, 1)$ and correlation 1/2. Eval $\mathbb{E}\left[ e^{X} \ | \ Y=1 \right]$

Question: I need help with this question: Let X and Y be jointly normal random variables with $X, Y \sim N(0, 1)$ and correlation 1/2. Evaluate $\mathbb{E}\left[ e^{X} \ | \ Y=1  \right]$.
Here's where I'm stuck: we know that:
$$
\mathbb{E}\left[ e^{X} \ | \ Y=1  \right] = \int_{ -\infty }^{\infty} e^{x} f_{X|Y}(x|1) dx
$$
And that:
$$
f_{X|Y}(x|y) = \frac{f_{X,Y}(x, y)}{f_{Y}(y)}
$$
$$
f_{X,Y}(x, y) = \frac{1}{\pi \sqrt{3}} e^{-\frac{2}{3}(x^2 + y^2 - xy)}
$$
$$
f_{Y}(y) = \frac{1}{\sqrt{2\pi}} e^{-\frac{y^2}{2}}
$$
Plugging all the numbers, I get to the following integral:
$$
\mathbb{E}\left[ e^{X} \ | \ Y=1  \right] = \sqrt{ \frac{2}{3\pi} } \int_{ -\infty }^{\infty}  e^{-\frac{1}{6} (4x^2 - 10x + 1) } dx
$$
and I don't know what's the best approach to solve it (actually any approach). Wolfram tells me that this magically solves to $e^{7/8}$. Can anyone help?
Comment: Complete the square in the exponent and then use the [Gaussian integral](https://en.wikipedia.org/wiki/Gaussian_integral).
Comment: The intuitition here is that with a joint normal distribution, X given Y is also Gaussian. So this is fundamentally the same problem as any log normal distribution.
Comment: https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Bivariate_case_2
Answer: We are told $X,Y\sim N(0,1)$ are jointly normal with correlation $\rho$.  Observe that $X-\rho Y\sim N(0,1-\rho^2)$ and $Y$ are jointly normal and uncorrelated and hence independent. Thus,
$$\begin{align}E[e^X|Y=1]&=E[e^{X-\rho Y}e^{\rho Y}|Y=1]\\
&=E[e^{X-\rho Y}e^{\rho}|Y=1]\\
&=e^{\rho}E[e^{X-\rho Y}]\quad (\text{by independence})\\
&=e^{\rho}e^{\frac{1}{2}(1-\rho^2)}\quad (\text{using MGF})\\
\end{align}.$$
For $\rho=1/2$, this simplifies to the desired solution, $e^{7/8}.$


What is the relationship between Cartan matrices and Coxeter matrices?

Question: Let $\Phi$ be a crystallographic root system. The Cartan matrix of $\Phi$ is the integer matrix $A=(a_{ij})$, where $a_{ij}=\frac{2(\alpha_i,\ \beta_j)}{(\alpha_i,\ \alpha_j)}$ for all $\alpha_i,\alpha_j \in \Phi$, and $i,j \in I$.
A group $W$ is said to be a Coxeter group if it has a presentation of the form
\begin{align}
W= \langle s_i:i\in I  |(s_i s_j)^{m(i,j)}=1,for\ all\ i,j \in I\rangle.
\end{align}
If $W=W_{\Phi}$ is a crystallographic reflection group with simple system $\alpha_1,\alpha_2,\ldots \alpha_n$ ,we note  that for $i \neq j$, if $m(i,j)=2$, then $a_{ij}=a_{ji}=0$; if $m(i,j)=3$, then $a_{ij}=a_{ji}=-1$; if $m(i,j)=4$, then $a_{ij}=-1,a_{ji}=-2$; if $m(i,j)=6$, then $a_{ij}=-1,a_{ji}=-3$.
Is this the relationship between them?
Answer: Take $m_{ij}$ such that $(\alpha_i, \alpha_j) = - |\alpha_i||\alpha_j|\cos(\pi/m_{ij})$, where $|\alpha_i|=\sqrt{(\alpha_i,\alpha_i)}$. Then $(m_{ij})$ is the Coxeter matrix. Take $c_{ij}=2(\alpha_i,\alpha_j)/(\alpha_j,\alpha_j)$. Then $(c_{ij})$ is the Cartan matrix.
For example, when $(c_{ij})=\left( \begin{matrix} 2 & -1 \\  -1 & 2 \end{matrix} \right)$. We have $(\alpha_1, \alpha_2) = -1/2$, $|\alpha_1|=|\alpha_2|=1$. Therefore $m_{12}=3$. Similary, $m_{21}=3, m_{11}=m_{22}=1$. We recover the Coxeter matrix of type $A_2$: $\left( \begin{matrix} 1 & 3 \\  3 & 1 \end{matrix} \right)$.
When $(c_{ij})=\left( \begin{matrix} 2 & -2 \\  -1 & 2 \end{matrix} \right)$. We have $2(\alpha_1, \alpha_2)/(\alpha_2,\alpha_2) = -2$, $|\alpha_1|=\sqrt{2},|\alpha_2|=1$. Therefore $(\alpha_1,\alpha_2)=-1$. Using the formula $(\alpha_i, \alpha_j) = - |\alpha_i||\alpha_j|\cos(\pi/m_{ij})$, we have $-1=(\alpha_1,\alpha_2)=- |\alpha_1||\alpha_2|\cos(\pi/m_{12})$, $m_{12}=4$.
We have $-1=(\alpha_2,\alpha_1)=- |\alpha_2||\alpha_1|\cos(\pi/m_{21})$, $m_{21}=4$.
Similary, $m_{11}=m_{22}=1$. We recover the Coxeter matrix of type $B_2$: $\left( \begin{matrix} 1 & 4 \\  4 & 1 \end{matrix} \right)$.
Answer: Dynkin diagram dertermines the Cartan matrix of crystallographic root system $\Phi$, that is, Dynkin diagram is a graph with vertices $I$ with $a_{ij}a_{ji}$ edges between $i$ and $j$.
Moreover, Dynkin diagram implies the coefficient $m(i,j)$ of $s_is_j$, see http://arxiv.org/pdf/1112.2300.pdf.


Guitar - Palm Cyst - Should I Change Hand?

Question: I started learning the guitar (left handed) as my new years resolution and am absolutely loving it.
For a couple of years, I've had a cyst in the middle of the palm of my right hand (my fretting hand). It doesn't usually bother me, but as I've been playing more and more, it really gets quite sore after playing. I'm not sure whether this is part of standard hand pain for a guitarist, or whether to be more concerned. There seems 100's of articles about wrist cysts (e.g. here), but little on issues with the palm. I need my hands to work, so need to keep them in good condition!
I've been considering changing to play right handed to try avoid aggravating the issue, but am not sure. I've tried turning my guitar upside down and although it feels awkward, I think I could manage it. I have read several accounts of left handers having issues with rhythm and fine control when changing over, but many also doing just fine. It would mean losing 8 months hard practice to virtually start again + the expense of new guitar, but it might mean I can play without "days off".
Any ideas what I should do please?
P.s. I don't consider this a duplicate because I'm not asking 'can I play right handed?', but 'given the issue with my hand; should I?'
EDIT
Following the excellent responses (upvoted): The doc won't take any action, preferring the 'wait and see' approach, however it was too painful to play, so I bought a right handed guitar.
Progress Week 1:
My wrist flexibility needs a lot of work and I need to build up some hard skin on those fresh fingertips! However, I've been surprised by how much of my learning has been theory that could quickly translate over. My right hand has rhythm as most of that seems to be in the head, though it will take a little while to start hitting the strings as nicely.
Progress week 5 (final update)
While it was undoubtedly frustrating to start, within about 3 weeks I was back to the level I was at with my left hand. Another 2 weeks on from that and I'm now considerably above where I was. I can play for long periods and my right hand doesn't bother me at all. Holding a pick is nowhere near as strenuous on the hand as fretting. It's saves me having to rethink every right handed tutorial to left handedness and there's now a larger range of guitars to choose from too :). Overall, I've been really pleased I made the change.
Comment: As a left handed person, I learned right handed. I do not have the issue that you have, but it is very convenient as most guitars are for right handed, it is easier to play with whatever guitar is where you are. I do not think these 8 months will be lost actually…
Answer: So the only reasonable thing to do is see a doctor.  I had a crippling massive cyst on my fretting hand wrist 30 years ago that I had drained by a doctor.  He used a syringe and just pulled the fluid out.  It turned out that the "massive" cyst was really about a dozen small pea sized cysts.  It was a fairly simple procedure, not very risky, and the issue NEVER came back.  My cyst was on a nerve and it made playing impossible.  At the time I was a professional (or semi-professional) musician working in bands and doing studio work while going to school.  So this could have been the death of my work.  I tried to put up with it as long as I could and changed playing style to accommodate it.  But in the end getting rid of it was the best move.  As for changing from left to right handed playing, there is no reason to expect that the cyst won't bother you.  You'll be holding onto a pic, or using your fingers to play and that will aggravate it.
Comment: Try physical therapy then.  There may be a way to tape it.  Cysts can develop for no reason at all.  But in many cases it is caused by some type of stress.  How's your technique?  Are you holding the neck too tight, palming the neck and putting the thumb over like a lot of us do?
Comment: That's a really good point about it still being a problem holding a pick/ strumming. The doc says it's too small to do anything about, so just have to put up with it for now. I'll give it another month or two and see how it fares
Answer: I've often advocated lefties playing right-handed, for several reasons, yours not being one! There may not be the need to buy a different guitar - Jimi would be testament to that.
What you have learned so far will not be wasted, a lot of it is stored in the brain, and just needs adaptation.
As we always say, a teacher is a good thing to have - he would have helped solve your problem by now, so it's a consideration for at least a few lessons. The 'net can be good...or not so! And it'll not give much advice (unlike this site, of course).
Answer: You need to change the thecnique. Chaning hands will only transfer the pain to the other hand. Playing guitar and using computer are one of the biggest sources of Repetitive Strain Injury


Python - Verificação de itens em uma lista

Question: Estou com um cenário, um pouco confuso de explicar... mas vou tentar...
Preciso comparar listA com listaB, onde caso 1 ou mais itens da listaA estejam dentro da listaB, eu printo isso na tela, mas caso na listaB tenha algum item que não esteja na listaA, nada aconteça.
As listas são parecidas com as abaixo:
dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

app1 = ['s-tcp-443', 'Domain-logon']
app2 = ['s-tcp-443', 'DNS']
app3 = ['s-udp-53', 's-tcp-80']
app4 = ['DNS']
app5 = ['s-tdp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']

dns_svc seria a listaA, enquanto que as listas appx são a listaB.
Se alguém poder dar uma sugestão.
Fiz o script abaixo, mas ele está me trazendo mais linhas do que deveria. Ele deveria me trazer 3 linhas:
app1 = ['tcp-443', 'Domain-logon']
app2 = ['tcp-443', 'DNS']
app3 = ['udp-53', 'tcp-80']
app4 = ['DNS']
app5 = ['tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
applist = [app1, app2, app3, app4, app5, app6]

dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

for i in dns_svc:
    for a in applist:
        if i in a:
            print(i)

Comment: Esses itens nas listas, eles podem se repetir dentro de cada lista ou são itens únicos dentro de cada lista?
Answer: Uma solução para imprimir os dados únicos que estão tanto na listaA e na listaB eu utilizei o set que é uma coleção de items onde não pode ter valores duplicados
Segue o código:
dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

app1 = ['tcp-443', 'Domain-logon']
app2 = ['tcp-443', 'DNS']
app3 = ['udp-53', 'tcp-80']
app4 = ['DNS']
app5 = ['tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
applist = [app1, app2, app3, app4, app5, app6]

items = set()

for i in dns_svc:
    for a in applist:
        if i in a:
            items.add(i)

for item in items:
    print(item)

o resultado após rodar o código:
junos-dns-udp
DNS
junos-dns-tcp
s-udp-53

Answer: Kaique, muito obrigado! Eu estava tentando aqui e acho que consegui tbm... Mas a sua sugestão parece ser muito mais eficiente (to começando ainda...), mais simples e mais claro :). De qualquer forma segue como eu fiz:
app1 = ['s-tcp-443', 'Domain-logon']
app2 = ['s-tcp-443', 'DNS']
app3 = ['s-udp-53', 's-tcp-80']
app4 = ['DNS']
app5 = ['s-tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
app7 = ['junos-dns-udp']
app8 = ['s-tcp-53', 'DNS']

def comparing(lst):
    dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']
    flag = True
    for ap in lst:
        if ap not in dns_svc:
            flag = False
            continue
        else:
            if flag:
                flag = True

    return flag

applist = [app1, app2, app3, app4, app5, app6, app7, app8]

for app in applist:
    a = comparing(app)
    if a:
        print(app)


Not able to redirect to a specific page on login

Question: I am trying to create django authentication but I am not able to redirect to a specific page.
Here is my urls.py file. I think the error may be in this file but I am not able to get it.
"""demo_project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from blog.forms import LoginForm

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blogs/', include('blog.urls', namespace='blogs')),
    path('login/', auth_views.LoginView.as_view(template_name='blog/login.html', authentication_form=LoginForm), name='login'),
]

The problem is on clicking the login button the url comes as http://localhost:8000/login/blogs/get_blogs instead of http://localhost:8000/blogs/get_blogs/.
Here is the settings.py file.
"""
Django settings for demo_project project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5c^1lok8qf$x0vo-ey3iuzksgh!#7$x&!0x*tb0!6-odgk8p(3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'blog.apps.BlogConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'demo_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'demo_project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
LOGIN_REDIRECT_URL = 'blogs/get_blogs'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

As you can see that I have set LOGIN_REDIRECT_URL = 'blogs/get_blogs' but still this issue is coming.
[Here is the link to the git repository] (https://github.com/AnshulGupta22/demo-project)
I am new to django so some help will be appreciated.
Comment: You need to use `LOGIN_REDIRECT_URL = '/blogs/get_blogs'`. Without the leading slash, it is relative to the login url.
Answer: You are working with a relative URL. But it is likely better to here work with the name of the path, so set the LOGIN_REDIRECT_URL setting [Django-doc] to:
# settings.py

LOGIN_REDIRECT_URL = 'blog:get_blogs'


Reduce Size of Standard Persistent Disk of 500GB to 50GB?

Question: I have a VM instance running on Windows Server. It has a SPD of 500GB. I couldn't reduce it. I can only enlarge this. This happen because I am having an impression that if Digital Ocean can increase/decrease, then Google Compute should be able to do the same. I am totally wrong.

How can I reduce the size? Is there any easier way to do so?
Will the feature available soon?

Any advise are greatly appreciated.
Answer: Cloud providers generally only allow disk expansion, disallowing disk shrinking. This is done because, when shrinking disks, data loss is a very probable outcome.
If you need a smaller disk, the better option probably is to spin up a new VM/disk, then migrate your data to it.
Comment: Thank you for the feedback. I am thinking of create a new smaller SPD and migrate the data there. But, I am not sure how to do it. My VM is now running on single SPD (500GB).


How to check that I'm dealing with a list in Haskell?

Question: I'm learning Haskell, and I'm trying to add preconditions to a (trivial, as an exercise) element_at function (code below). I've created a "helper" elem_at_r because otherwise, len x fails at some point (when x is a 'literal' rather than a list? - I still have trouble parsing ghci's error messages). elem_at now has all the error checking, and elem_at_r does the work. In elem_at, I'd like to add a check that x is indeed a list (and not a 'literal'). How can I do that?
len x = sum [ 1 | a <- x]

elem_at_r x n | n == 0     = head x
              | 0 < n      = elem_at_r (tail x) (n-1)

elem_at x n | x == []    = error "Need non-empty list"
            | len x <= n = error "n too large " ++ show (len x)
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n

Thanks!
Frank
Comment: Wait, wat? The type system will make sure it's a list. `len :: [a] -> a` so `x` must be `[a]`, i.e. a list. If it isn't, that's a compiletime error. And unlike some much-despised functions, `len` won't throw an `error` for *any* list - why would it?. Please specify "len x fails".
Comment: Could you please paste the error message you cannot parse? I could help you deciphering it. That you get an error message when you pass something else than a list is expected - The error message probably just tells you that GHCi can't figure out how the input can be a list.
Comment: And BTW, all your error-conditions are special cases of the second one.
Comment: The error message was ghci complaining with me calling elem_at with 3 and 3: elem_at 3 3. Now I understand, the type system is catching that the first '3' is not a list. If I had been compiling, the compiler would have stopped me, right?
Answer: Due to Haskell's type system, elem_at can only take a list as its first argument (x); if you try to pass a non-list, GHC will detect this and give an error at compile time (or interpretation time in GHCi).  I don't know why len would "fail"; could you post the error message that GHCi gives you?
Comment: Many times I put in signatures if I can't understand the errors ghci / ghc gives me. Once I fix the errors, I can (but usually don't) do away with the signatures. One advantage of removing the signatures is that ghc can sometimes make the function general enough that it works for more types than you envisioned. For example, if the signature of elem_at was "elem_at [Int] -> Int" and you remove it, the function magically works on all lists, not just Int's.
Comment: @Frank: Think of the type signatures as telling GHC what you're expecting something to be. That way, if you're wrong, it will tell you what expectation was violated, instead of just trying its best to find something that works and then complaining wherever it gets stuck.
Comment: :-) - got it. I thought I could dispense with types to make the code more concise but I see everybody is telling me they are useful :-)
Comment: More specifically, it's an example of [Type Inference](http://www.haskell.org/haskellwiki/Type_inference)
Comment: Please bear with me, I'm a beginner at Haskell :-) "Fail" was probably not the right word. Here is the original code and the ghci error message I'm seeing: elem_at x n | x == []    = error "Need non-empty list"
            | len x <= n = error "n too large " ++ show (len x)
            | n < 0      = error "Need positive n"
            | n == 0     = head x
            | 0 < n      = elem_at (tail x) (n-1)
Comment: Sorry for the formatting: *Main Data.Typeable> elem_at [1,2,3] 2

:1:14:
    No instance for (Num [Char])
      arising from the literal `3'
    Possible fix: add an instance declaration for (Num [Char])
    In the expression: 3
    In the first argument of `elem_at', namely `[1, 2, 3]'
    In the expression: elem_at [1, 2, 3] 2
Comment: @Frank: Were you trying to use the return value of `elem_at [1,2,3] 2` as a `String` (a type synonym for `[Char]` which the literal value `3` cannot be converted to implicitly)?  Without more code and/or context, that's the only explanation for the error I can think of.
Comment: I'm just on the command line in ghci trying my trivial function to see if I coded the exercise properly. That's the context, it's not part of a larger program that would try to use the returned value.
Comment: @jwodder: if you put in function signatures you'll get a more useful error message....
Comment: Tim - I rewrote the code with your pattern matching and type signatures, and I can't load the function anymore... Couldn't match type `a' with `[Char]'
      `a' is a rigid type variable bound by
          the type signature for elem_at :: [a] -> Int -> a
          at exercise-99-1.hs:36:1
    In the expression: (error "n too large " ++ show (len x))
Comment: @Frank: Check your indentation. I just cut-n-pasted the code from my post into a file and it worked.
Comment: @Frank: generally I write my functions in a file and load them into ghci using ":l ". Trying to cut-n-paste my code directly into ghci will lead to errors. It is possible if you add some curly brackets and have patience. I don't have patience so I use ":l". There is a post either on stack overflow or in the Haskell Beginners mailing list telling how to do it the other way
Answer: It looks like you were getting errors because of the "x == []" line. The code below pattern matches for that condition and adds a few signatures. Otherwise it is the same. Hope it helps.
len x = sum [ 1 | a <- x]

elem_at_r :: [a] -> Int -> a
elem_at_r x n | n == 0     = head x
              | 0 < n      = elem_at_r (tail x) (n-1)

elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n

You could also make your helper functions part of this function using a where clause:
elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n
  where
    len :: [a] -> Int
    len x = sum [ 1 | a <- x]

    elem_at_r :: [a] -> Int -> a
    elem_at_r x n | n == 0     = head x
                  | 0 < n      = elem_at_r (tail x) (n-1)

Comment: @Frank: Sorry, nope. It's basically `function_name [pattern_matches] | boolean_predicate = expression`. However, if the predicates don't handle all cases, it will fall through to the next pattern match, so you can still use guards to select which matches you want, in a way.
Comment: Just an extra question: adding type signatures is nice for documentation, but it works without, and I like concise code. Can I dispense with writing those type signatures?
Comment: Thanks for the speedy replies! Greatly helps!
Comment: One more thing, I can't pattern match [] _ right after a |, right? - IMHO, it would be cuter.
Comment: You know, I don't know about that pattern match. You might consult Real World Haskell or Learn You a Haskell for Great Good.
Comment: Type signatures tend to force GHC (and ghci) to give more useful errors. However, no, they are not necessary.
Comment: I'm in the middle of reading those 2 references. I thought I could do some Prolog-like "pattern matching" anywhere. Thanks a lot for the answers.
Comment: @camccann: thanks. I was going to say that but I wasn't positive.
Comment: Yes, I realized that. I wanted to do pattern matching inside the boolean predicate, i.e. have the predicate return a true/false value AND bind x and xs in (x:xs) for me... I'm guessing that's not in line with Haskell's philosophy (no side-effects?)?
Comment: That is, if the pattern matches, it's a "true", if it doesn't it's a "false" - I'm guessing Haskell won't have any of that kind of reasoning :-)
Comment: Well, you can only pattern match on constructors and the pattern (x:xs) means there is a value "x" that is cons'd ":" onto a list. But if you have an empty list, there is no value cons'd onto a list. Note the list in "xs" can be either empty [] or a value cons'd onto the rest of the list.
Comment: @Frank: How does that differ from just pattern matching? If you have `elem_at (x:xs) n = ...` then it will either match the `:` constructor and bind `x` and `xs`, or it will fail to match (i.e., if you give it `[]`) and fall through to the next pattern.
Comment: @Frank: As a more explicit example, your two definitions for `elem_at_r` could be written as `elem_at_r (x:_) 0 = x` and `elem_at_r (_:xs) n | 0 < n = elem_at_r xs (n - 1)`
Comment: Yes, makes sense. I was experimenting with the syntax, and wanted to have everything under a single "heading", using | to provide all the alternatives.
Comment: @camccann: I like your solution very much.


an issue in Assembly using Emu 8086 , jump not working

Question: i just start on making my project for university for  flipping card game,
using emulator from emu8086.com
sadly i got stuck on such a early stat .
somehow can't quite figure out whats wrong .
the jump using JZ or JE , should work if i use cmp on 2 equal value , but it is not working .
nothing happening ! i used
mov ah,1
int 21h

cmp al,1 or cmp al,'1'
JE or JZ  Card1

but it is not jumping no matter what i write ,
my full code :
include "emu8086.inc"
; multi-segment executable file template.

data segment
     ; add your data here!
     pkey db "press any key...$"
     data_error dw "input error....    $"
     datar db 0      ;row
     datac db 0      ;cloumn
     datacard db '1','2','3','4','5','6','7','8','9'
     data1 dw ?
     data2 dw ?
     dataf dw "False              $"
     endapp dw "END GAME....              $"
     datat dw "True               $"
     datas db '0'
     score dw "Score : $"
     x db ?
     y db ?
     a db '0','0','0','0','0','0','0','0'
     data3 db 'D','B','A','O','C','C','A','B','D'

ends

stack segment
    dw   128  dup(0)
ends

code segment
start:
; set segment registers:
    mov ax, data
    mov ds, ax
    mov es, ax

    ; add your code here

GOTOXY 25,0
;PRINT 'Wellcom to My Flipping Game !?!'
GOTOXY 10, 5
mov si,offset data3
PUTC [si]
GOTOXY 15, 5
inc si
PUTC [si]
GOTOXY 20, 5
inc si
PUTC [si]
GOTOXY 10, 8
inc si
PUTC [si]
GOTOXY 15, 8
inc si
PUTC [si]
GOTOXY 20, 8
inc si
PUTC [si]
GOTOXY 10, 11
inc si
PUTC [si]
GOTOXY 15, 11
inc si
PUTC [si]
GOTOXY 20, 11
inc si
PUTC [si]

GOTOXY 10, 5
mov si,offset datacard
PUTC [si]
GOTOXY 15, 5
inc si
PUTC [si]
GOTOXY 20, 5
inc si
PUTC [si]
GOTOXY 10, 8
inc si
PUTC [si]
GOTOXY 15, 8
inc si
PUTC [si]
GOTOXY 20, 8
inc si
PUTC [si]
GOTOXY 10, 11
inc si
PUTC [si]
GOTOXY 15, 11
inc si
PUTC [si]
GOTOXY 20, 11
inc si
PUTC [si]

GOTOXY 25, 15

Print 'Enter your Selection : '

mov ah,1
int 21h

mov ah,al

cmp ah,1
JZ card1

cmp ah,2
JE card2

cmp ah,3
JE card3

cmp ah,4
JE card4

cmp ah,5
JE card5

cmp ah,6
JE card6

cmp ah,7
JE card7

cmp ah,8
JE card8

cmp ah,9
JE card9

JMP deadend

card1 :

GOTOXY 10, 5
mov si,offset data3
PUTC [si]
JMP deadend

card2 :

GOTOXY 15, 5
mov si,offset data3
inc si
PUTC [si]
JMP deadend

card3 :

GOTOXY 20, 5
mov si,offset data3
inc si
inc si
PUTC [si]
JMP deadend

card4 :

mov si,offset data3
inc si
inc si
inc si
PUTC [si]
JMP deadend

card5 :

mov si,offset data3
inc si
inc si
inc si
inc si
PUTC [si]
JMP deadend

card6 :

mov si,offset data3
inc si
inc si
inc si
inc si
inc si
PUTC [si]
JMP deadend

card7 :

mov si,offset data3
inc si
inc si
inc si
inc si
inc si
inc si
PUTC [si]
JMP deadend

card8 :

mov si,offset data3
inc si
inc si
inc si
inc si
inc si
inc si
inc si
PUTC [si]
JMP deadend

card9 :

mov si,offset data3
inc si
inc si
inc si
inc si
inc si
inc si
inc si
inc si
PUTC [si]
JMP deadend

deadend:

    lea dx, pkey
    mov ah, 9
    int 21h        ; output string at ds:dx

    ; wait for any key....
    mov ah, 1
    int 21h

    mov ax, 4c00h ; exit to operating system.
    int 21h
ends

end start ; set entry point and stop the assembler.

i left the sample codes from making a new file in emulator in my code , will remove them later.
u see i put AL into AH and used it too , just coz i couldn't  figure whats wrong ,
but it didn't work when i used AL itself in cmp either
non of the JE / JZ jumps work , only the JMP one work .
Tnx.
Comment: You should be comparing against `'1'..'9'`, not `1..9`. Anyway, reduce this down to a program where you've removed everything except the code to read a character and print something if the character equals whatever value (let's say `'1'`). That should make it easier for you to find the problem.
Comment: damn net was down for 2 hours , anyway , i did check it with '1' '2' and '9' too , still no result.
Answer: Fixed it , Quite Silly ,
The Problem was just that i was puting an space before : of my lable ! lol
like
card1 :

..... while it should have been
card1:

i also change back my code to use AL for everything , and put ' ' on the numbers.


General solution to diffeerential equation

Question: Given the differential equation $$\frac{dy}{dt}=\frac{4t}{1+3y^2}$$ is this the general solution?  $$y+y^3=2t^2+c$$  Can we continue to simplify it?
Comment: Yes. It is the solution. Well done :). You could solve for y, but that will look more ugly.
Answer: Often the solution of a problem can be expressed on several forms. If the wording of the problem do not specify what kind of form is expected, your answer $y+y^3=2t^2+c$ is an implicit form which is a correct form of answer.
of course, other forms can be proposed :
$$t=\pm\sqrt{\frac{1}{2}(y+y^3-c)}$$
which gives the inverse function $t(y)$. It is not specified in the wording of the question what function is wanted $y(t)$ or $t(y)$.
On can also solve $y+y^3=2t^2+c$ for $y$ and express the result on parametric form:
$$y=\frac{1}{3}z-\frac{1}{z}$$
$$z=\left(x\pm\sqrt{x^2+27}  \right)^{1/3}$$
$$x=\frac{27}{2}(2t^2+c)$$


Differentiating $\mbox{tr} (ABA^TC)$ w.r.t. $A$

Question:
Why is $\nabla_A \mbox{tr} (ABA^TC) = CAB + C^TAB^T$?

Here $A, B, C, D$ are all $n \times n$ matrices.
$$\nabla_A f(A) = \left[\begin{matrix}
\frac{\partial f}{\partial A_{11}}... \frac{\partial f}{\partial A_{1n}}\\
...\\
\frac{\partial f}{\partial A_{n1}}... \frac{\partial f}{\partial A_{nn}}\\
\end{matrix}\right]$$
I tried to prove it in this way:
$$\begin{align}
\nabla_A \mbox{tr} (ABA^TC) &= \nabla_Atr (BA^TC)A\\ &= \nabla_A \mbox{tr} DA ......let  \ D=BA^TC\\ &= \nabla_A \mbox{tr} AD\\ &=D^T\\ &=B^TAC^T\end{align}$$
Since $B^TAC^T \neq CAB + C^TAB^T$, there must be something wrong in my derivation. How to prove this property?
Comment: Your mistake was to neglect that $A^T$ (hidden in your $D$) also depends on $A$. You treated it as a constant.
Answer: $$tr(ABA^TC)=\sum_{ijkl}A_{ij}B_{jk}A^T_{kl}C_{li}=\sum_{ijkl}A_{ij}B_{jk}A_{lk}C_{li}$$
$$(\nabla_{A}tr(ABA^TC))_{mn}=\frac{\partial}{\partial A_{mn}}\sum_{ijkl}A_{ij}B_{jk}A_{lk}C_{li}$$
$$=\sum_{ijkl}B_{jk}A_{lk}C_{li}\delta_{im}\delta_{jn}+\sum_{ijkl}A_{ij}B_{jk}C_{li}\delta_{lm}\delta_{kn}$$
$$=\sum_{kl}B_{nk}A_{lk}C_{lm}+\sum_{ij}A_{ij}B_{jn}C_{mi}$$
$$=\sum_{kl}C_{lm}A_{lk}B_{nk}+\sum_{ij}C_{mi}A_{ij}B_{jn}$$
$$=\sum_{kl}C^T_{ml}A_{lk}B^T_{kn}+\sum_{ij}C_{mi}A_{ij}B_{jn}$$
$$=(C^TAB^T)_{mn}+(CAB)_{mn}$$
$$\nabla_{A}tr(ABA^TC)=C^TAB^T+CAB$$
Comment: @ Cesc Fangs , you are wrong. It is the worst answer.
Comment: found this answer most easy to follow
Answer: Given $\mathrm A, \mathrm B, \mathrm C \in \mathbb R^{n \times n}$, define $f : \mathbb R^{n \times n} \to \mathbb R$ by
$$f (\mathrm X) := \mbox{tr} (\mathrm A \mathrm X \mathrm B \mathrm X^T \mathrm C)$$
The directional derivative of $f$ in the direction of $\mathrm V$ at $\mathrm X$ is
$$\begin{array}{rl} D_{\mathrm V} f (\mathrm X) &= \displaystyle\lim_{h \to 0} \frac{1}{h} \left( f (\mathrm X + h \mathrm V) - f (\mathrm X) \right) \\\\ &= \mbox{tr} (\mathrm A \mathrm V \mathrm B \mathrm X^T \mathrm C) + \mbox{tr} (\mathrm A \mathrm X \mathrm B \mathrm V^T \mathrm C)\\\\ &= \mbox{tr} ((\mathrm A^T \mathrm C^T \mathrm X \mathrm B^T)^T \mathrm V) + \mbox{tr} (\mathrm V^T \mathrm C \mathrm A \mathrm X \mathrm B )\\\\ &= \langle \mathrm A^T \mathrm C^T \mathrm X \mathrm B^T , \mathrm V \rangle + \langle \mathrm V, \mathrm C \mathrm A \mathrm X \mathrm B \rangle\\\\ &= \langle \mathrm A^T \mathrm C^T \mathrm X \mathrm B^T + \mathrm C \mathrm A \mathrm X \mathrm B, \mathrm V \rangle\end{array}$$
Hence,
$$\nabla_{\mathrm X} f (\mathrm X) = \mathrm A^T \mathrm C^T \mathrm X \mathrm B^T + \mathrm C \mathrm A \mathrm X \mathrm B$$
If $\mathrm A = \mathrm I_n$, then
$$\nabla_{\mathrm X} f (\mathrm X) = \color{blue}{\mathrm C^T \mathrm X \mathrm B^T + \mathrm C \mathrm X \mathrm B}$$

matrix-calculus scalar-fields gradient
Answer: If you write the function in terms of the Frobenius Inner Product, then finding the differential and gradient is almost trivial
$$\eqalign{
 f &= C^TAB^T:A \cr\cr
df &= C^T\,dA\,B^T:A + C^TAB^T:dA \cr
   &= (CAB + C^TAB^T):dA \cr\cr
\frac{\partial f}{\partial A} &= CAB + C^TAB^T \cr\cr
}$$
Frobenius products can be rearranged in a variety of ways
$$\eqalign{
 A:BC &= AC^T:B \cr
   &= B^TA:C \cr
   &= A^T:(BC)^T \cr
   &= BC:A \cr
   &= {\rm tr}(A^TBC) \cr
}$$
all of which can proved directly, or by using the trace-equivalence and the cyclic property of the trace.
Comment: @aroma The differential of a product is $$d(X\star Y) = dX\star Y+X\star dY$$ This simple rule holds for almost any type of product (e.g. matrix, hadamard, kronecker, frobenius, dyadic) that you are likely to encounter.   In the current problem, take $X=C^TAB^T$ and $Y=A$ and $(\star) = (:) $
Comment: I don't understand how is $df = (C^T)dA (B^T) : A + (C^T) A B^T : dA$


Como gerar um numero sequencial automatico no C#

Question: Boa tarde..
Tenho um txtbox1.Tex no meu formulário, e preciso gerar um numero sequencial de 2 dígitos automaticamente. EX 01, 02, 03 e assim sucessivamente, e mostra no txtbox.
Alguém poderia me ajudar.
Obrigado.
Comment: Poderia postar oque já foi desenvolvido?
Answer: No formulário:
private int _contador = 0;

No método no qual você vai alterar o texto:
this._contador++;
this.txtBox1.Text = this._contador.ToString().PadLeft(2, '0');

O método PadLeft da classe String recebe dois parâmetros. O primeiro diz o comprimento mínimo que você deseja ter, e o segundo diz com qual caractere você vai fazer preenchimento à esquerda.
Comment: Renan muito obrigado, resolvido parte do meu problema agora preciso dar sequencia no código. vlw
Answer: Cria um metodo do Genero
private void Gerar()
{
  // Gerando Código Incremento
   this._contador++;
   this.Codigo.Text = this._contador.ToString().PadLeft(2, '0');
 }

no Lod
 private void Cliente_Load(object sender, EventArgs e)
  {

            Gerar();

  }


Python - Ignorar valores NaN em um .csv e somar o resto

Question: Olá,
Tenho um arquivo .csv que estou tentando passar pra json
Produtos      Quantidade
    Bala          50
    Refri         NaN
    Salgado       25

E estou importando pra um json, queria saber como ignorar os valores NaN e retornar a soma.
Este é o codigo:
df = pd.read_csv(r"quantida.csv", sep=";")

totalQuantidade = sum(data['Quantidade'])

dataJSON = {
        "Volume": totalQuantidade
    }
#Escrever no JSON
with open('estoque.json', 'w') as jsonFile:
       jsonFile.write(json.dumps(dataJSON, indent=4))
print('Concluído')

Answer: Utilizando o método sum, podes especificar o valor do parametro skipna para excluir NaNs:
totalQuantidade = df['Quantidade'].sum(skipna=True)


Can TableSort be used without a query?

Question: In my module, I'm using TableSort for some of my tables, but I also have some tables that are generated by code, so not directly linked to a query. These tables are also created with theme('table') and so have the $header and $rows arrays. Is it possible to use TableSort on those as well, maybe with writing my sorting function?
The documentation for tablesort.inc seems to suggest it is possible (All tables created with a call to theme('table') have the option of having column headers that the user can click on to sort the table by that column). However, I haven't found any instructions or example on how to do this. Everything I found so far is based on a query. I'm using Drupal 7.
Comment: Here is the Drupal 8 version of this question: https://drupal.stackexchange.com/questions/300620
Answer: Thanks to Berdir I got it working. This is how it works in more detail.
Tablesort is triggered "automatically" if the (column) arrays in the $headers array contains the keys 'data', 'field' and optionally 'sort'. This will create links with 'sort' and 'order' in the column headers and show the little arrow and such.
To do your own sorting, get the current sort settings with tablesort_get_order and tablesort_get_sort and use those values for your own sorting function. The key 'sql' in the array returned by tablesort_get_order contains the field name to be used for sorting.
A piece of (untested) example code with the array $users containing some details for each user:
<code>// setup the table data that we want to show
$tableData = array();
foreach ($users as $userDetails) {
  $tableData[] = array(
      'name' => $userDetails['name'],
      'visits' => $userDetails['visits'],
      'views' => $userDetails['views'],
      'comments' => $userDetails['comments']
  );
}

// headers array, sorting by default on comments
$headers = array(
    array('data' => t('Name'), 'field' => 'name'),
    array('data' => t('Visits'), 'field' => 'visits'),
    array('data' => t('Views'), 'field' => 'views'),
    array('data' => t('Comments'), 'field' => 'comments', 'sort' => 'desc')
);

// getting the current sort and order parameters from the url
$order = tablesort_get_order($headers);
$sort = tablesort_get_sort($headers);

// sort the table data accordingly (write your own sort function)
$tableData = my_array_sort($tableData, $order['sql'], $sort);

// create the array with rows for theme table
$rows = array();
foreach ($tableData as $entry) {
  $rows[] = array(
      array('data' => $entry['name']),
      array('data' => $entry['visits']),
      array('data' => $entry['views']),
      array('data' => $entry['comments']),
  );
}

// add any attributes and sent everything to theme table
$attributes = array('class' => array('my_class'));
$table = array('header' => $headers, 'attributes' => $attributes, 'rows' => $rows);
$html = theme('table', $table);
</code>
Comment: https://stackoverflow.com/a/19454643/763010 helped me here with the `write your own sort function`.
Answer: Tablesort actually consists of two different systems which work together.
The first part is the rendering, the stuff that happens directly within theme_table() or is called from that. All it does is display the table headers with the sort indication if a default sort or override through $_GET is present and makes them links so that you can click on them.
The second part is the TableSort query extender, that adjusts the query it is added on based on the default sort direction or the $_GET override.
These two systems are actually pretty separated, the just work together easily because they get their data from the same $header structure and use the same helper functions and naming conventions for the $_GET parameters. But nothing stops you from using only one of these.
To actually answer your question, if you just need the rendering part, you just need to make sure to do something similar to TableSort::orderbyHeader(). Instead of the orderBy() call, you'd use a array sort function, or pass it as an argument to a web service or anything else.
And for the opposite, you'd just need to make sure that you display a link that is basically the equivalent of tablesort_header() so that it is recognised by the TableSort query extender.
Comment: Thank you for pointing me in the right direction, I got it working now. For those trying to achieve the same, I put my steps in a separate answer as it doesn't fit in a comment field.
Answer: Here is the code that i ended up on the answer of whiskey. It uses entity field query.
<code> $query = new EntityFieldQuery();
  $query
  ->entityCondition('entity_type', 'vehicle')
  ->entityCondition('bundle', 'car');
  $result=$query->execute();
  $ids=array_keys($result['vehicle']);
  $values=entity_load('vehicle',$ids);
  $rows=array();
  foreach($values as $val){
    $rows[]=array('data'=>array(
      'id'=>$val->id,
      'title'=>$val->title,
      'price'=>$val->field_price['und'][0]['value'],
      'model'=>$val->field_model['und'][0]['value'],
      'color'=>$val->field_color['und'][0]['value'],
      'speed'=>$val->field_speed['und'][0]['value'],

    ));
  }

  // We are going to output the results in a table with a nice header.
  $header = array(
    // The header gives the table the information it needs in order to make
    // the query calls for ordering. TableSort uses the field information
    // to know what database column to sort by.
    array('data' => t('Entity Id'),'field' => 'id'),
    array('data' => t('Title'),'field' => 'title'),
    array('data' => t('Price'),'field' => 'price'),
    array('data' => t('Model'),'field'=>'model'),
    array('data' => t('Color'),'field'=>'color'),
    array('data' => t('Speed'),'field'=>'speed'),

  );

  $order = tablesort_get_order($header);
  $sort = tablesort_get_sort($header);
  $sql=$order['sql'];
  if($sort=='desc') {

    usort($rows, function($a, $b) use($sql) {
    return $a['data'][$sql] > $b['data'][$sql]? -1 : 1;

  });

  }
  if($sort=='asc') {
      usort($rows, function($a, $b) use ($sql) {
        return $a['data'][$sql] < $b['data'][$sql]? -1 : 1;
      });
  }

  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));

  return $output;
</code>

Can TableSort be used without a query?


Post becomes unpublished upon editing it and no additional date values or image uploads are possible

Question: I have a custom content with a large number of multivalue date fields (around 200-300 values). I created a node and added a large number of dates. When subsequently editing the post, the following occurs:

The post is saved as unpublished
Changes to the body field and other text fields such as tags are saved
No additional dates can be saved
Clicking on Preview doesn't show a preview, but saves the post as unpublished
Upon attempting to upload an image file, the Drupal message "[content-type] [post-title] has been updated" (with the specific values in place of the [...] placeholders) appears, but it appears BEFORE clicking Save; upon saving the post, no file is saved
"The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved." appears when clicking Save after the file upload
The node can be made Published from the content administration screen (but not from editing it individually)
The Revision tab is missing even though the content type has revisions enabled by default
The Authored on date is reset to the first time the node become unpublished

I would like to have some instructions as to how to debug this situation.
PS: The site is hosted on Hostgator.com.
Comment: There's only one way to debug that really - change the theme to rule that out, then disable contrib/custom modules methodically until you find the culprit. Or step through with a debugger, of course
Comment: What if the high number of multiple date values have to do with the form data not being saved correctly? I tried to print the $_POST data to screen but I discovered that it is always an empty array on save even in normal cases ($_POST shows data on Preview but not on Save in normal cases). The site is live and I cannot disable modules that easily.
Comment: I wouldn't have thought so; either you're exceeding the max POST size or you're not, you wouldn't expect some of those fields to save and others not to if it's just a size problem. Plus the node and fields are saved in a transaction, which should be rolled back if any part fails (or at the very least not committed)
Answer: I was having a similar problem when editing a node with a field that allowed for unlimited field collection values. Each field collection had 8 input fields, and after adding in over 100 field collection items it stopped adding in more and it would unpublish on Save.
I could publish it from the content administration screen.
I modified max_input_vars in the server php.ini file from max_input_vars=1000 to max_input_vars=2500 and that allowed for the addition of more field collection items and to keep the node published when saved.


Como pegar dados de relacionamento hasMany

Question: Eu tenho uma tabela Grupo e uma Topicos, onde o grupo tem muitos tópicos e está assim meu código:
public function topicos()
{
    return $this->hasMany('App\Topico');
}

No meu Controller está assim:
public function grupo($slug)
{
    $grupo = Grupo::where('slug', $slug)->first();
    return view('grupo', compact('grupo'));
}

No entanto, dessa maneira eu não consigo acessar acessar os dados das duas tabelas através de um único foreach, eu gostaria de pegar os dados assim:
$grupo->topicos->titulo

mas isso não funciona e ao invés de usar first() eu tenho que usar get() e depois fazer dois foreach pra poder pegar todos os dados.
O problema é que tem várias partes do código que eu preciso inserir apenas o id do grupo, e ter que fazer um foreach só pra isso me parece desnecessário.
Answer: No seu código e na sua pergunta tem explicitamente dito uma relação 1:N (um para muitos), sendo que grupo tem vários tópicos e um tópico é de um grupo. No site tem várias explicação de como funciona essa relação, exemplo:

Problemas com relacionamento um para muitos laravel
Como usar o relacionamento hasmany no laravel 5.2?
Como mudar a palavra chave de relacionamento do laravel

sendo que o modo das suas configurações não estão presente como informações na sua pergunta e eu imagino que as suas configurações de relação estejam corretas:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Grupo extends Model
{
    public function topicos()
    {
        return $this->hasMany('App\Topico','grupo_id', 'id');
    }
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Topico extends Model
{
    public function grupo()
    {
        return $this->belongsTo('App\Grupo','grupo_id', 'id');
    }
}

esse exemplo de relação que imagino ser a sua.
Para buscar os items da relação de Grupo com Topicos:
$grupo = Grupo::with('topicos')->where('slug', $slug)->first();

terá os itens de grupo e na relação de tópicos uma coleção, e é assim que foi configurado, mas, se quiser trazer na relação apenas um tópico também dá (eu entendi que você precisa trazer apenas um tópico achei isso estranho, mas, existe a possibilidade de fazer um filtro na relação e limitar o número de itens retornados), exemplo:
$grupo = Grupo::with(['topicos' => function($query){$query->limit(1);}])
    ->where('slug', $slug)->first();

e para recuperar mesmo trazendo um item da coleção (que seria bom por causa do desempenho, por trazer só o que precisa):
{{ $grupo->topicos[0]->titulo }}

porque o que vale nisso tudo é a relação sendo que tópicos sempre gera uma lista, mas, com esse código acima restringe apenas um item a ser trazido na SQL.
Observação: também é bom lembrar que o carregamento adiantado feito com with é otimizado, gerando no caso duas SQL o contrário se for feito o carregamento em tempo de execução é ruim por gerar em cada interação uma instrução SQL para o banco de dados.
Comment: é bem isso que precisava entender. No meu caso, eu preciso pegar todos os topicos de um grupo e exibir. É uma especia de forum de discusão. Mas sua explicação me fez compreender melhor o que estou fazendo. Muito obrigado


NoSQL vs Other SQL Drupal Setups

Question: What are the advantages of running NoSQL (ex MongoDB) over MySQL, PostGRE SQL or MSSQL in Drupal? Are the advantages gained from simply using the storage or does some Drupal configuration need to change?
Comment: This is a question to which Károly Négyesi would give an "authoritative" answer. He surely knows the advantage of using MongoDB with Drupal.
Comment: Read my mind.. very interested in other options if there is substantial benefits, and of course the pros come with cons.
Answer: MongoDB can be used to store most or all your entities into fast, document-oriented storage. This type of storage scales way better then the standard SQL based storage we have in Drupal core (which is based on a "one table per field" schema).
In the current state of Drupal 7, you would have:

The base table of the entity stored on SQL (ie. the users table, the node table, etc.)
All fields stored in SQL
The properties of the entities from their base tables duplicated in MongoDB

This allows fast querying on the entities on MongoDB, and the ability to add complex indexes that no Opensource SQL database support (including indexes across tables). At the same time, you don't lose interoperability because the base table of the entity is still stored in SQL and can thus be joined by modules that are still SQL-only (like Flag).
This type of fast querying is available thanks to the EntityFieldQuery mechanism, a way to build queries on entities, their properties and their fields in an abstract manner. The default implementation in core translate those queries to SQL, but the MongoDB module has a full-featured implementation that can satisfy those queries from MongoDB directly.
Thanks to the EntityFieldQuery backend for Views, you can easily leverage this power, by using the tools you are used to. The only downside is that relationships are not supported (but in practice you rarely need them anyway - and this can be worked-around by pushing additional data into the entity object and add exposing them as additional properties of the entity).
In a nutshell, as soon as query performance is a problem on your project, which happens as soon as you have a significant dataset (let's say starting at a few tenth of thousands of entities on a given entity type), MongoDB is a net gain for very very few drawbacks. Highly recommended.
Comment: No module should expect the fields to be in MySQL. The only way to query fields on Drupal 7 is EntityFieldQuery. Open a bug in the module if it is querying the field tables directly. I don't know any of those modules at this time.
Comment: I think you are underselling the cons a little. Modules which join on the entity itself will work, but modules which expect the fields to be in Mysql will not.
Comment: Can you expand on "relationships are not supported"? Do you mean node/term/user reference fields? or relationships in the database directly? some clarity would be great for us non-db-pros
Comment: Damien Tournoud: If you experience performance problems with only a few tenth of thousands entries, then there probably is an underlaying problem (DBMS configuration, poorly written queries, it can be anything).

If the underlaying SQL schema is good enough, you shouldn't have to worry before a million entries on a single table (but fields can grow fast if you consider revisions and multi-valued fields probably).
Comment: My point exactly: our schema is normalized, and as a consequence has very poor querying performance. To improve query performance, you need to denormalize the schema. The main advantage of using MongoDB in our case is that it is some sort of "automatic denormalization engine".
Comment: And of course, MongoDB is great here because it is a document oriented database. Storing complex documents like entities in SQL storage is just plain stupid. It is our default implementation, but it doesn't mean you should use it :)
Comment: @Pierre: Damien talked about a few tenth thousand *entities*, which can be a completely different thing than table rows. For example, you could have 10 or more fields on that entity, then you have 10 additional tables that needs to be queried with a separate query every time such an entity is loaded. And MongoDB can replace these additional tables, not the entity base table.
Comment: @Berdir, I agree. @Damien: Not sure about the fact a normalized schema is that Evil, in fact it helps understanding it. A good normalization can also the base of a good import/export handling. Some of the Relational Model and normalization concept goals were at a time to achieve the best performances while avoiding data redundancy.
Comment: @Damien you are right about the fact that data denormalization is often made for performance reasons. I'd take a look at MongoDB module, it seems promising. Further, doesn't it create a new latency in the whole system by querying another storage engine (you have to maintain two connections) ?
Comment: @Pierre: I never said that a normalized schema is evil. I said that you need some form of de-normalization as soon as you need some decent query performance. At this point either you manually maintain de-normalized tables (for example via the Materialized Views module) or you adopt a real document oriented database like MongoDB, which does not need de-normalization.
Answer: MongoDB and similar are designed to store structured (hierarchical) data in a relatively flexible way.
For example in Drupal 7, when using field_sql_storage, every field gets it's very own tables. When you attach 10 fields to a content type, you end up with 10 tables in your database. When you load that node, field_sql_storage will execute a query per field and per node (or multiple nodes, when using node_load_multiple).
When you use mongodb_field_storage, you can store all fields of a node in a single document and get with a single query.
You can also store other things like watchdog, sessions, cache, blocks in MongoDB.
You still need MySQL however, MongoDB doesn't replace it (only for specific parts).
Another advantage is that it is easier with MongoDB to scale, you can add many servers to a cluster share the data between them.
Comment: Well, for a start, you can't just drop it in. Each field has configured which storage backend it uses you will have to change/re-create your fields, re-create your views (as they need to use the efq_views backend), maybe your own queries if you wrote direct queries against the field data tables. Might be easier to re-create the same structure in a new installation for an initial comparison.
Comment: Hi Berdir! Do you know if I drop MongoDB in an existing proyect to test for performance would I enable & disable the module without consequences? I want to try mongo, but what if it doesn't work or something? Is it safe to try? (I know you can not guarantee it but I wonder what happens in most cases)
Comment: Thanks Berdir! I tried MongoDB a few days ago but there wasn't a noticeable gain in performance, but also I wasn't aware of the things/changes you are telling me right now. I thought "MongoDB should make a difference in larger sites". I'll try MongoDB again.
Answer: The pros come with cons.
Drupal as a whole can't be switched to MongoDb, so you will have to support two databases and make sure they work well together.
Many modules will not be able to work with mongodb so you will loose interoperability.
Unless you have a pressing need (like part of your system is not coping with the number of request/or amount of data) I wouldn't switch. And even when you start approaching limits look at throwing hardware at the problem or tuning before switching.
I thought I had answered this before, there is a almost duplicate on SO

NoSQL vs Other SQL Drupal Setups


Multiplicação e soma de inputs em um site

Question: Estou construindo um site e necessito de uma ajuda: tenho 3 campos nesse site (input) e cada um representa um valor fixo (1.500, 250 e 500), gostaria de poder inserir nestes campos a quantidade de vezes que quero esse valor para que seja feita a soma e o resultado seja apresentado sem a necessidade de carregar a página:
Exemplo:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Orçamento</title>

Orçamento

        Quantidade item 1 =
        <input type="number" name="campoUm" id="">
        x R$ <var id="valorUm">1500</var> =

        Quantidade item 2 =
        <input type="number" name="campoDois" id="">
        x R$ <var id="valorDois">250</var> =

        Quantidade item 3 =
        <input type="number" name="campoTres" id="">
        x R$ <var id="valorTres">500</var> =

        Total =

Conseguem me ajudar?
Comment: Tem como colocar o HTML desses campos?
Comment: Não ficou bom, mas executando dá pra ver visualmente melhor o que estou tentando fazer.. Mas a partir dai, não sei como salvar em variáveis pra poder fazer os cálculos. Usaria o valor do id/class/name para isso?
Answer: Boa noite.
Você pode utilizar jQuery, para facilitar o manuseio de alguns elementos do HTML.
Com todo o respeito, eu tomei a liberdade de ajustar algumas coisas no seu código. Veja por favor se o exemplo abaixo te ajuda de alguma forma.

Explicação: Para cada campo onde o usuário digita o valor, eu criei duas funções no jQuery, uma para o evento keyUp(Depois que ele termina de pressionar alguma tecla) e outra é a função change(caso o usuário clique na seta pra cima ou pra baixo, que fica dentro do campo).
  A ideia é que toda vez que é digitado algum valor em qualquer um dos três campos, o script está pegando o valor de todos os campos e multiplicando pelo valor fixo que está definido nas tags VAR. Por último, está somando todos os resultados das multiplicações e exibindo o valor total na tag valorTotal
  Para te ajudar, caso você precise pegar o valor total da compra, existe um campo input type=hidden com o ID e name igual a valorTotalCompra, caso você envie esse valor para uma outra página que irá processar o pagamento

<!DOCTYPE html>

<meta charset="UTF-8">

<title>Orçamento</title>

Orçamento

    Quantidade item 1 =
    <input type="number" name="campoUm" id="campoUm">
    x R$ <var id="valorUm">1500</var> = <var id="resultado1"></var>

    Quantidade item 2 =
    <input type="number" name="campoDois" id="campoDois">
    x R$ <var id="valorDois">250</var> = <var id="resultado2"></var>

    Quantidade item 3 =
    <input type="number" name="campoTres" id="campoTres">
    x R$ <var id="valorTres">500</var> = <var id="resultado3"></var>

    Total = <var id="valorTotal"></var>
    <input type="hidden" name="valorTotalCompra" id="valorTotalCompra" value="" />

Answer: É possível pegar o valor das variáveis utilizando javascript, seja pelo id, name ou class, sendo que as duas ultimas opções, podem retornar 1 array já que na tela podem ter mais de 1 item com o mesmo nome ou classe.
No exemplo que criei peguei os itens pelo id, após isso fiz uma checagem se eles são numéricos e, caso não sejam, atribui o valor 0 para eles. Após isso fiz o calculo e por fim atribui o valores do calculo na tela através do elemento html (para isso dei 1 id para cada).
Para que o calculo fosse feito cada vez que o valor dos inputs fossem alterados, joguei o código em uma function e chamo essa function no evento onchange, ou seja, toda vez que o valor for alterado:

    function somaTudo(){

        var valorUm = parseInt(document.getElementById("campoUm").value)
        var valorDois = parseInt(document.getElementById("campoDois").value)
        var valorTres = parseInt(document.getElementById("campoTres").value)

        if(isNaN(valorUm))
        valorUm = 0

        if(isNaN(valorDois))
        valorDois = 0

        if(isNaN(valorTres))
        valorTres = 0

        var TotalUm = (valorUm * 1500);
        var TotalDois = (valorDois * 250);
        var TotalTres = (valorTres * 500);

        document.getElementById("TotalCampoUm").innerHTML= TotalUm;
        document.getElementById("TotalCampoDois").innerHTML = TotalDois;
        document.getElementById("TotalCampoTres").innerHTML = TotalTres;
        document.getElementById("Total").innerHTML = (TotalUm + TotalDois + TotalTres);
    }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Orçamento</title>

Orçamento

        Quantidade item 1 =
        <input onchange="somaTudo()" type="number" min="0" name="campoUm" id="campoUm">
        x R$ <var id="valorUm">1500</var> =

        Quantidade item 2 =
        <input onchange="somaTudo()" type="number" min="0" name="campoDois" id="campoDois">
        x R$ <var id="valorDois">250</var> =

        Quantidade item 3 =
        <input onchange="somaTudo()" type="number" min="0" name="campoTres" id="campoTres">
        x R$ <var id="valorTres">500</var> =

        Total =

Answer: Uma forma prática e que funciona em tempo real é criando eventos aos inputs que vai atualizando o valor à medida em que se vai alterando os campos. Não necessita de ids.
Para isso coloquei a tag <var id="total"></var> para receber o valor da soma:

var qtd = document.body.querySelectorAll("input[type='number']");
for(var x=0; x<qtd.length; x++){
   qtd[x].addEventListener("input", function(){
      var vals = document.body.querySelectorAll("var[id*='valor']");
      var soma = 0;

      for(var y=0; y<vals.length; y++){
         soma += parseFloat(vals[y].textContent)*vals[y].parentNode.querySelector("input").value;
      }

      if(!isNaN(soma)) document.body.querySelector("#total").textContent = soma;
   });
}

Orçamento

   Quantidade item 1 =
   <input type="number" name="campoUm">
   x R$ <var id="valorUm">1500</var> =

   Quantidade item 2 =
   <input type="number" name="campoDois">
   x R$ <var id="valorDois">250</var> =

   Quantidade item 3 =
   <input type="number" name="campoTres">
   x R$ <var id="valorTres">500</var> =

   Total = <var id="total"></var>


Declaração do construtor padrão dentro de uma classe em java

Question: Ao criar uma classe no java em IDE eclipse < public class TerceiraQuestao apareceu a declaração public TerceiraQuestao() dentro da classe criada sem que eu a tivesse declarado. Alguem poderia me ajudar? Segue o código..
package fundamentos;

public class TerceiraQuestao {
public TerceiraQuestao() {
    // TODO Auto-generated constructor stub
}

}
Comment: Bem-vindo ao Stack Overflow em Português! Por favor explique melhor o problema, sua pergunta não está tão clara. Não quer que seja declarado? Como retirar? Para que serve?
Answer: Pessoal queria registrar a solução que foi desmarcar a opção "Constructors from superclass" ao criar a classe .
package fundamentos;

public class TerceiraQuestao {
}nsira o código aqui
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


injective and surjective

Question: How to prove that a composite function $f\circ g$ is bijective$?$
because i have two questions.
if $f$ is injective and $g$ is surjective, can $g\circ f$ be both injective and surjective?
because the question assumes both sets to be the same criteria ( $f$ injective, $g$ surjective) , so one question is whether $g\circ f$ is injective and the other is if $g\circ f$ is surjective.
i proved that if $f$ is injective then, $x=y$, $f(x)=f(y)$, then $g(f(x)) = g (f(y))$ so $g\circ f$ is injective.
but is it true that if $f$ is injective and $g$ is surjective, then $g\circ f$ can also be surjective. its making me confused.
Comment: For surjective, you want an element in the target set (where $g$ maps TO) to come from an element in the domain set (where $f$ maps FROM) in the case of $g\circ f$. So you notice that there must have been some $f(x)$ such that $g(f(x))$ is the element you wanted, so $x$ was the original element you needed. For injective, let $g(f(x))=g(f(y))$ and see where that takes you. You might find that a surjective $g$ is too weak. Or you might find it works.
Comment: Your Injectivity  proof   is   not  correct
Comment: how is it not correct
Comment: See ,  to  prove  injectivity  of  $g\circ f$ ,  you  have  to  show  that  ,  ; if $(g\circ f) (x)=(g\circ f)(y)$  then  $x=y$. But  what  you  have  shown  is  that $x=y$  implies  $(g\circ f) (x)=(g\circ f)(y)$ ,that  is  well-definedness,not  injectivity
Comment: Keep one thing in your mind  when you try to prove this kind of statement: $f \circ g$ is just another function. You start with let $h = f \circ g$, then prove  $h$ is bijective using whatever conditions $f$ and $g$ have.
Answer: "if $f$ injective and $g$ surjective can $g\circ f$ be both injective and surjective?"
Sure, e.g. let $f:\{0\}\rightarrow\mathbb R$ and $g:\mathbb R\rightarrow\{0\}$.
But not always, e.g. let $g:\{0,1,2\}\rightarrow\{0,1\}$ be prescribed by $0\mapsto0$, $1\mapsto1$, $2\mapsto1$ and let $f:\{0,1\}\rightarrow\{0,1,2\}$ be prescribed by $0\mapsto1$, $1\mapsto2$.
Then $f$ is injective and $g$ is surjective.
However $g\circ f:\{0,1\}\rightarrow\{0,1\}$ is constant (and prescribed by $0\mapsto1$ and $1\mapsto1$).
It is evidently not injective and is not surjective.
Comment: do u mean that it can be known as injective and also known to be surjective? so my statement that when f is injective and g is surjective, gof is injective is true? and the other statement when f is injective and g is surjective, gof is surjective is true?
Comment: My first example gives you an injective $f$, a surjective $g$ and a $g\circ f$ that is injective and surjective. So the answer on the question between quotes is: yes. My second example gives you again an injective $f$ and a surjective $g$, but now with a $g\circ f$ that is *not* injective and is *not* surjective. This together shows that injectivity of $f$ and surjectivity of $g$ does not exclude injectivity and/or surjectivity of $g\circ f$, but also does not guarantee injectivity and/or surjectivity of $g\circ f$. That's all I am saying.
Answer: drhab's answer is excellent. However, I want to add two more things that are true.
Theorem
Let $f: A \rightarrow B, g: B \rightarrow C$ be surjective functions. Then $g \circ f: A \rightarrow C$ is a surjection.
Proof:
Let $c \in C$. Then, there exists $b \in B$ such that $g(b) = c$ (because $g$ is surjective). Because $b \in B$, there exists $a \in A$ such that $f(a) = b$
Therefore, $c = g(f(a)) = g \circ f(a)$, leading us to conclude that $g \circ f$ is a surjection. $\quad \triangle$
Theorem
Let $f: A \rightarrow B, g: B \rightarrow C$ be injective functions.Then $g \circ f: A \rightarrow C$ is an injection.
Proof
Let $a,a' \in A$ such that $g \circ f(a) = g \circ f(a')$
equivalently, we can say:
$g(f(a)) = g(f(a'))$
and by injectivity of $g$:
$f(a) = f(a')$
and by injectivity of $f$
$a = a'$
Hence, $g \circ f$ is injective.$\quad \triangle$
From the two previous theorems, it immediately follows that the composition of $2$ bijective functions is bijective.

injective and surjective


Mudar a imagem conforme a resolução da tela

Question: Estou estudando alguma coisa em jQuery para o caso.
É possível mudar uma imagem conforme a resolução da tela?
Por exemplo: no próprio navegador, com ele sem minimizar é a imagem grande.
Se minimizar, a função troca para a imagem pequena.
Answer: Sim, é possível! Podes fazê-lo utilizando o método .width()

Descrição: O .width() obtem a largura atual calculada para o primeiro elemento no conjunto de elementos correspondentes apontados.

Neste caso o elemento correspondeste apontado será a window, para obtermos a largura da janela/viewport:
$(window).width()

Depois iremos calcular se a largura do viewport é ou não maior que um valor que queiramos determinar, por exemplo:

if ($(window).width() > 500) {
   alert('A largura da janela é menor que 500');
} else {
   alert('A largura da janela é maior que 500');
}

Aqui tens também um exemplo no jsFiddle para veres este código em acção. Arrasta as bordas da secção de resultados diminuindo ou aumentando o tamanho da janela para veres a imagem a mudar.
Answer: Você pode colocar uma chamada para a sua função dentro do $(window).resize(function() { ... });.
Sugiro usar document.body.scrollWidth ao invés de $(window).width() pois o primeiro pega a largura de dentro da tela descontando a barra de rolagem, borda do browser, etc.


Switch between databases in spring/ hibernate

Question: In my project I use Spring and hibernate. I use MySql and use auto increment for Ids. But now I need to support multiple database types. (separate installations). Say, MySql, Oracle (11g), Postgresql, etc.
My current idea is to use uuid for primary keys since I can switch to any database without much worrying about database layer. But since  I have used Integer for auto_increment I have to modify my code base.
Is there a way to preserve Integer id? or shall I proceed with uuid ?
Current implementation
<code>@Id
@GeneratedValue
@Column(name = "id", nullable = false, updatable = false)
private Integer id;
</code>
Or this, (or any other solution)
<code>    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    @Column
    @Id
    private String id;
</code>
Answer: I found a way to do this.
Idea is to add annotation configuration and override it using xml.
<code>XML metadata may be used as an alternative to these annotations, or to override or augment annotations
</code>
Here is a good tutorial for this,
https://vladmihalcea.com/how-to-replace-the-table-identifier-generator-with-either-sequence-or-identity-in-a-portable-way/


How do I make a Login System in Android?

Question: I am new to this site so I am sorry if there are any inaccuracies in this question. I am trying to create a login system using a local database. Previously I did some research on how to make a login system but still have no luck. I am using something like intent.putExtras() (sorry, not sure what the correct word for that is) to store user's details such as username, date of birth etc, so the following activity can receive the data from the previous activity. However, I just figured out that SharedPreferences is used by many people to implement a login system and I am planning on using it as I have an impression that it is more reliable (correct me if I am wrong). However, I have been implementing a login system using intent.putExtras() and never seen anyone implementing a login system that way. To make sure my current way of implementation is reliable, my question is, can I use intent.putExtras() instead of using SharedPreferences?
Answer: intent.putExtras(//something) only stores data in Bundle temporarily. You need to store the user info (or if user has logged in) somewhere, to be accessed next time you open the application.
intent.putExtras() are intended to be used, for example, when you want to pass data from one Activity to another.
Locally, sqlite and shared preferences are your only options.

My question is, can I use "intent.putExtras(//something)" instead of using SharedPreferences?

With what you want to achieve, no you can't.

After you edited your question:
If you only want to pass data then you can do so with intent.putExtras(), if you want to store data locally, then you will have to use sqlite or shared preferences.
Comment: I am using sqlite and intent.putExtras()
Comment: Like I said `If you only want to pass data then you can do so with intent.putExtras()`
Comment: For instance, in my login system, I pass user's inputs from there to another activity and the data are stored in a database.
Comment: `SharedPreferences` is only to store data, since it's already stored in SQLite you don't have to use `SharedPreferences` again, just use `intent.putExtras(//something)`


How to control the access/permission of custom controllers by user-management module?

Question: At Yii 1.x, I use user and rights modules for role and permission of user and controllers.
Now, I tried to migrate my projects from Yii 1.x to Yii 2 Advanced. I tried to use user-management module, but I'm having issues with how this module manages access/permissions of the custom controllers.
How do I control the access/perminssion of custom controllers with the user-management module in Yii2 to mimic the behavior of the user and rights modules of Yii 1.x?"
Answer: In yii2 you can control access in several way  eg: using access filter http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html
or using  an a full Role-Based Access Control (RBAC) http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#rbac
you can use default yii2 RBAC module or extensions Yii2-admin https://github.com/mdmsoft/yii2-admin  ... rbac https://github.com/dektrium/yii2-rbac
You can find useful info in http://www.yiiframework.com/doc-2.0/guide-security-authorization.html