Hibernate many-to-many relation returns empty collection

Question: I am adding a many-to-many relationship between two entities in my Spring Boot application. I have the following mappings:
Business.java:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "business_vendor",
        joinColumns = @JoinColumn(name = "business_id"),
        inverseJoinColumns = @JoinColumn(name = "vendor_id"))
@JSON(include = false)
protected List<Vendor> vendors;

Vendor.java
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "vendors")
@JSON(include = false)
protected List<Business> businesses;

I am able to add a vendor to a business then save it to the database. However, when (in a new request) I load a business then call business.getVendors(), I get an empty List. I can see from the application logs that Hibernate is selecting from the linking table, and if I run that Hibernate-generated query against the database manually, I see one row as I expect. I have tried switching the FetchMode to eager and have tried removing CascadeType.ALL, neither of which has helped.
This application is on Hibernate 4.3.11 (cannot upgrade at this time for "reasons").
Edit: Here is a minimal example:
public List<Vendor> getVendorsForBusiness(UUID businessId) {
    Business business = businessRepository.findOne(businessId.toString());
    return business.getVendors();
}

I expect this to return a List with 1 Vendor, but I get an empty List, even though there is a row in the linking table in the database.
Edit 2: Here is the relevant portion of the persist method I am using, which does successfully create a row in the business_vendor table:
public void addVendorToBusiness(UUID businessId, UUID vendorId) {
    Vendor vendor = vendorRepository.findOne(vendorId.toString());
    Business business = businessRepository.findOne(businessId.toString());
    business.getVendors().add(vendor);
    vendor.getBusinesses().add(business); // This line doesn't make a difference
    businessRepository.save(business);
}

Comment: Build a minimal example with the persist method. The mapping looks good.
Comment: I am in agreement with @jklee.  I more complete example would help others respond to your question.
Comment: How you save the entities? The mapping works into my project.
Comment: Strange. I think the problem is deeper.
Comment: I wonder if there is something odd going on with the lazy loading proxy. If I walk through the code in a debugger, I can see that the query to select the vendors is getting run at the start of the `getVendors` method, but then the `vendors` List that gets returned by the getter still has a size of 0. Unfortunately IntelliJ's debugger won't let me step inside the function that lazy loads the data however, so I can't see exactly what is going on at a lower level.
Answer: @ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "business_vendor",
        joinColumns = @JoinColumn(name = "business_id"**, referencedColumnName = "enter business Id name"**),
        inverseJoinColumns = @JoinColumn(name = "vendor_id", **referencedColumnName = "enter vendor Id name"** ))
@JSON(include = false)
protected List<Vendor> vendors;

**OR**

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "business_vendor",
        joinColumns = @JoinColumn(**name = "tablename_idname"**),
        inverseJoinColumns = @JoinColumn(**name = "tablename_idname"**))
@JSON(include = false)
protected List<Vendor> vendors;

Comment: The code might answer the question but the OP won't learn why this is working now. So please explain why your code snippet answers the question.
Comment: referencedColumnName when specified will help to reference the Table while fetching data, but if referencedColumnName is NOT specified, then Hibernate tries to generate the referencedColumnName from the JoinColumn name, if it is unable to fetch Table primary key then No data will be fetched.
Answer: Simply use the bidirectional strategy. Something like this:
Business.java
@Entity
@Table(name = "BUSINESS")
public class Business implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "business_vendor",
            joinColumns = @JoinColumn(name = "business_id"),
            inverseJoinColumns = @JoinColumn(name = "vendor_id"))
//@JSON(include = false)
    private List<Vendor> vendors;

    public Business() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<Vendor> getVendors() {
        return vendors;
    }

    public void setVendors(List<Vendor> vendors) {
        this.vendors = vendors;
    }
}

Vendor.java
@Entity
@Table(name = "VENDOR")
public class Vendor implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "vendors", fetch = FetchType.EAGER)
//    @JSON(include = false)
    private List<Business> businesses;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<Business> getBusinesses() {
        return businesses;
    }

    public void setBusinesses(List<Business> businesses) {
        this.businesses = businesses;
    }

    public Vendor() {
    }
}

Main.java
public class Main {

    private static final SessionFactory SESSION_FACTORY = new AnnotationConfiguration().configure().buildSessionFactory();
    private Session session;
    private Transaction transaction;

    public static void main(String[] args) {

        Main main = new Main();
        main.save();
        List<Vendor> vList = main.getVendorFromBusinessId(2L);
        main.displayVendors(vList);

        SESSION_FACTORY.close();
        System.exit(0);
    }

    private void save() {

        this.session = SESSION_FACTORY.openSession();
        this.transaction = null;
        try {

            this.transaction = this.session.beginTransaction();
            Business b1 = new Business();
            Business b2 = new Business();
            Business b3 = new Business();

            Vendor v1 = new Vendor();
            Vendor v2 = new Vendor();

            List<Business> bList = new ArrayList<>();
            bList.add(b1);
            bList.add(b2);
            bList.add(b3);

            List<Vendor> vList = new ArrayList<>();
            vList.add(v1);
            vList.add(v2);

            b1.setVendors(vList);
            b2.setVendors(vList);
            b3.setVendors(vList);

            v1.setBusinesses(bList);
            v2.setBusinesses(bList);

            this.session.save(b1);
            this.session.save(b2);
            this.session.save(b3);

            this.transaction.commit();
        } catch (Exception e) {

            if (this.transaction == null) {

                this.transaction.rollback();
            }
        } finally {

            this.session.close();
        }
    }

    private List<Vendor> getVendorFromBusinessId(Long businessId) {

        List<Vendor> vList = null;
        this.session = SESSION_FACTORY.openSession();
        this.transaction = null;

        try {

            this.transaction = this.session.beginTransaction();
            Business business = (Business) this.session.get(Business.class, businessId);
            vList = business.getVendors();
            this.transaction.commit();
        } catch (Exception e) {

            if (this.transaction == null) {

                this.transaction.rollback();
            }
        } finally {

            this.session.close();
        }

        return vList;
    }

    private void displayVendors(List<Vendor> vList) {

        if (vList != null) {

            System.out.print("Vendor List IDs: ");
            vList.forEach((vendor) -> {
                System.out.print(vendor.getId() + " ");
            });

            System.out.println();
        }
    }
}

Hope this will solve your problem.
My output:
My Output Image
Comment: I don't have a problem saving the relation, it's getting that I'm having a problem with. And I already tried adding `fetch = FetchType.EAGER`.
Comment: Well, did you tried bidirectional strategy ? After using bidirectional mapping does getVendors() returns empty ?
Comment: I have tried with the bidirectional strategy and am still getting an empty list from getVendors() after persisting.
Comment: Dear brother, may be you are missing the point again and again.  Here I'm sharing all the code segment already done and it's working.
Comment: One more thing, when you create a Business object then it's vendor list must be null because it's not initialized. So when you are calling `business.getVendors().add(vendor);` it doesn't make any sense
Comment: Hibernate will always return an empty list if there are no entries, it will never return null on a OneToMany or ManyToMany. And you're still looking in the wrong place, you're thinking that the problem is in the persisting, but it's in the fetching.
Comment: Actually the problem is your question. You have just provided `businessRepository.findOne(businessId);`. What does the businessRepository method do ? Did you described that? I thought it's providing a Business object. Whatever, I know what hibernate returns in which situation. By the way, it working in my system. You can see the output I have provided with the answer. Whatever I think you want to update an existing object.
Answer: In the database, we use UUIDs for primary keys. However, the people who built this application decided that instead of using a Java UUID type, they should use Strings for the UUIDs. So, sometimes the application would send a lowercase UUID to the database, and sometimes it would send an uppercase UUID. The database doesn't care, because UUIDs in SQL Server are case-insensitive, but Java Strings are case-sensitive, so Hibernate doesn't recognize that the Business with the lowercase UUID is the same as the Business with the uppercase UUID. So I had to .toString().toUpperCase() all of the IDs before sending them to the database to make sure they're the same.
Of course, Java UUIDs are case-insensitive, so this whole problem could have been avoided if the people who built this software just used those instead of Strings.


$(X,Z) \stackrel{D}{=} (Y,Z)$ implies $\mathbb{E}[f(X) \mid Z] = \mathbb{E}[f(Y) \mid Z]$ for any $f : \mathbb{R} \to \mathbb{R}$

Question: A more precise formulation of the problem is as follows:

Let $X,Y,Z$ be random variables such that $(X,Z)$ and $(Y,Z)$ have the same joint distribution; that is, $\mathbb{P}[X \in B,Z \in B'] = \mathbb{P}[Y \in B,Z \in B']$ for all $B,B' \in \mathcal{B}(\mathbb{R})$, where $\mathcal{B}(\mathbb{R})$ denotes the Borel algebra. Show that $\mathbb{E}[f(X) \mid Z] = \mathbb{E}[f(Y) \mid Z]$ almost surely, where $f$ is any real-valued function.

By linearity of expectation, this problem is equivalent to showing that $0 = \mathbb{E}[f(X) - f(Y) \mid Z]$. It is obvious that $0$ is $\sigma(Z)$-measurable, so it remains to show that $\mathbb{E}[(f(X) - f(Y))1_A] = 0$ for all $A \in \sigma(Z)$.
This is where I'm stuck. I feel that the trick is similar to showing the uniqueness (up to a.s.) of conditional expectation, where we cleverly choose $A_{\epsilon} = \{f(X) - f(Y) > \epsilon\}$, and show that it occurs with probability $0$. However, I'm not sure how to guarantee that $A_\epsilon$ lies in $\sigma(Z)$, hence I can't proceed.
Thanks for the help in advance.
Answer: For $A\in\sigma(Z)$ there is a $B\in\mathcal{B}(\mathbb{R})$ such that $A=\{Z\in B\}$. Now,
$$
\int_\Omega f(X)\mathbf{1}_A\mathrm dP=\int_\mathbb{R}f(x)\mathbf{1}_B(z)P_{(X,Z)}(\mathrm dx,\mathrm dz)=\int_\mathbb{R}f(y)\mathbf{1}_B(z)P_{(Y,Z)}(\mathrm dy,\mathrm dz)=\int_\Omega f(Y)\mathbf{1}_A\mathrm dP
$$
showing that $\mathrm{E}[(f(X)-f(Y))\mathbf{1}_A]=0$ as you want.
Comment: Thanks, but I don't have (and the course I'm taking does not require) background on Lebesgue integral. Is there a way to solve this without using Lebesgue integral?
Comment: @ClementYung If you don't know about Lebesgue integrals, then how do you define expectations and conditional expectations?
Comment: We follow the definitions in Ross' 2nd Course in Probability, which says:
$$
\mathrm{E}[X] \equiv \sup_{\text{all simple variables }Y \leq X}\mathrm{E}[Y]
$$
and, the conditional expectaion $\mathrm{E}[X \mid \mathcal{F}]$ to be the random variables $Z$ such that 1) $Z$ is $\mathcal{F}$-measurable and 2) $\mathrm{E}[Z1_A] = \mathrm{E}[X1_A]$ for all $A \in \mathcal{F}$.
Comment: @ClementYung Well, that is actually how the Lebesgue integral is defined. I'm not sure there is a shorter path for showing the result than to rely on the "change-of-variables"-formula for the Lebesgue integral which is what I did in my post. The formula is what is stated [here](https://en.wikipedia.org/wiki/Pushforward_measure) or alternatively [here](https://math.stackexchange.com/questions/236077/how-expected-value-is-related-to-density-function/237022#comment524888_237022).


