Property of short exact sequences.

Question: If $0 \to L \to M \to N \to 0$ is a short exact sequence of $A$-modules then the following statements are equivalent:

There is an isomorphism $M \cong L \oplus N$ under which $L \to M$ is given by $m \mapsto (m, 0)$ and $M \to N$ by $(m, n) \mapsto n$.
There exists a section of $M \to N$.

I understand that the condition "there is an isomorphism $M \cong L \oplus N$" is much weaker than the condition 1. above, so

I wonder if there are some simple $M, L$ and $N$ such that $M \cong L \oplus N$, but there is no section of $M \to N$.
Comment: The section should be $N\to M$.
Comment: @ArnaudD. section **of** $M \to N$ means a map $N \to M$ such that...
Comment: @user374573 That's weird...but I guess it is possible. Whose definition of "section" is that?
Comment: @user374573 I hadn't noticed that "of", that makes more sense.
Comment: @DonAntonio I know it from M. Reid's "Commutative Algebra"
Comment: @user374573 In 2.10, page 45 of Reid's "Undergraduate Commutative Algebra" I read " a section $\;N\to M\;$" , not the other way around. Now, the section is of **the map** $\;\beta:M\to N\;$ , which really makes sense.
Comment: @DonAntonio looks like a legitimate form of verbiage. I see no difference in "the section of the map $\beta: M \to N$" and "the section of $M \to N$"
Comment: @user374573 Perhaps, but the fact is it caused a little confusion among, at least, two of us, mathematicians with advanced degrees. Of course, it is only a matter of agreement, yet Reid uses it the way I wrote you above.
Comment: @DonAntonio thank you. I will take this into account in the future.
Comment: @user374573 In your question, do you mean whether there are $\;M,L,N\;$ s.t. $\;M\cong L\oplus N\;$ **and also in the corresponding place in an exact sequence** ? Or already without the exact sequence requirement?
Comment: @DonAntonio also in the corresponding place in the exact sequence. I just want an example which shows, that a weaker version of statement 1. does not imply 2.
Comment: @user374573 If I understand you correctly, that is impossible as conditions (1)-(2) are *equivalent*...and also equivalent to "there's a section $\;M\to L\;$" , which is even less used.
Comment: @DonAntonio what is impossible? Yes 1. and 2. above are equivalent, but I want to make  statement 1. a bit weaker and show (by an example) that it does not imply 2.
By "a bit weaker" I mean taking "$M \cong L\oplus N$" instead of "$M \cong L\oplus N$ under which $L \to M$ is given by $m \mapsto (m, 0)$ and $M \to N$ by $(m, n) \mapsto n$".
Comment: @user374573 Oh, I see. But I think that to make some sense all this it should be somehow related to the maps that make  the short sequence short shouldn't it?
Comment: @DonAntonio Yes, $ \{0\} \to L \to M \to N \to \{0\} $ must be a s.e.s.
Answer: That's a great question!
Usually counterexamples are already easy to find for $\mathbb{Z}$-modules (also known as abelian groups), but sadly, in this case, if you look only at finitely generated abelian groups, then any short exact sequence
$$0 \to A' \to A \to A'' \to 0$$
with $A \cong A'\oplus A''$ is actually split. (It is possible to see it by revising the classification of finitely generated abelian groups and calculations of the Yoneda $\operatorname{Ext}^1_\mathbb{Z} (A'',A')$.)
So we need to look for counterexamples among abelian groups that are not finitely generated. Maybe the easiest is the following. Take an infinite direct sum of copies of $\mathbb{Z}/n\mathbb{Z}$ and consider the map
\begin{align*}
p\colon \mathbb{Z} \oplus \bigoplus_{i \ge 0} \mathbb{Z}/n\mathbb{Z} & \twoheadrightarrow \bigoplus_{i \ge 0} \mathbb{Z}/n\mathbb{Z},\\
(x,y_0,y_1,y_2,\ldots) & \mapsto (x \mod{n}, y_0, y_1, y_2, \ldots).
\end{align*}
This is not the projection, but this is a surjective homomorphism, and we have a legitimate short exact sequence
$$0 \to \mathbb{Z} \xrightarrow{x \mapsto (n x, ~ 0,0,0,\ldots)} \mathbb{Z} \oplus \bigoplus_{i \ge 0} \mathbb{Z}/n\mathbb{Z} \xrightarrow{p} \bigoplus_{i \ge 0} \mathbb{Z}/n\mathbb{Z} \to 0$$
But you can see that $p$ doesn't have a section.
Comment: Someone already marked this question as a duplicate of another one, having... an identical answer :'( I copied mine from my homological algebra notes, and I think it is hard to come up with something easier.
Comment: Thank you, that is a great answer :)
Answer: How about taking
$$ 0 \to \Bbb Z/2 \Bbb Z \to \Bbb Z/2 \Bbb Z $$
and
$$ \Bbb Z \xrightarrow{\cdot 2} \Bbb Z \to  \Bbb Z / 2 \Bbb Z. $$
Both are short exact. But if you take the countable direct sum of both then the middle term is the direct sum of the both other terms, but there is no section.
Comment: Nonse of these two short sequences seem to comply with the OP's intention. Read last comments below the question.
Comment: @DonAntonio I want to combine both s.e.s. via direct product to a s.e.s. with $L=\bigoplus_{\Bbb N} \Bbb Z $, $N=\bigoplus_{\Bbb N} \Bbb Z/ 2 \Bbb Z $ and $M = \bigoplus_{\Bbb N} (\Bbb Z\oplus \Bbb Z/ 2 \Bbb Z)$. Since the second s.e.s. does not split the resulting sequence does not split. Where is my error?
Comment: Both s.e.s in the OP begin and end with zero , and thus the middle maps are injective/surjective resp. (from left to right) .
Comment: @DonAntonio Those too?
Comment: @DonAntonio Decorate the formulas above with "$0\to$" and "$\to 0$" :-)

Property of short exact sequences.


ScrollTop não funciona após certa rolagem

Question: Tenho uma div chamada busca, quero que após o ScrollTop 100, ele fique fixo.
Não está funcionando.
var $w = $(window);

$w.on("scroll", function(){
   if( $w.scrollTop() > 100 ) {
        $('busca').css("position", "fixed");
   }
   else{
        $('busca').css("position", "static");
   }

});

Comment: Pera, seu elemento não chama busca... Não falta um ponto antes? ou uma hashtag? Tipo $('#busca').css("position", "fixed"); ???
Comment: Felipe acho que da pra resolver isso só com CSS, a não ser que vc quera mesmo usar jQuery... Se quiser posto um exemplo simples pra fazer isso com 5 linhas de CSS...
Comment: @DiegoSantos era isso sim.
Comment: Aparece algum erro no console? Tenta pegar o valor do scrollTop e dar um console e vê o resultado...
Comment: @DiegoSantos inclui o console.log no if e ele retornou certo. console.log("Maior que 100");
Comment: @hugocsl pode ser sim
Answer: Seu codigo possui alguns erros
primeiro  sue selector busca deve ser um ID ou Class então deve ser "#busca" ou ".busca"
segundo variaveis em  javascript não tem $ então o codigo deve ficar assim
var w = $(window);

w.on("scroll", function(){
   if( w.scrollTop() > 100 ) {
        $('.busca').css("position", "fixed");
   }
   else{
        $('.busca').css("position", "static");
   }

});

EDIT
Talvez funcione melhor assim definindo  top:0 z-index um nivel  a cima dos demais
    var w = $(window);

w.on("scroll", function(){
   if( w.scrollTop() > 100 ) {
        $('.busca').css({"position":"fixed", "top":"0px","z-index":"1"});
   }
   else{
        $('.busca').css({"position": "static"});
   }

});

Comment: Provavelmente esta correto!
Comment: Vc chutou e acertou, mas ele poderia estar usando uma tag personalizada e o lance da variável com $ não influi em nada. :/
Answer: Conforme mensionado no comentário, e dentro do que eu entendi da pergunta, acho que esse exemplo com CSS pode te ajudar caso não pretenda usar o jQuery etc.
Nesse exemplo o elemento está a 100px do topo, e quando vc der o scroll ele vai parar a 50px do topo. Deixei os comentários no código.

body {
    height: 200vh;
}
.teste {
    background-color: red;
    width: 100px;
    height: 50px;
    margin-top: 100px; /* altura que está do topo */
    top: 50px; /* altura que vai parar antes do topo */
    position: sticky;
}


If five coins are flipped simultaneously, find the probability of each of the following:

Question:
If five coins are flipped simultaneously, find the probability of each of the following:
(a) At least one coin lands heads;

My answer:$\frac{2^5 -1}{2^5}$. I took the complement for the numerator.

(b) At most one coin lands heads.

My answer: $\frac{6}{2^5}$. I counted how many times heads appears $1$ or $0$ times.
Is this correct?
Answer: Good job!!
For part a, notice that this is the OPPOSITE of (no coin lands heads <=> all coins land tails), which is $\displaystyle \left(\frac12 \right)^5=\frac{1}{32}$ chance.
For part b, any $5$ of the coins can land heads, if in total one coin lands heads. If no coin lands heads, that can be done in $1$ way. That is $\displaystyle \frac{6}{32}=\frac{3}{16}$ chance.
In general, take a look at the binomial distribution.
Comment: For this homework we have to assume we don't the binomial distribution or any combination numbers.
Comment: Alright! Then just count the ways to pick k coins to be heads, from n coins.
Answer: Your answers are correct. In terms of notation I would use the binomial distribution, where the probability of $k$ successes out of $n$ attempts equals:
$${n \choose k} p^k (1-p)^{n-k}$$

The probability of at least one heads equals 1 minus the probability of no heads:
$$1 - {5 \choose 0} \bigg(\frac{1}{2}\bigg)^0 \bigg(\frac{1}{2}\bigg)^5 = 1 - \frac{1}{32} = \frac{31}{32}$$
The probability of having at most one heads equals:
$${5 \choose 0} \bigg(\frac{1}{2}\bigg)^0 \bigg(\frac{1}{2}\bigg)^5 + {5 \choose 1} \bigg(\frac{1}{2}\bigg)^1 \bigg(\frac{1}{2}\bigg)^4 = \frac{6}{32}$$
Comment: For this homework we have to assume we don't the binomial distribution or any combination numbers, because my professor hasn't gone over it yet..


Advice on how to compare a date input value against min/max date ranges

