why i += 1 changes to i += 2 works?

Question: It's my first time to ask a question here.
I try to get players whose height is above 200 centimeters but I don't know why it doesn't work until I adjust i += 1 to i += 2, and I still don't know why it works.
By the way, I try to use while loops but not for loops to write this code.
Thanks in advance!
players = [['James', 202],
           ['Curry', 193],
           ['Durant', 205],
           ['Jordan', 199],
           ['David', 211]]

i = 0
while i < len(players):
    if players[i][1] < 200:
        continue
    print(players[i])
    i += 1

Comment: If `players[i][1] < 200` then you go into an infinite loop because you never change the value of i and it's always at the same item. The reason it works with +=2 is that if you do that you are skipping the only list item that falls into that category.
Comment: I have been programming for a long time and never ever use while loop in any programming language because they are just very illogical to me. "for" loops are most straight forward logical loops to write, execute and understand. Just my 2 cents
Comment: @SamB `i` will always be 1, `i < len(players)` will always be True and the loop will run forever.
Comment: @SamB more specifically, once `i==1` the `if` is true and executes `continue` so the `i+=1` never executes again.
Comment: agreed, took my comments back
Comment: `for player in players:` is more pythonic and would prevent this type of error.
Comment: Why do not you use a cycle?
Comment: I'm so grateful to you for actually solving my mystery, appreciate a lot!
Answer: Restructure with a for loop and specify only when you want to do something:
players = [['James', 202], ['Curry', 193], ['Durant', 205],
           ['Jordan', 199], ['David', 211]]

for p, height in players:
    if height >= 200:
        print(p)

# James
# Durant
# David

Or use a list comprehension:
[p for p, height in players if score >= 200]
# ['James', 'Durant', 'David']

The problem with your code is that when it hits continue, i does not increment as the next iteration of the loop begins. Read up on continue here. Here's how you would do it with a while loop:
i = 0
while i < len(players):
    p, height = players[i]
    if height >= 200:
        print(p)
    i += 1

# James
# Durant
# David

Comment: Agreed `for` loop is better but OP wants to "try to use while loops but not for loops to write this code".
Comment: `for player, height in players`** I'd say is the best
Comment: I have added the `while` version for good measure. since OP is a learner, it's good to see / understand all methods.
Comment: @AntonvBR maybe OP is trying to learn how to use `while` loops. Even if this is not the case it is helpful to explain why code is not working.
Comment: @Alex I find it very strange when people try to use something less efficient and less readable for a simple task as for/while. Nevertheless, you have a valid point.
Comment: thank you guys for helping me out, I was trying to use different ways to write this. But actually, for loops is way more better to use :D
Answer: Your problem is that you end up in an infinite loop due to the following bit of code:
if players[i][1] < 200:
    continue  # here you skip to the top of the loop without changing i

When you change to i += 2 this problem still exists but you happen to avoid getting stuck in it. This is because you only process the even-indexed elements. Each of these has a value over 200 so your code never gets to the continue statement.
[['James', 202],
 ['Durant', 205],
 ['David', 211]]

Try:
i = 0
while i < len(players):
    if players[i][1] < 200:
        print(players[i])
    i += 1

Answer: If you insist on using while loop here is another, clean, alternative:
players = [['James', 202],
           ['Curry', 193],
           ['Durant', 205],
           ['Jordan', 199],
           ['David', 211]]

while players:
    p, height = players.pop(0)
    if height >= 200:
        print(p)

This works because players evaluates to false when it is empty []. And in every step we are popping away an item. However, after running the loop, players is an empty list.
Answer: Before adding  i += 1 to i += 2 and not understanding what it means just think what you are trying to do.
You want to get values from the array right? i.e.
players[0][1] will get you 202
players[1][1] will get you 193
players[2][1] will get you 205
....

So increment i accordingly.
Sometimes the easiest way to write code is to first say out loud in your head or write it in simple english.

You want to loop over values of the array
You want to then check if the value matches something
If it does print it
If it doesn't don't print it and then move on to the next value
Keep doing it till you have checked every value in the array

Now writing code makes sense right?
The easiest way to understand increment is to write it like this
i = i + 1

Answer: simplest way to achieve what you're after in the future
players = [['James', 202],
           ['Curry', 193],
           ['Durant', 205],
           ['Jordan', 199],
           ['David', 211]]

for name,height in players:
    if height>=200: print(name)

why i += 1 changes to i += 2 works?


Ordinals, cardinals and how to understand $2^{\aleph_0}$ versus $2^{\omega_0}$

Question: I have read that $2^{\omega_0}=2^{\omega}=\omega$. (in the sense that they have the same order type). On the other hand, I know that $\omega=\aleph_0$, since it is the least infinite countable ordinal. I also know that $2^{\aleph_0} = \aleph_1 = \omega_1$ which is the least uncountable ordinal. Doesn't this gives us $2^{\omega_0}=\omega_1$? So, which of the above facts that i have stated is not correct?
Thank you,
Also. if you find my question duplicated, I will be greatfull if you could mention where can i find the answer.
Comment: See all the links [in this answer](http://math.stackexchange.com/a/598226/622).
Answer: Firstly, $2^{\aleph_0} = \aleph_1$ is not always true, this is independent of the ZFC axioms of set theory, and is known as the Continuum Hypothesis. What is true is that this is an uncountable cardinal, so $|\mathbb{R}| = 2^{\aleph_0} \ge \aleph_1$.
As a set, $\omega = \aleph_0$ (in the usual set theoretic set-up), but just like addition is different for ordinals, so is exponentiation. When we write $\omega$, we mean to look at the set as an ordinal (i.e. having a specific well-order), and when we write $\aleph_0$ we mean to use it as a "yard-stick" for infinite sets. So $\omega+1 \neq \omega$ as ordered sets, but $\aleph_0 + 1 = \aleph_0$ as cardinals (they have the same size). Also, exponentiation is different, so the meaning of $2^\omega$ is some specific order type, and $2^{\aleph_0}$ is the cardinality of the powerset of $\aleph_0$.
The operations $+$ and powers depend on the context. Also wikipedia warns for the confusion and the different symbol uses.
Comment: I think I am begining to get it. Is the following statement correct? $2^\omega = lim\{2^n | n \in \omega\}$ and $2^{\aleph_0} = \{ f | f $ is a function from $\omega$ to $\{ 0,1 \}$ $ \}$.
Comment: Indeed, the definition of $2^\omega$ is the $\sup$ or limit of the set of ordinals $\{2^n: n \in \omega\}$, while $2^{\aleph_0}$ is the **cardinality** of the set of functions from $\omega$ to $2 = \{0,1\}$. This cardinality equals some $\aleph_\alpha$ (if we assume the axiom of choice, which I do). Exactly which $\alpha$ is undetermined by the axioms.


Migration Class CreateSessionTable error 301

Question: i accidentally execute php artisan migrate:session.
and it migrated, i delete the file createSessionTable,
and now i try to execute php artisan migrate:reset and the migrator in laravel still searching for CreateSessionTable.
i already use composer dump-autoload
composer dumpautoload
php artisan dump-autoload
php artisan dumpautoload
composer update // doesn't resolve the problem
it doesn't work anymore.
do you encounter it?
Answer: If you deleted the migration file you have two options:
1) Create a new one with the same name 2014_0000_create_session_table.php (the numbers doesn't really matter in this case, and rollback with it, you don't really need to create things in those methods (but you better create a drop method to drop that sessions table for you), you just need the class CreateSessionTable to be available for Laravel. After creating that file you'll need to composer dump.
2) Manually delete the line in the migrations table and also drop the sessions table.
You can also delete all your tables manually and all records on migrations file and then migrate again.


Proof: Probability using Induction

Question: You have $n$ coins $C_1$, $C_2$, ..., $C_n$ for $n \in \mathbb{N}$. Each coin is weighted differently so that the probability that coin $C_i$ comes up heads is $\frac{1}{2i + 1}$. Prove by induction that if the $n$ coins are tossed, then the probability of getting an odd number of heads is $\frac{n}{2n + 1}$.
So what I have done first is prove the basecase:
Let $C_i=1$. Thus, we have the probability of coin $C_i$coming up heads as $\frac{1}{2+1}= \frac 13$.

Now let $n=1$. Then we see that $n_1= \frac 1{2+1}= \frac 13$. Therefore the result holds when $C_i=1$ and when $n=1$.
Induction Step
Assume that when $n = k$ for $k\in \mathbb{N}$, the result is true. Thus, $n= \frac{k}{2k+1}$. We wish to show the result is true for $k+1$.
Now from here, I am unsure how to proceed. Any help is greatly appreciated!
Answer: HINT: In order to get an odd number of heads when you toss $n+1$ coins, exactly one of two things must occur:

You get an odd number of heads in the first $n$ coins and a tail on the $(n+1)$-st coin.
You get an even number of heads in the first $n$ coins and a head on the $(n+1)$-st coin.