Does good calibration surpass roughly met assumptions and mediocre discrimination?

Question: My question arises from my current task to develop a clinical prediction model using ordinal logistic regression (with rms), but applies to any kind of regression analysis.

The proportional odds assumption (difficult to assess...) is only roughly met. (I am aware of the continuation ratio approach).
Results of measures of discrimination (another difficult topic) are not overwhelming.
But the calibration plot is quite nicely.

So, do I have to worry about 1 and 2 or does the very good calibration surpass basic assumptions and discrimination?
Comment: Would you care to add a bit of detail to your question? I'm willing to start a bounty, as your question is perhaps related to mine: http://stats.stackexchange.com/questions/29133/effects-of-ignoring-the-sampling-strategy
Answer: "If a model has poor discrimination, no adjustment or calibration can correct the model. If discrimination is good, the predictor can be calibrated without sacrificing discrimination. Here, calibrating predictions means modifying them without changing their rank order"
Tutorial in biostatistics: Multi variable prognostic models : issue in developing models, evaluating assumptions and adequacy and measure and reducing errors. Harrell et al. 1996).
So, I would be inclined to say that poor discrimination, but good calibration is a problem. But this is also a strange result.  If you have a high probability, such a 0.9, to be perfectly calibrated you would need to have an observed frequency of 90% for the case (for example, in this decile 90% of patients do have cancer), and this relationship needs to be true throughout. In order to achieve something like that, I am inclined to say you need good discrimination too (i.e. False positives may bring down the observed frequency at the high end and vice versa, thus resulting in poor calibration).
Maybe you need to make sure that your calibration is actually "good" and discrimination "bad".


Banach Algebra: $r_\sigma(x)=\|x\| \iff \|x^2\|=\|x\|^2$

Question:
I am trying to see that if we have a complex Banach algebra with unity, we will have that $$r_\sigma(x)=\|x\| \iff \|x^2\|=\|x\|^2.$$

I was able to do the first implication: Since we know that $\|x^2||\leq \|x||^2$ always and we have that $r_\sigma(x^2)=r_\sigma(x)^2=\|x\|^2$ so we will have that $\|x^2\|\geq r_\sigma(x^2)=\|x\|^2$.
Now for the other one, I haven't figured out how to do it yet I just can't seem to see why we have $r_\sigma(x)\geq \|x\|$ if $\|x^2\|=\|x\|^2$, so any tips are appreciated. Thanks.
Answer: Hint: Since $\|x^2\|=\|x\|^2,$ therefore $\|x^{2^n}\|=\|x\|^{2^n}\\$ for all $n \in \mathbb{N}.$
Edit: To see this, consider $\|x\|^4=(\|x\|^2)^2=\|x^2\|^2=\|x^4\|.$ Now repeated application/induction proves it for all $n \in \mathbb{N}.$
Comment: Oops, I made a typo. I have fixed it and added details.
Comment: Oh yeah , ok with that I think I have figured it out because we will have that $(r_\sigma(x))^2=r_\sigma(x^2)=\lim\limits_{n\rightarrow \infty} (||x^{(2n)}||)^{(1/n)}$ and using $||x^{2n}||=||x||^{2n}$ we get the result.
Comment: I am trying to see why the hint is true , tried using induction but it hasnt worked yet , my question is if $x$ is fixed or do we need to have the condition that for all $x\in X$ $||x^2||=||x||^2$? @Sahiba Arora
Answer: $||x^2||=||x||^2 \implies ||x^2||^{\frac{1}{2}} =||x|| \implies ||x^{2^n}||^{\frac{1}{2^n}} =||x||\\$
$r(x)=\lim_n||x^{2^n}||^{\frac{1}{2^n}} =||x||$.


Disable button not working inside if-else, but working without if-else

Question: I'm trying to create a button that should check if user input is not empty before submitting. When user input is set, the button would be disabled, change in innerHTML and have a spinner at the bottom.
Below are what I have got so far.

let form = document.getElementById("form");
let button = document.getElementById("btnSub");
let text = document.getElementById("inpSub");
let spin = document.getElementById("soonSpin");
button.addEventListener("click", submit_fn, false);

function submit_fn() {
  if (text.innerHTML.length == 0) {
    alert("Please fill out the question");
    // return;
  }
  form.submit();
  text.disabled = true;
  button.disabled = true;
  button.innerHTML = " Please wait! Loading...";

  spin.className = "spinner-border";
  spin.setAttribute("role", "status");
  let span = document.createElement("span");
  span.className = "sr-only";
  span.innerHTML = "Loading...";
  spin.appendChild(span);
}
<form id="form" method="post" action="{{url_for('prediction')}}" enctype="multipart/form-data">
  <input class="border border-danger" id="inpSub" type="text" name="question" placeholder="Enter question here" required />
  <button class="btn-danger" type="submit" id="btnSub">Find closest answer</button>
</form>

My code always shows the alert in both cases when I have the input or having nothing. And, it doesn't run any of the code outside if statement, but do render to the next page.
Does anyone know what's the problem here?
Thanks in advance!
Comment: You want to check `text.value`, not `text.innerHTML`
Comment: omg, it works, thank you!!
Answer: You need to listen for the change on the text input as well to disable / enable the button :
text.addEventListener("input", e => {
  if (text.value.length > 0) {
    button.disabled = false
  } else {
    button.disabled = true
  }
});

Check the comments to see the differences in the code : ( mainly check text.value instead of text.innerHTML )

let form = document.getElementById("form");
let button = document.getElementById("btnSub");
let text = document.getElementById("inpSub");
let spin = document.getElementById("soonSpin");

button.addEventListener("click", submit_fn, false);
text.addEventListener("input", e => {
  if (text.value.length > 0) {
    button.disabled = false
  } else {
    button.disabled = true
  }
});

function submit_fn(e) {
  if (text.value == 0) {
    alert("Please fill out the question");
    // return;
  }

  e.preventDefault(); // comment this to submit the form

  // uncomment this line to submit the form
  // form.submit();

  text.disabled = true;
  button.innerHTML = " Please wait! Loading...";

  spin.className = "spinner-border";
  spin.setAttribute("role", "status");
  let span = document.createElement("span");
  span.className = "sr-only";
  span.innerHTML = "Loading...";
  spin.appendChild(span);
}
<form id="form" method="post" action="{{url_for('prediction')}}" enctype="multipart/form-data">
  <input class="border border-danger" id="inpSub" type="text" name="question" placeholder="Enter question here" required />
  <button class="btn-danger" type="submit" disabled id="btnSub">Find closest answer</button>
</form>


how to make scrollable button in android

Question: Hello i'm trying to make an equalizer for my app but i can't figure out how to make the buttons. I don't really know how to explain myself so here is a picture that reveals more than my words:

Do i need animations? Can you guys point me in the right direction?
Thanks in advance.
Comment: Seems to me that you need to create custom Views extending button of imagebutton or imageview and handle touch events. That's the first newbie thought.
Comment: @Madcoderz : I want to create an music equalizer in my app.Can you help me in that.
Answer: There's a nice tutorial here for creating an odometer widget. It's not at all the look you want, but many (most) of the same issues apply, including custom rendering, dealing with touch events, and wiring up a series of sub-widgets into a larger control. It's the first thing I thought of when I saw your graphic.
Answer: This is simple vertical seekBar....
<code>public class SimpleVerticalSeekBar extends SeekBar {

    public SimpleVerticalSeekBar(Context context) {
        super(context);
    }

    public SimpleVerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SimpleVerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    protected void onDraw(Canvas c) {
        c.rotate(-90);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}
</code>
Answer: I think you mean a SeekBar. It's the JSlider of Android.
Comment: @Ted I found [this older](http://stackoverflow.com/questions/631238/modifying-the-android-seekbar-widget-to-operate-vertically) topic with the same problem.
Comment: Yep, the suggestions on that thread also require a custom widget. I think that's going to be a lot easier than trying to subclass SeekBar and force it to operate vertically.


Which statistical analysis replaces MANOVA when there are too many dependent variables?

Question: I want to understand if an experiment gives equal response at two different levels of an experimental parameter. What I did was to repeat the experiment 6 times at the first level of the parameter and 6 times at the second level. The problem is that the experiment measures 20 variables, so I have 12 experiments and 20 measured variables. I'm not sure, but I think that MANOVA will not work in this setting.
Is this correct? What kind of alternative test should I use?
Comment: Also, if you want to get some quick idea, you can (1) run 20 t-tests, one for each measured variable, (2) standardize all 20 variables, do PCA in this 20-dimensinal space, take the two first PCs, and look at the scatter-plot of your 12 points. Neither procedure is a statistical test you are looking for, but it can give you some idea about whether there is some difference or not.
Comment: Interesting question. [This paper](http://arxiv.org/pdf/1002.4547.pdf) looks like it could be relevant, but I have not looked into it yet.
Comment: See also [this paper](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3755504/).
Comment: Thanks. I had some fear to use PCA because I don't understand the possible effect of standardize the variables and of the choice of how many PCs to take. Thanks also for the references. I had a look at the first paper. It is interesting. I'll try the proposed test. I still have to read the second paper.
Comment: It would be great to hear from you how well these tests worked. I have briefly looked through both papers and could in principle write it down here as an answer, but I don't have any experience with either of these tests, so you might prefer to answer your own question after you tried them out. I also see that there is a large body of literature preceding these two papers starting with Dempster 1958 (citations are in the two papers above).
Comment: Note also that your situation (with only two groups) corresponds to Hotelling's test which is technically a simplest case of MANOVA, but to call it MANOVA might sound as an overkill. You might want to add `hotelling` tag and mention Hotelling's test in the title/body of your question (for future references and to attract more attention).
Answer: If possible I would suggest first using either PCA to find a small number of composite variables or EFA to identify some latent variables. Then run the MANOVA on those components/factors to see if the experiment had an effect. Otherwise, when you test for group differences you (software) must estimate all of the 19*20/2 covariance parameters among the DVs and subsequently your power will be very low.


Is it valid to keep insignificant variable?

Question: I'm building a model that predicts rather rare event. The data set consists of about 240.000 examples from which only 1410 are positive. One of the variables from the data set, let's call it $X_{1}$ is a binary variable with value 1 in only about 1% examples. From the knowledge about the event I know that it is impossible to occur an event when $X_{1} = 1$. When I include $X_{1}$ in logistic regression model then it has highly negative coefficient, but it is also highly non significant. The coefficient is -12 and the standard error is 122.
Question:
Is it valid to keep the variable $X_{1}$ despite the low significance?
Comment: Partly relevant answer also [here](http://stats.stackexchange.com/a/51585/3277).
Comment: And see [here](http://stats.stackexchange.com/questions/11109/how-to-deal-with-perfect-separation-in-logistic-regression) re separation. If you're using maximum likelihood parameter estimates & you're judging significance by Wald standard errors **they're badly wrong** when you have separation.
Answer: In principle it is perfectly OK to include non-significant variables. You are interested in the effect of a variable, and the fact that that effect is not significant is valueable information. The logical way to convey that information is to have it be part of your model and show that it is not significant.
However, in your case I would be worried about perfect separation. If that is the case the non-significance is not really informative and I would not include that variable or use one of the alternatives proposed in the link.
Comment: Removing the variable on which separation occurs when you have prior knowledge that it reflects a true impossibility (as the OP says) is *not* a good idea.
Comment: IMHO removing the variable is not a good idea, although I'm a bit concerned that it might lead to some numerical instability. Firth LR seems to be a good solution and fortunatelly it is both R and SAS. Maarten thanks for the link, it helped me to found Firth LR!
Comment: @Tomek: Note that Firth's penalization will change your "impossible" to "improbable".
Answer: As you say, it seems that X1 is quite a good predictor for your response.
It is not significant itself in Wald test maybe because the strange structure of the data set, or maybe some other variable can explain such effect.
The Wald test can not tell us too much in such sense.
Maybe a Chi-square test about adding that X1 can tell us more, and also AIC, BIC.


UIBezierPath vs putting png in imageassets

Question: I'm helping create an app that will use images that can be resized (think AutoCAD). Fortunately, I have PaintCode and I have Illustrator so it's very easy for me to convert a svg file into code should I want to.
I converted one image into code and it's around 10,000 lines of code for the image. For speed purposes, is it better to have just a frame with a uiimage inside of it or to use the 10,000 lines of code filled with bezier paths?
Comment: How about benchmarking it?
Comment: Yup definitely tried it. It's roughly around the same.
Answer: I agree with Sami that benchmarking is the best way to answer the question.
In general bitmaps tend to be faster but take more storage space. Vector graphics tend to be smaller, and resolution-independent, but get slower and slower as complexity goes up. (Where bitmap performance is all but independent of image complexity. I say "all but" because some compression formats like JPEG do more work on complex images.)
Comment: Thanks for the answer. Yeah I read up on it a bit and it seems this is definitely the case. Benchmarks were roughly the same initially with just a few images placed onto the VC. We've decided to go with the code for more flexibility in the future.
Comment: You should compare a worst-case example (an image generated from 10,000 lines of code). In that case you'll likely find the bezier path much slower.


Redhat / CentOS 7.4 Volume Group with different size disks and RAID 1

Question: I have 4 disks: 2 x 1TB and 2 x 4TB.
In the RHEL 7.4 installation disk partitioning section, I can create a single Volume Group over all 4 disks and set RAID level: RAID 1 (Redundancy)
This theoretically gives me +- 5TB of available space in a single volume group - but I have no idea how the RAID 1 mirror is applied.
To me it makes conceptual sense to have the 2 x 1Tb drives mirror each other and and the 2 x 4Tb drives mirror each other and define a volume group over the mirrored pairs, however there doesn't seem to be any way that I can see to "tell" the RHEL GUI how I want the mirror configured within the volume group.
My question is: Is there something I'm missing withing the GUI, and should I even be concerned about pairing "like" disks; or does it truly make no difference ie. does RHEL 7 handle the RAID aspect transparently within the volume group?
thanks so much!
Answer: Raid 1 can be applied in a layer between LVM and the disks.
Raid 1 can also be applied to the logical volumes themselves inside LVM without the use of a separate raid layer.  This is nice because it would let you make a large raid5 or raid0 LV after installation if you needed a larger amount of space available.
You could even get more usable space that way.  3TB (from the first 1TB of each drive in raid5) + 3TB (from the rest of the 4tb drives in raid1) = 6TB usable, redundant storage.  And if you do it inside LVM, you can change it around while you're booted and running.
As far as your situation goes, it depends entirely on how you build it in the installer.  Test in a VM with two 1GB and two 4GB virtual disks, and find out.
Comment: I can't see a way via the install GUI to make a mirror across the 4 disks giving me 5Tb usable mirrored space. What I've done is create VG "centos" in the GUI of only the 2 x 1Tb drives, which allows me to install the OS. When installed my plan is to manually create a a RAID 1 device from the 4Tb drives and then add the mirrored device to the "centos" VG ...which will hopefully give me a final "centos" VG of 5Gb (all RAID1) ie. doing what I wanted in my question above. Does this sound sensible? Thanks so much
Comment: Yes, that should work.  Anaconda has never been ideal for setting up advanced partitioning.  Many people recommend setting it up manually with parted, mdadm, and lvm from a live cd, then telling anaconda only to use what is already there.
Comment: One last question: am I understanding correctly from your answer that another possible approach would be to create a single VG having no RAID across all 4 disks - and then create 2 equal size LVs from the VG and place them in a RAID 1 configuration?
Comment: No.  That's not what I meant to convey.
Comment: I said you could put all four disks in one VG and then have ANY NUMBER OF LVs inside that VG.  Each of them could have their own raid level.  If the highest possible fault tolerance was your goal would use raid6 on my first LV, since you have four disks to work with.  It could be 2TB and span the first TB of space on all four disks.   Then I'd make a 3TB raid1 (also called a 'mirrored LV'  in the remaining space.


How to keep item from menu selected after clicking on it

Question: I have tried to create a small filter menu using Html, Css and Javascript.
I have the following issue: when I click on a different item of the menu except for the first, the white "pill" element goes on the selected one, but after the page loads, it returns to the first element - when an item is clicked, the page reloads and goes to that section.
This is the menu and the white pill element which is at the first item is the one that should remain on the selected items: the current behavior is that when I click on "today", for example, it moves over it, but when the page loads and I see the page for "today", the white pill returns to the first element.

The code is here:

route()->getName(), 'last-day') }}" class="nav-item nav-link {{ $match_date == $third_day_date? 'active': '' }}">{{ $third_day_date }}

route()->getName(), 'yesterday') }}" class="nav-item nav-link {{ $match_date == $second_day_date? 'active': '' }}">Yesterday

route()->getName(), 'today') }}" class="nav-item nav-link {{ $match_date == $today_date? 'active': '' }}">Today

route()->getName(), 'tomorrow') }}" class="nav-item nav-link {{ $match_date == $tomorrow_date? 'active': '' }}">Tomorrow

What can I do in order to make the white pill element remain on the clicked item of the menu?
I think the items that might needs a change are the ones from the end of the css, ".nav-item::before"...but I am not sure. Can anyone help me?
Answer: This is because you are not redirecting the URL.
A solution is to create tabs of sort. This fairly simplifies the explanation so check it out once. It shows how to create full page tabs.
Answer: You are using  tags which are links.  When you click on them the link address will load.  You can prevent default behavior as shown, but what are you trying to do?

                $(document).ready( function() {

                $("#filter-bar li").click(function(){
                 event.preventDefault();
                   $("#filter-bar li").removeClass("active");
                    console.log(this);
                    $(this).addClass("active");
                    $("#filter-bar").removeClass().addClass($(this).attr("data-target"));

                });

            })

#filter-bar {
     width: 100%;
     margin:0;
     padding:0;
     height:auto;
     display:inline-flex;
}

#wrapper-filter {
     background-color:#484747;
     width: 100%;
     height:auto;
     margin:30px auto;
     border-radius: 30px;
     box-sizing: border-box;
}

#filter-bar li {
     width: 100%;
     background-color: transparent;
     text-align: center;
     list-style-type: none;
     z-index:10;
     cursor: pointer;
     font-family: Open Sans, sans-serif;
     font-weight: 100;
     font-size: 18px;
     line-height:36px;
}

.pill {
     position: absolute;
     width:25%;
     height: 50px;
     background-color: #fff;
     border-radius: 30px;
     color: #444;
     z-index:10;
     border: 5px solid #eee;
     box-sizing: border-box;
}

.filter-option {
     transition: color 500ms;
}

#filter-bar.option-1 .pill {
     margin-left: 0%;
     transition: margin-left 200ms ease;
}

#filter-bar.option-2 .pill {
      margin-left: 24.5%;
      transition: margin-left 200ms ease;
}

#filter-bar.option-3 .pill {
       margin-left: 48.8%;
       transition: margin-left 200ms ease;
}

#filter-bar.option-4 .pill {
        margin-left: 72.5%;
        transition: margin-left 200ms ease;
}

.option-1.active{
    color:#484747; transition: color 200ms;
}

.option-2.active{
    color:#484747; transition: color 200ms;
}

.option-3.active{
    color:#484747; transition: color 200ms;
}   .

.option-4.active {
    color:#484747; transition: color 200ms; }

.nav-item {
    margin: 0 1px;
    position: relative;
}

.nav-item .nav-link {
    text-transform: uppercase;
    font-weight: 600;
}

.nav-item::before {
    position: absolute;
    width:25%;
    height: 50px;
    background-color: #fff;
    border-radius: 30px;
    color: #444;
    z-index:10;
    border: 5px solid #eee;
    box-sizing: border-box;
    -webkit-transform: scaleY(0);
    transform: scaleY(0);
    -webkit-transform-origin: top;
    transform-origin: top;
    transition: -webkit-transform .3s ease;
    transition: transform .3s ease;
    transition: transform .3s ease, -webkit-transform .3s ease;
}

route()->getName(), 'last-day') }}" class="nav-item nav-link {{ $match_date == $third_day_date? 'active': '' }}">{{ $third_day_date }}

route()->getName(), 'yesterday') }}" class="nav-item nav-link {{ $match_date == $second_day_date? 'active': '' }}">Yesterday

route()->getName(), 'today') }}" class="nav-item nav-link {{ $match_date == $today_date? 'active': '' }}">Today

route()->getName(), 'tomorrow') }}" class="nav-item nav-link {{ $match_date == $tomorrow_date? 'active': '' }}">Tomorrow

