Python: can a function return a string?

Question: I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
def lsubstr(x):
    a= ''
    b= ''
    if x == '':
        return ''
    else:
        a = a + x[0:]
        b = b + x[1:]
        lsubstr(x[2:])
        #print (a,b)
        return a and b

lsubstr('hweolrllod')

so I changed my code to this:
def lsubstr(x):

if len(x) <1:
        return x
else:
        return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')

and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
the error I get is
TypeError: Can't convert 'tuple' object to str implicitly
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.
Comment: Yes, a function *can* return a string. Your issue, at least one of your issues, is that you're not returning from the recursive call at all (e.g. `return lsubstr(..)`). Secondarily, what is `a and b` supposed to return exactly?!
Comment: The `and` operator is normally used for boolean logic. I believe you want to use `+` to concatenate the strings.
Comment: Part of your problem may be that you aren't doing anything with the value returned from either of the calls to `lsubstr`. Perhaps you want to print it out or assign it to a variable or something?
Comment: if I am going to concatenate the strings, it wouldn't give me the desired results, infact it would make it a single string back again
Answer: The and keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
...
return (a, b)

And then you can access the values using the indexing operator like this:
a = lsubstr( ... )
a[0]
a[1]

Or:
word1, word2 = lsubstr( ... )

Comment: "it gives me an error" is not useful to us. Exactly what error do you get?
Comment: I might still take issue with the description of `and` being a "boolean" operator... but the rest makes a lot more sense now. ;o)
Comment: @deceze I've edited my question, if that makes anything better.
Comment: if I return anything like "return (a,b)" it gives me an error

Python: can a function return a string?


drop fin packet with iptables rule

Question: Os is linux mint 19, i want to setup a rule in iptables to drop the incomming FIN packet as a response of the FIN_WAIT_2 state.
This for a given port. I want to test an application and need some connections staying in the FIN_WAIT_2 tcp state.
Firewall is ufw
Answer: If you just want to drop the incoming FIN packet when you always initiate the shutdown of the connection, then a rule such as the following should suffice:
iptables -I INPUT --protocol tcp --destination-port 1337 --tcp-flags FIN FIN -j DROP

However this will mess up closing of connections by the other end of the connection. I don't think that it's possible to only drop the FIN if preceded by an ACK.
Comment: At the client site the connection stays in FIN_WAIT1. This is one of the states i want the client to stay in for testing purpose.
Answer: Unfortunately I haven't found any notes about checking the tcp flags in the ufw manual.
In iptables your scenario can be implemented in some complex way using the ipset, but there are some limitations. I guess, your host is the tcp client, and server port number is 1234 (free to change it).
# create the ipset list for fin_wait sockets.
# every entry is tuple (local-ip,local-port,remote-ip)
ipset create fin_wait hash:ip,port,ip timeout 3000

# if local host sends the fin packet inside established connection
#   add entry into fin_wait list
iptables -A OUTPUT \
         -p tcp --tcp-flags FIN FIN \
         --dport 1234 \
         -m conntrack --ctstate ESTABLISHED \
    -j SET --add-set fin_wait src,src,dst --exist

# if local host receives the fin packet for fin wait socket
#   drop it before tcp stack processing
iptables -A INPUT \
         -p tcp --tcp-flags FIN FIN \
         --sport 1234 \
         -m set --match-set fin_wait dst,dst,src \
    -j DROP

For server there is difference.
# create list for test clients
ipset create test_clients hash:ip

# add addresses of test clients
ipset add test_clients 192.168.100.10

# create list for clients in fin wait state
# server ip,port is known, so ip,port type is enough
ipset create fin_wait_clients hash:ip,port timeout 3000

# if server receives fin from test client
#     add client's ip,port into set
iptables -A INPUT -p tcp \
         --dport 1234 \
         --tcp-flags FIN FIN \
         -m set --match-set test_clients src \
    -j SET --add-set fin_wait_clients src,src --exist

# if server sends fin to test client as reply
#     block this fin
iptables -A OUTPUT -p tcp \
         --sport 1234 \
         --tcp-flags FIN FIN \
         -m set --match-set fin_wait_clients dst,dst \
    -j DROP

Some notes:

Use ipset list fin_wait command to list the current blocked entries from iptables' point of view
Use ss -t4 state fin-wait-2 command to list sockets in fin wait 2 state
Order of rules is very important.
Better use the iptables-save / iptables-restore / iptables-apply tools to safety rule set changing.
Comment: i don't see the 'ss -t4 ...' part of the rule, should it be part of the rule? Can you please add a destination port for which the rule is valid?
Comment: `ss -t4 state fin-wait-2` isn't a part of any rule, it's a separate command to list sockets in a host system. Most suitable set type is ip.port,ip, so there isn't way to use full 4-elements tuples and destination port, but you can add the server side port number with adding `--dport ` / `--sport ` into `OUTPUT` / `INPUT` rules.
Comment: >>> I guess, your host is the tcp client, and server port number is 1234. I want to apply the rules at the server. So the incomming connection is at port 20000 in this case. I've added the rules but I don't see any blocked entries. Something wrong with INPUT and OUTPUT?
Comment: For server need other rules. I'll edit the answer to provide the rules for server too. I've written rules for client because you asked about client, not server.
Comment: I've got a "bad argument 'test_clients' '" probably because of the line "-m set test_clients src"
Comment: Fixed. I've missed the 'match-set' option in the rules.
Comment: There were no entries in fin_wait_clients after a connection to the server and given port. After I changed -sport to -dport in the OUTPUT rule a entry was created in the fin_wait_clients. However at the client site the connection stayed for a longer period in TIME_WAIT (seen with netstat) and later on all data was sent end the connection closed.
Comment: Entry is added into fin_wait_clients only after client has sent the tcp segment with fin flag and server receives this segment. Also, server side after this stays in LAST ACK state, but client side - in FIN WAIT 2 state.
Comment: for some reason the filter doesn't work, is it possible to add a rule to see the packets dropped for a given destination address? (in /var/log/kern.log or syslog). In a previous filter a check was  done for the ESTABLISHED state, is that removed on purpose?
Comment: Let's try to solve your issue. Can you paste into the question the output of `iptables-save -c`? Are the server and the client on different hosts or on the same?
Comment: client and server are on different hosts. The server listsens on port 20000, iptables rules are applied at the server host. The clients ip address is added to test_clients. I removed the ip address (filled with xxx)  for privacy purposes in the next comment (output of iptables-save -c)
Comment: [2:72] -A INPUT -j ufw-after-logging-input
[2:72] -A INPUT -j ufw-reject-input
[2:72] -A INPUT -j ufw-track-input
[0:0] -A INPUT -p tcp -m tcp --dport 20000 --tcp-flags FIN FIN -m set --match-set test_clients src -j SET --add-set fin_wait_clients src,src --exist
[0:0] -A FORWARD -j ufw-before-logging-forward
[0:0] -A FORWARD -j ufw-before-forward
[0:0] -A FORWARD -j ufw-after-forward
[0:0] -A FORWARD -j ufw-after-logging-forward
[0:0] -A FORWARD -j ufw-reject-forward
[0:0] -A FORWARD -j ufw-track-forward
Comment: [2347:2205188] -A OUTPUT -j ufw-track-output
[0:0] -A OUTPUT -p tcp -m tcp --sport 20000 --tcp-flags FIN FIN -m set --match-set fin_wait_clients dst,dst -j DROP
[0:0] -A ufw-after-input -p udp -m udp --dport 137 -j ufw-skip-to-policy-input
Comment: The saved file was to big so the relevant part is split into the INPUT and OUTPUT part.
Comment: Move up the your rules to the top of INPUT / OUTPUT chains. They should be on the first place, not after any ufw rules. As you can see, in the INPUT chain your custom rule has zero counters because the packets are accepted before it.
Comment: That's better. I flushed the iptables and added the rules. In the fin_wait_clients I've got two entries. However at the client side the state is FIN_WAIT1. (Want to have FIN_WAIT2) Shouldn't we drop the ACK sent from the server side? Counters: [9:468] -A INPUT -p tcp -m tcp --dport 20000 --tcp-flags FIN FIN -m set --match-set test_clients src -j SET --add-set fin_wait_clients src,src --exist
[38:2072] -A OUTPUT -p tcp -m tcp --sport 20000 --tcp-flags FIN FIN -m set --match-set fin_wait_clients dst,dst -j DROP
Comment: Check the dump. I think server sends replied the ack and the fin in the same tcp packet, so client side will stuck in FIN WAIT 1. There isn't way to fix it with iptables.
Comment: I've made the dump at the client side.From client to server [FIN, ACK] after that from server to client [ACK].
After that a buch of retransmits from client to server [FIN, ACK]
Comment: Yep, it's exactly that behaviour, what you wanted to get.
Comment: Thanks a lot for your effort, much appreciated!!
Comment: Seems like we've misunderstood each other. You're welcome. In lab I've got exactly what you asked and it was working. Check again the TCP fsm diagram.
Comment: What I see that the client stays in FIN_WAIT1, that is also what you 've got in the lab? I'm a little bit confused now...

drop fin packet with iptables rule


Confused about C6/9 guitar chord

Question: I have two questions (detailed below).
So I've been watching a Frank Vignola video course on TrueFire.com and in a song called Tranquility he uses a chord which he has labelled C6/9 (he pronounces it as a "C 6 9 chord". Below is a screen shot of the music/tab notation:

Now at first I thought it must mean a "C Dominant 6th 9th" chord because that's typically how I've seen dominant chords written (e.g. C7 is a C dominant 7th chord) and it wasn't written down as "Cmaj6/9" (which is what I would've expected).
But a quick cursory google reveals it is also known as a Cmaj6/9.
So my first first question is...
Why is it written like C6/9 when to me that confuses it with a dominant variety of chord?

Next I stumbled across the site http://www.jamplay.com/tools/guitar-chords/1-standard/3-c/4-69 which shows the C6/9 chord in different voicings. The one I was interested in (because it looked to match the one Frank Vignola had tabbed, but this one is on the 9th fret where as we're looking for the 2nd fret) was:

But this confused me because I've never heard of a 'set 3' voicing? It didn't look to be an inversion or a drop voicing as there is no B note in the C6/9 chord.
So my second question is...
How and/or why are jamplay playing the same 'chord shape' but on a different fret, and yet both they and Frank Vignola are able to refer to it as the same chord? (unless the 'set 3 voicing' means something hence the difference in fret placement)
When I look at the notes that are being fingered from the 2nd fret perspective it looks like a 'rootless' Cmaj6 with an added 9th (we finger: E, A, D, G).
Any help understanding this is appreciated.
Many thanks
Answer: I agree that C6add9 would be a better way to describe the chord. It shouldn't be confusing though: A C6 chord is defined as the major C chord with an added 6. The only other use of the slash '/' symbol is with chords that should be played with a different bass note than the root note of the chord. So for example C6/E would be a C6 chord with an E in the bass. However, /9 doesn't have any meaning in that sense, so it's not strange they came up with a way to reuse that symbol to mean 'add'. Especially since a 6/9 chord is common in Jazz and there they like to shorten notation with all those advanced chords.
Comment: Thanks for the feedback. You look to be correct in that it looks to be a rootless C6add9. I've since discovered that players apparently will usually play a 9th chord simply by replacing the root with the 9th (which seems to be the case here)
Comment: I've occasionally (and annoyingly) seen slash chords with numbers meaning to play that number note as the root. C6/9 might be played on the frets             x-5-5-5-5-x (D-G-C-E). I suspect someone had the idea that when you transpose or modulate (to say D), you can leave the /9 as is instead of changing it to D6/E.
Comment: @Integralist the chord symbol is normally written with 6 in the superscript and 9 in the subscript, this is what the slash symbol is trying to approximate for. Personally I think C69 is even more clear. I read: C6 with 9. A dominant chord would be written C9/13.
Answer: You thought C6/9 might mean something else.  Now you know it doesn't.  Problem 1 solved?
And it is just C6/9.   We don't use Cmaj6/9.  (Though we might use Cm6/9.  Which would be Cm with added 6 and 9.  Not C major with a minor 6th.)
Not quite sure what you're getting at in question 2.  But yes, guitarists often leave the root of a chord to the bass player.  And the notes E, A, D, G, in any order, could be the upper structure of a C6/9 chord.
Answer: I think there is a danger in getting too dogmatic or pedantic about the spelling of chords. It can close one's mind to many interesting possibilities.
Many chords can function in entirely different ways depending upon context. I recommend taking a look at the voicings used by gypsy jazz guitarist Django Reinhardt. As he was missing a couple fingers, he often only used three notes to make a chord, and the same three notes could function as various different chords depending upon the harmony at that point in the chord progression. I don't recall anyone complaining about him not hitting the "correct" chords, even though he maybe omits a flat-7 here or major/minor third there in his voicing.
Comment: Of course, the b7 or 3rd are the  notes he would have been careful NOT to omit when constructing 'skeleton voicings'!  Root and 5th, not so essential.
Comment: From what I've seen/heard, for his rhythm playing, one or the other (3rd or 7th) can be dropped. Rarely both though. He only had two good fingers. Was he able to use the fused/damaged 4th/5th finger at all in his chords? IDK. He found ways to make substitutions and "incomplete" chords work. Here's another link with transcriptions. https://www.premierguitar.com/lessons/acoustic-lessons/django-gypsy-jazz-chords
Answer: 1st . Dominant involves the b7 of any chord. Without that, it's not a dominant chord. Dom 9 (written such as C9) will contain 1,3,5,b7 and 9.So there isn't a dominant 6th. C6/9 is a common way it's written, and it will be spelled C,E,G,A and D - C triad with a maj6 and a maj9.Naming chords that are basically major often leaves the 'maj' bit out. A sort of default system. The chord you show has no root, which isn't a problem provided the bass or keyboard is putting that C down somewhere.
2nd. C6/9 doesn't contain a B note, so it can't be right. Just 'cos it's on the Internet shouldn't give it credence.
EDIT: 'set 3 voicing' may be his way of naming 'drop 3 voicing'. However, with drop voicing, the notes still remain as the same letter names - that can't change - but in his examples, they do. In fact, they're not even the same chord. BEAD might make Bm7add4, or E7sus4, but not C6/9.
Comment: I disagree that a Dominant chord requires the b7 to be a Dominant chord. The Dominant is the name for the 5th scale degree of the diatonic scale and a  "Dominant" chord is a chord built off of the 5th scale degree, and may be extended to include the 7th, but the 7th isn't required for it to function as a 5 chord.  In jazz vernacular it may be that calling a chord "dominant" implies that the 7 is present though...
Comment: I think in this context, it's clear that "dominant" is referring to the quality of the seventh chord. Yes, you're right that chords built on the fifth of the key are often called dominant as well, but when discussing chord qualities, "dominant" is explicitly defined to include the major third and minor seventh. As you note, in jazz there aren't a lot of times when the dominant chord isn't a dominant chord, if you catch my drift :)
Comment: @user45266 - I guess the comment was for Alphonso - if so it needs '@A...' in it.
Answer: I think "set 3 voicing" might be referring to the 3rd set of strings. I had an old jazz guitar book that talked about playing drop voicings on all three string sets, where the first set was the E, A, D, and G strings; the second set was the A, D, G, and B strings; and the third set was the D, G, B, and E strings. "Set 3" could therefore be saying that the chord is played on the highest-pitched set of strings.
And of course, as others have mentioned, I'll restate that 6/9 is an exception to normal chord naming conventions. We already have 6 for major 6th chords, and for whatever reason, we use the slash there to denote an added 9th degree. Completely unambiguous, since slash chords use letter names to mark the bass note.

Confused about C6/9 guitar chord


Solving a nonlinear system of matrices using Mathematica

Question: I am trying to find solutions to nonlinear systems of matrix equations with Mathematica. The solution space is too complicated to try to use Solve, and thus I have tried to use FindInstance. Here is this simplest example of a nonlinear system that I am trying to find a solution for:
T + A + C + CBA = 0
I - A - C - ABC = 0

where A, B, C are any matrices, Det[T] = 1, and I is the identity matrix with dimension of 2x2. I also want all matrices to have only integer entries. I am using the command
FindInstance[{T + a + c + c.b.a == z, IdentityMatrix[2] - a - c -
    a.b.c == z, Det[T]==1} , Integers]

where z is the zero matrix. However, every time I do so it responds with "FindInstance::exvar: The system contains a nonconstant expression a independent of variables {Integers}."
Retrying the command as
FindInstance[{T + a + c + c.b.a == z,
   IdentityMatrix[2] - a - c - a.b.c == z,
   Det[T] == 1}  /. {a -> {{1, 0}, {0, 1}}}, Integers]

returns "FindInstance::exvar: The system contains a nonconstant expression b independent of variables {Integers}."
How can I use FindInstance or Solve to find a solution to this system without finding the solution myself by fixing "independent variables?"
Answer: I discovered that I was having a syntax problem.
The correct syntax to solve these matrix equations is the following:
A = {{A11, A12}, {A21, A22}}

B = {{B11, B12}, {B21, B22}}

C = {{C11, C12}, {C21, C22}}

T = {{T11, T12}, {T21, T22}}

FindInstance[{T + A + C + C.B.A==0, IdentityMatrix[2] - A - C - A.B.C==0, Det[T]==1},
{T11, T12, T21, T22, A11, A12, A21, A22, B11, B12, B21, B22, C11, C12, C21, C22},
Integers]


The Fourier transform of $\log^m|x|/x$

Question: We know that $\mathcal{F}(1/x)(\xi) \sim \text{sgn}(\xi)$ is bounded. Now consider function
$$f_m(x) = \frac{\log^m|x|}{x}.$$
Can we show that $|\mathcal{F}(f_m)(\xi)| \lesssim \log^m |\xi|$? I feel we may use the Fourier transform of $\log|x|$ to get this estimate but I don't know how to carry out the details.
Answer: In fact, the Fourier transform of (the principal-value integral of) $(\log |x|)^m/x$ is a constant multiple of $\mathrm{sgn}(x)\cdot (\log |x|)^m$, plus lower order terms of the form $\mathrm{sgn}(x)\cdot (\log |x|)^k$ with $0\le k<m$.
To see this, consider the family $\mathrm{sgn}(x)/|x|^s$ of tempered distributions, with $x\in\mathbb C$, initially for $\Re(s)<1$, and then by meromorphic continuation. These are odd (in the sense of parity), and homogeneous of degree $s$ (with suitable normalization of "degree"). By general properties of Fourier transforms, the Fourier transform is a constant multiple of $\mathrm{sgn}(x)/|x|^{1-s}$. Yes, for odd integer $s<0$ the function is the polynomial $x^{-s}$, and its Fourier transform is a constant multiple of an odd-order derivative of Dirac delta, which appears as a residue of the meromorphic continuation.
Let $F$ denote Fourier transform. Then
$$
F((\log |x|)^m\cdot \mathrm{sgn}(x)/|x|^{s+1})
\;=\; (-1)^m F(({\partial\over \partial s})^m \mathrm{sgn}(x)/|x|^{s+1})
\;=\; (-1)^m ({\partial\over \partial s})^m F(\mathrm{sgn}(x)/|x|^{s+1})
$$
$$
(-1)^m\cdot ({\partial\over \partial s})^m c_{s+1}\cdot (\mathrm{sgn}(x)\cdot |x|^s)
\;=\; (-1)^m\cdot \Big(c_{s+1}\cdot(\log |x|)^m+\ldots\Big)\cdot \mathrm{sgn}(x)\cdot |x|^s
$$
where $c_{s+1}$ is the constant arising in the Fourier transform. It can be determined by integrating against $xe^{-\pi x^2}$, which is multiplied by $-i$ under Fourier transform.
Evaluating at $s=0$ give
$$
F((\log |x|)^m/x) \;=\; \Big((-1)^m\cdot c_1\cdot (\log |x|)^m+\ldots\Big)\cdot \mathrm(sgn)(x)
$$
EDIT: To treat the Heaviside (=step) function $H$, multiplied by integer powers of $\log|x|$, it is perhaps clearest to break it into odd and even parts, since the family $1/|x|^s$ behaves differently than the family $\mathrm{sgn}x/|x|^s$. Certainly $2\cdot H=1+\mathrm{sgn}$. Namely, the family $\mathrm{sgn}/|x|^s$ has its first pole at $s=-2$ with residue (a constant multiple of) the derivative of Dirac $\delta$, while it is holomorphic at $s=1$ and gives (a constant multiple of) the principal-value integral against $1/x$. In contrast, the family $1/|x|^s$ has its first pole at $s=1$, and the residue is a constant multiple of Dirac $\delta$. Fourier transform does send $1/|x|^s$ to (a multiple of) $1/|x|^{1-s}$, as Fourier transform sends $\mathrm{sgn}x/|x|^s$ to a multiple of $\mathrm{sgm}x/|x|^{1-s}$. Differentiating with respect to the parameter $s$ achieves the same outcomes (and is completely justifiable via some standard devices using Gelfand-Pettis integrals and Schwartz-Grothendieck ideas about holomorphic vector-valued functions...)
Comment: Hi Professor Garrett, many thanks for the answer! I like the idea of treating $\log|x|$ using derivative of $|x|^s$ with respect to $s$.
Comment: May I ask a further question? Does this estimate hold if we multiply the original function by a Heaviside function $H(x) = \mathbf{1}_{[0, \infty)}(x)$? It seems now the case $s = 0$ is a critical case...

The Fourier transform of $\log^m|x|/x$


Prove properties of a standard n-simplex

Question: I would like to prove the following properties for the standard $n$-simplex whose vertices are $e_i$ in $\mathbb{R^{n+1}}$ and then use the properties of an affine transformation $T$ to generalize to any simplex.  Can you help me simplify the more general proof (in the answer section) and prove the existence of $T$?
Let the set $S=\left \{ a_{0}, a_{1}, a_{2}, ..., a_{n} \right \} \in \mathbb{R}^{n+1}$ be a geometrically independent set and let $\sigma$ be the simplex spanned by $S$.
Prove

The n-simplex $\sigma$ is the union of all line segments joining $a_0$ to points of the simplex $s$ spanned by $\left \{ a_{1}, a_{2}, ..., a_{n} \right \}$.  Two such line segments intersect only at $a_0$.

The $n$-simplex $\sigma$ is a compact, convex set in $\mathbb{R}^{n+1}$ which equals the convex hull of $\left \{ a_{0}, a_{1}, a_{2}, ..., a_{n} \right \}$.

Given $\sigma$, there exists a unique set of geometrically independent points (vertices) spanning $\sigma$.

The interior of $\sigma$ is convex and is open in the plane $P$; its closure is $\sigma$.  $Interior(\sigma)$ is the union of all open line segments joining $a_0$ to the points of $Interior(s)$ where $s$ is the face of $\sigma$ opposite $a_0$.
Answer:
First we show that the union of the line segments is in $\sigma$. Let $x=\left \{ \sum\limits_{i=1}^n s_ia_i | s_i \geq 0, \sum\limits_{i=1}^n s_i=1 \right \}$ be a point on the simplex spanned by $\left \{a_1,...,a_n \right \}$.  Then the line segment $\left \{t_0a_0+(1-t_0)\sum\limits_{i=1}^n s_ia_i | 0 \leq t_0 \leq 1 \right \}$ is in $\sigma$ because $t_0s_i \geq 0$ and $t_0+(1-t_0)(s_1+...+s_n)=1$.