The induction hypothesis tells you the probability of getting an odd number of heads in the first $n$ coins, and hence also the probability of getting an even number.
Comment: Sorry, but still unsure. I get the idea of having both probabilities of even and odd because since odd is given as k/(2k+1), then even probability would be k/(2k). But am I trying to prove that
k+1=(k+1/(2(k+1)+1)?

(k+1) = (k/2k+1) + (k+1). Then get it into a single fraction, thus: (2k^2+4k+1)/(2k+1). Then solve until it matches up with the hypothesis?
Comment: @PaperThin88: No, the probability that the first $n$ include an even number of heads is $1-\frac{n}{2n+1}=\frac{n+1}{2n+1}$. Then the probability of a head with the final coin is $\frac1{2n+3}$ so the probability of this case is $\frac{n+1}{2n+1}\cdot\frac1{2n+3}$. Calculate the probability of the other case similarly, and add them to get the probability of an odd number of heads with $n+1$ coins.

Proof: Probability using Induction


Will Parse working correctly if I set StoreKit's status to optional in Build Phases

Question: I would like to use the Appirater library in my project, but after reading its install tutorial one thing is not clear.

Be sure to change Required to Optional for StoreKit in your target's
  Build Phases » Link Binary with Libraries section.

If I set the status of the StoreKit framework to Optional from Required, will this affect anything that is related to my Parse implementations? Because the Parse iOS SDK also requires StoreKit. Or switching to Optional means the framework will be loaded when it's needed only and don't have any side effects so Parse will also work properly? Am I right or it's not easy like that?
I would really appreciate if somebody could give me some guidance, thanks.
Answer: tl;dr It doesn't matter. Optional or Required are effectively the same for StoreKit in 2015.
Setting a framework to be Optional is essentially telling the system "Don't crash this app if you can't find this framework on the iOS device you are running on". StoreKit was introduced a long time ago in iOS so it's very unlikely that there are still devices with iOS versions before 3 (when StoreKit was introduced).
The only reason the Appirater instructions say to set it to Optional is because at the time those instructions were written, there were still a lot of iOS devices out there with versions of iOS that didn't have StoreKit, and Appirater could run without it, so there was no reason to crash the app over it. Thus, the instructions say to make it Optional.
That said, I should just simplify the Appirater setup and @import StoreKit in Appirater.h so nobody has to deal with that anymore.
Comment: Arash, thank you very much! It's really great to get answer straight from the creator of this amazing library! I take my hat off to you.


Display data in two columns c++

Question: I am trying to display the same data but in two columns, so after school week 19, the data should be displayed in the columns to the right of the table until the total school weeks is reached i.e. 36. Below is the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;
int const schoolWeeks = 37;
string week[] = { "A", "B", "C", "D" };
int num = 0;

int main()
{
cout << left << setw(9) << setfill(' ') << "Week " << left << setw(9) << setfill(' ')<< "Menu" << left << setw(9) << setfill(' ') << "Week " << "Menu" << endl;
for (int i = 1; i < 20; i++)
{
    cout << left << setw(9) << setfill(' ')<< i << week[num] << endl;

    num = num + 1;
    if (num == 4)
    {
        num = 0;
    }

}
for (int i = 20; i < schoolWeeks; i++)
{
    cout << left << setw(9) << setfill(' ') << i << week[num] << endl;

    num = num + 1;
    if (num == 4)
    {
        num = 0;
    }

}

}

Comment: Why your **second** `for` is outside the **main**?
Answer: Standard output with std::cout is based on the idea of a stream of data. Remember, it's called "iostream" for a reason. This means once you have written something to std::cout, you simply cannot "go back" a few lines and add something.
Consider piping in a Linux shell or on the Windows command line. It's possible to redirect the output of your program to be the input of another program, which could then do any imaginable thing with it, e.g. sending it over the internet:
myprogram.exe > otherprogram.exe

How could you possibly add something to an already written line in such a scenario?
Considering all of this, it becomes clear that the only viable solution is to know in advance the contents of every line. You cannot wait until line 19 before thinking about the second column, you must do it right away. In other words, first print week 1 and week 19, then week 2 and week 20, then week 3 and week 21, and so on. See the pattern? It's always "week X in column one, week X+18 in column two". And that's pretty much the solution.
Here's a quickly written loop adhering to the style of your existing code:
for (int i = 1; i < 19; i++)
{
    cout << left << setw(9) << setfill(' ')<< i << week[num]
         << left << setw(9) << setfill(' ') << " " << (i + 18) << " "
         << left << setw(9) << setfill(' ') << " " << week[num]
         << endl;

    num = num + 1;
    if (num == 4)
    {
        num = 0;
    }
}

The manipulators like std::setw or std::setfill could probably use some improvement, but the point is that:

The loop only counts from 1 to 18.
The body performs the output for i and for i + 18.
Comment: Thank you, there seems to be small problem with the week counter, it resets after reaching 19 or the first week on the second column, it should be CDABCD but it starts ABCDABCD. I have tried to add 2 to the num counter but it skips the first letters AB and instead displays CD..CD..CD etc. Is it not possible to continue with the counter in the new column without reseting the week lettering i.e ABCD?
Comment: @user3057164: This sounds as if you have written a new program based on a new idea (the one explained in my answer). I suggest you just ask a new question with the relevant code that does not work, because it's really a new problem, isn't it?

Display data in two columns c++


Select on change

Question: With Drupal 8, I have a form with two selects, both filled. I want to add a button/link after each of these two selects, looking like this.
[__SELECT__v][BUTTON]
[__SELECT__v][BUTTON]

The buttons, however, don't have a fixed link because the link target depends on what is selected in the select. Also, the link needs to open a new tab.
For example, if in the select "car1"  the key "12345" is selected, the link should open /cars/12345; if "car2" is selected with the key
"67890" then "/cars/67890"
This is the code I am using.
$form['select_g1'] = array(
                    '#type' => 'select',
                    '#prefix' => '
',
                    '#title' => t('Select       '),
                    '#options' => $contarray,
                    '#empty_value' => '',
                    '#default_value' => ($ext) ? $row['model'] : "",
                    );
$form['button'] = array(
                    '#markup' => '
',
                    );

Can someone help me there?
Answer: This is easy to do with javascript.
You can do an onchange event for your select that updates the link,
or you can do a mousedown event on your link that grabs the value from the select.
A quick google search shows many possibilities:
https://stackoverflow.com/questions/11758659/compose-a-link-based-in-selects-option-value
https://stackoverflow.com/questions/20357075/how-to-update-append-to-it-an-href-based-on-dropdown-selection
To add javascript to your form, you need to add the js to your custom module, say in mymodule/js/updatelink.js
then add a mymodule.libraries.yml file in your module
mymodule.updatelink:
  version: VERSION
  js:
    js/updatelink.js: {}
  dependencies:
    - core/jquery
    - core/drupal

then attach it to your form like this:
$form['#attached']['library'][] = 'mymodule/mymodule.updatelink';

You'll want to wrap your code in a Drupal.behaviors class.  See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
Comment: Thank you very much! So far it works with including the js and (for testing) displaying a alert when the select changes.

Select on change


Securing OpenLDAP and AD

Question: We are using OpenLDAP server as a proxy to AD by adding AD as subordinate to OpenLDAP.
I've secured OpenLDAP traffic by using StartTLS connection, Now I've been told to use LDAPS protocol for the bind which we do to connect to AD Server(We are using simple bind).
So my question was, Is it necessary to use LDAPS for communication with AD as OpenLDAP is already using StartTLS?
I don't have much knowledge about OpenLDAP and AD so just wanted the suggestions.
I've used below configuration for adding backend ldap[Lightweight Directory Access Protocol (Proxy) backend] database.
dn: olcDatabase=ldap,cn=config
objectClass: olcDatabaseConfig
objectClass: olcLDAPConfig
olcDatabase: ldap
olcSuffix: ou=xyz,dc=xyz,dc=xyz
olcSubordinate: TRUE
olcAccess: to dn.subtree="ou=xyz,dc=xyz,dc=xyz"  by * read
olcAddContentAcl: FALSE
olcLastMod: FALSE
olcMaxDerefDepth: 15
olcReadOnly: FALSE
olcSyncUseSubentry: FALSE
olcMonitoring: FALSE
olcDbURI: "ldap://xx.xx.xx.xx"
olcDbStartTLS: none starttls=no
olcDbACLBind: bindmethod=simple timeout=0 network-timeout=0 binddn="cn=xyz,ou=xyz,dc=xyz,dc=xyz" credentials="xxxxxxxxxxxxxxxxxxxxxx"
olcDbIDAssertBind: mode=legacy flags=prescriptive,proxy-authz-non-critical bindmethod=simple timeout=0 network-timeout=0 binddn="cn=xyz,ou=xyz,dc=xyz,dc=xyz" credentials="xxxxxxxxxxxxxxxxxxxxxx"
olcDbRebindAsUser: TRUE
olcDbChaseReferrals: TRUE
olcDbNoRefs: FALSE
olcDbNoUndefFilter: FALSE

Comment: And with addition to what Rayan Ries said: do the traffic dump and do not guess.
Answer: LDAP simple binds that are not protected by SSL/TLS are very insecure, as it involves sending username and password credentials in clear-text over the network.
LDAP simple binds are acceptable only over SSL/TLS/LDAPS.
All you have to do to enable LDAPS on an Active Directory domain controller is install a suitable certificate with private key on the AD domain controller:
https://support.microsoft.com/en-us/help/321051/how-to-enable-ldap-over-ssl-with-a-third-party-certification-authority
Be sure and read the requirements section of the article above to see what constitutes an acceptable certificate.
Once you've installed an acceptable certificate on the domain controller, Active Directory will automatically sense its presence and enable LDAPS over port 636.
You may source the certificate from any Certification Authority you wish, as long as it is trusted by all parties who will participate in the communication. It can be an existing AD-integrated PKI, or it can be a non-Microsoft CA on your corporate network, or it may even be a public, globally-trusted CA like Godaddy, Symantec, etc., as long as it is capable of producing a certificate that meets the requirements:

The LDAPS certificate is located in the Local Computer's Personal certificate store (programmatically known as the computer's MY certificate store).
A private key that matches the certificate is present in the Local Computer's store and is correctly associated with the certificate. The private key must not have strong private key protection enabled.
The Enhanced Key Usage extension includes the Server Authentication (126.96.36.199.184.108.40.206.1) object identifier (also known as OID).
The Active Directory fully qualified domain name of the domain controller (for example, DC01.DOMAIN.COM) must appear in one of the following places:

The Common Name (CN) in the Subject field.
DNS entry in the Subject Alternative Name extension.

The certificate was issued by a CA that the domain controller and the LDAPS clients trust. Trust is established by configuring the clients and the server to trust the root CA to which the issuing CA chains.
You must use the Schannel cryptographic service provider (CSP) to generate the key.

(Technically, it may even be a self-signed certificate, though this isn't a secure solution.)
Once you install this certificate, the domain controller will automatically enable LDAPS service on port 636. (And global catalog service on 3269.)
So far I have only described LDAPS but not specifically StartTLS.
You may use startTLS against a Microsoft LDAP server if you wish:
https://msdn.microsoft.com/en-us/library/aa366997(v=vs.85).aspx
It doesn't require any additional configuration on the server. It just involves the client sending the correct LDAP controls (commands) to the server. (The control OID for startTLS is "188.8.131.52.4.1.1466.20037".)
Comment: Thanks Ryan!! I will try it.. Can you please confirm if it is a good idea to add AD database as a subordinate to OpenLDAP database for querying AD through OpenLDAP?
Comment: @Vishal I can't answer that as I don't understand your business needs or requirements. It's not an implementation I would be likely to recommend though, as Active Directory was not designed with this scenario in mind. But if you can make it work, then more power to you.
Answer: There are two network segment you have to secure:

from clients to OpenLDAP;
from OpenLDAP to AD.

They both have to be secure.
The first part has already been done with StartTLS.
You only need to put security on the second network hop. I think it would be enougth to modify:
olcDbURI: "ldap://xx.xx.xx.xx"
olcDbStartTLS: none starttls=no

to:
olcDbURI: "ldaps://xx.xx.xx.xx"
olcDbStartTLS: false

(because of course it's not possible to have both StartTLS and LDAPS)

Securing OpenLDAP and AD


Proof About Point and Triangles

Question: Suppose we are given $n$ points in a plane, where $n\ge 4$ and no 3 of the points are collinear. If $k$ distinct triangles are designated with vertices among the $n$ points, show that no more than $k(n-3)$ of the $n\choose 4$ groups of four points contain at least one of the designated triangles.
I tested $n=4$, and had $2$ distinct triangles designated among the 4 points and I had to prove that:
No more than $2$ of the $1$ group of four points contain at least one of the designated triangles?
Also, can I clarify something? When it says

$k$ distinct triangles are designated with vertices among the $n$ points,

it basically means that $k$ can take on any value from $1$ to $n\choose 3$, right? If $n=4$, $k$ could be $1,2,3$, or $4$ right? (up to $4$ triangles can be formed from $4$ points)
Comment: The problem statement does not rule out $k=0$ or $k>{n\choose 3}$, but in both these cases the claim is vacuously true.
Answer: Your example with $n=4$, $k=2$, shows that the inequality to be shown mya not be sharp, or at least not for all $n$ and $k$.
Hint: The expression $k(n-3)$ seems to hint towrds considereing tuples consisting of a) one of the triangles, b) any of the points except three (which three, may depend on the triangle in a)
So how do you find three special points given a triangle? How do you get a group of four points, given a triangle and another point?
Comment: You can get a group of 4 points by taking the 3 points of an arbitrary triangle, and adding any one of the other n-3 points. Since there are k triangles, there are at most k(n-3) groups of 4 points which contain at least one of the k triangles. However, we may have overcounted because some of the group of points may be counted for more than one triangle. I still don't get what it means by 2 of the 1 group.
Comment: @miamiheatftw Well, ther is only one grou of four points if you have only $n=4$ points to begin with, hence the number of four-point-groups containing a triangle is trivially $\le 1$. Now if you have $k$ triangles, the claim is that the number of four-point-groups containing a triangle is $\le k(n-3)$. As $k(n-3)=k$, we have to show that the number of four-point-groups containing a triangle is $\le k$.As we already know that the number of four-point-groups containing a triangle is $\le1$, there is nothing to show for $k\ge 1$; of course there is also nothing to show for $k=0$. So all is fine.
Comment: Ah, I think it's getting to me now. So, we just have to show that it's "no more" than k(n-3).

Proof About Point and Triangles


Jazz chords: left hand fingerings

Question: I'm an amateur guitarist, I like jazz and I decided to try to learn the basics from the beginning (self-teaching at the moment). I started reading Mickey Backer's "Complete Course in Jazz Guitar" method, but suddenly stopped at Lesson #1 !
I found this Amin7 right hand fingering:

which looks quite un-natural (I must rotate my left hand and shift up the thumb too much to properly "bar" the 4 strings).
I usually play it in this way:

