Glossary of Guitar Effects

Question: There are numerous effects options available to the guitarist, especially the electric guitarist. This question is intended to gather and cultivate a set of answers to questions in the form of:

What is insert guitar effect here for? How does it sound?

Please create a single answer for each effect and feel free to edit answers to make them more comprehensive and / or accurate.
It might also make each answer more useful if there were an example listed of a good representative recording of the effect.
Comment: It would be extremely useful to have at least one example of a good example of each effect and, where appropriate, of some combined effects. That way, perhaps people could work backwards from "I want to sound like *insert guitarist here*.
Comment: I am creating some "stub" answers intended to be improved and updated by those more expert than I. This question is a result of discussion in the comments of another question.
Comment: could we also make tags fro these that have this info?  maybe  effects-compression, or more hierarchicallike: effects-modulation-chorus.
Answer: Delay
Delay is an effect in itself, and also the basis of some of the other effects1.
Delay is simply the effect of playing the input signal some time later than it was fed into the device. Delays can be as short as a couple of milliseconds, as long as a bar, or more.
Usually, but not always, the delayed signal is combined with the original signal, because players want to hear what they play the moment they play it. Often it is mixed such that the original signal is louder than the delayed signal.
Originally delay was achieved using a loop of magnetic tape - first on improvised arrangements with a reel-to-reel recorder, and later on dedicated machines. The tape would pass through a recording head, then a playback head, then an erase head. The timing of the delay could be adjusted by moving the heads, or changing the speed of the tape. Tape adds its own colour to sound, so the echo would have that added warmth.
Later, analogue circuits were developed to achieve delay, first with tubes, then with transistors, each of these adding a certain colour to the delayed signal.
Digital delay inevitably followed, and of course, now we have digital delays which attempt to model the effects of the analogue devices of history.
When the delay is very short, the signals tend to interfere with each other in interesting ways -- see Phaser and Flanger.
When the delay is slightly longer -- close enough to still be considered "on the beat" -- you get what is known as doubling echo. This sounds similar to having two instruments playing in unison. The delay is simulating the slight difference in timing two human players would have.
Chorus is a variation on doubling echo, in which the delay varies -- the tape loop speeding up and slowing down continually. This means your "virtual" duet partner is slightly off time by a varying amount, and also slightly off-pitch by a varying amount. See the separate answer on chorus.
When the delay is longer still -- long enough that you begin to be able to hear it as a distinct note -- this is known as slapback echo. It's an effect frequently heard in rockabilly guitar and the "skanking" guitar parts of reggae.
When the delay is even longer, delay becomes a melodic tool -- you are effectively duetting with your earlier self. Many U2 songs, e.g. "Where the Streets Have No Name", are built around this effect.
It's common to feed the delayed signal back into itself so that you get echoes of echoes, each (usually) quieter than the last.
Using this fed-back delay on short delays creates a crude reverb effect. With longer delays, it becomes a rhythmic/melodic effect. For example, it's common to add delay to parts of drum patterns to create a complex rhythm part.
With analogue delay (and simulations thereof), each subsequent echo is not only quieter, but also more distorted. Dub reggae tracks often make prominent use of this effect -- look out for the effect where the engineer momentarily turns a knob so that the echoes get louder instead of quieter, surging and distorting before he turns it back down again so they can die away.

1Note that no signal processing is instantaneous, so every effect adds some small delay. For digital effects, this is the measurable and sometimes notable latency of something millisecond-ish (hopefully not more than a few ms). In simple analogue effects like distortion it's at most in the nanosecond range and basically neglectable. Any equaliser/filter component also introduce phase delay, which can be interpreted as delaying various frequencies by different amounts; but this too is normally not noticeable and works quite differently from a digital delay.
Answer: Gate / Noise Cancellation
A gate is used to silence the output if the input signal is quieter than a configured level.
Noise Cancellation is a common application of a gate. By setting the cutoff level to a level that is louder than the buzz and noise when no note is being played, yet quieter than the quietest note that you will play, it suppresses the buzz and noise when you are not playing.
A poor quality device, or one with the cutoff set too high, can cause notes that you wanted to be heard, to be suppressed.
More sophisticated gates will allow you to adjust the response curve -- how the volume ramps up around the cutoff point -- and its response time -- how quickly it turns the volume up when it detects a loud enough signal.
It can sometimes be useful to trigger the gate using a different signal from the one it is gating. For example you might have a guitar line pulsate in time to a drum.
Comment: One type of "effect" I've thought would be useful to have in a multi-pedal, though I've not seen it, would be to have a configurable automatic gain control (level compression) which would be applied before a distortion effect, followed by a gain adjustment after the distortion which would undo some or all of the effect of the previous AGC.  For example, things might be set up so that playing at a level of -20dBm would boost the signal by 21dB (clipping slightly) and then reduce volume by 20dB, while playing at -10dBm would boost by 12dB (clipping a bit more) and then reduce by 12dB.
Comment: As it is, it seems most distortion effects have a fairly small "sweet spot" of levels where they work well, and cause dynamics in one's playing to translate primarily into changes in timbre rather than volume.
Answer: Chorus
Chorus is an effect that copies the input signal passed to it, modulates the pitch of it by some configured parameters, and stacks it back on top of the original signal.
Originally, the motivation would have been to simulate the sound of two singers -- the second being very slightly delayed by a gently varying amount, and at not precisely the same pitch, by a gently varying amount.
However once the technology had been created, people experimented with the parameters, and by varying the speed faster, and by a greater degree, achieved a distinctive sound all of its own.
Choruses (Chori?) come in mono, stereo, and true stereo versions, and a good one will provide lots of control across the depth and speed of the modulation desired. In the case of a mono unit, the aggregate tone produced by the circuit is flattened and passed through a single jack, where as a stereo (sic) unit will pass wet and dry signals through different jacks. A true stereo chorus unit will produce a true stereo signal, where the effect is mixed properly into left and right channels.
Answer: Octave
Octave effects take the input signal and produce synthesized tones that are one or more octaves above or below it.  They can be blended in with the input signal to harmonize with it in real time.  The effect can be synthesized by monitoring the waveform of the input and multiplying or dividing the observed frequency by, for example, 2 (to go up or down an octave) or 4 (to go up or down two octaves).  This takes advantage of the fact that tones that are an octave apart have a 2:1 frequency relationship; the frequency of the tone one octave higher than a root tone is always double the frequency of the root tone.
Because they're acting on the monitored waveform, octave effects sound best on, and are meant to be used for, single-note riffs.  For this reason, they are popular with many bass guitarists and soloists.
Answer: Reverb
Reverb is the effect of playing a sound in an enclosed space, or a simulation of that effect. The sound travels from the source to your ear directly, but it also bounces off surfaces in the room to reach your ear, each reflection arriving at a different time, with different frequencies lost.
If you play with no effects, in a room full of soft surfaces which absorb sound, it can sound very lifeless and unnatural. Indeed, such a room is described as acoustically "dead".
If you play in a room full of hard surfaces, the reverberations add interest and colour to the sound. Such a room is often described as "lively". However, taken too far, the reverberations can overpower the original sound and make everything sound mushy.
The ideal is to find the sweet spot between these two extremes.
Clearly, when playing live rather than recording, the room you are in will create its own reverb. Live performance spaces are often prepared with a combination of acoustically absorbent and reflective materials to achieve the desired balance. Sometimes this means hi-tech purpose made fittings made of special materials. Often it's just judicious arrangement of curtains and rugs, combined with bare walls.
However it is still often desirable to apply artificial reverb as an artistic effect. Think of the lead guitar in Chris Isaac's Wicked Game; drenched in reverb.
Chamber reverb is how "artificial" reverb was originally achieved. The signal is played through a loudspeaker in a dedicated, soundproofed room, and picked up by microphones in that room. Chambers like this are a feature of high-end recording studios.
Plate reverb and spring reverb were the first attempts to simulate reverb in a portable device. The plate and the spring, respectively, are made of metal and attached to a transducer. The signal is fed to the transducer, which causes the plate or spring to vibrate. Reverberations bounce around the plate or spring. A pickup at the other end, converts the spring or plate's vibrations back into an electrical signal.
Plate and spring reverb, of course, are distant approximations of room reverb, but as with many artificial effects, they became popular in their own right.
Early Digital reverb used a large number of digital delays, at a mixture of volumes and timings.
Today, digital delays can simulate real rooms, and of course they also simulate plate reverb and spring reverb.
Answer: Compressor/Limiter
Compression is used to reduce the dynamic range of a signal. It can be used at the top of the amplitude range, to reduce the volume of a specified range of inputs, or at the bottom of the amplitude range, to increase the volume of a specified range of inputs.
In the case where a compressor is used to reduce volume it may be referred to as a limiter.
A more in-depth description can be found on this question: What Does a Compressor Pedal Do?
Answer: Boost
Boost is an effect which boosts the volume of an input signal, in order to assure that the amplifier is driven beyond its regular dynamic range and thus will produce clipping and thereby distortion. Boosts are very useful for tube amp players who wish to increase the gain on their amplifier without having to modify the tone the way a traditional overdrive or fuzz pedal would. A boost is often measured by how transparent it is--although there are some on the market (such as the Katana by Keeley and the EarthTone by NOC3) that employ JFET designs to produce additional "dirt" when engaged to add a subtle fattening effect to the boost.
Note that any pedal with a volume knob that past unity gain* can function as a boost. For example, turning a volume control past unity gain on something as benign as a Chorus pedal will produce additional distortion from a tube based amplifier.
*Unity gain is the position on a volume control where the input level is equal to the output level. Typically this works out to be at about 1 O'clock on most pedals.
Answer: Distortion
One of more commonly known effects for musicians is distortion. It falls into the family of effects sometimes referred to as "dirt" boxes: Distortion, Overdrive, and Fuzz. In simple terms, it is cutting the top and bottom of the sound wave off using a technique known as "hard" clipping to create a more square shaped wave instead of the more natural sine wave formation. A solid explanation on the techniques and methods of creating different types of distortion can be found on Wikipedia.
Comment: No offense, but I may edit this to remove the wiki reference and expand on what Distortion (more commonly referred to as overdrive) is. I sometimes feel dirty whenever I see a wiki link :D.
Comment: @Jduv - I can't imagine that he would take offense. **Please** update the answer - that's why this is CW, and is entirely in the spirit with which I asked the question!
Comment: I like the wiki link, leave it in as Wiki is another collaborative source just like this site.
Comment: Actually this can be merged with fuzz answer
Comment: Agree - I was trying to work out what the difference between fuzz and distortion/overdrive is. They're both abouta wave getting squared owing to some degree of saturation.  If there is a difference, maybe it's worth making that clearer ? I'd do this myself but i@m only familiar with the term distortion/overdrive.
Answer: Fuzz
Fuzz gained much glory from the sixties and seventies when popularized by musicians such as Jimi Hendrix. Today, fuzz pedals have evolved into a staple for some bands and is capable of producing everything from a singing, warm sustain to a scratchy, velcro sound. The mainstay of a fuzz pedal's sound is produced by an electrical component called a transistor. Fuzz pedals today can be created from silicon transistors, or germanium transistors. Silicon is known to produce a slightly harsh or bright sound (some consider it sterile) while germanium typically accentuates the low end and produces a warmer sound. Just as extreme settings on a silicon fuzz pedal can easily produce a harsh, glass-like sound, extreme settings on a germanium transistor based fuzz can produce an overly warm, and muted tone.
One unique application of a fuzz pedal involves starving the pedal of voltage--which will produce a scratchy, velcro-like tone. This is desirable by some musicians because it is a highly unique sound and is often employed by more avant garde musicians. This sound can be achieved by purchasing a power supply with a sag output, or using a nearly dead battery, although the pedal won't last long when using that method.
Another application of a fuzz pedal is available when the user has control over the the amount of feedback signal routed back into the transistor loop while the pedal is engaged. By configuring the feedback to more sensitive levels, the pedal will feed back into itself causing oscillation*. As the pedal oscillates, certain frequencies will be produced, causing a singing sustained note without the guitarist playing anything at all. The player can consequently play over the note produced to cancel out the feedback loop, but once the player stops the pedal will feed back into itself producing the configured signal once again.
*The oscillation concept can be though of as exactly like a delay pedal set to infinite repeats. As the pedal feeds back into itself, the sound compounds; however unlike a delay pedal fuzz pedal oscillation is not additive.
Comment: Where does fuzz octave pedals fit in ?
Answer: Phaser and Flanger
Both Phaser and Flanger effects are "Comb Filters".
A comb filter combines a wave with a very slightly delayed version of itself, causing both constructive and destructive interference. The result is that some frequencies are boosted, and some are cut. A graph of the frequency response has evenly spaced spikes, hence the "comb".
In a flanger, the delay in the signal is equal for all frequencies, and is slowly varied. This causes the accentuated frequency to sweep up and down.
In a phaser, the delay is achieved by an "all pass filter", which delays some frequencies more than others. This creates an other-worldly "wooshy" effect.
Answer: Amp Simulator
Although it is not really an effect in the sense it changes the sound before it enters the speaker, it is found more and more by digital guitar effect units.
An amp simulator does what it says: it simulates a guitar amplifier, mimicing mostly famous guitar amps by adding a combination of effects mentioned earlier (like boost, distortion).
The sound output from an amp simulator can be used to be directed to a normal amplifier, PA system etc.
Some advantages of using an amp simulator are:

easy switching between different simulated guitar amps
usually cheaper than the original (let alone the sum of possible simulations)
effective at low volumes (some amplifiers only produce their best sounds when cranked up loud)
effective in 100% microphone-free applications -- can output direct to a mixing desk, DAW or PA.
it sounds good with very clean amps (like Fender Twin Reverb)

The main disadvantage is that some people consider the simulated sounds inferior to a real amplifier. Due to it is not transparent may not sound well with dirty amps that provide their own tone.
When used in conjunction with a real guitar amplifier, there's a complicated interplay between the tone created by the real amp, atop the tone create by the simulation.  It makes more sense to use amp simulation with a PA amp or a HiFi amp, designed to faithfully reproduce its input: the amp simulation provides tone; the real amp provides volume.
Comment: Ok I will remove it ... I'm not a guitarist but keyboardist (sssh)
Comment: I would argue against "The main disadvantage is the quality is not as good as the original". I think some of the current advanced units such as AxeFX II and Kemper Profiling Amp can sound essentially and practically indistinguishable from their source amp and may offer subjective improvements.
Answer: Pitch Pedal / Whammy Pedal
Although this might fit in the octaver pedal, it deserves a category of its own. This pedal raises or lowers the pitch of the incoming sound. Most models and emulation go from one octave below to two octave above. Lowering the pitch by an octave enables you to simulate dive-bombing without a floating tremolo for example.
The opposite, going up one or two octaves, is famously used by Tom Morelo (Audioslave's "Like a stone" solo, among others), Matthew bellamy ("Fury" and "Muscle Museum"), and Johnny Greenwood("Subterranean homesick alien"). Other famous users from the top of my head: Satriani, Buckethead, Steve Vai.
Although it's less frequently used, the Whammy pedal can go to intermediate intervals, minor second, fifth etc.
Harmonizer
This unit can play the harmony to any lead you're playing: it's fifth, or third. The difference with a whammy pedal is that it respect the interval of the scale you're in. Of course you'ld have to tell the unit the tonality and scale type before-hand.
Tremolo
Modulate the volume of the sound at a given rate and intensity.
Comment: Does a tremolo pedal modulate the volume?  I once thought this was the case, but all of the tremolo effects I have tried on multi-FX pedals produce a modulated stereo-panning effect, but no volume modulation at all.
Answer: Envelope Filter
This effect gives a guitar that ska/reggae/funk sound. It works by varying the cutoff frequency of a low-pass or bandpass filter (the same filter that's in a Wah-Wah effect, hence the Envelope Filter is also called an Auto-Wah) using an envelope follower which watches the signal for amplitude changes. So it wahs your attack, and then gives less and less wah as the signal attenuates. So the sound has a crunchier attack and the tone is very sensitive to varying dynamics.
Answer: Multi-Effects (Multi-FX or MFX unit)
A multi-effects unit can offer a broad range of effects in one unit, including Amp emulation and speaker simulation.
These effects are usually produced by digitizing the audio signal and using digital processing of the original effects produced by a Digital Signal Processor or DSP.
Generally several effects can be applied and these combinations of effects may be stored as patches. Groups of patches may also be stored as banks, depending on the limitations of the system.
Some units may have limits on the number of effects, often determined by the DSP processing power, or may allow only certain effects to be applied together. More advanced units may offer fewer practical limitations.
Multi-effects units can be used in conjunction with an amp, either before the amp signal, in the effects loop of an amp, or sometimes both (this is known as the 4 Cable Method or 4CM). However, many units may also act as a usb-interface to record or play through a computer, direct sound through xlr out, or simple headphone support for practice.
Examples of multi-effects units include:

Digitech RP series pedals
Digitech DSP rackmount units
Line6 PodHD series pedals and desktop units
Avid Eleven Rack rack mount unit
Fractal Audio AxeFX series rack mount unit
Kemper Profiling Amp series desktop and rackmount units
TC Electronics Nova system pedals
Comment: Boss (by Roland) also make a great range of multi-effects boards too. Bit surprised to not see them listed here.
Answer: Looper
A looper pedal or "phrase looper" allows a performer to record and later replay a phrase or passage from a song. Loops can be created on the spot during a performance or they can be pre-recorded. Some units allow a performer to layer multiple loops. The first loop effects were created with reel-to-reel tape using a tape loop. High-end boutique tape loop effects are still used by some studios who want a vintage sound. Digital loop effects recreate this effect using an electronic memory.
Comment: There's an obsolete recording technology using magnetic *wire*. I wonder if you could make a "tape looper" that uses a guitar string?!
Answer: Wah-wah (or just "wah")
This is effectively a foot-operated parametric equaliser.
A frequency is determined normally by the position of a foot pedal. The input signal is boosted at, and around, this frequency, above the rest of the signal. As you move the pedal, the frequency being amplified changes up or down. The frequency range is set so that it sits well with a guitar, which in turn isn't hugely dissimilar to the human voice's frequency range.
The end result is that at the lower end of the the wah-wah's frequency you get a "wwwww" kind of effect and it transforms at the higher end to a "aaaaah" sound, hence the name.
The pedal rocks forward and backward like a see-saw as you rest your foot on it. Move the pedal to get the wah effect. On some pedals, there is a switch under the toe end to switch ceon straight-through (no effect) to using the wah effect. This means that when you switch it on, it's always in the "aaaa" position. You can hear this in some of Hendrix's work.
Others just detect that the pedal has moved, and switch the effect on. When you stop moving the pedal, it switches off.
On some wah pedals, the signal-with-effect ends up slightly louder than the original signal because a portion of it is being boosted. Other (normally more modern) ones cater for this by bringing the overall signal down a little when using the effect, so that you just get the effect and not extra output.
To hear a classic example of this effect, listen to the beginning of Hendrix's  Voodoo Child (slight return)
Answer: Freeze pedal
Sometimes also called a "granular synthesizer", this effect allows guitarists to infinitely sustain what they are currently playing on their guitars.
Simple versions of this pedal are the Electro Harmonix "Freeze" pedal and the "Freeze" effect on the Boss ME-80 multi-effects pedal.  A more sophisticated version is the Electro Harmonix "SuperEgo" pedal which allows control of the attack and fade of the otherwise infinitely-sustaining signal.
Answer: Ring Modulator
Ring modulation takes two separate signals and multiplies them. A ring modulator will typically take the input signal from an instrument and mix it with a second signal generated by an internal oscillator of which you can vary the frequency.
When two sine waves with frequencies A and B are ring-modulated, the output will also contain the frequencies A+B and B-A. If frequency B is not a multiple of A, these additional frequencies are inharmonic; e.g. ring-modulating sine waves at 1000Hz and 1250Hz will add the frequency 2250Hz, which is neither a multiple of 1000Hz, nor of 1250Hz. When more complex sounds are ring-modulated, sums and differences of all the harmonic frequencies are added.
Moderate frequencies generate eerie, bell-like tones that sound awesome beneath oceans of reverb. Higher frequencies produce ear-shredding shrieks. Meanwhile, ultra-low frequencies (under 10Hz, say) can create pretty, pulsing tremolo effects. But you always need to be careful when you adjust them, as the volume can get very quickly out of control.
Answer: Bit Crusher
Converts the sound to digital (then back to analogue) using a bit depth that is intentionally low enough to add noise and distortion to the signal due to quantisation error. This also reduces the dynamic range of the signal and at very low bit depths, can produce a very synthetic gated effect.
Answer: DI (Direct Injection) boxes
Like an Amp Simulator these are not considered effects however they have significance to performing musicians (connecting to an in-house PA system or studio recording rig) so I'm giving them a mention.
A DI box converts the guitar/effects output to a mic-lead connection.
Besides the obvious difference in the shape of the connector there is also a difference in the signal transmitted:
<technical>

The guitar output (jack-lead) is a hi-Z (or high-impedance) signal
The DI outputs a lo-Z (or low-impedance) signal

Firstly these are both 'mic-level' or 'instrument-level' inputs (they carry very quiet signals) but hi-Z signals are more prone to interference.
The lo-Z signal consists of the instrument's mono signal (hot) and it's inverted waveform (cold), the cables are twisted around one another such that any interfering signal generated in one is negated by the other (much the same as the way a humbucking pickup works).
</technical>
The result of this noise-cancellation is that the signal deteriorates less over distance.
There are two types of DI, active and passive, which have their own advantages and disadvantages a comparison can be seen
here.
The next stage of signal processing is the pre-amp.
Answer: Overdrive
The overdrive pedal is similar to a boost pedal; where the pedal will increase the amplitude of the input signal, therefore having a very large output signal that will be large enough to be distorted by the amplifier.
However, unlike a boost pedal, the overdrive effect is not dependent on the amplifier to have a distorted sound. The overdrive pedal will internally boost the input signal so much that the top of the signal wave will be forced to naturally shrink itself. This is called soft clipping and it simulates amplifier like clipping as though an amplifier was being overly driven, hence the name overdrive. The distortion pedal will also boost the input signal but will then add resistors within the circuitry to not just shrink or soft clip the wave form but completely flatten the wave peaks. This is called hard clipping. For more understanding on the differences between soft clipping and hard clipping see the illustration below.

Multi-Processing Overdrive (most common)
The most common overdrive will also alter the tone of the input signal by adding in a muli-processing chip within the circuitry. Such as the classic Ibanez TS-808, made in the 1980's, having the MP-D01201A multi-processing chip. Depending on the brand of the overdrive, the installed multi-processing chip and the preferences of the player, this type of overdrive is typically a go-to overdrive and is commonly the cheapest to purchase.
Examples of multi-processed overdrives:Ibanez TS-9, Ibanez TS-, Electro-Harmonix East River Drive.

Transparent Overdrive
The transparent overdrive is the most natural sounding overdrive. Unlike the most commonly used multi-processing type overdrives, the transparent overdrive does not alter the tone of the input signal. The transparent overdrive's output signal will sound exactly the same to that of the input signal tone wise, just with added drive and boosted signal (dependent on the users settings). Which means there is no tone loss for more natural sounding drive. The transparent overdrive is typically priced higher due to it having nothing but the purest of sound and smooth drive.
Examples of transparent overdrive: JHS Superbolt, JHS Morning Glory, Emerson Paramount.
The most famous transparent overdrive is the Klon Centaur. Notable users: Jeff Beck, John Mayer, Joe Perry, Keith Urban, ZZ Top and more!
Answer: MIDI Guitar Synthesizer
These are synthesizers that combine with special guitar pickups to allow the guitarist to trigger a huge variety of synthesized sounds, basically any musical sound you can sample and synthesize.
Examples of this include the Roland Guitar Synthesizer.
Answer: Analog Keyboard Simulator
Distinct from MIDI synthesizers, these pedals combine a number of effects in one box to simulate keyboards such as organs, melotrons and electric pianos.
ElectroHarmonix has pioneered this type of pedal with models such as the B9 Hammond Organ simulator.
Answer: Volume Swell/Killswitch
These are effects that are often produced just using the guitars own control rather than through pedals, but can also be found on pedals.
Volume Swell Normally guitar has a very fast attack. It is at its loudest just after a not has been picked and there is a definite picked sound. You can get a softer pad style sound be picking with the volume off or very low and then raising the volume as the note/chord plays. This can be done with the guitar's own volume knob, but sometimes it is more convenient to leave your picking hand free and use a rocker pedal. By adding delay and/or reverb you can soften the note's ending also so that it doesn't stop abruptly.
Kill Switch A kill switch abruptly stops the sound while it is active and lets the sound play again whilst not active. On guitars with a pickup and pots configuration like that of a typical Les Paul this can be achieved by turning the volume for one pickup off and playing with the pickup selector in the middle position. Whilst holding a note, the player can rapidly switch between middle pickup and the silenced pickup giving a stuttering effect. Do this at your own risk because rapidly switching pickups will inevitably wear your pickup selector. This effect is sometimes implemented by a pedal which is only active while it is pressed down (unlike most pedals which are one click on/one click off). Some people will also modify their guitars to add a dedicated killswitch.

Glossary of Guitar Effects


Cartesian product of an indexed family of sets

Question: I'm reading Classic Set Theory for Guided Independent Study, and it gives this definition:

I don't really understand.
"Given $a_i\in A_i$ for each $i\in I$" means that if $I$ is for example $ℤ$, we have ...$a_{-1}\in A_{-1}$, $a_0\in A_0$, $a_1\in A_1$, ...
Does this mean that each $A_i$ has only one element $a_i$?
"the sequence $<a_i>_{i\in I}$  is the function $f:I\rightarrow⋃\{A_i:i\in I\}$ where $f(i)=a_i$" so that means that given a number $i$ in $ℤ$ this function gives us an element of $A_i$, so $a_i$".
"the cartesian product of the indexed family of sets $\{A_i:i\in I\}$ is the set of all such sequences" so it means that the cartesian product is the set of all these functions, but i don't really see how.
The book just gives an "example":

but i don't get it, first thing, by my understanding of the definition, $A_i$ has one element, $a_i$, and here has infinite elements (the elements of the interval of $ℝ$ $(i,i+1)$) so i'm confused already, because, for example $A_1=(1,2)$, what is then $a_1$? Any element in that interval?  And the function $f(i)=a_i$ for each $i\in I$? how is $<i+1/4>$ a function $f:$ℤ$\rightarrow⋃\{A_i:i\in $ℤ$\}$ where $f(i)=<i+1/4>$?
Could you guys make my ideas a little clearer and maybe give me a simple example like, with $I=\{1,2\}$, $A_1=\{v, w\}$ and $A_2=\{x, y\}$?
Thank you!
Answer: Let me try to add some context. What we want to do is generalize the familiar concept of finite sequences and finite Cartesian products. For example, from the real numbers $\mathbb{R}$ we can make the Cartesian product $\mathbb{R} \times \mathbb{R}$, which consists of tuples $(x_1,x_2)$ where $x_1,x_2 \in \mathbb{R}$. A finite sequence here could be the tuple $(3,5)$, which would be the function $f: \{ 1,2 \} \rightarrow \mathbb{R}$ given by
$f(1)=3, \quad f(2)=5$
In that way, we have that $f \in \mathbb{R} \times \mathbb{R}$. In a similar manner, we can define an inifinite Cartesian product by letting the index set be for example the natural numbers $\mathbb{N}$. An element of such should be familiar to you as a sequence $(x_1,x_2,...,)$, seen in for example convergent sequences of numbers in analysis or calculus. For example, a sequence could be
$(1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, ...)$
This sequence is then in the language presented to you here the function $f: \mathbb{N} \rightarrow \mathbb{R}$ given by
$f(i) = \frac{1}{i^2}$
The set of all sequences is then denoted $\prod_{i\in \mathbb{N}} \mathbb{R}$.
So you see, the sets are not one element sets, but just sets where you can choose an element from to make a sequence. Does this make sense to you, or is it as confusing as the definitions you posted yourself?
Comment: Thanks for the answer, I understand the first part but i have a doubt on the second part, the function $f:ℕ\rightarrowℝ$ given by $f(i)=1/i^2$ would only give all the values from $1$ to (almost) $0$, but if this defines one sequence, how can you define another one? if "the formula" is just $f(i)=1/i^2$? what is the "set of all sequences"?
Comment: Yes, this just defines one particular sequence. The set of all sequences here would be all the functions $f:  \mathbb{N} \rightarrow \mathbb{R}$.


The canonical bundle of an elliptic surface

Question: I'm reading Beaville's Complex Algebraic Surface. In Example IX.5, he constructed an elliptic surface of Kodaira dimension $1$: Let B be a smooth curve, $p,q$ the two projections of $B\times\mathbb{P}^2$ onto $B$ and $\mathbb{P}^2$, $|D|$ a base-point free linear system on $B$. A general divisor $S\in |p^*\mathcal{O}_B(D)\otimes q^*\mathcal{O}_\mathbb{P}(3)|$ is smooth; the restriction $p:S\to B$ is a fibration by plane cubics, hence elliptic curves. We have $K_S\equiv p^*(K_B+D)$, and when $\deg D>2-2g(B)$ we have $\kappa(S)=1$.
I have no idea how he computes the canonical divisor of $S$. I just found out that Kodaira's canonical bundle formula is similar but not exactly sure how it is related to this example.
Answer: To compute the canonical bundle $K_S$ of $S$, we use adjunction, which shows that $K_S \equiv (K_{B \times \mathbf{P}^2} + S) \vert_S$. The canonical bundle of $B \times \mathbf{P}^2$ is just $K_{B \times \mathbf{P}^2} \equiv p^{\ast} K_B \otimes q^{\ast} K_{\mathbf{P}^2}$. We know that $K_{\mathbf{P}^2} \equiv \mathcal{O}_{\mathbf{P}^2}(-3)$, and hence, $K_{B \times \mathbf{P}^2} \equiv p^{\ast} K_B \otimes q^{\ast} \mathcal{O}_{\mathbf{P}^2}(-3)$. Applying the adjunction formula, we see that $$K_S \equiv (p^{\ast} K_B \otimes q^{\ast} \mathcal{O}_{\mathbf{P}^2}(-3) + p^{\ast} \mathcal{O}_B(D) \otimes q^{\ast} \mathcal{O}_{\mathbf{P}^2}(3) ) \vert_S.$$ From @KReiser's helpful comment (thank you), the $q^{\ast} \mathcal{O}_{\mathbf{P}^2}(-3)$ and $q^{\ast} \mathcal{O}_{\mathbf{P}^2}(3)$ terms cancel out. Hence, $K_S \equiv p^{\ast} K_B \vert_S + p^{\ast} \mathcal{O}_B(D) \vert_S \equiv p^{\ast}(K_B \otimes \mathcal{O}_B(D) ) \vert_S$, or in the language of divisors, $K_S \equiv p^{\ast}(K_B + D) \vert_S$.
Comment: It's not true that $q^*\mathcal{O}_{\Bbb P^2}(3)$ becomes trivial, but that doesn't matter since it cancels with $q^*\mathcal{O}_{\Bbb P^2}(-3)$.
Comment: Thanks, I got it.
Comment: This is a nitpick, but I think mixing the additive notation $+$ and the multiplicative notation $\otimes$ in one formula might confuse some readers.
Comment: How should I use adjunction formula? I can show that the restriction of $K_S$ onto a smooth fiber is trivial by adjunction but what's next?
Comment: @KReiser Thank you for pointing out the silly mistake :-)
Comment: @SergeyGuminov Absolutely, in a formal piece of writing, I would never do that. But this was just a quick answer on MSE :-)


