Show that $\sup_{0<x<\infty} (\mathrm{cos}x+\mathrm{sin}\sqrt{2}x)=2$.

Question: This is a problem in V Arnold's Ordinary Differential Equations.
By plotting the function $f(x)=\mathrm{cos}x+\mathrm{sin}\sqrt{2}x$ (the first graph below), I see that the graph is bounded from -2 to 2. But the boundary points $\{2,-2\}$ are not attained by $f(x)$. Intuitively, it seems true that $f(x)$ approaches 2 when both $\mathrm{cos}x$ and $\mathrm{sin}\sqrt{2}x$ approach 1. From the graph of both $\mathrm{cos}x$ and $\mathrm{sin}\sqrt{2}x$ (the second graph below), one can see that around $x=19$, both $\mathrm{cos}x$ and $\mathrm{sin}\sqrt{2}x$ approach 1.
But this doesn't seem like much of a proof. Is there another approach to show this equality? Also, I fail to find an ODE-related approach to this problem.
Answer: You are on the right track. We note that:
$\cos(x)=1$ when $x=2\pi n$, $n\in\mathbb{N}\cup\{0\}$
and
$\sin(\sqrt{2}x)=1$ when $\sqrt{2}x=2\pi n + \dfrac{\pi}{2}$, $n\in\mathbb{N}\cup\{0\}\implies x=\sqrt{2}\pi n+\dfrac{\pi}{2\sqrt{2}}=\sqrt{2}\left(\pi n+\dfrac{\pi}{4}\right)$.
The values for the cosine term are all rational multiples of $\pi$, and those for the sine term are all irrational ones, proving that both will never be $1$ at the same time.
But, we can get arbitrarily close. Are you familiar with the property from algebra that given two integers $x,y$, any multiple of $\gcd(x,y)$ can be constructed via linear combinations? A similar rule will help you demonstrate that you can get as arbitrarily close to $2$ as you want here. I freely admit I do not have the details worked out, at which point mathematicians usually say "I'll leave that part as an exercise".
Comment: Yes, I am familiar with the construction of gcd(x,y) via linear combination. But I couldn't see how it will help me to demonstrate that the sum can get arbitrarily close to 2.
Comment: @Orca_1 I thought about this a bit more today, so you're in luck. I *think* I know how to do it, but before I try to write it all out, what is this for? If it is for an undergraduate or introductory graduate course in analysis, my idea won't be of much help. Secondly, have you had any courses or experience in field theory and specifically with field extensions and rings of the form $R[\sqrt{-w}]$?
Comment: This is a practice problem in V Arnold's Ordinary Differential Equations. I have learned field extensions and rings of the form $R[\sqrt{D}]$ for $D>0$.
Comment: @Orca_1 dezdichao seems to be willing to type the rest of the info, I'll yield since I need to study for my qualifying exams.
Answer: It suffices to prove that you can find integers $m$ and $n$ such that $2\pi m$ and $ \sqrt{2}\pi n+\frac{\pi}{2\sqrt{2}}$ are arbitrarily close. But this is a routine application of the Equidiistribution theorem.
See if you can figure the rest out on your own.
Proof:
Let $\varepsilon>0$ be given. By the equidistribution theorem above, $a_n = \{\frac{4n+1}{4\sqrt{2}}\}$ numbers are equidistributed in the interval $(0,1)$. Hence, we can find $n$ such that $a_n<\frac{\varepsilon}{2\pi}$. Now let $m = \frac{4n+1}{4\sqrt{2}} - a_n = \frac{n}{\sqrt{2}} + \frac{1}{4\sqrt{2}} - a_n\in\mathbb{Z}$. By our construction, $$|2\pi(m-\frac{n}{\sqrt{2}}-\frac{1}{4\sqrt{2}})| = |2\pi m - \sqrt{2}\pi n-\frac{\pi}{2\sqrt{2}}| = 2\pi
a_n<\varepsilon.$$
Note that in the original comment, I wrongly cited Dirichlet's approximation theorem instead of the equidistribution theorem. Also, this theorem proved by using only pigeon-hole principle, so this is basically nothing advanced.
Comment: I have tried the following, please help me see if it's valid.
Comment: I want to find integers $m$ and $n$ such that $|2\pi m- \sqrt{2}\pi(n+\frac{1}{4})|$ is arbitrarily small, i.e. $\sqrt{2}\pi|\sqrt{2}m-\frac{4n+1}{4}|$ is arbitrarily small. By the thrm, for any irrational number $\sqrt{2}m$, there exists rational number $\frac{4n+1}{4}$ such that $|\sqrt{2}m-\frac{4n+1}{4}|<\frac{1}{16}$.
Comment: Not quite. You want to find such $m,n$,  given a small $\varepsilon.$ I will type up a solution later in the day.
Comment: @Orcha_1 you are very close. Thanks dezdichado for stepping up. Much appreciated. Will upvote when the answer is there.


The derivative of $\int_0^xxf(t)dt$ and why we cannot treat $xf$ as continuous.

Question: This comes from Calculus by Michael Spivak, 3rd ed., chapter 14, Problem 11.

Find $F'(x)$ if $F(x) = \int_0^x xf(t)dt$. The answer is not $xf(x)$; you should perform an obvious manipulation on the integral before trying to find $F'$.)

Here, Spivak fails to include the assumption that $f$ is continuous.
With this assumption, the answer is $\int_0^xf(t)dt + xf(x)$, and is solved here, here, and here.
I understand the solution. I was able to do it myself. It makes sense to me. I also solved it using the $\lim_{h\to 0}$ approach, and that worked too.
Yet, naively, it seems like the answer should be $xf(x)$. It seems like since $x$ "behaves like a constant" in that integration, and because $f$ is continuous, then $xf$ must also be continuous, and so $F'(c) = cf(c)$.
I'm hoping to build better intuition about why this is wrong.
I was thinking perhaps one way of looking at it is that $xf$ cannot be assumed to be continuous because we are free to change the value of $x$ somewhat arbitrarily. In fact, at any fixed point $c$, $xf(c)$ varies with $x$, so certainly we cannot guarantee anything about the value of $xf(t)$ simply by restricting $t$ to certain values.
Does this make any sense? I'm sorry to use such sloppy reasoning/language/arguments.
There's a good chance I just don't yet have the tools to fully "get it" yet, but I appreciate any insight you might be able to share.
Edit
Ian's answer helps explain something that confused me in Spivak's solution to a later problem.
The next two problems are:

Prove that if $f$ is continuous, then
$$\int_0^xf(u)(x-u)du = \int_0^x\left(\int_0^uf(t)dt\right)du.$$
Hint: Differentiate both sides, making use of Problem 11.

Use Problem 12 to prove that
$$\int_0^xf(u)(x-u)^2du = 2\int_0^x\left(\int_0^{u_2}\left(\int_0^{u_1}f(t)dt\right)du_1\right)du_2.$$

These each require fairly straightforward calculations, the details of which we can skip here. However, in the published Answer Book solution for the latter, problem 13, Spivak does something that initially I found baffling. He begins:

Applying Problem 12 to $g(u) = f(u)(x-u)$, we obtain
$$\int_0^xf(u)(x-u)^2du =\int_0^x[f(u)(x-u)](x-u)du$$
$$=\int_0^x\left(\int_0^uf(t)(x-t)dt\right)du$$