Other chords in the first chart of the method look weird as well, so I got another method: Jody Fisher's "Beginning Jazz Guitar", but surprisingly there is no left fingers notations at all on chords charts ?
So:

Should I struggle with the weird fingerings suggested in the Mickey Backer's book until I find them natural ?
Where can I find other "valid" chord fingerings (if any) ?
Why a (very) popular  method like the Jody Fisher's book, doesn't provide any left-hand chord fingerings advice ?

What are your suggestions?
Answer: Both shapes you pictured are A - 7 chords.
Also 6th string 5th fret, 5th string 3rd fret and 4th string 5th fret is  form of A - 7.
If you play the top four strings, 1,2,3,4 together leaving out the 6th string bass that is also a form of  A - 7.
Sometimes you don't have to or want to play the full array of chords, just enough for the listener to get the idea.
In jazz sometimes all you need are the Root, the third which shows if it is major or minor and the 7th which shows if it is dominant or Major 7th chord.
Answer: If you fretted the full barre version - E5,A7,D5,G5,B5,e5, then you could mute whatever you need, with a little practice. Or play the strings you want to with hybrid picking. In the barre version, there are 2 A, 2 E, a G and a C. If playing alone, an A,C and G are sufficient - in jazz the 3rd shows maj/min., while the 7th shows, well, the 7th! In an ensemble situation, the bass would likely play root A, so you could actually play middle two strings to do the job.
Your question - don't rely on other players fingering. It works for them but you don't have their hands. Work out your own - there aren't that many combinations. Sometimes there is only one way to finger a chord, and if you find it next to impossible, find another voicing, and/or play it somewhere else, different strings, different frets.
Answer: I learned to fret this quite effectively from Rick Peckham at Berklee Online in the Chords 101 class. Use the ring finger to barre the top  strings, then wrap the middle finger on top of that to fret the sixth string. The fifth string and first string will be naturally muted. This is a much quicker and convenient fretting method.
To answer your first question, Mickey's suggested fingering is the most effective, fastest and it naturally mutes the necessary strings.
Comment: It's generally accepted that the thick strings are called the bottom strings, as they produce lower sounding notes.. Did you mean 'barre the top strings'?
Comment: Yep. I usually avoid that error. Kind of embarrassing, actually. Yes, I did mean barre the top strings.
Answer: Answer 1 - Definitely not! You don't need struggle with those chords I tough disable people (with no middle finger, as example) and a solution for that particular chord was using a bar, it means press all strings with one finger it seems difficult but it's an alternative
Answer 2 - It should be a bunch of it but I don't know sorry, but I will explain why I don't in the answer 3
Answer 3 - Yes! The Jody fisher's is a good book. And why I think they don't provide chord fingers suggest... I think the musician has to Be free to make his own choice, there's no a particular way that someone can say it's wrong or correct, correct way is the way that u can do with no problems. There are many difficult jazz chords and probably u will face good challenges but remember, there's no struggle after few hours practicing.
Answer: Your frustration with the Mickey Baker book is completely understandable. For a beginner without a teacher it is well-nigh incomprehensible:lots of chords and exercises and not a single hint as to how one might 'turn them into jazz'. It is also a method 'of its time', which is a long time ago, so it doesn't include some of the cool sounds that have emerged in the last fifty years.
For help with the chords: our fingers are designed to open and close in one plane. Our knuckles aren't ball and socket joints and our fingers don't tend to bend sideways, unless you're in the act of breaking them. You can use this to your advantage by rolling your barring finger/s slightly sideways. This can help to make the barre a tad more flat and rigid.

Jazz chords: left hand fingerings


PostgreSQL in Google Kubernetes Engine reinitialise database

Question: I'm trying to create a PostgreSQL database in Google Kubernetes Engine, backed on a PVC to maintain the stored databases. Currently I have this definition:
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  serviceName: "postgres"
  selector:
    matchLabels:
      db: postgres
  template:
    metadata:
      labels:
        db: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:12.1
        ports:
        - containerPort: 5432
        volumeMounts:
        - name: postgres-disk
          mountPath: "/var/lib/postgresql"
        env:
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        - name: PGUSER
          value: postgres
        - name: POSTGRES_DB
          value: postgres
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: password

  volumeClaimTemplates:
  - metadata:
      name: postgres-disk
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: "standard"
      resources:
        requests:
          storage: 1Gi

It works as expected, but if I kill the pod to simulate a node failure the whole database is restarted from scratch losing all stored data.
Comment: There are many configuration points to check, that could cause data loss, and many of them are out of GKE scope or unknown at this time: is data committed before killing the pod; where transaction logs are stored; what is the initdbscript, and so forth.  Does database save your data when you shutdown the database gracefully?
Comment: It should be noted that killing a pod simulates crash of a particular process only, not a node failure. That way impact on the data consistency might be significantly different between a pod and a node crash.
Comment: I see your points, but if the data cannot survive a pod crash I cannot trust it to survive a full node failure.
Comment: As mebius99 noted you can't really simulate a node crash in GKE, although you can do it in cloud providers that run on bare metal as Digital Ocean. With some adaptions to handle the differences in the DO storage the configuration in the answer works.
Answer: For what I found the problem are the mount permissions, adding a folder level does the trick
volumeMounts:
- name: data-disk
  mountPath: "/var/lib/postgresql/data"
env:
- name: PGDATA
  value: "/var/lib/postgresql/data/pgdata"


How to fix rules which unable to evaluate action?

Question: I have created two rules to act on some events related to commerce products.
The first is to act on reference node delete event, to remove the product upon node delete.
the second is to delete the node upon expiration event using node_expire
When running the cron to make expired event to be happen no actions executed except if I disabled the first rule
I have tried rules components and rule sets as that two rules have conditions and actions in common But nothing changed.
Edit:
I did some debugging and found that warning and error messages

[warning]
WD rules: Unable to load commerce_product with id "102"
WD rules: Unable to evaluate action entity_fetch.
WD rules: Unable to get variable entity_fetched, it is not defined.
[error]
WD rules: Unable to evaluate action entity_delete.
Comment: Have you tried turning on Rules debugging and/or running the various events using devel's execute PHP functionality?
Comment: display errors is on and no logs in drupal also didn't record any thing
Comment: Does the first rule work if you delete the node by other means?
Comment: It works fine and the second rule is the same
Answer: The error:

WD rules: Unable to get variable X, it is not defined.

means that Rules can't load the variable X.
If you're using contributed modules, please check if your rules are in the right order and the configuration is right, otherwise check the module issue queue for possible bug issues.
If you're using custom modules, please make sure that these rule variables are passed in the correct way.
For example if you've the following sample rule in hook_rules_action_info:
'foo_rule' => array(
  'label' => t('Foo rule'),
  'provides' => array(
    'object_to_send' => array(
      'type' => 'data',
      'label' => t('Data Object to pass'),
    ),
  ),
),

The object_to_send needs to provide the matching array key, e.g.:
return array( 'object_to_send' => $object);

So the next rule in sequence will "see" that variable, so you can use it.
Answer: In your rule, scroll to the bottom, click "Settings" and give the first rule a higher weight than the second.
Comment: I did with no change the rule didn't apply


AUC-ROC interpretation

Question: I performed AUC-ROC curve analysis to confirm the biomarker potential of genes that were significant in gene expression results. This is how the graphics came out in the genes I determined. How can I comment, can you help me?
Comment: Please provide details about your analysis: what's the data and how did you analyze it. I would check for errors in the implementation as well.
Answer: An AUC of 1 means your model perfectly classifies the outcome 100 percent of the time. I would be a bit wary depending on what this data is like, as this may be a sign of overfitting or misspecification.
Comment: What would you recommend in this situation?
I have a control and experimental group, and the study was repeated 3 times.
Comment: Have you looked at the outcomes of your data in any other way? May be helpful to plot or inspect your data to see what is afoot. Otherwise I can't really say.
Comment: My data is:
GRUPLAR Chst2
KONTROL 3,582099
DENEY         24,23418
Comment: Since I have 2 groups, I did the T test. I confirmed the genes with significant t-test results with ROC curve analysis.
Comment: You need to look at the data distributions, regression assumptions, etc. and see if there is something weird going on. I'm not sure what t-test you did but either way you need to look further.
Comment: As a result of statistical analysis, data distributions were homogeneous.

AUC-ROC interpretation


Generating random survival values using Cox model estimates

Question: Background
I'm fresh to survival analysis and I'm using R's survival and coxme libraries to evaluate the effects of two covariates -- population size and resource level -- on the lifespan (in weeks) of local populations.
I scaled down population size by 100 and resource measure by 10. From the subsequent censored data frame:
> head(pop.surv)
  location lifespan censor size resource
1       13        2      1 3.10      0.0
2       13        1      1 0.68      0.0
3       26        2      1 2.02      0.0
4       26        2      1 2.04      0.0
5       30        3      1 5.23      0.1
6       13        1      1 5.22      0.0

I ran a mixed-effect cox-proportional hazard model:
res <- coxme(Surv(lifespan, censor) ~ size + resource + (1|location), data=pop.surv)

Based on the result,
> summary(res)
Cox mixed-effects model fit by maximum likelihood
  Data: pop.surv
  events, n = 1940, 1940
  Iterations= 23 165
                    NULL Integrated    Fitted
Log-likelihood -12751.36  -12318.14 -12288.69

                   Chisq    df p    AIC    BIC
Integrated loglik 866.45  3.00 0 860.45 843.74
 Penalized loglik 925.35 21.51 0 882.33 762.50

Model:  Surv(lifespan, censor) ~ size + resource + (1 | location)
Fixed coefficients
                coef exp(coef)    se(coef)      z       p
size     -0.01693793 0.9832047 0.003612058  -4.69 2.7e-06
resource -0.15943564 0.8526248 0.007610163 -20.95 0.0e+00

Random effects
 Group    Variable  Std Dev   Variance
 location Intercept 0.3320527 0.1102590

I interpret that, holding the other covariate constant, an additional 100 members in a population reduces the weekly hazard of extinction by a factor of 0.9832 on average -- that is, by 1.68 percent. Similarly, each 10 unit increase in resource level reduces the hazard by a factor of 0.8526, or 14.74 percent.
Question
Based on this knowledge, I now want to write a predictive function survfunc(s,r) that takes the arguments of population size s and resource level r, then outputs a survival distribution with a covariate-dependent hazard rate and randomly samples a lifespan value from it. How would I do that?
Answer: Cox regression is an attractive choice for survival analysis because it focuses on comparing covariate levels without assuming much about the overall survival distribution. However, simulating the survival times is not so easy - you will need to specify the baseline hazard rate. Without it, your model does not know anything about the scale and shape of the distribution that should result, only that it should become "steeper" in the high-risk groups.
Typically, baseline hazards are chosen so that the resulting survival time distributions would be exponential, Weibull, or Gompertz. My advice would be to try fitting these functions, using, for example, flexsurv package. Once you choose the function, you can take the parameter values obtained from the fit, and then use the inverse hazard function to generate the survival times. Bender et al. present a nice overview of this method and include formulas for the typical distributions, and this answer will be helpful as well.
Comment: @neither-nor You can apply the inverse hazard method as long as you have the inverse hazard function for the underlying distribution. But I don't have an intuition on how complicated it would be to do that for a neg binomial. Worst case scenario - you can always write a simulation to loop through each day and "roll a die" for each survivor on that day.
Comment: @neither-nor exponential distribution works fine, the inverse is $t/\lambda$, or $t e^{-\beta x} / \lambda$, with $t = -log(Unif)$. (I should have written that you need the inverse of _cumulative_ hazard function $H(t)$, not $h(t)$.)
Comment: @neither-nor yes, that would be my approach. For Weibull in particular additional care is needed because it has several common parametrizations - if your simulations suddenly look weird, you might need to fiddle with the parameters, e.g. use $1/\lambda$ instead of $\lambda$.
Comment: Thanks! I didn't think the process would be this complicated. So far, I have fitted the entire lifespan data to a negative binomial due to the data's high number of zeros. Would the fitted parameters from that be appropriate?
Comment: By the way, where do the zeros come from? Is that a very short lifespan, or is it something else - maybe censoring could be more appropriate then?
Comment: Would Bender's method work if I want to assume an exponential distribution for survival time, in which case hazard is constant and the inverse function is not defined?
Comment: Thanks! One follow-up question: To find, for example, fitted Weibull baseline hazards parameters, do I simply run `flexsurvreg(Surv(lifespan, censor) ~ size + resource, data = pop.surv, dist = "weibull")` and then use the `est` values for `shape` and `scale`?


