Do chord progressions usually move by fifths?

Question: I'm wondering if chords usually move down by fifths. It seems so by the diagram, so iii to vi, vi to ii, ii to V, V to I. etc. Other chords can also be thought of like that, because IV/ii and V/vii are often interchangeable. So IV -> V can be thought of as ii -> V.

Is that the most typical movement of a chord progression?
See 4:55 in the video below. This is one of many teachers explaining this flow. I've seen this flow myself in plenty of songs I've played.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/92755/discussion-on-question-by-foreyez-do-chord-progressions-usually-move-by-fifths).
Comment: Please use the chat above if you want to discuss the premise of the question. Any future comments that don't apply to the [when should I comment guideline](https://music.stackexchange.com/help/privileges/comment) will be deleted.
Answer:
I'm wondering if chords usually move down by fifths.

A ponderous question. It is simple in presentation but difficult to answer depending on the OP's background. In order to properly answer this question it needs to be properly unpacked:

First, I take it that the OP intends to ask if chord roots usually move by fifths. Supposing this is true, we need to understand that while seemingly broad, the answer is actually quite specific:
Composers only began thinking about music in terms of constructing vertical harmonies around the time of Renaissance / Early Baroque. Harmonius vertical relationships were a reactionary bi-product of horizontal thinking. Composers then developed these relationships over several hundred years until the introduction of pan-tonal (i.e. non-functional) harmonic languages in the early 20th century. Yes, there are many, many examples of earlier composers using non-functional harmony, but that fall outside the realm of this answer.
The vast majority of music written after early 20th century branches out in myriad directions. While hard data is nearly impossible to quantify, the extreme prevalence of pantonality during the mid-20th century, the emergence of minimalism, and technology's role in giving voices to non-traditionally educated musicians means that if incorporating progressions at all, it is less likely those progressions will be functional, let alone functional in the way the OP describes.
Further, it is important to acknowledge that the OP must only be referring to music written in the Western European Classical tradition. Many, many, many other types of music around the world do not incorporate functional harmony as we describe it, among many other things.

So now that we've unpacked the context let's look at the actual question:

I'm wondering if chord [progressions written in the Western European Classical musical tradition between the years 1600–1930] usually [contain root movement] of mov[ing] down by fifths.

And here's the answer: it depends
You see, progressions stem from cadences. Cadences have different types of strength. Not all are the same, and different cadences are used for different reasons. This is the result of building and releasing tension. In the Western European Classical musical tradition, an Authentic Cadence is the strongest (with a PAC being the strongest of the two). The interval from tonic to dominant is the fifth.
If we cycle backwards, we run into what's known as the pre-dominant. The root note for the IV chord is known as the "sub-dominant" as it is a fifth below the tonic.
Thus if we look at the following progression:
I–IV–V–I
We see that while the roots of both intermediary chords are in fact, a perfect-fifth away from tonic, the root movement between them is actually only a major-second. In other words, it does not move "down by fifths".
Why are these chords so popular?
As the OP stated, the perfect-fifth is the most harmonically-pure interval after the octave and perfect unison. The above chords are therefore, with respect to their interval, the best suited to give the strongest progression.
Now, what about the ii6/5?
This chord is wonderful as gives the impression of IV-V, while giving descending root-movement of perfect-fifths. While this progression is very popular (especially during the Baroque period, in which the clearest examples of root movement by descending fifths may be found), it does not and cannot constitute the majority of written music.
Alright smart guy, so what about the other chords?
Oh, substitutions?
Sure, ii may be substituted for IV, as I described above. Other chord substitutions are weaker: iii for I or V, for example, vi for I or IV. Substituting vii for V gives you a leading-tone chord, which has root movement by minor-second and doesn't fit the "descending by fifth" theory. Let's put some of these substitutions in context:
iii–V–I
(root movement by 3rd then 5th)
vi–V–I
(2nd then 5th)
vii–V–I
(2nd then 5th)
As you can see, substitutions do not intrinsically beget root movement that fits your model.
But all of this is merely looking at how root-movement by fifth is possibly used, not whether or not composers employ them more than any other progression. The fact of the matter is that unless an individual has compiled data for the entirety of written music, it is impossible to answer with 100% accuracy. That said, we need to think about what is the "most likely".
The fact is composers use a variety of chord progression (and regressions) to suit their needs. Theory is developed to try and explain how it is that they make the music that they make. Theory comes after music, not before, and it is just that, a theory. Simply wanting something to be true doesn't in fact make it so.
So root movement by fifths? During one period of human history in the context of one musical tradition, it was a widely-used musical device.
Comment: @foreyez - are you here to learn or are you here to entrench your own view? One of those ways is productive, the other is not. The very nature of your question ignores a staggering amount of world music. I never said it wasn't evident in other times or genres. You asked when it *usually* happened, and I answered. It happened the most transparently during Common Practice. If you are not satisfied you are asking the wrong question.
Comment: It can't just be limited to Common Practice Period. Jazz, pop, rock, edm, rap they all do it. Just look at the top hits today.
Comment: The question wasn't about "widely used" but "usually move." The difference in the wording is critical.
Answer: There are two melodic clauses  - probably the most usual:

soso lati dododo (and its minor relative: mi fi si la
sofa mire do ... ( miredoti la)

Both are leading a fourth up or fifth down.
also the usual bass-line that goes do re mi do, fa so la fa or so  la ti so, do re mi do etc.
They are developed by counterpoint as well they are basic for harmonic progressions! (Since Baroque - if not even Gregorian chant - till many popsongs and walking bass in jazz.
Btw.: this question is related to another that has been asked recently about the circle of fifths which is actually a circle of fourths.
Another reason is: that dominant and secondary dominant chords have two tones in common.
The other most usual progression is IV-V. We wonder that here are no common tones. A possible answer/explanation could be: The progression IV-V is actually a whole  turn round skipping the whole circle. (That's what I read in my first theory book that I held in my hand with 17 years.)
Answer:
Do chord progressions usually move by fifths?

No.
I think you are overlooking an important part of that flow chart: the curved arrow to the right of I means "the tonic chord can move to any other chord."
So, that results in a super common progression I ii6.
The rest of the flow chart does display descending fifth progressions with some options variations like IV ii and vii0 V.
Of course IV V is absolutely essential to functional harmony and that is root progression by step.
Step-wise movement of 1st inversion chords is completely missing from the flow chart.
Keep in mind that a lot of harmony by descending/ascending fifth will occur as sequential harmony. In terms of phrasing and structure in common practice those sequential passages don't just happen anywhere. There are structural conventions to consider.
Anyway, IV V, I ii6, and V vi are so super common that we really can't say progression by fifths is the usual movement.
The flow chart isn't "wrong" but it leaves out a lot of important information about formal structure and harmonic conventions in common practice music.
Comment: Be careful to not use "usual" as a weasel word to justify an overly simplistic view. Commonest root progressions will be descending 5ths, 4ths, and 3rds, and ascending step... all of them very common, very usual.
Comment: That flow chart is found in many forms, but the original source is Kostka, Payne, Tonal Harmony. So it gets _re-presented_ on the web, minus the 400 pages of text of the original book. That leave many unsuspecting webizens thinking they've found the holy grail of harmony in a single chart. I wish the rule of the octave was to top Google result instead!
Comment: Also note that I said "usually" which means most of the time. If it's not most of the time then what interval is? Hasn't there harmonic/frequency analysis done on this?
Comment: I'm quite concerned that people may believe in anything they find on the 'net. Find something, post it, and suddenly it's credible. It worries me that peple could be that fickle. I can't say more. Someone might believe me...
Comment: IV -> V can also be seen as ii -> V since ii and IV can be switched. You're right that from the tonic it can go to any chord, but then it tends to move back to the tonic in fifths.
Comment: You probably should make that `ii6` interchangeable with `IV` - then we really get the notion the treble voice is optionally `^1` or `^2` and not nearly as harmonically essential as the bass.
Answer: "Usually" is arguable. Not every chord progression is downwards by fifths only, but there is something to be said for that sound of a descending fifth.
Lots of common chord movements do follow this pattern. The ii-V-I, ubiquitous in jazz music, is two consecutive root movements down by a fifth. In general, resolutions downward by a fifth seem more final than others, but of course there are no hard rules for this kind of thing.
I've seen this exact kind of chart in some of my education (ta-da!)

, so you're not alone. The image marks the work of www.scaletrainer.com, but I came into possession of it from an instructor. I've even seen the same diagram on musictheory.net (scroll down). But I quickly realised the limitations of the chart, and I get the feeling you already have as well.
Why does the dominant lead to the tonic? has some explanation of the descending 5th root motion while focusing on some other aspects of harmonic resolution. That root motion of the dominant scale degree to the tonic seems to be implying a whole chord progression itself even when played alone!
Answer: The vast majority of chord progressions in the classical theory move, four forward, one forward or three steps back. That is the easiest and best way to move between chords.
Comment: "four forward, one forward or three steps back" didn't quite get that. example?
Answer: No.  It's not ALL about 'the circle of 5ths'.  You really need to let this one go!
The teacher in that video is stating 'rules' that just don't exist.  (I think she's obsessed with the 'circle' too :-) )
Yes, dominants resolving to tonics, and the secondary extension - dominants of dominants of dominants moving to tonics)  are very frequently found in tonal music.  But so are other things.
Comment: @foreyez you'll probably never be happy with any answers if you are trying to quantify it like "what happens over 51% of the time". Based on your style and your goal what is expected and what happens is vastly different and trying to pigeonhole all chord progressions into this general sense is not very useful.
Comment: @foreyez ...except when it isn't by desc 5ths, like the tritone sub, modal jazz, Giant Steps, etc. roots by fifth is a harmonic essential, but don't overlook the _other_ harmony essentials!
Comment: haha, you caught it :). but I really think it is though. to give you an example, yesterday I played something that I've been playing since I was about 8 years old on the piano, I never knew what it was. it was just some jingle I always had in my head. Turns out, it was the circle of fifths progression. not just that, but today I stumbled upon the lead sheet for 'all the things you are' which is a jazz standard that is also based on the circle. then I found out that 'autumn leaves' also based on the circle. and pretty much every pop song I find forms arcs on the circle.
Comment: And dare I say it - the theme tune for 'Coronation Street' (a U.K. soap, so it's heard several times a night) contains that same sequence...
Comment: @MichaelCurtis not overlooking but I just asked what happens over 51% of the time. according to that diagram and the many songs I played it looks like fifths.
Comment: also she's not the only one talking about this. I've seen many teachers talk about this progression flow. that chord flow diagram for example is shown across many, many websites.
Comment: She's giving the impression that the 'circle of 5ths' method of deciding what chord comes next is the 'correct' way.   It's ONE way, in SOME circumstances.  Ever in quite simple music.
Comment: @LaurencePayne no-one said it's the only way it signifies what people are expecting to hear, what typically happens in popular music. if one does different then it's actual a good thing. my favorite artist elliott smith moves his progressions in thirds alot, that's his signature sound. besides, she's not the only one that admires the circle. dude right here tattood the damn thing to his arm at 0:40. https://youtu.be/50CpDZvTWks?t=40


InlineShape not added to Range after calling AddPicture in Microsoft Word

Question: I'm creating a Microsoft Word 365 Add-in where I need to be able to add and remove inline shapes. I currently have the following test code:
bookmark.Range.InlineShapes.AddPicture("c:\\temp\\test.png");

And although the InlineShape gets added to the page, and seemingly on the correct position, i.e. within the provided bookmark, the bookmark.Range.InlineShapes collection stays empty:
Assert.IsTrue(bookmark.Range.InlineShapes.Count > 0); // This fails

As far as I can see, the shape is actually not added to the range, but directly after it.
This behavior is odd and causes problems in my situation, where I need to be able to iterate the inline shapes of the bookmark later on, especially to be able to remove (toggle) the image again. But without the inline shape as part of the bookmark
What am I doing wrong and how can I fix this, in such way that the inline shape is becoming part of the bookmark again?
Answer: That's because your code doesn't insert the shape within the bookmark. This is a quite common misunderstanding. You need to first point a Range object to the bookmark range. Then, add the InlineShape to your Range object's range, then extend the range by one character. Finally, re-apply the bookmark to the Range object's range.
Following is a VBA example:
Sub Demo()
Dim wdRng As Word.Range, BkMkNm As String
BkMkNm = "MyBookmark"
With ActiveDocument
  'Confirm that the bookmark exists
  If .Bookmarks.Exists(BkMkNm) Then
    Set wdRng = .Bookmarks(BkMkNm).Range
    'Delete existing contents
    wdRng.Text = vbNullString
    'Insert Pic
    .Range.InlineShapes.AddPicture FileName:="PictureFullName", Range:=wdRng
    'Extend Range
    wdRng.End = wdRng.End + 1
    'Re-apply bookmark
    .Bookmarks.Add BkMkNm, wdRng
  End If
End With
End Sub

Comment: Hi Macropod, thank you for your answer. Can you show a code example that demonstrates this?
Comment: I don't code in c#. I could post a VBA solution, though.
Comment: VBA is absolutely fine by me. Thanks in advance.
Comment: Sample VBA code added to answer.


Changing commit message in GitHub pull request

Question: I have pushed some code for review and have been asked to change couple of my commit messages.
I tried doing git rebase -i HEAD~5 since it isn't my latest commit which needs to be changed.
Upon making changes, I now see that my branch has been diverged.
What would have been the correct approach here?
I am not that confident, so would probably end up creating a new pull request all together. But, I would have liked to change in same pull request so that review comment history would have been retained.
Comment: Well, there is no way to rewrite a commit message without making a new commit, and that is what you did. There is absolutely no way to rewrite the message of "the same" commit. So, yes, these are new commits and are not what was pushed previously. As you have already proposed, you could withdraw the pull request, construct a new version of the branch, and push it to make a new pull request.
Comment: What's wrong with what you did? Interactive rebase permits you to rewrite the commit messages for any of the commits within the purview of the rebase. You presumably did that. What's the problem?
Comment: I see that it rewrote but GitHUb statuscheck has a check to validate if Jira ticket was provided. It still fails as previous history shows commit messages without Jira ticket number
Answer: You don't need to create a new pull request.  You can simply make the changes to your commit messages (or any other changes you'd like to make to your commits) and force-push them to the same branch on the remote.  The pull request will be updated with the new commit contents.  You can do that either by specifying the -f option when you run git push or putting a plus sign (+) in front of the branch name when pushing.
Usually your CI system will realize that your commits have changed and run again on the new commits.  So if your old commits didn't meet the standard for whatever reason, that shouldn't be a factor in whether your new commits pass.
The benefit to updating the pull request is that it retains any description you've provided and any comments folks have provided on previous versions.
Comment: Is there a way to figure out if GItHub pull request has commit message changed?
Comment: One can look at the individual commits, but there isn't a notification in the interface when that happens, other than that a force-push occurred.
Answer: Here is what worked for me.

