Area of rectangle.

Question: I know that why we take area of a rectangle proportional to the product of its width and height. I also know why take area proportional to product. It is due to the theorem of Joint Variation. But it's really hard for me to make a visual concept or make sense of that how product of width and height give us the area of a rectangle?
Comment: That is completely circular, @Heisenberg. You defined the (Riemann) integral as the sum of the areas of smaller rectangles in the first place.
Comment: Area is a very tricky business. More sophisticated approaches to area, e.g., Riemann and Lebesgue integrals, both require the axiom that the area of a rectangle is the product of its sides. You absolutely can't rely on any of these methods to *prove* the formula for area of a rectangle.
Comment: With regard to the area of the rectangle height into width formula is derived by simple integration
Comment: Possibly [related](http://math.stackexchange.com/questions/800699).
Answer: The area of a rectangle of sides $a$ and $b$ is defined to be $ab$. The motivation for this definition is coming from counting points in discrete rectangles. If you arrange $b$ rows of marbles, each row having $a$ marbles, then the total number of marbles you have in the rectangle is $ab$.

Area of rectangle.


How do I refresh a page when clicking on a href? | HTML, CSS

Question: What do I have:
HTML, CSS, JS

What do I need:
Reload a page when clicking on .
What do I know:
I can reload a page using window.location.reload(). To use it in HTML code, I have to put it into

It will execute the given function after you click on the link.
Comment: This answer needs to attract more attention. No excessive code, just clarified, clear information.
Answer: You can simply do as below:

Refresh Page

Comment: Works, but for some reason it takes more time than the marked answer, check it
Comment: because that is being loaded by an explicit function, If you want you can execute it in that way. If still, it will take more time then you should check the order of html page like css, js.
Comment: Try this way:
location.reload(true/false);
If false, the page will be reloaded from the cache, else from the server.
Comment: Still takes a lot of time, like a second
Comment: Did u try this: javascript:window.location.reload(true)
Comment: It takes even more, 3-4 seconds


CAROUSEL não alinhado com a NAVBAR

Question:
texto em negrito
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

  <title>Projeto Site</title>
  <link rel="stylesheet" href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

                Home (página atual)

                História

                Serviços

                Contato

            <form class="form-inline my-2 my-lg-0">
              <input class="form-control mr-sm-2" type="search" placeholder="Pesquisar" aria-label="Pesquisar">
              <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Pesquisar</button>
            </form>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Third slide label

Praesent commodo cursus magna, vel scelerisque nisl consectetur.

      Previous

      Next

Comment: Não alinha onde? Me parece centralizado certinho, seu problema não ficou claro
Comment: Gostaria que ele ficasse alinhada igual a primeira foto...obrigado pela resposta!
Answer: Cara é só vc tirar a nav de  dentro dessa estrutura de container > row > col, pois essa estrutura tem alguns padding e margins do grid do Bootstrap, algo que vc não precisa nessa situação!
Isso está descrito na documentação oficial https://getbootstrap.com/docs/4.0/components/navbar/#containers

Removendo o  container

Código da imagem acima, comentei no código as tag dispensáveis

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

  <title>Projeto Site</title>
  <link rel="stylesheet" href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

                Home (página atual)

                História

                Serviços

                Contato

            <form class="form-inline my-2 my-lg-0">
              <input class="form-control mr-sm-2" type="search" placeholder="Pesquisar" aria-label="Pesquisar">
              <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Pesquisar</button>
            </form>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Third slide label

Praesent commodo cursus magna, vel scelerisque nisl consectetur.

      Previous

      Next

Comment: Muito obrigado!
Comment: @AlexFlausino de nada jovem! Se a resposta resolveu o problema considere marca-la como aceita clicando nesse ícone ✓ abaixo das setinhas ao lado da resposta. Assim ela não fica em aberto mesmo já tendo sido resolvida ;)

CAROUSEL não alinhado com a NAVBAR


End syntax for unbracketed namespace (to mix with bracketed namespace)

Question: As we know, we can't use/mix namespaces in a single file like this:
namespace A;
...
...
namespace B{
   ...
}