Question: I have set up a jQuery datepicker that accepts a date of birth and would like to use the date selected to output a specific category comparing the inputted date with min and max dates per category. At the moment I'm having problems actually comparing the dates and was hoping I could get some advice. I know right now my problem is because I'm trying to compare a string and a string but I would like to know should I be converting each of the dates to something like a unix value to make the comparison or is there some Date() I should be using on each of my ageLimits
JS
var ageLimits = {
    'under10': {
        'minAge': '06-05-2005',
        'maxAge': '07-04-2004'
    },
    'under13': {
        'minAge': '08-04-2003',
        'maxAge': '15-08-2001'
    },
    'under15': {
        'minAge': '16-08-2000',
        'maxAge': '07-12-1999'
    }
}
function getUserDate(val) {

    dateInput = moment( $('#datepicker').val(), 'MM-DD-YYYY');

    //pass full date to selectAgeCategory
    selectAgeCategory( dateInput.format('MM-DD-YYYY') );

}

function selectAgeCategory(date) {
      console.log(date);

    if( date >= ageLimits.under10.minAge && date <= ageLimits.under10.maxAge ) {
        console.log('Under 10 category');
    } else if ( date >= ageLimits.under13.minAge && date <= ageLimits.under13.maxAge ) {
        console.log('Under 13 category');
    } else if ( date >= ageLimits.under15.minAge && date <= ageLimits.under15.maxAge ) {
        console.log('Under 15 category');
    } else {
        console.log('No category available for this age');
    }
}

JSFiddle: http://jsfiddle.net/qA9NT/5/
Comment: Stop storing and comparing dates as strings
Comment: Hey @ryan yeah I realise thats the problem but what should I do right now to resolve this?
Answer: Use Date objects instead of strings.
You can get the Date object using
dateInput._d

Comment: Hey @Oriol, I'm slightly confused do I need to set each date inside my ageLimits object using Date()?
Comment: Yes, you should convert your ageLimits to a Date object, and compare those with `dateInput._d`
Answer: I see you are already using moment.
You can parse the date strings using moment and get a native date object from the moment instance using toDate. Then you can just compare the native Date objects naturally.
The native Date constructor can already parse some formats so you might not even need to use moment for parsing.
Note that if you are hardcoding the ageLimits object you could construct date objects right away rather than storing strings.
var date1 = moment("12-25-1995", "MM-DD-YYYY").toDate(),
    date2 = moment("12-25-1996", "MM-DD-YYYY").toDate();

if (date1 < date2) console.log('first date is smaller');

FIDDLE
Comment: hey @plalx thanks for this, I've tried updating my fiddle but still have an issue with comparing the input date with my ranges. Could you advise where I may be going wrong? http://jsfiddle.net/qA9NT/10/
Comment: @styler Well your date ranges are wrong. For example, the min date for under 10 is for year 2005 while the max ends in 2004.
Comment: thanks for letting me know!! I didn't realise I'd mixed them up :/
Answer: I'm not sure what your date criteria is but if it is strictly based on years you can get exact date in the past using following:
var yearsAgo=10

var d=new Date();
d.setYear( d.getFullYear() - yearsAgo) ;

Won't require any hard coding of your test dates and will always be calculated from today's date
Can then compare date objects directly


moxy how to find object set null or the object is not given

Question: @XmlRootElement
class Person{
String id;
String name;
}

JSON
{
"id":null
}

I want to find the id that is set to null and the name is not given in the json。I know the method the object set to null will  invoke the set method。But I have so many object I want not do as that。If have general method。
I need you help @Blaise Doughan
Answer: You can leverage JAXBElement for this.  One of the roles of JAXBElement is to handle the case where an XML element is both nillable and optional:
<element name="foo" type="string" nillable="true" minOccurs="0"/>

Domain Model
Person
We will leverage field access (see:  http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html) for our JAXBElement and code our accessor methods to look the way we want.
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Person {

    static final String ID = "id";
    static final String NAME = "name";

    @XmlElementRef(name=ID)
    JAXBElement<String> id;

    @XmlElementRef(name=NAME)
    JAXBElement<String> name;

    public String getId() {
        if(null == id) {
            return null;
        } else {
            return id.getValue();
        }
    }

    public void setId(String id) {
        this.id = new JAXBElement<String>(new QName(ID), String.class, id);
    }

    public String getName() {
        if(null == name) {
            return null;
        } else {
            return name.getValue();
        }

    }

    public void setName(String name) {
        this.name = new JAXBElement<String>(new QName(NAME), String.class, name);
    }

}

ObjectFactory
When we leverage a JAXBElement on a field we need to have a corresponding @XmlElementDecl on a class annotated with @XmlRegistry.
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;

@XmlRegistry
public class ObjectFactory {

    @XmlElementDecl(name=Person.ID)
    public JAXBElement<String> createId(String id) {
        return new JAXBElement<String>(new QName(Person.ID), String.class, id);
    }

    @XmlElementDecl(name=Person.NAME)
    public JAXBElement<String> createName(String name) {
        return new JAXBElement<String>(new QName(Person.NAME), String.class, name);
    }

}

Demo Code
Below is some code you can run to show that everything works.
Demo
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {ObjectFactory.class, Person.class}, properties);

        Person person = new Person();
        person.setId(null);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(person, System.out);
    }

}

Output
{
   "id" : null
}


How to export a multi-layer ggplot to googleVis?

Question: I created a plot with ggplot with 4 different layers.
The bulk of the data is in blue dots, while the datapoints that meet condition A are surrounded by a green halo.
Likewise, the datapoints that meet condition B are surrounded by a red halo.
In addition, datapoints that meet condition C are surrounded by a larger yellow halo.
I want all of these 4 colors to be possible in a point, so I don't want to use color=factor(condition) or something like that.
The thing is I want to make this plot interactive so that people can hover over the points, and most importantly, see the row.names of a given point.
How can I give googleVis a layered ggplot?
I would like to use googleVis because I think this is the only tool that would let me display the name of the data point in the bubble, but I am open to trying plotly or Rcharts as well if this is possible.

ggplot code:
genePlot <- ggplot() +
list(geom_point(data=correlSelect[c("GENE_A", "GENE_2", "GENE_3", "GENE_4", "GENE_5", "GENE_6", "GENE_7", "GENE_8", "GENE_9", "GENE_10"),] , aes(condition1, condition2), colour="yellow", alpha=1, size=5)
+ geom_point(data=correlSelect[row.names(resSignif1),] , aes(condition1, condition2), colour="red2", alpha=.5, size=3)
+ geom_point(data=correlSelect[row.names(resSignif2),] , aes(condition1, condition2), colour="seagreen3", alpha=.5, size=3)
+ geom_point(data=correlSelect, aes(condition1, condition2), colour="steelblue", alpha=.3))

And my data frame looks like this:
       cond1  cond2  score
GENE_A  .5     .2     -10
GENE_B  .3     .8     -3
GENE_C  .4     .1     -5
GENE_D  .8     .8      6
GENE_E  .7     .4      8
GENE_F  .1     .6      2
.
.
.
GENE_Z  .9     .3      5