This substitution is misleading. The result he's using from problem 12. applies only to functions that do not depend on $x$, while Spivak's $g$ here clearly does depend on $x$.
I think he gets away with it here only because $\frac{\partial}{\partial x}[f(u)(x-u)] = f(u).$
Comment: It is just the product rule, nothing more.
Comment: There is a product rule that happens when you pull the $x$ out. If you could not do that because the integrand depended on $x$ in some more complicated way, the point would still be that the function depends on $x$ both through the limit of integration and the integrand. $xf(x)$ only captures the former contribution.
Comment: Does this answer your question? [Find $F'(x)$ if $F(x) = \displaystyle \int_{0}^x xf(t)dt$.](https://math.stackexchange.com/questions/1787750/find-fx-if-fx-displaystyle-int-0x-xftdt)
Comment: Ian, that is very helpful. The derivative of $\int_0^x7f(t)dt$ at $x = 7$ is $7f(7)$. This is not the same as the derivative of $\int_0^xxf(t)dt$ at $7$. The former doesn't have the same dependence on $x$, duh! Thank you!
Comment: Thanks all for helping shed more light on this. @Ian, if you wish to paste your comment as an answer I'll happily accept it.
Answer: The Fundamental Theorem of Calculus  says that the derivative of $\int_a^{x}  g(t)dt$ is $g(x)$ if $g$ is  continuous. This does not apply to the derivative of $\int_a^{x}  g(t,x)dt$. You cannot apply the theorem when the integrand depends on $x$ even if it continuous in both variables.
Comment: Understanding a theorem requires much needed focus on the hypotheses so that one does not jump to conclusion blindly. That the integrand must be independent of $x$ is very important here. +1
Answer: In this particular case, you can solve the problem as
$$\frac{d}{dx} \int_0^x x f(t) dt = \frac{d}{dx} \left ( x \int_0^x f(t) dt \right ) = \int_0^x f(t) dt + x f(x)$$
by the product rule together with FTC.
More generally you have the Leibniz rule:
$$\frac{d}{dx} \left ( \int_{a(x)}^{b(x)} f(t,x) dt \right ) = f(b(x),x) b'(x) - f(a(x),x) a'(x) + \int_{a(x)}^{b(x)} \frac{\partial f}{\partial x}(t,x) dt.$$
The Leibniz rule captures the dependence of the integral on $x$ through both the limits of integration and the integrand. In your problem, giving the answer $x f(x)$ would only encapsulate the dependence on the limits of integration.


Node Access Product Module (nap) - Really embarrassing error message

Question: I have built an Ubercart site, using the Node Access Product module, that sells only two products, one of which is access to a single node. Everything works correctly, but after the customer makes a successful purchase the following errors are repeated all the down the completed order page:
"Notice: Trying to get property of non-object in nap_save_purchase() (line 1508 of /home/mysite/public_html/sites/all/modules/nap/nap.module)"
and
"Notice: Undefined index: type in drupal_write_record() (line 7025 of /home/mysite/public_html/includes/common.inc)"
I have been everywhere looking for an answer. Can anyone help?
Answer: This error is thrown when an object is empty, and you attempt to determine the value of a property. In this case the following code is responsible:
 // Go through each of the products purchased.
  for ($i = 0; $i < count($product_nodes); $i++) {
    // Easy referencing.
    $node = &$product_nodes[$i];
    $settings = nap_get_nap_settings($node->nid); <- Throws error

My guess is that $product_nodes is empty.
Try wrapping the for loop as follows:
 // Go through each of the products purchased.
  if (!empty($product_nodes)) {
    for ($i = 0; $i < count($product_nodes); $i++) {
      // Easy referencing.
      $node = &$product_nodes[$i];
      $settings = nap_get_nap_settings($node->nid);

      ..rest of loop code ...

    } //End of for loop
  }

This should work. You should also bring this up as an issue on the project page.
Comment: @Patrick Wire - This was already an [issue on D.O.](http://drupal.org/node/1936502). I know you are new to Drupal Answers, but if the answer helped, please indicate it by accepting the answer so other will know it has been solved. Otherwise please post a comment indicating that it did not work so we can look for other solutions.
Answer: 2 things.

Somewhere in your code your saving something with a column type in
a database table. It's probably in nap_save_purchase(). The field
is blank when you save the record to the DB. fix that.
You have all error messages likely going to the screen on your live website. You can hide Notice messages in your settings.php file with like ini_set('error_reporting', 'E_ALL ^ E_NOTICE');


Factorization into irreducible factors

Question: I am trying to find a factorization of the following polynomial $f=X^{4}Y^{2}+X^{3}+X^{2}Y^{4}+XY^{2}$ into irreducible factors over $\mathbb{Z}_{2}[X,Y]$.
I know that $\mathbb{Z}_{2}[X,Y]$ can be written as $\mathbb{Z}_{2}[X][Y]$, so we have to bring first $f$ in the form of $\sum_{i=1}^{n}f_{i}Y^{i}$, where every $f_{i}$ is an irreducible polynomial of the ring $\mathbb{Z}_{2}[X]$, but i have problems with this and in general i don't understand how to show the factorization in cases of $\mathbb{Z}[X,Y]$, $\mathbb{Q}[X,Y]$ etc.
Can anybody help me or give me a hint how to find this factorization? Thank you in advance!
Comment: Hint (to an ad hoc solution): $f(0,Y)$ and $f(X,X)$ both vanish. Also, look at the homogeneous parts.
Answer: Hint: Group the terms for which the sums of exponents is the same, then factor the appropriate power of the form $X^aY^b$ within each group, then notice other obvious factors.
Answer: $X^{4}Y^{2}+X^{3}+X^{2}Y^{4}+XY^{2}=X^2Y^2(X^2+Y^2)+X(X^2+Y^2)=X(X+Y)^2(XY^2+1)$.
Answer: Thanks to everybody for the help!
After the hint of Lucian, i figured out that i can write $f$ as $X^{2}Y^{2}(X^{2}+Y^{2})+X(X^{2}+Y^{2})=X(X^{2}+Y^{2})(XY^{2}+1)=X(X+Y)^{2}(XY^{2}+1)$.
With some more details:

$X$ is already irreducible;
Since we have $\mathbb{Z}_{2}$, a finite field with characteristic $2$, we have that $(X^{2}+Y^{2})=(X+Y)^{2}$, because every linear factor of the form $X+a$ in a prime power is irreducible;
Consider the last term $(XY^{2}+1)$ i look at  $X$ as a constant, my variable in this case is $Y$, clearly this polynomial has no roots in the given polynomial ring.

If you have any other comments, i will be glad to read them. Thank you one more time.

Factorization into irreducible factors


How to generate two sonar reports from the same project?

Question: I would like to create two sets of Sonar reports from the same project. One would have everything covered and the other one would have some packages excluded.
Is this possible and if so, how to do such?
Edit: Setting exclusions is not a problem but having two reports is.
Answer: Create new profile in maven and add call sonar with new branch for each profile: mvn clean install -Pprofile1 sonar:sonar -Dsonar.branch=BRANCH1
   <properties>
       <sonar.branch>
          DEFAULT_BRANCH
        </sonar.branch>
    </properties>

    <profiles>
            <profile>
                <id>sonar</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
                <properties>
                    <sonar.host.url>
                      http://localhost:9000
                    </sonar.host.url>
                </properties>
            </profile>
            <profile>
                <id>profile1</id>
                <properties>

                    <sonar.host.url>
                      http://myserver:9000
                    </sonar.host.url>
                </properties>
            </profile>
         </profiles>


Java Iterator for circular linked list

Question: I've created a CircularLinkedList class, instead of using the util LinkedList class. The problem is based off of the Josephus problem, stating that for a circle of 20 people, each 12th person is to be killed until it is determined which position the survivor will be left standing in (using an Iterator). I'm confused as to how I could use an Iterator with this problem, since I'm using my own class instead of LinkedList, which already has an iterator() method so that I could declare an Iterator like this:
Iterator<E> iter = cll.iterator();

I have no idea how I would write my own Iterator method, and I feel like I have to be over thinking this. Any help is appreciated! I can post my code if it would clear anything up that I forgot to mention
I'm still stuck on this, so I figured I'd post my code to see if anyone can help. It's a lot, so I apologize.
Itr class (Iterator)
import java.util.Iterator;

public class Itr<E> extends CircularLinkedList<E> implements Iterator<E>
{

  /** the size of the list */
  private int size = 0;
  /** for the hasNext() method for Iterator */
  private int nextNode = 0;
  /** two Nodes used for next() method for Iterator */
  private Node<E> lastReturned = null;
  private Node<E> nextUp;

  /** part of the Iterator implementation */
  public boolean hasNext()
  {
    return nextNode < size;
  }

  /** part of the Iterator implementation */
  public E next()
  {
    lastReturned = nextUp;
    nextUp = nextUp.getNext();
    nextNode++;
    return lastReturned.data;
  }

  /** part of the Iterator implementation */
  public void remove()
  {
    Node<E> lastNext = lastReturned.getNext();
    if (lastReturned == null)
      nextUp = lastNext;
    else
      nextNode--;
    lastReturned = null;
  }
}

Josephus class
public class Josephus<E>
{
  public static void main(String[] args)
  {
      CircularLinkedList cll = new CircularLinkedList();
      Itr iter = cll.iterator();

      int lastMan = 0;
      int n = 20;
      int passes = 12;
        while(n > 1)
        {
          iter.next();

          for(int i = 0; i < n; i += passes)
          {
          iter.hasNext();
          iter.remove();
          if(n == 1)
            lastMan = n;
          }
        }
    System.out.println("Survior: " + lastMan);
  }
}

CircularLinkedList class
public class CircularLinkedList<E>
{
  public class Node<E>
  {
    /* data value **/
    public E data;
    /* the link **/
    private Node<E> next = null;

    /** constructs a Node with given data and link
      * @param data the data value
      * @param next the link
      */
    public Node(E data, Node<E> next)
    {
      this.data = data;
      this.next = next;
    }

    /** construct a Node with given data value
      * @param data the data value
      */
    public Node(E data)
    {
      this.data = data;
    }

    /** return the data value of a Node
      * @return the data value
      */
    public E getData()
    {
      return data;
    }

    /** set the next Node in a list
      * @param append the data value that the new Node will contain
      */
    public void setNext(Node append)
    {
      next = append;
    }

    /** return the next Node
      * @ return the next Node
      */
    public Node<E> getNext()
    {
      if(current.next == null)
      current.next = current;

      return next;
    }
  }

  /** a reference into the list */
  private Node<E> current = null;
  /** the size of the list */
  private int size = 0;

  /** helper methods */

  /** remove the first occurance of element item.
    * @param item the item to be removed
    * @return true if item is found and removed; otherwise, return false.
    */
  public void removeItem(E item)
  {
    Node<E> position = current;
    Node<E> nextPosition1,
            nextPosition2;

    while (position.next != null)
    {
      if(position.getNext().getData().equals(item))
      {
        nextPosition1 = position.getNext();
        nextPosition2 = nextPosition1.getNext();
        position.setNext(nextPosition2);
      }
      else
      {
        position = position.getNext();
      }
    }
  }

  /** set the first Node in a list
    * @param append the data value that the new Node will contain
    */
  public void addFirst(E append)
  {
    current = new Node<E>(append, current);
    size++;
  }

  /** add a new Node as the last in the List
    * @param data value of the new Node
    */
  public void addNext(E value)
  {
    // location for new value
    Node<E> temp = new Node<E>(value,null);
    if (current != null)
    {
      // pointer to possible tail
      Node<E> finger = current;
      while (finger.next != null)
      {
        finger = finger.next;
      }
      finger.setNext(temp);
    } else current = temp;
    size++;
  }

  /** return the data value of the fourth Node in the list
    * @return the data value
    */
  public E printFourth()
  {
    current.next.next.next = current;
    return current.next.next.next.getData();
  }

  /** return the size of the LinkedList
    * @return the size
    */
  public int size()
  {
    return size;
  }

  public E get(int index)
  {
    Node<E> temp = null;
    for(int i = 0; i < index; i++)
    {
      temp = current.next;
      System.out.print(temp.getData() + " ");

    }
    return temp.getData();
  }

  public Itr<E> iterator()
  {
    return new Itr<E>();
  }

  @Override
  public String toString()
  {
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    Node<E> aux = this.current;
    boolean isFirst = true;
    while(aux != null)
    {
      if(!isFirst)
      {
        sb.append(", ");
      }
      isFirst = false;
      sb.append(aux.data.toString());
      aux=aux.next;
    }
  return sb.append("]").toString();
  }
}

I'm getting a NullPointerException from the next() method in the Itr class on the line
nextUp = nextUp.getNext();

Am I doing something wrong in the CircularLinkedList class for it to not actually be circular or is there a problem with my driver/Itr classes? I'm kind of lost at this point. Any help is appreciated.
Comment: Posting code is a good idea. To create your own `iterator` method you need to create a class which provides some methods: http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html. Those will pick the next one out of your data structure.
Comment: Extremely relevant post:  http://stackoverflow.com/questions/5849154/can-we-write-our-own-iterator-in-java
Answer: Create a custom class which implements Iterator and return the custom Iterator from your CLL.iterator method.
See LinkedList#ListItr for inspiration - but only conside the Iterator methods (next, hasNext, remove) for this exercise. A true circular linked-list will simply follow the next node, always, and has no end - hasNext will always return true if there is at least one element. If your CLL implementation has an "end", then make sure to "move back to the start" when it is encountered.
In addition, the CLL class should conform to Iterable, which means it has an iterator method to obtain an Iterator.
Comment: Thanks for the advice, I have since implemented Iterator in a custom class but I'm still having some issues that I've edited into my original post. Any ideas of what I could be doing wrong?
Comment: @smittywerbenjagermanjensen You never set `nextUp` to a value before it's first used. Or, if you did, it was `null`. Then this is simply a matter of *debugging* your code - you know that `nextUp` is null, so find out *why* and fix it.
Comment: If I do nextUp = null, I still have the same problem. Unless I'm supposed to be assigning another value that I'm not realizing(I've been working on this for a while and am losing focus).
Comment: `(null).getNext()` *is* what causes the exception; and `nextUp` *is* null in the line `nextUp.getNext()`, as witnessed by the exception. This is clearly invalid and must be addressed. I suspect that `nextUp` is not initially assigned a *valid* (i.e. the first) Node; if this is not the case, then at some point `nextUp.getNext()` itself results null, such that `nextUp` is null after `nextUp = nextUp.getNext()`.

Java Iterator for circular linked list


Opening serial port used by a printer

Question: I'm sending ESC/P codes (http://webpages.charter.net/dperr/links/esc_p83.htm) to an Epson LX-300 printer which is connected to the COM1 and the pc already has the correct driver installed because someone else needs it.
So i wrote this:
<code>using System.IO.Ports;

public class EpsonPrint {

    private char esc = (char)27;
    private char ff = (char)12;

    public static void Main (string[] args) {
        new EpsonPrint();
    }

    public EpsonPrint() {
        SerialPort port = new SerialPort("COM1", 19200, Parity.None, 8,  StopBits.One);
        port.Open();
        port.Write(esc+"@hola mundo!"+ff);
        port.Close();
    }
}
</code>
and it works but only with the Epson driver pointing to another port or something else, because if i let it using COM1 the code above throws:
"The given port name does not start with COM/com or does not resolve to a valid serial port."
and for the record, this is not a "port already open" error.
Answer: I think you need to send it to the Driver and not to the port.  Check out this article:
http://support.microsoft.com/kb/138594/EN-US/
Comment: Ok, that didn't work but thanks. My little C# does the job but is annoying to keep the original epson driver disabled.

Hehehe, stackoverflow is joking me, how can i start a bounty with only 1 reputation point?
Answer: COM1 hold by printer's driver. This prevent opening port by Your application. Try switch printer port in properties of printer's driver to something other then COM1. After this Your application will be free to use COM1.

Opening serial port used by a printer


which kind of statistics for continous variables

Question: I have one sample composed by 18 subjects. I measured the performance of a game and the fatigue before and after going to sleep and before and after a certain wake condition.
So, I have game scores and fatigue scores detected in 4 times.
All variables are continous and I cannot turn them in ordinal or nominal.
I want to test the differences among the performance in each condition (1- before sleep, 2-after sleep, 3-before wake, 4-after wake) controlling for the effect of fatigue measured in these 4 conditions.
I cannot perform a repeated measure Anova because my IV is not a fixed factor.
Which kind of statistical test is best suited for these kind of variables (i.e. continous)?
Thanks a lot!
Answer: I would recommend doing a Linear Mixed-Effects Model. You would assume something like this, where $i$ is the patient and $j$ is the condition:
$$
performance_{ij} = \beta + \alpha_j + \gamma*fatigue_{ij}+\epsilon_{ij}
$$
where $\epsilon_{ij}, \alpha_j$ are normally distributed with mean 0
the model has two types of effects (hence the word mixed):
fixed effects: $\beta,\gamma$
random effects: $\alpha_j$
It is like a simple linear regression but there is an extra intercept $\alpha_j$ that depends on the condition, which is what you want to measure. In other words, a different intercept is assumed for each condition. In this model the conditions only determine the intercept and not the slope, however you could assume a slope for each condition too.
After fitting the model you can use ANOVA to compare this model VS a model without random effects (i.e., a simple linear regression)
Are you familiar with R?
https://cran.r-project.org/web/packages/lme4/vignettes/lmer.pdf
Here is a simluation based on the formula above:
library(data.table)
library(magrittr)
library(lme4)

subjects <- 1:18
fatigue_effect <- -3
conditions <- c(1,2,3,4)
beta <- 10
alphas <- c(4,-2,-5,3) # this were not simulated so that you could see the actual values
set.seed(123)
fatigues <- runif(length(subjects)*length(conditions),0,2)

data <- lapply(conditions, . %>% data.table(subject=subjects,condition=.)) %>% rbindlist
data[,fatigue:=fatigues]
set.seed(123)

data[,performance:=beta+fatigue_effect*fatigue+alphas[condition]+rnorm(.N,0,2)]
model <- lmer(performance~fatigue+(1|condition),data)
coef(summary(model));ranef(model)

Here the 2 fixed effects, slope and sensitivity to fatigue are 10 and -3 respectively, and random effects by condition are: 4,-2,-5,3. The code will give the following results, pretty close to the actual values:

         Estimate Std. Error   t value
(Intercept) 10.158661  2.1848023  4.649693
fatigue     -3.089768  0.4240635 -7.286096
$condition
  (Intercept)
1    4.180160
2   -2.089153
3   -4.898196
4    2.807189

and the ANOVA test:
lreg <- lm(performance~fatigue,data)
anova(model,lreg)

refitting model(s) with ML (instead of REML)
Data: data
Models:
lreg: performance ~ fatigue
model: performance ~ fatigue + (1 | condition)
      Df    AIC    BIC  logLik deviance Chisq Chi Df Pr(>Chisq)
lreg   3 413.31 420.14 -203.65   407.31
model  4 322.56 331.67 -157.28   314.56 92.75      1  < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


How do I trill between F and D in the middle register?

Question: In a few pieces there are trills between the middle register F and D. I try to trill it with the normal fingering, but the trill ends up very clumsy and the notes, not well defined. How do I trill between these notes?
Comment: What instrument are you playing?
Comment: I'm playing the Flute.
Answer: There is an alternate fingering for this tremolo, but you will still end up moving two of your fingers. I believe you are trying to do a D5-F5 tremolo (correct me if I'm wrong). The easiest way to do this would be to finger a regular D, except place the first finger on your left hand down as well. Then you would lift your second and third fingers on your right hand to change to an F. It is not much of a fancy alternate fingering, but it is the only one that works for this tremolo as far as I know. Hopefully that will make it a bit easier for you to do.
Answer: You can also do it this way, which works better for me:
F - LH T123, RH 1-3
D - LH T-23, RH 123
No RH pinky for either note
That way, LH 1 moves, and RH 2, but the flute is stable and the D doesn't break as easily.  The F is slightly less full, but in a trill it's not as big a deal.


How to fix the error which is "Could not connect to remote process. Aborting debug session"

Question: when I am going to debug my application using android studio, I cannot do that because of this massage which is Waiting for application to come online: com.example.myapplication | com.example.myapplication.test . After sometime Could not connect to remote process. Aborting debug session is shown.
Comment: The device might have gone offline. Restart the device and try again
Comment: I tried but It didn't work, please help
Comment: Go in the file menu and click on **Invalidate cache and restart**. It should work after the restart
Comment: It also didn't work
Comment: Your question is duplicate of this https://stackoverflow.com/questions/36723813/not-able-to-debug-app-on-android-device-android-studio-2-0. Visit the link to check out plethora of answers
Comment: Possible duplicate of [Not able to debug app on android device - Android Studio 2.0](https://stackoverflow.com/questions/36723813/not-able-to-debug-app-on-android-device-android-studio-2-0)
Answer: I know this is an old post, but I had the same issue and could not get it to work, I then found in my app config that the Launch option was on nothing, changing that to "Default activity" fixed it for me
Answer: This work for me:
in directory C:\Users\your_name\ .android\avd I deleted all devices and then in Android Studio i created them again.
Before this, I tried Invalidate cache and restart option, some restarts/reboots of Android Studio/Devices/PC and deleting devices in Android Virtual Device Manager all of them with no results.
Comment: "Invalidate cache and restart" worked for me, thanks :)
Answer: The solution for me:

Go to Tools-> AVD Manager
Delete your Virtual device:

Create a new Virtual device
Answer: I had the same issue. The app didn't launch when I tried to run it without debugging. Debugging gave the same results as for OP. No real info about the issue.
The solution was looking through the recent changes I made.
My mistake was that I declared a permission under the <application> tag in the manifest file:
android:permission="android.permission.INTERNET"

instead of writing
<uses-permission android:name="android.permission.INTERNET"/>

above the <application> tag.
Answer: In my case the issue was in IntelliJ Idea being open along with Android Studio at the same time.
Closing IntelliJ Idea fixed the problem.
Answer: Restarting Android Studio and my phone worked for me


Handling data from form in modal dialog

Question: I'm building a tool that contains a few clickable regions. Each region has a link with class="use-ajax" data-dialog-type="modal" pointing at a custom form route.
Everything is working great and I'm able to get the data from the form and store it. I, however, need the user's selection in this modal form to be reflected in the region they initially clicked.
I'm at a loss aside from storing their selections in localStorage or something and populating that region when they close each modal. That seems a little hacky though. Is there a cleaner way of accomplishing this that I'm missing?

      Click to select

Comment: Why dont you include the region as a parameter in your route? `/my-route/{region}`
Comment: I mean if you pass down the region to you route you could later on your forms submit return an AJAX command udpating your HTML. I'll provide you an answer using dialog and AJAX callbacks.
Comment: @d70rr3s I think I could do that but I don't fully understand how I would then visually update that content in that region.
Answer: You can pass down your region's ID as parameters to your route. For example:
...

As explained here you can add arguments from the route to your form.
On the buildForm method you can have something like this
public function buildForm(array $form, FormStateInterface
  $form['button'] = [
    '#type' => 'button',
    '#value' => $this->t('Submit this form'),
    '#name' => 'ajax_trigger',
    '#ajax' => [
      'callback' => '::updateRegionAjaxCallback',
      'wrapper' => $region, // Assuming $region is the argument passed down.
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'click',
    ],
  ];
}

Later your callback method could look like.
public static function updateRegionAjaxCallback(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AppendCommand(NULL, [
    // Your render array with the data to be displayed.
    '#cache' => [
      'max-age' => Cache::PERMANENT,
      'contexts' => ['url'],
    ],
  ]));

  return $response;
}

This should work but keep in mind that will be best capture the form submit and triggering a custom AJAX event.
Comment: Thank you for the great answer! This was exactly what I needed!

Handling data from form in modal dialog


How can i exclude a specified path on my server from X-frame-options same origin?

Question: I have the following problem. My page is protected by x-frame-options same origin. The use of this header is known to me and works well. But I would now like to exclude a path on my server (i.e. mydomain.net/embed/ ...). So that this can be embedded in an iframe and not the rest of the website.
Website Server is NGINX. If statement should be avoided.
How can i solve this?
Answer: Remove x-frame-options same origin header from http or server block
Add x-frame-options same origin header on / location block and the excluded path /embed on separate location block
server {
    listen 80 default;
    server_name example.com;
    root /var/www/html/;

    location / {
        add_header X-Frame-Options "SAMEORIGIN";

    }

    location /embed/ {
        # Do nothing.
    }
}


Binomial uniform prior bayesian statistics

Question: Suppose to have a binomial distribution where the prior of the parameter is uniform.  How can I get the posterior distribution of the parameter?
Answer: This is very simple to do if you use a prior distribution that is conjugate to the Binomial likelihood function. A prior and likelihood are said to be conjugate when the resulting posterior distribution is the same type of distribution as the prior. This means that if you have binomial data you can use a beta prior to obtain a beta posterior. Conjugate priors are not required for doing bayesian updating, but they make the calculations a lot easier so they are nice to use if you can.
A beta prior has two shape parameters that determine what it looks like, and is denoted Beta(α, β). Taking your prior for p (probability of success) as uniform is equivalent to using a Beta distribution with both parameters set to 1.
In order to obtain a posterior, simply use Bayes's rule:
Posterior $\propto$ Prior x Likelihood
The posterior is proportional to the likelihood multiplied by the prior. What's nice about working with conjugate distributions is that Bayesian updating really is as simple as basic algebra. We take the formula for the binomial likelihood function,
$Binomial Likelihood \propto p^x (1-p)^{n-x}$
where x is the number of successes in n trials. and then multiply it by the formula for the beta prior with α and β shape parameters,
$Beta Prior \propto p^{\alpha-1} (1-p)^{\beta-1}$
to obtain the following formula for the posterior,
$Beta Posterior \propto p^x(1-p)^{n-x}p^{\alpha-1}(1-p)^{\beta-1}$
You'll see that we are multiplying together terms with the same base, which means the exponents can be added together. So the posterior formula can be rewritten as,
$Beta Posterior \propto p^xp^{\alpha-1}(1-p)^{n-x}(1-p)^{\beta-1}$
which simplifies to,
$Beta Posterior \propto p^{x+\alpha-1}(1-p)^{n-x+\beta-1}$
Which amounts to: Take the prior, add the successes and failures to the different exponents, and voila. In other words, you take the prior, Beta(α, β), and add the successes from the data, x, to $\alpha$ and the failures, n – x, to $\beta$, and there's your posterior, Beta($\alpha$+x, $\beta$+n-x).
When you start with a Beta(1,1) as your prior the posterior will have the exact shape of the Binomial likelihood, and the posterior is written Beta(1+x,1+n-x).
Graphs
If you start with your uniform prior, Beta(1,1), that looks like this:

If you have 13 successes in 25 trials the new posterior is Beta(1+13,1+12) or Beta(14,13), shown below:

There is code to make graphs like this and others at my blog, here.
Comment: Sure. The Beta distribution is just one way of parameterizing a uniform prior. Since the shape of the distribution is characterized by $p^{\alpha-1}(1-p)^{\beta-1}$, plug in $\alpha=1$ and $\beta=1$ and it simplifies to $p^0(1-p)^0$ which is equal to 1 for all values of p (the probability of success).
Comment: Sorry can you explain how we passed from the uniform prior to the beta?


control to show steps to do something in winforms

Question: i want to show steps on how to cook something in winform c# .net as steps. Something like a set of text area would be nice but:
-> list box considers the whole string of one step as one item so user needs to scroll horizontally to view the whole step.
-> datagridview is also not suitable as i want the text to word wrapped.
i also want the user to be able to edit the step.
any suggestions of custom control would be nice.
Comment: possible duplicate of [Controlling user workflow in Winforms](http://stackoverflow.com/questions/2064196/controlling-user-workflow-in-winforms)
Answer: Maybe a wizard like app would be suitable for you. AFAIK there's no native wizard control in C# but you could implement one using tabs or using one of many in the web.
Answer: A multi line text box will do the job great. just take a simple text box and do the following to it, and it will turn to a text area:
<code>                     TextBox listBoxNewInput  = new TextBox();
                    //Initialize label's property

                    listBoxNewInput.Multiline = true;
                    // Add vertical scroll bars to the TextBox control.
                    listBoxNewInput.ScrollBars = ScrollBars.Vertical;
                    // Allow the RETURN key in the TextBox control.
                    listBoxNewInput.AcceptsReturn = true;
                    // Allow the TAB key to be entered in the TextBox control.
                    listBoxNewInput.AcceptsTab = true;
                    // Set WordWrap to true to allow text to wrap to the next line.
                    listBoxNewInput.WordWrap = true;

                    listBoxNewInput.Width = 315;
                    listBoxNewInput.Height = 150;
                    listBoxNewInput.DoubleClick += new EventHandler(listBoxNewInput_DoubleClick);

                    flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
                    flowLayoutPanel1.Controls.Add(labelInput);
                    flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
                    flowLayoutPanel1.Controls.Add(list
</code>
BoxNewInput);


How to alter the POS order item table header and columns

Question: Using Drupal 8/Commerce 2 and the Commerce Point of Sale (POS) module, the autocomplete form to search and add a product to an order shows this table header.

  As indicated by @JayPan below, here is the code that outputs the header and the order item https://git.drupalcode.org/project/commerce_pos/-/blob/8.x-2.x/src/Plugin/Field/FieldWidget/PosOrderItemWidget.php#L285

My requirement is to remove the Return and Quantity columns and add custom ones based on custom fields set in the Default item type POS uses. Thank you.
Comment: https://git.drupalcode.org/project/commerce_pos/-/blob/8.x-2.x/src/Plugin/Field/FieldWidget/PosOrderItemWidget.php#L285
Comment: I would remove the part asking where the header is set, show the code the comment from @Jaypan is linking, and ask how to change that header.
Answer: Looking through the code, the table is generated as part of the form element for a field widget in Drupal\commerce_pos\Plugin\Field\FieldWidget\PosOrderItemWidget.
You will need to create a class that extends this class:
namespace Drupal\example\Plugin\Field\FieldWidget;

use Drupal\commerce_pos\Plugin\Field\FieldWidget\PosOrderItemWidget;

class ExamplePosOrderItemWidget extends PosOrderItemWidget {
  // Class methods go here.
}

You will then need to override the formElement() method (https://git.drupalcode.org/project/commerce_pos/-/blob/8.x-2.x/src/Plugin/Field/FieldWidget/PosOrderItemWidget.php#L223)
formElement() generates the header for the table. You can call the parent, then alter the form object
/**
 * {@inheritdoc}
 */
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element = parent::formElement($items, $element, $form, $form_state);
  // $element['order_items'] contains the table.
  // Make your alterations to $element['order_items']['header']
  // and $element['order_items']['rows'].
}

Note that $element['order_items'] will contain the fully generated table. You should can remove any header items and column items you want, and add any new ones. However, you may want to also consider overriding orderItemForm() (https://git.drupalcode.org/project/commerce_pos/-/blob/8.x-2.x/src/Plugin/Field/FieldWidget/PosOrderItemWidget.php#L321). This method generates the form elements for each table row. You could rewrite the implementation to not generate the elements you don't want, and to generate the elements you do. Then in your formElement() override, you will only need to alter the header of the table, as the rows will already be built with the elements you need.
After you have overridden the class, you need to implement it. There are two ways to do this, depending on your requirements.
If you want this table change to be across all field widgets of this type anytime this widget is ever used, you can use hook_field_widget_info_alter():
hook_field_widget_info_alter(array &$definitions) {
  $definitions['pos_order_item_widget']['class'] = 'Drupal\example\Plugin\Field\FieldWidget\ExamplePosOrderItemWidget';
}

You will then clear the cache, and now anywhere that the widget is implemented in the system, now or in the future, your override will be used instead of the original class.
If you want to be able to apply this change to specific fields, and still have the original implementation available, you can use your override class to create a new widget type by adding the widget annotation as the comments for your class:
/**
 * Plugin implementation of the 'example_pos_order_item_widget' widget.
 *
 * @FieldWidget(
 *   id = "example_pos_order_item_widget",
 *   label = @Translation("Example Pos order item widget"),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = true
 * )
 */
class ExamplePosOrderItemWidget extends PosOrderItemWidget {

Now the system will have a new widget type available, Example Pos order item widget. You can go to the field implementation(s) you want to change, and select this widget.
Comment: this suggestions took a while to get use to but it worked! Answer accepted.
Comment: Thank you. D8 is still very strange, where do I place all these, within a custom module or within the .theme file?
Comment: The class will be in its own module and file, according to PHP PS4 standards. Unfortunately, the explanation for this is about PHP OOP coding, which is outside the scope of this Q&A. The solution I've given assumes and requires an understanding of how PS4 autoloading and PHP OOP class overriding work, which is a prerequisite of Drupal 8 module development.
Comment: Right, it's very clear, guess it's time roll up the mod development I've been dodging. I'll revert with what I come up. Really appreciate the details


sls remove without .serverless directory

Question: The Serverless Framewokrk creates the .serverless directory with configuration of AWS components.
If it is not present what will happen with sls remove?
Imagine that someone else deployed, and I just cloned the repo and need to remove everything. Should I add this directory in the repository?
Answer: sls remove will be referring to serverless.yml file and will be removing the stack.
.serverless directory is created when you do a sls deploy
It will basically have some contents like zip file which is used to deploy it to AWS.
So you need not create an .serverless directory manually for anything. It is also not recommended to push this directory to git either.


Tracking OSI packets with Wireshark

Question: All the 7 layers of the OSI model work together to define to the endpoint what is the type of machine he is dealing with.
But I wonder why can't I detect a OSI packet with an software like wireshark? Because Wireshark should track every packet that goes to my machine, right? But I've never seen an "OSI packet" before.
Am I doing something wrong? Is my concept of OSI packets right?
Comment: You can't detect an OSI packet with anything, because there aren't any. It is as dead as the dodo.
Answer: Wireshark shows layers that are not exactly OSI or TCP/IP but a combination of both layers.
As Wireshark decodes packets at Data Link layer so we will not get physical layer information always.
But in some cases, capturing adapter provides some physical layer information and can be displayed through Wireshark.
Generally, we see layers whick do not exceed below layers:
<code> - Physical Layer
 - Data Link Layer
 - Network Layer
 - Transport Layer
 - Application Layer
</code>
It should be noted that the layers is in reverse order different from OSI and TCP/IP model.
Refer to link for more details.

Tracking OSI packets with Wireshark


What day number in TABLEAU online

Question: I want to extract DAY number from any dynamic date
is there a better way to do it?
I need to recieve an integer as a result
this does not work =
<code>DAY(Today())
</code>
Answer: added MAX to property and it sorted out

What day number in TABLEAU online


Implementing css with html file does not work

Question: I'm a beginner in using html and css files and have been stuck with the following problem for a while.
I made these files but I cannot get the css implemented in the html file:
app.py
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    greeting = "hello there!"
    return render_template('index.html', greeting=greeting)

if __name__ == "__main__":
    app.run()

index.html
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>epic website</title>
        <meta name="description" content="">
        <meta name="viewport" conent="width=device-width">
        <link rel="stylesheet" href="style.css">

Sup, {{ greeting }}

Praisethelord

basinga

style.css
h1 {
    color:pink;
    font-size: 12px;
}

p {
  color:yellow;
  font-size: 1px;
}

.x {
  color:brown;
}

When I open the browser it does use the html file but without the css file (for some reason I cannot show pictures).
When I press f12 to check what's going on, it gives me the following errors:
Failed to load resource: the server responded with a status of 404 (NOT FOUND)style.css:1
Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Any idea what I am doing wrong? I have a feeling it has something to do with the directories, but I have been playing around with it for a while and cannot seem to figure it out.
Comment: Are index.html and style.css in the same folder?
Answer: You have to add a static file folder and it should in the same directory.Css files are added to it
from flask import Flask, app

app =Flask(__name__,static_url_path='',static_folder='static')

Answer: Consider to use this structure:
project_folder
    | ---------- config.py
    | ---------- app.py
    | ---------- .flaskenv
    | ---------- app/
                  | ---------- routes.py
                  | ---------- __init__.py
                  | ---------- models.py
                  | ---------- templates/
                                   | ---------- index.html
                  | ---------- static/
                                  | ------ css/
                                             | ------ styles.css

Your routes go to rotues.py, templates will found in templates sub-folder, all styles will be in css sub-folder.
Initialize your application in __init__.py You do not need to use this on this file:
# ...

if __name__ == "__main__":
    app.run()

Because your top-level file app.py will act as the entry point of your application. Eventually, you will have this kind of application:
# __init__.py

from flask import Flask

app = Flask(__name__)

from app import routes, models

# routes.py
from app import app
from flask import render_template

@app.route('/')
def index():
    greeting = "hello there!"
    return render_template('index.html', greeting=greeting)

# app.py
from app import app

Templates will be in index.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>epic website</title>
        <meta name="description" content="">
        <meta name="viewport" conent="width=device-width">

        <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'css/styles.css') }}">

Sup, {{ greeting }}

Praisethelord

basinga

To run your app, pass flask's environment variables in .flaskenv:
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=True

Run flask run in your terminal to start your server.


Convergence of binomial to normal

Question:  Problem: Let $X_n \sim \operatorname{Bin}(n,p_n) $ where $p_n \xrightarrow{} 0$ and $np_n \xrightarrow{} \infty$. What I need to show is that
$$\frac{X_n - np_n}{\sqrt{np_n}} \xrightarrow{d} N(0,1) \text{ as } n\xrightarrow{} \infty.$$
My thoughts: My first thought was to set
$$Y_n=\frac{X_n - np_n}{\sqrt{np_n}}$$
and investigate $P(Y_n=k) = p_{X_n}(\sqrt{np_n}k + np_n) $ as $n$ goes to infinity, but this led to very messy calculations so I don't know if it is the right approach. My second attempt was with Central Limit Theorem, rewriting $X_n$ as a sum of Bernoulli random variables, $X_n = Z_1 + \dots + Z_n$, $Z_n \sim \operatorname{Be}(p_n)$. The expectation and variance of each $Z_i$ is dependent on $n$ in that case. Will that violate any assumptions in CLT?
I prefer working out these kind of questions from definition rather than using a theorem and previous results, so if anyone can show me that I would be very grateful!
Thanks.
Comment: Your second attempt is definitely on the right track. For the first one, do you mean $k$ to be an integer? Because obviously that's not right. Plus, even if you allow $k$ to be any real number, you still get into trouble because the probability goes to zero. You need to be careful in going from a discrete to a continuous distribution.
Comment: The reason why this doesn't yield instantly to the most usual form of the central limit theorem is that these are not identically distributed, since $p_n$ depends on $n$.  And the fact that $np_n\to\infty$ matters.  One approach might be to try to prove this the same way the central limit theorem is proved, by looking at the limit of the sequence of characteristic functions.
Comment: Hm.. true, didn't think of that. How would one approach this question if one was not allowed to use CLT to solve it?
Comment: Thanks for the comment. But for every $n$, all $Z_i$ are indentically distributed?
Comment: Why $\sqrt{np_n}$ in demoninator and not $ \sqrt{var(X_n)} = \sqrt{np_n(1-p_n)} $?  Shouldn't $Y_n = \frac{(X_n - \bar{X_n})}{\sqrt{var(X_n)}} \sim N(0,1)$?
Answer: I would do this in two steps. First take $n\to \infty$ and $p\to 0$ while keeping $np=m$ for some finite integer $m$. That brings you from the Binomial distribution to the Poisson distribution with parameter $m$ because
$$
P(X_n=k)=\binom{n}{k}p^k(1-p)^{n-k}\approx\frac{1}{k!}\left(\frac{np}{1-p}\right)^k(1-p)^n
\rightarrow\frac{m^k}{k!}e^{-m}.
$$
Then view this Poisson distribution with parameter $m$ as the result of summing $m$ independent Poisson random variables, each with parameter $1$. You can then use the central limit theorem to take $m\to\infty$.
Answer: Here is a nice review that lists four proofs: De Moivre's method using Stirling's formula to approximate the factorials in the binomial coefficient; a relatively new "method of ratios" and then the "method of moments" plus the CLT-based approach.
Comment: I see Section 3.1. Is there really no simpler way to show via this method?

Convergence of binomial to normal


Views callback work only once with advanced form block

Question: this code work but the views is callback only once (reload only once), any idea to reload more than one time ?
see in detail on drupal.org
function modulename_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'form_id_of_your_afb_form':
            $form['#validate'] = array();
            $form['ajax-submit']['#ajax']['callback'] = 'modulename_create_callback';
    }
}
function modulename_create_callback($form, &$form_state) {
    // load view
    $view1 = views_embed_view('view_name','view_display_name',$view_arguments_as_required);

    // replace the afb form with a clean form
    $newform = afb_ajax_handler($form, $form_state);
    $commands = array(
      ajax_command_replace('#target_div_id_of_view_to_update .view',$view1),
      ajax_command_replace('#target_div_id_of_afb_form_to_replace',render($newform)),
    );
    $form['#type'] = 'ajax';
    $form['#commands'] = $commands;
    return $form;
}

Answer: you just need to put the number of tid directly here :
ajax_command_replace('#target_div_id_of_view_to_update .view','1'),

Answer: According to your description and code you have only one requirement that is update views block on form submission. So,

You don't have to alter the form AJAX as AFB form submission already uses AJAX.
Furthermore, you don't have to replace the form using ajax_command_replace() as its already replacing using AFB
You don't have even to return the form as well.

What do you need is to

Get the Term ID and set as views contextual filter
Alter AJAX rendering using HOOK_ajax_render_alter()
Replace using ajax_command_replace()

So, use below code to get it worked.
function MODULENAME_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'sport_node_form':
            if ($term = menu_get_object('taxonomy_term', 2)) $_SESSION['tid'] = $term->tid;
    }
}
function MODULENAME_ajax_render_alter(&$commands) {
    if(isset($_SESSION['tid']) && is_numeric($_SESSION['tid'])){
        $mavue_new = render(views_embed_view('mavue_new','default', $_SESSION['tid']));
        $commands[] = ajax_command_replace('.view-mavue-new', $mavue_new);
    }
}

