Secure Login not Working

Question: I'm running drupal 7 with the secure login module and login toboggan. After installing it, going to http://site.com I see the usual site, with the login button.
The login form action has not changed, it remains a POST to /node?destination=node. Sure enough, if I login there my password is sent in the clear with a POST to http://site.com/node?destination=node
Any ideas on how I might start debugging this? The securelogin.module seems really straightforward, just some hooks. Is there a logging statement I can add there to see if these hooks are being called?
update I also noticed this other problem (probably the same cause).
Sometimes when I start a fresh browser and go to http://site.com I get 302's to https://site.com automatically. If I then log in the POST goes over https (good!) but I then get 302'd back to http://site.com, where I appear NOT logged in. If I just change the URL to https://site.com I can see that I am indeed logged in.
I am very confused.
Answer: To force SSL for login, admin, node editing etc, I use http://drupal.org/project/securepages - also has has configuration options to force plain HTTP when browsing the site as well (which can save you load).
Answer: Ok, the problem seems to have been that I had $base_url = 'http://site.com' set in my settings.php.
This resulted in that, after a successful login on https, the user got 302'd back to an http: page which showed him as not logged in. By commenting out the base_url the re-direct now sends the user back to an https and shows him logged in. So, it all seems to work.

Secure Login not Working


Why does dpm() sometimes fail and krumo() works

Question: They both dump variables in the same format & style. From some articles or documentation that I'd read, it seems krumo() calls dpm().
The problem is that sometimes I call dpm($var) and nothing happens, but krumo($var) on the same script works fine. I think I'd had the same problem in the reverse circumstance(ie: krumo($var) does not work, dpm($var) works). Why is this so? Is there some structure that needs to be available on the particular page or script that either of these functions uses for it's display? Maybe some region or block?
Answer: typically inline php code such as a views php field value, or a Display Suite code field for example ... doesn't always run in a page's context.
When you have a field expecting <?php  /* some code here */ ?> this is run an Anonymous php function and returns a value.
In my experience dpm() doesnt always work in these cases.
Another example is trying to dpm within a Cron or Queue task. These dont run in a page context either so using something like Devel's dd function can be useful.
Answer: Another problem with dpm is that if you call if from a theme function a preprocess or a template it will only work after a refresh.
That is because the place the date gets printed is already processed when calling the dpm function


Use online VM as default Gateway (Jump box)

Question: I have two Ubuntu servers:

Server 1 (IP: 192.168.10.11)
is online and connect to two network interface (internal, public)

Server 2 (IP: 192.168.10.10)
with no public access (internal)

I am trying to use server1 as a default gateway for server2, and this is what I've done:
# on online server (Jumpbox)
iptables -t nat -A POSTROUTING -s 192.168.10.10 ! -d 192.168.30.1/24 -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward

# On offline server
route add default gw 192.168.10.11

Docker is installed on both (172.17.0.0)
They can PING each other, but from server2 it is not  possible to PING  Google.
Comment: try this on jumpbox: iptables -t nat -A POSTROUTING -o public_internet_interface -j MASQUERADE
Comment: @MartynasSaint I will get error when I add the interface name _No ... by that name_
Comment: Fixed above issue but still no ping from offline VM.
Comment: try to see if the rule is hit - iptables -vL . maybe docker puts some rules that are matched first
Comment: yes it is there, ip range for docker is in different range
Answer: Debian Style (the lazy way):
edit /etc/network/interfaces
iface eth0 inet static
address  10.0.0.1
netmask  255.0.0.0
post-up   echo 1 > /proc/sys/net/ipv4/ip_forward
post-up   iptables -t nat -A POSTROUTING -s '10.0.0.0/8' -o eth0 -j MASQUERADE
post-down iptables -t nat -D POSTROUTING -s '10.0.0.0/8' -o eth0 -j MASQUERADE

The Lazy Crontab Way:
edit /etc/crontab
@reboot root "echo 1 > /proc/sys/net/ipv4/ip_forward; iptables -t nat -A POSTROUTING -s '10.0.0.0/8' -o eth0 -j MASQUERADE; iptables -t nat -D POSTROUTING -s '10.0.0.0/8' -o eth0 -j MASQUERADE"

Bash Style:
nano /root/allow_lan_nat.sh
You have to ajust the correct LAN that fits to you which might
192.168.0.0/24 (One Lan Subnet, Default Class C)
192.168.0.0/16 (all Subnets of 192.168)
172.16.0.0/16 (Default Class B)
10.0.0.0/8 (Default Class A)
#!/bin/bash
#Ajust the LAN, as above shown
MYLANIP=10.0.0.0/8

#The IFACE that has Internet.
MYINETIFACE=eth0
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s $MYLANIP -o $MYINETIFACE -j MASQUERADE
iptables -t nat -D POSTROUTING -s $MYLANIP -o $MYINETIFACE -j MASQUERADE

run bash /root/allow_lan_nat.sh
Direct answer to your question
Remind, that at i state this Answer, i dont know the Interface, so i assume ens3 s your interface that face to the internet, else update it like above
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s '192.168.10.0/24' -o ens3 -j MASQUERADE
iptables -t nat -D POSTROUTING -s '192.168.10.0/24' -o ens3 -j MASQUERADE

REMIND, ens3 must be the internet facing interface so update it to your needs.


What type of stationarity preferred during the time series analysis: strong stationary or week stationary?

Question: I was googling the answer for the above-mentioned question. I had the definition of both but I don't know which one is preferred during the analysis. So which one is recommended? Reason? Thank you!
In this blog, it mentioned that
"Note that statistics assumes that the variable examined is strong stationary (serial independent)."

Well, I got a short answer from the professor. According to him, weak stationary is the basic and it will be the same for Gaussian distributions. WHY??? And my question was which one would be more preferred. Anybody would like to elaborate a little bit:)
Comment: Strong stationarity does not imply weak stationarity because weak stationarity requires existence of a finite second moment which strong stationarity does not. Now if you restrict attention to Gaussian distributions, the second moment is finite. Thus for this class, strong and weak forms of stationarity coincide.
Answer: In statistical modelling there is not really a "preferred" type of stationarity --- we prefer whatever model fits the data well and is most justifiable in the analysis.  When conducting data analysis we fit models to the data and see which models are plausible.  Sometimes a strongly stationary model will be a plausible fit to the data and sometimes a model which is only weakly stationary will be a better fit.  Weakly stationary models are stationary up to second order (i.e., up to variance), so the only time a weakly stationary model (that is not also strongly stationary) will be necessary is when there is non-stationarity at moments of high order (skewness and above).$^\dagger$
As a practical matter, standard models for time-series analysis are usually Gaussian models (e.g., Gaussian ARMA).  Since Gaussian models are fully determined by their first two moments, there is a correspondence between strong and weak stationarity in this case --- every weakly stationary Gaussian model is also strongly stationary.$^\dagger$  If you use non-Gaussian models then it is possible to formulate models that are weakly stationary but not strongly stationary.  In some cases it is possible that the weakly stationary models might fit the data better than the strongly stationary models, but it would be unusual.

$^\dagger$ It is important to note a slight technicality here.  Weak stationary is implied by strong stationarity if the moments of the process exist up to second order.  For Gaussian models the moments exist, so strong stationarity also implies weak stationarity.
Comment: Thanks@Ben. Glad to have a more intuitive answer now. In the future, other students could also get benefit from your explanation. Thank you!


Python multiprocessing.Queue.get raises EOFError on first call

Question: I'm using python 3.7 on ubuntu 20.04 OS. My problem statement is similar to that of producer and consumer problem, where there is a pair of reader and writer processes. My reader process calls Queue.get in an infinite loop, (As per documentation, the Queue.get is blocking call until any data is put into the queue by another process).
Making this call raises EOFError.
reader.py
import multiprocessing as mp

def reader(queue):
    while True:
        try:
            data = queue.get()
        except Exception as e:
            print(f'Exception occurred: {e}')
        # Do something

queue = mp.Manager().Queue()
p = mp.Process(target=reader, args=(queue,))
p.start()
# Prepare some data to send
queue.put(some_data)
# Do my own tasks

Running This results in
    Traceback (most recent call last):
  File "/usr/src/app/src/processor.py", line 775, in classification_manager
    slot_data = classification_queue.get()
  File "<string>", line 2, in get
  File "/usr/lib/python3.7/multiprocessing/managers.py", line 819, in _callmethod
    kind, result = conn.recv()
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 250, in recv
    buf = self._recv_bytes()
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 407, in _recv_bytes
    buf = self._recv(4)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 383, in _recv
    raise EOFError
EOFError
2022-02-18 20:45:01,528 classification_1 INFO     Waiting for Data!
2022-02-18 20:45:01,528 classification_1 ERROR    BrokenPipeError
Traceback (most recent call last):
  File "/usr/src/app/src/processor.py", line 775, in classification_manager
    slot_data = classification_queue.get()
  File "<string>", line 2, in get
  File "/usr/lib/python3.7/multiprocessing/managers.py", line 818, in _callmethod
    conn.send((self._id, methodname, args, kwds))
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 404, in _send_bytes
    self._send(header + buf)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 368, in _send
    n = write(self._handle, buf)
BrokenPipeError: [Errno 32] Broken pipe

Comment: The code you show is from `reader.py`, yet the error message you show are from `processor.py`.  Are you saying your code sample generates a similar error?
Comment: Why I run your sample code I get completely different error.
Comment: Please post a working demonstration... the details matter. You'll get that error if the parent process exits while the child is still using the queue. Do you see some data processing before this error?
Comment: The parent exiting without terminating the child explains the EOFError, but not the following broken pipe error. Are you catching the EOFError and trying again?
Comment: @RufusVS the reader.py is just a demonstration that I can upload. I can't just upload the actual codebase of my repositiory as of now.
Comment: @tdelaney In my case, the parent process never exits. It's a forever running process (Just like a server). I'm catching any exception that occurs in the child process. So, for the first time I'm getting EOFError and then in every iteration I'm getting BrokenPipeError.
Comment: @BhaveshAchhada  When you provide example code, you should run the example code and post the error from the example,  so the code and error are correlated (plus doing that might have clarified the issue in your own mind.)
Answer: The threading equivalent to your code works fine:
import threading as th
from queue import Queue
from time import sleep

def reader(queue):
    while True:
        data = queue.get()
        print ("Reader saw",data)
        # Do something

queue = Queue()
p = th.Thread(target=reader, args=(queue,))
p.start()

queue.put("Expect More Data")

call_count = 0
while True:
    sleep(2)
    call_count += 1
    queue.put(call_count)