I am only plotting the values in cond1 and cond2, but I would like people to be able to hover over the points and see the row.name (GENE_X) and the value in the 'score' column.
Thanks!
Answer: Please try and convert your ggplot plot to a plotly one (via ggplotly(), see https://plot.ly/ggplot2/). Let me know if some layers are not supported or the conversion is incomplete.
Comment: Thanks, mkcor. I tried ggplotly( ) but the size of the second, third and fourth layers is not respected. They are plotted as small points within the blue points, instead of as halos.
Comment: I also have not been able to figure out if Plotly can display the names of the observations in the hover bubbles. For now I have only been able to display the values that are being plotted with Plotly.
Comment: Yep, Plotly lets you customize the hover data. Here is [an example bubble chart](https://plot.ly/~jackp/1835). Here's [a question and answer](http://stackoverflow.com/questions/26152856/customise-the-infowindow-tooltip-in-r-plotly) about custom hover with R. Can you post a reproducible example so we can check out your code?
Comment: @MateoSanchez, that is awesome and just what I mean! I will update my question to include my ggplot code and a snippet of my data frame in R. Thanks!
Comment: I have just updated my question to better reflect what I am trying to do.


Close modal on click

Question: I have a Model with custom buttons
 <modal #modal>
        <modal-header [show-close]="true">
           Header Text
        </modal-header>
        <modal-body>
          Body Text
        </modal-body>
        <modal-footer>
            <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">Cancel</button>
            <button type="button" class="btn btn-primary" (click)="SaveProject()">Ok</button>
        </modal-footer>
    </modal>

On the component side I have code for SaveProject()
 SaveProject() {
//      Some Logic

    }

I want to close the modal after the logic is complete. For this, I implemented this in the component page
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';

In export class I have
   modal: ModalComponent;

And in my click event I have
SaveProject() {
//      Some Logic
this.modal.close();
    }

But it is not working
Answer: You need to use ViewChild like mentioned.
@ViewChild('modal')
modal: ModalComponent;

Then you can use close or even dismiss if you want, depending on your use case:
SaveProject() {
   this.modal.close();
   // this.modal.dismiss();
}

More info here, excerpt from page:

close(value?: any): Promise<any>

Closes the modal. Causes onClose to be emitted. Returns a promise that resolves the value passed to close when the modal is completely hidden.
dismiss(): Promise

Dismisses the modal. Causes onDismiss to be emitted. Returns a promise that resolves when the modal is completely hidden.

Close modal on click


Am I damaging my battery by never using it?

Question: I have a MacBook Pro that stays plugged in for weeks or months at a time. Am I damaging my battery by not using it? I know you should cycle it monthly to recalibrate it...is that good enough?  Should I just take the batter out and shelve it for a while?
Thanks!
Answer: Short answer: yes, this will damage your battery. Take it out for extended periods when it's not going to be used.
Lithium Ion batteries (as in your laptop) have a pretty short life anyway. Even if you leave it sitting on a shelf, never used, within 5 years or so it will be useless (which is why I feel sorry for people who are buying the $100,000 Telsa car, it's loaded with batteries that won't last for more than a few years!).
There's a great explanation of why this is on Wikipedia.
Comment: He can't take it out if he has a unibody macpro ...
Comment: Two comments: (1) Taking a lithium-ion/lithium-polymer battery out of the computer when it is at 100% charge will still cause it to lose capacity. It would be much better to remove the battery at a 50% state of charge. (2) If the battery is non-removable, it is still advisable to cycle the battery on a regular basis by simply unplugging the computer and letting the battery discharge (just pretend you're using it on a commuter train), even if you are using it at an office desk. Apple provides [excellent laptop battery care recommendations](http://www.apple.com/batteries/notebooks.html).
Comment: Oh wow, I never thought about that. I do have the first gen Unibody, which means I do have a removable battery....but yea, the new unibody can't.
Answer: Factors affecting Li-Ion battery life:

Everything I've read says that Li-Ion batteries last longest if they're kept cool and lightly cycled: run them down a little bit and then charge them.
They basically have a fixed number of discharge/charge cycles, so keeping them plugged in most of the time is fine.  I see 300-500 cycles mentioned frequently, one site has it as high as 1000.  Since Li-Ion's don't have memory effects, you don't need to "waste" cycles by running them down.
Li-Ion batteries are sensitive to temperature, so if the computer runs hot, you're better off taking the battery out when the computer is plugged in.  Anything else you can do to keep the batteries cool is a good idea.
All batteries self-discharge, but Li-Ion's are slower than NiCads or NiMH's.  So if you leave your batteries out for a long time, they'll need to be charged up again.

At one point, I tried to preserve my battery by taking it out when I was just sitting in the office w/ my laptop plugged in, but then I gave up and figured that for the life of my notebook, I could probably count on the batteries being available to buy a new one after a couple of years so I just use it and hope for the best.
Good sites for battery info:
Battery University: The Li-Ion Battery
Power Electronics article on Li-Ion battery care
Battery Education: How many times can I charge my battery
Answer: Apple has a good webpage about batteries and an iCal calendar to remind you to regulary do a cycle.

Lithium-ion polymer batteries need to
  be used for maximum performance. If
  you don't use your device often, be
  sure to complete a charge cycle at
  least once a month.
Answer: Supposedly, the new MacBook Pros have "adaptive charging" that is tuned to each individual battery cell. This is designed to eliminate the headaches associated with maintaining lithium batteries that used older charging technology.
The technology is also supposed to extend the number of recharge cycles. It accomplishes this by tuning the charging and discharging of each individual cell.
See here for the marketing material on the subject.
Answer: This is what I do, as it's been recommended by the manufacturer:

Unplug the computer when it's not on (so that it's not constantly trying to charge the battery).
Keep the battery in the computer when it's on, but plug the computer in (so that it maintains a full charge for when I need it, but it gets charged slower).

I've lost less than 5% of the battery's capacity over the past 9 months that I've had this laptop this way. My wife's laptop battery however, has been pretty much wiped out over the past 3 years.
If however, your computer is always at your desk and you never take it mobile, then it's probably best to remove the battery entirely because you don't use it. Drain the battery to between 40 and 60%, then put it in the refrigerator. It will permanently lose 2% of its capacity over the course of a year if you do it this way, versus 20% if you keep it fully charged at room temperature.
Lithium ion batteries can generally survive for 1000 or more cycles, and a partial cycle only counts as a partial cycle, unlike (much older!) NiCd or NIMH batteries, which can build a memory effect.
By the way, to respond to another poster, the Tesla manages its battery pack much differently from a laptop in order to extend its life. That pack is never charged to full capacity (I believe 80 or 85%) and never allowed to drain less than 20%. Laptop users are much more picky about discharge times, and their manufacturers much less worried about how many years the batteries last than they are about selling more laptops than the next guy. Also, the battery pack they're using in the production cars are of a different chemistry than their original prototype (which actually used laptop batteries), for safety.
Answer: I'm with Ward. My understanding of li-ion batteries is that they have a charge-cycle lifespan and that keeping them plugged in is the best way to preserve it's lifespan.
I think the official word from Apple is charge...drain...charge at least once a month or so to properly calibrate it... but then again Apple is known for making a buck or two off of dead batteries so I would take their advice with a few spoonfuls of salt.
Answer: If you are using your macbook on the adapter all the time, it was recommended to me by one of the apple genius' that you remove the battery.
I had my battery die (not charging and pulling the power killed the laptop) and they ran their battery diagnostics on it, it showed that it had completed 300 charge cycles. THis was explained to me as when you are using it on adapter, it will actually run on battery until about 95% then top up your battery and that increments your Charge Counter. If it's over a certain amount then they won't replace the battery in warranty.


como passar dados em formato json para uma select?

Question: Olá, recebo dois JSON, um de marcas outro de modelos.
{
"data": {
    "JEEP": 40,
    "LAND ROVER": 46,
    "LAMBORGHINI": 42,
    "LIFAN": 43,
    "IVECO": 94,
    "ASIA MOTORS": 5,
    "AM GEN": 1,
    "ENVEMO": 23,
    "WAKE": 77,
    "NISSAN": 59,
    "FIBRAVAN": 26,
    "MASERATI": 52,
    "ROVER": 65,
    "BUGGY": 9,
    "CADILLAC": 14,
    "LADA": 45,
    "LEXUS": 47,
    "CROSS LANDER": 17,
    "PLYMOUTH": 61,
    "VW - VOLKSWAGEN": 75,
    "CHERY": 13,
    "FIAT": 25,
    "SATURN": 68,
    "MAZDA": 54,
    "FORD": 27,
    "MG": 49,
    "CHRYSLER": 15,
    "SMART": 79,
    "ALFA ROMEO": 4,
    "SEAT": 69,
    "RELY": 83,
    "AUDI": 6,
    "TOYOTA": 73,
    "MERCEDES-BENZ": 55,
    "JAGUAR": 39,
    "ROLLS-ROYCE": 84,
    "GM - CHEVROLET": 29,
    "GREAT WALL": 30,
    "HYUNDAI": 34,
    "DAEWOO": 18,
    "MATRA": 53,
    "PONTIAC": 62,
    "FOTON": 82,
    "TESLA": 92,
    "EFFA": 21,
    "LANDWIND": 86,
    "FYBER": 28,
    "SUZUKI": 71,
    "ASTON MARTIN": 81,
    "PEUGEOT": 60,
    "HAFEI": 32,
    "FERRARI": 24,
    "BABY": 93,
    "SAAB": 67,
    "SUBARU": 70,
    "TROLLER": 74,
    "VOLVO": 76,
    "CITROEN": 16,
    "ISUZU": 35,
    "BUGRE": 10,
    "MAHINDRA": 51,
    "RENAULT": 64,
    "ACURA": 95,
    "MERCURY": 56,
    "JPX": 38,
    "DODGE": 20,
    "CBT JIPE": 11,
    "KIA MOTORS": 41,
    "LOTUS": 48,
    "DAIHATSU": 19,
    "MITSUBISHI": 57,
    "SHINERAY": 80,
    "INFINITI": 91,
    "WALK": 78,
    "PORSCHE": 63,
    "BMW": 7,
    "JAC": 36,
    "LOBINI": 44,
    "DKW VEMAG": 85,
    "MCLAREN": 2,
    "MINI": 50,
    "CHANGAN": 12,
    "GURGEL": 31,
    "HITECH ELETRIC": 96,
    "AGRALE": 3,
    "MIURA": 58,
    "TAC": 72,
    "JINBEI": 37,
    "SSANGYONG": 66,
    "BRM": 8,
    "GEELY": 87,
    "PUMA": 89,
    "CHANA": 88,
    "ENGESA": 22,
    "HONDA": 33,
    "RAM": 90
},
"status": "ok"

}
esse é de modelos
{
"data": {
    "DUCATO-10": 8,
    "MAREA": 17,
    "DUCATO-8": 10,
    "TEMPRA": 25,
    "DUCATO-15": 9,
    "ELBA": 12,
    "ARGO": 34,
    "GRAND SIENA": 31,
    "COUPE": 5,
    "MOBI": 33,
    "CRONOS": 36,
    "SIENA": 21,
    "TIPO": 26,
    "BRAVA": 2,
    "FREEMONT": 14,
    "IDEA": 15,
    "UNO": 27,
    "PANORAMA": 29,
    "LINEA": 16,
    "OGGI": 30,
    "TORO": 32,
    "FIORINO": 13,
    "BRAVO": 3,
    "DUNA": 11,
    "STRADA": 23,
    "PALIO": 18,
    "CINQUECENTO": 4,
    "PUNTO": 20,
    "STILO": 22,
    "147": 28,
    "500": 1,
    "PREMIO": 19,
    "DOBLO": 6,
    "DUCATO": 7
},
"status": "ok"

}
quero passar eles para select, para ficar como na imagem abaixo

1ª duvida é como passar desse formato json para a select
2ª ao escolher marcas, popular os modelos.
estou tentando usar nesse jeito, mas está dando erro:

$(document).ready(function () {

    colors = {
      "data": {
          "JEEP": 40,
          "LAND ROVER": 46,
          "JINBEI": 37,
          "SSANGYONG": 66,
          "BRM": 8,
          "GEELY": 87,
          "PUMA": 89,
          "CHANA": 88,
          "ENGESA": 22,
          "HONDA": 33,
          "RAM": 90
      },
      "status": "ok"
    };

  $.each(colors, function(key, value) {
      $('#divSelect').append($("<option/>", {
          value: value,
          text: key
      }));
  });

});

Answer: Não está funcionando, pois você está adicionado os options a uma div, não a um select. Tente fazer seu html assim:

<select id="idSelect"></select>

E troque o "#divSelect" por "#idSelect" no seu javascript.
Comment: olá, agora no select apareceu DATA e STATUS. Como fazer para aparecer as marcas e excluir da lista esses dois(data e status).
Comment: consegui fazendo assim $.each(colors.data, function(key, value) { ......
vou ver como popular agora.
Answer: Tinha esse código aqui, vê se te ajuda :)

var dic = {
   'Cachorro': ['Poodle', 'Bulldog', 'Pinsher'],
   'Gato': ['Gato - Siames', 'Gato - sei la'],
};

$('#animais').on('change', function() {
   var selectValue = $(this).val();
   $('#racas').empty();

   for (i = 0; i < dic[selectValue].length; i++) {
      $('#racas').append("<option value='" + dic[selectValue][i] + "'>" + dic[selectValue][i] + "</option>");
   }
});

<select id="animais">
  <option value="" disabled selected>Selecione um animal</option>
  <option value="Cachorro">Cachorro</option>
  <option value="Gato">Gato</option>
</select>

<select id="racas">
  <option value="" disabled selected>Selecione uma raca</option>
</select>
Comment: vou tentar trabalhar em cima do seu código. obrigado


Computing contour integral - switch limit and integral

Question: Context: I want to compute the Dirichlet integral with the help of $f(z)=\frac{\exp(iz)}{z}$ but without residues, Jordan's lemma etc, so everything by hand. While I understood how to show that something converges to $0$, I still don't understand how to show that something converges to a specific value.
I am confused about the rules of switching limits and integrals. In particular:
I want to show that the integral of $f(z)=\frac{\exp(iz)}{z}$ along the curve $\gamma:[0,\pi] \to \mathbb C$,  $\gamma(t)=\epsilon \exp(it)$
- thus the small semicircle around $0$ - goes to $i\pi$.
So it boils down to  showing $lim_{\epsilon \to0} \int_{0}^{\pi} \exp(\epsilon i e^{it} ) dt=\pi$
I know that one method would be showing that $\exp(\epsilon i e^{it} )$ converges uniformly to $1$ but I think formally i might get problems as
$|\exp(\epsilon i e^{it} )|=|\frac{1}{\exp(\epsilon \sin(t))}|$ and the convergence won't be uniformly as $\sin(t)$ can be small on $[0,\pi]$
Is it possible to  use dominated convergence by showing that $|\frac{1}{\exp(\epsilon \sin(t))}|$ is integrable?
$\int_{0}^{\pi} |\frac{1}{\exp(\epsilon \sin(t))}| dt$
$\le \int_{0}^{\pi} |\frac{1}{1+\epsilon \sin(t)}| dt$
$= \int_{0}^{\pi/2} |\frac{1}{1+\epsilon \sin(t)}|dt+\int_{\pi/2}^{\pi} |\frac{1}{1+\epsilon \sin(t)}|dt$    and by convexity/concave of $\sin$
$\le \int_{0}^{\pi/2} |\frac{1}{1+\epsilon \frac{2}{\pi} t}|dt+\int_{\pi/2}^{\pi} |\frac{1}{1+\epsilon (-\frac{2}{\pi} t+2)}|dt$
$=\int_{0}^{\epsilon} \frac{1}{1+u}\frac{2}{\epsilon \pi}du+\int_{1}^{0} \frac{1}{1+\epsilon u} \frac{-\pi}{2} du$
$=\pi (\frac{\ln \epsilon+1}{\epsilon})$ $<\infty$
So by DCT: $lim_{\epsilon \to0} \int_{0}^{\pi} \exp(\epsilon i e^{it} ) dt=\int_{0}^{\pi} lim_{\epsilon \to0}  \exp(\epsilon i e^{it} ) dt = \int_{0}^{\pi} 1dt=\pi$
So, my question is: Is this a formally correct way or were all these computation useless? Or is there a standard method for doing this?
Answer: You have a mistake in the evaluation of the last integrals. And for the dominated convergence theorem, you need a dominating function that is independent of $\epsilon$.
But you are thinking too complicated. On $[0,\pi]$, we have $\sin t \geqslant 0$, and we have $\epsilon > 0$, so
$$\biggl\lvert\frac{1}{\exp (\epsilon \sin t)}\biggr\rvert \leqslant 1.$$
Since the domain of integration has finite measure, that shows that the dominated convergence theorem is applicable.
Also, the convergence of $\exp (i\epsilon e^{it})$ to $1$ is uniform. For every $z \in \mathbb{C}$ we have
$$\lvert e^z - 1\rvert = \Biggl\lvert \sum_{n = 1}^{\infty} \frac{z^n}{n!}\Biggr\rvert \leqslant \sum_{n = 1}^{\infty} \frac{\lvert z\rvert^n}{n!} = e^{\lvert z\rvert} - 1,$$
so we see
$$\lvert \exp(\epsilon ie^{it}) - 1\rvert \leqslant e^{\epsilon} - 1.$$
When $\epsilon \leqslant 1$, we can bound the right hand side by $(e-1)\cdot \epsilon$.
Comment: Thank you very much! I already had a feeling that it got to computational...


Orthogonal matrix preserves volume

Question: An $n\times n$ matrix is said to be orthogonal if $AA^T = A^TA = I_n$; that is, if $A^T = A^{-1}$
    (It turns out that in two or three dimensions, the orthogonal matrices describe rotations and reflections).
    Suppose that $T : \mathbb{R}^3 \to \mathbb{R}^3$ is a linear transformation with standard matrix $A$, and $A$ is orthogonal.
    Show that $T$ preserves volume: if $S \subset \mathbb{R}^3$ is a solid with volume $V$, then $T(S)$ also has volume $V$.
So this is my question. I did not have any clue at this moment. Could anyone help me?
Comment: You should show your attempts
Comment: If you are talking about general solids, not just parallelepiped, then you may need an analysis tag here. You may start with interpreting the determinant as a signed volume and using $\det(AB)=\det(A)\det(B)$.
Comment: Any isometry preserves volumes. You may show this either by invoking a decomposition in polytopes or by computing a Jacobian.
Answer: Here is one idea. Show that if you have any cube, $T$ preserves its volume. Then you can think of any volume as a sum of little cubes, like 3D Riemann integral sums such things to get volumes...

Orthogonal matrix preserves volume


What is the kind of graph for number of partitions of an integer

Question: How do you call a graph showing the count of a partition of a specific size?
This is what it looks like:
Answer: That is called a histogram. It is showing the distribution of partition sizes.


Subseting the lowest date by a factor

Question: I have the following dataset:
id<-c("1a","1a","1a","1a","1a",
      "2a","2a","2a","2a","2a",
      "3a","3a","3a","3a","3a")
fch<-c("22/05/2020","12/01/2020","01/01/2019","10/11/2020","01/01/2019",
       "10/10/2015","01/01/2015","20/10/2015","08/04/2020","12/12/2019",
       "01/05/2020","01/01/2013","10/08/2019","12/01/2020","20/10/2019")
dat<-c(25,35,48,97,112,
       65,85,77,89,555,
       58,98,25,45,336)
data<-as.data.frame(cbind(id,fch,dat))

My intention is to extract the row corresponding to the earliest date by the factor "id".
So my resulting data frame would look like this:
id<-c("1a","2a","3a")
fch<-c("01/01/2019","01/01/2015","01/01/2013")
dat<-c(48,85,98)
data_result<-as.data.frame(cbind(id,fch,dat))

This was my unsuccessful attempt:
DF1 <- data %>%
  mutate(fch = as.Date(as.character(data$fch),format="%d/%m/%Y")) %>%
  group_by(id) %>%
  mutate(fch = min(fch)) %>%
  ungroup

Answer: We arrange the data by 'id', and the Date converted 'fch', grouped by 'id', use slice_head to get the first row of each group
library(dplyr)
library(lubridate)
data %>%
  arrange(id, dmy(fch)) %>%
  group_by(id) %>%
  slice_head(n = 1) %>%
  ungroup

-output
# A tibble: 3 x 3
#  id    fch          dat
#  <chr> <chr>      <dbl>
#1 1a    01/01/2019    48
#2 2a    01/01/2015    85
#3 3a    01/01/2013    98

NOTE: cbind returns a matrix by default and matrix can have only a single type.  Instead, we can directly create the data.frame
data
data <- data.frame(id, fch, dat)

Answer: Slightly different method from @akrun. Note that one of the earliest dates in your data has two entries. Without a time there is no way to know which occurred first (or maybe you want both?).
library(tidyverse)
library(lubridate)

data.frame(id = c(rep("1a",5), rep("2a",5), rep("3a",5)),
           fch = c("22/05/2020","12/01/2020","01/01/2019","10/11/2020","01/01/2019",
                   "10/10/2015","01/01/2015","20/10/2015","08/04/2020","12/12/2019",
                   "01/05/2020","01/01/2013","10/08/2019","12/01/2020","20/10/2019"),
           dat = c(25,35,48,97,112,65,85,77,89,555,58,98,25,45,336)) %>%
  group_by(id) %>%
    mutate(fch = dmy(fch)) %>%
    filter(fch == min(fch))
    ungroup()

# A tibble: 4 x 3
# Groups:   id [3]
  id    fch          dat
  <chr> <chr>      <dbl>
1 1a    01/01/2019    48
2 1a    01/01/2019   112
3 2a    01/01/2015    85
4 3a    01/01/2013    98

Subseting the lowest date by a factor


Changing logo when signed in

Question: In page.tpl.php, the logo section is handled as:
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

When user signs in, I want logo to change from logo.png to inner_logo.png
I can track where $logo comes from and add an if statement like <?php if($user->uid <=0) { $logo = "logo.png" } else { ... ?>
But would this be the correct practice? Is there a more practical Drupal way?
edit:
/* Override or insert variable into the pre-process_template*/
function bartik_preprocess_page(&$variables) {
    if (user_is_logged_in()) {
        $variables['logo'] = (drupal_get_path('theme', 'bartik') . '/images/inner_logo.png');
    }
}

Answer: In general, every .tpl.php has what is called a "preprocess" function.  The default one for page.tpl.php is template_preprocess_page().  This sets up the variables that are available in the template.  Other modules and themes can have their own; then don't replace each other, rather, they all run in a defined order.
So, you would add in a preprocess function for your theme's template.php like:
function MYTHEME_preprocess_page(&$variables) {
  if (user_is_logged_in()) {
    $path = drupal_get_path('theme', 'MYTHEME');

    $variables['logo'] = file_create_url($path . '/images/inner_logo.png');
  }
}

This will check to see if the user is logged in using the proper API call (program to the interface not the implementation), and then change the logo variable to a new path from within your theme.  Just make sure you clear the Drupal caches from admin/config/development/performance first so the function gets picked up.
Comment: On the website that you shared, it states that `template_preprocess_page()` function is located in `includes/theme.inc, line 2539`. But I couldnt locate to it?
Comment: It's there; it's line 2532 in the current version in git.  You wouldn't edit this directly, though.  You would make your own version in your own theme.
Comment: use `template.php`
Comment: I made the change here; `function theme_get_setting($setting_name, $theme = NULL) {` and it worked. Please review the original question edited codes. Is this acceptable or would you still recommend me to use `template.php` or the `template_preprocess_page()` function?
Comment: @Efe Editing your question with your solution isn't the StackExchange way.  If you have another solution, you can answer your own question.  To answer your question above, editing includes/theme.inc is [bad](https://drupal.org/best-practices/do-not-hack-core);  use template.php
Comment: I have then misunderstood the article on the link that you have shared. I thought I had to make a change in the `includes/theme.inc` file since `template_preprocess_page()` is located there.
Comment: So I now removed my changes in `theme.inc` file and put the code that you have written inside `template.php`. But the if statement stopped working now?
Comment: @Efe  Do a little googling on preprocess functions and template.php.  That should shed some light on the matter, and my answer will start to make sense.
Comment: Strangely, I deleted the theme, reinstalled it with the new template.php and it worked!

Changing logo when signed in


Integer input without submit buttom to instantly set a loop limit

Question: I am trying to set the first input "Enter # of Circles" as a variable "ContestantNum" without a submit button which is then supposed to be the limit in the loop (i=0; i<=ContestantNum; i++)
Not sure if there is any event to be applied in addEventListener() that can pull the data from the input with no submit.
Thanks Alot!
    <!DOCTYPE html>

    <title>Intro Webpage!</title>

     <meta charset="UTF-8" />
     <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0; target-densitydpi=device-dpi" />
     <link rel="stylesheet" type="text/css" href="style.css"/>

       Enter # of Circles

    <input type="integer" id="circles">

    <form>

      <svg height="100" width="200">
    <line x1="0" y1="50" x2="100000000" y2="10000" style="stroke:rgb(0,255,0);stroke-width:5" />

       <svg height="100" width="100">
              <circle id="cir" cx="50" cy="50" r="30" stroke="black" stroke-width="3" />
       </svg>
       </svg>

       Color

    <input type="integer" id="Color">

//Inputing integer 1, 2 or 3 which instantly applies color formatting (RGB) to circle in the same div
            var cir = document.getElementById("cir");
            var into = document.getElementById("Color");
           into.addEventListener("keyup",myFunction,false);

            function myFunction() {
                if (document.getElementById("Color").value == 1)
                    cir.style.fill = "green";
                else if (document.getElementById("Color").value == 2)
                    cir.style.fill = "red";
                else if (document.getElementById("Color").value == 3)
                    cir.style.fill = "blue";
                else cir.style.fill = "Yellow";
                                  }

       </script>

  </form>

Comment: Poll the data through a timer, like twice a second
Answer: When do you need the loop to start, on page load or when the input has changed? You could tie the onkey up event to your input, which gives you access to the input value in the event handler, which could then set the ContestantNum var.
Comment: yes, when the input has changed.
That is the exact method i have tried yet for some reason it is not working.
Comment:
Answer: You need to have an event such as keydown, keypress etc, with a debounce:
var participantsField = document.getElementById("Participentfieldwrap"),
  form = document.getElementsByTagName("form")[0],
  ContestantNum = document.getElementById("circles"),
  i, timer;

function createCircles(val) {
  for (i = 0; i <= val; i++) {
    var clone = participantsField.cloneNode(true);
    form.appendChild(clone);
  }
}

ContestantNum.addEventListener('keydown', function(e){
   if(timer){ clearTimeout(timer); }

   timer = setTimeout(function(){
     createCircles(ContestantNum.value);
   }, 800);
});

Comment: Thanks alot! it is very close but it is incrementing everytime a value enters the input field
Comment: You could try increasing the timeout delay to `800,900 ms`.


Como fazer para transformar a largura de uma div 'infinita'?

Question: Estou criando uma aplicação com várias colunas, cada coluna com várias etiquetas. Na tela cabem aproximadamente 5 colunas, no máximo, após isso elas recomeçam uma embaixo das outras, assim.
COLUNA1 COLUNA2 COLUNA3 COLUNA4 COLUNA5
COLUNA6 COLUNA7 COLUNA8 COLUNA9 COLUNA10
COLUNA11 ...

Eu gostaria que isso não ocorresse, mas que elas continuassem sempre para a direita, independente de quantas eu insira, assim.
COLUNA1 COLUNA2 COLUNA3 COLUNA4 COLUNA5 COLUNA6 COLUNA7 COLUNA8 ...

E também inserir uma barra de rolagem vertical para ver todas as colunas.
Da mesma forma, preciso que em cada coluna eu insira quantas etiquetas eu quiser, e a altura da coluna (com um tamanho mínimo) aumente conforme o número de etiquetas.
Meu código está assim.

.coluna1 {
    margin-left: 5px;
    margin-right: 5px;
    width: 280px;
    height: 600px;
    background: rgba(0, 0, 0, 0.19);
    float: left;
}

.oportunidade1 {
    padding: 10px;
    color: black;
    background: rgba(69, 164, 255, 0.45);
    border: 1px solid #828282;
}

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

Answer: Cara uma das formas de fazer é com display:flex e overflow-x:auto, ai as colunas vão ir ficando "infinitamente" uma ao lado da outra sem quebrar a linha.
OBS: Não mexi em nada no seu HTML, não precisei colocar classe nos elementos, pois vc já havia colocando, então só precisei fazer uns ajustes como falei no CSS e colocar flex na classe .colunas-status

Execute em Página toda para visualizar melhor, o snippet aqui do site tem pouca altura e fica ruim de testar.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.coluna1 {
  margin-left: 5px;
  margin-right: 5px;
  width: 100%;
  height: 600px;
  background: rgba(0, 0, 0, 0.19);
  float: left;
}

.oportunidade1 {
  padding: 10px;
  color: black;
  background: rgba(69, 164, 255, 0.45);
  border: 1px solid #828282;

  width: 280px;
}

.colunas-status {
  display: flex;
  overflow-x: auto;
}

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ

                edit

ID: 4 - R$ 700,00

Rafael MZ


Trouble to create new subscription

Question: I am getting trouble to creating new  subscription in the Local publication.
I was able to create the Local publication at the Replication
However, after I created sub subscription and I just right clicked the subscription and clicked "View synchronization state "
It is displaying only this message

The concurrent snapshot for publication 'Publisher_team7' is not available because it has not been fully generated or the Log Reader
  Agent is not running to activate it. If generation of the concurrent
  snapshot was interrupted, the Snapshot Agent for the

I am not really sure the solution of this problem.
I also tried to delete Local publications and start again but i can not delete .
I can only see this error message

Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you
  do not have permission. Changed database context to 'TV_Data'. (.Net
  SqlClient Data Provider)

How can I fix this problem ?
Answer: Take a look at the replication monitor.  You should be able to look at each of the log reader, snapshot, and distribution agent's status and get specific status for each of them.  Troubleshoot them in the order above as that's how data flows from publisher to distributor to subscriber.  A lot can go wrong with replication, so I'll need to know more before troubleshooting further.

Trouble to create new subscription


Gtk: GtkVPaned second child height

Question: Is there any way to make GtkVPaned to set splitter position so second child would take 100px height?
Thanks.
Answer: If you have a GtkVPaned and have already added your two widgets to it something like this should work:
GtkVPaned *vpane = ...;

// set up stuff here

int pos = ;// calculate correct position here, easy if you know the height already
g_object_set(vpane,
            "position", pos,
            "position-set", TRUE);

It gets harder if you don't know the height of the region, then you actually have to add the VPane to whatever you want it in, make sure layout happens then ask for the height.

Gtk: GtkVPaned second child height


Evaluation Metrics for Recommendation Systems

Question: I am building a collaborative filtering recommendation engine and i am trying to measure how accurate is my model and the quality of the recommendations. I test my algorithm with the following steps.
1) Train the model with 3 months data ( t )
2) I recommend items for the next day (t1 =  t+1day )
3) Calculate the Accuracy, Precision and Recall from validation set.
As validation i use a 30 days time-space ( t1 + 30days) to check if the user interact with the product
This is the way that  i measure my model now:
Accuracy: How many times a user buy 1 item from my top 5 recommendation
For Precision and Recall i measure the 2 metrics for every user and then i found the mean Precision and Recall of all my users:
Precision at Top 5 recommendations: Correct recommendations / 5
Recall at Top 5 recommendations: Correct recommendations / Known products that
the user buy in 30 days validation
Is the way that i measure the Recall correct?
What the Recall represent in recommendation engines?
Is there any other metrics that i can use?
Answer: Recall adopted for recommendation systems measures the ratio of products that were actually bought by customers (hits) in relation to their number of products in the test set (|T|).

This measure is first calculated for each test customer and then averaged for all users in the test set. More information about the basic idea can be found in the paper of Cremonesi et al. (2010) "Performance of Recommender Algorithms on Top-n Recommendation Tasks" or in an early paper of Herlocker et al. (2004) "Evaluating collaborative filteringrecommender systems"
Other metrics which may be suitable can take both into account, precision and recall. E.g., F1-Score is the harmonic mean of both measures and can be calculated by

However, some studies have shown that customers usually look at the recommendation lists from top to bottom, often only perceiving the few products at the top of the list. To overcome this issue ranking-based measure e.g., Mean Average Precision (MAP) can be used.


Invertible linear mapping of an open set is still open

Question: I am stuck on how to prove an open set is still open after invertible linear transformation.

If $\delta =(\delta_{1},\dots ,\delta _{d})$ ,$\delta _{i}>0$ for all $i$,and $E \subset \Bbb R^{d}$, we define
  $$\delta E= (\delta _{1} x_{1},\dots,\delta _{d} x_{d})$$
  where$(x_{1}, \dots, x_{d}) \in E$
E is open, prove $\delta E$ is open.

My attempt is that for all $x\in E$, we can find $r$ such that $B_{r}(x)\subset E$. If we define $\delta '$=$\min (\delta _{i})$, then $B_{\delta ' r}(\delta x) \subset \delta E$. But I don't know how to show it formally. Could someone help me with it?
Thanks in advance!
Comment: You mean $\delta E = \{ (\delta_1x_1,\dots,\delta_dx_d) :\, (x_1,\dots,x_d)\in E \}$?
Comment: @Azif00 Yes, this is what it means
Answer: If $A\colon\mathbb R^n\longrightarrow\mathbb R^n$ is an invertible linear transformation, then $A$ is continuous (for this, being linear is enough). In particular, $A^{-1}$ is continuous. And therefore, if $E\subset\mathbb R^n$, $A(E)=\bigl(A^{-1}\bigr)^{-1}(E)$, which is an open set (it is the inverse image of $E$ with respect to a continuous map).


