jQuery Animation Hover Issue

Question: I have the following code for 3 images so that when a user hovers over the image, the images zoom slightly:

A demo can be seen here:
https://ts361831-container.zoeysite.com/#global-wrapper-cp-09977e207fd109223f695752160117fd
This works fine if you perform the hover slowly, but if you hover quickly or hover over multiple images at once, the width and height keep decreasing.
Can anybody help me identify why this is happening? Thank you very much in advance.
Comment: Why don't you use a plugin for getting that effect.It will be easily available.
Comment: you can add multiple hover to image.. check it out https://jsfiddle.net/klakshman318/jd2agz8r/1/
Answer: try this! Simply you can do it with css transform

.image-box{
  width:300px;
  overflow:hidden;
}
.image {
 width:300px;
  height:200px;
 background-position:center;
 transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
}
.image:hover {
  transform: scale(1.5);
  -moz-transform: scale(1.5);
  -webkit-transform: scale(1.5);
  -o-transform: scale(1.5);
  -ms-transform: scale(1.5); /* IE 9 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1.5, M12=0, M21=0, M22=1.5, SizingMethod='auto expand')"; /* IE8 */
   filter: progid:DXImageTransform.Microsoft.Matrix(M11=1.5, M12=0, M21=0, M22=1.5, SizingMethod='auto expand'); /* IE6 and 7 */
}

JSFIDDLE
Comment: I never knew about scale. This is perfect for me - thank you.

jQuery Animation Hover Issue


C++ functors usage, code duplication avoidance

Question: ok so im not sure if its related to functors but from what i understood it is so
the question is:
lets assume i have the next class:
class Matrix{
public:
    Matrix(int, int);                       // constructor
    Matrix(const Matrix&);                  // copy constructor

    Matrix& operator+= (const Matrix&);
    Matrix& operator-= (const Matrix&);
    int* operator[] (int) const;

private:
    int rows;
    int cols;
    int** Mat_p;
};

and i want to overload the += and -= operators in Matrix class.
now, in order to sum or subtract 2 matrices we need to iterate over each value of both matrices and add or subtract so it will be some thing like:
Matrix& Matrix::operator+= (const Matrix& M){
    for (int indexR = 0; indexR < rows; ++indexR)
        for (int indexC = 0; indexC < cols; ++indexC)
            Mat_p[indexR][indexC] += M[indexR][indexC];
}

Matrix& Matrix::operator-= (const Matrix& M){
    for (int indexR = 0; indexR < rows; ++indexR)
        for (int indexC = 0; indexC < cols; ++indexC)
            Mat_p[indexR][indexC] -= M[indexR][indexC];
}

as you can see both operators "+=" and "-=" has the same structure give or take, so one of the basic so called "rules" is to avoid code duplication.
so the asked question is how do we avoid this duplication and keep the code effective ?
Comment: This small amount of code duplication is not a real issue imo
Comment: @Brian Well and still I would like to avoid it (and any way it's just an example...)
Answer: You could implement a single templated function and make two calls into it.
template<typename T>
Matrix& add_or_sub (const Matrix& M, const T &op){
    for (int indexR = 0; indexR < rows; ++indexR)
        for (int indexC = 0; indexC < cols; ++indexC)
            Mat_p[indexR][indexC] = op(Mat_p[indexR][indexC], M[indexR][indexC]);
    return *this;
}

Matrix& Matrix::operator+= (const Matrix& M){
    return add_or_sub(M, std::plus());
}

Matrix& Matrix::operator-= (const Matrix& M){
    return add_or_sub(M, std::minus());
}

Comment: 4 minutes late... I have two notes though. I think it's better to name `add_or_sub` `piecewise_apply`, as this is what it does. And shouldn't it return `M` or `*this` if it's meant as a member function?
Comment: @luk32 I just copied the code from the question, didn't notice it was missing a `return`. P.S. [naming is hard](http://martinfowler.com/bliki/TwoHardThings.html).
Comment: @MarkRansom Thanks, much appreciation, lets say i would like to add another operator overload, lets say for *= or * (without assignment) with scalar parameter (int), means i want to multiply each node of my matrix by scalar int. could it be implemented in the given code with the given template ??
Thanks in advance.
Comment: @Itay.V I can't see an easy way to make the same code work for both situations, they're too different.
Answer: I'm a bit late, but I guess the example is more complete. I would suggest writing a piecewise functor applicator which uses underlying scalar as operands, and returns the same type as well, and implement operators using this.
An example:
#include <iostream>
#include <functional>
using namespace std;

template <int Rows, int Cols, typename Scalar = int>
class Matrix {
    public:
    void piecewise_apply(const Matrix& other, std::function<Scalar(Scalar,Scalar)> f) {
        for (int indexR = 0; indexR < Rows; ++indexR)
            for (int indexC = 0; indexC < Cols; ++indexC)
                data[indexR][indexC] = f(data[indexR][indexC], other.data[indexR][indexC]);
    }

    Matrix<Rows,Cols,Scalar>& operator+=(const Matrix<Rows,Cols,Scalar>& rhs) {
        piecewise_apply(rhs, std::plus<Scalar>());
        return *this;
    }

    Matrix<Rows,Cols,Scalar>& operator-=(const Matrix<Rows,Cols,Scalar>& rhs) {
        piecewise_apply(rhs, std::minus<Scalar>());
        return *this;
    }
    private:
    Scalar data[Rows][Cols];
};

int main() {
    Matrix<5,5> a;
    Matrix<5,5> b;

    a.piecewise_apply(b, [](int a, int b){return a*b;});
    a -= b;
    return 0;
}

The example is not complete, as it lacks initialization. Also there is no protection when &rhs == this (a interesting place for optimizations), and probably some more, but it shows the idea. As for code efficiency.. well you should rely on the compiler on this one.
One advantage of this approach is that, even if it's a bit slower in the default version, you can try writing piecewise_apply which uses more elaborate optimization techniques, like blocking, or parallelization, etc. and get speedups in various places.
For a simple version, like in your example, the copy-paste version is shorter, and easier to understand, so probably a better choice.


I cannot spread my fingers easily. Am I anatomically disadvantaged for playing the guitar?

Question: Six months ago I started to play the guitar. I like it very much. It became one of these things that I regret not started earlier in my life (I am 25 years old)! By now I can say I am not a complete beginner anymore. I practice whenever I can (about 7 hours per week).
One thing that bothers me a lot is that I seem to be unable to spread my index finger and ring finger far enough to play power chords like the F5:

When I play this chord with not investing much effort it looks like this:

By no effort I mean that my hand and my upper body are relaxed and under no tension. My left arm is leaned onto my body. The guitar is resting comfortably on my leap and is slightly pointing away from me.
When I try hard to play the chord perfectly, so the fingers are in a 90 degrees angle to the strings, it looks like this:

As you can see it is slightly better. But to achieve this I have to put much more effort in my body tension. I have to position the guitar a little bit outside my lap so I can achieve a 90 degrees angle between my arm and the guitar neck. Also I have to move my left arm a little bit away, so it is not leaned against my body anymore.
I met other guitar players and explained my problem to them. They seemed totally unaware of this so it makes me think that I might be one of few "anatomically disadvantaged" guitar players. Is anybody experiencing (or has experienced) this problem?
Update
I want to thank all of the answerers for encouraging me. It really boosted my will to play guitar even more. Additionally I lowered my strings on my guitar, because they were way to far from the fretboard. Now it is even easier to play this chord. It does not sound nasty because I don't need that much force anymore.
Comment: I *never* have a 90 degree angle between my arm and the guitar neck. In fact, I *avoid* such an angle because it causes me terrible icky pain and makes it so I can't play at all. The most comfortable way to finger a chord that sounds good is the right way to play it. I don't know where or how you got the notion that there should be a 90 degree angle between your arm and the neck, but I recommend you don't listen to that source of incorrect information again. I've played for 24 years and my hand looks very much like your top photo when I play this chord.
Comment: Ahh, now we are getting somewhere. See the daylight between the neck and the part of your palm behind your pinky finger? I don't have that. I bring my hand up until it's touching the bottom of the neck more completely. **Don't** swing your elbow out to make chords sound good, that way lies injury. **Do** give yourself more than six months to learn to play a clean, comfortable F chord at the first fret. This is the hardest power chord to play on the whole neck, it should take quite a while before your fingers learn perfect placement.
Comment: You don't have a problem. In your second picture you are doing the right things - you just need to learn how to use less pressure.
Comment: Thanks for your comment. Actually when I play the guitar like you see in the first picture, it sounds not good at all and very dirty, because I cannot put enough pressure with my ring finger onto the string. I don't think it is a problem about too low pressure. It is just that I cannot put that much pressure onto the string when I do not have a 90 degrees angle between strings and fingers.
Comment: Btw, I started at 19 and it's the best thing in my life. Stick with it, it's never too late!
Answer: You shouldn't need to aim for 90 degrees, and you shouldn't need much effort or pressure at all.
When I play that, I use only a little pressure, and my wrist is entirely relaxed. My little finger and index finger also are relaxed and floating.
Unlike Todd's guidance, though, my hand does not touch the neck at all - it's free floating, just resting between thumb and fingers, which makes moving really easy.
Comment: Nice double neck.
Comment: It's only an epiphone but it's a nice one. It's my usual composing one by my desk (as the others are all up on the wall)
Comment: Bit awkward hanging double necks...
Answer: Don't try to have a 90° angle, it's bad for ergonomics and could cause injury.
For this chord based on your first photo, I think you actually want to try to work your ring finger closer to the third fret. Your index finger looks just right. You might try angling your hand even more (not less), and try bringing your palm up closer to the bottom of the neck.
This is how I play the F power chord:

The main reason why I like to have my palm against the back of the neck is to make it so I can just squeeze with my fingers without having to put as much tension on my arm. Normally I don't bend my wrist this much, but I have to in order to get my fingers up high enough.
I do keep my fingernails pretty short to prevent the adjacent strings from rattling against them and so they don't impede my fretting in any way.
And give yourself plenty of time to learn precise finger positioning. Your hand looks really good (in the top photo) for someone who has been playing for only six months. Be patient and don't go for uncomfortable hand positions. And if you really want to progress quickly and safely, get a teacher.
BTW, for many years when I played power chords on the low E string, I fretted the low E with my thumb over the top, like this:

The knuckle of my thumb is actually fretting the low F on the E string. Even though my pinky is in the fretting position for the three note power chord, I'm just muting with it there.
Notice my wrist is higher up and not bent.
Comment: Thanks for the nice words! So you say it will get better after a while of (a lot more) practicing? I enjoy it much, this issue won't stop me from going on and trying harder.
Answer: It looks as if your hand is normal.  Stretching to extended chord shapes does take a lot of practice.  Try putting your thumb nearer the center of the back of the neck, you appear to be 'grasping' the neck rather too much.
Answer: Firstly, try to free your left arm from your body. It'll be better in the future, as keeping the elbow in restricts whole arm movement.
Secondly, when a power chord is played, it's either two or three strings. If you prefer two, then you need no more than two fingers! But- why not use index and pinky? You could even put down the ring finger next to pinky, for support, because it won't affect the sound. Then, later, when you're feeling a bit more advanced, you'd be able to reach the same fret on 4th string for the root octave, which thickens things up a little. Practise power chords further up the neck, where the frets are a little closer, thus less stretchy.
Thirdly, watch a video or two of one Django, who had far less stretch than even the most stretch-challenged of us. Your worries may disappear!
Comment: @arminb  - There is no supposed. I have taught for 40+ yrs, and each student finds their own best way, with my help. Most of my students get onto 3 and 4 finger chords within a couple of months, regardless of finger length. Another option of course, is to D tune the bottom string, which seems pretty popular, and then, one can use any old fingers one wishes.
Comment: I personally disagree with the "why not use index and pinky" part of your answer. Avoiding things you're not comfortable with by circumventing them seems to be a bad idea to me. I'd rather start at higher frets and slowly work my way down the fretboard, as you suggested :)
Comment: Yes I also think it is not a good idea to substitue ring with pinky. I want to learn it the right way. At one point maybe I will get to a situation, where I need all three fingers together (or even all four). So I think it's better to learn it how it is supposed. To be flexible and "prepared" for more difficult future tasks.
Comment: The pinky is usually shorter and weaker than the ring finger. That would probably be worse for fretting the A string for power chords. While I don't think the left arm needs to be held close to the body, it should hang in a relaxed manner from the shoulder. The fretting elbow should not move outward like a bird wing because that is caused by tension and it causes more tension. Tension makes playing slower and less comfortable, and could lead to injury.
Comment: @ToddWilcox - Have to disagree with you. Ring and pinky work well together, and this double idea is good.Yes, pinky's weak, but if one needs strength to fret notes, there's something wrong! By moving the elbow out slightly, the pressure on ring/pinky is increased slightly, saving the finger/hand doing the squeezing. Playing power chords often doesn't need a lot of l.h. speed : movement is usually lateral anyway, involving whole arm movement.
Comment: Well maybe my body is weird. I suffered a repetitive motion injury from playing guitar and it set me back about a year in total. I had to stop playing completely for several months and then force myself to start up again slowly playing way below my level. Two things were crucial in my recovery: not bending my wrist up and keeping my elbow relax and hanging down. So I'm loath to ratify the idea of intentionally swinging the elbow out. And it's definitely not necessary for any technique I can think of.
Comment: Fair enough. Was the wrist bending to enable the thumb on the bottom string, something I don't really encourage, as for a lot of folk, it puts the whole hand in a not so good position.
Comment: If by "bottom string" you mean the low E string, then you're imagining the wrist bending in the opposite direction. When the first knuckles are *below* the wrist, the tendons have a straight path through the carpal tunnel. Usually to fret the low E string, people tent to bend their wrist up so that the first knuckles are above the wrist (like Dr Mayhem's photo) which creates a bend right at the carpal tunnel. Playing thumb over the top is more ergonomic because of the straighter tendon path, but it does make it very hard to fret the low E string.
Comment: Yes, bottom string, low E. I can't get my thumb over the top of the neck, so my fingers do all the work. As my guitars are slung high, it makes life a bit easier on my wrist, but with a span of only one octave (on pno), that's the only option available! Your span looks like a 10th+, and that's a good way for you, it appears in the pic. I guess when you need to fret the bottom string with a finger, your whole hand slides forwards and upwards, with a lot more wrist bend.  The elbow out idea just adds a little leverage for barre chords, using the barring finger - generally index - as a (cont.)
Comment: (cont.) fulcrum point. It also keeps the elbow from being stuck to one's body, restricting arm movement. I've seen it in too many students.  When seated, I tend to face 'north', while the guitar neck/head faces 'nnw' or at least 'nw', instead of the more usual 'west', which again changes angles somewhat.
Comment: No I can't really do a 10th on piano. A 9th I can play cleanly but not comfortably. But you're right that wearing a guitar higher makes a difference. Also my wrist angle is better for the flexor digitalis but a little harder on the extensor digitalis. Since the flexors do all the work in my playing style, it's best for me to favor them. A lower wrist position might be better for lower actions, light strings, light touch, and speed. I'm a heavy string compound bends kinda player so I need all the strength I can get.
Answer: Nobody else has mentioned it yet but there are a couple other factors you may want to consider in addition to wrist angle before deciding your fingers simply won't spread appropriately for the given chord you are trying to hit.