Comment: I want the link to load as expected, but the white pill to go on the selected item of the menu. So, after adding your changes, the white pill moves as expected and it remains there, but the page does not load. How can I make the page load also ?
Comment: So, if I run your code snippet, the behavior is right ( the white pill moves as expected). But I also need my page to go to /tomorrow or /today
Comment: can you help me with a suggestion ? I am new in front-end development and I do not know how to make both these things happen :( I need my scenario combined with yours in order to be right
Comment: when the new page loads it comes from the server.  You need to take the information from javascript and pass it to your controller.  From there, you need to update the page. Or, do yopu just want to move to a different place on the current page?
Comment: so, the code that I put was loading fine, when I clicked on "today" it went to /today because of the routes that are created. I need this behavior added to the "white pill" movement accordingly to the item clicked. So, if I click on "today" I want to white pill to remain there, because my code does this: I click on "today". the white pill goes to "today". but after the page loads, it comes back to the first item
Comment: what you did is the thing that I want from the white pill, but the page does not load anymore. I need what I have, with the page load, plus what you provided me: the white pill remaining where I click on
Comment: are you loading a different page?
Comment: yes, this is the website that I try to modify: https://www.findyourbets.com/ I am trying to change the way date is shown
Comment: you can see here what happens if you click on "today". "tomorrow" etc
Comment: so I went to your site.  Very Nice!.  But it doesn't look like anything really changes when you click on the tabs
Comment: what are you using on the backend? php? python?
Comment: well, nothing changes because there are no tennis matches right now :D take a look at the link of the page, that one changes :D for backend, php
Comment: so, in php you need to update the css for the linked page


a good resource to study about 2 classification ways?

Question: One of my friends has asked me a question and because I haven't been involved with clustering a lot, I decided to ask his question here. He says that:

There are two classification ways :  C4.5 and jordan/Elman ANNs.
  Do you know of any good resource which has covered these 3 ways
  comprehensively?

He wants to know about the concept of these two ways and their algorithm. In fact he wants to understand these ways intuitively and get the purpose of them. Do you of any good book or another resource which has explained the concept extensively?
Comment: None of those are clustering/unsupervised algorithms!

Instead, they're all classification methods (they take some labeled data and learn how to label other, unlabeled data). Furthermore C4.5 and J48 are the same algorithm! J48 is a java implementation of Quinlin's C4.5 algorithm.
Comment: @MattKrause ok do you know any resource? Any good neural networks book that has comprehensively explained the `jordan/Elman networks`? And any resource which has explained the Quinlin's C4.5 algorithm? Is there any relation between the latter one and fuzzy c-means clustering?
Answer: These are classification algorithms.
You can find detailed information e.g. in the Weka book. Look for "decision trees". Or in fact, pretty much any other textbook on machine learning.


Alterar menu dropdown atravez do input checkbox

Question: Estou tentando criar um menu dropdown dinâmico que possa mostrar seu conteúdo conforme checkbox seja marcado.
<!DOCTYPE html>

<input type="checkb" value="produto"/>Produto

<input type="checkb" value="servico"/>Servicos

<input type="checkb" value="outros"/>Outros

<select name="listaPSO" id="LISTAPSO">
<option value="">--- Select ---</option>
<option value="">----Produto----</option>
<option value="Produto">Celular</option>
<option value="Produto">Tablet</option>
<option value="Produto">TV</option>
<option value="">----Servico----</option>
<option value="Servico">Troca</option>
<option value="Servico">Compra</option>
<option value="">----Outros----</option>
<option value="Outros">Outros A</option>
<option value="Outros">Outros B</option>
</select>

Conforme eu marco checkbox, gostaria de poder mostrar no menu dropdown apenas o conteúdo relacionado,quando marco Produto teria que mostrar apenas a lista de produtos no menu, assim como serviço e outros, não sei se essa forma que estou fazendo é ideal, o problema que estou tendo é que ao marcar e desmarcar o conteúdo nem sempre marca corretamente e ao desmarcar todos ele fica com última lista marca.

Comment: Podes mudar esse HTML ou não tens acesso a ele?
Comment: Não vejo problema em alterar o HTML, o que estou buscando é uma solução usando checkbox e dropbox.
Answer: Se podes mudar o HTML podemos juntar mais informação a essas option que facilita a tarefa.

$('#checkbox').change(function() {
  var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  var options = document.querySelectorAll('#LISTAPSO option');

  var filtros = [].reduce.call(checkboxes, function(filters, el) {
    if (el.checked) return filters.concat(el.value);
    return filters;
  }, ['vazio']);

  for (i = 0; i < options.length; i++) {
    var option = options[i];
    option.style.display = filtros.includes(option.getAttribute('data-group')) ? 'block' : 'none';
  }
});

  <input type="checkbox" value="produto"/>Produto

  <input type="checkbox" value="servico"/>Servicos

  <input type="checkbox" value="outros"/>Outros

<select name="listaPSO" id="LISTAPSO">
  <option data-group="vazio" value="">--- Select ---</option>
  <option data-group="produto" value="celular">Celular</option>
  <option data-group="produto" value="tablet">Tablet</option>
  <option data-group="produto" value="tv">TV</option>
  <option data-group="servico" value="troca">Troca</option>
  <option data-group="servico" value="compra">Compra</option>
  <option data-group="outros" value="outros a">Outros A</option>
  <option data-group="outros" value="outros b">Outros B</option>
</select>
Comment: Thanks Sergio, your solution works just fine!
Comment: @bernlt ótimo! Se quiseres podes marcar  resposta como aceite


Can't figure out how to use schedule and tidy resource in puppet

Question: I have puppet code, that I can't manage to get to work:
<code>schedule { 'daily_once':
        period => daily,
        repeat => 1,
}
node 'puppet1' {
        tidy { '/opt/puppetlabs/server/data/puppetserver/bucket':
                age => '5w',
                recurse => true,
                rmdirs => true,
                backup => false,
                schedule => 'daily_once',
        }
        tidy { '/opt/puppetlabs/server/data/puppetserver/reports':
                age => '5w',
                recurse => true,
                rmdirs => true,
                backup => false,
                schedule => 'daily_once',
        }
}
</code>
tidy resource still keep gets executed every time puppet agent runs.
Answer: This is an long outstanding bug in Puppet, first reported for Puppet 2.6.4
As far as I know, there is currently no known solution.


Taxonomy from URL

Question: I want to show a views-block on a taxonomy page.
There are two taxonomy vocabularies.
Collections: bronze, silver, gold & Sizes: small, medium, large
So I have url's like this:
collections/bronze/small
So what I want to do: show articles that have a taxonomy term "collection" set to "bronze" and size set to "small".
I found similar problems, but I can't get it to work :(
Same issue, but didn't work out for me:
Edit: Hmm, it works when I enter "bronze" into "Preview with contextual filters:", but when I try it on the taxonomy page nothing is shown. My path looks like this:
http://localhost/drupalwebsite/?q=collections/bronze
Overview of my view settings:
Fields:
Title
CK field: Image
Contextual filter:
Collections taxonomy term
When value NOT available:
Provide default value -> Raw value from URL -> 2th component.
When value IS available:
Specify validation criteria -> Validator: Taxonomy -> Type: Term name conv. to ID -> Transform dashes to spaces
The taxonomy "sizes" isn't included yet in my view!
Comment: Enable the "taxonomy term" view, it's disabled by default. Then configure the 2 contextual filters.
Comment: Please tell us what filters, fields and context filters (and settings) you have.
Comment: Edited my previous post, there's an overview of my view now.

Thanks in advance!
Comment: Enabling the "taxonomy term" view is not such a bad idea... Is there an easy way to show the taxonomy terms: "sizes" if I go to the "collection" taxonomy page? Because they are divided in 3 sizes... Maybe I can make children in the "collection" taxonomy... Gold, with children Small, Medium and Large... Instead of using two taxonomy vocabularies. So I want to show the children of the taxonomy term if there are children. Otherwise I want to show the products.
Comment: Hmm, the "taxonomy term" view doesn't show the "body / description (I use a dutch version so I don't know how it is called in english)" of the term on the page like the regular taxonomy pages does... THIS CAN BE EASILY SOLVED: http://www.pridedesign.ie/content/drupal-taxonomy-description-view
Comment: If you use the method I found above, use "taxonomy_term_load" instead of "taxonomy_get_term" in Drupal 7
Answer: Enabling the "taxonomy term" view and changing the settings is a way to solve this problem.
If you want to show the "taxonomy description" on your view you can use this method:
http://www.pridedesign.ie/content/drupal-taxonomy-description-view
In Drupal 7 use the taxonomy_term_load() function instead of the taxonomy_get_term() function.

Taxonomy from URL


How to unset an ajax loading

Question: I have this script which loads external content:

This is the select that retrieves the content:
<select name="port_post" id="port-post" onchange="get(this.parentNode);">
    <option value="1">Select one...</option>
    <option value="2">Pear</option>
    <option value="3">Pineapple</option>
</select>

And this is the container div:

Default content

All I whish to know is how I can unset the ajax loading when I change the selection to "Select one...". I wish to say, how restoring the Default content once the "Select one..." option is selected.
Answer: If you use the same XMLHttpRequest object every time, instead of making a new instance at every call, the pending connection will be aborted, the event handler will be disconnected and the object will be reset when calling http_request.open() a second (or third, etc.) time (reference).
Answer: I think something like this would be what you want:
function get(obj) {
  var selObj = document.getElementById('port_post');
  var selectedVal = selObj.options[selObj.selectedIndex].value; //this is more Xbrowser compatible than your previous method
  if (selectedVal == 1){
      if (http_request)
         http_request.abort();
      document.getElementById('opciones').innerHTML = 'Default content';
  } else {
      var poststr = "port_post=" + encodeURI( selectedVal );
      makePOSTRequest('http://www.site.com/inc/metaform.php?opcion='+ encodeURI(selectedVal ), poststr);
  }
}

How to unset an ajax loading


Given the triangle $ABC$...Prove that the $ME$ line always goes through a fixed point when $M$ moves.