Through terminal, cd to repo directory
Checkout to [FEATURE_BRANCH] that contains the commit message to be updated
Run git commit —amend
VIM editor will open, look for commit message and update, save and exit
Run git push —force-with-lease origin [FEATURE_BRANCH]
Commit message should be updated with new SHA hash.

Note
As per the git docs,

In Git, the text of the commit message is part of the commit. Changing
the commit message will change the commit ID--i.e., the SHA1 checksum
that names the commit. Effectively, you are creating a new commit that
replaces the old one.

Reference
https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/changing-a-commit-message


Gradle build fails with MalformedJsonException

Question: After the migration from jcenter to maven-central repository, like
//from
repositories {
  jcenter()
}
//to
repositories {
  mavenCentral()
}

I got:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':my-module:compileJava'.
...
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':my-module:compileClasspath'.
...
project :my-module > org.junit.jupiter:junit-jupiter-api:5.7.1 > org.junit:junit-bom:5.7.1
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve org.junit.jupiter:junit-jupiter-params:5.7.1.
Caused by: org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.MetaDataParseException: Could not parse module metadata https://everon.jfrog.io/everon/libs-release/org/junit/jupiter/junit-jupiter-params/5.7.1/junit-jupiter-params-5.7.1.module

How to fix it?
Answer: After the change, Gradle misused the metadata file and the solution would be to explicitly declare artifacts metadata sources:
repositories {
  maven {
    metadataSources {
      mavenPom() //use maven pom
      artifact() //look directly for the artifact
      ignoreGradleMetadataRedirection() //it fixes the issue actually
    }
  }
}

See https://docs.gradle.org/current/userguide/dependency_management.html#sec:supported_metadata_sources for more
Comment: You are a hero to the people for this answer. Thank you!


Three.js materialLoader doesn't load embedded texture image

Question: I'm exporting a three.js material using material.toJSON() provided method, this is the result:
{
"metadata":{"version":4.5,"type":"Material","generator":"Material.toJSON"},
"uuid":"8E6F9A32-1952-4E12-A099-632637DBD732",
"type":"MeshStandardMaterial",
"color":11141120,
"roughness":1,
"metalness":0.5,
"emissive":0,
"map":"876D3309-43AD-4EEE-946F-A8AE8BA53C9E",
"transparent":true,"depthFunc":3,"depthTest":true,"depthWrite":true,

"textures":[
    {
        "uuid":"876D3309-43AD-4EEE-946F-A8AE8BA53C9E",
        "name":"",
        "mapping":300,
        "repeat":[1,1],
        "offset":[0,0],
        "center":[0,0],
        "rotation":0,
        "wrap":[1001,1001],
        "minFilter":1008,
        "magFilter":1006,
        "anisotropy":1,
        "flipY":true,
        "image":"C6B4FEDA-8E7E-490A-A1AD-866ECE36E952"}],

"images":[
{
    "uuid":"C6B4FEDA-8E7E-490A-A1AD-866ECE36E952",
    "url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAEACAYAAADFkM5nAAAg[...]"
}]}

I try to use MaterialLoader as the example suggest
https://threejs.org/docs/#api/loaders/MaterialLoader
but at parsing time I always get this error

THREE.MaterialLoader: Undefined texture
  876D3309-43AD-4EEE-946F-A8AE8BA53C9E

I'm I wrong if I expect from the MaterialLoader to use the embedded resources?
I'm doing it wrong or missing something?
How can I also load the images in the json file into the related texture?
Thanks!
here a fiddle:
http://jsfiddle.net/akmcv7Lh/211/
Answer: Notice that MaterialLoader is not able to load textures. It expects that textures are set via MaterialLoader.setTextures() before loading a JSON file like ObjectLoader does:
const loader = new MaterialLoader();
loader.setTextures( textures );

So MaterialLoader can only be used as a standalone loader if the respective materials have no textures. Otherwise you have to prepare the textures on app level similar how ObjectLoader does.


Where are syscalls located in glibc source

Question: So I was looking through the linux glibc source and I don't see where it actually does anything.  The following is from io/chdir.c but it is indicative of many of the source files.  What's going on here?  Obviously I am missing something.  What's the secret, where does it make a system call or actually do something?
stub_warning is some legacy craziness.  __set_errno seems to be a simple macro that sets errno.  And while I find a million usages of weak_alias I don't see it defined anywhere.
Is there a helpful guide to understanding how glibc works somewhere?
#include <errno.h>
#include <stddef.h>
#include <unistd.h>

/* Change the current directory to PATH.  */
int
__chdir (path)
     const char *path;
{
  if (path == NULL)
    {
      __set_errno (EINVAL);
      return -1;
    }

  __set_errno (ENOSYS);
  return -1;
}
stub_warning (chdir)

weak_alias (__chdir, chdir)
#include <stub-tag.h>

Comment: Ouch.  Many more layers to this onion than I anticipated.  Thanks to everyone.  Stay tuned.  More hilarity may ensue in coming weeks.
Answer: What you've found is a stub function for systems it's not implemented on. You need to look under the sysdeps tree for the actual implementation. The following may be of interest:

sysdeps/unix/sysv/linux
sysdeps/posix
sysdeps/i386 (or x86_64 or whatever your cpu arch is)
Comment: Thanks for accepting my answer, but please be sure to look at the others too, especially if you're interested in how glibc builds syscall wrappers. My answer was less targetted at your specific question (about `chdir`) but may be more useful if you want to know where/how more complex (not just a syscall wrapper) system-specific functions are implemented.
Answer: The actual system call code for chdir() is auto-generated on most systems supported by glibc, by the script make-syscalls.sh.  That's why you can't find it in the source tree.
Answer: That's a generic stub that is used if another definition doesn't exist; weak_alias is a cpp macro which tells the linker that __chdir should be used when chdir is requested, but only if no other definition is found.  (See weak symbols for more details.)
chdir is actually a system call; there will be per-OS system call bindings in the gibc source tree, which will override the stub definition with a real one that calls into the kernel.  This allows glibc to present a stable interface across systems which may not have all of the system calls that glibc knows about.
Answer: Note that the actual system calls aren't defined anywhere in the source tree - they're generated at build time from syscalls.list (linked is the one in sysdeps/unix, there are additional ones further down), a series of macros in sysdep.h (linked linux/i386), and a script that actually generates the source files.
Comment: without sources, on a live system,  how can I see the os api called ? is it possible to strace an application , but only the code executed into glibc ?