Call click handler without clicking item

Question: I have some JavaScript/jQuery code that needs to call the checkbox's click handler after it completes.
I can use trigger() to call that handler; however, I see that this also causes the checkbox's checked state to toggle (as though it had been clicked).
Is there any way to call a click handler without actually performing a click on the checkbox?
Comment: Can you provide some code? Most probably you might have to do event.preventDefault().
Comment: @yaswanth: But if I do `event.preventDefault()`, wouldn't that prevent toggling the checkbox when the user actually clicks it with the mouse? I still want the checkbox to work.
Answer:
Is there any way to call a click handler without actually performing a click on the checkbox?

Yes
The handler is just a function. Call the function:
function example() {
  $(this)...do something...
}

$(...selector...).on('click', example);

...elsewhere...

$(...another selector...).each(example)

If you don't have a reference to the function, and you want to trigger all handlers on the element without triggering the native behaviors, you can use jQuery's .triggerHandler() method.
$(...selector...).on('click', function () {...})

...elsewhere...

$(...another selector...).triggerHandler('click')

Comment: Yes, I was looking for something more clever I guess. But you're right. That will work fine.
Comment: @JonathanWood I hadn't finished writing. You probably want `triggerHandler`, although I've never found a case where I've actually wanted `triggerHandler` because calling a named function has always been more appropriate. `triggerHandler` won't stop *other* handlers from being fired, which makes it prone to unintentional consequences.