Comment: I just cannot use multi-threaded model in my application, I've some computation intensive tasks, which I have divided into several processes.
Answer: If I just elaborate your code (which isn't runnable as it stands) then there's no problem at all.
import multiprocessing as mp

def reader(queue):
    while (data := queue.get()) != 'stop':
        print(data)

def main():
    queue = mp.Manager().Queue()
    p = mp.Process(target=reader, args=(queue,))
    p.start()
    for some_data in ['Hello', 'world', 'stop']:
        queue.put(some_data)
    p.join()

if __name__ == '__main__':
    main()

Output:
Hello
world

Comment: @tdelaney If OP's process runs indefinitely then join() is irrelevant. Of course, having no (clean) way to terminate the process is bad practice IMO. Having said that, the issue is allegedly occurring during get() on the queue. What I've tried to show is that queue handling is simple and robust. OP's code (as shown) doesn't seem to have anything to do with his/her real problem
Comment: Except that's the problem, isn't it? OP doesn't have a way to exit the child process and doesn't join the subprocess in the parent. Those are the bugs. I'd say your additions are the answer.
Comment: Actually I found the problem. The parent process was killed abnormally. That's why the child process was getting the EOFError and BrokenPipeError.
Answer: I got my answer. In my case, the Linux OOM killer was killing the parent process. That's why the child process was getting this EOFError and then BrokenPipeError.
You can read about linux OOM killer here.


How to generate an arbitrary object property that's not in use?

Question: I have a bound function f:
var f = someFunction.bind(this);
Rather than passing f to a function, I save it in an object and instead pass an id to f:
var obj = {};
var nextID = Object.keys(obj).length;
obj[nextID] = f;
// pass nextID to some other function

However, I also want to delete entries at some point:
delete obj[someID]
This is a problem, because if I add some bound functions a and b and then delete a, the next id I get will be 1, and the bound function I put there will overwrite b.
What I could do is:
function getNextID() {
    var possibleID = Object.keys(obj).length;
    while (obj[possibleID])
        possibleID *= 2; // or some other mutation

    return possibleID;
}

But this feels ugly.
I tried using the bound functions as the key, but that didn't work:
obj[a] = a;
obj[b] = b;
console.log(Object.keys(obj).length); // 1

How can I get an arbitrary object property that isn't currently in use? Surely I'm overthinking this...
Answer: Wow, I should just use arrays.
var arr = [];

function f() { }
function f2() { }

var a = f.bind(this);
var b = f2.bind(this);

arr.push(a);
var id = arr.length; // 1

delete arr.id;

arr.push(b);
console.log(arr.length); // 2


Covariance Matrix with all equal entries

Question: by training a Gaussian Process Regression Model I'm finding the weird result
where the resulting covariance matrix has all the entries equal between each others.
I'm using a Gaussian kernel with additive noise as covariance function.
The calculation are all correct according to my checking...so I was thinking that what I'm trying to fit is actually white noise...
Don't know...any ideas?
Thanks
Comment: I neglected to explicitly mention that these identical elements must be non-negative.
Comment: Can you provide a small reproducible example?
Comment: If it were white noise, the covariance matrix would be diagonal: all non-diagonal elements would be zero!
If by "all the entries equal between each others" you mean that the covariance matrix is symmetric: well, that is the case for every covariance matrix.
Comment: Also, a covariance matrix with all entries equal to each other is impossible. Such a matrix would not be positive definite, as is required for the covariance matrix of Gaussian processes.
Comment: @StijnDeVuys , your statement that "a covariance matrix with all entries equal to each other is impossible" is incorrect according to my view of the world.  A matrix with all entries equal to each other is a symmetric rank one matrix, which is positive semidefinite, and hence a covariance matrix, and in one dimension is positive definite unless the entry is 0. I am not aware of any convention which disallows the covariance matrix of a Gaussian Process from being singular, and in any event, it is not disallowed according to my definition.
Comment: @Mark L. Stone: You are right, a covariance matrix is positive semidefinite, and not necessarily positive definite. But if that matrix is the result of training a Gaussian Process regression model from noisy data, is it possible that the result is a rank 1 covariance matrix? In my opinion, that is not so. In all texts on GP regression, I see the requirement that the kernel is positive definite.
Comment: Well, a singular, let alone, rank one matrix, may not be a great regression result, but in my book (not written yet, ha ha), it's valid.  How about in one dimension?  Let's say the variance = 0.  What's wrong with that?  BTW, I'm not trying to imply that the OP"s calculations aren't screwed up.
Comment: What is your $\sigma_{noise}$?
Comment: When you say all entries are the same, do you mean all the off-diagonal elements, or all elements including the diagonal?
Answer: If all elements of the covariance matrix are identical, including the diagonal, then you basically have a degenerate process. Suppose, for definiteness, that the index space is [0,1]. Then each realization of the process will be a horizontal line. The $y$ intercept of the lines will be normally distributed with mean 0 and variance $\sigma^2$, where $\sigma^2$ is the common variance/covariance entry.
If you meant to say that the covariances are equal but the diagonal repeats a different value ... then this would be consistent with the classic repeated measures design. Each realization would be white noise with the mean of the white noise varying from realization to realization.


What are exactly restricted boltzmann machines?

Question: I've been reading through some stuff related to Restricted Boltzmann Machines (RBM). By wikipedia for example I can see the graphical model is in general very similar to a standard Feed Forward Network (FFN), but on the other hand there's the training which is based on Gibbs Sampling.
What I don't get though is the difference, if there's any, between RBM and FFN, apart from the training process. The basic algorithm to train a ANN is gradient descent, but you can use in general other optimization methods, such as L-BFGS for example.
So if the difference is only the training method it doesn't seem to me they're different networks.
On the other hand some people when introduce RBM starts with probabilistic graphical models, which makes me think maybe an RBM is different from a FFN.
Can you clarify what exactly is an RBM then?
Answer: A feed forward neural network is just a function $f(x; \theta)$ of some inputs and its weights. There is a clear procedure for computing the values of each unit/layer in the network from the previous layer. You can ascribe your own interpretation for what the outputs mean (a probability value, an RL policy, a point estimate, etc) and train the model accordingly.
On the other hand, an RBM models $P(x; \theta)$. It doesn't have any outputs and can't do anything other than tell you the probability of the data given the parameters. You can't compute the value of any unobserved variables in the RBM, because they're random variables.
Comment: So what's the difference with a bayesian network then?
Comment: @user8469759 a bayes net is a directed graphical model, whereas RBMs are undirected


How to add google analytics code for onclick functions in drupal 6

Question: My requirement is that, i need to my site to be tracked when i click on categories, menus, submenus, send mail button and shopping carts. Need to add onclick function for each  tags and that onclick functions need to be tracked.
Answer: What you're looking for is the GA Event Tracking module. It allows your custom module to select web page elements (via CSS selectors), bind them to jQuery events (e.g. clicks, mouseover, etc.), and send them out to the GA Event Tracking API.


Transforming quadratic parametric curve to implicit form

Question: I have an algebraic parametric curve
$$ \mathbf{p}(t) = (x(t), y(t)) $$
where $x$ and $y$ are both polynomials of degree $\leq p$. Now, I want to find the implicit form $f(x, y) = 0$.
A document I'm reading claims without argumentation that there is always an equivalent implicit formulation of the form
$f(x, y) = 0 $, where $f$ is a polynomial of degree $\deg(f) \leq p$.
This is not obvious to me. I found some documents stating similar results. For example, in [1]:

Algebraic geometry provides us with the following key facts about algebraic curves: e.g. [2]:
Every plane parametric curve can be expressed as an implicit curve. Some, but not all, implicit curves can be expressed as parametric curves.

Unfortunately, I can't get my hands on a copy of [2].
[This question][3] considers the case of a quadratic parametric curve.
I was wondering if there is a simple proof for the statement every algebraic parametric curve on the plane can be expressed as an implicit curve. Moreover, I am curious if $x$ and $y$ being polynomials of degree $\leq p$ implies that $\deg(f) \leq p$ as well.
Since I don't know the nature of the answer, pointing me to a resource might be more appropriate.
[1]: Conversion methods between parametric and implicit curves and surfaces, Christoph M. Hoffmann, from http://graphics.stanford.edu/courses/cs348a-17-winter/Handouts/a228715.pdf
[2]: R.J. Walker, Algebraic Curves, Springer Verlag, New York, 1978.
[3]: Parabola in parametric form
Comment: Cox, Little and O'Shea _Ideals_, _varieties_ _and_ _algorithms_ 3$\S$3.
Comment: I don't think I am qualified to give an algebraic geometric answer, but maybe you can get help from gradient of level set polynomial being orthogonal to tangent of the curve. (Or maybe I am having a brain fart?)
Comment: Great idea! I am trying to work this out right now: it seems promising.
Answer: To begin with, you are dealing with the "great old theory" of elimination.
In this case, the answer is : yes, it is always possible to eliminate parameter $t$ between polynomial expressions and obtain an implicit  polynomial expression.
Let us show it on an example, with a parametric curve defined by these equations :
$$\tag{1}\begin{cases}x=t^2+t+1\\y=t^3-1\end{cases}$$
If you use a Computer Algebra System such as Mathematica, elimination process is implemented under the following form: Eliminate[{x==t^2+t+1,y==t^3-1},t] giving the following implicit equation :
$$\tag{2}x^3-3x^2-3xy-y^2=0$$
as its result.
But there is more to say. You need for this to be familiar with resultants (see remark below) (https://en.wikipedia.org/wiki/Resultant). The theorem you are looking for is the fact that the implicit equation can be obtained as the resultant of the $\color{red}{2}$nd degree polynomial $t^2+t+(1-x)$ (I was tempted to write $=0$...) and $\color{red}{3}$rd degree polynomial $t^3-(1+y)$ which the $5 \times 5$ parametric determinant (5 = $\color{red}{2+3}$):
$$d=\left|\begin{array}{ccccc}1& 1& (1-x)& 0 &0 \\
   0& 1& 1& (1-x)& 0\\
   0& 0& 1& 1& (1-x)\\
   1& 0& 0& -(1+y)& 0\\
   0& 1& 0& 0& -(1+y)\end{array}\right|=0$$
(one writes $\color{red}{3}$ times the $\color{red}{2}$nd degree polynomial, then $\color{red}{2}$ times the $\color{red}{3}$rd degree one, with a right shift for every "carriage return").
The expansion of determinant $d$ gives back (up to a certain unimportant constant factor) implicit equation (2).
This example can evidently been extended to a general case.
Remark 1: The excellent reference (Cox, Little, O'Shea "Ideals, Varieties and Algorithms") given by @Jan-Magnus Økland can be found online. See pages 155-162 devoted to Sylvester's resultant.
Remark 2: the main idea behind the concept of resultant is that it expresses a necessary and sufficient condition between parameter(s) present in coefficients of 2 equations for these equations to have at least a common root. Let us take an example : consider a quadratic polynomial $at^2+bt+c$ (with $a\ne0$) and its derivative $2at+b$. They have a common root $t_0$ which is a double root iff the following resultant is zero:
$$\delta=\left|\begin{array}{ccc}a& b& c \\
   2a& b& 0\\
   0& 2a& b\end{array}\right|=-a(b^2-4ac)$$
This value is $0$ iff $b^2-4ac=0$, which is the classical criteria for a quadratic equation to have a double root. We have thus found back the concept of discriminant by using the resultant!
Comment: I didn't understand your example the first time, but your second remark was very enlightening. Even though I don't understand why this result holds (I am still planning to read Cox, Little, and O'Shea), it is very beautiful! :)
Comment: Tom Sederberg has done work applying resultants to Bezier curves, primarily for curve-curve intersections.
Comment: The book by Tom Sederberg can be found [here](https://scholarsarchive.byu.edu/cgi/viewcontent.cgi?article=1000&context=facpub) where indeed the resultant is used in this context.
Answer: Hint Another idea based on my comment which may help. The tangent vectors along the parametric curve (using same notation as Jean Marie) will be given by
$$\left[\begin{array}{c}\frac{\partial x}{\partial t}\\\frac{\partial y}{\partial t}\end{array}\right]$$
These should be orthogonal to the gradient of the polynomial level-set you are seeking. This should give you a set of quite specific equations as the only thing remaining should be constant (quite literally the particular level you want to set your curve on).
Comment: Any f(x, y) that satisfies p'(t) · ∇f = 0 also satisfies f(x(t), y(t)) = c, so f(x, y) = c is an implicit formulation of the curve defined by p. (This reasoning is not completely correct since x, y not on the curve might also satisfy f(x, y) = c, for example when f = 0). This seems like a reasonable idea, but I was not able to work this out in practice (which does not mean the method in itself does not work).
Comment: I don't see the relationship with the problem.
Comment: @Ruben: Yes, I have not tried it myself yet, so there may be cases when it does not work.
Comment: @mathreadler I'm not arguing that there are cases where it doesn't work. I'm saying I don't see how to solve this system of equations. It is nonlinear and I don't think there is an easy algorithm one can use.


midi tracks with chords and melody

Question: I've had a decent look at the midi file format and I thought I understood, so I wrote a python script that removed midis with multiple tracks from my data set in order to have only melodies in single tracks left. I did this by checking the track number bits in the header and if the track number was higher than one.. bingo!
I am dealing with a large number of files so I checked a reasonable number of the latter removed files and they were indeed polyphonic with a melody and a chord sequence played simultaneously.
I thought that that was mission accomplished but it was not, further data cleansing meant I heard midis as part of the testing and some of my remaining midis were still polyphonic. I can't see how to strip them from the dataset because I cannot figure out what uniquely identifies them as polyphonic midis.
I hope this is clear. Please advise.
Comment: There is no part of the MIDI or GM specification that identifies whether a track is monophonic and/or contains the melody. Research has been done into identifying the melody track algorithmically, e.g. https://www.academia.edu/4998164/Melodic_track_identification_in_MIDI_files ; http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.81.3161&rep=rep1&type=pdf ; http://www.insota.com/fileadmin/publications/A-Complexity-based-Approach-to-Melody-Track-Identification-in-MIDI-Files.pdf
Answer: As per Uncle Bob's comment, the tracks in a MIDI file are not necessarily monophonic lines - they typically represent data to be played back using a single instrument voice, but each of those parts could well still be polyphonic. A solo piano piece might well be recorded as one MIDI track (as only one instrumental voice is needed to play it back), but it would typically contain many notes sounding simultaneously.
If you need to identify monophonic tracks in your MIDI files, a good starting point would be to find tracks where the notes don't actually overlap. Even this wouldn't be 100% accurate as the actual synthesizer voice is what determines what you hear, but if you are dealing with General MIDI data, you could look at the voice being used to play the track and make your judgement based on that too.
Of course you might find that some MIDI files have more than one monophonic track, and you might find that some have a monophonic track that nevertheless doesn't seem to be a 'melody'. Your job then might be to more tightly define what you mean by 'melody'.
Answer: Tracks in MIDI files are useful when you want to edit the file later, but have no meaning whatsoever on the MIDI level. It is possible to have events for multiple channels in one track (as you've seen), and to have events for the same channel in multiple tracks.
To filter out files that send note events to multiple channels, you have to parse all events in the file and to check their channel numbers.
Answer: I'm not sure if I get your question right, but in general there are two types of MIDI files.

MIDI 0
MIDI 1

MIDI 0 = all the tracks are merged into a single track
MIDI 1 = contains separate information for each track
So if you would write a score for multiple instruments in Sibelius for example and export them as a MIDI 0 file, you will get just one (track-)file. If you would import this file into any DAW, you would get only one file with all instruments merged into this file.
On the other hand, if you would export it as a MIDI 1 file and import it into your DAW, you would get a separate MIDI-track for each instrument.
This however doesn't really say anything about a monophonic or polyphonic file. If you would export a piano as MIDI 1 for example, you would still get a merged file with melody + chords, because in the end a piano (even tho it's polyphonic) is only one instrument.
So if you would want each file separate, you would have to do two piano tracks - One with melody only, one with chord only and then export it as MIDI 1. Then you would get each file separate, because it exports each track like it's a single piano.

midi tracks with chords and melody


Detect when the user has muted AVPlayer

Question: I am playing a live stream using AVPlayer and AVPlayerItem.
Is there a way to know if the user has muted/unmuted the video while playing it
Answer: You can check the isMuted value of the AVPlayer.
Documentation:
https://developer.apple.com/documentation/avfoundation/avplayer/1387544-ismuted
Comment: Yes I know the property of AVPlayer but I wanted  a way to get notified whenever user mutes/unmutes the player without keep checking this property.
Comment: are you using any standard player interfaces or a custom one?
Comment: Standard player interfaces
Comment: Ok, AVPlayer should supports KVO, I would try with them.

https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift
Comment: I already did try that. But there is not property of AVPlayer to observe for volume change.
Comment: @shoan have you get any solutions yet?
Comment: @webmastx I found no solution.
Answer: You can use a combination of KVO and Combine to observe changes to isMuted property:
let player: AVPlayer
private var cancellables = Set<AnyCancellable>()

//...

player
    .publisher(for: \.isMuted)
    .sink { isMuted in
        // here you can handle the fact the the user has muted or unmuted the player
     }
     .store(in: &cancellables)

Answer: You should implement KVo to detect mute/unmute changes.
Note: in swift, although the property is isMuted, but you still should use ObjectiveC properties in KVo, so listen for muted key and you are set.

Detect when the user has muted AVPlayer


Display a code snippet based on a taxonomy term

Question: I am trying to build a node file for a content type in Drupal 7.59. I have for example a field for a taxonomy term. There is only 2 terms Expert and Guest.
I want to display something on the node if this term reference choice is marked as Expert.
So I need to figure out how to write a line that checks for the value of the taxonomy term and then if it matches expert then it displays something but if it is guest it doesn't.
The field I have setup in my content type is:

Name of field: author type
Machine Name: field_author_type
Field Type: Term reference

The root taxonomy term is Author Type and the two terms are Expert and Guest.
Does anyone know how to accomplish this? I hovered over the taxonomy term I wanted to reference and it was /taxonomy/term/57/ Is 57 the actual number or do I find it elsewhere?
So far I have this which is not much and it doesn't work so it is wrong. I am really sucky at php.
<?php if ($content['field_authors_type']->taxonomy[57]): ?>
    Put what you want to display here
<?php endif; ?>

Comment: So you're using a node template file, like node.tpl.php? If you want to check the value of a field, you can use something like this $content["field_authors_type"]["#items"][0]["tid"].
Answer: The value you're looking for would be stored like so
$content["field_authors_type"]["#items"][0]["tid"]

You could, if you wanted to be tidier, put this if statement in your theme's template.php in a template_preprocess_node or template_preprocess_page function (more on that here: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x).
You would store your boolean value $variables['author_is_expert'] and then in your node.tpl.php, you can just use if ($author_is_expert)


vertical vs. horizontal regression

Question: A horizontal regression is defined as the following:
$$m=\frac{\sum_{i=1}^n (x_i-\operatorname{average(x)})(y_i-\operatorname{average(y))}}{\sum_{i=1}^n (x_i-\operatorname{average(x)})^2}$$
whereas a vertical regression is defined as
$$m=\frac{\sum_{i=1}^n (y_i-\operatorname{average(y)})^2}{\sum_{i=1}^n (x_i-\operatorname{average(x))}(y_i-\operatorname{average(y))}}$$
In several math-books it says that you use the horizontal regression if you want to calculate the x values to given y values and the vertical regression formula if you want to find the corresponding y values to given x values.
But how can it be that the function I get with the vertical regression formula is more accurate than the horizontal one for x on y values?
For example:
$ x := \{1,2,3,4,5,6,7,8\}$
$ y := \{0.3,0.5,0.7,1,1,1.5,1.6,2.1\}$
That gives me the vertical function: $f(x)=0.24404*x-0.0107$
and the horizontal function: $f(x)=0.25256*x-0.04902$
If I calculate the least-squares-sum (x on y):
$$\sum_{i=0}^7 (x_i-f(y_i))^2$$
I get 181.33... for the vertical one but 183.14... for the horizontal one.
Why is in general the horizontal regression associated with "x on y" if the vertical one obviously be more accurate?
Thanks a lot in advance!
Comment: I think it must be minimized $\sum_{i=0}^7 (y_i-f(x_i))^2$, not $\sum_{i=0}^7 (x_i-f(x_i))^2$, doesn't it?
Comment: $\sum_{i=0}^7 (y_i-f(x_i))^2$ tells me how good the y-values correspond; but I want to know how good the x-values correspond. So I think my formula should be alright...
Comment: Now I see what you meant. You are (half) right... it should be $\sum_{i=0}^7 (x_i-f(y_i))^2$ since I get x-values from my function...
Comment: still that doesn't solve my problem... it was just a typo
Comment: The whole point of the horizontal regression is that it minimizes the $x$-on-$y$ residual, so I'd recommend checking your work and seeing if you got all your numbers right.
Comment: I went over my work several times... I've also double checked everything with Mathcad. Results are still the same. The example I've given above leads me to exactly the results I've stated (181.33 for vertical but 183.14 for the horizontal)
Answer: I see the problem. You've computed linear fits of the form $y=f(x)$, and then you're comparing $x$ with $f(y)$! But of course, if $y=f(x)$, then $x$ is $f^{-1}(y)$, not $f(y)$. This is why your sum of squared residuals are so large for such small inputs. If you want to compare residuals in $x$, you need to compute $\sum \left(x_i - f^{-1}(y_i)\right)^2$ instead.
The inverse functions of the "vertical" and "horizontal" regressions are $$x \approx f^{-1}(y)=4.09756y+0.0439024$$ and $$x \approx f^{-1}(y)=3.95944y+0.194109$$ respectively. The respective sums of squared residuals in $x$ are $1.46513$ and $1.41574$. As you can see, the horizontal regression does better.
Answer: The idea is that one variable (usually $x$) is a value you input-maybe the temperature or concentration of something-which you know accurately.  The other one (usually $y$) is less well known as it is something you measure with errors.  The fit then assumes the $x$ values are exact and minimizes the sum of the squares of the errors in $y$.  If your data fit a straight line well, the difference will be small.  If not, it will be large.  This is the origin of the correlation coefficient equation.
Comment: Sure, but if you get the variables mixed up and try to do a regression of $x$ on $y$ instead, the line you get should still give you a smaller $x$ on $y$ residual than the line you would have gotten if you had done it the right way, right? And I think OP is claiming to have a counterexample, and that shouldn't happen.
Comment: @Ross: It seems like you didn't get me right: I minimized the residual for the x-values by using the horizontal regression formula. Still my vertical-regression formula gives me a more accurate line than I get with the horionztal one. ( $\sum_{i=0}^7(x_i-f(y_i))^2$ is smaller with the vertical than with the horizontal function)
Comment: @libjup:  you say the error is always smaller when minimizing the horizontal residuals, but I don't see why that should be the case.  For your data the variation in $y$ is much smaller than the variation in $x$-that may have something to do with it.  Also the difference is pretty small.
Comment: Then there is the regression that minimizes the sum of the squares of the distances to the regression line itself. This is independent of the coordinate system, and can be done with a few additional statistics.

vertical vs. horizontal regression


Why a pointer needs to be returned when the return type is actually error?

Question: I am reading the article Error handling and Go, and don't quite understand why a pointer (&errorString{text}) has to be returned when the return type is actually error?
My understanding is error is an interface, and errorString implements the interface, therefore, return errorString is also okay (but it is not the case).
// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

errorString implementation
// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

Answer: Because error interface for errorString is implemented for a pointer (func (e *errorString) Error()), if it was implemented like below you would return the value directly:
func (e errorString) Error() string {
    return e.s
}

Comment: Thanks, Arjan. It works like what you said.  One thing I noticed is that if it were implemented as what you said, both return directly or return pointer work, do you know why?
Comment: It's how method sets for types are defined: http://golang.org/ref/spec#Method_sets
Comment: *T type can call methods with receiver defined both as *T or T


Sum of squares finite for two sequences implies sum of products finite?

Question: Let $a_1,a_2,\ldots$ and $b_1,b_2,\ldots$ be sequences of real numbers such that $\sum_{i=-\infty}^\infty a_i^2$ and $\sum_{i=-\infty}^\infty b_i^2$ are both finite. Is it true that $\sum_{i=-\infty}^\infty |a_ib_i|$ is also finite?
This looks a lot like the Cauchy-Schwarz inequality, but the sum is an infinite sum, so I don't know how to apply it.
Comment: Cauchy-Schwarz is valid for infinite series, too.
Comment: @JJ Beck : just use $|a_i b_i| \leq (a_i^2+b_i^2)/2$.
Answer: Note that we have
$$\overbrace{\sum_{k=1}^n a_k b_k \leq \sqrt{\sum_{k=1}^n a_k^2} \sqrt{\sum_{k=1}^n b_k^2}}^{\text{Cauchy-Schwarz inequality for finite dimensional vector-space}} \leq \sqrt{\sum_{k=1}^{\infty} a_k^2} \sqrt{\sum_{k=1}^{\infty} b_k^2} = \text{constant}$$
Now let $n \to \infty$, to conclude what you want.


Can't use Advanced User Interactions in Webdriverjs

Question: I am trying to use webdriverjs to click on a flash animation.
I tried using the Advanced User interactions, but I can't seem to click where I want.
Not even when I try to click a normal web element, such as a button.
Optimally, I would like to do something like the following:
element = driver.findElement(webdriver.By.Id("elementID"));

driver.actions()
.mouseMove(element)
.mouseClick()
.perform();

-or-
driver.actions()
.click(element)
.perform();

However, the feedback I get from the standalone server is always in the form of [someaction: nothing].
I tried enabling firefox native events in browser capabilities via 'nativeEvents': true, but it didn't help.
I can use webdriverjs to click on elements on a page normally otherwise. (except for flash)
Answer: Selenium cannot interact with Flash objects.
If you want to do this you would need to modify the source code of the flash object to provide some test hooks that JavaScript could access and then use something like:

https://code.google.com/p/flex-ui-selenium/
https://code.google.com/p/flash-selenium/


I'm trying to write a function in MIPS, int mash(int x, int y): Parameters x and y are passed in the stack

Question: Returns the value of 10*x + y in a register. Eg, max(8, 9) returns 89.
I have this and whenever I run it, it gives me 2147481597 for some reason, what am I doing wrong?
<code>.text

   li $a0, 8
   li $a1, 9
   jal mash

   addi $a0, $v0, 0
   li $v0, 1
   syscall

   li $v0, 10
   syscall

   mash:
      mul $v0, $a0, 10   # result = 10*x
      add $v0, $v0, $a1  # result = 10*x + y
      jr $ra # return
</code>
Comment: The code you've posted works just fine for me in QtSpim (after adding a `main` label). You haven't stated which simulator you're using.
Answer: You've written a very vague code.
after calling the jal function you should save it in some variable initialized under .data using the command below.
<code>              sw $v0, answer
</code>
Not sure why you applied that addi function.
also for the Mash function, you can save the values in general purpose register first and then move them to $v0
Instead of directly loading value in $a0 and $a1, you can first save them in some variable and use them later on.
I've corrected the code for you.
<code>         .data
         x:          .word 8
         y:          .word 9
         answer:     .word 0

        .text
        .globl main
        main:
                    lw $a0,x
                    lw $a1,y
                    jal mash
                    sw $v0,answer

                    lw $a0,answer
                    li $v0,1
                    syscall

                    li $v0,10
                    syscall
        .end main

         mash:
                    li $v0,0
                    mul $t0, $a0, 10
                    add $t1, $t0, $a1
                    move $v0, $t1
                    jr $ra
        .end mash
</code>
Comment: `addi $a0, $v0, 0` copies the value of `$v0` to `$a0`. Although `ori` might be more common, or just `move` if you're ok with using pseudo-instructions. Those data section variables are unnecessary.


Inserir um elemento na lista encadeada

Question: Estou tentando inserir um novo elemento um uma lista encadeada sem cabeça, eu até consigo inserir mais ao sair da função o ponteiro aponta para nulo novamente
void cadastrar_produto(char codProd[], char descricao[], char fornecedor[], char data_validade[], int qtd, double preco, produto *prod){

    produto *p = (produto *) malloc(sizeof(produto));

    strcpy(p->codigo,codProd);
    strcpy(p->descricao,descricao);
    strcpy(p->fornecedor,fornecedor);
    strcpy(p->data_validade,data_validade);
    p->qtd = qtd;
    p->preco = preco;
    p->prox = NULL;

    /* Inserindo o Produto na lista */

    if(prod == NULL){// ele cai dentro desse if sempre
        prod = p;
    }else{

        produto *lst;

        for(lst = prod;lst->prox != NULL; lst = lst->prox){

            puts("for");
            if(comparaString(lst->codigo, p->codigo) == 1){
                puts("Código já cadastrado !!!");
                break;
            }

            if(lst->prox != NULL){
                lst = lst->prox;
            }else{
                lst->prox = p;
                break;
            }
        }
    }

    listar(prod);// ele lista o produto corretamente

    system("pause");
}

Eu não estou ver o porquê ele não ficar dentro da lista após sair da função
Answer: A questão aqui é que você tem um ponteiro no main que passa à função na esperança que a função altere esse ponteiro, com uma atribuição simples mas isso não funciona como imagina.
O cenário simplificado é este (todos os ... significam o resto do código):
void cadastrar_produto(..., produto *prod){
    if(prod == NULL){
        prod = p; // <-- instrução critica
    }
    ...
}

int main(){
    produto *lista = NULL;
    void cadastrar_produto(..., lista);
    ...
}

A instrução prod = p altera o parametro prod que existe na função e não o ponteiro lista que existe no main e por isso esse fica sempre a nulo. Lembre-se que os parametros são passados por copia.
Para conseguir alterar o ponteiro tem de passar o endereço do ponteiro, para ir ao local certo na memória e fazer a alteração:
Exemplo (assinalei com comentários todas as linhas que necessitam ser alteradas):
void cadastrar_produto(..., produto **prod){
//                                   ^--
    if(*prod == NULL){
//     ^--
        *prod = p;
//      ^--
    }
    else{
        produto *lst;
        for(lst = *prod;lst->prox != NULL; lst = lst->prox){
//                ^--
            ...
}

int main(){
    produto *lista = NULL;
    void cadastrar_produto(..., &lista);
//                              ^--
    ...
}

Inserir um elemento na lista encadeada


Como identificar a ausencia de um termo num arquivo usando PERL

Question: Ola, preciso de uma ajuda aqui.
Estou escrevendo um programa perl que ira identificar certos padroes num arquivo de texto usando regex. Porem, quando o termo buscado nao estiver presente no texto, preciso que o programa informe isso ao usuario.
Eu abro o arquivo e salvo num array e percorro ele com um laço for. Uso if para encontrar meu padrao e imprimi-lo. Quando adiciono elsifou else, o programa imprime para cada linha que ele percorreu que nao encontrou o padrao. Precisava que ele imprimisse apenas ao chegar ao fim do documento se nao achar o padrao. alguem sabe como fazer isso? Talvez com while. Valeu o/
for($i=0; $i<=$#report; $i++){
    if($report[$i] =~ /target/){
       chomp $report[$i];
       print "$report[$i]";
    }
    else{
       print "not found\t";
    }
 }

Answer: Pode usar uma variável que regista se o padrão foi encontrado. Por exemplo:
my $found=0;
for($i=0; $i<=$#report; $i++){
   if($report[$i] =~ /target/){
      chomp $report[$i];
      print "$report[$i]";
      $found=1;
   }
}

print "not found\t" if (!$found);

Answer: Já agora uma versão um pouco mais criptica:
print ( join(";", grep /target/,@report) || "not found\t")

Onde:

grep /target/,@report dá a lista dos elementos do report que fazem match;

(Exemplo: grep /33/, (1..300) ---> 33 133 233)


How to send email through server alias mail

Question: I've create a script that used the ipn of PayPal. All working perfectly, after the purchasing the data of the clients are inserted in the database. But recently the server of my hosting provider doesn't send the email. I don't understand the reason. I'm trying so to create an alias email server for send the email of contact form through the alias mail and it's working!
Now i want replicate the license send with alias mail server, actually i send the email with this code:
<code>*$headers = 'From: '.$AdminEmail . "\r\n" .
    'Reply-To: '.$AdminEmail . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers)*
</code>
In the past this code working good but now doesn't working more. How can send the email through the alias server mail?
Comment: If it was working before, iI think it would be worthwile to understand why it's not working anymore. Has the config changed? What do the logfiles say?
Comment: Do you mean by alias mail server a local MTA (like exim) that is configured to use a relay mail server? that should work, I actually did that many times to avoid setting up my own mailserver (which is sometimes not even possible in a reliable way ,e.g. if you are behind a dialup line...)
Comment: I tried to contact support but being free hosting does not give much explanation. What should I include in the log file? I can try to simulate a purchase request to PayPal via the sandbox.
Comment: Well, testing the sendmail functionality does not require the involvement of Paypal I think :)
Comment: Yeah but the problem appears when the client buy the license, it isn't sended at the client. But with the canged that I've apported in the contact form, using the alias mail server, the mail working good.
Comment: Sorry, I don't get your last sentence - so is it working now? That would make the whole question obsolete.
My point above was that you should investigate the send mail functionality isolated first an then integrate taht with your paypal / purchasing functionality to make sure you don't try to solve many problems with one step (which usually doesn't work out that well...)
Comment: The sending of the email only works if I use the mail alias that comes from space hosting.
This email alias currently I used to send emails from the support form on the site.
I would like to replicate the operation in the code I posted above, in particular, I would try to send emails directly with the alias email.
Comment: Ah, so you try to change the "From" and then the email is not send anymore. This is probably a security setting from your hostingprovider to protect themselves from being misused by spammers.
Comment: So how can I solve the problem?
Answer: Outcome of the discussion in the comments is that your provider restricts you from changing the from: field for email sent from you php scripts.
As a result of this, you need to use a external mail server that allows you to do so or talk to your provider if they can provide another (probably paid) solution.
Comment: You can learn about the cause of adding some kind of exception in the code I pasted above?
That way I'll know the exact reason.
Comment: Not that I'm aware of. IMHO you would need access to both php/webserver log and mail server logfiles.


Sonicwall not handing out address to VLAN on Dell switch

Question: I have a dell switch N1548
I have a sonic wall TZ 215
I have followed every blog and forum post i can find online and still cannot get my sonicpoints to hand out addresses from the sonicwall to wireless clients.
DHCP works fine for all others
Here is my running config from the switch
console(config)#show running-config

!Current Configuration:
!System     description "Dell Networking N1548, 18.104.22.168, Linux 3.6.5"
!System Software Version 220.127.116.11
!
configure
vlan 10
exit
vlan 10
name "Wireless"
exit
sntp unicast client enable
sntp server "us.pool.ntp.org"
clock summer-time recurring USA zone "EST"
clock timezone -5 minutes 0 zone "EST"
stack
member 1 3    ! N1548
member 2 3    ! N1548
member 3 3    ! N1548
member 4 2    ! N1524P
exit
ip domain-name "corp.haven-oakland.org"
ip name-server "10.2.0.10"
ip name-server "10.2.0.13"
ip host "hvnsw004" 10.2.0.4
interface vlan 1
ip address 10.2.0.4 255.255.255.0
exit
interface vlan 10
ip helper-address 10.2.0.2
exit
ip default-gateway 10.2.0.2
username "admin" password 45f315a95c02cea3a684f9ef61451288 privilege 15 encrypted
ip ssh server
ip ssh port 1025
!
interface Gi4/0/1
description "SonicWALL Uplink X6"
gvrp enable
spanning-tree disable
spanning-tree portfast
spanning-tree cost 20000
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/2
description "SonicWALL Uplink X6"
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/3
description "SonicWALL Uplink X6"
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/4
description "SonicWALL Uplink X6"
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/5
description "SonicWALL Uplink X6"
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/6
description "SonicWALL Uplink X6"
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/7
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/8
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/9
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/10
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
!
interface Gi4/0/11
spanning-tree disable
spanning-tree portfast
switchport mode trunk
switchport general pvid 10
switchport general acceptable-frame-type tagged-only
switchport access vlan 10
switchport trunk native vlan 10
exit
snmp-server engineid local 800002a203f8b156838a19
snmp-server community "public" rw
exit

Am i missing something in the switch or could it be the sonicwall?
I have setup the sonicwall according to dell BP and should be working
Thank you if any additional info is needed please let me know.
Answer: You probably need a helper-address to be defined in the VLAN that's not receiving DHCP. I don't know the exact syntax for your switch, but something like:
ip helper-address 126.96.36.199

Where 18.104.22.168 is the IP of the DHCP server or Sonicwall.
Comment: I did that, I ran the command "ip helper-address 10.2.0.2" as 10.2.0.2 is the address on my sonicwall
Answer: whats the interface config for x6 from the sonicwall?  Do you have multiple VAP's on sub-interfaces with VLAN's assigned?  Usually I have my sonicpoints on the base interface and SSID's on various VLAN's, which will need adding as tagged to the general ports.  No DHCP is usually down to a VLAN breakdown as the SDP assigns these to the AP's upon provisioning, even if they have no access.
P.s. re-skimming the config, no need for ip-helper, just noticed port type is trunk, can you change this to access with no sub interfaces or general with sub interfaces.


Plugin development: how to insert parameterized content into the editor similar to Live Templates?

Question: I am developing a domain-specific custom language as an Intellij IDEA plugin.
I created an intention that allows the user to fix an error in the code.
I am able to make updates to the content in the editor, and then place the caret where I want the user to add some text. However, there are multiple places the user needs to add text at, and I would like to automatically have the caret placed in all of them, one after the other, similar to how it's done when using the Live Templates feature, when adding a Live Template with parameters in it.
When using Live Templates, it looks like this:

Notice the red box. The caret gets there automatically, and when I finish typing and click enter - it moves to the next parameter and the red box appears there.
Note that in the scenario I'm implementing the text is completely dynamic. If creating temporary ad-hoc Live Templates on the fly is possible then that might be a viable solution, but otherwise I need another way to control this mechanism.
Does anyone know how to pull it off?
Answer: It's possible to create live templates on the fly. The most convenient API for that is TemplateBuilder, see its javadoc. If you don't have PSI available, you can assemble a template manually by carefully constructing TemplateImpl object and then using TemplateManager#startTemplate. There are numerous examples for both cases in IntelliJ IDEA Community edition codebase.
Comment: I actually found that after posting the question, but how do I actually put ("expand"?) the template in the editor?
Comment: TemplateBuilder.run() seems to work, thanks! Now I'm having some (related) problems with updating the Psi tree using code but I guess I'll create a separate question for that.


How to lock distros so they can only be used on 1 URL?

Question: I plan on making distributions for dating sites and stuff like that.
Maybe sell them as functional themes.
How do I lock the distribution and theme so the client can only use it on 1 URL?
I have seen this done with many website and templates, how can I do this with Drupal?
Answer: I see 2 possible approaches (there might be others):

Include "something" that requires an API key, whereas 1 such key can be used on 1 URL only.
Offer a "hosted" version only, which uses your distribution. That way you don't have to ... "distribute" the distribution.

PS: Drupal is GPL, so before creating something that is based on Drupal, make sure you do understand the legal aspects of GPL ...


a function constant on open ball implies constant everywhere

Question: let $U$ be a domain and $f:U \rightarrow \Bbb C$ be analytic function such that $f$ is constant on some open ball $D_r(z_0)$
how to prove $f$ must be constant on $U$
hints?
Comment: This is just [Identity Theorem](https://en.wikipedia.org/wiki/Identity_theorem)
Answer: Show that the set where $f^{(k)}=0$ for every $k$ is both open and closed. Closed is clear; for open use power series.


Do power chords have some kind of function/meaning?

Question: Every guitar player runs into these at least once (and probably way more often, too): power chords. This is a general term for chords consisting of the root note, the fifth, and an octave.
In most situations, these chords are played on the lower strings, often with distortion/overdrive. In my view, that's why power chords never contain thirds; with the distortion and the low tones, this small interval would sound a bit messy.
I wonder if this kind of chords is ever used in other situations though. In rock music, you'll sometimes find chord schemes consisting entirely of power chords played on guitars, with not a single third note anywhere. Is this something that appears in other kinds of music, and on other instruments as well? Additionally, is there a specific kind of emotion/feeling that you create by omitting the third note of your chord(s)?
Comment: A major fifth does not exist. Fifths and octaves can't be major or minor (so fourths and primes neither).
Comment: Note that thirds can actually sound great through distortion. Unfortunately, 12-edo has blessed us with thirds which are rather far off from just intonation; it's mainly this difference that makes full chords so messy through distortion. In Bohlen-Pierce tuning (which is pretty weird because it has no octaves, but has much more precise third and harmonic-seventh intervals) even 7th chords sound pretty amazing distorted.
Comment: lol you get that thing where you're begging to hear a 3rd .. somewhere. . anywhere ..
Comment: The best part of power chords is dropping the low e string to a d string. You literally just place your finger on the dots and strum and BLAM instant rock star. Plus, since it's such an easy fingering, your bassist doesn't have to bug you about what note to play. HE is playing on the dots TOO! It's a win-win situation all around.
Answer: Like you and others said, the main reason of using power chords is to avoid the intermodulation distortion: Thirds sound muddy with distortion.
I think that they generally have two functions in rock music. One function is to use it as a substitute for a triad. Here, the third is generally implied. But it may be played by a solo guitar or sung by the vocalist for example. In this case it has the same function as the triad it replaces.
In some riffs, though, it doesn't make sense to analyze them as chords. They're just fuller sounding monophonic melodic notes. The fifth is not heard independently, it's just part of the timbre.
In classical music, they're called bare, open or empty fifths. According to Wikipedia:

The closing chord of the Kyrie in Mozart's Requiem and of the first
  movement of Bruckner's Ninth Symphony are both examples of pieces
  ending on an empty fifth.

My personal impression is that, open fifths give kind of an ancient sound in classical music alluding to the Middle Age music where thirds were considered dissonances.
Also, omitting the third opens up the possibility for leaving the triad ambiguous, ambiguity is a fairly common tool in romantic period music. Beethoven starts his ninth symphony with an open fifth if I remember correctly.
You can also think of Strauss's Also sprach Zarathustra, where you have to wait quite a bit for the third to appear and when it does finally appear as a major third, it instantly shifts to minor, and doing it the other way next time before finally concluding with a convincing cadence in C major. Until then, the modality is left ambiguous.
Comment: They are also called horn fifths on the dominant. They are so called because valveless horns could not make the leading tone (B in the key of C), so omitting the third was common for that chord. ([source](http://www.dangutwein.net/courses/theorytxt/text/appendix.htm#l))
Answer: Bagpipes come close, even though their drones are at a pitch and its octave. The harmonics come into play here (pun intended), because every instrument produces not only the fundamental note that we think we hear, but some/lots of others too.Each instrument will have particular overtones, partials or harmonics that it will produce in different proportions. The first harmonic is an octave above the fundamental. As such, it's quite easy to miss the fact that it's sounding. The second is a perfect (not maj. or min.) fifth above that, and this one is quite clear on some instruments. The next is two octaves above the fundamental, as such, difficult to discern against the original and its octave already sounding.
With no third sounding in a chord, one can't tell if it's major or minor - a feature the Western world of music seems to appreciate when it's there.So it's a sort of 'hard' sound, with not much flavour.
The other factor is that with distortion/ overdrive the harmonics of a note are accentuated. Those of a fundamental and its fifth work without sounding too discordant. Put a third in - maj. or min. - and those harmonics, as well as the note itself, start to make the sound too crowded.
Another possibility, and I'm not knocking guitar players, is that it's quite easy to just play power chords - particularly with the bottom string tuned to D - one finger will do. Instant success !
Answer: I would venture that ONE of the functions of a power chord is to provide an open melodic soloing space. I recall an interview with Eric Johnson in which he referred to fifth/power chords as "open chords" -- meaning that the soloing space over the chord was unrestricted. That was a different perspective than I had ever used for that terminology(*). I concede that each voice added to a chord restricts (or more tightly defines) the available [traditional] melodic/harmonic choices.
(*) I had always employed that terminology to differentiate chords that contained one or more open strings.
Answer: A "power chord" under this name is used for distortion play, period.  If you have frequencies f and its harmonics, and 3/2f and its harmonics, the intermodulation frequencies are all multiples of f/2.  So that basically means that the harmonics "hint" at a fundamental frequency of f/2 which is in line with the bass note of the power chord.
Organs do have fifth registers which are a perfect fifth (not! a tempered fifth) plus some octaves above other pipes they are combined with.  You use them to give a different tone color to some registration by adding overtones.  You can also use them for "hinting" at non-existent lower bass notes: combining a 5⅓' register with an 8' register "hints" at a 16' register psychoacoustically.  However, on a guitar the notes don't have constant volume, so the characterics and composition of the distorted tones varies with the dynamics of the notes, leading to a much more lively action than the static harmonic composition of organ registers provides.
With smaller intervals than a fifth, the intermodulation frequencies become messier and the resulting spectrum so sparse and irregular that it does not really point convincingly to an underlying bass note in the audible spectrum (power chords tend to be played on the lower strings of a guitar or even bass guitar).  Also a fifth tends to be the purest interval in any kind of tempered, particularly equally tempered, tunings and thus gives the clearest approximation to some bass frequency when looking at the sums and differences of the frequencies of fundamental and harmonic frequencies.
Answer: I think they do evoke an emotion, which is quite hard to describe ..
I wish I could remember the song but there's a solo in said tune where a fiddle player plays a power chord for a bar or two. It's an american folk/country song- the power chord shines right through everything, even though it's not that loud. The rest of the fiddle solo involves a lot of notes (probably 3rds all over the place) so when it settles on the power chord it kind of has a "home" feeling and a notion of "and I mean it".
That's similar-but-different-to power chords on a distorted electric guitar; as you say, the usual reason to miss out the 3rd is to allow the distortion to be more harmonious.
I'm sorry I can't remeber the tune, if it comes to me I'll post it as an edit.
Answer: Power chords and shell chords both serve a similar function. A power chord strips a triad down to the root and fifth; a shell chord uses the root, seventh, and sometimes the third.
Power chords and shell chords both sacrifice some of the chords' character but still drive the chord progression. They simplify the harmony, which has a couple of major benefits:

They are easier to play, which not only helps less-skilled musicians, it also enables pianists to focus more on right-hand melody and less on left-hand harmony.
They reduce overtones, which makes the overall sound less muddy. This is a well-known issue for distorted guitars, but it's also important for the lower octaves on a piano, which have their own kind of distortion.

Depending on the overall instrumentation, other voices may fill in the missing chord tones, or the arrangement may simply use a sparser, more ambiguous voicing. In the latter case, natural overtones may lend the piece a subtle major-key feel.
Comment: Shell chords are one of the reasons I love the sound of many Faith No More songs - they use thirds and sevenths extensively with heavy distortion, leading to some lovely harmonics.
Answer: Arguably, adding 5⅓' and 2⅔' registers to 16', 8' and 4' on a pipe organ lets you play "power chords" all over.
Of course, there is a subtle difference involved: those pipes are tuned in perfect fifths in relation to the others rather than in some form of tempered fifth.  That makes them blend into the sound without any beatings, in contrast to instruments taking fifths from some tempered scale.


Dice rolls, simulation vs. theory

Question: I just ran into something interesting, and was hoping someone could shed some light on it.  I'm trying to calculate rolling at least N on multiple dice.  I wrote a simulation script in R that uses the sample(8,1,TRUE) to simulate a d8 (8 sided die) roll and iterates and sums.  I also calculated the probability in excel using a normal distribution with variance (for kdN) = k*(N^2-1)/12 and mean = k*(N+1)/2.  I used excel function of: 1-Norm.dist(number.to.roll, mean, sd, TRUE).  I consistently get a few percentage points higher on the simulation than on the calculation.  For example, to roll 8 on a 2d8, simulation succeeds 67.6% of the time (+/- 0.3%).  Excel predicts 62.1%.  I think it has something to do with dice being integers and excel calculating based on a continuous distribution.  I have tried using +1, or -1, or -.5 to get excel to match.  It gets closer, but I can't find a constant that work across different dice sizes.  Is there a discrete distribution that will model the rolls better?  I tried the R "triangle" package, but it gives values very close to the Normal approximation in Excel.  My question is less how to get the formula right, than can someone provide me insight as to why there is the difference?  This is for my own edification only.  Am fiddling with numbers while I wait for parts to show up at work.  :)  Thanks.
Comment: No, the answer is 'yes, there is some distribution other than the normal' that models it better, whuber already stated so explicitly.
Comment: There is only one distribution that models the rolls *correctly*: it is the one you employed in `R`.  There should be no mystery why using other distributions gives other (wrong) answers!  Is your question about how to implement that distribution in Excel, then?
Comment: When you say "to roll 8 on 2d8" do you mean "to roll *at least 8* on 2d8"?
Comment: No, that pretty much answers it.  I wanted to know if the difference between simulation and formula was just the error in the normal approximation, or if there was another theoretical explanation, as it seemed to be somewhat divergent in some cases.  I also was wondering if there was some hyper-super-duper-geometric distribution that modeled it better than the normal approximation.  Apparently that answer is "no."  Thanks!
Comment: Yes, meant "at least 8."  Sorry.
Comment: Simulation in Excel with a suitable formula, such as `=INT(8*RAND()) + INT(8*RAND()) + 2`, tends to produce estimates (of the chance a 2d8 is $8$ or greater) that are between 66.5% and 68% (using 10,000 independent rolls), in close agreement with your `R` simulation.  Thus, it's not *Excel* that predicts 62.1%: it is an erroneous calculation that predicts 62.1%.
Answer: The distribution of 2d8 is discrete triangular.
     x       2    3    4    5    6    7    8    9   10   11   12   13   14   15   16
64.P(X=x)    1    2    3    4    5    6    7    8    7    6    5    4    3    2    1
       %   1.56 3.13 4.69 6.25 7.81 9.38 10.9 12.5 10.9 9.38 7.81 6.25 4.69 3.13 1.56

If you need an algebraic expression for it, for 2d8 it's:
$p(x) = P(X=x) = \frac{1}{64} \min(x-1,17-x)$
As you add more dice, the cdf becomes closer and closer to a normal distribution, but if you want to use normal distributions to approximate probabilities for it, I'd suggest using a continuity correction. If you don't get too far into the tail, it should work pretty well for more than 3 dice. However, it's not all that hard to do the convolution - or even complete enumeration - by hand for small numbers of dice to get exact answers. e.g. here's me doing 3d8 in R:
 o2d8=c(outer(1:8,1:8,"+"))
 o3d8=c(outer(o2d8,1:8,"+"))
 table(o3d8)
o3d8
 3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 1  3  6 10 15 21 28 36 42 46 48 48 46 42 36 28 21 15 10  6  3  1

The table at the end shows the number of ways (out of $8^3=256$) of getting each result on 3d8. You convert them to probabilities by dividing by $8^3$:
> print(table(o3d8)/8^3,d=2)
o3d8
     3      4      5      6      7      8      9     10     11     12     13
0.0020 0.0059 0.0117 0.0195 0.0293 0.0410 0.0547 0.0703 0.0820 0.0898 0.0938

    14     15     16     17     18     19     20     21     22     23     24
0.0938 0.0898 0.0820 0.0703 0.0547 0.0410 0.0293 0.0195 0.0117 0.0059 0.0020

The algebraic formula becomes relatively complicated past 3 dice, and I wouldn't bother with it, but the probabilities are easy to work out in either R or Excel (or any other tool with the relevant ability to do the kind of calculations you need)
Let's say I want to compute probability of rolling at least 9 on 3d8 from a normal approximation (I suggested more than 3 dice, but let's try it anyway). The exact answer is easily computed by summing probabilities in the above table (it's 0.890625).
> pnorm(8.5,3*(8+1)/2,sqrt(3*(8+1)*(8-1)/12),lower.tail=FALSE)
[1] 0.896144

(The use of 8.5 rather than 9 is because of the continuity correction).
That's not too bad, a relative error of a little over half a percent. But the exact answer takes only a few seconds longer to generate.

Incidentally, a simulation script for rolling 2d8 in R is as simple as:
r2d8=replicate(10000,sum(sample(8,2,TRUE)))

And to display a table of the results as proportions:
table(r2d8)/length(r2d8)

The results of the simulation can be seen as red circles, compared with the exact values (black dots):

--
There's detailed instructions on how to use Excel to do similar calculations to the ones I did in R to compute the exact probabilities here

Dice rolls, simulation vs. theory


Inverse of $y=2x^2-12x+13$

Question: I'm having a problem finding the inverse of $y=2x^2-12x+13$.
At the end I get to the following:
$$x=3 \pm \frac{\sqrt{40+8y}}{4}$$
As far as I know the answer is suppose to be $x= 3 \pm \frac{\sqrt{y+5}}{\sqrt{2}}$
but I am unable to get to it.
Please can someone help me with the process of obtaining that answer.
Thank you
Bernard
Answer: $$\frac{\sqrt{40+8y}}{4} = \frac{\sqrt{8}\sqrt{5+y}}{4}=
\frac{\sqrt{8}\sqrt{5+y}}{\sqrt{16}}=\frac{\sqrt{5+y}}{\sqrt{2}}$$
Answer: $$\sqrt{40+8y} = \sqrt{8}\sqrt{5+y}$$

Inverse of $y=2x^2-12x+13$


Different method called when using Laravel form request validation

Question: I have a controller (API\Fields) with a method named store, the route to that method is set up like this:
POST /api/templates/{template}/fields -> API\Fields@store
Everything worked properly until I created a very simple form request validation class with the following rules (This is the only thing I changed besides the return value for the authorize method):
    return [
        'name'          =>  ['required', 'alpha_num'],
        'coordinates'   =>  ['required', 'json'],
        'type'          =>  ['required', BaseField::RULE],
        'page'          =>  ['required', 'numeric'],
        'readonly'      =>  ['sometimes', 'boolean'],
        'required'      =>  ['sometimes', 'boolean']
    ];

After I created the class, I simply changed the request class from Request, to CreateFieldsRequest and it messed pretty much the whole routing for that route up. Instead of calling store, Laravel seems to be calling index. When I restore CreateFieldsRequest back to just the Request class, it behaves as it should again.
I haven't been able to find any information on this topic, and I've verified over and over that I don't have some sort of incorrect routing or redirections on any of the related classes.
Any help or guidance with this would be greatly appreciated, thank you!
Answer: After running a very simple test I realized that this seems to be an issue with Postman. If you are experiencing this issue stick to adding a _method=POST parameter on your POST body, or simply use XHR or a different API testing tool.
Edit: After further testing I realized the issue had not been fixed. When I run the request through the Chrome developer console as a POST request, Laravel kicks it back as a "GET" request, not sure why.
Comment: This is only necessary if you're not sending the request as an actual POST. Postman can absolutely do it, but it sounds like you're sending some other type of request (a GET, most likely).
Comment: Yeah, I realized that the issue had not been fixed. However I noticed that when I send the request as a POST request via the Chrome developer console, Laravel kicks it back and then Chrome shows it as a GET request. Once I change the request type back to `Request`, it shows a POST request type as it should.
Comment: That sounds like you're receiving a redirect due to failed validation, which is [the default behavior for a FormRequest](https://github.com/laravel/framework/blob/e6c8aa0e39d8f91068ad1c299546536e9f25ef63/src/Illuminate/Foundation/Http/FormRequest.php#L128).
Answer:
When I run the request through the Chrome developer console as a POST request, Laravel kicks it back as a "GET" request, not sure why.

A FormRequest that fails validation issues a redirect. It's the default behavior.
If you issue an AJAX request, or request a JSON response with an Accept header, it'll respond with a JSON list of validation errors and a 422 HTTP code instead.
Comment: Thank you! I found an issue about this on the repo once I figured out that it was a redirect that was giving the issue. Adding a `X-Requested-With` header has also fixed it.


How many pitches does a reliever usually need to warm up?

Question: A one-inning "reliever" in Major League Baseball will typically throw between 5 and 20 pitches in a game. How many warm up pitches does he need before he can do this?
Said reliever is allowed up to eight "practice" pitches from the mound (except in the case of an unexpected injury, when the reliever gets as many pitches as he needs). So how many pitches might the reliever have thrown in the bullpen before being called into a game?
Comment: This depends a lot of things ranging from team protocol to the game situation to the individual pitcher. I don't really think a good specific answer can be given but I would say that a pitcher would throw an average of 20-30 pitches in the bullpen starting with soft warm up tosses and ending with full speed hard stuff.
Answer: It really depends on the individual pitcher. You are granted 8 pitches when brought in during an inning but while in the bullpen, you basically throw until you're ready and only you know that.


How do I print the node creation timestamp in a computed field?

Question: I want to store the node creation timestamp in a computed field. I know I should use date_format(), but I don't know which code should I use for the field value.
Which code should I use?
Answer: $timestamp = date($entity->created);


How do I remove this blank space to the left of this header?

Question: I've started recently learning css and html by myself, and I wanted to make a header/banner at the top of the page with some menus etc., but I realized that there is this "gap" to the left of the header.
This is my css for this header.
.header {
    background: #555;
    color: #f1f1f1;
    position: fixed;
    top: 0;
    width: 100%;
    margin: 0 auto;
}

this is the html

Comment: please post your HTML and CSS
Comment: Please provide your html code as well
Comment: Use `* { margin: 0; padding: 0; }`
Comment: i added the html
Comment: Where is your image?
Comment: oh wait i thought i added it
Comment: ok its added now
Answer: You can try again with this code.
You have to set left: 0;

.header {
    background: #555;
    color: #f1f1f1;
    position: fixed;
    top: 0;
    width: 100%;
    margin: 0 auto;
    left: 0;
}

Hype RP


Diferença entre duas datas em dias, horas, minutos e segundos

Question: Problema: Como realizar a subtração entre duas datas  e retornar o valor em Dias, Horas, Minutos e Segundos em uma consulta SQL com SQL Server 2014?
Exemplo:
Dados:

DataRecebimento          DataEnvio
2013-11-29 11:30:40.157  2014-05-27 14:10:50.637
2013-11-29 17:30:40.157  2014-05-27 14:10:50.637

Resultado pretendido (intervalo entre as datas):
179d 03:40:10
178d 21:40:10

Comment: Bem-vindo ao Stack Overflow em Português! Por favor explique melhor o problema, e se possível inclua um [exemplo de código que reproduza o que está acontecendo](http://pt.stackoverflow.com/help/mcve), pois está ampla demais a sua pergunta. Usa MySQL, SQLServer, etc? [Veja na Central de Ajuda Como Perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Comment: Via TransactSQL, use `DATEDIFF`. http://msdn.microsoft.com/en-us/library/ms189794.aspx
Comment: Veja se este link esclarece sua dúvida http://msdn.microsoft.com/pt-br/library/ms189794.aspx
Comment: Fiz alguns calculos com data:
http://adjuniordba.wordpress.com/2014/01/30/calculo-simples-de-data/ []´s
Answer: DECLARE @antes DATETIME = '2013-11-29 11:30:40.157';
DECLARE @depois DATETIME = '2014-05-27 14:10:50.637';

SELECT  CONVERT(VARCHAR, DATEDIFF(DAY, @antes, @depois)) + 'd '
        + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(HOUR, @antes, @depois) % 24), 2) + ':'
        + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(MINUTE, @antes, @depois) % 60), 2) + ':'
        + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(SECOND, @antes, @depois) % 60), 2);

Ou em forma de função abaixo (com tratamentos adicionais):
CREATE FUNCTION dbo.fnCalculaTempo
(
    @antes DATETIME, @depois DATETIME
)
RETURNS VARCHAR(20)
AS
BEGIN
    DECLARE @temp DATETIME;
    IF (@antes > @depois)
    BEGIN
        SET @temp = @antes;
        SET @antes = @depois;
        SET @depois = @temp;
    END
    RETURN  CASE WHEN @temp IS NULL THEN '' ELSE '-' END
            + CASE WHEN DATEDIFF(DAY, @antes, @depois) <> 0 THEN CONVERT(VARCHAR, DATEDIFF(DAY, @antes, @depois)) + 'd ' ELSE '' END
            + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(HOUR, @antes, @depois) % 24), 2) + ':'
            + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(MINUTE, @antes, @depois) % 60), 2) + ':'
            + RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(SECOND, @antes, @depois) % 60), 2);