Muted Strings - I'm looking at your first picture and I think your hand placement is slightly wrong which could contribute to your inability to easily stretch your pointer and ring finger. You appear to be holding the F5 as if you your first 4 strings are going to be openly ringing. But take notice of the Xs in the chord diagram: 1-3-X-X-X-X. Those Xs actually mark the strings as muted, which means that you should be able to strum all 6 strings of your guitar and only hear the first fret of your low-E and the 3rd fret of your A string. All of the other strings will give you a low "whump" sound as you lay your pointer finger across them without actually holding them to the fret board. This "laying down of your pointer" finger will relax your hand somewhat and may allow you to more easily spread your fingers apart as necessary.
Guitar Neck Size - I can't tell exactly from the picture but the dark ebony could represent an Electric Gibson neck (which have necks that are thicker than some other brands like Fender). Keep in mind that not all guitars are created equal. Classical guitars have very thick necks which force a very specific hand technique which requires that the neck be tilted upward somewhat. Some electrics on the other have thinner or thicker necks depending on the style of the guitar. Depending on the size of your hand you may find certain guitars more comfortable than others and certain chords easier or harder. If you have a specific chord which is giving you trouble, you may try going to a guitar shop and experimenting with some other guitar styles to see if they all give you trouble or if it is just a specific characteristic of the guitar you are using.
Setup of the Guitar - Similar to the neck issue above, depending on how close your strings have been setup to your fretboard, you may be exerting more force than is ideal in order to press your strings down to play notes. When you play a guitar where the strings are too far away from the fretboard, the tendency will be to place your thumb more squarely on the back of the neck which could be somewhat uncomfortable on your hand. Stretching your pointer and ring finger apart when you have unnecessary strain elsewhere could absolutely contribute to the difficulty you are describing.
Comment: @arminb If the strings are too high then it's actually a setup issue as opposed to design issue. Acoustics are a little more tricky to setup so you'll want to take it to a luthier or your local guitar shop and have them set it up. Basically they'll check the truss rod in the neck to determine if you have inappropriate warping and then if necessary they'll file down the nut on the bridge so the strings lay flatter against the fret board. All guitars need to be reset over time so I'd budget having your guitar set up professionally every couple of years at minimum.
Comment: armin - you don't necessarily want your strings too close to the fretboard. I have different setups on different guitars specifically to have different tonal qualities and playing styles.
Comment: Thanks for comment! Really appreciate it. This is my first guitar. It is an acoustic Squier by Fender. Indeed the strings are kind of far away from the fretboard. But what are the benefits of building guitars this way? If it is easier to press strings with low gap between fretboard and strings, why not build all guitars this way? Or is this simply a quality criteria (The better the guitar the lower the gap)?
Answer: The more you play the more comfortable you'll get.  Your style will adapt to your strengths.  Django had his left hand maimed in an accident and played beautifully.

Answer: I have another suggestion, basically to help you develop your ability to stretch.
Whatever hand position you settle on, try playing this chord form higher up the neck.  So try playing a C power chord at the eighth fret (for example) instead of an F at the first fret. You might find it a bit easier up there mainly because the frets are closer together. If playing a chord formation higher up (closer to the bridge) is easier, you can start working your way down (toward the nut) gradually to the F chord and this will slowly increase your ability to stretch in the lower frets.
I don't use these formations so often but, for what its worth, my hand position looks close to Dr. Mayhem's above.  I find the F position is probably the most difficult on my guitar - it's easier to play the formation higher up.
Answer: Everyone has different geometry and so not everyone suits the recommended positions. I have large hands but short fingers and so I stretch my fingers out on both hands every day, several time a day, to make the most of what I have, and to keep flexibility. It does make a difference. Also placing your fingers on a table (hover your palm) and practising moving each finger (especially ring fingers), very slowly and deliberately, up and down off the table without moving the others, will make chords and switching chords easier. I stress, slowly and very deliberately, with control.
It will become easier in time, honestly. Playing things higher up the neck (as suggested above) does work but make sure you keep pushing gently to move back down the neck to lower frets or you will get stuck there at the dusty end
Answer: I have played for over 50 years and have been constantly plagued by the size and shape of my hand.  The first issue I confronted was the difference between playing seated (especially if you hold the guitar up high and close to you) and playing standing. Playing seated one tends to hold the guitar higher and closer to your body this actually facilitates the positioning of your fingers however, it is totally different from playing standing, which necessitates a different positioning of the hand.  Next I encountered the difference that scale length makes.  With Fender having a longer scale length I have found that Gibson's shorter scale makes it easier to reach more frets.  If you really want to experience nirvana try a Gibson Byrdland which has an even smaller scale length. All guitars have different neck widths and depths these have a dramatic impact on your playing ability.  A fat neck such as 50's era Gibson's is almost unplayable for folks with small hands.  Next up is hand and finger stretching. I highly recommend two dvd's from Lick Library "Guitar Aerobics Beginner" and "Guitar Aerobics Advanced"  they introduced me to warm up and practice exercises that forced me to stretch my fingers beyond anything I was previously used to and introduced me to correct hand positioning. To sum up finger stretching and correct hand placement selecting the best neck size for you will do wonders.
Answer: Bring the neck in closer to you and hunch/lean forward over the neck and guitar.  I have the same problem as you have.  I play the Greek Bouzouki now by trying different positions that suited me.  The Greek Bouzouki has a big sound bowl which makes it harder to hold and balance.  I was determined to play and now I can.  You have to be determined  although the bouzouki has a narrower fret board and its a tetrchord 4 course not a trixachordo 3 course(narrower fret board).  I can play the guitar well  to make my own recorded backing.  Have fun.
Answer: just practise chromatic scale starting with lower 6th string to 1st string (4 note per string) . And then go back from 1st string to 6th string. This exercise helps me the most.


