Nutch issues with crwaling website where the url differes only in termes of parameters passes

Question: I am using Nutch to crawl webistes and strangely for one of my webistes, the Nutch crawl returns only two urls, the home page url (http://mysite.com/) and one other.
The urls on my webiste are basically of this format
http://mysite.com/index.php?main_page=index&params=12
http://mysite.com/index.php?main_page=index&category=tub&param=17
i.e. the urls differ only in terms of parameters appened to the url (the part "http://mysite.com/index.php?" is common to all urls)
Is Nutch unable to crawl such webistes?
What Nutch settings should I do in order to crawl such websites?
Answer: I got the issue fixed.
It had everything to do with the url filter set as
skip URLs containing certain characters as probable queries, etc
-[?*!@=]
I commented this filter and Nutch crawle dall urls :)


jquery click background pos Y + count++

Question: I have a div with overflow hidden with a set height and inside I have an image with position relative and top: 0px
I would like to know how I can add a count to css position top: 0px so every time the user click on the "up button", the image moves by 10px up within the div.
I can't seem to get the count++ to work, please see JS Fiddle here: http://jsfiddle.net/michelm/wE2Tz/
<code>//var count = 10++;

$('#button_up').click(function(){
    $('#banner img').css('top', '-10px') ;
});

$('#button_down').click(function(){
    $('#banner img').css('top', '10px');
});
</code>
Comment: Have you tried binding click with your logic?
Answer: Try with:
<code>$('#button_up').click(function(){
    $('#banner img').css('top', '-=10px') ;
});

$('#button_down').click(function(){
    $('#banner img').css('top', '+=10px');
});
</code>
Working example here.
Comment: Thanks Jonathan. It works great :)
 I tried that too but I had the syntax wrong. Thanks very much
Answer: Try this one:
<code>$('#button_up').click(function(){
    var currentTop = $('#banner img').position().top;
    $('#banner img').css('top', currentTop - 10) ;
});

$('#button_down').click(function(){
    var currentTop = $('#banner img').position().top;
    $('#banner img').css('top', currentTop + 10) ;
});
</code>
http://jsfiddle.net/3wEMz/

jquery click background pos Y + count++


Transação PHP PDO com vários objetos

Question: A ideia seria essa: Tenho 3 classes, uma para conexão ao banco, outra para Usuários e outra para Produto.
A classe Usuário com o banco de dados tb_usuarios.
A classe Produto com o banco de dados tb_produtos.
Faço o INSERT em cada classe Usuário e Produto.
Estou tentando agora em dois objetos fazer uma transação com o código abaixo.
try {
    require_once 'Connection.php';

    $conn = new Connection();
    $conn->connectionDB()->beginTransaction();

    $objuser = new Usuario();
    $objuser->insertUser("Nome Teste", "email@example.com");

    $objproduct = new Produto();
    $objproduct->insertProduct("Nome Produto", "Preço", "Data");

    $conn->connectionDB()->commit();
}

catch(PDOException $ex) {
    $conn->connectionDB()->rollBack();
    echo $ex.getMessage();
}

A falha ocorre no trecho abaixo:
$conn->connectionDB()->rollBack();

Comment: Se ele entrou na `catch`. A falha ocorre no `try`. O que o `$ex.getMessage();` informa?
Comment: Outra coisa esse `$conn->connectionDB()->rollBack();` não pode ser usado pois o objeto `$conn` não foi instanciado dentro do `catch`.
Answer: você precisa incluir a instância da conexão antes do try, para que esteja disponível no catch.
require_once 'Connection.php';

$conn = new Connection();

try {

    $conn->connectionDB()->beginTransaction();

    $objuser = new Usuario();
    $objuser->insertUser("Nome Teste", "email@example.com");

    $objproduct = new Produto();
    $objproduct->insertProduct("Nome Produto", "Preço", "Data");

    $conn->connectionDB()->commit();
}

catch(PDOException $ex) {
    $conn->connectionDB()->rollBack();
    echo $ex.getMessage();
}

Comment: Fiz uma classe de transação e passei os INSERT que precisava. Fiz a conexão antes do try e funcionou.

Transação PHP PDO com vários objetos


Why is it called the chromatic scale?

Question: The definition of chromatic as given by Google:
adjective: chromatic

MUSIC: relating to or using notes not belonging to the diatonic scale of the key in which a passage is written.
(of a scale) ascending or descending by semitones.
(of an instrument) able to play all the notes of the chromatic scale.
of, relating to, or produced by color.

I, being un-synesthetic, do not associate sound to color. Its certainly fun to imagine what sounds look like but I just don't associate a color to a sound.
So why is the chromatic scale called the chromatic scale? Was it named by a some person who had synesthesia?
Comment: As someone with some degree of synaesthesia I have to say that, at least when played as a scale, the chromatic scale does not sound particularly colourful to me. Major, minor, pentatonic scales etc. sometimes have quite distinctive colours, but the chromatic scale is generally muddy and brown for me.
Comment: Why must it relate to colour? Surely both terms equally stem from the notion of a space divided into chunks? In the former case, into notes of a scale; in the latter, colours of the spectrum.
Answer: It is impossible to say for sure, since the term chromatic has had a musical meaning since at least ancient Greek times (hence the use of a Greek word). More on that in a moment, but first, its worth noting that "color" has idiomatic meanings as well, such as these definitions for "colorful" in the Merriam-Webster Learner's Dictionary:

2. interesting or exciting
He gave a colorful account of his travels.
She has a colorful [=bright, cheerful] personality.
He was a colorful character. [=a very unusual person]

3. If you use colorful language you use words that are usually considered rude or offensive.
He's been known to use some colorful language when he starts talking about politics.

Either of these definitions could easily be applied to the case of chromatic notes in music. They add interest or excitement by using improper notes that are usually considered offensive (by virtue of being outside the scale).

As for the origins of the term... In Ancient Greek music theory, full scales were built by combining smaller tetrachords -- 4-note scales that spanned an interval of a perfect fourth. While the two outer notes had to be a fourth apart, the two inner notes could move around. Tetrachords were classified as belonging to a genus, depending on which of three distributions they had. The three genera were Diatonic, Chromatic, and Enharmonic. Note: the following explanations are only approximate, because the tuning system was considerably freer than what we have.

In the diatonic genus, the notes were distributed roughly as Half-step, Whole-step, Whole-step (HWW). Such as in E-F-G-A.
In the chromatic genus, the distribution was roughly Half-step, Half-step, Minor third (HHm3). Such as in E-F-G♭-A.
In the enharmonic genus, even smaller, microtonal intervals were used, such as E-E½♯-F-A.

As you can see, the diatonic genus primarily used whole steps, with half steps only to fill in the gap, which the chromatic genus used primarily half-steps (with a rather large gap). This is different than the modern usage of the term, to be sure, but the similarity should be evident.
The modern usage of the term can be traced back to this ancient usage through the Renaissance, and its interest in reviving ancient Greek culture. This can be seen especially clearly in the works of Nicola Vicentino. In Rome, 1551, there was a major music theory debate between him and Vicente Lusitano. The later argued that music could be understood through the application of only the diatonic genus, while the former was attempting to revive the importance of the chromatic and enharmonic genera. Although Lusitano was judged to be the winner of the debate, this didn't keep Vicentino from advocating for chromatic and microtonal music. In fact, in 1555, he designed and built a 31-note-per-octave keyboard, known as an Archicembalo, and published a treatise and music to go with it: L'antica musica ridotta alla moderna prattica (ancient music adapted to modern practice).

Similar instruments were built during this period, including one from 1606 which still survives and is actually called 'Clavemusicum Omnitonum Modulis Diatonicis Cromaticis et Enearmonicis' (roughly, something like "Keyboard to play all notes diatonic, chromatic, and enharmonic").

I found a translation of Vicentino's work on Google Books, and when introducing the three genera (which he calls "divisions" of the fourth) he has this to say about chromatic (emphasis mine):

The second division was called chromatic, which means transformed into steps unlike those of the first division [i.e. diatonic]. The third and last [division] was called enharmonic, which means composed of small parts.

Now "transformed" may seem an unusual translation for chromatic, but this is described in more detail later. Vicentino refers to the famous medieval theorist Boethius who wrote about Greek music theory in his 6th century work, De Institutione Musica (The Principles of Music).

Boethius says that chromatic means nothing more than the changing or the transforming of the diatonic sequence... transformed from one system to another. In calling this genus "colored" he did not mean to speak of color in similitudes rather than in literal terms, as some people believe. For just as mixed colors present diverse effects to the eyes, so transformed musical steps mixed in ascent and descent provide the ear with a variety of sounds.

Around the same time, Orlandus Lassus was experimenting with wildly chromatic harmonies in his set of motets, Prophetiae Sibyllarum, whose introductory movement, a sort of Prologue named Carmina chromatico, opens with the following exotic chord progression: C G B C♯m E.

Thus this use of the Greek term "chromatic" had become common place in the Early Baroque, where it was used to describe works like Girolamo Frescobaldi's Toccata Cromatica and Recercar cromatico post il Credo, or Tarquinio Merula's Capriccio Cromatico, his Sonata Chromatica, and his Toccata & Genus Cromaticum (the especially chromatic bit begins at 2:41). It would have been old-hat nearly a century later, when Bach wrote his famous Chromatische Fantasie und Fugue.

