Prevent Opening new NSDocuments and show a warning message

Question: I have an NSDocument based app in which I want to limit the number of documents open at the same time (for a Lite version). I just want to have n documents, and if the user tries to open more than n, show a message with a link to the full app download.
I have managed to count the number of documents using NSDocumentController and, inside readFromFileWrapper, I can return FALSE. That prevents the new doc from opening, but it shows a standard error message.  I don't know how to avoid that.  I would like to open a new window from a nib.
Is there  any way to prevent NSDocument showing the standard error message when returning FALSE from readFromFileWrapper? Or is there any other way to prevent the document from opening   before readFromFileWrapper is called?
Answer: Try the init method, which is called both when creating a new document and when opening a saved document. You simply return nil if the limit has been reached. However, I have not tried this, and it might cause the same error to be displayed.
- (id)init {
    if([[NSDocumentController documents] count] >= DOCUMENT_LIMIT) {
        [self release];
        return nil;
    }
    ...
}

In case the same error is displayed, you could use a custom NSDocumentController. Your implementations would check the number of open documents, display the message at the limit, and call the normal implementation otherwise.
- (id)openUntitledDocumentAndDisplay:(BOOL)displayDocument error:(NSError **)outError {
    if([[self documents] count] >= DOCUMENT_LIMIT) {
        // fill outError
        return nil;
    }
    return [super openUntitledDocumentAndDisplay:displayDocument error:outError];
}
- (id)openDocumentWithContentsOfURL:(NSURL *)absoluteURL display:(BOOL)displayDocument error:(NSError **)outError {
    NSDocument *doc = [self documentForURL:absoluteURL];
    if(doc) { // already open, just show it
        [doc showWindows];
        return doc;
    }
    if([[self documents] count] >= DOCUMENT_LIMIT) {
        // fill outError
        return nil;
    }
    return [super openDocumentWithContentsOfURL:absoluteURL display:displayDocument];
}

Comment: Great. You pointed me in the right direction. I used your code, with  openDocumentWithContentsOfURL, and i could prevent the document creation. But the warning message still appeared when i returned nil. Finally i solved it by overriding "presentError". It the error is my "max documents reached", I show my custom window. Else, i call [super presentError] to show the standard error message. Thanks a lot for your help.


Encrypting digits of a numeric input

Question: Imagine that I have a 4-digit numeric input, 9092, for example. If I want to add +1 to each digit of that number, so that 9 becomes 0, 0 becomes 1, and 2 becomes 3, what should I do?
Comment: Use the modulus operator (%).
Comment: Please post in future code of your attempts to solve the problem. It's not a place to find somebody to solve it for you.
Answer: Here some Code.
x=input("Please Enter Any number: ") #=== Input
y=[char for char in x] #== List of characters
print(y)
for j,i in enumerate(y):
    if int(i)==9: #== if i=9
        y[j]='0' #=== Replace that index with 0
    else:
        print(i)
        y[j]=str(int(i)+1) #== Replace that index with num+1
print(''.join(y)) #=== Print joined slist

input: 9092
output: 0103

Answer: It might not be the best solution, but it works.
num = 9092

print("".join([str((int(n)+1)%10) for n in str(num)]))

Output:
0103

Comment: I tried this, but when I put 9092, I returned 103, not 0103. In this specific coding case, the 0 on the left makes a difference.
Comment: Yeah, I changed it so it returned a string instead to deal with leading zeros.
Answer: that should work:
tmp = [int(i) for i in str(9092)]
output = ""
for i in range(len(tmp)):
    if tmp[i] == 9:
        tmp[i] = 0
    else:
        tmp[i] = tmp[i] + 1
    output = output + str(tmp[i])
print(int(output))

Encrypting digits of a numeric input


How to check and free up disk space in CentOS 7

Question: I have a160 GB VPS with pre-installed CentOS 7 and Webuzo. Using the du -sh command in the www dir I noticed that my sites consume barely 60GB, while the total used space is 120 GB.
Which means my CentOS installation is using 60 GB of space. I read somewhere that 20 GB is enough to install CentOS, so the question is exactly how do I find out what's eating up all space? The Webuzo dir itself in /usr/ is less than 1 GB.
Being a Windows user, I'm not very fond of Unix commands, so any help will be appreciated... I need to free up as much space as possible, thanks. I have full root access via SSH and WinSCP.
Comment: https://dev.yorhel.nl/ncdu is a nice tool to help you discover where your system is consuming the most disk space. - Fairly typical are log files that get too big or kept too long or even indefinitely btw
Answer: you can use du in /
cd /
du -skh * |sort -h

This will sort the biggest directories at the bottom. thne navigate into them and execute the du again until you are satisfied with your findings.


Rename commit message in GitHub

Question: *commit N+20 <-- (HEAD)branch fb/abc(i made 20 commits in this branch)   [most recent]
.
.
*commit N <-- branch dev-abc, origin/dev-abc //created another feature branch from here "fb/abc"
.
.

then I ran the following commands:
git checkout dev-abc
get merge fb/abc

No other changes were made to the dev-abc branch. So this was a simple fast forward merge.
At this point, the graph looks like this.
 *commit N+20 <-- branch fb/abc, dev-abc(HEAD)  [most recent]
 .
 .
 *commit N <-- origin/dev-abc
 .
 .

Now, I pushed all these changes to remote
At this point, while creating a Pull Request, I got a merge conflict in one of the files. (WHY??)
Anyway, I resolved all the conflicts in the GitHub conflict resolver itself. This created a new commit in GitHub which is not present in my local copy. I need to change the commit message for this commit. How can I do this?
There is one more thing, I made two additional commits locally which I haven't pushed yet. Whenever I try to push, I get an error message saying, I have some changes in remote which are not present locally. It suggests me to git pull those changes first(I think it is the additional commit that was created on the GitHub(whose message I want to change)).
 *commit N+22 <-- branch dev-abc(HEAD)  [most recent] // how the graph appears locally
 *commit N+21

 *commit N+20 <-- branch fb/abc, origin/dev-abc
 .
 .
 *commit N <-- origin/dev-abc
 .
 .