Name and graph this quadric surface in three-space.

Question: Name and graph the equation $9x^2-y^2+9z^2-9=0$ in three-space. First, graph and name the two points dimensional coordinate trace of the surface. Hint: Use Plot 2D implicit and Plot 3D implicit.
Comment: "My 3D Function Graph"?
Comment: "What is that?"
Comment: A possible name for the graph. Can you be more specific when you say "name" the graph?
Answer: This surface has the equation $9x^2-y^2+9z^2=9$. To understand what kind of quadric you have, you need to understand how it meets both the coordinate planes and axes.

The $xy$-plane: The surface meets the $xy$-plane when $z=0$. In this case you have $9x^2-y^2=9$. This is a hyperbola.
The $xz$-plane: The surface meets the $xz$-plane when $y=0$. In this case you have $9x^2+9y^2=9$, i.e. $x^2+y^2=1$. This is the unit circle.
The $yz$-plane: The surface meets the $yz$-plane when $z=0$. In this case you have $9z^2-y^2=9$. Again, this is a hyperbola.

Already, it seems like you have a single sheeted hyperboloid. Let's look at how it meets the axes:

The $x$-axis: The surface meets the $x$-axis when $y=z=0$. In this case you have $9x^2=9$ or $x = \pm 1$. The surface meets the $x$-axis at $(\pm 1,0,0)$.
The $y$-axis: The surface meets the $y$-axis when $x=z=0$. In this case you have $-y^2=9$. This has no real solutions. The surface misses the $y$-axis.
The $z$-axis: The surface meets the $z$-axis when $x=y=0$. In this case you have $9z^2=9$ or $z = \pm 1$. The surface meets the $z$-axis at $(0,0,\pm 1)$.

You should have a very good idea of what the surface looks like by now. If not, here's a plot of it.


No clear elbow and low Silhouette scores K-Means

Question: I am implementing the K-Means algorithm to group books based on their title and their description.
I pre-processed the data merging the fields and deleting all the punctuations and some undesirables words. I also applied the Snowball Stemmer. Then I applied the TF-IDF algorithm and got vectors with approximately 15000 components.
When I apply the K-Means algorithm I cannot see a clear elbow and my silhouettes scores are below to 0.03.
What can I do to improve the classification?
Comment: Just to clarify here, how big is the final dataset being clustered? If we have 15K features those are extremely hard to cluster reasonable using $k$-means as in such high-dimensional domain data have "no neighbours" ( [Curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality#Nearest_neighbor_search))
Comment: Until now the dataset contains between 6000 and 9000 rows.
So, should I use PCA?
Comment: Yes, that would be a good idea so the dimensionality of the data is reduced.
Answer: Such Data is

Very high dimensional
Very noisy

K-means does not handle such situations very well, and nor does the Elbow method (there won't be a clear elbow) nor silhouette (curse of dimensionality).
You'd better use LDA and similar methods designed for text.
Comment: Do you mean Linear Discriminant Analysis or Latent Dirichlet Allocation?
Comment: @HasQUIT--Anony-Mousse You could have simply informed him/her about the specific LDA to use, rather than coming across as unkind.
Comment: The one which is "designed for text", obviously... One very clearly is, and the other very clearly is not.


Picture in odoo qweb report

Question: I'd like show a picture in my qweb report.
When I copy i.e. from the website_quote modul to my xml file this line:

it works fine, but if I copy the partner_icon_01.png file to my module directory, and change the line:
, the picture doesn't appear in my report.
Any help would be appreciated.
Cheers: Janos
Comment: Have u try to check and print the report as the report type as HTML  and try to print again ?? tell me what is your result get ..??
Comment: You could see the report on my edited question. (the result mark withe black arrow)
Answer: Try the following code and check

This will working fine from my side also follow the below link
Click to See the Reference Link
I hope this should helpful for you ...! :)
Comment: It works if I put image in /my_module/static/src/img/ folder, but doesn't in /my_module/img/ folder.
Only works if I use the filename extension (like png).
Works whithout "class img......"

Picture in odoo qweb report


Extending partition on linux gparted but not more space in the vm

Question: I have a vm test installation of a linux running a build server. Unfortunately I just pressed ok when adding the disk and ended up with an 8gb drive to play with. Well into the test the builds are consuming more and more space, of course.
The vm drive was resized to 21gb and using gparted I expanded the drive partitions and that all worked fine but when I go back into the console and do df there's still only 8gb available.
How can I claim the other 13gb I added?
fdisk -l

Disk /dev/sda: 21.0 GB, 20971520000 bytes
255 heads, 63 sectors/track, 2549 cylinders, total 40960000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0006d284

Device    Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      499711      248832   83  Linux
/dev/sda2          501758    40959999    20229121    5  Extended
/dev/sda5          501760    40959999    20229120   8e  Linux LVM

vgdisplay

--- Volume group ---
VG Name               ct
System ID
Format                lvm2
Metadata Areas        1
Metadata Sequence No  4
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                2
Open LV               2
Max PV                0
Cur PV                1
Act PV                1
VG Size               19.29 GiB
PE Size               4.00 MiB
Total PE              4938
Alloc PE / Size       1977 / 7.72 GiB
Free  PE / Size       2961 / 11.57 GiB
VG UUID               MwiMAz-52e1-iGVf-eL4f-P5lq-FvRA-L73Sl3

lvdisplay

  --- Logical volume ---
LV Name                /dev/ct/root
VG Name                ct
LV UUID                Rfk9fh-kqdM-q7t5-ml6i-EjE8-nMtU-usBF0m
LV Write Access        read/write
LV Status              available
# open                 1
LV Size                5.73 GiB
Current LE             1466
Segments               1
Allocation             inherit
Read ahead sectors     auto
- currently set to     256
Block device           252:0

--- Logical volume ---
LV Name                /dev/ct/swap_1
VG Name                ct
LV UUID                BLFaa6-1f5T-4MM0-5goV-1aur-nzl9-sNLXIs
LV Write Access        read/write
LV Status              available
# open                 2
LV Size                2.00 GiB
Current LE             511
Segments               1
Allocation             inherit
Read ahead sectors     auto
- currently set to     256
Block device           252:1

Comment: Please paste the vgdisplay output and lvdisplay ... if your lvm see now new free physical extends then you only have to extend lvm volume and do resize2fs ...
Comment: @B14D3 added...
Comment: You have Free  PE / Size       2961 / 11.57 GiB wait I will update my answere
Comment: You're almost there - you need to resize the filesystem on your partition (I assume it's on /dev/sda5) as well (This is well documented on the 'net).
Answer: You resized the partition now you have to resize lvm and file system ... You can do that with pvextend and resize2fs read the manual do backup use with consideration... :)
All you have to do is extend proper lvm volume in your case I think /dev/ct/root  with you new free pe (phisical extends). You can see all volumes using lvdisplay and extend proper one with command
lvextend -l +2961 /dev/ct/root
after that you must extend your file system with command
resize2fs -p /dev/ct/root
That's all! You can do this on working filesystem even when its mounted (WARNING I have never do that on root partition / so I can't give you any warranty about this tutorial )
Comment: Dude, your answer reads like a squirrel on speed wrote it.
Comment: @Roman Still better then your answere "go search in google" :P
Comment: @B14D3. It was just 'lvextend -l +2961 /dev/ct/root' but otherwise worked fine! Edited the answer... jesus how annoying that I needed to edit 6 characters :)
Comment: Same problem here; needed both lvextend and resize2fs (VM was Oracle VirtualBox, OS is CentOS 5, used gParted like the OP for the partition work).

Thanks, B14D3!


Showing inequality in integrating polynomials

Question: Let the polynomial $|P(x)| = a_0 + a_1x + \dots + a_nx^n$ have coefficients satisfying the relation $$ \sum_{i=0}^{n} a_i^2 = 1.$$
Prove that $$\int_{0}^{1} |P(x)| \ dx \leq \frac{\pi}{2}.$$
Show that this inequality continues to hold if $\pi/2$ is replaced by $\pi/\sqrt{6}.$
I was able to solve the first part using $P(x) \leq \sqrt{1 + x^2 \dots + x^{2n}}$ by the Cauchy inequality and the showing that the original integral is less than or equal to $$\int_{0}^{1} \frac{1}{\sqrt{1-x^2}} = \frac{\pi}{2}.$$
I'm not sure how to do the second part. The hint is to use the Schwarz inequality for integrals.
Comment: Perhaps you should try to prove that $\left(\int_0^1P(x)dx\right)^2\le\sum_{n=1}^\infty\frac1{n^2}$
Comment: I think I thought about this. Wouldn't I still need the modulus signs inside integral since it is larger than the modulus of the integral?
Answer: $$\int_{0}^{1}|P(x)|\,dx \leq \sum_{i=0}^{n}\int_{0}^{1}|a_i|x^i\,dx = \sum_{i=0}^{n}\frac{|a_i|}{i+1}\color{red}{\leq}\sqrt{\sum_{k=1}^{n+1}\frac{1}{k^2}}\leq\sqrt{\zeta(2)}=\frac{\pi}{\sqrt{6}}$$
where $\color{red}{\leq}$ follows from the Cauchy-Schwarz inequality.


Max/Min for whole sets of records in PIG

Question: I have a set set of records that I am loading from a file and the first thing I need to do is get the max and min of a column.
In SQL I would do this with a subquery like this:
   select c.state, c.population,
(select max(c.population) from state_info c) as max_pop,
(select min(c.population) from state_info c) as min_pop
from state_info c

I assume there must be an easy way to do this in PIG as well but I'm having trouble finding it. It has a MAX and MIN function but when I tried doing the following it didn't work:
records=LOAD '/Users/Winter/School/st_incm.txt'  AS (state:chararray, population:int);
with_max = FOREACH records GENERATE state, population, MAX(population);

This didn't work. I had better luck adding an extra column with the same value to each row and then grouping them on that column. Then getting the max on that new group. This seems like a convoluted way of getting what I want so I thought I'd ask if anyone knows a simpler way.
Thanks in advance for the help.
Answer: As you said you need to group all the data together but no extra column is required if you use GROUP ALL.
Pig
records = LOAD 'states.txt'  AS (state:chararray, population:int);
records_group = GROUP records ALL;
with_max = FOREACH records_group
           GENERATE
               FLATTEN(records.(state, population)), MAX(records.population);

Input
CA  10
VA  5
WI  2

Output
(CA,10,10)
(VA,5,10)
(WI,2,10)

Comment: Thanks - I knew there had to be a simple way to do that.


the relationship of autorelease and runloop and thread?

Question: I have a question about the autorelease,now I have the code below:
int main(int argc, char *argv[]){
@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}}