HTML button object not going to the intended link

Question: I'm trying to test my website by using the buttons that I've coded, one of which should take me back to the homepage of my website. However, when I press this button, the page seems to simply refresh and remain where it is (I am not returned to the homepage).
I've checked the names of all of the provided functions/links to make sure that I am giving the button the correct destination.
Below is the code for my "upload" page, which should allow the user to upload a name and a file.

            <form action="{{ url_for('algorithm') }}" method="POST" enctype="multipart/form-data">

New Algorithm:

                    User Name:

                    Algorithm:

                    <input class="text" type = "text" name = "usr" />

                    <input class="text" type="file" id="file" name="file" />

                    <input class="submit" type="submit" style="width: 60px" value="Submit" />

                    <button id="home-button" class="submit" style="width: 130px">Return to Homepage</button>

            </form>

And below is my "welcome" function in the main app of my website:
@app.route("/")
def welcome():
    rows = get_all_algos()
    return render_template("index.html", rows=rows)

And here is the "algorithm" function which takes me to the "/algorhithm" page:
@app.route("/algorithm", methods=["GET", "POST"])
def algorithm():
    print('entrypoint')
    if request.method == "POST":
        if request.form["file"] != "":
            try:
                print('link-friend')
                usr = request.form["usr"]
                ln = request.form["file"]

                with sql.connect("database.db") as con:
                    c = con.cursor()
                    c.execute("INSERT INTO algorithms (user, source) VALUES (?,?)", (usr, ln))
                    con.commit()
                    msg = "Algorithm Added Successfully"
            except:
                con.rollback()
                msg = "Error in adding algorithm"
            finally:
                return render_template("results.html", msg=msg)
                con.close()
        else:
            if "file" not in request.files:
                flash("No file part")
                return redirect(request.url)
            file = request.files["file"]
            if file.filename == "":
                flash("No selected file")
                return redirect(request.url)
            if file and allowed_file(file.filename):
                usr = request.form["usr"]
                filename = secure_filename(file.filename)
                print(file.filename)
                print(filename)
                file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
                c = con.cursor()
                c.execute("INSERT INTO algorithms (user, source) VALUES (?,?)", (usr, filename))
                con.commit()
                msg = "Algorithm Added Successfully"
                return render_template("results.html", msg=msg)
                con.close()
               # return redirect(url_for("uploaded_file",
               #                       filename=filename))
    return render_template("new_algo.html")

When I click on the button (which is on a webpage with the route "/algorithm"), I should be taken back to the index/home page ("/"), however, I remain on "/algorithm".
*Note: I am using Flask, which is why I use {{ url_for() }} format for links.
Comment: Try to fix a typo onClick -> onclick. Info https://www.w3schools.com/jsref/event_onclick.asp
Comment: Thanks, the code has been updated.
Comment: Why have you made home-button `type=submit` if you don't want it, actually, to submit?
Comment: That is a separate Submit button above the home-button. I made them both class "submit" for the purpose of formatting, but I don't believe I made the home-button have `type=submit`
Answer: Try redirecting from your "form action" ('algorithm') function instead of using html.
return redirect('/welcome')

Comment: I edited the quesiton to include my "algorithm" function. I don't see what you mean by redirecting from the function instead of using html.
Comment: In the algorithm function you have return render_template("new_algo.html"). new_algo.html is the page that will get rendered when you press the button. If you want it to go to /welcome simply replace "new_algo.html" with "welcome.html" or as my answer states use return redirect('/welcome')
Comment: And this is true even though that return statement is only used in case of GET method on algorithm? I assumed that would only be rendered when I first go the "/algorithm" link, with the button itself pointing to the `welcome()` function.
Comment: If that is what you want you should intent the return statement into your else condition. Otherwise you will return the new_algo regardless because it is now outside the scope of the else condition.
Comment: I tried your solution, but I still face the same problem. The page does not redirect.
Comment: Did you try placing the return redirect inside: the if request.method == "POST": statement?
Comment: I did. No luck.
Comment: I'm not great at JavaScript but maybe try removing the "button" script since Flask is handling that for you.
Answer: Thank you for your responses, but I believe I've solved the issue. It appears that keeping within the <form> section of the code forced its functionality to match that of the form (when pressed, the page was submitted, bring up the /algorithm script again, keeping me on the same page.
Moving the <button> object to outside the <form> section solved my issue.


Especificar elemento para não receber propriedades dos outros elementos principais

Question: Tenho um menu e eu queria apenas especificar um elemento para ele não receber as mesmas propriedades aplicadas nos demais, no caso o elemento seria #lk "PRODUTOS" ele está recebendo todos os atributos que foram aplicados em outros elementos, mas eu pretendo não aplicar nenhum tipo de atributo nele, como eu faço para ignorar os atributos inseridos nele??

body{background-color:#6C9;}
*{ padding:0px; margin:;}
input{ display:none;
}
.menu{ width:100%;
height:52px;
background-color: #333;
font-family:Arial, Helvetica, sans-serif;
}
.menu ul{ list-style:none;
position:relative;
top:2px;
}
.menu ul li{ width:150px;
float:left;
}
.menu label, .menu a{ padding:15px;
display:block;
text-decoration:none;
text-align:center;
background-color:#FFF;
color: #06F;
user-select:none;
transition:all 0.3s linear;
}
.menu ul ul{ position:absolute;
top:50px;
visibility:;
}
.menu ul li:hover ul{ visibility:visible;
}
.menu label:hover, .menu a:hover{ background-color:#CCC;
}
.menu ul ul li{ float:none;
}
.menu ul ul li label, .menu ul ul li a{ border-bottom:1px solid #000;
background-color: #F93;
}
hr#hr1{ position:absolute;
left:149px;
top:-3px;
height:35px;
}

/*sub*/
.sub{ position:fixed;
width:100%;
height:100%;
left:0px;
right:0px;
background-color:#3CF;
display:;
}
#ln1:hover .sub{ display:block;}

<input type="checkbox" class="rd" id="t1"/>
<input type="checkbox" class="rd" id="t2"/>

News

Serviços

PRODUTOS-01

PRODUTOS-02

Informações

Links

Links

Answer: Primeiro nunca use IDs com o mesmo nome. Cada ID é único e só pode ser aplicada a UM elemento.
Mas caso vc quera apenas fazer uma variação no nome do ID vc pode fazer a seleção do atributo usando um ^ para selecionar apenas o atributo que começa com o mesmo nome tipo: [id^="lk"] isso significa qualquer ID que começa com lk por exemplo id="lk1" e id="lk2". Então vc conseguem com o attr pegar os dois IDs de uma vez.
Repare que com esse css eu limpei todos os estilos que são aplicado nos IDs dentro do .menu para baixo
.menu [id^="lk"] {
    all: unset !important;
}

Veja o exemplo aplicado no seu código

body{background-color:#6C9;}
*{ padding:0px; margin:;}
input{ display:none;
}
.menu{ width:100%;
height:52px;
background-color: #333;
font-family:Arial, Helvetica, sans-serif;
}
.menu ul{ list-style:none;
position:relative;
top:2px;
}
.menu ul li{ width:150px;
float:left;
}
.menu label, .menu a{ padding:15px;
display:block;
text-decoration:none;
text-align:center;
background-color:#FFF;
color: #06F;
user-select:none;
transition:all 0.3s linear;
}
.menu ul ul{ position:absolute;
top:50px;
visibility:;
}
.menu ul li:hover ul{ visibility:visible;
}
.menu label:hover, .menu a:hover{ background-color:#CCC;
}
.menu ul ul li{ float:none;
}
.menu ul ul li label, .menu ul ul li a{ border-bottom:1px solid #000;
background-color: #F93;
}

.menu [id^="lk"] {
all: unset;
}

hr#hr1{ position:absolute;
left:149px;
top:-3px;
height:35px;
}

/*sub*/
.sub{ position:fixed;
width:100%;
height:100%;
left:0px;
right:0px;
background-color:#3CF;
display:;
}
#ln1:hover .sub{ display:block;}

    <input type="checkbox" class="rd" id="t1"/>
    <input type="checkbox" class="rd" id="t2"/>

News

Serviços

PRODUTOS-01

PRODUTOS-02

Informações

Links

Links

Comment: Hugo! eu não consegui limpar o efeito hover da linha: .menu label:hover, .menu a:hover{ background-color:#CCC;} eu fiz assim, .menu a:hover [id^="lk"] { all:unset; }
Comment: @ElienayJunior isso é por causa da hierarquia de prioridade de classes, editei a resposta e coloquei um important, dessa forma `all: unset !important;` e agora limpou 100%. O restante do estilo que vc quiser colocar tem que vir apos o unset ok, tipo `all: unset !important; color black;` por exemplo
Comment: Eu acabei de descobri outro jeito!  .menu #lk1, .menu #lk2 { all:unset; }
Comment: @ElienayJunior sim assim tb acredito que funcione, porém usando o [id^="lk"] vc não precisa ficar repetindo linhas de css. De qq forma a mágica mesmo fica por conta do `all:unset`
Answer: Existem duas maneiras:
1) usar o seletor :not para aplicar a tudo que o seletor pegar, menos algo.
Por exemplo, no elemento que você não quer coloque um ID diferente, lkProdutos por exemplo, então nos seletores que afetam esse link, use o not, assim:
.menu ul ul li a:not(#lkProdutos){  .... }

2) usar um CSS Reset no elemento, ou seja, "limpar" os estilos, trazendo o elemento para o seu estilo original. Tem um texto interessante sobre isso aqui: http://blog.thiagobelem.net/css-reset-o-que-e-e-como-usar
Basicamente, fazer um seletor para o elemento e remover os estilos indesejados:
#lkProdutos {
  /* reset dos estilos */
}


Degrees of freedom for a t ratio?

Question: summary.glm() does not print degrees of freedom along side the t (or z) ratios. In many published studies, t ratios are reported with their p-values, but no DF. It seems to me that one should still give DF for t-ratios (as you would for a t-statistic).
Should DF be given along with t ratios?
If so, how can you find the appropriate DF for each t ratio in a glm with multiple predictors and an interaction?
Comment: What is a t ratio? Do you mean the t-statistic?
Comment: Since they are the same for each coefficient it would just take up valuable screen real estate. Try doing 2 * pt(,insert value of t here>, , lower.tail = FALSE) and compare with the glm output.
Comment: https://stats.stackexchange.com/questions/373629/why-does-a-summary-call-on-a-glm-model-give-me-t-rather-than-f-values#comment702411_373629
Answer: In a GLM, we don't usually use the T-distribution unless we use a quasilikelihood. See relevant question here.
Let's assume that's what you mean; a GLM with quasilikelihood (variance proportional to some function of mean). An ordinary linear regression is the most common case. The distribution that the test-statistics take under the null is the same for each parameter when ideal modeling assumptions are met: T with $n-p$ degrees of freedom ($p$ number of parameters in model).
Thus it's trivial to report this DF more than once (for each parameter as you say). Furthermore, if the reader knows how many parameters are in the model, it's trivial to report the DF at all; nevertheless, some choose to report it anyway.
Most published studies will at least let you know the $n$, and if it matters, they're explicit about the $p$, but even when not, the $p$-value and confidence interval are calculated from this T-distribution. At the very least, this assures the reader that appropriate control has been made for the nuissance parameter of unknown residual variance.