does there exist any end syntax for unbracketed namespace, so it would become available to mix two namespaces?  (like it's endif; for unbracketed if) ?
p.s. please, don't suggest to use brackets, I know that already (hence, my question is not "how to mix two namespaces in single file").  but my question is what I ask - if there is an end syntax for unbracketed NS.
Comment: No, it's not possible. Hence the fatal error *Cannot mix bracketed namespace declarations with unbracketed namespace declarations...*
Comment: I would like to emphasise the comment in the answer **However is strongly not recommended to declare two namespaces inside same php script**
Comment: @NigelRen are you sure that this is a duplicate question? please, re-read it  -it is different.
Comment: I flagged the dupe as that is how is has to be done AFAIK.  If you want me to remove it and see if anyone can come up with something else then I will.  It would probably help if you added a specific use case so that it would explain why you want to do this to make the context clearer (IMHO).
Comment: The dupe I flagged was https://stackoverflow.com/questions/22606792/declaring-two-namespaces-in-the-one-file, but see if anything else comes up.
Comment: I think the main problem is a case of which namespace should it use at any point when two namespaces are in play.
Answer: There is no alternative syntax and endnamespace keyword, because there is no real need for it.
Using multiple namespaces in one file is a bad practice and should be avoided anyway, so one way to do this is more than enough. if and endif (and similar) was designed for using in templates since it increase readability when you mix HTML and PHP code. But views does not need to use namespaces at all, thus there is no pointless endnamespace tag. Using brackets is the only way to mix two namespaces in one file*.
* I don't count some ugly hacks like using eval().
Comment: I don't agree with `there is no real need for it`. If there exists `{}` for namespaces, to define its start and end, then that means there is a need to end the namespace. and if the namespaces can be declared with two different methods, both of them should have the endings.
Comment: @T.Todua You have two ways of declaring namespace: file-level (declares namespace for the whole file content) and custom-scope-level (declares namespace for content inside of `{}` brackets). You don't need custom tag to end file-level namespace, because end of file is natural end for this scope.


How to create Page variant Selection rule "if URL contains"?

Question: I want my variant to apply to all pages if the URL contains a certain string, eg: "cars".
So the cars variant should apply to cars, cars/toyota, cars/toyota/camry, etc.
Is there a way to use a wild card (cars/*?)?
I can't find any documentation on this.
Thanks
Comment: * should work. Try under Variant -> Selection rules, in the pulldown Select:URL Path then Add. In the new dialog box, select "Allow access to the following pages" then enter "cars/*" in the textarea, then save. According the description below the textarea which says: `The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog.`
Comment: if "cars" is a contentype, is easy, just in panels selection rules, apply node:type="cars"
Comment: The question lacks of context to provide accurate answer because there are several possibilities to build up url ... and this usually happen in views, panel or page manager ... and the answer will change, please elaborate about what you are trying to do with more details
Answer: Try under Variant -> Selection rules, in the pulldown Select:URL Path then Add. In the new dialog box, select "Allow access to the following pages" then enter "cars/*" in the textarea, then save. According the description below the textarea which says
The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog.

Answer: /* works. The issue I was having was I was separating them by  commas, where's they had to be separated by line breaks.


How to get value from dropdown menu in bootstrap 4?

Question:

                    Material Type

                    Mud

                    Cloth

                    Thread

                    Jute

                    Cotton

                    Cane

                    Bamboo

Can I get the value from the menu after selecting like following?
var email=document.getElementById('signUpEmail').value;

So that I can use this variable in ajax.
Edit
As @Timir suggest to use select then the menu is look like

<select class="custom-select custom-select-lg mb-3" id="mydropdown">
  <option selected>Material Type</option>
  <option value="Mud">Mud</option>
  <option value="Cloth">Cloth</option>
  <option value="Thread">Thread</option>
  <option value="Jute">Jute</option>
  <option value="Cotton">Cotton</option>
  <option value="Can">Can</option>
  <option value="Bamboo">Bamboo</option>
</select>

Comment: are you looking for https://v4-alpha.getbootstrap.com/components/forms/#select-menu ?
Comment: No you can't - it's a dropdown menu used for navigation rather than a select input. Check out [Bootstrap forms](https://getbootstrap.com/docs/4.0/components/forms/#form-controls) for a select dropdown
Answer:
Can I get the value from the menu after selecting like following?

No, there are no input to retrieve their value.
but you can get the text inside the link like
$('.menu2 a.dropdown-item').on('click', function(){
    $(this).text()
});

Answer: Turn it into a select, give it an id, then say:
    $("#mydropdown option:selected").val();
Comment: Yes, that's what I was suggesting. Were you able to test the val() approach?
Answer: There are workarounds for basically everything in JavaScript. Including this. Without using JQuery, you could add an event listener, or you could make an onlick within each option or anchor tag.
When you click on the drop down and set the option, it calls the function which sets the variable. So even though there is no input box... you are just setting a global variable. And then you utilize that variable as a part of a form or however you plan on using it.


Is the probability of the union of $N$ sets increasing in all terms? i.e., $P(A\cup B)=P(A)+P(B)-P(A)P(B)$ is increasing in $P(A)$ and $P(B)$

Question: I wonder if the pprobability of the union of $N$ independent events $P(A_1\cup A_2\cup ...A_N)$ is increasing in all its terms when it is decomposed. To be more precise Let $N=2$ then the intersection of two tests can be given as $P(A\cup B)=P(A)+P(B)-P(A)P(B)$, which  can be translated to some function of two variables  $f(x,y)=x+y-xy$. It is obvious that $f(x,y)$ is increasing in both $x$ and $y$. In a similar way, if we write the intersection of $3$ events we will have the function $$f(x,y,z)=x+y+z-(xy+xz+yz)+xyz$$ which is also increasing in all $3$ terms $x$, $y$ and $z$. If $N$ is $4$ or $5$ or in general $N$, do we have any proof which shows that $f(x,y,z,...)$ is increasing in $x,y,z,..$?
Thanks in advance.
Sorry for previous confusing post.
Comment: May you explain a little bit further what are you asking for ? What are "terms" of sets : their elements ? If you are consider "usual" sets what kind of operation on them you are considering with "+" and "-" ? Thanks ...
Comment: @MauroALLEGRANZA please see the edit. I think it is okay now. Please let me know if there are some more issues. I was confused.
Comment: @MauroALLEGRANZA I am talking about "Principle of inclusion and exclusion"
Comment: @MauroALLEGRANZA are you able to understand the question now? please feel free to edit. I will really appreciate.
Comment: @MauroALLEGRANZA i think my question is slightly different isnt it? I want to see the monotonicity property.
Comment: and I must take the derivative w.r.t. all variables and who that is it always positive?
Comment: @MauroALLEGRANZA No. Symbolically I change all $\cap$ at the right hand side to multiplication and this gives me a function as I described. $x$ and $y$ are not actually the sets they represent the probabilites coming from those sets. $P(A\cup B)=P(A)+P(B)-P(A)P(B)$. Okay this is the one!
Comment: Note that $P(A \cap B) = P(A) P(B)$ is not true in general; it's only true when $A,B$ are independent events.
Comment: @NateEldredge i edited the question including the information about independency of the events.
Comment: Please replace "intersection" by "union", three times in the question.
Answer: If the events $(A_i)$ are independent, then
$$
P(A_1\cup A_2\cup\cdots\cup A_N)=1-P(A_1^c\cap A_2^c\cap\cdots\cap A_N^c)=1-\prod_{i=1}^NP(A_i^c),
$$
hence
$$
P(A_1\cup A_2\cup\cdots\cup A_N)=G(P(A_1),P(A_2),\ldots,P(A_N)),
$$
where
$$
G(x_1,x_2,\ldots,x_N)=1-\prod_{i=1}^N(1-x_i),
$$
that is, yes, $P(A_1\cup A_2\cup\cdots\cup A_N)$ is a nondecreasing function of each argument $P(A_i)$.
Comment: sorry forgot to replace it, edited. By the way thanks for the answer. The question was about this MO question and the following answer, http://mathoverflow.net/questions/155478/comparing-the-stopping-times-of-two-stochastic-processes.


Best way to call Clojure function with named/default args from Java

Question: When calling a Clojure function from Java, what's the best way to specify named arguments to the function?
I have the following function:
(defn myFn [a b & {:keys [c d] :or {c 1 d 2}}]
   ; do something
   )

And I currently call it from Java with lines like this:
IFn myFn = Clojure.var("my.namespace", "myFn");
myFn.invoke(5, 6, Clojure.read(":c"), 7, Clojure.read(":d"), 8);

I find the Clojure.read... parts of the above statement verbose.  Is there a simpler way to make this call?
Comment: Why don't you use a function with arity 4?
Comment: Because the arguments are optional.  I also call the same function without c and d.
Answer: The question is not about how to pass named argument, but how to create keywords in Java code:
import clojure.lang.Keyword;
// others omitted...
myFn.invoke(5, 6, Keyword.find("c"), 7, Keyword.find("d"), 8);

Clojure.read would be considered too cumbersome for the task and too dangerous as it can read in any code.
Comment: You seem to have a typo: invokde should be invoke.
Comment: This is still verbose.  Is there anything shorter?  Or is there a better way to design this interface between clojure and Java?  Like using clojure prototypes or multi-methods?
Comment: @Jason Thanks, fixed. Regarding the further question, I don't see any *shorter/better* ways than this method invocation with arguments prepared. Not much redundancy here to be removed.
Comment: Hmmm... I feel an unsettling dissatisfaction with this answer. I suppose if I factored out the `Keyword.find("c")` and "d" bits into constants then they can be reused and the call to `invoke` will be shorter. So I accept your answer, but part of me is still waiting for something better :-)


How can I play two overlapping parts with different sounds on keyboard?

Question: I'd like to be able to play two separate overlapping parts using different sounds, without having to invest in two separate keyboards.
In my new project, we're moving from some arrangements laid down in logic to live performance. We'd ideally like to play everything live without relying on anything that's been pre-recorded. However, there are parts of our current arrangement which would require me (as the only keyboardist) to play two parts at the same time. These parts may overlap in range, and require different sounds.
What sorts of features would enable me to do this?
Comment: We don't do equipment recommendations here. I can tell you that there are keyboards that can do this. Have you tried going to a music instrument shop or calling an online retailer?
Comment: I've made a reasonably substantial edit to remove the gear recommendation part. This should mean that the question does not get closed. You should be able to use the contents of any answers to inform your shopping list. Hopefully this is helpful; feel free to revert the edit.
Answer: There are two main ways to play different sounds on a keyboard: layers and splits.
A layer is when you play more than one sound at the same time. For example, you could play a piano sound and a string sound together.
Layers could be velocity sensitive; depending on how hard you play, different sounds are heard. For example, my keyboard has an orchestral sound. If I play softly, I get woodwinds. Slightly harder, and the strings come in. Even harder, and the brass show up. And if I really give it a whack, the timpani come in at the low end. This uses both velocity sensitive layers, and some splits.
A split is when you play different sounds in different parts of the keyboard. For example, a bass sound in the left hand, and an electric piano in the right.
Splits are almost always defined with a split point. Above that point, one sound is used, and below it another is used. Sometimes you can have gradual split points; The sounds fade into each other over several keys. Some keyboards allow you to set split points anywhere. Others restrict you to certain predefined locations.
Different manufacturers sometimes use different terms to describe this functionality.

So, to play two different parts with different sounds, you need splits. Many, many keyboards have this capability. You also need the ability to transpose each sound separately. This is also quite common.
Generally speaking, there are a few different types of keyboard:

Workstations have many features, and will easily support most kinds of layering, splitting, and transposition. They have a wide range of sounds. The user interfaces often are a bit quirky. To put it nicely.
Stage pianos. This is not a great name, but there's a whole class of keyboards like the Nord Stage and Korg Grandstage that are not quite a workstation, but are significantly more powerful than a digital piano. They are designed for ease of use during live performance, and will support splitting and layering. There are likely to be less options than a workstation.
Digital pianos are more focused on just being a piano. They are less likely to have voice-specific transposition. Most will still have split points.
MIDI controllers have no brains at all; you run a program on your computer to generate sound. Any software platform that's worth using will support all kinds of layering and splitting. It's possible to use almost any keyboard as a MIDI controller these days.
Analog or virtual analog synthesisers not support any of these features at all. Neither will many "vintage" keyboards. Actual vintage, or modern-reproduction-vintage.
Arranger keyboards are designed to play along with you. They will often support all sorts of splitting and layering.

There are probably other subcategories. In general, you probably require a workstation, stage piano, or midi controller of some sort. As there are many possible options, you will need to decide how many parts you need to play at once, and how complicated the splits and layers need to be. There are also many other tradeoffs; sound quality, weight, ruggedness, aesthetics, etc. Those are outside the scope of this question (and probably this site).
Comment: Actually, many synthesizers allow splits. Even something as vintage as the Roland Jupiter 8 from 1981 could do both layer and split; on the later Jupiter 6 you could even set the split point.


Renders my safe_value instead of the value

Question: When I'm displaying the contentfield of a node, Drupal only shows the safe_value. I want to use the full HTML from my WYSIWYG. I know this because, when I change $items[$id][$delta]['safe_value'] into $items[$id][$delta]['value'] (in modules/field/modules/text/text.module line 159 in the text_field_load hook implementation), it displays the correct HTML from my WYSIWYG.
How can I change this, so that Drupal shows the value with the HTML?
Answer: I needed to change the filter of the field. That fixed the problem.
Comment: Could you please elaborate a bit more? If you remember after more than a year, that is.


How to find id in array object then edit and delete a object in oop javascript?

Question: I coding demo student management . But have problem below, please help me resolve them.
The requirement

Manage student : add, edit, remove
Using console building data table. The table contain fiedls: id Name Age Point
Using console call function
List all student have point > = 5;

This is my code:

//
function Student(id, name, age, point) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.point = point;
}

Student.prototype = {
  setId: function (value) {
    this.id = value;
  },

  getId: function () {
    return this.id;
  },

  setName: function (value) {
    this.name = value;
  },

  getName: function () {
    return this.name;
  },

  setAge: function (value) {
    this.age = value;
  },

  getAge: function () {
    return this.age;
  },

  setPoint: function (value) {
    this.point = value;
  },

  getPoint: function () {
    return this.point;
  },

};

function StudentController(student) {
  this.listStudent = [];
  this.id = 1;
}

StudentController.prototype = {
  addNew: function (name, age, point) {
    var student = new Student(this.id, name, age, point);
    this.listStudent.push(student);
    this.id += 1;
    return student;
  },

This is function find id . But it always return last id in array object.
  findId: function (id) {
    var student = null;
    for (var i = 0; i < this.listStudent.length; i++) {
      if (id = this.listStudent[i].getId()) {
        student = this.listStudent[i];
      }
    }

    return student;
  },

This is function edit student. But it can't getId from function findId();
  editStudent: function (student) {
    var oldStudent = this.findId(student.getId());
    console.log('oldStudent', oldStudent);
    for (var x = 0; x < this.listStudent.length; x++) {
      if (oldStudent = this.listStudent[x].getId()) {
        this.listStudent[x] = student;
      }
    }
  },

This function same too editStudent() function.
  deleteStudent: function (student) {
    var crrentStudent = this.findId(student.getId());
    for (var y = 0; y < this.listStudent.length; y++) {
      if (crrentStudent.getId() === this.listStudent[y]) {
        this.listStudent.splice(y, 1);
      }
    }
  },

This this function sort point of student > = 5. But look like not working :(
  // find point student > = 5
  findByPoint: function (point) {
    var point = '';
    for (var i = 0; i < this.listStudent.length; i++) {
      if (this.listStudent[i].getPoint() >= point) {
        return point;
      }
    }
  },

  showStudent: function () {
    console.table(this.listStudent);
  },
};

var studentController = new StudentController();
studentController.addNew("Hanh", 20, 8);
studentController.findId(1);
studentController.editStudent();
studentController.deleteStudent();

Please help me resolve and explanation. Thank you so much !!
Answer: The problem is pretty straight forward, for a comparison operator you need == in if condition, = is for assignment and adding
Change findId() function
findId: function (id) {
    var student = null;
    for (var i = 0; i < this.listStudent.length; i++) {
      if (id == this.listStudent[i].getId()) {    // change here
        student = this.listStudent[i];
      }
    }

    return student;
  },

and in editStudent function
editStudent: function (student) {
    var oldStudent = this.findId(student.getId());
    console.log('oldStudent', oldStudent);
    for (var x = 0; x < this.listStudent.length; x++) {
      if (oldStudent == this.listStudent[x].getId()) {    //change here
        this.listStudent[x] = student;
      }
    }
  },

Comment: Thank for your answer. So please help me explain why function `editStudent` can't call `student.getId()` from function `findId` ?
Comment: You are not passing any argument to editStudent function,


Issues with authentication and Redux/Router

Question: 1. How to access to Redux dispatch function and router history object in a a function like bellow
export const loginHelper = ({ userInfo }) => {
    dispatch(loginUser(userInfo)); // from where can i get dispatch ??
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    history.push('/foo/search'); // from where can i get history ??
}

2. Instead of localStorage Where can I store my user info data so when i close the browser it gets cleared too
Answer: Stop using localStorage
Here's the deal: most of the bad things about local storage aren't all that important. You can still get away with using it but you'll just have a slightly slower app and minor developer annoyance.
Local storage wasn't designed to be used as a secure storage mechanism in a browser. It was designed to be a simple string only key/value store that developers could use to build slightly more complex single page apps. That's it.
What the problem really boils down to is cross-site scripting attacks (XSS).
If an attacker can run JavaScript on your website, they can retrieve all the data you've stored in local storage and send it off to their own domain. This means anything sensitive you've got in local storage (like a user's session data) can be compromised.
To answer your question, try dispatching the userInfo and save it in your store through reducers. then use that to query the userInfo data.


Is there a theory term for using a restricted 'vocabulary' of chord types?

Question: An example - Good Life by Inner City:

The repeating progression here is (as I hear it) bm7 - f#m7 - am7 - em7.
Whilst not a standard diatonic progression, the consistent use of this one chord type maintains a sense of... er... consistency.
I have noticed that many songs and even whole styles of music can be characterised by their use of certain types of chord (and avoidance of other types of chord). Blues, for example, is associated with the dominant 7th, used (rather like my example above) in a way not fully consistent with standard diatonic/functional harmony.
Are there music theory terms for the size of 'vocabulary' of chord types used in a song, or the deliberate restriction of that 'vocabulary'? (Especially as doing so seems to be an 'excuse' for straying from the diatonic scale, and other ways of deviating from the diatonic do have names...)
Comment: @ToddWilcox the example seems to strongly exhibit parallel harmony, though I think the use of a restricted chordal palette can be observed in works that don't (or at least, not to the same extent).
Comment: Is this different from [parallel harmony](https://en.wikipedia.org/wiki/Parallel_harmony)?
Comment: Maybe the term is "four chord song"? It sure seems that some pop songs spam exclusively the I-V-vi-IV chord progression at times....
Answer: I've heard the term harmonic palette used many times. We might say, for instance, that the harmonic palette of Herbie Hancock's "Maiden Voyage" is limited to minor seventh chords (with Dorian extensions).
The metaphor, which is perhaps obvious, is to the visual arts. It's most often used in relation to painting, when we say that palette is the "particular range, quality, or use of color" (that's from Merriam-Webster). In fact, M-W has a second definition of "a comparable range, quality, or use of available elements." In music, harmony is one of those "available elements."
And this isn't the first time we've hijacked a visual term for our uses. What makes music "chromatic" if not the addition of color ("chroma")?
And I'd be remiss if I didn't also point out the term "ostinato" for the particular repeating progression that you pointed out. An ostinato is a repeating musical element, whether it be motivic, rhythmic, harmonic etc. I know you knew that already, but the two can be closely related, as in your example.


"Undefined offset" Soma de Array multidimensional

Question: Meu sistema, lê os arquivos XML dentro de uma pasta e coloca os dados ("número da nota fiscal", "código do produto","quantidade") dentro de um array.
Criei um novo array para ter o total por produto, onde a conta está correta, e o resultado é o que eu espero.
O problema é que eu recebo erro abaixo:
 Erro na Linha: #160 :: Undefined offset: 10452
C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php

Erro na Linha: #160 :: Undefined offset: 10485
C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php

Erro na Linha: #160 :: Undefined offset: 10433
C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php

Erro na Linha: #160 :: Undefined offset: 3767
C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php

Erro na Linha: #160 :: Undefined offset: 3768
C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php

C:\xampp\htdocs\controledeentregasver209112019\Romaneio\RomaneirodeCarregamentoTeste_1.php:171:
array (size=5)
  10452 => float 30
  10485 => float 20
  10433 => float 10
  3767 => float 40
  3768 => float 30

Segue o código fonte:
    <?php

$notaPesoQuantidade = [];
$totalizando=[];

// ****************PEGANDO OS ARQUIVOS DA PASTA
$path   = "./arquivos/";
$files = scandir($path);
foreach ($files as &$value) {
    if($value=='.' ||$value=='..'):
    else:
     $arquivo = simplexml_load_file('./arquivos/'."$value");

foreach($arquivo->NFe as $key => $xml){
//dados DA nf
$nNF = "".$xml->infNFe->ide->nNF.""  ;
}
?>

<?php
//IMPRIMINDO OS PRODUTOS DA NOTA FISCAL
echo "
";

echo " NF-e $nNF ($value) ";
?>

      COD

      Quant

<?php
//PERCORRENDO OS PRODUTOS DA NOTA FISCAL
 foreach ($xml->infNFe->det as $value) {
?>

      <?php echo $value->prod->cProd; ?>
      <?php echo $value->prod->qCom; ?>

  <?php

  $nNF = intval ($nNF);
  $cProd = intval ($value->prod->cProd);
  $qCom= floatval ($value->prod->qCom);

//  $notaPesoQuantidade[$nNF]["$cProd"]=$qCom;

 $notaPesoQuantidade[] = [

         'nota'=>$nNF,
         'produto'=>$cProd,
         'quantidade'=>$qCom

                                 ];

?>

<?php
}
?>

<?php

echo "
";
echo "
";
echo "
";

endif;

}

echo " ***************** CARREGAMENTO TOTAL ******************";

foreach ($notaPesoQuantidade as $key => $value) :
    //$key = indice do array
    //$value = é o arrai, ex $value['nota']
    $p = $value['produto'];
    $q = $value['quantidade'];

          $totalizando[$p]+=$q;

endforeach;

  var_dump($totalizando);

?>

Answer: A solução que encontrei foi mudar a lógica. primeiro coloquei tudo em um array por produtos e depois somei.
$compras[$cProd][] = $qCom;

Soma:
foreach ($compras as $key => $value) {
    echo "
" . "$key = " . array_sum($value) . "
";
}


Call function with parameter in its name

Question: Hello I'm using laravel 4. I want to know how to call function like :
$model->trans('name'), $model->trans('title')
as
$model->transName(), $model->transTitle()
So this mean I want to call function trans with parameter name,or title, but the function name and parameter are attached.
It's like Eloquent when we do something like this : whereEmail(), whereId().
I hope this makes a sense.
Thank you
Comment: Well, it doesn't make sense, but its not a problem as long as you can call functions in php just like a string. `function trans($field) { $function = 'trans' . $field; $function(); }`
Comment: If you don't want to create `trans function` - check out __call magic method - http://php.net/manual/en/language.oop5.overloading.php#object.call
Comment: but actually it only means poor application design
Comment: What do you mean by ` poor application design?,  it is means this method is not goo ?
Comment: I mean if you need to do something like you've described in your question probably you went wrong somewhere. Can are you explain, what you trying to do?
Comment: I just liked this way it is so clean and simple to use.
Comment: Once again, can you explain what you trying to do? After you call `$model->transName()` what it will return?
Comment: It will return the translation of the attribute in param from database.
Answer: Okay, if you sure that you need it, here is working example using magic method
<?php

class Model
{
    public function __call($func, $args)
    {
        if(strstr($func, 'trans'))
        {
            return $this->trans(strtolower(str_replace('trans', '', $func)));
        }

       return parent::__call($func, $args);
    }

    public function trans($field)
    {
        return $field;
    }
}

$m = new Model();

$m->transSomething();

When undefined method will be called, it will check if method name starts with 'trans', and if so pass it to $this->trans() without "trans" at beginning.
But in my opinion the way with $model->trans('somefield') is better.
Comment: Comment: I get some methods call issue like : `Call to a member function inLanguage() on a non-object` when I use __call in the model, have you any idea ?
Comment: I modified the example, try it now.
Comment: I modified also the code, and now it works :). Thank you a lot


When is a Fourier transform of a function continuous

Question: I have read about a following claim in a book but cannot prove it.
If a function $\psi(x)$ fulfills $\int dx|\psi(x)|^2|x|^2<\infty$, its Fourier transform $\phi(k)$ is continuous and nearly everywhere differentiable.
Can anyone explain this claim to me?
Comment: Hint: show that the Fourier transform is in the Sobolev space $ H^1(\mathbb {R})$. Functions in this space are (almost everywhere equal to functions that are) continuous and almost everywhere differentiable.
Answer: You can show this directly. Suppose $\psi$ is as stated, and define
$$
    \hat{\psi}_n(s)=\frac{1}{\sqrt{2\pi}}\int_{-n}^{n}\psi(x)e^{-isx}dx.
$$
The function $\hat{\psi}_n$ is infinitely differentiable, and $\{ \hat{\psi_n} \}_{n=1}^{\infty}$ converges uniformly to $\hat{\psi}$ as $n\rightarrow\infty$ because
\begin{align}
 |\hat{\psi}_n(s)-\hat{\psi}(s)|
  & \le \frac{1}{\sqrt{2\pi}}\int_{|x|\ge n}|\psi(x)|dx \\
  & \le \frac{1}{\sqrt{2\pi}}\left(\int_{|x|\ge n}|x\psi(x)|^2dx\right)^{1/2}
        \left(\int_{|x|\ge n}\frac{1}{x^2}dx\right)^{1/2} \\
  & \rightarrow 0 \mbox{ as } n\rightarrow\infty.
\end{align}
And $\{ \hat{\psi}_n ' \}$ converges in $L^2$ because
$$
     \hat{\psi_{n}}'(s) = \frac{1}{\sqrt{2\pi}}\int_{|x|\le n}e^{-isx}(-ix)\psi(x)dx,
$$
and the Parseval identity gives
$$
       \|\hat{\psi_n}'- \widehat{(-ix\psi)}\|=\int_{|x|\ge n}|x\psi(x)|^2dx
      \rightarrow 0 \mbox{ as } n\rightarrow \infty.
$$
Therefore,
\begin{align}
      \int_{0}^{x}\widehat{(-ix\psi)}(s)ds &= \lim_n \int_{0}^{x}\hat{\psi_n}'(s)ds \\
   & =\lim_n \hat{\psi_n}(x)-\hat{\psi_n}(0) \\
   & =\hat{\psi}(x)-\hat{\psi}(0).
\end{align}
This proves that $\hat{\psi}$ is an absolutely continuous function on every finite interval because it is the integral of $\widehat{(-ix\psi)} \in L^2(\mathbb{R})$. It follows that $\hat{\psi}$ has a derivative a.e. on $\mathbb{R}$, with $\widehat{\psi}'=\widehat{(-ix\psi)}$ a.e., and $\hat{\psi}$ is the the integral of its derivative.


Absolute convergence of $\sum\limits_{n=0}^{\infty} \frac {z} {(z+n)^2}$

Question: I want to check the absolute convergence of $\displaystyle\sum_{n=0}^{\infty} \frac {z} {(z+n)^2}$ in the half plane  $\Re(z)>0$, and to see if the convergence is uniform or locally uniform. How do I find the sum function?
Answer: To check the absolute convergence, use
$$
|z+n|^2\geq |Re(z+n)|^2=(Re z + n)^2
$$
and comparison with $1/n^2$.
Because of $z$ in the numerator, the convergence of this series is locally uniform in any compact subset of the half plane $Re z > 0$.
I don't have the sum function for your summation, but there is a formula which gives the following summation.
$$
\sum_{n=-\infty}^{\infty} \frac{1}{(z+n)^2}=\frac{\pi^2}{(\sin\pi z)^2},\
$$
for non-integral $z$. You can obtain this formula by contour integration of
$$f(s)=\frac{\pi\cot\pi s}{(z+s)^2}$$


How to create something like a textual "add other term" for taxonomy terms?

Question: How can I setup taxonomy terms so that you can have an extra field called "others", where you can add your own terms if the term you want to use is not defined yet as a term of that taxonomy?
I have researched and came across a module called Select(or other). It does what I want, but it is in text.
My problem now is that I've added so much taxonomies for my student record content type (like countries, or faculties). So I've gone too far and cannot cancel (undo) the taxonomies and replace them with the module I found.
Any suggestion of how to add something like such extra field to the existing taxonomy module?
I imagine that when users insert data, they might not find appropriate terms to choose from. So I want to give them an option that "if current term don't apply to you, then please insert your term manually".
I'm still newbie in Drupal7 and PHP programming.
Answer: When you go to your Taxonomy Vocabulary ([your_domain]/admin/structure/taxonomy/your_vocabulary) you can click on Manage Fields tab and add any field you want. Or go to [your_domain]/admin/structure/taxonomy/your_vocabulary/fields.
Comment: will that make the user add new filed by himself in content type?
i mean i dont expect the users to have any access other than the content type when inserting data.
Answer: Consider something that looks like this "Type of Fruit" taxonomy (with 'Banana' and 'Pear' as the only existing terms):

Obviously, the Select (or other) module that you mentioned is for select lists, you cannot use it for taxonomies. However, to somehow address your requirement like "... insert term here ...", you might want to consider using "Widget type" = "Autocomplete term widget (tagging)" when you actually define the Term reference field.
To further enhance the experience of your users, you may want to also consider the Autocomplete Deluxe module or the Chosen module (for better UI and functionality).
Comment: Oh very nice idea..i always thought that tagging will get the user to guess what are the option available. but never knew it could do that!
i think I'll use the the Field Description to tell the user what the the options available, so that he doesn't create a (dum term) by himself, otherwise, i would be a mess.
i think the solution to my problem is perfectly addressed. Thank you very much :)


What is the meaning of a limit as $e^{(n+1) \infty}$ in WolframAlpha?

Question: I inputted the following into WolframAlpha:
lim x to 0 of (cotx)/x^n
And I got
$$\lim_{x \rightarrow 0}{\frac{\cot{x}}{x^n}} = e^{(n+1) \infty}$$
What does this mean?
Comment: I think if you write that as an answer on an exam, it will be marked wrong.
Comment: WA often gives Wrong Answers for limits, because its programmers anyhow use ad-hoc heuristics. I have experienced them doing that: Sometimes, the wrong answer would even appear before it is substituted by the correct answer. Other times, contradictory answers would appear. At any point in time (including in the future), you can easily come up with an infinite class of limits that WA will give the Wrong Answer to. I'll leave it as a fun exercise for anyone interested.
Answer: It probably denotes that the final value of the limit depends on $n$. Specifically, if $n+1 < 0$, then the limit is $\to e^{-\infty} = 0$ while if $n+1 >0$, then the limit is $\to e^{+\infty} = \infty$.
Comment: But for certain values of $n$ if the limit is not defined then how does it compensate for that?
Comment: And if $n+1=0$ it is  $\lim\limits_{x \rightarrow 0}{x \,{\cot{x}}} = e^0=1$
Comment: Simple answer : It doesn't compensate. It compensates for these values which the limit exists and the sign of the infinity on the exponent is defined by the strict sign of $n+1$ (not equivalent to $0$).
Comment: Presumably W. Alpha considers $0\cdot \infty$ to be $0.$
Comment: @DanielWainfleet: No, you cannot assume WA actually does it right; see [my comment on the question](https://math.stackexchange.com/questions/3049012/what-is-the-meaning-of-a-limit-as-en1-infty-in-wolframalpha/3049015#comment6297359_3049012).
Comment: @user21820 . I wouldn't assume that WA does it right.  My comment was not  serious.
Comment: @DanielWainfleet: Lol okay!


Why did Greece go through over Russia in Euro 2012?

Question: Given that both Greece and Russia were tied on 4 points, with Russia having +2 goal difference and Greece having +0, why did Greece finish higher than Russia (and thus progress to the knock-out stages) in the group in Euro 2012?
<code>Country     W   D   L   GD  Pts
Czech Rep.  2   0   1   -1  6
Greece      1   1   1   0   4
Russia      1   1   1   2   4
Poland      0   2   1   -1  2
</code>
This question seems to indicate Russia should be favoured over Greece (and this is what I thought was the case as well?)
Comment: Wikipedia: https://en.wikipedia.org/wiki/UEFA_Euro_2012#Group_A and https://en.wikipedia.org/wiki/UEFA_Euro_2012_Group_A
Answer: The rules in Euro 2012 (see 8.07) state that if 2 teams are equal on points, the first criteria applied to separate the teams is the winner of the game of the respective teams. If the teams had drawn and were still equal points, only then would it be decided by goal difference.

If two or more teams are equal on points on completion of the group matches, the
following criteria are applied, in the order given; to determine the rankings:

higher number of points obtained in the matches among the teams in question;
superior goal difference in the matches among the teams in question (if more
than two teams finish equal on points);
higher number of goals scored in the matches among the teams in question (if
more than two teams finish equal on points);
superior goal difference in all the group matches;
higher number of goals scored in all the group matches;
position in the UEFA national team coefficient ranking system (see Annex I,
paragraph 1.2.2);
fair play conduct of the teams (final tournament);
drawing of lots.

An exception to this is 8.08, which handles cases where two teams are tied, and they play each other in their last group match;

If two teams which have the same number of points, the same number of goals
scored and conceded play their last group match against each other and are still
equal at the end of that match, the ranking of the two teams in question is
determined by kicks from the penalty mark (Article 16), provided no other teams
within the group have the same number of points on completion of all group
matches. Should more than two teams have the same number of points, the criteria
listed under paragraph 8.07 apply.
Answer: It's because Greece beat Russia 1-0. In the Euro, when teams are equal on points the decider is which team beat the other. Goal difference is the second decider in the event of the two teams having drawn their match.
Answer: The first criteria applied to separate the teams is the winner of the game of the respective teams (head to head). If the teams had drawn and were still equal points, only then would it be decided by goal difference. This follows the Champions League method rather than the World Cup method.
Enforced, basically, to stop a 'Peru 78' type event, whereby Argentina intentionally delayed the kick-off of its last match to await the result of the Brazil-Poland encounter which favoured Brazil, 3-1. Argentina now had to beat Peru by four clear goals to reach the final. The hosts managed to do it with what some saw as a suspicious degree of ease. Trailing 2–0 at half-time, Peru simply collapsed in the second half, and Argentina eventually won 6–0.
Source: Personal knowledge, but text from: Wikipedia
Comment: -1: I don't see how tiebreaking by head-to-head match result could help avoiding the Argentina–Brazil situation when their head-to-head match ended with a goalless draw.
Comment: It wouldn't have helped in that instance had it been implemented, but that was why it was introduced to give another layer before relying on goal difference.
Answer: Basically... Greece got through due to head to head vs Russia (1-0 win) but Holland can still qualify because if they win by more than two goals then 3 teams will be on the same points meaning the head to head results no longer counts, so it goes to goal difference


A smooth topological embedding that is not a smooth embedding

Question: I am reading Introduction to smooth manifolds by Lee. In example 4.18 it says that the map $\gamma: \mathbb{R} \rightarrow \mathbb{R}^2$ given by $\gamma(t) = (t^3,0)$ is not a smooth embedding, since  $\gamma '(0)= 0$. I am confused why the fact that $\gamma '(0)= 0$ implies that $\gamma$ is not a smooth immersion. I know that $\gamma ' = (3t^2,0)$ and so the only value that gives $0$ is $t = 0$, doesn't this say that $\gamma '$ is injective? Can anyone clarify this for me? Thanks!
Answer: $\gamma$ is an immersion if for every $t\in\mathbb{R}$, $\gamma'(t)$ is injective. Equivalently, the rank of the $\gamma'(t)$ must be maximal for every $t$. If $\gamma'(0)=0$, then the derivative has rank $0$ at $t=0$, so $\gamma$ is not an immersion. For $t\neq 0$, the rank of $\gamma'(t)$ is $1$.
Comment: Thanks!! So then, the fact that the only value that maps the derivative to $0$ is not equivalent to the condition that $\gamma '(t)$ is maximal rank? Or how are these conditions are related. It's just I always thought about finding injective maps by showing the only value that mapped to $0$ was the $0$ element in the domain.
Comment: $\gamma'(0)$ is the zero map, which is not injective. A linear map is injective if and only if its matrix has maximal rank. So if there is a value of $t$ such that the rank of the Jacobian matrix is not maximal, for that value of $t$, $\gamma'(t)$ is not injective.


AngularJS: access to a controller of a template from a directive function

Question: Let's say I have a directive mydir applied to the  element:
.
Inside  I have an embed
 used for the templating:

My template has a dedicated controller:

...

Controller1Ctrl has a declared function foo():
app.controller("Controller1Ctrl ", ['$scope',
    function ($scope) {
        $scope.foo = function() {
             console.log("I am in foo...");
             ...
        }
    }
]);

And I want to invoke this function foo() from my directive on some event (let's say scroll):
app.directive("mydir", function ($document, $route) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            $document.bind('scroll', function (evt) {
                scope.$apply(attrs.scrollable);
                // here!
                scope.$apply("ctrl1.foo()");
                console.log("Just invoked foo()");
            });
        }
    };
});

The problem is that scope.$apply("ctrl1.foo()"); does nothing. No errors in console. I see my "Just invoked foo()" log there, but there is no "I am in foo...". I suppose that this is because mydir directive simply doesn't see ctrl1 object. While I see the contents of my template on the page (so it is active template).
But how can I achieve it?
And yes, I can not apply mydir to the
 inside template. Please don't ask why, simply can not. It should be strictly applied to the .
Answer: You can use a $broadcast to trigger a custom event.
Broadcast an event from your directive
scope.$broadcast('myEvent', myVariable);

And then listen to that event in your controller
$scope.$on('myEvent', (event, myVariable) => {
    // deal with the event
});

Edit
Directive
app.directive("mydir", function ($document, $route) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            $document.bind('scroll', function (evt) {
                scope.$apply(attrs.scrollable);
                console.log("Just invoked foo()");

                // Broadcast the event
                scope.$broadcast('myEvent');

            });
        }
    };
});

Controller
app.controller("Controller1Ctrl ", ['$scope',
    function ($scope) {

        $scope.foo = function() {
            console.log("I am in foo...");
            ...
        }

        // listen for the event
        // call $scope.foo() every time the event is received
        $scope.$on('myEvent', (event) => $scope.foo());

    }
]);

Comment: Could you please describe it a little bit more detailed. I am newbie in the AngularJS. Where should I place this **broadcast**? Inside the directive function?
Comment: Okay, thank you, that's much closer to what I want to achieve. But now `$scope.foo()` becomes invoked multiple times, while directive's event function only once. I think this is a direct aftermath of the broadcasting. Any ideas how to improve it?
Comment: Well, actually this is an another problem related to how this event is applied to the controller. I am accepting your answer as it answers generally my initial question.
Comment: I am not sure why that might be the case.
Comment: It will be my another question :-)
Answer: mdir directive has scope which is parent scope of emded template controller (Controller1Ctrl ). If you want invoke some function in child controller use $broadcast
app.directive("mydir", function ($document, $route) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            $document.bind('scroll', function (evt) {
                scope.$apply(attrs.scrollable);
                // here!
                scope.$broadcast("scrolled");
            });
        }
    };
});

in Controller1Ctrl listen
app.controller("Controller1Ctrl ", ['$scope',
    function ($scope) {
        $scope.foo = function() {
             console.log("I am in foo...");
             ...
        }

        $scope.$on('scrolled', $scope.foo)

    }
]);

Comment: Hm... it entails another problem: `$scope.foo()` becomes invoked regardless `scroll`  event it self, just when template becomes rendered...
Comment: I think it should be ` $scope.$on('myEvent', (event) => $scope.foo());` as @VladimirZdenek described


Distribution of Ratio of Two Dependent Binomial Random Variables

Question: I have two random variables: $n_1$ and $n$.
$$n_1 \sim \textrm{Bin}(m, p_1g)\\ n\sim \textrm{Bin} (m, (p_1g+p_0(1-g)))$$
What would be distribution of (or at least expectation and variance) of $n_1/n?$
$p_0,p_1,g \in (0,1).$
This is based a a small model that I am working on but this stats part is where I am stuck.

Model: There's a population of size $N$. $g$ fraction is of type $1$ and rest $0$.
$m$ are randomly approached but type $1$ is available with probability $p_1$ and others with $p_0$.
It is observed that total $n$ are available of which $n_1$ are type 1.
I am looking to estimate $g$ from this data but first wish to prove that $n_1/n$ is a biased estimate of $g$. Further my hunch is that itay not even be consistent. And even if it is then the rate of decrease of variance would be slower than what it would have been, had $p_0=p_1$.
Hopefully my derivation of distribution are correct $n, n_1$. They are not independent clearly.
I have also run simulations and the intuition about variance seems to be correct. I am still lost about how to get a good estimate of g.
Comment: Where is the dependence between $N$ and $N_1$? There is no direct analytical formula but it is always feasible to compute $$\mathbb P(N_1/N=a/b)$$ when $a=0,\ldots,m$ and $b=1,\ldots,m$. The rv is undefined when $N=0$.
Comment: @Xi'an: I have added the details of the model. I have also voted to reopen. Please do comment if you think the question is still incomplete.
Comment: The model as described is incomplete, as it does not spell out the dependence between $N_1$ and $N$. I would suggest introducing a latent variable $M_1\sim\text{Bin}(m,g)$ and, conditional on $M_1$, $N_1\sim\text{Bin}(M_1,p_1)$ and $N_0=N-N_1\sim\text{Bin}(m-M_1,p_0)$. And there is always the issue of $N_1/N$ being undefined when $N=N_1=0$.
Comment: @Xi'an: I though this part was obvious from description. There is one sample and n and n1 are both from this sample. Let me be more explicit: let j be index of individual approached. Rj=1 if he's available. Gj=1 if he's of type 1. $n = \sum_1^m R_j$. And $n_1=\sum_1^m R_jG_j$
Comment: Rj and Gj are both Bernoulli
Comment: Some more description: $Pr(R_j=1 | G_j=1) = p_1$, $Pr(R_j=1 | G_j=0) = p_0$. @Xi'an
Comment: I think it would be better if you dropped all the maths, and just described your actual physical problem. People are wasting time addressing a likely incorrect mathematical description
Comment: Can you confirm or infirm that the model I gave in my last comment applies?
Comment: @SextusEmpiricus: I agree that my first post was wrong. But I thought the part I added later answers the queries raised. The multinomial description sounds interesting. But the probabilities of the events in multinomial are not independent. Is the model described in terms of Rj and Gj okay? n_1, n are realizations of binomial distributed random variables. If you think these are still insufficient will add more. Thanks for your comments
Comment: @Xi'an I guess not. Is there a problem with Rj, Gj description. If so I'd better delete this and post ahain maybe.
Comment: Yes, repost a new question with a fully specified model, including the dependence between $N$ and $N_1$. (In my understanding, $M_1=\sum_i G_i$, so I still do not get why this is not the model of interest.)
Comment: @SextusEmpiricus: So I am still not very sure about the multinomial thing. Basically we have 4 possibilities: an individual is type 1 but is not available, type 0 unavailable and same with available. I modelled this with two separate random variables. These two are not really independent variables as their conditional probabilities are different exogenously given (so not the product of probabilities of the events separately). In any case I have made a mess here so would appropriately edit the question.
Comment: @SextusEmpiricus Meanwhile please share the link to your answer you are referring to
Comment: Do you need an analytical solution (doubt) or will an approximation do?
Comment: Preference is for analytical but I'd appreciate approximation as well...also be good bounds if can be provided @user2974951
Comment: I am thinking of doing simulations but still some mathematical result be great
Comment: Yeah so I am not very sure about the dependence thing. Let me describe the full model as soon as I get time. Basic idea is that data for both come from same sample of size m and their parameters are related to g, p_1, p_0 @Xi'an
Answer: Your initial problem description does not follow entirely the description in the second part. But based on that description I get to the following:
You have a pool of $N$ People of which a fraction $g$ is of type 1 and a fraction $1-g$ is of type 0. From this pool you sample $m$ people but you only register the people that are 'available'. Among the different types there are different probabilities of being available (and being actually observed).

I translate this into the following problem.
Assuming that the sample is much smaller than the population size $m \ll N$, then the sampling from the population is similar to sampling without replacement and we can regard the distribution as approximately categorical distributed.
You sample the following cases:

$n_1$, type 1 and available, with probability $gp_1$

$n_0$, type 0 and available, with probability $(1-g)p_0$

$n_u$, unavailable, with probability $1-p_0-gp_1+gp_0$

You can not have a combination of these. It needs to be either one of these three. So the output needs to be multinomial distribution with the respective probabilities with
$$\begin{array}{rcl}
\mu_{n_1} &=& mgp_1\\
\mu_{n_0} &=& m(1-g)p_0\\
\operatorname{Var}({n_1})&=& mgp_1(1-gp_1)\\
\operatorname{Var}({n_0}) &=& m(1-g)p_0(1-(1-g)p_0\\
\operatorname{Cov}(n_1,n_0) &=& -mgp_1(1-g)p_0
\end{array}$$

Distribution of $\frac{n_1}{n_1+n_0}$
When $m$ is large then you can approximate $n_1$ and $n_1+n_0$ as a multivariate normal distribution. And use the Delta method to approximate the distribution of the outcome.
A discription of this is given in this question A/B testing ratio of sums.
For the location of the Normal distribution that approximates the distribution of the ratio we use $$\frac{\mu_{n_1} }{\mu_{n_1} + \mu_{n_0}} = \frac{mgp_1}{mgp_1+m(1-g)p_0} = g \frac{1}{1 +\frac{1-g}{g}\frac{p_0}{p_1}}.$$
For the variance the computation is a bit longer but you can already see that this distribution will be biased.
Comment: I hope you have no problem with the edits done.
Comment: Thanks. So multinomial also looks like a great option but I still have this lingering doubt that the unavailable comprises of two categories although we cannot differentiate between these two. In any case multinomial approach seems to make life easier. I will check the link to your other answer for details about the variance.
Comment: Btw, in the final formula there should be a other than the one in denominator.


Gradle: com.android.support:support-compat:25.3.1 and com.android.support:animated-vector-drawable:24.0.0 must use the exact same version

Question: On the following 'complie' in my Gradle file:
dependencies {
    compile 'com.android.support:support-v4:25.3.1'
}

I have got the following error:

*All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found
    versions 25.3.1, 24.0.0. Examples include
    com.android.support:support-compat:25.3.1 and
    com.android.support:animated-vector-drawable:24.0.0.
There are some
    combinations of libraries, or tools and libraries, that are
    incompatible, or can lead to bugs. One such incompatibility is
    compiling with a version of the Android support libraries that is not
    the latest version (or in particular, a version lower than your
    targetSdkVersion.)*

But I don't find any use reference to this 'animated-vector-drawable' library in my project (used the search tool).
Any idea how to solve this problem?
Thanks !
Comment: can you put all your gradle file here Regis?
Answer: Just add this line your app gradle file
compile 'com.android.support:animated-vector-drawable:25.3.1'

Comment: Thanks ! Has also to add : compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:mediarouter-v7:25.3.1'
Answer: you need to set all gradle version should be same version


Nested rules with selectors in LESS?

Question: I have the following CSS-rule(s):
div > a,
div > span {
  background-color: #ccc;
}

Is it somehow possible to nest a and span within the div >, e.g.
div > {
  a, span {
    background-color: #ccc;
  }
}

Answer: This should do the trick.
div {
  > a,
  > span {
    background-color: #ccc;
  }
}

Comment: Sure, check http://lesscss.org/features/#features-overview-feature-nested-rules for more details. You'd use the ampersand when nesting pseudoselectors for instance. In other words, when there's no space between the parent and the child. You can also play with it on an online compiler: http://winless.org/online-less-compiler
Comment: Do you have a reference? Do I have to add an ampersand in front of the selector? (e.g. `& > a`)?
Comment: @Edward: The above code should work with or without ampersand (parent selector).

Nested rules with selectors in LESS?


Remove disabled menu links from menu settings

Question: I have a multilingual site, and when adding content theres an option to add a menu link. Both languages show up in the drop down selection, my goal is to hide/remove the links that are "disabled" (NOT in the current language).
So only the current language links should be visible in the dropdown.
Answer: Never solved this, finally i deleted the drupal site and rewrote the site with dogescript.


Do something conditinally on node.tpl.php depending on if the node is tagged with certain taxonomy vocabulary

Question: I found how to do this if the node is tagged with certain terms here.
But what I would like to do is to do something conditionally in node.tpl.php only if the node is tagged with a certain vocabulary.
For example, I have a vocabulary called "Color" with terms "Red" "Blue" "Yellow". I would like to display the text "It has color" only if the node is tagged with at least one of those terms. Otherwise print nothing.
How can I do this in  node.tpl.php ?
Comment: are you using drupal 6 or 7?
Answer: Each taxonomy term in a node also gives you the vocabulary id that it belongs to.  So you could look through the terms to see if one matches the vocabulary id of your "Color" vocabulary and then display "It has color" when found.
An easy way to do this would be to use a loop:
<?php foreach ($node->taxonomy as $key => $term): ?>
  // Say the vocabulary id of "Color" is 10.
  <?php if ($term->vid == 10): ?>

      <?php print views_embed_view('my-views', 'default', $args); ?>

    // etc
    <?php break; ?>
  <?php endif; ?>
<?php endforeach; ?>

For reference, to access the vocabulary id of a single term:
$node->taxonomy[TERM_ID]->vid;

Where TERM_ID is the id of the taxonomy term.
Comment: Thank you @Laxman13. I actually need to print several `` blocks including Views output inside. I simply thought I could do something like `` but obviously not.Sorry for my very limited php... For example if I want to print several of something like  ``, Should I print them inside php where "It has color" is in the example above? Or possibly I can use `print<<<EOF` ?
Comment: Yes you can add something like that to where "It has color" is printed above. I changed the example in my answer to be more tpl friendly


Text not changing with a delay

Question: I have a label in a different class, and I am changing the text of this label in a action of another component. Anyways I have tried a delay on it like Thread.sleep(300) and even implementing my own method like
    private void waitTime(long WaitTime){
        long waitUntil = System.currentTimeMillis() + WaitTime;
        while(System.currentTimeMillis() != waitUntil);
    }

It worked fine but the text didn't change before the delay. Is there an alternative delay that the text will actually change itself then delay?
if(frame.Index == 10){
        frame.label.setText("Wow, you're more patient then I am, you win.");
        waitTime(3000);
        if(frame == null) return;
        System.exit(1);
}

Comment: 1) Please learn common [Java naming conventions](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307) (specifically the case used for the names) for class, method & attribute names & use them consistently. 2) For better help sooner, post an [SSCCE](http://sscce.org/). 3) Which GUI toolkit?  Swing, AWT, Java-FX, GWT, SWT, Android..?
Answer:
You're putting the Swing event thread and thus the whole application to sleep with Thread.sleep(...). So you don't want to use this on the Swing event thread (also known as the Event Dispatch Thread or EDT).
Instead, use a Timer, not a Thread.sleep(...)
An alternative is to throw a JOptionPane at the user with the desired message, and then to exit from your application when the JOptionPane returns. This way you are guaranteed that the user has at least seen the option pane and hopefully its message before the application exits.

Text not changing with a delay


Fixed Effect vs Random Effect Models

Question: Can anyone tell me what is Fixed effect and Random effect models? How to make out that when to use fixed effect and random effect model? What algorithms are the examples of fixed effect and Random effect models?
Comment: This is a pretty decent explainer https://www.tjmahr.com/plotting-partial-pooling-in-mixed-effects-models/
Comment: This question is better suited for stack exchange, since it's more about statistics than `R` programming. Anyhow, [you could start](https://rstudio-pubs-static.s3.amazonaws.com/372492_3e05f38dd3f248e89cdedd317d603b9a.html)
Answer: Both models assume that there are certain parameters that determine the distribution of the observations.  Those parameters determine the "effects":  For example, there might be 3 groups of observations, and the means for each group are assumed to be the same for every observation in each group, but different between groups.  The "effect" of groups is a measure of the differences between those means.
Random effect models make the additional assumption that those parameters are themselves random variables drawn from some distribution, which may have its own parameters (sometimes called "hyperparameters").  This assumption gains you the ability to make predictions about unobserved groups.  In a fixed effect model, all you know is that the new group would have some mean, but you don't know anything about it.  In a random effect model, you can assume that new mean would be similar to the other means because it is drawn from the same distribution.
Depending on how they are analyzed, sometimes the estimates for each group will change between random effect models and fixed effect models.  This reflects the fact that the means are assumed to come from the same distribution, so estimates get pulled towards the overall mean.
The last part of your question doesn't really make sense.  Models are models, and algorithms are algorithms.  An algorithm can't be an example of a model.  If you really meant "what algorithms are used with each type of model", it would make more sense, but it's too big a question to really answer.  There are many algorithms for estimating the parameters of a model, and many more algorithms for computing things from those estimates.

Fixed Effect vs Random Effect Models


Adding a background to an SVG

Question: What's a quick easy way to add a background to an SVG?  At the moment, the SVG appears to have a white background.  I am not sure if that is because the SVG file has a transparent background and is allowing the default white to come through when viewed in a browser, or if the SVG file actually have a white background.
I would like to change it so when viewed on the web, the SVG link appears to have a background.
The link consists of only the SVG file, for example, if this example link was real, it would be http://oshiro.com/file.svg.
Comment: What kind of background?
Comment: @RobertLongson, an image background, such as a jpg, png etc.
Comment: Create an `` tag as the first item. Or fill a rect with a pattern that has an `` in it.
Answer: It's hard to give you an exact answer without seeing the SVG.  But assuming you just want to add a coloured background then you can just add a <rect> element to the beginning of your SVG.
Try adding something like the following as the first item inside your <svg> element.
<rect width="100%" height="100%" fill="#ffffee"/>

Adding a background to an SVG


How can I get the Date from year and how much total days have passed?

Question: I have two variables,
let year = 2003;
let passedDays = 275;

I need to get the Date as  2003-10-02 from those two variables.
How can I do it without writing a hundred lines of if statements.
Thanks in advance.
Answer: Build a date object with the given year, for January, the first, then add the needed days :

let year = 2003;
let passedDays = 275;

// note that months starts with zero
//                        |
//                        V
let date = new Date(year, 0, 1);
// Make sure passedDays is a number, not a string containing a number,
// otherwise you'll get wrong result (string concat)
//                            |
//                            V
date.setDate(date.getDate() + +passedDays);

console.log(date);
Comment: It works great here, but when I implemented it to my script, it said Oct 3 instead of Oct 2.
`let date = new Date(year, 0, 0);`. So I changed the day `1` to `0`. Now it works great in the script too. My edit won't cause any other errors will it ?
Comment: As far as I know, no it won't. The day 0 is the last day of the previous month
Comment: Oh, wait, this shouldn't be the case, using `new Date(year, 0, 1);` should give you the correct result. This could be due to some timezone issues
Comment: I thought so too, My time zone is GMT+0530.


Why doesn't print module_invoke('user', 'block', 'view', 0); use template files?

Question: If I invoke the user login block using module_invoke it doesn't use block-user-0.tpl.php. If I drop the block in the right sidebar and print $right it does use block-user-0.tpl.php.
Also, why will it only print the block once so that printing $right and module_invoke only results in one login form?
Answer: The code module_invoke('user', 'block', 'view', 0) eventually calls user_block('view', 0). The user_block function returns an array in this case; that's just how hook_block works. The documentation for hook_block says:

If $op is 'view': return an array which must define a 'subject'
  element (the localized block title) and a 'content' element (the block
  body) defining the block indexed by $delta. If the "content" element
  is empty, no block will be displayed even if "subject" is present.

If you want to know how to render this block, check this comment on the theme_block documentation page.
Answer: 1st:
Call
 print drupal_get_form('user_login_block');

2nd:
Drupal marks each printed element with
$elements['#printed'] = TRUE;

so any content cannot be rendered twice. You can modify this value if you need to render twice any element.


Comparing assault rates at one facility with two other facilities

Question: Assaults on staff are fairly uncommon in our facilities with between 70-140 in a year at a given facility.  Time, similar to 'person years' in epidemiology, is tracked as 'number of bed days' (i.e., number of days a bed is occupied).  Bed days per facility range from 75,000 to 135,000.
For the comparisons, I'm thinking to calculate Confidence Intervals modeled with Poisson distribution with a Bonferonni correction on the confidence level for multiple comparisons (comparing x facility with both y and z facilities; hence confidence level set to 0.975[see below]).

facility x assaults=71; days stay=93,516
facility y assaults=61; days stay=74,272
facility z assaults=142; days stay=133,699

R procedures and output (EpiTools package):
1. > pois.exact(71, 93516, conf.level = 0.975)
      x    pt         rate        lower        upper conf.level
1    71 93516 0.0007592284 0.0005717496 0.0009874694      0.975

2. > pois.exact(61, 74272, conf.level = 0.975)
   x    pt         rate        lower       upper conf.level
1 61 74272 0.0008213055 0.0006038488 0.001090219      0.975

3. > pois.exact(142, 133699, conf.level = 0.975)
    x     pt        rate        lower       upper conf.level
1 142 133699 0.001062087 0.0008724176 0.001279991      0.975

As there is overlap of CIs between facility x and both y and z, there is no significant difference in assault rates.
Does this analysis look alright?
Comment: But you haven't really told us what you are trying to do, so I'm not sure if we can tell you if your analysis looks right.
Comment: One issue you might want to deal with is the people in the facility. Presumably some people have a higher propensity to assault (perhaps on their first day). If stays are shorter, you have more people passing through. if that's the case, you might expect more assaults.  This violation of independence means your CIs are not correct.
Comment: Trying to answer the question: Does facility x have lower staff assault rates than facility y or facility z?
Comment: Jeremy, thank you for fixing the code formatting!  We don't have good reason to believe that people at facility x are at higher risk of committing assaults due to personal factors.  We have a reasonably predictive actuarial risk assessment that suggests (in aggregate) there are not demonstrable differences between clients at any of these facilities.  Of course, there may be some unknown issues that violate independence assumption, but we don't have any evidence to suggest this is currently the case.
Comment: I think you are moving toward the right conclusion, but something I'd caution about is that CI overlap doesn't exclude statistical significance a priori. Though if there is significant overlap as I believe is the case here, then it sorta points that way.
Answer: As said in comments, judging statistical significance by overlap of confidence intervals is problematic. So I would prefer to build a model, in this case a Poisson regression model for rate, that is, using the logarithm of beddays as an offset.  Then we can test the hypothesis of some differences between facilities with a 2 df test, as one hypothesis, avoiding multiplicity concerns. In R I do that as
    fac_df  <- data.frame(fac=c("X", "Y", "Z"), bed_days=c(93516, 74272, 133699), assaults=c(71, 61, 142))
    fac_mod <- glm( assaults ~ offset(log(bed_days))+fac, family=poisson(), data=fac_df)
    fac_mod0 <- glm( assaults ~ offset(log(bed_days)), family=poisson(), data=fac_df)
     anova(fac_mod0, fac_mod, test="Chi")
    Analysis of Deviance Table

Model 1: assaults ~ offset(log(bed_days))
Model 2: assaults ~ offset(log(bed_days)) + fac
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1         2      6.364
2         0      0.000  2    6.364   0.0415 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

so this indicates some differences between facilities. Then you could continue with a post-hoc analysis, looking at individual contrasts. See Post-hoc after GLM.
But see
summary(fac_mod)

Call:
glm(formula = assaults ~ offset(log(bed_days)) + fac, family = poisson(),
    data = fac_df)

Deviance Residuals:
[1]  0  0  0

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -7.18321    0.11868  -60.53   <2e-16 ***
facY         0.07859    0.17458    0.45   0.6526
facZ         0.33569    0.14535    2.31   0.0209 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 6.3640e+00  on 2  degrees of freedom
Residual deviance: 2.6645e-15  on 0  degrees of freedom
AIC: 24.849

Number of Fisher Scoring iterations: 2

this is a saturated model, as evidenced by the deviance residuals of zero. That means that model criticism based on residuals is impossible, which always is a concern. In particular, with Poisson regression overdispersion is always a possibility. To look into that you would need to use data with more details, maybe per week or per month.
Comment: This is awesome Kjetil!  I will take some time to digest, but it looks very promising.  Thank you!


Reverse the order of integration and evaluate the integral

Question: Reverse the order of integration and evaluate the integral:
$$\int_0^1 \int_x^\sqrt{x}{e^{x\over y}} \, dy \, dx$$
The answer is supposed to be $\frac{e}{2}-1$ but I keep getting $\frac{x}{2}(e-1)$.
This is my work:
$$\int_0^\sqrt{x} \left[e^\frac{x}{y}y\right]_0^y \, dy$$
$$\left[e^\frac{x}{y}y\right]_0^y=e^\frac{y}{y}y-e^\frac{0}{y}y=ey-y$$
$$\int_{0}^\sqrt{x}(ey-y)\,dy = \left[\frac{ey^{2}}{2}-\frac{y^{2}}{2}\right]_0^{\sqrt{x}}=\frac{ex}{2}-\frac{x}{2}=\frac{x}{2}(e-1)$$
What am I doing wrong?
Comment: That you have an $x$ in your final answer means not only that you've done something wrong, but that you haven't entirely understood the question, or you'd know why an $x$ can't be there. ${}\qquad{}$
Comment: Reversing the order of integration is not as simple as just switching the order. You must consider the area defined by the limits of the integral.
Comment: See this answer for an example of how to reverse the order of a double integral. http://math.stackexchange.com/questions/1560628/sketch-the-solid-of-integration
Answer: in your question, the cross scection is vertical. If you want to reverse the the order of integration, the cross section should be horizontal. so
$$\int_{0}^1\int_{x}^\sqrt{x}{e^{x\over y}}dydx=\int_{0}^1\int_{y^2}^y{e^{x\over y}}dxdy$$
Answer:
Consider the region of integration satisfied by the conditions $$0 \le x \le 1, \quad x \le y \le \sqrt{x}.$$  Integrating first with respect to $y$ and then $x$ corresponds to taking vertical strips of differential thickness $dx$, then integrating along those strips from the lower boundary corresponding to the diagonal line $y = x$ to the upper boundary parabolic arc $y = \sqrt{x}$.  If you reverse the order of integration, this clearly implies that $y$ ranges from $0$ to $1$, and $x$ should range from $x = y^2$ to $x = y$; corresponding to taking horizontal strips of differential thickness $dy$ and integrating along these strips from the lower bound of the parabolic arc to the upper bound of the diagonal line.
Hence, $$\int_{x=0}^1 \int_{y=x}^{\sqrt{x}} f(x,y) \, dy \, dx = \int_{y=0}^1 \int_{x=y^2}^y f(x,y) \, dx \, dy.$$  Now letting $f(x,y) = e^{x/y}$, the rest is a straightforward exercise.  Note that regardless of how the integration is performed, the answer cannot be a function of $x$ or $y$:  a definite integral of a function with respect to some variable of integration cannot remain a function of the variable of integration.
Answer: You should have this:
$$
\int_0^1 \left( \int_x^\sqrt{x}{e^{x\over y}} \, dy \right) \, dx = \int_0^1 \left( \int_{y^2}^y e^{x/y} \, dx \right) \, dy
$$
The inside integral on the left side is tractable.
Here's how you get that:
For each fixed value of $x$ between $0$ and $1$, you have $y$ going from $x$ up to $\sqrt x$.  Draw the picture and see that that's a vertical line intersecting two curves.  Then draw a horizontal line to see what $x$ does for a fixed value of $y$.  You'll see it going from $y^2$ up to $y$.
Answer: To reverse the order of integration you need to think about the area your integral is being calculated on. It goes from $x$ is $0$ to $1$ and $y$ from $x$ to $\sqrt{x}$. Sketch these two curves to visualize it.

You now want to consider the range of $y$ values and then try to express the range of $x$ values as a function of $y$. In this diagram $y$ goes from $0$ to $1$. For a given $y$ value we see that $x$ goes from $y^2$ to $y$. So the integral (with reversed order) becomes:
$$\int_0^1\int_{y^2}^y e^\frac{x}{y} \, dx \, dy$$
Now evaluating the integral:
$$\int_0^1\int_{y^2}^y e^\frac{x}{y} \, dx \, dy$$
$$=\int_0^1 \left(e^\frac{x}{y}y\right)_{y^2}^y \, dy$$
$$=\int_0^1 \left(e^\frac{y}{y}y\right)-\left(e^\frac{y^2}{y}y\right) \, dy$$
$$=\int_0^1 \left(ey\right)-\left(e^yy\right)dy$$
For the second half of the integral we need to use by parts: $u=y$, $dv=e^y$ hence $du=1$, $v=e^y$.
$$=\left(\frac{ey^2}{2}\right)_0^1-\left(ye^y\right)_0^1+\int_0^1 e^y \, dy$$
$$=\frac{e}{2}-e+e-1$$
$$=\frac{e}{2}-1$$


Blurring a .BMP with box BLUR in C

Question: To resume. the code I ve written below doesn t get me a blur image. But a black IMAGE instead ( except for the pixel edges).
For testing i ve just tried the interior PIXELS, without edges RGBTRIPLE pixels because I wanted to see if I was making well so far.
Could anybody tell me whats wrong with my code, please?
is muy BUFFER RGB newImage correct done?? if image[height][width].rgbtRed it means that newImage[height][width].rgbtRed will exist?? thanks in advance
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{

    //create a buffer to allocate new pixels.
    RGBTRIPLE newImage[height][width];

    // iterate through each row
    for (int i = 0 ; i < height ; i++)
    {
         // iterate through each column passing through every RGBTRIPLE
        for ( int j = 0; j < width ; j++)
        {
            int redSum = 0;
            int greenSum = 0;
            int blueSum = 0;

             //counter for pixels being add in every avg.
             //int count = 0;
             // take the average amount of RGB of every pixel in a range of 3x3 pixels
             // avg for left top corner
             /*if ( r == 0 && l == 0) {

             }
             // avg left bottom corner
             else if ( r == height - 1 && l == 0 ){

             }
             // avg right top corner
             else if ( r == 0 && l == width - 1){

             }
             // avg left bottom corner
             else if ( r == height - 1 && l == width - 1){

             }
             // avg  top side
             else if ( r == 0 && l > 0 && l != width - 1) {

             }
             // avg right side
             else if ( l == width - 1 && r > 0 && r != height - 1) {

             }
             // avg bottom side
             else if ( r == height - 1 && l > 0 && l != width - 1) {

             }
             // avg left side
             else if ( l == 0 && r > 0 && r != height - 1){

             }*/

             for ( int iy = -1 ; iy >= 1 ; iy++)
             {
                 for ( int jx = -1 ; jx >= 1 ; jx++)
                 {
                     redSum = redSum + image[i + iy][j + jx].rgbtRed;
                     greenSum = greenSum + image[i + iy][j + jx].rgbtGreen;
                     blueSum = blueSum + image[i + iy][j + jx].rgbtBlue;
                     //count++;
                     }
             }

             int avgRed = redSum / 9;
             int avgGreen = greenSum / 9;
             int avgBlue = blueSum / 9;
             newImage[i][j].rgbtRed = avgRed;
             newImage[i][j].rgbtGreen = avgGreen;
             newImage[i][j].rgbtBlue = avgBlue;

        }

    }

    for ( int y = 1 ; y < height - 1; y++)
    {
        for ( int x = 1; x < width - 1; x++)
        {
            image[y][x].rgbtRed = newImage[y][x].rgbtRed;
            image[y][x].rgbtGreen = newImage[y][x].rgbtGreen;
            image[y][x].rgbtBlue = newImage[y][x].rgbtBlue;
        }

    }

    return;
}