the doc says at the end of the @autoreleasepool{} the object marked as autorelease will receive a release message. but the UIApplicationMain never return ,which means the flow will never get to the end of the @autoreleasepool then the object marked as autorelease will never get release until the app die. There has no meaning of autorelease.....
I asked someone who says that the iOS system will generate some threads,(you know,one thread,one runloop).he says that the runloop will create the autorelease pool.so the autorelease object will release at the end of the thead or runloop. But the most situation we use the main thread.so what he says doesn't persuade me.
what's the proper time to use autorelease.It confused me a long time.
I get another point that the autorelease object will get release when one runloop end(the main runloop will exist all the app's life??) so I'm not sure..
any point and related document will be appreciated!!
Comment: I asked the same question.  It is most likely for semantic / demonstration reasons of what is acceptable behavior.  The only way out of UIApplicationMain is for the program to `exit()`, so any memory will be returned to the operating system anyway.
Answer: Yes, technically, UIApplicationMain never returns, so it never hits the end of that @autoreleasepool block, so in this case if you removed that @autoreleasepool block it would make no difference (other than maybe things complaining that they have been autoreleased without an autorelease pool). However, it's possible to imagine a main function written in a way that doesn't always call UIApplicationMain (perhaps not in iOS applications, but in general); then it would make a difference.
It is just good practice to always put an @autoreleasepool block around the body of the entry point of every thread, and main is the entry point of the main thread. So for consistency, it makes sense to always put it there.
What the person you talked to is talking about is that inside UIApplicationMain, there is a run loop (an infinite loop that handles events), and inside each iteration there is an autorelease pool (or perhaps every few iterations; it's an implementation detail). This has nothing to do with the autorelease pool in main though.


Solving Limits with L'Hospital's Rules

Question: I am having difficulties solving this limit. I was given the question and equation:
Try using L'Hospital's Rules to evaluate the follwing limit:
$$\lim\limits_{u \to \infty } \frac{u}{\sqrt{u^2 +1}}$$
How do you solve this with L'Hospital's rules? Do you solve this with them?
Comment: The limit is as $x \to \infty$ but the function $\tfrac{u}{\sqrt{u^2+1}}$ depends on $u$ not $x$. Are you sure this isn't a typo?
Comment: @asdfasdfasdf Please avoid using L'Hôpitals Rule :)
Comment: Possible duplicate of [Are there any limit questions which are easier to solve using methods other than l'Hopital's Rule?](http://math.stackexchange.com/questions/1534296/are-there-any-limit-questions-which-are-easier-to-solve-using-methods-other-than)
Comment: @asdasdfasdf I understood that you wanted to see this limit using LH, but since a sound answer was already posted, I hope that you don't mind my having shown the solution using a non-LH way forward.
Comment: You can use l'Hopital's rule.  You would probably be better off in this case just using the epsilon-N definition, though.
Answer: $\color{red}{\text{Method 1}}$: Using L-Hospital's Rule for $\frac{\infty}{\infty}$ form as follows $$\lim_{u\to \infty}\frac{u}{\sqrt{u^2+1}}$$ $$=\lim_{u\to \infty}\frac{\frac{d(u)}{du}}{\frac{d}{du}(\sqrt{u^2+1})}$$
 $$=\lim_{u\to \infty}\frac{1}{\frac{2u}{2\sqrt{u^2+1}}}$$ $$=\lim_{u\to \infty}\frac{\sqrt{u^2+1}}{u}$$ $$=\lim_{u\to \infty}\sqrt{\frac{u^2}{u^2}+\frac{1}{u^2}}$$ $$=\lim_{u\to \infty}\sqrt{1+\left(\frac{1}{u}\right)^2}$$ Let, $u=\frac{1}{t}\implies t\to 0 \ as \ u\to \infty$ $$=\lim_{t\to 0}\sqrt{1+(t)^2}$$ $$=\sqrt{1+0}=1$$
$\color{red}{\text{Method 2}}$: Without using L-Hospital's rule
Given, $$\lim_{u\to \infty}\frac{u}{\sqrt{u^2+1}}$$
Let, $u=\frac{1}{t}\implies t\to 0 \ as \ u\to \infty$, hence we have  $$\lim_{t\to 0}\frac{\frac{1}{t}}{\sqrt{\left(\frac{1}{t}\right)^2+1}}$$ $$=\lim_{t\to 0}\frac{1}{\sqrt{1+t^2}}$$ $$=\frac{1}{\sqrt{1+0}}=1$$
Comment: in fact, you  may simply call it substitution.
Comment: Take, $u$ inside the square root. like $u=\sqrt{u^2}$
Comment: @Eric Towers, yes you are absolutely right, you may let $\frac{1}{u}=t$ & proceed. For the sake of clarity, I have edited the answer.
Comment: what is this method of solving limits called? (representing $u$ as a rational function $\frac {1}{t}$) I'd like to look further into it. Thank you!
Comment: How do you go from $\lim\limits_{u \to \infty} \frac{\sqrt{u^2 +1}}{u}$ to $\lim\limits_{u \to \infty} \sqrt{1+(\frac{1}{u})^2 }$ ??
Comment: In your method 1, could you not have taken a shortcut at your fourth line, having shown that $\lim_{u\rightarrow\infty} f(u) = \lim_{u\rightarrow\infty} 1/f(u)$?
Answer: @Harish Chandra Rajpoot has already presented two very sound approaches including use of the requested L'Hopital's Rule
So, I thought that it would be instructive to show another way forward that can be used broadly.
Here, we use asymptotic analysis and write
$$\begin{align}
\frac{u}{\sqrt{u^2+1}}&=(1+u^{-2})^{-1/2}\\\\
&=1-\frac{1}{2}u^{-2}+O(u^{-4})\\\\
&\to 1\,\,\text{as}\,\,u\to \infty
\end{align}$$
... and we are done! Fast and efficient.
Answer: Wow, these answers. I can't believe this. This is such a straightforward limit!
$$\lim_{u\to \infty } \frac{u}{\sqrt{u^2+1}}$$$$ = \lim_{u\to \infty } \frac{u}{\sqrt{u^2(1+\frac{1}{u^2})}} $$$$= \lim_{u\to \infty } \frac{u}{u \sqrt{1+\frac{1}{u^2}}} $$$$= \lim_{u\to \infty } \frac{1}{ \sqrt{1+\frac{1}{u^2}}}$$$$ = 1$$
Boom! No substitutions, no l'Hôpital's rule.
Comment: The only thing that you miss is that the OP himself explicitly asked for a solution based upon l'Hospital's theorem, therefore your post cannot be considered an answer.
Comment: @jyerkimenon And I concede that my way forward is overkill.  Buy note that I preceeded it by stating I was presenting a way forward that has broad use (i.e., asymptotic analysis).
Answer: Use l'hopital's rule $$\lim\limits_{u \to \infty } \frac{u}{\sqrt{u^2 +1}}=\lim\limits_{u \to \infty } \frac{1}{\frac{2u}{2\sqrt{u^2 +1}}}$$
$$=\lim\limits_{u \to \infty } \frac{\sqrt{u^2 +1}}{u}$$
$$=\lim\limits_{u \to \infty } \sqrt{1+\frac1{u^2}}=1$$
Answer: $$\lim\limits_{u \to \infty } \frac{u}{\sqrt{u^2 +1}} = \lim\limits_{u \to \infty } \frac{\color{red}{\sqrt{u^2}}}{\sqrt{u^2 +1}}$$
because

 while $\sqrt{u^2} = |u|$, we may assume $u \ge 0$ since $u \to \infty$ so $\sqrt{u^2} = |u| = u$

After that we have

 $$ \lim\limits_{u \to \infty } \frac{\color{red}{\sqrt{u^2}}}{\sqrt{u^2 +1}} = \lim\limits_{u \to \infty } \sqrt{\frac{u^2}{u^2 +1}} =  \sqrt{\lim\limits_{u \to \infty }\frac{u^2}{u^2 +1}}$$

Actually

 It may help to note that for large $u$, $\sqrt{u^2 + 1}$ behaves like $\sqrt{u^2}$

Solving Limits with L'Hospital's Rules


Sorted is sorting numbers in the wrong direction?

Question: I have the following code:
marketUSDC = {"LTC":USDC_LTC,"BCHABC":USDC_BCHABC}
[key for (key, value) in sorted(marketUSDC.items(), key=lambda x:x[1])]

USDC_LTC and USDC_BCHABC each return a numerical price from an API, which are 60.80000000 and 153.00000000, respectively. The problem is that the second line should be returning [LTC, BCHABC] but it's returning [BCHABC, LTC]. How can I fix this problem such that it's sorted as it should be, from low to high? I understand I could just reverse it, but that would break the code for everything else.
Answer: use sorted(variable, reverse=True), so that it will be the reverse order. SOURCE


Ordenar lista ligada em C

Question: O meu problema envolve ler dados de um arquivo texto, onde é fornecido o CPF,nome,email,idade, ordenar guardar usando lista ordenar em ordem crescente através da idade, caso tiver idade igual ordenar por cpf. Porém estou com dificuldade em ordenar a lista ligada, até agora fiz isso
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Dado{
    char CPF[12];
    char nome[41];
    char email[31];
    int idade;
    struct Dado* proximo;
}Dado;

int ler_string_arq(FILE* arq, char *campo_destino){
    int letra = 0;
    char ch;
    if (fscanf(arq,"%c",&ch) == EOF)
    {
        return 1;
    }
    while( ch != ',')
    {
        campo_destino[letra] = ch;
        fscanf(arq,"%c", &ch);
        letra++;
    }
    campo_destino[letra] = '\0';
return 0;
}

int main()
{
FILE *arq, *arqout;
char ch,teste;

arq = fopen("read.txt","r");

Dado *inicio = NULL, *fim = NULL;

while (1)
{
    Dado *pessoa = malloc(sizeof(Dado));
    pessoa->proximo = NULL;
    if (inicio == NULL){
        inicio = pessoa;
    }
    if (fim != NULL){

        fim->proximo = pessoa;
    }
    fim = pessoa;

    if (ler_string_arq(arq, pessoa->CPF)){
        free(pessoa);
        break;
    }
    ler_string_arq(arq, pessoa->nome);
    ler_string_arq(arq,pessoa->email);
    fscanf(arq,"%d", &pessoa->idade);
    fscanf(arq,"%c", &ch);
}
fclose(arq);

arqout = fopen("write.txt","w");
Dado* pessoa = inicio;
while (pessoa->idade != 0){
    fprintf(arqout,"%s,%s,%s,%d\n", pessoa->CPF, pessoa->nome, pessoa->email, pessoa->idade);
    pessoa= pessoa->proximo;
}
fclose(arqout);
return 0;
}

Estou começando a estudar listas, alguém poderia indicar uma boa maneira de ordenar oq já fiz e como isso alteraria o print
Answer: Ordenando com cópia de valores
A forma mais simplificada de o demonstrar para o código que tem é através de um algoritmo tipo o bubble sort com a copia dos valores de cada estrutura entre si. A diferença dá se maioritariamente no percorrer da lista, que é feito através dos ponteiros proximo.
Implementação:
Dado *pessoa1 = inicio;

while (pessoa1 != NULL){
    Dado *pessoa2 = pessoa1->proximo;
    while (pessoa2 != NULL){
        if (pessoa1->idade > pessoa2->idade){ //se maior troca o conteudo das duas pessoas
            int temp_idade = pessoa1->idade;
            pessoa1->idade = pessoa2->idade;
            pessoa2->idade = temp_idade;
            troca_string(pessoa1->CPF, pessoa2->CPF, 12);
            troca_string(pessoa1->nome, pessoa2->nome, 41);
            troca_string(pessoa1->email, pessoa2->email, 31);
        }
        pessoa2 = pessoa2->proximo;
    }

    pessoa1 = pessoa1->proximo;
}

O primeiro while percorre a lista do inicio ao fim, e o segundo while vai a percorrer mais à frente e sempre que achar uma pessoa com uma idade maior faz a troca de todos os valores dessa pessoa. Como existem várias strings a serem trocadas optei por criar uma função que faz a troca de string até uma determinada quantidade de carateres de forma a simplificar. Como apenas havia um campo do tipo inteiro a ser trocado não fiz nenhuma função para essa troca.
A função troca_string seria:
void troca_string(char *str1, char *str2, size_t tamanho){
    static char temp[50];
    memcpy(temp, str1, tamanho);
    memcpy(str1, str2, tamanho);
    memcpy(str2, temp, tamanho);
}

Neste caso o static evita que a string temp seja cria toda a vez que a função é chamada, e passa a ser criada apenas uma vez, que é o ideal para este cenário. Para a troca da string em si utilizei a função memcpy que já existe para copiar a string toda, mas podia ter feito o mesmo à custa de um loop normal copiando letra a letra.
Esta implementação apesar de funcionar não é muito boa pois a troca de cada elemento da estrutura é bem pesada. Na minha máquina o sizeof(Dado) dá 92, que são 92 bytes, o que significa que cada troca tem de copiar 92 bytes 3 vezes. E pode ainda ser pior dependendo da quantidade e tamanho dos campos da estrutura, assim como da quantidade de elementos a ordenar. A solução a este problema é ponteiros.
Ordenando por troca de ponteiro
Com troca de ponteiros conseguimos evitar a copia dos vários valores, mas esta solução regra geral implica mudar a estrutura original e consequentemente grande parte do código e por isso torna-se um pouco chata.
Neste caso a estrutura passaria a ter um ponteiro para os dados e outro para o próximo nó da lista como já tinha anteriormente:
typedef struct Info { //informação de cada pessoa
    char CPF[12];
    char nome[41];
    char email[31];
    int idade;
} Info;

typedef struct Dado {
    Info* info; //agora ponteiro em vez de os campos diretamente
    struct Dado* proximo;
} Dado;

A estrutura Dado corresponde na verdade a cada nó da lista ao passo que a estrutura Info corresponde às informações de cada pessoa.
Com esta alteração a leitura das informações do arquivo teria que ser diferente pois não só tem de alocar também espaço para o Info como a leitura tem de passar a ser sobre o Info:
int main() {
    ...
    Dado *inicio = NULL, *fim = NULL;

    while (1) {
        Dado *pessoa = malloc(sizeof(Dado));
        pessoa->info = malloc(sizeof(Info)); //alocar também o info

        pessoa->proximo = NULL;
        if (inicio == NULL) {
            inicio = pessoa;
        }
        if (fim != NULL) {
            fim->proximo = pessoa;
        }

        if (ler_string_arq(arq, pessoa->info->CPF)) { //agora ->info->CPF
            free(pessoa->info); //liberar tambem o info
            free(pessoa);
            fim->proximo = NULL;
            break;
        }
        fim = pessoa;

        ler_string_arq(arq, pessoa->info->nome); //->info->nome
        ler_string_arq(arq,pessoa->info->email); //->info->email
        fscanf(arq,"%d", &pessoa->info->idade); //->info->idade
        fscanf(arq,"%c", &ch);
    }
    fclose(arq);

A ordenação agora fica mais simples e mais eficiente pois quando é necessário trocar duas pessoas de ordem, basta trocar o ponteiro para as informações de cada nó:
Dado *pessoa1 = inicio;

while (pessoa1 != NULL){
    Dado *pessoa2 = pessoa1->proximo;
    while (pessoa2 != NULL){
        if (pessoa1->info->idade > pessoa2->info->idade){
            Info *temp = pessoa1->info; //agora troca só o info
            pessoa1->info = pessoa2->info;
            pessoa2->info = temp;
        }
        pessoa2 = pessoa2->proximo;
    }

    pessoa1 = pessoa1->proximo;
}

No mostrar também tem de trocar para ->info:
arqout = fopen("write.txt","w");
Dado* pessoa = inicio;
while (pessoa != NULL) {
    fprintf(arqout,"%s,%s,%s,%d\n", pessoa->info->CPF, pessoa->info->nome, pessoa->info->email, pessoa->info->idade);
    pessoa= pessoa->proximo;
}
fclose(arqout);

Código completo para referência:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Info {
    char CPF[12];
    char nome[41];
    char email[31];
    int idade;
} Info;

typedef struct Dado {
    Info* info;
    struct Dado* proximo;
} Dado;

int ler_string_arq(FILE* arq, char *campo_destino) {
    int letra = 0;
    char ch;
    if (fscanf(arq,"%c",&ch) == EOF) {
        return 1;
    }
    while( ch != ',') {
        campo_destino[letra] = ch;
        fscanf(arq,"%c", &ch);
        letra++;
    }
    campo_destino[letra] = '\0';
    return 0;
}

int main() {
    FILE *arq, *arqout;
    char ch,teste;

    arq = fopen("read.txt","r");

    Dado *inicio = NULL, *fim = NULL;

    while (1) {
        Dado *pessoa = malloc(sizeof(Dado));
        pessoa->info = malloc(sizeof(Info));

        pessoa->proximo = NULL;
        if (inicio == NULL) {
            inicio = pessoa;
        }
        if (fim != NULL) {

            fim->proximo = pessoa;
        }

        if (ler_string_arq(arq, pessoa->info->CPF)) {
            free(pessoa->info);
            free(pessoa);
            fim->proximo = NULL;
            break;
        }
        fim = pessoa;

        ler_string_arq(arq, pessoa->info->nome);
        ler_string_arq(arq,pessoa->info->email);
        fscanf(arq,"%d", &pessoa->info->idade);
        fscanf(arq,"%c", &ch);
    }
    fclose(arq);

    Dado *pessoa1 = inicio;

    while (pessoa1 != NULL){
        Dado *pessoa2 = pessoa1->proximo;
        while (pessoa2 != NULL){
            if (pessoa1->info->idade > pessoa2->info->idade){
                Info *temp = pessoa1->info;
                pessoa1->info = pessoa2->info;
                pessoa2->info = temp;
            }
            pessoa2 = pessoa2->proximo;
        }

        pessoa1 = pessoa1->proximo;
    }

    arqout = fopen("write.txt","w");
    Dado* pessoa = inicio;
    while (pessoa != NULL) {
        fprintf(arqout,"%s,%s,%s,%d\n", pessoa->info->CPF, pessoa->info->nome, pessoa->info->email, pessoa->info->idade);
        pessoa= pessoa->proximo;
    }
    fclose(arqout);
    return 0;
}

Ordenar lista ligada em C


How to add a notification drawer to the toolbar in Jira

Question: We recently switched to Jira+Confluence and I am quite puzzled by the notification drawer.
In Confluence, the toolbar has a notification drawer, where I receive notifications about activity on Jira issues I am participating to:

So, if someone comments on one of my issues in Jira, I see a small notification in Confluence and can jump there to see more. So far, so good.
The strange thing is that this notification drawer is that it does not appear in the Jira toolbar itself:

It seems rather odd to me that Confluence offers me an easy access to Jira activities I could be interested in while Jira itself does not.
I reviewed the configuration options in my profile and made unsuccessful basic researches on this question.

Is there any way to enable this notification drawer in Jira?
If not, what is the rationale being this choice?
Answer: The Notification Drawer is only available in Confluence.
It has been requested for JIRA as well, see JRA-32465. Atlassian answered that they would not work on it for now. If you'd like to have it, you should vote on the issue. Atlassian sometimes does pick up requests with lots of votes.
To receive notifications from JIRA directly, some options are to configure email notifications, or if you use a messaging application like hipchat or slack, you could have JIRA send notifications to chat rooms.
More info about integrating JIRA with Hipchat is available here.
And for Slack, look here.


Show $\int_0^{\infty} \frac{e^{-x}-e^{-xw}}{x} dx = \ln{w}$ for $\operatorname{Re}({w})>0$

Question: I want to show that for $\operatorname{Re}({w})>0$, $$\int_0^{\infty} \frac{e^{-x}-e^{-xw}}{x} dx = \ln{w}.$$ I've tried setting the problem up as: $$\int_\gamma \frac{e^{-z}}{z} dz = 0,$$ where $\gamma$ is the path around the quadrilateral with vertices $a,b,bw,aw$ for some $a,b \in \mathbb{R}$ where $0<a<b<\infty$, but I'm not sure if I am parametrizing the paths between these points correctly.
Comment: There's some way to do this with differentiation under the integral sign. Also: do you know Frullani's integral?
Comment: I didn't know it, but I see how it could be useful here. Thanks for sharing.
Comment: Yeah, for real $w$ anyway, you just have to dominate the partial derivative of the integrand w.r.t. $w$ uniformly by some integrable $g(x)$. Since said derivative is $e^{-xw}$ with $w,x>0$, not too hard. For complex $w$ (real part $>0$), I'm not sure if those arguments carry over.
Answer: Consider the integral
\begin{align}
\int_{1}^{w} e^{-x u} \, du = \left[ -\frac{1}{x} \, e^{-u} \right]_{1}^{w} = \frac{e^{-x} - e^{-w x}}{x}.
\end{align}
Now,
\begin{align}
I &= \int_{0}^{\infty} \frac{e^{-x} - e^{-w x}}{x} \, dx = \int_{0}^{\infty} \, \int_{1}^{w} e^{-x u} \, du \, dx \\
&= \int_{1}^{w} \left[ \int_{0}^{\infty} e^{-x u} \, dx \right]  \, du = \int_{1}^{w} \frac{du}{u} = [ \ln(u) ]_{1}^{w} \\
&= \ln(w).
\end{align}
Hence
\begin{align}
\int_{0}^{\infty} \frac{e^{-x} - e^{-w x}}{x} \, dx = \ln(w).
\end{align}


How do I make a custom  element be used in place of a  in a pre-existing plugin?

Question: I am customizing a theme and a plugin in Wordpress. The plugin has a button where a user can click to bring up a form where they can ask a question. I want users to use post questions through this button on this plugin, but I don't fancy the visuals on it. So I thought I'd make a form on my landing page that will post into the plugin's form. If this is a terrible idea in the long run, please feel free to let me know because I am still new to web dev.
So the goal is to create a new form whose aesthetics are to my liking but still use the plugin's built in posting capability. How do I make my form paste into the plugin's form and then submit it? You'll notice that my form has 1 additional field: the add money field. I also need to integrate this into the plugin. If anyone know how to begin modifying the code for this I'm all ears to anything I need to start reading or a general way of how to approach this.
My form
Plugin's form
Summary:

Need to have my form paste to plugn form and submit
Need to add a field to the plugin code that my form can post to similar to how the other fields will do do
Comment: we can't help you very much without any code
Comment: @Markasoftware what part of the code should I look for specifically? I wanted to post it, but this is someone else's plugin, so there are a TON of files inside the zip file I have. And since I'm new to web dev I'm not sure what to look for.
Answer: You can post from a different form if you get the destination URL or javascript that is handling the original form post. You can use the debugger in Firefox or Chrome to inspect the page contents to see how the form is handled.
Adding the money field will be more complicated because you will need to update the server side handling to accept the additional parameter so that it is not simply ignored or causing errors. How much work this is depends on what the server has to do. It may involve adding a column to the database or creating a new table which you will likely want to do the wordpress way if you want to have something that is maintainable.
Lastly keep in mind, that every time the original plugin is updated, it may bust your add on code unless you create your own plugin from the original.
Comment: Well if I'm customizing the plugin, what benefit would come from downloading updates to the original plugin? Maybe security fixes? Because other than that I am branching it off in another direction because I didn't like the original plugin
Comment: Ok I used the "Inspect Element" tool in Chrome to see what's under the hood. [This is a screenshot of the elements of the form.](http://imgur.com/LF32zEI) What am I supposed to interpret from this?
Comment: You will notice the ap_ajax_form entry in data-action. You need to relate this to the handler in the wordpress javascript that is making the AJAX submission to the server. If you have not yet learned to debug javascript, you will need to do so to understand what the AJAX call is doing and how to add your form entries to it.


Pegar os valores de dois inputs, realizar o cálculo e exibir em um terceiro input

Question: Galera, estou desenvolvimento um formulário que irá calcular o valor do frete e descontar os débitos para chegar ao valor líquido que o Motorista tem para receber. Porém eu queria que alguns campos exibissem os valores conforme o usuário vai preenchendo o formulário.
Por exemplo a imagem, o campo "Diferença de Peso" irá calcular o "Peso de Saída" - "Peso de Chegada" para saber a diferença.
Alguém sabe de algum tutorial de JavaScript/jQuery que realize algo parecido que eu consiga me basear?

            Peso de Saída
            <input type="text" value="0" placeholder="37000" name="PesoSaida" id="ps"/>

            Peso de Chegada
            <input type="text" value="0" placeholder="37090" name="PesoChegada" id="pc"/>

            Diferença de Peso
            <input type="text" value="0" name="PesoTotal"  id="pt" readonly="readonly" tabindex="-1"/>

Comment: E o que você tentou fazer até agora? Qual a sua dificuldade específica?
Comment: Eu andei pesquisando, porém não consegui encontrar nada relacionado a jQuery que seja como se fosse um "sair do campo" pra realizar o evento.
Comment: Com isso vc pode calcular enquanto o usuário vai digitando... http://stackoverflow.com/questions/1481152/how-to-detect-a-textboxs-content-has-changed
Comment: Mas como vou falar quem é o input1, input2 e input3? Para passar os valores.
Comment: Id, name do campo... qualquer seletor válido.
Comment: Está muito errado da forma que coloquei na pergunta agora? @gmsantos
Comment: @JulianoBazzi se puser o trecho do HTML que tem os campos, ajuda.
Comment: @Bacco editei a pergunta com o código fonte do formulário. Obrigado.
Answer: Segue uma demonstração bem simples de como fazer em JS:

var tQtd = document.getElementById( 'qtd' );
var tVlr = document.getElementById( 'vlr' );
var tTot = document.getElementById( 'tot' );

tVlr.onkeyup=calcula;
tQtd.onkeyup=calcula;

function calcula() {
  tTot.value = tQtd.value * tVlr.value;
}
<input id="qtd" value="0" name="quantidade">

<input id="vlr" value="0" name="valor">

<input id="tot" value="0" name="total" readonly>

Notar que não está sendo feita nenhuma verificação dos valores, apenas coloquei o básico para demonstrar como fazer.
Se precisar de coisas mais avançadas, como controlar o separador de decimais, e ajustar a formatação numérica, temos respostas explicando como fazer aqui mesmo:

Como calcular moeda aparecendo casas decimais em JS?
Comment: Utilizar um Framework CSS pode influenciar no funcionamento do JavaScript? Editei a pergunta com o trecho do código que fiz baseado no seu.
Comment: Se quer mesmo usar name, precisa de um índice: `var tPesoSaida = document.getElementsByName( 'PesoSaida' )[0];` mas ainda recomendo o ID.
Comment: O OnKeyUp no caso quando o usuário der uma tab que ele vai efetuar?
Comment: @JulianoBazzi quando digitar qualquer coisa e soltar a tecla. Tem que ser no Up, pois no Down o valor do campo ainda não é alterado. Se preferir que mude somente quando o campo perder o foco, é `onchange`. Se rodar o demo acima, vai ver que muda quando vc está digitando.
Comment: Se quiser cobrir situações mais complexas (copiar e colar, mudanças por JS, etc) melhor um timer atualizando o campo. Em vez de chamar a função no key, chama no setinterval.
Comment: Eu sou novo nessa área de JavaScript, estou começando a mexer agora com ele.. Eu não tenho que dar um "set" pro código passar o resultado pro input do total?
Comment: @JulianoBazzi você clicou no "executar trecho de código" acima e testou? A função `calcula()` faz exatamente isso: calcula e coloca no input.
Comment: fiz o teste e realmente funciona, só no meu código que não
Comment: `tTot` é o campo que tem o total. Estamos colocando o resultado na propriedade `value` deste campo (ou seja, mudando efetivamente o valor). Precisa conferir se não tem coisa digitada errada. Notou o índice que eu mencionei no comentário sobre pegar por nome?
Comment: Sim, eu arrumei o id e no código também isso. Mas continua sem alterações no campo do total.
Comment: a forma de colocar o código está correta? É antes dos campos mesmo?
Comment: O ideal pra quase qualquer JS é carregar no OnLoad, depois da página já toda montada. Se não for fazer no OnLoad, pode deixar esse JS no final do body, depois de todos os outros elementos.
Comment: Muito obrigado, deu certo.


Coefficent Estimates Collinearity Ridge Regression

Question: Suppose you are experiencing collinearity in your data set which is warping estimates of the regression coefficients. If you apply regularisation (in particular ridge regression) to combat this - will the estimates on the coefficients be more reliable or do you still need to mitigate further to combat the collinearity?
Answer: Ridge regression reduces the standard errors of the parameter estimates by allowing some bias in those estimates. You can select the amount of bias to allow. There are methods for selecting this so as to get a "best" result - that is, one that minimizes a combination of bias and error.
Comment: Yes, it will. That's its main purpose. However, colinearity doesn't affect your coefficients, it affects their variance.
Comment: Hi - so if collinearity is impacting your coefficients, will regularisation such as ridge reduce this issue?
Comment: So colinearity doesnt impact the expected value of the coefficients just the variance? Are you able to explain how this is the case please?
Comment: It's because the covariance matrix will be nearly singular.
Comment: Thank you. In your experience is regularisation sufficient or is it still required to remove collinear features? Could you calculate the variance of the coefficients and based on this decide if you need to take additional action?


Characterization of free modules

Question: Let $M$ be a finitely generated module over a commutative ring $A$. Is it true that if there exists a positive integer $n$ and a pair of homomorphisms $\pi:A^n\rightarrow M$ and $\phi:A^n\rightarrow M$ such that $\pi$ is surjective and $\phi$ is injective then $M\cong A^n$?
Answer: Yes, it is.
Let $N=\phi(A^n)$. Then $N$ is a submodule of $M$ isomorphic to $A^n$. Now define $f:N\to M$ by $f(\phi(x))=\pi(x)$. Then $f$ is surjective, and therefore injective. We thus get that $M$ is free of rank $n$.
Comment: @MartinBrandenburg M. Orzech proved that it is not necessary to be an endomorphism: http://www.jstor.org/discover/10.2307/2316897?uid=3737528&uid=2129&uid=2&uid=70&uid=4&sid=21104550594211
Comment: Why does $f$ exist?
Comment: @MartinBrandenburg $f$ is this composition: $\phi(A^n)\simeq A^n\stackrel{\pi}\to M$.
Comment: Alright, but $f$ is not an endomorphism, and therefore the result doesn't apply.
Comment: I didn't know it, thank you!

Characterization of free modules


How do I in Drupal 7 hook into the status message update area after saving a node and it says "updated node" to be a link to that node

Question: In Drupal 7, after saving a node it redirects you back to the page of the node with the message status saying "blog 'title of blog' has been updated".
How do I turn that status message into the link of that node? I need to do this since I have rules setup where I have it redirect to another part of my site, and it just shows the status message of that node being updated. I just need that clickable. im assuming it would be a hook somewhere hook node save?
Answer: You can use hook_node_update() that responds to node updates. There you can add the link in drupal_set_message().
However you may get two status messages, a default status message and another the custom message you just created. For removing the default message you can use Disable Messages module.
Answer: Since you're using Rules, you could add a reaction rule "After saving content" and use a "Display message on site" action to add your own message, e.g add a link using the node tokens available there. Configurable, and no code required.


Vue 3.0 VsBreadcrumb error - Prop being mutated: "items"

Question: I am developing a website using vuesax theme.
vue cli 3.0
Default Layout Page
<template>

        <Navbar
          :topbarColor="topbarColor"
          :logo="require('@/assets/images/logo/logo-light-icon.png')"
          :title="logotitle"
        />

        <SideBar parent=".main-wrapper" />

        <Breadcrumbs :pageTitle="pageTitle" :breadcrumbLinks=breadcrumbLinks />

          <slot />

    </template>

Dashboard Component
<template>
  <DefaultLayout :pageTitle="$t('dashboard.pageTitle')" :breadcrumbLinks=breadcrumbLinks>

    <States />
    <vs-row vs-justify="center">
      <vs-col vs-lg="12">
        <vs-card>

{{ $t('dashboard.projects.recent') }}

                  {{ $t('dashboard.projects.total') }}

90

          <RecentProjects />
        </vs-card>
      </vs-col>
    </vs-row>

  </DefaultLayout>
</template>

Breadcrumbs Component
<template>
  <vs-row class="vs-breadcrumb-row" vs-type="flex" vs-justify="space-around">
      <vs-col
          type="flex"
          vs-justify="center"
          vs-align="center"
          vs-lg="12"
          vs-sm="12"
          vs-xs="12"
          code-toggler
        >
        <vs-card class="br-0">

            <vs-row vs-justify="space-between" vs-align="center">
            {{ pageTitle }}

                <vs-breadcrumb separator="chevron_right"
                :items="breadcrumbLinks"
                ></vs-breadcrumb>

            </vs-row>

        </vs-card>
        </vs-col>
  </vs-row>
</template>

I am getting the following error

and also I have integrated vue i18n module, translation is working fine except for one condition: when I change from EN to FR the current page breadcrumbs translation doesn't change, it still remains in EN, but it's changed to FR when I switch to other pages.
Answer: i18n translates should be a computed property, this is the reason you are getting warnings.
The breadcrumbLinks prop is mutating on the child component whenever you switch one language from another, and this is the reason that breadcrumb translations aren't working, just use a computed property instead:
<template>
  <DefaultLayout :pageTitle="$t('dashboard.pageTitle')" :breadcrumbLinks=breadcrumbLinks>

    <States />
    <vs-row vs-justify="center">
      <vs-col vs-lg="12">
        <vs-card>

{{ $t('dashboard.projects.recent') }}

                  {{ $t('dashboard.projects.total') }}

90

          <RecentProjects />
        </vs-card>
      </vs-col>
    </vs-row>

  </DefaultLayout>
</template>

Comment: Thank you for the answer. now the breadcrumb translation works but still I am getting vue warning. _Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "items"_
Comment: the error / warn occurs in **Breadcrumbs Component** please check that code. thank you


"Cannot allocate memory" when starting new Flink job

Question: We are running Flink on a 3 VM cluster. Each VM has about 40 Go of RAM. Each day we stop some jobs and start new ones. After some days, starting a new job is rejected with a "Cannot allocate memory" error :

OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x0000000340000000, 12884901888, 0) failed; error='Cannot allocate memory' (errno=12)

Investigations show that the task manager RAM is ever growing, to the point it exceeds the allowed 40 Go, although the jobs are canceled.
I don't have access (yet) to the cluster so I tried some tests on a standalone cluster on my laptop and monitored the task manager RAM:

With jvisualvm I can see everything working as intended. I load the job memory, then clean it and wait (a few minutes) for the GB to fire up. The heap is released.
Whereas with top, memory is - and stay - high.

At the moment we are restarting the cluster every morning to account for this memory issue, but we can't afford it anymore as we'll need jobs running 24/7.
I'm pretty sure it's not a Flink issue but can someone point me in the right direction about what we're doing wrong here?
Comment: you have to gain access! :-)
Answer: On standalone mode, Flink may not release resources as you wished.
For example, resources holden by static member in an instance.
It is highly recommended using YARN or K8s as runtime env.


MySQL server eating all of my memory

Question: I have installed MySQL 5.3 and I don't know why it's eating all of my resources. These are some screenshots of my memory usage.

What can I do to diagnose this problem?
My Server is having: Ram:2GB, RedHat5/Apache2/PHP5/Mysql5.1
Comment: Wait, you're *complaining* that the queries are being served from cache?? **Please** tell me I'm misunderstanding you....
Comment: This is _waay_ to broad; we can't answer your question without knowing _anything_ about your software or hardware setup.
Answer: Download and run the MySQL Tuning Primer script (I think you need to edit some things in the top of the script first).
This is a very useful little script that will analyze your my.cnf configuration file and suggest changes etc.

MySQL server eating all of my memory


What is the standard fingering technique to play arpeggio triads with inversions?

Question: Novice here. In playing C Major, it seems pretty straight forward. You start for example playing, 1-3-5 / 5-3-1 (or a 1-2-3) depending on the hand, but other scales like Db for example are starting on a black key, so you end up having to roll your thumb under.
This works for individual notes going up and down the scale, but if you want to play root triads or their inversions all at once, then you can't roll your thumb. Is there a standard arpeggio fingering technique which works for both individual notes and the entire chord?
Comment: I have seen some teachers recommend using thumbs on the black keys as an alternative to rolling, so it doesn't seem as if their is any standard way of playing. I don't know enough to tell if this is an encumbrance or not later on.
Answer: It depends on the linear pattern played. This image covers the basics:

Source: https://imslp.org/wiki/Mastering_the_Scales_and_Arpeggios_(Cooke%2C_James_Francis)
The basic difference is how you change position.
The first group of examples uses linear patterns that stay within the range of one octave and then shift position simply by moving the arm and hand up or down the keyboard. In those cases it's OK to use the thumb on black keys.
The second group labeled with Roman numerals uses linear patterns exceeding one octave and passing the thumb under to change position. When passing the thumb under for those you don't want to pass the thumb under to a black key. You especially don't want to go from a white key to passing the thumb to a black they. It's just a matter of the shape of the hand and the keyboard. Thumb on a white key and fingers on the black keys fits the hand.
Notice that the fingering for...

...is essentially the same as...

...but the F natural where the thumb is used falls on different metrical positions. One is one the beat, the other is off the beat.
You can see that same kind of pattern for the other chords rooted on a black keys.
You could think of it as just one set of fingerings for the three chord positions (inversions) but various linear patterns require starting with differing fingers and changing position at different times.
Comment: actually the pictures say everything
Answer: If I understand the question properly, you want to play only triads - inversions included, with one hand.There is nothing at all wrong with using thumb on black keys for this. Since there are only three notes to be played at a time - either sequentially or as a block chord - it makes sense to use the hand 'flat', as in not move it left or right as you play the three notes. Obviously this is for an arpeggio of the three notes - a block chord with a 'passing thumb' would be pretty daft.
Answer: This depends of what fallows and from the pattern of the arpeggio:
If it's only the triad you can play it like you're proposing. ( e.g. Bachs prelude C).
.
As you see you can also use 1,2,4.
But look at Chopin's Etude 1:
here you need to play with different fingers as it is a quit different arpeggio pattern:

As I have no chance to become a virtuous pianist I always play the arpeggios in my personal finger settings (most comfortable to me!)
(To show and demonstrate simple triads to pupils I let them play even 1,2,3 or even 2,3,4. They have never been ambitious to become pianists and to perform Bach or Chopin. Their purpose was just to accompany the school band on the keyboard - and my goal was to teach them simply chords and the basics of harmony, they were not able to read sheet music! ,
The aim was to discover the joy that lays in making music with friends.)
Comment: Search for bwv 846 in free-scores, musescore or imslp.
Comment: If I am understanding you correctly, there doesn't seem to be any established standard for fingering. Just use what works for the piece you're attempting to play.
Comment: If you want just play the triad c,e,g  and inversions, then yours fingering 135, 125, 135 might be quite established!
Comment: Problem is, that only works for the white keys, unless you are breaking convention and using thumbs on the black keys. Some teachers say that's okay, while others are adamantly against it.
Comment: Any chance you could point me to where I can get hold of the rest of the score for the Bach Prelude above please? I've just spent two months learning to play this using the image above and I'm ready for the next page now! I'd really really like to get hold of a continuation in exactly the same style, with the same fingering and chord notation.
Comment: Thanks @AlbrechtHügli, those sites are a treasure trove, but alas after searching them all I can't find that exact score, nor anything quite as good. Thanks anyway.
Comment: strange! when I google bwv 846 pdf I get plenty of sites.https://www.google.com/search?safe=active&rlz=1C1CHBH_deCH697CH697&sxsrf=ALeKk03hHDA3pedSbH8wy-mYd_j0RF3ByQ%3A1589355002284&ei=-qG7XsTxELCSmwWa85nABA&q=bwv+846+score+pdf&oq=bwv+846+pdf&gs_lcp=CgZwc3ktYWIQARgJMgQIIxAnMgQIABAeMgQIABAeMgYIABAFEB4yBggAEAUQHjIGCAAQBRAeMgYIABAFEB4yBggAEAgQHjIGCAAQCBAeMgYIABAIEB46BAgAEEdQz-wCWJbyAmDtywNoAHABeACAAc4BiAG-ApIBBTAuMS4xmAEAoAEBqgEHZ3dzLXdpeg&sclient=psy-ab


The BV minimizing problem depends on a moving weighted parameter

Question: Let $v\in L^2(Q)$ be given, where $Q:=(0,1)\times(0,1)$ is an unit square. Define a sequence of parameter function $\alpha_s$ by
$$
\alpha_s(x):=
\begin{cases}
1&\text{ if }x\in(1/2+s,1)\times(0,1)\\
2&\text{ if }x\in(0,1/2+s)\times(0,1)
\end{cases}
$$
where $0<s<1/2$.
Define
$$
u_s:=\operatorname{argmin}\{\|u-v\|_{L^2(Q)}^2+|\alpha_su|_{TV(Q)}:\,\,u\in BV(Q)\}\tag 1
$$
where $BV$ denotes the bounded variation space and $TV$ denotes the total variation seminorm.
My question: do we have $u_s\to u_0$ in $L^1$ as $s\to 0$? ($u_0$ is defined by letting $s=0$ in $(1)$)

I am also wondering what if I change $(1)$ by replacing $BV$ with the Ambrosio-Tortorelli functional, i.e.,
\begin{multline}
(u_s,z_s):=\operatorname{argmin}\{\|u-v\|_{L^2(Q)}^2+\int_Q |\nabla u|^2(z^2+1)\alpha_sdx+\\
\int_Q[|\nabla z|^2+(1-z)^2]\alpha_s dx:\,\,u,z\in W^{1,2}(Q)\}\tag 2
\end{multline}
Then, do we have $(u_s,z_s)\to (u_0,z_0)$ in $L^1$? or even weakly in $W^{1,2}$?
Thank you!
Comment: Do you really need convergence in $L^2$ or is convergence in $L^q$ for $1\le q<2$ enough? Since you are in dimension $N=2$ and the Sobolev critical exponent is $1^*=2/(2-1)=2$, I doubt you will have convergence in $L^2$ but by Rellich-Kondrachov you should get $1\le q<2$.
Comment: @Gio67 I was thinking about $L^2$ but yea, let me change it to $L^1$.
Answer: For every $u\in BV(Q)$ define $w:=\alpha_{s}u$. Then $w\in BV(Q)$ (this can be
seen by looking at the weak derivatives of $w$) and so we can write
$$
\Vert u-v\Vert_{L^{2}}+|\alpha_{s}u|_{TV}=\Vert\alpha_{s}^{-1}w-v\Vert_{L^{2}%
}+|w|_{TV}.
$$
Conversely, given $w\in BV(Q)$, if we define $u:=\alpha_{s}^{-1}w$ we have
that $u\in BV(Q)$ and
$$
\Vert\alpha_{s}^{-1}w-v\Vert_{L^{2}}+|w|_{TV}=\Vert u-v\Vert_{L^{2}}
+|\alpha_{s}u|_{TV}.
$$
Thus,
$$
\inf\{\Vert u-v\Vert_{L^{2}}+|\alpha_{s}u|_{TV}:\,u\in BV(Q)\}=\inf
\{\Vert\alpha_{s}^{-1}w-v\Vert_{L^{2}}+|w|_{TV}:\,w\in BV(Q)\}.
$$
The latter problem is much simpler to deal with. Let now $w_{s}$ be a
minimizer for the latter problem (do you need a proof of this?). By taking
$w=0$ you have that
$$
\Vert\alpha_{s}^{-1}w_{s}-v\Vert_{L^{2}}+|w_{s}|_{TV}\leq\Vert v\Vert_{L^{2}
}=M
$$
for every $s$. Since $\Vert w_{s}\Vert_{L^{2}}^{2}\leq2\Vert\alpha_{s}
^{-1}w_{s}\Vert_{L^{2}}\leq2\Vert\alpha_{s}^{-1}w_{s}-v\Vert_{L^{2}}+2\Vert
v\Vert_{L^{2}}\leq4M$, it follows that the sequence $\{w_{s}\}_{s}$ is bounded
in $BV(Q)$ and so by the Rellich-Kondrachov theorem it admits a subsequence
$\{w_{s_{n}}\}$ which converges in $L^{q}(Q)$ for every $1\leq q<2$ to a
function $z\in BV(Q)$ with $z\in L^{2}(Q)$. By selecting a further subsequence
you can assume that $w_{s_{n}}$ converges pointwise $\mathcal{L}^{2}$ a.e. in
$Q$. By the lower semicontinuity of the total variation seminorm and Fatou's
lemma you have that
$$
m_{0}:=\Vert\alpha_{0}^{-1}z-v\Vert_{L^{2}}+|z|_{TV}\leq\liminf_{n\rightarrow
\infty}(\Vert\alpha_{s_{n}}^{-1}w_{s_{n}}-v\Vert_{L^{2}}+|w_{s_{n}}|_{TV}).
$$
On the other hand, if $w\in BV(Q)$, then since $w_{s_{n}}$ is a minimizer
$$
\Vert\alpha_{s_{n}}^{-1}w_{s_{n}}-v\Vert_{L^{2}}+|w_{s_{n}}|_{TV}\leq
\Vert\alpha_{s_{n}}^{-1}w-v\Vert_{L^{2}}+|w|_{TV}%
$$
and so letting $n\rightarrow\infty$, you get
\begin{align*}
\Vert\alpha_{0}^{-1}z-v\Vert_{L^{2}}+|z|_{TV}  & \leq\liminf_{n\rightarrow
\infty}(\Vert\alpha_{s_{n}}^{-1}w_{s_{n}}-v\Vert_{L^{2}}+|w_{s_{n}}|_{TV})\\
& \leq\liminf_{n\rightarrow\infty}\Vert\alpha_{s_{n}}^{-1}w-v\Vert_{L^{2}%
}+|w|_{TV}=\Vert\alpha_{0}^{-1}w-v\Vert_{L^{2}}+|w|_{TV},
\end{align*}
where the last equality follows by the Lebesgue dominated convergence theorem.
This shows that $z$ is a minimizer of the problem for $s=0$. Now if $w_{0}$ is
another minimizer of the problem with $s=0$, then taking $\frac{1}{2}%
z+\frac{1}{2}w_{0}$, by the convexity of the norms
\begin{align*}
& \Vert\alpha_{0}^{-1}(\tfrac{1}{2}z+\tfrac{1}{2}w_{0})-v\Vert_{L^{2}}
+|\tfrac{1}{2}z+\tfrac{1}{2}w_{0}|_{TV}\\
& \leq\tfrac{1}{2}\Vert\alpha_{0}^{-1}z-v\Vert_{L^{2}}+\tfrac{1}{2}
|z|_{TV}+\tfrac{1}{2}\Vert\alpha_{0}^{-1}w_{0}-v\Vert_{L^{2}}+\tfrac{1}
{2}|w_{0}|_{TV}=m_{0}.
\end{align*}
Since the $L^{2}$ norm is strictly convex, we have that $z=w_{0}$. Hence, the
full sequence must converge to the same function $z$, which is a minimizer of
the problem with $s=0$.
Comment: Sorry for my late response. Just got back from other city. I will read your answer asap by tonight! thank you for answering!


version support in android

Question: HI i developed application in android 1.5 and i make it for support screens in large and medium and small through coding if i release android 1.5 on market it will appear in all android version phone market (android 1.5 +) .am i get application in droid,small device market and it is work fine or not
Thanks in Advance
Aswan
Answer: Check the Documentation. Please Note the 1.6 and later version devices's only supports the multiple screen. If you create your app in 1.5 you have to main concentrate on the -v4 attribute. study carefully the Document. Topic Name: Strategies for Legacy Applications.

version support in android