Now we show that $\sigma$ is in the union of the line segments.
Given a point $\sum\limits_{i=0}^n t_ia_i$ in $\sigma$ with $t_0 \neq 1$, set $s_i=\frac{t_i}{1-t_0}$ for $i=1,...,n$.  This shows that every point in the simplex spanned by $a_0,...,a_n$, except $a_0$, is in the union of the line segments.  Clearly $a_0$ is also in the union, since it is in each line segment.  Therefore $\sigma$ is the union of all line segments from $a_0$ to the simplex spanned by $a_1,...,a_n$.
Furthermore, we show that two such line segments intersect only at $a_0$. Clearly two line segments from $a_0$ to the simplex spanned by $a_1,...,a_n$ do intersect at $a_0$.  Now suppose they intersect at some other point $y$.  Then the two segments must lie on the same line.  The other endpoints of the line segments lie on the simplex spanned by $a_1,...,a_n$.  But then the line must be contained in the simplex spanned by $a_1,...,a_n$.  This contradicts the fact that $a_0$ does not lie on the simplex spanned by $a_1,...,a_n$, since $\left \{a_0,a_1,...,a_n \right \}$ are geometrically independent.

We demonstrate compactness by showing that $\sigma$ is closed and bounded.  The simplex $\sigma$ is bounded since
\begin{equation}
\left \Vert \sum\limits_{i=0}^n t_ia_i \right \Vert \leq \max \left \{ t_0,...,t_n \right \} \max \left \{\|a_o\|,...,\|a_n\| \right \} \leq \max \left \{\|a_0\|,...,\|a_n\| \right \}
\end{equation}
The standard $n$-simplex is closed since it is the inverse image of $\left \{1 \right \}$ under the continuous map $\left(x_i \right) \rightarrow \sum\limits_{i}{x_i}$.

For convexity, suppose that $\left(t_0,..,t_n\right)$ and $\left(s_0,...,s_n\right)$ are two distinct $n$-tuples satisfying $t_i \geq 0$, $s_i \geq 0$, $\sum\limits_{i}{t_i}=1$ and $\sum\limits_{i}{s_i}=1$.  Then $\lambda \left(t_0,...,t_n\right) + (1-\lambda)\left(s_0,...,s_n\right)$ parametrizes a line segment between these two points for $\lambda \in \left[ 0,1 \right]$.  The corresponding curve
\begin{equation}
\lambda\sum\limits_{i=0}^n{t_ia_i}+(1-\lambda)\sum\limits_{i=0}^n{s_ia_i}=\sum\limits_{i=0}^n{(\lambda t_i + (1-\lambda) s_i) a_i}
\end{equation}
is a line segment connecting $\sum\limits_{i=0}^n{t_ia_i}$ to $\sum\limits_{i=0}^n{s_ia_i}$.  Since $t_i$ and $s_i$ are non-negative and sum to $1$, and since $\lambda \in \left[0,1\right]$, we have $\lambda t_i + (1-\lambda) s_i$ is also non-negative and sums to $1$.  So $\sigma$ is convex.
To show that $\sigma$ is the convex hull of $\left\{a_0,...,a_n\right\}$, we apply Theorem \ref{thm:convexsets} and show that $\sigma$ is the intersection of all convex sets containing $\left\{a_0,...,a_n \right\}$.  Suppose $S$ is a convex set containing $a_0,...,a_n$.  Then for every point $x=\sum\limits_{i=0}^n{t_ia_i} \in \sigma$, we can show that $x \in S$ as follows.  By convexity, since $a_0$ and $a_1$ are in $S$, we have $b_1=\frac{t_0}{t_0+t_1}a_0+\frac{t_1}{t_0+t_1}a_1$ must also be in $S$.  Therefore,
\begin{equation}
b_2=\frac{t_0+t_1}{t_0+t_1+t_2}b_1+\frac{t_2}{t_0+t_1+t_2}a_2
\end{equation}
\begin{equation}
b_2=\frac{t_0}{t_0+t_1+t_2}a_0 + \frac{t_1}{t_0+t_1+t_2}a_1 + \frac{t_2}{t_0+t_1+t_2}a_2
\end{equation}
is also in $S$.  Continuing in this manner, we find
\begin{equation}
b_n=\frac{t_0}{t_0+...+t_n}a_0 + ... + \frac{t_n}{t_0+...+t_n}a_n \in S,
\end{equation}
but $\sum\limits_{i=0}^n{t_i}=1$, so $x \in S$.  Then $\sigma$ is contained in every convex set containing $\left\{a_0,...,a_n \right\}$

We begin by showing that if  $x \in \sigma$ and $x \neq a_0,...,a_n$ then $x$ lies in some open line segment contained in $\sigma$.  Suppose $x=\sum\limits_{i=0}^n{t_ia_i}$ is not a vertex.  Then $t_i \neq 1$ for any $i$.  It follows that at least two of the $t_i$ are nonzero, say $t_0$ and $t_1$, without loss of generality.  Choose $\epsilon > 0$ such that $(t_0-\epsilon, t_0+\epsilon) \subset (0,1)$ and $(t_1-\epsilon, t_1+\epsilon) \subset (0,1)$.  Then for $t \in (-\epsilon, \epsilon)$, $(t_0+t)a_0+(t_1-t)a_1+\sum\limits_{i=2}^n{t_ia_i}$ is in $\sigma$.  Then it follows that every point in $\sigma$ which is not a vertex is on an open line segment contained in $\sigma$.

Next we'll show that the vertices are not on any open line segments contained in $\sigma$.
If any vertex, say $a_0$, were on an open segment contained in
$\sigma$, then there would exist points $x,y\in \sigma$ with $a_0 = tx+(1-t)y$.  If $x=\sum\limits_{i=0} ^n t_i a_i$ and $y=\sum\limits_{i=0}^n s_i a_i$, then this means $a_0 = \sum\limits_{i=0}^n \left( t t_i + (1-t) s_i\right) a_i$.  This violates the geometric independence of $a_0,
..., a_n$, unless $t_0=s_0=1$ and the others are zero, in which case
$x=y$.  Thus $a_0$ is not on an open line segment.

The barycentric coordinates $t_i$ are continuous functions from the plane $P$ spanned by vertices of $\sigma$ to $\mathbb{R}$. The preimage of the open interval $(0, \infty)$ under each $t_i$ is therefore open in $P$. The interior of $\sigma$ is the intersection of these finitely many open sets and therefore it is open.

The interior of $\sigma$ is convex since the convex combination $(1-t)x+ty$ of any $x,y \in Int(\sigma)$ is in $Int(\sigma)$.
\begin{equation}
(1-t)x+ty\, =\, (1-t)\sum\limits_{i=0}^nt_ia_i + t \sum\limits_{i=0}^n s_ia_i
\, =\, \sum\limits_{i=0}^n ((1-t)t_i+ t s_i)a_i
\end{equation}
and if $t_i$ and $s_i$ are positive, so is $(1-t)t_i+ t s_i$.
Since $\sigma$ is closed, the closure of $Int(\sigma)$ is a subset of
$\sigma$. On the other hand if a point $x \in Bd(\sigma)$ is not in the
closure of $Int(\sigma)$, one can construct a sequence of points
in $Int(\sigma)$ which converges to $x$.
Without loss of generality, assume that
$x= \sum\limits_{i=0}^n t_i a_i,$ and $ t_i(x) > 0$ for $0 \le i \le k$
and $ t_{k+1}(x)= ... = t_n(x)=0.$
Let $r=\min\{ t_i(x)\, \vert \, 0\le i \le k\, \}/2$ and let $x_m\, =\, \sum\limits_{i=0}^k (t_i(x) - \frac{r}{m(k+1)})a_i
+ \sum\limits_{i=k+1}^n \frac{r}{m(n-k)}$. \newline
Then $x_m \in Int(\sigma)$ and the sequence converges to $x$.
Finally, we show that $Int(\sigma)$ equals the union of open line segments
which join a vertex $a_0$ to points in the interior of the opposite
face. Let $x$ be an interior point of $\sigma$ so that $x = \sum\limits_{i=0}^{n} t_ia_i$ with $t_i > 0$ and $\sum{t_i} =1.$
Rewrite this as $x= t_0a_o + (1-t_0)
\sum\limits_{i=1}^{n} \frac{t_i}{1- t_0} a_i.$  Therefore $x$ is on an open line segment joining $a_0$ to a point on the face opposite $a_0$.
Comment: The plane $P$ does not make sense to me. Since we have already shown $\sigma$ is compact, it follows that $\sigma$ is closed. And the interior is by definition open. But nice post anyway, +1 from me.
Comment: Also, regarding the closedness part, the domain should be taken to be $(x_0,...,x_{n})\in\mathbb R^{n+1}$ with $x_i\ge 0$ for all $i=0,...,n$.


If $\mathfrak m_s$ generates $\mathfrak m_x$ and $\kappa(x)/\kappa(s)$ is finite separable, then $\Omega_{X/S,x} = 0$

Question: I'm trying to understand the various equivalent definitions of an unramified morphism of schemes.  Let $f: X \rightarrow S$ be a morphism of schemes which is locally of finite type, $x \in X$, and $s = f(x)$.  Let's say that $f$ is unramified if the stalk of $\Omega_{X/S}$ at $x$ is zero.  I want to understand the following result:

If the maximal ideal $\mathfrak m_x$ is generated by the maximal ideal $\mathcal m_s$, and if $\kappa(s) \subset \kappa(x)$ is a finite separable extension, then $f$ is unramified at $x$.

Let $k = \operatorname{Spec} \kappa(s)$, $X_s = X \times_S \operatorname{Spec} k$ be the fiber of $s$, and $p: X_s \rightarrow X$ the "projection."  We have
$$p^{\ast} (\Omega_{X/S}) = \Omega_{X_s/k}$$
And therefore
$$(\Omega_{X_s/k})_x = (\Omega_{X/S})_x \otimes_{\mathcal O_{X,x}} \mathcal O_{X_s,x} = (\Omega_{X/S})_x \otimes_{\mathcal O_{X,x}}(\mathcal O_{X,x} \otimes_{\mathcal O_{S,s}} \kappa(s)) = (\Omega_{X/S})_x \otimes_{\mathcal O_{S,s}} \kappa(s)$$
I'm trying to reduce the problem to the special case when $S$ is the spectrum of the field.  I thought I could use Nakayama's lemma to say that if we show $(\Omega_{X_s/k})_x = 0$, then $(\Omega_{X/S})_x = 0$.  But I do not know that $(\mathcal O_{X/S})_x$ is finitely generated as an $\mathcal O_{S,s}$-module.  It is only finitely generated as an $\mathcal O_{X,x}$-module.
How should I go about proving the result?  And where is the hypothesis that $\mathfrak m_s$ generates $\mathfrak m_x$ coming in?
Answer: Using Property (1) in your previous question, you can reduce your last term in the middle of the post the following case. Let me use the notation $(S,n) \subset (T,m)$, where $m \cap S= n$ and $S/n \subset T/m$ is finite and separable. Your last expression is then
$$\Omega_{(T/S)} \otimes_S S/n
 \cong \Omega_{(T\otimes_S S/n)/(S/n)},$$