Question: Given the triangle $ABC$, $M$ is the point inside that triangle. Construct $BMCD$ and $MAED$ parallelograms. Prove that the $ME$ line always goes through a fixed point when $M$ moves.
(In the drawing, I found the line $ ME $ always through the fixed point centroid $ G $ of the triangle ABC, but I have not proven it.)
Answer: $$\vec{EM}=\vec{EA}+\vec{AM}=\vec{DM}+\vec{AM}=\vec{DB}+\vec{DC}+\vec{AM}=$$
$$=\vec{CM}+\vec{BM}+\vec{AM}=\vec{CB}+\vec{BM}+\vec{BM}+\vec{AB}+\vec{BM}=3\vec{BM}+\vec{AB}+\vec{CB}.$$
In another hand, $$\vec{EG}=\vec{ED}+\vec{DI}+\vec{IG}=\vec{AM}+\frac{1}{2}(\vec{DB}+\vec{DC})+\frac{1}{3}\vec{IA}=$$
$$=\vec{AB}+\vec{BM}+\frac{1}{2}(\vec{CB}+2\vec{BM})+\frac{1}{3}(\frac{1}{2}\vec{CB}-\vec{AB})=$$
$$=2\vec{BM}+\frac{2}{3}\vec{AB}+\frac{2}{3}\vec{CB}=\frac{2}{3}\vec{EM}$$ and we are done!
Another way.
Let $EM\cap AI=\{G'\}$.
Thus, since $\Delta AG'E\sim\Delta IG'M,$ we obtain:
$$\frac{AG'}{G'I}=\frac{AE}{MI}=2,$$ which says that $G'\equiv G$ and we are done!
Comment: Thank you for the interesting vector solver. I'm looking for a non-vector solution, which is very difficult.
Comment: I have found another way. See now.
Comment: Thank you so much Michael Rozenberg.
Comment: You are welcome!


EC2 instance not working with Amazon route 53 domain name

Question: I have an EC2 instance running with following details
 - t2.micro
 - virtualization type  = hvm
 - Elastic IP assigned = 54-152-108-137
 - Public DNS assigned = ec2-54-152-108-137.compute-1.amazonaws.com
 - Security group created with following rules/ports enabled
22 tcp 0.0.0.0/0 ✔
80 tcp 0.0.0.0/0 ✔
All All 0.0.0.0/0 ✔
53 udp 0.0.0.0/0 ✔
443 tcp 0.0.0.0/0 ✔
I access the url with public DNS It works fine.
I access the url with public IP. It works fine.
But, I want to access through the domain name which I brought from Amazon route 53.
My domain name is einfachmachen dot ch
Now, I wanted to map this domain to my EC2 running instance
I did the following.

Created a Hosted Zone. (as the one originally created while buying the domain got deleted or so)
Choose Domain Name as my registered domain name = einfachmachen.ch
Type = Private Hosted Zone and chose the VPC id listed in my EC2 console (vpc-24d2a641)
This got created with 2 default record. One with type NS and another with type SOA
Updated the NS record set with the NS addresses from my domain (copied the NS addresses from registered domains in AWS Route 53)
Created a A record for einfachmachen.ch with IPv4 Address and Value = 184.108.40.206
Created a A record for www.einfachmachen.ch with CNAME and Value = ec2-54-152-108-137.compute-1.amazonaws.com

After this, I checked the url with domain name ..
Nothing works.
I get the error in browser as "This page can't be displayed".
I checked if it works with static web pages.
I created 2 Buckets in S3
and provided the A record values as the end-points from S3 buckets.
Then it works.
What is wrong in Ec2 and domain linking?
Answer: A Private Hosted Zone is used to resolve DNS names within a VPC.
Use a public hosted zone if you want to resolve DNS names on the Internet.
See: Working with Private Hosted Zones
Comment: I tried with public hosted zone as well. but, no luck. But, when I try the public hosted zone for S3 static site it works fine. the same domain name gets resolved.
Comment: the output of 'dig +recurse +trace www.einfachmachen.ch any':
Comment: ;; Received 434 bytes from 184.108.40.206#53(184.108.40.206) in 23 ms
einfachmachen.ch. 3600 IN NS  ns-1536.awsdns-00.co.uk.
einfachmachen.ch. 3600 IN NS  ns-1024.awsdns-00.org.
einfachmachen.ch. 3600 IN NS  ns-0.awsdns-00.com.
einfachmachen.ch. 3600 IN NS  ns-512.awsdns-00.net.
;; Received 176 bytes from 220.127.116.11#53(184.108.40.206) in 97 ms
;; Received 38 bytes from 18.104.22.168#53(22.214.171.124) in 6 ms
Comment: Well, it seems to point to your Route 53 configuration, since NSLOOKUP doesn't resolve to an IP address for either of those DNS entries. Start by experimenting with your CNAME record (www.einfachmachen.ch), since NSLOOKUP should resolve it to einfachmachen.ch -- currently it doesn't. Make sure you're using a Public hosted zone. Try resolving it from an EC2 instance to avoid propogation delays. You could even try adding another sub-domain just for testing purposes (eg test.einfachmachen.ch)
Comment: I recreated the public hosted Zone and updated the NS record to 53 hosted Zone. It works now. Thanks


Bloquear Internet Explorer

Question: O IE tem um desempenho muito ruim no meu site.
Não Funcionam as Bordas Arredondada nos botões, e alguns outros defeitos.
Basicamente, o Internet Explorer está sendo Extinto pelo Mozilla Firefox e Pelo companheiro Chrome (Sem contar no Sucessor, o Microsoft Edge, Antes chamado de Spartan).
Eu Gostaria de um Código que detectasse o Navegador, e Se o usuário estivesse usando o IE, Redirecionasse para outra página. Nessa página, eu iria sugerir o Download do Mozilla ou do Chrome
Obrigado.
Comment: Talvez seja melhor utilizar algum *framework* como o [Modernizr](http://modernizr.com/) e tratar esses recursos ao invés de bloquear o acesso. - "Me force a trocar de navegador que nunca mais acesso o seu site, ou melhor, encontro um concorrente que dê suporte ao que eu utilizo".
Answer: JavaScript
Para detetar o IE numa versão <= a 11 acho que podes usar:
if ("ActiveXObject" in window && document.documentMode <= 11){
    alert('é IE <= 11');
    // ou: window.location.href = "http://novo.url"
}

Exemplo: http://jsbin.com/dulisibuqa/1/
O ActiveXObject é uma propriedade só encontrada no IE e o .documentMode indica a versão do IE, e creio que é coerente com pequenas diferênças nas versões mais aintigas em_strict mode_, mas certamente <=11.
PHP
preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
  preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}

if (count($matches) > 1 && $matches[1] <= 11){
    header('Location: http://novo.url'); die();
}

Answer: Para não perder o costume, procure utilizar Frameworks como Bootstrap que trabalham pensando na questão de compatibilidade, o que não faz você ter muito trabalho, e eventualmente lidar com essas coisas chatas, o pessoal já vai fazer isso pra você. Mas em todo caso, abaixo está o código.
if(preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']){
   die('Internet explorer bloqueado.');
}

Para mais informações sobre as funções:

http://php.net/manual/pt_BR/reserved.variables.server.php
http://php.net/manual/pt_BR/function.preg-match.php
Comment: Ao invés de `die` coloque `window.location.href = "http://site.com/bloqueado";`.
Comment: @RafaelAlmeida isso é javascript... e a resposta está em PHP.
Comment: @HugoMarcelo No lugar de `die` coloque `header('Location: /pasta/pagina-escolhida.html'); exit;` :)
Comment: O Que eu gostaria é que ele redirecionasse para outra página.
Comment: Assim vai aparecer apenas um texto.
Comment: __Nota:__ este código pode também bloquear versões >11 do IE.
Answer: A ideia de simplesmente tentar bloquear o Internet Explorer ou redirecionar o usuário para outra página talvez seja muito agressiva para usuários que ainda usam esse browser.
A melhor alternativa mesmo é seguir outro caminho: trabalhar com as limitações do browser e contorná-las sempre que possível. E assim como foi apontado no comentário à sua pergunta, pode-se usar o Modernizr para detectar se o browser suporta as features que você utiliza no seu site.
Tem também a ferramenta Site scan que ajuda a detectar possíveis problemas além de pontos a melhorar no seu site. Isso pode ajudar a fazer seu site a funcionar corretamente em diferentes browsers.
Seguem também alguns artigos que descrevem mais sobre como fazer um site funcionar melhor no IE e também como fazer um site simplesmente funcionar em diferentes browsers.

Bloquear Internet Explorer


Draft-js get mention position in editorState currentContent

Question: I'm using draft-js-mention-plugin and I'm looking for a method that returns the mention position in the whole text (without using indexOf()).
For exemple, I want to get the beginning and the ending positions of piRstone in this sentence :
Welcome to piRstone, our new colleague.
I'm supposed to get 11 for the beginning position and 19 for the ending.

    <Editor
        editorState={this.state.editorState}
        onChange={this.onEditorChange}
        plugins={plugins}
        // placeholder={this.state.placeholder}
        ref={(element) => { this.editor = element; }}
    />
    <MentionSuggestions
        onSearchChange={this.onSearchChange}
        suggestions={this.state.suggestions}
        onAddMention={this.onAddMention}
    />

Here is my onAddMention() method :
onAddMention(object) {
    console.log(object);
}

Maybe there is an easier method to work with but the mentions plugin doc is a bit weak.
Answer: You will get the offset & length of particular mention in entityRanges object of the block, the offset will be the initial index & offset + length of your mention will be the last index
[
  {
    "key": "4p8mh",
    "text": "Nice to meet you #name#",
    "type": "unstyled",
    "depth": 0,
    "inlineStyleRanges": [],
    "entityRanges": [
      {
        "offset": 20,
        "length": 6,
        "key": 0
      }
    ],
    "data": {}
  }
]

By iterating over this object you will get offset & length
Object.keys(content.blocks).map(i => {
         const {entityRanges, text} = content.blocks[i];
         entityRanges.map((range, idx) => {
              console.log(range.offset)
              console.log(range.length)
         });
    });

Answer: In 2022 you can run these in your code to get mentions positions from editorState
 const rawContentState = convertToRaw(editorState.getCurrentContent());
  console.log(rawContentState) <---- this is an object with a key called blocks and key called entityMap. blocks has an entityRanges object with start and end points ;))


Drupal.settings.ckeditor is undefind in CKEditor module

Question: I have installed CKeditor module as per the guidelines of ckeditor README.txt file.
But in neither text area ckeditor is loading.
When I inspected in firebug it shows me following error

Error: TypeError: Drupal.settings.ckeditor is undefined Source File:
  localhost/drupal7/sites/all/modules/contrib/ckeditor/includes/ckeditor.utils.js
  Line: 5

I am wondering is there any problem in configuration?
I have installed and configured CKEditor module previously many times but I haven't encountered such type of error
Comment: Are you installed on same environment as before ? Maybe system is unable to read from directory (file permissions) ?
Comment: Yes. I have enabled in previous Drupal 7 sites. In same Wamp setup, every thing is same
Comment: Try to check server php log if there is an error... or simply try to wipe out and reinstall module... Also there may be another module causing that, see if there is difference there btween this and your other setups
Comment: I reinstalled it three times but no clue.
Comment: It is a JavaScript error. It might be problem with jQuery update module or conflict with some other JavaScript driven module, or settings.
Comment: @HoverFusion: thanks for giving your time. One module which i installed was creating bottleneck.
Answer: Finally I got a clue. I had enabled HeadJs module for improving jquery loading time. This module was creating bottleneck. Just uninstalled this module and work like a charm.


How to get current buildType in Android Gradle configuration

Question: I want to dynamically add a dependency in an Android Gradle project based on the current buildType. I know I can specify the buildType in the dependency:
compile project(path: ':lib1', configuration: 'debug')

But how can I use the current buildType to specify which variant of the library I want to import, so that a debug or release build automatically imports the debug or release variant of the library? What I want is something like this (where currentBuildType is a variable containing the name of the currently used buildType):
compile project(path: ':lib1', configuration: currentBuildType)