END
GO

Testes com valores negativos (@depois antes de @antes):
SELECT dbo.fnCalculaTempo('2013-11-29 11:30:40.157', '2014-05-27 14:10:50.637');
SELECT dbo.fnCalculaTempo('2013-11-29 17:30:40.157', '2014-05-27 14:10:50.637');
SELECT dbo.fnCalculaTempo('2013-11-29 17:30:40.157', '2013-11-29 18:34:00.249');
SELECT dbo.fnCalculaTempo('2014-11-29 11:30:50.157', '2014-11-29 10:30:50.637');
SELECT dbo.fnCalculaTempo('2014-11-29 10:30:50.157', '2014-11-28 10:30:40.637');

Comment: ^^ hehehe tirou minhas duvidas, só melhorando um pouquinho a query, pela lógica se eu tenho um horário no *@depois menor que no *@antes eu não tenho um dia corrido ainda. O DATEDIFF tem esse bug ao calcular os dias corridos, e era isso que tava me matando.... Desculpem se eu não expressei minha duvida mais claramente, pois tinha ficado a sexta feira inteira quebrando a cabeça.
Comment: @Fredguapo, troquei a função para que ela tratasse os valores negativos. Acho que faz mais sentido e é mais simples trocar os valores antes, dá uma olhada em como ficou. A alteração que você tinha sugerido fazia com que quando tivesse 1 hora negativa passasse a mostrar 1 dia e 1 hora negativos.
Answer: Este código está errado no cálculo da diferença de horas. A diferença da hora deve ser assim:
+ RIGHT('00' + CONVERT(VARCHAR, DATEDIFF(MINUTE, @antes, @depois) / 60), 2) + ':'