where the isomorphism follows from (1). Notice that $T \otimes_S S/n \cong T/nT = T/m$ since $nT = m$. As $S/n \subset T/m$ is finitely and separable, we see that the module in question is zero.
Comment: Thank you.  So this shows that $\Omega_{T/S} \otimes_S (S/n) = 0$.  But how does this imply $\Omega_{T/S} = 0$?
Comment: You have it by the last equality after "and therefore". It implies $\Omega_{k(m)/k(n)} = 0$ because $(*) \otimes_S (S/n) =  (*) \otimes_T T \otimes_S (S/n) = (*) \otimes_T (T/m)$ so you can use nakayama.


Proof Artin-Rees lemma

Question: I'm reading the proof of the Artin-Rees lemma in Matsumura's Commutative Ring Theory, and I'm having trouble understanding the proof of the Artin-Rees lemma. The lemma states

Let $A$ be a Noetherian Ring, $M$ a finite $A$-module, $N\subseteq M$ a submodule and $I$ an ideal of $A$. Then there exist a positive integer $c$ such that for every $n>c$ we have $I^nM\cap N=I^{n-c}(I^cM\cap N)$.

Now I'm in doubt of how we get $\eta\in I^{n-c}(I^cM\cap N)$ in the last line. Why is that the case? I get the things stated in the above line, but I Don't see why thay means $\eta\in I^{n-c}(I^cM\cap N)$?

The below questions are clear to me now - thanks!
The proof states that the inclusion $\supset$ is obvious, but I don't see why that is the case?
Secondly it also states that if $I=(a_1,...,a_r)$ and $M=(\omega_1,...,\omega_s)$ then elements of $I^nM$ can be written as $\sum^s_1f_i(a)\omega_s$ where $f_i(a)=f_i(a_1,...,a_r)$ is homogenous of degree $n$ with coefficients in $A$. Why is that the case?
Answer: First, $\supset$ is obvious because $I^cM\cap N\subset I^cM$ so $$I^{n-c}(I^cM\cap N)\subset I^{n-c}(I^cM)\subset I^nM.$$ Similarly, $I^cM\cap N\subset N$ so $$I^{n-c}(I^cM\cap N)\subset I^{n-c}N\subset N.$$
Therefore, $I^{n-c}(I^cM\cap N)\subset I^nM\cap N$.
Secondly, elements of $I^n$ are of the form $f(\underline{a})=f(a_1,\ldots, a_r)$ where $f(\underline{x})$ is homogeneous of degree $n$ with coefficients in $A$.
Thirdly, it is impossible to answer this question without knowing where $\nabla$ comes from, what the $d_j$ are, and how $c$ was found.

Proof Artin-Rees lemma


Django websockets implementation

Question: I'm new to python and Django and i'm trying to implement websockets in Django.
What i do is i'm following the steps described in websockets documentation
The problem is that the server side command described has to be run in console. When i run it from console it works, but i want to run it inside the Django view asynchronously with a GET request. When i try it the server raises an exception something like this RuntimeError: There is no current event loop in thread 'Thread-2'.
To be more specific I want to use the technology to show a real time logs. For example an oracle procedure performs an insert and server pushes it to a page with websockets.
Am I on a wrong path for implementing the described or can anyone suggest a right/better solution?
I'm on django version 1.9  implemented on both Django's development server and Uwsgi and Nginx server, python  version 3.5.2 on RedHatEnterpriseServer Release:        6.7

UPDATE
The exact code from the above URL and i put it in the view.
def ws(request):

    async def time(websocket, path):
        while True:
            now = datetime.datetime.utcnow().isoformat() + 'Z'
            await websocket.send(now)
            await asyncio.sleep(random.random() * 3)

    start_server = websockets.serve(time, '192.168.4.177', 9876)

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

return render(request,"ws.html")

When the URL is handled by this view the above mentioned error occurs.
My ws.html  is the exact copy from the above mentioned websockets documentation example
Comment: Could you please show us what you tried?
Comment: @juankysmith Please see the update.
Answer: Django's request/response cycle is strictly synchronous. What you are trying to do is not possible in a normal Django view.
You might be interested in Django Channels, a project that aims to remove this limitation.
Answer: You can't really do this. I can't say why you're getting the exact errors you're getting, but a GET request to a Django view needs to return a response after some finite time, not run forever, otherwise the browser (or other parts in between like Nginx) will see the non-response as a timeout. If you want to run a websocket server, do it in a separate process outside of Django's.
There is much ongoing work to add async functionality and websockets to Django, in the form of channels -- I think the docs at http://channels.readthedocs.io/en/latest/ are the latest version of the code you can currently already use; hopefully it will be part of Django 1.10. Current version should be useable as a Django app that will allow you to make websockets in Django, but it's not as easy as your try above.
Comment: Note that Channels [will not be](https://groups.google.com/forum/#!topic/django-developers/QRd4v7OErT8) in 1.10, but will live as a separate app for the foreseeable future. That shouldn't stop you from using it, though!
Comment: After the answers i started reading and learning the concept and implementation of ``channles``. Thanks for the feedbacks

Django websockets implementation


Null Pointer Exception when trying to update SQLite table

Question: I am trying to update an item in a table. At the moment I have an activity that displays a list of contacts to the user. When they click on the contact I create a new activity which displays a form that allows the user to modify the contacts first and last name.
Every time I attempt to update the table I get a null pointer exception. Below is the error:
java.lang.NullPointerException at com.example.sqlitedemo.EditContact$1.onClick(EditContact.java:41)
This is the code the error seems to be linked to :
update.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter.updateContact(fName.getText().toString(), lName.getText().toString(), id);
            Toast.makeText(v.getContext(), "UPDATING", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(v.getContext(), MainActivity.class);
            startActivity(i);
        }
    });

this is my updateContact() method in the ContactsDBAdapter class:
public boolean updateContact(String fName, String lName, int rowId){

    ContentValues values = new ContentValues();
    values.put(COLUMN_FNAME, fName);
    values.put(COLUMN_LNAME, lName);
    Toast.makeText(context, "Contact updated", Toast.LENGTH_SHORT).show();
    return db.update(DB_TABLE, values, COLUMN_ID + "=" + rowId, null) > 0;
}

I pass the data to the edit activity via intent. I retrieve it in the following code. All the data seems to be arriving just fine as I have displayed it in the log.
Intent i = this.getIntent();
    fName.setText(i.getStringExtra("fname"));
    lName.setText(i.getStringExtra("lname"));
    id = i.getIntExtra("_id", 0);

Any ideas?
This is the stack trace:
01-15 02:21:45.053: E/AndroidRuntime(26854): FATAL EXCEPTION: main
01-15 02:21:45.053: E/AndroidRuntime(26854): java.lang.NullPointerException
01-15 02:21:45.053: E/AndroidRuntime(26854):    at com.example.sqlitedemo.EditContact$1.onClick(EditContact.java:41)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.view.View.performClick(View.java:4202)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.view.View$PerformClick.run(View.java:17340)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.os.Handler.handleCallback(Handler.java:725)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.os.Looper.loop(Looper.java:137)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at android.app.ActivityThread.main(ActivityThread.java:5039)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at java.lang.reflect.Method.invokeNative(Native Method)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at java.lang.reflect.Method.invoke(Method.java:511)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-15 02:21:45.053: E/AndroidRuntime(26854):    at dalvik.system.NativeStart.main(Native Method)

Comment: If you've logged that `fname`, `lname`, and `id` are all non-null, the only other possibility I see offhand is `adapter`.
Comment: Literally posted my answer a second before your comment came in! Thank you though, that was the issue.
Comment: Yea, noticed that. Good timing, and glad you got it fixed up.
Comment: Which is line 41?  Is it the first line of your onClick method?  If so, there are many object references on that line, any of which could be the culprit.  I suggest breaking that into multiple lines.  E.g. String s1 = fName.getText(); , ...
Answer: I solved the issue myself. It turns out the NPE was being cause because I had failed to create an instance of the Database adapter object and open the connection to the db.
By adding the following code into my onClick listener the problem was fixed:
update.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter = new ContactsDbAdapter(v.getContext());
            adapter.open();
            adapter.updateContact(fName.getText().toString(), lName.getText().toString(), id);
            Toast.makeText(v.getContext(), "UPDATING", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(v.getContext(), MainActivity.class);
            startActivity(i);
        }
    });


enumeration of subsets

Question: Good evening.
Let $\lambda>\omega$ a cardinal. We know that there is a bijection $\pi$ between $\lambda^+$ and $\lambda\times\lambda^+$. I don't understand in Remark 1 of the paper Shelah's proof of diamond of Komjath the words : "a club set of $\delta<\lambda^+$ (do we take a $C\subset\delta$ club in $\delta$ ? or ... ?)" $\pi$ is a bijection from $\delta$ onto $\lambda\times\delta$ " (why ?)
Thanks a lot.
Comment: Please add a citation of the paper you read, and link if possible!
Answer: The paper is here. The actual remark is:

If $\pi$ is a bijection from $\lambda^+$ onto $\lambda\times\lambda^+$ then for a club set of $\delta<\lambda^+$ (the restriction of) $\pi$ is a bijection from $\delta$ onto $\lambda\times\delta$.

It means that $D\triangleq\{\delta<\lambda^+:\pi\upharpoonright\delta\text{ is a bijection onto }\lambda\times\delta\}$ is a club set in $\lambda^+$. Verification that $D$ is closed is straightforward, and verification that $D$ is unbounded is almost as easy: just use the usual closing-off construction.

enumeration of subsets


Unknown error in txtview.settext in android

Question: I want to set txt of an text view from a query but I get "index -1 requested with size 1 error..Can some one help me?
    Cursor information = db.rawQuery("select id as _id,description from poet where _id="+Peot_ID_for_db,null);
    TextView poet_info=(TextView)findViewById(R.id.Poet_info);
    poet_info.setText(information.getString(information.getColumnIndex("_id")));
//  poet_info.append(information.getString(information.getColumnIndex("description")));

I searched this error but nothing found in google..I hope you can help me..
I have just one row in my table that matches with this query so I think I dint need any loop or sth like that to get all rows
Comment: [Here is a great little SQLite tutorial that I used when I started](http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/)
Answer: You haven't move the cursor to the row..It will throw that error for you
Try using this
if(information.moveToFirst())
{
do{

//Write your code here
}
while(information.moveToNext())

}

Comment: In this instance `information.moveToFirst()` and `information.moveToNext()`
Answer: Make sure you start off by using a moveTo function.
It will not get a row for you until you do.
Example:
http://developer.android.com/reference/android/database/Cursor.html#moveToNext()
Snippet:
StringBuilder sb = new StringBuilder();

while(information.moveToNext()) {
    sb.append(information.getString(information.getColumnIndex("_id"))+" ");
}

poet_info.setText(sb.toString());


How does auto Vacuum cleares non transaction table old transactions?

Question: How the Non transaction table single record update  will be vacuumed as per  auto vacuum settings it never selected single record page, but how old transaction will cleared on this table and save from wraparound.
I tried by changing all kind of settings in auto vacuum, and performed 10M transactions on other tables but this single transaction on non tx table not cleared by auto vacuum. how this transaction will be cleared ?
Comment: What is a nontransaction table?
Answer: I hope that I understand this question correctly if I assume that you are asking how a single deleted row in a table that does not receive any other data modifications will eventually get removed, thus preventing data corruption due to transaction ID wraparound.
PostgreSQL keeps track of the oldest transaction ID used in a non-frozen row of a table in the relfrozenxid column of pg_class. If that value is more than autovacuum_freeze_max_age transactions old (by default, 400 million), an anti-wraparound autovacuum run will be started that will insist on visiting all pages that are not all-frozen. That will get rid of the deleted row.