Comment: This: `for ( int py = 0 ; py >= 2 ; py++)` looks wrong. If you correct the comparison, you'll access the pixel buffer out of bounds, because contrary to what you've said you don't consider only the inner pixels, at least not with the large block of tests commented out.
Comment: Please, please never use the variable name l. Was that `l` or was it `1`? In a monotype font you can tell by squinting, but not in proportional font. It just makes code very hard to read. Anyway, using `r` and `l` together deceives the reader into thinking they are `right` and `left` but they are `row` and `column`.
Comment: `/*if ( r == 0 && l == 0) {
 }
 // avg left bottom corner
  else if ( r == height - 1 && l == 0 ){
...  else if ( l == 0 && r > 0 && r != height - 1){
 }*/` does nothing.  Why is it there?
Comment: @WeatherVane thanks. I ll take that in consideration.
Comment: @chux-ReinstateMonica it was my next move... but I was trying to fix  the first issue.
Comment: @MOehm I can see. Thanks for that!
Answer: A major mistake not already mentioned in a comment is that redSum, greenSum and blueSum are initialized to 0 only once, while they must be set to zero before each pixel is processed, so better move the definitions right before the for ( int py = 0 ; py >= 2 ; py++) loop.
Comment: Also, the second pair of loops which copies the new image to the old, have their limit off by one. I think I can see why - the edge pixels have been skipped, but then the loops' initial `0` is incorrect. When the code is completed, don't divide by `9` but by the number of pixels that could be averaged at the edges (which you also can sum).
Comment: Thanks @WeatherVane I corrected all these u said. Now I have the 4 edges without edition. But the no edges pixels are BLACK.