The library project I want to import has set publishNonDefault true, so all buildTypes are published.
Comment: possible duplicate of [Build variants in Gradle for a Library Project in Android](http://stackoverflow.com/questions/17451803/build-variants-in-gradle-for-a-library-project-in-android)
Answer: You can use
if (gradle.startParameter.taskNames.contains("assembleExample")) {
    // do stuff
}

That variable will be set before the buildConfig block is evaluated
Comment: @ShellDude That returned an empty list for me but     def isDebug = gradle.startParameter.taskRequests.any {it.args[0].contains("Debug")}
 did the trick
Comment: However, one complaint. This doesn't work when in Android Studio and you just do a rebuild or re-sync your Gradle. There is no task name arguments.
Comment: @JLund More like def isDebug = gradle.startParameter.taskRequests.any { !it.args.isEmpty() && it.args.first().contains("Debug") }
Comment: you should take a look at all of your tasks for the active config to ensure you've got the right task name defined as it has a couple variations depending on how your project is setup. System.out.println(gradle.startParameter.taskNames) should do the trick.  Then look for that task in @Shooky's example above.
Comment: I like that method better... may even convert to it.  I wonder if we're seeing a difference in gradle versions or build config here.   There's probably some subtle difference between taskRequests and taskNames.
Comment: This is the best answer in all of stackoverflow for this. Every other answer tells you to create another task and check a dependency graph and my skin starts to itch, all you need to do is check an argument. Thanks!
Comment: You are a effing genius! I've searched nearly 20 different answers to this same question and this is the only answer that actually makes sense. **UPVOTE THIS TO THE TOP!**
Answer: I could not find a clean way to get the current build type during the configuration phase of Gradle. Instead I define the dependency for each build type separately like that:
debugCompile project(path: ':lib1', configuration: 'debug')
releaseCompile project(path: ':lib1', configuration: 'release')

If you have many build types and many project dependencies this can get very verbose, but it is possible to add a function to make the dependency a one-liner. You need to add this to your main Gradle build file:
subprojects {
    android {
        dependencies.metaClass.allCompile { dependency ->
            buildTypes.each { buildType ->
                "${buildType.name}Compile" project(path: ":${dependency.name}", configuration: buildType.name)
            }
        }
    }
}

Then you can add project dependencies in your Gradle modules like this:
allCompile project(':lib1')

If you also use build flavors you would have to adapt the solution. See this link for a documentation of the feature:
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication
Please note that the Android team is working on an improvement for this behaviour:
https://code.google.com/p/android/issues/detail?id=52962
Comment: Adding your allCompile to my android class works fine, but adding it to my root gradle file doesn't work. It seems that gets applied before the android plugin, and as such it breaks :/
Comment: @neuron Try change `subprojects` to `allprojects`. From docs: 'Configures this project and each of its sub-projects. This method executes the given closure against this project and its sub-projects.'
Comment: As it is not obvious how this works for the combination buildType and flavor, here is the solution: Because the configuration 'ReleaseCompile' or 'DebugCompile' is not known to gradle in the evaluation phase, these have to be added also dynamically:

    allprojects {

        configurations.metaClass.addFlavorConfiguration {
                            def configName = "$flavor.name${buildType.name.capitalize()}Compile";
                            create(configName)
                        }
            }
        }
    }
Answer: Add a task which depends on each assembleXxx task and property setting up after it invoked
ext {
    currentConfig = ""
}
task generateConfigProperty(dependsOn: 'installDebug') {

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->

            def taskName = "taskindicate$output.name"
            task "$taskName"() << {
                project.ext.set("currentConfig", "$output.name")
            }
            output.assemble.dependsOn "taskindicate$output.name"
        }
    }

}

task getConfig(dependsOn: ['installDebug', 'generateConfigProperty']) << {
    println("My config is $currentConfig")
}

took idea from the answer
Comment: +1 Note that if you are using the `com.android.library` plugin, `applicationVariants` is not an accessible property. It becomes `libraryVariants` instead. http://stackoverflow.com/questions/28547203/module-dependency-android-studio
Answer: This one is quite simple:
android {
    applicationVariants.all { variant ->
        variant.buildType.name // this is the value!
    }
}

Edit: Apparently at some point with gradle update, this is not working as I mentioned in a comment below. So I'd recommend checking other options.
Comment: This loops trough all available build types.
Comment: I keep getting the BuildType names in the same order
Comment: Didn't work for me either, with gradle 3.2.1. It always returns the build types in the same order.
Comment: @timkranen if it does, at least the last one in the loop, is the current. For instance, if I run `assembleDebug` it returns "debug" if I run `assembleRelease` it does return Release, which does the job for me!
Comment: I get an error:  **The following model rules could not be applied due to unbound inputs and/or subjects:android.applicationVariants.all { ... }**
Comment: @Reinherd why the last one is the current?  how about gradle assemble? it will call assembleDebug and assembleRelease.
Comment: Doesn't give me the latest- `assembleRelease` is giving me the last variant I defined and not `release`.
Comment: Didn't know that! Then it's a nice solution. Like it more than the accepted answer!
Answer: Based on Shooky's answer and JLund's comment, this is what works for me. I have this code in my app build.gradle towards the end:
ext.getCurrentBuildType = {
    def isDebug = gradle.startParameter.taskRequests.any {
                            it.args.any { it.endsWith("Debug") } }
    return isDebug ? "Debug" : "Release"
}

Just call it afterEvaluate. Example:
afterEvaluate {
    tasks.getByName("externalNativeBuild${ext.getCurrentBuildType()}")
         .dependsOn myOtherTask
}

Apparently, gradle.startParameter has plenty of info about current run. Take a look at the doc.
Comment: @AlexCohn Updated the answer with your suggestion.
Comment: I prefer `it.endsWith("Debug")` to be on the safe side
Answer: // declare a custom task class so you can reuse it for the different
// variants
class MyTask extends DefaultTask {
     String mVariantName;
     public void setVariantName(String variant) {mVariantName = variant;}
     public String getVariantName() { return mVariantName; }
     @TaskAction
     void action(){
        // do stuff
     }
}

// put this after your `android{}` block.
android.applicationVariants.all { variant ->
    def taskName = "myTask_$variant.name"
    task "$taskName"(type: MyTask) << {
        // you can setup this task to various info regarding
        // variant
        variantName = variant.name
    }
    variant.assemble.dependsOn (taskName)
}

See Advance customization for more details of what you can extract from the variant variable.
now you it will properly hookup your MyTask into to the chain. Doing it this way should also cleanly handle building multiple flavors all at once as it creates a new instance of MyTask for each variant.
Answer: The idea of executing a certain code based on the environment should be through dependency injection.

Take into account to use the following declaration only for exceptional configurations because in general it should not happen that in the code there are conditionals that make references to the environments.
build.gradle
android {

    def TRUE = "true"
    def FALSE = "false"
    def IS_DEV = "IS_DEV"
    def IS_RELEASE = "IS_RELEASE"

    defaultConfig {
        //...
        buildConfigField BOOLEAN, IS_DEV, FALSE
        buildConfigField BOOLEAN, IS_RELEASE, FALSE
    }

    buildTypes {
        debug {
            buildConfigField BOOLEAN, IS_DEV, TRUE
        }
        release {
            buildConfigField BOOLEAN, IS_RELEASE, TRUE
        }
    }

}

GL
Answer: Running Gradle task 'assembleRelease'...
Comment: Please consider adding links and statements to the comments.


Delete duplicates records from DB Laravel

Question: I'm trying to eliminate duplicates from a table but the query I'm using deletes the entire database and not the duplicates, can you tell me why and what I can do? Thank you very much in advance to the whole community..
This is code
<code>$ids = EsitiAudit::
groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])->get(['id'])->all();

EsitiAudit::whereNotIN('id', $ids)->delete();

</code>
Comment: well id is not in groupBy which will cause issues on some databases, ex : `SQLSTATE[42000]: Syntax error or access violation: 1055 'id' isn't in GROUP BY`
Answer: You're passing complete elements to the <code>->delete()</code> query, try this instead:
<code>$esitiAudits = EsitiAudit::groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])->get(['id']);

$ids = $esitiAudits->pluck('id')->toArray();

EsitiAudit::whereNotIn('id', $ids)->delete();
</code>
Pick just the ids from the elements on the query and then delete the files.
Comment: So doesn't the `pluck()` extract values from the `id` column, and it doesn't take into account the grouping of columns. Then shouldn't the first line be `select()->groupBy()->get()` and then you can use the `pluck()`. I am understanding this wrong?
Comment: @Adi Im not retrieving the ID from the table column to pass it to `pluck()`, the IDs are generated by the groups of elements made by `groupBy`, so each group will have a unique ID, then `whereNotIn()` ensures that one row of the duplicated are retained, by eliminating the one with the lower ID number.
Comment: Oh okay thanks for clarification.
Comment: You can use `::select()->groupBy()->get()` but that will be like another entire line of code with all the elements again, and select the lowest `id` to pass it into `pluck()`, but I think it's cleaner this way.
Comment: No worries i think i understood how your solution works too since they are many ways of doing, so upvoted. It's just confusing sometimes as to how pluck works with groupby function.
Answer: <code>$ids = EsitiAudit::select('id')
->groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])
->havingRaw('COUNT(id) > 1')
->get();

$idsToDelete = $ids->pluck('id')->toArray();

EsitiAudit::whereNotIn('id', $idsToDelete)->delete();
</code>

we have to check whether the id is present multiple times or not by checking the count.
Next, we use pluck('id') to extract the id values from the result.
we use whereNotIn with the extracted idsToDelete to delete the duplicate rows that are not in the list of IDs to keep.
Comment: That way you'll end deleting every row that doesn't have a duplicated `id`, and keep just 1 of the duplicated ones. On a normal use, where the `id` is set to `auto_increment`, you'll never have duplicated ID on the table. That will just empty the entire table...


Probability that an observed variable is greater than zero

Question: I observe a variable $\hat{x}$. I know that my observation is noisy due to some Gaussian measurement noise $\mathcal{N}(0, \sigma)$.
My goal is to compute the probability $p(x > 0\mid\hat{x})$ that the true underlying $x \in \mathbb{R}$ is positive. The a priori probability of any $x$ is unknown, i.e. the prior distribution is assumed to be flat.
Also assume I know $\sigma$ precisely. What is $p(x > 0\mid\hat{x})$?
Answer: We can find the posterior distribution of $x$:
$$p(x|\hat x)\propto p(\hat x|x)p(x)\propto\exp\left[-\dfrac{(x-\hat x)}{2\sigma^2}\right]\Rightarrow x\sim\mathcal N(\hat x, \sigma^2)$$
Since $x|\hat x$ is normal, we can easily calculate $p(x>0|\hat x)$ using the standard normal CDF, $\Phi$:
$$p(x>0|\hat x)=1-\Phi\left(\dfrac{0-\hat x}{\sigma}\right)=\Phi\left(\dfrac{\hat x}{\sigma}\right)$$
Notice that, in this case, this happens to be the same as one minus the p-value for the frequentist Z-test for $x>0$.
Comment: Thanks, much appreciated!


"strong stationary process" equivalent to a process with "indentically distributed" random variables?

