To compute improper integral $\int_3^{5}\frac{x^{2}\, dx}{\sqrt{x-3}{\sqrt{5-x}}}$

Question: I am given improper integral as
$$\int_3^{5}\frac{x^{2}}{\sqrt{x-3}{\sqrt{5-x}}}dx$$
DOUBT
I see that problem is at both the end points, so i need to split up the integral. But problem seems to me that when i split up integral one of terms in denominator which is ${5-x}$ becomes negative. So how do i split up the integral ? Kindly help
Thanks
Comment: Could you fix the denominator of the integrand ? It is not clear. Thanks.
Comment: @ClaudeLeibovici i tried but square root doesnt appear over 5-x
Answer: I'd suggest that you do $u=x-4$ to get an integral from $-1$ to $1$. It will be
$$
\int_{-1}^1\frac{(u+4)^2}{\sqrt{1-u^2}}\,du=\int_{-1}^1-\sqrt{1-u^2}+\frac{8u}{\sqrt{1-u^2}}+\frac{17}{\sqrt{1-u^2}}\,du.
$$
The first term in the integrand gives $-\pi/2$, since it represents (minus) the area of a half circle. The second term gives nothing, since it is odd, and the interval is even. The last term gives
$$
\bigl[17\arcsin u\bigr]_{-1}^1=17(\pi/2-(-\pi/2))=17\pi.
$$
All in all, the integral equals $-\pi/2+17\pi=33\pi/2$.
Comment: @TaylorTed. Just for symmetry, I suppose : $\frac{3+5}2=4$
Comment: @mickep your solution is of course neat :-) I was trying to make clear why you made such a variable change choice in the beginning of your post.
Comment: Few questions 1. How did you know about which substitution to use? 2.How did you simplified the integral? Thanks
Comment: Nice and simple !
Comment: 1) The limits and the square roots hinted me (and as Claude mention, to have a symmetric interval). 2) Expanding the numerator gives $u^2+8u+16$, which can be written as $(u^2-1)+8u+17$.
Comment: @mickep expanding the numerator we obtain $-(x^2-8x+15)$ which we can write as $1-(x-4)^2$.
Comment: @Math-fun I don't follow. Do you mean what is inside the square roots from the beginning?
Comment: @Math-fun Because I wanted to integrate over a symmetric interval. Of course one could use symmetry around $x=4$ instead (I think that is your point?). To me it is easier to use symmetry around $x=0$.
Comment: @mickep this is right, thanks :-)
Answer: Beta Function Approach
Substituting $x\mapsto2x+3$,
$$
\begin{align}
&\int_3^5\frac{x^2\,\mathrm{d}x}{\sqrt{(x-3)(5-x)}}\\
&=\int_0^1\frac{(2x+3)^2\,\mathrm{d}x}{\sqrt{x(1-x)}}\\
&=\int_0^1\frac{(3(1-x)+5x)^2\,\mathrm{d}x}{\sqrt{x(1-x)}}\\
&=9\int_0^1\frac{(1-x)^2\,\mathrm{d}x}{\sqrt{x(1-x)}}
+30\int_0^1\frac{(1-x)x\,\mathrm{d}x}{\sqrt{x(1-x)}}
+25\int_0^1\frac{x^2\,\mathrm{d}x}{\sqrt{x(1-x)}}\\
&=9\operatorname{B}\left(\frac52,\frac12\right)
+30\operatorname{B}\left(\frac32,\frac32\right)
+25\operatorname{B}\left(\frac12,\frac52\right)\\
&=9\cdot\frac38\pi
+30\cdot\frac18\pi
+25\cdot\frac38\pi\\
&=\frac{33}2\pi
\end{align}
$$
using the Beta Function.