A good website builder that I can save / export as HTML? (Bootstrap?)

Question: I used wix to create a site, then I downloaded it from my browser and removed the ads, but now the embedded youtube videos dont work. I basically want to start from scratch and create a website like this, but with working embeds...
My problem is that the youtube videos are not playing in my modified wix files. I either need to get those working or start from scratch.
Thanks in advance.
Comment: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Comment: you could view the page source for that page and then copy the parts you want
Comment: The only problem is that the embeds arnt working.
Comment: Lexi, thanks for letting me know, I added the problem.
Comment: Ah, I found webflow.
Answer: Well all you need to do is, Look at the page source and find the containing the unplayable YouTube video.  Replace it with an iframe from "YouTube.com" for example YouTube image
JS-fiddle example https://jsfiddle.net/Lp3h60m0/
Comment: Thanks. Ill try it.
Comment: Would those iframes be in chace.htm (index.html)?
Comment: Wow it worked! Thank you!!!
Comment: you are very welcome my friend


Want a Excel 2007 formula to Execute my Problem

Question: I have a list of serial numbers with a prefix and then a few numbers. All serial numbers are different length of  characters, so depending on the prefix and amount of zeros, different amounts of leading zeros are added between the prefix and numbers. (ex. MSC00001, CAT0005640, MCSE0070, M0CSEP0003, MISCR01, MP002) How can I remove all leading zeros from the Serial Numbers, but keep any zeros that are part of the actual number?
I would love to create a FORMULA by using MS EXCEL 2007 that does this, as I would have to run this FORMULA on multiple workbooks.
Comment: Is there **always** at least one 0 after the letters ???
Comment: Yes sir want to remove all 0 between Character & Positive Numbers @ Gary's student
Answer: With data in A1, in B1 enter:
<code>=MID(A1,1,FIND("0",A1)-1) & --MID(A1,FIND("0",A1),99)
</code>

NOTE:
This simple formula will fail for strings like:
<code>QWERTY870
</code>
because there  no "leading zeros".
EDIT#1:
This is a more general formula:
<code>=IF(MID(A2,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A2 & "0123456789")),1)<>"0",A2,MID(A2,1,FIND("0",A2)-1) & --MID(A2,FIND("0",A2),99))
</code>
Comment: Thanks for quick reply, but a little bit problems in the formula. it is removing all the 0 from the strings ex. MCS107, MC1008 converted like MCS17 & MC18 but 0 at the end of strings are not removed Ex. MC10, MCSE110 , its kept same. I want only removing the 0 before positive numbers.
Comment: @MalayKr.Barik  See my **EDIT#1**
Comment: @MalayKr.Barik  Much practice and using Google..............Helping other people helps me to learn.
Comment: THANK U SIR U R GREAT, 2ND ONE IS WORKING EXCELLENT. U R GENIUS.....


Open Graph Protocol via HTTP response headers

Question: Is it possible to provide Open Graph Protocol (OGP) metadata in HTTP response headers (serialized or individually) instead of the the current HTTP response body implementation with HTML <meta> tags?
I understand the reasoning of avoiding content-related data in HTTP headers, but do any OGP clients read/parse OGP response header metadata instead? This could be very useful for HEAD requests for media file URLs (*.mp4, *.mkv, *.opus, etc) without requiring responses to be Content-Type: text/html.
Comment: To my knowledge, no major network supports that. Facebook has the ability to "point" from one HTML document to a different URL to fetch the meta data from there (https://developers.facebook.com/docs/sharing/webmasters/optimizing), but that's it. Nothing in terms of HTTP headers.
Comment: _"This could be very useful for HEAD requests for media file URLs (*.mp4, *.mkv, *.opus, etc) without requiring responses to be Content-Type: text/html."_ - not sure I get the point here; you would not respond to GET request for a video file with an HTML response either? Or are you asking in terms of _sharing_ the URL to a plain video file directly - instead of an HTML document, that will embed said video? [...]
Comment: [...] I don't think Facebook or other networks would _want_ links to "plain" files so much to begin with. (Can't get people to inject a tracking pixel into those, so how would they keep on sniffing on what their users are doing then, haha.)
Comment: You could try and test if Facebook accepts the `` from that pointer method, as a [`Link`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) HTTP header instead ... But I really rather doubt it will work, if they had implemented that as an alternative, I think it would be mentioned in the docs.
Answer:
but do any OGP clients read/parse OGP response header metadata instead?

To my knowledge, no major network supports that. Facebook has the ability to "point" from one HTML document to a different URL to fetch the meta data from there (https://developers.facebook.com/docs/sharing/webmasters/optimizing), but that's it. Nothing in terms of HTTP headers.

This could be very useful for HEAD requests for media file URLs (*.mp4, *.mkv, *.opus, etc) without requiring responses to be Content-Type: text/html.

Not sure I get the point here; you would not respond to a GET request for a video file with an HTML response either? Or are you asking in terms of sharing the URL to a plain video file directly - instead of an HTML document, that will embed said video? I don't think Facebook or other networks would want links to "plain" files so much to begin with. (Can't get people to inject a tracking pixel into those, so how would they keep on sniffing on what their users are doing then, haha.) –
You could try and test if Facebook accepts the <link rel="opengraph" href="{DESTINATION_URL}"/> from that pointer method, as a Link HTTP header instead ... But I really rather doubt it will work, if they had implemented that as an alternative, I think it would be mentioned in the docs.


Como saber em qual posição uma incógnita está localizada em um vetor?

Question: Exemplo:
a=c(10,9,8,7)
b<-max(a)
a[b]

Preciso saber em que posição b está localizado no vetor a,o R deve retornar 1 (que é a resposta)
Answer: Dê uma olhada na função which():
a=c(10,9,8,7)
b<-max(a)
a[b]
which(a == b)
# [1] 1

Outras opções é a função match():
match(b, a)
# [1] 1

Comment: Muito obrigado,estou no meio de um código gigantesco para um trabalho e não sabia desse comando básico! Grato!
Answer: Outra maneira de resolver é com a função which.max:
a=c(10,9,8,7)
which.max(a)
[1] 1


Filtro não funciona por causa de problema de acentuação do retorno, o que fazer?

Question: Estou trabalhando com datatables e php, de forma server side.
Venho fazendo filtros personalizados com ele, tudo funcionando ok, com uma salve exceção, as palavras que tem acentuação, não funciona no filtro.
Vamos dizer, que eu seleciono a seguinte empresa:
Gabriela e Ana informática LTDA, ele vai dizer que a tabela está vazia.
Não entendendo o erro, reparei que isso só acontecia com palavras que tinham acentuação, então eu olhei como estava o retorno.

Claramente, ficou claro o problema, porém não sei soluciona-lo
// código que faz o retorno do json
   $data = array();
    while( $row=mysql_fetch_array($rResult) ) {  // preparing an array
        $nestedData=array();

        $nestedData[] = utf8_encode($row["razao_social"]);
        $nestedData[] = utf8_encode($row["organization_name"]);
        $nestedData[] = $row["organization_type"];
        $nestedData[] = $row["edition"];
        $nestedData[] = $row["licensed_version"];
        $nestedData[] = date("d/m/Y",strtotime($row["issued_date"]));
        $nestedData[] = date("d/m/Y",strtotime($row["support_expiry_date"]));
        $nestedData[] = date("d/m/Y",strtotime($row["updates_expiry_date"]));
        $nestedData[] = $row["advanced_clients_licensed"];
        $nestedData[] = $row["users_licensed"];
        $nestedData[] = "<button class='btn btn-success'> Detalhes</button>";
        $nestedData[] = "<button class='btn btn-success'> Download</button>";
        $data[] = $nestedData;
    }

    $output = array(
        "draw" => intval($_GET['draw']),
        "recordsTotal" => $iTotal,
        "recordsFiltered" => $iFilteredTotal,
        "data" => $data
    );

    echo json_encode( $output );

// código que envia para o php fazer o tratamento dos dados
$('#btnFiltrar').on( 'click', function () {
    var dados = new Array();
    $('#frmReportLicense').find(":text:visible,:checkbox:checked,select:visible,input:checked").each(function(v) {
        dados[v] = $(this).val();
    });

    dataTable.columns().search(dados).draw();
    console.log(dados);
});

Atualização
Na minha saída coloquei:
$output = array(
    "draw" => intval($_GET['draw']),
    "recordsTotal" => $iTotal,
    "recordsFiltered" => $iFilteredTotal,
    "data" => $data
);
echo json_encode( $output, JSON_UNESCAPED_UNICODE );

Ele até começou a retornar o valor certo, só que ele não filtra.
Comment: Possíveis relacionadas, se não "quadriplicada": https://pt.stackoverflow.com/questions/65867/acentua%C3%A7%C3%A3o-no-json, https://pt.stackoverflow.com/questions/43193/d%C3%BAvida-com-charset-iso-8859-1-e-utf8, https://pt.stackoverflow.com/questions/193059/json-em-php-com-campos-existentes-imprimindo-como-null-como-resolver e  https://pt.stackoverflow.com/questions/100008/como-permitir-retorno-de-acentuação-em-json-utilizando-php.
Answer: Não sou muito experiente nesta área mas talvez dar um encodeURIComponent no valor possa resolver o problema.
Ficando então:

dados[v] = encodeURIComponent($(this).val());

Também estava com problemas com caracteres especiais e essa função resolveu o problema.
Espero que resolva seu problema :D
Comment: valeu pela dica, vou testar assim que terminar minha hora do almoço
Comment: cara, não deu certo


How to "fix" $\int_{-1}^1 \frac {dx}{x^2}$ with complex numbers?

Question: Given the following definite integral,
$$\int_{-1}^1 \frac {dx}{x^2}$$
I can see that it is an improper integral because of the asymptote at $x=0$ and I know from the graph of $\frac 1{x^2}$ that both parts on either side of the $y$-axis are identical.
Hence, computing only the part on the right of the $y$-axis I find that the integral $\int_{-1}^1 \frac {dx}{x^2}$ is divergent since $-$as expected from the graph of $\frac 1{x^2}-$ this part goes to $\infty$:
$$\lim_{\epsilon\to 0^+}\int_{0+\epsilon}^1 \frac {dx}{x^2} \;=\; \lim_{\epsilon\to 0^+}-\frac 1x \;\bigg|_{\,0+\epsilon}^1 \;=\; -1-\left(\lim_{\epsilon\to 0^+}-\frac 1{0+\epsilon}\right) \;=\; \infty\;.$$
If I intentionally overlook that and blindly compute the integral, I get the silly result
$$\int_{-1}^1 \frac {dx}{x^2} = -2\;.$$
That is, a negative value for the area under a function that is above the $x$-axis everywhere.
I was told that $\int_{-1}^1 \frac {dx}{x^2}$ can be "fixed" using imaginary numbers by a T.A. but neither of us had the time to expand on that point.
I understand complex numbers and how they work so I am left to wonder; how can I "fix" an improper integral using complex numbers?
Comment: Generally the principal value of an integral of a function of a singularity $x = c$ in the path of integration is defined as