Mobile application development in .Net for all mobile OS

Question: I am c# developer and want to develop one application on all major mobile platforms. I would like to share my business logic via .net services (WCF, REST or WEB.API) to all platforms. Is it possible? If yes then in what major platforms I can use those services? Please suggest, what kind of application architecture should I use?
Let me clarify it.
Can I use .net services (WCF, REST or WEB.API) in android and ios mobile phone app?
Comment: I must really be missing something, if you business logic is all in REST services, this is by definitely about as cross platform as it could be. As far as you architecture is concerned, that should depend on your requirements (and budget). I see someone has already recommended phonegap and jquery mobile as I was typing (and they are quite useful). Still, you have not even specified native app vs web app vs hybrid app, so it is not possible to answer your question
Answer: I would look into phone gap http://phonegap.com/ and jquery mobile http://jquerymobile.com/. I have only used jquery mobile but made a web app with a .net service to get data. Then you use the jquery mobile to display it on the different mobile devices.
Answer: Look at this: http://xamarin.com/
Its a C# framework for developing Cross-Platform Mobile Apps.
Comment: It's worth noting this would cost at least $2000/year to use.


Calculating flow panel width based on its contents

Question: I am dynamically populating frames into flow panels (as part of a horizontally oriented VCL Metropolis app). I need to resize each group's flow panel to fit all its items horizontally. I have a very simple formula which does the trick sometimes, but not all the time - specifically when adding an odd number of items. The flow panel's FlowStyle is set to fsTopBottomLeftRight and fits 2 frames vertically.
For example, adding 7 items automatically detects the correct width (4 items across). But adding 5 items does not detect the correct width (supposed to be 3 across but winds up detecting 2 across).
How can I make it correctly calculate the width for each group?
Here's the procedure that populates the items into each item group (some irrelevant stuff removed):
procedure TSplitForm.LoadScreen;
const
  FRAME_WIDTH = 170;    //Width of each frame
  FRAME_HEIGHT = 250;   //Height of each frame
  FRAME_MARGIN = 30;    //Margin to right of each group
  FRAME_VERT_COUNT = 2; //Number of frames vertically stacked