I hope this would help someone else.


Linear Algebra, Finding Matrices

Question: Find the matrix of a given linear operator in given new bases:
a) L=< e1, e2, e3>, M=< ge1, g2>
f(e1)=g1-2g2, f(e2)=g1+g2, f(e3)=2g1+3g2
e ̃1=2e1−e3, e ̃2=e2+e3, e ̃3=e1−e2
g ̃1=g1+2g2, g ̃2=2g1-g2
So far I have this, what are the next steps?
f(e ̃1) = 2f(e1)-f(e3) = 2(g1-2g2)-(2g1+3g2) = -7g2
f(e ̃2) = f(e2)+f(e3) = g1+g2+2g1+3g2 = 3g1 + 4g2
f(e ̃3) = f(e1)-f(e2) = g1-2g2-g1-g2 = -3g2
Comment: Is $ge_1$ in the first line meant to be $g_1$?
Answer: Recall the change of basis formula for a linear transformation: If $A=\operatorname{Mat}_{L,M}(f)$ is the matrix of a linear transformation $f$ with respect to the bases $L$ and $M$, and $P$ and $Q$ map from $L$ to $\tilde L$ and $M$ to $\tilde M$, respectively, then the matrix of $f$ with respect to $\tilde L$ and $\tilde M$ is $\operatorname{Mat}_{\tilde L,\tilde M}(f)=QAP^{-1}$. These matrices are easy to find if you remember that the columns of a matrix that represents a linear transformation are the images of the basis vectors.
In this problem, we're given the operation of $f$ on the $L$ and $M$ bases, so we can write down $\operatorname{Mat}_{L,M}(f)$ directly: $$\operatorname{Mat}_{L,M}(f)=\pmatrix{1 & 1 & 2 \\ -2 & 1 & 3}.$$ Similarly, we can write down the matrices for the $\tilde L\to L$ and $\tilde M\to M$ mappings directly from the given information. I'll leave that and the inversion and multiplications to find $\operatorname{Mat}_{\tilde L,\tilde M}(f)$ to you.