$$\mathrm{PV} \int^b_a f(x) dx = \lim_{\epsilon \to 0^+} \left[ \int_{a}^{c-\epsilon }f(x)\,dx + \int_{c+\epsilon}^{b}f(x)\,dx\right] $$
Comment: there is a theorem that states that if $f$ is unbounded in $(a,b)$ then the integral of Riemann $\int_a^b f$ is not defined.
Answer: You are right that the integral is infinity and there isn't anything complex variables is going to do to change this. However, going to the complex numbers allows us to consider related integrals that are finite.
We can imagine the integral you wrote down as an integral over a path along the real axis in the complex plane. The function $1/z^2$ has a divergence at the origin $z=0$ and the fact that the path goes through this point is what is making the integral come out to infinity. When considering a real variable, if you're trying to get from positive to negative territory, you have no choice but to go through the origin. However in the complex plane you can move the integration path so that it "goes around" the origin.
The simplest way to do this is to shift the integration path up slightly in the imaginary direction. To that end, we consider $$ \int_{-1}^1\frac{1}{(x-i\epsilon)^2}dx$$ where $\epsilon$ is some arbitrariliy small positive integer. Now that you aren't going through any bad points, it turns out that naive use of the usual rules of integration is valid and we get $$\int_{-1}^1 \frac{1}{(x-i\epsilon)^2}dx = \left.\frac{-1}{x-i\epsilon}\right|_{-1}^1=-\frac{1}{1-i\epsilon}-\frac{1}{1+i\epsilon} = -\frac{2}{1+\epsilon^2}.$$
If you take the limit $\epsilon \to 0$ of this result you get $-2,$ your wrong answer from above. This means that we have a limit and integral that don't commute: $$ -2=\lim_{\epsilon\to0} \int_{-1}^1 \frac{1}{(x-i\epsilon)^2}dx \ne \int_{-1}^1 \lim_{\epsilon\to 0}\frac{1}{(x-i\epsilon)^2}dx=\infty.$$
So the $-2$ does seem to have a special meaning for the integral, although it is not its value. In fact, what is going on is that the integral along any complex path from $-1$ to $1$ that does not go through the origin has the value $-2$ (the reason for this is similar to the reason why conservative vector fields have path-independent integrals, if you're familiar. The antiderivative $-1/z$ is like a potential field). Seriously, the integral over any complex path is $-2$ provided it starts and ends at $-1$ and $1$, no matter what it does in between... except if it touches the origin. I should add that this isn't the case with any integrand (just like not all vector fields are conservative).
Granted this rather amazing path-independence property, it's no longer surprising that we don't see any inkling of an infinite divergence as we take $\epsilon\to 0.$ None of those lines from $-1+i\epsilon$ to $1+i\epsilon$ pass through the origin, since we have path independence, the limit is just taking the endpoints down to $-1$ and $1$ and anything can happen in the middle except touching the origin.
Going back to the real integral at hand, we have its definition as an improper integral $$ \int_{-1}^1\frac{dx}{x^2} = \lim_{a,b\to 0^+} \int_{-1}^{-b}\frac{dx}{x^2}  + \int_a^1 \frac{dx}{x^2} = \lim_{a,b\to 0^+} -2 +\frac{1}{a}+\frac{1}{b} $$
which we can see takes the form $-2+\text{divergence}$ and in this case the divergence has a well-defined limit of $\infty.$ (Contrast this to the case where you're integrating, say, $1/x$ instead of $1/x^2$ and you'll see that the divergence takes the indeterminate form $\ln(a/b)$ so the improper integral does not exist.) So the $-2$ is sort of a residual when we disregard the divergence at the origin, in accord with it being the path-independent value of the complex integral.
Others have mentioned the Cauchy principal value which is a way of handling the divergence at the origin that is a little more forgiving than the improper integral since it restricts the above limit to be symmetric (i.e. along the line $a=b$) where behavior might be well-defined. Here, for the integral of $1/x^2,$ this just turns the divergence to $\lim_{a\to0^+} 2/a$ so we still just get infinity. (But in the case of $1/x$ mentioned above, the $\ln(a/b)$ becomes zero, which means the Cauchy principal value is defined.) Even though the principal value by this definition has no direct relationship to complex variables, it comes up so much in that arena that it is effectively part of that subject, so its possible this, and not the above path shifting, is what your TA was referring to, although as we've seen it does nothing for this particular integral.
However, the principal value is quite related to the integration along a particular complex path that avoids the divergence. Instead of shifting the whole path up as before, keep the path as normal from $-1$ until you get within a distance of $\epsilon$ of the origin, and then go around the origin in a semicircle. Then continue from $\epsilon$ to $1$ along the real axis. I'll take the semicircle above the origin rather than below, though it doesn't matter.
We know from path independence that this integral needs to come out to $-2$. We can split it up into two parts: the semicircle and the pieces along the real axis. The second part has the value $$ \int_{-1}^{-\epsilon}\frac{dx}{x^2}+ \int_\epsilon^1\frac{dx}{x^2} = -2+\frac{2}{\epsilon}$$ which we see is just like the principal value, only before you take the limit $\epsilon\to0.$ The integral around the semicircle must be $-2/\epsilon$ in order for the whole integral to come out to $-2$. So we see that the divergence from the principal part and the divergence from the integral around the circle cancel out. This gives a detailed view of how path independence is preserved for this integral, even when we get as close to the divergence as possible without touching it.
Comment: This answer was very informative and went above and beyond. Absolutely brilliant! Thank you, @spaceisdarkgreen ✊
Comment: Nice answer, but I think it would be good to also explicitly show that the integral around the semicircle must be −2/.
Answer: A way to give a value to such integral is to consider a principal value:
$$\text{PV}\int_{-1}^{1}\frac{dx}{x^2}=\lim_{\varepsilon\to 0^+}\left(\int_{-1}^{-\varepsilon}\frac{dx}{x^2}+\int_{\varepsilon}^{1}\frac{dx}{x^2}\right)=\lim_{\varepsilon\to 0^+} 2\left(-1+\frac{1}{\varepsilon}\right)=+\infty. $$
In general, you may "integrate through singularities" by deforming the integration path, avoiding the singularities through arcs of circles with radius $\varepsilon$, then considering the limit as $\varepsilon\to 0^+$.
For instance $\text{PV}\int_{-1}^{1}\frac{dx}{x}=0$, even if $\frac{1}{x}$ is not integrable over $(-1,1)$, strictly speaking.
Comment: Thank you very much for taking the time to answer. If I'm not mistaken you are speaking of Cauchy principal values and this is beyond the scope of my understanding at the moment, although I intend to get there soon, I was hoping that there was a possibly slightly more elementary explanation that I could understand at my level.
Answer: Denote the path  $\Gamma$ on the real line with a deformed contour that approaches zero around the origin

Consider the following function
$$f(z) = \frac{1}{z^2}$$
Now to integrate
$$\int_{\Gamma} \frac{dz}{z^2} = \lim_{\varepsilon\to 0^+}\left(\int_{-1}^{-\varepsilon}\frac{dx}{x^2}+\int_{\varepsilon}^{1}\frac{dx}{x^2} +\int_{C_{\varepsilon}} \frac{dz}{z^2}\,dz\right)$$
Note that
$$\int_{C_{\varepsilon}} \frac{dz}{z^2}\,dz =-i \frac{1}{\varepsilon}\int^{\pi}_0 \frac{e^{i\theta}}{e^{2i\theta}} d \theta = -\frac{2}{\varepsilon} $$
This can be simplified to the following using the princpal value
$$\int_{\Gamma} \frac{dz}{z^2} = \lim_{\varepsilon\to 0^+}\left(-2+\frac{2}{\varepsilon}-\frac{2}{\varepsilon}\right) = -2$$
EDIT:
I made a mistake in evaluating the limit around the semi-circle.
Comment: @Phyllotactic, I know that might look Greek to you but I thought a concrete analysis is important here. Actually the Principal value is an important ingredient in solving real integrals by contour integration.
Comment: To my own surprise, I can follow your explanation (although I really can not pretend to understand it fully yet) I think I see the point. In any case, I prefer rigor much more than simplicity, it may require more work to reach substantial understanding on my part but it is generally worth while in the long run. Thank you for taking the time to answer!
Comment: @Phyllotactic, It makes sense to deform the integral around the singularity at $x = 0$ in order to evaluate the integral on that path.
Answer: The function $f(z) = 1/z^2$ has anti-derivative $F(z) = -1/z$ everywhere in the complex plane except $z=0$.  If $\gamma$ is any contour in the complex plane that goes from $-1$ to $1$ and avoids $0$, then
$$
\int_\gamma f(z)\,dz = F(1) - F(-1)= -2.
$$
So of course we say
$$
\int_{-1}^1 \frac{dz}{z^2} = -2 .
$$
Most contour integrals are not independent of the path, and then you need to say more to specify what you mean by integral from $a$ to $b$.  For example,
$$
\int_{-1}^1 \frac{dz}{z}
$$
is nonsense, because the answer differs, depending on which contour going form $-1$ to $1$ you choose.
Answer: When you first looked at an integral like $\int_{-1}^{1}dx/x^2$, your instinct was to apply the fundamental theorem of calculus, and evaluate $[-1/x]|_{-1}^1$. This answer was clearly wrong, but why? Why does having a singularity in between screw up the fundamental theorem of calculus?
Well, you might have the intuition for the fundamental theorem of calculus as having to do with, e.g. a disk expanding outwards, and the derivative of the area being the circumference -- so with some $dr$ added to the radius, $2\pi r\cdot dr$ is added to the area. And with a lot of $dr$'s getting added, the total addition to the circumference -- the integral of $2\pi r$ across the total length of $dr$'s that got added -- is the difference in area over the expansion.

But you might imagine a set-up where there's a singularity somewhere in the expansion, so the area suddenly blows up to infinity somewhere in between the expansion, then starts back from 0 1. Something's not quite wrong here. Our intuition just broke -- the actual amount of area that got added isn't the same as the total area change here.
Like in our exercise above, let's look at the antiderivative of $1/x^2$ between -1 and 1. And for comparison, we'll keep another function -- a normal, continuous function -- and its antiderivative.

And that's the fundamental problem here -- the integral is taking a different path (and if you wrapped the xy-plane around a sphere, you'd actually be able to visualise this path as going all the way to infinity then coming back from behind) from the $F(b)-F(a)$ calculation. $F(b)-F(a)$ is -2, but the path taken by the integral is in fact, $\infty-2$.
On the real line, there's no other path you can take (besides going to infinity and coming back) on which the integral is valid. But if you could just budge the path a bit "out" of the xy-plane, it would be valid, because you wouldn't be going to infinity -- just a really high number. An example way of doing this is to use complex numbers, since the added dimension allows you to draw the path between -1 and 1 a little out of the plane, and take the limit as this "little out" approaches 0. As an example, you can look at the integral:
$$\int_{-1}^1 \frac1{x^2+\epsilon}dx$$
(Explain why this integral may be interpreted as using the complex plane.)
In fact, it is quite natural to use the complex numbers as a way to "poke out" of the real line, since "integrals are done along curves, not between limits" is a central insight from complex calculus.
1 obviously, to be clear on this, we'll need to introduce some concept of time/a parameterisation t, and differentiate with respect to it instead, and claim that there is a singularity in $r(t)$.
Answer: When we are speaking about the function $f(x)=\frac1{x^2}$ we can mean two different things:

$\,f_1(x)={\begin{cases}0,&{\mbox{if }}x=0\\\frac1{x^2},&{\mbox{otherwise}}\end{cases}}$

We consider $f_2(x)$ as a holomorphic function.