var
  CurGroup: TFlowPanel; //Flow panel currently being populated
  procedure ResizeGroup(FP: TFlowPanel);
  var
    Count, CountHalf, NewWidth, I: Integer;
  begin
    //Resize the specific flow panel's width to fit all items
    Count:= FP.ComponentCount;
    NewWidth:= FRAME_WIDTH + FRAME_MARGIN;  //Default width if no items
    if Count > 0 then begin
      //THIS IS WHERE MY CALCULATIONS DO NOT WORK
      CountHalf:= Round(Count / FRAME_VERT_COUNT);
      NewWidth:= (CountHalf * FRAME_WIDTH) + FRAME_MARGIN;
    end;
    if FP.Parent.Width <> NewWidth then
      FP.Parent.Width:= NewWidth;
    //Resize main flow panel's width to fit all contained group panels
    //(automatically extends within scroll box to extend scrollbar)
    Count:= TFlowPanel(FP.Parent.Parent).ControlCount;
    NewWidth:= 0;
    for I := 0 to Count-1 do begin
      NewWidth:= NewWidth + FP.Parent.Parent.Controls[I].Width;
    end;
    NewWidth:= NewWidth + FRAME_MARGIN;
    if FP.Parent.Parent.Width <> NewWidth then
      FP.Parent.Parent.Width:= NewWidth;
  end;
  procedure Add(const Name, Title, Subtitle: String);
  var
    Frame: TfrmItemFrame;
  begin
    Frame:= AddItemFrame(CurGroup, Name); //Create panel, set parent and name
    Frame.OnClick:= ItemClick;
    Frame.Title:= Title;
    Frame.Subtitle:= Subtitle;
    ResizeGroup(CurGroup);
  end;