I recon is there is something wrong with the buffer..
`//create a buffer to allocate new pixels.
    RGBTRIPLE newImage[height][width];`
 and then...
`newImage[i][j].rgbtRed = avgRed;
   newImage[i][j].rgbtGreen = avgGreen;
   newImage[i][j].rgbtBlue = avgBlue;`

.rgbtRed .rgbtGreen . rgbtBlue really exist for newImage 2 array??
Comment: You could add the corrected edition to your question, so that we can see whether there's still a cause of undefined behavior.
Comment: Good, only you'd better not changed the original code, rather added the modified version.
Answer: It's hardly believable how the many eyes (including mine) who looked at the code could overlook the main, simple error - the inner loops (in their original as well as in the edited version) are never executed:
             for ( int iy = -1 ; iy >= 1 ; iy++)
             {
                 for ( int jx = -1 ; jx >= 1 ; jx++)

Of course, the iy >= 1 condition is false from the start; you surely meant iy <= 1 and jx <= 1.
Comment: issue Resolved! it was that loop exactly :)

Blurring a .BMP with box BLUR in C


Entity Framework Lazy Loading in .NET 3.5

Question: Due to server restrictions I am limited to .Net 3.5, I was using lazy loading with Linq to SQL but have since switched to the Entity Framework.  L2E does not have lazy loading in 3.5 while L2S did.  Is there a way to regenerate the templates somehow to achieve this?
Answer: You have to explicitly call a load method in EF 1 / .NET 3.5.
So, before you access a related collection or entity that is not loaded, you have to call something like:
Examples:
<code>if (!person.Pets.IsLoaded)
    person.Pets.Load();