Side Note:
It's also worth noting that a decade before Vicentino re-appropriated the tetrachord-based use of the term "chromatic", it had acquired an alternative meaning. The Italian term note nere ("black note") was used to describe an ornamented style of madrigals that were written with shorter-than-usual durations (i.e. the "black" noteheads of quarter- and eighth-notes, as opposed to the usual unfilled noteheads of whole- and half-notes). Sometimes, such madrigals could also called "chromatic". It's not clear if this term was meant in a literal sense (e.g. colored notes), or a figurative one (the elaborate musical style being flamboyant and "colorful"), but the term had no connection to the Greek chromatic genus, as was noted by theorists at the time. However, this alternate association of embellished musical lines being "colorful" can still be seen in the term coloratura.
Comment: Woot, that's a great answer.  It's particularly appropriate that you mention the Greek scales, because I'm just finishing up a kithara.  If you're interested, here's a pic of my last one: http://i578.photobucket.com/albums/ss221/therealzilch/kithara.jpg
Comment: I think your tetrachord intervals should be applied *descending* from higher pitch to low pitch, ie. the half-step in the diatonic genus is the leading tone <-> tonic interval, or 8-7-6-5 from the Major scale.
Comment: @luserdroog Yes and no. My understanding is that while the Greek tetrachords *were* written descending, the larger intervals came first (higher in the scale), for example: A-G-F-E, or A-Gb-F-E. The half step thus acted like the upper leading tone in what we would now call Phrygian mode (though I think the Greeks originally called it Dorian mode). At any rate, I ignored all this in my answer because it was irrelevant to the question.
Answer: The chroma in chromatic does mean color. In chromatic scale, we have full access to all the notes available in the twelve tone equal temperament system.
We don't typically use all 12 notes when composing or playing and we'll mostly stick with a smaller set of typically seven notes from a heptatonic (seven note) scale. We'll also most likely be in some kind of key that defines the expected harmony and tonic. When we use notes outside the typical scale or key that don't necessarily add function to the melody or harmony they are though to add "color" to the piece hence why we describe these tones as chromatic and name the scale that collects all the pitches we have access to as chromatic.
Comment: Very simple, concise and plausible.  In fact the most logical explanation I can think of.  +1.
Answer: That is an interesting question.  And Dom's answer gives the simple explanation that most plausibly explains how the term "chromatic" which originally referred to color and not sound or pitch (from the Greek word chrôma, meaning color) was adopted to describe the full set of 12 musical pitches in Western Music.  I would like to add to Dom's answer and further explore the relationship between colors and musical pitches.
Much of what we perceive in our brain (if not all) originates in the form of some type of frequency that the built in computer inside our skull translates into color or sound among other things.  We know that brain waves can be measured in terms of frequency and new research is applying this concept to allow people who have been paralyzed to control mechanical devices mentally by harnessing varying brain wave frequencies created by thinking about a certain thing - and assigning the different frequencies to different actions of the mechanical device (sort of a computer generated mind over matter).
Just as there is an audible bandwidth of sound (beyond which most humans cannot hear) measured in frequency (how many waves occur in a given moment of time - commonly measured as hertz, or cycles per second) - there is a visible spectrum or bandwidth of light (beyond which most humans cannot perceive) measured in wavelength.  Both sound and light can be measured in terms of "frequency".
Both sound and light travel in "waves" (hence wavelength) - but the light waves are so short it is easier to express their frequency in terms of length of the waves or wavelength.
But we speak of "sound waves" and "light waves". The frequency of these waves is what our internal computer is able to process into what we translate or perceive as a certain pitch or certain color.  Color is nothing more than the "frequency" (measured in wavelength) of the light that is reflected off of a given surface.
There has been a great deal of research correlating sound with color and the chart below provides one example of how to visually demonstrate a correlation between a given wavelength of light and a corresponding frequency of sound.

WWW.LunarPlanner.Com
We perceive sound when the frequency of the sound waves creates a corresponding vibration in the mechanisms of our inner ear which sends this message to our brain.  We perceive light when the receptors on the retina in our eyes calculates the "frequency" of the light waves (wavelength) and sends the message to our brain.  Both sound and color (which again is the wavelength of reflected light) are processed by determining the relative "frequency" (how fast or slow) the light waves or sound waves excite the respective receptors in either our ear or eye - and send this information to be processed by our brain.
This might explain why some people who have synesthesia are actually able to see the color of sound.  And it further supports the logic of using a term associated with color, "chromatic", to describe the full spectrum of available pitch classes in a 12 tone musical scale - (or any other full spectrum scale used in various cultures).
I hope this information provides further enlightenment and illumination into the relationship between sound and color.
Comment: Before anyone points out that this is not a direct answer to the "heading" of the question - I feel that folks who's search terms lead them to this question - may also be interested in the relationship between sound and color (which I find quite fascinating). And it's the only answer so far that address synthesia (mentioned twice in the question).  A deeper interpretation of the entire question leads to a conclusion that it is essentially a question about how sound and color might be associated (with a supposition that this "association" might be behind the use of "chromatic" in music.
Comment: A more interesting color coding assigns adjacent colors to notes which are seven half-steps apart.  If C is a neutral color, a C major chord will contain 0 +4 +1, while C minor will contain 0 +3 +1.  A C7 chord will contain 0 +4 +1 -2, with the +4 and -2 being six colors apart (a tritone).  A music visualizer that uses that approach will only work well if it is tuned to match the music it's responding to, but given that constraint will make two notes a fifth apart appear as very similar colors rather than wildly different.  A tritone will represent opposing colors using either approach.
Comment: @supercat  I agree that would be a great idea for a musical visualizer.  The chart I posted is based on a scientific correlation whereby the frequency of light is correlated with the frequency of sound and matched using a mathematical formula which correlates wavelength (frequency of light) with sound frequency.
Comment: A wavelength-based color visualizer should have notes in lower octaves as red, those in higher octaves as blue.  The colors of light don't repeat with every doubling of frequency the way the keyboard picture does.
Comment: @supercat  Agreed that would be one way to do it.  I think the creator of the keyboard diagram correlated the visible spectrum of light to only one octave and then repeated.  Expanding the range by correlating the entire visible spectrum of light (color) to the entire audible spectrum of sound - might yield less contrast between notes in a given octave.  Let's just agree that there could be numerous ways to  visually represent the idea that sound wave frequency can potentially be correlated mathematically with light wave frequency and a computer or brain could interpret the correlation.
Comment: @supercat  To make the purpose of the chart used in the answer clearer, I edited the paragraph explaining the chart.  Thanks for your assistance in understanding that correlating colors and notes can be represented in many different ways.
Answer: Source: http://etymonline.com/index.php?term=chroma&allowed_in_frame=0
(emphasis mine)

chroma (n.)
  "quality or intensity of color," 1889, from Latinized form of Greek khroma "surface of the body, skin, color of the skin," also used generically for "color" and, in plural, "ornaments, embellishments," related to khros "surface of the body, skin," khrozein "to touch the surface of the body, to tinge, to color;" the root is explained as being somehow from PIE *ghreu- "to rub, grind" (see grit (n.)).

Combined with the information in Caleb Hines' answer, a good explanation is that the ancient Greeks considered tones outside of the diatonic scales/modes to be used for embellishment.
Answer: The analogy of colour is actually really apt. Chromatic notes along with other nonchordal notes are indeed used to give melodies colour. Nonchordal notes or notes that do not belong to the scale often are used to make music interesting by bridging between chordal notes in a manner that makes musical sense.
Melodies, when made effectively, have a strong, conservative choosing of chords with an effective use of nonchordal notes (Including the use of chromatic notes.)
You can if you wish to use an analogy compare it to the work of an Architect. When the Architect is commissioned to build the house he first needs to comprehend the basics of house building.
The house at the very least needs to have a proper foundation. It needs a roof, some windows, and a ceiling.
When he is has done all the basics he can then concern himself with the finer points of the house so that it can appeal to the aesthetics of the homeowner.
Answer: The octave is a rainbow that repeats.
Just as the rainbow has a pattern, if you choose any reference pitch and go up an octave or down an octave, this "pattern" repeats again and again.
Of course 400Hz does not sound exactly the same as 800Hz, but they have the same "color" (Like an Ab and the Ab higher one octave) and thus something that shows this recurring pattern-per-octave can be thought of as chromatic.
Really, the chromatic scale is just an enumeration/play of all the "notes" in a scale, kind-of like how we can "enumerate" all the colors of the rainbow.  Really there are many more than the basic ROYGBIV, and likewise there are far more sounds than can be accurately represented by a 12-semitone instrument.  Considering it this way, the term chromatic takes on the notion of fuzzy-bucketing of sounds into label-able buttons.

Why is it called the chromatic scale?


Approximation of Lebesgue measurable functions by continuous functions.

Question: Let $K\subseteq \mathbb{R}^n$ be a compact set; let $f\colon K\to [-\infty,+\infty]$ Lebesgue measurable function. Then for all $\delta>0$ exists a continuous function $\hat{f}\colon K\to \mathbb{R}$ such that:

$\lambda_n(\{f\ne\hat{f}\})<\delta;$
$\sup_{x\in K}\lvert \hat{f}(x)\vert\le\sup_{x\in K}\lvert f(x)\rvert$.

$\lambda_n$ denotes the lebesgue measure on $\mathbb{R}^n$.
Proof. $(n=1)$
We can assume that $K=[0,1]$. Let $\delta>0$; for known results exists a closed set $C\subseteq [0,1]$ such that $\lambda([0,1]\setminus C)<\delta$ and also $f_{|C}$ is continuous.Since the set $(0,1)\setminus C$ is open in $\mathbb{R}$, results:
$$(0,1)\setminus C=\bigcup_{k=1}^\infty (a_k,b_k),$$
where the intervals $(a_k,b_k)$ are disjointed. We define
$$
\hat{f}(x):=
\begin{cases}
f(x) & \text{if $x\in C$} \\
f(a_k)+\frac{f(b_k)-f(a_k)}{b_k-a_k}(x-a_k) & \text{if $x\in (a_k,b_k)\quad (k\in \mathbb{N}$)}
\end{cases}
$$

Question 1. How do you prove the existence of the limit $$\lim_{x\to 0^+}\hat{f}(x)?$$

Question 2. How to generalize the prove to case $n$? Can you suggest me some text where this theorem is already present? Thanks!
Answer: Answer to Question 1: we split into cases:

If $0 \notin C$ and $C$ closed, then $0$ is not an accumulation point, so there is $(0,\eta) \subseteq (0,1)\setminus C$. The linear interpolation $\hat f$ is clearly continuous at $0$ in this case (a line is right continuous). In fact even if $0 \in C$ but $0$ is not an accumulation point, the same argument holds.
The remaining case is that $0 \in C$ is an accumulation point of $C$. Because the restriction $f|_C$ is continuous, $\forall \epsilon>0$ there is $\delta>0$ s.t. for all $c \in C \cap (0,\delta)$ we have $|f(x)-f(0)|<\epsilon$. Because the linear interpolation on $(a_k,b_k)$ takes values between the numbers $f(a_k),f(b_k)$, if both $f(a_k),f(b_k)$ are within $\epsilon$ of $f(0)$, then so will the intermediate values. Thus we have that for any $c_0\in C \cap (0,\delta)$, we indeed have $|x-0|<c_0 \implies |\hat f(x)-\hat f(0)|<\epsilon$, so continuity from the right at $0$ is proved.

Answer to Question 2: the Tietze extension theorem tells that we can extend any continuous function defined on a closed subset of a normal topological space (e.g. $\mathbb R^n$) to a continuous function defined on all of $\mathbb R^n$ (and we can do so in a way that preserves the sup of the function, which your problem requires). If you already have Urysohn's lemma, this link provides a decent proof. Wikipedia has a nice sketch of the proof of Urysohn's lemma. There is also a proof of Tietze in the context of metric spaces, which may feel more concrete (though it is quite messy): Easier proof of Tietze theorem in metric case..


How to call c++ methods from JNI

Question: in Java code:
System.loadLibrary("twolib-second");

int  z = add(1, 2);

public native int add(int  x, int  y);

first.cpp:
#include "first.h"

int  first(int  x, int  y) {
    return x + y; }

first.h:
#ifndef FIRST_H
#define FIRST_H

extern int first(int  x, int  y);

#endif /* FIRST_H */

second.c:
#include "first.h"
#include <jni.h>

jint
Java_com_example_jniexample_MainActivity_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    return first(x, y);
}