dplyr lookup from same table

Question: I have data of how team members rated one another, from multiple teams. Each person has their own id number but also a team and rater number within the team like so:
  StudyID TeamID CATMERater Rated   Rating
    (int)  (int)      (int) (dbl)    (dbl)
1    2930    551          1     1 5.000000 #How rater 1 rated 1 (themselves)
2    2938    551          2     1 3.800000 #How rater 2 rated 1
3    2939    551          3     1 5.000000 #How rater 3 rated 1
4    2930    551          1     2 3.666667 #How rater 1 rated 2
5    2938    551          2     2 4.000000 #...
6    2939    551          3     2 3.866667
...

and so on. I got this format using tidyr and am trying to get a new column of the StudyID where the TeamID and person being rated are the same. This is what I've tried, but doesn't work because I'm not sure how to reference the same table:
edges %>% mutate(RatedStudyID = filter(edges, TeamID == TeamID & Rated == CATMERater))

Hopefully this makes sense, but I'd appreciate a recommendation to get headed in the right direction. If it is something with left_join how do I say where TeamID == TeamID?
Here's what I'd like to see in the end (mostly the last column though):
  StudyID TeamID CATMERater Rated   Rating   RatedStudyID
    (int)  (int)      (int) (dbl)    (dbl)
1    2930    551          1     1 5.000000   2930
2    2938    551          2     1 3.800000   2930
3    2939    551          3     1 5.000000   2930
4    2930    551          1     2 3.666667   2938
5    2938    551          2     2 4.000000   2938
6    2939    551          3     2 3.866667   2938
...

dput results per @akron that gives an error:
structure(list(StudyID = c(2930L, 2938L, 2939L, 2930L, 2938L,
2939L, 2930L, 2938L, 2939L, 2930L, 2938L, 2939L, 2930L, 2938L,
2939L, 2930L, 2938L, 2939L, 2920L, 2941L, 2989L, 2920L, 2941L,
2989L, 2920L, 2941L, 2989L, 2920L, 2941L, 2989L, 2920L, 2941L,
2989L, 2920L, 2941L, 2989L, 2922L, 2924L, 2943L, 2922L, 2924L,
2943L, 2922L, 2924L, 2943L, 2922L, 2924L, 2943L, 2922L, 2924L
), TeamID = c(551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L,
551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 552L,
552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L,
552L, 552L, 552L, 552L, 552L, 552L, 553L, 553L, 553L, 553L, 553L,
553L, 553L, 553L, 553L, 553L, 553L, 553L, 553L, 553L), CATMERater = c(1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L,
2L, 1L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L), Rated = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6,
6, 6, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 1,
1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5), Rating = c(5, 3.8, 5,
3.66666666666667, 4, 3.86666666666667, 4.53333333333333, 4, 4.8,
NaN, NaN, NaN, NaN, NaN, NaN, NA, NA, NA, 3.93333333333333, 5,
5, 5, 5, 5, 5, 5, 5, NaN, NaN, NaN, NaN, NaN, NaN, NA, NA, NA,
4, 4, 4, 4, 4, 4, 4, 3.86666666666667, 4, NaN, NaN, NaN, NaN,
NaN)), .Names = c("StudyID", "TeamID", "CATMERater", "Rated",
"Rating"), class = c("tbl_df", "data.frame"), row.names = c(NA,
-50L))