Degrees of freedom for a t ratio?


Need keyboard that sustains like an acoustic piano

Question: I have always hated playing even nice keyboards, because I want to play them as a piano. The problem is always the same... the sustain is not at all like it is on an acoustic piano. I don't care about all the synthesizer options.  I just want a piano which can be played through headphones and takes up less space, but still have the sustain needed to enjoy it as I would playing an acoustic piano.
Is there anything out there that will accomplish that?  I am willing to spend more to get that.
Comment: Are you missing the sympathetic ringing of the strings of unpressed keys?
Comment: Do you mean as in long-sounding notes or the sustain pedal or something else? Have you tried digital pianos? You know, the kind that even looks almost like an acoustic piano?
Comment: @slim: I haven't actually measured but it does seem to be the case for many digital pianos, especially when comparing low notes with those of a grand piano. The first 10 or so seconds are good but then the volume starts to diminish a bit too quickly.
Comment: @nonpop I suggest you measure it, to verify that your mind isn't playing tricks on you. 10 seconds seems like an impossibly long sustain to me; there's no technical reason a sampled/synthesised piano note should be short (now that storage for samples is cheap) and developers put a lot of effort into making faithful simulations.
Answer: If by "sustain" you mean resonance (sympathetic ringing of strings, as Ulf Akerstedt says), the closest you can get is a digital piano whose notes are recorded samples of the notes on a high-quality acoustic piano. The acoustic piano's resonance is recorded with the sampled notes. It's not exactly the same but it has a lot more richness than a synthesized sound.
If by "sustain" you mean "sustain pedal," that's pretty simple to determine. Check the input jacks of the instrument to see if there is one marked "Sustain." Usually it's a 1/4" jack. That's where a sustain pedal plugs in. The pedal might come with the instrument or you might have to buy it separately. They usually cost around US $25.
If by "sustain" you mean "decay time" of the sound (the time it takes the sound to get softer and softer and eventually stop), many keyboards and digital pianos allow you to modify the decay time, either as an option on its own or by changing a reverb setting. More reverb = longer decay time.
I don't know if we are allowed to recommend brands here, but any instrument's documentation should say whether notes are synthesized or sampled, what the sample source is, decay and reverb options, and whether sustain pedal is an option. Check out those details as you shop.
To save money: avoid instruments with more computer capacity than you need (e.g. built-in sequencers or other DJ software), and look for instruments that are just the keyboard part and a simple folding stand, not the full piano-like cabinet structure.
Comment: I just want to point out a couple things which may easily go unnoticed if one just looks at documentation: First, some sample-based digital pianos emulate sympathetic resonance, some don't, and there are differences in how well it works for example together with the pedals. There are also non-sample based virtual pianos where this works as a result of physical modelling. Secondly, there are differences in sustain pedals. Some are only on-off, some are full-half-off, and some allow more variation. Thirdly, besides decay time there are also differences in how naturally the sound decays.
Comment: @terpsichore I can't make any specific recommendations (I'm not all that fussy) but to see an example of the kind of modelling piano synth, you could try http://www.pianoteq.com - there are similar products varying from cheaper to much more expensive. Most, including pianoteq, have demo versions.
Comment: This is mostly a good answer but I can't agree that sampling is inherently best. A model-based synth should theoretically be able to do a better job than samples of reproducing sympathetic resonance when playing chords. It's a matter of how good the models are.
Comment: Hi Slim, do you know of any actual instruments at a reasonable price point that have the synth capability you describe?
Answer: Frequently, digital pianos will not treat the depression of a footswitch as a fully depressed damper pedal. Instead, it's treated as a half-pedal, to help the pianist avoid creating a muddy mess for want of better articulation. This is actually billed as a feature sometimes, although I cannot recall where I have seen it listed as such.
My Yamaha digital piano behaves in this way. I find that the effect is not particularly limiting, but I am concerned over the potential to develop bad pedalling habits... when using an acoustic piano, I frequently overuse the pedal now.
I suspect that using a pedal with half or continuous pedalling support will result in the keyboard behaving as expected, but I do not have any such pedals to check with.


Mixed Effects Logistic Regression vs Logistic Regression

Question: I'm conducting a study on how pregnancy weight gain affects risk of breast cancer and decided to go with a logistic regression model (outcome is yes/no for breast cancer) and my primary independent variable is categorical (<10lbs, 10-19 lbs, 30-39 lbs and >40 lbs each compared to the referent 20-29lbs). I've recently been told that mixed modeling may be a better alternative to account for random effects (which as I understand is basically variation between subjects if I treat that as a random effect for example).
My question is: are there any major drawbacks to using mixed-effects logistic regression? Is it a more complex model by any chance that I may not necessarily need? Could it inflate odds ratios?
In other words, how do I defend my use of logistic regression over mixed-effects logistic regression, if I can?
Comment: You started off on the wrong foot by classifying a continuous variable and pretending that subjects are homogeneous in the <10lbs and >40lbs groups.  This will do more damage to the model than any benefit you will achieve by better modeling.
Comment: Are there known causes of breast cancer that you have no data for?  (eg, smoking & alcohol consumption)
Comment: I have data for most breast cancer risk factors and do plan on including them as covariates in my model. What are your thoughts?
Comment: What would your 'groups' of observations be in a mixed model?  E.g. Do you have multiple measurements per subject?
Comment: Yes, pretty much. The way the data is set up is that the subjects are asked to fill out a questionnaire every 2 years and they're asked if they've been diagnosed with breast cancer, so I suppose those count as repeated measurements?
Answer: There are different approaches of including random effects in your model (random slope model, random slope + intercept model, random intercept model). You can check for the magnitude of random effects using for example "induced correlation" (Zuur et al. 2008).
Based on its magnitude you can then justify whether to include the random effect in your model or not.
While there is no threshold (at least that I know of) at which to include or exclude a random effect in your model (talking about "induced correlation"), you can most often easily justify the exclusion of random effects with a value close to 0. Furthermore, you have a generalized comparison of the influences of your random effects.
In general, simple models are preferred over complex ones in statistical modelling.


Equivalence of cross products Kunneth formula

Question: In Hatcher Theorem 3.19, he writes that the following cup product for $i+j=n$:
$$H^i(\mathbb{R}^n,\mathbb{R}^n-\mathbb{R}^j)\times H^j(\mathbb{R}^n,\mathbb{R}^n-\mathbb{R}^i)\xrightarrow{\cup} H^n(\mathbb{R}^n,\mathbb{R}^n-\{0\}).$$
He then claims that it is equivalent to the cross product
$$H^i(I^i,\partial I^i)\times H^j(I^j,\partial I^j)\xrightarrow{\times} H^n(I^n,\partial I^n).$$
I can't seem to see how this is the case. I can short of see how the right hand side is induced by some sort of deformation retract, but I am confused about the rest of the geometry (how to shrink to $I^i$, for example), and what precisely needs to be done algebraically to prove this.
Answer: $\def\diaguparrow#1{\smash{
  \raise.8em\rlap{\scriptstyle #1}
  \lower.3em{\mathord{\diagup}}
  \raise.52em{\!\mathord{\nearrow}}
}}$
The pair $(\mathbb{R}^n,\mathbb{R}^n-\mathbb{R}^j)$ deformation retracts on its projection on $\mathbb{R}^i,$ the orthogonal complement of $\mathbb{R}^j$. This will make this pair into $(\mathbb{R}^i,\mathbb{R}^i-\{0\}).$ Expanding the "hole" $\{0\}$ and contracting $\mathbb{R}^i-\{0\}$ (as on the right) to a circle then gives the desired pair.
To convince oneself that the products are "the same", one can take a look at the diagram (I omit subspaces for simplicity):
$\require{AMScd}$
\begin{CD}
H^i(\mathbb{R}^n) \times H^j(\mathbb{R}^n) @>{\times}>>  H^n(\mathbb{R}^n \times \mathbb{R}^n) @>{\Delta^*}>> H^n(\mathbb{R}^n)\\
@VVV @VVV \\
H^i(\mathbb{R}^i) \times H^j(\mathbb{R}^j) @>{\times}>> H^n(\mathbb{R}^i \times \mathbb{R}^j).
\end{CD}
The upper row is by definition what was given initially. The lower row is what has to be shown to be equivalent. The left vertical isomorphism here is by definition how we identify the corresponding groups. What needs to be done is we need to identify those target copies of $H^n(\mathbb{R}^n)$ from both rows in a consistent way (to make this diagram commute when adding the isomorphism between these copies). But for the evident homeomorphism $s: \mathbb{R}^i \times \mathbb{R}^j \to \mathbb{R}^n$ the triangle commutes:
$\begin{CD}
\mathbb{R}^n \times \mathbb{R}^n @<{\Delta}<< \mathbb{R}^n \\
@VVV \diaguparrow{s} \\
\mathbb{R}^i \times \mathbb{R}^j,
\end{CD}$
meaning that $s^*$ can be taken as the desired identification.
The passage to $(I^i,\partial I^i)$ can be done similarly, fixing the identifications on the left and making sure that the identification on the right is consistent with them.
Comment: @Vasting Good question. It's unclear indeed on the space level, but all you need is to know that $(I^n,\partial I^n) \rightarrow  (I^n,I^n-\{0\})$ gives an isomorphism on cohomology, which follows from the induced map of long exact sequences.
Comment: @Vasting In the triangle with spaces each $\mathbb{R}^n$ projects as in the first sentence of the answer. The cohomology then admittedly has to be mapped in the other direction; by maps $H^n(\mathbb{R}^n\times \mathbb{R}^n)\rightarrow H^n(\mathbb{R}^i\times\mathbb{R}^j)$ I meant inverses of that.
Comment: I just realized that I don't quite understand what is happening when we are expanding the hole, even on the right hand side. I can see how we can end up with $(I^n,I^n-\{0\})$ from $(\mathbb{R}^n,\mathbb{R}^n-\{0\})$ by deformation retract, but what is the continuous map $(I^n,I^n-\{0\})\rightarrow  (I^n,\partial I^n)$? At its core it is a map from $I^n\rightarrow I^n$ that respects the pair; it seems like we need to move all of $I^n-\{0\}$ to the boundary but I'm not sure how that can be continuous given $0$ in the middle.
Comment: Just another quick question: what exacty is the map $H^n(\mathbb{R}^n\times \mathbb{R}^n)\rightarrow H^n(\mathbb{R}^i\times\mathbb{R}^j)$? Intuitively it seems like the first copy of $\mathbb{R}^i$ should be included into the first copy of $\mathbb{R}^n$, and same for $\mathbb{R}^j$. But then it doesn't seem so clear that the triangle with $s$ commutes.