Showing a sequence is convergent using the $\epsilon$-$N$ definition

Question: I need to prove that the following sequence converges:
$\lim_{n\rightarrow \infty} \frac{2n^2+3n+1}{n^2+n+1}=2$
So for the proof/solution I have the following:
Let $\epsilon >0$. Then let $N=\frac{1}{\epsilon}$.  Then for all $n\geq N$,
$|\frac{2n^2+3n+1}{n^2+n+1}-2| = |\frac{n-1}{n^2+n+1}| < \frac{1}{n} < \frac{1}{N} = \epsilon$
Thus the sequence converges to 2.
Is this the correct way of going about this?  Thanks in advance.
Comment: It depends on the class and what's expected of you (even down to your professor and their style really). I've had one real analysis class where that wouldn't be a problem, and another with a professor that required us to prove "every detail" of what we were doing (so making a statement f(n) < g(n) required a side proof using the axioms from the start of the course). In most cases though I'd say it should be fine (with the symbolic adjustment as noted made).
Answer: The calculations are right, but some wording changes would be useful. We are given an $\epsilon \gt 0$.
We have, for $n \ge 1$, the inequality
$$\left|\frac{2n^2+3n+1}{n^2+n+1}-2\right| \lt \frac{1}{n}.$$
Thus if we put $N=\lceil \frac{1}{\epsilon}\rceil$, then
$$\left|\frac{2n^2+3n+1}{n^2+n+1}-2\right|\lt \epsilon$$
for every $n\gt N$.
Answer: There is a small error with symbols, it should be like this:
Choose $\epsilon\gt 0$
Let $N=\lceil\frac{1}{\epsilon}\rceil$.  Then for all $n\gt N$,
$|\frac{2n^2+3n+1}{n^2+n+1}-2| = |\frac{n-1}{n^2+n+1}| < \frac{1}{n} < \frac{1}{N} = \epsilon$
Comment: Then, you are all right :)


Cisco 1841 with Muliple WAN - load balancing & failover

Question: I have a Cisco 1841 router with 4 interfaces: FE 0/0 , FE0/1, AUX, CONSOLE. I have DSL line (WAN - PPP0E) which goes to FE0/1 & FE 0/0 goes to my LAN Switch.
Now we want to get another DSL line for the purpose of Load balncing/bonding/failover. I have some questions:

Is it feasible to use two WAN interfaces for this purpose? I meant people are using this kind of scenario. Any opinions...
Hardware: Do i need to buy Cisco WAN interface expansion card module or
I just can buy Cisco etherswitch 4 port module (which can connect to my LAN switch)

I really appreciate any feedback for experts..
Thanks,
Hemal
Answer: Is your LAN switch managed? In other words, is it VLAN capable?
If it's VLAN capable, you could have one VLAN on the switch for each DSL connection, and  trunk them both back into Fa0/1, then split them back out on the router's subinterfaces.
You could buy either a PPPoA/PPPoE modem and an ethernet HWIC, or an ADSL HWIC, but be aware they're bloody expensive.
The cisco etherswitch modules are similarly pricy.  I'd probably be tempted to get a second hand Cisco Catalyst 2950 off ebay, and use that for the Vlan solution.
Comment: Thank you for your reply Tom. My existing LAN switch doesn't support VLAN. So if I understand your solution, I just need to get Catalyst 2950 switch. Can you please tell me how the physical cabling will look like means where the router ports(FE 0/0 & 0/1), LAN switch will be connected.. Thank you in advance for reply..
Answer: An alternative if you're not dead set on Cisco you could get a small branch series Juniper SRX220 or 240 with two ADSL2 adapters in it. Set equal cost routing to each interface and it would load balance or set a secondary default route preference to the other interface. I like things integrated. This would also give you a ton more ethernet interfaces and they're not too pricy.
If you stick with the Cisco, you're short on Ethernet interfaces to be able to connect to the device upstream to two DSL modem. I'd get the ADSL WIC myself.


Consider the operator $T:l^2\to L^2(\mathbb{R})$ defined by:

Question: $$T(\{a_k\})=\sum_1^\infty 2a_k\mathbb{1}_{\big[\frac{k}{4},\frac{k+1}{4}\big)}(x)$$
Show that $T$ is a linear isometry. It is a linear ishomorphism?
Don't know how to start.
Comment: How to start is always with definitions. Write out the definition of an isometry. Write out the definition of an isomorphism. Think for a while and if you're still stuck, come back. Good luck
Comment: So it's a function of the sequence $\{a_k\}$?
Comment: Yes, I assume, but can't understand very well because it's from $l^2$ to $L^2(\mathbb{R}).$
Answer: $$\|T(\left\{a_k\right\})\|_{L^2}^2= \sum_{k=1}^{\infty}\int_{k/4}^{(k+1)/4}4a_k^2 dx= \sum_{k=1}^{\infty}\frac{1}{4}\cdot 4a_k^2=\|\left\{a_k\right\}\|_{\ell^2}^2$$
So it is an isometry. It is non surjective, because $T(\left\{a_k\right\})$ is always a function which is constant on intervals of the form $\left[\frac{k}{4},\frac{k+1}{4}\right]$, and thus a function like $f(x)=e^{-x^2}\in L^2(\mathbb{R})$ cannot be image of any $\left\{a_k\right\}$. Even more simply, if $\ell^2=\ell^2(\mathbb{N})$, we have $T(\left\{a_k\right\})(x)=0$ for all $x<0$, therefore any $L^2$ function which is non-zero on a positive measure subset of $(-\infty,0]$ cannot be in the range of $T$.
Therefore, it is not an isomorphism.
Comment: A linear operator $T$ is an isometry iff $\|Tu\|=\|u\|$ for all $u$. Do you know a different definition?
Comment: You're welcome. Also remember that for an isometry $T$ the following are equivalent: $(1)$ $T$ is an isomorphism; $(2)$ $T$ is surjective; $(3)$ the range of $T$ is dense.
Comment: In this case isometry implies that the norms are equals, right? So you calculated $||T(\{a_k\})||_{L^2}^2$ and it's equal to $||\{a_k\}||_{L^2}^2$ $\forall k$, so it's an isometry, right?
Comment: No, but I'm new in functional analysis and I still can't remember all stuff together. Thanks, it was a very easy solution applying only the definition.


How to create checkbox instead of radio for just 1 allowed value?

Question: Because of this major Drupal 7 bug (http://drupal.org/node/811542), I cannot use radio options in my form.
I have three options in my form and I want them to be checkboxes, but the user can only select one checkbox.  By Drupal 7's auto form design, it converts single value items to become radios.  How can I get the below to become checkboxes that users can only select one without having to write my own module to override the form?
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian
Comment: The core issue has been fixed.
Answer: Since checkboxes are multi-value options by nature. It would be detrimental to usability to override this default and expected behavior. You could change the validation as jimajamma suggests, but this would definitely lead to mass confusion amongst your users, as checkboxes are specifically intended for use for multi-value selections.
A slightly better, but still sub-optimal, option would be to use javascript to make sure that only one checkbox option is selected. Using javascript would at least mean that  users have immediate feedback rather than finding out after submitting the form (and it failing validation) that the completely expected behavior of multiple values for checkbox form items is no acceptable in this situation.
Since the Drupal core issue that you linked to specifically refers to sets of radio options that are not set as required, why not re-phrase the radio options so that you can make the form item be required?
For example, instead of the three options
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

create a forth option,
none|No preference
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

and set that fourth option as the default. In this way, you can successfully work-around the existing Drupal bug without confusing your users with non-standard behavior of form items and without creating any additional work for them. Not only is this better for users, but it requires no code customizations and is more easily maintainable (and easier to change once the bug is fixed).
In a situation with a yes/no question, you could use checkboxes and only provide one option, "Yes." Then you could evaluate "Yes" in its unchecked state the same way you would have evaluated "No" in its checked state.
Comment: Let me make sure I understand the situation correctly. You want to have a required field that allows only one value, but does not return the confusing error message "An illegal choice has been detected. Please contact the site administrator." And you are concerned that my Answer will somehow create duplicate "None" options. Is that correct? Also, I have thus far assumed that the form you are building is a content type via the Drupal UI, but please let us know how you are actually building this form (Webform module? FAPI in a custom module?).
Comment: I see.  So you are suggesting that I reframe the question to a simple yes/no to utilize a single checkbox.  I suppose this would do the trick.
Comment: I chose the simple yes/no as an easy example, and I should not have done that (my bad).  I updated my original question to have 3 choices.  Is there any other way I can get the same effect as radios?  I realize I could use a select list, but I have other questions that are longer sentences that end up taking a lot of room in terms of width.  Select options don't seem to wrap.
Comment: I edited my answer to include a similar language-based, rather than programming-based, solution for situations other than yes/no options.
Comment: Sorry to add complexity to this, but what if "none|No preference" was not an option?  You either eat chicken, beef, or are a vegetarian (I know this example is getting lame, but just go with it, please).  The only simple way to remove the default "N/A" from not required radios choices would be to make it required, correct?  This would put me back into the Drupal bug problem.  Or is there a way to easily remove "N/A"?  Anyhow, I think the best option is if Drupal fixes this bug (since 2010!) or I override the form with my own custom module.  I appreciate your response and help.
Comment: I would like to have only one value be chosen and be a required response without throwing the error message, "An illegal choice has been detected. Please contact the site administrator."  The "problem" (and I mean that loosely!) with your response is that "none" cannot be an option.  If I do not tick the box that says "Mark this field as required", then Drupal automatically adds an "N/A" radio choice.  Apparently the Drupal team thinks this is best for us!  I built the form using Drupal 7, CCK, and the Conditional Fields module.  This is completely through the UI - no custom programming.
Comment: My suggestion was to make the the form field required and create a "none" option (like you would all the other options) that is selected by default
Comment: As I stated earlier, I cannot have a "none" option (or an "N/A" option) for this particular question.  I think I might have to bite the bullet and temporarily write my own module to hide the "N/A" option for a required radio field to get around this Drupal bug.  If you have any other suggestions or ideas, then please share!  Thanks!
Answer: Simply create three fields. One for each of your beef, checken and veggie with type: Boolean widget: Single on/off checkbox
The use the Conditional Fields module to create a relationship between the three, so that when one is checked off the other two disappear.
Answer: You could also allow for multiple values to force the checkboxes and then create a custom validation function that makes sure only one is actually checked.
Comment: But this validation would require me to write a custom module, correct?
Comment: it would require custom php code yes


Erro de sintaxe em "else if"

Question: Com essa função o meu programa funciona, mas quando adiciono outra condição da erro:
if ((nota >= 6) && (frequencia >= 75)){
   alert("Aprovado");
}
else if (frequencia >= 50){
   alert("Recuperação");
}
else{
   alert("Reprovado");
}

Quero adicionar mais uma condição ai essa da erro:
    if ((nota >= 6) && (frequencia >= 75)) {
        alert("Aprovado");
    }
    else if (frequencia >= 50) {
        alert("Recuperação");
    }
    else {
        alert("Reprovado");
    }

    //essa
    else if (nota >= 4) {
        alert("Aluno de Recuperação");

    } else {
        alert("Aluno Reprovado");
    }
}