Comment: Check out [how to create a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for better ways to share sample data to make it easier to help you.
Comment: `edges %>% group_by(Rated, TeamID) %>% mutate(new = StudyID[CATMERater == Rated]) ` ?
Comment: Can you dput the dataframe?
Comment: @jeremycg I tried this but it gave an error `Error: incompatible size (0), expecting 3 (the group size) or 1`
Comment: Is it possible that you have more than one rows that have the same value for each Rated and TeamID
Comment: It looks like you have some where they did not rate themselves - what do you want in that case?
Comment: @akrun Each team member rated each other so there are 4 or 5 Rated per TeamID and Rater.
Comment: @jeremycg I am going to be dropping those for this case because I'm putting this into a graph visualization.
Comment: Please update your post with a small data that gives the error message.  The above dataset is not showing any error for me.
Comment: Can you also show the expected output based on the new dataset
Comment: @akrun and @jeremycg with my data I noticed that NA and NaN values might be throwing this off so I used `edges %>% group_by(Rated, TeamID) %>% filter(!is.na(Rating)) %>% mutate(new = StudyID[CATMERater == Rated])` with the added `filter()` and it worked. I'm double checking the results now but it looks good!
Comment: Yes, I would use `x %>% group_by(Rated, TeamID) %>% filter(any(CATMERater == Rated)) %>% mutate(new = StudyID[CATMERater == Rated]) `, but same idea
Comment: @jeremycg Thanks for the answer. I'll accept it if you add it below. I'm trying to understand the StudyID[...] part. It is looking within the group to find the ID where the rater is the same as the one being rated, right?
Answer: From the comments:
library(dplyr)
x %>%
   group_by(Rated, TeamID) %>% #group by each team/rated individual
   filter(any(CATMERater == Rated)) %>% #filter out any groups with unrated individuals
   mutate(new = StudyID[CATMERater == Rated]) #make the new column

The new column is created by subsetting each group - it is the same as x$StudyID[x$CATMERater == x$Rated] would be on the whole dataframe. As long as we have one place where this is true (ie self rating) the value is set to every member of that group.
Answer: With data.table
library(data.table)
setDT(edges)[ , RatedStudyID := StudyID[CATMERater == Rated] , .(Rated, TeamID)]
edges
#   StudyID TeamID CATMERater Rated   Rating RatedStudyID
#1:    2930    551          1     1 5.000000         2930
#2:    2938    551          2     1 3.800000         2930
#3:    2939    551          3     1 5.000000         2930
#4:    2930    551          1     2 3.666667         2938
#5:    2938    551          2     2 4.000000         2938
#6:    2939    551          3     2 3.866667         2938

In the new dataset, there are groups that don't have any similar values for CATMERater and Rated in the same row.  So, we can use an exception to return NA for those.
setDT(df1)[, RatedStudyID :=if(!any(CATMERater==Rated)) NA_integer_
             else StudyID[CATMERater ==Rated], .(Rated, TeamID)]

Answer: I think you can solve this with a join
edges %>%
  select(TeamID, Rated = CATMERater, RaterStudyID = StudyID) %>%
  inner_join(edges, by = c("TeamID", "Rated"))

dplyr lookup from same table


Incrementar uma string numérica em 1

Question: Estou querendo somar 1 a um contador que está representado como uma string. o objetivo é obter a sequência de números posterior. Por exemplo: de 000570370 para 000570371.
parte do código:
 def rangeOrdemServ(self):
        db = self.conexaoBanco()
        cursor = db.cursor()
        cursor.execute("SELECT ordem_serv_num FROM ordem_serv ORDER BY id DESC LIMIT 1")
        dadosOrdemServ = cursor.fetchone()
        db.commit()
        global rec
        dados1 = [dadosOrdemServ]
        dados2 = [1]
        dados3 = (dados1) + (dados2)

        self.entrOrdServ.insert(END,dados3)

quando eu executo esse código obtenho a seguinte resposta:
[('000005703701021',), 1], e não a esperada 000005703701022
Comment: Por que os colchetes?
Comment: sem os coLchetes da o seguinte erro:     'dados3 = dados1 + dados2
TypeError: can only concatenate tuple (not "int") to tuple'
Comment: `dadosOrdemServ` é uma String. Você quer tratá-la como um número para somar 1? É isso? Porque, se for, isso não tem nada a ver com concatenação.
Comment: sim é isso, trabalho a pouco tempo com python, nao tenho muita experiencia, pode me ajudar com essa questao?
Answer: Use essa função:
def incrementarStringNumericaEmUm(stringNumerica):

    qtdDigitosComZeros = len(stringNumerica)
    originalComoNumero = int(stringNumerica)
    qtdDigitosSemZeros = len(str(originalComoNumero))
    resultadoComoNumero = originalComoNumero + 1

    qtdZerosNaOriginal = qtdDigitosComZeros - qtdDigitosSemZeros

    if len(str(resultadoComoNumero)) == qtdDigitosSemZeros:
        # Não houve "vai um"
        return ('0' * qtdZerosNaOriginal) + str(resultadoComoNumero)
    else:
        # Aumentou um dígito no resultado, então precisamos colocar um zero a menos
        return ('0' * (qtdZerosNaOriginal - 1)) + str(resultadoComoNumero)

Ela recebe uma string numérica no formato que você tem em dadosOrdemServ e retorna uma string numérica com o valor incrementado em um. Pra isso ela conta quantos zeros tem na original, depois converte a original para um número inteiro, incrementa esse número em um, transforma esse número em string e concatena de volta os zeros, tomando o cuidado de colocar um zero a menos em caso de "vai um".
Comment: deu esse erro:  originalComoNumero = int(dados)
TypeError: int() argument must be a string or a number, not 'tuple'
Comment: Não é pra passar `dados`, mas sim `dadosOrdemServ`.
Comment: deu o mesmo erro
Comment: Dê um print em dadosOrdemServ e me diga o que sai.
Comment: Pelo que estou vendo, dadosOrdemServ é uma tupla. passe `dadosOrdemServ[0]` para a função, então.
Comment: quando dou um print sai: ('000005703701021',)
Comment: Passe `dadosOrdemServ[0]` para a função, então.
Comment: não deu nenhum erro agora mas não deu nenhum print tambem, onde eu recupero a resposta
Comment: A resposta é o retorno da função. Tipo: `numeroIncrementado = incrementarStringNumericaEmUm(dadosOrdemServ[0])`
Comment: no meu caso a resposta eu preciso que seja inserido dentro de uma entry, ex: self.entrOrdServ.insert(END,resposta)
Comment: Use o valor retornado pela função para fazer a inserção. Se está tendo problemas ao inserir algo no banco, isso seria assunto pra outra pergunta.
Comment: deu certo eu usei o resultadoComoNumero para inserir a reposta e ele da a sequência certinha, obrg pela força
Comment: Tranquilo. Bom trabalho.

Incrementar uma string numérica em 1


Get image width/height units in JavaScript

Question: I am creating an image object in JavaScript as
myImg = document.createElement('');

The image HTML will be obtained from database as in the given form.
Now, how can I get the height and width with the units (i.e. 50% for width in this case)?
Comment: This will only work in IE8 and below. IE9 and other browsers don't support providing attributes in `document.createElement()`. You can only pass the element name.
Comment: If you were able to you would create the element using the tag name and then setting attributes via properties. You can create elements from JS libraries including jQuery or Prototype, check out [How do I create a new DOM element from an HTML string using built-in DOM methods or prototype](http://stackoverflow.com/questions/494143/how-do-i-create-a-new-dom-element-from-an-html-string-using-built-in-dom-methods)
Comment: then what would be the better way to create an image element, with the above HTML?
Comment: so, I'll be creating an `IMG` element and then parsing the HTML string to populate the respective `IMG` attributes, is there any better way?
Comment: The link shows another way, essentially creating a `div`, setting it's `innerHTML` and then using `childNodes` which will be the HTML content of the string.
Answer: var width = myImg.width,   // width = '50%'
    height = myImg.height; // height = '80%'

// or
width = myImg.getAttribute('width'),
height = myImg.getAttribute('height');

Comment: for any image object you can find it using above method.
Comment: i tried both even before posting the question, the only way to get the value is `myImg.attributes['width'].ie8_value` but this will make it IE8 specific, Can I have some way to do it for atleast some popular IEs (7,8 & 9)?
Comment: @kashif: `getAttribute('width')` correctly returns `'50%'` in IE9 and Chrome 10. I'm not set up to test any other versions of IE, sorry. http://jsfiddle.net/mattball/xHDL7/
Answer: As documented every DOMElement has a ClientHeight and ClientWidth property, those will have the values you need.
https://developer.mozilla.org/en/DOM/element
Comment: `clientHeight` and `clientWidth` return pixel values, which is not what the OP wants.


Ordered field in convex subset definition

Question: In the  following wikipedia article
we read that :

Let $S$ be a vector space or an affine space over the real numbers, or, more generally, over some ordered field. This includes Euclidean spaces, which are affine spaces. A subset $C$ of $S$ is convex if, for all $x$ and $y$ in $C$, the line segment connecting $x$ and $y$ is included in $C$.

My question is why we need the field to be ordered in this definition? and does this mean that there is no  notion of convex subsets in complex vector spaces?
Comment: The order is used to define "line segment". The notion of convexity in complex vector spaces is the notion inherited from the underlying $\mathbb{R}$-vector space structure.
Comment: When we're writing "$0 \leq t \leq 1$", then we use the order of the field.
Comment: In a sense, they necessarily are. Every ordered field has characteristic $0$, thus contains (an isomorphic copy of) $\mathbb{Q}$ as its prime field, and hence in every ordered field, $0$ and $1$ are (modulo canonical identification) the rational numbers $0$ and $1$. The difference between various ordered fields is "what lies between $0$ and $1$?". There are a lot of options for that.
Comment: If $x$ and $y$ are in $C$ then the line segment between $x$ and $y$ is the set of $(1-t)x+ty$  for each $0\le t \le 1$, so where do we use order on the field here?
Comment: @DanielFischer is right -- most of the time folks are talking about an ordered field, and this is required for most of the results I've seen in convex analysis. However, if I recall, I think one generalization for complex Hilbert spaces is to replace $0\leq t\leq 1$ with $0\leq |c|\leq 1$ where $c\in\mathbb{C}$ and $|\cdot|$ is the complex modulus. However, I'm not sure which results still hold with this generalized definition.
Comment: @DanielFischer I think i see my confusion:  $0\le t \le 1$ is an abuse of notation of $0_F\le t\le 1_F$ where $0_F$ is the zero element of the field $F$ and  $1_F$ is the multiplication identity of $F$, and so $0$ and $1$ in this abuse of notation are not necessarily the usual real numbers.
Answer: The line segment connecting $x$ to $y$ is the set$$\{(1-\lambda)x+\lambda y\mid0\leqslant\lambda\leqslant1\}.$$As you can see from this definition, you are supposed to have an order relation on your field of scalars.
If $V$ is a complex vector space and $C\subset V$, we say that $C$ is convex if it is convex when we see $V$ as a real vector space.


updating while loop to mysqli

Question: hello everyone i have the following issue to solve. i have an autosuggest search field. i would like to update my code from using mysql to mysqli. thats why i have this code ($db=mysqli):
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {

    $search_term = $db->real_escape_string(htmlentities(trim($_POST['search_term'])));

    $search_term_query = "SELECT `a` FROM `b` LIKE '$search_term%'";
    $result_search_query = $db->query($search_term_query);

    while (($row = $result_search_query->fetch_assoc()) !== false) {

        echo '
', $row['a'], '
';
    }

}

for some reason i get:

Call to a member function fetch_assoc() on a non-object

so where is the problem with the object? if there is someone who could help me out i really would appreciate. thanks a lot.
Comment: Please include how $db is defined
Comment: $db = mysqli that comes from an other file.
Answer: This means that $result_search_query is not the object you are expecting. Possible reasons:

connection failed to the database
query execution failed

Please take a look at the examples in http://php.net/manual/en/mysqli-result.fetch-assoc.php and http://www.php.net/manual/en/mysqli.query.php. It should show you how you can catch errors.

updating while loop to mysqli


Can I send an image with Apple's Push Notification Service?

Question: I need to show an image whenever my application receive Notification.
Does Apple push notification support image sending?
Update
If above thing is not possible can we show image from url on UIAlertview when we receive notification.
Comment: You can send URL of your image within notification
Comment: Brief about your plan of showing an image on alertview - I'll be more than interested to know its possibility.
Comment: So can we show image from URL on alertview?
Comment: Of course we can show image on alert, you can find that on below link
http://stackoverflow.com/questions/2323557/image-in-uialertview
Comment: Yep. Thanks - But to answer your question, No - Push notification cannot send images with its allowable payload limit.
Comment: Yes but when we can show alertview in didReceiveRemoteNotification method we can show image from url, and url can we sent from server
Comment: Yes. Definitely possible:)
Answer: Update! iOS 10 introduced the ability to add media attachments to push notifications. So now we have the ability to include an image in a push notification. [Source: Andrew from comments, and other tutorials that show how to do this, such as this one.]

No. The notification payload can be up to 256 bytes long. You can send an image only if the encoded image size plus the rest of the payload is no more bigger than that... useless.
You can, however, use launch-image property from alert apn dictionary to specify an image from app bundle that will be used at app launch.
Or you can send a URL from which the image can be downloaded within the app.
Please take a look at Apple Docs
Comment: **Update!** iOS 10 introduced the ability to add media attachments to push notifications. So now we have the ability to include an image in a push notification.
Comment: Nop, the notification icon will be always the app icon. You can't do anything with the notification, it's only sent to device, device takes care of showing the alert. You can only use the notification when the user opens the app, read the data and act according.
Comment: So can we show image from URL on alertview?
Answer: As far as Push Notifications go, when the user actions the notification or the notification is received while the app is in the foreground, the app will only get the push message payload. The only intent is to let the user know that there is new content.
Hence, you should not be using Push Notifications to deliver content to your app. Your app should be responsible for pulling any new content from your backend server as soon as it is in a position to do so.
UPDATE: However, if you mean "emoji" this might help you.
Comment: From iOS 9 payload size becomes 2KB.


want to animate svg image in python

Question: i have two svg file ,my_avatar.svg and my_avatar1.svg in which one image has an avatar with eye open and one with eye closed I want to animate these two svg file such that animmation will show eyes open and eyes closed
If any one could help me please
i have tried svgwrite but did not get the desired output
Comment: Best to show your attempt by editing the question to include it. Personally I'd animate a single image using SMIL.
Comment: Welcome to StackOverflow, hope you will find new knowledge here. You can help us answering your question, by adding a [minimal-reproducible-example StackOverflow Snippet](https://stackoverflow.com/help/minimal-reproducible-example). It will help readers execute your code with one click. And help create answers with one click. Thank you.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: What is the connection between Python an the SVGs? Is the animation going to be displayed in a Python application, would you like to generate a GIF based or the SVG using Python or is it a web application that uses Python? Is the SVG going to be displayed in a browser or somewhere else?
Answer: A few months back I had also created an animation from some images. I think they were jpegs but now I tested my python code for creating animations from svg images too and it worked. Here's the code:
<code>import cloudinary
from cloudinary import uploader

cloudinary.config(
    cloud_name='your_cloud_name',
    api_key='your_api_key',
    api_secret='your_api_secret'
)

def upload_images_and_create_gif():
    try:
        image_public_ids = ['my_avatar', 'my_avatar1']
        tag = 'avatar_gif'

        uploaded_images = []
        for public_id in image_public_ids:
            upload_result = uploader.upload(f"{public_id}.svg",
                                            public_id=public_id,
                                            tags=[tag])
            uploaded_images.append(upload_result)

        create_gif_result = uploader.multi(tag, resource_type='image')

        gif_url = cloudinary.utils.cloudinary_url(f"{tag}.gif", type="multi")[0]
        print('Animated GIF URL:', gif_url)

    except Exception as error:
        print('Error:', error)

upload_images_and_create_gif()
</code>
You can just sign up to cloudinary and add your credentials in the code above. Then add the local paths of your svg images. Make sure that your image is in the same directory as the script otherwise use the correct relative path.

want to animate svg image in python


I have a program, worked on win95 and i did not compile on winXP

Question: i have a program and work on win95 old machine. I want to work on win xp and want to be executed this program on xp. Application use some hardware (two card which is plugged in isa slot). I have application soruce code but, codes not support on xp. For example, graphics.h, eg_proto.h,color.h, wg_var.h header files don't have anywhere on modern compiler. I have turbo c 1.0 compiler but not support me for this situation.
So, what can i do about this situation? Would you suggest anythings about?
Some header files from source code:
<code>#include <ctype.h>
#include <color.h>
#include <stdlib.h>
#include <errno.h>
#include <alloc.h>
#include <time.h>
#include <dir.h>
#include <process.h>
#include <eg_proto.h>
#include <pchrt.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <math.h>
#include <string.h>
#include <dw.h>
#include <dwdata.h>
#include <wdh.h>
</code>
I dont know anything about some header file. for example, dw.h, dwdata.h, wdh.h. I didnt found any description about this header file.
Edit:
My compiler is Turbo C 2.01
https://i.stack.imgur.com/LQFnI.jpg
Comment: @aix: http://en.wikipedia.org/wiki/Borland_Turbo_C I'm quite amazed that he's got a tool from 1987..
Comment: You require professional help to do the code conversion... It is not easy to figure out what your system does from just looking at the headers.
Comment: @aix no it's old MFC foundation class stuff...
Comment: @AhmedMasud: The author said that he's got a Turbo C 1.0 compiler..
Comment: i am sorry. i have 2.0 version. i am editing it from question.
Comment: You may be in trouble. This program's intended to talk to ISA hardware, right? Unfortunately, unlike Windows 95, Windows XP is an NT based operating system and isn't based on DOS, and while it's got pretty good DOS emulation, it's not complete. One of the things it won't let you do is talk directly to hardware. It _might_ be possible to persuade it to lift the security restrictions for certain processes, but I don't know about that. You may need to write an NT kernel driver for the hardware, and that's really not nice. You'll have to find someone how knows, I'm afraid.
Comment: it is impossible with me. Maybe, i have to find someone as you said. Lastly, I will try to create virtual (win95 or win98) machine and compile or run on the virtual machine and share some file with winXP to report their datas. Maybe, i can be successful. Thank you.
Answer: If you're using the same compiler on both systems, it is almost certain that the missing headers are not part of the compiler package. They are certainly not part of the OS since your compiler predates both operating systems.
I see two main possibilities:

These headers are part of your project and are not being found due an error in the build process.
These headers are part of some third-party libraries that you have installed in one environment and not the other.

Either way, you need to find them and either fix your build settings, or copy the headers across from the old system to the new one.
Comment: i dont compile the system on win95. Executable application is running on win95. I did not try to compile on win95. I tried to compile on winxp.


Tamanho máximo de QRcode

Question: Estou implementando em um projeto um leitor e gerador de QRcodes e me veio a dúvida, até quanto tempo um QRcode pode armazenar?
Eu conseguiria algo em torno de 3 páginas de texto?
Answer: Não entendi muito bem, você quer saber a quantidade de armazenamento que um QRCODE pode conter? se sim

Numérica - máx. 7089 caracteres
Alfanumérica - máx. 4296 caracteres
Binário (8 bits) - máx. 2953 bytes
Kanji/Kana - máx. 1817 caracteres

Tamanho máximo de QRcode


Compatibility of ESX 4 and LTO 3 with LSI2032 Dell Power Edge

Question: does anybody know something about the compatibility of an LTO 3 Tapedrive (PV HH LTO 3 400GB) attached to an LSI2032 SCSI-Controller? These devices are added to an Dell PowerEdge T610 Server which is listed in the certified Compatibility Guide.
I can`t find any information for this controller and this tapdevice. Or are they automaticly compatible because they are options for an compatible Server?
greetings Dennis
Comment: Can you tell us how you intend to use this tape drive, are you going to pass it through to a VM or do you want it working from the COS/SC?
Comment: ah ok, missed your comment sorry, in that case you simply need to enable VT-d functionality in your BIOS if your CPU has it and then follow the following guide to hardware passthrough setup; http://software.intel.com/en-us/blogs/2009/02/24/step-by-step-guide-on-how-to-enable-vt-d-and-perform-direct-device-assignment/
Answer: When you purchase a TBU set with an HBA with a Dell server, you should get a compatible HBA.
LSI is pretty much the standard SCSI HBA Dell ships, so as long as the TBU is ok, you should be fine.
If still in doubt, try to call the suport line and ask them


Generate page for each json entry

Question: I'm new to Drupal.
I want to customize the search module in order to show results from an external JSON.
I was able to insert JSON data in the search page, but now I want to generate a page for each result. Something like blog posts.
I'm using the latest Drupal 6 Version.
Please give me some ideas how can I generate the pages for each Drupal result.
Anticipated thanks!
Answer: I've used Feeds JSONPath Parser module to parse a JSON feed and insert the objects as a specific content type (e.g. blog posts).
It works well but I'm unsure about your search results, you might just have to set the template to link to each of the content nodes by getting the node based on a specific field that you know will be unique for all of your nodes? e.g. title?
If you don't want to actually store the parsed data as content, and just want to display them as a page, then you'll need to use the hook_menu() function. I've linked to API 6 as you noted you were using D6.
Comment: The idea is that I don't want to save the data as blog posts, I just want to read It and to show it first on the search page, and then as individual pages.
Comment: is there a function in drupal that generates static pages? or something like that
Comment: Well `hook_menu()` is basically for 'pages' (or least URLs) -> so you could use that. Check the Examples module and have a look through the Page Examples sub-module inside that module.

Generate page for each json entry


Scale selection for the Hyperparameters

Question: During the scale selection for hyperparameters
I have a question generally if we have to select a random number in the interval $[2,5]$
It is fairly straight forward that we select either $2,3,4,5$ just by using the linear scale
But my friend pointed out if I have to select a random number in the interval $[0.0001,1]$ he said using the linear scale has a problem that
$90\%$ of the time I will be selecting between $[0.1,1]$ interval and $10\%$ I will be selecting from the interval $[0.0001,0.1]$
I was unable to understand how this is the case?
He suggested me to use logarithmic scale for selecting the number if it is in the interval $[0.0001,1]$, Because both 0.0001 and 1 are at different orders of magnitude
If I understand the order of magnitude properly in the interval $[2,5]$ the order of magnitude is $10^0$
But not in the case of interval $[0.0001,1]$ because one is $1*10^{-4}$ and the other is $1*10^0$
Can you please explain how will the logarithmic scale will be helpful? when the orders of magnitude are different why they cant be accomplished using the linear scale?
Thanks in advance
Answer: If you use linear scale (say 5 values) for the range $[0.0001, 1]$, the hyperparameter set you'll be trying will look like approximately as follows: $$\mathcal H=[0.0001, 1/4, 2/4, 3/4, 1]$$
In this selection, the values you try is within the range $[0.1,1]$ $80\%$ of the time (i.e. 4 out of 5). If you increase the number of in-between steps/values linearly, this probability will get closer to $90\%$. If you were using the logarithmic scale, then the values would look like as follows:
$$\mathcal H=[0.0001, 0.001, 0.01, 0.1, 1]$$
Which one to use depends on the application and the set of the hyper-parameters you want to explore.  For example, if you're trying various learning rates in neural nets, logarithmic steps are the typical choice and more useful.
As a rule of thumb, you use logarithmic scales to observe the effect of multiplicative changes in your HP, and you use linear scales to observe additive effects in your HP.
Comment: Understood so any interval we take for example $[0.0001,100]$ here I can take the interval $[1,100]$ covers the most of the part that is mostly $99.999999\%$ and the other interval i.e. $[0.0001,1]$ is around $0.000001\%$? is my understanding right? If so generally when you consider taking a random number in this interval $[0.00001,1]$ is always much biased towards the interval $[0.1,1]$?  is that true? the probability of selecting the random number in the interval $[0.0001,0.1]$ is very less?
Comment: Thanks for the reply, If you take more than five values then the probability changes right? for the linear scale or is there something I am missing? Kindly reply
Comment: Yes, it changes and converges to 90% approx.
Comment: No I meant the values between 0.0001 and 0.1 will increase no?
Comment: That results in less probability right?
Comment: If you take linearly scaled uniform samples between $0.0001$ and $1$, you'll also have values between $0.0001$ and $0.1$ in addition to values between $0.1$ and $1$. Forget about $0.0001$ (since it's close to zero and explaining with it is not the simplest thing to do) and think about the interval (line segment) $[0,1]$ on the real axis. And, think about marking the line segment at regular intervals, and assume you have lots of marks. The segment $[0,0.1]$ will approximately cover 1/10 of the marks (since it's 1/10 of the whole line segment) and the remaining part will cover 9/10 of the marks.
Comment: Yes, if your random selection is uniform.
Comment: Thank you for the clear explanation of the concept, Can you please point me a link or something how uniform random selection is done?
Comment: Recall that in your original question, it's just selection of numbers uniformly in an interval. It's not random selection. But, uniformly and randomly selecting numbers from an interval  can be achieved by rand() function in Matlab, np.random.random() function in Python etc.

Scale selection for the Hyperparameters


Remover UI Debugging Tools da Janela

Question: Gostaria de saber como remover a opção UI Debugging Tools for XAML que aparece no topo da janela WPF (conforme imagem abaixo)
Answer: Desmarque a opção:
Tools ⇢ Options ⇢ Debugging ⇢ General ⇢ Enable UI Debugging Tools for XAML.

Fonte

Remover UI Debugging Tools da Janela


php or perl javascript compression for jQuery

Question: Anyone know a PHP scripts that done a good compression for jQuery?
Comment: Are you looking to compress the jQuery source (which is already compressed) or to compress the scripts that you have written?
Comment: Compressing JavaScript on the fly is very expensive. You should do this statically during your build or deployment.
Comment: @Dancrumb: Yes, its to compress my JQuery Script.
@Matthew: minify could cache. It works and make my JQuery less expensive.
Answer: Google Closure Compiler Service for all your javascript minifying needs!
Comment: You can use this from php by calling the command line program.
Answer: JSMin is a PHP class which we've found to work well to minify our JS. Minify is another PHP project which has been built on JSMin and looks pretty interesting (combines multiple files, handles local caching, etc) but I haven't had a chance to test it out yet so can't vouch for how well it works.
Depending on how complex you want your codebase to be, you've a couple of different options as to when or how you use a minifier:

minify the JS off-line, and check in both the minified and non-minified versions to your codebase. This will result in extra files floating around your codebase, and at some point someone will edit the un-minified version, forget to re-minimise it, and wonder why their change hasn't taken effect!
minify the JS off-line, and store only the minified JS in your codebase. This is not a good idea, as it makes maintenance substantially more difficult in future.
another option is to minimise on-the-fly, as the files are requested.

Minimising on the fly can be an attractive option, as it means that you can store your un-compressed JS file in your codebase for easy maintenance, yet get all of the benefits of having minimised JS served.
The problem with this approach is that it can be very computationally expensive to minimise your javascript on every single request.
To get around this, most JS minimisers offer the option of caching the resulting, compressed JS on the server. This means that the first user to request the JS will have trigger the minimising process, but subsequent users will get the compressed file from cache, without the additional overhead required to minimise the JS again.
There are a number of packages available - depending on your webserver of choice - which will take care of all of this for you (Apache example), or if you really want to, you can roll your own solution. Probably not the best idea, but no harm in trying it as a pet project!
At a pseudo-code level, it works basically as follows:
www.example.com/js/jsm.php?js=foo.js (this url can easily be made prettier using url rewrites)
<code>// jsm.php
// On-demand JS minification
// Store result to local cache to reduce overhead from
// multiple requests

// JSMin class
require( 'jsmin.php' );

// Has this file already been cached and put in cache?
// ($cache could be anything from local file cache, memcache, etc)
if( !$cache->checkFor($requestedFilename) )
{
    // No.. minimise and put in cache
    $minifiedContents = JSMin::minimiseFile(
                             file_get_content( $requestedFilename )
                                           );
    $cache->putValue($requestedFilename, $minifiedContents);
}

// Now serve minimised js from cache
echo $cache->getValue($requestedFilename);
</code>
Answer: If you're looking for a Javascript Minifier that works on PHP, check out this:
http://github.com/rgrove/jsmin-php/
Answer: Dean Edwards's JS Packer comes in PHP/Perl.
<code>http://dean.edwards.name/download/#packer
</code>
Answer: I run a website that lets people compress javascript code blocks online, and I would recommend against using the PHP translations of packer or JSMin. They are not very efficient, and the compressed code that comes out the other end often has errors or incorrectly translated or conflicting characters. It has been a source of many headaches.
Either use one of the primary Java JAR files to run all your code through (YUI Compressor, Dojo Shrinksafe, or Google Closure Compiler), or use the Google Closure web service.


Change ExpandableList view programmatically

Question: I have an ExpandaleList, and BaseExpandableListAdapter which I implements.
Now sometimes I need to show other xml content, So I am trying to do:
ExpandableList.this.setContentView(R.layout.errorscreen);

but then I get this exception:

ERROR/AndroidRuntime(23948): java.lang.RuntimeException, Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'.

Now, I have been told to do this in order to fix it:
add  ExpandableListView to your xml layout and set it's id to list. Like so:
  <ExpandableListView android:id="@id/android:list" android:layout_width="fill_parent"android:layout_height="fill_parent"/>

How to do it programmatically?
Answer: You are setting this Activity's contentView to a Layout which is defined in an xml file called errorscreen.xml:
ExpandableList.this.setContentView(R.layout.errorscreen);

The activity you're doing this from however extends ExpandableListActivity (I guess). Such an Activity needs an ExpandableListView in it's xml to display it's data. Now simply open your errorscreen.xml and add this element.
Cheers


How to NOT hardcoded project settings

Question: I'm making a simple android application and i want share the repo with other developers but i want write settings to external file and use into the android Code, this is possible with gradle?
example i want put in a file project_settings.gradle something like
APP_HOST=192.168.0.1

and in any place of my code i want use something like
String url = "http://" + BuildConfig.APP_HOST

that way i can share a project_settings.gradle.dist with the others developers
Comment: You may set this IP address as an environment variable. Or if specifically this is You own IP address You can get it via groovy script.
Comment: You can crib this for code: http://stackoverflow.com/questions/20203787/access-sdk-dir-value-in-build-gradle-after-project-evaluation/20272398#20272398
Comment: @ScottBarta I'm really new with gradle please provide me a example as an answer
Answer: You can try to set resValue in your build.gradle. This will create Android resources that will be available to access through your code.
https://plus.google.com/+XavierDucrohet/posts/UVKA58MZV3J
For example:
defaultConfig {
    minSdkVersion 9
    targetSdkVersion 21

    resValue "string", "country", "US"
    resValue "string", "oauth_token", "some_token"
}

In your code if you need to access country, call context.getString(R.string.country)

How to NOT hardcoded project settings


`drush cc all` command takes too long time, what can I do?

Question: On a site of mine drush cc all takes more than 4 mins to run. The site db is a few GBs. However, I cannot see a clear reason as to why it takes too long. What can I do to locate the bottle neck?
Comment: Check first mysql query log: http://drupal.stackexchange.com/questions/75629/what-module-will-show-me-all-sql-queries-being-run-on-the-loaded-page
Comment: Do you have cron running?
Comment: Yes I do have a cron running. The site is slow in general. So many legacy code that is not worth re factoring.
Comment: I agree with @MPD here, I don't think this is memory related. MySQL is also just one of the possible reasons. There's only one way to find out and that's to profile it. The easiest way to do that is using the xhprof extension and devel, that also works with drush (use -d to see the link to the report). My guess is that there are a number of issues, A typical problem if the site is slow for all requests is missing modules, see http://drupal.stackexchange.com/questions/724/why-is-drupal-7-so-slow. Views also has some major performance issues with caches, see https://drupal.org/node/1944674.
Comment: Thank you, I figured that I have to do profiling, but in the case of drupal code base, it's always hard to pinpoint the bottleneck. Although I said the site is slow, it is not too slow and drush cc all, is unproportionally slower.
Comment: If you are using Breakpoint be sure you have the v1.4. this version fix a bug with drush cc all.  https://www.drupal.org/node/2635698. This update fix the issue in our case.
Comment: drush cc all --d it will give you the debug information and can check which process is taking more time.
Answer: The clearing cache it-self doesn't take a long time, since it's just truncating cache tables. What takes time the most is rebuilding the cache registry after that. Usually it's theme registry which scanning for all new hooks and all your Drupal folders for new template files, system which scanning files for the new modules and class files, and similar.
You can always clear specific cache by specifying drush cc theme-registry or any other.
It's highly recommended that you use PHP caching mechanism (e.g. OPCache, XCache, etc.) to speed up the processing. And memory-base cache to replace heavy usage on SQL tables (e.g. memcached or redis), so clearing cache would take no time, just by flushing the cache (e.g. echo flush_all > /dev/tcp/127.0.0.1/11211 in Bash).
Alternatively you can always clear cache manually, e.g. by:
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

Debugging
To check what's taking the most time specifically, you need to debug/profile it (e.g. XDebug, XHProf, phpdbg, dtrace).
On OS X/Unix, this can be achieved by dtrace (after running drush):
sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

On Linux, use strace, e.g.
strace -e trace=sendto,recvfrom -s1000 -p $(pgrep php)

To look for some specific things, try adding e.g.: strace ... 2>&1 | grep -C5 UPDATE.
Answer: If you have a really large database, and your system is running fine when you are not doing a cache clear, it is likely that you do not have enough memory to fully support your setup.
If your site is running on a Linux box, run 'top' (from your shell) and press shift-M to sort the process list by memory used.  Then, run your cache-clear operation from another terminal.  You should see mysql and apache rise to the top of the list.  You'll be able to see what percentage of total memory each of these processes are using, and how much free RAM is used.  If you have a large amount of virtual space, but all of your physical RAM is exhausted, this operation could be causing VM memory to thrash, which can drive your execution time down to a small fraction of what it normally is.
Once, I was running a mid-traffic Drupal site on a box w/out -quite- enough memory to support the setup.  When I ran a cache-clear on an unrelated low-traffic site, the cache rebuild pushed the system past its limit, and everything all but locked up.  So, the total system behavior is important here; this is why simple tools like 'top' are a handy place to start.
Comment: Yes, if the whole site is slow all the time even with a lot of memory, then cc is not the problem; you'll have to do more general profiling.
Comment: Thanks, I think the underlying cause is that the site has been around for a while, the db is a bit large and the code terribly needs re factoring. For example, a node_delete operation takes about 3 seconds. I think giving too much memory may be redundant, do you agree?
Comment: I have it on my machine and it is also slow. I doubled the memory, up to 1GB and timed it ` time drush cc all`. Not much better only got 4s faster.
Comment: Also, if the site is really old and needs a refresh, consider rebuilding from scratch with fresh modules, and use drupal-to-drupal migration (https://drupal.org/project/migrate_d2d) to move your content over.
Answer: I am going to disagree (somewhat) with @greg_1_anderson here.
If the system isn't crashing totally during a cc all, then I don't think you have a general memory issue.  When a LAMP server runs out of memory, it will hit swap.  An active server hitting swap will cause an avalance of badness.  httpd processes will start to stack up due to system slowdown (swap makes a system run very slow), which will cause more swap to be used, etc.  On sites where I have seen this happen, I would see the process load hit 100, and a ton of active httpd processes.
If your system eventually comes back, then I think you are poorly tuned.  drush cc all will result in a lot of database accesses, so I think it is showing the problem more.  My suggestion would be to run mysqltuner on the site.  If you have a multi GB database, my guess is that your innodb_buffer_pool_size isn't even remotely sized properly, and your MySQL instance is thrashing.  I would also investigate an alternate cache backend to try to keep the database footprint smaller.
Comment: Thanks, drupal is used only for editoria use that has a servie layer which has varnish infornt of it. Users do now get to drupal. I just want to investigate whats happening because I think there is bottleneck. I think my best bet is to turn on the mysql slow log and monitor the db. And then do some profiling with xdebug
Comment: SHOW FULL PROCESSLIST will tell you what's happening without need to use slow query log (and so without server restart). See other answer for mytop as well.
Answer: It could be your web hosting environment. Are you referring to a local setup, or something hosting on shared hosting or a VPS/server?

hosting environment - if you are on shared web hosting, the amount of
memory Drupal/drush can use will be limited see:
https://drupal.org/node/207036
max execution time - needs to be increased
Comment: drush normally isn't limited by `max_execution_time`.  You can do `drush php-eval "print ini_get('max_execution_time');"` to double check, though.
Answer: This is not a complete solution, just one more tool to help identify the source of your delays.
As well as using top to monitor processes, you might find the output of mytop informative. (Other answers above presume MySQL but if you're using another DB backend, you'll need to swap mytop for an equivalent tool.)
mytop simply executes MySQL SHOW FULL PROCESSLIST in a loop, and shows you which queries are being executed (so which take a lot of time). If the cache clear is taking a long time cleaning up this or that table, you'll see exactly what's holding things up here. If you don't have access to install mytop, just do a crude version in your shell -
while true; do mysql -e 'SHOW FULL PROCESSLIST' && sleep 5 && clear ; done

If the delay is not stemming from MySQL queries, then this tool may at least confirm that for you.
Answer: I found a blog post entitled Speed Up Cache Clearing on Drupal 7 to be very helpful in narrowing down precisely what portion of the cache clear process was slowing things down. The issues it pinpoints in features module and the entity api module were affecting my site, but the process detailed in the post also helped me track down issues we were encountering in Drupal core and breakpoints module.
It takes some time to work through the process, but it has helped me to reduce cache clears down from multiple minutes to under a minute.


Best way to do geo redirection?

Question: I am working on a multilingual Drupal 7 site. I've been asked to set up an automatic redirect based on the user's location. I've tried the geo_redirect module but it does not work with internal URLs because it creates a redirect loop.
My site uses paths to switch languages. For example the German homepage is example.com/de.
It seems like there are various modules that say they can do this but some are just dev versions, some require a subscription to a geo-location service, and some like to populate the Drupal database with 200MB of geoIP data (huhhh???).
Here is an example of what I need...

User located in Germany goes to example.com
Website detects that they are located in Germany
User gets redirected to example.com/de (the German homepage)
If user in Germany goes to any URL with /de in it then no redirect occurs

Just wondering if anyone has any experience with this and how they went about doing it.
Thanks!
Comment: Can you write an example of what you want to do?
Comment: Just added an example.
Comment: @Dustin I updated my code, Use the new one
Answer: I would use Smart IP module.

Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored in session variable ($_SESSION) with array key 'smart_ip', Drupal $user->data object with array key 'geoip_location' in Drupal 6 and 7 and user data service using the parameters 'smart_ip' as module and 'geoip_location' as name in Drupal 8 of the user but optionally it can be disabled (by role) at Smart IP settings page. Other modules can use the function smart_ip_get_location($ip_address) in Drupal 6 and 7 and \Drupal\smart_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.

You can get the user location in different ways using this module.
<?php
$smart_ip_session = smart_ip_session_get('smart_ip');
if ($smart_ip_session['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Or
<?php
if ($_SESSION['smart_ip']['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Now, in the Theme_preprocess_html function of your theme in the template.php file, use the above codes to check if the user is in a right place. Create template.php file in your theme and use this function:
function themeName_preprocess_html(&$variables){
{
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = arg(1); //it returns the /de or any language
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

If the default provides the language code, it works well but if not, you need to handle that case. For example if the default language is English and the /en is not coming after example.com, then you need to check if arg(1) == 'en'. It is easy to do.

update
To get the user language use this code
global $language;
print $language->language;

So your code will be
function themeName_preprocess_html(&$variables){
{
      global $language;
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = $language->language;;
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

Best way to do geo redirection?


Passing Database Column Values to VB6 Function

Question: I need to pass 8 database column dates to my CalculateMostRecentDate function since vb6 doesnt have a max function.  Am i simply able to pass the database values like this? or how would I do it?
Public Function CalculateMostRecentDate(ParamArray dates() As Variant) As Variant
Dim i As Integer
Dim MostRecentDate As Variant

MostRecentDate = dates(LBound(dates))
For i = LBound(dates) + 1 To UBound(dates)
    If MostRecentDate < dates(i) Then MostRecentDate = dates(i)
Next i
CalculateMostRecentDate = MostRecentDate
End Function

Call function within another function:
RECENT_APPRV_DT = CalculateMostRecentDate(EMPLOYER.UW_APPRV_DT,  EMPLOYER.BE_APPRV_DT, . . .)

Comment: What data type are your "database values"? Is EMPLOYER a recordset object?
Comment: its the datetime data type. and EMPLOYER is the table
Answer: Looks about right.
Google turned up this which looks quite polished, also this from the old VB6 newsgroup.
Answer: The function looks OK but you cannot call it the way you have indicated.  You will need to load the dates into an array and then pass the array in.


Form with manged_file filed is not submitted?

Question: I have a form in my drupal module. in my form, I have used manged_file field.
form name is "difference_form" and I have created two functions.
one is "function diffence_form" for form definitions.
here is code:
function difference_form() {
  $validators = [];
  $form['new_image'] = [
    '#type' => 'managed_file',
    '#name' => 'new_personal_image',
    '#title' => 'New Image',
    '#description' => theme('file_upload_help', [
      'description' => 'Please insert your new image.',
      'upload_validators' => $validators,
    ]),
    '#upload_location' => $path,
    '#default_value' => variable_get('new_image', ''),
    '#upload_validators' => $validators,
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => 'submit',
  ];

  return $form;
}

function difference_form_submit($form, &$form_state) {
  drupal_set_message('test_form_submit called');
}

and also I have created a block for this form in hook_block_view.
function customize_block_view($delta = '') {

  $block = NULL;
  $block['content'] = drupal_get_form('difference_form');
  $block['subject'] = 'Difference Form';
  return $block;
}

Form is rendered correctly, but when I click on submit button, submit function is not called.
I tried to debug my codes. I found if I remove file_managed field from form definition, submit function works.
also if I found if I renamed all difference_form to another name for example "test_form"
drupal_get_form('test_form');
function test_form(){....}
and
function test_form_submit(......
submit function works.
it seems system is sensitive on "difference_form" only
I am thinking might the expression "difference_form" be blocked in database or somewhere else ?
Comment: Today, I made a test. I made a new Drupal 7 installation and installed my custom module. I faced submit handler works on new Drupal install with no problem. but exact codes in base project I see submit handler doesn't work. it seems file_managed causes form goes to black list and Drupal doesn't call submit handler.
Answer: I found the reason of this problem finally.
It was as a result of jQuery code mistakes.
in form submission, I tried to disable submit button immediately after clicking.
I had to change the coding because set button disable causes this problem.


Enviar formulário sem saber o nome

Question: Tenho um formulário que muda o seu nome constantemente , e quero  dar o submit nele por uma função. Nesta função "altera" ele recebe o nome do formulário, mas desta forma que fiz ele não funciona. O "+ide+" do formulário é um numero aleatório, por isso passo ele para a função "altera". Se alguém poder me ajudar e explicar como fazer funcionar o que quero fazer.
<form method='get' action='GG.php' name='alteracao"+ide+"'>
    <button onclick='altera(alteracao"+ide+")'>Enviar</button>
</form>

function altera(ide){
        document.ide.submit();
    }

Comment: Há um `'` faltando no onclick. Fora isso, não entendi o que você está tentando fazer. De onde é que vem o nome do formulário que sempre muda? Você está tentando descobrir qual é o nome ou tentando inventar um novo nome aleatório?
Comment: Esse  '  eu que esqueci quando fui escrever aqui. Esse "+ide+" ele muda sempre, por exemplo, ele pode ser "alteracao10" ou "alteracao55". Mas minha duvida fica sendo na própria função, ele funciona colocando document."ide".submit(); sendo que esse "ide" é o parâmetro que mimha função recebe?
Comment: Mas com vc faz a interação neste **"+ide+"**, já vem de algum lugar?
Comment: Como você esta gerando os formularios ?
Comment: Esse "+ide+" é gerado pelo banco de dados com um AutoIncrement, @LeAndrade
Comment: O `+ide+` é substituído por um número apenas na tag `form` ou também é na tag `button`?
Comment: Os formulário são gerado por um createElement + innerHTML. Que o createElement cria o lugar onde o formulário ira aparecer e o innerHTML coloca o formulário ja pre-criado no javacript. @MarcosJunior
Comment: @VictorStafusa na tag button o +ide" só é usado para enviar o parâmetro na função, assim enviando o nome exato do Form.
Comment: No caso aí não seria só pegar o valor do name? Pq o name já não vai vai com o valor do banco?
Answer: Ao invés de gerar um name aleatório para o formulário, gere um id aleatório:

function altera(ide) {
    var form = document.getElementById(ide);
    alert(form.teste.value); // Para você se certificar que pegou o objeto correto.
    form.submit();
}
<form method='get' action='GG.php' id='alteracao123'>
    <input name="teste" type="hidden" value="Segredo secreto!" />
    <button onclick='altera("alteracao123")'>Enviar</button>
</form>

No exemplo acima, estou partindo do pressuposto de que 123 é o número gerado automaticamente.
Answer: Pode obter o nome do form pela relação entre o botão e próprio form

function altera(meuForm){
  alert(meuForm.name);
  meuForm.submit();
}
<form method='get' action='GG.php' name="esse form tem um nome muito difícil"  id='alteracao"+ide+"'>
    <button type="button" onclick='altera(this.parentNode)'>Enviar</button>
</form>
Comment: Opa Obrigado , desta forma deu certo aqui.
Comment: Considere a resposta correcta e dê up ;)
Answer: Você pode dar um id para seu formulario como 'altera'
<form method='get' action='GG.php' name='alteracao"+ide+"' id="altera">
    <button onclick='altera(alteracao"+ide+")>Enviar</button>
</form>

Com isso é possivel verificar quando for dar 'submit' no form e rodar sua função:
document.getElementById('altera').addEventListener('submit', function(
    // Aqui você realiza suas funções
    altera();
));

Comment: Há um problema , terei vários formulários que são gerados por javascript quando clico em um botão, assim posso ter vários formulários sem saber qual o Id deles, que cai na mesma duvida que tenho.
Comment: Tente definir uma class em padrão para eles, e colocar esse mesmo event listener com isso ele vai pegar o submit do form que foi enviado.
Comment: Mas o evento submit só ira acontecer pela própria função que fiz, estou usando a função para "forçar" o submit
Comment: Caso seja possível reformular sua pergunta, não entendi direito o que você quer saber para enviar para sua função, seria apenas esse ide?

Enviar formulário sem saber o nome


Hartigan's dip test significant for bimodality with clearly unimodal data

Question: I have used the following data x to check whether my results produced by Hartigan's dip test are ok or not. But the data I used suggest a unimodal distribution while Hartigan's test indicates that the distribution is not unimodal.
Now what to do. Am I not understanding it?
x = c(1,1,1,2,2,2,2,2,2.5,2.5,2.5)
hist(x)
dip.test(x)
#
#   Hartigans' dip test for unimodality / multimodality
#
# data:  x
# D = 0.13636, p-value = 0.04419
# alternative hypothesis: non-unimodal, i.e., at least bimodal

Comment: [Unimodality test for discrete distributions](https://stats.stackexchange.com/questions/234835/unimodality-test-for-discrete-distribution)
Answer: The Hartigan dip test (Hartigan and Hartigan, 1985 [1]) is for continuous distributions, or at most a mixed distribution with a single jump in the cdf at the mode. As they explain in the paper:

A unimodal F may have an atom only at a unique mode

As a result you would not expect it to work for a distribution with multiple atoms, as the one from which your sample was (at least notionally) drawn must be. In particular it wouldn't be expected to work well for discrete distributions.
[1] J. A. Hartigan and P. M. Hartigan (1985),
"The Dip Test of Unimodality"
Ann. Statist., Volume 13, Number 1, 70-84.
http://projecteuclid.org/euclid.aos/1176346577  (open access link)
Comment: Thanks alot. So, what test I should use to check for uni and bimodality for discrete distribution?


Credential from Firebase EmailAuthProvider not working

Question: I use firebase with react then need to convert anonymous account to permanent. I have follow firebase doc but when I try look like cannot use this function they have error message as undefined
in code
let credential = firebase.auth.EmailAuthProvider.credential(email, pass)
error message
Uncaught TypeError: Cannot read property 'credential' of undefined
Someone please help me to fix a problem
ps. in my package
"firebase": "^4.5.0"
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve)
Comment: Got it and so sorry this is my first question thank for your suggestion
Answer: First check whether you are anonymously signed in or not.Below code will be helful to do so.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
   // User is signed in.
   var isAnonymous = user.isAnonymous;
   var uid = user.uid;
// ...
} else {
    // User is signed out.
    // ...
}
 // ...
});