I also have some changes which are not committed yet. They are not even in the staging area.
What is the correct sequence of steps that I should take? So, I don't lose any of my work and change the commit message too?
Comment: look at this [tutorial](https://help.github.com/en/github/committing-changes-to-your-project/commit-exists-on-github-but-not-in-my-local-clone)(so that you get all commits locally) and for rename the last commit at this [tutorial](https://help.github.com/en/github/committing-changes-to-your-project/changing-a-commit-message)
Answer: The git commit --amend command allows you to change the most recent commit message.
I'll explain to you how to rename both pushed and unpushed commit.
For pushed commit:
Navigate to the repository.
Amend the message of the latest pushed commit:
git commit --amend -m "New commit message."
Force push to update the history of the remote repository:
git push --force branch-name
Navigate to the repository directory in your terminal.
Run the following command to amend (change) the message of the latest commit:
git commit --amend -m "New commit message."
What the command does is overwriting the most recent commit with the new one.
The -m option allows you to write the new message on the command line without opening an editor session.
Before changing the commit message you can also add other changes you previously forgot with:
git add .git commit --amend -m "New commit message."
Comment: then you need the 'ForcePush' permission to perform this action. If that is the case it is the same as  git reset --soft HEAD~1, commit everything again and then git push branch -f.

Rename commit message in GitHub


Graph theory problem and connected components

Question:
In a connected graph $G$ where degree of every vertex $v$ is even, show that $G\setminus v$ has at most $\dfrac{1}{2}\deg(v)$ connected components.

$G\setminus v$ is the graph which is left after removing $v$ and all of its incident edges from $G$.
Answer: The graph $G$ is Eulerian.  Fix any Eulerian cycle on $G$. It is easy to see, when we remove $v$ from $G$, the cycle will be cut into at most $\frac 12\deg v$ parts, each of which is connected. Since each connected component of $G\setminus\{v\}$ is a union of these parts, there are at most $\frac 12\deg v$ components.


Read and write array from txt in Verilog

Question: First of all I want to say that I'm running the simulation in ADS (Advanced Design System 2017) through a Verilog model compiled in ModelSim.
My objective is loading data from a .txt file into the testbench as input in order to run the simulation, and afterwards save the results of this simulation in another .txt file.
Here is the content for the input test .txt file called "param.txt":
1
2
3
4
5
6
7
8
9
10

And here is my Verilog testbench code:
`include "disciplines.vams"

module resistor(p,n);
electrical p,n;
parameter real R=50.0;
integer file;
integer out;
real pwm_A[0:50];
integer i;
integer j=1;

analog begin

    @(initial_step) // Initial Conditions
    begin

////////////// Read

file=$fopen("param.txt","r");

    if (file)  $display("File was opened successfully : %0d", file);
    else       $display("File was NOT opened successfully : %0d", file);

    for (i=1; i<50; i=i+1) begin
        pwm_A[i]=$fscanf(file,"%d",j);
        j = j+1;
    end

////////////// Write

out=$fopen("out.txt","w");

    for (i=1; i<=15; i=i+1) begin

        $fwrite(out,"%d\n",pwm_A[i]);

    end

// Trying to manually display data
$fdisplay(out,123);

$fclose(file);
$fclose(out);

end

// Simulation (doesnt matter)
V(p,n) <+ R * I(p,n);

end
endmodule

The simulation log has no errors or warnings:
File was opened successfully : -32

But the output .txt file called "out.txt" generates this:
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
123

Instead of the original data.
It's noticeable that the '123' manually introduced value has no problems to be written, but the rest of the data are '0' or '1'.
May anyone spot the problem?
Thanks in advance.
Answer: This line here
pwm_A[i]=$fscanf(file,"%d",j);

should read
$fscanf(file,"%d",pwm_A[i]);

The $fscanf system function is the opposisite of $fdisplay - the function outputs into variables in its argument list. It returns the number of items successfully read from the line. This will (hopefully) be 1 for the first ten lines and will be 0 for the next lines. So, you should really check that number and do something if it's not what you expect, eg:
count = $fscanf(file,"%d",pwm_A[i]);
if (count != 1)
  // whatever

Comment: Thank you very much for your reply. In order to test this code I established 15 values for seeing that the first 10 were 1 and the rest were 0, so I could see anything was going wrong.

In my real design I do know how many values the .txt has, so this is not a problem.

Let's suppose the initial .txt has 10 values (1-10). Using your corrected line:

for (i=1; i<10; i=i+1) begin

 count = $fscanf(file,"%d",pwm_A[i]);

end

I get this error:

Error: Incorrect target supplied to integer-valued $fscanf field.

Any suggestions? count is defined as integer at the beginning
Comment: Yes, but this is a different question. Please ask a new question instead. The idea of Stack Overflow is not only to help the original asker of the question, but also to provide a useful resource for future Googlers.
Comment: Of course, here it is: https://stackoverflow.com/questions/55042142/read-and-write-from-txt-in-verilog


ModuleNotFoundError: No module named "dmidecode"

Question: I have a python code that it has different packages like "dmidecode". I installed dmidecode using Python Interpreter successfully. But when I run the code, I receive this error:

import dmidecode
ModuleNotFoundError: No module named 'dmidecode'

Also, I installed dmidecode like this:
pip install dmidecode

But I received the same error again.
Would you please guide me what is wrong with installing dmidecode?
Any help is really appreciated.
Comment: *I installed dmidecode using Python Interpreter*, did you do ```pip install dmidecode```?
Comment: Dear @Sujay, thank you for your feedback. Yeah, I do that, but I receive the same error.
Comment: What OS are you working with?
Comment: @ductTapeIsMagic, OS is ```Windows 10```.
Answer: did you check, whether your python interpreters (from your pycharm project and where you installed your packages) are the same?
Check if your package is in File/Settings/Project:"YourProjectName"/Python Interpreter All installed packages for this interpreter are listed there.
If it is not, you should change your python interpreter for that project
Comment: Do you mean, the packages that I installed must be in the same path of python interpreter?
Comment: No, when you create a new pycharm project normally a new virtual python env is created too.
But if you installed your package in your default (non-virtual env) than it could be a diffrent one, than your python-env which is used by your pycharm project
Comment: Check if your package is in File/Settings/Project:"YourProjectName"/Python Interpreter All installed packages for this interpreter are listed there.
Comment: If it is not, you should change your python interpreter for that project :)
Comment: Dear @Tim, thank you. I change python interpreter and it solved.


AVAudioUnitEQ / .BandPass filter doesn't work

Question: I can't get the AVAudioUnitEQ to work.
Here's a piece of code that should filter out everything except 659.255Hz +/-0.05 octaves:
// Create Audio Engine

var audioEngine = AVAudioEngine()

// Create Equalizer Node

var equalizerNode = AVAudioUnitEQ(numberOfBands: 1)
var epualizerParameters: AVAudioUnitEQFilterParameters = equalizerNode.bands.first as AVAudioUnitEQFilterParameters
epualizerParameters.filterType = .BandPass
epualizerParameters.frequency = 659.255
epualizerParameters.bandwidth = 0.05
epualizerParameters.bypass = false
audioEngine.attachNode(equalizerNode)

// Configure Audio Engine

var format = audioEngine.inputNode.inputFormatForBus(0)
audioEngine.connect(audioEngine.inputNode, to: equalizerNode, format: format)
audioEngine.connect(equalizerNode, to: audioEngine.outputNode, format: format)

// Start Audio Engine

var error:NSError?
audioEngine.startAndReturnError(&error)

However, when I run it, put on my headphones and sing into the microphone, I can hear myself loud and clear.
Now, according to Wikipedia, the Band Pass filter is:

... a device that passes frequencies within a certain range and
  rejects (attenuates) frequencies outside that range.

What am I doing wrong? I want to filter out everything except given frequency range.
Comment: Did you find any solution?
Comment: @BhavinVaghela I do not even remember ever having this problem. 7 years ago. :)
Comment: Okay no problem :)
Answer: It was your EQ params.
I created a github project with sliders and switches. You can hear the difference.
Try it.
Comment: Even though it doesn't work for me, I'm awarding this answer +50 for all the effort. Thank you!
Comment: I'm using XCode6 beta 7 on OSX 10.9.4. How about you? Try doing a git pull, clean the project, put on headphones, run it and say "work, damnit" and see what happens.
Comment: "Page not found" for this link.
Comment: Hey, thanks! I've just tried it. 1) In the iOS Simulator, all I get is silence; 2) On the iPhone with headphones, when I turn on the EQ, I get `AUSetFormat: error -10868` on `inputFormatForBus(0)` line; 3) On the iPhone without headphones I can hear myself without filtering (with `bypass` is set to `NO`). Any ideas?
Comment: This looks like a bug in the SDK. I've tried to search for `AUSetFormat: error -10868` with absolutely no success. The Audio Engine crashes every time I plug the headphones (into my iPhone 4S). I was planning to address this later when the filtering works, but nope. Sigh.
Comment: I tried my project just in the simulator and I hear it working OK. I haven't tried it on my iPhone because I don't have iOS 8 on it. When you say "I've just tried it", does "it" mean my project?
Comment: Yeah, I mean the project. Now, this is weird.
Answer: This works in my project which uses a playerNode.
var format =  engine.mainMixerNode.outputFormatForBus(0)
engine.connect(playerNode, to: EQNode, format: format )
engine.connect(EQNode, to: engine.mainMixerNode, format: format)

I see you're using the engine's inputNode. Try swapping out these few lines (hook into the mixer instead of the outputNode) and let us know if it works.
Comment: Try a larger value for bandwidth and see if you hear anything
Comment: Tried it. Still the same.


Restrict Yammer Embed

Question: I have been reading through the Yammer embed API doc and one thing to me is unclear. Can our users embed our Yammer group feeds into a website that will be publicly viewable?
I used the code that was provided by clicking on the Yammer Embed button from the web interface, and it appeared that it required authentication. Is it possible that a user could embed this in a website with an auth token so that it would be visible without login?
If this is possible, is there a way that I as a network admin can restrict the embed feature?
Thanks!
Answer: By the nature of Yammer being a private, corporate social network, you are NOT able to embed a feed from your network that is displayed publicly without user authentication using the Yammer Embed widget.
Comment: Thanks Chris! That's the answer I was expecting but it's good to hear it confirmed.

Restrict Yammer Embed


Music theory for Bach's Inventions

Question: I just got a piano and want to start working on Bach's Inventions.  I
have sort of managed to play 2 and 14 some years ago, but my knowledge
of music theory pretty much consists of being able to work out which
dots on a sheet correspond to which keys on the board.  My question is:
what music-theory learning-resources would help me appreciate the
Inventions more and perhaps even memorize them more easily?
Comment: Although (some of) Bach's Inventions are reasonable early pieces to play, music of the Baroque era (composers like Bach, Handel and Vivaldi) isn't really the best place to start for learning the rudiments of music theory. The harmonic structures tend to be far clearer in music of the Classical era such as Mozart and Clementi (and to a lesser extent Haydn and early Beethoven). Clementi in particular has a number of Sonatinas that are excellent starters both in terms of piano technique and basic theory.
Comment: You may want to be able to read sheet music instead of memorize...
Comment: A little more info on your background would help. Do you have a basic understanding of harmony? For example, if you were asked to play a C minor triad, could you do it?
Comment: @replete, no, I don't and couldn't.
Comment: @PatMuchmore, thanks, I'll have a look at the Sonatinas (Op. 36, right?).  They're far from as beautiful as the Inventions though.
Answer: A friend of mine was exceptionally good at playing long pieces from memory. I asked him how he did it. He told me that (a) he memorised the sound of each part (b) he memorised the finger movements (c) he memorised the sheet music!
It never occurred to me to do the last because of course it requires a good visual rather than musical imagination. If it is something you can do then it means you can play the piece as though sight reading but without having to look up and without having to turn any pages.
Interestingly, although all the above sounds like a lot of work, psychological studies show that memory actually works better with many associations than with just one.
Incidentally a good preparation for playing two-part inventions is to learn each part separately. Then try to play them together without having practised them together. Note you can do this with a well-known canon such as London's Burning, Three Blind Mice etc. Start playing with one hand and, by ear, bring in the second part. This helps you hold two parts in your mind at the same time.
Comment: You have mentioned aural memory, finger memory, and visual memory. Structural memory - memory of how the music is made - is also valuable. The inventions are the perfect place to start developing it, because they are composed from so few materials so clearly arranged.
Comment: @replete - Now you mention it, I think he may have said that as well. It was a while ago. I'm pretty sure he memorised everything there was to memorise, including vertical harmony and what inversion each chord was. He also knew figured bass so if necessary he could presumably wing it by harmonising the melody!
Answer: You could study traditional tonal harmony, which would be immensely useful. If you like to learn from books, then something like Percy Goetschius's The Theory and Practice of Tone-Relations is a good place to start. It's quite old, but basically covers all the harmony you'd find in Bach. Here's a free online copy: https://archive.org/details/cu31924021809797. If you're more into YouTube videos, I can strongly recommend all of Rick Beato's stuff. This video should get you started:

.
Answer: This would be a very good idea to start with Bach's Invention. I was tought so too, but my piano teacher was only fixed on phrasing and not at all on harmony. I had to develop all by myself. And I still discover new relations today.
I ment to propose you not to begin with no.1, but with no. 14 and no. 8.
And so I found this link:

I think this will be a good start and most of the analyzing job is already done. You will surely find similar helps on Y.T. if not ask again.
edit
Well, I've just checked the roman numbers and I've noticed that they are relating to C-major and not to a-minor.
In the notation of the link above is meant:
I = C, V = G, ii =dm, vi = am etc. the result of the transcription of roman letters to chords would be ok ...
but the roman nrs. in fact are wrong:
actually in a-minor the first bars will be i - V -i as am is i. until the modulation begins to C-major. And then in C you will write the capital letters for the major chords: C = I, G = V and E7 = V7. Mind that the dominant is always a major chord and so it's a V.
So you can right start to transcribe and ad the chords of no. 1. This is in C-major: The correct Chiffre will be:
Jk
I - V - I (C - G -  C)
The following analysis is much better:

This site contains a pretty nice formal analysis that will be a big help to memorize the whole invention. You can also make an abstract drawing of it and try to do the transfer to other pieces:
http://www.teoria.com/en/articles/BWV772/index.php

Music theory for Bach's Inventions


Trying to add and remove items from an array

Question: The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

printList = function() {
    var listLength = myList.length;
    for (i = 0; i < listLength; i++) {
        document.write(i + ":");
        document.write(myList[i] + "
");
    };
    document.write("

");
};

// initial list
var myList = new Array ();
if (myList.length === 0) {
    document.write("I have " + myList.length + " item in my list. It is:
");
}
else {
    document.write("I have " + myList.length + " items in my list. They are:
");
}
printList();

var continueAdding = "yes";
var askToContinue = "";

while (continueAdding === "yes") {
    // loop
    var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
    switch (askUser) {
        case "A": { // add an user specified item to the list
            var addItem = prompt("Add something to the list");
            myList.push(addItem);
            printList();
            break;
        }
        case "R": { // remove an user specified item from the list
            var removeItem = prompt("what do you want to remove?");
            var listLength = myList.length;
            for (i = 0; i < listLength; i++) {
                if (removeItem === myList[i]) {
                    document.write("I found your " + removeItem + " and removed it.
");
                    myList.remove(i);
                }
                else {
                    document.write(removeItem + " does not exist in this list.
");
                    break;
                }
                if (myList.length === 0) {
                    myList[0] = "Nada";
                }
            };
            printList();
            break;
        }
        default: {
            document.write("That is not a proper choice.");
        }
    };

    askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
    if (askToContinue === "Y") {
        continueAdding = "yes";
    }
    else {
        continueAdding = "no";
    }
}

Answer: Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
    if (removeItem === myList[i]) {
        document.write("I found your " + removeItem + " and removed it.
");
        myList.remove(i);
        break;
    }
    else {
        document.write(removeItem + " does not exist in this list.
");
    }
};

if (myList.length === 0) {
    myList[0] = "Nada";
}

Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.


how to Draw train route map between source and destination in android

Question:
Possible Duplicate:
Android draw route on a Mapview with twoo POI-s

I draw route map between two areas using Google direction API, but I am thinking to draw train route between two stations in android. Can anyone help me?
Comment: Here is a link from web.. Now I don't know how to get the kml file: http://www.google.com/maps?saddr=51.493480,+-0.168690&daddr=Streatham+High+Rd%2FA23&hl=en≪=51.463098,-0.145569&spn=0.086735,0.222988&sll=51.474434,-0.144024&sspn=0.086713,0.222988&geocode=%3BFQrTEAMdTAv-_w&vpsrc=0&dirflg=rT&ttype=dep&date=12%2F14%2F11&time=7:00am&noexp=0&noal=0&sort=walk&mra=ls&t=m&z=13&start=0
Answer: I guess you will be interested in Google TRANSIT and not google direction.
See this page and this too.
Comment: There is no Google Transit API. The spreadsheet linked here isn't an official Google project, it's a spreadsheet with made up data, which it says on the spreadsheet. The feed specification is useful for getting data from agency providers, but you would have to get that route data from the transit agency specifically.
Answer: Google does not provide an official API for getting transit directions or to describe routes, you need to source the data from somewhere else.


How to solo over diminished triads in a bluesy style?

Question: I play the guitar and I like throwing in diminished triads.
They can be easier to finger than the full diminished seventh chord or seventh chord if you're doing country or jazzy less fully voiced styles.
They also work better for tritone substitution.
I kind of have trouble figuring out how to solo over diminished triads though. And I'm not really sure how throw in bends/blue notes as well here.
I mostly like using diminished triads in place of dominants and the tonic. I usually followup with a strong cadence afterwards if I mess with the dominant too much.
So progressions like

VII-dim I V I
VII-dim/bV I V I
VII-dim/V V I
VII-dim/bII V I

Now the simplest way to do this would be to treat these as implied seventh chords

V7 I V I
V7/bV I V I
V7/V V I
V7/bII V I

But I feel this is a bit wasteful of the opportunity here?
Answer: "Bluesy" was mentioned in the title, so there's nothing wrong with playing pentatonic based lines over anything and everything. Minor pentatonic lines on the key center work on basically everything, and that's why guitarists like the pentatonic scale.
If you want to outline the changes better, one easy alternative to deal with backing dim chords in a solo is to arpeggiate the notes of a dim7 chord in some order. Like xx3434 over a B dim with the dim substitution you like to do. You can shift that up in steps of three frets and keep the same notes: xx6767 etc.
If you want the solo to stand out in a different way, try the half-whole diminished scale on the V, over the V chord. The scale contains all the notes of the V dim7 chord, plus the notes of the dim7 a half-step above.
Robben Ford's diminished licks could be a nice starting point, like this one:

Note that the backing band doesn't have to play any diminished stuff, you can overlay a VII dim over a V chord without asking for permission. And since this is blues, where dominant sevenths don't "resolve", you can play a similar pattern over other chords as well, not just the V. For a C chord, play C half-whole diminished lines.
Here's another tutorial on the same style:

Here's Robben himself showing and explaining it:

Another guitarist to steal licks from is Scott Henderson. More info on Youtube.


Processando instruções SQL com JDBC

Question: Estou tentando utilizar o JDBC, mas tendo dificuldades com o uso apropriado da linguagem.
Gostaria de passar o código sql a baixo para o java, e preciso de ajuda com o SELECT.
Em relação as variaveis sql1, sql2, sql3 e o uso dos respectivos where...(para mim estão errados).
Eu fiz desse jeito tendo a clara impressão de que esta errado, mas os coloquei ai para mostrar o que pretendia com o meu código.
select *
from voo, voo_comissarios
where voo.voo_id=voo_comissarios.voo_id and
voo_comissarios.com_cpf=580069359 and
voo.voo_data between '1000-1-1' and '2019-1-1';

static ResultSet vooComissario() {
        ResultSet res = null;
        String sql = "SELECT * FROM voo",
               sql1 = sql+  "WHERE voo.voo_data > ?"
               sql2 = sql1+ "WHERE voo.voo_data < ?"
               sql3 = sql2+ "WHERE voo.voo_id=voo_comissarios.voo_id";
               sql4 = sql3+ "WHERE voo_comissarios.com_cpf= ?"

        Connect();
        try {
            PreparedStatement stm;
                stm = con.prepareStatement(sql4);
                stm.setInt(1, serial);
                res = stm.executeQuery();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível recuperar os dados", "Erro", JOptionPane.OK_OPTION);
        }
        CloseConnection();
        return res;
    }
}

Comment: Você precisa mesmo de todos os dados das duas tabelas? Você tem uma classe voo ou vooComissario? Você quer que os parâmetros sejam opcionais ou poderão variar? Qual o banco de dados?
Comment: E qual a duvida?
Comment: Quanto ao uso do sql1, sql2, sql3 e o uso dos respectivos wheres...(para mim estão errados)
Eu fiz desse jeito tendo a clara impressão de que estava errado, mas queria passar a mensagem da intenção do meu código.
Comment: Qual banco de dados está usando? O que são essas variaveis sql1, 2 e 3? O que você quer comparar? Eu sinceramente não entendi nada do que essa query faz.
Comment: Seguinte, eu estou usando as varias sql, para tentar replicar a consulta que fiz em sql (acima do código em java), como não entendo de jdbc foi nesse código meio estranho que cheguei.
Estou tentando fazer as restrições do where linha a linha, com cada variavel sql recebendo a consulta anterior e restringindo.
Comment: Veja a resposta, com o que foi apresentado, é o que deu pra entender.
Answer: Você não explicou direito o problema, mas pelo que deu pra entender, se for para adaptar a query dentro do método, creio que deve ficar assim:
static ResultSet vooComissario() {
        ResultSet res = null;
        String sql = "select * from voo, voo_comissarios " +
                      "where voo.voo_id = voo_comissarios.voo_id and " +
                      "voo_comissarios.com_cpf = ? and " +
                      "voo.voo_data between ? and ?";

        Connect();
        try {
                PreparedStatement stm = con.prepareStatement(sql);;

                //se for usar números em cpf,
                //utilize o tipo LONG no lugar de INT
                stm.setLong(1 , variavelCpf);
                //passe as datas no formato java.sql.Date
                setm.setDate(2, dataInicial);
                setm.setDate(3, dataFinal);

                res = stm.executeQuery();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível recuperar os dados", "Erro", JOptionPane.OK_OPTION);
        }
        CloseConnection();
        return res;
    }
}

Comment: Nobre cavaleiro Jedi do mundo Java, ensine a nossos jovens padawans a usar o *try-with-resources* para fechar recursos como `con`, `stm` e `res` automaticamente. Ensine aos nossos jovens aprendizes que é mais seguro e menos acoplado retornar uma lista ao invés de um `ResultSet`. Que a força esteja com você!
Comment: @MarcosPinheiroMoura você pode aceitar a resposta como aceita, clicando no `V` ao lado.
Comment: @VictorStafusa boa! hehe Pra falar a verdade eu não tenho muita pratica no uso do `try-with-resources`, mas não sabia que ele fechava todos os recursos sem precisar de finally, vou da uma pesquisada a respeito, valeu pela dica.

Processando instruções SQL com JDBC


Drupal 7 Fields, when adding an existing field during content type creation, how to tell where else its used?

Question: I just realized that if you use an existing field that is used in another content type and you change the field settings, you end up changing it on the other content types that share the same field. Is there a way to tell where else an existing field is being used?
Example: I have a field called "field_image" and using it in my basic page content type. Now I use it for my blog content type. How can I tell my basic page content type was using that same field?
Answer: There's no UI for this anymore. The UI is in admin/reports/fields (h/t Clive)
Here's a good stack about how to find this info with drush:
Is there a listing of Drupal fields?
Or you can grab it from the database:
SELECT entity_type, bundle FROM field_config_instance WHERE field_name = '$MY_FIELDNAME'

Comment: ;( thats not very easily accessible.
Comment: The UI is under the admin reports (where it's always been as far as I know)
Comment: Indeed! I never would have looked there. In Drupal 6 it was under admin/content/types/fields. Thanks, Clive.
Comment: Oh yeah it was somewhere else in Drupal 6, forgot about that :)
Answer: Yes that information is easily accessible on the /admin/reports/fields page. It looks like this:

The first column is the field name, second is the field type, and the third is a list of bundles the field is currently attached to (with links to manage the fields).


How to access gridview data in a seperate button click event?

Question: My requirement is I need to access the Grid view data in a button click event.
I have Grid view with name gvData and have button named Update.
On click of update button I am saving data entered in the grid by user to DB.
Please suggest me in getting this done. Code snippets would be of great help.
I am populating the gridview on page load:
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataTable dt;
                String SQL = "SELECT * FROM tbl_Class";

                string sConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(sConstr))
                {
                    using (SqlCommand comm = new SqlCommand(SQL, conn))
                    {
                        conn.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(comm))
                        {
                            dt = new DataTable();
                            da.Fill(dt);
                        }
                    }
                }

                gvMarks.DataSource = dt;
                gvMarks.DataBind();

            }
        }
<asp:GridView ID="gvMarks" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="Name"/>
                    <asp:TemplateField HeaderText="One">

                        <ItemTemplate>

                            <asp:TextBox ID="txt1" runat="server" Text='<%# Bind("One") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Two">

                        <ItemTemplate>
                            <asp:TextBox ID="txt2" runat="server" Text='<%# Bind("TWO") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Three">

                        <ItemTemplate>
                            <asp:TextBox ID="txtThree" runat="server" Text='<%# Bind("THREE") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Four">

                        <ItemTemplate>

                            <asp:TextBox ID="txt4" runat="server" Text='<%# Bind("FOUR") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="FIVE">

                        <ItemTemplate>
                            <asp:TextBox ID="txtFive" runat="server" Text='<%# Bind("FIVE") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="SIX">

                        <ItemTemplate>
                            <asp:TextBox ID="txt6" runat="server" Text='<%# Bind("SIX") %>'></asp:TextBox>

                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:Button ID="btnUpdae" runat="server" Text="Update Marks" OnClick="btnUpdae_Click" />

    protected void btnUpdae_Click(object sender, EventArgs e)
        {
             //Need to acces the grid view rows and colums here
         }

Comment: Narrow the question to a specific issue. Some code would definitely promote an answer.
Comment: What have you tried so far? If nothing, then try researching first, trying something and if you still have issues come back here and see if we can help. Also, show code you've tried and what problems you've hit.
Comment: I am able to access the column names in the button click event abd i am not able to get the values of rows and columns.
Answer: fetch row one by one by foreach or for loop and save the data.
Click This to know more about save the gridview data to your database
Answer: Try this.
protected void btnUpdae_Click(object sender, EventArgs e)
    {
            int rowIndex = 0;
            StringCollection sc = new StringCollection();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)gvMarks.Rows[rowIndex].Cells[0].FindControl("txt1");
                        TextBox box2 = (TextBox)gvMarks.Rows[rowIndex].Cells[1].FindControl("txt2");
                        TextBox box3 = (TextBox)gvMarks.Rows[rowIndex].Cells[2].FindControl("txt3");
                        TextBox box4 = (TextBox)gvMarks.Rows[rowIndex].Cells[3].FindControl("txt4");
                        TextBox box5 = (TextBox)gvMarks.Rows[rowIndex].Cells[4].FindControl("txt5");
                        TextBox box6 = (TextBox)gvMarks.Rows[rowIndex].Cells[5].FindControl("txt6");

                        //get the values from the TextBoxes
                        //then add it to the collections with a comma "," as the delimited values
                        sc.Add(box1.Text + "," + box2.Text + "," + box3.Text+ "," + box4.Text + "," + box5.Text+ "," + box6.Text);
                        rowIndex++;
                    }
                    //Call the method for executing inserts or update
                }
            }
    }

Answer: You can go with the following approach-
TextBox txt=(TextBox)gvMarks.Rows[i].Cells[0].FindControl("txt1");
string txtOne= txt.Text;

You can use this with for loop and for all the text boxes. Then insert/update the data taken in string variable like txtOne(above used) into the table.Then bind the grid again. You can hit the following link for another solution.
http://forums.asp.net/t/1647616.aspx?Get%20Value%20of%20TextBox%20inside%20the%20GridView%20in%20c%20
I hope this can make your work done.


Special characters (german umlauts) are displayed as ASCII

Question: In our database german umlauts are displayed as ASCII.
Here some examples
Ü is displayed as "š"
ä is displayed as """
Ä is displayed as "Ž"
ö is displayed as """
Ö is displayed as "™"

Here some Oracle enviroment variables:
SELECT distinct client_charset FROM v$session_connect_info
WHERE sid = sys_context('USERENV','SID');
retuns Unknown

select * from v$NLS_PARAMETERS;
NLS_LANGUAGE    GERMAN
NLS_CHARACTERSET    WE8MSWIN1252

I have also noticed, that there is no NLS_LANG setted up.
Can someone give me any clue how to check if this is a problem of env variable or character-encoding itself? Or how to fix it so that the umlauts would be displayed correctly?
Thanks in advance!
Comment: I don't think ASCII has characters like `ä`. You've also shared some characters that look like Czech. Do you mean that e.g. `Ü` displays as `š`? What client program are you using?
Comment: I mean I wish to see ä and I see ". I see this output in sqldeveloper and in toad.
Comment: What character set are your operating system and clients using - e.g. in SQL Developer, what do you have set under Tool->Preferences->Environment->Encoding?
Comment: See http://stackoverflow.com/questions/33783902/odbcconnection-returning-chinese-characters-as/33790600#33790600
Comment: A flagrant [mojibake](https://en.wikipedia.org/wiki/Mojibake) case (example in Python): `'ÜäÄöÖ'.encode('cp437').decode('cp1250')` returns `'š"Ž"™'`.
Comment: I have encoding cp1252 .
Comment: @JosefZ thanks, that gives me the hint for correct answer.
Answer: The first sentence is already wrong, it must be "my client application displays german umlauts as ..." Characters like Ž are not ASCII either. The Oracle environment variables have nothing to do how your client displays any characters.
There could be two reasons:

Characters like š " Ž " ™ are really stored in your database because they are inserted wrong, and you just think it should be Ü ä Ä ö Ö

Your client uses the wrong character set.

NLS_LANG is used to tell the database "my client uses character set XYZ" - no more, no less! Well, some clients inherit the NLS_LANG value for own character set setting but that is not always the case.
Actual answer:
You have wrong data in your database! When you inserted the data then your client was using CP437 (Oracle Character Set US8PC437) but you did not tell this the database.
Most likely data was inserted by sqlplus which inherits the codepage from cmd.exe which is by default 437 on English Windows machines. NLS_LANG character set was set to WE8MSWIN1252. When character set of client and database is the same then data is transferred byte-by-byte without any conversion - there is the mismatch!
Solutions:

Before you run your sqlplus script Set NLS_LANG accordingly, e.g.
SET NLS_LANG=.US8PC437
sqlplus ...

Language and Territory are optional and thus can be skipped.

Your database uses character set WE8MSWIN1252, then it would be beneficial to use it also by your client. By this you can insert and display any character which is supported by the database (no less but also no more)
chcp 1252
SET NLS_LANG=.WE8MSWIN1252
sqlplus ...

Correction of wrong data:
In order to correct the wrong data try this:
UPDATE table_name SET column_name = CONVERT(column_name, 'WE8MSWIN1252', 'US8PC437');

Note, this should be a one-time correction only. Do not put such update as part of your application code!
Update
For correction of PL/SQL code, try this one (not tested):
Create a SQL script like this:
SET HEADING OFF
SET FEEDBACK OFF
SET NEWPAGE NONE
SET VERIFY OFF
SET TRIMSPOOL ON
SET DEFINE OFF
SET ECHO OFF
SET TERMOUT OFF
SET PAGESIZE 0
SET LINESIZE 32767
SET LONG 2000000000
SET LONGCHUNKSIZE 32767

spool PACKAGE_NAME.sql;
SELECT DBMS_METADATA.GET_DDL('PACKAGE', 'PACKAGE_NAME', USER) FROM DUAL t;

spool OFF;
EXIT

And the run it like this
c:\> chcp 437
c:\> SET NLS_LANG=.WE8MSWIN1252
c:\> sqlplus -s ... @<above script>

c:\> SET NLS_LANG=.US8PC437
c:\> sqlplus ... @PACKAGE_NAME.sql

Comment: What do you mean by "change dictionary tables"?
Comment: I see. For ü I get 81. Typ=1 CharacterSet=WE8MSWIN1252: 81,a
Comment: square is displayed as ü. And I get Typ=1 Len=1 CharacterSet=WE8MSWIN1252: 81 for square.
Comment: Thank you. Any chance to change dictionary tables? As it happens in comments of procedures/functions and packages...
Comment: The problem occurs in source code of functions procedures and  packages which  I can see in sys.all_source view. And AFAIK they are stored in some dictionary tables which are read only. So I cant update them just so... And the amount is quite large as there are around 300 such source codes.
Comment: So this is not "normal" data but PL/SQL code? Simply re-deploy the code with proper client settings.
Comment: Ok, thanks! Is there any chance to do it automatically? As There are 300 of them and at least 1600 errors.
Comment: Please see my update
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241811/discussion-between-hajduk-and-wernfried-domscheit).


Using Fancybox, how can I get a "lightbox" to reposition in rails?

Question: I have a lightbox that comes up with instructions in it. It has remote links that then flip through several pages of content, replacing elements in the lightbox remotely.
The problem I have is that when new content is rendered in the lightbox, it doesn't reposition the lightbox. It DOES however, reposition the box if you attempt to resize the window.
Does anyone know how I can add a line of code to reposition the lightbox following a remote page change?
Background information: I render content in the lightbox as such:
 <%= render 'partial1' %>

The link that remotely changes this partial uses a "next_page" action in a controller. This action responds remotely, and thus a next_page.js.erb file is available (wherein maybe a solution could be added).
If there is other relevant background information I can provide, please let me know.
Answer: If the lightbox re-sizes itself when the browser is re-sized, try triggering a resize event on the window object (since the lightbox probably has an event listener for the resize event):
$(window).trigger('resize);

Add the above code to the end of the JavaScript that updates the contents of your lightbox.
There are also a couple options in the Fancybox API that may help:

$.fancybox.resize - You can cal this method and the lightbox will re-size itself based on the height of its current content.
autoDimensions - this is an option you can set to true when initializing the lightbox and Fancybox will automatically re-size itself to the dimensions of new content. As the documentation states:

"Make sure it has dimensions otherwise this will give unexpected
  results"

Here's where I found the API options: http://fancybox.net/api
Comment: you missed an apostrophe on the right bit, might want to correct that.. Otherwise, great! thanks so much!
Comment: also, I've tried using autoDimensions, which is great for resizing - except, it doesn't seem to be able to resize based on the width of the content. Any ideas? (it will resize on height, though).


Existe alguma API que liste estados e cidades?

Question: Estive buscando por alguma API json que liste os estados de um determinado país, ou cidades de um determinado estado, procurei esta funcionalidade por várias APIs do Google Maps mas não encontrei nada que fosse exatamente para isto.
Eu não quero usar uma DB com uma lista de estados e cidades porque acredito que falta flexibilidade e é algo bastante pesado.
Obs: a necessidade é criar um combobox de países, estados e cidades, porém posso utilizar uma lista de países direto do banco de dados sem nenhum problema, mas caso haja uma API que disponibilize esta lista também é melhor ainda.
Há uma boa opção?
Comment: Já há boas respostas aqui sobre isto, em particular para cidades PT & BR. Isso serve-te ou queres cidades do mundo inteiro?
Comment: Sei que é um pouco antigo, mas pode ajudar outros Use a API do IBGE para isso, fonte mais confiável é impossível.
Segue a documentação:
https://servicodados.ibge.gov.br/api/docs/localidades
Comment: Sim, vou precisar de uma lista com todos os países, e em sequência fazer uma requisição da lista de estados, e cidades referente a cada estado.
Comment: Estive procurando por algum similar e achei [esse JSON no Github](https://gist.github.com/letanure/3012978) que pode ser útil.
Comment: so pra constar, da pra usar a api do google maps também.
Comment: Não usar BD é complicado por ficar dependente de API de terceiros, eu já tenho um migrate para cidades e estados que utilizo em Laravel.
Para o seu caso a solução do IBGE citada acima seria a melhor opção.
Comment: Encontrei uma outra API com estados e municípios do Brasil que tem sido bem útil pra mim, é essa aqui: https://www.back4app.com/database/back4app/api-estados-cidades-brasil
Answer: Você pode utilizar o serviço público geonames.org.
Esta página de exemplo mostra as chamadas ao serviço:
http://vikku.info/programming/geodata/geonames-get-country-state-city-hierarchy.htm
A função específica que você deseja utilizar é Children, que retorna coleções de entidades-filhas de um dado GeoNameID - países de um continente, estados de um país, cidades de um estado e assim em diante.
O exemplo acima faz as seguintes chamadas:

Obtém uma lista de continentes
http://www.geonames.org/childrenJSON?geonameId=6295630
Após a seleção de América do Sul (GeoNameID 6255150), obtém a lista de países
http://www.geonames.org/childrenJSON?geonameId=6255150
Após a seleção de Brasil (GeoNameID 3469034), obtém a lista de estados
http://www.geonames.org/childrenJSON?geonameId=3469034

O resultado final é uma lista similar ao exemplo abaixo:
{
"totalResultsCount":27,
"geonames":[
    {
    "geonameId":3665474,
    "toponymName":"Acre"
    },
    {
    "geonameId":3408096,
    "toponymName":"Alagoas"
    },
    {
    "geonameId":3407762,
    "toponymName":"Amapá"
    },
    [...]

Comment: Essa API falta algumas cidades, ao selecionar o estado de São Paulo, você não obtem algumas cidades como a Capital São Paulo, São Bernado do Campo e etc.

[Sâo Paulo](http://www.geonames.org/childrenJSON?geonameId=3448433)
Comment: não é que falta, a chamada da API limita os resultados


How to force an app icon on Android O? (Prevent the launcher from adapting it)

Question: This is my first question on StackOverflow, so please bear with me if I fail to articulate my question.
I am working on an Android app that targets Android O, and I want the launcher to NOT show the icon adapted i.e. remove the white background.
I tried to use adaptive icons and they work, but the problem is that they change the icon itself making it rouned, square, squircle and tear-shaped.
At first I thought it's out of my hands, but some other apps (facebook, whatsapp and snapchat for example) have their icons unchanged.
tl;dr: How can I force an icon to be used by the launcher on Android O?
Answer: The other apps you mention (Facebook, Whatsapp, and Snapchat) don't yet target Android O. Once they do, they'll also be forced to have an adaptive icon as well.
Comment: @dazza5000 - given the [requirement to target API 26 by November 2018](https://android-developers.googleblog.com/2017/12/improving-app-security-and-performance.html), that is, at best, a temporary workaround.
Comment: Yep, how launchers treat apps that target API 26 will be different (it isn't the system that forces the white background, but the launcher), but for the Google created launchers, you should assume an adaptive icon is a requirement for targeting API 26.
Comment: that being said, it looks like you could change your target sdk version to get the result you desire
Comment: hehehehe - i knew ian would protest :) it is good to be mindful of the api bump in november
Comment: But that would also deprive me of the perks of targeting API 26. Thanks for shedding light on that.
Answer: Just remove the targetSdkVersion property from your app level build.gradle file. It will work.
Comment: Or just use a targetSdkVersion below 26 (maybe not ideal solution but it works)


epsilon-delta proofs: can delta be defined in terms of both epsilon and x?

Question: I'm trying to construct a proof for the following limit:
$\lim_{x \to -2} \frac{2x+5}{x+4} = \frac{1}{2} $
I know I need to show that for $ \epsilon > 0$ ,  $\exists \delta > 0$ such that if $0 < |x-(-2)| < \delta$,  $\left|\frac{2x+5}{x+4} - \frac{1}{2}\right| < \epsilon$
Here's the steps I took that led me to my question:
$\left|\frac{2x+5 - \frac{1}{2}(x+4)}{x+4}\right| < \epsilon$
$\left|\frac{2x+5 - \frac{1}{2}x - 2}{x+4}\right| < \epsilon$
$\left|\frac{\frac{3}{2}x +3}{x+4}\right| < \epsilon$
$\frac{3}{2} * \left|\frac{x+2}{x+4}\right| < \epsilon$
I know I want to get this value in terms of just $x+2$ so that I can pick my delta value in terms of epsilon, since the limit is defined as $-2$. Since I have that $x+2$ sitting right in the denominator (and this professor is not sadistic so I don't think he would try to make this overly difficult), I'm wondering if it's "legal" for me to pull the whole $|x+4|$ out of the denominator, and do something like:
$\frac{3}{2(x+4)} * \left|x+2\right| < \epsilon$
and then make $\delta = \frac{\epsilon}{\frac{3}{2x+8}} = \frac{\epsilon(2x+8)}{3} $
If I'm not allowed to do this, does anyone have suggestions about where I might go with it next? I'm really not sure how else to get rid of the denominator. Thanks very much!
Answer: Let's start with where you left. The inequality which needs to be ensured is $$\frac{|x+2|}{|x+4|}<\frac{2\epsilon}{3}\tag{1}$$ To proceed further we need to bound the denominator from below. Thus we can see that $$|x+4|=|x+2-(-2)|\geq 2-|x+2|$$ If we assume $|x+2|<1$ then we have $|x+4|>1$ and therefore $$\frac{|x+2|}{|x+4|}<|x+2|$$ Thus our target inequality $(1)$ can be ensured if we have $|x+2|<2\epsilon /3$ and $|x+2|<1$. It follows that a suitable value of $\delta$ is $$\delta=\min\left(1,\frac{2\epsilon}{3}\right)$$
Answer: So, consider the following:
Take a $\delta_{1} = 1: |x+2|<\delta_{1}$, then this conveys that $1<|x+4|$. Then $\dfrac{|x+2|}{|x+4|}<|x+2|$
So it is proved for: $\delta = min(1, \frac{2}{3}\epsilon)$
Comment: thank you John, that makes sense


Extract tuple containing 'PERSON' in StanforNER list result

Question: I am trying to create a name filter to filter out names from a given text. I am using the StanfordNER and NLTK to do so and doing this actually gives me a list containing tuples. (As shown below)
    [(u'I', u'O'), (u'met', u'O'), (u'with', u'O'), (u'Alan', u'PERSON'), (u'yesterday', u'O')]

What I want to do is that I just want to extract the exact name that has been tagged as 'PERSON' from the list above which contains tuples to get only 'Alan' at the end of the process. Please help.
Answer: weird_list = [(u'I', u'O'), (u'met', u'O'), (u'with', u'O'), (u'Alan', u'PERSON'), (u'yesterday', u'O')]
for word, tag in weird_list:
    if tag == 'PERSON':
        print word

Answer: weird_list = [(u'I', u'O'), (u'met', u'O'), (u'with', u'O'), (u'Alan', u'PERSON'), (u'yesterday', u'O')]
for item in weird_list:
    if 'PERSON' in item:
        print item[0]    #will return item number 1 of the tuple

consider reading pythons documentation on Data Structures


$L^1(μ)$ is finite dimensional if it is reflexive

Question: If $(X,\Omega,\mu)$ is a $\sigma -$ finite measure space, show that if $L^1(X,\Omega,\mu)$ is reflexive then it is finite dimensional.
My attempt: I want to show there is a copy of $\ell^1$ in $L^1(X,\Omega,\mu)$.
For this suppose $L^1(X,\Omega,\mu)$ is infinite dimensional. there is a sequence $\{x_n\}$ of disjoint points of $X$. For every n, Put $\chi_n:=\chi(x_n)$ (characteristic function ). define $\phi:\ell^1\to L^1(X,\Omega,\mu)$ such that $\phi(\{a_n\})=\Sigma a_n \chi_n$. But I can not show that $\phi$ is an isometry.
I think I did not in a correct way. Please help me. Thanks in advance.
Comment: Also you need to normalize $\chi_n$. Once you did it, you can show it is an isometry. Note: since $\chi_n$ have disjoint supports $|\sum a_n\chi_n|=\sum|a_n||\chi_n|$.
Comment: You need to take sets of positive measure instead of points
Comment: Huh? Finite dimensional vector spaces are easy to describe, and you can use equivalence of norms there to get an inner product to dualize.
Comment: Adam Hughes :sorry,I made a mistake in the question. I correct it
Comment: Norbert: Thanks for your advice. I always like your answers.
Comment: I think a big part of the problem is to show there are indeed infinitely many pairwise disjoint subsets each of positive measure.
Comment: I agree. when I choose a sequence of points there is not any problem but now I can not show there is such sequence
Comment: My first thought is to proceed inductively, using the fact that the space is not the linear span of any finite set of characteristic functions.
Comment: I deleted my earlier comment, which pointed out that the original question (the converse of the present question) was trivial.
Answer: Call $A\in\Omega$ an atom if $\mu(A)>0$, but if $B\subset A$ is measurable, then $\mu(B)=0$ or $=\mu(A)$. Since $\mu$ is $\sigma$-finite, we can cover all atoms by at most countably many atoms $A_n$. Let $Y=X\setminus \bigcup A_n$. Then $\mu(Y)=0$ if $L^1(X,\mu)$ is a dual space because the unit ball of $L^1(Y,\mu)$ has no extreme points: if $\|f\|=1$, we can split $\{x\in Y: f(x)\not=0\}$ into two disjoint sets of positive measure (since we're away from the atoms) and write $f$ as a corresponding convex combination, which would contradict Krein-Milman + Banach-Alaoglu (we're applying KM to the relative topology induced by the weak $*$ topology on the subspace $L^1(Y)$).
However, if $\mu(Y)=0$, then $L^1(X)\cong \ell^1$ via the isomorphism $f\mapsto\int_{A_n}f\, d\mu$.
Answer: This is less smart solution than Christian's.
For the begining, every measure space $(\Omega,\mu)$ have continuous $(\Omega_c,\mu_c)$ and atomic part $(\Omega_a,\mu_a)$. Note, for $\sigma$-finite spaces, all atoms are of finite measure. See this question.
Case 1. If atomic part contains infinite amount of atoms we may choose a countalble collection of of disjoint atoms $(A_n)_{n\in\mathbb{N}}$. The desired embedding then would be
$$
i:\ell_1\to L_1(\Omega,\mu):(a_n)_{n\in\mathbb{N}}\mapsto \left(\omega\mapsto\sum_{n\in\mathbb{N}}a_n\mu(A_n)^{-1}\chi_{A_n}(\omega)\right)
$$
Therefore $L_1(\Omega,\mu)$ can't be reflexive as it contains a copy of $\ell_1$ which is not reflexive.
Case 2. If $(\Omega_a,\mu_a)$ consist of finite amount of atoms and continuous part is non empty, then choose any set $A\subset\Omega_a$ of positive finite measure. By Sierpinski theorem, we can divide $A$ onto two parts of equal measure. Each of these aprts we can divide onto two parts of equal measure and etc. In the end we get a sequence of disjoint sets of positive measure. The desired embedding is
$$
i:\ell_1\to L_1(\Omega,\mu):(a_n)_{n\in\mathbb{N}}\mapsto \left(\omega\mapsto\sum_{n\in\mathbb{N}}a_n\mu(A_n)^{-1}\chi_{A_n}(\omega)\right)
$$
Therefore $L_1(\Omega,\mu)$ can't be reflexive as it contains a copy of $\ell_1$ which is not reflexive.
Case 3. If continuous part of measure space is empty, and atomic part consist of finite amount of disjoint atoms $(A_n)_{n\in\mathbb{N}_m}$, then the $L_1(\Omega,\mu)=\operatorname{span}\{\chi_{A_n}:n\in\mathbb{N}_m\}$. So $\dim (L_1(\Omega,\mu))=m$, and $L_1(\Omega,\mu)$ is finite dimensional.


Inserir HTML identado no jQuery

Question: Por que não da pra colocar o HTML identado no jQuery? Se eu coloco ele em "linha reta" ele funciona, ja se eu coloco ele identado, pra ficar mais fácil editar depois, ele ja não funciona. Por que?

SEM FORMATAÇÃO, FUNCIONA:
$j('

FILTROS

Cor

  Amarelo

  Azul

  Branco

').insertAfter('main.col-main');

COM FORMATAÇÃO, NÃO FUNCIONA:
$j('

FILTROS

Cor

               Amarelo

               Azul

               Branco

').insertAfter('main.col-main');

Answer: Porque a partir do momento que é uma nova linha é uma nova instrução, nesse caso você precisar concatenar as linhas para valer como somente uma instrução:
$j('
' +
   '
FILTROS
' +
   '
').insertAfter('main.col-main');

Coloquei somente parte do código para deixar claro o problema.
Comment: Obrigado, Lucas, não sabia disso! :)
Comment: Se a resposta atendeu, poderia marcar como aceita @LucasCarvalho?
Comment: Sim, claro! Só estava esperando, pôs não dava pra marcar antes de 10 minutos acho, mas agora foi.
Answer: Outra forma de inserir textos multi-linhas é com template strings do ES6.
Para declarar uma template string é necessário envolver o texto por crases, dessa forma:
`

FILTROS

`

Dessa forma dispensa o sinal de + para concatenar.
Para usá-lo o browser precisa ter compatibilidade com esse recurso ou usar algum transpiler, como Babel.

Inserir HTML identado no jQuery


creating relationship table at startup MySQL Spring Boot from data.sql

Question: Hello i have a task to build an application using spring boot and hibernate. The thing is i'm building the database through a data.sql file to persist data and create the database. Now i need to create a relationship table between my two tables. This should be a one to many relationship given that a worker can have a user account or may not have an account. The problem lies on how to build this relationship table when the application starts because the references should be the foreign keys user_id and worker_id which i do not have at startup because they are created automatically by hibernate so there's no way to hardcode them. So the question is how would i go about creating this relationchip table from data.sql.
data.sql:
INSERT INTO worker (name, last_name, status) VALUES
('manuel', 'dias', 'active'),
('sailin ', 'nal', 'active'),
('abraham', 'lincon', 'active'),
('mick', 'smith', 'active'),
('jose', 'perez', 'inactive'),
('luis', 'nuñez', 'inactive'),
('ruben', 'puertas', 'inactive'),
('anders', 'stone', 'inactive'),
('luis', 'alvarez', 'deleted'),
('claudio', 'martinez', 'deleted'),
('morfeo', 'rodriguez', 'active'),
('onetys', 'estrada', 'inactive'),
('rene', 'fajardo', 'active');

INSERT INTO users (username, password, user_type, status) VALUES
('madi', 'madi', 'worker', 'active'),
('sana', 'sana', 'worker', 'active'),
('abli', 'abli', 'worker', 'active'),
('mism', 'mism', 'worker', 'active'),
('jope', 'jope', 'worker', 'active'),
('lunu', 'lunu', 'worker', 'active'),
('rupu', 'rupu', 'worker', 'active'),
('anst', 'anst', 'worker', 'active'),
('lual', 'lual', 'worker', 'active'),
('clma', 'clma', 'worker', 'active');

Users.class:
@Entity
@Table(name = "users")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id", nullable = false)
    private int userId;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;
    @Column(name = "userType")
    private String userType;
    @Column(name = "status")
    private String status;

    @ManyToOne
    @JoinColumn(name = "worker_id")
    private Worker worker;

Worker.class:
@Entity
@Table(name = "worker")
public class Worker implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "worker_id")
    private int workerId;
    @Column(name = "name")
    private String name;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "status")
    private String status;

    @OneToMany(mappedBy = "worker", cascade = CascadeType.ALL)
    private Collection<Users> users;

So do i have to:
1: Create another Entity to be able to make a new table in the database holding the foreign keys to user and worker entities?
2: Can it be done with a script in data.sql.
I would create a column in users table referencing the worker id but the task explicitly says:

"make a third table to hold the relationship"

Thanks in advance
Answer: In OneToMany relationship, you can have all needed information on the entity of the many side. Creating another join table only makes sense on ManyToMany relationship, it would only add redundant data on OneToMany and violates normalization.
That being said, if you really need another table to define the two entities relationship, you can achieve this without creating another entity using @JoinTable.
@Entity
@Table(name = "users")
public class Users implements Serializable {
    //....
    @ManyToOne
    @JoinTable(name = "worker_users",
                joinColumns =  @JoinColumn(name = "user_id"),
                inverseJoinColumns = @JoinColumn(name = "worker_id"))
    private Worker worker;
}

@Entity
@Table(name = "worker")
public class Worker implements Serializable {
    //...
    @OneToMany(cascade = CascadeType.ALL) //remove mappedBy
    @JoinTable(name = "worker_users",
                joinColumns =  @JoinColumn(name = "worker_id"),
                inverseJoinColumns = @JoinColumn(name = "user_id"))
    private Collection<Users> users;
}

It would create new worker_user table with this structure
|WORKER_ID  |USER_ID  |

Comment: i get an exception >Illegal attempt to map a non collection as a ´@OneToMany, @ManyToMany or @CollectionOfElements´ I dont know why i get this error because i'm using an Interface. I tried to use List and it would also throw the same error.
Comment: problem solved by changing the variable in the one to many side to a Collection. I had the variable as a Worker object. Dumb mistake. Thanks for the help
Comment: My bad, I misplaced the `@OneToMany` and `@ManyToOne` annotation. Already edited, glad to help!


When a major 6th (or an octave thereof) is in a chord, when is the chord symbol written as a 6th vs. a 13th?

Question: I'm not asking about obvious cases like regular 6th chords or extended chords with 13ths. For example, I'm clear that C E G A is a C6 chord. I'm also clear that C E G B♭ D F A is a C13 chord. (And yes, I know that, in practice, some of those notes—the 5th, 9th, or the 11th—may be omitted.)
I'm interested in theoretical and edge cases. Let's begin with an example like C E G A B♭. Wikipedia says it's a C7/6 chord. Fine.
The 7/6 notation seems to begin and end with sevenths, however. There is no 9/6 chord that I can find, for example. (That's not to be confused with a 6/9 chord, which does not have a 7th.) So, if we had C E G A B♭ D, what would that be, assuming C is the root and we wanted to leave nothing to ambiguity? Our choices are:

C9(add13)
C7/6(add9)
C9(add6)
C13(omit11)

Again, I'm sure someone's going to say that you can omit the 11th from a 13th chord, so C13 is appropriate. But what if I wanted to find a chord symbol that was unambiguous about what's in and what's not, irrespective of the voicing?
If we root the chord on G, we have a similar problem:

Gm6(add9,11)
Gm(add9,11,13)
Gm13(omit7)

(I thought of Am11(♭9), which is perhaps the simplest of all, but that's not useful to the question.)
What plays into the decision to call it a 6th or a 13th? Sure, we could say it's the proximity of the 6th to the root, but that doesn't feel totally comfortable to me because chord symbols don't necessarily imply or reflect chord voicings. So what is the rule?
Update
I understand the answers I'm getting. Thank you. I was hoping for answers which don't take context into consideration, though. (Think of an algorithm which generates possible chord names given nothing but a set of pitch classes.)
Answer: This is a tricky question, and I think answering it requires digging into various music notation systems and their purpose.
Sometimes as a composer, you want to specify exact notes for people to play. Standard notation is perfect for this. Other times, you want to lay out a structure and let your musicians decide on the exact voicing and other details. Chord symbols and slashes are perfect for this.
When you get into these extremely detailed extended chord symbols, it often seems like an unholy union of these two ideas. If you're composing something and you really want me to play C E G A B♭ D, then just write that (in standard notation), don't try to communicate that to me with a crazy symbol. If you're analyzing a piece of music and need a label for that set of pitches, then again I ask for what purpose? If it's so that you can give it to someone and have them recreate it then I have the same answer as before. If it's to understand the theory of the piece, then are the extreme extensions of the chord actually important? Is the absence of a note (the 11th in your case) actually important? The ambiguity should be a hint that it doesn't really matter.
As far as the validity of the labels you suggest, my opinion is that multiple "add"s are bad. I would probably go with C13(no11) or C9(add6) for a C root.
Comment: Thank you; that's useful. +1 I especially appreciate the "multiple 'add's are bad". But the title question remains... Should the A be called a 13th or a 6th, and are there rules which govern this? Or is it simply my choice based on voicing?
Answer: When naming chords, composers can hardly find them agreeing with each other, especially when they are in different eras, genres or instruments. For example, the C6 chord may refer to C E G A, which is a C major triad plus a major sixth; but it's more common to be C E A in classical music, as the first inversion of the A minor triad, with the 6 notating the A being the major sixth of the inverted root, C; which is more often written as Am/C in modern music. It all depends on the context.
P.S. I personally like to notate C E G A as C6 and C E A as C6 (if necessarily not written as Am/C), to avoid confusion. In my system, I use superscript for intrinsic attributes such as major/minor/seventh/extension/bass note etc., and subscript for added/omitted/suspended notes.
Every composer is entitled to invent his/her own way to notate chords, as long as it can be understood by the musicians who read his sheet. C6 can be more ambiguous than Cadd13, but if the chord appears many times in a score, no one would blame you for using the more abbreviated form. It's just you are obligated to make sure no one is confused, most times a small line of text will do the trick - which in the C6 case is not necessary, because it's so common that everyone can recognize it.
The C7/6 in your question, can be found in publications by minimalism musicians. I myself prefer to write it as C7add13, so it's clearly a dominant 7th chord with an added 13th. The so called "C9/6" chord should be a C9add13. It's technically equal to a C13omit11, but when you say "C9/6" in the first place, you are emphasizing it's functioning as an extended 9th chords rather than a 13th.
As for the 6th vs 13th, I personally always try to avoid using the 6 notation. Some may interchange them, some may use 6 only when there is a note which has to be exactly a 6th above the root. Then again, it all depends on the context and which system the composer/editor uses. I respect them as long as they are self-consistent.
Answer: To be exact, one needs to write in all the appropriate dots. Writing merely a chord name just won't do it, in so many cases. When we see 'C' written, there are numerous ways in which it can be played/voiced, all of which would be construed correct. Even seeing C/G only guarantees that the lowest note would be G, under a however-voiced C chord.
Drop chords will to some extent make playing closer to what the writer expects, but those aren't often used. Leaving out 9 and 11 is commonplace in 13th chords, but not as accurate as the OP wishes for. Even seeing a carefully thought out C13,no11 or C9add6 will result in several different versions being playable - although restrictive on guitar - so for me the only concrete way is to prescribe exactly what you want played in the dots. But be careful when writing for guitar - it may not be possible to reach each in the written order!
Answer: I think the issue is that there are a few different ways to say a lot of things and none of them are necessarily more correct than another.  Theory is a means of describing what is happening in the music, so when we try to describe what's happening and have to choose between 6 and 13, what's the difference?  They're the same note and tend to have the same effect on the harmony, so I think the terminology that is most commonly used is going to depend on context.  This isn't to say that there is no way to spell out exactly what notes you want to be in your chord, just that the standard notation that you will find people using doesn't provide this.  The best notation that I've seen to describe exactly what notes are in a chord is to basically define the chord type, then, in parentheses, write the extensions and alterations that apply.  Since 9, 11, and 13 are all enharmonically equivalent to 2, 4, and 6, there shouldn't be too much concern for which of those you choose to use.  I think there are some better choices to be made based on context but in an attempt at using notation without context, I would think that 9, 11, and 13 are more commonly accurate representations of those notes.
So for your first example (C E G Bb D A), the notation I am referencing would look like this:
C7 (9, 13)
This allows you to show exactly which notes are in the chord.  This can get tricky in a few areas, for instance, the altered chord, which you could potentially spell out this way:
C+7 (b9, #9, #11)
This is difficult because the way the world of jazz talks about an altered chord does not include an augmented fifth, they refer to it as a b13.  With that in mind, there wouldn't really be a standard chord symbol to indicate a 7 chord with no 5, so I think writing it as I did would be the easiest way to spell out every note in the chord, even though it goes against the standard terminology.
On the whole, context does need to be considered.  You can find instances of the same terminology being used in two different realms of music and find that they don't mean the same thing.  For example, the dreaded 13 chord.  In Jazz, you will find that a 13 chord is basically a dominant chord that has a 13. In Classical, a 13 chord (which I believe they call a 13th chord), would be based on the scale degree that it was formed on, so in C Major a C13 would be a major chord but an A13 would be a minor chord.  On top of that, the 13 of each chord would be different, where C13 would have a Major 13 and the A13 would have a Minor 13.  Taking it a step further, if we were in A Major, A13 would be a major chord with a major 13 and C13 would be a major chord with a major 13 (derived from the parallel minor)
We also see plenty of instances of one concept having more than one name.  In rock/pop/country/etc you don't really see 13 very commonly; you are much more likely to see 6.  Add2 and Add9 are another example.  These are effectively the same thing but someone might understand one and not the other.
Answer: Your main question is "how to decide whether a chord be called 6th or 13th" and the answer is: well yes the proximity to the root IS a deciding factor. Not 100% (because again context) but a very strong one. What makes it stronger is the fact that there's NO OTHER factor. The only other factor is particular context, that might invalidate the guiding principle.
Now, you say that it's not comfortable, as "chord symbols don't necessarily imply or reflect chord voicings". But in fact they can imply some details about the voicing, even if they don't imply the complete layout. So in this case notation might strongly suggests, the 6th should not be played in root octave.
So if you apply this thinking to your first example, and will check only for that single aspect of the voicing (namely where is the 6th), then you will end up with choice of two labels for each chord, out of each there's always one that is a definitely simpler description of what is going on (C7/6(add9) and C9(add13))
And anyway from this point on the only factor playing into choosing the label is wider musical context, which in case of your algorithm that works without context doesn't exist and makes the choice purely aesthetic.
To elaborate a bit about the 'simplicity' and 'aesthetics' for example: the choice between labels: C9(add13) and C13(omit11) is really a matter to sticking to certain convention. I can't see any harmonic context where choice of one over another would carry any information. I personally like the convention where 'omit' is applied to base voices and 'add' is used to selectively apply extensions, as it reflects how we naturally think about building chords - we add extensions and decide to omit some core voice.
Answer: You're asking for a definite ruling on 'theoretical and edge cases'.   Sorry, almost by definition one isn't available.  Chord symbols cannot be a full description of every possible chord.  Sometimes we need notation.
Comment: I agree that chord symbols cannot be a full description of every possible chord. But I'm trying to go as far as the "chord symbol rules" allow. Which of the choices I gave do you think are the best? And why?
Answer:
I understand the answers I'm getting. Thank you. I was hoping for
  answers which don't take context into consideration, though. (Think of
  an algorithm which generates possible chord names given nothing but a
  set of pitch classes.) - trw

Step 1: Identify the intervals that best fit the pitch classes specified.
This step would provide you with:

interval set (p1-m3-p4) when the pitch classes are (0,3,5)
interval set (p1-m3-d5-dd7) when the pitch classes are (0,3,6,9)
and so on ..

the algorithm for this is not straightforward and would include parameters as:

fit the intervals against a set of available qualities (dom7, dim7, min, maj, ..)
fit added, altered notes against the reference scale (major/mixolydian)
avoid as many as possible intervals with conflicting degree classes
prefer certain intervals or combination of intervals over others
and many more subtleties ..

Step 2: Identify the (compound) degrees that best fit the intervals calculated.
The following context-free algorithm can be used to identify compound degrees for chords that adhere to tertian standards. (chords with mixed sixths are excluded)

If no sevenths

any sixth would be of degree 6 (A)

otherwise

if no ninths and no elevenths

if the sixth is major

this sixth would be of degree 6 (B)

otherwise

any sixth would be of degree 13 (C)

Examples:

(A) Cm6add#11, D#6no3
(B) C7/6(b5), D#(7/6)
(C) Cm7b13, D#13b5b9
Answer: The most important element of the question is the "not considering context" element. Calling a note the sixth or thirteenth is specifically dependent on context or, once given, implies a context.
Edward Aldwell and Carl Schachter offer a very useful distinction (in the context of classical music): in a chord with a 6, the 6 is a suspension delaying the arrival of 5; in a chord with a 13, the 13 replaces the 5.1 (They do not address the possibility that both 6/13 and 5 are present.)
Further, by giving the chord a name (Cm6, Cm7add13, etc...) there is also typically an implied meaning (i.e., context) to the chord (Cm6 suggests a tonic chord; Cm7add13 suggests a ii chord).
If you really want to name the chords consistently and accurately without context, then use a contextless notation. To take the first example from the OP, C E G A B♭ D, which otherwise could be

C9(add13)
C7/6(add9)
C9(add6)
C13(omit11)

would all simply be (02479T) (i.e., a set of "pitch classes").2 If note order is important (i.e., some minimal context), then you could call it [0479T2] (ordered pitch classes). And if you really want to get fancy, you could name it according to the intervals <43214> ("interval classes"), which is non-specific in terms of the chord root. Then, to designate the above example, it would be T_0(<43214>) (T_0 here means [T]ranspose to C (= 0)). To transpose the identical chord to C# would be T_1(<43214>).

1 Edward Aldwell and Carl Schachter, "Harmony and Voice Leading", 2nd ed. (Harcourt Brace Jovanovich, 1989), pp. 449-53.
2 The notation here is called "pitch-class notation", which assigns 0 = C; 1 = C#; 2 = D; ...; T = 10 = A#/Bb; E = 11 = B. There is a closely related interval-class notation which assigns intervals based on the number of half-steps (mod 12): 0 = unison/octave; 1 = one half-step; 2 = two half-steps; T = ten half-steps; E = eleven half-steps. Given a set of pitches (or intervals) they can be transposed by X half-steps by the function TX: thus, T1(CC#E) = T1(014) = (125) = C#DF. Searching terms like "pitch class", "interval class", and "musical set theory" will provide a wealth of information. Text books on "post-tonal theory" also will generally discuss these concepts.
Comment: What's the name of the notation you're using there? (02479T), for example. And is it documented some place?
Comment: @trw It's called "pitch-class notation". I've added a note with a (very) brief explanation and some suggestions for how to learn about it.
Comment: The OP is asking a question about how to write notation that will be understood by other people. Pitch class notation is not the way to do that.
Comment: @BenCrowell You're discounting a whole lot of "other people" who understand pc notation perfectly well. But even allowing for that, OP specifically mentions pitch classes, asks for rules that could be applied algorithmically, and asks for a definition of 6th vs 13th. I've answered those questions. Other answers address the issue of traditional chord symbols. Since OP asks about contextless naming, I've given an answer that expands the possibilities.
Comment: @Aaron A better term here may be "pitch-class sets," since technically these aren't pitch classes.


Forçar saída do laço while em switch C

Question: Galera, eu fiz um menu em linguagem C, porem preciso que quando o usuário digite a opção 4, ele saia do laço de repetição do/while, alguém pode me ajudar. Mais uma vez obrigado a todos pela participação.
int opcao;

do
{
    menu();
    printf("\n");
    printf("Opção selecionada: ");
    scanf_s("%d", &opcao);

    switch (opcao)
    {
        case 1: adicionar();
            break;
        case 2: modificar();
            break;
        case 3: relatorio();
            break;
        case 4: Sair;
    }
} while ((opcao >= 1) && (opcao <=4));

Answer: Creio que o que deseja é:
int opcao;
do {
    menu();
    printf("\nOpção selecionada: ");
    scanf_s("%d", &opcao);
    switch (opcao) {
        case 1:
            adicionar();
            break;
        case 2:
            modificar();
            break;
        case 3:
            relatorio();
            break;
        case 4:
            break;
        default:
            printf("\nOpção inválida");
    }
} while (opcao != 4);

Comment: Top, era exatamente isso que eu queria fazer muito obrigado
Answer: Se o seu código estiver dentro de uma função, você poderia usar return para sair, veja só:
void foobar(void) {
    int opcao;

    while(1) {
        menu();
        printf("\n");
        printf("Opção selecionada: ");
        scanf_s("%d", &opcao);

        switch (opcao) {
            case 1:
                adicionar();
                break;
            case 2:
                modificar();
                break;
            case 3:
                relatorio();
                break;
            case 4:
                return;
            default:
                printf("\nOpção inválida");
        }
    }
}

Forçar saída do laço while em switch C


PHP echo img src

Question: I got something like this: print '';
it shows me right link, but image doesn't appear. When I go to browser console, I get this error: http://somesite.com/somesite.com/thisimage.jpg
I tried <img src="<? php echo $rlink; ?>"/>
It is not working. I was looking around forums but didn't found a solution. Thank you for any help!
Comment: what is the value of `$rlink` variable
Comment: It means the URL to the image is wrong. Without knowing a) what URL that is exactly and b) what it *should* be, we obviously can't help you a whole lot here.
Comment: Is `$rlink` an absolute or relative url?
Comment: $rlink is somesite.com
Answer: <img src="<? php echo $rlink; ?>"/>

needs to be:
<img src="<?php echo $rlink ?>">

it might not solve the problem because i dont kno what the value of the variable is. It might be wrong.
Answer: I'm guessing your variable $rlink contains somesite.com/thisimage.jpg. Since it doesn't have a protocol at the beginning, the browser thinks it's a relative path, thus trying to go to somesite.com folder, which doesn't exist. You can either put http:// at the beginning of the src, or remove domain so it's treated like the relative path it is as of now
Comment: OMG IT WORKED thanks man!!!
Comment: No problem, glad it worked out for you

PHP echo img src


What can we say about open unit balls of sup-norm and integral-norm

Question:
Consider the normed linear spaces $X_1=(C[0,1], ||.||_1)$ and $X_{\infty}=(C[0,1],||.||_{\infty})$ , where $C[0,1]$ denotes the vector space of all continuous real valued functions on $[0,1]$ and $$||f||_1=\int_0^1|f(t)|\,dt.$$and $$||f||_{\infty}=\sup\{|f(t)|:t\in [0,1]\}.$$Let, $U_1$ and $U_{\infty}$ be the open unit balls in $X_1$ and $X_{\infty}$ respectively. Then

$U_{\infty}$ is a subset of $U_1$.

$U_1$ is a subset of $U_{\infty}$

$U_{\infty}=U_1$

Neither $U_{\infty}$ is a subset of $U_1$ nor $U_1$ is a subset of $U_{\infty}$.

I really don't know from where I start to solve and conclude about open balls..Please help..
Comment: Hint: What's the relationship between a Riemann integral on the interval $[a,b]$ and the difference $(b-a)$?
Answer: Since it seems that you want to solve it yourself, I'll just give you a hint. If you want a more accurate answer, just leave a comment.
HINT: In a normed space the unit open balls is the set of all elements which have a norm strictly less than 1. Now, what does it mean that $\left\Vert f \right\Vert_1 < 1$? What does it mean that $\left\Vert f \right\Vert_{\infty} < 1$?
Edit: We have
$$\left\Vert f\right\Vert_1 = \int_0^1 |f(t)| ~ dt \leq \int_0^1  \left\Vert f \right\Vert_{\infty} ~ dx  = \left\Vert f \right\Vert_{\infty} \cdot \int_0^1 1 ~ dx = \left\Vert f \right\Vert_{\infty}$$
for every $f \in C[0,1]$. It follows that if $\left\Vert f \right\Vert_{\infty} < 1$, then $\left\Vert f \right\Vert_1 < 1$ also. Hence, $U_{\infty} \subseteq U_1$, i.e. 1. is true.
This already shows us that 4. is false.
Now to see that 2. and 3. (which are now equivalent) are false: Consider the function
$$f(x) = \begin{cases} 2 - 8x  & , x \leq \frac{1}{4} \\ 0 &, \text{ otherwise} \end{cases}$$
Then, $f \in C[0,1], \left\Vert f \right\Vert_{\infty} = 2$ but
$$\left\Vert f \right\Vert_1 = \int_0^{1/4} 2 - 8x ~ dx = [2x - 4x^2]_{x=0}^{1/4} = \frac{1}{4} < 1$$
Hence, $f \in U_1$ but $f \notin U_{\infty}$. This shows that neither 2. nor 3. can be true.
Comment: $||f||_1<1$ and $||f||_{\infty}<1$ both..Then ?
Comment: I'm asking you to think about what each of these statements means and find a connection between them. However, if you want, I can just give you the answer.
Comment: I am unable to do..Please give more details.
Comment: I edited the answer to contain the complete solution.


Função remove em uma lista altera elementos em outra Python3

Question: def almostIncreasingSequence(sequence):
x = sequence
for i in range(len(x)):
    sequence = x
    cont = 0
    y = False
    sequence.remove(sequence[i])
    for j in range(len(sequence)):
        try:
            if sequence[j] < sequence[j+1]:
                cont += 1
                if cont == (len(sequence)-2):
                    y = True
        except:
            if sequence[-1] > sequence[-2]:
                    cont += 1
        if cont == len(sequence)-1:
            if y == True:
                pass
            else:
                y = False
return y

Estou com um problema nesse código, pois quando uso o remove na lista sequence, além dele remover o elemento na lista sequence, mas como também remove o mesmo elemento da lista x, gostaria de saber como consertar isso, ou caso não seja possível utilizando o remove, se é possível ter uma variavél para guardar a lista sequence sem que ela seja alterada.
Comment: O que esta função precisa fazer?
Comment: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Comment: Eu continuo com o mesmo problema, quando removo o item da lista sequence, ele continua excluindo da lista x também
Answer: Em Python, as listas são mutáveis, o que significa que quando você passar uma lista por parâmetro para uma função, não será realizada a cópia do objeto, mas sim passado o próprio objeto. Qualquer modificação no objeto dentro da função, tal como o remove, será refletida no objeto fora da função.
Assim, por exemplo, se eu passar uma lista de dois valores para uma função e nesta remover o último elemento, fora da função também terei uma lista de um elemento.
def remover_ultimo_elemento(lista):
    lista.pop()

lista = [1, 2]
remover_ultimo_elemento(lista)

print(lista)  # [1]

Veja funcionando no Repl.it | Ideone
Sobre isso você pode ler também aqui:

Como passar argumentos por referência em Python?
Referência e Parâmetro em Python
Como Python mantém a mesma referência de memória de uma lista após redimensioná-la?
Como passar argumentos por valor no Python?

Mas perceba que em nenhum momento o enunciado do problema pede para remover o elemento da lista; o que se pede é para determinar se, a partir da lista de entrada, é possível criar uma lista estritamente crescente removendo apenas um elemento. Uma lista é considerada estritamente crescente se para qualquer valor a[n] da lista seja menor que a[n+1] - perceba que é menor, não menor ou igual.
Ou seja, para fazer a verificação, basta você percorrer a lista em pares de valores e verificar se o primeiro valor é menor que o segundo. Se o primeiro for maior ou igual ao segundo nenhuma ou uma vez na lista inteira, então o retorno será verdadeiro; caso contrário, falso.
def is_strictly_increasing(numbers):
    counter = 0
    for a, b in zip(numbers, numbers[1:]):
        if a >= b:
            counter += 1
    return counter <= 1

print(is_strictly_increasing([1, 2, 3, 4, 5]))  # True
print(is_strictly_increasing([1, 2, 3, 3, 5]))  # True
print(is_strictly_increasing([1, 2, 2, 1, 5]))  # False

Ou em sua forma resumida:
def is_strictly_increasing(numbers):
    counter = sum(1 if a >= b else 0 for a, b in zip(numbers, numbers[1:]))
    return counter <= 1

Comment: Excelente solução ao problema! Como não podia deixar de ser, python resolve o problema com uma linha :D
Comment: Muito obrigado, me esclareceu bastante. =D
Answer: Em Python quando você faz list1 = list2 então as duas listas apontarão para o mesmo objeto e mudar o valor de uma implica em mudar o valor de outra. Você pode resolver o seu problema fazendo uma cópia da lista utilizando list.copy().
Gostaria de adicionar que como você fez x = sequence antes do loop e sequence = x após o loop então mesmo que você utilize a cópia que sugeri acima, você vai voltar a apontar para o mesmo objeto. Ex.: x = sequence.copy()


Ansible Java 17 priority task has no permission

Question: I am trying to create a task in Ansible which makes my GraalVM Java JDK as the default installation. I do the following:
<code>    - name: Make GraalVM Java as the selected version
      community.general.alternatives:
          name: java
          path: '{{ graalvm_home }}/bin/java'
</code>
Unfortunately I get the following permission error. In the community.general.alternatives I did not see any option on running the command as sudo (the device I am doing my operations is running on Linux 18). How can I remove this permission error ?
<code>     Make GraalVM Java as the selected version] ***
    fatal: [default]: FAILED! => {"changed": false, "cmd": "/usr/bin/update-alternatives --install /usr/bin/java java /opt/graalvm/graalvm-22.1.0-java17/bin/java 50", "msg": "update-alternatives:
error: unable to create file '/var/lib/dpkg/alternatives/java.dpkg-tmp': Permission denied", "rc": 2, "stderr": "update-alternatives:
error: unable to create file '/var/lib/dpkg/alternatives/java.dpkg-tmp': Permission denied\n", "stderr_lines": ["update-alternatives:
error: unable to create file '/var/lib/dpkg/alternatives/java.dpkg-tmp': Permission denied"], "stdout": "", "stdout_lines": []}
</code>
Answer: Apparently the "sudo" of Ansible is "become : true". So the following should work:
<code>  - name: Make GraalVM Java as the selected version
    become: yes
    community.general.alternatives:
      name: java
      path: '{{ graalvm_home }}/bin/java'
</code>


Contour Integral About A Circle

Question: I have $\int_\delta \frac{z}{z^3 -1} dz$, where $\delta(t) = (\frac{1}{2})e^{it
}$ with $t \in [0, 2\pi]$.  It's clear that the winding number is $Ind_\delta(z_0) = 1$, where $z_0 = 0$. I'm just unsure of how to rewrite the integral so that I can use Cauchy's integral formula.
Comment: Try Cauchy's integral theorem.
Comment: Alternatively, $f(z) = \frac{z^2}{z^3-1}$.
Comment: Is f(z) = z/(z^3 -1) analytic?  And I'm a little unsure of what you're getting at with the alternative.
Comment: $\frac{z}{z^3-1}$ is analytic except at - where?
Comment: At 1, but it's not continuous there.  Isn't that a requirement for Cauchy's theorem?  That any points where the function is not analytic, the function be at least continuous?
Answer: By Cauchy's Integral theorem:
$$\int\limits_\delta\frac z{z^3-1}dz=0\;\;\text{since}\;\;\frac z{z^3-1}\;\;\text{analytic on}\;\delta\;\;\text{and within it}$$

Contour Integral About A Circle