Java create object array of numbers in string format

Question: I'm writing a function for a program and I need to generate a list of numbers in an Object[]
For example.
Object[] possibilities = functionName(13);

Should generate
    Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};

How should I go about achieving this?
Comment: Learn about for loops.
Comment: create an array of size given in functionName. Then use a for loop and put the value of the iterator plus one in the corresponding position in the array.
Answer: Try this method.
private Object[] function(int size) {

        Object[] result = new String[size];

        for (int i = 0; i < size; i++) {

            result[i] = Integer.toString(i + 1);
        }

        return result;

    }
}

Comment: ? I don't think you understood the question
Answer: String functionName(int number){
   StringBuilder str = new StringBuilder("{");
   for(int i = 1; i <= number; i++){
      str.append(Integer.toString(i)).append(", ");}
   String string = str.toString().trim();
   string = string.substring(0, str.length()-1);
   string += "}";
   return string;
}

This should give you the desired string and you just print it.
Comment: Object[i-1] = Integer.toString(i);} should be  obg[i-1] = Integer.toString(i);}
Comment: @ShivamPaw Sorry just changed it, but I think you got the idea.
Answer: First, you need a method to print the results from your functionName (that's setting a goal post). Something like,
public static void main(String[] args) {
    Object[] possibilities = functionName(13);
    System.out.println(Arrays.toString(possibilities));
}

Then you might implement functionName with a basic for loop like
static Object[] functionName(int c) {
    Object[] ret = new String[c];
    for (int i = 0; i < c; i++) {
        StringBuilder sb = new StringBuilder();
        sb.append("\"").append(i + 1).append("\"");
        ret[i] = sb.toString();
    }
    return ret;
}

And when I run the above I get (the requested)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]

Comment: @ShivamPaw Java arrays are declared that way, they don't print that way.


(Garry's Mod DarkRP) Wildcard selector from ammo.lua searching jobs.lua

Question: I'm not sure if this is the right section for games, but still. I am a developer for a in-dev server that I believe uses FAdmin & ULX for the admin.. things.. anyway; I am currently developing the jobs.lua, shipments.lua, and ammo.lua. It's supposed to be a militaryrp, so there's obviously alot of custom-made teams. Shipments? Easy. Jobs? Easy. Ammo? Well, it might be easy if this question has the solution I'm looking for. Here's an excerpt for 2 jobs, 2 shipments, and 1 ammo type. I'll explain for each section.
TEAM_ARMY = DarkRP.createJob("Army Infantry", {
 color = Color(0, 0, 255, 0),
 model = "models/codmw2/codmw2h.mdl",
 description = [[You are an Army Infantry!
Please read the rules found in the !motd, it describes the limitations of each job very well!]],
 weapons = {"fas2_g3", "fas2_glock20", "fas2_dv2"},
 command = "armyi",
 max = 5,
 salary = 80,
 admin = 0,
 vote = false,
 hasLicense = false
})

TEAM_ARMYSH = DarkRP.createJob("Army Shotgun", {
 color = Color(0, 0, 255, 0),
 model = "models/codmw2/codmw2.mdl",
 description = [[You are an Army Support!
Please read the rules found in the !motd, it describes the limitations of each job very well!]],
 weapons = {"fas2_m3s90", "fas2_ots33", "fas2_dv2", "riot_shield"},
 command = "armys",
 max = 4,
 salary = 100,
 admin = 0,
 vote = false,
 hasLicense = false
})

Here are two custom ARMY jobs [teams]. This is the problem I'm facing. I need to be able to [let's say] select these two plus countless other jobs for the ammo type below that targets them to be the only teams/jobs that can buy that ammo type. I've seen the tutorial on the DarkRP Wiki, but that's not the correct format for this sever. The ammo types are being imported as FAS2 ammo.
DarkRP.createAmmoType("5.56x45MM",  {
 name = "5.56x45MM",
 model = "models/items/boxsrounds.mdl",
 price = 145,
 amountGiven = 60,
 customCheck = function(ply) return CLIENT or ply:IsTeam("TEAM_ARMY") or ply:IsTeam(TEAM_%ARMY$) or ply:IsUserGroup("owner") end,
  CustomCheckFailMsg = "You must be apart of the Army!"
})

What I attempted to do is this;
If the player is on the TEAM_ARMY, or the Army Infantry job, OR is on the TEAM_ARMY%, where % is supposed to be a wildcard, then that means it can target lets say TEAM_ARMYSH for Army Shotgun and also TEAM_ARMYS for Army Sniper, if those were the only two other jobs that had ARMY beginning with it [although that's NOT the case.]
The shipments makes it easier; there's a simple allowed = {} cmd line, which can be used like this.
AddCustomShipment("AK12", "models/weapons/world/rifles/w_ak12.mdl",  "fas2_ak12",  3500,  1  true,  3500,  true,  {TEAM_TALI})

AddCustomShipment("AK47",  "models/weapons/w_ak47.mdl",  "fas2_ak47",  4000,  1  true,  4000,  true,  {TEAM_TALI, TEAM_BMARKET})

The attributes go [in order]: Name; Model; Entity; Price; Amount; Seperate; PriceSep; NoShip; and Allowed. The allowed simply lets me target a team for the usage. Sadly, ammo does not. So what I'm trying to figure out is how can I select multiple groups from one ply:IsTeam("TEAM_ARMY") that begin with 'ARMY' and have some sort of wildcard after ARMY for selection? This is so that I don't flood the ammo types with tons and tons of groups.
Answer: You can do something like:
 customCheck = function(ply) return string.find(string.lower(team.GetName( ply:Team() )),"army") or ply:IsUserGroup("owner") end,

string.find(<haystack>,<needle>) will return a number if it finds <needle> in <haystack>:
Example:
string.find("ABC","B") returns 2 since it's the second letter.
Now string.lower(<text>) returns a lowercase version of <text>
Example:
string.lower("Hello World!") returns "hello world!"
Now team.GetName(<number>) gets the team name biased on the team number and to get the number I used ply:Team() which returns a number.
Hopefully this will help you and you can get back to working on it quickly.
If it doesn't work just comment, this code is untested.


Why do harmonics played on guitar sound lower as you move to higher frets while fretted notes sound higher?

Question: By lightly touching a guitar string at specific nodes (most commonly at the 12, 7th and 5th fret) and releasing your finger immediately upon plucking the string - a clear ringing tone is produced.  These tones are called harmonics.
When fretting the strings on the guitar, the closer you move towards the body, the higher the note.  So a note fretted on the 7th fret will be higher in pitch than a note fretted on the 5th fret on the same string.  A note fretted on the 12 fret is higher than either.
But when playing harmonics - it's just the opposite!  A 12th fret harmonic produces a lower tone than a 5th or 7th fret harmonic played on the same string.
What causes this seemingly counter-intuitive phenomena to occur?
EDIT: Also wondering why on the 12th fret harmonics the fretted note corresponds with the harmonic note, but this is not the case on any of the other harmonic nodes.
Comment: You know you don't have to stop at just the 12th, 7th or 5th frets. Any position that cuts the string in an integer partition, ie there are an integer number of waves on the string, will give you an harmonic. (See Edouard's image.)
Comment: Your fretboard shortens the string to the length of fret->bridge. Your harmonic "shortens" the string to the length of node->[bridge or nut, whichever is closer].
Comment: The 9th fret node is the same harmonic as the 4th fret node. Each successive harmonic divides the string up into a smaller division, so all but the first harmonic (12th fret) occur more than once.
Comment: You don't have to immediately remove your finger. It can stay there and you can even touch again in the same spot - the string isn't moving there.
Comment: @RockinCowboy You have a misapprehension in your question: harmonics don't always get higher when you move towards the nut (e.g., 9th fret harmonic is higher than 7th). One thing maybe not clear in Édouard's answer is that every harmonic other than the 12th fret one has *more than one place* you can play it. The 5th can be played at the 24th, which also sounds the same note as the harmonic. See this: https://upload.wikimedia.org/wikipedia/en/thumb/3/34/Guitar_harmonic_nodes.svg/1280px-Guitar_harmonic_nodes.svg.png
Comment: @NReilingh okay - that does make sense but does not quite explain why the 9th fret harmonic is higher than the 7th fret harmonic which is closer to the nut so should be higher as both are closer to nut than bridge.  And what phenomena causes only the shorter portion of the string to produce a tone when the entire string is vibrating.
Comment: I am getting some good pieces to the puzzle but still don't have enough pieces to see a clear picture.  But hopefully I will get a few more pieces and it will become clear.
Answer: It is not true in general that the higher you go on the fret board, the lower your harmonic is. Actually, if your were to play an harmonic at the 24th fret, you would hear a note sounding an octave higher than the harmonic at the 12th.
Still, however, the harmonics behave differently than fretted notes. Now, let's get physical and explain why. On perfect strings fixed on both extremities.
Basics of perfect strings
Because its extremities are fixed, a perfect string of length L can only vibrate at certain frequencies. These frequencies are such that the matching wavelength are of the form:

λn = 2⨉L/n

The next image1 illustrates why: the extremities don't move, so must be on nodes of the vibrating strings.

The matching frequencies for these wavelength are:

fn = k⨉n/(2⨉L)

for a some constant k which depends on the characteristics of the string.
In practice, whenever a string vibrates, it vibrates at a combination of these frequencies. f1 is the fundamental, which determines the note you hear, the various fn≥1 are the harmonics, which are multiples of the fundamental and create the timbre of the note.
Remember that the higher the frequency, the higher the pitch.
What happens when you fret a note
Whenever you fret a note, what happens is that, without changing the other characteristics of the string2, you change its length; i.e. instead of having fixed points at the bridge and the head, you have fixed points at the bridge and the fret.
The fundamental frequency of the note you're playing is thus:

fʹ1 = k/(2⨉Lʹ)