If you get some defined values then use EmailAuthProvider to get credentials.
var credential = firebase.auth.EmailAuthProvider.credential(email, password);

Comment: Yes I still signIn and get anonymous data but when I use EmailAuthProvider credential they cannot find this function


Reverse proxy replace folder with subdomain?

Question: I'm trying to expose Jenkins build status externally via Nginx reverse proxy.  I have created a subdomain buildstatus.ourcompany.com, but I don't want the url to be buildstatus.ourcompany.com/buildstatus/icon?... so I'm trying the following, without luck:
server {
    listen              80;
    server_name         buildstatus.company.com;
    location / {
        proxy_pass      $scheme://192.168.1.5:8080/buildStatus/;
    }
}

This results in the following error when I visit buildstatus.companyname.com/icon?job=projectname:

HTTP ERROR 404 Not Found
URI:  /buildStatus/
STATUS:   404
MESSAGE:  Not Found
SERVLET:  Stapler

I have confirmed that visiting 192.168.1.5/buildStatus/icon?job=projectname works as expected.
I tried a couple other things, including one that used url_rewrite, but just got other errors.
How can I have buildstatus.companyname.com/icon?job=projectname produce the same result as 192.168.1.5/buildStatus/icon?job=projectname?
Answer: Your configuration sends all requests to $scheme://192.168.1.5:8080/buildStatus/ URL.
You need to use
proxy_pass $scheme://192.168.1.5:8080/buildStatus$request_uri;