SharePoint com MVC 5 qual melhor forma de trabalhar?

Question: Minha dúvida é qual forma de Hospedagem devo usar?

Provider-hosted
Autohosted
SharePoint-hosted

Aplicação vai ficar no servidor para ser consumida pelos usuários internos e para usuários externos.
Nossa equipe é formada por desenvolvedores em MVC e tem uma pessoa de Sharepoint, qual padrão para usar MVC com Sharepoint nesta situação?

Temos que fazer o usuário logar
Precisamos ler lista do Sharepoint
Vai existir workflow do Sharepoint
Answer: Considerando que a maior parte da equipe é de desenvolvedores em MVC, a melhor solução pode ser o Provider-hosted, uma vez que a arquitetura gira em torno de uma webapplication comum, que é integrada ao Sharepoint.
Desta forma, é possivel contar também com algumas facilidades como o SharePoint Client-Side Object Model (CSOM) ou  REST/OData APIs para acessar e gerenciar informações de dentro do Sharepoint.
Aqui vão alguns links que podem te ajudar nesta decisão:
Choose patterns for developing and hosting your SharePoint Add-in
https://msdn.microsoft.com/en-us/library/office/fp179887.aspx
SharePoint Add-ins
https://msdn.microsoft.com/en-us/library/office/fp179930.aspx


Bias and MSE increasing with parameter size in logistic regression simulation study

Question: I have conducted a simulation study of the logistic regression model with parameter $\beta = (1,2,3,4,5)^T$ and covariates all generated from standard normal distribution. I then estimated $\beta$ using the GLM function in R using logit link.
From here I estimated bias and mean square error in the usual way.
One thing that struck out to me was that both the bias and MSE of estimates $\beta_j$ increased with $j$, so that as the value of $\beta_j$ increased (from 1 to 5), the corresponding bias and MSE did as well.
Why is this? Is it due to how the GLM function finds MLE estimates?
I repeated the simulation study with $\beta = (1,2,3,4,1)^T$ and the bias/MSE of $\beta_5 = 1$ was significantly lower than that of $\beta_4 = 4$ so I don't believe it's due to the order of the parameters.
I guess what I'm asking is I don't understand why both bias and variance of estimates increases with the true size of $\beta_j$ when the underlying covariates are generated from $N(0,1)$ regardless of size.
Comment: Can you edit your post to include a minimal working example?
Comment: In addition to what Stephan Kolassa says, 5 is an incredibly large coefficient. You'll have some probabilities very close to 0,1. You may be inducing quasi-separation problems. Any one of these issues will lead to biased maximum likelihood estimation. I ran this quick simulation on my phone: `mean(replicate(1000, {x<-rnorm(100); y<-rbinom(100,1,plogis(1*x) ; coef(glm(y~x,binomial))["x"]}))`. With 1 as coefficient for x, no problems, small bias. With 5, 13 warnings about fitted probabilities close to 0 and 1, plus upwardly biased coefficient.
Answer: It would be helpful to provide additional information about your simulation so we can see what you have done. Code snippets are the least ambiguous.
There are a number of things to be aware of. MLE has a small sample size bias so bias is more likely to manifest at small n. And what counts as a small sample is a higher number when there are more predictors; you have six (including the intercept). I'm assuming your intercept is zero, and in this situation ($N(0, 1)$ predictors), you will have an almost equal proportion of 0s and 1s, which is the ideal situation as you then have minimal sample size requirements.
An additional issue is the separation problem in logistic regression. Some of your coefficients are unrealistically huge. 3, 4 and 5 are odds ratios of 20, 55 and 148 respectively. At small sample sizes, this will most likely lead to separation problems. For example, if $x_5$ has a coefficient of 5, it is possible that for all values of $x_5$ greater than 0, the response is always 1, and for the values of $x_5$ less than 0, the response is always 0. This is complete separation and ML coefficients will tend towards infinity. Inference will also be problematic, you will get huge standard errors.
There are some approaches to dealing with the issue of separation. But in your situation, it would be more beneficial to use more realistic coefficients like $\ln(3), \ln(5)$. $\ln(5)$ is already a large effect. You can also increase your sample size. Ultimately, your choices should depend on the goal of your simulation which you did not state.
Comment: Thanks for your answer! It turns out you were right that my coefficients were too large. I reduced them to be between 0 and 1 each, and the issue disappeared. Thanks for the detailed explanation,


Hook into other module's field formatter?

Question: Am currently trying to implement a node referenced image field on my Drupal 7 site that will change it's 'view mode' depending on programmatical logic just before render. The field is currently being rendered on a number of content types via their display mode settings, each of which are using the field formatter 'Rendered node'.
first attempt
My first idea was to implement the following, considering a hook is a hook is a hook:
function HOOK_field_formatter_view( $entity_type, $entity, $field ... ){
  switch ($display['type']) {
    case 'node_reference_node':
      /* Programatical logic here to modfy field render settings */
    break;
  }
}

Obviously exchanging HOOK for my module's name.
It didn't really matter if the above would fire before or after the original function node_reference_field_formatter_view in node_reference.module because I would either override it's output entirely or, hopefully, modify its values before rendering. The only problem is, the above hook seems to function only on a per module basis — i.e. it's not site-wide, so basically it doesn't fire for my module.
Now obviously I can write my own field formatter to output a rendered node. But it seems a bit of a waste considering there is already one that exists.
other approaches
My other approaches have been to HOOK_preprocess_node and HOOK_preprocess_field but the former doesn't contain any view_mode information, and the latter contains at least 5 different complicated structures that all have references to a view_mode property at different levels — and it feels rather hacky to have to modify each of their values. Even when I've changed certain view_mode properties the resulting image doesn't change.
question
Does anyone know of a clean way to step in before a field formatter renders (of a contrib module) and change it's settings on a per page request basis — i.e. by not having to change the actual content type's permanent view mode settings?
Comment: I've been looking for a `hook_field_formatter_view_alter()` or similar for probably over a year now, it just doesn't exist unfortunately. FYI `hook_preprocess_node()` definitely _does_ have `view_mode` available to it, it's in `$vars['view_mode']`, not `$vars['node']->view_mode` which you might have been tempted to try.
Comment: @Clive, have you found your magic alter hook mentioned here for D7?
Comment: @Clive thanks for the info, oh and for pointing out the `view_mode` on `hook_preprocess_node`, foolish me! I wonder if anything like `hook_field_formatter_view_alter()` this exists in D8...
Comment: I haven't seen anything yet...but then everything's being converted to plugins in D8 (I'm not sure about fields) so it might be that you can just override an existing class to get the job done, that would be ideal. Here's hoping!
Answer: The question mentions that hook_field_formatter_view() is only called on the originating module, but you can take ownership of the field formatter via hook_field_formatter_info_alter().
You should be able to set the module key of the formatter to MYMODULE like:
function MYMODULE_field_formatter_info_alter(&$info) {
  $info['some_field_formatter']['module'] = 'MYMODULE';
}

Then you can implement MYMODULE_field_formatter_view(), optionally feeding through the existing module which handled it to get an element to alter.
function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  // Your custom logic
  $element = OTHER_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display);
  // Any alterations
}

Comment: @ScottJoudry ~ might just be worth noting that if you take over in this way you need to make sure you have methods for all the `field_formatter` functionality of node_reference i.e. `MYMODULE_field_formatter_settings_summary` and `MYMODULE_field_formatter_settings_form` (even if they are just proxy functions back to the original module) otherwise the back-end UI breaks on any display mode panels, when it tried to find these methods in the wrong module.
Comment: Can you elaborate on your answer? Provide some code?
Comment: Nice solution, I almost never think to take complete possession of another module's business (and relay back after changes)... just tried it out though and I end up with much simpler code. Cheers!
Comment: The approach of Graham C is interesting, but requires too many overrides.
Answer: Ok so I realised why my changes to #view_mode in either hook_preprocess_node and hook_preprocess_fields weren't working. (Thanks to Clive for pointing out that I had totally missed the presence of #view_mode in hook_preprocess_node).
My problem stemmed from the fact that #view_mode had already been processed and converted to the correct #image_style property — something which I had neglected to search for.
Even so, changing this value seems too heavily dependent on which hook you modified it in. I finally got some code working though, that actually changes the rendered image:
function HOOK_preprocess_field( &$vars ){
  $element     = &$vars['element'];
  $entity_type = !empty($element['#entity_type']) ? $element['#entity_type'] : 'unknown';
  $bundle      = !empty($element['#bundle'])      ? $element['#bundle']      : 'unknown';
  $view_mode   = !empty($element['#view_mode'])   ? $element['#view_mode']   : 'unknown';
  $field_name  = !empty($element['#field_name'])  ? $element['#field_name']  : 'unknown';
  switch ( "$entity_type:$view_mode:$bundle/$field_name" ) {
    case 'node:full:mlandingpage/field_lead_image':
      if ( !empty($vars['items']) &&
           ($subelement = &$vars['items'][0]) ) {
        if ( !empty($subelement['field_image']) &&
             ($subfield = &$subelement['field_image'][0]) ) {
          /// this needs to be set to the image_style value, not the view_mode value.
          $subfield['#image_style'] = 'grid-normal-4-cols';
        }
      }
    break;
  }
}

The above still doesn't feel very eloquent, but at least it works. I'll take Clive's word on the fact that such an _alter method doesn't exist for field formatters — it's a shame, formatters are an extremely powerful feature of D7, it would be nice to have more augmenting ability.
Anyway, if any future people have any better ideas, answer away :)
Answer: The easiest approach will be using the Panelizer.
If don't use Panelizer but default Drupal view modes or Display Suite, try hook_field_display_alter() or hook_field_display_ENTITY_TYPE_alter().
You have entity, display context as well as all the formatter settings there. And you can easily change field render settings.
You can even change field formatter to a different one.
The approach works perfect for me. The only disadvantage is that you might be confused with different settings in the the "Manage display" UI.
Answer: https://www.drupal.org/node/2130757
It gives a good example.
hook_field_formatter_third_party_settings_form() is useful to alter the form of the existing field formatter.
But this doesn't work with field groups.


(Simple) question about modules and ideals