Pois no seguinte exemplo:
SELECT (SUM(DATEDIFF(HOUR,'2015-05-03 10:42:00','2015-05-03 12:00:00')) % 24)

O select acima vai retornar 2 horas e o select abaixo vai retornar corretamente 1 hora, pois a diferença é de 1 hora e 18 minutos.
SELECT (SUM(DATEDIFF(MINUTE,'2015-05-03 10:42:00','2015-05-03 12:00:00')) / 60)

Answer: Encontrei essa solução para o problema das horas:
CONVERT(VARCHAR, ABS(DATEDIFF(SECOND, 2013-11-29 11:30:40.157, 2014-05-27 14:10:50.637) / 60 / 60 / 24))
                    + 'd ' + RIGHT('00' + CONVERT(VARCHAR, ABS(((DATEDIFF(SECOND, 2013-11-29 11:30:40.157, 2014-05-27 14:10:50.637) / 60) / 60) % 24)), 2)
                    + ':' + RIGHT('00' + CONVERT(VARCHAR, ABS((DATEDIFF(SECOND, 2013-11-29 11:30:40.157, 2014-05-27 14:10:50.637) / 60) % 60)), 2)
                    + ':' + RIGHT('00' + CONVERT(VARCHAR, ABS(DATEDIFF(SECOND, 2013-11-29 11:30:40.157, 2014-05-27 14:10:50.637) % 60)), 2)