to add the original URI to the upstream request.


what is equivalent methods in C# for mark and reset methods in java

Question: I am trying to convert a java class which extends BufferedInputStream class. It uses mark(1024) which I think it means the cursor will move to position 1024 and last it invokes reset() method. Now I have changed the class to inherit from BufferedStream in System.IO namespace, but I don't know whether there are equivalent methods for mark(int) and reset() methods in .net.
Comment: Now I have used Seek(1024, SeekOrigin.Begin) instead of mark(1024). after a for and some code in the end of the java methods it calls reset(). do I need to set Position = 0 instead of rest() method?
Comment: I think the `Seek` method and `Position` property are all you need. http://msdn.microsoft.com/en-us/library/System.IO.BufferedStream.aspx
Comment: you are right, I am going to test them.
Answer: There are no equivalent methods in .NET. mark marks the current position as the position reset should jump to.
But you can implement simplified versions of them yourself:
public class YourClass
{
    private int _resetPosition;

    public void Mark()
    {
        _resetPosition = Position;
    }

    public void Reset()
    {
        Position = _resetPosition;
    }
}


How to change placement of block or region on events?

Question: I want to change the placement of 2 regions based on window size. I know that I can print 2 blocks and use css dipslay:none based on window size, but I prefer not to double print a block.
Is there any way I can change the placement of blocks / regions based on events, such as screen size, using JS or similar?
Answer: You can use the flexbox order property: https://css-tricks.com/almanac/properties/o/order/
Comment: I think this will only work to reorder blocks within same region, but not so put them into another region.
Comment: What I was thinking to suggest this was to arrange the regions themselves. If that is not the case, than it was my misunderstanding :p
Answer: I managed to do this using js $('#source').appendTo('#destination');
I'm not sure if this is the drupalish way to do it? But at least it works!
I found it from this page;
https://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element