begin
  CurGroup:= fpMainGroup;
  Add('boxMainItem1', 'Item 1', 'This is item 1');
  Add('boxMainItem2', 'Item 2', 'This is item 2');
  Add('boxMainItem3', 'Item 3', 'This is item 3');
  Add('boxMainItem4', 'Item 4', 'This is item 4');
  Add('boxMainItem5', 'Item 5', 'This is item 5');

  CurGroup:= fpInventoryGroup;
  Add('boxInventItem1', 'Item 1', 'This is item 1');
  Add('boxInventItem2', 'Item 2', 'This is item 2');
  Add('boxInventItem3', 'Item 3', 'This is item 3');
  Add('boxInventItem4', 'Item 4', 'This is item 4');
  Add('boxInventItem5', 'Item 5', 'This is item 5');
  Add('boxInventItem6', 'Item 6', 'This is item 6');
  Add('boxInventItem7', 'Item 7', 'This is item 7');
end;

This is a screenshot of what that code is producing:

As you can see, the first group with 5 items is hiding the 5th item, but the second group with 7 items is showing all 7 just fine.
The structure of parent/child relationships is like so (with flow panels in question bold):

SplitForm: TSplitForm (main form)

ScrollBox2: TScrollBox (container of main flow panel)

fpMain: TFlowPanel (container of all group panels)

pMainGroup: TPanel (container of flow panel and title panel)

fpMainGroup: TFlowPanel (container of item frames)
pMainGroupTitle: TPanel (title at top of group)

pInventoryGroup: TPanel (container of flow panel and title panel)

fpInventoryGroup: TFlowPanel (container of item frames)
pInventoryGroupTitle: TPanel (title at top of group)

(other panels for more groups)

I tried using each flow panel's AutoSize property, but it didn't acknowledge the heights (2 up) and made things even worse. I basically just need to properly detect the total number of columns within these flow panels.
Comment: However, if you ever want to use more than 2 rows what you need is Ceil.
Comment: @SertacAkyuz That did the trick perfectly :-)
Comment: @SertacAkyuz Yes, I was thinking about that. For now, I'll support 2 :-)
Answer: Round(Count / FRAME_VERT_COUNT);

Here FRAME_VERT_COUNT is 2. When Count is 5 your expression becomes
Rount(2.5);

The default rounding mode is bankers rounding and this evaluates to 2. When Count is 7 the expression is
Round(3.5);

Bankers rounding means this is 4.
You could do what Sertac suggests and use ceil. However, I would simply avoid floating point altogether. It is just not needed and as a general rule, integer arithmetic is always to be preferred if it is viable. Your expression should be
(Count + FRAME_VERT_COUNT - 1) div FRAME_VERT_COUNT

Answer: You don't want a partial tile, so when you're calculating how many columns are needed you want the nearest (equal or greater) integer.
In the default rounding mode, Round(7/2) is '4'. That's fine. However Round(5/2) is '2'. That's because

With the default rounding mode (rmNearest), if X is exactly halfway
  between two whole numbers, the result is always the even number.

With only two rows, rounding up can be a solution (division is always a whole number or a number exactly in between two whole numbers). For a general solution, better use Ceil.


using ajax jquery to run php script

Question: Using Codeigniter, I am trying to get a php script to run after a user clicks on a submit button.  I have followed quite a few tutorials and have come up with the following code:
If it would help to see the actual page you can visit it here: http://rickymason.net/townbuilder
guest/guest to login (currently required)
In my view (structures.php), I have :

Build

<form name="buildForm" id="buildForm" method="POST">
    <select name="buildID" class="buildClass">
    <option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?>
    <?php echo $structure_info['timebuildmins'] ?> minutes
<?php echo $structure_info['buy_gold'] ?> gold'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
    </select>

        <input class="button" type="submit" value="Submit"/>

</form>

 Result here

This creates my select form and creates it in html.  I then created a .js file to run the ajax:
$("#submit").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '../php/build.php',
data: "",
dataType: 'json',
success: function(data)
{
  alert("success!");
}
});
});

I tried to keep it as simple as I could, just for testing purposes.  Javascript is new to me, and I find it extremely confusing for some reason.  From what I can gather, this script should activate after the submit button is pressed.  It then runs the build.php script, then if it returns an echo through json, it alerts success. right?
my build.php script is below:
<?php
    $query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '7')";
    mysql_query($query) or die ('Error updating database');
    echo "success";
?>

Again, very simple...
Unfortunately, when I click submit, the page seems to "refresh" but nothing happens.  I don't expect anything to happen on the page, but the database doesn't receive any values either.
I do not have the build.php or build.js files in a controller or model, they are outside the application directory and are accessed outside the CI uri/url structure.
As of right now, I am simply trying to successfully run a php script by clicking submit.  My final goal is to take the str_id value that is created for the form, then pass that variable and the user_id into the build.php file, create the db entry, then refresh the page to display the updated DB info.
Obviously, it is not working! Any help would be greatly appreciated.
Comment: `echo "success";` doesn't return a JSON string. Also you don't prevent the form from being submitted. Also do you really need all those opening / closing php tags to build your select box?
Comment: First of all, you don't have anything with ID = "submit", what's jQuery supposed to pick?
Comment: thanks, I removed id='submit' before posting the code.  I did so because a specific example I was mimicking did not have it, as I believe they were calling the form name.  Thanks for pointing that out.
Answer: That script works with an element having id "submit"  (because you use "#submit" as the selector)
Use the click event instead of submit
Either you can give an id to your submit like this

and use like this
$("#btnSubmit").click(function(e){
   // your rest of code
});

or use the class name
$(".button").click(function(e){
   // your rest of code
});