if (!person.Address.IsLoaded)
    person.Address.Load();
</code>
Of course it's so ugly, but this is how it worked in that version.
More details from Microsoft Blogs here:
http://blogs.microsoft.co.il/blogs/idof/archive/2008/08/20/entity-framework-and-lazy-loading.aspx


similarity distance when weight should change

Question: I am trying to find a similarity measure for a very specific problem.
I have a list of cities that have some characteritisques. For example bilingual school, firemen stations, etc. These cities are represented as binary vectors where each element corresponds to a characteristic.
On the other side I have possible citizens. The citizens give a punctuation between 0 and 1 to the importance they give to each of the characteristics in the cities.
So I could have :
Citizen 1 = {0.83, 0.3, 0, 1}
City 1 = {1, 0, 0, 1}
City 2 = {1, 0, 1, 1}
I would like to find the best city for each citizen. The important thing would be to find cities with a 1 in the characteristics that the citizen cares about and we don't mind if the city has a zero when the citizen did not care or not care much ( less weight or not weight at all if the citizen does not care)
I have tried some distance (eg hamming, cosine) but they give weight when the citizen and the city have both zero in the same characteristic.
what would be a good similarity to use in this case?
Thanks
Answer: I assume by "similarity" you mean some score that measures how well a given city matches a given citizen. Think of each weight as the extent to which a citizen is happy when a city has the corresponding feature, or unhappy when it doesn't. Assuming happiness and unhappiness are both proportional to the weight, here's one possible score you could use:
Let binary vector $x = [x_1, \dots, x_n]$ represent a city, where $x_i \in \{0, 1\}$ denotes whether or not the city has feature $i$. Let weight vector $w = [w_1, \dots, w_n]$ represent the preferences of a citizen, where $w_i \in [0, 1]$ denotes how much the citizen cares about the presence of feature $i$. For each feature, we add happiness $w_i$ when feature $i$ is present, and subtract happiness $w_i$ when feature $i$ is absent. The happiness of the citizen with the city is then given by the dot product:
$$h(x, w) = w \cdot (2x - 1)$$
Of course, $2x-1$ is simply a copy of $x$ with the zeros replaced by negative ones. Since $h$ is a simple dot product, you could easily relate it to Euclidean or cosine distance if you were so inclined.
Comment: Hi,I have tried cosine and euclidean but they take into account when the citizen gives zero or low points to a characteristic.If the citizen did not give importantce to one characteristic, I would like to give it weight or little weight in the final outcome. I want to be ignored or more or less to be ignored whether the city has it or not. I
Comment: $h$ as I described it should have the properties you want. What I mean about Euclidean/cosine distance is *not* that you should use Euclidean/cosine distance between the original $x$ and $w$ (clearly they won't have the desired properties). Rather, because all of these measures contain dot products between $w$ and $x$, it's easy to derive expressions that relate them.


Criar barra com CSS

Question: Um cliente pediu para criar um menu baseado na imagem abaixo:

Como eu poderia fazer essas barras com CSS? Estou usando o Bootstrap para o desenvolvimento.

Home

Esportes

Masculino

Feminino

Crianças

Outlet

Lançamentos

Answer: Fiz essa opção usando só o caractere / mas vc pode criar o elemento que quiser no ::after da LI

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
ul {
  padding: 10px 0;
  color: #fff;
  margin: auto;
  list-style: none;
  display: flex;
  background-color: green;
  justify-content: center;
}
li {
  position: relative;
}
li:not(:last-child):after {
  content: "/";
  margin-left: 20px;
  margin-right: 20px;
}

Home

Esportes

Masculino

Feminino

Crianças

Outlet

Lançamentos

Comment: Perfeito, Hugo. Muito obrigado!
Comment: @Fox.11 sem problemas meu caro

Criar barra com CSS


When expectation of minimizer is minimizer of expectation?

Question: $X$ is a random variable with unknown distribution law $P$ taking values in set $A$.
Given $\rho : I \times A \to \mathbb{R}_+$, where $I$ is a closed bounded real interval, it is clear that
$$  \mathbb{E} \min_{t \in I} \rho(t,X) \le \min_{t \in I}  \mathbb{E} \rho(t,X)  $$
Now concern estimate
   $$
     \hat r = \arg \, \min_{t \in I} \rho(t,X)
   $$
and value
   $$
      r =  \arg \, \min_{t \in I} \mathbb{E} \rho(t,X)
   $$
The problem is to find condition on $\rho$ which makes $\hat r$ an unbiased estimator of $r$, i. e.
$$ \mathbb{E} \hat r = r $$
Are where any known results for this problem?
Answer: I'm going to assume the argmin always exists and is unique. Since our condition needs to work for any possible distribution of $X$ we need the argmin to be linear in $X$ for the result to hold (If the argmin were a non-linear function of $X$ then some part of it would be locally strictly concave or convex, and if the distribution of $X$ had support in a subset of this region then by Jensen's inequality $E\hat{r}\neq r$). A sufficient condition for this is for $\rho$ to be of the form $\rho((a+bX)t)$ where $a$ and $b$ are constants.