Question: I want to know if a strong stationary process is equivalent to a process with identically distributed RVs.
In another words : if A is the set of s.s.s processes and B is the set of processes with identically distributed RVs, is it true that A = B ?
Comment: What do you mean by an "identically distributed process"? That $X_1,X_2,\dots$ all have the same distribution?
Comment: Yes they have the same distribution
Comment: If I am not mistaken i.i.d processes are a subset of s.s.s processes set. I wanted to know what is the processes other than i.i.d ones that forms the set of s.s.s processes
Comment: I was thinking that since the s.s.s processes are characterised by random variables that have the same CDFs, then these random variables are identically distributed.  Is this correct?
Answer: No, they are not the same. In a strong stationary process $(X_1,X_2,\dots)$ it is the case that all of the $X_n$'s have the same distribution. However, the converse does not hold.
To see why, take $X_2,X_3,\dots$ to be IID (whatever distribution you like, but not constant), and $X_1=X_2$. Then all of these terms are identically distributed, but this is not a strong stationary sequences because, for instance, $(X_1,X_2)$ is not equal in distribution to $(X_2,X_3)$.
Comment: @starriet No, an IID process *is* a strong stationary process. For your second question, $\mathbb{P}(X_1=X_2)=1$ while $\mathbb{P}(X_2=X_3)<1$ since $X_2$ and $X_3$ are independent and not constant.
Comment: @starriet Yes, every strong stationary process is a sequence of identically distributed RVs, but not every sequence of identically distributed RVs is a stationary process. If you add the condition that the sequence is *independent* (so an IID process), then it is a stationary process. But not every stationary process is an IID process.
Comment: Thanks this is clear. Can you give me an example of a strong stationary process that is not an IID process ?
Comment: I think it should work to take $X_1 \sim N(0,1)$, and define $X_n = X_1$ if $n$ is odd, and $X_n=-X_1$ if $n$ is even. This should be a strong stationary process, but it's not IID.
Comment: Do you mean an i.i.d. random process is _not_ a strict stationary random process? And what do you mean by "(X1, X2) is not equal in distribution to (X2, X3)"? Why aren't they equal even if all Xs have identical probability density/mass functions?
Comment: So, any "strong(strict) stationary process" _is_ an "identically distributed" process, but not vice versa, right? (The first paragraph of the answer is a little bit confusing) Thanks! :)


Compute ANOVA F if you only know post-hoc results

Question: It's not uncommon to read a scientific article in which the authors perform an ANOVA followed by post-hoc t-tests, but don't report the results of the ANOVA at all, and instead skip straight into the results of the post-hoc t-tests. Assuming all post-hocs are reported, is there any way that a reader could back-calculate the results of the ANOVA? For simplicity, let's say it's a 2-way ANOVA.
Edit here is an example:
Load data
library(palmerpenguins)
library(emmeans)

data(package = 'palmerpenguins')
dat = penguins

Categorical x continuous interaction
model1 = lm(body_mass_g  ~ species*flipper_length_mm ,data=dat)
# anova
anova(model1)
Analysis of Variance Table

Response: body_mass_g
                           Df    Sum Sq  Mean Sq F value    Pr(>F)
species                     2 146864214 73432107 534.660 < 2.2e-16 ***
flipper_length_mm           1  24776495 24776495 180.398 < 2.2e-16 ***
species:flipper_length_mm   2   1519564   759782   5.532  0.004327 **
Residuals                 336  46147424   137344
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# post-hoc tests
res1 = emtrends(model1, pairwise ~ species, var = "flipper_length_mm")
res1$contrasts
 contrast           estimate   SE  df t.ratio p.value
 Adelie - Chinstrap    -1.74 7.86 336  -0.222  0.9733
 Adelie - Gentoo      -21.79 6.94 336  -3.139  0.0052
 Chinstrap - Gentoo   -20.05 8.19 336  -2.448  0.0394

P value adjustment: tukey method for comparing a family of 3 estimates

Categorical  x categorical interaction
model2 = lm(body_mass_g  ~ species*sex,data=dat)
# anova
anova(model2)
Analysis of Variance Table

Response: body_mass_g
             Df    Sum Sq  Mean Sq F value    Pr(>F)
species       2 145190219 72595110 758.358 < 2.2e-16 ***
sex           1  37090262 37090262 387.460 < 2.2e-16 ***
species:sex   2   1676557   838278   8.757 0.0001973 ***
Residuals   327  31302628    95727
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# post-hoc tests
res2 = emmeans(object = model2, pairwise ~ species|sex)
res2$contrasts
sex = female:
 contrast           estimate   SE  df t.ratio p.value
 Adelie - Chinstrap     -158 64.2 327  -2.465  0.0377
 Adelie - Gentoo       -1311 54.4 327 -24.088  <.0001
 Chinstrap - Gentoo    -1153 66.8 327 -17.246  <.0001

sex = male:
 contrast           estimate   SE  df t.ratio p.value
 Adelie - Chinstrap      105 64.2 327   1.627  0.2357
 Adelie - Gentoo       -1441 53.7 327 -26.855  <.0001
 Chinstrap - Gentoo    -1546 66.2 327 -23.345  <.0001

P value adjustment: tukey method for comparing a family of 3 estimates

In either case, is it possible to compute any of the ANOVA results, using only the post-hoc test results?
Comment: Please post an example dataset.csv, some (simple!) ANOVA results, and t-test results. If you also include the code you used, that would be helpful to folks responding.
Comment: I've added some examples.
Answer: In principle, this may be possible if you have a completely randomized design. When there are blocks, pairing, or mixed effects, it gets harder or impossible.
Simplest case is with a table of cell means and their standard errors:
> emmeans(model2, ~sex*species)
 sex    species   emmean   SE  df lower.CL upper.CL
 female Adelie      3369 36.2 327     3298     3440
 male   Adelie      4043 36.2 327     3972     4115
 female Chinstrap   3527 53.1 327     3423     3632
 male   Chinstrap   3939 53.1 327     3835     4043
 female Gentoo      4680 40.6 327     4600     4760
 male   Gentoo      5485 39.6 327     5407     5563

Confidence level used: 0.95

Then you can use the emmobj function to construct an emmGrid object:
> eobj = emmobj(c(3369,4043,3527,3939,4680,5485), V=diag(c(36.2,36.2,53.1,53.1,40.6,39.6)^2),
+     levels = list(sex=c("f","m"), species=c("a","c","g")), df = 327)

> eobj # shows same table as before
 sex species estimate   SE  df lower.CL upper.CL
 f   a           3369 36.2 327     3298     3440
 m   a           4043 36.2 327     3972     4114
 f   c           3527 53.1 327     3423     3631
 m   c           3939 53.1 327     3835     4043
 f   g           4680 40.6 327     4600     4760
 m   g           5485 39.6 327     5407     5563

Confidence level used: 0.95

> joint_tests(eobj)
 model term  df1 df2 F.ratio p.value
 sex           1 327 311.580  <.0001
 species       2 327 747.804  <.0001
 sex:species   2 327   8.735  0.0002

This is comparable to the Type III anova for the model:
> joint_tests(model2)
 model term  df1 df2 F.ratio p.value
 species       2 327 746.924  <.0001
 sex           1 327 311.838  <.0001
 species:sex   2 327   8.757  0.0002

But the anova you show is the Type I (sequential) anova, and you can't get that from eobj.
Now, with only the pairwise comparisons shown in the illustration, you do't have any information about the sex effects or sex:species effects. If you had also the results for pairwise comparisons of sex for each species, I think it may be possible to cobble a table of means and SEs, though with a different grand mean, by arbitrarily setting one of the cell means to zero and working from there. But it gets messy because each SE you see is $\sqrt{1/2}$ times the square root of the sum of two cell variances. In principle, it's possible to work through this but it won't be fun.
It is not possible to do the anova for model1 where we have comparisons of slopes. Again it may be possible if we know the slope estimates themselves, and some kind of information about the interaction. But it would be very ugly.
Again, I emphasize these ideas won't work for mixed models or others where cell means are in any way correlated.


MongoDB-Express::ENOTDIR: not a directory,...gssapi.js/package.json