Answer: Mesmo com a correção proposta na resposta número 3, a função não retorna os valores corretos. Segue a função com alterações na forma de cálculo:
CREATE FUNCTION dbo.fnComputeDateDiff
(
    @dtStartDate DATETIME, @dtEndDate DATETIME, @Mode CHAR
)
RETURNS VARCHAR(20)
AS
BEGIN
    DECLARE @Temp DATETIME;
    DECLARE @Days    INT
    DECLARE @Hours   INT
    DECLARE @Minutes INT
    DECLARE @Seconds INT
    DECLARE @TotalSeconds INT
    DECLARE @Ret VARCHAR(20)

    SET @Ret = ''

    IF (@dtStartDate IS NOT NULL AND @dtEndDate IS NOT NULL AND @Mode IN ('H','D'))
       BEGIN
          IF (@dtStartDate > @dtEndDate)
             BEGIN
                 SET @temp = @dtStartDate;
                 SET @dtStartDate = @dtEndDate;
                 SET @dtEndDate = @temp;
             END

          SET @TotalSeconds = DATEDIFF(SECOND, @dtStartDate, @dtEndDate)

          SET @Days = @TotalSeconds / 86400
          SET @TotalSeconds = @TotalSeconds % 86400
          SET @Hours = @TotalSeconds / 3600
          SET @TotalSeconds = @TotalSeconds % 3600
          SET @Minutes = @TotalSeconds / 60
          SET @Seconds = @TotalSeconds % 60

          IF @Mode = 'H'
             BEGIN
                SET @Hours = @Hours + @Days * 24
                SET @Days = 0
             END

          SET @Ret = CASE @Days WHEN 0 THEN '' ELSE RTrim( Convert(Char,@Days)) + ' d ' END
          SET @Ret = @Ret + Right(RTrim(Convert(Char,@Hours)),10) + ':'
          SET @Ret = @Ret + Right('00' + RTrim(Convert(Char,@Minutes)),2) + ':'
          SET @Ret = @Ret + Right('00' + RTrim(Convert(Char,@Seconds)),2)

       END

    RETURN @Ret