But It is always better to use the id becaues there will be only one ( and should be) element with an id.  More than one element can have the same class.
Comment: The submit() event would be just fine, if he had a submit input with the right id, of course
Comment: I added id='btnSubmit' to the submit tag.  Then I changed the js to $("#btnSubmit").click(function(e){.  I am still not getting a change to the database.  Could it be due to the fact that, since the build.php file is being called, and is not being loaded through the controller, it needs to get connected once again to the DB?  I will try that and report back.
Comment: check in firbug to see whether a call is being made to the correct file ( i mean the path)
Comment: Thank you all.  I was able to get it working based on all the advice given.  After the small changes made, I decided to the code to my controller.  It currently is working! So at least now I have something to build on.
Answer: Add an action attribute for your form:
<form action="build.php" name="buildForm" id="buildForm" method="POST">`

OR:
<form action="<?php /* Script code here */ ?>" name="buildForm" id="buildForm" method="POST">`

Answer: Your jquery code targets an element with the id of 'submit' however, your form has an id of 'buildForm' hence the code does not target the form and when you click submit it just goes on with its normal behaviour, which causes the screen to refresh, To fix this, change the selector in your jquery code
$("#buildForm").submit(function(e){
    // the rest of the code here remains
});

This should fix it

using ajax jquery to run php script


Internal consistency reliability in item response theory models

Question: How can internal consistency reliability of a test and of individual test items be quantified in Item Response Theory models? I know I can resort to Classical Test Theory, Cronbach's alpha, and other measures, but is there a way to characterize reliability within IRT?
Answer: You can compute test information curves from your IRT parameter estimates. These curves give you the precision of the test at each $\theta$ of the latent trait. The information $I$ can be transformed into the standard error of estimate $SEE$, which is a direct estimate of the reliability of the test at that $\theta$: $SEE = 1 / \sqrt{I}$.
The metric of the test information can also be converted to a traditional reliability metric expressed by a correlation coefficient (Thissen, 2000): $Rel = 1 - (1/I)$. Here are the conversions from a set of TICs to correlational reliability estimates:
<code># following Thissen, 2000:
TIC <- seq(1, 12, by=1)
round((rel <- data.frame(TIC, SEE=sqrt(1/TIC), REL=1-1/TIC)), 2)

TIC  SEE  REL
  1 1.00 0.00
  2 0.71 0.50
  3 0.58 0.67
  4 0.50 0.75
  5 0.45 0.80
  6 0.41 0.83
  7 0.38 0.86
  8 0.35 0.88
  9 0.33 0.89
 10 0.32 0.90
 11 0.30 0.91
 12 0.29 0.92
</code>
For example, a TIC > 5 corresponds to a reliability > .80.

Thissen, D. (2000). Reliability and measurement precision. In H. Wainer (Ed.), Computerized adaptive testing: A primer (2nd ed., pp. 159–184). Lawrence Erlbaum Associates Publishers.
Comment: Thanks for your answer; I've asked a follow-up http://stats.stackexchange.com/questions/43405/item-information-in-irt
Comment: I'm not sure your formula for changing information to reliability is correct. The way it is now, any information value <1 will yield a negative reliability. I've seen this formula elsewhere: Reliability = information / (information+1), but I don't have a reference for it other than (https://www.lesahoffman.com/PSYC948/948_Lecture6_Binary_Responses.pdf). This avoids negative reliability values.


dnsmasq not forwarding request to nameserver

Question: I'm trying to run two instances of dnsmasq on a raspberry pi, I've gotten quite far. I'm currently trying to get the first dnsmasq server to forward any request it doesn't know the answer to to the second server but it only seems to be working if I dig <address> @127.0.0.1. Using the external addresses of the either interface, or querying from another machine doesn't do it.
Querying either server directly gets the desired result, but trying to get the first server to forward results from the second... not so much.
Config for instance A (lan):
root@Raspberry-server:~# cat /etc/dnsmasq/dnsmasq.conf

port=53
except-interface=eth0.1
bind-interfaces

no-hosts
#changing the cache size makes no difference
#cache-size=5000
cache-size=0

# uncomment to forget about 404 responses
#no-negcache

#resolv-file=/etc/dnsmasq/resolv.lan.conf
#no-poll
no-resolv
strict-order

server=192.168.1.13

auth-server=raspberry.lan,eth0
auth-zone=lan,192.168.1.0/24
host-record=raspberry.lan,192.168.1.11
host-record=htpc.lan,192.168.1.10
host-record=tom.lan,192.168.1.12

Config for instance B (global):
root@Raspberry-server:~# cat /etc/dnsmasq/dnsmasq.blocker.conf

port=53
bind-interfaces
listen-address=192.168.1.13

no-hosts
addn-hosts=/etc/dnsmasq/blocked.host
cache-size=100000

# uncomment to forget about 404 responses
#no-negcache

resolv-file=/etc/dnsmasq/resolv.blocker.conf
#no-poll

strict-order

Instance A status log:
systemd[1]: Starting DNSMasq Lightweight DNS server...
dnsmasq[1651]: dnsmasq: syntax check OK.
dnsmasq[1656]: started, version 2.76 cache disabled
dnsmasq[1656]: compile time options: IPv6 GNU-getopt DBus i18n IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth DNSSEC loop-detect inotify
systemd[1]: Started DNSMasq Lightweight DNS server.
dnsmasq[1656]: using nameserver 192.168.1.13#53

Answer: Turn on query logging (log-queries) and use dig/nslookup against each server in turn.
In your current setup serverB looks like it will never ask any other server for information. Server A should pass queries to Server B when it cannot answer them itself.
Dnsmasq servers attempt to resolve the query locally, forwarding only if necessary. Enabling query logging should show you which server you're hitting and when, and what they do with that query.
Answer: Have a look at /etc/default/dnsmasq. In some distributions, this file prevents to read "resolv.conf" files other than /etc/resolv.conf.


Tokens for Profile 2 field

Question: I created a field for users using the Profile 2 module with machine name "field_user_country"
I created a block on my user profile page and i need to dynamically display the country of the currently viewed profile.
I have tried various tokens and they do not work.
What token can I use to get the country of the currently viewed user profile?
Thank you.
Answer: I'm having the same issue at the moment. Looking into including a few fields from a Profile2 content type into a Display Suite custom code field.
I used the following PHP code in the custom code field (using php filter format and enabling tokens, just in case). Then I was able to view a collapsed tree of all tokens available to that node.
You could prabably do the same in a block and have it displayed when you need it.
<code><?php
$output .= 'Available tokens:';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
?>
</code>
I'm sure there's a better way, but that quickly worked for me! gOOD LUCK.

Tokens for Profile 2 field


Azure App Service access restrictions - Open to Public but block specific IPs

Question: I'm trying to implement a blacklist/blocklist of IPs in Azure App Service. I created a series of firewall rules that blocked specific IPs, I then added a rule that allowed all IPs (0.0.0.0/0) as a lower priority rule. My assumption was that the higher priority deny rule for specific IPs would block, if none of the deny rules matched than it would allow.
What I found was that all traffic was still allowed, that the deny rule was ignored. Is denying specific IPs while allowing all other traffic not possible or do I need to setup in a different way?
Also, I did try remove the Allow IPs rule, but received a 403 from an IP that wasn't being blocked.
Example of rule setup (note the IP is from a comment spammer, so don't try to resolve):
Answer: How you had it configured, with explicit deny rules and then an allow rule with a lower priority is the correct method, and is documented here. A couple of things I would check:

Is your allow rule definitely the lowest priority
Is your deny rule actually covering the IP or range that your traffic is coming from
Comment: @Josh The rules are "matched" in priority order from lowest to highest.  The first one to match, applies.  In your screenshot, you appear to have it setup correctly (assuming you've entered the correct IP to block).
Comment: Yes, that is what I tried, I've put in a screenshot into the question to show how I have it setup.


Network connection throttling with Selenium - Java

Question: I have been trying to implement network throttling with Selenium-WebDriver based on the snippet available here in this post. https://stackoverflow.com/a/56526094/2122388
Re-posting the code from above link:
protected void networkThrotting() throws IOException {
  Map map = new HashMap();
  map.put("offline", false);
  map.put("latency", 5);
  map.put("download_throughput", 500);
  map.put("upload_throughput", 1024);

  CommandExecutor executor = ((ChromeDriver)driver).getCommandExecutor();
  Response response = executor.execute(
        new Command(((ChromeDriver)driver).getSessionId(), "setNetworkConditions", ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map)))
  );
}

It throws as exception like org.openqa.selenium.UnsupportedCommandException: setNetworkConditions. With my debugging, found like there is no definition for setNetworkConditions in AbstractHttpCommandCodec but found setNetworkConnection. SO tried changing this as below:
protected void networkThrotting() throws IOException {
      Map map = new HashMap();
      map.put("offline", false);
      map.put("latency", 5);
      map.put("download_throughput", 500);
      map.put("upload_throughput", 1024);

      CommandExecutor executor = ((ChromeDriver)driver).getCommandExecutor();
      Response response = executor.execute(
            new Command(((ChromeDriver)driver).getSessionId(), "setNetworkConnection", ImmutableMap.of("network_connection", ImmutableMap.copyOf(map)))
      );
    }

It does not throw any exception and let the test pass, but there is no change in the network speed as intended. I am using Selenium 3.x and Chrome 100.x.
So any input here is much appreciated.
Answer: If anyone else is here because of same issue, then here is the solutions (alternate) I figured out at the end:

Upgrade to Selenium-4.x and use DevTools can make things much easier and straightforward
Use BrowserMob-Proxy and play around

I chose Option-2 for implementing the network throttling, since I had some limitations in upgrading my Selenium version to 4.x (but upgrading the Selenium version is much simple and easy solution).
Answer: Here is a working example to help others about how to use Selenium-4.x version with DevTools.
try (DevTools devTools = ((ChromeDriver) driver).getDevTools()) {
        devTools.createSession();

        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

        // network offline
        devTools.send(Network.emulateNetworkConditions(true, 0, 0, 0, Optional.of(ConnectionType.WIFI)));

        // Your offline code puts here.

}
// Your online code puts here, if any.

Note: Your Chrome Driver version should match the Selenium-Devtools version, for example
'org.seleniumhq.selenium:selenium-devtools-vNN:SELENIUM_VERSION'

vNN is your chrome version like selenium-devtools-v111:4.8.3 with Selenium 4.8.3 version.


How to get the id of a window.alert()?

Question: I want to pop up a window.alert() if the user mouses out of an area when they haven't saved changes yet (for structural reasons, there are several forms and a common problem I've seen in other apps is making changes in multiple areas, submitting one and losing the rest) and automatically close the alert when they mouse back into the area.  To do that, I need the id of the window that pops up, but I'm not sure how to get it.
Comment: Alerts are not DOM elements, they don't have an ID.
Comment: Use a CSS dialog instead of `window.alert()` if you want more control.
Answer: The window does not have an id, and you cannot close it from Javascript. It is not a part of the DOM.
You can only open an alert() box, and then wait till the user closes it. Nothing else.
Answer: No alert() please :)
Actually an alert() will block further code execution anyway so even if you COULD close it programatically it would never actually execute that dialog-closing code.
You need something you can access through the DOM (like every other response here says).
Make your Javascript track the mouse location and upon leaving the area you overlay a dark translucent background or do a modal dialog
Techniques on creating modal dialogs
I would also advise adding a pointer-events: none; and position: fixed to the underlying content to prevent further action until the user actually goes back where they should be.
If you want real specifics on how to code this let me know.  I'm hoping you'll travel down the rabbit hole and discover the wonders on your own, though.  Much more satisfying.

How to get the id of a window.alert()?


If $f(x)$ is uniformly continuous for $x \ge 0$, then it is bounded above by a straight line.

Question: Explicitly: If $f(x)$ is uniformly continuous in $[0,+\infty)$, then there exists positive numbers $a, b$ such that $f(x) \lt ax+b$ for any $x \ge 0$.
Comment: Please consider updating your question with some information about what you have tried or where you are getting stuck. You will find people are much more willing to help if you do!
Answer: We write the definition of the uniform continuity:
$$\text{for}\; \epsilon=1\quad \exists\alpha>0\colon |x-y|\le\alpha \Rightarrow|f(x)-f(y)|<1$$
Now if $x\in[0,\alpha]$ we have $f(x)<1+f(0)$ and if $x\in [\alpha,2\alpha]$ we have $f(x)\le f(\alpha)+1<f(0)+2$ and so on by induction we find: if $x\in [n\alpha,(n+1)\alpha]$ we have $f(x)<f(0)+n+1$ but $x\ge n\alpha$ so $\frac 1 \alpha x\ge n$ and then
$$f(x)<n+f(0)+1\le \frac 1 \alpha x +(f(0)+1)$$
so take $a=\frac 1 \alpha$ and $b=f(0)+1$ and you have the desired result.
Comment: I'll do the same as Amy cause that happened to me likewise.


Can I use Spearman's rho?