Comment: Sugiro que leia isso: [ask]
Comment: Colocando de forma simples: O `else {` é o último. Você não pode ter outro `else if` depois de um `else {`.
Comment: O `else` deve ser o último recurso quando todos os `else if` falharam, então ele deve ficar por último e só pode ter um.
Comment: Esse u´tlimo bloco de comparação que vc aponta dar erro, tem a ver com o primeiro ou são coisas separadas?
Answer: O else if não pode ir depois do else {. O else deve ser a última condição, ela diz algo como, todas as outras são falsas, então deve executá-la. O correto seria entender a lógica primeiro.
Presumo que nota e frequência sejam importantes, mas só um alert poderá ser exibido por vez, tem bastante coisa estranha nas suas condições, mas creio que se frequência abaixo de 50 e nota abaixo 4 reprovam, então ambas podem dividir o mesmo else
Acaso o aluno precise ter frequência 50 ou nota 4 (não sendo necessárias ambas ao mesmo tempo), o correto então deve ser:
if (nota >= 6 && frequencia >= 75) {
    alert("Aprovado");
}
else if (frequencia >= 50) {
    alert("Recuperação");
}
else if (nota >= 4) {
    alert("Aluno de Recuperação");
} else {
    alert("Aluno Reprovado");
}

Mas acaso ambas sejam necessárias, no mínimo o aluno tenha frequência igual á ou maior que 50 e nota igual ou maior que 4, isto ao mesmo tempo, para estar de recuperação:
if (nota >= 6 && frequencia >= 75) {
    alert("Aprovado");
}
else if (frequencia >= 50 && nota >= 4) {
    alert("Aluno de Recuperação");
} else {
    alert("Aluno Reprovado");
}

Comment: O curioso é que se a frequencia for maior ou igual a 50 e a nota for 10, o aluno fica de recuperação... meio esquisita essa conta rs.. ou melhor, de a frequencia for 100 e a nota for 10, tb fica de recupa..
Comment: @GuilhermeNascimento Sim, era praticamente o mesmo que você respondeu. Deletei aquela resposta.
Comment: @dvd o autor não especificou a lógica necessária, e supondo que o sistema de ensino de escolas municipais, estaduais e particulares tem métodologias diferentes não cabe a mim questionar, podemos supor que aluno é nota 10, mas frequência reflete na qualificação dele (algo comum para determinar em universidades americanas, a presença é um fator de avaliação também).
Comment: Sim, a lógica dele que tá estranha.
Comment: @VictorStafusa obrigado pela edição o/
Comment: cara, eu tenho esse condigo em pascal apredendo agora coloque em javaScript pode dar uma olhada ele em pascall,,
Comment: Procedure ResultFin( NOTA, FREQUENCIA : real);
begin
readln(NOTA, FREQUENCIA);
if (NOTA >= 60) then begin
if (FREQUENCIA >= 75) then begin
writeln('APROVADO');
readln;
end
else if (FREQUENCIA > =50) then begin
writeln('RECUPERACAO');
readln;
end
else begin
writeln('REPROVADO');
readln;
end;
end
else if (NOTA >=40) then begin
writeln('RECUPERACAO');
readln;
end
else begin
writeln('REPROVADO');
readln;
end;
end.
Comment: @LuccasAndrade Se for ObjectPascal sim, crie uma nova pergunta para isto por favor.
Comment: ficou meio paia ai, to apredendo usar aqui esse forum
Comment: @LuccasAndrade não somos um fórum de debate, somos um site de perguntas e respostas diretas, ou seja sem rodeios e assistencialismo, clique aqui para fazer uma pergunta https://pt.stackoverflow.com/questions/ask sobre o assunto especifico de Pascal
Comment: irei criar agora @GuilhermeNascimento

Erro de sintaxe em "else if"


Use Views field output as a class? Tokens?

Question: I have a field in my view which displays the taxonomy vocabulary that each result/node is linked to. However, I need a way to get that taxonomy vocabulary result and use it as a class for the view row - not just the field.
Has anyone had any success with something like this before? Options I can think of might be Tokens, direct template theming, or Display Suite, but I don't know how I would go about fetching that vocabulary field output and using it as the row's class.
Any help would be received gratefully :)
Answer: If you're looking to use it as a class for the whole row rather than just for the field, use a views template.
The Advanced -> OTHER -> Theme: Information section of your view usually has good ideas on what to call files but it doesn't seem to include anything for the row.
If you're using row style: fields... try making a template file called views-view-fields--myviewname.tpl.php.
To dig into the variables available to that template file, the first thing you want to do is install the Devel module, turn it on, and put this in the template:
dpm($content);

or maybe
dpm($output);

dpm() prints the named variable on the screen when the file is run.
Answer: You can achieve this by passing replacement token to row class as shown in figure below:

Update #1
Install Views PHP & add Global: PHP field in view, then enter following values in PHP field
Value code => return strtolower(str_replace(' ', '-', $row->title));
Output Value => <?php echo $value; ?>
Replace [title] with [php] in Row class. Check image below for reference.
Comment: Hi Vishal; that does work! Only one problem. If the content of a [title] field is 'Hi There', then the row class also becomes 'Hi There', when I need it to be 'hi-there'. For a class I obviously need to make the output lowercase and replace the space with a dash. Any ideas?
Comment: Check Update #1 for your query.


Rendering video on user created wayland surface using gstvideooverlay

Question: I am trying to play a video file over self created wayland surface but rendering is not happening. I took reference from
https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstvideooverlay.html
and
https://git.collabora.com/cgit/user/gkiagia/gst-wayland-gtk-demo.git/tree/main.c
After creation of pipeline (filesrc->parser->decoder->waylandsink); I am setting bus_set_sync_handler as
    gst_bus_set_sync_handler (bus, (GstBusSyncHandler) create_window_own,
        gstreamerData.pipeline, NULL);

Implementation of create_window_own is below
static GstBusSyncReply create_window_own (GstBus * bus, GstMessage * message, GstPipeline * pipeline)

{
if (counter == 0)
{
    display = wl_display_connect(NULL);

    if (display == NULL)
    {
        fprintf(stderr, "Can't connect to display\n");
        exit(1);
    }
    printf("connected to display\n");

    struct wl_registry *registry = wl_display_get_registry(display);
    wl_registry_add_listener(registry, &registry_listener, NULL);

    wl_display_dispatch(display);
    wl_display_roundtrip(display);

    if (compositor == NULL) {
        fprintf(stderr, "Can't find compositor\n");
        exit(1);
    } else {
        fprintf(stderr, "Found compositor\n");
    }

    surface = wl_compositor_create_surface(compositor);
    if (surface == NULL) {
        fprintf(stderr, "Can't create surface\n");
        exit(1);
    } else {
        fprintf(stderr, "Created surface\n");
    }

    shell_surface = wl_shell_get_shell_surface(shell, surface);
    if (shell_surface == NULL) {
        fprintf(stderr, "Can't create shell surface\n");
        exit(1);
    } else {
        fprintf(stderr, "Created shell surface\n");
    }
    wl_shell_surface_set_toplevel(shell_surface);

    wl_shell_surface_add_listener(shell_surface,
            &shell_surface_listener, NULL);

    create_window();
    //paint_pixels();

    wl_surface_attach(surface, buffer, 0, 0);
    //wl_surface_attach(surface, NULL, 0, 0);
    //wl_surface_damage(surface, 0, 0, WIDTH, HEIGHT);
    //wl_surface_commit(surface);
    printf("Before Thread\n");
    pthread_create(&tid, NULL, myThreadFun, (void*)display);
    printf("After Thread\n");

    counter = 1;
}
if (gst_is_wayland_display_handle_need_context_message (message)) {
    if (display != 0) {
        GstContext *context;
        printf("getting context\n");
        context = gst_wayland_display_handle_context_new (display);
        gst_element_set_context(GST_ELEMENT (GST_MESSAGE_SRC (message)), context);

        /* HACK save the pointer to the sink (which implements GstWaylandVideo)
         * from this point. Unfortunately, d->overlay can also be the playbin
         * instead of waylandsink */
        wlvideo = GST_WAYLAND_VIDEO (GST_MESSAGE_SRC (message));
    } else {
        g_warning ("Should have obtained display_handle by now!\n");
    }

    gst_message_unref (message);
    return GST_BUS_DROP;
} else if (gst_is_video_overlay_prepare_window_handle_message (message)) {
    if (surface != 0) {
        /* GST_MESSAGE_SRC (message) will be the overlay object that we have to
         * use. This may be waylandsink, but it may also be playbin. In the latter
         * case, we must make sure to use playbin instead of waylandsink, because
         * playbin resets the window handle and render_rectangle after restarting
         * playback and the actual window size is lost */
        overlay = GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message));
        /*
           g_print ("setting window handle and size (%d x %d)\n",
           d->video_widget_allocation.width, d->video_widget_allocation.height);
         */
        gst_video_overlay_set_window_handle (overlay, (guintptr) surface);
        if (wlvideo && overlay ) {
            gst_wayland_video_begin_geometry_change (wlvideo);
            printf("setting rendrer rectangle\n");
            gst_video_overlay_set_render_rectangle (overlay,
                    0, 0,
                    800, 480);
        } else {
            g_warning ("Should have obtained surface by now!\n");
        }

        gst_message_unref (message);
        return GST_BUS_DROP;
    }
}