END

GO

Comment: Ao ler a sua resposta fiquei na dúvida se este código está ou não correcto ou apenas incorpora a correcção proposta na resposta 3. Quando fizer referência a um outro poste faça-o indicando o nome do autor, porque a numeração das respostas depende da opção de ordenação.
Comment: Note que o número que aparece na resposta é o número de votos e não o número de sequência.
Answer: Versão mais compacta:
SELECT FORMAT(FLOOR(CAST(@depois-@antes AS FLOAT)),'0d ')+FORMAT(@depois-@antes,'hh:mm:ss')

A MS, numa série de produtos, define internamente a data como o número de dias desde 1/1/1900. A diferença entre duas data resulta precisamente na diferença de dias.


Coletar nome da categoria WordPress

Question: Estou tentando coletar o nome da categoria com o seguinte código
<a href="<?php get_cat_name( $cat_id ); ?>">

Porem não estou tendo muito sucesso.. outra coisa é, eu tenho umas 4 categorias porem o código precisa saber se esta utilizando categoria a ou b dentro das 4, se não tiver nenhuma categoria que seja a A ou a B não mostra nada.. se alguém puder me ajudar.
Answer: A função get_cat_name retorna uma string como informado na documentação, e em sua linha onde você coloca a tag a você não esta usando o echo nem <?= para exibir o nome.
<a href="<?php echo get_cat_name( $cat_id ); ?>">