If we integrate the first case, we get the principal value and it will be infinite:
$$PV\int_{-1}^1\frac{dx}{x^2}=\infty$$
If we integrate the second case, we will get the Hadamard finite part and it will be $-2$:
$$\operatorname{f.p.}\int_{-1}^1\frac{dx}{x^2}=-2$$
Now, what happens? I will try to explain in simple language.
If we take the first case, the integral $\int_{-\infty}^\infty f_1(x)dx$ is equal to $\int_{-\infty}^\infty 1 dx = 2\pi\delta(0)$ formally (or germ of $\frac2x$ at $x\to 0^+$) which can be seen from the Laplace transform. This integral has the regularized value of $0$.
Since $\int_1^\infty \frac1{x^2} dx=1$, the integral $\int_{-1}^1 f_1(x)dx$ has the regularized value $-2$. We can write it formally as $2\pi\delta(0)-2$.
Lets now consider the second case.
Here, the function has singularity at zero... and that singularity behaves in such a way as if it was infinitely negative, so it balances out the other parts of the function:
$\int_{-\infty}^\infty f_2(x)dx=0$
This is analogous to the imaginary jump the logarithmic function has at zero, except in this case the jump is infinite (and not imaginary).
So, $\int_{-1}^1 f_2(x)dx=-2$.
This, second case is used in tables of Fourier transforms, for instance.


Show that 3^(n-1) is greater than or equal to n^2 by mathematical induction

Question: Show that $ n^2 \leq 3^{n-1} $ by mathematical induction.
I set my base case as $n = 1$, and got that $1 \leq 1$.
I assume $n = k$.
Then my inductive hypothesis is $ k^2 \leq 3^{k-1} $.
So when I check my claim I did: $(k+1)^2 \leq 3^{(k+1)-1}$. But I get lost after this.
Comment: The second inequality is what you need to derive from the first. Start by multiplying each side of the inequality by $3$
Answer: You're on the right track. Again, let's assume $n=k$ for some natural number $k\geq 2$. By our inductive hypothesis, $3^{k-1}\geq k^2,$ or equivalently, $3^k\geq 3k^2.$ From here, we see that
$$ \begin{align}
(k+1)^2 &= k^2+2k+1 \\\
 &\leq k^2+k^2+k^2 \\\
 &=3k^2\leq 3^k.
\end{align} $$
This closes induction.


I need to display the post value in drupal

Question: $query = $this->database->select('users_field_data', 'u');
$query->innerJoin(
  'group_content_field_data',
  'gc',
  "gc.entity_id = u.uid"
);

$query->leftJoin(
  'opigno_learning_path_achievements',
  'a',
  'a.uid = u.uid'
);

echo $status = \Drupal::request()->query->get('status');

    $query->condition('u.status',$status);

I have tried with this line after selecting on the dropdown and then click on the submit button but it is not working.
Answer: As stated in the docs, \Drupal::request()->query with get the query parameters, to get the post parameters use \Drupal::request()->request.
ie. change.
\Drupal::request()->query->get('status');
to
\Drupal::request()->request->get('status');


Font-Awesome issue: how to remove menu-link text from a menu item with font-awesome icon?

Question: I installed the module Font awesome icons (with it's library) & the module Menu attributes; I've configured them, and now have a working font-icon in my main menu.
The problem is that instead of the desired icon, there is a combination of icon&Text (img1), and I need only an icon to appear... If there was an option to delete the text I would do that, But I haven't seen such an option - The menu-link text seems to be mandatory (img2).
I though of the css command text-indent: 200px to remove the text but the font itself is also text... Any ideas how to safely remove the text without removing the icon? Thx,
Answer: In this case you're better off using a background image. Save yourself the hassle.
.menulink{
  Width: 25px;
  Height: 0;
  Padding-top: 25px; /* height of image */
  Overflow: hidden;
  Background: url(images/home-25x25.png) 0 0 no-repeat;
}

Comment: I used one at the past and than I thought to myself to try font-awesome, but indeed a background image is simpler, though both take so much time to handle, so I'll just write a text there until (maybe in drupal 8) there will be a more efficient solution. Thanks.


How to embed high quality video with new YouTube iframe style code

Question: I am using youtubes new iframe code to embed video but the videos seem to be lower quality than if I watch them on youtube. Is there a way to embed the high quality video?
My code at the moment is

Answer: &vq=hd720 or &vq=hd1080 did the trick where all else failed
Comment: @AdamTomat and it did :)
Comment: Doesn't seem to work anymore, but `quality=high` made it play at 720p for me.
Comment: Still works, although by the sounds of it youtube are constantly changing the URL parameters they accept so wouldn't be surprised if this stops working at some point in the future.
Comment: Nice, I tried this, and it did, in fact, force the proper quality. This is great.
Answer: The following code did the trick for me:

Answer: Try this for specific quality of video..
144p : &vq=tiny
240p : &vq=small
360p : &vq=medium
480p : &vq=large
720p : &vq=hd720
example :

Answer: Also, it seems that YouTube now automatically serves up the quality that it thinks is optimized for the size of the embed, for iframe and AS3, regardless of whether or not the HD parameter is set.
See this post, and this for more information.
UPDATE: See Jason Renaud's answer for a good method that allows explicitly forcing the quality type. I tried it with an HTML5-embedded player, and it worked as expected.
Answer: It seems that the answer changes with time.
To look at the meta of what is going on, it seems that there are two generalities to the desired effect.
1) You can try and 'hack' the iframe code itself.
2) You can try and create a container to trick the iframe into thinking it should display HD.
Let's do both.
[ SPECIFIC IFRAME CODE]
You can possibly edit the typical embed youtube iframe link using current standards. I would recommend using a base size that would demand that size anyways and proceeding with step two to resize it.
Look up a current listing such as the one on h3xed to see the way youtube calls the files when embedded.
Of note, I didn't find the following code anywhere, I discovered it. I need to call videos that are 720. I was looking for the answer to this question and when viewing the file I noted that it said 720p60 as the actual youtube setting.
So I altered what seems to have worked before and sure enough...

worked.
Note that essentially I added ?rel=0&vq=hd720p60
And made the iframe size large enough to demand hd.
[ CREATING A CONTAINER ]
This works because you are asking youtube for a higher quality video and then going behind it's back and resizing it to fit the space you desire. Although you directly ask how to embed, I'm assuming you're asking to embed whenever and wherever you want -  not being restricted to giant videos on page for high quality files.
A simple responsive container works well since iframes are made to be controlled through CSS. Using code similar to that found on thenewcode's Force-Embedded-Youtube-Videos-To-Play-In-HD article we create a code that restricts the aspect ratio to a limited size.
.responsive-container {
    position: relative;
    padding-bottom: 53.25%;
    padding-top: 30px;
    height: 0;
    overflow: hidden;
}
.responsive-container,
    .responsive-container iframe {
    max-width: 1280px;
    max-height: 720px;
}
.responsive-container iframe {
    position: absolute;
    top: 0; left: 0;
    width: 100%;
    height: 100%;
}

*Of note: 'Legacy' code of &fmt=35, &fmt=22, or &fmt=37 works at this point for video links. The youtube video opens up at this specific quality.
Also note that you also have to notice a difference in tdl between youtube videos and embedded videos. They are (from my experience) not cross compatible. * (youtube.com/embeded... VS youtu.be/...)
Answer: Oh I've found it now you have to put ?vq=hd720 on the end of the url like so:


How to know if your sms filter extension is enable in iOS settings?

Question: When we add an extension to our application for example by filtering SMS
Add extension:

After launching our application on the device (hereinafter referred to as the host app), we need to activate our extension in the iOS settings in the message section:
Enable extension:

How in the host app to know the status of the extension, is it active in the settings or not?
I need to know the state in order to ask the user to activate the extension or not to ask the user to activate the extension, and instead show other content in the host app
Comment: Looking for the same kind of API to test. It is really difficult to test the development.
Answer: Unfortunately,There is no API to check SMS filter extension is enabled in containing app or not.
Comment: But for call extension iOS has API
Answer: Apple doesn't allow it and I don't think they will do it even in the future.
Here is what they say in the IdentityLookup documentation

Also for privacy reasons, your app extension cannot write data to containers shared with the containing app.


Deseriliaze JSON object

Question: I am trying to deserialize JSON file but I am getting null values after deserialization. I am using Newtonsoft.Json. Could you please let me know if I am doing right? appreciate any help.
static void Main(string[] args)
{
    using (StreamReader r = new StreamReader("json4.json"))
    {
        string json = r.ReadToEnd();
        var items = JsonConvert.DeserializeObject<RootObject>(json);
    }
}

JSON file
{"$pArray": {
  "Items":[{
     "c_date": "13-JAN-2016",
     "c_summary": "test",
     "ItemDetails":[        {
       "name1": "TESTFN",
       "name2": "TESTLASTNAME"
      },
     ]}
]}}

My RootObject class:
public class RootObject
{
    public Items items { get; set; }
}

Items class:
public class Items
{
    public string c_date { get; set; }
    public string c_summary { get; set; }
    public List<ItemDetails> itemDetails{ get; set; }
}
public class ItemDetails
{
    public string name1 { get; set; }
    public string name2 { get; set; }
}

Answer: A couple of mistakes:

Your property name under RootObject should be Items instead of items
Its type should be a collection
In your JSON you have an extra level of the $pArray and only then the RootObject

All together:
public class RootObject
{
    public IEnumerable<Items> Items { get; set; }
}

See that JSON format is:
{"Items":[{
     "c_date": "13-JAN-2016",
     "c_summary": "test",
     "ItemDetails":[        {
       "name1": "TESTFN",
       "name2": "TESTLASTNAME"
      },
     ]}
]}

If you do not have access to change the JSON format or need that extra depth then add another object and nest the RootObject in it. Then if for the pArray look at the JsonPropertyAttribute:
public class PArray
{
    public IEnumerable<Items> Items { get; set; }
}

public class RootObject
{
    [JsonProperty(PropertyName = "$pArray")]
    public PArray Root { get; set; }
}

Comment: This assumes he has access to change the json that is being serialized, if he's calling it RootObject, and he's serializing with something called `$pArray`, I would assume he doesn't control it.
Answer: Your root object contains a $pArray, it doesn't contain a list of items. However, $pArray is not a valid name.
void Main()
{
    using (FileStream fs = new FileStream(@"D:\t.txt", FileMode.Open))
    {
        using (StreamReader reader = new StreamReader(fs))
        {
            string line = reader.ReadToEnd();

            JsonConvert.DeserializeObject<RootObject>(line).Dump();
        }
    }
}

public class ItemDetail
{
    public string name1 { get; set; }
    public string name2 { get; set; }
}

public class Item
{
    public string c_date { get; set; }
    public string c_summary { get; set; }
    public List<ItemDetail> ItemDetails { get; set; }
}

public class PArray
{
    public List<Item> Items { get; set; }
}

public class RootObject
{
    [JsonProperty(PropertyName = "$pArray")]
    public PArray RootNode { get; set; }
}

is a more correct example, assuming you can't change the $pArray
Comment: I couldn't get this working. I am getting error message here: public PArray PArray { get; set; }

Deseriliaze JSON object


Frama-Clang: Invalid integer constant

Question: While working with Frama-Clang, I ran into a problem.
The following code shows the problem broken down to the minimum:
<code>const long long value = -1;

int main(){
    return 0;
}
</code>
Running the Frama-C (Frama-Clang) analysis leads to the following output.
<code>> frama-c invalid_integer.cpp
[kernel] Parsing invalid_integer.cpp (external front-end)
Now output intermediate result
[kernel] invalid_integer.cpp:3: Failure: Invalid integer constant: -1
[kernel] User Error: stopping on file "invalid_integer.cpp" that has errors.
[kernel] Frama-C aborted: invalid user input.
</code>
There are several ways to work around this error.

works if value is type short or int, fails for long and long long
works without the const keyword
works if the variable value is defined inside the main function instead of global definition