Question: I am using mongodb in my express-js project. I am trying to run the server in vs code but it is throwing errors with the npm packages. It works fine with Webstorm and from command-line.
Error: ENOTDIR: not a directory, stat '/home/user/Workspace/Project1/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js/package.json'
    at Error (native)
    at fs.existsSync (fs.js:219:13)
    at find_package_json ('/home/user/Workspace/Project1/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js:13:9)
    at require_optional ('/home/user/Workspace/Project1/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js:37:18)
    at Object.<anonymous> ('/home/user/Workspace/Project1/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js:27:14)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)

I have tried installing packages many times and updated npm itself but could not fix it. Can someone please advise how to fix this? Thanks.
This is my package.json file.
{
  "name": "Project 1",
  "version": "1.0.0",
  "description": "Project 1 apis",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "license": "BSD-2-Clause",
  "dependencies": {
    "body-parser": "^1.17.2",
    "connect-multiparty": "^2.0.0",
    "cookie-parser": "^1.4.3",
    "csvtojson": "^1.1.7",
    "express": "~4.14.0",
    "moment": "^2.18.1",
    "mongodb": "^2.2.31",
    "mongoose": "^4.11.6",
    "mongoose-double": "0.0.1",
    "morgan": "^1.8.2",
    "static-favicon": "^2.0.0-alpha",
    "uniqid": "^4.1.1"
  }
}

Comment: at the time of `npm install` ?
Comment: No, but when running the server in vs code. It works fine with Webstorm and from command line.
Comment: select the correct terminal from the drop down, and run it again
Comment: Did you ever solve this, by trying a another terminal?
Comment: @DauleDK Yes, I got around it, I cleaned up the package files and reinstalled. It didn't work at first so I reinstalled latest versions of npm and node. It seemed like the best thing to do.
Comment: and what launch configuration did you end with using?
Comment: { "version": "0.2.0", "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/bin/www"
        }
    ]
}
Comment: @DauleDK Its the default one, I never had to make a change here.
Comment: Ok - I keep getting the same error, so created a new question.
Answer: I had the same problem.
I solved it by just removing sources from disk, cloned repo to another folder, install all packages and then it starts working.
Hope that will help you.


Using Styles and in CSS

Question: I'm very new to CSS and trying not to create more styles than I need but getting a bit caught up when trying to apply multiple things to one element.
Basically I have a document with 10 chapters I'm using CSS to create output for. Each chapter looks the same but has different coloured headings and headers and footers.  So I created a generic class for each chapters colour and have applied that to the headings in the relevant chapters (eg, h1.Operation applies the Operation chapter colour to the heading 1 style).
But then I needed style to right align the header so I created that style (eg, td.RightAlignHeaderFooter) but now I can't apply the chapter colour using the generic class for the chapter.
Basically, I'm trying to avoid creating 10 identical styles where the only difference is the colours. Is using a generic class the right way to go about this?
Answer: Yes, using generic class is right way to use CSS classes.

.header-red {
  color: red;
}

.header-blue {
  color: blue;
}

.align-right {
  text-align: right;
}

.align-center {
  text-align: center;
}

TEXT

TEXT

TEXT

TEXT

Using Styles and in CSS


cov(A,1) equivalent in R

Question: in the matlab documentation there function cov(A,1),where A is a matrix, is used to compute the covariance normalized by the number of rows. what is the equivalent of cov(A,1) in R? thank you.
Comment: divide by the number of rows after calculating cov? `ans <- cov(A); ans / nrow(ans)`
Comment: could you define what it means to normalize by the number of rows?
Comment: @chinsoon12 it's not that. it give different result with the one in matlab
Comment: @TUSHAr as stated in [here](https://www.mathworks.com/help/finance/cov.html) cov(X, 1) or cov(X, Y, 1) normalizes by N and produces the second moment matrix of the observations about their mean
Answer: Just use cov(A). Don't complicate things. A co-variance matrix is automatically normalised by the number of records
Comment: Thanks for your answer, but i still need the `cov(A,1)` to match the output of some function in matlab and R. and i've got the answer in https://stackoverflow.com/questions/3256798/why-does-matlab-native-function-cov-covariance-matrix-computation-use-a-differ?rq=1
Answer: apparently,
A = A-matrix(1,T,1) %*% colMeans(A)
covmat = Conj(t(A))%*%A/T
where T is number of rows will give the same output with matlab cov(A,1), thanks everyone.

cov(A,1) equivalent in R


Mudança de um false para true com Vuex e Axios

Question: Atualmente tenho uma estrutura com Nuxt e Vuex no projeto, á um objeto que vem diretamente de uma Api e preciso fazer ele trocar o estado de "false" para "true" caso a API retorne ele como true, assim ele irá exibir 1 campo no menu, porem no vuex ele está salvando no localstorage e não á essa troca de estado.
Codigo do vuex
state: {
user: {},
}
actions: {
  async betaUpdate(context, user) {
    const usuario = (await Axios.get(`http://api-interna/me/${usuarioId}`)).data
  }

dentro de user eu recebo informações como
beta: user.beta, betachart: user.betachart,
porem nessa minha API quero verificar se internamente sempre que houver uma atualização nesses dois campos e mudar o valor de false deles para true caso a API retorne true,
no VUE coloquei um mapActions, chamando a action porem não consigo(não estou sabendo) fazer a mudança caso haja um retorno TRUE da Api a cima.
Answer: O fluxo correto seria sempre alterar o state a partir de uma mutation, no caso a partir do context na action tu tens acesso as mutations (através da função commit), e aí na tua mutation mudaria o estado
state: {
  minhavar: false
},
mutations: {
  alteraMinhaVar(state, valor) {
    state.minhavar = valor
  }
},
actions: {
  async chamaAPI (context) {
    ...request
    context.commit('alteraMinhaVar', valorRetornadoPelaAPI)
  }
}

Comment: Problema ainda permanece porque, eu recebo no meu State.user um usuer: {} porque ele está vazio, recebo ele depois de algum tempo e quando faço a chamada do ...mapState(["betaChange"]), no componente ele sobre escreve e logo mantem ele vazio.

Eu teria que isolar ou capturar somente esses dois campos Beta e betaCharts para modificar somente eles, e não consigo fazer essa intervenção somente nesses dois campos sem remontar o objeto inteiro


RHEL 8 extend iSCSI LUN without reboot

Question: In short: I´m building computer systems with mounted iSCSI storage. Is it possible to extend the iSCSI storage in live operating without rebooting the systems?
Details:

One LUN is planned with 5 TB of data.
For the beginning we want to start with 600 Gigabyte for the LUN.
The LUN is used for database systems.
We don't want to create a LUN with 5 TB. We want to keep them small, what gives us flexibility in moving storage.
We are using device-multipathing with two nodes.
I have created a lvm (with XFS) that gives the flexibility of merging the LUN´s and should allow for expansion in live operation.

About the last point I´m not sure and wanted to ask for other experiences in RHEL8 with GPDB and iSCSI.
Comment: It is not clear who provide this LUN, RHEL? or some SAN storage? Draw the schema.
Comment: The LUN will be provided by NetApp SAN. One problem is that the metro cluster is already on his edge. It will be extended in the future :)
Answer:
Is it possible to extend the iSCSI storage in live operating without
rebooting the systems?

Yes, very easily - simply extend the LUN at the Target end and run a scsi refresh. That should allow your client machine to see the extended LUN - if you've used LVM you can simply vgextend/lvextend and grow the filesystem.
That said what's wrong with simply using thin provisioning at the Target end and creating the LUN as 5TB one day-one - that way you won't ever need to extend it but also only store the data that's actually written?
Comment: Thank you for the quick reply. I would use thin provisioning. One problem is that the Target (NetApp) is already relatively full. I want to create small LUN´s to provide flexibility in moving the LUN´s and concatenate them with LVM. Will my plan influence the IOps?
Comment: Probably not no
Comment: Before `vgextend/lvextend` you need to run `lvextend` to update LVM about the new size or this "disk"
Answer: You can provision on NetApp this LUN via thin provisioning to full size and it will extend as RHEL request more space in this LUN. So not need to play this game with extending.

RHEL 8 extend iSCSI LUN without reboot


Como implementar o cordova-plugin-accountkit no meu projeto cordova?

Question: pesquisei por exemplos mas não achei nada pra elucidar minha dúvida, não tenho experiência com cordova (talvez por isso não saiba usar o cordova-plugin-accountkit).
esse é o código do arquivo index.js (praticamente do jeito que foi baixado):
var app = {
// Application Constructor
initialize: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},

// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
    this.receivedEvent('deviceready');
},

// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);

//código do account kit que eu não sei o que fazer com ele

    loginWithPhoneNumber: function(options, onSuccess, onFailure) {
        options = {
            defaultCountryCode: "BR",
            facebookNotificationsEnabled: true,
            initialPhoneNumber: ["55", "123456789"]
        };
        function sucess(params){
            console.log(params);
        }
        function failure(params){
            console.log(params);
        }
        AccountKitPlugin.loginWithPhoneNumber(options, onSuccess, onFailure);
    },

   },
};

app.initialize();

só queria saber como deve ficar meu arquivo index.js e como chama-lo no index.html
Answer: Resolvi mudando o plugin usei este e só precisei da documentação;
https://www.npmjs.com/package/cordova-plugin-facebook-account-kit
deixei a minha pergunta aqui caso alguém encontre o mesmo problema.
Comment: Marque a resposta como uma solução para o problema... =D


Show Euclidean plane with usual topology is not compact

Question: I need to show an open cover with no finite subcover.
My try
I assume Euclidean plane with usual topology deals with open sets/intervals.
So
Let A=(a,b). Let $G_n$:=(a-(1/n),b) for each
n$\in $N then A =$\bigcup_{r=1}^{\infty}G_n$. So
G is an open cover for A
. Let {$G_{n_1},G_{n_2}$,…,$G_{n_k}$ } be
a subcollection of $G_n$ .Take
K=max{$n_1,n_2$,…,$n_k$ }
then $\bigcup_{r=1}^{K}$ $G_{n_r}$= $G_n$ =(a-($1$/K),b)
Since $a-(1$\K)$\in$ A$\notin$ $G_K$ ,no finite subcover can be found.
Therefore A is not compact.
I hope I solved it.
Any feedback would be appreciated.
Comment: This argument successfully shows that an open interval on a line is not compact. This is not the same as showing the whole Euclidean plane is not compact. For this you need to display an open cover of the whole plane with no finite subcover
Comment: Ok, so I have to use disks say $B_r$($0$) as a cover of E. Take a sub collection {$B_{r_0}(0),…,B_{r_k}(0)$} The union of subballs is the original ball.,so no finite subcover exists?
Comment: That's basically it. I'm not sure what you mean by "the original ball.". You need to cover the whole Euclidean space by, for example,  the collection of balls $B_r(0)$ where $r=1,2,3,.....$. This clearly has no finite subcover.
Comment: I did that .Thanks
Answer: Consider a family of open sets $$U_n =\{(-n,n): n \in \mathbb{N}\}$$
$$\mathbb{R}=\cup_{n \in \mathbb{N}}(-n,n)$$
But this open cover has no finite subcover.
Comment: I used this prove R is not compact...Thanks


Revelando os caracteres certos - jogo da forca

Question: Estou criando as funções antes de montar o jogo em si, e travei na parte de revelar os caracteres. Na minha função, eu quero receber uma palavra em string, essa mesma palavra oculta no formato ' ___ ' e uma letra.
Com isso eu recebo a string com os valores revelados, mas ela só revela o primeiro índice com a letra certa. Como eu posso consertar isso?
def revelando(string, string_oculta, letra):

    for i in range(len(string)):
    if string[i] in letra:
        return  string_oculta[:i] +string[i] + string_oculta[i+1:]

o que esta acontecendo:
entrada: revelando('amar',['_ ','_ ','_ ','_ '], 'a')
retorno: ['a', '_ ', '_ ', '_ ']
Answer: palavra = "amar"

def jogo_forca():
    letras_ocultas = ["_"] * len(palavra) # Troca as letras por "_".
    palavra_para_letras = list(palavra) # Cria uma lista com as letras da palavra.
    usadas = [] # Lista com as letras que já foram usadas pra não ficar sem mostrar nada.
    while palavra_para_letras.count("$") != len(palavra): # Enquanto ainda houver letras e não $ vai continuar pedindo.
        print(f"|- {''.join(letras_ocultas)}") # Mostra a palavra atualizada mas como str e não como lista
        print("__--__" * 10) # Perfumaria pra não ficar tudo junto.
        letra = input("Digite uma letra: ") # Pede a letra .
        if letra not in usadas: # Verifica se a letra já não foi usada, se foi mostra a mensagem e volta a pedir uma letra.
            usadas.append(letra)
        else:
            print(f"A {letra} já foi usada")
            continue
        quantidade_letras = palavra_para_letras.count(letra) # Pega a quantidade de vezes que a letra está dentro da lista exemplo amar = 2.
        if quantidade_letras: # Verifica se a há alguma letra como no python 0 == False eu não preciso colocar > 0 pois se for 0 é Falso.
            for _ in range(quantidade_letras): # roda o loop pela quantidade de letras que foi encontrada na palavra exemplo: se usar a letra "a" vai fazer o loop 2x.
                index = palavra_para_letras.index(letra) # Pega o index que a letra aparece exemplo : letra "a" vai pegar o index 0 no primeiro loop e 2 no segundo AMAR -> 0123.
                palavra_para_letras[index] = "$" # Troca a letra por "$" assim fica mais fácil ter um controle, pois se apagar muda o index da lista.
                letras_ocultas[index] = letra # Troca "_" pela letra encontrada

    print(f"Parabéns você acertou a palavra: {palavra}") # Fim do While e acaba o programa.

jogo_forca()

Não tive muito tempo de testar mas acredito que isso possa te dar uma luz.
Comment: Você precisa colocar uma letra ou um atalho pra parar o while.
Comment: caraca, ficou muito bom! muito obrigada!