Trigonometric Subsitution
After the substitution $x\mapsto2x+3$, we can use $x\mapsto\sin^2(x)$
$$
\begin{align}
&\int_3^5\frac{x^2\,\mathrm{d}x}{\sqrt{(x-3)(5-x)}}\\
&=9\int_0^1\frac{(1-x)^2\,\mathrm{d}x}{\sqrt{x(1-x)}}
+30\int_0^1\frac{(1-x)x\,\mathrm{d}x}{\sqrt{x(1-x)}}
+25\int_0^1\frac{x^2\,\mathrm{d}x}{\sqrt{x(1-x)}}\\
&=9\int_0^{\pi/2}2\cos^4(x)\,\mathrm{d}x
+30\int_0^{\pi/2}2\sin^2(x)\cos^2(x)\,\mathrm{d}x
+25\int_0^{\pi/2}2\sin^4(x)\,\mathrm{d}x\\
&=9\cdot\frac38\pi
+30\cdot\frac18\pi
+25\cdot\frac38\pi\\
&=\frac{33}2\pi
\end{align}
$$
Comment: It's nice to be familiar with the beta function. Then, an integral as this one can be pushed through without fear! :)
Comment: @mickep: indeed, but showing alternate approaches is something i always appreciate.
Comment: Not clear your second step.Which substitution you used? Could you add more details
Comment: @TaylorTed: sorry, I have added a bit more explanation.
Comment: Great answer! Are there any other functions are useful for calculating integrals? (like Gamma and Beta).
Comment: @Rowan: I have found [Gamma](https://en.wikipedia.org/wiki/Gamma_function) and [Beta](https://en.wikipedia.org/wiki/Beta_function) to be the most useful after trig and exponential functions. After those, [Digamma](https://en.wikipedia.org/wiki/Digamma_function) and [Polylogarithm](https://en.wikipedia.org/wiki/Polylogarithm) functions are also useful.
Answer: Hint:
$$(5-x)(x-3)=(-x^2-15+8x)=(1-(x-4)^2)$$
now let $x=sint$ and you will get rid of the square root. And be careful about the range, which changes when you changing your variable.
Answer: Notice, the following
$$x^2=A(x-3)(5-x)+B(8-2x)+C$$
On solving we get
$$x^2=-(x-3)(5-x)-4(8-2x)+17$$
Now, we have
$$\int_{3}^{5}\frac{x^2dx}{\sqrt{(x-3)}\sqrt{(5-x)}}$$
$$=\int_{3}^{5}\frac{(-(x-3)(5-x)-4(8-2x)+17)dx}{\sqrt{(x-3)}\sqrt{(5-x)}}$$
$$=-\int_{3}^{5}\frac{(x-3)(5-x)dx}{\sqrt{(x-3)}\sqrt{(5-x)}}-4\int_{3}^{5}\frac{(8-2x)dx}{\sqrt{(x-3)}\sqrt{(5-x)}}+17\int_{3}^{5}\frac{dx}{\sqrt{(x-3)}\sqrt{(5-x)}}$$
$$=-\int_{3}^{5}\sqrt{(x-3)}\sqrt{(5-x)}-4\int_{3}^{5}\frac{(8-2x)dx}{\sqrt{8x-x^2-15}}+17\int_{3}^{5}\frac{dx}{\sqrt{1-(x-4)^2}}$$
$$=-\int_{3}^{5}\sqrt{1-(x-4)^2}-4\int_{3}^{5}\frac{(8-2x)dx}{\sqrt{8x-x^2-15}}+17\int_{3}^{5}\frac{dx}{\sqrt{1-(x-4)^2}}$$
$$=-\frac{1}{2}\left[(x-4)\sqrt{1-(x-4)^2}+\sin^{-1}\left(x-4\right)\right]_{3}^{5}-4\left[2\sqrt{1-(x-4)^2}\right]_{3}^{5}+17\left[\sin^{-1}(x-4)\right]_{3}^{5}$$
$$=-\frac{1}{2}(\pi)-8(0)+17(\pi)=\frac{33\pi}{2}$$


How to change Java version for decompiled bytecode in IntelliJ?

Question: I'm trying to view the decompiled bytecode for a Java 8 class in IntelliJ but when opening it up it is trying to decompile the class using bytecode version Java 6:

I have managed to open it using Java 8 in the past (not sure how) but I have no idea how to change settings in IntelliJ to open it. Does anyone know how to do this?
Comment: Run `javap` on your `.class` file to confirm that it really targets Java 8. It looks like it was compiled with `-target 1.6`.
Comment: Ah I just went to find the .class file in my external libraries and when I pick the class from there it correctly decompiles it with Java 8. It's only when I ctrl+click the class in my project that it tries to use Java 6 for some reason..
Comment: See http://stackoverflow.com/a/12900859/104891.
Answer: Apologies I realise I did something very silly. The class En I have imported was not the correct Java 8 one. :(


Learning an instrument with visual impairment

Question: I have been lately delving into instrument learning now that I can afford some gear and lessons I am seriously thinking into dedicating into it.
The thing is I only have one seeing eye - the right eye. And to make matters worse (In my little to no knowledge opinion) I am right handed, which makes me having to look at what I am doing a little bit harder (at least when i compare it to my sports experience).
My question is: Is this a serious issue or am I making a huge deal out of it?
Prior to any musical related people's advice, I am pondering Violin (and cello by that matter but my local musical school does not teach it), Guitar (more bass oriented) and the Piano.
I am mostly asking this because it can be a serious investment for a disappointment if I find that the obstacles are bigger than my motivation.
EDIT:
I want to thank you all for your answer and I'll definitely try to learn an instrument!
Comment: @topomorto added them to my question
Comment: Helmut Walcha, one of the great organists, was blind. You have nothing to fear from a little piano.
Comment: Telling us the instruments you had in mind might allow us to come up with some more detailed thoughts...
Comment: as other have said here, when you play, you don't really look at what your hands do; you'll discover very quickly that it's muscle memory and tactile feedback more than anything else. Most of the time you just glance if there is a break because you want to make sure you hands are at the right place when you start, but after that every movement you do is mostly relative to the position you were at a moment ago. I'd even say that the moment you start to look at your fingers and think is usually the moment you will make a mistake when you play.
Answer: The type of music you intend to play and whether single or in ensemble/band has an influence, but in general sight is important for (in increasing order):

Monitoring, what your hands do. This is a bad idea anyway on most instruments (exception may be keyboard/organ setting buttons), since muscle memory or perception of fingers is preferred.
Decode the score. Ensuring, that you have a proper lamp in adverse lighting conditions should cover this. If you are the type of person only needing the score when learning a new piece, or prefer to improvize, the importance is drastically reduced.
Optical part of synchronization with your playing partners, important e.g. to start together. This can be addressed either by restricting to small ensembles or to ones with a conductor.

So summarized: It should not be much of a problem and definitely no reason for not attempting it.
Comment: For monitoring: don't forget that most wind instruments do not require the user to see watch the instrument. Trumpet, sax, clarinet, etc.
Answer: Honestly don't think it's a big problem. Lots of musicians out there who are blind. Even some musicians out there who are deaf! I think there's one guy in South America who learned to play guitar with his feet. Django Reinhardt only had 3 usable fingers in his fretting hand.
Drums may be a little tricky since seeing out of one eye throws off your depth perception, but I can't imagine anything else giving you Earth-shattering trouble. Remember, some guy learned to play guitar with his feet because he had no arms.
With his FEET.
Comment: Did Django have *that* many usable fingers?  And let's not forget the Def Leppard drummer!
Comment: Drums are obnoxiously expensive. But, if a deaf marimbist can become world class by feeling the music vibrate through her feet, you could probably get in there if you stuck with it long enough.
Comment: If you're thinking of Eveline Glennie, she plays a heck of a lot more than marimba.
Comment: Thank you for your answer, I know I make it sound like it's a huge deal but there are a ton of cases that make it sound like nothing when compared to that kind of people. Regarding the drums that has been my issue my whole life (depth) and the prices and the busy work threw me off.
Comment: @Tim - I forget if it was 2 or 3 fingers he had. I want to say 2 now. Also, yes, absolutely!
Comment: @Tim, yes that was my reference. Didn't think the name was important in this context, and yes, she is a BEAST
Answer: Why being right-handed could be seen as problematic, I don't understand. Probably 85% of the world's population has the same 'problem'!
There are lots of instruments that don't get looked at much while being played - trumpet and sax come to mind. Piano probably benefits from using both eyes, although many players have no eyesight at all, and it doesn't stop them. Stevie Wonder comes immediately to mind.
You need to consider which instruments inspire you, their sound, the kind of music you like played by them, and so on. You may or may not want to use music, but having one working eye isn't going to be much more of a challenge than having two. Guitar will need an eye on the fretting hand at least initially, but again, many good players are blind.
Just decide what you like, read other answers here, talk to people in music shops and schools. Talk to music teachers of all instruments, and go for it !
Comment: I wouldn't worry about that - everybody turns their head to look at their hands when they're playing anyway.
Comment: Thank you for the inspiring words. They are really motivating. The right hand 'thing' I was thinking on a possible guitar scenario where my nose gets in the way and I have to look directly into the guitar's arm to know where my left hand is.
Comment: Youi could always consider playing a guitar left-handed. There are many good reasons why this is advantageous, which have been covered in other answers on this site.
Answer: YMMV but when learning a stringed instrument like guitar, a good teacher will help you build muscle memory with your fingers quickly. I'm not sure if you want to play very jazz-y pieces, but if you're content playing cowboy chords with blues scales I don't forsee your vision being a major impediment. Frankly, with guitar chords you don't even really need to look at the neck that much.
Answer: Maybe see if there is a Suzuki teacher in your area - based on a foundation of listening to the music and playing what you hear, rather than reading the score, the Suzuki method would seem to be ideal in your situation (Reading is not ignored, it's just delayed until the music is there).
There are Violin, Cello, Piano, Guitar, Flute and other courses (Mandolin is under development in Italy :)) available, although you may be restricted by what teachers live in your area. Depending on where you are there should be a national or local Suzuki Association, otherwise you can start from www.internationalsuzuki.org/regional_associations.htm.
As the parent of a Suzuki Violin student now in his 9th(?) year of learning, I wholeheartedly recommend the program.
Also: as a blind guitarist, Jose Feliciano comes to mind...
Answer: Playing an instrument is mostly about muscle memory. As you learn to play, you will map certain sounds to certain movements using this muscle memory. The main thing you'll be missing is depth perception and peripheral vision.
Depth perception is unlikely to be a problem. Many instruments require your hands to be in a fixed position (wind instruments come to mind), and your eye will be on the sheet music. Other instruments do require displacing your hands, but this will be mostly baked into your muscle memory. Furthermore, their layout is fixed and you only need to look quickly for large jumps (e.g. on a piano). Depth perception for such instruments is not required. It may even be an advantage - my attempts at playing my girlfriend's harp were hampered by trying to look at the strings and getting cross-eyed and headached.
Peripheral vision can be a problem, in that you may have some more trouble switching from looking to the sheet music and to your instrument. Personally, I never learned to fluently read sheet music, and yet became a rather good musician, with the added advantage that I can impress at parties because I play every piece from memory. Also, you are free to place your sheet music wherever you want, so you can certainly adjust for this (I've seen professional players spread the piece out in front of them on the floor).
I've never seen left- or right-handedness as a problem in playing an instrument. I'm left-handed to a fault, but play piano easier with my right hand.
My advice is thus to completely ignore your visual impairment, and grasp this opportunity to play whatever instrument appeals the most! This is actually a hobby where visual impairment is a very small factor.
Answer: You shouldn't have any problem with the piano and the cello.
As for the guitar, you can try to play it standing with a loose strap, punk-rock style, you will still see the whole guitar neck even only with your right eye. Anyway, when you'll get better at it, you won't even need to look at your hands anymore, except at the very start of a song for positionning.
I won't give any advice for the violin as I could never handle that instrument well.
Answer: If you are mainly interested in having fun and don't want to get into sheet music, my suggestion would be to get a keyboard with a range of sounds (including a rock organ) then listen to old R&B. Play along, working with only the right hand at first. Figure out the key note for each measure and play along. As you keep repeating this you can then add a second note to make a simple chord, and play along with this. You can then add a third note. At this point, listen to the key note for each measure that is being played by the keyboardist or the bassist and add this.
Two songs I recommend: First is I'm a Man (Spencer Davis Group with Steveie Winwood on organ). The organ is simple, ballsy and fun. Following the method described above, you can pick it up quickly. The second song (which is more complex but which is still based on a very simple progression) is Green Onions (Booker T. and the MGs). With Green Onions, start with the left hand. The thing with Green Onions is that the right hand has notes that walk down while the left hand walks upwards.
When it comes to having fun, just take the above two songs and noodle around with your right hand to figure out the scale. Base it on the chords you worked out and add a sharp or flat now and then. Add a repeating sequence on the left hand and before long you will have something to show for it.
Comment: This hardly addresses the OP's question - it could refer to any beginner.
Comment: When I close my left eye I can't see anything to the left of my nose. This is not worth pursuing.
Comment: Certainly. The key point is that if he is blind with the left eye and apparently right-handed, a stringed instrument would be more difficult than a keyboard, which has a key arrangement that does not vary between hands, which makes it far easier to find one's place by feel than on a guitar.

Being visually impaired, he can get up on the instrument aurally much faster than with something like a guitar. As he is essentially a beginner, this response addresses both issues.
Comment: I'm disagreeing again. As a guitarist, I've just checked. Without moving one's head, looking at the fingerboard, there's actually a slightly better view of fingertips on frets using the right eye, although it's quite possible to move one's head to create a better view anyway. As a pianist, I'm not going to search for notes by feel - I expect you mean the 2/3 pattern of black keys. Only playing on whites, as a beginner would, there's no mileage there. That apart, looking with one eye, whichever, is no great problem.
Comment: Thanks for your thoughts. Nothing was said about white keys. It's just as easy to find a C# by feel as a C. As for the guitar being easier to see, If I could close my left eye and see my left hand playing a basic chord without turning my head, that would be unexpected. I don't play the keyboard entirely by feel (to a great extent I do) but I'm not visually impaired. None of this is a big deal. At it's most basic level, the suggestion is to start with keyboards and, if reading music is unlikely, it can be easy to learn to play by ear if you start with something fun and simple.


numpy - could not broadcast input unknown error

Question: I am attempting to run the following code, but am getting the following error:
line 71, in cross_validation
    folds[index] = numpy.vstack((folds[index], dataset[jindex])). ValueError: could not broadcast input array from shape (2,8) into shape (8)

What is interesting is that when I print out the shapes of the two items I am trying to use in the vstack, they have the same shape (8,)
I am trying to determine why this line of the function is failing. Any advice would be greatly appreciated.
import numpy

def csv_to_array(file):
    # Open the file, and load it in delimiting on the ',' for a comma separated value file
    data = open(file, 'r')
    data = numpy.loadtxt(data, delimiter=',')

    # Loop through the data in the array
    for index in range(len(data)):
        # Utilize a try catch to try and convert to float, if it can't convert to float, converts to 0
        try:
            data[index] = [float(x) for x in data[index]]
        except Exception:
            data[index] = 0
        except ValueError:
            data[index] = 0

    # Return the now type-formatted data
    return data

def create_folds(dataset):
    length = len(dataset)
    folds = numpy.empty_like(dataset)
    for index in range(5):
        tempArray = numpy.ndarray(shape=(1, length))
        numpy.append(folds, tempArray)
        temp_class_array = numpy.ndarray(shape=(1,1))
        numpy.append(folds, temp_class_array)

    return folds

def class_distribution(dataset):
    dataset = numpy.asarray(dataset)
    num_total_rows = dataset.shape[0]
    num_columns = dataset.shape[1]
    classes = dataset[:,num_columns-1]
    classes = numpy.unique(classes)
    class_weights = []

    for aclass in classes:
        total = 0
        weight = 0
        for row in dataset:
            if numpy.array_equal(aclass, row[-1]):
                total = total + 1
            else:
                continue
        weight = float((total/num_total_rows))
        class_weights.append(weight)

    class_weights = numpy.asarray(class_weights)
    return classes, class_weights

def cross_validation(dataset):
    classes, class_weights = class_distribution(dataset)
    total_length = len(dataset)
    folds = create_folds(dataset)
    added_so_far = 0

    for a_class, a_class_weight in zip(classes, class_weights):
        amt_for_fold = float(((a_class_weight * total_length) / 5)-1)

        for index in range(0,10,2):
            added = 0
            for jindex in range(len(classes)):
                if added >= amt_for_fold:
                    break
                if classes[jindex] == a_class:
                    print(folds[index].shape)
                    print(dataset[jindex].shape)
                    folds[index] = numpy.vstack((folds[index], dataset[jindex]))
                    # print(folds)
                    folds[index + 1] = numpy.vstack((folds[index + 1], [classes[jindex]]))

                    if index < 8:
                        dataset = numpy.delete(dataset, jindex, 0)
                        classes = numpy.delete(classes, jindex, 0)

                    added_so_far = added_so_far + 1

    for xindex in range(len(folds)):
        folds[xindex] = numpy.delete(folds[xindex], 0, 0)

    print(folds)
    return folds

def main():
    print("BEGINNING CFV")
    ecoli = csv_to_array('Classification/ecoli.csv')
    cross_validation(ecoli)

main()

On the following dataset:
0.61,0.45,0.48,0.5,0.48,0.35,0.41,0
0.17,0.38,0.48,0.5,0.45,0.42,0.5,0
0.44,0.35,0.48,0.5,0.55,0.55,0.61,0
0.43,0.4,0.48,0.5,0.39,0.28,0.39,0
0.42,0.35,0.48,0.5,0.58,0.15,0.27,0
0.23,0.33,0.48,0.5,0.43,0.33,0.43,0
0.37,0.52,0.48,0.5,0.42,0.42,0.36,0
0.29,0.3,0.48,0.5,0.45,0.03,0.17,0
0.22,0.36,0.48,0.5,0.35,0.39,0.47,0
0.23,0.58,0.48,0.5,0.37,0.53,0.59,0
0.47,0.47,0.48,0.5,0.22,0.16,0.26,0
0.54,0.47,0.48,0.5,0.28,0.33,0.42,0
0.51,0.37,0.48,0.5,0.35,0.36,0.45,0
0.4,0.35,0.48,0.5,0.45,0.33,0.42,0
0.44,0.34,0.48,0.5,0.3,0.33,0.43,0
0.44,0.49,0.48,0.5,0.39,0.38,0.4,0
0.43,0.32,0.48,0.5,0.33,0.45,0.52,0
0.49,0.43,0.48,0.5,0.49,0.3,0.4,0
0.47,0.28,0.48,0.5,0.56,0.2,0.25,0
0.32,0.33,0.48,0.5,0.6,0.06,0.2,0
0.34,0.35,0.48,0.5,0.51,0.49,0.56,0
0.35,0.34,0.48,0.5,0.46,0.3,0.27,0
0.38,0.3,0.48,0.5,0.43,0.29,0.39,0
0.38,0.44,0.48,0.5,0.43,0.2,0.31,0
0.41,0.51,0.48,0.5,0.58,0.2,0.31,0
0.34,0.42,0.48,0.5,0.41,0.34,0.43,0
0.51,0.49,0.48,0.5,0.53,0.14,0.26,0
0.25,0.51,0.48,0.5,0.37,0.42,0.5,0
0.29,0.28,0.48,0.5,0.5,0.42,0.5,0
0.25,0.26,0.48,0.5,0.39,0.32,0.42,0
0.24,0.41,0.48,0.5,0.49,0.23,0.34,0
0.17,0.39,0.48,0.5,0.53,0.3,0.39,0
0.04,0.31,0.48,0.5,0.41,0.29,0.39,0
0.61,0.36,0.48,0.5,0.49,0.35,0.44,0
0.34,0.51,0.48,0.5,0.44,0.37,0.46,0
0.28,0.33,0.48,0.5,0.45,0.22,0.33,0
0.4,0.46,0.48,0.5,0.42,0.35,0.44,0
0.23,0.34,0.48,0.5,0.43,0.26,0.37,0
0.37,0.44,0.48,0.5,0.42,0.39,0.47,0
0,0.38,0.48,0.5,0.42,0.48,0.55,0
0.39,0.31,0.48,0.5,0.38,0.34,0.43,0
0.3,0.44,0.48,0.5,0.49,0.22,0.33,0
0.27,0.3,0.48,0.5,0.71,0.28,0.39,0
0.17,0.52,0.48,0.5,0.49,0.37,0.46,0
0.36,0.42,0.48,0.5,0.53,0.32,0.41,0
0.3,0.37,0.48,0.5,0.43,0.18,0.3,0
0.26,0.4,0.48,0.5,0.36,0.26,0.37,0
0.4,0.41,0.48,0.5,0.55,0.22,0.33,0
0.22,0.34,0.48,0.5,0.42,0.29,0.39,0
0.44,0.35,0.48,0.5,0.44,0.52,0.59,0
0.27,0.42,0.48,0.5,0.37,0.38,0.43,0
0.16,0.43,0.48,0.5,0.54,0.27,0.37,0
0.06,0.61,0.48,0.5,0.49,0.92,0.37,1
0.44,0.52,0.48,0.5,0.43,0.47,0.54,1
0.63,0.47,0.48,0.5,0.51,0.82,0.84,1
0.23,0.48,0.48,0.5,0.59,0.88,0.89,1
0.34,0.49,0.48,0.5,0.58,0.85,0.8,1
0.43,0.4,0.48,0.5,0.58,0.75,0.78,1
0.46,0.61,0.48,0.5,0.48,0.86,0.87,1
0.27,0.35,0.48,0.5,0.51,0.77,0.79,1
0.52,0.39,0.48,0.5,0.65,0.71,0.73,1
0.29,0.47,0.48,0.5,0.71,0.65,0.69,1
0.55,0.47,0.48,0.5,0.57,0.78,0.8,1
0.12,0.67,0.48,0.5,0.74,0.58,0.63,1
0.4,0.5,0.48,0.5,0.65,0.82,0.84,1
0.73,0.36,0.48,0.5,0.53,0.91,0.92,1
0.84,0.44,0.48,0.5,0.48,0.71,0.74,1
0.48,0.45,0.48,0.5,0.6,0.78,0.8,1
0.54,0.49,0.48,0.5,0.4,0.87,0.88,1
0.48,0.41,0.48,0.5,0.51,0.9,0.88,1
0.5,0.66,0.48,0.5,0.31,0.92,0.92,1
0.72,0.46,0.48,0.5,0.51,0.66,0.7,1
0.47,0.55,0.48,0.5,0.58,0.71,0.75,1
0.33,0.56,0.48,0.5,0.33,0.78,0.8,1
0.64,0.58,0.48,0.5,0.48,0.78,0.73,1
0.11,0.5,0.48,0.5,0.58,0.72,0.68,1
0.31,0.36,0.48,0.5,0.58,0.94,0.94,1
0.68,0.51,0.48,0.5,0.71,0.75,0.78,1
0.69,0.39,0.48,0.5,0.57,0.76,0.79,1
0.52,0.54,0.48,0.5,0.62,0.76,0.79,1
0.46,0.59,0.48,0.5,0.36,0.76,0.23,1
0.36,0.45,0.48,0.5,0.38,0.79,0.17,1
0,0.51,0.48,0.5,0.35,0.67,0.44,1
0.1,0.49,0.48,0.5,0.41,0.67,0.21,1
0.3,0.51,0.48,0.5,0.42,0.61,0.34,1
0.61,0.47,0.48,0.5,0,0.8,0.32,1
0.63,0.75,0.48,0.5,0.64,0.73,0.66,1
0.71,0.52,0.48,0.5,0.64,1,0.99,1
0.72,0.42,0.48,0.5,0.65,0.77,0.79,2
0.79,0.41,0.48,0.5,0.66,0.81,0.83,2
0.83,0.48,0.48,0.5,0.65,0.76,0.79,2
0.69,0.43,0.48,0.5,0.59,0.74,0.77,2
0.79,0.36,0.48,0.5,0.46,0.82,0.7,2
0.78,0.33,0.48,0.5,0.57,0.77,0.79,2
0.75,0.37,0.48,0.5,0.64,0.7,0.74,2
0.59,0.29,0.48,0.5,0.64,0.75,0.77,2
0.67,0.37,0.48,0.5,0.54,0.64,0.68,2
0.66,0.48,0.48,0.5,0.54,0.7,0.74,2
0.64,0.46,0.48,0.5,0.48,0.73,0.76,2
0.76,0.71,0.48,0.5,0.5,0.71,0.75,2
0.84,0.49,0.48,0.5,0.55,0.78,0.74,2
0.77,0.55,0.48,0.5,0.51,0.78,0.74,2
0.81,0.44,0.48,0.5,0.42,0.67,0.68,2
0.58,0.6,0.48,0.5,0.59,0.73,0.76,2
0.63,0.42,0.48,0.5,0.48,0.77,0.8,2
0.62,0.42,0.48,0.5,0.58,0.79,0.81,2
0.86,0.39,0.48,0.5,0.59,0.89,0.9,2
0.81,0.53,0.48,0.5,0.57,0.87,0.88,2
0.87,0.49,0.48,0.5,0.61,0.76,0.79,2
0.47,0.46,0.48,0.5,0.62,0.74,0.77,2
0.76,0.41,0.48,0.5,0.5,0.59,0.62,2
0.7,0.53,0.48,0.5,0.7,0.86,0.87,2
0.64,0.45,0.48,0.5,0.67,0.61,0.66,2
0.81,0.52,0.48,0.5,0.57,0.78,0.8,2
0.73,0.26,0.48,0.5,0.57,0.75,0.78,2
0.49,0.61,1,0.5,0.56,0.71,0.74,2
0.88,0.42,0.48,0.5,0.52,0.73,0.75,2
0.84,0.54,0.48,0.5,0.75,0.92,0.7,2
0.63,0.51,0.48,0.5,0.64,0.72,0.76,2
0.86,0.55,0.48,0.5,0.63,0.81,0.83,2
0.79,0.54,0.48,0.5,0.5,0.66,0.68,2
0.57,0.38,0.48,0.5,0.06,0.49,0.33,2
0.78,0.44,0.48,0.5,0.45,0.73,0.68,2
0.78,0.68,0.48,0.5,0.83,0.4,0.29,3
0.63,0.69,0.48,0.5,0.65,0.41,0.28,3
0.67,0.88,0.48,0.5,0.73,0.5,0.25,3
0.61,0.75,0.48,0.5,0.51,0.33,0.33,3
0.67,0.84,0.48,0.5,0.74,0.54,0.37,3
0.74,0.9,0.48,0.5,0.57,0.53,0.29,3
0.73,0.84,0.48,0.5,0.86,0.58,0.29,3
0.75,0.76,0.48,0.5,0.83,0.57,0.3,3
0.77,0.57,0.48,0.5,0.88,0.53,0.2,3
0.74,0.78,0.48,0.5,0.75,0.54,0.15,3
0.68,0.76,0.48,0.5,0.84,0.45,0.27,3
0.56,0.68,0.48,0.5,0.77,0.36,0.45,3
0.65,0.51,0.48,0.5,0.66,0.54,0.33,3
0.52,0.81,0.48,0.5,0.72,0.38,0.38,3
0.64,0.57,0.48,0.5,0.7,0.33,0.26,3
0.6,0.76,1,0.5,0.77,0.59,0.52,3
0.69,0.59,0.48,0.5,0.77,0.39,0.21,3
0.63,0.49,0.48,0.5,0.79,0.45,0.28,3
0.71,0.71,0.48,0.5,0.68,0.43,0.36,3
0.68,0.63,0.48,0.5,0.73,0.4,0.3,3
0.74,0.49,0.48,0.5,0.42,0.54,0.36,4
0.7,0.61,0.48,0.5,0.56,0.52,0.43,4
0.66,0.86,0.48,0.5,0.34,0.41,0.36,4
0.73,0.78,0.48,0.5,0.58,0.51,0.31,4
0.65,0.57,0.48,0.5,0.47,0.47,0.51,4
0.72,0.86,0.48,0.5,0.17,0.55,0.21,4
0.67,0.7,0.48,0.5,0.46,0.45,0.33,4
0.67,0.81,0.48,0.5,0.54,0.49,0.23,4
0.67,0.61,0.48,0.5,0.51,0.37,0.38,4
0.63,1,0.48,0.5,0.35,0.51,0.49,4
0.57,0.59,0.48,0.5,0.39,0.47,0.33,4
0.71,0.71,0.48,0.5,0.4,0.54,0.39,4
0.66,0.74,0.48,0.5,0.31,0.38,0.43,4
0.67,0.81,0.48,0.5,0.25,0.42,0.25,4
0.64,0.72,0.48,0.5,0.49,0.42,0.19,4
0.68,0.82,0.48,0.5,0.38,0.65,0.56,4
0.32,0.39,0.48,0.5,0.53,0.28,0.38,4
0.7,0.64,0.48,0.5,0.47,0.51,0.47,4
0.63,0.57,0.48,0.5,0.49,0.7,0.2,4
0.69,0.65,0.48,0.5,0.63,0.48,0.41,4
0.43,0.59,0.48,0.5,0.52,0.49,0.56,4
0.74,0.56,0.48,0.5,0.47,0.68,0.3,4
0.71,0.57,0.48,0.5,0.48,0.35,0.32,4
0.61,0.6,0.48,0.5,0.44,0.39,0.38,4
0.59,0.61,0.48,0.5,0.42,0.42,0.37,4
0.74,0.74,0.48,0.5,0.31,0.53,0.52,4

Answer: The vstack() is returning a shape (2,8) array.
You're then assigning that (2,8) array to the LHS folds[index], which is just a shape (8,) array.
numpy tries to see if such a mismatched assignment can be justified by broadcasting, subject to the rules and constraints of broadcasting, and is finally giving up, with that error message.
Not sure what your actual intent is, so I'm not able to suggest alternative.
My guess is that folds should actually be created as a 3d array, in which each inner 2d array has as many rows as the length of each fold.
I also have this suspicion that, the line folds = numpy.empty_like(dataset) is based on some wrong understanding of numpy.empty_like(). Please double-check that.
Answer: I think you might be misunderstanding what vstack does. Given two vectors with 8 items it will stack them vertically and you will get a 2x8 matrix. Indeed the output will always be at lead 2D. See doc and the examples in https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html
E.g.
a = np.array([1,2,3])
b = np.array([1,2,3])
np.vstack((a,b))

outputs
array([[1, 2, 3],
       [1, 2, 3]])


Pass Vars from Django template to views

Question: Im creating a filter for product categories and would like to pass the category name from the appropriate image on my template.
Part of the filter bar:

Urls:
path('search/<category>/', store_views.product_filter ,name='product-filter'),

I want MISC from the template to pass and become the category so that i can use it in views:
# ? Filter Products by Catagory
def product_filter(request, category):
    products= Product.objects.all()
    filter=ProductFilter(category,queryset=products)
    context={'products':filter}
    return render(request,'store/filter.html',context)

Getting this currently even just on my home page:
NoReverseMatch at /

Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$']

And this when on /search/MISC:
NoReverseMatch at /search/MISC/

Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$']

Answer: Your url routing is not matching. Your error is in category.
path('search/<category>/', store_views.product_filter, name='product-filter'),

FIX:- Give the data type to category or any regex. Like:
path('search/<str:category>/', store_views.product_filter, name='product-filter'),

Comment: I belive Django defaults to str anyway
Comment: Well adding str: changed nothing
Comment: Thank you for your edit. Adding quotes to the url in template seemed to fix the home page but still getting no reverse match when link is clicked. Doesnt seem to be passing argument possibly?
New Link:
``
Comment: Will you check ``````
Comment: Same issue
`with arguments '('',)'`
The URL works and goes to /MISC but the url.py doesnt seem to be working
Comment: urlpatterns = [
    path('admin/', admin.site.urls),

    # ? STORE
    path('',include('store.urls') ),
    path('product/new/', staff_member_required(ProductCreateView.as_view(), login_url='login'), name='product-create'),
    path('product//', ProductDetailView.as_view(), name='product-detail'),
    path('product//update/', ProductUpdateView.as_view(), name='product-update'),
    path('product//delete/', ProductDeleteView.as_view(), name='product-delete'),

    path('/', store_views.product_filter ,name='product-filter'),
Comment: In the last line it is: ```path('/', store_views.product_filter ,name='product-filter'), ```. Should be: ```path('search//', store_views.product_filter ,name='product-filter'), ```
Comment: Goes to http://127.0.0.1:8000/search/MISC/
But same error
`NoReverseMatch at /search/MISC/

Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P[^/]+)/$']`

Pass Vars from Django template to views


calculate sample size, differences between software

Question: Currently I'm doing a power calculation using the pwr package. I thought it should be very simple, but I'm not sure if I'm doing it right. I use R to calculate the sample size. I checked my results using other software. The results are really different. The documentation of the other software isn't available, that's why I post this question.
In short. I'm going to perform a two-sample, two-sided t-test. The no. of observations between the two groups are the same. I would like to measure/calculate a difference between the means of 4. The variance of my test is 12. The variance is equal between the groups. sig. level = 0.05 and the power is 0.8.
Using the pwr package I get the following code
d <- 4/12
pwr.t.test(n=NULL, d=d, sig.level=0.05, power=0.8, type="two.sample", alternative="two.sided")

With the following results

Two-sample t test power calculation
          n = 142.2462
          d = 0.3333333
  sig.level = 0.05
      power = 0.8
alternative = two.sided

NOTE: n is number in each group

However, the other software I use says that I just need 13 replications. Is the other package using another theory about calculating the no. of replications for a t-test? Or am I doing something wrong?
I hope you can help me out.
Best regards,
Robin
Answer: This is from Minitab:
Power and Sample Size

2-Sample t Test

Testing mean 1 = mean 2 (versus ≠)
Calculating power for mean 1 = mean 2 + difference
α = 0.05  Assumed standard deviation = 3.464

            Sample  Target
Difference    Size   Power  Actual Power
         4      13     0.8      0.806340

The sample size is for each group.

I think you may be confusing the population variance (not 'test' variance)
$\sigma^2 = 12$ with the population standard deviation $\sigma = 3.464.$
If I enter $\sigma = 12,$ I get $n = 143.$
I believe the parameter $d$ in your
output is intended to be $d=\Delta/\sigma,$ which should be $d = 4/3.464,$
but by using $\sigma = 12,$ you make it $d = 4/12 = 1/3 = 0.333.$
Comment: you're right. This is what I didn't understand. Thank you for this clarification


How do you specify stylesheets for spcific media using ASP.NET Themes?

Question: This is a question brought up in a local user group mailing list at dot.net.nz ...

I when I create an XHTML page
  old-fashioned way, I used to use the
  following syntax for my CSS
  declarations:

<code><link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />

<link rel="stylesheet" type="text/css" media="print" href="css/printer.css" />
</code>

Now, since I code using ASP.NET 2.0
  and beyond; I fell in love with the
  Themes. However, I don't know how to
  do the same thing using Themes.
Answer: You should define media in the CSS file:
<code>@media print
{
    p
    {
        ...
    }

    ...put styles here.
}
</code>
Comment: So then I would have a screen.css which encapsulates the style within @media screen { ... } and a printer.css when encapsulates the styles within @media print { ... }

I guess that makes sense.
Comment: This is not the most elegant solution for mobile devices where bandwidth is a concern and now the device has to download the styles for all media types.
Answer: You can declare the media type inside the stylesheets. For example, printer.css:
<code>@media print
{
    /* Print CSS rules here */
}
</code>


Are there normalized equivalents to Skewness and Kurtosis?

Question: What would be the normalized equivalent to Skewness that would have the same unit as the data? Similarly, what would be the normalized equivalent to Kurtosis? Ideally, these functions should be linear with respect to the data, meaning that if all observations were to be multiplied by a factor n, the resulting normalized skewness and kurtosis would be multiplied by the same factor n. The benefit of having such normalized equivalents would be to be able to overlay them on top of a standard box-and-whisker plot.
Comment: What are you trying to show about your data? If it's a certain qualitative behavior of the distribution, might a [violin plot](https://en.wikipedia.org/wiki/Violin_plot) be preferable? But yes, anyway, it's a fun question.
Comment: What a fun question!
Comment: I'm not sure how enlightening it would be to illustrate these on graphs. The reason we illustrate standard deviations is that they give a natural measure of the dispersion of the data (if it's normally distributed): 65% of the observations lie inside the interval. I don't think there are such natural visual interpretations for the third and fourth moments.
Comment: One can get a sense of skewness and kurtosis by looking at a histogram showing the distribution of one's dataset, but it will give a very subjective perception of these measures. I would like to depict them on two linear scales, one for skewness parallel to the axis of the box-and-whisker plot, the other orthogonal to it. This could be depicted as a separate box overlaid on top of the primary box. The taller that box, the more skewed the data is. The wider, the more pointy (high kurtosis).
Comment: And thanks for the link to the violon plot. It's really clever.
Comment: @Ben Kuhn: 65% for a normal; should be 68%. (Naturally, you can add arbitrarily more significant figures.)
Comment: "Normalized" across mathematics and science has a whole bundle of different meanings, but it often means scaled, unit-free, standardized or corrected, If anything here is normalized, it is the unit-free shape measures called skewness and kurtosis, not what you seek instead.
Answer: Skewness measures are deliberately unitless.
The usual moment-skewness is a standardized third moment, $E[(\frac{X-\mu}{\sigma})^3]$.
If you center but don't standardize, you have $\mu_3=E[(X-\mu)^3]$... which is plainly then in cubed units.
If you wanted something in the same units as $X$, you'd have to take the cube-root, in the same way that we take square root of variance and get something in the same units of the original data. (However - beware, because many packages won't take cube roots of negative numbers, you might have to compute it as: $\quad\text{sign}(X-\mu)\times |E(X-\mu)^3|^{1/3}\:$.)
I'm not sure how useful that will be.
For some other skewness measures, like the two Pearson skewness measures, you just multiply by $\sigma$.
For sample skewness measures where $\sigma$ and $\mu$ are generally not known, as with sample skewness, you'd typically replace them by their own sample estimates.
Kurtosis follows the same pattern - for moment kurtosis, you'd need to take fourth roots of the unstandardized fourth moment to get something that scaled with the data.
For some of the other measures of kurtosis, they would only need to be multiplied by $\sigma$.
Answer: Skewness and kurtosis are shape characteristics. So, if I tell you that the thing, a ball, is round it shouldn't matter what is a radius of the thing. It can be a small ball or a big ball. On the other hand, when I say small ball or a large cube I'm referring to the size of the object, not the shape.
In this regard, the standard deviation is the size of the distribution, that's why skewness and kurtosis are normalized by size. You could also say that standard deviation belongs to mechanics, and skewness and kurtosis to geometry. Therefore, no, we don't need to have them in units of measure of the variable. Size and shape are separate. A large and a small ball are equally round, i.e. size doesn't matter in this case :)
Answer: Denoting vectors which is distributed in region $R$, let's assume the zeroth and the first moment is already normalized. The second moment is calculated with $M_2 = \int_R {x x^T} |dx|$, so if we can find diagonalization $M_2 = P\Lambda^2 P^T$, then we will be able to define $$x'=\Lambda^{-1} P^Tx$$
so that $M_2$ is normalized:
$$M'_{2ij} = \int_R {(\Lambda^{-1}P^T x)(\Lambda^{-1} P^T x)^T} |dx|$$
$$= \Lambda^{-1} P^T (\int_R { xx^T |dx|}) P \Lambda^{-1} $$
$$= \Lambda^{-1} P^T P \Lambda^2 P^T P \Lambda^{-1} = I$$
Geometrical meaning of the second moment is "orientation", which is justified by the fact that diagonalization normalizes the second moment. When skewness is calculated under this normalization, it is called Mardia's skewness.


Maven Buildnumber plugin - Git

Question: The Maven Buildnumber plugin doesn't appear to work with GIT yet.  Is there a workaround for the time being?  I recently switched from SVN to GIT and have found it to be an easy transition, but this is the only thing that I don't have working presently.
Walter
Answer: I use this Maven plugin:
https://github.com/ktoso/maven-git-commit-id-plugin
and have it filter values directly into my spring files where I can inject them into anything I want (mostly just for reporting versions at start-up / or via a REST service).
When first starting, set it up to generate the properties file so you can see everything that is available.  Extremely easy to use.   Love it.
Comment: Thanks for recommending it! I'm really trying to keep it updated as new feature requests come in :-) If you have any problems feel free to ping me via github issues! // I'm the author of this plugin.
Comment: I must did something wrong. In my project https://github.com/actframework/actframework/blob/master/pom.xml, I just can't get the maven-git-commit-id-plugin working :-(
Answer: I have written a blog post that describes how you can use the buildnumber-maven-plugin to add the Git SHA-1 to your project.
For the record, I used version 1.0 of the plugin, which was released in April 2011.
Comment: One hint: If you add `scm:git:git://localhost/${basedir}`, you can use the plugin in every build directory regardless of which remote SCM URL you have. This simplifies configuration a little bit.
Comment: @matsev Thank you Mattias. In the past, we have implemented a plugin themselves (and I think it is not good). This solution works for me with: maven-scm-plugin:1.9.4; buildnumber-maven-plugin:1.4; maven-jar-plugin:2.6
Comment: You link to blogpost is invalid. Please update it.
Answer: Well, there is MOJO-1199 about the buildnumber plugin and GIT support but the patches haven't been applied yet. However, it seems that Antony Stubbs did some work around this and made it available in this git mirror. Have a look at it.
Comment: Hi guys! I have spies everywhere ;) Yes, it is weird. Seems the plugin may be essentially abandoned. Me and a [friend of mine](http://github.com/talios) are toying with the idea of publishing the fork to repo1.
Comment: As from now, even given that MOJO-1199 has been marked as resolved and  builnumber-maven-plugin has 1.2 version the issue is still there :(
Comment: I've tried **1.0, 1.1, 1.2**, and **1.3** versions of the plugin and the issue mentioned in [this comment to MOJO-1199](http://jira.codehaus.org/browse/MBUILDNUM-53?focusedCommentId=230305&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-230305) still exists, which excludes using of this plugin from any build which is not on `master` branch.
Comment: I just chatted with pgier and wsmoak on irc.codehaus.org#maven, they said if the patch applies cleanly, they'll accept in the buildnumber-maven-plugin.
Comment: From Antony (or Justin?) - "I use my build every day, it definitely works for me. However, yes, I noticed the failure and disabled the tests! ;) but yes, the git integration works fine. I welcome a patch to fix the integration tests". I'll try to get to this soon. I recall maven plugin integration tests being kinda hard to debug, so I'll probably ask for help on some mailing lists.
Comment: The issue MOJO-1199 has been marked as resolved. In case you need branch info, there's still MBUILDNUM-66.
Answer: I used buildnumber-maven-plugin with git for some time. But one day our manager was unable to setup Git CLI (in win7 with non ASCII user name). It forced me to write maven plugin using JGit API without git command line. See maven-jgit-buildnumber-plugin.
Comment: For non standard git installs (especially Windows) this makes dealing with the build far easier.
Comment: Thank you, Alex! I also added more features to your plugin: https://github.com/elab/jgit-buildnumber (released to Maven Central as well)
Answer: This blog post describes how to use profiles to have the buildnumber plugin work differently when in a git or svn working copy.
Obviously(*) the buildnumber created in the git repository does not contain the subversion revision number.
(*) It should be possible to include the subversion revision number in the buildnumber when working in a git repository for commits that are already pushed back to the subverion repository.
Answer: The current version of buildNumber plugin - 1.0 -  supports the Git SCM.
In the version 1.1-SNAPSHOT there is a new configuration tag shortRevisionLength for getting the short git id. More details http://yevgen-fr.blogspot.com/2012/02/maven-buildnumber-plugin-short-revision.html
Answer: I had problems with getting the ones provided above to work.
So I wrote my own, which simply executes the git describe and assigns to a property to be used in the MANIFEST.MF.
See: https://github.com/koekiebox/git-maven-plugin
Thanks.

Maven Buildnumber plugin - Git


How to purge cached content every day via cache tag?

Question: Drupal 8 page has a day specific element which is valid for current day. I would like to add a cache tag so that it can be purged in varnish/fastly periodically. Is there a way to invalidate cache tag periodically on Drupal8?
Here is few FAQs/As:

Why can't use max-age?

max-age can be used, but it's page level header which can get quite confusing when more than one component try to set it. Cache tag is kind of self-contained to the component.

Why don't run cron?

Trying to avoid explicit cron/job to do this as it's environment specific.
Comment: Notice that you are merely stating facts, without asking any explicit question. The question is then about code, but you aren't showing any tentative to resolve the problem. This is valid also for self-answered questions, for which the closing reasons are still valid.
Comment: You can use the max-age #cache which is in seconds so you have have a pre/process function on the element that would compute the time left in current day. Or you can create cache context for current day as well.
Comment: @kiamlaluno Thanks for quick review. updated to reflect my question.
Comment: I don't really understand why max-age is not a solution either. If you want to say that having a high max-age results in caching within browser that you can't invalidate then that is correct, but there are pretty easy ways to avoid that, for example, you can use the Surrogate-Control header with Fastly: https://docs.fastly.com/guides/tutorials/cache-control-tutorial (I'm sure a custom varnish configuration can be configured to use a similar header)
Comment: @Berdir, I might be wrong here, but this is one element (i.e. a block) in almost all pages and we don't want to flush the whole page just to refresh this one component?
Comment: @vijaycs85 I don't know what you mean. whether it gets explicitly invalidated through a tag or implicty by expiring it, you have to invalidate everything that contains your content, both the block caches and any cached full page, in the internal page cache and varnish. tags vs. age makes no difference there?
Comment: @Berdir probably I misunderstood the many-to-many relationship part on https://www.fastly.com/blog/surrogate-keys-part-2. Thanks for your time. I will update the question reflect this change.

P.S: one more reason to use cache tag vs max-age is, when multiple component tries to set max age on a single request, we might need a custom implementation to decide which one should be used.
Comment: Multiple max-ages are reasy to resolve: the lowest number wins. If there are 3 components, with 5, 10 and 15 minutes max-age, then the page is valid for 5min.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/50917/discussion-between-vijaycs85-and-berdir).
Answer: Here is the code that flush cache on first hit of a day:
<code>  public function build() {
    ...
    ...
    ...
    $this->handleCacheTag($build['#cache']['tags']);
  }

  protected function handleCacheTag(&$tags) {
    // Get the current date number.
    $current_date_number = date('z');
    $last_date_number = \Drupal::state()->get('module_name.foo.date_counter', $current_date_number);
    // If last date in settings is different from current day, invalidate
    // tags.
    if ($last_date_number < $current_date_number) {
      $invalid_tags = range($last_date_number, $current_date_number);
      array_walk($invalid_tags, function(&$invalid_tag){
        $invalid_tag = 'foo:date.' . $invalid_tag;
      });
      Cache::invalidateTags($invalid_tags);
    }
    \Drupal::state()->set('module_name.foo.date_counter', $current_date_number);
    $tags[] = 'foo:date.' . $current_date_number;
  }
</code>
Comment: Thanks for sharing your code. I found that this didn't exactly worked as I had hoped/expected. When you enable all of Drupal 8's caching, the build process of a page controller is often bypassed because the result has been cached. This means the invalidation logic is skipped too. I ended up putting the invalidation logic in a hook_cron implementation. Another detail I changed in my implementation, is using `date('Yz')` to prevent problems around new years day.


Graph Theory Question (Bipartite graph/Cartesian)

Question: Prove that G and H are bipartite if any only if G x H is bipartite.
Can anyone give me an idea of how to start this proof?
Comment: The notation is in some need of clarification. According to [Wikipedia](http://en.wikipedia.org/wiki/Tensor_product_of_graphs) the cross product notation is more commonly used for the tensor product of graphs than for the Cartesian product of graphs. From the title it seems that you're denoting the Cartesian product with it?
Comment: A Cartesian product is bipartite if and only if each of its factors is. For G a simple graph, G is bipartite if and only if every induced cycle of G has even length.
Comment: If $G$ (resp. $H$) has bipartition $(A, B)$ (resp. $(C, D)$), make a guess as to what the bipartition of $G \times H$ is in terms of $A, B, C, D$ and try to prove it. Hint: look at their adjacency matrices.
Answer: HINT: I'm assuming that you mean the product written $G\square H$ here. If $G$ and $H$ are bipartite, let the two parts of $V(G)$ be $A$ and $B$, and let the two parts of $V(H)$ be $C$ and $D$. Then $V(G\square H)$ is the disjoint union of the four sets $A\times C$, $A\times D$, $B\times C$, and $B\times D$. Consider a vertex $\langle a,c\rangle\in A\times C$; it's adjacent to $\langle x,y\rangle\in V(G\square H)$ iff either $a=x$ and $y$ is adjacent to $c$ in $H$, or $c=y$ and $x$ is adjacent to $a$ in $G$. In the first case $\langle x,y\rangle\in A\times D$, and in the second case $\langle x,y\rangle\in B\times C$. If you continue this analysis, you should have no trouble splitting $V(G\square H)$ into two parts that witness bipartiteness of $G\square H$.
The other direction is perhaps a little less straightforward to approach. Assume that $G\square H$ is bipartite, and let $A$ and $B$ be the parts of $V(G\square H)$. Fix an $x_0\in V(G)$, and let $$A_H=\{y\in V(H):\langle x_0,y\rangle\in A\}$$ and $$B_H=\{y\in V(H):\langle x_0,y\rangle\in B\}\;.$$ Show that the sets $A_H$ and $B_H$ witness bipartiteness of $H$.
Answer: Assume $G$ and $H$ are bipartite. Each circuit in $G\Box H$ can be split into  edges coming either from $G$  or edges coming from $H$ (but not both). These edges form an even circuit in $G$ and an even circuit in $H$ (not necessarily simple). The number of edges of  the circuit in $G\Box H$ is the sum of the two circuits and therefore even.
The other direction is also straightorward. If $G\Box H$ is bipartite there are no odd circuits in $G\Box H$. Since both $G$ and $H$ are subgraphs of $G\Box H$ there are no odd circuits   in $G$ and there are no odd circuits in $H$. Hence they are bipartite.


Exibir o nome no input usando autocomplete

Question: O autocomplete está funcionando corretamente, recebo o seguinte json:
[{"label":"Jorge Valdivia","value":"16"},{"label":"Vinicius Aquino","value":"15"}]

O problema é que quando eu seleciono alguma opção, o input recebe o ID do registro, eu gostaria de fazer com que exiba o nome da pessoa no input.
// -------------- Autocomplete --------------
    $('#search_broker').autocomplete({
        source: path + "User/get_brokers",
        minLength: 2,
        select: function (event, ui) {
            broker_name = ui.item.label;
            broker_id = ui.item.value;
            alert('Nome: ' + broker_name);
        }
    });

Olha como está ficando:
Comment: Tem mais algum código além desse?
Comment: Você está falando do código no servidor que retorna o json?
Comment: Não, do javascript do autocomplete
Comment: Tem não, o único JS do autocomplete que estou usando é esse.
Answer: Tente fazer assim, inserindo o label no input pelo ID dele:
$('#search_broker').autocomplete({
   source: path + "User/get_brokers",
   minLength: 2,
   select: function (event, ui) {
      $("#id_do_input").val(ui.item.label);
      return false;
   }
});

Comment: Deu certo, muito obrigado! Eu tinha tentando dessa forma, porém não usei o return false.
Answer: Qual autocomplete está usando? Como funciona? Estou fazendo uma busca por nome de usuário num campo input porém retorna só o nome para o value.
Acredito que seja o mesmo que esteja acontecendo com o seu problema que foi sanado.
Ao buscar por USUARIO em um form de cadastro de nova ocorrência, até consigo retornar o usuário corretamente, porém precisava gravar o id dele ao invés do nome.
estou usando a função "autocomplete/jquery.autocomplete.js"
$(document).ready(function(){
        $("#userb").autocomplete("completar.php?userb=", {
            width:200,
            selectFirst: false
        });
    });

página completar.php assim:
//conecta no banco
include("conecta.php");

$q = $_GET["userb"];

$sql = "SELECT * FROM user WHERE nome like '%".$q."%'";

$query = mysqli_query($conn,$sql); // or die ("Erro". mysql_query());

while($reg=mysqli_fetch_array($query, MYSQLI_ASSOC)){

    echo $reg["id"]."|".$reg["nome"]."\n";

}

da forma como esta busco pelo nome e ao seleciona-lo fica o id no input.
se troco o primeiro $reg['id'] por reg['nome'] fica o nome no input porem preciso salvar o id no banco.


filter entity reference by another entity reference field in create content

Question: there is two content types "country" and "state".
content type "state" has entity reference field for "country".
there is another content type called "shop" which has two entity reference field for "country" and "state".
when i creating "shop" it display all the "state" .
but i want something like when user select one country, the corresponding states to the country should display.
how to do that help needed .
Comment: In Drupal 8, this can be done with [Business Rules' dependent field functionality](https://www.drupal.org/docs/8/modules/business-rules/advanced-usage/dependent-field), but there's a core issue for this at [Add AJAX support to fields using Dynamic Views Arguments via Tokens](https://www.drupal.org/project/drupal/issues/3073970).
Answer: It appears like you are looking for Reference field option limit module. Your case is their first example:

Example 1: countries and cities
Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

And yes, it works with nodes just as well as with taxonomies, as both kinds are entities.
Comment: the check box is disabled. Limit this field's options according to matching field values
Comment: @amal have you done everything exactly like they described? It worked for me. "no repo" here unless you can provide some more data (in new question if it would change meaning, and it would if you are to ask about specific implementation problems).


What is singular and non-singular values in the context of STL iterators?

Question: The section §24.1/5 from the C++ Standard (2003) reads,

Just as a regular pointer to an array
  guarantees that there is a pointer
  value pointing past the last element
  of the array, so for any iterator type
  there is an iterator value that points
  past the last element of a
  corresponding container. These values
  are called past-the-end values. Values
  of an iterator i for which the
  expression *i is defined are called
  dereferenceable. The library never
  assumes that past-the-end values are
  dereferenceable. Iterators can also
  have singular values that are not
  associated with any container.
  [Example: After the declaration of an
  uninitialized pointer x (as with int*
  x;), x must always be assumed to have
  a singular value of a pointer.]
  Results of most expressions are
  undefined for singular values; the
  only exception is an assignment of a
  non-singular value to an iterator that
  holds a singular value. In this case
  the singular value is overwritten the
  same way as any other value.
  Dereferenceable values are always
  nonsingular.

I couldn't really understand the text shown in bold?

What is singular value and nonsingular value? How are they defined? And where?
How and why dereferenceable values are always nonsingular?
Answer: If I understand this correctly, a singular value for an iterator is essentially the equivalent of an unassigned pointer.  It's an iterator that hasn't been initialized to point anywhere and thus has no well-defined element it's iterating over.  Declaring a new iterator that isn't set up to point to an element of a range, for example, creates that iterator as a singular iterator.
As the portion of the spec alludes to, singular iterators are unsafe and none of the standard iterator operations, such as increment, assignment, etc. can be used on them.  All you can do is assign them a new value, hopefully pointing them at valid data.
I think the reason for having this definition is so that statements like
set<int>::iterator itr;

Can be permitted by the spec while having standardized meaning.  The term "singular" here probably refers to the mathematical definition of a singularity, which is also called a "discontinuity" in less formal settings.
Comment: I don't think so.  It's a valid past-the-end iterator.  If it were singular, you couldn't use it to define the enf of a stream, since you couldn't compare it to any other iterators.
Comment: Can a default-constructed `istream_iterator` be considered singular?
Answer:
Iterators can also have singular values that are not associated with any container.

I suppose that's its definition.

How and why dereferenceable values are always nonsingular?

Because if they wouldn't, dereferencing them would be undefined behavior.
Answer: Have a look at What is an iterator's default value?.
As the quote indicates, singular values are iterator values that are not associated with any container. A singular value is almost useless: you can't advance it, dereference it, etc. One way (the only way?) of getting a singular iterator is by not initializing it, as shown in templatetypedef's answer.
One of the useful things you can do with a singular iterator, is assign it a non-singular value. When you do that you can do whatever else you want with it.
The non-singular values are, almost by definition, iterator values that are associated with a container. This answers why dereferenceable values are always non-singular: iterators that do not point to any container cannot be dereferenced (what element would this return?).
As Matthieu M. correctly noted, non-singular values may still be non-dereferenceable. An example is the past-the-end iterator (obtainable by calling container.end()): it is associated with a container, but still cannot be referenced.
I can't say where these terms are defined. However, Google has this to say about "define: singular" (among other definitions):
remarkable: unusual or striking

I suppose this can explain the terminology.
Comment: Watch out! Non-singular values include the past the end iterator, this one cannot be dereferenced.
Comment: @Matthieu: you're 100% right. I have updated my answer to reflect that non-singular values may still be non-dereferenceable. Thanks!
Answer:
What is singular value and nonsingular value? How are they defined? And where?

Let us use the simplest incarnation of an Iterator: the pointer.
For a pointer:

the singular value alluded to is the NULL value an uninitialized value.
a non-singular value is an explicitly initialized value, it may not be dereferencable still (the past-the-end pointer shall not be dereferenced)

I would say that the NULL pointer is a singular value, though not the only one, since it represents the absence of value.

What is the equivalence for regular iterators ?

std::vector<int>::iterator it;, the default constructor of most iterators (those linked to a container) create a singular value. Since it's not tied to a container, any form of navigation (increment, decrement, ...) is meaningless.

How and why dereferenceable values are always nonsingular ?

Singular values, by definition, represent the absence of a real value. They appear in many languages: Python's None, C#'s null, C's NULL, C++'s std::nullptr. The catch is that in C or C++, they may also be simple garbage... (whatever was there in memory before)

Is a default constructed iterator a singular value ?

Not necessarily, I guess. It is not required by the standard, and one could imagine the use of a sentinel object.
Comment: I was thinking on the same lines as you did, with *singular* iterators referring to things like a null pointer or `std::istream_iterator()`, but then I reread a couple of times the quote and came to the conclusion that this might not be the case. There is a guarantee that you cannot only assign to, but also compare null pointers (or `std::istream_iterator()` So I am no longer convinced that this interpretation holds.
Comment: @David: I think that the standard is unclear here. The use of *most of* follow by *the only exception* is dubious, why not *all*/*except* ? It seemed they were willing to account for unitialized values as well (like the example) and not only null values.
Comment: "the singular value alluded to" is actually _not_ `NULL`. The example text quoted is clear: "After the declaration of an uninitialized pointer x (as with `int* x;`), x must always be assumed to have a singular value of a pointer.". Now, an uninitialized pointer is not `NULL`. You can't even compare it to `NULL`.
Comment: @MSalters: it was supposed to be corrected but I had missed a `/` to close the `strike` tag :)


Upgrading Zerigo DNS plan through Heroku failure

Question: I'm hosting an app on Heroku and have a basic DNS plan with Zerigo. I tried to upgrade the Zerigo plan from "basic" to "tier 1" through the Heroku command line tool and received the following error:

Hostname may not be assigned to both a CNAME and other record types
at the same time (the CNAME would override all other record types
with the same hostname anyway)

Can anyone help me understand this error message, or has anyone experienced this issue firsthand?
Update:
I had no duplicate CNAME entries and I was able to upgrade my account directly through the Zerigo site. See my comment to the accepted answer below. I'll add another update if/when Zerigo or Heroku confirms the root cause.
Comment: This issue still exists to this day.
Answer: This is a known issue with the Heroku Zerigo integration. The best thing to do if you encounter this is to transfer your Heroku Zerigo account to a Zerigo direct account.
Fortunately Zerigo provides a domain reassignment function which allows you to migrate your domain between accounts with zero downtime or hassle. You can find the domain reassignment function under DNS -> Domains -> (your domain) -> Tools -> Reassign Domain in the Heroku Zerigo add-on.
If you have trouble locating the domain reassign function, check out this screenshot.
Answer: Once you create a CNAME record entry you may not then create another record with the same name.
See RFC 1034, section 3.6.2.
"If a CNAME RR is present at a node, no other data should be
present; this ensures that the data for a canonical name and its aliases
cannot be different.  This rule also insures that a cached CNAME can be
used without checking with an authoritative server for other RR types."
http://www.ietf.org/rfc/rfc1034.txt
Comment: I checked and didn't have a duplicate CNAME entry. I was able to upgrade my account directly through Zerigo, so it appears to be a bug in either the Zerigo API or Heroku CLI. Accepting your answer, thanks.


How to make popup box appear on top of body and not above body

Question: I have a popup box appears on the homepage.But the problem is ,it appears above the body or header,wherever I placed in the template. But I want it to display with transparents background,overlaying the content.Thats how popup box works normally. But how do I achieve that please?
home.tpl(This is where I play around placing the popup box)
<!DOCTYPE html>

<?php include($data['config']['THEME_DIR_INC'].'inc/meta_common.inc.php'); ?>
<title>
<?php include($data['config']['THEME_DIR_INC'].'inc/title.inc.php'); ?>
</title>
<?php include($data['config']['THEME_DIR_INC'].'inc/scripts_common.inc.php'); ?>

  <?php include($data['config']['THEME_DIR_INC'].'inc/header.inc.php'); ?>
  <?php #include($data['config']['THEME_DIR_INC'].'inc/nav_main.inc.php'); ?>

 <?php include($data['config']['THEME_DIR_INC'].'inc/promo.inc.php'); ?>

    <?php require($this->view_location); ?>

  <?php include($data['config']['THEME_DIR_INC'].'inc/footer.inc.php'); ?>

Script

Answer: you have to add css to your boxes div
div#boxes{
    position:fixed;
    z-index: 99; /* so that the div stays on top of others */
    top: 50px; /* distance from the top */
    height: 400px; /*set as neccessary */
    width: 400px;  /*set as neccessary */

    /* To center the box */
    margin-left: auto;
    margin-right: auto;
}


Display collection value using their attributes name

Question: I want to display value of collection by passing their respective attribute name.
@mandates is the result of an active-record query.
@tabattributes contains array of attribute names previously selected by users.
The code below show field attributes but I want the value of these field instead.
I've tried several syntaxes but errors occurs each time.
How can I modify my code to do that?

@mandates.map do |f|
@tabattributes.each { |att| " #{att} "}
end
Answer: If I understand you right, you have an array of elements, and you want to have an array containing the name of each element, is that it ? If yes, then array.map {|elem| elem.name} should do it. There is a shorter form (array.map(&:name)) which does the same, if you're interested in how this is working, I can detail.
Answer: If @mandates is a result set that contains models with attributes a, b, and c and @tabattributes is the array %w{a b} (i.e. you want to extract a and b from each element of @mandates) then:
a = @mandates.map { |m| m.attributes.slice(*@tabattributes) }

will give you an array of hashes with keys 'a' and 'b'. For example:
@tabattributes = %w{id created_at}
slices = @mandates.map { |m| m.attributes.slice(*@tabattributes) }
# slices is now like [ { 'id' => ..., 'created_at' => ... }, ... ]

If you only want the values and don't care about the keys then perhaps this will work for you:
@mandates.map { |m| m.attributes.slice(*@tabattributes).values }

That would give you an array-of-arrays. The first array-of-hashes would probably be easier to work with though.
If you can get at @mandates before accessing the database then you could slice out just the columns you're interested inside the database with something like this:
@mandates = Mandate.select(@tabattributes)
slices    = @mandates.map(&:attributes)

Comment: Thank's so much.  It's now working with @mandates.map { |m| m.attributes.slice(*@tabattributes).values }


Corrigir Soma resultado php mysql

Question: Codigo usado para obter o resultado
<?php
   $total = 0;
   while($row = mysql_fetch_object($trabalho)) {
      $total += $row->valor;
      echo "
$row->os	$row->descricao	$row->valor
";
   }
   echo "
TOTAL: $total
";
?>

Como faço para exibir o valor correto
resultado da soma no php e no mysql
R$: 237688.6
Resultado desejado
R$: 237688.60
Pessoal eu usei o codigo publicado pelo Eduardo Silva que resolve meu problema em varias parte no meu sistema mas encontrei um codigo que talves possa ajudar muita gente aqui
Formatação de números (php)
formartar codigo
<?php
  while($row = mysql_fetch_object($recibo_pagador)) {
      echo "
$row->nome_empresa	$row->nome_cliente	$row->data_recibo	R$ ";
      echo number_format($row->valor_recibo,2,",",".");
      echo "	id_recibo' class='btn grey darken-3'>Imprimir
";
        }
 ?>
Comment: Não seria melhor você mudar o tamanho da casa decimal na sua coluna do banco? Seria menos código para o PHP processar
Comment: Por favor nos mostre o que você fez para conseguir seus resultados
Comment: Não como comentário Cristiano, edite sua pergunta e coloque o código lá, é mais fácil de visualizar
Comment: [Formatação de números php](http://pt.stackoverflow.com/q/11301/91)
Comment: esta assim  decimal(10,2)
Answer: Utilize a função number_format():
echo '
TOTAL: ' . number_format($total, 2, ".", "") . '
';

Onde:

1º parâmetro: número a ser formatado.
2º parâmetro: quantidade de casas decimais.
3º parâmetro: dígito separador de decimais.
4º parâmetro: dígito separador de milhares.
Comment: Obrigado Eduardo
Comment: Eduardo tem como voce me ajudar a formatar meu codigo dessa parte ai? nao estou conseguindo exibir dessa forma que voce colocou apenas usando varios `echo`
Comment: O seu código completo é aquele que você adicionou à pergunta, @CristianoCardosoSilva?
Comment: Esse mesmo Eduardo

Corrigir Soma resultado php mysql


Mark location on Gmap without Click on gmap

Question: I am using Location + Gmap module. When creating a content user have to mark location on gmap. I want to to mark location on gmap automatically when user enter the values in location.

I enabled Geocoding for India and tried after set Google Maps Geocoding Accuracy to Premise, Country Level etc. but it is not marking on Gmap
I tried this documentation, But map is only displaying if I manually mark on gmap. I am using a Location CCK Field.
Answer: The location module already geolocates automatically. Go to admin/config/content/location/geocoding and make sure you have chosen a geolocation service for the counties you need.
Comment: I used it but it is not marking in map I don't know why?
Answer: Instead try this modules it have the option same like your requirement. See the below screenshot and also easy to configure.
Geofield Gmap allow to use a google map v3 map to input a location.
A quick text input + geocode allow you to specify an address.
You can drag and drop the marker to narrow the position.

Geofield Gmap require geofield.
Geofield is a module for storing geographic data in Drupal 7. It supports all geo-types (points, lines, polygons, multitypes etc.)
Comment: Can't It be done with the `location` + `gmap` module only.
Answer: Solved this using hook_node_api
if ($op == 'presave') {
    $geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
    $latitude = $output->results[0]->geometry->location->lat;
    $longitude = $output->results[0]->geometry->location->lng;
    $node->field_event_location[0]['latitude'] = $latitude;
    $node->field_event_location[0]['longitude'] = $longitude;
    $node->field_event_location[0]['locpick']['user_latitude'] = $latitude;
    $node->field_event_location[0]['locpick']['user_longitude'] = $longitude;
    node_save($node);
}


Remover parâmetro da URL com JavaScript

Question: Estou criando uma funcionalidade para um sistema e me deparei com a necessidade de manipular parâmetros da URL, desta forma, gostaria de saber, como excluir um determinado parâmetro da URL?
Segue um exemplo mais claro:
http://site.com.br?c=cliente&a=editar&id=31228

Eu preciso remover o parâmetro a=editar da URL, tentei fazer da seguinte forma:
var urlReplace = document.URL.replace('&a=editar','');

ou
var urlReplace = document.URL.replace(/&a=editar/g,'');

Porém, nenhuma das duas formas funcionaram!!!
Comment: O que te dá `document.URL`? Não vejo porque `var urlReplace = document.URL.replace('&a=editar','');` não funciona, está correto...
Comment: `document.URL´ retorna a URL completa do meu site. E não funciona, conforme apresentei acima.
Comment: E testaste `window.location = urlReplace;`?
Answer: Se você fizer assim funciona:
window.location = document.URL.replace('&a=editar','');

Lembrando que a página será recarregada.
Answer: Tive um problema semelhante, resolvi da seguinte forma.
Primeiro atribui a url à uma variável
url = new URL(window.location.href);

Segundo, removi o parâmetro da Variável, no caso do exemplo acima é o a=editar da url site.com.br?c=cliente&a=editar&id=31228
url.searchParams.delete("a")

Por ultimo reescrevi a URL sem o parâmetro
window.history.pushState('object or string', 'Title', url)

O código completo ficou assim
url = new URL(window.location.href);
url.searchParams.delete("a")
window.history.pushState('object or string', 'Title', url)

Comment: +1 por sugerir o [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL). Recomendo que ajuste o código para usar window.location ao invés de pushState, porque a pergunta não é sobre o history.pushState, é apenas sobre remover parametro e direcionar de verdade.
Answer: Em browsers modernos essa operação pode ser feita com o auxilio da interface URL, Internet Explorer ainda deve utilizar o polyfill. Veja Tabela de compatibilidade com os browsers.
A interface URL representa um objeto que fornece métodos estáticos usados para criar URLs.
Use o constructor URL() para retornar um objeto URL definido por uma string.
Esse objeto possui a propriedade URL.searchParams que permite o acesso aos parâmetros de consulta que a URL possui.
Dois métodos de URL.searchParams serão uteis:

URLSearchParams.has() que retorna um booleano true indicado que aquela URL possui determinado parâmetros de consulta. Caso o contrário retorna false.
URLSearchParams.delete() que exclui o parâmetro de pesquisa fornecido.

//Cria uma instância de url a partir dum string.
const url = new URL('http://site.com.br?c=cliente&a=editar&id=31228');

console.log(`URL original: ${url}`);     //Imprime a url original.

let params = url.searchParams;           //Obtém os parâmetros de consulta da url.
//Verifica se o parâmetro a existe...
if (params.has('a')) params.delete('a'); //Se o parâmetro existir o remove.

console.log(`URL modificada: ${url}`);   //Imprime a url modificada
Comment: Ótimo, muito mais simples do que escrever algo com regex (não estou dizendo que não funciona, só que é mais simples), apresentando as propriedades básicas úteis ao casos, has e delete e colocando em um exemplo "TESTAVEL" com um unico clique +1 ... vou +1 para o Willian porque ele sugeriu a mesma coisa, apesar de ter adicionado coisas irrelevantes como pushState.
Comment: @GuilhermeNascimento o acompanhei nesse +1 para o Willian.

Remover parâmetro da URL com JavaScript


htop cgroup column widen

Question: How can I see full length of text CGROUP column in htop? I cannot enlarge it.
Answer: Seems a duplicate of this: https://stackoverflow.com/questions/33269339/htop-process-viewer-set-column-width
In short, in current versions the column width is fixed. You can ask for this enhancement to the devs or implement it yourself :-)
You can use ps to find the processes in control groups you're interested in.

htop cgroup column widen


Laurent expansion on border of annulus

Question: $$ f(z)= \frac{1}{(z-2)(z^2+i)} $$
I want to find the laurent expansion of this function at z=2 in the region
$$ 1 < |z| < 2 $$
if someone could help me with this not just telling me what to do but help me visualizing what this means.
Comment: Your question doesn't make sense. The region you mentionne doesn't contain $2$.
Comment: This is the exactly how it was written in my exam by the professor, i doubt he got it wrong
Answer: As stated, this is nonsensical, since $2$ is not in the region $1<|z|<2,$ so we won't be able to help you visualize what it means. Probably what happened is that your professor copied and pasted from another problem, but didn't quite finish editing out the parts that weren't supposed to be there.
The best I can do for you, then, is speculate about what your professor may have intended to say, and see what sense the alternatives might make. Off the top of my head, the following could be what was intended:

Find the laurent expansion in the region $1<|z|<2.$
Find the laurent expansions at $z=2$ and in the region $1<|z|<2.$
Find the laurent expansion at $z=2.$
Find the laurent expansions at $z=2.$
Find the laurent expansion at $z=2$ in the region $1<|z-2|<2.$

Of course, it could be that something wildly different was intended, but those are the only obvious alternatives I can see.
I suspect that options 2-4 are incorrect (and know that option 5 is incorrect), for several reasons. For one, we typically specify regions for laurent expansions, unless the function is entire, which is not the case, here. Thus, asking for a laurent expansion at a point (a singular point, no less) is nonsensical. It could be that "at $z=2$" should be interpreted as "centered at $z=2,$" but even then, option 3 is nonsensical, as there are three annuli about $z=2$ on which a laurent series for $f(z)$ can be obtained, and it is not specified which of the three to use. Also, option 5 is impossible even under that interpretation, because the annulus $1<|z-2|<2$ contains the pole $z=-\sqrt{2}+i\sqrt{2}.$ Thus, we're left with options 1, 2, and 4.
If we want to fully cover our options, we should assume that option 2 is what was meant, but that means finding four different laurent expansions, so in a testing situation, that would perhaps be inadvisable. However, it only differs from the posted problem by the single short word "and," so it could well be what was intended. It seems unlikely that option 4 was intended, because that would mean that the professor would have to misspell a word and fail to notice a fairly long phrase that wasn't supposed to be there, especially if "$1<|z|<2$" was typeset in the center, as it is in your post. It would be relatively easy to miss the short phrase "at $z=2,$" though, so I could easily see it being option 1.
The best advice I can give, if you encounter such a situation again, is to get up, take the exam copy to your professor, and ask for clarification. Everyone makes mistakes, and hopefully, your professor isn't the sort who won't admit to them.
If your professor is unwilling to provide such clarification, or if you are for some reason unwilling or unable to ask for it, there are really only two ways to go that I can see. You could assume that option 2 was meant, which would cover all the obvious options. Alternatively, you could (and in your place, I would) assume that option 1 was meant, then move on to the rest of the exam, and return to cover the other expansions if you have time to spare after completing the rest.
Comment: Isn't it possilbe though that the region is the intersection of $$ 1<|z|<2 $$ and $$ |z-2|< \sqrt{5} $$ where $$ \sqrt{5} $$ is the distance from the closest singularity. Isn't it possible to expand the series in this region?
Comment: The closest singularity to $z=2$ (aside from itself) is $z=\frac{\sqrt2}{2}-\frac{\sqrt{2}}{2}i,$ so the distance between them comes out to $\sqrt{5-2\sqrt{2}}.$ We can certainly expand it in the intersection of $|z-2|<\sqrt{5-2\sqrt{2}}$ and $1<|z|<2,$ but we could just as easily do so in the intersection of $|z-2|>\sqrt{5-2\sqrt{2}}$ and $1<|z|<2,$ and I see no reason to suspect that one of these is more likely to be the intended region than the other.
Comment: sry about the wrong math i brainlagged a bit and computed the wrong distance thanks for correcting me.Anyways, why would you assume that this couldn't be the desired region in this problem?
Comment: It's not that it couldn't be, it's just that I see no evidence that it should be. As I said in my answer, the five options that occurred to me are by no means the only ones that could've been intended, just the most obvious ones, based only on the text.
Comment: Couldn't it be that its $$ \sum a_n (z-2)^n $$ for the intersection $$|z-2|<\sqrt{5-2\sqrt{2}}  $$ and $$1<|z|<2 $$ and $$ \sum b_n (z-2)^{-n} $$ for the intersection $$|z-2|>\sqrt{5-2\sqrt{2}}  $$ and $$1<|z|<2 $$. If so is it correct to just compute the series and say that the regions are these intersections? Is there a way to write these intersections as one inequality?
Comment: It certainly could be! We can't reduce the intersections to a single inequality, but we can certainly express them as a single set, such as $$\left\{z\in\Bbb C:1<|z|<2\textrm{ and }|z-2|<\sqrt{5-2\sqrt{2}}\right\}.$$
Comment: See [here](https://www.wolframalpha.com/input/?i=1%3C%7Cz%7C%3C2+and+%7Cz-2%7C%3Csqrt(5-2*sqrt(2))) for some other ways the region could be described.
Comment: I don't know what else to assume for this problem so after thinking about it all day this is the only thing i can come up with. Thanks for helping my friend!
Comment: You're welcome!
Comment: By the way, if you find an answer helpful, you can give it an upvote. If an answer completely (or at least sufficiently) addresses a question, you can also "accept" it by clicking the check mark. This garners reputation for you and the answerer, and lets other users know that the question has already been answered to the asker's satisfaction. Welcome to the site!
Comment: Thanks for informing me i will do it!

Laurent expansion on border of annulus


Jacobi Method with error

Question: Preparing for my Numerical Analysis exam,
If the Jacobi's method is used to solve the linear system, $Ax=b$, where
$$A=\begin{pmatrix}5 & -2 & 3\\-3 & 9 & 1\\2&-1&-7\end{pmatrix}$$
will the method be convergent?
This part I think I can do. Since there is no $b$ vector as in $Ax = b$, we cannot iterate toward a solution. Instead we reason that $A$ will converge using the Jacobi method as it is diagonally dominant.
Then it says, Determine the matrix G in the error equation $e_{n+1} = Ge_n$, and test the convergence criterion using either $||\cdot||_\infty$ or $||\cdot||_1$ norm.
I know that the norms are the max of the column and row sums, but I don't understand the "find the matrix G in the error equation" part of the question.
Comment: If you don't have a solution vector, then you don't have a problem; so we can take it as read that $b$ exists, even if we don't know what it is.  Its value is irrelevant to the problem.
Comment: If you do the calculations, writing $x_i = x+e_i$, you should find that the error $e_{i+1}$ depends in a nice way on the previous error $e_i$ (and in fact, it may well satisfy a linear transformation).
Comment: @tabstop forgive me, but I truthfully don't understand what you mean. Given that there is no solution vector, we cannot iterate toward convergence / divergence, but knowing that $A$ is diagonally dominant, means that it's guaranteed to converge.
Answer: If we write
$$x_{k+1}=D^{-1}(b-Rx_k)$$
where $D$ is the diagonal bit and $R$ is everything else, and we write $x_k=x+e_k$ where $e_k$ is the error in the $k$'th iterate, then
$$x+e_{k+1} = D^{-1}b-D^{-1}R(x+e_k)$$
and multiplying through by $D$ we have
$$Dx + De_{k+1} = b-Rx-Re_k$$
but since $x$ is a solution, $Dx+Rx=b$; consequently
$$De_{k+1} = -Re_k$$
regardless of the value of $b$.  Presumably you can figure out from here how to get $e_{k+1}$ by itself.
Answer: In methods like Jacobi and Gauss-Seidel, you create a fixed point iteration of the form $f(x_k) = x_{k+1} = Tx_k + c$. For it to work, you require that at your solution $x^{*}$ the iteration returns $x^{*}=f(x^*)=Tx^{*} + c$ . We can express the equation $Ax=b$ as
$$Ax = (L + D + U)x = b$$
$$Dx = -(L+U)x + b$$
$$x = -D^{-1}(L+U)x + D^{-1}b$$
If we turn this into an iteration we already have the form we wanted above and we know that at the solution the iteration will return the solution, since that is how we got it in the first place.
This is actually the Jacobi iteration, where the iteration matrix $T=-D^{-1}(L+U)$.
The question now is whether this iteration will converge and for which $x_0$. To answer this question we define the error at step $k$ and then substitute with the equations we derived above.
$$x_{k} - x^{*} = e_{k} = Tx_{k} + c - Tx^{*} - c = T(x_{k} - x^{*}) = Te_{k} = T^{k}e_{0}$$
So the error at each step is transformed by $T$ and is amplified or increased linearly by it. We want the error to decrease, so we need to derive a condition that guarantees that the error will disappear, which we can do using matrix norms and two associated inequalities $|Ax| \leq ||A||\; |x|$ and $||AB|| \leq ||A||\;||B|| $:
$|T^ke_0| \leq ||T^k||\;|e_0| \leq ||T||^k\;|e_0| \implies e_0 \rightarrow 0$ as $k \rightarrow \infty$ iff $||T||<1$ for some norm of T and any $x_0$.
So the $G$ in your case is the $T$ in my explanation and it is the iteration matrix that ends up remapping the error you make at each step of the iteration we have derived above.

Jacobi Method with error


How to bootstrap panel data?

Question: I'm fitting some machine learning algorithms (e.g. SVM) on my panel data. It's taking too long for my entire dataset, so I'm considering generating smaller samples from bootstrapping then fit the SVM in parallel.
At first glance, it may seem like by bootstrapping I will destroy the time-dimension of my data. However, if I include variable lags and moving averages, can I just bootstrap as normal (i.e. considering each observation as independent)?
Comment: I'm not trying to be deliberately obtuse, but I find it confusing to call your procedure bootstrapping since that normally implies that the resamples are the same size as the original data set.  I would just call it "subsample with replacement." (And it's not clear to me why this would be a preferred solution to subsampling without replacement.)
Comment: Some sort of stochastic gradient descent would be the first direction I would turn if I had too much data, eg, http://scikit-learn.org/stable/modules/sgd.html.  Although the question still remains over the preservation of block structure.  Bootstrapping, in the sense of Efron , isn't going to help you to reduce computational effort because your resamples are the same size as the original data set.
Comment: My thinking is to use bootstrap to generate smaller samples, which can be fit in parallel. Does this not help?
Comment: That makes sense actually. Thanks for clearing up my thinking.
Answer: Generally, if you have a complicated data structure bootstrap sampling should reflect how real sampling was done. For example, with clustered or hierarchical data you rather sample whole clusters, than individual observations, because sampling individuals gives you a biased sample (e.g. Rena et al. 2010, Field and Welsh, 2007). For time-series two approaches were suggested in literature:

Model-based resampling - you fit a model to the data to construct residuals from the fitted data and then generate new data using those residuals, so that you can sample "approximate disturbances" that can be found in your data.
Block sampling - you sample blocks of data from time series (e.g. $x_{t-1}, x_t, x_{t+1}$) and then sample those blocks, so that local time structure is preserved.

You can find nice examples of those sampling strategies in a classic book by Efron, or in great handbook by Davison and Hinkley.
However, as also Andrew M mentioned, bootstrap applies to sampling with replacement $N$ observations out of $N$ observations, so this won't help with making the dataset smaller - it will make things worst, because you would have a sample of $N \times R$ draws.
Comment: In block sampling you sample *whole* blocks, not individuals, so the answer is not. Sampling individuals crushes the data structure. (See the inks provided)
Comment: I'm having block sampling in mind. My procedure is to sample observations independently, then for each selected observation also include the n-lags from the previous time periods. Is this procedure the same as block sampling?
Answer: I would use something called cross-ssectional resampling discussed in this paper and here with less detail
I like this approach because its simple and intuitive.  Basically where the panel data dimensions are time and individual unit, I would simply bootstrap (sub-sample) the individual units and keep all the observations for those units along the entire time period in the sample.
In  other words, if you have $50$ individuals over $20$ time periods  I would bootstrap (sub-sample) the $1:50$ individuals, and for those selected include all $1:20$ time periods.
The idea is that the data are likly auto-correlated in time, and you want to keep the time dependence structure intact while re-sampling, as to reflect the original sample.
If you for some reason had to reduce the size of the time dimension as well, then you would probably want to randomly sample by blocks of time.

How to bootstrap panel data?


Mastering carnatic gamakas (slides, deflections)

Question: I started learning Indian classical violin a couple of years ago. There is a lot of rigor in getting things right with my instructor, and sometimes I feel I'm plateaued and not making progress.
Particularly, I'm learning to produce deflections at various speeds (4 notes per beat) and it is really hard to understand the difference between last time I played the same note sheet and this time, and evaluate where I go wrong. Every time, it is a completely different aspect, each time.
However, I started learning to sing along with it (taking classes), and I made a lot more progress in terms of notes, raagas and melodies I can sing, including varnams and krithis.
Can anyone relate to this, or tell me how to approach improving my skills and keep motivated? My instructor keeps telling me that this aspect takes a long time, (couple of years), and this will fall in place. I just don't see how though.
Comment: Reaching and then moving past plateaus has been, and continues to be, part of the learning process for me on all the instruments i play.
Answer: Your instructor is correct that improving your skills is a long term process and happens over years of study. However, you should also be able to see improvement from week to week and even from day to day if you are practicing effectively. Here are some suggestions:
1) As your instructor to be clear about what he/she sees improvement on from week to week. This can be very motivating for you!
2) When practicing, be clear about what specific goals you have each day. Make sure these goals are measurable (ex. playing farther without making a mistake, playing at a faster tempo (use a metronome), etc.) If your goals are not measurable they will be harder to see. It does not mean you aren't making progress, but you may not feel like you are. Writing down what your goals are and how you are progressing with them can also help you see where your progress is and help you stay motivated.
Answer: I'm learning Indian classical violin and I relate to the issues you have mentioned . One of the things that helped me is to keep practising the basic lessons everyday, no matter what lesson I am in currently. I also set goals for myself for each 15 day period and record myself to see the differences. Also, if I know I  get stuck on a particular deflection, I play it repeatedly until I get it. That has been helpful in perfecting the song when it I play the composition fully. Hope this helps.


Suppose that $f'(z)$ exists on $\mathbb{C}$ and $\Im(f'(z))=6x(2y-1)$, $f(0)=3-2i$ and $f(1)=5-5i$. Find $f(1+i)$.

Question: Suppose that $f'(z)$ exists on $\mathbb{C}$ and $\Im(f'(z))=6x(2y-1)$, $f(0)=3-2i$ and $f(1)=5-5i$. Find $f(1+i)$.
I think $f'$ satisfy the Cauchy-Riemann equations, but I don't know how to complete. Any help?
Thanks!
Answer: Hint:
Since $f'$ exists on $\mathbb C$, it follows that $f$ is entire, and hence $f'$ is also entire.
Therefore, as you said, $f'$ satisfies the CR equations.
Let $f'(x+iy)=u(x,y)+iv(x,y)$. Then, you are told that $v(x,y)=6x(2y-1)$.
You can use the Cauchy Riemann equations to find $u$ up to a constant.
Use $f'(x+iy)=u(x,y)+iv(x,y)$ together with $x=\frac{z+\bar{z}}{2}, y=\frac{z-\bar{z}}{2i}$ to get $f'(z)$ as a function in $z$.
This gives you $f'$ and by integration you can get $f$, with two constants.
$f(0)$ and $f(1)$ tell you what these constants are, therefore, you get $f(z)$.
Comment: @RobertDavis Simple example$f'(z)=2z-1$. What is$f(z)$? BTW: I told you step by step what to do, but you jump directly to step 3, that's why you are confused...
Comment: @RobertDavis The bars didn't cancel, which means that you already did a mistake, so there is no need to go to the next step yet, you have first to find your mistake. Check again the steps when you went from $x,y$ to $z,\bar{z}$, note that $$x^2=\left( \frac{z+\bar{z}}{2} \right)^2$$ and I think you forgot to square the denominator.
Comment: @RobertDavis When you find $f'(z)$ you can check your answer by replacing $z=x+iy$. If you plug $z=x+iy$ into $ 9z^2 +3\bar{z}-i6z$ you do not get $u(x,y)+iv(x,y)$, and this tells you that there is a mistake in your computations.
Comment: @RobertDavis This comes from experience, but is a bit subtle so I would not expect my students to see this. Here is why this must be the case in this problem. First $v(x,y)$ is a polynomial of degree 2 in two variables, which together with CR implies that so is $u(x,y)$. Therefore, after replacing $x,y$ by $z, \bar{z}$ we will get a polynomial in $z, \bar{z}$ of degree 2. Thus, I knew that the answer will have the form $$f'=az^2+bz \bar{z} + c \bar{z}^2+dz +e \bar{z}+f$$ Since this is entire, subtracting the entire function $az^2+dz +f$ we get that $$bz \bar{z} + c \bar{z}^2+e \bar{z}$$
Comment: is entire. Now, by adding the right function of the form $\alpha z^2 + \beta z$ you can write this in the form $u^2+ \gamma u$ where $u$ has the form $u= (\sqrt{c} \bar{z} + \sqrt{\alpha} z)$ . Finally, as $u^2+ \gamma u$ is entire as a function in $u$, and $\sqrt{c} \bar{z} + \sqrt{\alpha} z$ is nowhere differentiable unless $c=0$, it is easy to show that the composition between an entire function and a nowhere differentiable function is non-differentiable at all points where the derivative of the entire function is zero.
Comment: By this argument we can get that $c=0$  and by playing the same game two more times you get $b=e=0$....... Rule of thumb:  If a polynomial in $z, \bar{z}$ is entire, it has to be a Polynomial in $z$.
Comment: @RobertDavis You know that $x=\frac{z+\bar{z}}{2}$ and $y=\frac{z-\bar{z}}{2i}$. By doing this $f$ becomes a function in $z$, and since $\bar{z}$ is nowhere differentiable, the terms with $\bar{z}$ will cancel eachother...
Comment: @RobertDavis What did you get for $f'$?
Comment: I obtain $u=6x^2+6y-6y^2+c=6(z^2+\bar{z}^2)-3i(z-\bar{z})+c$. The $\bar{z}$ didn't cancel each other. Are you certain of your method? I don't understand at all!
Comment: @RobertDavis So what is $f'$? I said that the $\bar{z}$ should cancel in $f$ not in $u$ ;)
Comment: So I obtain $(6(z^2+\bar{z}^2)-3i(z-\bar{z}))+i(-3((z^2-\bar{z}^2)i+(z+\bar{z})))=9z^2 +3\bar{z}-i6z$. Could you tell me the next step, because I don't see it? And I reverified  the equation, I don't see how to cancel $\bar{z}$.
Comment: What is the advantage of using this method, then we can use Cauchy-Riemann?
Comment: @RobertDavis What do you mean the advantage of this method? As opposite to what? CR equations allow you to find one of $u,v$ if you know the other, and this is exactly the first step we do. If we know $u$ and $v$, we can combine them in our function...But we are given the imaginary part of $f'$ not $f$, which means that at this point we find $f'$. From here, next step is to figure what f is ...
Comment: Yes, but using Cauchy-Riemann equations you get something like this, I think
$$f '(z)=u_x(x,y)+iv_x(x,y)=v_y(x,y)-iu_y(x,y)$$
From here, you can get the answer
$$f(z)=f(x,y)=f(x+iy)=u(x,y)+iv(x,y)$$
Comment: @RobertDavis And what is $v$? Because the $v$ you are using is the imaginary part of $f'$ not the imaginary part of $f$! If you want, you can denote by $g=f'$ and use the CR equations for $g$.... Because you know the imaginary part of $f'$ you are using the CR equations for $f'$ NOT for $f$.
Comment: @RobertDavis Or if you want to go on this route you started, the problem tells you that $Im(f')=6x(2y-1)$. This means that $$v_x(x,y)=-u_y(x,y)=6x(2y-1)$$ Try to find $u,v$ from here.
Comment: One last question : "By doing this $f$ becomes a function in $z$, and since $z¯$ is nowhere differentiable, the terms with $z¯ $will cancel eachother...'' How do you know this is true? I don't understand why it works


"Items in your active configuration have changes"

Question: I'm trying to setup configuration management for our team, so i test the workflow on my local machine:
Starting from a fresh copy of our website + database backup, with an empty /config folder ($settings['config_sync_directory'] = '../config';). When i use the command "drush config:export", the task runs and all the .yml files are generated in the /config folder.
I then change the websites name (system.site), just as a simple test.
Then, when visiting the configuration management UI in drupal, i would expect to see only 1 change. And indeed that is the case but i also see a huge list (all config) of untouched settings and the warning "The following items in your active configuration have changes since the last import that may be lost on the next import"
If i just exported all my config, did 1 change, then why is it saying that i have changes in my db that don't match with .yml files in the /config folder?
However, if i first click on 'import all', do the 1 change, revisit the configuration management UI, then i also get the warning but only with the 1 change.
So why is that?

Comment: Init git, track changes exactly. Probably just sorting. What happens when you re-export again, then change site name again?
Answer: It could be because of configuration sorting.


First "Simple" Audio Player Application

Question: Can anybody please tell me how to implement an audio player application in an iPhone? I am pretty new to iPhone development and I am just starting to learn the tricks of the trade.
PS: I need sample code!
Answer: If you want to play your own sounds, the AVAudioPlayer class. If you want to play media from the iPod library, see MPMusicPlayerController.

First "Simple" Audio Player Application