Como faço para verificar se um número está contido em um intervalo de dois números?

Question: Preciso verificar se o número 25 está contido no intervalo de dois números passados como parâmetro. a função retorna true caso 25 esteja contido no intervalo e false caso não esteja.
O problema é que não tem um número mínino e máximo que será passado como parâmetro, então não sei como fazer o if, se vier um 10 e um 30 era pra dar true mas tá dando false pois 30 é maior que 25 mas o 25 está contido no intervalo
function verifica25(x, y){
    if ((x <= 25) && (y <= 25)) {
        return true;
    }
    return false;
}

Comment: https://ideone.com/aqB8wD
Answer: Você tem que testar os limites
function verifica25(x, y){
  if( (x < y) && (x <= 25) && (25 <= y) ){
    return true;
  }
  else if( (y <= x) && (y <= 25) && (25 <= x) ){
    return true;
  }
  return false;
}


How to use Or operator in javascript

Question: I am trying to use an if statement and the or || operator to test if the value of the select box option for type of room is either single King, single Double Queen, or single two twins and then execute some code. I keep getting the message "uncaught syntax error unidentified token ||" right where the || operator is in the if statement.

var hotel = {
 name:"Benson hotel",
 rooms:500,
 jsuites:10,
 ssuites:10,
 booked:100,
 checkAvailability: function(){
 return this.rooms - this.booked;
}

};

