Is there a way to have Xcode 5 autocomplete like Visual Studio?

Question: Xcode 5 now displaced Xcode 4, and one common complaint that I had against both IDEs is that they don't autocomplete very aggressively. In Visual Studio, autocompletion is committed as soon as you hit a non-identifier key (like a parenthesis, a comma, a dot, a space, etc). On Xcode 5, you have to hit tab or enter.
Is there a known way to get a behavior closer to Visual Studio's for autocompletion?
Comment: @zneak Although the answer to this question is no there are two caveats covered as alternatives in my answer.
Comment: @TommieC. I saw your answer yesterday. You'll understand, however, that this question has been open since 2011, and that at this point, if I wanted to take "no" as an answer, I had more than two years to do so :) With Xcode 3 there was a plugin that made autocompletion okay-ish. I'm still not losing hope that someone will do something similar for Xcode 5.
Answer: You can select following two options from XCode->Preferences->Text Editing:

Suggest completions while typing.
Enable Type-over completion
Answer: You're not listing the other problem, XCode autocompletes by alphabetical values, not compatible ones. Visual Studio actually gives you things that work, but in XCode you can shove an Int to a class or visa-versa thanks to autocomplete.
The options that come closest are in XCode menu->Preferences->Text Editing. However, it doesn't have what you are after. I do notice autocompleting the brackets isn't very intelligent and I may turn mine off soon.
Anyway, the XCode alternative IDE actually has contextual autocomplete, which greatly improves your ability to code without looking at the docs. Unsure what its preferences are but it may be worth looking at. I'm not trying to advertise it so I'll let you google the XCode alternative if you want to.
In practice, the . and , "stopping" autocomplete actually saves me many times. For example, write for(int x = 0; x < 5; x++) {} then try to change the x to a y. Autocomplete will step in and completely throw you off, unless you hit space or . or ,. If you had aggressive autocomplete, it would shove in its nonworking alphabetical value at the top of the list.
Long story short, XCode 4 isn't separate from the rest of the mac, a nightmare when you try to go and use it. For one clear example, take a large text file in TextEdit, and scroll halfway down. Wait a second, now try to highlight half of the document. (Your scroll bar will disappear before you can do anything, for example).
The answer you're looking for may or may not exist, but I hoped to provide you with some alternatives that may satisfy your craving. The example at the end just shows the true nature of the tools and their UI principle.
There's always Monodevelop, (not objective C, but should be more customizable), or perhaps an ide that has Objective C, if you don't mind coding in alternatives.
Good luck, I wish XCode had more customizing too.
Comment: If you don't like the disappearing scrollbar, feel free to go to System Preferences -> General and select "Always" under "Show scroll bars". Other than that, for selecting half the document, you could put your mouse where you want the selection to begin, then press shift+cmd+up to select everything from the beginning of the document to there.
Comment: Ah, thanks for the pointer! I try to keep my anti-points as use-cases. For example, the Mac just disabled USB power because I plugged my arduino in for more than 5 minutes. Or I have developer mode enabled and cannot install web apps without finding settings, as you described, buried in strange places. You can't show hidden folders without googling the terminal command. XCode has the bugs I stated above, it's far from friendly to developers. Try to find the definition of MKMapRect in the docs... anyway, I will use your tips and appreciate them. Note that we still can't answer the guy's q!
Comment: I'm actually a long-time Mac user and I find your usability concerns unfounded. I am much more productive with Mac OS than I am on Windows, IDE autocomplete aside.
Comment: The guy happens to be me. ;) (Also, you might like this one if you need to deal with invisible folders: you might know how shift+cmd+g lets you navigate to a folder by its path? You can do the same thing inside open and save dialogs.) I'm not saying all that power user stuff is intuitive for power users from other platforms, but as a casual Mac user that grew into a developer, there's nothing I do on Windows that I don't know how to do/do better on Mac OS. (Of course, I keep myself to pretty "standard" development targets, so YMMV if you like less mainstream stuff.)
Comment: (And again, that excludes a number if IDE quirks. Visual Studio is definitely better than Xcode, but I like Mac OS better than Windows.)
Comment: hehe, I didn't check name, oops. I do similar, trying to stick to mainstream. Mac has bugs that show up randomly, but always annoy the crap out of me. All text sometimes filters into the search box, no matter what. Windows definitely has more, but Macs seem to take away my ability to be productive. Erasing a core data relationship made XCode crash until I reverted the file... anyway I wanted to say thanks for the tips on invisible folders, and I'll look up the shortcuts to try and get proficient with it. I've read the prog. guides and know the systems pretty well. You've answered my Q's! lol
Answer: In xCode the only way to autocomplete is pressing tab key or "ctrl space" to have a list of all methods and variable starting with that char sequence.
If you want, you can customize the key shortcut pressing "cmd ," and, in the section "Key Bindings", you can customize it.
Comment: Everybody knows that. I was asking if there was a way to autocomplete more aggressively. In Visual Studio and other IDEs, pressing one of ,.(); will select the autocomplete choice.
Answer: You can use a key shortcut to show a completion list.
You can press "ctrl + ," and it will show the "visual studio like and feel" list for autocomplete.
Comment: @Daneil, the display is fine, but the behavior is not the same as Visual Studio's C# or C++ autocompletion. With Visual Studio, when you highlight an entry, inserting any character that can't be part of an identifier (like a dot, a space, a parenthesis, a comma, etc.) will commit the autocomplete. Under Xcode, it doesn't.
Comment: It still doesn't commit with the first non-identifier character you type, which is my worst complaint. :/
Comment: Ctrl+, does nothing on my version; is that with Xcode 4.3 DP or have I changed something at some point?
Comment: meh, I didn't realize Xcode 4.3 was out. I'll download it and try again.
Comment: `^,` definitely does nothing for me (even with Xcode 4.3). The [Xcode cheat sheet](http://www.1729.us/xcode/Xcode%20Shortcuts.png) I found doesn't list this shortcut either. Am I missing something?
Comment: The + is not the char that you must press, you must press ctrl AND ,
Comment: I figured that out. I am pressing ctrl and the comma key, and Xcode just does a "beep". When I looked in my bindings preferences, this key combination was not used for anything. There was ctrl+space bound to "Show completions", but no traces of ctrl+,. "Show completions" waits that I press 'enter' to commit my choice.
Comment: well, I have Xcode 4.3.2 now. As the question title indicates, I'm looking for Xcode 4 answers.
Comment: Now I understand, sorry, I dont know
Answer: Now if you start typing auto-complete will pop up. There is nothing you need to do.
EDIT
Sorry about that. Misunderstood the question. The only way to select autocomplete is by typing a tab, enter, or right arrow key. There is no way to do this in normal XCode.
Comment: But it's still not autocompleting the way I would like it. As stated in my question, you have to press enter to select an autocomplete choice. In Visual Studio, you just have to type a character that can't be part of an identifier to select that choice (for instance, enter, space, a parenthese, a comma, a dot, ...)
Answer: The following key binding options are available for code completion. I do not believe there is any way to change the underlying engine to make finding appropriate completions easier, however one could write as many code snippets as desired to quickly reuse code.

Alternative
I prefix my code snippets with my own initials followed by my own logically phrased structures. This presents a pretty useful [faux] index that let's me short-circuit the auto completion routines.
e.g. Structure of a typical user snippet
[tnc][AddMethod][Somename]
When necessary I then start tnc... to gain access to my [faux] index of commonly used snippets.
Snippets are not autocompletion per se but they do provide an alternative index to autocomplete coding and could address the concern of finding relevant information quickly.
Answer: control+space is probably the only feature I've known. I agree xcode does not have any auto completion that I'm aware off.
But otherwise since visual studio keeps on getting updated most of the time. The auto completion on it works fine. At some point Xcode might add a feature like that on their future updates.
Answer: I don't know if this works with xCode 4 though, but its worth a try
http://code.google.com/p/xcode-auto-assistant/
Comment: The Xcode plugin API is private and has changed between Xcode 3 and Xcode 4. It's pretty much bound to crash, but thanks anyways.
Answer: If you want to complete the same things every time you could use third party software like text expander for this or use Snow Leopards integrated textreplacement feature.
Comment: The whole point of autocompletion is to provide contextual suggestions. "Normal text" autocompleters can't do this.


API Olist - access blocked by CORS policy

Question: Preciso utilizar a API Olist, através de uma callback, porém estou obtendo erro ao realizar a requisição POST que retornaria o access_token.

O fluxo seria:

Utilizar a callback/getlink para enviar o client_id via GET para https://id-sandbox.olist.com/openid/authorize
A https://id-sandbox.olist.com/openid/authorize abre automaticamente a callback/olist?code=coderetornado&&secret=secretretornado
A callback/olist requisita via POST o access_token, enviando o secret e o code retornados no passo 2
Com o retorno do passo 3, a callback/olist salva o access_token no banco de dados para utilizar

Porém no passo 3, não consigo enviar a requisição POST pelo navegador, retornando o erro da imagem anterior. Utilizando o POSTMAN e enviando os dados direto para a API eu consigo, mas é necessário passar pela callback/olist para salvar o token.
Na requisição GET, utilizei o dataType: 'jsonp', assim evitando o CORS, mas na requisição POST não é possível utilizá-lo.
O código para a requisição é:
<code>    $.ajax({
        url: url,
        method: 'post',
        dataType: 'json',
        processData: false,
        data: function(){
            var formDataAuth = new FormData();
            configJson = JSON.parse('<?= $configJson ?>');
            formDataAuth = new FormData();
            formDataAuth.append('client_id', configJson.code);
            formDataAuth.append('grant_type', 'authorization_code');
            formDataAuth.append('client_secret', configJson.secret);
            formDataAuth.append('redirect_uri', configJson.callback);
            formDataAuth.append('code', configJson.key);
            return formDataAuth;
        }(),
        success: function(data) {
            savetoken(data);
            console.log(data);
        },
        error: function(data) {
            console.log('erro', data);
        },
    });
</code>
O erro acontece por faltar alguma informação na requisição? Pode ocorrer por não possuir um SSL? Ou por outro motivo?
Answer: O erro apresentado não é por falta de informação na requisição. Este é um erro de CORS, você está tentando fazer uma requisição para outro servidor/domínio que não é o seu, leia mais em https://developer.mozilla.org/pt-BR/docs/Web/HTTP/CORS
O CORS é tratado no back-end do servidor para o qual você está fazendo a requisição e não em seu código front-end
Comment: Então não há nada que eu possa fazer para tratar isto, certo?
Comment: esse site para o qual você está fazendo a requisição é seu? Ele é uma API com chave de acesso? acredito que deve haver alguma seção na documentação deles sobre CORS
Comment: É uma API, Olist é o nome. https://dev.olist.com/docs/authentication essa é a documentação, procurei mas não achei nada


Dell PowerEdge 1800 Hangs at boot after Dell PERC Sata RAID Controller Successfully POSTs

Question: Server crashed one night. I rebooted, now it hangs just after the SATA RAID Controller successfully POSTs.
This unit has a RAID 5 array, but I haven't pulled a recent enough backup of the data on it to feel comfortable, so I simply can't break the array in any way.
Questions:
-First off, what are my options for troubleshooting this without affecting my array?
-Second, can I replace the RAID card without losing my array informatoin?
-Third, how do I back up or transport the array to another machine / card without data loss if I need to?
Thanks for any help you can provide
EDIT:
I finally got past the hang by disabling the Boot BIOS (telling the card not to act as a boot device) and for the first time I was able to get into the RAID utility (Ctrl + A) to see the status of my array. DEGRADED. So now I'm trying to identify which drive failed in the 3 drive array.
Essentially the Boot BIOS being enabled was preventing me from accessing the RAID config BIOS while the drives were connected. I had to disconnect the drives, disable the boot BIOS, reconnect the drives, then I was finally able to get into the config BIOS to see that I had a dregraded array.
QUESTIONS:

How do I identify which drive failed? The array status screen doesn't seem to indicate which drive is causing the degradation. I'm verifying each drive with the BIOS utility right now, but I'm wondering if there's an easier way that doesn't take hours and hours.
I have the option to rebuild a failed array with the (Ctrl + R) Rebuild tool in the BIOS. Is this an option for a DEGRADED array as opposed to a FAILED array, as the tool was designed for? What are the risks?
Why didn't my array boot with a single drive failure? RAID 5 should have kicked in and allowed the system to recover and boot on 2 drives.
If it had multiple drive failures, then why is the array DEGRADED instead of FAILED?
Answer: Dell Warranty Check: Perhaps the until is still covered under warranty?
Comment: Agreed. This is exactly what Dell support is for!
Answer: Options for Troubleshooting:
 Try to determine if the error is with the server or the Raid.
 Check Bios for changes//correct boot device.
 Check Raid Bios for correct information (memory, # of hdd, raid level)
 Try booting to another media (cdrom, usb, network)
 Remove raid card and drives from system then see if the system boots
2nd: The raid configuration information should be stored on the drives and the controller. You may have to "accept the new configuration" to continue either in the bios or during boot.
3rd: Move the drives and RAID card to the new box, provided your OS can handle the change in hardware or its another Dell 1800.
4th: Moving the array to another card typically does not work unless the new card is the same make and model of RAID controller. You may have to "accept the new configuration" to continue either in the bios or during boot.
Comment: So I assume accepting new config binds the array information on the new card?
Comment: Yes, Some Dell raid cards will allow you to by-pass this with a warning.
Comment: So binding the array information to a new card worked, but it didn't resolve the problem. I'm looking into the default boot device, and updating the firmware on the poweredge. Problem is that I can't get into setup when the card is in because it hangs before entering setup (just after RAID card POST).
Comment: Applying firmware to the card did not resolve the issue. I found some documentatoin from Dell "Firmware and Driver – A mismatch of firmware and driver could result in random controller
lockups, hangs or BSODs. The system should be at the current approved level. The latest
firmware and driver versions can be found on support.dell.com. When performing a firmware and
a driver update, it is recommended that the driver be updated before the firmware. The driver is
always backward compatible with older firmware. A new firmware with an older driver will usually
result in abnormal behavior."
Comment: The only problem is that I can't install drivers when the array won't boot.
Comment: I also nitced that when I disabled the BIOS in the SATA controller (with the drives disconnected to get past the hang), I got past the hang and I could now get back into the config screen with the drives plugged into the card. So either the array is corrupted, or the bios is


What's problematic about finding out if a large number is Prime or not?

Question: I was reading somewhere that it's hard to determine if a number is prime or not if it gets too large.
If I understand correctly, all numbers can be broken into prime factors. And numbers which can't be broken down to any factors beside $1$ and themselves are prime.
So to check if $N$ is prime, you need to
calculate prime numbers upto $N/2$, (as any number bigger than $N/2$ can't be a factor for $N$ since multiplying it with the minimum number that will have effect, which is $2$, will make it more than $N$).
and check if any of these are factors of $N$.
I want to know if I am right, and what I am missing in terms of it being hard to compute.
Comment: Actually, you need only test divisors up to $\left\lfloor\sqrt{n}\right\rfloor$. What you're missing is the amount of time required to do this when $n$ is large.
Comment: If $n=ab$ with $a\le b$, then we must have $a\le\sqrt{n}$, since otherwise $ab>(\sqrt{n})^2>n$.
Comment: It is hard to check for a large number's primality, yes, but at least that is a comparatively easier task than attempting to factor a large number. (As an aside, most of the efficient probabilistic tests should be properly called "compositeness tests", since they can show compositeness with certainty, but not primality.)
Comment: can you explain Sqrt(N) part
Comment: oh i see, thanks
Comment: Also, if you dont like the "brute force" way of testing for primality, there are more advanced algorithms. I suggest looking up Fermat Primality Testing or the Miller-Rabin Primality Test which runs in polynomial time.
Comment: @BrianScott This can be reduced to $\pi(n/2)$ which is much smaller if you make a list of primes early on so it can be used to check if any of the primes divide it.
Comment: Its complexity is $O(\sqrt n)$ and that's why brute force is not suitable for large numbes.
Comment: @MuhammadUmer Do you know the meaning of the expression "hard to compute"?  It doesn't refer to how conceptually hard the calculation is, only the length of the calculation.  The calculation you describe is conceptually very simple but it will take an extremely long time when $N$ is large, and this is all that is needed for someone to call it hard.
Answer: The most brute force procedure that is not inefficient for completely naive reasons is trial division up to $\lfloor \sqrt{n} \rfloor$, because if $n$ has a factor greater than or equal to $\sqrt{n}$ then it must also have a factor less than or equal to $\sqrt{n}$. (For example, $\lfloor \sqrt{91} \rfloor = 9$. Although $91$ has a factor of $13$ which is larger than $9$, it also has a factor of $7$, and dividing by this factor reveals the factor of $13$.)
The difficulty is that if $n$ has 100 digits then $\sqrt{n}$ is like $10^{50}$, so if you try a trillion numbers per second then it will take you more than $10^{30}$ years to finish trying all the factors less than $\sqrt{n}$.
There are much better algorithms out there, though, especially for the problem of primality testing (as opposed to factorization of a number which is known to be composite).
Comment: @manshu, determining the primality of possible factors can be much more expensive that doing directly the trial division.
Comment: @manshu it is not a lot less, it's less by a factor of $50\ln(10)$ by the prime number theorem, so you get all the way down to about $10^{48}$. And this ignores all issues with constructing this list of primes.
Comment: @manshu There are infinitely many prime numbers, so of course your computer doesn't have a list of all of them. Even with the most compact representation we could come up with, there isn't enough storage capacity in the world to store all the primes up to 25 digits.
Comment: @manshu, the list of *all* the prime numbers? The list of prime numbers up to $\lfloor\sqrt{n}\rfloor$?
Comment: ok. ok . I get it
Comment: you don't need to try $10^{50}$. You need to try only **prime** numbers out of those $10^{50}$ numbers. which I think are lot less.
Comment: @Martín-BlasPérezPinilla We are using a computer program for determining the prime number. So I think computer should have the list of all the prime numbers.
Comment: You do save a significant amount of time if you have a list of all the primes up to $\lfloor \sqrt{n} \rfloor$ already. However, constructing this list takes a comparable amount of computational time to doing all the trial divisions in the first place. (I do think there is a little bit of asymptotic savings, but it can't be all that much.)
Answer: Probably what you have read (in the context of public key encryption) is that it is hard to factor a large integer in its prime divisors if each of these divisors is large. In essence, factoring a number consisting of $n$ bits into prime components, requires trial divisions using numbers containing up to $\frac12n$ bits. As there are $2^{n/2}$ such numbers, this computational effort scales exponentially. More specifically, every two additional bits in the number to be factored, doubles the computational effort.
One can improve upon this scaling by using more advanced algorithms, but there is no known algorithm that one could run on present-day computers that would make the computational effort scaling as a polynomial in the number of bits.
Checking for a number being prime or composite (rather than explicitly finding the composites) can actually been done in polynomial time. In highly optimized algorithms the computational effort scales with the sixth power of the number of bits ($n^6$).
Comment: The [AKS primality test](https://en.wikipedia.org/wiki/AKS_primality_test) runs in polynomial time in the number of digits.
Comment: @Mok-KongShen In other words we use the tests in a probabilistic way because a result with 2^(-100) probability of error is already good enough for us and only require a fixed number of trials. If you go on you can prove primality but this requires O(n) tests, i.e. more than plain trial and division.  If Riemann hypothesis is true then it was already proved that you need only O(log^2 n) trials to prove primality, and you obtain a deterministic algorithm with complexity comparable to AKS or maybe a bit less (and surely with smaller constants).
Comment: However, for practically interesting cases of large numbers (e.g. of the order of those employed as moduli for RSA encryption), AKS is nonetheless not a practically favourable method, for it would take too much computing time, despite some later improvements of it, if I don't err. One commonly employs the probabilistic method of Miller-Rabin, which doesn't prove the primality, in case it fails to find that the number is composite. (I read somewhere a suggestion to additionally do the Lucas test.)
Comment: @Mok-KongShen It's well known. In case of Fermat test you have the bad property that a composite n can pass the test for all possible basis, but in the case of Euler pseudoprimes (Solovay Strassen primality test) or Strong pseudoprimes (Miller Rabin) this is not true. I.e. you can do the test for all basis between 2 and n-1 (prime with n) and if none fail *you are sure* that the number is prime.  In fact for solovay strassen only half the tests are required and for miller rabin only one fourth. That's way we say that after k trials the chances of false positive is 4^(-k) or 2^(-k)
Comment: @RamchandraApte - good point, have modified my answer to clarify this.
Comment: @Mok-KongShen You **can** prove whether a number is prime or not using Miller-Rabin. However it requires an exponential number of trials. Assuming the Riemann hypothesis we know that you can use Miller-Rabin to prove primality in polynomial time.  Regarding Lucas: it is an other probabilistic test, however there are no known composite numbers that are pseudoprime in both tests, and this was exhaustively checked up to something like 2^64.
Comment: @Bakuriu: Concerning your 1st sentence: In my present humble understanding, each additional run of Miller-Rabin reduces the probability that a composite number yet fails to be revealed by the test by a certain finite factor. If that's indeed the case, then there could theoretically exist cases that even with an arbitrarily large number of trials of Miller-Rabin such defects could occur. Do you happen to have references proving the sufficiency of a certain upper bound of trials of Miller-Rabin?
Answer: It sounds like you've got the gist. You actually only need to check up to $\sqrt{N}$. The reason for this is that if $N$ is divisible by $a$, with $a\geq \sqrt{N}$, then $N=ab$, where $b\leq\sqrt{N}$. So if you check up to $a$, you would have checked $b$ already. And even then there are better and faster methods that mathematicians have come up with. But however you do it, you have to make a lot of calculations.
And I mean a lot of calculations. big numbers here are numbers with hundreds of digits. Even if you only check up to $\sqrt{N}$, that is still over $10^{50}$ calculations, one hundred trillion trillion trillion trillion. Doing these calculations can be done quickly, but to do so many of them takes a while.
Answer:
What I am missing in terms of it being hard to compute?

Let $k$ denote the length of your input.
If your input number is $N$, then $k\approx\log_2N$, and therefore $N\approx2^k$.
The runtime complexity of an algorithm is measured as a function of the input-length.
Since the runtime complexity of your algorithm is $O(N)$, it is also $O(2^k)$, hence exponential.
Answer: I would like to choose somewhat different perspective than in the other answers and say something about the topic in question. For me, it is hard to determine whether some (big enough) number is prime because prime numbers tend to exhibit strange enough behavior which still is not understood. See for example this conjecture. If this conjecture is correct then, in a certain sense, its correctness reveals why it is hard to determine when we will stumble upon a prime in the sequence of natural numbers because sometimes from the prime $p$ to the next prime $q$ we will have only to add $2$ to $p$ to obtain $q$, sometimes $4$, sometimes $80$, sometimes $222$, just choose even numbers which you like at the moment, any should do the work, should it?
Another reason, closely related to the above written thoughts, is that it is not easy to determine whether (big enough) number is prime because we do not have (correct me if we have) general enough and efficient enough methods that would settle whether some number is prime or not. To clarify this suppose that we investigate sequence $a_n=\sum_{i=0}^n 10^i$. This is just the sequence of numbers such that $n$-th term has $n+1$ ones in the base $10$ representation. Even for this sequence (which is simple to describe) we still do not have necessary and sufficient condition for primality of the terms in the sequence, so you can imagine how hard could it be to find the theorem of the form "$n$ is prime if and only if "this hols"" which is such that gives testing for primality in a straightforward easy-to-calculate way.


Capybara: fill_in action locator

Question: So I have this spec
describe "visit /signup" do
    before(:each) do
        get signup_path
    end
    it "has an email input field" do
        page.has_field?("#user_email")
    end
    it "accepts an email address" do
        page.fill_in('#user_email', :with=>Faker::Internet.email)
    end
end

The first test (has an email input) passes, the second fails with
Failure/Error: page.fill_in('#user_email', :with=>Faker::Internet.email)
Capybara::ElementNotFound:
   cannot fill in, no text field, text area or password field with id, name, or label '#user_email' found

The input[type='text'] element exists on the page with that DOM ID, have tried locating with the ID with and without the hash, and using its input:name as a locator too.
What am I doing wrong?
Comment: `save_and_open_page` was super useful in debugging too
Answer: It's because you're using get when you should be using visit inside the before block. This:
before(:each) do
  get signup_path
end

Should be this:
before(:each) do
    visit signup_path
end

Otherwise you're telling Rack::Test to visit that path, not Capybara! A small distinction that trips quite a few people up frequently!
Answer: maybe you should remove the #, e.g.
fill_in('user_email', :with=>Faker::Internet.email)

Answer: I think fill_in is not on page. Just use fill_in:
describe "visit /signup" do
    before(:each) do
        get signup_path
    end
    it "has an email input field" do
        page.has_field?("#user_email")
    end
    it "accepts an email address" do
        fill_in('#user_email', :with=>Faker::Internet.email)
    end
end

Capybara: fill_in action locator


Python 3 create error if user input is not an integer

Question: I have the code below working the way I want it to.
How do I add an error if the user does not enter an integer?
userdata = input("Input the number of numbers to be stored :")

userNumz = []

print("Input " + str(userdata) + " numbers :")
for index in range(int(userdata)):
    userNumz.append(input(str(index) + " is "))

I have tried to use ValueError but can't get it to work . My attempt below:
while True
    try:
        userdata = input("Input the number of numbers to be stored :")
    except ValueError:
        print("The input was not a valid integer.)

Comment: The user **does not ever** enter an integer, **even if** it consists of all digit symbols.
Answer: If you cast the input as int then it will throw the error you want:
while True
    try:
        userdata = int(input("Input the number of numbers to be stored :"))
    except ValueError:
        print("The input was not a valid integer.)

Answer: Code:
To invoke an error on an invalid conversion try:
userdata = int(userdata)

In Context:
while True
    try:
        userdata = input("Input the number of numbers to be stored :")
        userdata = int(userdata)
    except ValueError:
        print("The input was not a valid integer.)

Answer: User input will be a string, so when you try to convert it to an int you'll get a ValueError if the user gave you a letter or word.
def get_int():
    userdata = input("Enter an int, or 'q' to quit: ")
    if userdata == 'q':
        return None
    try:
        user_num = int(userdata)
        return user_num
    except ValueError:
        print("I need an integer to continue.")
        return(get_int())

user_number = get_int()

This function will loop until the user enters an int or quits with a 'q'. The following lines would deal with the returned number (or the None object if they quit).


Prove that $\sigma$-algebra of subsets of $\mathbb{R}$ of the form $(a,\infty)$ contains all the intervals.

Question: I want to prove that if a $\sigma$-algebra of subsets of $\mathbb{R}$ contains intervals of the form $(a,\infty)$, then it contains all the intervals.
Proof:
Let $\mathscr{B}$ to denote the $\sigma$-algebra defined above. We have that since $(a,\infty) \in \mathscr{B}$, then since it contains the complement, we have that it also contains the intervals of the form $(-\infty,b]$, i.e. $$(-\infty,b] \in \mathscr{B}$$
In particular, we have that $(a,b) \in \mathscr{B}$. It's enough to prove that:
$$[b, \infty) \in \mathscr{B}$$
$$[a,b] \in \mathscr{B}$$
$$[a,b) \in \mathscr{B}$$
$$(a,b) \in \mathscr{B}$$
This is clear, since:
$$[b, \infty) = \bigcap_{k=1}^{\infty} (b-\frac{1}{n}, \infty)$$
$$[a,b] = \bigcap_{n=1}^{\infty} (a-\frac{1}{n},b+\frac{1}{n})$$
$$[a,b) = \bigcap_{n=1}^{\infty} (a,b+\frac{1}{n})$$
$$(a,b) = \mathscr{B} \backslash [(-\infty,a]\cup[b,\infty)]$$
Is this proof correct?
Comment: $[b, \infty) = \bigcap_{k=1}^{\infty} (b-\frac{1}{n}, \infty)$.
Comment: @TeresaLisbon If this is Problem 11 in Section 2.3 of _Real Analysis_ by Royden and Fitzpatrick, it remains to show that all intervals are of the forms you listed. The authors leave that proof as a reader exercise on page 10 of the text.
Comment: You say in particular that $(a, b) \in \mathscr R$, can you explain a bit more?
Comment: @JohnMa   correct me if I am wrong, I can write: $(a,b) = \mathscr{B} \backslash [(-\infty,a]\cup[b,\infty)]$.
Comment: Technically you haven't shown $[b, \infty) \in \mathscr R$ yet.
Comment: then I need to prove $[b, \infty) \in \mathscr R$ and I'm done?
Comment: Yes, the remaining of your works are correct.
Comment: what about $(-\infty,b)$?
Comment: @user0 I'm reading this late, hence I apologize. I will check page 10 of the text.
Answer:
A new organized answer is required.

$\newcommand{\b}{\mathscr B}$Ok, I will give it.
What is the structure of an interval? It is one of the following : $(a,b),[a,b),(a,b],[a,b]$, where one of $a,b$ could be $\pm \infty$.
Let us start with $(a,\infty) \in \b$ for all $a \color{blue}{(1)}$.
Without complementation, note that $[a,\infty) = \bigcap_{n=1}^\infty \left(a-\frac 1n,\infty\right)$, so $[a,\infty) \in \b$ for all $a\color{blue}{(2)}$.
Now, the complements of $\color{blue}{(1)}$ give $(-\infty,b] \in \b$ for all $b\color{blue}{(3)}$.
The complements of $\color{blue}{(2)}$ give $(-\infty,b) \in \b$ for all $b\color{blue}{(4)}$.
Thus, one sees that all cases where one endpoint is infinite is covered. This can be used to systematically process the rest of the intervals.

Now,

$(a,b) = \mathbb R \setminus ((-\infty,a] \cup [b,\infty))$.
$[a,b) = \mathbb R \setminus ((-\infty,a) \cup [b,\infty)$.
$(a,b] = \mathbb R \setminus ((-\infty,a] \cup (b,\infty))$.
$[a,b] = \mathbb R \setminus ((-\infty,a) \cup (b,\infty))$.

Which shows that each of these intervals, for arbitrary $a \leq b \in \mathbb R$ belong to $\b$.


Dúvida simples sobre :after, :before (clearfix e etc)

Question: Já vi alguns dev's usando tanto o display:block quanto table em um after/before, mas porque usar ? Eu acho que sei do porquê usar o block mas porque o table?
Qual a diferença?
Outra dúvida é sobre esse *Zoom: 1;. Por que usar?
Código
.clearfix:before,
.clearfix:after {
   content: " ";
   display: table;
}

.clearfix:after {
   clear: both;
}

.clearfix {
   *zoom: 1;
}

Comment: Artigo em inglês que pode te ajudar http://nicolasgallagher.com/micro-clearfix-hack/
Answer: Diferença entre block e table, como o próprio nome sugere:

display: block: o elemento vai ser renderizado como bloco.

.exemplo{
  display: block;
  border: solid 1px red;
}

.classeTeste{
  display:block;
  border: solid 1px red;
}

 Teste

        Div 1

     Div 2

display: table: os elementos se comportam como
.

.exemplo{
  display: table;
  border: solid 1px red;
}

.classeTeste{
  display:table;
  border: solid 1px red;
}

 Teste

        Div 1

     Div 2

A propriedade zoom especifica o fator de zoom inicial para a janela ou área de visualização. Pense nele como uma lupa. Veja esse exemplo e uma explicação mais detalhada nesse Tutorial sobre Zoom.
:after e :before são chamados de pseuso-elementos e como o próprio nome já fala, são utilizados para inserir um determinado conteúdo antes ou depois de um determinado elemento. Lembre-se que os pseudo-elementos não suportam diversos conteúdo ao mesmo tempo e inserção de códigos HTML. Para saber mais detalhes e ver exemplos veja: :before e :after.
Links úteis:

A propriedade Display
The zoom descriptor
CSS display


What determines the overall key of a work with multiple movements and key changes?

Question: For example, we talk about Beethoven's Symphony No. 5 in C minor, yet the movements are in a variety of keys:

Allegro con brio (C minor)
Andante con moto (A♭ major)
Scherzo: Allegro (C minor)
Allegro (C major)

The key can also change within a movement. For example, the first movement begins in C minor with the iconic "da-da-da-daaas", but Wikipedia states:

[the] second theme is in E♭ major, the relative major [to C minor], and it is more lyrical...

So now we have the additional task of determining the overall key of each movement.
Factors for determining overall key
Here are some factors that I think could determine (or at least influence) the overall key of the work:

The (first?) key of the opening movement
The (last?) key of the final movement*
The key used most often within the piece
The key used for the most iconic section of the piece
The key that any recurring theme within the piece is written in

I could construct a similar list of criteria for determining the overall key of each movement, but the question is: what is the deciding factor?
* Since Beethoven's 5th doesn't end in C minor, this would appear to go against the idea that the overall key is the final key. However, Wikipedia states:

The music [of the 4th movement] resounds in C major, an unusual choice by the composer as a symphony that begins in C minor is expected to finish in that key.

So if Beethoven's 5th is an exception then perhaps the final key is important in determining the overall key, at least most of the time?
Note: I have used Beethoven's 5th Symphony as an example, but people are welcome to refer to other pieces in their answers/comments. I am really interested in the general case, and links to evidence are appreciated.
Answer: Heinrich Schenker's notion of the "auxiliary cadence" (Hilfskadenz) starts to answer this very question: it tries to explain how a movement can begin away from tonic.
I don't have firm data for this, but my experience as a musician (and conversations with other musicians) tells me that the general belief is that a composition's final key is its overall key.
But interestingly, this only tends to be true for individual movements. When we get to multi-movement works, opinion seems to be focused on the beginning. (Again, I don't have data to prove this, this is just my experience.)
Originally, these multi-movement works were always bookended by the same key. The four movements of Haydn's "Surprise" Symphony, for instance, are in G, C, G, and G. This key---G major in this case---was viewed as the overall key.
Occasionally, composers would get a little innovative, often by giving a "slow introduction" to the first movement. Haydn's Symphony 104, for instance, begins in D minor. But the four movements still have a pattern of D (major), G, D, D, so it's clear to see that the overall symphony is in D major.
But when we get to Beethoven 5, we switch to C major at the end, yet we still consider it a symphony in C minor. But C major and minor are parallel keys, so this isn't too much of a stretch. Mahler 2 takes it the next step: the first movement is in C minor, but it switches to the relative key of E♭ major by the final movement; but we still say Mahler 2 is in C minor!
Mahler 5 then took it all the way: a symphony whose first movement is in C♯ minor ends with a movement in D major. Yet every score and recording will tell you it's a symphony in C♯ minor.
In short, it seems that we tend to privilege the final key when analyzing single movements. But in multi-movement works, we tend to use the key of the first movement to determine the key of the entire work. (And typically we find the key of the first movement by looking at its ending.)
And a comment below reminded me of another important distinction: that of ending in major compared to ending on major. When a piece ends in major, it's been in major for some time. This is different than a minor piece ending on a major chord on account of a Picardy third.
Comment: "I don't have firm data for this, but my experience as a musician (and conversations with other musicians) tells me that the general belief is that a composition's final key is its overall key."
Not so.  Particularly when the work is titled as being in a minor key.  See the examples in my answer below.
Comment: @LaurencePayne But don't your answers follow the multi-movement stipulation that I placed in the latter half of my answer?: "But in multi-movement works, we tend to use the key of the first movement to determine the key of the entire work. (And typically we find the key of the first movement by looking at its ending.)"
Comment: If you derive the key of the first movement from its ending, a whole lot (but not all) of pieces that composer and publisher have agreed to label as 'in X minor' will have to be re-named!
Comment: Perhaps so. (Though I personally think there's a difference between endings with a Picardy third and endings where the last 50 measures are all in major.) I just wanted to point out that the examples you listed all follow my stipulations given above.
Comment: I think this is a great answer, and the best answer so far, but I am reluctant to mark it as the accepted answer as, like the other answers, it is primarily opinion-based. The consensus seems to be that the final substantial key of the first substantial section/movement determines the overall key, but I would like to see this confirmed with a quote from a definitive source.
Answer: Yes, multi-movement works tend to be named for the key of the first substantial section.  And it's very common for a work that starts off in a minor key to end up in either the tonic major or relative major. In fact, in the context of the 'classical' period - which could be defined as that when key relationships were paramount in defining the structure of a musical work - it would almost be unusual for it NOT to.
The Wikipedia quote:

The music [of the 4th movement] resounds in C major, an unusual choice
  by the composer as a symphony that begins in C minor is expected to
  finish in that key.

is rubbish.  Let's look at a few symphonies 'in E minor'.   Dvorak 9 (the 'New World') ends in E major.  Tchaikovsky 5 ends in E major. Brahms 4 ends in E minor - it CAN happen :-)  Rachmaninoff 2 ends in E major.  I could go on...  We could compare this reluctance to end in a minor key to the Tierce de Picardie, popular since about 1500.
Comment: I wonder if the Wikipedia editor meant that Beethoven 5 was unusual *for its time*? Dvorak, Tchaikovsky, Brahms, and Rachmaninoff all came after Papa B.
Comment: @Richard: Haydn has at least four minor-key symphonies that end in the parallel major (26, 45, 83, and 95).
Answer: Here's my guess for how finding overall keys works:
Multi-Movement Works
The name is probably the definitive, canon indicator for the key the multi-movement work is in. For example, Chopin's Piano Sonata No. 3 in B Minor, Op. 58 is in B minor, despite one of its movements being in B major and another in E flat major. Heck, the last movement ends in B major (and starts in B minor)! Another example is Mendelssohn's Symphony No. 4 in A Major, Op. 90, "Italian" is in A major, despite one of its movements being in D minor and its last movement being in A minor. Yet another example is Beethoven's Piano Sonata No. 27 in E Minor, Op. 90, which is in E minor despite being only 2 movements long--the 1st movement is in E minor and the last is in E major.
Once you've found enough multi-movement works with names that reveal their keys, you can sketch out some rough rules for determining the overall key of a multi-movement work. I generally agree with your proposed factors, except that I agree more strongly with the first key of the final movement being a major factor. This is because minor-key works often end in the tonic major.
I'll have to provide some caveats--some multi-movement works have no overall key, and some movements have no overall key. Your rough rules must be flexible enough to accommodate this. For example, whatever the key of Bartok's fifth string quartet is, it hasn't been widely published.
Single Movements
From listening to a LOT of music, here are my rough factors for finding what overall key a piece has, if any:

The key of the first motive
The key of the last motive
The most often used key
The percentage of the piece that is atonal
All keys that are playing simultaneously (in the case of polytonal music)
The key in the piece that has the closest relationships with all other keys in the piece (dominant/subdominant/tonic major are closer relationships than chromatic mediant, for example)
The assigned key of other pieces with the same form as this piece (e.g. marches tend to be assigned their 1st key as their overall key, even though they often don't end in the same key as they start with)

You can also figure out the overall keys of contemporary music with these guidelines.
Gary P. Gilroy's Heart of the City should be a fairly straightforward example--it starts in F minor, it ends in F minor, and it's in F minor the most often, so its overall key is F minor. It doesn't matter much that some of its phrases are in F major or A flat major.
A less straightforward example is C-R-O-W-N-E-D from Kirby's Return to Dream Land. It also starts in F minor and ends in F minor. However, portions of it are also in A flat minor, E minor, and C minor, and it quite possibly ends up in A flat minor the most often. Despite C minor arguably having the closest relationships to all the other keys (it's the dominant of F minor and chromatic mediants of all the other keys, while F minor has a very loose relationship with E minor), I'd still say the overall key of this piece is F minor. This piece still begins and ends in that key, after all.
For me at least, overall keys get more tenuous the higher percentage of the piece is atonal. While The Defender from Shovel Knight is in D minor overall (it arguably starts in D minor and is in D minor the most often), large portions of that piece are chromatic to the point of atonality, and a phrase of it is even in B minor.
Eventually, pieces stop having overall keys. Half or more of Ginastera's Danza del gaucho matrero, Op. 2, No. 3 from his Danzas Argentinas is atonal, and the rest is desperately trying to cling onto a C major-like tonic. Some of it is actually in C major (with an interlude in A flat major), but I'd hesitate to say this piece has any overall key.
By the way, given these tips, can you help me find the overall key (if any) of Mind in a PROGRAM from Kirby: Planet Robobot? Portions of it are in C minor, F# minor, B minor, D minor, G# minor, C# minor, and E minor, and whatever key the intro is in, it probably isn't any of those. But I cannot determine which of those keys is the overall one. Even though the largest percentage of this piece is in E minor, that's its ending, non-starting key. I'm starting to give up on determining whether this piece has an overall key. Does this piece have an overall key?
Answer: I agree that specifically the /first/ key of the opening movement, or the key of its first subject (after any introduction) is a deciding factor. In some multi-movement works, even the opening movements begin in a  minor key and end in the tonic major. (And not just with a Tierce de Picardie.) For example:
C-V. Alkan. Grand duo concertante (Violin Sonata), op.21. (in f#)
Haydn. String quartet 59 ("Rider"), op.74 no.3 (in g)


How to check and get different part of a string

Question: I'm looking to have it so someone does !whisper EXAMPLE this is a test example.
It would output
$whisperuser as "EXAMPLE" & $whispermessage as "this is a test example".
<?php
    if (strpos($message, '!whisper') === 0) {
        $arr = explode(' ',trim($message));
        $whisperuser = $arr[1];
        $whispermessage = $arr[2]; // I need Whisper message to be anything arr[2] and HIGHER.
        // WOULD DO OUTPUT STUFF HERE
    }
?>

Answer: Your code can be written easy. After adding the 3rd argument to explode, it will put the rest of a string to the last item
list( , $whisperuser, $whispermessage) = explode(' ',trim($message), 3);

demo
Answer: Use preg_match for that. Assuming that user can't have space in name
$str = '!whisper EXAMPLE this is a test example';

$matches = [];

preg_match("/!whisper\s(\w+)\s(.*)$/", $str, $matches);

if (!empty($matches[1]) && !empty($matches[2])) {
    echo "Wispering to user {$matches[1]}: '{$matches[2]}'";
} else {
    echo "No actions taken!";
}

PHP Snippet and RegEx example

IF user can have space in name, than you must somehow specify where it's name ends. Because with your example whispering to some user new would be impossible if there is user some user.


The Type DefaultConventionScanner must be Convertible to ITypeScanner, StructureMap

Question: I've tried googling this in many ways and somehow this is the first generic seeming error message I haven't been able to find ANY results for.
Anyway, I'm upgrading my StructureMap to the newest version (I'm not sure what the last one I had installed was I'm afraid) and I keep getting the error: Error    1   The type 'StructureMap.Graph.DefaultConventionScanner' cannot be used as type parameter 'T' in the generic type or method 'StructureMap.Graph.IAssemblyScanner.With<T>()'. There is no implicit reference conversion from 'StructureMap.Graph.DefaultConventionScanner' to 'StructureMap.Graph.ITypeScanner'..
The code that's causing the problem is:
Scan(scanner =>
            {
                scanner.Assembly(typeof(PersonService).Assembly);
                scanner.AddAllTypesOf(typeof(IEntityService<>));
                scanner.AddAllTypesOf(typeof(IRootEntityService<>));
                scanner.With<DefaultConventionScanner>(); // This line
            });

Anyone have any ideas / experience with this sort of problem?
Comment: Did you try scanner.WithDefaultConventions()?
Comment: I did after I made the post as no responses were coming up :) I was going to set it as the answer in a few days, but since you got it you can have the points :D
Answer: Worked it out now, it should be replaced with scanner.WithDefaultConventions();


Parameter type lookup for out-of-namespace function definitions

Question: The software project I lead occasionally uses nested namespaces as a means of indicating which parts of the library are intended to be internal and should not be considered user-facing.  For example:
namespace project::detail {
  // Hands off; library implementation internals
  class Internal {};
  int important_number(Internal internals);
}

Before C++17, the indentation would become somewhat dreadful (depending on the source code formatting), so we opted for defining functions out-of-namespace:
int
project::detail::important_number(Internal const internals)
{ ... }

Observe that although the type Internal was declared and defined in the project::detail nested namespace, it is not required to fully qualify the parameter type (i.e.):
int
project::detail::important_number(/*unnecessary*/ project::detail::Internal)

I have scoured en.cppreference.com and bits of the C++14 standard and have not found the place(s) that support the abbreviated function definition (the first example above).  I am assuming the relevant rules did not change for C++17.  Can anyone tell me which rules of the C++14/17 standard apply here--i.e. where does the standard support non-fully-qualified parameter types for out-of-namespace function definitions?
Comment: For future reference, cppreference.com gives the particular rules for this situation in https://en.cppreference.com/w/cpp/language/unqualified_lookup
Answer: You're looking for unqualified name lookup and it can be found in the standard under basic.lookup.unqual

In the definition of a function that is a member of namespace N, a
  name used after the function's declarator-id shall be declared before
  its use in the block in which it is used or in one of its enclosing
  blocks  or shall be declared before its use in namespace N or, if
  N is a nested namespace, shall be declared before its use in one of
  N's enclosing namespaces.
Comment: I'm having trouble parsing the sentence--that appears to be referring to names used in a "block" or a nested "block."  But this is the use of the typename before the block--i.e. in the function type.  What am I getting wrong?
Comment: The standardese basically says that the declaration of `Internal` being used in `important_number` must appear in the nested namespace `detail` before being used by the definition of `important_number` (it is). So unqualified name lookup will successfully search the nested `detail` namespace of `project` and find `Internal`
Comment: @KyleKnoepfel I think `block in which it is used` and `enclosing blocks` basically just refer to the cases of e.g. local variable declarations in the function body. They do not really apply in the parameter list.


How to fix error Undefined index: parent in taxonomy_form_term_submit()?

Question: I got below error on my site recently.

Notice: Undefined index: parent in taxonomy_form_term_submit() (line 829 of /var/www/Sites/xxxxx/modules/taxonomy/taxonomy.admin.inc).

I google it and find there is an old issue but seems nothing solved.
In the issue, @Cracu did mention some part of core code may cause this error:
  if (!variable_get('taxonomy_override_selector', FALSE)) {
    $parent = array_keys(taxonomy_get_parents($term->tid));
    $children = taxonomy_get_tree($vocabulary->vid, $term->tid);

    // A term can't be the child of itself, nor of its children.
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
    $exclude[] = $term->tid;

    $tree = taxonomy_get_tree($vocabulary->vid);
    $options = array('<' . t('root') . '>');
    if (empty($parent)) {
      $parent = array(0);
    }
    foreach ($tree as $item) {
      if (!in_array($item->tid, $exclude)) {
        $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
      }
    }
    $form['relations']['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent terms'),
      '#options' => $options,
      '#default_value' => $parent,
      '#multiple' => TRUE,
    );

  }

I try to look into the latest core, this part of code is still there with same logics. Unfortunately, I need taxonomy_override_selector be TRUE.
Apart from setting taxonomy_override_selector to FALSE or adding new form validation handler to set $form_state['values']['parent'].
Do anyone know if there is solution for that?
Comment: You must of done something to cause it. What have you done recently? installed any custom module? contrib module? Do you have a backup(s) to check if the error is there or not?
Comment: I am working in a large project and there are so many changes / commits every day. It is very hard to say what have been changed. LOL
Answer: There's a couple of ways you could go about the problem:

Patch Core: If there's no outstanding issue for the problem, alter core, create a patch & bug report, and submit your patch. You can manage your patch in your deployment process until the patch is accepted upstream.
Custom Module: Looking at the comment above the code you posted, it was authored with the intention that someone might need to alter the form ("Contrib modules can then intercept before hook_form_alter to provide scalable alternatives."). You can use a HOOK_form_taxonomy_form_term_alter invocation to alter the submission handler or the form array to mitigate the warning introduced.


Pedal Notation with a cross or plus sign — is it supposed to be an asterisk?

Question:
Can someone help me with this unusual notation for pedal usage. It has P and +P does the +P mean pedal release? See attached photo please. The image is from the first measure Siloti's arrangement of Gluck's Orphée et Eurydice, Wq.41.
Comment: Melody (SECOND BALLET) from Orfeo Ed Euridice by GLUCK arranged for piano by Alexander Siloti who was a student of Tchaikovsky and famous pianist Franz Liszt
Answer: TL;DR
It's two separate symbols: the + indicates pedal release; the P means to reapply the pedal. The overall notation is to indicate a quick up-down of the pedal so that there is a "clean" start at the +P moment in the music (i.e., the previous two beats should not bleed over into the third beat).
The + symbol means the same thing as the more standard asterisk.
More ...
This can be seen more clearly when the + appears by itself at the end of the second measure (shown below) as well as in his arrangement of Bach's Cello Suite in Eb Major (second image below), this time without the connecting "slur" mark.

(IMAGE SOURCE: IMSLP)

(IMAGE SOURCE: IMSLP)
This particular marking appears to have been peculiar to Siloti — as opposed to being standard for the publisher, Carl Fischer. It is used in Siloti's two-piano arrangement of Bach's Brandenburg Concerto No. 2 (shown below) and in his arrangement of Saint-Saëns's Carnival of the Animals (second image below), but it does not appear in other Carl Fischer publications from the same time period.

(IMAGE SOURCE: IMSLP)

(IMAGE SOURCE: IMSLP)
Other symbols have been used at times to indicate pedal release. Two variants are shown in an answer to the question "Why does the pedal sign look like 'Leo'?"
Comment: Isn't that the usual modus operandi anyway?
Comment: It is if you are a pianist which i am not.
Answer: Up as you play the note, down again immediately.  A 'change of pedal'.  Very common pedalling technique.  A somewhat unusual way of notating it, but clear enough I think.
Comment: Would one use an asterisk instead of a + sign if that is what is desired by the  composer?
Comment: The problem is I am making an arrangement of this piece on Sibelius notation program.
Comment: @Rnmusik what symbol you use is entirely up to you, there's no real significant difference. There _is_ some discussion (of course there is!) on which symbols are the clearest in which situation.
Comment: @Rnmusik Probably best to use the symbols offered as standard in Sibelius then.  No-one will query them, and they'll even play back!


Coefficients of general Fourier Series

Question: I know how to compute coefficients of Fourier Series on an interval of $2\pi$. But in this case I need to find the sine series of $f(x)=b$ on the interval $x \in [-L,L]$. Can someone please let me know if the procedure for finding coefficients in this case is about the same, i.e. I can use the same formulae as for finding $a_n$ and $b_n$ on the interval of $2\pi$? Namely, $b_n = \int_{-\pi}^{\pi} f(x) \cos(nx)dx$? I have doubts about that.
I tried to find $b_n$ using the complex form, but got $c_n = 0$, which shouldn't be the case.
Any help would be much appreciated.
Answer: Assuming $f$ periodic with period $2L,$ it's Fourier series is
$$\frac{a_0}{2}+\sum\limits_{n=1}^{\infty}{a_n \cos{\left(\frac{n\pi x}{L}\right)} + b_n \sin{\left(\frac{n\pi x}{L}\right)}},$$
where
$$a_0=\frac{1}{L}\int
\limits_{-L}^{L} f(x) dx, \\
a_n = \frac{1}{L}\int\limits_{-L}^{L} f(x) \sin\left(\frac{n\pi x}{L}\right)dx,\\
b_n = \frac{1}{L}\int\limits_{-L}^{L} f(x) \cos\left(\frac{n\pi x}{L}\right)dx.$$

Coefficients of general Fourier Series


Is there a documented API for supporting the new Google Hangouts features so I can create a Hangout app for Windows Phone?

Question: I see the Hangouts API here, but it talks about creating an app that would integrate with the Google+ webapp.
https://developers.google.com/+/hangouts/api/gapi.hangout?hl=en
I'm looking to create a client so Windows Phone users can chat with their friends on other platforms as well, but can't find too much information on how to get started here.
The quick start for .NET/C# doesn't really help much for this either. I was able to get the PeopleFeed but there is no mention of a list of current hangouts, start a new hangout, etc... Did they not make this public yet? Will they ever?
https://developers.google.com/+/quickstart/csharp#step_1_enable_the_google_api
Answer: There currently are not Google+ libraries that will work on Windows Phone and the API currently does not support starting hangouts. You can request these features from the Google+ Developers issue tracker.


Solution of the Beast in Disguise $y'=x-y^2$

Question: $y'=x-y^2$
Its a first-order nonlinear ordinary differential equation. The solution is given here http://www.wolframalpha.com/input/?i=solve+y%27%3Dx-y%5E2&x=0&y=0.
But how is it obtained? Whats happening here? Direct answers are appreciated, If not possible I will do with a few links to know more about these kind of equations. And some more personified help.
Comment: It's a Ricatti equation. https://en.wikipedia.org/wiki/Riccati_equation Also see https://math.stackexchange.com/questions/99850/how-can-i-solve-the-differential-equation-yy2-fx?rq=1
Comment: You've effectively just specified an easy-to-state difficult-to-calculate integral. Integrals don't have to be nice even if they're easy to state.
Comment: Yes, its easy to state, but its the hard part that's where I am interested in.
Comment: I appreciate it. Thanks
Answer: $y'=x-y^2$ is Riccati ODE classically solved thanks to a change of function, in this case :
$$y=\frac{f'}{f}$$
$y'=\frac{f''}{f}-\frac{f'^2}{f^2}$
$$\frac{f''}{f}-\frac{f'^2}{f^2}=x-\left(\frac{f'}{f}\right)^2$$
$$f''=x\:f$$
This is an Airy ODE. The solutions are the Airy functions $\text{Ai}(x)$ and $\text{Bi}(x)$ which derivatives are  $\text{Ai}'(x)$ and $\text{Bi}'(x)$
$$y(x)=\frac{f'}{f}=\frac{c_1 \text{Ai}'(x) +c_2 \text{Bi}'(x)  }{c_1 \text{Ai}(x)  +c_2 \text{Bi}(x)  }$$
Alternatively all can be expressed in terms of Bessel functions. So, $y(x)=\frac{f'}{f}$ is a fraction of Bessel functions.
Comment: I doubt that "a more simplified version" exists. If your problem is raised on a lower level of mathepatics, probably there is something fishy. Are you sure of the ODE ?. Is there no information in addition which allows to bring to a less general case (for example particular boundary conditions or something else) ?. Can you give more details about the context of the question. The best should be to give the original wording of the problem from which the ODE is coming.
Comment: I am not much affiliated to this deep mathematics but as always, thanks for the heads up. A more simplified version will be as good.
Comment: Accepted it as answer. The question came to my mind, I tried to solve it, I couldn't, Then I viewed its solution in wolfram alpha,. Hence i wanted to know more about ODE, and the method to obtain the solution.
Comment: It is valuable to know more about ODEs. Also it is valuable to know more about special functions because many solutions of ODEs involve special functions. The ODE $f''=xf$ is a good example requiring some knowlege about Airy or Bessel Functions. There is a paper for general public : https://fr.scribd.com/doc/14623310/Safari-on-the-country-of-the-Special-Functions-Safari-au-pays-des-fonctions-speciales


problemas lista em python

Question: Estou tentando resolver este problema em python:
Faça um programa que carregue uma lista com os modelos de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc). Carregue uma outra lista com o consumo desses carros, isto é, quantos quilômetros cada um desses carros faz com um litro de combustível.
Calcule e mostre:

O modelo do carro mais econômico;
Quantos litros de combustível cada um dos carros cadastrados consome para percorrer uma distância de 1000 quilômetros e quanto isto custará, considerando um que a gasolina custe R$ 2,25 o litro.

Abaixo segue uma tela de exemplo. O disposição das informações deve ser o mais próxima possível ao exemplo. Os dados são fictícios e podem mudar a cada execução do programa.
Comparativo de Consumo de Combustível
Veículo 1
Nome: fusca
Km por litro: 7
Veículo 2
Nome: gol
Km por litro: 10
Veículo 3
Nome: uno
Km por litro: 12.5
Veículo 4
Nome: Vectra
Km por litro: 9
Veículo 5
Nome: Peugeout
Km por litro: 14.5

Relatório Final
 1 - fusca           -    7.0 -  142.9 litros - R$ 321.43
 2 - gol             -   10.0 -  100.0 litros - R$ 225.00
 3 - uno             -   12.5 -   80.0 litros - R$ 180.00
 4 - vectra          -    9.0 -  111.1 litros - R$ 250.00
 5 - peugeout        -   14.5 -   69.0 litros - R$ 155.17

O menor consumo é do peugeout.
Aqui em cima é como deve ficar. Segue meu código abaixo e o que está faltando fazer. Neste código que enviei só não estou sabendo como achar o menor valor do consumo, para imprimir o carro. Se alguém poder me ajudar agradeço.
Meu código:
listaCarro = [None] * 5
listaConsumo = [None] * 5
listaDistancia = [None] * 5
listaCusto = [None] * 5

precoGasolina = 2.25
distancia = 1000

for i in range(0,5):
    print ('Digite o nome {} carro: '.format(i+1))
    listaCarro[i] = input()

for x in range(0,5):
    print('Digite o consumo {} carro (km por litro): '.format(x+1))
    listaConsumo[x] = float(input())
    listaDistancia[x] = distancia / listaConsumo[x]
    listaCusto[x] = listaDistancia[x] * precoGasolina

for j in range(0,5):
    print('Veiculo {}'.format(j+1))
    print('Nome: {}'.format(listaCarro[j]))
    print('Km por litro: {}'.format(listaConsumo[j]))

for p in range(0,5):
    print('{} - {}    -    {}  -  {} litros - R$ {}\n'.format(p+1, listaCarro[p], listaConsumo[p], round(listaDistancia[p],1), round(listaCusto[p],2)))

Answer: Consoante os dados que apresentas podes fazer os calculos todos de uma só vez (no mesmo ciclo), assim como podes popular as duas listas também no mesmo ciclo:
listaCarro = []
listaConsumo = []

while len(listaCarro) < 5:
    listaCarro.append(input('Digite o nome do carro: '))
    listaConsumo.append(float(input('Digite o consumo do carro (km por litro): ')))
    print('novos dados inseridos\n')

results = ''
valor_gas = 2.25
total_km = 1000
for j, c in enumerate(listaCarro):
    print('Veiculo {}'.format(j+1))
    print('Nome: {}'.format(c))
    print('Km por litro: {}\n'.format(listaConsumo[j]))

    consumo_l = round(total_km/listaConsumo[j], 2)
    results += 'O carro {} consume {}L e custará $R{} quando fizer {}km\n'.format(c, consumo_l, round(consumo_l*valor_gas, 2), total_km)

print('O carro mais económico é o {}'.format(listaCarro[listaConsumo.index(max(listaConsumo))])) # descobrir na listaCarro o carro cujo o indice e o mesmo do que o indice do maior valor na listaConsumo
print(results)

DEMONSTRAÇÃO
NOTA: o carro que faz mais km por litro é o mais económico
Answer: Outra solução, mais simples, porém fugindo do que foi solicitado explicitamente pelo enunciado, seria criar um objeto namedtuple para representar um determinado carro ao invés de armazenar os valores em listas distintas.
from collections import namedtuple
from operator import attrgetter

Carro = namedtuple('Carro', ('nome', 'rendimento'))

carros = [
  Carro(nome='Fusca', rendimento=7.0),
  Carro(nome='Gol', rendimento=10.0),
  Carro(nome='Uno', rendimento=12.5),
  Carro(nome='Vectra', rendimento=9.0),
  Carro(nome='Peugeout', rendimento=14.5)
]

carro_mais_economico = max(carros, key=attrgetter('rendimento'))

print('Mais econômico:', carro_mais_economico.nome)

for i, carro in enumerate(carros):
  consumo = 1000 / carro.rendimento
  gasto = 2.25 * consumo
  print(f'{i+1} - {carro.nome:<10} - {carro.rendimento:>5} - {consumo: >6.2f} - R$ {gasto:.2f}')

Veja funcionando no Repl.it
O resultado seria:
Mais econômico: Peugeout
1 - Fusca      -   7.0 - 142.86 - R$ 321.43
2 - Gol        -  10.0 - 100.00 - R$ 225.00
3 - Uno        -  12.5 -  80.00 - R$ 180.00
4 - Vectra     -   9.0 - 111.11 - R$ 250.00
5 - Peugeout   -  14.5 -  68.97 - R$ 155.17

problemas lista em python


Javascript gallery works only once

Question: I've made a simple image gallery using W3.css and javascript. Each image is a w3-card with text under it and takes one third of the screen (using w3-third). I got the javascript to zoom the image and move it the front ( so it is visible) on click and make it go back on second click. The proble is, once the image goes back, clicking it does nothing. Here is the code for the gallery.html (without the header, as it has nothing to do with gallery)
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Strona Główna</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet"
href="http://www.w3schools.com/lib/w3-theme-light-green.css">

image 1

image 2

img3

Copyright© killermenpl 2015. All rights
        reserved

        Uses
        W3.css

And here is the code for galeria.js
function onClick(element) {
//alert("onclick");
// if (element.tagName != "img") {
// alert("not an image");
// return;
// }

if (!element.dataset.zoom) {
    element.dataset.zoom = "0";
}

if (element.dataset.zoom == "0") {
    element.dataset.zoom = "1";
    element.dataset.zindex = element.style.zIndex;

    element.style.position = "relative";
    element.style.zIndex = 100;

    element.style.width = "300%";
    element.style.height = "300%";

    //alert("zoom!");
} else {
    //alert("zoom!");
    element.style.zIndex = element.dataset.zindex;

    element.dataset.zoom == "0";

    element.style.width = "100%";
    element.style.height = "100%";
}
}

It's probably something stupid that everyone should know about, but I'm new to javascript and kind of new to css. Also, I know the images don't align to the middle of the screen when zoomed in. I'll add it later.
Comment: where is `onClick()` assigned   to any event
Comment: I copied my index.html instead of gallery.html. My bad. Fixing it right now. There isn't much difference. Basically every  has `onclick="onClick(this);"`
Answer: Change this line in the else statement :
element.dataset.zoom == "0";

to this:
element.dataset.zoom = "0";

for assignments you should use '=' instead of '=='.
And if you want images to zoom at its center origin you should use CSS3 trasform: scale(x,y); attribute and scale the element. for example:
element.style.transform = "scale(1.5,1.5)";

and for webkit browsers:
element.style.webkitTransform = "scale(1.5,1.5)";

Comment: Thanks! I knew it was something trivial. I think I need to get a new keyboard, as I've noticed this one sometimess registers one click twice.

Javascript gallery works only once


Helmholtz decomposition of smooth vector field with compact support

Question: Im trying to show that if we apply the Helmholtz decomposition on a smooth vector field $\mathbf{f} \in C^\infty_c(\Omega)^d$ with compact support, then the gradient potential is also smooth and has compact support:
$\qquad \mathbf{f} = \nabla \phi + \mathbf{\psi},\qquad \phi \in C^\infty_c(\Omega), \psi \in C^\infty(\Omega)^d, \nabla \cdot \psi = 0$.
Im assuming $\Omega$ to be Lipschitz.
I looked through some proofs in the smooth case (e.g. The proof of the Helmholtz decomposition theorem through Neumann boundary value problem) where use was made of the Dirichlet fundamental solution $\Phi$:
$\phi(x) = -\int_\Omega \Phi(x-y)\nabla_y\cdot\mathbf{f}(y)dy + \int_{\partial \Omega}\Phi(x-y)\mathbf{f}(y)\cdot\mathbf{n}dS(y)$
$\psi(x) = \nabla\times(\int_\Omega \Phi(x-y)\nabla_y \times \mathbf{f}(y)dy-\int_{\partial \Omega}\Phi(x-y)\mathbf{n}\times\mathbf{f}(y)dS(y))$.
Initially I thought compact support on $f$ would induce compact support on $\phi$, but its not that easy. The Evans contains a theorem (Thm. 1, p. 23) stating that if $f$ is $C^2_c(R^n)$-smooth with compact support, then the singularity of the fundamental solution just renders $u(x) = \int_{R^n}\Phi(x-y)f(y)dy$ to be $C^2(R^n)$ WITHOUT compact support. Thus, currently I don't think I can show the existence of such a potential. What do you think?
Cheers, Uplink
Comment: If $f=0$ for $|x| \ge R$, then $\nabla\cdot f = 0$, gives $\nabla^2\phi=-\nabla\cdot\nabla\times F=0$ for $|x| > R$. Maybe it's possible to add something in the far field by sacrificing some smoothness at a chosen boundary?
Answer: I remember one lemma, hope it would give you some help. Let $B$ be a rectangle in $R^d$, $\phi\in C_c^\infty(B)$ with $\int_B\phi dx=0$. Then the divergence equation $$\nabla\cdot\psi=\phi,\ \ in\ \ B$$ has a solution $\psi\in C_c^\infty(B)^d$.


Selecting Threshhold from ROC curve

Question: I plotted an ROC curve for a classification problem and I am looking a way to find out the threshold point for the left most top point - Highest TPR and low FPR. How do I do it in Python ?
Comment: The point of the ROC curve is that it tells you the *trade-offs* of each operating point. You can always detect more positives by lowering the threshold, but this comes with the cost of increasing the FPR (except for the trivial ROC with AUC=1). Picking the **highest TPR** is tautologically the same as choosing the point (1,1), because this is the point that detects all positives *at the cost of also retrieving all false positives*. Therefore, your description of the "top leftmost" point needs some clarification: what kind of a tradeoff do you want between TPR and FPR?
Comment: For example, one way to think about the ROC curve is the Youden's $J$ index, which measures the vertical distance from random classification to each operating point. A certain kind of trade-off is attained by choosing the point that maximizes $J$, maximizing $J$ isn't universally the best option because the tradeoff between TPR and FPR might not be appropriate for any particular task. https://en.wikipedia.org/wiki/Youden%27s_J_statistic
Comment: Unfortunately, there's no way to answer this other than saying that you choose the operating point that matches your needs -- I can't tell you what the trade-offs are, because I don't know the equities involved, and how I value the outcomes might differ from how you value them. You'll have to ask yourself how many FPRs are you willing to incur to achieve a certain level of TPR.
Comment: I completely get your point but then how do I select the optimal threshold point ?
Comment: Thank you so much, your answer really helped me to arrive at conclusion that selecting threshold is completely subjective.
Answer: Unfortunately, there's no way to answer this other than saying that you choose the operating point that matches your needs -- I can't tell you what the trade-offs are, because I don't know the equities involved, and how I value the outcomes might differ from how you value them. You'll have to ask yourself how many FPRs are you willing to incur to achieve a certain level of TPR.
The point of the ROC curve is that it tells you the trade-offs of each operating point. You can always detect more positives by lowering the threshold, but this comes with the cost of increasing the FPR (except for the trivial ROC with AUC=1). Picking the highest TPR is tautologically the same as choosing the point (1,1), because this is the point that detects all positives at the cost of also retrieving all false positives. Therefore, your description of the "top leftmost" point needs some clarification: what kind of a tradeoff do you want between TPR and FPR?
For example, one way to think about the ROC curve is the Youden's $J$ index, which measures the vertical distance from random classification to each operating point. A certain kind of trade-off is attained by choosing the point that maximizes $J$, maximizing $J$ isn't universally the best option because the tradeoff between TPR and FPR might not be appropriate for any particular task.

Selecting Threshhold from ROC curve


Can a basketball player play in college after playing in the NBA?

Question: If an NBA player never played at the collegiate level, can he ever play for an NCAA Division 1 team?  Thinking about LeBron, Kobe, Kevin Garnett, etc.  Surely the NCAA prevents anyone with active professional status to do so, but what about free agents or retirees?
I couldn't find much more than this NCAA page on Amateurism, from which I couldn't discern an answer to my question.
If LeBron retires tomorrow and forfeits any remaining contracts and salaries, would he be eligible to go play for a Division 1 NCAA team?
Answer: According to the NCAA, there are required steps in order to become a college athlete.  One of them is registering with the Eligibility Center.  In the typical situation, that's done during grade 10 in high school.  The NCAA Eligibility Center is responsible for reviewing the Amateurism requirements you linked in your post.  The center uses the information gathered from the athlete to provide a certification of amateurism.  Lebron would be considered a college bound student athlete, and so…

As part of the process, each college-bound student-athlete is asked to
  answer several questions regarding his or her sports-participation
  history. This is to capture a better picture of the prospect's amateur
  status and to identify any potential issues that might conflict with
  NCAA rules. If the answers indicate a possible violation, the
  amateur-certification staff will work with the school to determine the
  facts. If the agreed-upon facts indicate a violation occurred, an
  eligibility penalty will be imposed based on the severity of the
  violations. Penalties include repayment of money, sitting out a
  specified number of games or, in rare cases, permanent ineligibility.

And, while there is no definitive statement suggesting he would be ineligible, given the following eligibility review criteria from the Center,

Contracts with a professional team.
Salary for participating in athletics.
Prize money.
Play with professionals.
Tryouts, practice or competition with a professional team.
Benefits from an agent or prospective agent.
Agreement to be represented by an agent.
Delayed initial full-time collegiate enrollment to participate in
organized sports competition.

I would suggest that after review, he would not be eligible to play.


SQL LEFT and patindex

Question: I am trying to write a select query that takes off the leading zeros and takes of all characters that are not numeric.  I figured out how to do one or the other just not both at the same time.
So far I have:
SELECT
    Substring(rt_VehicleName, patindex('%[^0]%', rt_VehicleName), +4),
    [rt_Odometer],
    [rt_CumHours],
    [Date],
    [Emco]

FROM
    [GPS_Data].[dbo].[Engine_Hours]

and the results are 28 S. I want to get rid of the S
Comment: Great!  You seem to be learning SQL.  If you have a question, follow the guidelines on the site for asking a question.
Comment: What have you got for your LEFT() and PATINDEX() queries?  It'd be easier to combine them if you edit your question and show what you've already got.
Comment: SELECT Substring(rt_VehicleName, patindex('%[^0]%',rt_VehicleName),+4)
      ,[rt_Odometer]
      ,[rt_CumHours]
      ,[Date]
      ,[Emco]
  FROM [GPS_Data].[dbo].[Engine_Hours]                                                    The results are 28 S.  I want to get rid of the S
Answer: This query seems overcomplicated but it works in my data.
select top 10 SUBSTRING(LEFT(SUBSTRING([Your Column Here], PATINDEX('%[0-9.-]%', [Your Column Here]), 8000), PATINDEX('%[^0-9.-]%', SUBSTRING([Your Column Here], PATINDEX('%[0-9.-]%', [Your Column Here]), 8000) + 'X') -1), PATINDEX('%[^0]%', [Your Column Here]+'.'), LEN([Your Column Here])) as 'No 0s or Letters', * from [Your Table Here]

SQL LEFT and patindex


How to calculate PCB byte for apdu command

Question: I need simple example for calculate PCB bit for APDU command. For example I have command select aplet:
<code>{ 0x00, 0xA4, 0x04, 0x00, 0x06, 0x9A, 0xFC, 0xC3, 0x22, 0x88, 0x91 };
</code>
were byte is:

CLA
INS
P1
P2
Len
Aplet ID(6 byte)

How I can calculate PCB for its command?
I know that it byte must be '0x02', but how to calculate it dynamically?
Thank you!
Answer: Google Books has the "Smart Card Handbook By Wolfgang Rankl, Wolfgang Effing". It has tables 9-5 through 9-7 which give the PCB format.


Guitar String Ringing

Question: My guitar string is ringing after the intended note duration and I am having a hard time muting the open strings. It is like the LET RING technique of guitar. So when do you know if you should stop the strings from resonating or letting it ring?
Comment: By listening very carefully, and deciding which way you play it sounds better. More effective than trying to abide by 'rules', which won't apply in all cases anyway.
Answer: Traditional classical guitar methods (e.g. Carcassi) teach one to let the open strings ring in resonance with the notes played to increase overall volume and improve the tone of the guitar.  This is not the same thing as stopping a plucked note once the sheet music indicates that its time is over.
As Tim's comment points out this is somewhat of a personal choice that should be motivated by whether it sounds good.
There are some principals that can be used to make good choices.  Here are few examples.

If you are playing a piece that is mostly open string chords and the ringing is in tune with the rest of the notes, let it ring as that will generally help with volume and tone and not be dissonant.
If the music states that notes are separated then you should try and mute them.  If you are playing written pieces from sheet music then there are probably instructions for what the composer or arranger intended the music to sound like.
Regardless of the situation, if some of the melody or chords change key but open strings are still resonating in another key then you should probably mute them.  It often happens that a piece will change from minor to major on the same root, or there may be a chromatic passing chord.  Take, for example, C maj going to C min.  If you play the open C maj chord with the 3rd on the D string the open E string will vibrate in sympathetic resonance.  This will be loud enough to hear even when you lift the C chord up to mute it.  If you were to play C- after C by lowering the E to Eb on the D string that would create a (E, Eb) harmony.  The E harmonic would die soon enough and if the Eb were plucked you may not hear the dissonance or be offended by it.  Really, you need to play with some of these and decide for yourself what you like and don't like.  Some people may find the conflict between the open harmonics and the other notes interesting.
If the resonance becomes deafening and the true melody and harmony are hard to distinguish then it's time to mute.  This can happen.  On a really good acoustic guitar each new note plucked will feed energy to the resonating open strings, especially if the note matches one of the natural harmonics.  Depending on the situation this can cause "reverb" to increase and eventually become too much.  This is especially important if the dynamics are piano or quieter.
If you are playing something fast chances are that the quick release of the fingers to the next note will be enough to shorten the sound, but there is also the chance of creating open string notes every time you lift.  This is where practice and good technique come in.  You just need to practice developing a delicate sense of touch and you will be able to move without creating scrapes, squeaks, clicks, and open string hiccups.
Lastly, if the piece is meant to be percussive then you may be playing with the edge of your hand on the strings or slapping down between chords to stop everything.

Keep in mind there are competing factors in the decision.  You may be trying to play a piece that everyone knows and want it to be faithful to the artist.  You may be trying to develop your own style.  Or, you may be trying to get through a music curriculum with guitar as your instrument.  What sounds good to you may not to others, or to your instructor.  Also, sometimes we just default to what is easy rather than develop good technique.  You can work on a piece and take advantage of open string resonances only to hear a judge or your teacher say "why are you letting it ring like that, sounds awful" or you may mute and hear "it sounds dead, let the strings ring".  If you are serious about getting the techniques correct, (1) take lessons, and (2) try multiple ways of playing the same piece until you converge on an approach that you really like.  Then your choice is an artistic one.

Guitar String Ringing


Como criar um sistema para gerar hashes e conseguir quebrar sem a string original?

Question: Existe alguma forma de quebrar o Sha-256? Existe um processo matemático para conseguir quebrar?
Preciso criar um programa que gera vários hashes e outro para quebrar sem ter a string original (Similar ao Bitcoin), apenas usando o processamento.
Comment: O sistema do bitcoin não quebra. Ele estabelece um limite para o que é um hash "aceitável" (ex.: 10 zeros à esquerda) e qualquer hash que satisfaça essa condição é aceito no *blockchain*. Se um valor *exato* fosse necessário, nem todos os mineradores do mundo conseguiriam quebrar um único hash...
Comment: Relacionado: ["Como funciona exatamente o algoritmo SHA-256"](http://pt.stackoverflow.com/q/97566/215)
Comment: Não dá. Esses hashes criptográficos são feitos justamente pra ser muito difícil adivinhar a entrada.
Comment: Mas como o sistema de mineração do bitcoin consegue quebrar?
Comment: Eu sei que o algoritmo resolve quebra-cabeças matemáticos, mas não entendo como é o processo.
Answer: O SHA-256, como qualquer sistema de hash bem feito, é resistente a pré-imagem ("função de mão única"). Isso significa que, dado o valor de um hash, é impraticável se descobrir (com alta probabilidade) algum dado que dê origem àquele hash. Assim, a única maneira conhecida de se "inverter o hash" é gerando uma grande quantidade de dados e hasheando-os um a um, até chegar no mesmo resultado do hash original.
Como o SHA-256 é um hash bastante rápido - e facilmente paralelizável - é possível quebrar muitos hashes caso o dado original seja uma string razoavelmente curta (ex.: senhas típicas de usuários). Por essa razão ele é frequentemente usado em conjunto com um sal, que é um valor aleatório que é concatenado ao dado antes do mesmo ser hasheado, e então salvo junto com o valor do hash. Se esse sal for suficientemente longo (hoje em dia usa-se 64 bits, creio eu, mas para garantir é melhor 128 ou mais) então é totalmente impraticável inverter o hash - pois o número de tentativas necessárias pra acertar é superior ao poder computacional combinado de toda a humanidade.
(Falei bobagem: a dificuldade para inverter um hash é a mesma, usando sal ou não; o sal evita somente que você quebre muitos hashes usando um único processamento. Não use SHA-256 para proteger senhas, ou qualquer outro dado de baixa entropia. A menos que você consiga manter o sal secreto, é claro, mas aí ele é chamado de "chave" e a construção resultante é uma forma de MAC.)
Nota: você menciona o Bitcoin, mas o sistema de mineração do Bitcoin não inverte hashes em nenhuma parte de sua operação. O que é feito é pegar o hash do bloco que está sendo formado (inclui o hash de todo o blockchain atrás dele, numa estrutura conhecida como Merkle Tree) e anexar um valor aleatório, hasheando e vendo se o resultado satisfaz a ao critério de dificuldade da rede. Esse critério é basicamente verificar se o valor final é menor ou igual a um valor arbitrário, que é ajustado pra cima ou pra baixo dependendo do poder de processamento combinado de toda a rede Bitcoin (estimado conforme a frequência com que novos blocos são criados, em comparação com o alvo de 1 bloco a cada 10 minutos).


.sh to .bat files converting

Question: I need to convert a .sh file to a .bat file but don't know the right syntax. I already done some translations I've found but I'm not really sure about all sh syntax. Very thanks for all advices you can give to me.
Here is what I've done so far :
<code>setlocal
rem!\bin\bat`enter code here`

    rem *****************************************************
    rem * Setting up the JBOSS local variables
    rem *****************************************************

    if [ "x%PROJECT_DIR%" = "x" ]; then
        DIRNAME=`dirname $0`
        PWD="$( cd -P "$DIRNAME" && pwd )"
        SET PROJECT_DIR="$( cd -P "$PWD" && pwd )"
    fi
    SET JBOSS_DIR=%PROJECT_DIR%\..\..\nqi\4.3\nqi\orchestra\jboss
    SET SERVER_HOME_DIR=$JBOSS_DIR\orchestra
    SET PORTFOLIO_CONFIG=%PROJECT_DIR%\..\..\nqi\4.3\nqi\orchestra\applications\custom\portfolio
    rem *****************************************************

    echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    echo ""
    echo "DIRNAME = %DIRNAME%"
    echo "PROJECT_DIR = %PROJECT_DIR%"
    echo "SERVER_HOME_DIR = %SERVER_HOME_DIR%"
    echo ""
    echo "  nqidb-ds.xml deployement"
    rm -f %SERVER_HOME_DIR%\deploy\nqidb-ds.xml
    cp -Tfv %PROJECT_DIR%\dev_stuff\nqidb-ds.xml %SERVER_HOME_DIR%\deploy\nqidb-ds.xml

    echo ""
    echo "  ui properties deployement"
    rm -rf %PROJECT_DIR%\applications\local
    mkdir %PROJECT_DIR%\applications\local
    mkdir %PROJECT_DIR%\applications\local\nqi-ui
    cp -Tfv %PROJECT_DIR%\dev_stuff\nqi-ui.properties %PROJECT_DIR%\applications\local\nqi-ui\nqi-ui.properties

    echo ""
    echo "  workflow deployement"
    mkdir %PROJECT_DIR%\applications\local\workflow
    cp -Tfv %PROJECT_DIR%\dev_stuff\workflow-config.xml %PROJECT_DIR%\applications\local\workflow\workflow-config.xml

    echo ""
    echo "  license deployement"
    mkdir %PROJECT_DIR%\applications\local\license
    cp -Tfv %PROJECT_DIR%\dev_stuff\nqi.license %PROJECT_DIR%\applications\local\license\nqi.license

    echo ""
    echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    echo ""
    echo "  JBoss Starting..."
    %JBOSS_DIR%\bin\run.bat endlocal
</code>
Comment: For `if [ "x%PROJECT_DIR%" = "x" ]; then` try a look at [What is the proper way to test if variable is empty in a batch...](http://stackoverflow.com/questions/2541767/what-is-the-proper-way-to-test-if-variable-is-empty-in-a-batch-file-if-not-1)
Comment: I'm voting to close this question as off-topic because Stack Overflow is not a code rewriting service.
Comment: Type `help` at the cmd prompt to see a list of commands you can use. To get help for a particular command you can type `help if` or `if /?`
Answer: Unfortunately this is a case where you just have to try & test until you get it right.
You are on the right track, and i dont think any advise you will get here will speed up the process much.
Identify the command in the sh file, google it for the bat equivalent syntax, add that to your new file and test. once you are sure that portion works as expected in your environment, move on to the next line.
As these files are "mostly" linear, read from top to bottom, it makes testing each line quite a bit easier.
Comment: Ok thanks to you for you answer ;)

.sh to .bat files converting


Lm adding coefficients for different level of variable

Question: I am testing out the lm function for multiple linear regression. One of my predictors, X, is categorical and has 2 levels (there are 2 labels that the observation could take on for this variable). Then I have some numeric predictors, and another categorical predictor, Y, which has levels (3 different labels that each observation could take on for this variable). When I use lm, variable X just shows up in the summary with one coefficient as I would expect, but then there are 2 coefficients in the model for variable Y, which are written as YName1 and YName2 (and not for name3). Why is this? Shouldn't there only be one coefficient for each predictor, and why is variable Y any different from variable X? My model is just specified as
model <- lm(dependent ~ X + ... + Y, data=data)

Any help would be appreciated.
Comment: See https://stats.stackexchange.com/questions/14005/linear-regression-with-factors-in-r/14029,   https://stats.stackexchange.com/questions/261274/linear-regression-with-categorical-variables-what-are-the-estimates-of-referen,   https://stats.stackexchange.com/questions/13353/interpreting-coefficient-in-a-linear-regression-model-with-categorical-variables and especially https://stats.stackexchange.com/questions/438599/why-is-my-categorical-variable-split-up-into-separate-variables-in-my-regression
Answer: Some additional information to help you to move forward with categorical variable...
When dealing with categorical variable (which can be enforced using factor() to make sure that R does not treat it as another type), the reference is actually included in the intercept:
require(datasets); data(InsectSprays)
model1 <- lm(count ~ spray, data = InsectSprays)
summary(model1)$coefficients

##                Estimate Std. Error    t value     Pr(>|t|)
## (Intercept)  14.5000000   1.132156 12.8074279 1.470512e-19
## sprayB        0.8333333   1.601110  0.5204724 6.044761e-01
## sprayC      -12.4166667   1.601110 -7.7550382 7.266893e-11
## sprayD       -9.5833333   1.601110 -5.9854322 9.816910e-08
## sprayE      -11.0000000   1.601110 -6.8702352 2.753922e-09
## sprayF        2.1666667   1.601110  1.3532281 1.805998e-01

So, here, spray A is included in the intercept and its value is 14.5. Since it is the reference, all the other coefficients are given based on this value (they are compared with the reference sprayA). For instance, the coefficient for sprayB is 14.5 + 0.833 = 15.333. The coefficient for sprayC is 14.5 - 12.416 = 2.084.
If you want to get the coefficient value of each spray category, you can also do the following (subtracting by 1) which remove the intercept:
model2 <- lm(count ~ spray - 1, data = InsectSprays)
summary(model2)$coefficients

##         Estimate Std. Error   t value     Pr(>|t|)
## sprayA 14.500000   1.132156 12.807428 1.470512e-19
## sprayB 15.333333   1.132156 13.543487 1.001994e-20
## sprayC  2.083333   1.132156  1.840148 7.024334e-02
## sprayD  4.916667   1.132156  4.342749 4.953047e-05
## sprayE  3.500000   1.132156  3.091448 2.916794e-03
## sprayF 16.666667   1.132156 14.721181 1.573471e-22

Which is equivalent to what we calculated manually earlier.
Finally, if you want to change your reference, you can use the relevel() function:
sprayDRef <- relevel(InsectSprays$spray, "D")
model3 <- lm(count ~ sprayDRef, data = InsectSprays)
summary(model3)$coefficients

##              Estimate Std. Error   t value     Pr(>|t|)
## (Intercept)  4.916667   1.132156  4.342749 4.953047e-05
## sprayDRefA   9.583333   1.601110  5.985432 9.816910e-08
## sprayDRefB  10.416667   1.601110  6.505905 1.212803e-08
## sprayDRefC  -2.833333   1.601110 -1.769606 8.141205e-02
## sprayDRefE  -1.416667   1.601110 -0.884803 3.794750e-01
## sprayDRefF  11.750000   1.601110  7.338660 4.035610e-10

Here, all the different spray category coefficients are compared with spray D.
Comment: Thanks for the answer, how do I know whether R is treating the variable as a type or not? When I use factor() on the variable in the lm statement (which I read you can do), it says 1:
  the response appeared on the right-hand side and was dropped
2: Problem with term in model.matrix: no columns are assigned
Comment: If your variable is categorical but coded as numeric (for instance, if in the example above, spray (A, B, C... F) is coded with (1,2,3...,6)), R will take it as numeric. You can check the type of the variable with the command `class()`. Not sure to understand the second part of your problem... Is this what you get when you run `model <- lm(dependent ~ factor(X) + ... + Y, data=data)` (if I take your original example)?
Answer: Actually when you have a categorical predictor such as yours, coefficients are computed regarding a reference value.
Thus, if Y can be "a" "b" or "c" , you have coefficients for "b" and for "c", no coefficients standing for a "baseline" value which is Y = "a".
You can do it differently by constructing 3 "dummy variables" mutually exclusives

Ya = 0 if non a and 1 if a
Yb = 0 if non b and 1 if b
etc.

Hope I have helped :)
Comment: I see, so since variable X only has two levels it only needs one dummy variable right?
Comment: If I want to test the model with/without the variable Y, do I remove the entire variable Y or do I remove one level of Y at a time?
Comment: Exactly : X is a binary variable so it counts for one dummy variable.
Comment: I think you should remove the entire variable but it depends on what you want to test.


current url javascript binding into html

Question: http://pastebin.com/KejQT7XQ
i am trying to bind current url of my page to this html
how can i do that
Answer: You may want to try to create your iframe dynamically:

Content

Content

Answer: Use window.location.href or window.location.pathname expressions if you don't need the full url


Tangent to integral curve

Question: I have an equation like:
$$4y'=y(x^2-4x-3)$$
and I have to find the equation to the tangent to the integral curve, which goes through a random point from the square $K =$ $\{-5≤x≤6,-6≤y≤5 \}$. I am confused by the square part. What is actually wanted here, me choosing a point that I like, or is there something more to it?
Comment: For a safe answer, consider that the point can be anywhere in the given square, and make sure to analyze if there are no "special behaviors" somewhere in it (like undefined tangent - as regards me, I don't see any).
Answer: I think that you just need to pick a random number, a, from 0 to 1 and pick another random number, b, also from 0 to 1. Then $x_0=-5+11a$ and $y_0=-6+11b$. So point $(x_0,y_0)$ is a random point in the specified square.
A line with known slope $k_0$ and going through a point $(x_0,y_0)$ is given by:
$$ y-y_0=k_0 (x-x_0) \text{   (1)}$$
The explicit expression of your curve is given by:
$$y(x)=C \exp\left(\frac{1}{12}(x^2-6x-9)\right)$$
To make sure that point $(x_0,y_0)$ is on the curve, we solve $C$ from
$$y_0=C \exp\left(\frac{1}{12}(x_0^2-6x_0-9)\right)$$
Since
$$k(x)=\frac{dy(x)}{dx}=\frac{1}{4}y(x)(x^2-4x-3)$$
You may get the desired equation by setting $k_0=k(x_0)$ in (1).
Comment: well, apart from the $$x_0=−5+11a$$ and $$y_0=−5+11b$$ I kind of did the same thing, hope the assistant doesn't rage at me...
Comment: @MarioStoilov I added formula $y(x)$ and made sure that point $(x_0,y_0)$ is on the curve.
Comment: @MarioStoilov Good. You are on the right track. By the way, I just corrected the value for $y_0$ according to your original question. Can you double check?
Comment: yea, didn't notice that. It's ok
Comment: hmm, I actually am having a problem with the tangent. What equation do you get for it?
Comment: from your original equation
Comment: I meant the end result for the tangent
Comment: Your original equation is $4y'=4(dy/dx)=y(x^2-4x-3)$. So the tangent is $k=(dy/dx)=y(x^2-4x-3)/4$.
Comment: isn't the tangent suppose to be a line? $$y(x^2−4x−3)/4$$ is not strait
Comment: good comment. I changed the answer to specify that the slope is taken at point $(x_0,y_0)$.

Tangent to integral curve


How to define a polynomial with abstract coefficients in Sage

Question: Let $f=ax^2+b$ be a polynomial in $Q[x]$, how to define $f$ in sage?
Answer: <code>sage: var('a b')
(a, b)
sage: R.<X> = QQ[]
sage: f = a * X * X + b
sage: f
X^2*a + b
sage: R
Univariate Polynomial Ring in X over Rational Field
</code>
You can get more information about polynomials in this tutorial here.