Question: I'm taking a research class for Social Work and this is not my strong suit, so please be kind. :)  The system that I have to do my statistical testing includes only the following tests: (ANOVA, Chi Square, Pearson's correlation, Spearman's correlation, Kruskal-Wallis H, Mann-Whitney U, Indpendent t-test, Paired t-test, Wilcoxxon Signed Ranks)
My problem is that I am working with a VERY small sample (currently only 9).  I am trying to determine if there is a correlation between 2 ordinal variables.  When I enter my data the scatterplot shows that it is non-monotonic.  I believe this is due to 2 of my respondents' data being serious outliers.  I'm hoping once I get my full results that the outliers will have less of an effect.  However, I have to submit a preliminary analysis with the data I currently have.  Can I use Spearman, or would one of the other tests be more appropriate?
Thank you so much!!
Comment: When the variables are ordinal, what other options for measuring correlation do you have?
Answer: Welcome to the site, and don't assume you cannot get good at statistics even if it seems daunting, just keep on trying to learn.
When choosing a statistical test, I think there are two important things to keep in mind:
1. Does it test the thing/question that you are trying to ask? (in this case whether there is a correlation between your two variables).
2. Does your data meet all of the assumptions of the test?
If the answer to either question is no, then you should probably not be using that test (or consider what you can do so you are no longer violating the assumptions, e.g. data transformation where possible).
If the answer to both questions is yes, a third question I might then consider is whether it is the most powerful test that can fulfil 1. and 2. (i.e. would another test have a greater probability of detecting a real difference or correlation, if it truly exists).
From what you have described of 1. what you are trying to test and 2. your data, I would say that the Spearman's rank test is appropriate, but you should read up on the assumptions of the test and check for yourself that you're happy your data meets the assumptions.

Can I use Spearman's rho?


Relation between autocorrelation function and periodogram in time series analysis

Question: I was wondering if anyone could give me some insight on the relation between the ACF and the periodogram of a time series.
I have a bunch of timeseries and their ACF's and periodograms are typically much like the examples below.
For my analysis, I'm mostly interested in periodicity at lag 8 and 16 (for theoretical reasons)
The frequencies 'B' and 'HB' correspond to lag 16 and lag 8 respectively. The time series actually concerns interresponse intervals in musical performance of a piece that consists solely of eighth notes (16 of them in a 4:4 bar so 'B' stand for bar and 'HB' for half bar).
The thing I actually wanted to ask: in my periodograms, I consistently get very large peaks at frequency 0.25 (which corresponds to lag 4). However, the ACF peak at lag 4 is much smaller than those at lag 8 or 16. I was wondering how to interpret this finding. A lot of time series variance can be explained at this frequency even though the lag 4 autocorrelation is quite low?
I hope I was sufficiently clear in my question. If not, don't hesitate to ask me.
Answer: The relation between the autocovariance (or autocorrelation) and the spectral density (for which the periodogram is an estimator) is given by the Fourier transform. The two form a so-called Fourier-transform pair meaning the two are time(or space)-domain vs. frequency-domain representations of the same thing. Specifically, if time series $\{X_t\}$ has autovariance function $\gamma(\tau)$ at time lag $\tau$, then the spectral density is defined by
\begin{equation}
f(\nu)=\sum\limits_{\tau=-\infty}^{\infty} \gamma(\tau)e^{-2i\pi\nu\tau}.
\end{equation}
In words, the spectral density partitions the autocovariance as energy-per-hertz of a signal. For example, if you have a deterministic signal with period $t=12$, then the series lagged with itself (ACF) at lag 12 will be perfectly correlated (autocorrelation=1). Subsequently, all power in the spectral density will be concentrated at frequency $1/t$.


How to fix Drupal commons 7.x-3 OgException

Question: Problem is fixed in new version commons 7.x-3.3-rc4
https://drupal.org/node/2067473
Modules:

Organic groups 7.x.2.3
Organic groups access control  7.x.2.3

The content access permissions have been rebuilt.
In OG field settings (as default)
User-User entity
Group visibility Determine access to the group
Group            Determine if this should be a group
I created a Private group with "Joining requires an invitation"
trying to add a post to the group I get following exception:

OgException: Cannot set visibility of node ID 13 as the group node of
  type "user"  does not have the "Group visibility" field attached to
  it.  in _og_access_verify_access_field_existence()  (line 250 of
  srv/www/htdocs/commons7x33rc2/profiles/commons/modules/contrib/og/og_access/og_access.module).

The same happens with a Public group with "Any site member can contribute"
What is wrong and how do I fix this?
Answer: A bit too late maybe but...
...check answer #8 at Organic Groups issues place: https://drupal.org/node/2063479#comment-7882345
I've followed it and solved (at least apparently) the issue.
Hope it helps. Have a nice day!
hip


Passing unquoted function arguments to i in data.table

Question: I'm creating a function for my co-workers to easily analyze some pre-specified datasets. I would like for them to be able to pass "i" arguments to select rows. To make it more robust, I would like to be able pass this argument with or without quotes.
Here is an example that works with quotes …
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
  sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
  where <- parse(text = paste0(list(...)))
  my.dt <- my.dt[eval(where), ]
  return(my.dt)
}
tmp <- test.function(x, 'x==3 | sex=="F"')
head(tmp)

If I remove the quotes, it fails saying "object 'sex' not found"…
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
  sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
  where <- parse(text = paste0(list(...)))
  my.dt <- my.dt[eval(where), ]
  return(my.dt)
}
tmp <- test.function(x, x==3 | sex=="F")
head(tmp)

In addition to the above, I have many failed attempts using quote, substitution and rlang: like this failed example …
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
                sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
  where <- rlang::quos(...)
  my.dt <- my.dt[!!where, ]
  return(my.dt)
}
tmp <- test.function(x, 'x==3 | sex=="F"')
head(tmp, 10)

In addition to any ideas for solutions, I would be grateful if someone could point me toward an simpleton's online resource for understanding symbols/expressions/quotes/etc. As I dug into this problem I realized that I have some serious gaps in my understanding of how R works.
BTW, I've already read through the following, but neither was able to help me: Passing function argument to data.table i
   and
   Passing multiple arguments to data.table inside a function
   .
Comment: How about passing x, sex, and the operator as separate arguments? test.function(x, 3, "F", "|"). Then set up your function to handle each input as a separate variable?
Comment: Thanks for your comment Chris. I'm trying to keep this as simple as possible for the end user, who will not be a proficient R user. That's why I want I want them to be able to pass the argument with or without quotes. Thanks again.
Comment: If you remove quotes you should not use parse anymore. Parse expects character, not an expression.
Comment: Thank you @jangorecki. After seeing Matt's solution, that became clear to me.
Answer: There may be other (better) options, but you can wrap it in tryCatch and use bquote for the unquoted argument
test.function <- function(my.dt, ...){
    where <- tryCatch(parse(text = paste0(list(...))),  error = function (e) parse(text = paste0(list(bquote(...)))))
    my.dt <- my.dt[eval(where), ]
    return(my.dt)
  }

tmp <- test.function(x, 'x==3 | sex=="F"')
head(tmp)
   x sex
1: 1   F
2: 2   F
3: 3   F
4: 3   M
5: 3   F

tmp <- test.function(x, x==3 | sex=='F')
head(tmp)
   x sex
1: 1   F
2: 2   F
3: 3   F
4: 3   M
5: 3   F


A generic terminology for a given object to be estimated?

Question: If one has to suggest, what is it one would call a given object that is to be estimated?
We already have a generic term "estimator" on the one hand. When the context is clear, usually there is no need to coin another term to address the target to be estimated. However, for instance, when we are in the context of estimating a given random variable using a set of random variables, e.g. when we are to project a random variable $Y$ on the linear span of a set of random variables $X_{1}, \dots, X_{k}$, then under regular conditions there is exactly one $\beta$ such that $X := (X_{1}, \dots, X_{k})'$ implies $X'\beta$ is the best linear approximation for $Y$ in the mean-square-error sense; in this case one may naturally call $X'\beta$ an estimator for $Y$. My question is, in a general similar situation, how one addresses $Y$? The "estimand"?
Comment: "Property" is often used in the literature.
Answer: The genetic term is estimand (that which is to be estimated).
An estimator is a rule/formula/method for obtaining an estimate of the estimand.
Comment: Thanks. That was what I was thinking (subject to typo however). The reasoning is simple because it just follows "maximand, summand, integrand, ...". Just want to make sure that usage would not be confusing.


Criar objeto javascript com outros objetos

Question: Preciso pegar os objetos de arrays javascripts que recebo do backend e transfoma-los em outros objetos para conseguir usar na biblioteca React-select.
Meu objeto vem do backend assim:
[
  { nome: 'Fulano', setor: 'Produção', filial: 1  },
  { nome: 'Ciclano', setor: 'Administrativo', filial: 2  },
  { nome: 'Maria', setor: 'Produção', filial: 1  }
]

Para funcionar no React-Select, ele deve ficar assim:
[
  { values: { nome: 'Fulano', setor: 'Produção', filial: 1 }, label: 'Fulano'},
  { values: { nome: 'Ciclano', setor: 'Administrativo', filial: 2 }, label: 'Ciclano'},
  { values: { nome: 'Maria', setor: 'Produção', filial: 1 }, label: 'Maria'}
]

Answer: Você pode transformar uma estrutura na outra:

const original = [
  { nome: 'Fulano', setor: 'Produção', filial: 1  },
  { nome: 'Ciclano', setor: 'Administrativo', filial: 2  },
  { nome: 'Maria', setor: 'Produção', filial: 1  }
]

const adaptado = original.map(usuario => ({
  values: usuario,
  label: usuario.nome
}))

console.log(adaptado)

Além disso, você pode usar o hook useMemo para "memoizar" esse resultado.


Django my models aren't carrying over from file to file

Question: I am getting my menu items to display on the ListView page, but when I click on the link, none of the data displays properly.
Here is my menu-carousel.html
    {% for item in object_list %}

{{ item.title }}

${{ item.price }}

{{ item.description }}

  {% endfor %}

And that works, now here is the broken part, when I got to /menu/1 or /menu/'whatever number'

{{ item.title }}

Price: ${{ item.price }}

Materials: {{ item.description }}

{{ item.description|safe|linebreaks }}

This is what displays in my browser

Price: $

Materials:

Here is my urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from django.contrib import admin
from . import views
from home.models import Menu

urlpatterns = [
    url(r'^$', views.home, name="home"),
    url(r'^menu/$', ListView.as_view(
                        queryset=Menu.objects.all().order_by("-title")[:25],
                        template_name="menu-carousel.html")),
    url(r'^menu/(?P<pk>\d+)/$', DetailView.as_view(
                        model = Menu,
                        template_name="menu-item.html")),
]

and here is my models.py
from django.db import models
from django.conf import settings

class Menu(models.Model):
    title = models.CharField(max_length = 140)
    price = models.IntegerField()
    description = models.TextField()
    image = models.ImageField(upload_to = 'media/' )
    menu = models.CharField(max_length = 10)

    def __str__(self):
        return self.title

Answer: I suppose you've used the wrong context object name in DetailView template. More details by link:
https://docs.djangoproject.com/es/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_object_name
Try to display menu item id with {{menu.id}} instead of {{item.id}}. Also you can use django debug template to see all context objects.
Comment: Thank you! That fixed it! Now I just have to figure out how to get my images to display properly!