where Lʹ is the length of the string up to the fret you're playing. Because, obviously, Lʹ < L, fʹ > f. The fundamental frequency is higher, the note has a higher pitch.
What happens when you graze a string
When you graze a string to "play a harmonic", what happens is very different. You don't shorten the length of the string: the whole string is still vibrating. However, you muffle some of the frequencies it's vibrating at by preventing mouvement at a given point.
For example, if you play a harmonic on the 12th fret, that is in the very middle of the string, you muffle every alternate frequency. If you look back to the previous illustration, you can see that the frequencies depicted on the right-hand side of the image don't make the string move in its very middle, but that the ones on the left-hand side all do. But if your finger is right there, the middle of the string cannot move.
That means that the only frequencies you allow to vibrate are the fn where n is even, f2, f4, …
The lowest frequency at which the string is vibrating is thus f2, which is the fundamental of the note you're grazing. The fundamental is twice as high as the open string; you're playing an octave.
If you were to graze the string at one quarter of its length, be it the first (~5th fret) or last fourth (exactly the 24th fret) of the string, you would only allow one out of four frequencies to be vibrate. The fundamental would be f4, that is two octaves above the open string.
If you were to graze the string at a third of its length, once again which third does not matter (the first is around the 7th fret), only one frequency out of three would vibrate and the fundamental would be f3, i.e. an octave and a perfect fifth above the open string.
You could theoretically play any note with fn as a fundamental this way, but higher harmonics have very little power.
Why do the 12th fret harmonic and fretted note are the same note
Should be left as an exercice for the reader. I'm way too nice.
We have said previously that a 12th fret harmonic sounds one octave higher than the open string, i.e. its frequency is double that of the open string.
Now, when you fret a note on the same fret, the length of the string is Lʹ = L/2 (we're at the middle of the string). Thus, when you fret this note, the fundamental is:

fʹ1 = k/(2⨉Lʹ) = k/(2⨉Lʹ) = k/L = 2⨉k/(2⨉L) = 2⨉f1 = f2

The fretted note is, once again, at the octave and share the same fundamental (and thus pitch) as the harmonic.
Please notice, however, that while the frequencies are the same, the power at which the string vibrates for each frequency is different. The pitch is the same; the timbre is different. Typically, harmonics are much softer.

Courtesy of Wikipedia.
Technically, you would be slightly changing the tension of the string, but on a well fit guitar, the effect should be minimal. No need to worry about that in our model.
Comment: @supercat Higher frequencies are audible as well. Our brain, however, doesn't interpret them as independent sounds, but as part of a whole. We don't hear a bunch of sinusoids, we hear a note whose pitch is the lowest frequency of the string (well, most of the time) with a particular *timbre*. When the power of higher frequencies change, the timbre is different. That's how we differentiate a guitar from, say, a trumpet (well, the unstable attack of the sound is also very important, possibly more).
Comment: @Édouard: It's also why power chords used with distortion sound an octave lower than played.  The three notes of a power chord have fundamentals with a 2:3:4 ratio, and distortion creates sum and difference tones with their harmonics, and all those sum/difference tones are multiples of the sub-harmonic.
Comment: It may be worth noting that plucking an undamped string causes it to vibrate at all of its harmonics, but only the lowest is generally audible.  Grazing a string will nullify all harmonics which would require the string to move at that spot.  If one grazes the string at the midpoint and then at the 1/3 point, that will nullify all odd harmonics, and then all that aren't multiples of three, leaving only those which are multiples of six (which may be quite faint).
Comment: @supercat. Interestingly when you pluck a string there can be no null point at the place where you pluck the string, because you are forcing it to move by plucking. I've heard it said that plucking near the 7th harmonic null point gives a purer tone because of this. Also it can be why the 3rd and 4th harmonics (7th and 5th fret) sometimes don't seem to work because the right hand is plucking in the wrong place and cancelling the harmonic.
Comment: @supercat There's [that question](http://music.stackexchange.com/questions/34531/what-is-virtual-pitch) I've wanted to answer for a while: your remarks about power chords would make for a good start for an answer.
Comment: @supercat that's a pretty neat way of playing very high harmonics. For example, you can play the fourth and third harmonic at the same time (I do it on double bass, which I think would be easier than on guitar) to get the 12th harmonic. Then you can play around with the 12th harmonic of the low E string against the 5th harmonic of the G string and hear the syntonic(?) comma.
Answer: After all the technical answers, try this. Play , say, the 7th fret harmonic, then press down on the EIGHTH fret. Pluck the string BEHIND - as in closer to the nut. You'll find that the note is the same. If there were more, smaller fretwires, you could do this for all the harmonics. You have been fooled into thinking the harmonic nodes only work going DOWN the neck, while notes only get higher by going UP. Think of it like a backwards guitar!
The other answers are brilliant.
Answer: My friend, you have just stumbled onto the Harmonic Series.  This was something Pythagoras tinkered around with using the monochord, and is primarily responsible for much of how Western music sounds, is written, is analyzed, and is perceived.
Very basically, all sound travels through vibration. Since vibrations are made up of waves, each wave has a crest, trough, amplitude, and frequency.  When you access a natural harmonic on your guitar, you are dividing the string at a length that neatly divides into the sum-total length of the string.  In other words, when you touch at the 12th fret, you're effectively dividing the string in half. Since a string half the length produces a sound twice as high (as the frequency is twice as high), the resultant note is twice as high as the fundamental.  All of the other notes that you access divide the string in similar, but different ways.
Nodes are symmetrical.  If you experiment with your guitar strings in the opposite direction (past the 12th fret), you'll find that you can create the same natural harmonics by playing above very high frets and even pickups.
The reason why the harmonics go higher as you move down (or to the opposite end of the string) is that you are accessing different nodes that further divide the string into equal but smaller divisions.  Just like the 12th fret divides the guitar in half, the 7th fret, 5th fret, and others divide the same string into several equal divisions.  Just like the string divided in half giving you a pitch twice as high, a string divided equally into 3 or 5 or 7 parts (if amenable to the base frequency) will give you proportionally higher pitches.
This is why I said that nodes were symmetrical - it doesn't matter which direction you go from the 12th fret.  You'll be able a to access the same harmonics in either direction.
Check out wikipedia for more information, but, for what it's worth, it might be a little heady for a first-time read:
http://en.wikipedia.org/wiki/Harmonic_series_%28music%29
Comment: The wiki link is a long read with your thinking cap on.  It does not tell me why the harmonic notes on my guitar go in opposite direction of fretted.  I know about 12th fret being half way point and that makes sense.  But since the entire string is vibrating on a 5th fret harmonic, why is it so much higher than the 12th fret?  And 12 fret harmonic is same as 12 fret fretted note.  Not so on other harmonics.
Answer: Although I definitely see what you're saying, it's not strictly true that harmonics closer to the nut will be higher. What's happening with natural harmonics is you are dividing the string into to equal parts. An open string will not only vibrate at its fundamental frequency but also at integer multiples of that frequency, each getting higher and quieter. The resulting series of notes is the harmonic series. When you place your fingers on the nodes, you are stopping certain harmonics from ringing, giving you the pure tone.
Your examples, the 12th, 7th, and 5th fret divide the string into 2, 3, and 4 parts respectively. On the twelfth fret, there is only one node in the middle of two parts. However, on the 7th fret, there are two nodes dividing three parts. The other node is on the 19th fret. For the 5th fret harmonic, there are two more nodes: the 12th fret and the 24th fret. Of course, if you pluck while your finger is over the 12th fret, you'll only get the lower harmonic. But you can pluck on the 5th fret and place your finger over the 12th fret, you will indeed find a node there and the note will not dampen.
So, back to the whole 'lower is higher' predicament. It's true that you can find progressively higher notes in the way you described, bridge to nut direction. But you can also do the same thing with nodes in the opposite direction (ie 12th, 19th, and 24th frets).
Comment: Your harmonics would also "match" the fretted notes for any other harmonics found on the bridge-side of the 12th fret. That is, if you had a theoretical fretboard that extended all the way to the bridge (with an infinite number of infinitely small frets in between) the harmonic nodes you found on that part of the fretboard would match the notes being played.
Comment: If you follow the harmonics in nut to bridge direction, they'll match up. The 19th and 24th fret match their harmonics. All the harmonics beyond this are off the fret board. If your intonation is off, though, it will be very apparent playing the harmonic and fretted note one after another. They will be out of tune. The 7th and 5th fret nodes are better understood as reflections of the 19th and 24th frets nodes using the 12th fret (half the string) as a point of symmetry.
Comment: Interesting information.  What about why the only harmonics that match the fretted notes seem to occur on the 12th fret.  This will sink in eventually but I'm not quite getting it yet.
Comment: @NReilingh: Plucking with a finger lightly on the 12th fret will produce both the 2x (octave) and 4x (two-octave) harmonics; because lower harmonics are generally louder, the 4x harmonic will not be noticeable, but that won't mean it's not present.  Indeed, plucking an open string will produce many harmonics, but they won't be as noticeable as the fundamental; one may demonstrate their presence, however, by lightly brushing the harmonic *after* the string is plucked.  If a harmonic is audible after one touches a fractional subdivision of a string, that means it was *present* beforehand.
Comment: @RockinCowboy  The harmonic and the fretted note will be the same at the 12th, 19th, 24th, and certain other higher positions. At the 12th fret, for instance, you divide the string length in half both fretting and stopping, giving the same frequency content. Stopping the string at the 7th and 19th frets divide the string in 3rds, but only fretting at the 19th fret gives the one third string length, fretting at the 7th fret lets the string vibrate 2/3's the string length, which is one octave lower.
Comment: @user3235  When I posted the question 5 years ago (wow time flies) I had never tried playing a harmonic on the 19th fret. Now I realize that past the 12 fret - the premise of my original question does not hold.   But thanks for elaborating on NReilingh's comment from Mar 03, 2015.  I appreciate the added explanation.  Thanks.
Answer: The harmonic nodes are uniformly distributed across the length of the string.

at the 12th fret (2x open string frequency)
at the 7th and 17th fret (3x open string frequency)
at at the (approx) 5th and 24th fret (4x)
at the (approx) 4th, 9th, 16th and 28th (5x)
and so on

for some of nodes closer to the bridge, like the "28th fret" you have to imagine
where such a fret would be.
It's just that, given that we fret with our hand out over the fret board we don't usually induce natural harmonics by touching the string with our fretting hand above, say, the 12th fret.  Note that you induce pinch harmonics by using your picking hand to lightly damp the string at the nodal points closer to the bridge.
Comment: A minor correction, the 1/3 length is at the 19th fret, not the 17th.
Answer: A string can support multiple independent vibrational modes simultaneously at multiples of its fundamental frequency; generally, only the brain will focus on the lowest one it hears and regard the others as subsidiary to it.  Brushing one's finger against part of a string will absorb energy from all vibrational modes which would require that part of the string to move, while leaving unaffected those modes which where that part of the string would naturally be stationary.
If one is careful and touches the string at just the right spot, it's possible to pluck a string, graze it lightly so as to nullify all vibration modes which would require motion at the finger's position, and then remove one's finger, leaving the string vibrating in only the reduced set of vibrational modes.  If one touches the string briefly at the midpoint, and then at either the 1/3 or 2/3 point, the first touch will eliminate all modes that aren't multiples of 2x the base frequency, and the second will eliminate any that aren't multiples of 3x, thus leaving only multiples of 6x the base frequency.  Such harmonics may naturally be very faint, but one can maximize their starting amplitude by plucking the string at a spot near 1/12 or 1/4 of its length (plucking the string a spot near k/N of its length for some integer k will produce very little of the Nth harmonic; plucking at at a spot near (k+(1/2))N of its length will maximize the Nth harmonic.
Answer: So basically, the 12th fret is the mid-point on the string and the lowest pitched harmonic. Anything from 12 to the nut gets higher in pitch and the same thing goes for the opposite direction, from 12 to 24. Makes sense now when you think of dividing the string equally. The nut and the bridge are the fixed points and the 12th fret is exactly midway between them. So dividing the string in half, anything higher or lower than the 12th will have a higher pitch as it gets closer to either fixed point.
Answer: Here are some basic ideas that are of interest to musicians. Music is based on a simple mathematical idea called 'Harmonic Series'.
https://en.wikipedia.org/wiki/Harmonic_series_(music)
The terms 'pitch' and 'frequency' can be used  almost interchangeably in this discussion. If we are talking about the physics of music, these terms are closely related.
The Harmonics Series is simple idea. If we multiply a base frequency (pitch) by integer multipliers, we create frequencies (pitches) that vibrate sympathetically (harmoniously) with the fundamental and the other pitches in the series. We really don't need to go far up the series to create the intervals that create the 12 divisions in the octave that Western music and even bird calls use. Eastern music divides the octave further, we also use smaller intervals from time to time in Western music, but we have no system of notation for these smaller intervals. At least I am not aware of such a system. I would not be the least bit surprised to learn that there is such a system, or systems.
If you look at the first picture in the Wiki article linked above, we see that if we place our finger on the twelfth fret of the the guitar, we cause the string to vibrate at double the frequency, creating the interval of an octave. If we place our finger on the 7th or the 19th fret, we triple the frequency. This creates a pitch one octave plus a fifth above the fundamental. If our fundamental pitch is E the resulting pitch is a B. If we place our finger on the 5th fret or the 17 fret, we get a pitch 2 octaves above the fundamental, or a frequency 4 times the fundamental. If we place our finger on the string at the 4th,9th,16th or the 21st fret we create a frequency 5 times faster than the fundamental, this produces a note that is 2 octaves plus a major 3d above the fundamental, creating a G# on the E string of a guitar.
We can continue up the series, but we have already produced all of the intervals necessary for the 12 tone scale that Western music uses. If our fundamental is E, we have a B and a G#. E to B is a fifth. B up to E is a fourth. The difference between a fifth and a fourth is a major 2nd. The interval between an E and a G# is a major 3rd. The interval between a G# and a B is a minor 3rd. The difference between a minor 3rd major 3rd is a minor 2nd, or half step.
There is a problem with this system, however. If you use a scale based on these pitches, there are tuning problems, if you try to play in a different key, you will be out of tune.
Bach solved this problem. He divided the octave into 12 equal intervals, based on the mathematic algorithm of multiplying the fundamental frequency by the 12th root of 2 to create a half step. If you do this 12 times, you end up with a frequency that is 2 times the fundamental i.e. an octave above, and a 'symmetric' scale that is identical in every key. The frequencies are not exactly the same, but they are very close.
For example, lets look at the Perfect 5th. Using the harmonic over tone series, a fifth is created by multiplying the fundamental by 3/2, or 1.5 .
Using Bach's method (the one used in modern music), to create a fifth, we multiply the fundamental by the 12th root of 2, raised to the 7th power (because a Perfect 5th is 7 half steps). The result here is the we multiply the fundamental by 1.49831. This difference is detectable by ear. As you can see, these numbers are pretty close.
Interestingly, if we create a overtone at the 5th fret (I like to use the A string on the guitar for this. It helps to use some overdrive which compresses the signal and makes the overtones louder.), then on the 4th fret, then the 3rd fret, slightly past the 3rd fret about 1/4 of the way towards the 2nd, then over the 2nd fret, we can create the notes in a dominant 9th chord!!! A, C#, E, G, B. !!!


Vídeos aleatórios background do site

Question: Como eu poderia fazer para que, a cada acesso ao site, um vídeo diferente aparecesse? Entendo que existe códigos que alteram o background com imagens conforme abaixo:

Mas como eu faria para aplicar em vídeos?
<video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="mp4/fundo.mp4" type="video/mp4">
</video>

PS: Solicito que apenas pessoas que entendam do assunto votem em fechar ou indiquem como duplicata, pois um caso é imagem e o outro é vídeo e se fizerem isso, por favor, me passem um exemplo, pois muitas pessoas que, assim como eu, não tem muita experiência em Jquery ou Javascript e vêem isso como casos diferenciados.
Comment: Possível duplicata de [Img no header mudando em cada carregamento da página](https://pt.stackoverflow.com/questions/256942/img-no-header-mudando-em-cada-carregamento-da-p%c3%a1gina)
Comment: Só um comentário rápido.
Você precisa selecionar os vídeos do seu diretório de forma dinâmica, e me lembro que há o método Random em JavaScript.
Pense em concatenar o nome do vídeo em duas variáveis para atribuição do source, algo como vídeo + 1 + mp4.
Comment: Pessoal. Desculpe, meu forte não é Jquery. Como eu faria para aplicar o exemplo do link em vídeos? Pois um caso é imagem (background) e no meu é vídeo. Poderiam me dar um exemplo?
Answer: Meu amigo, basta seguir o mesmo raciocínio aplicado nas imagens, o que muda é que você irá alterar no src do vídeo. Usando Jquery ficaria assim:

$('document').ready( function(){

   var video = Math.round(Math.random()*2);

   var videoaleatorio = [
   'fundo.mp4',
   'fundo2.mp4',
   'fundo3.mp4'
   ];
     $('source').attr('src', 'mp4/'+videoaleatorio[video]);

console.log('endereço do video selecionado: '+ $('source').attr('src'));

});

<video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="" type="video/mp4">
</video>
Comment: Perfeito Jorge. Funcionou! Muito obrigado!!!
Comment: Por nada! Boa sorte! :D
Answer: Você poderia salvar as urls dos videos em um banco de dados, e usar o Math.random() pra fazer a troca de URLs
Um exemplo usando array (como banco de dados):

let urls =
[
    'http://meuvideo.com/1',
    'http://meuvideo.com/2',
    'http://meuvideo.com/3',
    'http://meuvideo.com/4',
    'http://meuvideo.com/5',
];

function maxAndMin(max){
  return Math.floor(Math.random() * max);
}

console.log(urls[maxAndMin(urls.length)]);
Comment: Olá Lucas. Como eu faria para aplicar no código que passei? Pois não tenho muita experiência em Jquery ou Javascript.
Comment: Quais as urls dos videos?

Vídeos aleatórios background do site


Prometheus rate query over a long period

Question: When using the rate function over a long period (e.g. 7d) I am getting the error "query processing would load too many samples into memory in query execution".
My query is
histogram_quantile(0.90, rate(http_request_in_seconds_bucket[7d]))

Answer: This error happens because Prometheus has a limit of samples it can process in memory.
I solved this with subqueries which was added on Prometheus 2.7.
This allows you to separately query smaller time intervals and then aggregate them together.
For example, I changed my query to multiple 24 hours subqueries and then averaged it together
histogram_quantile(0.90, avg_over_time(rate(http_request_in_seconds_bucket[24h])[7d:12h]))
There are other solutions:

Increase the number of samples it can process by changing the flag query.max-samples (not recommended)
Use Recording Rules - recommended over subqueries as it reduces the load on prometheus servers, but takes more efforts to set up.


blazor wasm how to inject from di into custom class

Question: is there a way to inject let say httpClient into my own custom class?
Just to be clear - i known how to use DI in blazor injecting into components or other services.
Just for testing its possibility.
i want to do something like just in code
protected override async Task OnInitializedAsync()
{
  GSP gsp = new GSP("db1","table1");
  gsp.get("users", ()=>{ do something with data}); // and this should call api and get users
}

so i have
public class GSP
{
    [Inject]
    public HttpClient httpClient { get; set; }
 ...
}

but it is null
i checked also ctor option
    public GSP(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

but then i have to pass this httpClient manualy that was injected into component for example.
i can do
  private HttpClient httpClient = new HttpClient { BaseAddress }

but then i have no BaseAdres. and heare we go again - easier way to get this BaseAddres in this place ? ;)
is it possible? or it is just 'bad practise' thats  why i canot find that?
thanks a lot !
Comment: Duplicate? https://stackoverflow.com/questions/65629065/c-sharp-asp-net-core-inject-attribute-usage-for-dependency-injection
Comment: close but no because i wanted to create objects myself and also get DI injecton as property of that class
Answer: by ctor and with HttpClientFactory you can do something like this :
public class Program
{
    public static async Task Main(string[] args)
    {
         var builder = WebAssemblyHostBuilder.CreateDefault(args);
         builder.Services
         .AddTransient<GSP>()
         .AddHttpClient().ConfigureHttpClient(httpClient =>
         {
              httpClient.BaseAddress = builder.HostEnvironment.BaseAddress;
         });
         await host.RunAsync();
    }
}

or without HttpClientFactory
public class Program
{
    public static async Task Main(string[] args)
    {
         var builder = WebAssemblyHostBuilder.CreateDefault(args);
         builder.Services
         .AddTransient(p => new GSP(new HttpClient { BaseAddress = builder.HostEnvironment.BaseAddress });

         await host.RunAsync();
    }
}

Answer: I think the explanations in this article are quite good:

Complex services might require additional services. In the following
example, DataAccess requires the HttpClient default service. @inject
(or the [Inject] attribute) isn't available for use in services.
Constructor injection must be used instead. Required services are
added by adding parameters to the service's constructor.

You are on the right track here:
 public GSP(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

But this is where you are mistaken

but then i have to pass this httpClient manualy that was injected into
component for example.

Don't pass anything manually. Instead inject your GSP class into your component.
in your razor component base class:
   [Inject]
    public GSP myGspService { get; set; }

or directly in the razor file:
@Inject GSP myGspService

If you want a new instance each time you use it, inject a GSPFactory class. You cannot inject non-registered parameters (such as your "db1" and "table1") using DI directly, the factory class would have to deal with that, or you would have to set them each timeyou create it..
in your razor component base class:
   [Inject]
    public GSPFactory myGspService { get; set; }

or directly in the razor file:
@Inject GSPFactory myGspService

and your factory class:
public class GSPFactory {
   Func<GSP> iocFactory;
   public GSPFactory(Func<GSP> iocFactory) {}
      this.iocFactory = iocFactory;
   }

   public GSP Create(string option1, string option2) {
      var gsp = this.iocFactory();
      gsp.Option1 = option1;
      gsp.Option2 = option2;
      return gsp;
   }
}

The setup could look like this:
Services.AddTransient<GSP>()
.AddTransient<Func<GSP>>(x => () => x.GetService<GSP>())
.AddSingleton<GSPFactory>() // (... plus httpClient etc)

factory class variant if you insist on having an injected property:
public class GSPFactory {
   HttpClient httpClient;
   public GSPFactory(HttpClient httpClient) {}
      this.httpClient= httpClient;
   }

   public GSP Create(string option1, string option2) {
      var gsp = new GSP(option1, option2);
      gsp.HttpClient= httpClient;
      return gsp;
   }
}

The setup could then simply look like this:
Services.AddSingleton<GSPFactory>() // (... plus httpClient etc)

In any case, you would always inject the factory, and get a new instance of GSP like this:
injectedGspFactory.Create("db1", "table1");

Comment: thx i updated my quastion because i simplified it a bit and i see now that that is also important - what if i want use own ctor like new GSP("db1","table1"); ? is it also possible? or this is limitation - i can DI this GSP as you posted but canot use own ctors?


Operators $A$ such that $e^A$ is norm preserving

Question: Let $X$ be a Banach space. $A$ a bounded operator. We can define the exponential of $A$ by
$$e^{A}=\sum_{n=0}^{+\infty}\frac{A^n}{n!},$$
which is also a bounded operator.
Is there any sufficient condition on the operator $A$ to ensure that $e^{A}$ is a norm preserving operator (isometry) i.e. $|e^Ax|=|x|$ for all $x\in X$ ?
If $X=\mathbb{C}$, we get this if $A=a\in i\mathbb{R}$. Maybe if my intuition is right, we get also this in the case  $X=\mathbb{R^n}$ and $A$ has all its eigenvalues purely imaginary.
Answer: The natural generalization of what you noticed in $\Bbb C$ is the condition $A^* = -A$ in any Hilbert space.
Comment: This works in a Hilbert space. I don't know what we can say in the case $X$ is only a Banach space.
Answer: It is sufficient to assume that $(A-\lambda I)$ is invertible for all non-zero real  $\lambda$, and that $\|(A-\lambda I)^{-1}\| \le 1/|\lambda|$ for all such $\lambda$. This condition is equivalent to the condition that $e^{tA}$ is norm-preserving for all $t \ge 0$.
This condition is stated in a way that holds for real or complex Banach spaces, and I believe it holds for closed, densely-defined linear operators, too. If the Banach space $X$ is complex, then this condition forces the spectrum of $A$ to be a subset of the imaginary axis, and it forces $\|(A-\lambda I)^{-1}\|\le 1/|\Re\lambda|$ for all $\lambda$ for which $\Re\lambda \ne 0$.
Notice that the $0$ operator trivially satisfies the stated condition.
If $B$ is a densely-defined selfadjoint linear operator on a Complex Hilbert space $X$, then $A=iB$ satisfies this inequality, which is evident from the spectral theorem.
If $A$ is a complex $N\times N$ matrix, then the stated condition forces $A$ to have a basis of eigenvectors with purely imaginary or 0 eigenvalues. However, not all such $A$ satisfy the stated condition.
It is not sufficient for $A$ to have imaginary spectrum, even though the condition I stated implies that $A$ must have imaginary spectrum. For example, suppose $A^{2}=0$ for some $n > 1$ and $A\ne 0$. The spectrum of $A$ is $\{ 0\}$. If it were enough that the spectrum $\sigma(A)$ were on the imaginary axis, then $e^{zA}=I+zA$ would have to be norm preserving for all $z \in \mathbb{C}$. This $A$ does not satisfy the stated condition because
$$
        (\lambda I-A)^{-1} = \frac{1}{\lambda}I + \frac{1}{\lambda^{2}}A.
$$
Reference: http://en.wikipedia.org/wiki/Hille%E2%80%93Yosida_theorem#Hille-Yosida_theorem_for_contraction_semigroups


How to get minutes and seconds(mm:ss) from a timedelta object in python

Question: I'm writing a code in which I have added Time duration for each utterance(given as list of durations for each utterance) and the result is a timedelta showing sum of duration of all utterances. I need the result in only minutes and seconds**(mm:ss)** format.
Code
<code>def add_time(timeList):
   sums = datetime.timedelta()
   for i in timeList:
      x = datetime.datetime.strptime(i, '%M:%S.%f')
      d=datetime.timedelta(minutes=x.minute,seconds=x.second,microseconds=x.microsecond)
    sums += d
    print(str(sums))
    return sums
add_time(['00:04.0', '00:15.2', '1:10.4'])
</code>
Output
The output is like this:
<code> 0:01:29.600000
 Out[148]: datetime.timedelta(0, 89, 600000)
</code>
How can I get minutes and seconds from a timedelta object?
Answer: something like this should work:
<code> "{}:{:02d}".format(*divmod(sums.seconds, 60))
</code>


Redis Client del function not being called inside a for loop

Question: I have been trying to call the redisClient.del function inside a for loop and the function is not returning any state.
studentSchema.methods.generateAuthToken = function () {
    let admin = this;
    let access = 'student';
    let token = jwt.sign({ _id: student._id.toHexString(), access }, HRCSECRET).toString();
    student.tokens.forEach(element => {
        console.log(element.token);
        redisClient.del(element.token, (err, result) => {
            if(err){
                console.log(err);
            }
            else{
                console.log(result);
            }
        })
    });
    student.tokens = [{ access, token }];
    return student.save().then(() => { return token; });
};

There is no console.log statement printed during the execution
Comment: What is `student.tokens` ? Are you sure that it contains something?
Answer: Did you try to check in Redis-cli is your stuff deleted?
Just a little refactor below
studentSchema.methods.generateAuthToken = async () => {
  // your code before
  const promises = []
  student.tokens.forEach(element => {
    promises.push(redisClient.del(element.token))
  })
  await Promise.all(promises)
  // your next code
}

Comment: appearently the Exact thing happened


Signing Apache Cordova Android app

Question: I'm trying to release an Android application using Visual Studio Tools for Apache Cordova 5.1.1
I create a keystore file and edit the build.json with the data for the keystore as shown here
I get errors
Command failed with exit code 1 ERROR building one of the platforms

Command failed with exit code 1 MDAVSCLI

When I rebuild the project I get
MSB3073 The command "platforms\android\cordova\clean.bat" exited with code 1

...\vs-mda-targets\Microsoft.MDA.FileMirroring.targets
What am I doing wrong?
Thanks.
Comment: It looks like clean.bat is failing to reset the state of the project. Can you try deleting the platforms\android directory and retry?
Comment: When I delete platforms\android directory the rebuild succeeds, but when I try to run the release it gives the first two errors again.
Answer: Can you try updating your Cordova tools to version 3? We made a fix that might address this issue. It's hard to tell without seeing the entire log (disclosure: I work for Microsoft).

Signing Apache Cordova Android app


Continuous convolution between two functions

Question: I'm studing for an exam and I'm stuck on a simple exercise about convolution between two functions. It says:
A system has a triangular impulse response (LSF) centered at the origin of the plane $h(x)=Λ(x)$. We input an image with two impulses, defined as $f(x)=δ(x-x_0)+δ(x-2x_0)$. Get the output of the system.
I was thinking to use this formula:  $\int_{-\infty }^{+\infty} f(x-x_0) h(x_0) dx_0$
So it would become:
 $\int_{-\infty }^{+\infty} (δ(x-2x_0)+δ(x-3x_0))  Λ(x_0) dx_0$
I don't know if it makes sense, so i'll appreciate any help.
Thank you.
Answer: I think you've misunderstood what $x_0$ is. It is a constant, not a variable, so you should not be integrating over it. The variable you integrate over in the convolution is a dummy variable that won't appear in the final answer, so it give a name that doesn't match any names you already have for variables. In this case, the convolution formula would written as $$(f\star g)(x) = \int_{-\infty}^\infty f(x-y)g(y)dy = \int_{-\infty}^\infty f(y)g(x-y)dy$$
Can you try writing the convolution again?
Comment: $Λ(x- x_0)+Λ(x-2x_0)$ ?
Comment: It would became: $\int_{-\infty }^{+\infty} (δ(y-x_0)+δ(y-2x_0)) Λ(x-y) dy$
Comment: Perfect! Now what does the sifting property of the delta say that integral should be?
Comment: That's exactly right. And in fact it shouldn't be unexpected at all because our system $H$ was LTI. So if the impulse response $H(\delta(x)) = \Lambda(x)$, then what is the output for a linear combination of shifted deltas?
Comment: It should be a linear combination of the impulse response, so a combination of the triangular function shifted like the deltas, right? I think I got it, thank you so much for your help!
Comment: You got it, and you're welcome!
Answer: Since response of system to $input=\delta(x)$ is impulse response and equal to
$$h(x)=Λ(x)$$
Input to the system is a summation of two shifted impulses
$$f(x)=\delta(x-x_0)+\delta(x-2x_0)$$
What's the Output of system ?
$$Output=f(x)\star h(x)=\int_{-\infty }^{+\infty} \Big(\delta(x-x_0)+\delta(x-2x_0)\Big) Λ(x)dx$$
By definition and properties of $\delta$ function we have:
$$\int f(x) \delta(x-x_0) dx=f(x_0)$$
So the final result will be:
$$Λ(x_0)+Λ(2x_0)$$


jquery - show/hide unique content with checkboxes

Question: I'm trying to show and hide content with checkboxes.
I have 7 types of fruit salad.
They are as so:
1. Apple
2. Orange
3. Pear
4. Apple-Orange
5. Orange-Pear
6. Apple-Pear
7. Apple-Orange-Pear
I want the customer to be able to select their fruit using the 3 check boxes to select the type of salad they want. If the customer chooses, apple I only want apple to show, if they choose orange, i only want orange to show. If they choose apple-orange, i only want the apple-orange fruit salad to show (not the single apple and orange). Same with the Apple-orange-pear fruit salad -- if this is selected, I only want that specific salad to show, not the individual fruits.
But my code selects all the fruit - so for example, if you checkoff apple, orange and pear, it shows all associated fruit, when I only want the apple-orange-pear salad to show (the one unique selection). Can anyone help me with this?
Here is my fiddle:
https://jsfiddle.net/daysable/41uusunm/
my code:

        <input type="checkbox" id="apple" name="colorCheckbox" value="apple">apple

        <input type="checkbox" id="orange" name="colorCheckbox" value="orange">orange

        <input type="checkbox" id="pear" name="colorCheckbox" value="pear">pear

Apple

Orange

Pear

Apple Orange Fruit Salad

Orange Pear Fruit Salad

Apple Pear Fruit Salad

Apple Orange Pear Fruit Salad

Thank you
Comment: Won't solve your problem, but you should close your `input` tags like this: ``
Comment: Also, when you post code, please try to avoid including space consuming things that are not relevant for the problem, like the CSS for the colors. It takes away focus. (Or maybe that is just me, I should stop nagging now.)
Comment: Sorry about that! I'll make a note for the future. New to posting here, so thank you for the tips!
Comment: @Anders that is xhtml requirement ... if use `` you don't close them although both ways work. `` is a `void element`
Answer: Your if statements have some issues. A few of your conditions made no sense like
if ($('#apple').is(':checked') && !$('#orange').is(':checked'))
    $('.fs-apple-orange.box').show();

which would show the apple orange box when apple was checked and orange wasn't. For the single fruits you need to check that the others are false.

$('.apple-orange-pear.box').show();
$('input[type="checkbox"]').click(function () {
    $('.box').hide();
    var apple=$('#apple').is(':checked');
    var orange=$('#orange').is(':checked');
    var pear=$('#pear').is(':checked');

 if (apple&&!orange && !pear) $('.apple.box').show();
    else if (!apple&&orange&&!pear) $('.orange.box').show();
 else if (!apple&&!orange&&pear) $('.pear.box').show();
    else if (apple && orange &&!pear) {
  $('.fs-apple-orange.box').show();
    }
 else if (!apple && orange && pear) {
  $('.fs-orange-pear.box').show();
    }
    else if (apple&&!orange&&pear) {
   $('.fs-apple-pear.box').show();
    }
    if (apple&&orange&&pear)  {
   $('.apple-orange-pear.box').show();
 }
});
.box {
    padding: 20px;
    display: none;
    margin-top: 20px;
    border: 1px solid #000;
}
.apple {
    background: #F00;
}
.orange {
    background: #F60;
}
.pear {
    background: #FF0;
}
.fs-apple-orange {
 background: #F66;
}
.fs-orange-pear {
 background: #0C9;
}
.fs-apple-pear {
 background: #066;
}
.apple-orange-pear {
 background: #00F;
}

        <input type="checkbox" id="apple" name="colorCheckbox" value="apple" checked>apple

        <input type="checkbox" id="orange" name="colorCheckbox" value="orange"checked>orange

        <input type="checkbox" id="pear" name="colorCheckbox" value="pear" checked>pear

Apple

Orange

Pear

Apple Orange Fruit Salad

Orange Pear Fruit Salad

Apple Pear Fruit Salad

Apple Orange Pear Fruit Salad

Comment: thank you so much. this makes much more sense. It's exactly what I wanted the experience to be.
Comment: I want to show all three checkboxes checked by default. And the customer can uncheck as they see fit. How do I go about doing this?
Comment: thanks so much, this is great. But is there a way to show the checks checked as default too?
Answer: $('input[name="colorCheckbox"]').click(function () {
        $('.box').hide();
        var a = $('#apple').is(':checked');
        var o = $('#orange').is(':checked');
        var p = $('#pear').is(':checked');

        if(a && o && p)
            return $('.apple-orange-pear.box').show();
        if(a && p)
            return $('.fs-apple-pear.box').show();
        if(o && p)
            return $('.fs-orange-pear.box').show();
        if(a && o)
            return $('.fs-apple-orange.box').show();
        if(a)
            return $('.apple.box').show();
        if(o)
            return $('.orange.box').show();
        if(p)
            return $('.pear.box').show();
});

$('input[name="colorCheckbox"]').click(function () {
        $('.box').hide();
        var a = $('#apple').is(':checked');
        var o = $('#orange').is(':checked');
        var p = $('#pear').is(':checked');

        if(a && o && p)
      return $('.apple-orange-pear.box').show();
        if(a && p)
      return $('.fs-apple-pear.box').show();
        if(o && p)
      return $('.fs-orange-pear.box').show();
        if(a && o)
      return $('.fs-apple-orange.box').show();
     if(a)
            return $('.apple.box').show();
        if(o)
            return $('.orange.box').show();
     if(p)
            return $('.pear.box').show();
});
.box {
    padding: 20px;
    display: none;
    margin-top: 20px;
    border: 1px solid #000;
}
.apple {
    background: #F00;
}
.orange {
    background: #F60;
}
.pear {
    background: #FF0;
}
.fs-apple-orange {
 background: #F66;
}
.fs-orange-pear {
 background: #0C9;
}
.fs-apple-pear {
 background: #066;
}
.apple-orange-pear {
 background: #00F;
}

        <input type="checkbox" id="apple" name="colorCheckbox" value="apple">apple

        <input type="checkbox" id="orange" name="colorCheckbox" value="orange">orange

        <input type="checkbox" id="pear" name="colorCheckbox" value="pear">pear

Apple

Orange

Pear

Apple Orange Fruit Salad

Orange Pear Fruit Salad

Apple Pear Fruit Salad

Apple Orange Pear Fruit Salad

Comment: @KristinMann does that answers your question completely? ot you need any information
Comment: I want to show all three checkboxes checked by default. And the customer can uncheck as they see fit. How do I go about doing this?
Answer: This will work no matter what fruits you have and how many of them.
jQuery(function() {

    jQuery("input[name=colorCheckbox]").click(function() {

        //Get a list of the checked fruits.
        fruits = jQuery("input[name=colorCheckbox]:checked").map(function() {
            return this.id;
        }).get().sort().join("-");

        //Hide all boxes.
        jQuery(".box").hide();

        //Show the relevant one.
        jQuery(".fs-" + fruits).show();

    });

});

Just make sure to have all the class names set up as fs-fruit1-fruit2, with the fruit names are sorted in alphabetical order (like fs-apple-pear).
On a side note, you should put all your script in the , and instead wrap it like this jQuery(function() { /* CODE */ });. jQuery will not run the code until the DOM is ready.
Also, if you only have one div per fs-... tag you might want to use it as an ID instead of a class, since matching by ID is faster than matching by class.
Here is the jQuery documentation on map.
Comment: as long as order is maintained between class name structure and order of checkboxes. Not always intuitive for some. Switching checkbox positions would make the whole thing fall apart
Comment: I was already working on the edit, but thanks for pointing that out. Both sharp and quick.
Comment: I considered a similar approach but seemed fragile, opted for array matching instead
Comment: Hm, didn't think about the problem of changing the order. Added a `sort()` to solve that. Perhpas not necesarry to sort, but I don't think there will be a thousand fruits so it should be fine.
Answer: A more scalable approach is to set the filter values in data attributes as json array on the box elements .

Pear

Apple Orange Fruit Salad

These can be read as arrays using jQuery data().
Then you can use generic array matching code that doesn't care what the specific values you use are, or how many checkboxes there are .... just that they match between checkbox value and array value
var $checks=$('input[type="checkbox"]');

$checks.click(function () {
    // create array of checkbox values
    var values=$checks.filter(':checked').map(function(){
        return this.value
    }).get();
    // hide all the boxes and start filtering for matches
    $('.box').hide().filter(function(){
        // read filter array from box element
        var filterArr = $(this).data('filters');
       // reject if array lengths differ
       if(filterArr.length !== values.length){
          return false;
       }
        // check for all values matching between checkboxes and box filters
        var isMatch = filterArr.filter(function(val){
             return values.indexOf(val) >-1
        }).length === values.length;

        return isMatch
     // show the matching elemnts
    }).show();
});

Now when you get a new item in the mix, you don't have to refactor the code, just follow the same html format
DEMO


Alternative definition for order-embedding

Question: I realize that the traditional definition for an order-embedding f is that
$a_1 \sqsubseteq a_2 \iff f(a_1) \sqsubseteq f(a_2)$
However, is it also fair to say that if $(A, \sqsubseteq)$ is a lattice, a definition for meet and this partial-order uniquely define one another:
$a_1 \sqsubseteq a_2 \iff a_1 \sqcap a_2 = a_1$
And so an alternative/equivalent way of saying f is an order-embedding might be:
$f(a_1 \sqcap a_2) = f(a_1) \sqcap f(a_2)$
Thank you! Any advice would be helpful.
Answer: Embeddings are functions from one structure to another which preserve the structure (and do no add additional structure to the image either).
For partially ordered sets this means, as you suggest that $a\sqsubseteq b\iff f(a)\sqsubseteq f(b)$. Lattices have more structure, so we can expect embeddings of lattices to preserve that structure. But note that this requires additional and explicit statements.
Consider the lattices $\mathcal P(X)$ and $\mathcal P(Y)$ ordered by inclusion, where $X=\{1,2\}$ and $Y=\{1,2,3,4\}$. Now define $f\colon\mathcal P(X)\to\mathcal P(Y)$:
$$\begin{align} &f(\varnothing)=\varnothing\\ &f(\{1\})=\{1,4\}\\ &f(\{2\})=\{2,4\}\\ &f(\{1,2\})=\{1,2,3,4\}\end{align}$$
It is easy to see why $f$ is an order embedding, but the lattice structure is all skewered. $\{1\}\cap\{2\}=\varnothing$ but $f(\{1\})\cap f(\{2\})=\{4\}\neq f(\varnothing)$.
So while we can define a lattice structure on $\operatorname{Range}(f)$, this is not the structure inherited from the structure on $\mathcal P(Y)$, so in some sense it's cheating.
To sum up remember the motto, if you want more, assume more.
Comment: Very helpful, thank you! I have not been careful enough.
Comment: Is there a term to use for my second definition (preserves meet, embeds meet)? You are saying that my second definition implies that f is an order-embedding, but is a stronger statement and goes further than simply saying it is an order embedding?
Comment: If you read a bit about Boolean algebras, in particular complete Boolean algebras, you'll quickly learn that these examples are abundant, and that there's is a difference between requiring that the subalgebra agree on the completions, or the maximal and minimal elements, and so on.
Comment: And yes, since the order itself is definable from the join/meet operations, respecting those would necessarily mean respecting anything definable from them, and in particular the order. (Recall that in a lattice you also have joins, not just meets.)
Comment: Thank you so much! I was able to prove the latter for a function f and somewhat carelessly said it was an order-embedding. Thankfully this is a stronger property and I should only need to tweak my explanation. Your example was very helpful in clarifying this for me!
Comment: You're most welcome!


What are the generators of $\mathbb{Z}_n$?

Question: This article says that the generators of $\mathbb{Z}_n$ are the elements which are prime with respect to $n$.
For instance, the generators of $\mathbb{Z}_7$ would be $\{\overline0,\overline1,\overline2,\overline3,\overline4,\overline5,\overline6\}$.
Why can $\overline1$ and $\overline0$ not generate the whole group? $\overline1+\overline1=\overline{1+1}=\overline2$, etc.
Thanks in advance!
Comment: $\bar 0$ is never a generator of $\mathbb Z_n$.
Comment: @Ayush: Just by the way, the subscript should go outside the `\mathbb` font. Compare `\mathbb{Z_n}` which produces
$$\Huge\mathbb{Z_n}$$
with `\mathbb{Z}_n` which produces
$$\Huge\mathbb{Z}_n$$
There are no lowercase letters in the `\mathbb` font, and even if there were, it wouldn't change the fact that only the `Z` is supposed to be in the `\mathbb` font, while the `n` is supposed to look the way it normally does.
Comment: What generates $\overline0$ then?
Comment: The subgroup $\{\bar 0\}$ of $\mathbb Z_n$.
Comment: Sorry I guess adding $\overline1$ $n$ times does.
Comment: That doesn't make sense, you can not say "adding $\bar 1$ n times generates something". Yes, $\underset{n}{\underbrace{\bar 1 + \dots + \bar 1}} = 0$, but $\bar 1$ (more precisely the singleton $\{\bar 1 \}$) generates a larger subgroup than just $\{\bar 0\}$ (in fact, it generates $\mathbb Z_n$ entirely).
Answer: You probably misunderstood the statement. It does not say that a set of generators is given by all elements prime to $n$. It says that any element prime to $n$ will generate the group. In particular, you are right that $\overline 1$ will be a generator. Note the $0$ is not prime to $n$ and $\overline 0$ is not a generator.
Answer: You are correct that the set $\{\overline{0},\overline{1}\}$ generates the group $\mathbb{Z}/n\mathbb{Z}$.
However, that's not what the question is about. The issue is which elements of $\mathbb{Z}/n\mathbb{Z}$ generate the entire group on their own -  in other words, for which integers $k$ does the set $\{\overline{k}\}\subset\mathbb{Z}/n\mathbb{Z}$ generate all of $\mathbb{Z}/n\mathbb{Z}$? The answer to that is "the integers $k$ that are relatively prime to $n$".
Answer: The element $\overline{1}$ generates the group  $\mathbb Z_n$ but not the element $\overline{0}$.
Notice  that the element $\overline{k}$ generates the group $\mathbb Z_n$ if there's $p$ such that
$$p\overline{k}=\overline{1}\iff pk\equiv 1 \mod n\iff pk+qn=1\iff k\wedge n=1$$
Comment: Is $k\wedge n$ supposed to be a notation for the gcd of $k$ and $n$?
Comment: Yes it is and it is a commonly used notation.
Comment: Good to know...
Answer: Be careful, $\overline0$ is never a generator ($0$ is not prime with $7$).
You are right that $\overline1$ is always a generator of $\mathbb Z_n$, as it is always prime with $n$.
You don't need $\overline0$, since you can reach it with $\overline1$ in this way: $\overline1+\overline1+\dots+\overline1$ (n times) $=\overline n=\overline 0$.
Comment: Yes I noticed that a little later. Thanks!


Dugundji topology textbook. Is this an error?

Question:
3.4. Theorem
  Let $W$ be well-ordered, and $\Sigma\subset I(W)$ any family with the following properties:
  (a) Each union of members of $\Sigma$ belongs to $\Sigma$.
  (b) If $W(a)\in\Sigma$, then also $W(a)\cup \{a\}\in\Sigma$.
  Then $\Sigma = I(W)$ and, in particular, $W\in\Sigma$.

$I(W)$ denotes the set of all ideals of $W$.
But isn't the following a counterexample to this Theorem?  Consider $W = \{1,2,3,4,5\}$ and $\Sigma=\{\{1,2,3,4\},\{1,2,3,4,5\}\}$. These meet the conditions (a), (b), correct?
But $\Sigma\neq I(W).$
Answer: Your $\Sigma$ does not satisfy condition (a): if you take the subset $\emptyset\subset\Sigma$, then the union $\bigcup\emptyset=\emptyset$ is not an element of $\Sigma$.  That is, the union of elements of $\Sigma$ consisting of no elements at all is not in $\Sigma$.
Comment: @Arbitrary When one says "union of members", you need some way of indexing the members you're taking the union over; that is, you need to pick a subset of $\tau \subset \Sigma$, and then write $\cup_{x \in \tau} x$. We are simply taking the empty union, indexed by the empty set.
Comment: The thing is, you can't talk about nothing. You can talk about **the set which has no members/elements**, but that is not nothing: it is a set, and it can be a member, or not be a member, of some other set.
Comment: Aren't the members of $\Sigma$ only $\{1,2,3,4\},\{1,2,3,4,5\}$? Is $\emptyset$ also a member?
Comment: $\emptyset$ is a subset of $\Sigma$, not an element.  Condition (a) means that if $A\subseteq\Sigma$ is any subset, then the union of all the elements of $A$ is an element of $\Sigma$.  Here I'm taking $A=\emptyset$.
Comment: the term 'member' means subset? I thought member = element. Otherwise, member = element, and 'nothing' also is member in this context?
Comment: Ok I understood completely. Thank you all.


Find $\lim \limits_{y\rightarrow\infty}\left (\ln^2y\,-2\int_{0}^y\frac{\ln x}{\sqrt{x^2+1}}dx\right)$

Question: I have difficulty with this limit. Where to start?
$$\lim_{y\rightarrow\infty}\left (\ln^2y\,-2\int_{0}^y\frac{\ln x}{\sqrt{x^2+1}}dx\right)$$
Comment: Sorry, in Italy it's 5 pm and I'm tired :-)
Comment: Is the integral from $0$ to $y$? Near zero, the integrand looks like $\log x$, which is not integrable...
Comment: @Siminore, $\log x$ is integrable near $x = 0$.
Comment: @Chris, By elementary solution what do you mean? Though demonstrated in somewhat unintuitive fashion, my solution involves only calculus-level manipulations except that it exploited the result $$\zeta(2)=\frac{\pi^2}{6}$$ of the Basel's problem. So I wonder how elementary level you are expecting.
Comment: @sos440: maybe that description isn't the best one. I mainly refer to resorting to only high scool calculus tools and a very short solution. One of my colleagues told me that it can be solved in a single row of notebook. I don't know if that is possible.
Comment: Another solution can be found [here](http://www.mathematica.gr/forum/viewtopic.php?f=9&t=6947&start=180)
Comment: @Chris: I also agree that this may not be a best one. But considering the direct relationship with dilogarithm or $\zeta(2)$, your requirement seems as tough as to require an elementary one-line solution of the Basel's problem. That's why I'm skeptical, but in case there really is a such solution, it will be incredibly fascinating.
Answer: By simple integration by parts, we have
$$ \int_{0}^{y} \frac{\log x}{\sqrt{1+x^2}} \; dx = \log y \, \sinh^{-1}y - \int_{0}^{y} \frac{\sinh^{-1}x}{x} \; dx. $$
Now by the substitution
$$x = \frac{u^2-1}{2u} \quad \Longleftrightarrow \quad u = x + \sqrt{x^2+1},$$
and the easy equality $ \sinh^{-1} y = \log \left( y + \sqrt{y^2+1} \right)$, we have
$$ \int_{0}^{y} \frac{\sinh^{-1}x}{x} \; dx = -\int_{1}^{y + \sqrt{y^2+1}} \left( \frac{2u}{1-u^2} + \frac{1}{u} \right) \log u \; du = -F\bigg(y+\sqrt{y^2+1}\bigg),$$
where
$$F(s) := \int_{1}^{s} \left( \frac{2u}{1-u^2} + \frac{1}{u} \right) \log u \; du.$$
Now simple observation shows that for $s > 0$ we have
$$F\left( \frac{1}{s} \right) = -F(s).$$
Since $y + \sqrt{y^2+1} \gg 1$ whenever $y \gg 1$, in view of the identity above, we may calculate $F(s)$ for $s = \left( y + \sqrt{y^2+1} \right)^{-1} \in (0, 1)$ instead since
$$ F\left(y+\sqrt{y^2+1}\right) = -F\left(\frac{1}{y+\sqrt{y^2+1}}\right) = -F(s) .$$
Now we introduce the dilogarithm function, defined by
$$ \mathrm{Li}_{2} (x) = \sum_{n=1}^{\infty} \frac{x^n}{n^2} = -\int_{0}^{x} \frac{\log(1-t)}{t} \; dt.$$
Then
$$ \begin{align*}
F(s)
&= \frac{1}{2} \int_{1}^{s} \frac{\log(u^2)}{1-u^2} \; (2udu) + \int_{1}^{s} \frac{\log u}{u} \; du \\
&= \frac{1}{2} \int_{1}^{s^2} \frac{\log v}{1-v} \; dv + \frac{1}{2} \log^2 s \qquad (v = u^2) \\
&= - \frac{1}{2} \int_{0}^{1-s^2} \frac{\log (1-w)}{w} \; dw + \frac{1}{2} \log^2 s \qquad (w = 1-v) \\
&= \frac{1}{2} \mathrm{Li}_{2}(1-s^2) + \frac{1}{2} \log^2 s. \qquad (w = 1-v)
\end{align*}$$
Thus plugging back, we have
$$ \int_{0}^{y} \frac{\sinh^{-1}x}{x} \; dx = \frac{1}{2} \left[ \mathrm{Li}_{2} \left( \frac{2y}{y+\sqrt{y^2+1}}\right) + \log^2 \left(y+\sqrt{y^2+1}\right) \right].$$
This shows that
$$ \begin{align*}
\log^2 y - 2\int_{0}^{y} \frac{\log x}{\sqrt{x^2+1}}\;dx
&= \log^2 y - 2 \log y \, \log \left( y + \sqrt{y^2+1} \right) \\
& \qquad + \mathrm{Li}_{2} \left( \frac{2y}{y+\sqrt{y^2+1}}\right) + \log^2 \left(y+\sqrt{y^2+1}\right) \\
&= \mathrm{Li}_{2} \left( \frac{2y}{y+\sqrt{y^2+1}}\right) + \log^2 \left(1+\sqrt{1+y^{-2}}\right),
\end{align*}$$
which clearly converges to
$$ \mathrm{Li}_{2}(1) + \log^2 2 = \zeta(2) + \log^2 2 = \frac{\pi^2}{6} + \log^2 2.$$
Numerical experiment shows that this converges to its limit relatively fast.

In fact, reflection formula for dilagorithm gives the following estimate.
$$ \log^2 y - 2\int_{0}^{y} \frac{\log x}{\sqrt{x^2+1}}\;dx = \frac{\pi^2}{6} + \log^2 2 - \frac{\log y}{2y^2} + O\left(\frac{1}{y^2}\right).$$
Comment: Perfect answer.
Answer: An alternative approach: Write $ \ln^2y $ as the integral of its derivative:
$$ \ln^2 y = 2\int_1^y \frac{\ln x}{x}dx,$$
and then combine with the integral that explicitly appears in $F(y)$, where $F$ is the function whose limit you want to calculate. Combining yields
$$ F(y) = 2\int_1^y\frac{\ln x}{x\sqrt{x^2+1}(x+\sqrt{x^2+1})}dx - 2\int_0^1\frac{\ln x}{\sqrt{x^2+1}}dx,$$
and so the limit is
$$L = 2\int_1^\infty\frac{\ln x}{x\sqrt{x^2+1}(x+\sqrt{x^2+1})}dx - 2\int_0^1\frac{\ln x}{\sqrt{x^2+1}}dx,$$
where the improper infinite integral clearly converges due to $\ln x/x^3$ fall-off as $x\to\infty$. This at least shows that the limit exists. As for evaluating those integrals...Mathematica yields a bunch of log, polylog and arcsinh terms eventually yielding the same result that @sos440 found in a much nicer analytic way.
Comment: Yes, this is a good point! Thank you.
Answer: Take $y=e^{1/t}$,then this limit becomes $$\lim_{t\to0^+}\frac{1-2t^2\int_0^{e^{1/t}}\frac{\ln x}{\sqrt{x^2+1}}dx}{t^2}$$.Now you can solve it easily using L' Hopital's Rule.
Comment: You already have the answer to this?
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Leftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\, #2 \,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$

The Question:
  $\ds{\lim_{y \to \infty}\bracks{\ln^{2}\pars{y} -
      2\int_{0}^{y}{\ln\pars{x}\over \root{x^{2} + 1}}\,\dd x} =\, ?}$

\begin{align}
&\color{#f00}{\lim_{y \to \infty}\bracks{\ln^{2}\pars{y} - 2\int_{0}^{y}{\ln\pars{x}\over \root{x^{2} + 1}}\,\dd x}} =
\lim_{y \to \infty}\bracks{\ln^{2}\pars{y} - \int_{x = 0}^{x = y}
{x \over \root{x^{2} + 1}}\,\dd\bracks{\ln^{2}\pars{x}}}
\\[3mm] = &
\int_{0}^{\infty}{\ln^{2}\pars{x} \over \pars{x^{2} + 1}^{3/2}}\,\dd x =
\lim_{\mu \to 0}\partiald[2]{}{\mu}
\int_{0}^{\infty}{x^{\mu} \over \pars{x^{2} + 1}^{3/2}}\,\dd x\
\stackrel{x^{2}\ \to x}{=}\
\half\,\lim_{\mu \to 0}\partiald[2]{}{\mu}
\int_{0}^{\infty}{x^{\mu/2 - 1/2} \over \pars{x + 1}^{3/2}}\,\dd x
\end{align}

With the identity
$\ds{\int_{0}^{\infty}{t^{a - 1} \over \pars{1 + t}^{a + b}}\,\dd t =
     {\Gamma\pars{a}\Gamma\pars{b} \over \Gamma\pars{a + b}}}$:
\begin{align}
&\color{#f00}{\lim_{y \to \infty}\bracks{\ln^{2}\pars{y} - 2\int_{0}^{y}{\ln\pars{x}\over \root{x^{2} + 1}}\,\dd x}} =
\half\,\lim_{\mu \to 0}\partiald[2]{}{\mu}\bracks{%
{\Gamma\pars{\mu/2 + 1/2}\Gamma\pars{1 - \mu/2} \over \Gamma\pars{3/2}}}
\\[3mm] = &\
\color{#f00}{{\pi^{2} \over 6} + \ln^{2}\pars{2}} \approx 2.1254
\end{align}


Bayesian MLPs using the MCMC methods - any tricks of the trade?

Question: Having used the NETLAB library for MATLAB to implement Bayesian Multi-Layer Perceptron (MLP) neural networks using MacKay's evidence framework, I am now experimenting with Markov Chain Monte Carlo (MCMC) methods using metrop() and hmc().  Does anyone have any advice for successful modelling using this approach (preferably using NETLAB), e.g. how to set the parameters to get good mixing and acceptably low rejection ratios etc?
Has anybody used the Metrpolois-Hastings or HMC samplers for applications of MLP neural networks?  I'm beginning to think that perhaps everybody just uses the evidence framework!
Comment: Do you know about Stan?
Comment: Stan was originally written in matlab, so it should be available (see [here](http://andrewgelman.com/2011/11/30/stan-uses-nuts/) where one complaint was that stan was only available in matlab)   I don't know how matlab works - perhaps there is a stan package or add-on or something.
Comment: @probability is logic, no, is there a MATLAB interfacte for it (I need to keep everything within MATLAB for consistency and replicability).
Answer: I have no experience relating to Bayesian Neural Nets and HMC, but with a related task.
That involved using neural nets as an unormalized probability model (i.e. an energy based model) where training involved generating "contrastive/negative samples" from the model distribution via HMC. I suppose the problem is somewhat similar, since both models share some factors.
(More specifically, ${\partial y \over \partial w}$ where $w$ is the first layer's weights and $y$ the output of the net. Bayesian neural nets have a $\partial L / \partial y$ in front, EBMs a different $\partial E / \partial y$ in front and a $\partial w / \partial  x = w$ at the end.)
Long story short: to get decent results using adaptive step rates to reach a desired acceptance rate was making a huge difference.
You can find some code here, but it is python. The approach is described in "Learning Deep Energy Models", Ngiam et al and there is a footnote on the exact settings for HMC.
Comment: THanks for the answer, I'll definitely look into adaptive step size thing, although I would prefer advice on getting the standard Metropolis-Hastings and HMC samplers to work.
Comment: In case you gather enough experience on this to answer your own question I would really appreciate. This is one of the classic areas where research papers do not explain the important details. (Also, thanks for the bounty :)
Comment: You're welcome ;o)  Will do, the main reason why I was asking is that I am working on a method that ought to make the MCMC approach easier, but I don't want to compare against a straw man, so I needed advice on best practice.  The response to the question suggests that perhaps people just don't use it at all, perhaps due to it still being a bit of a "black art".
Answer: Radford Neal's flexible Bayesian modeling toolkit (fbm) also allows you to play with the Monte Carlo methods and has neural network functionality built in.


Google PHP API not returning refresh token

Question: I am working on a web application that, among other things, reads the gmail of a signed in user.  I am using the Google PHP library to handle authentication, and I am able to fetch emails without problems.  The problem is that the access token expires after 1 hour. The documentation indicates that you should get a refresh token with the initial authorization, but when I call $client->getRefreshToken(), it returns null.
I understand that the refresh token is only returned the first time that  a user signs in.  While testing this, I revoked the authorization on the account, and then tried again, but it still does not give me a refresh token. What am I doing wrong?
Edit: I had a friend sign in with his personal Google account, which has never been used on the site, and still, no refresh token was given.
Source code:
Login.php: The first page
<?php
session_start();
require_once 'vendor/autoload.php';
$force=(isset($_GET['force'])&&$_GET['force']='true');
if(!isset($_SESSION['google_token'])||force)
{
    $client=new Google_Client();
    $client->setAuthConfig('/path/to/client_secret.json');
    $client->addScope('https://www.googleapis.com/auth/gmail.readonly');
    $client->addScope('https://www.googleapis.com/auth/userinfo.email');
    $client->addScope('https://www.googleapis.com/auth/userinfo.profile');
    $client->setState('offline'); //I realized that the mistake is here, see my answer below.
    $client->setApprovalPrompt('force');
    if($force)
            $client->setPrompt('consent');
    $client->setRedirectUri('https://example.com/doLogin.php');

    $auth_url=$client->createAuthUrl();
    header("Location: " . filter_var($auth_url, FILTER_SANITIZE_URL));
    die();
}
header('location: /index.php');
die();

doLogin.php: The Google Oauth page redirects here.
<?php
session_start();
require_once 'vendor/autoload.php';
if(isset($_GET['error']))
{
    session_unset();
    header('location: /error.php?error='.urlencode('You must be signed into Google to use this program.'));
    die();
}
$client=new Google_Client();
$client->setAuthConfig('/path/to/client_secret.json');
$client->setRedirectUri('https://example.com/doLogin.php');
$client->setAccessType('offline');
$client->authenticate($_GET['code']);
$access_token=$client->getAccessToken();
$refresh_token=$client->getRefreshToken();

$service=new Google_Service_Oauth2($client);
$email=$service->userinfo->get()['email'];
$_SESSION['email']=strtolower($email);

$_SESSION['access_token']=$access_token;
$_SESSION['refresh_token']=$refresh_token;
header('Location: /index.php');
die();
?>

Comment: Are you using it in localhost?
Comment: You might fins this useful: http://stackoverflow.com/questions/9241213/how-to-refresh-token-with-google-api-client and read the comments to the most upvoted answer because there's a good tip as well.
Comment: This is on a dev server I have.
Comment: @Zeke I looked through the comments, and I don't see anything that I think will solve the problem, though it is good to know.
Comment: I mean, not just the comments, read the answer too which is more important. It does explain how to properly refresh the token!
Comment: I checked the answer, and as far as I understand it, there is the assumption that the refresh token is recieved at the beginning and stored in a database.  I am not getting the refresh token at any point.
Comment: OK, I found my mistake.  I posted it in my answer below.
Answer: OK, so after looking around, and poking through the raw http, I found my mistake.  I was calling $client->setState('offline'); instead of $client->setAccessType('offline'); I fixed that, and now I am receiving the refresh token when I should.


FPDF issue while generating pdf with images due to PHP 'allow_url_fopen' setting

Question: I am facing a problem with FPDF while generating the PDF file with images as explained here. Finally I found the reason for this issue but I am not sure how to fix that one, can anybody suggest some good solution to handle that issue.
This problem is due to the allow_url_fopen setting of my server, if I enable that setting then the FPDF library is generating the PDF file with images also without any errors.
I am using this FPDF library for one of my client sites, he(client) disabled the 'allow_url_fopen' setting for security reasons and he is not intersted to enable that setting. how can I solve this issue with out enabling that setting of my server.
Comment: https://stackoverflow.com/questions/3177716/fpdf-error-missing-or-incorrect-image-file/66607028#66607028   try this for some solution.
Answer: You can use CURL  to open remote resources.
$curlHandler=curl_init();

curl_setopt($curlHandler, CURLOPT_URL, "http://youurl.com");

curl_setopt($curlHandler, CURLOPT_HEADER,0);

curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);

$output =curl_exec($curlHandler);

....

curl_close($curlHandler);

Comment: Yes Luis Melgratti, I've used the CURL to fix this issue. To solve my problem I'm creating a temporary file in my local system using the CURL and sending that local file path to the FPDF function. Even your code snippet is not useful exactly for fixing this issue, I got an idea to solve my problem after seeing your answer. Once again thanks for your response...
Comment: Yeah thanks Luis Melgratti, CURL may do the trick to handle this issue. I am planing to get the image using CURL and store that in a temporary file before adding that image to PDF file using FPDF.
Answer: I had similar problem, the fix for it without setting allow_url_fopen on was
1. move the image to the server hosting the script
2. assume the image is imagefile.gif inside a folder called images
3. access the image in my script doing this  $_SERVER['DOCUMENT_ROOT']."images/imagesfile.gif"
Comment: This one worked for me, thank you for posting the solution.
Answer: Honestly, your best bet is going to finding another way to generate PDFs.  FPDF has had only one update since 2004, and no longer seems to be actively maintained.
Some other pure-PHP options include TCPDF and Zend_PDF, both of which seem to be actively maintained and supported.
You should also give some consideration to other PDF generation techniques.  For example, there are quite a few HTML-to-PDF converters, some commercial, some open source.  wkhtmltopdf, for example, uses the WebKit rendering engine (the one that Safari and Chrome use) to create PDFs.
Comment: Thanks Charles, I am also thinking to use some other PDF generator instead of FPDF library, but my client preferred to use the FPDF. Anyway I will try to convence him(client) to go for some other libary, can you please suggest me one good PDF generator so that I can replace the FPDF.
Comment: I recommended no less than three above.  :)
Comment: Furthermore, if your client is both telling you what libraries to use and also telling you what configuration the server must have, despite the library he told you to use *requiring* a different configuration, I expect that you may wish to either educate or stop working with the client.  He or she is probably more trouble than he or she is worth.
Comment: FPDF has been updated many times since 2004. The latest version is v1.84 (2021-08-28)


Bitmap class error in c# (The parameter is not valid)

Question: I want to convert an image to bitmap format. Here's the code i wrote :-
Bitmap bmp = new Bitmap("c:\\images\\a10.png");

The parameter image is taken from the function parameter. It takes a full path with filename. When i run, an error pops up showing "The parameter is not valid". But this class accepts filename as constructor.
Comment: Is `image` a System.Drawing.Image?
Comment: @paqogomez No it is just a string variable, that accepts a fully qualified path with filename.
Comment: GDI+ exceptions are not very good.  It can mean several things: bad filename, bad file content, file inaccessible or doesn't fit in memory.
Answer: The image path you set is not correct.  That image does not exist at that location.
Check your path to verify the image.
This code will properly save a png to a bmp provided the png exists.
Bitmap bmp = new Bitmap("c:\\images\\a10.png");
bmp.Save("c:\\images\\a10.bmp");

EDIT:
The above worked for me, but here is another way:
Image bmp = Image.FromFile("c:\\images\\a10.png");
bmp.Save("c:\\images\\a10.bmp", ImageFormat.Bmp);

Comment: That Save() call actually saves the image in the PNG format, the default format if you don't explicitly specify the image format.  It does *not* pay attention to the filename extension.  So your code leaves a .bmp file behind that is not actually a BMP file.  Pretty bad idea.
Comment: @HansPassant I thought so too until I tried it.  Did it myself, and it saved a bitmap.
Comment: I used .Net 4.5.  @Sandesh, HansPassant is correct, there must be something wrong w/ that file you are trying to load.
Answer: The simplest way ever is:
Bitmap bm = new Bitmap("C:/images/a10.png");


How to check the success of AJAX request for following chunk of code using Drupal.ajax()

Question: The following code makes and AJAX request using Drupal.ajax() function. What I want is to have some kind of callback that will be executed once the request completed, basically the 'success' parameter of usual jQuery AJAX request. Adding success = function(request, status) parameter doesn't help either, or maybe I did something wrong ther. So how could I get a success callback to this request?
var ajaxSettings = {
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
};
var req = new Drupal.ajax(null, popContClass, ajaxSettings);
$(popContClass).trigger('add_event');

Answer: Could you provide more information on why the success function didn't work for you or what code you were using for it? This should work exactly like ajax settings in jquery Ajax since its just a passthrough, so your code would be something like this in your js:
$.ajax({
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
    success: function(){
       $(this).html("woot.");
    }
});

Answer: In order to call javascript commands that are invoked via Ajax framework commands, Drupal uses a success callback (see the code in misc/ajax.js on HEAD of 7.x branch). Therefore if you specify your own success callback in settings for Drupal.ajax, no Drupal Ajax framwork commands will be executed.
In order to execute a custom code in success callback and leave Drupal Ajax framwork workings intact, you need to override the default Drupal Ajax framework's success callback with the one that executes both your code and that of Drupal Ajax framework, but you need to create Drupal.ajax object first.
Example:
var ajaxSettings = {
    // your settings here
};

// Initiate Drupal.ajax object
var req = new Drupal.ajax(null, element, ajaxSettings);

// Override success callback
req.options.success = function (response, status) {
  // Place your code here
  // your_code_here();

  // Proceed with default "success" callback code from Drupal Ajax framework

  // Sanity check for browser support (object expected).
  // When using iFrame uploads, responses must be returned as a string.
  if (typeof response == 'string') {
    response = $.parseJSON(response);
  }
  return req.success(response, status);
}

// Trigger event here

Another (and technically better) option is to call "success" callback code directly using call() method. This avoids code repetition.
var ajaxSettings = {
    // your settings here
};

// Initiate Drupal.ajax object
var req = new Drupal.ajax(null, element, ajaxSettings);

// Override success callback
req.options.success = function (response, status) {
  // Place your code here
  // your_code_here();

  // Call original method with main functionality
  Drupal.ajax.prototype.success.call(req, response, status);
}

// Trigger event here

Credit for the last approach goes to asghar as he described it in related topic on drupal.org.


How does a symphony orchestra play in such perfect harmony?

Question: I'm talking about live performances. I respect all musicians who allow us to enjoy beautiful art of music. The number of musicians in a modern symphony orchestra may be up to 100 and each person has a different job. They are all important for the orchestra. However, this is a lot of people. I believe the more people playing in the orchestra, the greater risk of failing. How do they accomplish a performance without any of them messing up?
Comment: If one of many messes up, it's *often* - not always - less noticeable than if one of a few messes up...
Answer: The string players in a symphony orchestra have a LOT of notes to play, often intricate passage-work at high speed.  The odd 'domino' is almost inevitable - but there are typically  8 First Violins, 8 Second Violins - everyone DOESN'T have a different job!  (And just occasionally we hear a top-class orchestra which has had ample rehearsal time and NO-ONE is 'faking it' in the tricky bits.  It's a wonderful thing.)
Outside the fiddle section, everyone is expected to (and capable to) play every note correctly.  Of course, there's the occasional mishap.  But it's rare to hear one with a good orchestra.
Of course, there are plenty of not-so-good orchestras :-(
Comment: Yes. An important skill for a classical orchestral string player is to hush over notes that aren't really 100% on spot in a way that still blends in, so the whole section sounds about correct. That same skill however tends to drive musicians crazy who try to play other genres with a few string players.
Answer: Amateurs are messing up rhythmically, embouchure, accidentals, bow leading, concentration, chatting, breathing, phrasing, intonation ...
profis shouldn't! They are trained, payed and if they mess up, they are fired. There's an enorm pressure and concurrence.

the order and structure in music and composition/arrangement is composing and arranging the order and structure in the body of mind of hundreds of people.

There's a flow in the music  - rhythmically and melodic - that keeps the whole orchestra together.

The conductor - inspired by the artwork - inspires the musician by the movements of his hands, the stick, his face, his eyes, his eyebrows, mouth, lips, tongue, his head, his whole body.

There are voice leaders in each section who are responsible for the mental presence of their colleagues and who coordinate the bow leading, the phrasing and breathing.

The concertmaster  (1st violinist nearest the conductor's desk) - assisted by the oboe - is responsible for the tuning.

Each musician has to be maximally prepared and to know his part.

Each musician is contributing his best and has learnt to communicate and express his intensions by his tone and his gestures. (Have a look at the  percussionist playing the cymbal or the triangle!)

There is a more or less strict hierarchy (written or unwritten) from the conductor, soloist, concert master, voice leaders, percussionist to the single musicians.

The unwritten hierarchy is formed by the  ranked position,  by the ancienity and the virtuosity of the members.

So the reason of the fact that there's not a lot of mess is the sum of  a good communication and interaction, gestures, positive group dynamic, motivation, competition, sympathy, ability and quality in practice and the will to do something beautiful for god.
Where one of these points lacks there will be a mess and you'll miss the good spirit and may not be touched.
Watch and listen to this:


Views - Filter "Content: Authored by" to show only content by anonymous users

Question: When filtering content in Views using the filter Content: Authored by, you get these choices:

For the username, I typed "Anonymous", which gave me the UID of 0.
However, when I click Apply (All Displays), I get this error:
There are no entities matching "(0)".
Is there a way to filter a view in Drupal 8 to only show content posted by anonymous users?
Answer: Filter by User ID, is equal to 0.


Epsilon/lambda of simple function

Question: In my homework I have the following function:
$u(x)=\sum_{n=1}^\infty \frac{1}{n^2(n+1)}1_{[-n,n]}$
I want to show that $\lambda(\{u\geq \epsilon\}) \leq \frac{2}{\epsilon}$
I have tried doing the calculations in Excel and it is indeed true.
But I am out of thoughts on how to show this. Can anyone provide some help/hint? Thank you
Answer: $\int u(x) dx=\sum \frac {2n} {n^{2}(n+1)} =2\sum (\frac  1n -\frac 1 {n+1})$. This is a telescopic sum and you get $\int u(x) dx=2$. Hence $\lambda(u \geq \epsilon) \leq \frac 1 {\epsilon} \int u(x)dx=\frac 2 {\epsilon}$.
I have used the following standard argument: $\int u(x)dx \geq \int_{u \geq \epsilon} u(x)dx \geq \int_{u \geq \epsilon} \epsilon dx=\epsilon\lambda (u \geq \epsilon)$
Comment: How do you know that $\lambda(u\geq \epsilon)$ is less than the integral divided by epsilon? I cannot see where this comes from
Comment: @Daniel I have included a proof. This inequality even  has  name: it is called Chebyshev's inequality.
Comment: Very cool! Now I understand - and interesting fact to know

Epsilon/lambda of simple function


Getting Feed Aggregator to ignore certain incoming data

Question: EDIT: So originally I posted the below, but I've found other issues and I have some more information. I noticed today that sometimes the links are wrong as well but correct when I view the feed. I looked at the XML being sent by the feed we're bringing in and for one thing, the extra timestamp is being sent in a tag called <updated>. I'm not sure why it's being appended to the body text though. Similarly, other tags are being interpreted/appended in such a way as to mess up some other things.
So my new question is: is there any way to have more control over how feed aggregator is arranging this incoming stuff? I want to get rid of that stuff from <updated> and a couple of other tags and tell it to link the header with the appropriate link (right now it doesn't always do that).
Previous Post text:
In Drupal 7 I've got a view to show some news items that another developer set up through aggregator. The fields are Link, Title, Timestamp, and Body (although Link is hidden; long story that doesn't seem to affect this). Everything looks good except there's an extra timestamp at the end of the body text. Here's an example:

Orange County (CA) Register SEILER: Legislature could ignite rush to smuggle cigarettes
Wednesday, August 19, 2015 - 11:19
But higher taxes here would push us in the direction of New York City, meaning more smuggling, more crime and less policing... California already has the nation's second-lowest rate of tobacco use, after Utah. It should leave higher taxes and other nann 2015-08-19T15:19:16+0000

The '2015-08-19T15:19:16+0000' is what I want to get rid of. I have looked all around but I'm not able to figure out what's causing this. I thought maybe it had something to do with the feed we're using but I looked at the link (http://www.tobacco.org/tagged/new-york.atom) and it doesn't seem to include this.
I'm fairly new to Drupal but I did try to figure this out on my own and I'm at a loss. After extensive Googling I can't even find another example of this happening so I know I'm missing something. Any help is greatly appreciated; thanks.
Answer: OK, so I'm considering deleting this but it was such a source of frustration for me I guess I'll leave it up in case someone else ever comes across this. This answer, to me, seems like more a workaround (mainly because I am still lacking a basic understanding of why it's happening) so if anyone else has a better answer or more information please do post your own answer.
It seems like you can't have complete control over how Views or Aggregator arranges elements from the XML feed. It also seems (from my fruitless Googling) that this isn't usually a problem. I don't really know if this is an issue with how the RSS feed we have to use is configured or if it's a Drupal thing but I know the answer is in gaining control over where and when the different XML elements appear.
Most people seem to use a module called Feeds to gain control over this type of thing (and do other stuff). From superficially looking into it, it seems like it could fix my problem but it creates a separate node for each incoming item, which is not ideal for my special case. The feed on the site I'm working on just keeps up with the latest 20 items and then discards them so I didn't want to have to deal with a separate node for each thing.
I've decided to try a different module called Views RSS which sounds like it can simply solve my problem (here's some more info). I haven't tried it yet but it looks promising. Thanks to anyone who read this and to anyone who might be able to contribute in the future.


procedure/protocol for ensuring the decency of a new IP address

Question: According to the comments on is it possible to get a bad IP address when setting up a new VPS? one can't assume that a new VPS IP address is decent.  So how do I ensure (before I start installing software and running services) that the IP is decent?
Is there a checklist of things to inspect?  Are there services to use to determine whether an IP is good or not, is there one service that is sufficient on its own?
Answer: IP-address "reputation" is as far as I know only a concern for reliable e-mail delivery.
You can easily find online query tools for such as https://mxtoolbox.com/blacklists.aspx  for public blacklists. If your new IP-address is listed in one or several that is probably a bad sign but when it is not, then there is no guarantee that it's history is good either.
If your IP is listed in a blacklist you may see it disappear automatically or there may be an appeal procedure where as the new operator you can request removal.
Since a clean inbox is quite an important competitive edge most of the large email providers don't disclose how they achieve that, although they certainly won't rely on public blacklists alone (or at all).  In the end  you can only determine if your messages will arrive in the intended recipients Inbox by sending them messages.
Before you start sending mail : configure your server correctly by reading these related Q&A's
How to send emails and avoid them being classified as spam?
Prevent mail being marked as spam
If you have neither the time or resources to build up a good sender score (when you relative frequently switch providers and/or change IP-address) consider using a transactional e-mail provider to avoid that hassle.


Derive the weak form for nonlinear problem.

Question: Let the equation be $$\frac{d^2 y}{dx^2}=\frac{y}{1+y}$$
For finite element formulation how to get the weak form? The major problem being the nonlinear rhs.`
Answer: Let me rewrite your expression as
\begin{align}
y_{xx} = \frac{y}{1+y}\Leftrightarrow y_{xx} +yy_{xx} -y = 0
\end{align}
Since
\begin{align}
\Bigl(\frac{y^2}{2}\Bigr)_{xx} =  (yy_x)_x = y_x^2+yy_{xx} \Leftrightarrow yy_{xx} =
\Bigl(\frac{y^2}{2}\Bigr)_{xx}-y_x^2
\end{align}
you can rewrite the first expression as
\begin{align}
 y_{xx} +yy_{xx} -y = 0
\Leftrightarrow
y_{xx} +\Bigl(\frac{y^2}{2}\Bigr)_{xx}-y_x^2-y = 0
\end{align}
Assume, that $\phi^i$ are our (standard) testfunctions (which vanish on $\partial \Omega$). For the weak formulation we project onto the testspace. Let $\Omega$ be our domain, we then have for all $i$
\begin{align}
&\int_{\Omega}\Bigl[ y_{xx} +\Bigl(\frac{y^2}{2}\Bigr)_{xx}-y_x^2-y \Bigr]\phi^i\,dx = 0\\
\Leftrightarrow&
-\int_{\Omega}\Bigl[y_x+\frac{y^2}{2}\Bigr]\phi^i_x\, dx -\int_\Omega \Bigl[y^2_x+y \Bigr] \phi^i\,dx=0
\\
\Leftrightarrow &
\int_{\Omega}\Bigl[y_x+\frac{y^2}{2}\Bigr]\phi^i_x\, dx +\int_\Omega \Bigl[y^2_x+y \Bigr] \phi^i\,dx=0
\end{align}
Now you have only derivatives of order zero and one and can use $y\approx y^N$ as it is always done with FEM.


Reduce Boolean Expression

Question: Note:
A B = A and B
A + B = A or B
The expression:
r = a̅ c̅ b + a̅ c b̅ + a c̅ b̅ + a c b

Simplify?
Answer: It is not possible to optimize this expression further and reduce the number of terms.
The Karnaugh map:
             ab
       00  01  11  10
      +---+---+---+---+
   0  | 0 | 1 | 0 | 1 |
c     +---+---+---+---+
   1  | 1 | 0 | 1 | 0 |
      +---+---+---+---+

There are no adjacent 1 terms which can be merged into minterms with fewer literals. In fact, the expression is the three-input exclusive or of a, b and c. Output r is true if an odd number of inputs is true.

Reduce Boolean Expression


CSS span height 100% inside table

Question: I've got a table.
Inside the table I've got available,
but it seems the height doesn't cover the whole table row.
html:

Available
Nose to mouthFrown Lines

css:
.list_table thead th, .list_table tbody td { border:1px solid #D3D9CB;  font-size:12px; position:relative !important;}
.available { background:#98AEB3; display:block; height:100%;}
.booked { background:#F2AE30; }

image is attached:
Comment: We can see on the image that it's only covering the height of the text, so you can't get a same height for all elements if some use one lines and other more.
Answer: A and SPAN are not block elements, therefore they shouldn't have width and height. Also, giving to height a value of 100% isn't interpretated the same way in all browsers.
As you seem to just want to change the background color of the content of the cell, I'd suggest you give the classes .available and .booked to the TD instead of the A tag.
Comment: Where a and span are not block elements, the OP has changed this in CSS.
Comment: And if you want the link to cover the whole cell (working when you click anywhere in the cell), remove the link and add a onclick function on your cell.
Comment: he does have `display:block` on the `a` in his CSS. But I do agree, that best solution is to put the `available` class on the `td`, instead of putting on the anchor tag.
Answer: if
.available { background:#98AEB3; display:block; height:100%;padding:0;margin:0;}

doesn't help, try adding:
.available { background:#98AEB3; display:block; height:100%;line-height:18px;}

play around with the line-height pixels to tweak it, should work.

CSS span height 100% inside table