Android.mk:
LOCAL_PATH:= $(call my-dir)

# first lib, which will be built statically
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-first
LOCAL_SRC_FILES := first.cpp

include $(BUILD_STATIC_LIBRARY)

# second lib, which will depend on and include the first one
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.c

LOCAL_STATIC_LIBRARIES := libtwolib-first

include $(BUILD_SHARED_LIBRARY)

I keep getting this error:

/home/username/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld:./obj/local/armeabi/objs/twolib-second/second.o: in function Java_com_example_jniexample_MainActivity_add:jni/second.c:26:
error: undefined reference to 'first' collect2: ld returned 1 exit status make: * [obj/local/armeabi/libtwolib-second.so] Error 1
Comment: first() should have its prototype declared inside an `extern "C" {}` block to avoid *name mangling* if you want it to be callable from C.  But you may have other issues with the build/link as well.
Comment: maybe "how to call c++ function from c" will make a better title for this question.
Answer: you need to use extern "C" to surround the declaration in first.h in order to call func first from second.c.
I guess this is because your first file is compiled as cpp but second as c. the difference is the name mangling. you can call linux bin util command nm to the static lib and object file to list up symbols and see wjere the rob is. i think you will see in the static lib there is a mangled symbol of funcion first; a unmangled symbol of func in the second.o
you will see many many undefined references while programming with ndk. linux bin utils will be nice tool to make life easier.
Comment: you should add that it should be `#ifdef __cplusplus
extern "C" {
#endif` because that way it looks like a C call from both a C and C++ compiler all the same. Also, it's not strictly only name mangling, depending on the platform it's [calling conventions in general](http://www.codeproject.com/Articles/1388/Calling-Conventions-Demystified) that may differ between C++ and C.

How to call c++ methods from JNI


Pythagorean Quadruple Parametric Equation in 3 variables

Question: I am looking for a pythagorean quadruple generator in 3 variables. I know this one with 4 variables.
$$a=2mp+2nq \\
b=2np-2mq \\
c=p^2+q^2-(n^2+m^2) \\
d=p^2+q^2+n^2+m^2 $$
Anyway to do this?
Answer: a=2mp
b=2np
c=p^2-(m^2+n^2)
d=p^2+m^2+n^2
http://mathworld.wolfram.com/PythagoreanQuadruple.html
Comment: you ought to do a simple test on computer, this three parameter method is very far from giving all quadruples. To be specific, it misses $(2,3,6,7)$


To make the shuffled choices appear?

Question: When I print_r($choices) it shows that the array is shuffled but when I don't print nothing happens. Is there a possibility to apply/merge the shuffled choices with the radio button.
Here is the output:

View:
 <?php if(count($questions) > 0):?>
        <?php $index = 1; ?>

        <?php foreach($questions as $row):?>

<?=$index++?>. <?=$row->ques?>

        <?php $choices= array($row->ch_des1, $row->ch_des2, $row->ch_des3, $row->ch_des4);
       shuffle($choices);
       print_r($choices);
       ?>

        <input type="radio" name="ch_id<?=$row->ch_id?>" value="<?=$row->ch_des1?>"> <?=$row->ch_des1?>

        <input type="radio" name="ch_id<?=$row->ch_id?>" value="<?=$row->ch_des2?>"> <?=$row->ch_des2?>

        <input type="radio" name="ch_id<?=$row->ch_id?>" value="<?=$row->ch_des3?>"> <?=$row->ch_des3?>

        <input type="radio" name="ch_id<?=$row->ch_id?>" value="<?=$row->ch_des4?>"> <?=$row->ch_des4?>

        <?php endforeach;?>
    <?php else:?>

                No records found!

    <?php endif;?>

Answer: You can do like this:
<?php if(count($questions) > 0):?>
        <?php $index = 1; ?>

<?php foreach($questions as $row):?>

<?=$index++?>. <?=$row->ques?>

    <?php
        $choices= array($row->ch_des1, $row->ch_des2, $row->ch_des3, $row->ch_des4);
        shuffle($choices);
    ?>
    <?php foreach($choices as $ch_des):?>
        <input type="radio" name="ch_id<?=$row->ch_id?>" value="<?=$ch_des?>"> <?=$ch_des?>

    <?php endforeach;?>

    <?php endforeach;?>
<?php else:?>

        No records found!

Comment: Works perfectly fine. Thank you.

To make the shuffled choices appear?


Linear Regression for iid sample: The value of $E(\epsilon_i^2|x_i)$ is not the same across i. Why?

Question: Linear Regression for iid sample (Y,X).
$E(\epsilon_i^2|X)=E(\epsilon_i^2|x_i)$, where $x_i$ is the i-th observation of k regressors, and epsilon is the error term.
The book I'm using states that from an iid sample we can deduce that $E(\epsilon_i^2)$ is constant across i, and also the functional form of $E(\epsilon_i^2|x_i)$ across i.
However, the value of $E(\epsilon_i^2|x_i)$ is not the same across i. Why is this?
Any help would be appreciated.
Comment: Where you write "the value of $E(\epsilon_i^2|x_i)$ is not the same across $i$," do you perhaps mean to refer to the *regression residuals* rather than the error term?  If not, your question seems to contradict itself.
Answer: Since this is linear regression, we assume the relation
$$y_i = \mathbf x_i'\beta + \epsilon_i,\;\; \forall i$$
and so the i.i.d. sample of size $n$ is, given our assumption, a collection of observations
$$\{y_i,\mathbf x_i\}_{\{i\in [1,n]\}} = \{\mathbf x_i'\beta + \epsilon_i,\mathbf x_i\}_{\{i\in [1,n]\}}$$
Note that we consider the statement "i.i.d. sample" to pertain to the joint distribution of the sample, i.e. of the $y$'s and the $\mathbf x_i$'s. This is the approach usually adopted in Econometrics (see for example Hayashi (2000) ch 1 p. 12 - legally downloadable). Viewed in this light, the "i.i.d. assumption" has some implications for the marginal distribution of the errors, as well as for autocorrelation (it implies no-autocorrelation of the errors), but it does not cover conditional homo/heteroskedasticity.
Specifically, if the sample is (or we assume it to be) i.i.d., then due to the assumed decomposition of $y_i$, it follows from the above that the $\epsilon_i$'s are i.i.d. and so
$$E(\epsilon_i^2) = E(\epsilon_j^2),\;\; \forall i,j \in [1,n]$$
Also
$$E(\epsilon_i^2 \mid \mathbf x_i) = E((y_i - \mathbf x_i'\beta)^2 \mid \mathbf x_i) = E(y_i^2 - 2y_i\mathbf x_i'\beta+ (\mathbf x_i'\beta)^2 \mid \mathbf x_i)$$
$$=E(y_i^2 \mid\mathbf x_i) - 2\mathbf x_i'\beta E(y_i \mid \mathbf x_i) + (\mathbf x_i'\beta)^2 $$
The $\mathbf x_i$'s may be i.i.d. but this does not mean that each actual realization is identical (this would turn the regressors into constants). So, without further assumptions, in general we will have
$$E(\epsilon_i^2\mid\mathbf x_i ) \neq E(\epsilon_j^2\mid\mathbf x_j),\;\; i,j \in [1,n]$$
In other words conditional homoskedasticity must be imposed as an additional assumption. Note also that the assumption of  strict exogeneity (or mean-independence) of the error vector with respect to  the regressor matrix, $E(\epsilon \mid \mathbf X) = 0$, which for an i.i.d. sample is equivalent to $E(\epsilon_i \mid \mathbf x_i) = 0,\; \forall i$, does not bring about conditional homoskedasticity, the latter remaining a distinct assumption.
Comment: @whuber ok, I get it now. Yes this is where our interpretations differ. By "i.i.d sample" I understand a statement about the joint distribution of the regressors and the dependent variable, perhaps because the actual sample contains values of $X$'s and $Y$'s, so any characterization of it seems natural, to me, to pertain to the data generating mechanism of these values. CONTD
Comment: @whuber CONTD Even seen in this light, the assumption does imply some things about the errors, like no-autocorrelation for example, or identical unconditional moments, but it does not cover conditional hetero/homskedasticity. I believe this is the approach usually adopted in Econometrics, for example Hayashi 2000, p.12, explicitly points out that under an i.i.d. sample, the conditional homo/heteroskedasticity assumption remains a distinct one.
Comment: Why doesn't the iid assumption imply "conditional homoskedasticity"?
Comment: @whuber I would say because it is a statement about "inter-observation" marginal/joint distributions, and not about "intra-observation" conditional ones? The law of Total Variance together with i.i.d. and strict exogeneity, impose only that all conditional variances have the same expected value. And the conditioning set $\mathbf x_i$ differs for each $i$, although it is identically distributed. Am I missing something?
Comment: Alecos Many thanks for your answer. Have some doubts about it though.Could you elaborate more on $E(y_i^2|x_i)$, namely on the distribution of $y_i|x_i$, without referring to the error term. $E(y_i|x_i)$ is a constant so there  is no need for elaboration here. But the other, I would like to know if from $(y_i,x_i)\sim F$ what we can say about $y_i|x_i\sim$?
Comment: $E(y_i|\mathbf x_i)$ is not a constant - it is equal to $\mathbf x_i'\beta$, which is not constant. These conditional expected values are not with respect to a specific value of the regressors, but to their sigma-algebras. Apart from that, the conditional distribution for each $i$ is exactly the subject of additional assumptions, we cannot "pin down" the conditional variance from the i.i.d. assumption.
Comment: Sorry, you're right, $x_i'\beta$ is not a constant. As to the answer to the last question in my previous comment, you say that we cannot pin down the conditional variance from the iid assumption.  But can we pin down something? (from the book I would say the functional form of the distribution can be pin downed) How or why?
Comment: I don't think you're missing anything, Alecos, but perhaps there are some different interpretations occurring. To me, the first line "linear regression for iid sample" means there exists an (unknown, vector) parameter $\beta$ such that the random variables $(Y-X\beta)|X$ are independent and all have the same distribution. At some level you seem to be adopting a different interpretation in which $(X,Y)$ has some (arbitrary?) bivariate distribution. I'm not completely sure what your assumptions are--but they do seem to lead you to different conclusions than my interpretation does.
Comment: Thank you. If you get a chance, it would be nice if you could incorporate this explicit characterization of your assumptions within your answer.
Comment: @whuber. Done as suggested.
Answer:
However, the value of $E(\epsilon_i^2|x_i)$ is not the same across i.
  Why is this?

Let's first clarify that your book is most likely talking about the errors, not the residuals. The difference is that the former is not observable, while the latter is. Regression assumes that the true model is $y=X\beta+\varepsilon$, where $\varepsilon$ is a random error. It's not observable.
The regression modeling will try to estimate the coefficients, and will come up with $y=Xb+e$, where $b$ is the estimated coefficients, and $e$ - residuals (estimated error). You are hoping that at least $X$ is correct, i.e. that you added all the true predictors, and didn't add wrong predictors. You hope that your model is correctly specified, then go ahead with estimating $b$ and $e$. Note, that at any moment you do not observe true errors $\varepsilon$. Therefore, your statement above seems to be stemming from confusion of errors and residuals. You can't really state that expectations of errors are correlated with predictors, because you don't observe them. You don't observe erros, and it's even less observable are their expectations. You can suspect that they are, and run some tests on residuals to support your suspicion.
The residuals are observable, of course. You estimated them. How are you going to estimate the expectation of residuals like in your statement above? You observe individual residuals $e_i$, but how would get $E[e_i]$? On the other hand $E[e|X]=0$ is guaranteed by the regression. It's just how the regression works: it will estimate residuals in such a way that this will be held true.


Mock or override extended class in angular2

Question: Hello every body i have some problems with angular2 unit tests. Can anybody help me?  I have some class like this

export class PostcodeApiService extends ApiService {

  constructor(Http: Http, auth: AuthService) {
    super(Http, auth);
  }

  getPostcodes(filterObject) {
    return super.post('postcodes/filter', filterObject );
  }
}

export class ApiService {

  constructor(private http: Http) {
  }

  post(url, payload: any) {
    return new Observable((observer) => {
        this.http.post(`someUrl/${url}`, payload)
          .map((res: Response) => res.json())
          .catch((error: any) => {
            return Observable.throw(error || `Server error ${url}`);
          })
          .subscribe((data) => {
            observer.next(data);
          });
    });
  }

}

How can do mock of ApiService.post() function?
My spec file look like this

describe('PostcodeApiService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PostcodeApiService,
        Http,
        ConnectionBackend,
        AuthService,
        UserService
      ],
      imports: [
        HttpModule
      ]
    });
  });

  it('should ...', inject([PostcodeApiService], (service: PostcodeApiService) => {
    // How ovveride post method ?
  }));

});