OU
<a href="<?= get_cat_name( $cat_id ); ?>">

Com relação a verificação você pode fazer um simples if
<a href="<? echo (get_cat_name( $cat_id ) == 'a' || get_cat_name( $cat_id ) == 'b') ? 'exibe o resultado' : ''; ?>">

Substitua o "exibe o resultado" pelo resultado que você quer que apareça caso a categoria a ou categoria b exista
Comment: Olá Rafael, obrigado pela ajuda, usei o codigo porem não funcionou:  >>
Comment: que erro deu @RenatoAssis?
Comment: Não funcionou @RafaelAcioly
Comment: @RenatoAssis como você colocou o código?
Comment: da mesma forma que você vê acima >
Comment: @RenatoAssis sugiro que você estudo um pouco mais de `PHP` para prosseguir com o uso do `wordpress` sem dor de cabeça, alterei a resposta para que fique mais claro.
Comment: Eu não entendo de PHP mais vou me virando das formas que consigo... vc não entendeu muito bem o que eu quero, não preciso exibir um resultado especifico preciso que exiba apenas o nome da categoria.. se for A exibe o nome A se for B exibe o nome B, se não for A nem B não exibe nada.. nada mais que isso se puder ajudar fico grato.
Comment: Entendo que o exibir resultado seria o ideal inserir a função que informa o nome da categoria, mais é ai que eu não consigo.. não sei a função que vai fazer isso.. já tentei de todas as formas.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/53568/discussion-between-renato-assis-and-rafael-acioly).
Comment: Poderia passar mais informações? - @RafaelAcioly