Where could this error come from and can it be solved?
Comment: Yes i am using Frama-Clang. In case that the Frama-Clang plugin is installed it is automatically used by Frama-C. Frama-C identifies the C++ file suffix and runs the Frama-Clang analysis.
Comment: `frama-c` amd `frama-clang` are two different things.  Your command use `frama-c`, is that an alias for `frama-clang` or are you actually using `frama-c`?
Comment: Does it work with `const long long value = -1LL`?
Answer: The error comes from a miscommunication between Frama-Clang and the Frama-C kernel itsef. Specifically, in the case of initializers of global integer variables, Frama-Clang neglects to convert a negative constant into the application of unary minus to a positive integer, which is what the kernel is expecting at this point. I've taken the liberty to open an issue on Frama-Clang's BTS.
Comment: Okay, I see. Thank you for your explanation and for opening the issue.

Frama-Clang: Invalid integer constant


When a solvable group is supersolvable?

Question: I am thinking about the following question:
We know if group $G$ has a normal subgroup such that $N$ and $G/N$ are solvable, then $G$ is solvable. But this is not true for the supersolvable groups.
Question: If $G$ is a solvable group with normal subgroup $N$ such that $N$ and $G/N$ are supersolvable, then $G$ is supersolvable. Is it true? or Is there any counterexample?
If $G/N$ is a small group such as the symmetric group of degree $3$, then it can be true.
Comment: @Dietrich Burde: Ok, Thanks. The post was not found in my search.
Answer: Let $G=A_4$ and $N=V_4$, the Kleinian $4$-group (it is the only nontrivial, proper normal subgroup of $A_4$). Then $N$ and $G/N=A_4/V_4\cong C_3$ are supersolvable, but $A_4$ is not supersolvable. In fact, $A_4$ is the smallest example of a finite non-supersolvable group.
On the other hand, there are conditions, so that the supersolvability of $N$, $G/N$ implies that $G$ is supersolvable. For example, if $N$ is cyclic.
Reference: Let $ G $ be a group and $ N \lhd G $. Why is $G $ supersoluble if $ N $ is cyclic and $ G/N $ is supersoluble?

When a solvable group is supersolvable?


How to send confirmation messages between clients - PeerJS

Question: I am using PeerJS to make audio calls between clients and it works. I am showing a Dialog to the user who is receiving a call with two buttons (Answer, and Decline). As shown below:
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  peer.on('call', function(call) {
   // sweetAlert("BINGO")

   bootbox.dialog({
     className: "modal-danger nonumpad",
     closeButton: false,
     animate: true,
     title: 'Call Recieved',
     message: "Accept or Decline",
     onEscape: null,
     buttons: {
      pickup: {
       label: " Answer",
       className: "btn-warning btn-lg pull-left",
       callback: function(){
       return false
      }
    },
    hangup: {
      label: " Decline",
      className: "btn-warning btn-lg pull-left",
      callback: function(){
        return false;
      }
    }
  }
});

});

My question here is, how can I send the action to the other user (who is making the call)?
The reason is because I want to show timer once the receiver press on "Answer" or show dialog to inform the caller that the receiver has pressed decline
Answer: From the PeerJS documentation:

Data connections
Connect
var conn = peer.connect('another-peers-id');
conn.on('open', function(){
  conn.send('hi!');
});

Receive
peer.on('connection', function(conn) {
  conn.on('data', function(data){
    // Will print 'hi!'
    console.log(data);
  });
});

You can get the id of the peer making the call via call.peer and then open a data connection to send a message ('accept', 'decline', etc) to the caller


How to publish a typescript package for both node and react

Question: I have an authentication library in typescript that I have published to npm and want to be able to use it for both node projects and react projects (that are created using create-react-app).
If I'm correct the packages that are published on npm will work in apps that are created using create-react-app since the bundling in create-react-app will do the magic to bundle the stuff correctly, however when I install and import my published library in react one of my dependencies won't load correctly.
It is interesting that the other dependencies work well, only this dependency is not being loaded correctly. Everything works in Node projects and the issue seems to only happen for React.
When I debug in the debugger I see the value of the imported dependency that is not loaded correctly
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsSigner = void 0;
const util_1 = require("dependency with issue");

is set to a path  "util_1: /static/media/index.325f9bf6594ebb34640d.cjs" while the other dependencies are correctly assigned with an object.
The interesting thing is that when I install/import the dependency package that has issues, directly in the react app it loads correctly.
I'm wondering if there is anything that needs to be set in my package before it is published to make it work for both node and create-react-app projects?! Or the published packages are supposed to work for both type of projects?!
Comment: If your code has nothing to do with react directly, and doesn't call anything only available in node, or only in the browser, then it should work fine without any special considerations. What does the `package.json` look like for this package? How are the depedencies declared?
Comment: Are you sure that package is compatible with browser environments? Not all packages are. Perhaps it imports something that is only available in node.js.
Comment: I believe it should be compatible since when I install that package (@polkadot/util-crypto) directly in my create-react-app it works fine, the issue only happens when it is loaded through my own published package.
Answer: The issue turned out to be due to the upstream dependency having two different published modules for different module systems using "exports" settings in package.json:
"exports": {
    ".": {
      "require": "./index.cjs",
      "default": "./index.js"
    }
}

the exports setting is a de facto package.json setting that is used by webpack to decide which exported module should be used.
my published package was compiled by typescript to publish CommonJs modules. So typescript would compile my code to use "require()" to import dependency modules so based on the specified exports setting in the upstream dependency, webpack (which is used by create-react-app) would package the ./index.cjs file from the upstream dependency in my react-app bundle! That's why I was seeing:

When I debug in the debugger I see the value of the imported
dependency that is not loaded correctly
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsSigner = void 0; const util_1 = require("dependency with
issue");

is set to a path "util_1:
/static/media/index.325f9bf6594ebb34640d.cjs" while the other
dependencies are correctly assigned with an object.

The solution:
I needed to set typescript to build both cjs and ems modules for my lib by adding build scripts for both formats in my package.json
scripts": {
    "build": "yarn build:ems && yarn build:cjs",
    "build:cjs": "tsc --module commonjs --outDir dist/cjs",
    "build:ems": "tsc --module esnext --outDir dist/ems",
  },

The above settings builds my typescripts in 2 different module formats

in commonJs module and saves the output in  dist/cjs
in esnext module and saves the output in  dist/ems

I also needed to add exports to my package.json to let webpack know which module should be loaded for which module systems:
"exports": {
    ".": {
      "require": "./dist/cjs/index.js",
      "default": "./dist/ems/index.js"
    }
  }

The above exports setting tells webpack to load ./dist/cjs/index.js when my package is imported using require(), and load ./dist/ems/index.js in other cases.


Using the unification algorithm to determine whether pairs of formulas are unifiable

Question: I would like to use the unification algorithm to determine whether or not the following pairs of formulas are unifiable, and if so, find a most general unifier, showing all my working. Am I doing it correctly? I have a feeling that ii) is not unifiable...
i) $G(x, y, W(x)) \quad G(J, W(z), z)$
Step 1.
$A = G(x, y, W(x)) \\
B = G(J, W(z), z) \\
t_A = x \\
t_B = J \\
mgu = [x/J]$
Step 2.
$A = G(J, y, W(J)) \\
B = G(J, W(z), z) \\
t_A = y \\
t_B = W(z) \\
mgu = [x/J][y/W(z)] = [x/J,~y/W(z)] $
Step 3.
$A = G(J, W(z), W(J)) \\
B = G(J, W(z), z) \\
t_A = W(J) \\
t_B = z \\
mgu = [x/J,~y/W(z)][W(J)/z] = [x/J,~y/W(z),~W(J)/z]$
Step 4.
$A = G(J, W(z), z) \\
B = G(J, W(z), z) \\
⇒ unifiable, ~ mgu = [x/J,~y/W(z),~W(J)/z]$
ii) $G(x, W(x), x) \quad G(J, y, W(y))$
Step 1.
$A = G(x, W(x), x) \\
B = G(J, y, W(y)) \\
t_A = x \\
t_B = J \\
mgu = [x/J]$
Step 2.
$A = G(J, W(J), J) \\
B = G(J, y, W(y)) \\
t_A = W(J) \\
t_B = y \\
mgu = [x/J][W(J)/y] = [x/J,~W(J)/y] $
Step 3.
$A = G(J, y, J) \\
B = G(J, y, W(y)) \\
t_A = W(J) \\
t_B = y \\
mgu = [x/J,~W(J)/y][J/W(y)] = [x/J,~W(J)/y,~J/W(y)]$
Step 4.
$A = G(J, y, W(y)) \\
B = G(J, y, W(y)) \\
⇒ unifiable, ~ mgu = [x/J,~W(J)/y,~J/W(y)]$
Answer: (i) does unify. (ii) fails to unify.
However, it appears you have a misunderstanding about unifiers.  A unifier is a substitution that maps variables to terms (which themselves might contain, or even just be, variables).  Your notation, particularly in your final step 4, suggests that you think you can map arbitrary terms to arbitrary other terms.  Assuming $J$ isn't a variable, a substitution like $[J/W(y)]$ simply doesn't make any sense.  Assuming $[T/x]$ means "replace the variable $x$ with the term $T$", your mgus should always be of the form $[T_1/x_1,T_2/x_2,\dots T_n/x_n]$.
While this may not be what you were taught, I recommend (and most computer implementations of unification work this way) that you simply generate a bunch of constraints and then "solve" them rather than trying to substitute as you go.
In the first case, you get $x = J, y = W(z), z = W(x)$ from which you can readily produce the substitution $[J/x,W(W(J))/y,W(J)/z]$.  In the second case, you get $x = J, y = W(x), x = W(y)$ from which you can easily see that $J \neq W(y)$ no matter what $y$ is.  In a slight variant of (ii) where the second term is $G(x,y,W(y))$ you get $x = x, y = W(x), x = W(y)$.  This simplifies to $x = W(W(x)), y = W(W(y))$. In this case unification fails because it fails the occurs check. Substitutions that replace a variable with a term that contains the variable as a (strict) subterm are disallowed.
Comment: Could you explain how you get $W(W(J))/y$ in more detail :)
Comment: As a human you just apply basic equational reasoning. For a computer, there are a variety of different ways of handling constraint generation and simplification and these lead to different implementations of unification. An inefficient approach is $x=J,y=W(z),z=W(x)$ produces the substitution $[J/x,W(z)/y,W(x)/z]$ call it $\sigma$. You can then iterate $\sigma$ until it reaches a fixed point, i.e. $\sigma\circ\sigma^n=\sigma^n$. To guarantee a fixed point will be reached you need to disallow substitutions that fail the occurs check and order variables to avoid cases like $[x/y,y/x]$.


How to print a page in drupal 7?

Question: I have a module for drupal 7 that generate reports. I want to print one of the reports with out drupal menus and footer. I want the report to be displayed on second page alone with view descriptive data? Please Help.
Comment: are you using any contributed module or using custom code to create report?
Answer: You might want to check out the Print Module.  I've used it successfully for print media in the past.
Comment: thanks for replay.
but I want to integrate print functionality into my module rather than using other module
Comment: Lester suggested a right module. This module will provide you to add your custom page template for your print layout. You can use it with your modules as well. Using this module if any path is prefixed with "print/" it will render content in print layout. print/mymodulepage OR print/node/1 etc.
Answer: You should ask yourself if you really need/want to display the content on a separate page before printing it.
Providing a simple print style sheet in your theme with display: none for the regions that don't make sense when printed will work for all the pages on your site without the overhead of print module's approach
People that like to print things know their browser can print and will try it anyway whether you give them a print link or not.
Answer: You could use the Print Module. This module actually fixed the problem and performs the required functionality.

How to print a page in drupal 7?