Linear Algebra, Finding Matrices


find equation of tangent line to y=1/x^2 at point where x=-1

Question: find equation of tangent line to y=1/x^2 at point where x=-1
I got the right answer by finding f'(-1)=2
and plugged (-1,1) and 2 as slope to get y-1=2(x+1)
I know there's more complicated way of solving but just want to be sure if the way I did it is correct.
This question does not meet our quality standard? I'm new to this and have no idea what this means.... please its easy question but our teacher didn't teach this specifically and I have a calculus test today.
Answer: Yes, you are absolutely right.


Login using "pre Windows 2000" username to Active Directory

Question: Is it possible to login to Active Directory using the pre Windows 2000 username to Active Directory using Unboundid ldap sdk?
The pre Windows 2000 username is DOMAIN\username and an end user may enter it in the login page.
If yes, how is possible to do it?
Is pre Windows 2000 username LDAPv3 compliant?
Added
For successful authentication I need to find a user DN user using provided user information.
Unfortunately, there is no such attribute as DOMAIN in Active Directory (and probably in other LDAPs also).
The domain is part of UPN – but I want to perform the standard LDAP search using the object attributes.
How is possible to find a user object using DOMAIN\username?
Comment: Why don't you simply do on after 13 years and use UPNs?
Comment: Thanks, it is legacy customers :)
Answer: If the SDK is implemented correctly, it should not care how the bind username looks like because it will simply pass the string to the directory. It can be a DN, Legacy Logon Name, Implicit or Explicit User Principal Name, maybe even a SID. Can't you simply try it out?
Comment: Read [here](http://tools.ietf.org/html/rfc4513#page-15). The RFC requires a DN but the Active Directory is more flexible, it supports several formats, and yes it support the legacy names too, unfortunately.
Comment: Yes, I did it without success.
For successful authentication I need to find a user DN user using provided user information.
Unfortunately, there is no such attribute as `DOMAIN` in Active Directory.
The domain is part of UPN – but I want to perform the standard LDAP search using the object attributes.
How is possible to find a user object using `DOMAIN\username`?
Comment: Please provide the exact error returned by the Active Directory. Use Wireshark if you need to and will see exactly why your bind fails. You can translate the realm to the netbios domain, see [here](http://stackoverflow.com/q/14119753/696632). I have fully functioning code how to find the DN of a user in forest based on the UPN, you'd simply nead to translate the Legacy Logon Name to a UPN.
Comment: Do you know if `DOMAIN\username` is LDAPv3 compliant?
Comment: Thanks! Unfortunately, it is only Active Directory supports several formats and the `DOMAIN\username` will not work for other vendors.
Comment: @Michael, correct. Did you try again and read the error message?
Comment: I decided not to support it since it is not LDAPv3 compliant. I promote and accept your answer for your help in comments.
Comment: @Michael, what do you use instead? No user will memorize his DN.
Comment: Correct, to find DN I perform search using for user using `sAMAccountName` and `userPrincipalName` attributes.
As I stated before, I can not search for the domain since LDAP do not support it.


imprimir valores não repetidos

Question: boa noite, tô desenvolvendo uma questão, já está quase completa, to conseguindo excluir valores repetidos sequencialmente, por exemplo: 1 1 2 3 4 5 1, tal qual exclui 1 e 1 e deixa somente 2 3 4 5 1, no entanto, se eu digito 1 2 3 4 1, ele imprime essa sequência, sem remover os repetidos, o que devo alterar no meu código para resolver isso? se alguém poder ajudar, agradeço.
segue anexo:
#include <stdio.h>
#include <string.h>
int main() {
    int vet[10];
    int pos[10];
    int semdup[10];
    int qtd=0; int qtd1=0;
    for (int i = 0; i < 10; ++i) {
        scanf("%d", &vet[i]);
        if (vet[i]>0) {
            pos[qtd++] = vet[i];
        } else {
            printf("Negativo.\n");
        }
    }

    printf("\n");
    for (int i = 0; i < 10; ++i) {
        printf("%d ", vet[i]);
    }

    printf("\n");
    for (int i = 0; i < qtd; ++i) {
        printf("%d ", pos[i]);
    }

    printf("\n");
    for (int i = 0; i < qtd; ++i) {
            if (pos[i] == pos[i+1]) {
                pos[i] = pos[i+1];

            } else {
                semdup[qtd1++] = pos[i];
            }
    }
    for (int i = 0; i < qtd1; ++i) {
        printf("%d\n", semdup[i]);
    }
    return 0;
}

Answer: Digamos que vc tem um array com elementos repitidos e fora de ordem 1, 1, 2, 3, 4 ,5, 1 e deseja imprimir na tela somento os valores que não são repitidos 1, 2, 3, 4, 5.
Primeiro, devemos organizar o array em ordem crescente, ou seja,1, 1, 1, 2, 3, 4 ,5. Pra isso percorremos o array, item por item, e testamos se o item atual é maior que o proximo item. Se verdadeiro, movemos de lugar o item de maior valor dentro do array.
Segundo, devemos percorrer o array testando se o item atual é diferente do proximo item, se for devemos imprimir o valor na tela, resultando em 1, 2, 3, 4, 5.
int main()
{
    int array[] = {1, 1, 2, 3, 4 ,5, 1};
    int size = sizeof array / sizeof *array;

    /*ORGANIZA ARRAY */
    for (int i = 0; i < size; ++i)
    {
        for (int j = i + 1; j < size; ++j)
        {

            if (array[i] > array[j])
            {
                int a = array[i];
                array[i] = array[j];
                array[j] = a;
            }

        }
    }

    for(int i = 0; i < size; i++)
    {
        int j = i + 1;
        if(j <= size)
        {
            if(array[i] != array[j])
            {
                printf("%d\n",array[i]);
            }
        }
    }

}

Comment: agradeço muito pela sua ajuda, nao havia pensado em ordenar, ainda sou meio ruim nessa área, deu certo ordenando, valeu.

imprimir valores não repetidos


Associate Every Displayed User Name With Corresponding users.data Table Row

Question: Updated:
I would like data from the users.data table displayed with every "User Name" however it is displayed.
As an example, I have this in hook_preprocess_page_title():
function hook_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $gUD = \Drupal::service('user.data');
    $routeUID = \Drupal::routeMatch()->getRawParameter('user');
    $gudValue = $gUD->get('module', $routeUID, 'name');

    if ($gudValue = $moduleValue)) {
      kpr('Success!');
    }

  }

}