printf("+++ret\n");
return GST_BUS_PASS;

}
Comment: your 2nd link is dead
Answer: set after create window
wl_shell_surface_set_fullscreen(shell_surface,
                                WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
                                0, NULL);


NSTextView CoreText note: Client requested name

Question: On a NSTextView when setting the font to .monospacedSystemFont Xcode shows warnings regarding an invalid font. Example:
CoreText note: Client requested name ".SFNSMono-Bold", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:]

Answer: Set the same font for the NSTextView.typingAttributes, example:
let textView = NSTextView()
textView.typingAttributes[.font] = NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
textView.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)


What exactly do --limit 1/s and --limit-burst mean in iptables rules?

Question: I'm using CentOS 5.x  trying to wrap my mind around the following iptables rule on one of my servers:
-A RH-Firewall-1-INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

On another server I have:
-A RH-Firewall-1-INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 3 -j ACCEPT

I understand that both of these rules are designed to allow (and throttle) incoming ping requests but what is the limit-burst option about?  And are these allowances on a per host basis? Or do they apply to any/all incoming ICMP connections at all?
Answer: The math is fully explained in the netfilter docs, but it's reasonable to say that the limit-burst argument specifies the number of matches that are allow through before the limit of 1 per second "kicks in". These two rules both apply only to ICMP echo request packets (incoming PING requests). These are not per-host limits and apply to anything the rule matches (which, in this case, would be all ICMP echo requests).
Comment: It's a token bucket. The bucket starts w/ 3 tokens in it, and a token is removed for each ICMP echo-request that is received. For each  1 second of no ICMP echo requests 1 token is added to the bucket until the bucket reaches 3 tokens again, where it stays until it receives more ICMP echo requests.
Comment: So for the second rule, it will allow up to 3 icmp echo request packets (no matter how quickly they're received) and then only allow 1 icmp packet per second after that (regardless of which host the request is coming from)?  At what point does iptables "reset" and allow a burst of up to three packets again?
Comment: Awesome. That's exactly what I needed to know. Thank you sir.
Answer: --limit: Specifies the rate at what tokens get refilled into the bucket. 4/hour means 4 tokens per hour (1 token every 15 minutes).
--limit-burst: Specifies the maximum amount of tokens that can be filled in the bucket. (This is also the amount of tokens the bucket starts out with).
Answer: I read both answers, but the actual man itables-extensions made me grok it:

limit
This module matches at a limited rate using a token bucket filter.  A rule using this extension will match until this limit is reached.  It can be used in combination with the LOG target to give limited logging, for example.
xt_limit has no negation support - you will have to use -m hashlimit !  --hashlimit rate in this case whilst omitting --hashlimit-mode.

--limit rate[/second|/minute|/hour|/day] -- Maximum average matching rate: specified as a number, with an optional /second, /minute, /hour, or /day suffix; the default is 3/hour.
--limit-burst number -- Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5.


Selecionar todos os Filhos, exceto o Primeiro com o css

Question:

Queria inserir algumas propriedades nas divs de classe "content", porém queria que essas propriedades ignorassem o primeiro filho, como a margem por exemplo. Gostaria que todos tivessem uma distância de 20px uma da outra, mas se aplico diretamente a classe "content", o primeiro filho também espaça 20px do topo do browser e não quero que o fato ocorra. Alguém pode me ajudar?
Comment: Uma sugestão. Se quiser aplicar uma margem entre os elementos e não quer aplicar esta margem ao topo, você pode usar a propriedade do css `margin-bottom`.
Comment: Mas assim o último filho também pegaria o margin-bottom. E, dependendo do caso, às vezes essa margem inferior pode não ser necessária. Mas mesmo assim obrigado pela sugestão!
Comment: Ai quando você precisa definir mais regras o ideal é utilizar os seletores que o @hugocsl mencionou :)
Answer: Existem algumas abordagens diferentes para isso, a que mais tem me agradado é com o :not() para fazer a exclusão do first-child

.content:not(:first-child) {
  color:red;
}

item

item

item

item

item

OBS: Se você não quiser pegar nem o primeiro nem o último filho você pode concatenar mais de um :not() tipo .content:not(:first-child):not(:last-child)
Suporte dos browsers: https://caniuse.com/#feat=css-sel3


Append Text to a dynamically generated Div via jquery not working