Question: Let $A$ be a ring and $M$ and $A$-module; let also $N\subseteq M$ be a submodule. If $I\subseteq A$ is an ideal, and $N\subseteq IM$, then $IM/N$ is a submodule of $M/N$, of the form $I(M/N)$. Now, if I start with an ideal of the form $I(M/N)$, is it said that $N\subseteq IM$? In other words, are the submodules of the form $I(M/N)$ in bijection with those of the form $IM$ containing $N$? I would actually say that they are in bijection with those of the form $IM+N$ (that are not necessarily of the form $JM$ for some ideal $J\subseteq A$). However I saw an argument that seem to use such bijection, so maybe I'm misunderstanding something.
Edit: in the argument that I referred to,  $N$  is itself of the form $JM$ for an ideal  $J$. So maybe the  reason is that the submodules of the form $IM+JM$ are isomorphic to  $(I+J)M$.
Answer: $\newcommand{\Z}{\mathbb{Z}}$This is true in the case $N=JM$. I guess the key to making this look more reasonable is that you have
$$I(M/N)=(IM+N)/N=(IM+JM)/N=((I+J)M)/N=(I+J)(M/N)$$
so ideals of the form $I(M/N)$ are the same those of the form $(I+J)(M/N)$ which are in bijection of those of the form $(I+J)M$ (all of which contain $N$) which are the same as those of the form $IM$ containing $N$ (the last two things are the same because when $IM$ contains $N$ you get $IM=IM+N=IM+JM=(I+J)M$).
Here's a counterexample to the general case: take $A=\mathbb Z$, $M=\Z/2\Z\oplus \Z/4\Z$ and $N=\Z/2\Z\oplus\{0\}$. You can see explicitly that there are three submodules of $M$ of the form $IM$, i.e. $0,M$, and $\{0\}\oplus\Z/2\Z=(2)M$, but only two of these contain $N$. On the other hand, $M/N\simeq \Z/4\Z$ which has three submodules of the form $I(M/N)$.


Upload file into a random folder

Question: I want users to upload a file into Google Drive, but not to the root. The Children resource allows only to list folders from the root(which makes sense), but does not put the name of the folders in the JSON response.
I cannot use Parent resource, because the fileID is non-existent and also because i need the users to see the folders(in their respective hierachy) and choose the folder of their choice. Here is what i have tried so far
void DriveClass::listFileFolderDrive(const QString& folderID){

QUrl url("https://www.googleapis.com/drive/v2/files/" + folderID + "/children");
//qDebug()<<" url for About Drive: "<< url;
QNetworkRequest* request = new QNetworkRequest( url );
request->setHeader( QNetworkRequest::ContentTypeHeader, "application/json" );
request->setRawHeader( "Authorization", QString( "Bearer %1" ).arg( this->_oAuth2->token() ).toLatin1() );
QNetworkReply* reply = m_networkManager->get(*request);
bool result = connect(reply, SIGNAL(finished()), this, SLOT(onlistFileFolderDriveFinished()));
Q_ASSERT(result);
Q_UNUSED(result);
}