Coletar nome da categoria WordPress


Custom RecyclerView adapter won't allow onBindViewHolder to use pre-defined ViewHolder

Question: I'm pretty new to android development, and I'm trying to create a custom adpater to provide a RecyclerView with a view containing just an image and a textview.
However, I'm trying to define a simple extended ViewHolder for onBindViewHolder(VH, int) and android studio simply will not take the custom ViewHolder, 'MyViewHolder' - saying that "the method does not override method from its superclass."
It's fine if I make the parameter into just a regular RecyclerView.ViewHolder...but I need the extra variables in MyViewHolder.
Finally, I tried altering the 'extends' declaration for the class, as per N.T.'s suggestion, but this did nothing.
Please, any help would be great!
public class ProductAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList CategoryNames;
private ArrayList CategoryImages;
private Context Context;

public ProductAdapter(Context context, ArrayList categoryNames, ArrayList categoryImages){
    this.Context = context;
    this.CategoryNames = categoryImages;
    this.CategoryImages = categoryImages;
}

private class MyViewHolder extends RecyclerView.ViewHolder {
    // initialise the item view's
    TextView name;
    ImageView image;

    private MyViewHolder(View itemView) {
        super(itemView);
        // get the reference of item view's
        name = (TextView) itemView.findViewById(R.id.name);
        image = (ImageView) itemView.findViewById(R.id.image);
    }
}

@Override
public int getItemCount() {
    return CategoryNames.size();
}

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
    // set the data in items
    holder.name.setText(CategoryNames.get(position).toString());
    holder.image.setImageResource(CategoryImages.get(position));
    // implement setOnClickListener event on item view.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // display a toast with person name on item click
            Toast.makeText(Context, CategoryNames.get(position).toString(),
                    Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    // infalte the item Layout
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_product, parent, false);
    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
    return vh;
}
}

Answer: Change
public class ProductAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolderr> {

to
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder>

It will work now
Comment: Also, change the access modifier of `MyViewHolder` from `private` to `public`.
Answer: You can write it like this
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {

   private ArrayList CategoryNames;
   private ArrayList CategoryImages;
   private Context Context;

   public ProductAdapter(Context context, ArrayList categoryNames, ArrayList categoryImages){
         this.Context = context;
         this.CategoryNames = categoryImages;
         this.CategoryImages = categoryImages;
   }

   private class MyViewHolder extends RecyclerView.ViewHolder {

       // initialise the item view's
       TextView name;
       ImageView image;

       private MyViewHolder(View itemView) {

           super(itemView);
           // get the reference of item view's
           name = (TextView) itemView.findViewById(R.id.name);
           image = (ImageView) itemView.findViewById(R.id.image);
       }

    }

    @Override
    public int getItemCount() {

        return CategoryNames.size();

    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position){
         // set the data in items
         holder.name.setText(CategoryNames.get(position).toString());
         holder.image.setImageResource(CategoryImages.get(position));
        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {

             @Override
             public void onClick(View view) {
                  // display a toast with person name on item click
                  Toast.makeText(Context, CategoryNames.get(position).toString(),
                  Toast.LENGTH_SHORT).show();
              }
        });
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
       // infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_product, parent, false);
      // set the view's size, margins, paddings and layout parameters
       MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
       return vh;
     }
}

Comment: Thanks! Works just fine now.


Coarse location from cell id (OpenCellId)

Question: I have a device which reports me the GSM cell towers in sees:

ID (Cell Id)
MCC (Mobile country code)
MNC (Mobile network code)
LA (Location Area code)
RxL (Received signal strength level) - mosly useless since trasmitter power is unknown
Ta (Timing Advance) - distance to the cell tower (only for the active one)

Having the data from OpenCellId, I can get the location of each cell tower. But how do I get the coarse location of the device itself?

What circle radius to use, when TA is only known for a single tower, and RxL does not map to an absolute value?
How to use N cells, where N=1,2,4?
Which algorithms are available for this?
Known pitfalls?
Comment: Related: http://stackoverflow.com/questions/2813615/trilateration-using-3-latitude-and-longitude-points-and-3-distances
Answer: http://en.wikipedia.org/wiki/Trilateration and http://en.wikipedia.org/wiki/Triangulation are two algorithms commonly used in this case.  How much information do you get beyond just tower ids?
Comment: Forgot the cell id, sorry :) Your links are correct, but precisely 3 circles are used, and my device can report less, or more. Also it's   not clear how to define the circle radius since the TA is only known for a single one. Signal power is usless as transmitter power is a variable