Question: I am creating div elements on click of a button. The div which are generated , are draggable and resizable .
On clicking the same dynamically generated div, a text box should appear where-in I put some text and then the same text should be appended inside that div.
But somehow the click event on the div is not registered. Any ideas?
jQuery:
$(".square").click(function () {
    alert("square clicked");
    $(".box").append("

");
    $(".box .comp1").resizable({
        containment: ".box"
    });
    $(".box .comp1").draggable({
        containment: ".box"
    });
});

$(".circle").click(function () {
    $(".box").append("

");
    $(".box .comp2").resizable({
        containment: ".box"
    });
    $(".box .comp2").draggable({
        containment: ".box"
    });
});

//script to append text
$(".comp1").click(function () {
    var obj = $(this);
    alert(1);

    $(".btnSaveTitle").click(function () {
        alert("save title clicked");
        alert($(".componentTitle").val());
        var title1 = $(".componentTitle").val();
        obj.append(title1);
    });
});

HTML:
<button type="button" class="btn btn-success square">Table</button>
<button type="button" class="btn btn-primary circle">Round Table</button>
<button type="button" class="btn btn-primary square">Stage</button>
<button type="button" class="btn btn-info pull-right btnSaveTitle">Save</button>
<input type="text" class="componentTitle pull-right" placeholder="name your component" />

JSFiddle
Answer: You have to use event delegation for newly created elements.
Also, you shouldn't register the click event handler inside another click handler.
// declare obj variable outside of the click handler:
var obj;
// delegate click event:
$(document).on('click', ".comp1", function () {
    // point the obj variable to the clicked element
    obj = $(this);
    alert(1);
});

// move click handler outside:
$(".btnSaveTitle").click(function () {
    // check whether the obj variable isn't undefined:
    if(obj !== undefined){
        alert("save title clicked");
        alert($(".componentTitle").val());
        var title1 = $(".componentTitle").val();
        obj.append(title1);
    }
});

JSFiddle
Comment: The fiddle is not working .. Also the alert `alert("save title clicked");` is not working.. Which means the click event is not triggering
Comment: The click does triggering. I have just commented out the alerts in Fiddle (I don't like alerts, as they take to long time and stop script from running. Use console for debugging instead). http://jsfiddle.net/02esepw9/


Harmonics in composition

Question: As a composer, I never took under consideration the harmonics and natural overtones of note frequencies and never had trouble, as long as it all sounded well and was not very dissonant (unless I intended it to be).
However, I read that composers and orchestrators can notate in a way that intends for harmonics to be heard.
My question is:

Does one learn all notes and what harmonics they produce so that their overtones will not collide and sound dissonant in a composition?
Does one consider overtones in a score when composing, and if so, how or where can one learn this?

Thanks!
Answer:
as a composer i never took under consideration harmonics

You might not have been thinking in terms of harmonics, but if you have ever considered which instrument you wanted to use to play a particular part, you have been (indirectly) considering harmonics. The reason that different instruments sound different is that they have different harmonic structures, which give rise to the different timbres:

you can see the different harmonics as the peaks in the 'spectrum' plot on the right.

I read that composers and orchestrators can notate in a way that intends for harmonics to be heard

It is possible for some instruments to play a note in such a way that a subset of the harmonics in the instrument's normal harmonic structure are sounded, and this can be notated - e.g. for violin, or guitar. Playing a note in this way is often referred to as 'playing a harmonic', but that is a different usage of the word 'harmonic'.

Do you learn all notes and what harmonics they produce so harmonics will not collide and sound dissonant in a composition.

Most people learning music in the conventional way don't have to do that. Instead, they use pre-existing musical scales that have been developed over the years and their associated 'rules' of harmony. In Western music, these scales have been defined to suit the partial structures of most Western instruments, which tend to approximately follow an ideal harmonic series. Cultures that have instruments whose partial structure does not follow the harmonic series (for example the Javanese gamelan) tend to use different scales.
Of course if you are actually making a new scale or tuning for your piece (or refining an existing one), you may well be considering how individual harmonics are interacting with each other, as when thinking in terms of limits.

Do you score in the purpose of heard harmonics and if so how or where to learn this?

The 'purpose' isn't really scored in, but how to play the instrument so that it produces the desired harmonics can be (see violin and guitar examples above).
Most of this answer is talking about conventional western composition. If you are doing computer music, you can potentially have complete control over each and every partial in the piece - but it might not be useful to show that using a conventional score.
Comment: I think that's basically the answer. When you're using the Western concepts of chords and harmony, you're using an elaborate heuristic to handle the way that the overtones of each instrument mesh with each other. Doing that "by hand" (calculating and comparing the frequencies of the harmonics etc.) would be extremely tedious.

Harmonics in composition


how do I put solfege on for chords?

Question:
How do I put on solfege for multiple notes stacked/chords? I mean, I could put it separately, but how do I indicate which solfege goes to which note?
Comment: Are you asking how to sing two notes at once? Or are you simply writing in the solfège and want to know a system for clarifying which syllable goes with which pitch?
Answer: The standard way to annotate chords is to stack the annotations in the same order as the chord pitches.
<code>X: 1
T: Solfege for chords
M: none
K: none
L: 3/8
[FB]
w:ti
w:fa
</code>
Comment: is there a standard way? I know sheet music where they write the solfege names above the soprano and alt (treble clef)  and below the tenor and bass (bass clef).
Answer: If you are a beginner and have not practice in sight reading and using movable doremi I recommend what I practiced with my students:
Use bigger staves than we have in ordinary printed music or blow your sheet music up that you are able to write the names exactly in the place of the note heads and not above or below the lines:
e.g. fa,la,do,mi in the spaces of  the treble clef (in C major) and mi,so,ti,re,fa right in the line (like the note heads). The same technique is useful for beginners when learning the absolute note names (c,d,e,f,g ...)

how do I put solfege on for chords?


Targetting divs that are inside other divs

Question: I'm trying to get this hover to work. The goal is when someone hovers over div.lol the div.sdf hides.
Not sure how to add the div.dang into the script to make this work. If I delete the div.dang my script works.

test

sdf

    $(document).ready(function(){
    $('.lol').hover(function(){
        $('.ugh').nextAll('.sdf:first').hide();
    },function(){
        $('.ugh').nextAll('.sdf:first').show();
    })
});

Here is a link to the jsfiddle http://jsfiddle.net/nLybj/297/
Comment: There you go: http://jsfiddle.net/nLybj/302/
Answer: You can use:
  $('.lol').hover(function(){
    $(this).parent().next().find('.sdf').hide();
  },function(){
    $(this).parent().next().find('.sdf').show();
  });

Working Demo
Answer: Try:
$(document).ready(function () {
    $('.lol').hover(function () {
        $(this).parent().next('.dang').find('.sdf').hide();
    }, function () {
        $(this).parent().next('.dang').find('.sdf').show();
    })
});

jsFiddle example
Answer: If you want to hide/show all elements with class "sdf",then you can try this:
$('.lol').hover(
   function(){
        $('.sdf').hide();
    },function(){
        $('.sdf').show();
});

Demo here
to select next closest:
$(document).ready(function(){
    $('.lol').hover(function(){
        $(this).parent().next().find('.sdf:first').hide();
    },function(){
        $(this).parent().next().find('.sdf:first').show();
    })
});

Demo
Comment: Unfortunately, I just want the next closest, not all.


Dar um loop infinito

Question: eu presiso de um comando que faz um loop em taskkill, exemplo:

Se o processo estiver aberto, será detectado o processo e ativara o taskkill, mas também quero que outros comandos diferentes executem, se você não entendeu, é assim:

o batch identifica o processo em um loop, e executem outros comandos além do taskkill

só que não achei nada sobre isso.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Seria algo assim, no caso esse batch verifica a cada 5 segundos se o processo existe e se existir finaliza ele com taskkill e executa mais alguns comandos (comando2, comando3...) que você pode substituir com os comandos que você quiser.
<code>@echo off
:Loop
Tasklist |find /i "NomeDoProcesso.exe"
if %errorlevel% equ 0 (
                       taskkill /im "NomeDoProcesso.exe" /f
                       comando2
                       comando3
                       comando4
                      )
timeout /t 5
goto :Loop
</code>

Dar um loop infinito


Duvida select em duas tabelas

Question: Estou fazendo um sistema em PHP, mas estou parado, pois não estou conseguindo encontrar a solução para um desafio.
Tenho 2 tabelas, uma chamada objetos e outra chamada gavetas. Eu tenho vários nomes de gavetas cadastradas na tabela gavetas e eu preciso saber quais delas possuem objeto dentro delas.
Estou tentando fazer um select onde independente de ter ou não objeto dentro da gaveta, traga todos os registros da tabela gavetas e as que tiver objeto, seja exibido o nome do objeto ao lado. E quando tiver ( Caneta ) dentro da gaveta o PHP imprime a palavra ( encontrado ) ao lado do nome do objeto. Já tentei INNER JOIN / LEFT JOIN / RIGHT JOIN, mas não estou conseguindo o resultado desejado.
Tabelas:
**Gavetas**

id
nome-gaveta

**Objetos**

id
nome-gaveta
nome-objeto

Exemplo
Gaveta 1 / Caneta - Encontrado
Gaveta 2 /
Gaveta 3 /
Gaveta 4 /
Gaveta 5 / Borracha

Comment: ja tentou fazer um select usando full outer join? select from tabela  a full outer join tabela b on a.id = b.id, se possível poste o select q vc está tentando fazer.. abraços
Comment: Qual o `SGBD` utilizado?
Answer: Você deve usar um LEFT JOIN pra buscar na segunda tabela mesmo que não haja registros. Após isso concatene o resultado, caso queira uma linha por gaveta:
SELECT g.nome_gaveta,
       CONCAT(GROUP_CONCAT(o.nome_objeto SEPARATOR ', '),
       (SELECT ' - Encontrado'
          FROM objetos o2
         WHERE o2.nome_objeto = 'Caneta'
         LIMIT 1)) AS objetos
  FROM gavetas g
       LEFT JOIN objetos o ON o.nome_gaveta = g.nome_gaveta

Se quiser uma linha por objeto a query será a seguinte:
SELECT g.nome_gaveta,
       CONCAT(o.nome_objeto,
       CASE o.nome_objeto
         WHEN 'Caneta' THEN ' - Encontrado'
         ELSE ''
       END) AS nome_objeto
  FROM gavetas g
       LEFT JOIN objetos o ON o.nome_gaveta = g.nome_gaveta

Answer: Uma outra solução, usando CASE ao invés de sub-select:
SELECT
    g.nome_gaveta,
    GROUP_CONCAT((
      CASE o.nome_objeto
        WHEN 'Caneta' THEN CONCAT(o.nome_objeto, ' - Encontrado')
        ELSE o.nome_objeto
      END
    ) SEPARATOR ', ') AS nome_objeto
FROM
    gavetas AS g
    LEFT JOIN objetos AS o ON g.nome_gaveta = o.nome_gaveta
GROUP BY
    g.id

Fiddle: https://www.db-fiddle.com/f/rNZT8bSFPrcajmW89TZ6J2/0

Duvida select em duas tabelas


How to deal with strings where encoding is unclear

Question: I know there is quite a lot on the web and on stackoverflow about Python and character encoding, but I haven't really found the answer I'm looking for. So at the risk of creating a duplicate, I'm going to ask anyway.
It's a script that gets a dictionary, where all keys are properly as unicode. The values are strings with unknown encoding. For the keys it wouldn't matter that much, keys are all very simple very unlike the values. The values can (and do) contain a large variety of encodings. There are some dictionaries, where some values are in ASCII others as UTF-16BE yet others cp1250.
That totally messes up further processing, which currently consists mainly printing or concatenating (yes, that simple).
The work-around that I came up with, which makes Python print statements work properly is:
for key in data.keys():
   # hope they did not chose a funky encoding
   try:
       print key+":"+data[key] # this triggers a UnicodeDecodeError on many encodings
       current_data = data[key]
   except UnicodeDecodeError:
   # trying to cope with a funky encoding
        current_data = data[key].decode(chardet.detect(data[key])['encoding']) # doing this on each value, because the dictionary sometimes contains multiple encodings
        print key+":", # printing without newline was a workaround, because connecting didn't work
        print current_data.encode('UTF-8')

In Python this works just fine. In Jython 2.7rc1 which I use in the project (not an option to switch), it prints characters which are definitely not the original encoding (funky looking characters). If anyone has an idea how I can make this also work in Jython that'd be great!
Edit (Example):
Sample-Value:
Our latest scenarios explore two possible versions of the future seen through fresh "lenses".

Creates a string where the right and left double quotes turn to \x8D and \x8E. I don't know what encoding that is. In Python after using the above code it strips them. In Jython it turns them into white squares.
Comment: How can we reproduce your problem? Please try to provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
Comment: Since I've put up the question I'm sick and still have no access to this data. Sorry.
Answer: I'm not familiar with Jython, but the following link I found may prove useful: http://python.6.x6.nabble.com/character-encoding-issues-td1766833.html
It says that you should keep all unicode strings in separate files to your source, and read them with codecs.open. This seemed to work for the person who was experiencing a problem similar to yours.
The following link also mentions something about specifying an encoding parameter to the JVM: https://answers.launchpad.net/sikuli/+question/156443
Without seeing any actual error output, this is the extent of the help I can provide.
Comment: The files I'm opening seem to sometimes have various encodings inside. It's PDF Document Information that I'm reading.
Comment: You still haven't given enough information. Without knowing what the problem is exactly, one can only guess as to what the problem is and why it is occurring. Have you tried to implement the advice from the above links? Here are two other issues from jython.org that seem similar to yours that may be of use: [issue 1841](http://bugs.jython.org/issue1841) and [issue 1592](http://bugs.jython.org/issue1592)
Comment: Did you see the comment I left under the main post?
Comment: Yes I did. I wasn't asking why you haven't given enough information; I was merely stating that there is still not enough information for someone to be able to help you.


What is a good proposal distribution for Metropolis-Hastings for strictly positive parameters?

Question: In Metropolis-Hastings sampling it is required to have a proposal distribution $g(\theta_{new}|\theta_{old},\lambda)$, where $\theta_{old}$ is the last accepted sample in the chain and $\theta_{new}$ is a newly proposed sample. Samples are drawn from $g$ which are then transformed into the acceptance probability (the proposal step) for subsequent use in the move step. For example, $g$ is often chosen multivariate normal with mean $\theta_{old}$ and variance-covariance matrix $\lambda$.
I have a parameter $\theta$ which is a precision (or scale or variance) so that $\theta >0$ is a constraint on the parameter space. This thread discusses various options in this situation. I find the best option to use a function $g$ which only proposes samples from the allowed parameter space.
My questions are: which are commonly used distributions in this situation? And, how should the proposal distribution be conditioned on $\theta_{old}$?
For example, I can imagine the uniform $U(0,b)$ distribution may be useful, but I do not see how to choose $b$ or how to condition on $\theta_{old}$ (i.e. the last accepted precision/variance in my case).
An alternative may be Gamma or inverse Gamma, e.g. $Gam(a,b)$, but then also the question is how to choose $a$ and $b$ and how to link them to $\theta_{old}$.
Comment: It is not clear why you think the "best option" is to only propose samples from the allowed parameter space. There is nothing wrong (although it may not be ideal) to propose negative values in a random walk Metropolis which then get rejected because the acceptance probability is zero.
Comment: I second Jarad's comment in that in situations with "sharp corners", it may prove more efficient to make proposals that may fall out of the space than proposals that get stuck into such "corners".
Comment: Requiring visits very close to zero with a truncated proposal may be inefficient: when visits to this region are rare, they get massively weighted by the Metropolis ratio and the chain stays there for very long in order to compensate.
Comment: @jaradniemi My intuition is that if $\theta$ is close to zero, the rejection rate may then be very high. My application is one where $\theta$ (the precision) effectively plays the role of a penalization parameter with small values signifying stronger penalization.
Comment: Thinking about it, I could reparameterize to the inverse of $\theta$ to avoid this problem. Still the argument stays valid I believe.
Answer: The most natural [and generic] resolution [imo] is to turn $\theta$ into $\eta=\log\theta$ in the original problem so that $\eta$ is unconstrained. This allows for the use of random walk proposals like Metropolis et al.'s. The only warning is that the prior must incorporate the change of variable through a Jacobian:
$$\pi_\eta(\eta)=\pi_\theta(\exp\{\eta\})\times\exp\{\eta\}$$
Warning: This proposal is only equivalent to propose a log-normal new value in the original parameterisation if the proper Metropolis ratio is used [in the original parameterisation, the proposal is no longer a random walk]. (Note that an exponential change of variables turns the likelihood $p(D|θ,ν)$ into $p(D|\exp\{η\},ν)$, without a Jacobian there!)
Otherwise, a Uniform $\text{U}(\theta^\text{old}-\epsilon,\theta^\text{old}+\epsilon)$ proposal, as in Hastings (1970), can be chosen as a proposal, with the potential to propose negative [and hence surely rejected] values.
Comment: Every where you see $\theta$, you plug in $e^\eta$, but you also need to multiple the prior by $e^\eta$ due to the Jacobian in the transformation.
Comment: Thank you -  I like the change of variables idea. Could you elaborate a bit more on the change of variable and where exactly it is required?
Comment: But $\theta$ also occurs in the likelihood, for example. Is that of no consequence? Let's say I need posterior $p(\theta|D) \propto p(D|\theta,\nu)p(\nu)p(\theta)$ (with $\nu$ some nuisance parameter and $D$ data). Then $\theta$ is also substituted in the LL.
Comment: One more question; it has been argued in the link I cited above and by @jaradniemi that an alternative is to reject proposals outside of the space of $\theta$. I wonder if any of the two methods, transformation or this simple rejection rule, can be expected to outperform the other.
Comment: There is no answer to this question, it all depends on the calibration of each version against the target to be simulated.


How is it handled when two opposing players are gripping the basketball?

Question: Does this only happen when kids play?
I have not seen this happen in adult leagues and when I play with friends nobody does this.  (We are adults).  But it happens at every game when my son plays (He is a kid).
Comment: It results in a jump ball in the NBA, change of possession in FIBA and NCAA.  It happens on every competition level, including frequently in the NBA.
Answer: This is a "held ball"; quoting from the FIBA rules, 12.1.2:

A held ball occurs when one or more players from opposing teams have one or
both hands firmly on the ball so that neither player can gain control without undue roughness.

This results in a jump ball situation (12.3):

A jump ball situation occurs when:

A held ball is called.

Somewhat confusingly under FIBA rules, a jump ball situation does not result in a jump ball, but instead teams alternating possession on a throw-in (12.5.1):

In all jump ball situations teams will alternate possession of the ball for a throw-in at the place nearest to where the jump ball situation occurs.

Under NBA rules, it is also a held ball (Rule 4.VI) but does actually result in a jump ball (Rule 6.VI).


python 3 'MarkerServer' object has no attribute 'setsockopt'

Question: I am having an old python 27 code that I am trying to port to python 35 and was having a doubt on the following part:
<code>class MarkerServer(asyncore.dispatcher):

def __init__(self, queue, proto):

    asyncore.dispatcher.__init__(self)
    self.queue = queue
    if proto.lower() == 'tcp':
        logger.debug('Opening TCP socket.')
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.setblocking(0)
        self.bind(('', PORT))
        self.listen(5)
    elif proto.lower() == 'udp':
        logger.debug('Opening UDP socket.')
        self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.setblocking(0)
        self.bind(('', PORT))
        handler = MarkerHandler(self, self.queue)
    else:
</code>
this is returning the following error:
<code>    self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    AttributeError: 'MarkerServer' object has no attribute 'setsockopt'
</code>
Comment: I think that should be `self.socket.setsockopt(...)`.
Answer: Thank you for the comment jasonharper.
I realised there is also a deeper problem in the asyncore module of python 35. Not all methods seem to have been ported and were generating errors.
Problem solved after modifying the module.
Comment: What modifications were made chief?


ASP Fileupload Accept Attribute

Question: I've tried a plenty ways to limit the ASP FileUpload by file extension. Using asp-validation, checking the file codebehind, javascript, and so on.
now i found a new way to limit the selectable files:
<asp:FileUpload ID="fuTest" runat="server" accept=".csv" />

i added the accept attribute. is this a valid way according to ASP.net? The
 <asp:Fileupload

is rendered as
<intput type="file"

and this attribute is used without any errors and works like a charm. Is this valid an exist any restrictions i have not noticed yet?
Answer: Try following:
<asp:FileUpload ID="fuTest" runat="server" />
<asp:RegularExpressionValidator ID="regexValidator" runat="server" ControlToValidate="fuTest" ErrorMessage="Only csv files are allowed" ValidationExpression="(.*\.([cC][sS][vV])$)"></asp:RegularExpressionValidator>

Internet Explorer 9 does not care about the accept attribute. Refer http://www.stackoverflow.com/questions/181214/
Do not use this attribute as a validation tool. File uploads should be validated on the server. Refer http://www.w3schools.com/tags/att_input_accept.asp .

ASP Fileupload Accept Attribute


Como faço para que um objeto se movimente na tela usando tkinter?

Question: Já comecei meu código só que não sei o que esta acontecendo de errado para que meu objeto não se movimente
#Praticar movimentação de objetos
from tkinter import*

class Bola(object):
    def __init__(self):
        self.janela = Tk()
        self.janela.geometry('600x500')
        self.janela.title ('Bola')
        self.janela.resizable(False,False)

        self.frame = Frame(bg='blue')
        self.frame.pack()

        self.canvas = Canvas(self.frame, bg='blue', width=400, height=400, cursor='target')
        self.canvas.pack()

        raio = 29
        p = (100,200)
        self.canvas.create_oval(p[0],p[1],p[0]+raio,p[1]+raio, fill='grey' )
        self.vx = self.vy = 3
        self.x, self.y = p

        self.iniciar = Button(self.janela, text='INICIAR', command=self.comecar)
        self.iniciar.pack()
        self.janela.mainloop()

    def comecar(self):
        self.jogar()

    def jogar(self):

        self.update()
        self.janela.after(1, 10)

    def update(self):
        self.canvas.move('bolinha' , self.vx ,self.vy)
        self.x += self.vx
        self.y += self.vy

if __name__ == '__main__':
     Bola()

Answer: Seu código tem três problemas:

Ele não chama a função jogar repetidamente, porque ela não é passada pro after.
def jogar(self):

    self.update()
    self.janela.after(1, 10)

Deveria ser:
def jogar(self):

self.update()
self.janela.after(1, self.jogar)

bolinha tem que ser guardado na instância de Bola. Assim,
self.canvas.create_oval(p[0],p[1],p[0]+raio,p[1]+raio, fill='grey' )

Deveria guardar o objeto como um objeto da classe:
self.bolinha = self.canvas.create_oval(p[0], p[1], p[0] + raio, p[1] + raio, fill='grey')

A função move deve que ser chamada com o objeto a ser movido como primeiro argumento. Assim,
self.canvas.move('bolinha' , self.vx ,self.vy)

Deve ficar:
self.canvas.move(self.bolinha, self.vx ,self.vy)


AWS - Postfix / RSYSLOG - CONNECT from unknown

Question: Getting several of these in my mail log:
lost connection after CONNECT from unknown[10.3.47.5]
10.3.47.5 isn't within my DNS and I cannot determine the hostname, nor can I ssh into it. Is it safe to assume this is one of the multiple IPS within a ELB used to check the status of the postfix service?
Answer: In the EC2 console, find Network Interfaces in the left sidebar menu and click on it.
On the list of network interfaces, you should be able to find this address in the Primary Private IP column.
If it is an ELB interface, the name of the ELB will be shown under Description.


Is this convex bounded set closed in $\mathcal H\times \mathcal H$?

Question: Let $\mathcal H$ be a Hilbert space. Let $A$ be a bounded convex subset of the Hilbert space $\mathcal H\times\mathcal H$ such that

$B:=\{ x : (x,y)\in A \}$ is a closed convex bounded subset of $\mathcal H$
For any $x\in B$, $C_x:=\{ y:(x,y)\in A \}$ is a closed convex bounded subset of $\mathcal H$

Can we show that $A$ is closed with no additional constraints ?
I don't really know where to start since $A$ feels like the arbitrary union of closed sets $\{(x,C_x)\}_{x\in B}$, maybe I need some kind of continuity of the mapping $x\to C_x$, but in what topology then ?
Any input is greatly appreciated.
Answer: This is not true : take $\mathcal H = \mathbb C$ and $A = \{(0,0)\} \cup ]0,1]\times [0,1]$. Then $A$ is a bounded convex subset of $\mathcal H^2$, $B =  [0,1]$ is closed, as well as $C_0 = \{0\}$ and $C_x = [0,1]$ for $x\in ]0,1]$. However, $A$ is not closed.