I would be grateful if you could help me with this thing.
Thanks for attention!
Answer: Create a mock class:
    class PostcodeApiServiceMock extends PostcodeApiService {
      post(url, payload: any) {
        // do something
      }
    }

and provide it with
    { provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }

You can find a good example here:
https://angular.io/guide/testing#test-a-routed-component
Comment: Somehow this is not working for me and afaik you can only override injectables that way (in the example `Http` and `AuthService`), not extended classes :(
Is there a way to completely exchange the service's superclass (aka prototype) for testing?


Algorithm to find the coefficient of GCD linear combination?

Question: One of the properties of the GCD of two integers is that it can be written as the linear combination of the two, is there an algorithm that can be used to find the coefficients of this linear combination?
Comment: There are many. Please look at the [*Extended Euclidean Algorithm*.](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
Answer: Once you have found the GCD of two numbers using the Euclidean Algorithm, you can work backwards and find the coefficients. I'll illustrate it with an example.
Find the GCD of  803 and 154, and then express it as a linear combination of 803 and 154.
$803 = 5 \centerdot 154 + 33$ call this line (1)
$154 = 4  \centerdot 33 + 22$ call this line (2)
$33 = 1  \centerdot 22 + 11$ call this line (3)
$22 = 2  \centerdot 11 + 0 $
and so the GCD is 11 (the most recent remainder in line (3)). Now we can express 11 as a linear combination of 803 and 154:
$(803, 154) = 11 = 33 - 1  \centerdot 22$ by (3)
$ = 33 - (154 - 4\centerdot 33)$ by (2)
$= 5\centerdot 33 - 154$
$= 5\centerdot (803 - 5 \centerdot 154) - 154$ by (1)
$= 5 \centerdot 803 - 26 \centerdot 154$
$= 5 \centerdot 803 + (-26) \centerdot  154$
and so we have found our coefficients.
Answer: The answer of @LonelyMathematician is perfect, but I confess that I have always found this way of describing the action just too confusing. Let's step back a bit and look at what's going on. In each step, you start with (dividend, divisor) and get a new pair, (newdividend, newdivisor), where the new dividend is the old divisor, and the new divisor is the remainder, equal to dividend - quotient times divisor. You see that this is a linear relationship expressible by a matrix equation:
\begin{align}
\begin{pmatrix}\text{newdividend}\\ \text{newdivisor}\end{pmatrix}
=
\begin{pmatrix}
0&1\\1&-\text{quotient}
\end{pmatrix}
\begin{pmatrix}\text{dividend}\\ \text{divisor}\end{pmatrix}\,.
\end{align}
Too wordy! Let's do exactly the same computation as @LonelyMathematician, finding the greatest common divisor of $805$ and $154$. The first step is to say that
\begin{align}
\begin{pmatrix}154\\33\end{pmatrix}
=
\begin{pmatrix}0&1\\1&-5\end{pmatrix}
\begin{pmatrix}803\\154\end{pmatrix}\,.
\end{align}
We didn't even need to write that out, except maybe to set our doubts to rest. The four matrices have the lower-right entries of $-5, -4, -1, -2$, these are the quotients of the divisions, but the matrices have to be written in the right order, and multiplied out.
\begin{align}
\begin{pmatrix}0&1\\1&-2\end{pmatrix}\begin{pmatrix}0&1\\1&-1\end{pmatrix}
\begin{pmatrix}0&1\\1&-4\end{pmatrix}\begin{pmatrix}0&1\\1&-5\end{pmatrix}=\begin{pmatrix}5&-26\\-14&73\end{pmatrix}\,,
\end{align}
and if we call this two-by-two matrix $A$, we see that
\begin{align}
\begin{pmatrix}11\\0\end{pmatrix}=A\begin{pmatrix}803\\154\end{pmatrix}\,,
\end{align}
in other words, the proper coefficients are found on the top row of $A$, namely $5$ and $-26$.
I think that you'll agree that this method is very easily programmed.
Comment: Nice methodical way of doing things for those who have seen matrix algebra before. I like it.


I'm a bass and I need to know what a Russian bass vocal range is

Question: My range extends down to a low D; I forget how high I can go. I'm 14 years old and my music teacher is saying that I'm a Russian bass.
What exactly is a Russian bass voice?
Comment: If you are 14, beware of making decisions about your vocal future by looking up blogs on the internet. Get yourself the best vocal advice you can. It might not be expensive. There might be a teacher at school or a choirmaster at church or someone else you can trust. Good luck for the rest of your vocal career.
Answer: A Russian bass is a person that can easily reach a deep-ranged basso profondo. It is named like this, because these notes appeared in a  lot of Slavic composers' works.
Per Wikipedia:

Many basso profondos have trouble reaching those notes, and the use of them in works by Slavic composers has led to the colloquial term "Russian bass" for an exceptionally deep-ranged basso profondo who can easily sing these notes. Some traditional Russian religious music calls for A2 (110 Hz) drone singing, which is doubled by A1 (55 Hz) in the rare occasion that a choir includes exceptionally gifted singers who can produce this very low human voice pitch.
Answer: Well, Praetorius "Erhalt uns, Herr, bei Deinem Wort" version in 17 voices had one voice going down to at least low C, possibly contra-A (don't remember exactly).  I remember because our director had to scratch together all eligible singers for that low voice, so I sang bass instead of the usual tenor.
That's not even Russian but still German, but admittedly in a setting with 4 choirs.  Russian singers will not infrequently be able to sing contra-A with conviction, and some go quite lower.


Too many TIME_WAIT state connections!

Question: I've been reading about this everywhere all day, and from what I've gathered, TIME_WAIT is a relatively harmless state. It's supposed to be harmless even when there's too many.
But if they're jumping to the numbers I've been seeing for the past 24 hours, something is really wrong!
<code>[root@1 ~]# netstat -nat | awk '{print $6}' | sort | uniq -c | sort -n
  1 established)
  1 Foreign
 12 CLOSE_WAIT
 15 LISTEN
 64 LAST_ACK
201 FIN_WAIT2
334 CLOSING
605 ESTABLISHED
816 SYN_RECV
981 FIN_WAIT1
26830 TIME_WAIT
</code>
That number fluctuates from 20,000 to 30,000+ (so far, the maximum I've seen it go is 32,000).
What worries me is that they're all different IP addresses from all sorts of random locations.
Now this is supposed to be (or was supposed to be) a DDoS attack. I know this for a fact, but I won't go into the boring details. It started out as a DDoS and it did impact my server's performance for a couple minutes. After that, everything was back to normal. My server load is normal. My internet traffic is normal. No server resource is being abused. My sites load fine.
I also have IPTABLES disabled. There's an odd issue with that too. Every time I enable the firewall/iptables, my server starts experiencing packet loss. Lots of it. About 50%-60% packets are lost. It happens within an hour or within a few hours of enabling the firewall. As soon as I disable it, ping responses from all locations I test them from start clearing up and get stable again. Very strange.
The TIME_WAIT state connections have been fluctuating at those numbers since yesterday. For 24 hours now, I've had that, and although it hasn't impacted performance in any way, it's disturbing enough.
My current tcp_fin_timeout value is 30 seconds, from the default 60 seconds. However, that seems to not help, at all.
Any ideas, suggestions? Anything at all would be appreciated, really!
Answer: A good discussion about time-wait is given by How to forcibly close a socket in time-wait.
According to this reference, the number of time-wait connections should correspond to the traffic in the last 4 minutes.  Do these numbers approximately match?
Answer: I've had this problem with connections in a close-wait state when the other end isn't hanging up properly. This may be because of a malicious reasons, or because there is a problem in your networking stack.
The fact that you appear to be having problems with iptables points to problems with your network stack too.
It is worth switching your connection to another network port if you have one to see if the same problem occurs on that. The problem could also be with an upstream firewall, router or bad guy.
There are also some reports of issues with the RedHat (+Centos?) settings of tcp_tw_recycle. You may want to look into that.

Too many TIME_WAIT state connections!


Laurent series for $\frac{e^z}{1 - z}$ for $|z| > 1$

Question: I do this like $\dfrac{e^z}{1-z}$ = $-e \dfrac{e^{z-1}}{z-1}$ = $-e \sum_{k=0}^{\infty} \dfrac{(z-1)^k}{k!(z-1)}$ = $-e \sum_{k=0}^{\infty} \dfrac{(z-1)^{k-1}}{k!}$
However doesn't this give me the Laurent series around $|z-1| > 0$? Should I do a taylor expansion of the first term $\dfrac{-e}{z-1}$ to a geometric series to get the expansion for $|z|>1$?
Maybe I have just messed up some definitions, sorry if that's the case.
Comment: *Hint:* Taylor series for $e^z$ converges everywhere and $$\dfrac1{1-z} = -\dfrac1z \dfrac1{1-1/z}.$$
Answer: $|z|>1$ is an annulus with center $0$, thus all powers of the relevant Laurent series should be of the form $(z-0)^k$.
On the one hand $$e^z=1+z+\frac{z^2}{2}+ \dots=\sum_{k=0}^\infty \frac{z^k}{k!}$$
On the other $$\frac{1}{1-z}= -\frac{1}{z} \frac{1}{1-1/z}=-\frac{1}{z} \sum_{k=0}^\infty \frac{1}{z^k}=\sum_{k=0}^\infty- \frac{1}{z^{k+1}} $$
Try multiplying both series and collecting the terms of the same degree.
Comment: Super! This was the answer I was looking for!
Answer: Put $1 - z = u$. So you shall get $\frac{e^z}{1 - z} = \frac{e^{1-u}}{u} = e \frac{e^{-u}}{u}$.
Now expand it in terms of $e^{-u}$ and get $e \left( \frac{1}{u} - 1 + \frac{u}{2!} - \dots \right)$
Now put the value of $U$ and finally you shall get
$$\frac{e^{z}}{1 - z} = e (\frac{1}{1-z} - 1 + \frac{1 - z}{2!} \dots )$$
The function has a pole of order $1$ at $z = 1$.
Comment: This idea will give the expansion for $|z-1|>0,$ not for $|z|>1$.
Comment: This is the same thing I've done in the question formulation. I wanted to know whether this expansion was around $|z-1| > 0$ or $|z|>1$ (answered above).


Does group by on entire dataframe followed by filter column take more memory compared to selecting the columns first?

Question: I am trying to understand the working of the below code snippets:

titanic.groupby("Sex")["Age"].mean()

This considers a group by sex for all columns, then selects Age column, then performs the aggregate.

titanic[["Sex", "Age"]].groupby("Sex").mean()

This fetches the sex, age columns. Then does a group by on sex. Then calculates the aggregate.
Is the 2nd option using lesser memory?
Answer: It seems to use more memory, based on this test using tracemalloc:
import tracemalloc
import pandas as pd

titanic = pd.read_csv('train.csv')
tracemalloc.start()
# titanic.groupby("Sex")["Age"].mean()
titanic[["Sex", "Age"]].groupby("Sex").mean()

print("Current: %d, Peak %d" % tracemalloc.get_traced_memory())

titanic.groupby("Sex")["Age"].mean() gave Current: 59549, Peak 69110
titanic[["Sex", "Age"]].groupby("Sex").mean() gave Current: 89642, Peak 125526
This is however just a small data set of shape (891, 12).


How do I build a user table with aggregated article data?

Question: I'm new to Drupal, and I want to make an overview over aggregated user data related to the articles they have written.
I basically want to build a table like this:
<code>------------------------------------------------------
| user | articles published | articles with comments |
------------------------------------------------------
| bob  |                 12 |                      3 |
------------------------------------------------------
| sue  |                 34 |                      0 |
------------------------------------------------------
| kim  |                  0 |                      0 |
------------------------------------------------------
</code>
What is the best way to make a table like this? Is this something I need to make my own module for?
Would it be possible to aggregate this with an existing module?
Comment: Which version of Drupal you are using ?
Comment: I'm using Drupal 7.15.
Comment: Ok, You can use below code then in a custom block with format as PHP. I hope you are using default Article Content Type that comes with Drupal Installation.
Answer: Welcome to the Drupal StackExchange !
You can achieve this with some custom php code and couple of queries.
<code><?php

   $articles_publishers = db_query("SELECT DISTINCT u.uid FROM {node} n LEFT JOIN {users} u on n.uid = u.uid where n.type = 'article'");
   foreach ($articles_publishers as $articles_publisher) {
     $publisher = user_load($articles_publisher->uid);
     $username = theme('username', array('account' => $publisher));
     $articles_published = db_query("SELECT count(*) FROM {node} where uid = :uid and status = 1 and type='article'", array(':uid' => $articles_publisher->uid))->fetchField();
     $articles_published_with_comments = db_query("SELECT count(*) FROM {node} n INNER JOIN {comment} c ON n.nid = c.nid where n.uid = :uid and n.status = 1 and n.type='article'", array(':uid' => $articles_publisher->uid))->fetchField();

     // Theme the information with above results

     print "Username :" . $username;
     print "articles published :" . $articles_published;
     print "articles with comments :" .  $articles_published_with_comments;
   }

?>
</code>
use above code in a module custom block or Add Block with php option to display the information.
Hope it helps.
Comment: Thank you! When I go through the Add block form, I never see any "php option". Is this due to my Drupal verson (7.15), or am I just missing it?
Comment: Enable PHP filter module to see the PHP format !
Comment: Aha! Tanks Anil! Sorry about not voting you up, I don't have enough reputation yet :-)


Views escapes HTML tags in node body

Question: I'm creating a view that displays a few fields from a specific content type. Among the fields is the trimmed nody body. The problem is that the HTML tags in the body are escaped and are visible as source in the view.
So instead of

Lorem ipsum dolor sit amet, in dolores propriae sapientem vim. Per no
  autem minimum iudicabit, ad numquam eloquentiam ius. Quas iusto ea
  vis. Mea quaestio gloriatur mediocritatem et. Mei rebum postea ne, his
  malorum necessitatibus ei. Ea pro animal mandamus, ad pri postea
  eripuit.

I get the following:

Lorem ipsum dolor sit amet, in dolores propriae sapientem
  vim. Per no autem minimum iudicabit, ad numquam eloquentiam ius. Quas
  iusto ea vis. Mea quaestio gloriatur mediocritatem et. Mei rebum
  postea ne, his malorum necessitatibus ei. Ea pro animal mandamus, ad
  pri postea eripuit.

From what I understand Drupal 8 escapes everything by default, so I suspect this has something to do with my problem. I looked at every setting I could find in Views, but I couldn't find anything that would change the escaping of HTML tags.
How can I output the body of a node unescaped in a Drupal 8 view?
Comment: I believe I saw an issue on drupal.org dealing with exactly this bug. Maybe it is already resolved and you just need to use the newest beta. Else you should search for the issue and apply the proposed patch manually in case it is urgent.
Comment: Yes, it may be this: https://www.drupal.org/node/2363423, committed to 8.0.x but it was after beta 14, so if you're just following betas it will be in beta 15.
Comment: Just to be 100% sure, the field is a full_html text type, right?
Answer: I'd recommend against accepting this right away even if it works for you because I suspect it isn't the best answer, but I ran into this same problem and I ended up just overriding the template with raw HTML like so:

Copy core/modules/views/templates/views-view-fields.html.twig to the appropriate location in your own theme (e.g. themes/custom/mytheme/templates/views/views-view-fields.html.twig for me)
For each variable output in the loop add the raw filter, e.g. {{ field.content | raw }}
Clear your caches and refresh the page to see the result

I think this should be okay since any HTML that comes from the views fields should already be filtered of anything harmful (and I believe this is more or less how it used to be done - take a look at the old PHP views templates) but if someone knows better please do correct me in the comments.
EDIT: I noticed one of the related questions (Drupal 8: HTML isn't rendering, HTML tags are being printed) has a link to this issue: https://www.drupal.org/node/2363423 which I believe is related, so this workaround may soon no longer be necessary.

Views escapes HTML tags in node body


Commerce, different price based on quantity

Question: Is that even possible?
I read that Drupal 7 has some discount modules for that, but Drupal 8 doesn't have anything. Is that true? And maybe someone can point me in the right direction how to achieve this goal...
I have found this post: Drupal Commerce - product attribute price based on quantity which suggests using https://www.drupal.org/project/commerce_price_table module but nothing for Drupal 8.
Comment: It looks like you would need price lists, like in a B2B situation. See this module, which should have some sponsored work behind it soon https://www.drupal.org/project/commerce_pricelist
Answer: You can set a Promotion based on Product's quantity if that's what you're looking for. Just give a go to commerce_promotion module (included in Commerce 2.x core) and enable set conditions as on the picture below.
Comment: Thanks. It does kinda work. It doesnt' change the price on the product page, and not even on the cart page, but adds a "discount" by substracting the amount difference. I'll live with that for now.
Answer: Try the Commerce Extended Quantity module price adjustments for a current quantity in the cart: https://github.com/drugan/commerce_xquantity#quantity-price-adjustments


WPF touch application for Windows 8

Question: I know it is possible to do a Touch Application for Windows 7 using the Surface SDK in Visual Studio 2010.
I would like to do the same thing in a Windows 8 environment but Surface is unfortunately not supported.
I do not want to build a Metro Application but I need an executable with touch support that works in Win 8.
Does anyone know if it possible to do a touch exe for windows 8?
Answer: You can use the SDK on a windows 8 machine. I'm using visual studio 2010 with the sdk on my machine. You'll need to install Xna to to make it work. And in xaml, change your windowtype from surfacewindow to window.
Comment: Thanks for your tip :-). Do you know if the executable is going to run even in another Win 8 machine without VS 2010 installed? I can't install in any pc where the program will work Visual Studio.
Comment: Yes it will work. I got it even running on a windows 7 computer, but this has given us some issues in the past. Best to use it on a win8 machine.

WPF touch application for Windows 8


MenuItems with fixed length

Question: I've got a Menu which receives a dynamic ItemsSource. The number of items and their length varies from time to time.
<Menu ItemsSource="{loc:CustomBinding CurrentMenuItems}" />

The menu's orientation is Horizontal, at times this causes the menu to overflow.
The Menu Items Template :
<ControlTemplate TargetType="{x:Type MenuItem}">
    <TextBlock Text="{loc:CustomBinding Title}"
               MaxWidth="200"
               TextTrimming="CharacterEllipsis"/>
</ControlTemplate>

When there are more than 4 items, the menu overflows outside the left side of the screen
(sorry can't upload pictures from the work place).

Are there any built in overflow options to WPF menu?
Is there an option to control overflow of menu items from the menu itself? Something along the lines of ItemsMaxLength which I could of bound to a calculated field?
Comment: 1) No, you customize its template
2) Yes there is and as long as the menu's control parent container is appropriate like Grid then it will automatically calculate what the width it
Answer: I'm not clear what you want to happen when the rightmost menu items cannot fit on the screen. Is it?:

wrap them to the next line
crop them fully
crop them partially
put them in an overflow dropdown?
show an ellipse or other "more" indicator?

The default ItemsPanel template for a Menu uses a WrapPanel...that should wrap them to the next line (unless you have set a height for the menu or your menu is in a container that is isn't allowing it to have its desired height).
We can change the ItemsPanel used to change how items are layed out.
In the example XAML below I show 4 ways to display a menu. You can use this within Kaxaml to see the different behaviours...resize the Window to a small width to see what happens when there isn't enough horizontal space.

the original menu style...wraps menu items that don't fit
a menu that fully crops the menu item that doesn't fit
a menu that partially crops the menu item that doesn't fit
a menu that uses a Toolbar...any items that don't fit go into an overflow panel (note this example isn't perfect...it doesn't exactly adhere to the standard menu
selection behaviour with the mouse/keyboard because its using separate menus for each item...and the style is a little off...and it shows a toolbar gripper....more work would be needed).

If 4 is closest to what you want, then you somehow need to combine the behaviour or a ToolBar with it's overflow panel...with the behaviour of a menu and it's tracking/navigation between menu items.
You might be able to achieve that by creatively re-templating the menu, or the toolbar, or creating your own custom control.
 <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="MainWindow"
    Width="640" Height="480">
    <StackPanel Orientation="Vertical">
        <Menu>
            <MenuItem Header="_File">
                <MenuItem Header="_Exit"/>
            </MenuItem>
            <MenuItem Header="_Edit"/>
            <MenuItem Header="_Window"/>
        </Menu>
        <Menu>
            <Menu.ItemsPanel>
                <ItemsPanelTemplate>
                <ToolBarPanel IsItemsHost="True" Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </Menu.ItemsPanel>
            <MenuItem Header="_File">
                <MenuItem Header="_Exit"/>
            </MenuItem>
            <MenuItem Header="_Edit"/>
            <MenuItem Header="_Window"/>
        </Menu>
        <Menu>
            <Menu.ItemsPanel>
                <ItemsPanelTemplate>
                <StackPanel IsItemsHost="True" Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </Menu.ItemsPanel>
            <MenuItem Header="_File">
                <MenuItem Header="_Exit"/>
            </MenuItem>
            <MenuItem Header="_Edit"/>
            <MenuItem Header="_Window"/>
        </Menu>
        <ToolBar>
        <ToolBar.Resources>

</Style>
        </ToolBar.Resources>
          <Menu>
            <MenuItem Header="_File">
                <MenuItem Header="_Exit"/>
            </MenuItem>
          </Menu>
          <Menu>
            <MenuItem Header="_Edit"/>
          </Menu>
          <Menu>
            <MenuItem Header="_Window"/>
          </Menu>
        </ToolBar>
    </StackPanel>
</Window>

Comment: it still gos outside the scode of the screen
it's already a StackPanel .

MenuItems with fixed length


Using YouTube Data API to upload videos only with OAuth 2.0

Question: For the context: I am building a React App that allows users to upload an MP3 file and an image. Both these files get rendered to an MP4 file through FFmpeg on the client side (in React). I then want to let the user upload the result to YouTube.
So technically everything executed on the YouTube API comes from the user and isn't made through any server. How would I go about uploading the video without having an API Key, just having an OAuth 2.0 object from the user that signed in and that wants to upload the processed video to their channel?
The main problem is that generally a YouTube user has a quota of 50 uploads per day that can be made use of but if I follow YouTube's docs I'd have to upload the videos through a Google Cloud Project Client (which gives me an API Key) and said client would have a predefined quota for all requests (which is about 2 videos per day). Now that's not what I want, through using a client my entire app would only have 2 uploads per day and not 50 uploads per day per user.
Does anyone have experience with such a problem or an idea on how I could work this out?
Comment: please edit your question and include [example]
Answer:
How would I go about uploading the video without having an API Key, just having an OAuth 2.0 object from the user that signed in and that wants to upload the processed video to their channel?

Uploading or inserting videos in to YouTube requires that you be authorized. What you do is send an authorization header with a bearer token as shown below.
<code>curl --request POST \
  'https://youtube.googleapis.com/youtube/v3/videos \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{}' \
  --compressed
</code>

The main problem is that generally a YouTube user has a quota of 50 uploads per day

This is actually a hard limit imposed by YouTube itself it is not related to the api you are using.  No one can upload more than 50 videos a day.

if I follow YouTube's docs I'd have to upload the videos through a Google Cloud Project Client (which gives me an API Key) and said client would have a predefined quota for all requests (which is about 2 videos per day).

Im not sure where you read this can i have a link to that doc?
First off api keys are used when accessing public data, for example public videos stored on youtube. you could do a video.search with an api key you dont need an access token.  What it does is identify your project to google so it knows which project to deduct the quota from.  But an access token does exactly that so you dont need both. In your case inserting a video you dont need an api key for that.
To be clear an api key should not give you access to insert a video as it can only access public things. IT cant upload to a privet user account with out permission and an api key has no permission.
Comment: Thanks for your detailed answer. The docs I was referring to at https://developers.google.com/youtube/v3/docs/videos/insert?apix=true show a sample curl request which has a parameter for the API key in the request URL. That, for me, meant that I would have to set up a Google Project which then is subject to quota reduction. Though that's not what I want. If I just send the upload POST-request to Google (as you showed in your curl snippet), do I still affect quota or would there only be the constraint of the 50 uploads per day?
Comment: key is a default value and is not required.  I have been trying to get google to remove that for ten years.   50 uploads per day per user / channel.   Its the user that authenticates your app that gets the access token that is used.   That is what defines the 50 limit.   So if you authorize your app you get 50, if i also authorize your app i also get 50.  But remember your going to be limited by the quota


Range of IDs via ActiveRecord

Question: I understand that I can use People.first(100) to retrieve the first 100 records, same goes for People.last(100).
What I don`t know, is how do I retrieve all objects in the range of 200-400, when the total number is lets say a 1000 records ?
Answer: What you need is limit and offset - read this for more info.
Example:
People.limit(200).offset(200)

The above code takes 200 records starting from 201st record - that means it would be records 201-400.
Comment: Keep in mind that this will not return values within a range, it will return 200 records starting at the 201st record.  So say you've deleted 50 records with ids between 200 and 400, you're going to get 200 records but your records could have an id of anywhere between 200 and 450.  Does that make sense?  So the limit-offset method ensures you get 200 records, but if you're looking for a range of ids(or some other field) you would use the where method.
Answer: Are you searching on a specific field, your title suggests you're searching on id?
People.where('id BETWEEN ? AND ?', 200, 400)

or...
People.where(id: 200..400)

If you're not searching on a particular field, you would want to use Big_Bird's limit and offset methods.

Range of IDs via ActiveRecord


File upload using PrototypeJs method $('formId').request()

Question: I was trying to upload file(s) using PrototypeJs request method but I failed.
The code I am using,
<form enctype="multipart/form-data" id="form1" runat="server" action="ajax.aspx"
onsubmit="upMe(this);return false;" >

If I make return true instead of false, the file is uploaded but that makes postback which I dont want as I am using the method request from PrototypeJs.
And the function upMe is very simple,
function upMe(frmEle) {
        $(frmEle).request({
            method: 'post',
            parameters: {},
            onComplete: function() { alert('file has been uploaded'); }
        });
    }

What I am missing to upload file in the above way?
Thank you so much.
Answer: The problem is you're using AJAX instead of normal submission methods to post the form.  This would require JavaScript to read the file and include it in the submission, but as you can imagine the ability for a script to read a local file from the client would be rather a large security risk :-)
The answer to this problem is to use a hidden  element instead, and submit the request to that.  You can register event handlers to the iframe's onload event for an oncomplete style callback.
http://www.openjs.com/articles/ajax/ajax_file_upload/
Comment: Thank you so much.
Using Iframe is like submitting the files which causes partial postback not adjactly the Ajax way. Though using Ifrmae the purpose is served. Would you mind to provide an example where ajax is really playing in the file upload.


Having multiple classes on a table row

Question: All,
I've got the following CSS for an HTML row:
.clickable_row:hover {
cursor: pointer;
}
.clickable_row:hover {
background-color: #FFFFCF;
}

Then my html looks like this:

Text

However, for the highest row I'd like to add a highlighted class to it as well. I tried to do something like this:

Text

Then added the following CSS:
.clickable_row highlighed{
background-color: #BFDEFF;
}

This doesn't highlight the row, any ideas on how to make this work?
Thanks
Answer: Use
.clickable_row.highlighed{
    background-color: #BFDEFF;
}

or just
.highlighed{
    background-color: #BFDEFF;
}

Your selector looks for a descendant of element with class clickable_row which is a highlighed tag
Answer: When you put a space in a class name, you are creating a completely new class, so
 creates the class "clickable_row" aswell as the class "highlighted".
If you want to highlight it, just do .highlighted { background-color: #BFDEFF; }
Although, if you want to optimise, I'd probably recommend using the :first-child selector, this will highlight only the first row, without you needed to give it a separate class

Having multiple classes on a table row


How to check if a given vector is in the image of a linear transformation?

Question:
Determine whether or not $(1,3,1)$ or $(-1,-1,-2)$ is in the image of the linear transformation $T: \mathbb R^4 \to \mathbb R^3$ defined by $T(x) = A x$, where
$$A = \left(\begin{array}{crc}
 1 &  2 &  -1 & -1\\
1 & 0 & 1 &  1\\
 2 &  -4 &  6 & 2\\
 \end{array}\right)$$

I don't know how to do this problem and would greatly appreciate some help!
Comment: To see if $\mathbf{b}$ is in the image of $A$, it suffices to see if the system of equations given by $A\mathbf{x} = \mathbf{b}$ has any solutions for $\mathbf{x}$.
Comment: @Jared It's possible that op hasn't made the connection between matrices as linear functions and as representing systems of equations. I think it's helpful
Comment: Use Rouché-Capelli theorem.
Comment: @qbert I don't think I have made the connection
Comment: @florence To me this doesn't really illuminate the problem (but maybe it does).  You are virtually restating the problem.  Of course to show that a certain vector is in the image is to find a vector in $\mathbb{R}^4$ that creates that said vector.
Answer: One way or another, you're going to have to do some form of row-reduction.  If we think of the "usual" case, then four dimensions should easily be able to be mapped to three dimensions meaning that any $3$-vector would be possible.  So the best thing to do is to row-reduce your matrix and find the rank of your matrix (The maximum number of linearly independent vectors in a matrix is equal to the number of non-zero rows in its row echelon matrix).
$$
\begin{pmatrix}
1&2&-1&-1\\
1&0&1&1\\
2&-4&6&2
\end{pmatrix}
$$
$$
\begin{pmatrix}
1&2&-1&-1\\
0&2&-2&-2\\
0&8&-8&-4
\end{pmatrix}
\sim
\begin{pmatrix}
1&2&-1&-1\\
0&1&-1&-1\\
0&2&-2&-1
\end{pmatrix}
$$
$$
\begin{pmatrix}
1&2&-1&-1\\
0&1&-1&-1\\
0&0&0&-1
\end{pmatrix}
$$
You can see from this that this matrix spans $\mathbb{R}^3$ (for it not to, it would have to have at least one row that is all zeros).  Therefore you can pick any vector in $\mathbb{R}^3$ and this matrix could produce it from a $4$-vector.
Answer: The correct procedure computationally is to bring thee matrix to echelon form by row operations (gaussian elimination), and mark the columns corresponding to leading 1's. Now again repeat the same procedure by appending the $b$ vector as extra column.  If no new columns are introduced by way of leading 1's then the said vector is in the image. Otherwise not.
Answer: Using the Gaussian elimination we have $T(2,0,\frac{-5}{4},\frac{9}{4})=(1,3,1)$ and $T(-1,0,0,0)=(-1,-1,-2)$.
Answer: The comment made by florence has the most obvious approach.

$b$ will be in the image of $T$ if and only if there exists an $x$ such that $T(x)=b$. This last equation simplifies to just be $Ax=b$, which corresponds to a system of linear equations for the components of $x$. If we can solve this system then we know $b$ is in the image of $T$. If the equations are inconsistent then $b$ is not in the image of $T$.
As an exaple consider the following case,
$$A= \left(\begin{array} \ 1 & 1 \\ 1 & 1 \end{array}\right) \qquad b=\left(\begin{array} \ 3 \\ 3 \end{array}\right),$$
then $Ax=b$ becomes,
$$ \left(\begin{array} \ 1 & 1 \\ 1 & 1 \end{array}\right) \left(\begin{array}\  x_1 \\ x_2 \end{array}\right)  =\left(\begin{array} \ 3 \\ 3 \end{array}\right),$$
which leads to the equation,
$$ x_1 + x_2 = 3,$$
since there is a solution $x_1=x_2=1.5$ we have that $b$ is in the range of $T$.
Now consider the case where $b=(1,-1)^T$. The equation $Ax=b$ is now,
$$ \left(\begin{array} \ 1 & 1 \\ 1 & 1 \end{array}\right) \left(\begin{array}\  x_1 \\ x_2 \end{array}\right)  =\left(\begin{array} \ 1 \\ -1 \end{array}\right),$$
which corresponds to the following two equations,
$$ x_1+x_2= 1,$$
$$x_1+x_2=-1,$$
in other words $x_1+x_2 \neq x_1+x_2$ which is contradictory. The equations are not consistent and there is no pair of real numbers $x_1$ and $x_2$ can simultaneously solve both of them. For this reason $b$ is not in the range of $T$.


(Beginner) How to combine jQuery's option and method in one statement?

Question: In the example, it uses jquery ui datepicker's "dateFormat" option to set the format and uses "setDate" method to set the default value.
<code>  $(document).ready(function(){
    // command 1 or statement 1
    $("#datepicker").datepicker({
      dateFormat: "yy-mm-dd",
    });

    // command 2 or statement 2
    $("#datepicker").datepicker("setDate", new Date());
  });
</code>
It works well and as expected but there are two separated commands (statements).
How to combine option and method together in one command/statement to make it more lean and clean?
Comment: You can't make it simpler, because of how the plugin is designed. Setting the date involves calling a setter function, which is not part of the initialization options.
Comment: did you read the jquery ui documentation ?
Answer: <code>$("#datepicker").datepicker({
      dateFormat: "yy-mm-dd",
      defaultDate: new Date()
});
</code>
Based on documentation at the below link:
https://api.jqueryui.com/datepicker/
defaultDate

Type: Date or Number or String Default: null Set the date to highlight
  on first opening if the field is blank. Specify either an actual date
  via a Date object or as a string in the current dateFormat, or a
  number of days from today (e.g. +7) or a string of values and periods
  ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m
  +7d'), or null for today. Multiple types supported: Date: A date object containing the default date. Number: A number of days from
  today. For example 2 represents two days from today and -1 represents
  yesterday. String: A string in the format defined by the dateFormat
  option, or a relative date. Relative dates must contain value and
  period pairs; valid periods are "y" for years, "m" for months, "w" for
  weeks, and "d" for days. For example, "+1m +7d" represents one month
  and seven days from today.
Comment: Thank you. It works but it uses 2 options not 1 option and 1 method.
Comment: In datepicker's document (https://api.jqueryui.com/datepicker/), there's no "date" option. But it works and makes the code cleaner. Thank you.
Comment: I've updated my answer. I guess it was defaultDate and not date.


How to remove rows from a table that doesn't fit some criteria

Question: I am stuck with a problem where I couldn't find an answer so far.
I have a table like this:
column1 | column2 | column3
---------------------------
name1   | 3       | 12
name1   | 3       | 10
name1   | 2       | 17
name2   | 3       | 15
name2   | 3       | 15
name2   | 2       | 11

How can I delete the rows, which have not the highest values in column2 and column3,(Column2 has priority)?
The result should look like:
column1 | column2 | column3
---------------------------
name1   | 3       | 12
name2   | 3       | 15
name2   | 3       | 15

Comment: What have you tried? I suggest you split your complex problem in several simpler problems.
Comment: I can separate the problem by deleting duplicates later on using ALTER IGNORE TABLE `table` ADD UNIQUE KEY idx1(column1, column2, column3) - now i update my 1st post
Answer: You could use a query like this:
DELETE FROM yourtable
WHERE
  (column1, column2, column3) NOT IN (
    SELECT * FROM (
      SELECT yourtable.column1, yourtable.column2, max(column3) max_column3
      FROM
        yourtable INNER JOIN (
          SELECT   column1, max(column2) max_column2
          FROM     yourtable
          GROUP BY column1) mx
        ON yourtable.column1=mx.column1
           AND yourtable.column2=mx.max_column2
      GROUP BY
        yourtable.column1) s
  )

Please see fiddle here.
Comment: This one works exactly. However, i'm not sure if i have asked the right question. Thanks a lot
Answer: Deleting makes it confusing but these are the rows you want to keep:
SELECT
    a.col1, a.col2, b.col3
FROM
    (select col1, max(col2) as col2 from table1 group by col1) as a INNER JOIN
    (select col1, col2, max(col3) as col3 from table1 group by col1, col2) as b
    ON
        a.col1 = b.col1 AND a.col2 = b.col2;

You could simply delete the rows that are not in this query as noted by @fthiella.
see this link.
Comment: i didn't try it out yet, because the answer above from fthiella works fine. I'll try it later, when i have more time to play around with alternatives. Thanks a lot


What is the Inclusion-Exclusion Principle for five sets?

Question: Anyone know where I can find the Inclusion-Exclusion Principle for five sets?
I tried to use google but found nothing.  Inclusion-Exclusion Principle for 4 sets are:
\begin{align}
&|A\cup B\cup C\cup D|\\[3pt]
&=|A|+|B|+|C|+|D|\Big\}\text{ all singletons}\\
&-(|A\cap B|+|A\cap C|+|A\cap D|+|B\cap C|+|B\cap D|+|C\cap D|)\Big\}\text{ all pairs}\\
&+(|A\cap B\cap C|+|A\cap B\cap D|+|A\cap C\cap D|+|B\cap C\cap D|)\Big\}\text{ all triples}\\
&-|A\cap B\cap C\cap D|\Big\}\text{ all quadruples}\\
\end{align}
Comment: Yes you have to proceed in much the same way to get to 5 sets as well. In the case of 5 sets, you'll have five quadruples and one quintuple.
Answer: All singles - all pairs + all triples - all quadruples + all quintuples.
Comment: Ok thanks I get it
Answer: We have
\begin{align}
|A_1\cup A_2 \cup A_3 \cup A_4 \cup A_5|
=&
|A_1|+|A_2|+|A_3|+|A_4 |+|A_5|
\\
&
-|A_1\cap A_2|
-|A_1\cap A_3|
-|A_1\cap A_4|
-|A_1\cap A_5|
\\
&
-|A_2\cap A_3|
-|A_2\cap A_4|
-|A_2\cap A_5|
\\
&
-|A_3\cap A_4|
-|A_3\cap A_5|
\\
&
-|A_4\cap A_5|
\\
&
+|A_1\cap A_2\cap A_3|
+|A_1\cap A_2\cap A_4|
+|A_1\cap A_2\cap A_5|
\\
&
+|A_1\cap A_3\cap A_4|
+|A_1\cap A_3\cap A_5|
\\
&
+|A_1\cap A_4\cap A_5|
\\
&
+|A_2\cap A_3\cap A_4|
+|A_2\cap A_3\cap A_5|
\\
&
+|A_2\cap A_4\cap A_5|
\\
&
+|A_3\cap A_4\cap A_5|
\\
&
-|A_1\cap A_2\cap A_3 \cap A_4|
\\&
-|A_1\cap A_2\cap A_3 \cap A_5|
\\&
-|A_1\cap A_2\cap A_4 \cap A_5|
\\&
-|A_1\cap A_3\cap A_4 \cap A_5|
\\&
-|A_2\cap A_3\cap A_4 \cap A_5|
\\
&
+|A_1\cap A_2\cap A_3\cap A_4 \cap A_5|
\end{align}
Answer: The Inclusion-Exclusion principle for $n$ sets can be found here for future reference.
https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle
The Pattern indeed continues, i.e.
$$|\cup^{n}_{i=1} A_i|=\sum |\text{Singletons}|-\sum |\text{Pairs}|+\sum |\text{Triples}|- \sum |\text{Quadruples}|+...+(-1)^{n+1} |\text{n-tuples}|$$
The inductive proof can be found here: https://proofwiki.org/wiki/Inclusion-Exclusion_Principle
Just consider the additive function used in the proof to be the function returning the size of a set.
So if $|A|=n$, then $f(A)=n$


Qualquer url abre no webview?

Question: Tenho minha função:
        webView.setWebViewClient(new WebViewClient(){
            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http://www.hotelcolonialdosnobres.com/")) {
                view.loadUrl(url);
                return true;
            }return false:
}

Porem eu queria que somente o meu site abrisse no webview o restante abrisse no navegador normal.
Answer: tente assim ó:
public class WebViewClientImpl extends WebViewClient {
    private Activity activity = null;
    public WebViewClientImpl(Activity activity) {
       this.activity = activity;
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        if(url.indexOf("hotelcolonialdosnobres.com") > -1 )
            return false;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }
}

Dessa forma, se na url contem teu site, shouldOverrideUrlLoading retorna false e retorna para a chamada do webview.
dai voce chama ele assim:
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);
        webView.loadUrl("http://www.hotelcolonialdosnobres.com/");
    }
}

Note que para instanciar o WebViewClientImpl é passada a mesma activity "new WebViewClientImpl(this);" como parametro.
para saber mais sobre isso, acesse Jakob Jenkov tutorial que foi de onde tirei a referencia.
espero que ajude!

Qualquer url abre no webview?


Fazer alertas em uma página com javascript

Question: Olá!
Tenho que pegar a data que está no banco de dados e fazer um alerta em javascript dois dias antes daquela data.
Como faço para colocar esse alerta em um box com javascript no sistema?
Comment: O que você já tentou fazer?
Comment: Qual linguagem *back-end* você está utilizando? Geralmente pra fazer isso você vai precisar mais do que só **JavaScript**.
Comment: @PauloImon a linguagem que está sendo utilizada é o PHP.
A minha dúvida é só como fazer esse time no javascript.
Comment: Se você quiser exibir o `alert()`, pode fazer a comparação das datas no **PHP** e em seguida passar alguma *flag* pro seu código dentro da *tag* `
Comment: É isso aí mesmo @PauloImon. Só que eu quero tipo criar uma div e quero que apareça esse alerta no box da div. Não em uma uma caixa de alert do javascript.
Answer: No PHP, você poderia ter algo mais ou menos assim:
<?php
    // Instancia o objeto MySQLi e faz a conexão com a base de dados
    // (Altere os dados com as credenciais do seu servidor MySQL)
    $conexao = new mysqli('host', 'root', 'pswd', 'db');

    // Declara a flag p/ exibição de mensagens como desativada
    $alerta = FALSE;

    // Consulta de exemplo
    // (Altere a consulta conforme a sua tabela)
    $sql = "SELECT `data` FROM `tabela` WHERE `id` = 1 LIMIT 1";

    // Executa a consulta
    $consulta = $conexao->query($sql);

    // Gera o resultado da consulta
    $resultado = $consulta->fetch_array();

    // Pega a data atual e converte p/ padrão timestamp do Unix
    $hoje = strtotime(date('Y-m-d'));

    // Converte a data do banco p/ padrão timestamp do Unix
    $data = strtotime($resultado['data']);

    // Verifica se a data ainda não foi ultrapassada
    if ($hoje < $data)
    {
        // Calcula a diferença em segundos
        $diferenca = $data - $hoje;

        // Converte a diferença p/ dias
        $dias = (int) floor($diferenca / (60 * 60 * 24));

        // Verifica se a quantidade de dias atende sua condição
        if ($dias <= 2)
        {
            // Ativa a flag p/ exibir mensagem
            $alerta = TRUE;
        }
    }

Agora no seu código HTML, você pode gerar a mensagem usando uma simples condição do PHP:

    <?php if ($alerta) { ?>

Atenção! Mensagem de alerta!

    <?php } ?>

Referência:
Calculando a diferença em dias entre duas datas - Blog Thiago Belem
Comment: Agradeço! É essa ideia aí mesmo...


How to use database slug field to display a respective blog entry and URL

Question: I am running a web2py web app that includes a blog. I use a slug field in the post database and would like to display the slug as part of the url (instead of the blog post id). I manage to pass the slug field as request.args to the post function, but can't display the related post - instead I am getting a 404 Page Not Found error. When I use the post.id field as request.args, the post is displayed correctly, but then the url shows the post id and not the slug field. I would like to use the slug mainly for SEO reasons. Any pointers would be great!
In my model I have:
db.define_table('post',
                Field('title', unique=True),
                Field('subtitle'),
                Field('intro', 'text'),
                Field('body', 'text'),
                Field('body_mid', 'text'),
                Field('body_end', 'text'),
                Field('published_on', 'date'),
                Field('category'),
                Field('file1', 'upload'),
                Field('caption_one'),
                Field('file2', 'upload'),
                Field('caption_two'),
                Field('slug', 'string', compute=lambda r: r['title']),
                format = '%(title)s')

In my controller I have:
#this selects all posts
def blog():
    post = db().select(db.post.ALL, orderby=~db.post.published_on)
    return dict(post=post)
#this selects a post based on request.args
def show():
    post = db.post(request.args(0, cast = int)) or redirect(URL('index'))
    return dict(post=post)

In the view for blog I have (this works):
{{for entry in post:}}
{{=LI(A(entry.title, _href=URL("show", args=entry.id)))}}                {{pass}}
When I change to (this does not work):
{{for entry in post:}}
{{=LI(A(entry.title, _href=URL("show", args=entry.slug)))}}                {{pass}}
How do I use the slug field correctly in order to show the slug in the URL and display the related database entry?
Many thanks
Answer: The db.post(id) syntax requires the value passed to db.post() to be the record ID. If you want to select the record based on another field, you must do one of the following:
`db.post(slug=request.args(0))`

or:
`db(db.post.slug == request.args(0)).select().first()`

See http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Fetching-a-Row.
Comment: Thanks Anthony! This works well now and as intended!


How to arpeggiate a seventh chord using only 3 notes?

Question: Which notes to choose when arpeggiating a seventh chord (or whatever other chord with more than three notes). This doubt strike me when reading a sheet music where the bass clef has a seventh chord and the root note is not played.
Is there a general rule for which notes to choose when I want to arpeggiate a chord?
I have various doubts about how to play a song when only the chords are available. But when trying to read the score of some musics in order to get the patterns to use. I have face this A7 chord of the image that makes me wonder, where is the A note?
Comment: Please can you also show the bar *before* the one you have shown. Context is also important in music. For example the previous bar could have had an A chord and your bar was a continuation of it.
Comment: Please clarify: How do you know it's a seventh chord if the root is not played? Does it appear elsewhere in the arpeggio? Posting an image from the sheet music that raised the question would be helpful.
Comment: The measure that raised the question was added.
Comment: The (incomplete) `A7` is notated with fingering in the lower clef. How does the question of arpeggiating it come in? It's written out in the score.
Comment: @MichaelCurtis OP is confused why the chord is named "A7" given there is no A note in the score. The left hand plays C#o.
Comment: @user1079505, but that's a question about incomplete chord. How would arpeggiated or not make any difference about omitting the root?
Answer: Arpeggiating isn't an exact science. You could play two notes (or more) during the arpeggio.
Chord-wise, the first to be sacrificed is usually the 5 note - in chord C7, for instance, the G would go Think about it - without C, it's not a C chord. Without 3 (E), it's not major, and without 7 it's not a 7th chord. So the same could apply in arpeggios.
If someone else is playing the root (say, bass) then that could go, so you could play a chord of more notes leaving the root out.
Or, you don't need to play one-note-per-beat, you could still play all 4/5/6 notes by sliipping in a couple in between the beats.
Answer: I think your question might be better worded as...

why did the composer or arranger of this sheet music use an A7 chord label for chord tones E G #C when the purported chord root A is missing?

The simple answer is: in this case the chord is regarded as an incomplete chord.
Strictly speaking you would say the first chord is a C# diminished chord in first inversion. You could label it like C#dim/E with jazz labeling or Dm: viio6/3 with Roman numeral analysis.
Why would someone treat it as an incomplete dominant seventh rather than an leading tone triad? I think two main reasons:

Dominant chords V and leading tone chords vii0 are often treated as theoretically parts of a larger dominant harmony. They are sort of equivalent in dominant function.
Root progression by descending perfect fifth is regarded as the "strongest" chord movement.

So, while vii06/3 i and V4/3 i are sort of functional equivalent, the labeling of V using an incomplete chord is a bit more straight forward in showing the dominant to tonic progression.
Another way to understand the omission of the root in this progression is through looking at the voice leading. Here are two basic version of the harmony with the A omitted and included and also with the D doubled at the octave...

The essential voice movements are the leading tone moving to the tonic (C# D) and the subdominant moving to the mediant (G F.) The supertonic to tonic (E D) is a bit subordinate. But notice the treatment of the dominant (A.) That tone doesn't move. There is a kind of redundancy that allows for an omission.
Play the two progressions with and without the A and they sound more or less the same, because they are more or less the same from a voice leading perspective.
Comment: If one views the fifth of the tonic chord an an "optional" note, it makes sense to treat the root of the dominant seventh likewise, though from a voice-leading perspective, they should generally either both be present or both be omitted.  I think your example with the A omitted would be better if the A in the tonic, rather than the high D, were the note marked in parentheses.
Comment: @supercat, I do follow what you mean about an `A` in parenthesis. But I put the `D` in parenthesis because it wasn't in the original sheet music example. There is sort of two implied things happening. I could do both and add some text annotation.
Answer: Chord symbols are an approximation and simplification of essential harmonic ideas for accompanists, leaving precise details up to players to decide. Whoever wrote the notation, declared that the essential idea is "A7", and playing the notes written on the lower staff is one possible realization of that idea.
Chord symbols are a way to describe the overall story in rough simplified terms. "Boy meets girl, boy learns piano, girl leaves boy." "A7 Dm" That story can be told in infinitely many different ways, when you get to details.
The same thing has been asked more explicitly here What is the relation of guitar chords to actual notes in the measure? What is the relation of chord symbols and written notes. Notes can draw a more detailed picture of the same idea. And actual performances of the notes are even more detailed.

Very low detail level: Chord symbols
Medium detail level: Notation
High detail level: Recording of a performance
Answer: The simple answer is that this isn't actually an A7 chord, it's a first inversion C# diminished chord.
When you go back before functional root-based chordal practice, you had basso-continuo-based practices. One of the most common guidelines for harmonizing bass scales was the rule of the octave, which typically prescribed a 6-chord (first inversion triad) over the second scale degree, both ascending and descending, which results in a diminished chord. I've recently been coming to realize just how common this harmony was in 18th century music.
Gjerdingen's book on Galant Schemata would call this pattern (descending 2 to 1 bass, with a 6 chord over the 2) a Clausula Vera. Depending on the previous bar, it might even be part of a Prinner.
Comment: Why should it be 1st inversion C#o? Could it more likely be root Eo?
Comment: @Tim No. Root inversion Edim7 would have a B♭ (the diminished 5th) as well as a D♭, not a C♯. Furthermore, an Edim chord would want to resolve up a half step to an F chord. Historically, though, 6-chords on the second scale degree (i.e. first inversion diminished triads, in modern terminology) were relatively common occurances, while root position diminished chords were extremely uncommon.
Answer: The picture in the OP has the appearance of coming from an "easy piano" arrangement. In such arrangements, it is not uncommon for the chord notation and staff notation to differ slightly.
In the case pictured, the arranger is likely trying to preserve both the voice-leading (as discussed by Michael Curtis) and simplicity of fingering/hand-movement. Thus, the "correct" chord is A7, but the arranger felt it would be easier for a pianist playing from the staff notation if an incomplete chord was used.
Since the G is prominent in the melody, it would be fair to replace one or both Gs in the accompaniment with As, giving you a complete chord. I would suggest perhaps leaving the first G as is, to emphasize the dissonance of the harmony, but change the second G to an A to capture the overall flavor of the A7 chord.
It does beg the question why the arranger didn't write the left-hand arpeggio as E-A-C#-A, since the melody carries the G.
Comment: To answer your question in the last paragraph, from my viewpoint as a composer, using (E,G,C♯) emphasizes the 'minor' or 'incomplete' flavour of the harmony at that point, whereas using (E,A,C♯) would give a more 'complete' feeling at that point. For this reason, it is common to see the A missing from an A7 chord, in a minor piece, but (at least in classical music) it will not typically be missing in a final V7-I cadence.
Comment: @Aaron I thought the same about the doubled `G`. I don't expect this music to be a Bach chorale - the example is too short to tell the style - but the resolution of the seventh is in parallel octaves. Not really a great exemplar for learning basic four part harmony.