The route entity.user.canonical allows me to reference the viewed user, and so I can use \Drupal::routeMatch()->getRawParameter('user') to get the non-current user ID. (it's not the route that counts, but my ability to reference the users.data table for the displayed user)
And this in hook_preprocess_username():
function hook_preprocess_username(&$variables) {
  $gUD = getUsersData();
  $gudValue = $gUD->get('module', $variables['uid'], 'name');
}

So what I am looking for is something like:
hook_preprocess_HOOK() {
  $UID = // From displayed user name.
  \Drupal::service('user.data')->get('module', $UID, 'name');
}

for each displayed user name.
The problem here: get user id from username or email without logging in, is that I don't know, and cannot manually enter the username value.

A couple of examples where the username is displayed on a page without using the username field:

Views field Name (not linked to user, uses views field base)
User type entity reference field (format display label, uses field base)

hook_preprocess_page_title() and hook_preprocess_username() are pretty straight-forward. And I believe I know where/when this template/hook will be used, but I am still having trouble defining a couple of other instances, and determining the best hook to alter the output as needed.
Comment: `loadByProperties()` queries the entire user table. Why should it be restricted to current user values?
Comment: While trying to get the value of `username` from a preprocess function, without a route parameter of `.user.`, I have not found a way to set that value to something other than the current user.
Comment: I might have had a little progress, and it may better define what I'm asking. Once I set the `format` option of the user entity reference field to `Author`, instead of `label` on my content type, and now actually renders out the username field value, `hook_preprocess_username(&$variables)` does return `$variables['name']` relative to the referenced user, not the current user. My error? Maybe, but now I'm unsure about `label format display.
Comment: The label display is generic to all entities, it simply prints out what is defined as label for the entity, title for a node, or username for a user. When you render the user you have the normal theming options including preprocess hooks.
Comment: It's not clear for which pages you are interested to get the user information. There are many pages for which the route name is not *entity.user.canonical*. Some of them could be user pages, some of them are for entities with a user entity reference field, and some of them aren't related to a user account in any way.
Comment: Just to make an example, if you are using `\Drupal::routeMatch()->getRouteName()` inside `hook_preprocess_page_title()` when the user is visiting /user/1/edit, the route name would not be *entity.user.canonical*, but the page is still about a user account; it's actually the edit form for the user #1, but still there is a user account associated to that page.
Comment: I've added to my question.
Answer: It sounds like you should start with what you don't want.
Drupal::currentUser()->id() will retrieve the current user's UID. From there, you can use the UserStorage::loadByProperties() method you referenced to pull the UID by user name. The last step is add code to check Drupal::currentUser()->id() doesn't match the UID found from UserStorage::loadByProperties()
Comment: What it's not clear from the question is for which pages the OP is trying to access the user information. There are many pages for which `\Drupal::routeMatch()->getRouteName()` doesn't return `'entity.user.canonical'`. If the page is associated to a user account, then it's quite easy to get information about that user. Differently, there are many users who aren't the currently logged-in user. `UserStorage::loadByProperties()` doesn't allow to load all the users for which the user ID is not a given one.
Comment: I think in most cases this would have been the correct answer, but @kiamlaluno is right about the UserStorage::loadByProperties() in my case. My question is how to get that value in the context of the user shown/listed. I did not ask the question very well as the issue may be a little different.


Envio de E-Mail pelo PHP Mailer

Question: estou usando o PHP Mailer para envio de e-mail, no Outlook aparece o título e assunto corretamente, mas onde está grifado em vermelho aparece parte do código HTML que compõe o corpo do e-mail, gostaria que aparecesse da mesma forma que a mensagem grifada em verde.
Procurei muito tentando achar algo, mas nada, não sei se é a forma que estou procurando, mas isso já me consumiu muito tempo.

A forma com que envio o e-mail é assim:
<?php

// Include PHP Mailer e Configurações

$mail->setFrom("FROM", "NAME_FROM");
$mail->addAddress("EMAIL", "NOME");
$mail->isHTML(true);
$subject = "ASSUNTO";
$mail->Subject = $subject;
$mail->Body = "HTML";
$mail->send();
$mail->ClearAddresses();

?>

Desde já agradeço.
Comment: Não tem nada de HTML onde está marcado em vermelho... Adicione na sua pergunta o valor que vc atribui à `$mail->Body`.
Comment: Se observar no final onde tem  essa tag é um link que provavelmente foi modificada pelo Outlook para aparecer desta forma
Answer: Resolvido o problema...
O Outlook precisa de uma tag especial para esse texto, espero que isso ajude alguém.

TEXTO AQUI

Envio de E-Mail pelo PHP Mailer


Video display with openGL

Question: I want to display very high resolution video directly with OpenGL.
The image data is going to be processed on the GPU and I want to avoid a round-trip back to the PC to show the video in a standard bitmap based window.
Cross platform is nice, Windows only would be OK (so would nvidia only)
Anyone have any links to ways doing this?
There is a poor NeHe tutorial and a few examples for embedded openGL widgets in Qt but I need much better performance and much larger images.
Answer: Assuming OpenGL 2.1, use a buffer object of type GL_PIXEL_UNPACK_BUFFER to stream pixel data to a texture. It's faster than uploading data every frame as the implementation might use DMA for copying when you use glMapBuffer, glMapBufferRange (OpenGL 3.2) or call glBufferData directly. You can also copy several frames in each batch to get a tradeoff between copy-overhead and mapping overhead. Last, create a shader to convert YUV or YCbCr to RGB and display the texture with a triangle strip.
Comment: Yes, quads suck in every respect and should not be used, Just forget they ever existed.
Comment: Any reason for the triangle over a fullscreen quad?
Comment: Triangles are optimized in Hardware. While quads are not. Manufacturers are lazy and the specs pander to the manufacturers, not the programmers. That's why.
Answer: The obvious thing to do with OpenGL would be to display the bitmap as a texture.
Comment: Yes - I just wondered if there were some video specific performance tricks, rather than just copying each frame to a full screen quad
Comment: @Martin: Not usually -- as long as you're keeping all the memory shuffling on the card itself, almost any reasonable video card can pretty easily provide the bandwidth to rewrite every bit on the screen at the maximum refresh rate (especially now, since LCDs almost never refresh faster than 60 Hz --it was harder with high end CRTs that did 100+ Hz refresh).
Comment: Thats the problem - I need to do 1080p at 120Hz (and ideally two of them!)
Comment: @Martin: I wouldn't be a lot on its being a problem anyway. I managed to keep up with ~100 Hz refresh using a GeForce 5800 driven by a Pentium III. The resolution was *somewhat* lower, but not drastically, and a modern card is *well* over twice as fast.
Answer: So you want to send your video on a texture and process it with fragment shader? Here's one short tutorial how to do something similar. It's just a simple OpenGL 2.0 example that creates 2 window size textures and mixes them in fragment shader. There's no video involved but shouldn't be hard to modify if you already have means to decode it.

Video display with openGL


Defining Many-to-Many Association in Entity Framework

Question: I have the following tables in my edmx :
Errors
Id, Description, solved, officeId, siteId

Sites
id, location, name , officeId

Offices
officeId, officeName

the mapping between offices to sites are 1-to-many(offices can have many instances of sites).
i want to create many-to-many association from Errors to Sites
so i can access Sites properties directly.
I always keeps error in mapping.
can someone guide me how to do it right?
thanks in advance
Answer: You don't need to ad foreign key properties like officeId in Erros table in the edmx. Instead of adding those add associations among entities(Right click on your entity and choose addnew-> associatoin ). When you are adding associations you can define the relationship (one to many,may to many ...).
Comment: but this is wrong , the relation between Errors and Sites are many-to-many, and i always keep getting mapping error
Comment: if  Errors and Sites are many-to-many then no point of keeping site id in the error table. If you have created a many-to-many relationship on Errors and Sites entity framework will add another table in your database to keep siteId and ErrorId for the realationship. And make sure after the mapping you have regenarate your db. If not you wll get a mapping error.
Comment: when i create the many-to-many association i always keep get error in mapping the association. that is my problem. since Errors can have many instances of Sites and Sites can have many Errors.
Comment: did you try after removing SiteId in errors table and adding navigation properties?


How to convert Rules 'text' data type to 'text_formatted' type?

Question: I am working with Rules to set a node's body. Based on the data selector, the node body requires a text_formatted type as input.
Currently, my custom event only provides a plain 'text' Rules data type. Is there a way I can programmatically convert the plain text to text_formatted? And when and where should it happen?
Answer: I tried fixing this myself but I'm not sure if this is the best.
I took a peek at entity/includes/entity.property.inc and found the definition of entity_property_text_formatted_info() enough for me to define it properly.
I simply wrapped the plain 'text' with an array definition of a
<code>    $text_formatted = array('value' => $text_plain,
                            'summary' => $text_plain,
                            'format' => 'full_html');</code>
And fed $text_formatted to the event invoke call.


Problem with differentiable function: is it concave up when the derivative is increasing?

Question:
This makes sense to me, and I feel like it would be an easy argument IF I could use the second derivative.
I'm only given that f is differentiable, NOT twice differentiable. Any help?
Comment: Are you sure you don't mean $f$ is below all secant lines?
Comment: What is your definition of concavity? This is really important information if you are constructing a proof.
Comment: If $f$ is concave up on $(a,b)$, then f is above all secant lines between any two points in $(a,b).
Comment: @Spencer actually yes, you're right.
Comment: @Spencer I thought that because of a proof I previously did. guess I did it wrong (this one)

http://i.gyazo.com/f857c71af148851ed009743761a5d860.png
Answer: Hint: Well, you're given that $f^\prime$ is increasing, implying that...
Comment: Sanath - can I make that argument? I was only given taht f is differentiable, not twice diffble.
Comment: Is that really true? Surely you can have a nondifferentiable function that can be monotone increasing or decreasing.
Comment: implying that.. what?
Comment: @terribleatmath In the sense of basic calculus, $f$ has a positive second derivative, and thus, that $f$ is concave up.
Comment: @terribleatmath Well, if $f$ is not second-differentiable, then no comment could have been made in the first place about whether $f^\prime$ is increasing or not.
Comment: @terribleatmath A function is concave up on an interval if it is continuous and its first derivative is continuous
and increasing on the interval. Use the fact that $f$ is differentiable, i.e., $C^\infty$ continuous.
Comment: Huh, I didn't know that it being differentiable in this implication meant it was of class $C^\infty$. good to know.

that's an easy direction then. what about the other direction?
Comment: @terribleatmath If concave up, then the slope of slope is positive, i.e., $f^\prime$ is increasing.
Comment: what do you mean by "slope of slope" ?
Comment: @terribleatmath The tangent to the graph of $f^\prime$ has positive slope.
Comment: makes sense. is this due to the fact that the tangent lines of $f$ are all above $f$?
Comment: @terribleatmath If all tangent lines are above $f$, then $f$ would be concave down, as you can see from a graph.
Comment: hm, well all secant lines are above f, i thought it meant the tangent was too - can you explain why the tangents are below if the secants are above?
Comment: This isn't really true. The assumptions given do not imply the function is infinitely continuously differentiable. There are functions which are strictly increasing which are not differentiable everywhere. Strictly increasing only implies that $f(x+a) > f(x)$ for all $a > 0$.
Comment: As an example consider the piecewise defined function $f(x) =  x^2/2-1/6 $ on $0\leq x \leq 1$ and $f(x)=x^3/3$ on $1 < x \leq 2$ which has a continuous increasing derivative everywhere on $[0,2]$ but whose second derivative is undefined at $x=1$.


Variable value as part of array key

Question: $pname = "postback_".$data;
$_SESSION["$pname"] = $data;

It is not working. How to use it?
Comment: Single quoted strings are literal and do not have variable substitution (you don't even need quotes in your case).
Comment: @Prix: I don't see single quoted strings here ;) (but of course you are right).
Comment: @Felix i am just saying that when using single quotes it does not matter if u have a variable on it as it will not be parsed hence you should just use the session variable name for example $_SESSION['time'] would be time other then this using quotes are not a good pratice in my point of view. My bad making it complicated.
Comment: @monkey_boys - Please click the tick mark sign, beside the correct answer, if you have already found one.
Answer: <?php
session_start();

$pname = "postback_".$data;
$_SESSION[$pname] = $data;

?>

Answer: Make sure that you have put session_start(); on top of your script.

Variable value as part of array key


Outputting different class other than default for status messages

Question: I'm trying to theme status messages, I want to change the HTML of the message.
Drupal default is

message!

What I want to achieve is

message!

I have used theme_status_messages to modify 'messages' but how can I modify the type (e.g. 'status'/'warning', etc)?
This is current code
function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

I've changed this line
$output .= "
\n";

to
$output .= "
\n";

as you can see in my code above, but how can I change the options for $type?? I want my types to be alert-success, alert-error, alert-warning, rather than status, error, warning.
Anyone got an idea?
thanks!
Comment: @caustic Why not just switch your CSS classes to correspond with the default Drupal ones?
Comment: I have no clue what you're asking for.
Comment: Can't just do: `$output .= "\n";` ?
Comment: @slawrence10 I'm using Bootstrap and requirements are that theres no additional classes for Bootstrap-served elements. Bootstrap has it alert alert-success format
Comment: @Beebee I caaaaan, but that still doesn't work. Because $type isn't correct. alert-$type will give me alert-status rather than alert-success. Any ideas?
Comment: @Beebee what I'm asking for is a way to change the default 3 message type classes - status, error, and warning. I want to change them to alert-succes, alert-info, alert-danger, for example.
Comment: That's so easy, you're just changing output. Check my answer.
Comment: I had to edit your original question in order to retract my downvote. Hopefully it made the question easier to understand too.
Answer: This is just some good old PHP logic, is this what you're after?
function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );

  // Map our drupal statuses to bootstrap classes
  $bootstrap_statuses = array(
    'status' => 'alert-success',
    'error' => 'alert-error',
    'warning' => 'alert-warning',
  );

  foreach (drupal_get_messages($display) as $type => $messages) {
    // Grab the bootstrap class that corresponds to $type
    $bootstrap_class = $bootstrap_statuses[$type];
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

You could even put the $bootstrap_classes and $status_heading arrays together. But I separated them for simplicity
Comment: Thank you very much , didn't realise it was so simple, thought that maybe there was another hook for that :) Works anyway!
Comment: You're welcome. Sometimes it's worth to take a step back and think "Can I solve this with good ol' PHP?" :) I've been there so many times.


Maxscript function doesn't update in while loop

Question: I have this function in maxscript that checks if verts are in the camera frame. What I want to do is put the function in a while loop and move the camera back, and every time the camera moves it should check if the object is in camera or not. But when I do that, the function in the while loop doesn't update, it always returns the values from the first check.
<code>fn getVertsInViewport theObject =
(
local theVerts = #() --return array
local theMesh = snapshotasmesh theObject --grab the mesh from top of the stack
local theCount = theMesh.numverts --get the number of vertices
local theTM  = viewport.getTM() --get the current view's transformation
local screen_width = renderWidth --get the current render height
local screen_height = renderHeight --get the current render width
for v = 1 to theCount do --loop through all vertices
(
    local thePos = (getVert theMesh v) * theTM --transform vertex in view space
    --get the world location of the upper left corner of the camera view at the depth of the vertex
    local screen_origin = mapScreenToView [0,0] (thePos.z) [screen_width,screen_height]
    --get the bottom right corner at the vertex depth
    local end_screen = mapScreenToView [screen_width,screen_height] (thePos.z) [screen_width,screen_height]
    --calculate the world size based on the two corners
    local world_size = screen_origin-end_screen
    --calculate the X and Y aspect factors
    local x_aspect = screen_width/(abs world_size.x)
    local y_aspect = screen_height/(abs world_size.y)
    --calculate the screen coordinates using all the above data:
    local screen_coords = point2 (x_aspect*(thePos.x-screen_origin.x)) (-(y_aspect*(thePos.y-screen_origin.y)))
    --if the vertex is outside of the screen (negative or higher than the render size), collect it
    if screen_coords.x <= 0 or screen_coords.y <= 0 or screen_coords.x > screen_width or screen_coords.y > screen_height  then
        append theVerts v
)--end v loop
delete theMesh --release the memory used by the TriMesh
theVerts  --return the collected vertices
)--end fn verts in viewport

maksimum = 3
counter = 1
 while counter < maksimum do
 (
    move $Camera001 [0,-550,0]
    cameraOK = getVertsInViewport $
    print (counter as string +"  "+ "camera_pos = "+ $Camera001.pos.y as   string +" : " +(cameraOK as string))
    counter += 1
 )
</code>
Answer: Add a call to forceCompleteRedraw() after moving the camera.
I assume you have the active viewport set to the camera view, since you're viewport.getTM() to obtain the camera transformation. The redraw seems to allow the viewport to refresh, respecting the new camera position, and give the intended result.
Note that MaxScript blocks the main thread of 3ds Max while running. That means UI events and other kinds of refresh activity are not processed, which is probably causing the conflict here.


How to generate a list of which Features are enabled in which Spaces?

Question: I'm running a Drupal 6.x site with Organic Groups, Features, and Spaces, and I'm interested in generating a list of which Spaces have which Features enabled. Preferably a table, with Spaces along the Y axis, and Features along the X axis.
Any ideas regarding how to generate this? I can generate a list of Group Spaces using Views, but can't find a field for the enabled Features.
Answer: Features are modules, and Views 3.x can make listings of enabled modules. But as explained in How to make a Feature available only to certain Spaces?, this is not possible, since modules are enabled site-wide.
Answer: I don't think there's a field to be able to do this with a view. Mainly because the data is stored in a serialized object.
But the query you want to use would be something like this.
<code>db_query("SELECT * FROM {spaces_overrides} WHERE object_type = 'variable' and object_id = 'spaces_features'");
</code>
Once you get those results the features for that specific space is going to be in the value column. Is going to be a serialized array so you will have to unserialized it.
The value is going to be a key => value array of feature_name => status.
Sadly you're going to have to build the page and the table yourself. But this should be enough to get the data that you want.
Also you're going to have do a lookup for the for the ID to get the proper group name.
Sorry the solutions is not as simple but this should work.


The value of the integral $\int_0^2\left(\sqrt{1+x^3}+\sqrt[3]{x^2+2x}\:\right)dx$

Question: The value of definite integral $$\int\limits_{0}^{2}\left(\sqrt{1+x^3}+\sqrt[3]{x^2+2x}\:\right)dx$$ is $$(A)\,4 \quad(B)\,5 \quad (C)\,6  \quad(D)\,7$$
My attempt:
I tried using $\int\limits_{0}^{a}f(x)dx=\int\limits_{0}^{a}f(a-x)dx$ but not working. I tried putting $x^3+1=\tan^2\theta$, its also not working.
Can someone help me solve this problem?
Comment: I just realized that the trapezoidal rule with just two points, $f(0)=1$ and $f(2)=5$, gives the value $\frac 12\cdot (2-0)(1+5)=6$: You can't get much easier than that! That is possibly what you were meant to do.
Comment: You could use the trapezoidal rule with three points. You can easily find $f(0)=1$ and $f(2)=5$, and can approximate $f(1)\approx 2.9$. The trapezoidal rule then gives the integral approximation $$\frac 12\cdot 1+2.9+\frac 12\cdot 5=5.9$$ Simpson's rule, just a little harder, gives about $5.87$. Either of these gives the answer (C).
Comment: You do not give any restriction on the method of solution. Why not just do numerical integration using WolframAlpha, software, or a good calculator? The answer seems to be (C) $6$, by the way. I used my TI-Nspire CX. [WolframAlpha](http://www.wolframalpha.com/input/?i=integrate+%28%281%2Bx%5E3%29%5E%281%2F2%29%2B%28x%5E2%2B2x%29%5E%281%2F3%29%29) gives a horrendous indefinite integral. You could even use Simpson's rule on a few points to get a good-enough answer for multiple choice.
Comment: @RoryDaulton,Sir if calculators are not allowed,can we solve it otherwise.
Answer: Hint. The function $ x \mapsto f(x):=\sqrt{1+x^3}$ is strictly increasing on $[0,2]$, then you may use the following property:

$$
\int_a^bf(x)dx+\int_{f(a)}^{f(b)}f^{-1}(x)dx=b{f(b)}-a{f(a)} \tag1
$$

(here $ x \mapsto f^{-1}(x+1)=\sqrt[3]{(x+1)^2-1}=\sqrt[3]{x^2+2x},\quad f^{-1}(0+1)=0,\,f^{-1}(2+1)=2$) obtaining

$$I=2\sqrt{1+2^3}-0\sqrt{1+0^3}=\color{red}{6}$$

as suggested.
Comment: amazing solution liked it
Answer: Let $f(x)=\sqrt{1+x^3}$. $\\$
Easily show that $f^{-1}(x+1)=\sqrt[3]{x^2+2x}$.
You are asked to find $$\int_0^2 f(x)dx +\int_0^2 f^{-1}(x+1)dx \\ =\int_0^2f(x)dx+\int_1^3 f^{-1}(x)dx \\ =\int_0^2f(x)dx+\int_{f(0)}^{f(2)}f^{-1}(x)dx$$.
Draw a picture.
Comment: You should be able to draw a picture and see for yourself. You may also consult [wikipedia](https://en.wikipedia.org/wiki/Integral_of_inverse_functions). If still nothing, see Olivier's answer.
Comment: ,Sir how will we calculate $\int\limits_{0}^{2}f(x)dx+\int\limits_{f(0)}^{f(2)}f^{-1}(x)dx$
Comment: @nospoon ) Can you please tell me how $\int_0^2f^{-1}(x+1)\,dx=\int_1^3f^{-1}(x)\,dx$ ?
Comment: @S.Panja-1729 substitute $t=x+1$. Also here a picture could help. We're just shifting the whole function to the right by a unit.
Answer: I have one more way to do this:
Let $$I_1=\int_{0}^{2} \sqrt{x^3+1} \:dx$$ By Integration by parts we get
$$I_1=x\sqrt{x^3+1} \bigg|_{0}^{2}-\int_{0}^{2}\frac{3x^3 dx}{2\sqrt{x^3+1}} \tag{1}$$
Now let $$I_2=\int_{0}^{2} (x^2+2x)^{\frac{1}{3}}dx$$ Use substitution $x^2+2x=t^3$ we get
$(2x+2)dx=3t^2dt$ that is
$dx=\frac{3t^2dt}{2(x+1)}$
But $(x+1)^2-1=t^3$ $\implies$
$x+1=\sqrt{t^3+1}$
Also the limits will be again $0$ and $2$
Thus
$$I_2=\int_{0}^{2}\frac{3t^3dt}{2(x+1)}=\int_{0}^{2}\frac{3t^3dt}{2\sqrt{t^3+1}}$$  since $t$ is Dummy variable
$$I_2=\int_{0}^{2}\frac{3x^3dx}{2\sqrt{x^3+1}} \tag{2}$$
Adding $(1)$ and $(2)$ we get
$$I_1+I_2=x\sqrt{x^3+1} \bigg|_{0}^{2}=6$$


How to project high dimensional space into a two-dimensional plane?

Question: I have a set of data points in a N-dimensional space. In addition, I also have a centroid in this same N-dimensional space. Are there any approaches that can allow me to project these data points into a two-dimensional space while keeping their relative distance information in the original space. Is PCA the correct one?
Comment: If you want to try to preserve distances, my first thought would have been multidimensional scaling on the distances themselves (which is related to PCA), but since you have the locations and not just the distances, by my understanding, PCA should work for that.
Comment: @Glen_b, The key point is not that MDS is for distances input and PCA is for coordinates input, but [that](http://stats.stackexchange.com/a/14017/3277) iterative MDS fits few dimensions while PCA retains few dimensions. So MDS preserves distances somewhat better than classic PCA does. The answer for the question is Yes, PCA is suitable, but MDS is more suitable.
Comment: This largely what is studied in the field of *metric space embedding*, i.e. how can you reduce the dimensionality of your data while minimizing distortion of distances.
Answer: A general framework which addresses your problem is called dimensionality reduction. You would like to project data from N dimensions to 2 dimensions, while preserving the "essential information" in your data. The most suitable method depends on the distribution of your data, i.e. the N-dimensional manifold. PCA will fit a plane using least squares criterion. This will probably work poorly for the "swiss roll" example: swiss roll.
More modern methods include Kernel PCA, LLE, diffusion maps and sparse dictionary representations. Regarding distance preservation, some methods can preserve non-euclidean distances.
Comment: It is important to note that "dimensionality reduction" methods typically do *not* maintain "relative distance information." Whether they do or not depends partly on the method and partly on the intended "distance."
Answer: As mentioned in the previous answer, there are a number of methods of dimensionality reduction, and an important thing to consider is what are you trying to represent - are you interested in Euclidean distance measures? Or a metric of similarity across samples?
For the former, PCA can be appropriate. It is commonly used with continuous measures such as measurements of samples (animals, plants, etc...). I would look into the more modern mentions in the earlier answer too though.
For the latter, where you might be trying to compare similarity using a non-euclidean distance metric, a few good methods exist such as Principle Components Ordination (PCoA) and Non-metric Multidimensional Scaling (NMDS). An example of when you might use these is when you are comparing the ecological communities among different areas, and you have numbers of different types of organisms that were found. So, your data are "count" data. There are a number of similarity metrics such as Jaccard, Sorensen, Bray-Curtis, that effectively let you estimate how similar the sites are in their composition of organisms. PCoA and NMDS basically let you to plot the samples (sites) to represent the ecological distance (similarity), and you have a score for site on each axis.
There are lots of good books and other resources for multivariate analysis. Search for "Ordination" on Google. Also, there's an R package called 'vegan' that is really good for actually carrying out a lot of this work.
Answer: Your problem sounds like a text-book application for multidimensional scaling. A good introduction can be found here: http://www.mathpsyc.uni-bonn.de/doc/delbeke/delbeke.htm
Of course you can try PCA. But PCA has no intention to keep the relative distance information in the original space.


Extracting nonorthogonal sources in ICA/PCA/blind source seperation problem

Question: My problem is essentially a 'blind source separation' problem. I have 3 non-orthogonal sources (or basis functions) and N random linear combinations (mixes) of said sources. My problem is to obtain the sources from the mixes.
Figure A shows the sources, B shows the mixes.
Approaches taken:
1) PCA- I tried PCA on the mixes (fig.C), but the issue is that PCA will only give orthogonal bases, while my sources/bases are non-orthogonal. This issue with PCA is shown in figure D, where the data is clearly described by 2 non-orthogonal basis, but PCA (the solid lines) cant reconstruct them!
2) Factor Rotation - I tried applying some solutions form Factor Analysis (not my forte). The promax rotation (matlab: nw = rotatefactors(cov,'method','promax') ) is shown in fig. D with the dashed lines. As far as I can tell, factor rotation works with the principal components, not the original matrix and thus I have no idea how it could reconstruct the right basis. I think this only works with factor matrices, not with generic ones...
3) ICA - I tried overdetermined ICA with the fastICA algorithm (also not my forte, but I think I understand it better). I was hoping this would work since independent components (ICs) are non orthogonal. The solution is shown in fig.E. While the ICs are indeed nonorthogonal, they are NOT my original sources :-(
Any other potential tips or leads or solutions would be greatly appreciated.

Thanks!
Answer: Is E truly showing the ICA activity, rather than the reconstructed signal (activity * component weights)? I think your ICA is actually fairly good, it's just that fastICA returned filters giving some of your component activations the "wrong" polarity. IC activities are sign ambiguous, as the sign of the reconstructed sources depends on both the sign of the activations and their corresponding maps. (I hope this is clear, or do I need to give an example?)
Plot the reconstructed signal (activity * component weights) and see if it checks out. If I'm right, in the reconstructed signal, the blue line will look like the blue line in the original sources, and the plot should look quite like the original sources in general.
Answer: Have you tried Varimax rotation? https://en.wikipedia.org/wiki/Varimax_rotation
It will show the makeup of each of the factors.