Category SubCategory

Question: I have category and subcategory for my user points.
and I want showing points with category and subcategory.
how I must do?
Example
Category-1
SubCategory-1 Point-1 Point-2 Point-3 Point-4
SubCategory-2 Point-1 Point-2 Point-3 Point-4
Category-2
SubCategory-1 Point-1 Point-2 Point-3 Point-4
SubCategory-2 Point-1 Point-2 Point-3 Point-4
Category-3
SubCategory-1 Point-1 Point-2 Point-3 Point-4
SubCategory-2 Point-1 Point-2 Point-3 Point-4
Comment: can you please elaborate on your question and also please share some code snippet for better understanding
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Use ListView Widget or GridView Widget to show the list category with the points....
Comment: I writing categories with listviews.
But i dont know how can write subcategories and releated points.
Comment: you have to write nested ListView... what's my idea is you can write ListView category in vertical scroll and inside each row you have to put subcategory as another listview with horizontal scroll...
Comment: how I call function in listview for category's ID.
So I can query by category ID and write subcategory and points.

Category SubCategory


How to parse JSON to viewpager

Question: I am a beginner at the android studio. I have parsed some JSON data from the server. I want to implement these data in a viewpager. I got A sample viewpager code. But when I apply these JSON data to list it shows cannot resolve constructor. My Viewpager code is below.
My JSON Fetching code
public class MainActivity extends AppCompatActivity {
// Constants
private static final String TAG = MainActivity.class.getSimpleName();

// UI Components
private VerticalViewPager mVvpMainPager;

// Other objects
private ViewPagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initView();
}