Integral curves of vector fields on closed surfaces

Question: If we have a vector field on a boundary less and compact 2-manifold,  which is neither a gradient nor a harmonic, does that imply its integral curves are closed?
Comment: @Eracnet: Out of after-the-fact curiosity, did you mean "_all_ integral curves are closed" (as your question wording suggests) or "_there exists_ a closed integral curve"? The only compact surfaces foliated by circles are the torus and Klein bottle, so if you mean "all", then your question has a negative answer for rather blunt topological reasons. (Of course, Amitai's post shows the answer is "no" even for the second wording, and the same idea extends the argument to arbitrary surfaces....)
Comment: No. Take straight lines of irrational slope on a torus.
Comment: If you are parametrizing the straight lines as (t,ct) (with appropriate modulus operations), then these are integral curves of a harmonic. I am interested in vector fields which are not harmonics.  Can you think of a different parametrization whose tangent field is actually continuous (and  therefore a vector filed)?
Answer: Let $T$ be the $2$-torus with the flat metric. Then every vector field of the form$$X=a\frac{\partial}{\partial x}+b\frac{\partial}{\partial y},$$where $a$ and $b$ are constants, is harmonic. By the Hodge decomposition theorem, the space of harmonic vector fields is $2$-dimensional, and hence all the harmonic vector fields have the above form.
Let $f:T\to\mathbb{R}$ be smooth, non-vanishing and non-constant. Define a vector field $X$ by$$X(p)=f(p)\frac{\partial}{\partial x}+cf(p)\frac{\partial}{\partial y},$$where $c$ is an irrational constant. Then the trajectories of $X$ are straight lines with irrational slope, hence not closed. Clearly, $X$ is not a gradient, as it does not vanish. By the first paragraph, $X$ is not harmonic.
Comment: That helps... Thanks!


Let A and B be independent. Show that $A^c$ and $B^c$ c are independent - better solution?

Question: My solution seems too long winded. This should take less writing, no? Here it is.
$B^c$ means complement of $B$ (i.e. $P(B) = 1 - P(B^c)$
If $A$ and $B$ are independent events:
$$
P(A \cap B) = P(A)P(B)
$$
So I do:
$$
P(A^c \cap B^c) = P(A^c | B^c)P(B^c) = (1 - P(A|B^c))P(B^c) = (1 - \frac{P(A\cap B^c)}{P(B^c)})P(B^c) = (1 - \frac{P(B^c|A)P(A)}{P(B^c)})P(B^c)
$$
Now, I can use the result that since $A$ and $B$ are independent $P(B^c|A) = 1 - P(B|A) = 1 - P(B) = P(B^c)$. Then:
$$
(1 - \frac{P(B^c|A)P(A)}{P(B^c)})P(B^c) = (1 - \frac{P(B^c)P(A)}{P(B^c)})P(B^c) = (1 - P(A))P(B^c) = P(A^c)P(B^c)
$$
Therefore, since $P((A^c \cap B^c) = P(A^c)P(B^c)$ then $A^c$ and $B^c$ are independent.
Comment: One approach: use indicator functions.  Since the indicator for the complement of a set is a (very simple) function of the indicator of the set, https://stats.stackexchange.com/questions/94872 provides a demonstration.
Answer: Here is another way:
$$\begin{align} P(A^c\cap B^c) &=1-P(A\cup B)=1-P(A)-P(B)+P(A\cap B)\\  &= 1-P(A)-P(B)+P(A)P(B) \\ &=1-P(A)-P(B)(1-P(A))=(1-P(A))(1-P(B)) \\ &= P(A^c)P(B^c)\end{align}$$
Comment: @DilipSarwate, corrected it, much appreciated. this is also an instance where one should be extra careful when writing answers on mobile :)
Comment: You need to be careful with your basic arithmetic.  $P(A\cup B)$ equals $P(A)+P(B)-P(A\cap B)$ whereas you equate it to $P(A)+P(B)+P(A\cap B)$ in your first line, and then you reverse the mistake when you replace $-P(B)-P(A)P(B)$ on the second line with $-P(B)(1-P(A))$ on the third line; the latter expression actually equals $-P(B)+P(A)P(B)$ which is what you _should_ have gotten on the second line.Since the final result is correct, I guess this is an instance of two wrongs making a right....