Proving $f$ is Lebesgue integrable iff $|f|$ is Lebesgue integrable.

Question: How can we prove the statement?
$f$ is Lebesgue integrable if and only if $|f|$ is Lebesgue integrable.
First, suppose $f$ is Lebesgue integrable, by definition, $f$ is measurable and nonnegative, so $f=|f|$ and $\displaystyle \int_E f \, d \mu=\int_E|f| \, d\mu$ implies that $|f|$ is Lebesgue integrable.
Second, suppose $|f|$ is Lebesgue integrable, if $f$ is nonnegative, then $f=|f|$, so $f$ is Lebesgue integrable; if $f$ is negative, then how can I prove?
Comment: Where did you get the idea that $f$ has to be nonnegative to integrable? A measurable function is Lebesgue integrable iff the positive and negative parts are Lebesgue integrable.
Comment: if f is measurable and nonnegative, define int_E f du =sup I_E(s). right? what does positive and negative parts mean?
Answer: That $f$ is measurable and $\int |f| \,d\mu < \infty$ is the definition of Lebesgue-integrability of $f$.  (There's no need for $f$ to be non-negative.  Rather, one first defines the value of the integral for non-negative functions and then one uses that to define the Lebesgue integral of functions whose ranges may include both negative and non-negative numbers.)
That $|f|$ is Lebesgue-integrable would therefore involve the absolute value of the absolute value of $f$.  But that's the same as the absolute value of $f$.
The statement "$f$ is Lebesgue integrable if and only if $|f|$ is Lebesgue integrable." is not true unless there is an assumption that $f$ is measurable.  A counterexample is that $f$ is $-1/2$ plus the indicator function of a non-measurable set in a space whose total measure is $1/2$.  Then $|f|$ is integrable (and its integral is $1$) but $f$ is not measurable.
Comment: If |f| is Legesgue integrable, so |f| is measurable, can it imply that f is measurable?
Comment: That $|f|$ is measurable and $f$ is not can happen, but only if $f$ is a fairly exotic function.  For example suppose for every value of $x$, $f(x)$ is either $1$ or $-1$, and the set of values of $x$ for which $f(x)=1$ is not a measurable set.  Then $|f|$ would be measurable (since it's equal to $1$ everywhere) although $f$ is not. ${}\qquad{}$
Comment: so how can you prove that if |f| is Legesgue integrable, then f is measurable? since f is measurable is an assumption of f is Legesgue integrable.
Comment: @Mathgoal: In general, you can't, as Michael's example in the comments shows. However, for *measurable* functions $f$, we *can* conclude that $f$ is Lebesgue integrable if and only if $\lvert f\rvert$ is Lebesgue integrable.
Comment: You probably want twice the indicator function minus one.  The indicator function *is* non-negative.
Comment: I assume  the integral equals $1/4$ and not $1$. Since $|f|$ in the answer equals $1/2$, it can be written as a product of $1/2$ and the indicator function of the set of measure $1/2$. The integral of this simple function equals $1/2\cdot 1/2=1/4$.
Answer: Simply remember the definition of $\mathcal{L}^1$ space (in the case of $\Bbb R^n$ with the borelian $\sigma$-algebra; the abstract case is similar): given $(\Bbb R^n,\mathcal{B}(\Bbb R^n),m)$, where $m$ is the Lebesgue measure on the measurable space $(\Bbb R^n,\mathcal{B}(\Bbb R^n))$, then
$$
\mathcal{L}^1(\Bbb R^n,\mathcal{B}(\Bbb R^n),m):=\{f:\Bbb R^n\to\Bbb R\;:\;f\;\;\mbox{is Lebesgue measurable and both}\;\int_{\Bbb R^n}f^+\,dm,\;\int_{\Bbb R^n}f^-\,dm\;\mbox{are finite}\}\;\;.
$$
Now simply observe that $f=f^+-f^-$ and $|f|=f^++f^-$.


Templates when using vectors instead of doubles as input

Question: I am trying to achieve a very simple thing using C++ templates. I would like to build a generic sign function that could handle the case sgn(x)where x could be either doubleor std::vector<double> (that is returning a std::vector<double> containing the results). In order to achieve that I am using templates
double f(double x) {
    return (x>=0)?1.0:-1.0;
};

template<typename T>
T F(T x) {
   // ?
};

I would like to cast the template and either use f if double or a for loop if std::vector<double>. Unfortunately my function does not use any arithmetic operator and the conditional operator cannot be overloaded. How should I proceed ?
Comment: Why use templates here? You should overload the function.
Answer: This is solved by overloading, not templates.
double sign(double x) {
    return x < 0.0 ? -1.0 :
           x > 0.0 ?  1.0 : 0.0;
};

std::vector<double> sign(std::vector<double> const& x) {
    // ?
};

That said, I'd doubt whether a sign function is meaningful for vectors.
This, by the way, has got nothing to do with "arithmetic" versus "non-arithmetic" functions, as alleged in the title of the question. This distinction doesn't exist in C++.
Comment: Thanks for noticing my error in the sign function. As pointed out I do not need any templates here, overloading will do fine. Just got confused here.
Answer: While overloading is the best way to achieve what you want, it is not
really the way to work with the C++ standard library.
If you want to apply a function to all elements of a container (either
mutating them or creating new results), use std::transform or
std::for_each with the function you want to use.
std::vector<double> doubles, results;
std::transform(begin(doubles), end(doubles), std::back_inserter(results), sgn);

That separates concern far better than your current approach. Only
operate on whole containers if it is really required, in all other
cases use iterators and higher-order functions.
Comment: Thanks, I won't have to reinvent the wheel here. Applying a function to a vector is what I needed, templates are useless for that purpose.
Comment: @vanna Well, `transform` et al **are** templates. They are perfect for that purpose.


How to tell Stringsoverrides module to replace text only in specific module?

Question: How to tell Stringsoverrides module to replace text only in specific module? Are there any alternatives to this module?
Answer: String Override works for the strings defined inside t(), t() takes context as one of the parameters, for example
1. t('May', array(), array('context' => 'Long month name')
2. t('May', array(), array('context' => 'Abbreviated month name')

Both the strings are 'May', if you replace it would be changed across, but t() function also takes context, so if you provide the right context, only that instance of sting will be replaced. String overrides also takes the context while replacing the string, you have to make sure the string you want to replace in a moudle passes through t() and with what context.
Other way could be if its a variable then do a variable_set()
What I prefer is to patch the module, keep the patch in patches folder. To me string replacement is not mission critical peace, after next update release we re-do our patch.


How do I prove completeness / incompleteness on a set of functions?

Question: I'm asked to show that
$$((C[0,1], \mathbb{R}), ||f||_1), \quad ||f||_1 = \int_0^1{|f(x)|dx}$$
is not a Banach space.
$||f||_1$ is a norm on this space so therefore I need to show that the space is not complete.
How do I prove completeness / incompleteness on a space of functions? How do I even construct a cauchy sequence of functions? What does it mean for a sequence of functions to converge? Is completeness defined in another way?
Comment: Do you know the general defintion of a Cauchy Sequence in a metric space ? If yes, just apply it with $d(x,y) = \|x-y\|_1$.
Answer: You can, for instance, define$$\begin{array}{rccc}f_n\colon&[0,1]&\longrightarrow&\mathbb R\\&x&\mapsto&\begin{cases}0&\text{ if }x<\frac12-\frac1{2n}\\2n\left(x-\frac12\right)&\text{ if }x\in\left[\frac12-\frac1{2n},\frac12+\frac1{2n}\right]\\1&\text{ if }x>\frac12+\frac1{2n}.\end{cases}\end{array}$$It's graph is like this:

Now:

Prove that this is a Cauchy sequence.
Prove that it doesn't converge in your space.
Answer: Given a norm $||\cdot||$, you can define a metric $d$ on the space as $d(x,y) := ||x-y||$.
Here, the norm is given by $||f||_{1} = \int_0^1 |f(x)| dx$. Thus, the metric is $d(f,g) = \int_0^1 |f(x)-g(x)| dx$.
A sequence of functions $\{f_n\}$ is said to be cauchy, if for every $\epsilon>0$, there exists $N \in \mathbb{N}$ such that $d(f_n,f_m) = \int_0^1 |f_n(x) - f_m(x)| < \epsilon$ for all $n,m \geq N$.
A sequence of functions $\{f_n\}$ is said to converge to $f$, if for every
$\epsilon>0$, there exists $N \in \mathbb{N}$ such that $d(f_n,f) = \int_0^1 |f_n(x) - f(x)| < \epsilon$ for all $n \geq N$.
$(C[0,1], \mathbb{R}), || \cdot||_1)$ is not Banach by the example in the answer above.


print line + next two lines with awk if next line matches

Question: I have a list like this to catch joomla version
./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla4/www/libraries/cms/version/version.php
./somedir/bla5/www/w/scripts/version.php
./somedir/bla6/www/libraries/cms/version/version.php
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

What I want is that only the line + the two next lines are displayed if public is in the next line. Else line must be ignored
So the result should be:
./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

I have tried to use Awk and this awk script
BEGIN{ RS=""; FS="\n" }
 /public/ {
    for (i=1; i<=NF; i++) {
        if ( ! (($i ~ /./) && ($(i+1) !~ /public/) && ($(i+2) !~ /public/) ) ) {
            print $i
        }
    }
    print ""
}

But this results in:
./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';

I am missing the second public line with the dev_level
Answer: You're making this harder than it has to be by thinking about it in terms of printing what's coming next (hard to do since you haven't seen it yet!) rather than printing what came before (easy to do - just save it and print it):
$ awk '/public/{print p $0; p=""; next} {p=$0 ORS}' file
./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

Any time you find yourself trying to figure out what to do with the current line based on what comes after it, take the time to rethink it in terms of doing something when you're processing the future line (so IT is then the "current" line) based on what came before it. In software and in life - seeing the future is much harder than remembering the past!
Comment: This. Twice. (thrice due to you-know-what)
Comment: Thrice the char filler.
Answer: Try it with grep
grep 'public $DEV' -B 2 yourfile.txt
from man grep
 -B NUM, --before-context=NUM
     Print NUM lines of leading context before matching lines.
     Places a line containing a group separator (--) between contiguous groups of matches.

Comment: Very useful comment. This made me show leading context before my pattern. Thanks


Does $\sum_{n=1}^{\infty}\left(-1\right)^{n+1}\frac{3\sqrt{n+1}}{\sqrt{n}+1}$ Diverge or Converge?

Question: Does the following summation converge or diverge?
\begin{align}
\sum_{n=1}^{\infty}\left(-1\right)^{n+1}\frac{3\sqrt{n+1}}{\sqrt{n}+1}.\tag{1}
\end{align}
I don't know where to begin. I think I should, however, use the absolute value test s. th. if
\begin{align}
\sum_{n=1}^{\infty}\left|\left(-1\right)^{n+1}\frac{3\sqrt{n+1}}{\sqrt{n}+1}\right|=\sum_{n=1}^\infty \frac{3\sqrt{n+1}}{\sqrt{n}+1}=3\sum_{n=1}^{\infty}\frac{\sqrt{n+1}}{\sqrt{n}+1}\tag{2}
\end{align}
converges then $\left(1\right)$ converges. If I pick arbitrarily large values of $n$ then it seems $\left(2\right)$ does not get smaller and eventually $\rightarrow 0$.
Thank you for your time,
Comment: THe $n$-th term doesn't go to $0$.
Comment: Unless you intended that to be a cubic root.
Comment: @bd1251252 What do you think...?
Answer: Use term test. Since $$
\lim_{n\to\infty}\frac{3\sqrt{n+1}}{\sqrt{n}+1}=\lim_{n\to\infty}\frac{3\sqrt{n+1}}{\sqrt{n}+1}=\lim_{n\to\infty}\frac{3\sqrt{1+\frac{1}{n}}}{1+\frac{1}{\sqrt{n}}}=3,$$
then
$$
\lim_{n\to\infty}(-1)^{n+1}\frac{3\sqrt{n+1}}{\sqrt{n}+1}=3$$
does not exist because it jumps between $3$ and $-3$. So the series does not converge.
Comment: Don't worry, just waiting for the time limit to run out so I could accept it.
Answer: $$\lim_{n\to\infty}{\sqrt{n+1}\over\sqrt n +1}=\lim_{n\to\infty}{\sqrt{1+1/n}\over1+1/\sqrt n}=1.$$
Hence
$$\lim_{n\to\infty}(-1)^{n+1}{3\sqrt{n+1}\over\sqrt n + 1}$$
does not exist, and the series diverges.


Detect if Object uses default toString() function or custom overwritten toString() function

Question: I have a function, which should check if an Object has a toString() function and output it or otherwise return the object. The problem is, it also triggers on plane objects  and finally returns [Object object] as a string which obivously looks awfull on the GUI. Is there a way to determine if an Object uses the default toString() method that returns the ugly [Object object] or has an custom toString() function that returns a pretty string.
Here is my current function:
(data: any) => (data != null && typeof data.toString === 'function') ? data.toString() : data;

Comment: you can check `Object.hasOwnProperty('toString')`
Answer: 1) You can compare with Object.prototype.toString. If it is not overridden the references are equal

const obj1 = {};
console.log(obj1.toString === Object.prototype.toString);

const obj3 = { toString() { } };
console.log(obj3.toString === Object.prototype.toString);

2) You can check the existence via hasOwnProperty

const obj1 = {};
console.log(obj1.hasOwnProperty('toString'));

const obj3 = { toString() { } };
console.log(obj3.hasOwnProperty('toString'));
Comment: On my node.js project only [ err.toString != Object.prototype.toString ] works. Trying [ err.hasOwnProperty("toString") ] reports false. The error object is an error object returned by the "pg" library from NPM. Which is a PostGreSql library.
Comment: Is the second solution robust against minification and obfuscation?
Comment: They are same. String literals will not be minified
Comment: @KANJICODER I observed the same, which is how I ended up here, except that I was just doing something even simpler: `Object.prototype.hasOwnProperty.call("foo", "toString") => false`.
Answer: We have two options:

myObj.hasOwnProperty('toString')
myObj.toString !== Object.prototype.toString

I think it is better to use second option, because method using hasOwnProperty isn't so robust. Check out this code snipped:
class MyObj {
  toString() {
    return "myObj";
  }
}

class MyObjEx extends MyObj {
  something() {}
}

var a = new MyObj();
var b = new MyObjEx();
var c = new Object();
c.toString = () => "created by new Object()";
var d = { test: "test", toString: () => "created with object literal" };
var unchanged = { test: "test" };

console.log(
  "hasOwnProperty with 'native' toString method",
  unchanged.hasOwnProperty("toString")
);
console.log("hasOwnProperty object from class", a.hasOwnProperty("toString"));
console.log(
  "hasOwnProperty object from extended class",
  b.hasOwnProperty("toString")
);
console.log(
  "hasOwnProperty object from new Object()",
  c.hasOwnProperty("toString")
);
console.log(
  "hasOwnProperty object from object literal",
  d.hasOwnProperty("toString")
);

console.log(
  "compare with Object.prototype on unchanged object",
  unchanged.toString !== Object.prototype.toString
);
console.log(
  "compare with Object.prototype object from class",
  a.toString !== Object.prototype.toString
);
console.log(
  "compare with Object.prototype object from extended class",
  b.toString !== Object.prototype.toString
);
console.log(
  "compare with Object.prototype object from new Object()",
  c.toString !== Object.prototype.toString
);
console.log(
  "compare with Object.prototype object from object literal",
  d.toString !== Object.prototype.toString
);

Output will be:
"hasOwnProperty with 'native' toString method"    false
"hasOwnProperty object from class"    false
"hasOwnProperty object from extended class"    false
"hasOwnProperty object from new Object()"    true
"hasOwnProperty object from object literal"    true

"compare with Object.prototype on unchanged object"    false
"compare with Object.prototype object from class"    true
"compare with Object.prototype object from extended class"    true
"compare with Object.prototype object from new Object()"    true
"compare with Object.prototype object from object literal"    true

Answer: o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // returns true
o.hasOwnProperty('toString');         // returns false
o.hasOwnProperty('hasOwnProperty');   // returns false

prototype properties will return false if you check with hasOwnProperty
Answer: None of the answers worked for me. The only one that worked was:
if (obj1.toString) {
  console.log(obj1.toString())
}


Don't manage to set up iptables rules for client/server socket exchange on localhost

Question: I am a client/server-IPC-iptables near-newbbie. I have made my homeworks deeply during one year and thought this should work :
# cat /root/firewall/iptable | nocomment
iptables -F
iptables -F -t nat
iptables -P FORWARD DROP
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 1 -s 127.0.0.0/24 -p tcp --dport 80:65535 -j ACCEPT
iptables -I INPUT 1 -s 127.0.0.0/24 -p udp --dport 80:65535 -j ACCEPT
iptables -A INPUT -s 192.168.0.0/24 -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -s 127.0.0.0/24 -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -s 192.168.0.0/24 -p udp -m udp --dport 631 -j ACCEPT
iptables -A INPUT -s 192.168.0.0/24 -p tcp -m tcp --dport 631 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 -j REJECT --reject-with tcp-reset
iptables -A INPUT -p udp -i eth0 -j REJECT --reject-with icmp-port-unreachable
iptables -L -v -n
/etc/init.d/iptables save

# /root/firewall/iptable
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     udp  --  *      *       127.0.0.0/24         0.0.0.0/0            udp dpts:80:65535
    0     0 ACCEPT     tcp  --  *      *       127.0.0.0/24         0.0.0.0/0            tcp dpts:80:65535
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
    0     0 ACCEPT     icmp --  *      *       192.168.0.0/24       0.0.0.0/0            icmptype 0
    0     0 ACCEPT     icmp --  *      *       127.0.0.0/24         0.0.0.0/0            icmptype 0
    0     0 ACCEPT     udp  --  *      *       192.168.0.0/24       0.0.0.0/0            udp dpt:631
    0     0 ACCEPT     tcp  --  *      *       192.168.0.0/24       0.0.0.0/0            tcp dpt:631
    0     0 REJECT     tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            reject-with tcp-reset
    0     0 REJECT     udp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 * Saving iptables state ...

# ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.10  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 xxxx::xxxx:xxxx:xxxx:xxxx  prefixlen 64  scopeid 0x20<link>
        inet6 xxxx::xxxx:xxxx:xxxx:xxxx::xxxx:xxxx:xxxx  prefixlen 64  scopeid 0x0<global>
        inet6 xxxx::xxxx:xxxx:xxxx::10  prefixlen 64  scopeid 0x0<global>
        ether xx:xx:xx:xx:xx:xx  txqueuelen 1000  (Ethernet)
        RX packets 204122  bytes 114225536 (108.9 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 230083  bytes 27756306 (26.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 17

# ifconfig lo
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 16436
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Boucle locale)
        RX packets 443796  bytes 25809111 (24.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 443796  bytes 25809111 (24.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ping 127.0.0.1 does not work.
A client/server socket exchange on port 9000 does not work (from a web example).
Browsing the Web works

What am I doing wrong please ?
EDIT 2013-08-12 08:28 CET

The client/server socket exchange test (point 2 above) is on localhost
I have built another example with another port (55555). This time it works. I have tried many ports and they work. Then I did a :

# netstat -a | grep 9000
getnameinfo failed
tcp6 0 0 [::]:9000 [::]:* LISTEN

So something has already binded to port 9000, which I assume is the cause of my problem. Have you an idea how I could identify the process ? ps aux | grep 9000 outputs nothing.

After suppression of the 127.0.0.0/24 rules, my working example with port 5555 stops working. I still have : tcp6 0 0 [::]:9000 [::]:* LISTEN – When I put back the 127.0.0.0/24 rules, it works again with port 5555.
Answer: First thing: you should be really cautious about using "iptables -F" when logged in via SSH for example, especially if the default rule (policy, iptables -P) on the input chain was DROP as you set it here. You will lock yourself out.
Now to the topic:
1) I wouldn't define the 127.0.0.0/8 (yeah! /8 not /24) anywhere in firewall rules. Take those out. Those addresses are local, why would you want to lock out sth local. You're looking for trouble.
2) "Socket exchange(?) on port 9000". From where? From the 192.168.0.0/24 network? What host exactly?
It can't work because you only have
0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
0     0 ACCEPT     udp  --  *      *       192.168.0.0/24       0.0.0.0/0            udp dpt:631
0     0 ACCEPT     tcp  --  *      *       192.168.0.0/24       0.0.0.0/0            tcp dpt:631

in there, meaning it will accept new connections on port 631 only.

You've found out that you're using IPv6 too. (Listener on port 9000 is tcp6)
Meaning: ipv4 firewall rules are not the problem (they're not concerned at all, in fact): you have to make whatever listens on tcp6:9000 also listen on tcp:9000. AND THEN configure the ipv4 firewall rules to allow access on port 9000. But if you're connecting from localhost that will work out of the box.
Note:

IPv4 = tcp/udp/... (netstat) = iptables (packet filter)
IPv6 = tcp6/udp6/... (netstat) = ip6tables (packet filter)
Comment: Thanks for your answer Marki. From localhost. I have built another example with another port (55555). This time it works. I have tried many ports and they work. Then I did a : # netstat -a | grep 9000, result is : getnameinfo failed, tcp6       0      0 [::]:9000               [::]:*                  LISTEN. So something has already binded to port 9000, which I assume is the cause of my problem. Have you an idea how I could identify the process ? ps aux | grep 9000 outputs nothing.
Comment: So what happens when you remove the rules with 127.0.0.0/24 as a source, as I suggested?
Comment: After suppression of the 127.0.0.0/24 rules, my working example with port 5555 stops working. I still have : tcp6       0      0 [::]:9000               [::]:*                  LISTEN
Comment: When I put back the 127.0.0.0/24 rules, it works again with port 5555
Comment: Well port 9000 seems to be a IPv6 socket. Doesn't strike me that an IPv4 connection to the port doesn't work. What does `ip6tables -vnL` say? What does netstat say about the service on port 5555?
Comment: # ip6tables -vnL
Chain INPUT (policy DROP 8 packets, 630 bytes)
 pkts bytes target     prot opt in     out     source               destination
4544K 4519M ACCEPT     all      *      *       ::/0                 ::/0                 ctstate RELATED,ESTABLISHED
    0     0 ACCEPT     all      lo     *       fe80::/120           ::/0
 263K   19M ACCEPT     icmpv6    *      *       ::/0                 ::/0
Comment: 0     0 ACCEPT     udp      *      *       fe80::/120           ::/0                 udp dpt:631
    0     0 ACCEPT     tcp      *      *       fe80::/120           ::/0                 tcp dpt:631
39185 2636K REJECT     tcp      eth0   *       ::/0                 ::/0                 reject-with tcp-reset
   16  1757 REJECT     udp      eth0   *       ::/0                 ::/0                 reject-with icmp6-port-unreachable
Comment: Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all      *      *       xxxx::xxxx:xxxx:xxxx::/64 !xxxx::xxxx:xxxx:xxxx::/64
    0     0 ACCEPT     all      *      *       ::/0                 ::/0                 ctstate RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT 132K packets, 15M bytes)
 pkts bytes target     prot opt in     out     source               destination
Comment: Please expand your initial question with what you've found out. In here it's unreadable.
Comment: I also suggest to mark the answer as accepted if it helped.
Answer: I read here post #3 that :

Linux doesn't let a process listen on the same port on both IPv4 and
  IPv6 (IPv4 connections will be passed to the app as IPv4-in-6 mapped
  connections).

But we cannot conclude from that that when a socket is opened with ipv6, it is not possible to open the same port with ipv4. Actually, my test application can bind to the same port on ipv4, and its client can connect too.
My conclusion is that the client may receive an answer from the process binded on ipv6 before the answer of its companion server binded on ipv4. That explains why the test program fails when it tries to use the same port.
Moreother, I could find the good options for netstat to identify the port thief :
# netstat -tlp | grep 9000
tcp6       0      0 [::]:9000               [::]:*                  LISTEN      15382/java

# ps aux | grep 15382
root      5459  0.0  0.0 110788   960 pts/21   S+   08:56   0:00 grep --colour=auto 15382
laurent    15382  1.7  2.8 5479456 465744 ?      Sl   août09  74:30 /usr/lib/jvm//sun-jdk-1.6/bin/java -Dosgi.requiredJavaVersion=1.6 -XX:MaxPermSize=256m -Xms40m -Xmx384m -jar /usr/opt/eclipse-CDT/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar -os linux -ws gtk -arch x86_64 -showsplash -launcher /usr/opt/eclipse-CDT/eclipse/eclipse -name Eclipse --launcher.library /usr/opt/eclipse-CDT/eclipse//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.100.v20110505/eclipse_1407.so -startup /usr/opt/eclipse-CDT/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar --launcher.overrideVmargs -exitdata f28017 -product org.eclipse.epp.package.linuxtools.product -nl en_US -vm /usr/bin/java -vmargs -Dosgi.requiredJavaVersion=1.6 -XX:MaxPermSize=256m -Xms40m -Xmx384m -jar /usr/opt/eclipse-CDT/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar

After having closed Eclipse, # netstat -tlp | grep 9000 returns nothing.
..... and my test application works on port 9000.


Easiest way to position iterator after the next line in a stream?

Question: I feel like there should be a method or stl function for this, but I can't find anything. I'm writing a simple parser, if you're interested in my specific problem:
while (curChar << postFileStream)
    {
        switch (curChar)
        {
            case '\n' || '\r':
                break;
            case '#':
                skip_line(postFileStream)
        }
    }

Do I really have to make my own function to skip a line? I know it's a rather simple function, but I feel like c++ shouldn't require so much boilerplate these days; I must be missing something?
Answer: postFileStream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

or
std::string s;
std::getline(postFileStream, s);

References:

http://www.cplusplus.com/reference/string/getline/
http://www.cplusplus.com/reference/iostream/istream/ignore/
http://www.cplusplus.com/reference/iostream/streamsize/
http://www.cplusplus.com/reference/std/limits/numeric_limits/


GLKit: [drawing pixels] initializing GLfloat array

Question: I am drawing a pixel using GLKit. I can successfully draw the pixel at (10, 10) coordinates if I have:
glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Prepare the effect for rendering
[self.effect prepareToDraw];

GLfloat points[] =
{
    10.0f, 10.0f,
};

glClearColor(1.0f, 1.0f, 0.0f, 1.0f);

GLuint bufferObjectNameArray;
glGenBuffers(1, &bufferObjectNameArray);
glBindBuffer(GL_ARRAY_BUFFER, bufferObjectNameArray);

glBufferData(
             GL_ARRAY_BUFFER,
             sizeof(points),
             points,
             GL_STATIC_DRAW);

glEnableVertexAttribArray(GLKVertexAttribPosition);

glVertexAttribPointer(
                      GLKVertexAttribPosition,
                      2,
                      GL_FLOAT,
                      GL_FALSE,
                      2*4,
                      NULL);
glDrawArrays(GL_POINTS, 0, 1);

But I want to decide at runtime how many and exactly where I want to draw pixels, so I tried this but it is drawing pixel at (10, 0), something's wrong here:
glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Prepare the effect for rendering
[self.effect prepareToDraw];

GLfloat *points = (GLfloat*)malloc(sizeof(GLfloat) * 2);
for (int i=0; i<2; i++) {
    points[i] = 10.0f;
}

glClearColor(1.0f, 1.0f, 0.0f, 1.0f);

GLuint bufferObjectNameArray;
glGenBuffers(1, &bufferObjectNameArray);
glBindBuffer(GL_ARRAY_BUFFER, bufferObjectNameArray);

glBufferData(
             GL_ARRAY_BUFFER,
             sizeof(points),
             points,
             GL_STATIC_DRAW);

glEnableVertexAttribArray(GLKVertexAttribPosition);

glVertexAttribPointer(
                      GLKVertexAttribPosition,
                      2,
                      GL_FLOAT,
                      GL_FALSE,
                      2*4,
                      NULL);
glDrawArrays(GL_POINTS, 0, 1);

Kindly help me out.
Edit:
Problem
Actually the problem is: I can't figure out what is the difference between:
GLfloat points[] =
{
    10.0f, 10.0f,
};

AND
GLfloat *points = (GLfloat*)malloc(sizeof(GLfloat) * 2);
for (int i=0; i<2; i++) {
    points[i] = 10.0f;
}

Answer: My bet will be that the problem is the sizeof(points) in the glBufferData data call: in this case it will return the size of the pointer which is a word i.e. 4 bytes (or something like this). You should pass the real size of your array that will be the same what you calculate in the malloc code.


Facebook C# SDK for Facebook Connect

Question: How can I use Facebook C# SDK for facebook connect using ASP.NET?
What I am trying to do is:

Provide a "Login with Facebook" button.
Once the user clicks on Login button, get the access token on server side and sign in  to my website.

Most articles (I found through google or SO) said use Facebook Javascript SDK for Log in and Authentication and then get the Access token from cookies created on web browser.
What I did so far:
Used Facebook login button in .aspx page with the below code.
<fb:login-button onlogin="window.location.reload();" perms="offline_access">Login with Facebook</fb:login-button>

Problems I am having:

When I click log in button on MY PAGE a window will pop up to log in to facebook. MY PAGE is supposed to reload when I login to facebook but it reloads even I click on Cancel button or close the pop up window. What I need is reloading MY PAGE only when I log in.

From the above step: If I log in and MY PAGE reloads perfectly. In code behind (Page load event) I can see the cookie created and it has the information (access token) what I needed. And from here I want to use Facebook C# SDK to get user information. how to do ?

I used Facebook C# SDK 3 months ago for developing a canvas application in Facebook. The documentation and examples listed on Codeplex are for Apps on Facebook (correct me if I missed to see facebook connect examples). Also, there was a link to documentation which lists all the Facebook C# SDK classes but I could not see that now. Please provide me the link if you know.
Any help will be greatly appreciated.
Thank you.
Comment: What do you want to do with it?
It's a fairly ambigous question.
Comment: [would *you* answer this question?](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx)
Answer: http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-First-Facebook-Application-v6.aspx
But there is one issue I am not using
parameters.response_type = "token";

Instead of that i have function to update Token
public static void UpdateToken()
        {
            var fb = new FacebookClient();

            dynamic result = fb.Get("oauth/access_token", new
            {
                client_id = AppId,
                client_secret = AppSecret,
                redirect_uri = Url,
                code = FacebookUtils.FacebookData.Code
            });
            FacebookData.AccessToken = result.access_token;
        }

Facebook C# SDK for Facebook Connect


How to calculate the frequency of CPU cores

Question: I am trying to use RDTSC but it seems like my approach may be wrong to get the core speed:
<code>#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>

using namespace std;

struct Core
{
    int CoreNumber;
};

static void startMonitoringCoreSpeeds(void *param)
{
    Core core = *((Core *)param);
    SetThreadAffinityMask(GetCurrentThread(), 1 << core.CoreNumber);
    while (true)
    {
        DWORD64 first = __rdtsc();
        Sleep(1000);
        DWORD64 second = __rdtsc();
        cout << "Core " << core.CoreNumber << " has frequency " << ((second - first)*pow(10, -6)) << " MHz" << endl;
    }
}

int GetNumberOfProcessorCores()
{
    DWORD process, system;
    if (GetProcessAffinityMask(GetCurrentProcess(), &process, &system))
    {
        int count = 0;
        for (int i = 0; i < 32; i++)
        {
            if (system & (1 << i))
            {
                count++;
            }
        }
        return count;
    }
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
}

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < GetNumberOfProcessorCores(); i++)
    {
        Core *core = new Core {0};
        core->CoreNumber = i;
        _beginthread(startMonitoringCoreSpeeds, 0, core);
    }
    cin.get();
}
</code>
It always prints out values around 3.3 GHz, which is wrong because things like Turbo Boost are on from time to time and my cores jump to 4.3 GHz for sure. Let me cross-reference some articles behind this idea.
Firstly (http://users.utcluj.ro/~ancapop/labscs/SCS2.pdf): "The TSCs on the processor's cores are not synchronized. So it is not sure that if a process migrates during
execution from one core to another, the measurement will not be affected. To avoid this problem, the measured process's affinity has to be set to just one core, to prevent process migration." This tells me that RDTSC should return a different value per core my thread is on using the affinity mask I set, which is great.
Secondly, and please check this article (http://randomascii.wordpress.com/2011/07/29/rdtsc-in-the-age-of-sandybridge/): "If you need a consistent timer that works across cores and can be used to measure time then this is good news. If you want to measure actual CPU clock cycles then you are out of luck. If you want consistency across a wide range of CPU families then it sucks to be you. Update: section 16.11 of the Intel System Programming Guide documents this behavior of the Time-Stamp Counter. Roughly speaking it says that on older processors the clock rate changes, but on newer processors it remains uniform. It finishes by saying, of Constant TSC, "This is the architectural behavior moving forward." Okay, this tells me that RDTSC stays consistent, which makes my above results make sense since my CPU cores are rated at a standard 3.3 GHz...
Which REALLY begs the question, how do applications like Intel's Turbo Boost Technology Monitor and Piriform's Speccy and CPUID's CPU-Z measure a processor's clock speed while undergoing turbo boost, realtime?
Comment: They directly access the BIOS to read the bus speeds/settings and do their own arithmetic. This requires having a database of all the different systems. Which is why CPUz needs to be updated every time a new processor comes out.
Comment: @Mysticial: Not the BIOS so much as the model-specific registers in the CPU.
Comment: Suggestion : If you are not bound to use RDTSC, give try a try using Win32_Processor class of WMI for your approach
Comment: @Alexandru: As a side note, in your `startMonitoringCoreSpeeds` function and after you `Sleep`, you should check the *actual* passed time (using an alternate method, e.g. `timeGetTime`, etc.) to have more accurate measurements. `Sleep` is not guaranteed to actually sleep for the given time. (I do realize that my point is moot, but you will run into the problem I'm talking about if you solve the RDTSC issue.)
Comment: @BenVoigt Damn... Ring 0. That sucks... :(
Comment: @Alexandru: I'm sure they do call into a kernel-mode driver to get those values.  The fact that you don't recognize anything in the `driverquery` output is not very convincing.  I'd suggest that you profile the program for `CreateFile` calls (drivers are exposed to user-mode as pseudo-files).  Try Process Explorer to see what pseudo-files are open, and Process Monitor or API Monitor to capture calls to `CreateFile`.
Comment: Or you could just read the source code of OpenHardwareMonitor: https://code.google.com/p/open-hardware-monitor/source/browse/trunk/Hardware/CPU/IntelCPU.cs  Look, I see a function in there named `Ring0.Rdmsr()` which is used for everything.  [Here's the implementation of that class](https://code.google.com/p/open-hardware-monitor/source/browse/trunk/Hardware/Ring0.cs), which drops a driver on the system.  You could use it from your application too, via `IOCTL_OLS_READ_MSR`, if you abide by [the license](http://openhardwaremonitor.org/license/#WinRing0)
Comment: possible duplicate of [Finding out the CPU clock frequency (per core, per processor)](http://stackoverflow.com/questions/8351944/finding-out-the-cpu-clock-frequency-per-core-per-processor)
Comment: @DNamto I tried that but that's also always constant.
Comment: @Mysticial Do you know of any examples to do this?
Comment: @Alexandru: Yes, search this site.  That exact "rdtsc in the age of Sandy Bridge" [has been cited before](http://stackoverflow.com/a/17774286/103167).
Comment: @BenVoigt Ah. Then you know more than me. :)
Comment: @BenVoigt "read frequency from model-specific registers" didn't turn up anything as a search query :)
Comment: @Alexandru: Most of [these](https://www.google.com/search?q=site%3Astackoverflow.com+cpu+frequency+msr) look relevant.
Comment: Something like this? http://stackoverflow.com/questions/65095/assembly-cpu-frequency-measuring-algorithm
Comment: @yzt: See my "has been cited before" link above, which does that correctly.
Comment: @BenVoigt Just ran ProcSpeedCalc() from that answer; it always returns 3300 MHz for me. :(
Comment: @Alexandru: Yes, it measures the `RDTSC` frequency, and does that correctly.  On new processors that won't be the same as the dynamic frequency.
Comment: @BenVoigt But I am looking to get the current, dynamic frequency
Comment: @Alexandru: Did you read the answers on the question I marked this as a duplicate of?
Comment: @BenVoigt You're really tempting me to try out these special registers. :) But I can't do that in VS since it doesn't allow inline assembly on x64. :(
Comment: @BenVoigt Yes, that's the first Stack Overflow article I consulted with for the past while, while trying to implement an algorithm to do this.
Comment: @Mysticial: You don't need assembly, there's [an intrinsic](http://msdn.microsoft.com/en-us/library/y55zyfdx(v=vs.90).aspx)  But the whole instruction only works from privileged code (drivers).
Comment: So the practical answer to this question is that you need to find a driver that reads MSRs and returns them to your program, and recommendation questions are off-topic.  Problems encountered while writing such a driver would be on-topic, but you'd need a lot of background in driver development.  OTOH, you can figure out what driver is used by CPU-Z or the TurboBoost monitor.
Comment: Also relevant: https://software.intel.com/en-us/forums/topic/278056
Comment: @BenVoigt No, this can't be the only way to do it...can I play devil's advocate for a second? I just queried my system for drivers: driverquery > "%userprofile%\drivers.txt", nothing shows up with Speccy or Piriform and yet this application still seems to get it right when it detects CPU core speeds.
Comment: My justification is that if this was the only way to measure the real frequency, I would expect some of these applications to actually piggyback off of a kernel mode driver that reads the MSR values...
Comment: @BenVoigt Ah, thanks man! I was able to get what I wanted. Actually, that led me to reading the copyright: Copyright (C) 2010-2012 Michael Möller . Then I went to openhardwaremonitor.org, and checked out and built the SVN branch of it at http://openhardwaremonitor.org/downloads/ using TortoiseSVN: http://open-hardware-monitor.googlecode.com/svn/trunk/
Comment: Alright so from this sample code I can see that they install either WinRing0x64.sys or WinRing0.sys on runtime (included inside the project) which are kernel level drivers; they use them to call Ring0.Rdmsr() like you said to calculate the actual frequency.
Comment: If you install WDK you can use this article to create an IO device and run communications between your kernel mode driver and the app: http://ericasselin.com/userlandkernel-communication-deviceiocontrol-method
Comment: @BenVoigt Full solution below.
Comment: @Mysticial Full solution below.
Answer: Full solution follows. I've adapted the IOCTL sample driver on MSDN to do this. Note, the IOCTL sample is the only relative WDM sample skeleton driver I could find and also the closest thing I could find to a WDM template because most kernel mode templates out of the box in WDK are WDF-based drivers (any WDM driver template is actually blank with absolutely no source code), yet the only sample logic I've seen to do this input/output was through a WDM-based driver. Also, some fun facts I've learned along the way: kernel drivers don't like floating arithmetic and you can't use "windows.h" which really limits you to "ntddk.h", a special kernel-mode header. This also means I can't do all of my computations inside of kernel mode because I can't call functions like QueryPerformanceFrequency in there, so I had to get the mean performance ratio between timestamps and return them back to user mode for some computations (without QueryPerformanceFrequency, the values you get from CPU registers that store ticks like what QueryPerformanceCounter uses are useless because you don't know the step size; maybe there's a workaround to this but I opted to just use the mean since it works pretty damn well). Also, as per the one second sleep, the reason I used that is because otherwise you're almost spin-computing shit on multiple threads, which really messes up your calculations because your frequencies will go up per core constantly checking results from QueryPerformanceCounter (you drive your cores up as you do more computations) - NOT TO MENTION - its a ratio...so the delta time is not that important since its cycles per time...you can always increase the delta, it should still give you the same ratio relative to the step size. Furthermore, this is as minimalistic as I could get it to be. Good luck making it much smaller or shorter than this. Also, if you want to install the driver, you have two options unless you want to buy a Code Signing certificate from some third party, both suck, so pick one and suck it up. Let's start with the driver:
driver.c:
<code>//
// Include files.
//

#include <ntddk.h>          // various NT definitions
#include <string.h>
#include <intrin.h>

#include "driver.h"

#define NT_DEVICE_NAME      L"\\Device\\KernelModeDriver"
#define DOS_DEVICE_NAME     L"\\DosDevices\\KernelModeDriver"

#if DBG
#define DRIVER_PRINT(_x_) \
                DbgPrint("KernelModeDriver.sys: ");\
                DbgPrint _x_;

#else
#define DRIVER_PRINT(_x_)
#endif

//
// Device driver routine declarations.
//

DRIVER_INITIALIZE DriverEntry;

_Dispatch_type_(IRP_MJ_CREATE)
_Dispatch_type_(IRP_MJ_CLOSE)
DRIVER_DISPATCH DriverCreateClose;

_Dispatch_type_(IRP_MJ_DEVICE_CONTROL)
DRIVER_DISPATCH DriverDeviceControl;

DRIVER_UNLOAD DriverUnloadDriver;

VOID
PrintIrpInfo(
    PIRP Irp
    );
VOID
PrintChars(
    _In_reads_(CountChars) PCHAR BufferAddress,
    _In_ size_t CountChars
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text( INIT, DriverEntry )
#pragma alloc_text( PAGE, DriverCreateClose)
#pragma alloc_text( PAGE, DriverDeviceControl)
#pragma alloc_text( PAGE, DriverUnloadDriver)
#pragma alloc_text( PAGE, PrintIrpInfo)
#pragma alloc_text( PAGE, PrintChars)
#endif // ALLOC_PRAGMA

NTSTATUS
DriverEntry(
    _In_ PDRIVER_OBJECT   DriverObject,
    _In_ PUNICODE_STRING      RegistryPath
    )
/*++

Routine Description:
    This routine is called by the Operating System to initialize the driver.

    It creates the device object, fills in the dispatch entry points and
    completes the initialization.

Arguments:
    DriverObject - a pointer to the object that represents this device
    driver.

    RegistryPath - a pointer to our Services key in the registry.

Return Value:
    STATUS_SUCCESS if initialized; an error otherwise.

--*/

{
    NTSTATUS        ntStatus;
    UNICODE_STRING  ntUnicodeString;    // NT Device Name "\Device\KernelModeDriver"
    UNICODE_STRING  ntWin32NameString;    // Win32 Name "\DosDevices\KernelModeDriver"
    PDEVICE_OBJECT  deviceObject = NULL;    // ptr to device object

    UNREFERENCED_PARAMETER(RegistryPath);

    RtlInitUnicodeString( &ntUnicodeString, NT_DEVICE_NAME );

    ntStatus = IoCreateDevice(
        DriverObject,                   // Our Driver Object
        0,                              // We don't use a device extension
        &ntUnicodeString,               // Device name "\Device\KernelModeDriver"
        FILE_DEVICE_UNKNOWN,            // Device type
        FILE_DEVICE_SECURE_OPEN,        // Device characteristics
        FALSE,                          // Not an exclusive device
        &deviceObject );                // Returned ptr to Device Object

    if ( !NT_SUCCESS( ntStatus ) )
    {
        DRIVER_PRINT(("Couldn't create the device object\n"));
        return ntStatus;
    }

    //
    // Initialize the driver object with this driver's entry points.
    //

    DriverObject->MajorFunction[IRP_MJ_CREATE] = DriverCreateClose;
    DriverObject->MajorFunction[IRP_MJ_CLOSE] = DriverCreateClose;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DriverDeviceControl;
    DriverObject->DriverUnload = DriverUnloadDriver;

    //
    // Initialize a Unicode String containing the Win32 name
    // for our device.
    //

    RtlInitUnicodeString( &ntWin32NameString, DOS_DEVICE_NAME );

    //
    // Create a symbolic link between our device name  and the Win32 name
    //

    ntStatus = IoCreateSymbolicLink(
                        &ntWin32NameString, &ntUnicodeString );

    if ( !NT_SUCCESS( ntStatus ) )
    {
        //
        // Delete everything that this routine has allocated.
        //
        DRIVER_PRINT(("Couldn't create symbolic link\n"));
        IoDeleteDevice( deviceObject );
    }

    return ntStatus;
}

NTSTATUS
DriverCreateClose(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp
    )
/*++

Routine Description:

    This routine is called by the I/O system when the KernelModeDriver is opened or
    closed.

    No action is performed other than completing the request successfully.

Arguments:

    DeviceObject - a pointer to the object that represents the device
    that I/O is to be done on.

    Irp - a pointer to the I/O Request Packet for this request.

Return Value:

    NT status code

--*/

{
    UNREFERENCED_PARAMETER(DeviceObject);

    PAGED_CODE();

    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;

    IoCompleteRequest( Irp, IO_NO_INCREMENT );

    return STATUS_SUCCESS;
}

VOID
DriverUnloadDriver(
    _In_ PDRIVER_OBJECT DriverObject
    )
/*++

Routine Description:

    This routine is called by the I/O system to unload the driver.

    Any resources previously allocated must be freed.

Arguments:

    DriverObject - a pointer to the object that represents our driver.

Return Value:

    None
--*/

{
    PDEVICE_OBJECT deviceObject = DriverObject->DeviceObject;
    UNICODE_STRING uniWin32NameString;

    PAGED_CODE();

    //
    // Create counted string version of our Win32 device name.
    //

    RtlInitUnicodeString( &uniWin32NameString, DOS_DEVICE_NAME );

    //
    // Delete the link from our device name to a name in the Win32 namespace.
    //

    IoDeleteSymbolicLink( &uniWin32NameString );

    if ( deviceObject != NULL )
    {
        IoDeleteDevice( deviceObject );
    }

}

NTSTATUS
DriverDeviceControl(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp
    )

/*++

Routine Description:

    This routine is called by the I/O system to perform a device I/O
    control function.

Arguments:

    DeviceObject - a pointer to the object that represents the device
        that I/O is to be done on.

    Irp - a pointer to the I/O Request Packet for this request.

Return Value:

    NT status code

--*/

{
    PIO_STACK_LOCATION  irpSp;// Pointer to current stack location
    NTSTATUS            ntStatus = STATUS_SUCCESS;// Assume success
    ULONG               inBufLength; // Input buffer length
    ULONG               outBufLength; // Output buffer length
    void                *inBuf; // pointer to input buffer
    unsigned __int64    *outBuf; // pointer to the output buffer

    UNREFERENCED_PARAMETER(DeviceObject);

    PAGED_CODE();

    irpSp = IoGetCurrentIrpStackLocation( Irp );
    inBufLength = irpSp->Parameters.DeviceIoControl.InputBufferLength;
    outBufLength = irpSp->Parameters.DeviceIoControl.OutputBufferLength;

    if (!inBufLength || !outBufLength || outBufLength != sizeof(unsigned __int64)*2)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        goto End;
    }

    //
    // Determine which I/O control code was specified.
    //

    switch ( irpSp->Parameters.DeviceIoControl.IoControlCode )
    {
    case IOCTL_SIOCTL_METHOD_BUFFERED:

        //
        // In this method the I/O manager allocates a buffer large enough to
        // to accommodate larger of the user input buffer and output buffer,
        // assigns the address to Irp->AssociatedIrp.SystemBuffer, and
        // copies the content of the user input buffer into this SystemBuffer
        //

        DRIVER_PRINT(("Called IOCTL_SIOCTL_METHOD_BUFFERED\n"));
        PrintIrpInfo(Irp);

        //
        // Input buffer and output buffer is same in this case, read the
        // content of the buffer before writing to it
        //

        inBuf = (void *)Irp->AssociatedIrp.SystemBuffer;
        outBuf = (unsigned __int64 *)Irp->AssociatedIrp.SystemBuffer;

        //
        // Read the data from the buffer
        //

        DRIVER_PRINT(("\tData from User :"));
        //
        // We are using the following function to print characters instead
        // DebugPrint with %s format because we string we get may or
        // may not be null terminated.
        //
        PrintChars(inBuf, inBufLength);

        //
        // Write to the buffer
        //

        unsigned __int64 data[sizeof(unsigned __int64) * 2];
        data[0] = __readmsr(232);
        data[1] = __readmsr(231);

        DRIVER_PRINT(("data[0]: %d", data[0]));
        DRIVER_PRINT(("data[1]: %d", data[1]));

        RtlCopyBytes(outBuf, data, outBufLength);

        //
        // Assign the length of the data copied to IoStatus.Information
        // of the Irp and complete the Irp.
        //

        Irp->IoStatus.Information = sizeof(unsigned __int64)*2;

        //
        // When the Irp is completed the content of the SystemBuffer
        // is copied to the User output buffer and the SystemBuffer is
        // is freed.
        //

       break;

    default:

        //
        // The specified I/O control code is unrecognized by this driver.
        //

        ntStatus = STATUS_INVALID_DEVICE_REQUEST;
        DRIVER_PRINT(("ERROR: unrecognized IOCTL %x\n",
            irpSp->Parameters.DeviceIoControl.IoControlCode));
        break;
    }

End:
    //
    // Finish the I/O operation by simply completing the packet and returning
    // the same status as in the packet itself.
    //

    Irp->IoStatus.Status = ntStatus;

    IoCompleteRequest( Irp, IO_NO_INCREMENT );

    return ntStatus;
}

VOID
PrintIrpInfo(
    PIRP Irp)
{
    PIO_STACK_LOCATION  irpSp;
    irpSp = IoGetCurrentIrpStackLocation( Irp );

    PAGED_CODE();

    DRIVER_PRINT(("\tIrp->AssociatedIrp.SystemBuffer = 0x%p\n",
        Irp->AssociatedIrp.SystemBuffer));
    DRIVER_PRINT(("\tIrp->UserBuffer = 0x%p\n", Irp->UserBuffer));
    DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.Type3InputBuffer = 0x%p\n",
        irpSp->Parameters.DeviceIoControl.Type3InputBuffer));
    DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.InputBufferLength = %d\n",
        irpSp->Parameters.DeviceIoControl.InputBufferLength));
    DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.OutputBufferLength = %d\n",
        irpSp->Parameters.DeviceIoControl.OutputBufferLength ));
    return;
}

VOID
PrintChars(
    _In_reads_(CountChars) PCHAR BufferAddress,
    _In_ size_t CountChars
    )
{
    PAGED_CODE();

    if (CountChars) {

        while (CountChars--) {

            if (*BufferAddress > 31
                 && *BufferAddress != 127) {

                KdPrint (( "%c", *BufferAddress) );

            } else {

                KdPrint(( ".") );

            }
            BufferAddress++;
        }
        KdPrint (("\n"));
    }
    return;
}
</code>
driver.h:
<code>//
// Device type           -- in the "User Defined" range."
//
#define SIOCTL_TYPE 40000
//
// The IOCTL function codes from 0x800 to 0xFFF are for customer use.
//
#define IOCTL_SIOCTL_METHOD_IN_DIRECT \
    CTL_CODE( SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS  )

#define IOCTL_SIOCTL_METHOD_OUT_DIRECT \
    CTL_CODE( SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT , FILE_ANY_ACCESS  )

#define IOCTL_SIOCTL_METHOD_BUFFERED \
    CTL_CODE( SIOCTL_TYPE, 0x902, METHOD_BUFFERED, FILE_ANY_ACCESS  )

#define IOCTL_SIOCTL_METHOD_NEITHER \
    CTL_CODE( SIOCTL_TYPE, 0x903, METHOD_NEITHER , FILE_ANY_ACCESS  )

#define DRIVER_FUNC_INSTALL     0x01
#define DRIVER_FUNC_REMOVE      0x02

#define DRIVER_NAME       "ReadMSRDriver"
</code>
Now, here is the application that loads up and uses the driver (Win32 Console Application):
FrequencyCalculator.cpp:
<code>#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strsafe.h>
#include <process.h>
#include "..\KernelModeDriver\driver.h"

using namespace std;

BOOLEAN
ManageDriver(
_In_ LPCTSTR  DriverName,
_In_ LPCTSTR  ServiceName,
_In_ USHORT   Function
);

HANDLE hDevice;
TCHAR driverLocation[MAX_PATH];

void InstallDriver()
{
    DWORD errNum = 0;
    GetCurrentDirectory(MAX_PATH, driverLocation);
    _tcscat_s(driverLocation, _T("\\KernelModeDriver.sys"));

    std::wcout << "Trying to install driver at " << driverLocation << std::endl;

    //
    // open the device
    //

    if ((hDevice = CreateFile(_T("\\\\.\\KernelModeDriver"),
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL)) == INVALID_HANDLE_VALUE) {

        errNum = GetLastError();

        if (errNum != ERROR_FILE_NOT_FOUND) {

            printf("CreateFile failed!  ERROR_FILE_NOT_FOUND = %d\n", errNum);

            return;
        }

        //
        // The driver is not started yet so let us the install the driver.
        // First setup full path to driver name.
        //

        if (!ManageDriver(_T(DRIVER_NAME),
            driverLocation,
            DRIVER_FUNC_INSTALL
            )) {

            printf("Unable to install driver. \n");

            //
            // Error - remove driver.
            //

            ManageDriver(_T(DRIVER_NAME),
                driverLocation,
                DRIVER_FUNC_REMOVE
                );

            return;
        }

        hDevice = CreateFile(_T("\\\\.\\KernelModeDriver"),
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        if (hDevice == INVALID_HANDLE_VALUE){
            printf("Error: CreatFile Failed : %d\n", GetLastError());
            return;
        }
    }
}

void UninstallDriver()
{
    //
    // close the handle to the device.
    //

    CloseHandle(hDevice);

    //
    // Unload the driver.  Ignore any errors.
    //
    ManageDriver(_T(DRIVER_NAME),
        driverLocation,
        DRIVER_FUNC_REMOVE
        );
}

double GetPerformanceRatio()
{
    BOOL bRc;
    ULONG bytesReturned;

    int input = 0;
    unsigned __int64 output[2];
    memset(output, 0, sizeof(unsigned __int64) * 2);

    //printf("InputBuffer Pointer = %p, BufLength = %d\n", &input, sizeof(&input));
    //printf("OutputBuffer Pointer = %p BufLength = %d\n", &output, sizeof(&output));

    //
    // Performing METHOD_BUFFERED
    //

    //printf("\nCalling DeviceIoControl METHOD_BUFFERED:\n");

    bRc = DeviceIoControl(hDevice,
        (DWORD)IOCTL_SIOCTL_METHOD_BUFFERED,
        &input,
        sizeof(&input),
        output,
        sizeof(unsigned __int64)*2,
        &bytesReturned,
        NULL
        );

    if (!bRc)
    {
        //printf("Error in DeviceIoControl : %d", GetLastError());
        return 0;

    }
    //printf("    OutBuffer (%d): %d\n", bytesReturned, output);
    if (output[1] == 0)
    {
        return 0;
    }
    else
    {
        return (float)output[0] / (float)output[1];
    }
}

struct Core
{
    int CoreNumber;
};

int GetNumberOfProcessorCores()
{
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
}

float GetCoreFrequency()
{
    // __rdtsc: Returns the processor time stamp which records the number of clock cycles since the last reset.
    // QueryPerformanceCounter: Returns a high resolution time stamp that can be used for time-interval measurements.
    // Get the frequency which defines the step size of the QueryPerformanceCounter method.
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    // Get the number of cycles before we start.
    ULONG cyclesBefore = __rdtsc();
    // Get the Intel performance ratio at the start.
    float ratioBefore = GetPerformanceRatio();
    // Get the start time.
    LARGE_INTEGER startTime;
    QueryPerformanceCounter(&startTime);
    // Give the CPU cores enough time to repopulate their __rdtsc and QueryPerformanceCounter registers.
    Sleep(1000);
    ULONG cyclesAfter = __rdtsc();
    // Get the Intel performance ratio at the end.
    float ratioAfter = GetPerformanceRatio();
    // Get the end time.
    LARGE_INTEGER endTime;
    QueryPerformanceCounter(&endTime);
    // Return the number of MHz. Multiply the core's frequency by the mean MSR (model-specific register) ratio (the APERF register's value divided by the MPERF register's value) between the two timestamps.
    return ((ratioAfter + ratioBefore) / 2)*(cyclesAfter - cyclesBefore)*pow(10, -6) / ((endTime.QuadPart - startTime.QuadPart) / frequency.QuadPart);
}

struct CoreResults
{
    int CoreNumber;
    float CoreFrequency;
};

CRITICAL_SECTION printLock;

static void printResult(void *param)
{
    EnterCriticalSection(&printLock);
    CoreResults coreResults = *((CoreResults *)param);
    std::cout << "Core " << coreResults.CoreNumber << " has a speed of " << coreResults.CoreFrequency << " MHz" << std::endl;
    delete param;
    LeaveCriticalSection(&printLock);
}

bool closed = false;

static void startMonitoringCoreSpeeds(void *param)
{
    Core core = *((Core *)param);
    SetThreadAffinityMask(GetCurrentThread(), 1 << core.CoreNumber);
    while (!closed)
    {
        CoreResults *coreResults = new CoreResults();
        coreResults->CoreNumber = core.CoreNumber;
        coreResults->CoreFrequency = GetCoreFrequency();
        _beginthread(printResult, 0, coreResults);
        Sleep(1000);
    }
    delete param;
}

int _tmain(int argc, _TCHAR* argv[])
{
    InitializeCriticalSection(&printLock);
    InstallDriver();
    for (int i = 0; i < GetNumberOfProcessorCores(); i++)
    {
        Core *core = new Core{ 0 };
        core->CoreNumber = i;
        _beginthread(startMonitoringCoreSpeeds, 0, core);
    }
    std::cin.get();
    closed = true;
    UninstallDriver();
    DeleteCriticalSection(&printLock);
}
</code>
It uses install.cpp which you can get from the IOCTL sample. I will post a working, fully working and ready solution (with code, obviously) on my blog over the next few days, if not tonight.
Edit: Blogged it at http://www.dima.to/blog/?p=101 (full source code available there)...
Comment: If you're going to make it public, it might be worth cleaning up a little.  For example, is it named `KernelModeDriver` or `ReadMSRDriver`.  The code uses both.
Comment: Also, skip the performance ratio averaging stuff.  Use the broken method with `__rdtsc()` *once* to calculate the base rate, thereafter you can get instantaneous clock speed by checking the performance ratio and precalculated base rate.
Comment: rdtsc will not report real cpu cycles in most chips, there is 16.11.1 Invariant TSC feature in intel ("Processor's support for invariant TSC is indicated by CPUID.80000007H:EDX[8]. The invariant TSC will run at a constant rate in all ACPI P-, C-. and T-states. ..the OS may use the TSC for wall clock timer  services (instead of ACPI or HPET timers).", more at http://stackoverflow.com/a/4145156/196561). If it can be used to provide wall clock, it is not dynamic cpu frequency counter. To get real cycle counter, ask for hardware PMU (in linux `perf stat ./any_program` does it) UNHALTED_CORE_CYCLES


Combining two datatable and getting the amount from second table by using linq

Question: I have two tables as shown below.
Table 1
╔══════════════╦═════╦════╗
║     NAME     ║ AGE ║ ID ║
╠══════════════╬═════╬════╣
║ firstname 1  ║  20 ║  1 ║
║ firstname 2  ║  21 ║  2 ║
║ firstname 3  ║  22 ║  3 ║
║ firstname 4  ║  23 ║  4 ║
║ firstname 5  ║  24 ║  5 ║
║ firstname 6  ║  25 ║  6 ║
║ firstname 7  ║  26 ║  7 ║
║ firstname 8  ║  27 ║  8 ║
║ firstname 9  ║  28 ║  9 ║
║ firstname 10 ║  29 ║ 10 ║
╚══════════════╩═════╩════╝

Table 2
╔════════╦══════════╗
║ LINKID ║ QUANTITY ║
╠════════╬══════════╣
║      1 ║        1 ║
║      1 ║        1 ║
║      2 ║        1 ║
║      2 ║        1 ║
║      2 ║        1 ║
║      3 ║        1 ║
║      3 ║        1 ║
║      3 ║        1 ║
║      3 ║        1 ║
║      4 ║        1 ║
║      4 ║        1 ║
║      4 ║        1 ║
║      4 ║        1 ║
║      4 ║        1 ║
║      5 ║        1 ║
║      5 ║        1 ║
║      5 ║        1 ║
║      5 ║        1 ║
║      5 ║        1 ║
║      5 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      6 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      7 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      8 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║      9 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
║     10 ║        1 ║
╚════════╩══════════╝

the result table looks like this.
╔══════════════╦═════╦════╦═════╗
║     NAME     ║ AGE ║ ID ║ QTY ║
╠══════════════╬═════╬════╬═════╣
║ firstname 1  ║  20 ║  1 ║   2 ║
║ firstname 2  ║  21 ║  2 ║   3 ║
║ firstname 3  ║  22 ║  3 ║   4 ║
║ firstname 4  ║  23 ║  4 ║   5 ║
║ firstname 5  ║  24 ║  5 ║   6 ║
║ firstname 6  ║  25 ║  6 ║   7 ║
║ firstname 7  ║  26 ║  7 ║   8 ║
║ firstname 8  ║  27 ║  8 ║   9 ║
║ firstname 9  ║  28 ║  9 ║  10 ║
║ firstname 10 ║  29 ║ 10 ║  11 ║
╚══════════════╩═════╩════╩═════╝

I wish to finish this within 1 linq statement. (if totally impossible, 2 statements)
I have worked my statement this far.
 var resultQuery = from a in dtbl1.AsEnumerable()
                      join b in dtbl2.AsEnumerable()
                      on a.Field<int>("ID") equals b.Field<int>("LinkID")

                      select new
                      {
                          ID = a["ID"],
                          Name = a["Name"],
                          Age = a["Age"],
                          Qty = b["Quantity"]
                      }
                      ;

That statement will combine 2 tables, but I dunno how to continue to count the for the quantity.
Any idea?

If I must use a second query, It has been done.
 var secondResultQuery = from row in resultQuery
                            group row by new { row.ID, row.Name, row.Age } into g
                            select new
                            {
                                g.Key.ID,
                                g.Key.Name,
                                g.Key.Age,
                                totalCount = g.Sum(count => (int)count.Qty)
                            };

Answer: var resultSet   =   from a in dtbl1.AsEnumerable()
                    join b in dtbl2.AsEnumerable()
                        on a.ID equals b.LinkID
                    group a by new
                        {
                            a.Name,
                            a.Age,
                            a.ID
                        } into g
                    select new
                        {
                            g.Key.Name,
                            g.Key.Age,
                            g.Key.ID,
                            g.Count()
                        };

Query to work with DataTable
var resultSetTicketNo   =   from a in dtbl1.AsEnumerable()
                        join b in dtbl2.AsEnumerable()
                        on a.Field<int>("ID") equals b.Field<int>("LinkID")
                        group a by new
                        {
                            Age = a["Age"],
                            ID = a["ID"],
                            Name = a["Name"]
                        } into g
                        select new
                        {
                            g.Key.Name,
                            g.Key.Age,
                            g.Key.ID,
                            Counter=g.Count()
                        };

    foreach (var a in resultSetTicketNo)
    {
        Response.Write(a.ID + "~" + a.Name + "~" + a.Age + "~" + a.Counter + "
");
    }

    Response.Write("

end of resultSetTicketNo

");

Comment: Thanks. u really helped me there. some syntax difference though. I will edit post the query with the syntax that i can compile with.


NetBeans erro: pacote org não existe

Question: Estou desenvolvendo uma aplicação para desktop utilizando o netbeans. Passei alguns meses sem mexer no projeto, e quando volto a abri-lo me aparece a mensagem que o pacote org não existe. Já deletei a pasta Cache do Netbeans, já atualizei, atualizei o java e nada. Alguém pode me ajudar?
Apos reiniciar a IDE o problema continua. O interessante que o erro é somente na classe principal, nas demais classes nao tem erro. Será que preciso refazer toda essa clase do 0 utilizando layout relativo?
Comment: Que pacote org? Adicione o eerro exatamente como aparece pra você na pergunta.
Comment: Qual versão do JDK do seu projeto?
Comment: esta na versao jdk1.8.0_65
Comment: Cheque se adicionou a lib abaixo corretamente, veja se ela está no classpath do projeto correto. Não era pro erro está acontecendo após adiciona-la, a classe citada está na lib que eu indiquei pra adição.
Comment: Mano o classpathda biblioteca esta vazio, nao tem nada.. enquanto outras tem o diretorio. Iai?
Comment: Adiciona a lib da resposta. O erro vai sumir somente quando a lib for adicionada no classpath. Olhe nas propriedades do seu projeto, o procedimento é parecido com o da resposta.
Comment: Resolvi da seguinte maneira: Baixei novamente o classpath da biblioteca aqui: http://www.docjar.com/jar/AbsoluteLayout.jar e importei pra minha biblioteca AbsoluteLayout. Ta funfando de boa agora.
Comment: Menos mal então :) Mas é bem estranho isso, a lib do netbeans é a mesma dessa ai que você baixou a parte. Até simulei o problema aqui, removendo a lib, o projeto deu os mesmos erros que no seu, depois adicionei e voltou ao normal. Tente reinstalar seu netbeans ou baixar a versão mais recente(8.1) pra evitar esse problema no futuro.
Comment: Ja tinha instalado a versao mais recente pra tentar solucionar e nada.. o unico jeito foi esse kk
Answer: Cheque se no classpath do seu projeto, há a lib AbsoluteLayout, ela é adicionada automaticamente toda vez que você cria um projeto java no netbeans(pelo menos até a versão jdk 7).
Expanda seu projeto e clique com o botão direito na pasta Libraries. Depois clique na opção Add Library,

e selecione AbsoluteLayout na lista.

Após isso, a lib deve ficar desta forma no seu projeto:
Comment: Fiz o que propos, consigo seguir todos os passos, porem a biblioteca nao é adicionada. Precisa reiniciar o netbeans apos a adiçao da biblioteca?
Comment: Só isso já resolve o problema, mas se seu projeto não estiver configurado para compilar automaticamente, ou você pode simplesmente executar o projeto.

NetBeans erro: pacote org não existe


Norm Product expression

Question: Prove the product expression $$\left \| AB \right \|_{U\rightarrow W} \leq \left \| A \right \|_{V\rightarrow W}\left \| B \right \|_{U\rightarrow V}$$
Hint: consider $(AB)u = A(Bu)$ and apply $\left \| Av \right \|_{W}\leq \left \| A \right \|\left \| v \right \|_{V}$ twice
Unfortunately, I'm having a problem figuring out how to apply the hint because my knowledge of norms is very poor. I am hoping for a very comprehensions explanation so that I may learn how to handle norms.
Answer:
It is very simple
  $$\|ABv\|_{W}\le \|A\|_{V\rightarrow W}\|Bv\|_{V}\le \|A\|_{V\rightarrow W}\|B\|_{U\rightarrow V}\|v\|_{V}$$
  for all $v$, then immediately we get,
  $$\|AB\|_{U\rightarrow W}\le  \|A\|_{V\rightarrow W}\|B\|_{U\rightarrow V}.$$

Norm Product expression


Dealing with the $dx$ that is in the denominator of a definite integral.

Question: I'm not sure if I should specify between a definite or an indefinite integral here but that's the instance I'm specifically interested in.
I was thinking about an integration rule that states that if we have $\sin x$ raised to an odd power we let $u=\cos x$ and respectively with $\cos x$. I'm aware that this isn't something that always works out but I tried to play with it.
Consider $$I=\int_{0}^{\frac{\pi}{4}}\tan x dx = \int_{0}^{\frac{\pi}{4}} \frac{\sin x}{\cos x}dx $$
This works out easily by letting $u=\cos x$ but letting $u=\sin x$
$$\int_{0}^{\frac{\sqrt 2}{2}} \frac{u}{du} $$
Can this be worked out? A comment here said we could maybe say $\frac{1}{dx}= \infty$
Do we just say that this is a bad substitution and move on? Is the answer to that integral different to what it would've been by doing the normal substitution?
Comment: If $u=\sin x$ then $du=\cos x dx \implies dx=\frac{du}{\cos x}$. Not sure how you got $du$ in the denominator.
Comment: Can you please edit your post to show us how you got the (wrong) result $\int_{0}^{\frac{\sqrt 2}{2}} \frac{u}{du}$?
Comment: That's embarrassing, I saw my teacher say something about how this substitution doesn't work and he said this is what could happen and I didn't think much of it. I vote this to be closed though the overall theme of my question still stands.
Answer: $\int_0^{\pi/4} \frac{\sin{x}}{\cos{x}}dx$
Note $u=\sin{x}$ does not imply $du=\cos{x}$, but rather $du=\cos{x}dx$.That in turn implies $dx=\frac{du}{\sqrt{1-u^2}}$
So $\frac{\sin{x} dx}{\cos{x}}=\frac{u}{du/dx}dx=\frac{u}{du}dx^2=\frac{u}{du}\frac{du^2}{1-u^2}=\frac{udu}{1-u^2}$
$\int\frac{udu}{1-u^2}=(-1/2)\ln{(1-u^2)}+C=-\ln{(\cos{x})}+C $
When messing with differential equations you might actually find something like $du$ in the denominator, but you'll have to cancel it out to get a meaningful integrand. There might be  more flexibility with numerical methods.


Pivot table to sum and count a column with respect to a reference

Question: I have data like:
Userkey.             Qty
420151.                5
421052.                8
421053.                3
421052.                6
421053.                4
421052.                7

What I want:
Userkey.             Sumofqty.           Countofqty(frequency)
421051.                    5.                               1
421052.                   21.                               3
421053.                    7.                               2

Comment: I've improved the formatting of the example data, but please also try to include it in a [copy-pasteable format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).
Comment: Add some more description on your question(doubt) and what result you are expecting. Explain in detail regarding your doubts and what other ways you have tried.
Answer: This tidy solution should work:
library(tidyverse)

data <- tribble(~Userkey, ~Qty,
                "420151.", 5,
                "421052.", 8,
                "421053.", 3,
                "421052.", 6,
                "421053.", 4,
                "421052.", 7)

data %>%
  group_by(Userkey) %>%
  summarise(Sumofqty = sum(Qty), Countofqty = n())

Comment: This depends on the formatting of the file. You should be able to import it (if using the tidyverse packages as loaded above with `library(tidyverse)` by implementing something like `data <- read_csv(file = "path_to_your_file")` instead of the `data <- tribble(...`. You might also need to set some of the other arguments - again depending on the formatting.
Comment: If I've a CSV file which contains USERKEY and QTY, then what will the code (R Programming)
Comment: If I want to add this summarisation in another data frame, then what is my code.
Comment: I'm sorry but you should create a new question for this. It depends on the the dimensions and nature of the other data frame. Please accept this answer if it solved your original question - then create a new question for your further inquiries.


How to connect this setup, i don't want to blow up something. (RCA to TS) Please advise

Question: In order to be more precise with this application, I will explain you the exact set up im aiming for.
I have an old dj mixer, the NUMARK DM1050, picking up dust for the past 1 year, and I recently decided to do some mixing on it, for practice.
I have Scarlett Focusrite 2i4 (studio audio interface), a laptop, this NUMARK DM1050 mixer, and a pair of STUDIO active monitors - the JBL LSR 305.
(if someone really needs pictures of ins and outs of the equipment, I can provide)
Here goes my thought for setup:
The laptop is running a dj softvare, 2i4 is connected to the laptop via USB cable, and a numark mixer is connected the 2i4 via RCA cables, where the channel one from the mixer with dual RCA goes to the 1/2 of the 2i4. Same for the second channel and 3/4 on the 2i4.
Here is my problem:
I am not sure (since If I understood correctly, to get the output from this setup, I need to connect speakers to the mixer) If I can connect the RCA main out (L and R) from the mixer, to these JBL LSR 305 active studio monitors. The JBL's have balanced TRS input (which I use normally with balanced TRS out on the 2i4 when I do music production), but they don't have the unbalanced RCA.
Is it possible to run RCA to TS cable from this mixer to these monitors?
Will it do any damage? I really don't want to damage something up this is the only set up I have atm and the first time I do this kind of connection.
Will it mess the ground?
Are the cables that need to be run mono or stereo? What should I do?...
Sorry for the rather long post, I just want to get this right, and if it can't work, I want to be sure of that so that i know whether i should buy some up to date dj equipment. I would rather to that then damage my JBL LSR 305 studio monitors.
Answer: Yes, that will be fine.  Generally speaking, the only way to cause damage would be to run a speaker output into a line or mic input. (Or to make the speakers do something impossibly loud - always a possibility with feedback if there's both a microphone and speaker in the system.  So see my final paragraph below.)
A cable of this type can't be 'stereo'.  It can be balanced or unbalanced.  As an RCA output is inherently unbalanced, there's no point in using a TRS jack plug at the other end.  The speaker will be perfectly happy with a TS jack plug.
The point of a balanced connection in this sort of setup is to reduce the possibility of noise and hum.  I doubt you'll have a problem.  But if you do, no damage will be done.
As always, when trying out a new setup start with the volume controls on the speakers right down.  There's also a sensitivity switch on the speakers. Start at the +4dB setting, though you may well end up using -10dB.
Comment: Thank's for answering.
I have to agree with your answer.
Currently with 2i4 they sit at +4dbU. Will see about switching to -10dbV when i get the cables and connect to the dj mixer, probably tomorrow.

I was considered by the thought that they are meant for studio monitoring and not for patching a dj mixer on it. Big PA systems play a role for that.
But i hope, that as long as i'm not pushing them far through (usually im satisfied with no more than 75ish db) it should be okay right
Comment: You can easily tell when speakers are being pushed too far, though some people seem to go into denial - "But I WANT it louder!"  :-)


PHP extensions dir with YUM

Question: I've installed PHP on a Linux machine but can't seem to find the 'modules' directory from PHP.
On Mac with MAMP installed, this folder is located in ~/Applications/MAMP/bin/php/php5.3.6/, but I can't figure out where this folder is installed on Linux, with yum.
Anyone who nows where yum installs these PHP-directory?

Edit: some more information about the environment
I'm working with Amazon EC2 on an Amazon Linux AMI (ami-1624987f).
But while developing, I've used Ubuntu and installed everything (Apache, PHP, MySQL) via apt-get.
The installation was done by yum install php php-devel php-mysql
Now, when moving the application to EC2, seems like apt is not available on this AMI and I have to use yum. Seems like the yum installation is different from apt because I can't find the folder as described above.
Edit2: conclusion
There were more issues so at the end I've switched from Amazon Linux to Ubuntu where I also could use apt-get. But the answer from chanthemanless works. Thanks everyone!
Comment: Open php.ini and look at the [`extension_dir`](http://php.net/manual/en/ini.core.php#ini.extension-dir) setting.
Comment: it says `extension_dir = "/"`, does this means it's in the root of the disk?
Comment: That would appear to be what it is saying, yes - that doesn't seem right though.
Comment: "I've installed PHP..." How? "... on a Linux device..." Which?
Comment: Neither yum nor apt is responsible for where packages install their files.
Comment: I've launched the EC2-instance, ssh'ed into it and `yum install php` works out of the box. Does yum use a default installation directory?
Comment: Yes. yum uses `/` by default.
Answer: You can run a:
sudo php -i | grep extension

The output should show something like:
extension_dir => /blah/blah/blah
Or you could run a:
sudo find / -name '*php*'

And look at all the places you have php files.
Answer: I was using PHP 7.2.24 in Amazon EC2 instance , even though extensions were installed and i was not able to locate the path. By doing phpinfo() I found extension_dir was set to /usr/lib64/php/modules where all directories where installed.
I modified php.ini under /etc folder and still could not reflect. But later found this very useful link Click here where i found we need to restart php-fpm after doing the modification and later restart apache.

sudo systemctl restart php-fpm.service

I hope it helps someone.

PHP extensions dir with YUM


Quando alocar memória dinamicamente?

Question: No C++ você pode declarar um objeto ou variável facilmente assim:
tipo_da_variável nome_da_variável;

Esse tipo de declaração é o mais fácil de usar, mas também pode-se usar o new para alocar memória dinamicamente e depois desalocar com delete.
É verdade que alocar dinamicamente objetos deixa o programa mais rápido, isto é, faz ele ocupar menos memória e CPU?
Devo sempre alocar dinamicamente objetos?
Se a resposta para essas 2 perguntas acima for não, Então poderia exemplificar alguns casos que o uso de memória dinamicamente alocada é justificável? Ou me explicar qual a utilidade de alocar dinamicamente a memória?
Eu ouvi falar que alocar memória dinamicamente é algo que deve ser feito quando nós não sabemos o quanto de memória iremos precisar, mas eu também não entendi direito esse argumento, afinal meu compilador aceita sem erros o código:
int num1;
cin >> num1;
char palavra[num1];

No código acima, o tamanho do array vai depender do valor que o usuário digitar, ou seja, de inicio, não sabemos o quanto de memoria que o programa vai utilizar e mesmo assim, não foi necessário o uso de new + delete
Comment: Os objetos "pre-criados" em QT são sempre alocados dinamicamente, para acessá-los se usa "->" e não "."
Answer:
tipo_da_variável nome_da_variável;
Esse tipo de declaração é o mais fácil de usar

Sim, mas está errado. Não inicializar um valor é um erro.
Essa forma chama-se alocação automática.

É verdade que alocar dinamicamente objetos deixa o programa mais rápido

Não, de forma geral é o oposto, deve-se evitar a alocação dinâmica o máximo possível, sem causar outros problemas.

faz ele ocupar menos memória e CPU?

São coisas distintas, mas a alocação dinâmica sempre consumirá mais memória, invariavelmente. O trabalho para alocar costuma ser monumental comparado com a alocação automática. E se não for, a liberação será monumental. Não dá para afirmar categoricamente porque C e C++ deixam você gerenciar a memória de maneiras diferentes.

Devo sempre alocar dinamicamente objetos?

Não, é muito mais complicado gerenciar isso.

poderia exemplificar alguns casos que o uso de memória dinamicamente alocada é justificável?

Acho que isso já está respondido em diversas perguntas:

Performance de acesso a dados na heap e stack e alocação de objetos
Quando devo escolher entre utilizar ou não um ponteiro ao criar um objeto?
O que são e onde estão a "stack" e "heap"?
Diferença das declarações de arrays C/C++
char[] ou *char malloc?

afinal meu compilador aceita sem erros o código

Funcionar é diferente de estar certo.

No código acima, o tamanho do array vai depender do valor que o usuário digitar, ou seja, de inicio, não sabemos o quanto de memoria que o programa vai utilizar e mesmo assim

Nenhum problema, pode fazer alocação automática definido em tempo de execução, isto não faz a alocação ser dinâmica.

Variáveis declaradas dentro de blocos ou subprogramas são alocadas dinamicamente?
O que impede um array de ser inicializado com um tamanho variável em C?
Answer: É importante lembrar que será gerado o código objeto. É possível fazer essa análise. Tenho lido bastante sobre arquitetura de jogos digitais, inclusive existe um livro escrito pelo "lead programmer" da reconhecida Naughtydog, no qual ele fala alguma coisa sobre isso, principalmente quando ser vai desenvolver para consoles.
Ponteiros pode te dar mais flexibilidade nas técnicas e métodos de codificação, talvez.
Comment: Em que isso responde os questionamentos apresentados na página?

Quando alocar memória dinamicamente?


Concatenar variável com outra variável PHP

Question: Meus inputs estão sendo gerados a partir de uma repetição do Javascript nomeando-os da seguinte forma: input.setAttribute("name",`tubo_${i}`) e input.setAttribute("name",`largura_${i}`)
Meu problema é quando preciso tratar e separar esses valores no PHP, recebo os itens via $_POST.
print_r($_POST):
Array
(
    [tubo_0] => tubo1
    [largura_0] => largura1
    [tubo_1] => tubo2
    [largura_1] => largura2
)

Preciso criar um array contendo os valores dos tubos e outro array com o valor das larguras.
Segue a minha tentativa falha:
extract($_POST);
$qtdModelos = (count($_POST)) / 2;

for ($i=0; $i < $qtdModelos ; $i++) {
    $arrayTubo[] = $tubo_.$i;
    $arrayLargura[] = $largura_.$i;
}

print_r($arrayTubo);
print_r($arrayLargura);

Resultado
Array
(
    [0] => 0
    [1] => 1
)
Array
(
    [0] => 0
    [1] => 1
)

Somente os valores de $i estão sendo armazenados, ou seja, as variáveis não estão sendo "concatenadas" da maneira que eu gostaria.
Comment: Por que não faz ``input.setAttribute("name",`tubo[${i}]['tubo']`)`` e  ``input.setAttribute("name",`tubo[${i}]['largura']`)``? Assim já terá um *array* com os dados organizados.
Comment: O certo não seria você fazer por exemplo: for ($i=0; $i < $qtdModelos ; $i++) {
    $arrayTubo[] = $tubo_[$i];
    $arrayLargura[] = $largura_[$i];
}

???
Comment: São variáveis gerada a partir do extract($_POST), neste exemplo, as variáveis existentes são $tubo_0, $tubo_1, $largura_0 e $largura_1.
Preciso armazená-las dentro de arrays específicos para cada propriedade.
Comment: A resposta do Rafael S. resolveu meu problema, desta maneira `${tubo_.$i}`.
Answer: Se não me engano você pode fazer isso:
${'tubo_' . $i}

Deixando seu código dessa forma:
extract($_POST);
$qtdModelos = (count($_POST)) / 2;

for ($i=0; $i < $qtdModelos ; $i++) {
    $arrayTubo[] = ${tubo_.$i};
    $arrayLargura[] = ${largura_.$i};
}

print_r($arrayTubo);
print_r($arrayLargura);

Nesse link fala um pouco sobre isso.
Answer: Ao invés de concatenar no nome, use o valor de i como índice:
Tubo 1
Nome: <input type="text" name="tubo[0]">
Largura: <input type="text" name="largura[0]">

Tubo 2
Nome: <input type="text" name="tubo[1]">
Largura: <input type="text" name="largura[1]">

Assim, quando enviar para o PHP, poderá recuperar os diferentes arrays com $_POST['tubo'] e $_POST['largura'].
Para tal, ao invés de fazer:
input.setAttribute("name",`tubo_${i}`)

Você poderia fazer:
input.setAttribute("name",`tubo[${i}]`)

Se os dois campos são relacionados entre si, você consegue agrupar melhor seus dados no HTML. Ao invés de concatenar o valor de i no nome do campo, use-o como índice do array e defina as colunas nesse índice.
Tubo 1
Nome: <input type="text" name="tubo[0][nome]">
Largura: <input type="text" name="tubo[0][largura]">

Tubo 2
Nome: <input type="text" name="tubo[1][nome]">
Largura: <input type="text" name="tubo[1][largura]">

Assim, quando enviar ao PHP, o valor de $_POST será algo como:
Array
(
    [tubo] => Array
        (
            [0] => Array
                (
                    ['nome'] => tubo1
                    ['largura'] => 100
                )

            [1] => Array
                (
                    ['nome'] => tubo2
                    ['largura'] => 200
                )

        )

)

Assim, para tratar os valores, bastaria percorrer esse array e consumir as informações. Uma forma seria:
foreach ($_POST['tubo'] as $tubo) {
    echo "O tubo {$tubo['nome']} possui largura {$tubo['largura']}";
}

Veja funcionando no repl.it
Comment: Realmente os dados ficam muito mais organizador, mas o meu objetivo não é juntar **tubo** com **largura**, e sim separar essas propriedades em diferentes arrays no PHP, para eu poder tratá-los e inseri-los no banco de dados em diferentes colunas.
Comment: @GabrielZedine Para isso bastaria fazer `array_column($_POST['tubo'], "largura")`, ou nomear de acordo os campos, por exemplo `name="largura[0]"` e buscar direto o valor de `$_POST['largura']`


Can I distinguish short and long options in org.apache.commons.cli

Question: Suppose I have a tool which uses org.apache.commons.cli package to take command line options.  I define an option
<code>Options opts    = new Options();
opts.addOption("v", "version",  false, "print tool version information");
</code>
So the user can call my tool with -v or with --version command line options.
The question is, can I then tell in my code if the user typed -v or --version?
What I am thinking is to associate long versions of command line options with verbose output, and short versions with non-verbose.  So, if a user passes -v, he/she will get version number of the tool, but if a user types --version, he/she will get version of the tool, versions of dependencies, some other versioning and vendor info, etc.
Two questions:

Can it be done with org.apache.commons.cli effectively?
Is it a good idea from the user perspective? Is this a common practice or am I inventing something esoteric here?

Experienced thought on both implementation and the philosophy of this approach are appreciated.
Thanks in advance
Answer: I don't think you will get that information this way, as the commandline is parsed into matching Options without access to the actualcommandline after parsing.
I would define two separate Option-objects here, one for 'v' and one for 'version', then you can check, which of the two options was matched and act accordingly.
Comment: This is the conclusion I came to as well.  Just wanted to check if I perhaps overlooked something.  Thanks


Developing sites while using Aegir and Drush make

Question: I read this article from mig5.net about 'Drupal deployments & workflows with version control, drush_make, and Aegir'. I am impressed by the efficiency of the workflow described here, and I really want to implement this. I read it again and again, but one thing won't get clear to me.
How do you, while developing websites, get your changes into the next build? When you find out you need an extra module, how can you get this in the next build when the (for example contrib) module isn't controlled in git? Do you need to edit your .make file every time you want to add a module, library etc.?
Thanks in advance.
Answer: Yes. The short answer is you update your Drush make file to point to the new version of the module you want to be included in your new platform(build).
In your drush make file you would include the version of each module you are including in your platform build. So views for example would look like this.
projects[views][subdir] = "contrib"
projects[views][version] = "3.4"

Now if you want to update to the new version of Views module you would update your make file to something like this.
projects[views][subdir] = "contrib"
projects[views][version] = "3.5"

Then build a new platform in Aegir using this updated drush make file. Then you would migrate the site to the new platform and Aegir will do the update for you.
It's a pretty slick workflow. I keep all of my drush make files in a repo called builds so I can have a record of each build of a project. Hope that helps.
Comment: Sure, but so does Capistrano-based builds. A smart engineer would implement automatic cleanup of old platforms that no longer have any sites on them (you can automate deletion of platforms in Aegir). And yes, you can call the platform name anything you like. These days I am even more brutal with my naming and simply use the serialised number eg '2009102601', because I find it doesn't matter so much what platform the application is on (it changes all the time so who cares)
Comment: Why is the build in the article called 'drupal-6.14_build_2009102601'? If I'm right, it's the application of Mig5, so wouldn't it be more logic to call it 'mig5_build_2009102601'? This workflow also involves you get a huge list of platforms when you're developing more sites, isn't it?
Comment: Okay, but when you have to roll back a change you don't have an idea to which platform to migrate to, because you didn't attach a descriptive alias to it (the date, but not a site-name)...
Comment: And am I able to auto-delete platforms with a module like Auto Expire? A problem is the fact that this module would also (try to) delete the latest released platform (if the site hasn't changed for a while).
Answer: Bob beat me to it :) but in response to this and your email you sent me, yes indeed this is the correct procedure. Treat your Drush makefile as the 'blueprint' of your application.
Work away in development manually / clone your live site and manually 'drush up' or 'drush dl' a module and test that everything works as expected.
Then fold that new module/updated version into your makefile, build a new platform each time the makefile is updated, and use the 'Migrate' task to 'upgrade' your application onto the target platform.
If something goes wrong during the upgrade (e.g during the drush updatedb which occurs during a Migration to apply schema updates in your database), Aegir will, in most cases, automatically roll back to the previous platform, which is the appeal of such a system.


New window not opening in fltk with button callback

Question: I created a button that when clicked on will open a new window through callback but when this button is clicked nothing happens but when it is released it blinks the new window and does not allow me to see the content in the new window. Please any help would be appreciated.
The callback
<code>//Callback for advanced search
static void ad_cb(Fl_Button *theButton, void*)
{
    Fl_Window adw (10,10,600,400);
    Fl_Button  adcc (30,40,120,20,"Advanced Search");
    adcc.tooltip ("Make advanced search");
    adw.show();

}
</code>
The Button
<code>Fl_Button  ad (30,460 + 40,120,20,"Advanced Search");
    ad.tooltip ("Make advanced search");
    ad.callback((Fl_Callback*)ad_cb);
</code>
Comment: Please provide [mcve].
Answer: The destructor is called as soon as the function exits. That is why you just see a flash.  Change it to
<code>//Callback for advanced search
static void ad_cb(Fl_Button *theButton, void*)
{
    Fl_Window* adw = new Fl_Window (10,10,600,400);
    Fl_Button*  adcc = new Fl_Button (30,40,120,20,"Advanced Search");
    adcc->tooltip ("Make advanced search");
    adw->show();
}
</code>
You can close the window by hitting the x in the top corner.
Comment: Thank you so much for ur answer it solved my problem but please I would like to make the main window not work until the window called by the button is closed
Comment: Make it modal - see http://stackoverflow.com/questions/25805938/create-custom-fltk-dialog-modal-window


Differential in vector calculus (Find coordinate expreession of directional derivatives)

Question: $p,w\in \mathbb{R}^n$ are vectors. Hence we can write
$$w=w_1e_1+...+w_ne_n$$
with $e_i$ being the basis.
My question is how to work out the RHS from the LHS in the following equation:
$$\frac{d}{dt}\bigg|_{t=0}f(p+tw)=w_1\frac{\partial f}{\partial x_1}(p)+\dots+w_n\frac{\partial f}{\partial x_n}(p)$$
I am also confused by the notation. What is $x_i$ in this context?

Here is what I tried:
\begin{align}
\frac{d}{dt}\bigg|_{t=0}f(p+tw)
&= \frac{df}{dt}\bigg|_{t=0}(p+tw)w\\
&= \frac{df}{dx}\frac{dx}{dt}\bigg|_{t=0}(p+tw)[w_1e_1+...+w_ne_n]\\
\end{align}
I cannot really make sense of it.
EDIT: Forgot to say: $f:\mathbb{R}^n\to \mathbb{R}$
Comment: Hint : Try it using chain rule.
Comment: @Sou燈馬想 Yes that is already what I tried. I don't understand how to apply it.
Comment: The $x_i$ are coordinates on $\mathbb{R}^n$. The $e_i$ are the bases you get for the tangent space from these coordinates.
Comment: The classical notation $\frac{\partial}{\partial x_i}$ is not very good. It must be understood as the derivative with respect to the $i$-th coordinate (in the given basis). The $x$ is unimportant here. The $i$ is.
Answer: You have $g : \mathbb{R} \rightarrow \mathbb{R}^n $ defined as $g : t \mapsto p+tw$ and the function $f : \mathbb{R}^n \rightarrow \mathbb{R}$, with $f: (x_1,\cdots,x_n) \mapsto f(x_1,\cdots,x_n)$. So $h = f \circ g : \mathbb{R} \rightarrow \mathbb{R}$.
Let $t_0=0$ and $g(t_0) = p + w \cdot 0 = p$. We have $g(t) =(g_1(t), \cdots , g_n(t))= (p_1 + w_1 t, \cdots , p_n+w_n t)$ and $g'(t_0) = \big(\frac{dg_1}{dt}(t_0) , \cdots , \frac{dg_n}{dt}(t_0)\big) = (w_1,\cdots,w_n)$.
The differential of function $g : \mathbb{R} \rightarrow \mathbb{R}^n$ is  $g'(t)$ which is $n \times 1$ matrix, and for $f : \mathbb{R}^n \rightarrow \mathbb{R}$ is $f'(x) = Df(x) = \big[\frac{\partial f}{\partial x_1}(x) \cdots \frac{\partial f}{\partial x_n}(x)\big]$ is a $1\times n$ matrix so the differential of the composition $h = f \circ g$ is just a number $h'(t) = Df(g(t)) \cdot g'(t)$.
By chain rule,
\begin{align}
h'(t_0) &=\frac{d}{dt}\Bigg|_{t_0=0} f(p+wt) =(f \circ g)'(t_0) = Df(g(t_0)) \cdot g'(t_0) \\
&= \Big[ \frac{\partial f}{\partial x_1}(p) \cdots \frac{\partial f}{\partial x_n}(p) \Big]
    \begin{bmatrix}
    \frac{dg_1}{dt}(t_0)\\
    \frac{dg_2}{dt}(t_0)\\
    \frac{dg_3}{dt} (t_0)\\
    \end{bmatrix} = \sum_{i=1}^{n} w_i \frac{\partial f}{\partial x_i}(p)
\end{align}
Comment: OK, everything makes sense now. Although I think you make a mistake $g(t_0)=p$ right? Anyway, thanks.
Comment: Opps. I'll fix that.