private void initView() {
    mVvpMainPager = findViewById(R.id.activity_main_vvp_main_pager);

    setupViewPager();
}

private void setupViewPager() {
    mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    for (BeanNews news : generateSampleNewsData()) {
        mPagerAdapter.addFragment(PagerFragment.newInstance(news), "News " + news.getNewsId());
    }
    mVvpMainPager.setAdapter(mPagerAdapter);
    mVvpMainPager.setOffscreenPageLimit(generateSampleNewsData().size());
}

private ArrayList<BeanNews> generateSampleNewsData() {
    String url ="http://maranamassapp.cf/json_getdata.php";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("server_response");
                        for(int i = 0; i < jsonArray.length(); i++){
                            JSONObject ser =jsonArray.getJSONObject(i);
                            String creatorname =  ser.getString("head");
                            String imageUrl = ser.getString("image");
                            String cat = ser.getString("content");
                            String postdate = ser.getString("weburl");
                            String dateall = ser.getString("date");
                            BeanNews news = new BeanNews(creatorname,imageUrl,cat,postdate,dateall);
                            ArrayList<BeanNews> newsList = new ArrayList<>();
                            newsList.add(news);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    return newsList;
}

Comment: Check [this link](https://developer.android.com/reference/android/support/v4/view/ViewPager) about `ViewPager`. Now, you'll need a `RecyclerView` or a `ListView` inside `ViewPager` xml layout file to show the data. That's why i said please paste your xml codes. So, you'll need `Fragment` inside `ViewPager`, A `RecyclerView` inside `Fragment` then showing data or adding to `RecyclerView` adapter. Check the documentation or [this](http://androidcss.com/android/fetch-json-data-android/).
Comment: Please post your BeanNews class
Comment: Hello Nasim welcome to Stack Overflow. What do you mean by **how to apply these JSON data to the viewpager** Did you mean showing data in ViewPager's `Fragment`s? Could you please paste your xml too? Not sure what you're trying to achieve now.Thanks
Comment: @ʍѳђઽ૯ท  I have edited and updated the full code. Thanks For Your Response.
Comment: @umang-burman  I Have Added The Full Code. THanks For Your Response
Comment: Post Your BeanNews Class
Answer: Check this about ViewPager:

Layout manager that allows the user to flip left and right through
  pages of data. You supply an implementation of a PagerAdapter to
  generate the pages that the view shows.
ViewPager is most often used in conjunction with Fragment, which is a
  convenient way to supply and manage the lifecycle of each page.

Now, you'll need a RecyclerView or a ListView inside ViewPager xml layout file to show the data. So, you'll need Fragment inside ViewPager, a RecyclerView || ListView inside Fragment then showing data or adding to RecyclerView adapter.
Can't actually pass list of items(from json in your case) to ViewPager to show on the view in Android.
Comment: iam not using recyclerview because i want to show one JSON object per viewpager.
Comment: You actually have to use `Fragment`(s) inside `ViewPager`. Look for it [in here](https://medium.com/@kyroschow/how-to-use-viewpager-for-navigating-between-fragments-with-tablayout-a28b4cf92c42). Then, use `RecyclerView` or `ListView` to set `Adapter` for your items in each `Fragment`. Check the link to see how it works. The way you think how `ViewPager` is working is not correct I'm afraid.
Comment: can you do me a project for money.
Comment: No need for money. My god please :] I'll help you it's alright. Just try to join this conversation: https://chat.stackoverflow.com/rooms/179702/conversation  or my email in my profile. I've added you to have access to write. Hope you can make it.

How to parse JSON to viewpager


Question about inverse with respect to convolution product.

Question: Let $\mathcal{I}(X)$ be the collection of real valued functions  $f:X\times X\to \mathbb{R}$ with the property that $f(x,y)=0$ when $x>y$. The convolution product $f*g$ for $f,g\in \mathcal{I}(X)$ is defined by $$ f*g(x,y)=\begin{cases}
      \sum_{\lbrace z:x\le y\le z\rbrace}f(x,z)g(z,y) & x\le y \\
      0 & \text{otherwise} \end{cases}$$
From page 14 of http://www.math.ust.hk/~mabfchen/Math232/Inclusion-Exclusion.pdf, I don't follow the last step.

If the latest summ where $\delta$ is the Kronecker Delta, is equal to $\delta(x,y)$, wouldn't that imply the sum representing $g(x,y)$ is 0?
Answer: No. It means, if $x<y$ then
$$\sum_{x\le z\le y} g(x,z)\,f(z,y)=0\,.$$
And, also $g(x,x)\,f(x,x)=1$.
For example, if $y$ covers $x\ $ ($y>x$ and there is no element in between), we have
$$g(x,y)=-\frac1{f(y,y)}\big(g(x,x)\,f(x,y)\big)=-\frac{f(x,y)}{f(x,x)\,f(y,y)}\,.$$
Then
$$g(x,x)\,f(x,y)\ +\ g(x,y)\,f(y,y)\ =\ \frac{f(x,y)}{f(x,x)}\ +\ \frac{-f(x,y)}{f(x,x)}\ =\ 0$$
indeed.


What is the difference/purpose of 'content' and 'elements' keys, in preprocess?

Question: I'm using hook_preprocess_node and looking at $variables. I can see there's two similar keys: content and elements. I see that there's a comment in the core code:
  // Helpful $content variable for templates.

next to code that copies all elements keys into content... I'm unsure why it's helpful, how it's different, and when one would use elements or content to achieve a particular goal.
This is a general question, but my task at hand is that I have two separate taxonomy term reference fields and I wish to combine them, alphabetically by term name, into one list for presentation.
Answer: elements is the variable name defined in theme_hook() to hold the renderable elements (for the node this is the entity build array). Preprocess is then responsible to prepare variables for rendering, like content.
If your goal is to modify the template output then check first which variables are actually printed. In a node template it doesn't make sense to change elements in preprocess, any changes you make will be discarded. You can however do this in the build process, for example in hook_entity_view_alter().
Comment: So the *node* module generates a render array with all the node's data in render arrays under `'elements'`. Then `template_preprocess_node()` sets defaults for the node, which is where the whole *copy `elements` to `content`* comes from. So this means `elements` is only left there "just in case" (?) but that in terms of continuing the render process, `content` is what now matters. Is that about right?
Comment: Yes, but in your case you might want to change the build array before it reaches the preprocess hook. This looks more like you want to alter the build array, not to theme the output.
Comment: Thanks, I've started [another question](https://drupal.stackexchange.com/questions/309299/render-two-taxonomy-fields-in-one-alphabetical-list/309300#309300) for that part of the task, to keep things clearer.


Is there still any legitimate reason (in 2011) to use proxy servers instead of NAT for sharing an internet connection?

Question: Proxies were around before NAT, and so early on in the internet, they were popular ways to get an entire network online with only a single public IP. NAT initially required complex software and/or hardware to get it working, and so understandably some organizations still used proxy servers to provide access.
In the last decade however, NAT has become immensely popular, and is available in virtually every router on the market. The hardware is so fast and cheap that unless you are trying to use a $50 home router to run say, a 5000 person office, you're not going to have issues. Firewalls are also smart enough to do complex authentication, easily allowing different users to access different services at different times of day (even the most basic home routers often have this functionality built-in). In fact, NAT is likely easier to set up and manage than a proxy server.
In my job I still often deal with clients using proxy servers to provide internet access, and the ensuing issues that arise from authentication, what account services are running as, etc. This includes some companies that are very big and old (and so I guess got their network installed over a decade ago, and just kept it that way) as well as relatively new organizations that have only a few years old.
So my question is, why in the heck are there still so many places using proxy servers for this purpose?
Comment: I think you're making a lot of assumptions in your question, most of which are incorrect. I mention this in my answer, but frankly, you're comparing apples to oranges here.
Answer: Proxies are still used for a few main reasons:

Content filtering
Authentication
Caching

While NAT and proxies are similar in some respects, they operate at different layers and as such, differ in many ways and they fulfill different needs. NAT is largely a layer 3 technology and HTTP proxies are a layer 7 technology.
Comment: Authentication is a huge one for businesses. NAT logs *might* be able to tell you that 10.1.1.1 accessed horse porn at work, but that could have been the cleaner connecting their iPad to the network using a WPA key their friend in office 8B gave them. A Proxy can tell you that "exampleorg\erika" was in fact doing the access.
Answer: NAT operates on a firewall and so acts on IP packets, while a proxy handles web requests at the application level, thus being able to filter, analyze and record them. This gives a proxy some capabilities which you just can't have on a router:

Authentication. A proxy can recognize (and accept/refuse, and log) user accounts, while a firewall only sees IP addresses.
Application-level filtering. In this case, URL filtering and content filtering; a proxy can analyze the web requests flowing through it and act based on their content, while a firewall can only block or allow specific IP addresses.
Malware protection. A proxy can check the web pages for malicious contents.
Logging. A proxy can log the HTTP requests and responses, complete with the full URLs your users accessed. A firewall, again, will only see IP addresses and TCP/UDP ports.
Caching. Less useful nowadays with so much dynamic content around, but can still help in reducing network traffic.

On the other hand, a proxy only acts on HTTP (and sometimes FTP) traffic, because it's made specifically for that; if you need any other kind of Internet traffic, a NAT is still in order.
Also, much confusion arises from the facts that there are lots of mixed firewall/proxy appliances and softwares around; but they are two fundamentally different functions, even if they run on the same device.
Answer: more than likely, they are using the proxy servers for monitoring, and blocking web traffic. there are many filtering tools that connect right into the proxy, and make it very easy.. Also, with proxying, you can get caching of commonly used files.  When I worked at a college, every computer had a routable IP, but we still used squid to cut down on traffic.
Answer: I can sympathize with the authors question because of the additional features offered by routing appliances.  There are several options from WatchGuard and SonicWALL which do web filtering services, Antivirus, Antispam and others all from the appliance.  The difference is that they do all this without requiring you to configure proxy settings in your browser.  Even though a web filter is technically a proxy server because of the layers it looks at, not having to configure browser settings makes it feel more like NAT only.
On the higher end, I feel that dedicated web filters with fiber channels scale better and are more seamless than a Windows proxy server.  On the lower end, you can get a much more cost effective all in one solution with one of these multi appliances.