Where folderID is "root". The response i get is:
QVariant(QVariantMap, QMap(("etag", QVariant(QString, ""dyf6dc5nFpQUIZ2nJvOu2LyLJk8/bD3mjJonFeCjTc8Eu8VRx_DzPtg"") ) ( "items" ,  QVariant(QVariantList, (QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_Ycab1hhT3I0T3ptMDg") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_Ycab1hhT3I0T3ptMDg") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_Ycab1hhT3I0T3ptMDg") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcabXdJd21CeWRHUXM") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcabXdJd21CeWRHUXM") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcabXdJd21CeWRHUXM") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcaM1ZCOXBaZzJSNmc") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcaM1ZCOXBaZzJSNmc") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcaM1ZCOXBaZzJSNmc") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcaSmtNMmRlTld5QkU") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcaSmtNMmRlTld5QkU") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcaSmtNMmRlTld5QkU") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcaY0I0czA4djNLT1U") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcaY0I0czA4djNLT1U") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcaY0I0czA4djNLT1U") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcaTW8zZklsNnFNTDBmQ1dodi1yTFhqX2s4SzNr") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcaTW8zZklsNnFNTDBmQ1dodi1yTFhqX2s4SzNr") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcaTW8zZklsNnFNTDBmQ1dodi1yTFhqX2s4SzNr") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/1_eVyijBnZPvFfn4WewtScnlSXRFpXInmop-AUD6Jp5nSV4rnxL4-IpLZ6uoR") ) ( "id" ,  QVariant(QString, "1_eVyijBnZPvFfn4WewtScnlSXRFpXInmop-AUD6Jp5nSV4rnxL4-IpLZ6uoR") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/1_eVyijBnZPvFfn4WewtScnlSXRFpXInmop-AUD6Jp5nSV4rnxL4-IpLZ6uoR") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/0B_0rcYNi_YcaYmNmZTEwMzYtNjgzZC00MjJkLWFmYWQtZmRlODc4OTEwZTVh") ) ( "id" ,  QVariant(QString, "0B_0rcYNi_YcaYmNmZTEwMzYtNjgzZC00MjJkLWFmYWQtZmRlODc4OTEwZTVh") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/0B_0rcYNi_YcaYmNmZTEwMzYtNjgzZC00MjJkLWFmYWQtZmRlODc4OTEwZTVh") ) )  ) ,  QVariant(QVariantMap, QMap(("childLink", QVariant(QString, "https://www.googleapis.com/drive/v2/files/1CHu3CzJ23I6WS3J8rOIpT5szN8r8mTOxztiWixwXafQ") ) ( "id" ,  QVariant(QString, "1CHu3CzJ23I6WS3J8rOIpT5szN8r8mTOxztiWixwXafQ") ) ( "kind" ,  QVariant(QString, "drive#childReference") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/0AP0rcYNi_YcaUk9PVA/children/1CHu3CzJ23I6WS3J8rOIpT5szN8r8mTOxztiWixwXafQ") ) )  ) )  ) ) ( "kind" ,  QVariant(QString, "drive#childList") ) ( "selfLink" ,  QVariant(QString, "https://www.googleapis.com/drive/v2/files/root/children") ) )  )

I hope that was clear enough. I parsed it in QVariant so as to use the result in a ListView. From my studying of the google drive docs, one needs a file to have a folderID before inserting can be achieved. And i do not have a folderID for a new file to be uploaded.
Comment: I will need to show us what you have tried and describe any problems you are having with your current solution.   Please read http://stackoverflow.com/help/how-to-ask
Comment: Thank you. I have requested a list of the root children folders. The question has been re-edited.
Answer: A few pointers...

You are using the v2 API. If this is a new app you should probably switch to v3.
Your REST call is requesting a list of Children resources. If you look at https://developers.google.com/drive/v2/reference/children you'll see    that there is no title/name in a children resource.
The more common way to achieve what you're looking for is to do a files.list with a query parameter of folder_id in parents.
Comment: Thats the thing, but i do not have folder_id ?. If for a new file to be uploaded to any folder, does it mean the folder_id will also be "root"?,  to do a files.list with a query parameter of folder_id in parents.
Comment: sorry I don't understand your comment.
Comment: Oh, What i meant was the parent id, Naturally, you do not need folder_id to upload a file or files.
Comment: parent = folder, so parent_id = folder_id
Comment: True, that works beautifully, when you want to create a folder into another folder, but does not work when you want to upload A file into any given folder.. been trying it for some days now... wont give up though...
Comment: oh and also, maybe i am the one who's wrong, maybe i do not know how to properly represent the parents[] when posting (uploading). I mean the information specifics.
Answer: Yep, was quite wrong... until now. For the record, any upload, whether file or folder, to any  location, whether root or any RANDOM folder, you'd need the folder_id of that particular folder. Use 'root' as id for the root folder. And to upload, you do not need the selfLink, or parentLink. just
parents:[{ "id" : "id of the folder, use root for root folder" }]

Thank you @pinoyyid.

Upload file into a random folder


Find the integral $\int_{-2}^{1} |x| d |x|$

Question: To handle the integral $\int_{-2}^{1} |x| d |x|$ I do not see a way to begin with.
If instead I am to compute $\int_{-2}^{1} |x| dx$ then things get easier, for simply computing $\int_{0}^{1} x dx + \int_{0}^{2} x dx$ suffices.
Comment: don't we have $$\int \clubsuit \; d\clubsuit = \dfrac{\clubsuit^2}{2} + C$$ ?
Comment: @Chou Replace $\clubsuit$ with $|x|$ in your calculation.
Comment: @MatthewLevy There is no requirement for being no-decreasing, but you might need bounded-variations (which would mean it is the difference of two non-decreasing functions.) See https://en.wikipedia.org/wiki/Riemann%E2%80%93Stieltjes_integral#Existence_of_the_integral
Comment: Yeah, my problem is that I am not sure how to deal with $d|x|$? You mean $d|x|$ doesn ot matter here?
Comment: Oh? If so then what is the primitive $\int |x| dx$? Thanks.
Comment: Is $d|x|$ even well defined here? I was under the assumption that this notation was reserved for the R-S integrals which require the function $|x|$ to be non-decreasing, which it does not satisfy in this case.
Comment: The most straightforward way to integrate this function is to split the domain accordingly where x < 0 gives -x in the that integrand and  $x\geq 0$ gives x in the integrand. You then add the results of both integrals. It turns out in this case it's even easier then that because  where x < 0, both x and dx are negative,which  yields a positive integrand when you multiply the 2 -1's.  Simple.
Answer: See this

$$ \int_{-2}^{1}|x|d|x| = \int_{-2}^{0}(-x)d(-x) + \int_{0}^{1}(x)\,d(x) = \int_{-2}^{0}x\,dx + \int_{0}^{1}x\,d x = \int_{-2}^{1} x \,dx$$

$$ = \dots\,. $$
Comment: Rather, if you understand what $\int f(x)dg(x)$, a Riemann-Stieljes integral.
Comment: There you go,bingo.Not difficult if you understand what |x|  means.


Concatenate rows of Pandas multiindex dataframe by index value

Question: Given the following DataFrame,
              00:00:00 01:00:00 02:00:00
Date       ID
2018-01-01 A1       x1       x2       x3
           B3       y1       y2       y3
2018-01-02 A1       x4       x5       x6
           B3       y4       y5       y6
2018-03-02 A1       x7       x8       x9
           B3       y7       y8       y9

which was obtained with
import pandas as pd
idx = pd.MultiIndex.from_product([pd.to_datetime(["2018-01-01", "2018-01-02", "2018-03-02"]),
                                 ["A1", "B3"]], names=["Date", "ID"])
col = pd.timedelta_range("00:00:00", periods=3, freq="1H")
df = pd.DataFrame([["x1", "x2", "x3"], ["y1", "y2", "y3"], ["x4", "x5", "x6"],
                   ["y4", "y5", "y6"], ["x7", "x8", "x9"], ["y7", "y8", "y9"]], idx, col)

I want to transform it to the following form,
datetime          A1   B3
2018-01-01 00:00  x1   y1
2018-01-01 01:00  x2   y2
2018-01-01 02:00  x3   y3
2018-01-02 00:00  x4   y4
2018-01-02 01:00  x5   y5
2018-01-02 02:00  x6   y6
2018-03-02 00:00  x7   y7
2018-03-02 01:00  x8   y8
2018-03-02 02:00  x9   y9

But how?
Answer: IIUC
df.unstack().swaplevel(axis=1).stack()
Out[1736]:
ID                   A1  B3
Date
2018-01-01 00:00:00  x1  y1
           01:00:00  x2  y2
           02:00:00  x3  y3
2018-01-02 00:00:00  x4  y4
           01:00:00  x5  y5
           02:00:00  x6  y6
2018-03-02 00:00:00  x7  y7
           01:00:00  x8  y8
           02:00:00  x9  y9

Comment: @joaoavf df.index=df.index.map('{0[0]}{0[1]}'.format) , when you do merge , make sure you change the datetime to str firstly
Comment: Does this guarantee chronological ordering or should a reordering of the index be performed for one to be sure?
Comment: @Bella it will follow your df order , it still the multiindex
Comment: Ok, great. Really nice in one line! Thanks for teaching me this.
Comment: @Bella yw~ :-) happy coding
Comment: Is there an easy way to merge that multindex into a simple index? I am just curious about it.


Como fazer script simples de include em html

Question: Gostaria de saber como posso fazer um script simples para disponibilizar a  minha tela de login aos meus cliente .

'Exemplo' tenho um formulario simples que loga no meu sistema
      <form action="http://www.xx.com.br/logar.php">
      <input type="text" name="login">
      <input type="text" name="senha">
      <input type="submit" value="Logar">
      </form>

Queria uma forma simples de disponibilizar esse formulario para meus cliente incluírem em seus sites tipo um include mais que rode em html simples
Answer: Vamos dizer que o domínio com o JavaScript com o formulário de login é seusite.com.
Crie um arquivo javascript: seusite.com/formulario.js
function loginMeuSite() {
    var divLoginSite = document.getElementById("divLoginSite");
    divLoginSite.innerHTML = '<form action="http://www.xx.com.br/logar.php"><input type="text" name="login"><input type="text" name="senha"><input type="submit" value="Logar"></form>';
}
document.addEventListener("DOMContentLoaded", function(event) { loginMeuSite(); });

Peça à seus clientes para inserirem o seguinte javascript preferencialmente entre as tags :

E peça para inserirem o
 do formulário de login no local desejado onde o formulário de login deverá aparecer:

Exemplo
sitedocliente.com/cliente.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Incluindo JS</title>
    <link rel="stylesheet" href="">

Comment: As respostas mais votadas no link que você citou dizem que isso é uma bobagem. Iframe ainda existe e é válido, só não precisa mais ser usado em tantas situações como antigamente. Mas incluir conteúdo de um site externo é o uso típico até hoje.
Comment: `IFRAME` já é considerado obsoleto por muitos http://stackoverflow.com/questions/755795/are-iframes-html-obsolete
Comment: Claro que é utilizado ainda até hoje, como adsense, etc, mas acho que javascript e outras tecnologias que são compatíveis com praticamente todos os mobiles avançaram tanto que tornam outras obsoletas (iframe), porém funcionais.
Answer: O modo mais simples que você pode fazer é criar um apontamento CNAME no site do seu cliente para determinada página, quando o cliente acessar a página de login dele através de um subdomínio por exemplo, o apontamento será para o seu sistema, sem vc precisar distribuir um iframe ou algo assim, que geraria um desgaste maior com manutenções futuras.
Segue um DNS RECORD de exemplo
NAME                 TYPE   VALUE
--------------------------------------------------
login.cliente.com.   CNAME  login.meusistema.com.

Comment: Nesse caso cada cliente incluiria o form por conta própria, e alteraria o action para o record criado? É essa a ideia?


How can i sum amount group by book_id and order_id

Question: I have a table:
book_id  order_id  amount
-------- -------   -------
   a      d1         10
   a      d1         10
   a      d1         10
   a      d2         20
   a      d2         20
   a      d3         30

i try this
SELECT book_id,sum(amount) as sum FROM table WHERE book_id= 'a' GROUP BY book_id;

Result
book_id      sum
--------   -------
   a         100

but i want to group them by book_id and sum amount like this
book_id      sum
--------   -------
   a         60     ==> d1+d2+d3

How would I write a mySQL to SUM row like d1+d2+d3?
Comment: Why do you have duplicate records? What happens if you have an additional record `a/d1/12` ?
Answer: Given the current data, you would SUM based on DISTINCT rows:
Working Test Case - Updated
The result of all:
book_id SUM(amount)
-------------------
a       60
-------------------

WITH cte AS (
       SELECT DISTINCT book_id,  order_id,  amount FROM tbl
     )
SELECT book_id
     , SUM(amount)
  FROM cte
 GROUP BY book_id
;

Add filtering as you wish to either the cte term or the final query expression.
WITH cte AS (
       SELECT DISTINCT book_id,  order_id,  amount
         FROM tbl
        WHERE book_id = 'a'
     )
SELECT book_id
     , SUM(amount)
  FROM cte
 GROUP BY book_id
;

With older versions of MySQL, you can use a derived table, instead of a CTE term:
SELECT book_id
     , SUM(amount)
  FROM (
         SELECT DISTINCT book_id,  order_id,  amount
           FROM tbl
          WHERE book_id = 'a'
       ) AS cte
 GROUP BY book_id
;

Trying to SUM(DISTINCT amount) is incorrect, since some different orders could have the same amount and those would be compressed into one value.
Comment: Only first one works. Others are wrong and don't work.
Comment: They are logically identical, but I added order_id filtering to some as the OP used that logic in the question.
Comment: @Rezu Yes.  Just a typo.
Comment: @Rezu Too tired.  It was book_id, of course, that the OP was filtering.
Answer: There are two ways. The first one is with Distinct:
Select t.book_id, sum(t.amount)
from
(
   SELECT DISTINCT book_id,  order_id,  amount
   FROM book
) t
group by t.book_id

The second one is with With:
WITH w AS (
       SELECT DISTINCT book_id,  order_id,  amount FROM book
          )
SELECT book_id, SUM(amount)
  FROM w
 GROUP BY book_id;

Answer: Try this nested SELECT.
SELECT book_id, SUM(amount) AS `sum` FROM (SELECT DISTINCT book_id, order_id, amount FROM book GROUP BY book_id, order_id) AS a;

Result
book_id  sum
-------  --------
a        60

Comment: @basha04 I edited my answer the result is now correct.
Answer:    SELECT DISTINCT(book_id), SUM(amount) FROM table GROUP BY book_id WHERE book_id ='a';


How can I use select tag in table

Question: I create a module that have a table . I create my select tag with this code :
$select = array(
    '#type' => 'select',
    '#options' => array(t('0'), t('1'), t('2'), t('3'), t('4'), t('5'), t('6'), t('7'), t('8'), t('9'), t('10')),
);

When I use this code in table, select tag not work :
$table = [
   '#markup' => '

' . $select . '

',
];
return $table;

The page that show to me :

Array

Answer: Use for the table the render element Table. There is also an example how to put form elements inside of a table:
$form['contacts'] = array(
  '#type' => 'table',
  '#caption' => $this->t('Sample Table'),
  '#header' => array($this->t('Name'), $this->t('Phone')),
);

for ($i = 1; $i <= 4; $i++) {
  $form['contacts'][$i]['#attributes'] = array('class' => array('foo', 'baz'));
  $form['contacts'][$i]['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
  );

  $form['contacts'][$i]['phone'] = array(
    '#type' => 'tel',
    '#title' => $this->t('Phone'),
    '#title_display' => 'invisible',
  );
}

How can I use select tag in table


PHP 5.3.10 SOAP server fails to process large messages

Question: We have a SOAP service that receives files as byte content. This service works fine for small files, but is failing for files ~25MB or larger. In the case of large files, the SOAP call executes but returns null. It literally returns nothing--no error message, no message at all. My associate indicated that the server is generating a 500 internal server error, which somehow gets back to the client but disappears in my testing. Tracing the code indicates that the handle() method of the code is not throwing an eror but also not doing anything at all--not calling the service's authorization method nor the method that puts the file to the server.
What is the likely cause of this problem, and how can I resolve it?
Answer: I think the client that calls the soap stop the service before having the answer.
Try to increase the value of default_socket_timeout in your php.ini.
You can also increase the value of max_execution_time
I hope it will help you. :)


Need help in finding name of specific thing I'm trying to do

Question: I think it's possible to somehow hook with the windows environment (specifically explorer.exe) and trigger specific things, for example launching control panel and using it as if I had mouse (meaning I'm clicking the interface from the code).
Basically what I'm trying to do is automate some redundant tasks I do often, just I don't know how it's done, or even how it's called. Anyone can point me in right direction?
Thanks!
Comment: Is there are requirement for Windows to take control of the cursor? You could probably bypass the GUI & just run the application that's accessed by the Control Panel..
Comment: No I just want to do everything I could if used mouse (for example if I'd record mouse sequence or something - at least it's clicks).
EDIT: pardon me, you're right about that, but control panel is just a plain dumb example. The app might be the explorer itself, like entering it's view menu or something like that.)
Comment: I think you're looking for mouse/keyboard macros. Though I agree that you could probably do everything you need by calling applications. Though maybe not -- not if you need to hook into DLLs and such.
Comment: You want "automate some redundant tasks I do often". Is "rolling down the view menu" a final effect you want to achieve? I don't think so. I think you want to customize the system - you don't have to fire up any GUI and simulate clicking. It will be much easier to i.e. use some COM interface.
Answer: Forget about "automated clicking". GUI tools are just front-ends to control the system. You can control the system like they do, it will be much easier.

Huge possibilities can give you Microsoft Management Console. Each "snap-in" can be accessed via COM model. Some of them have GUI front-ends, find and fire "*.msc" files (somewhere in Windows directory) to try them.
There is many command line tools i.e. "net" command has huge abilities related to networking.
PowerShell may be a better choice instead of C# or C++, it's designed for task automation. You can easily use COM, .NET, MMC ...
Comment: I was just looking for ideas how to do some interaction with system, this answer is the most comprehensive one. Although I'd add that SendMessage() answer from below may come in handy for anyone who approaches this question.
Answer: Windows Explorer has a COM object model that you can call from both C# and C++. (Most of the examples on MSDN are in Javascript or VBScript, which I guess aren't your languages of choice, but they demonstrate that the API is straightforward to call.)
Answer: AutoHotKey is a scripting environment specifically designed for this sort of task
Comment: The catch is that I'd like to do it on my own, otherwise this would be on Yahoo! Answers I suppose. I've used that and that's something similar I'm trying to recreate.
Comment: @Johnny: so look at their documentation to see what they call it, and look at their source to see how they do it…
Comment: I'm just about to do that now, had to go away for couple hours though.
This is just for practice purposes, I thought there just might be some  technique for that, a practical way instead of workaround.
Answer: If you want mostly to launch control panel you can do using RunDll32 interface existing in the most control panel applets. See http://www.osattack.com/windows-7/huge-list-of-windows-7-shell-commands/ , http://support.microsoft.com/kb/167012 or http://www.winvistaclub.com/t57.html for example. For the corresponding API see http://support.microsoft.com/kb/164787.
Another option is usage of control.exe (see http://msdn.microsoft.com/en-us/library/cc144191.aspx and http://vlaurie.com/computers2/Articles/control.htm).
If you google more you will find much more examples which you can to automate a lot of things without using of some general ways to automate GUI.
Answer: At more or less the lowest level within Win32, you can use the SendMessage() API to send raw click messages to windows of interest.  This will rely on a lot of intrusive knowledge about the apps you intend to drive.  However, you could easily implement a "click recorder" that could replay click sequences captured from user interaction.