hotel.name = "Bonton";

var elName = document.getElementById("hotelN");
elName.textContent = hotel.name;

 function checkin(){
  var nRooms = document.getElementById("numRooms").value * 1;
  var tRoom = document.getElementById("typeRoom");
  if (tRoom.value = "singleK")||(tRoom.value ="singleQ")||(tRoom.value = "singleT") { //*I am getting the following message about above line of code in the console. "uncaught syntax error unidentified token ||" Obviously the above if statement with || operator is not correct//

   hotel.booked = numRooms + hotel.booked;

   if hotel.checkAvailability() < 0 {
    var rAvail = nRooms + (hotel.checkAvailability());
    if rAvail <= 0 {
     var noSay = document.getElementById("say");
     noSay.textContent = "We have no rooms available";
            }

             else {
              var yesSay = document.getElementById("say");
             yesSay.textContent = "We have" + rAvail + "rooms available";

          }

       }

        /div>

   <form id="myForm">
   <fieldset>
   <legend>Book a Room</legend>

   Number of Rooms:
            <input type="number" max="10" min="1" value="1"name="rm" id="numRooms">
            Type of room: <select type="text" maxlength="14" id="typeRoom">
  <option value="singleK">Single King Bed</option>
  <option value="singleQ">Single Queen Bed</option>
  <option value="singleT">Single Two Twins</option>
  <option value="jsuite">Junior One Bedroom Suite</option>
  <option value="srsuite">Senior Two Bedroom Suite</option>
</select>

            Occupancy:<select type="text">
            <option>One adult</option>
            <option>Two adults</option>
            <option>One adult and Child</option>

            </select>

            Check In Date: <input type="date"name="checkin" id="cInDate">
            Check Out Date: <input type="date" name="checkout" id="cOutDate">
            <button  type="button" onclick="checkin()">Submit</button>
</fieldset>
   </form>

Hotel Room Availability

 and check out on July

jjjj

Comment: `if hotel.checkAvailability() < 0` - in your actual code or paste error? All conditions need to be wrapped in parens.
Comment: There's also an error on `if rAvail <= 0`. Needs parentheses: `if (rAvail <= 0)`
Answer: You just have to add a pair of parenthesis:
if ((tRoom.value == "singleK")||(tRoom.value =="singleQ")||(tRoom.value == "singleT")){
...
}

Or
if (tRoom.value == "singleK"||tRoom.value =="singleQ"||tRoom.value == "singleT"){
...
}

Comment: @zfrisch It's allowable in this instance (since the `value` attribute always returns a string) but yes, it's best practice.
Comment: And change `=` to `===`
Comment: You don't need to wrap every condition in a set of parentheses. You can wrap the whole thing in one set.
Comment: @zfrisch You're right he does not need them.
Comment: As @4castle pointed out, it's also worth noting that if the only valid type in tRoom.value is a string, then when you do your conditional checking you should be using === to compare that type as well as the value
Comment: @4castle good point. I hadn't thought of that!
Answer: The entire condition section of your if statement must be wrapped in parentheses. By doing if (condition1) || (condition2), you're terminating the conditions before your ||.
It would be like this instead:
if ((condition1) || (condition2))
Additionally: The conditional operator you're looking for is ==, not =. == is used to compare two values, whereas = is used to set.
Answer: if (tRoom.value = "singleK")||(tRoom.value ="singleQ")||(tRoom.value = "singleT") {

You CANT close if() before ||
if (tRoom.value = "singleK" || tRoom.value ="singleQ" || tRoom.value = "singleT") {

Answer: You have at least 2 issues with that line:

Your main issue is that you're missing a set of brackets around the whole of the condition:
if ((tRoom.value = "singleK") || ...) {

Right now your or-operator is just floating.

You need to use === to do comparisons. = is used to assign.

How to use Or operator in javascript


Insert form values in the database

Question: I am new to Drupal 7, and I am trying to insert the form values in a database table. I used many ways to do that, but I am not getting successful result. What is wrong with the code I am using?
<code>drupal_write_record('formtest', $data);
function form_test_form_submit($form, &$form_state) {
  $id = db_insert('formtest')
    ->fields(array(
      'First name' => $form_state['values']['firstname'],
      'Lastname' => $form_state['values']['lastname'],
      'Email' => $form_state['values']['email'],
      'Password' => $form_state['values']['password'],
      'Year of birth' => $form_state['values']['birthdata'],
      'Image' => $form_state['values']['fileimage'],
  ))
  ->execute();
  drupal_set_message(t('your messagees is added is sucessfule'));
}
</code>
Comment: What are you trying to do? Is it a node data that you want to insert?
Answer: Is your submit function getting called to begin with?  Just put a dsm in the beginning of your submit function and make sure it is being called.  If it is, then, dsm your form_state['values'].  If you can see all the values in form_state, then, make sure your table name and column names are spelled exactly the same as they are case-sensitive.
Comment: thanks shabana to share with me....this is helpful for me.

Insert form values in the database


Find the function given partial derivatives and points

Question: Find $f$$(x,y)$ given $f_x$$= $$3x^2y-4y^2$ and $f_y$$=$$x^3-8xy+6y$ and $f$$(1,1)$$=$$5$
Can anyone steer me in the right direction here? I assume I have to integrate but we haven't done integration with multivariable functions yet. Any help at all is appreciated.
Answer: Integrate with respect to $x$ and $y$ your partial derivatives. In both cases, you'll get a constant term which in this case is a function of y or x respectively.
For example
$$\int f_x dx = x^3y-4xy^2+c(y)$$
Do the same for $f_y$ and set them equal and solve.
Comment: Alternatively, differentiate $x^3 y - 4xy^2 + c(y)$ partially with respect to $y$ (not forgetting the the $c'(y)$ term), set equal to $x^3 - 8xy + 6y$, and solve for $c'(y)$.