Wednesday, November 26, 2014

#codingexercise
Int GetDistinctSum(int [] A)
{
if (A == null) return 0;
return A.DistinctSum();
}
We were reviewing the non-linear conjugate gradient method. We set the residual to the negation of the gradient. We compute the Gram Schmidt conjugation of the residuals to find the search directions. We find the step length by ensuring that the gradient is orthogonal to the search direction. We solve for the component  gradient of next step transposed applied to current search direction to be zero. We set the Gram Schmidt constants by one of two techniques : Fletcher Reeves (FR) formula and Polak Ribiere (PR) formula. FR was used in linear CG method and is easy to compute.PR is similar but uses the difference of the next residual from the current instead of just using the next residual. FR converges if the starting point is close to the desired minimum. PR may or may not converge but when it does it is quicker than FR. To force the convergence in the PR case, we ignore negative values of the constant and choose zero instead.  This is equivalent to restarting the CG search where we forget the previous search directions and start it in the direction of the steepest descent.
We see that in the non-linear CG case, there are fewer convergence guarantees. If the function of the next step is chosen such that it deviates from the quadratic form, the search directions tend to lose conjugacy. Moreover, the global minimum may not be found and even a local minimum may not be found if the function has no lower bound.
A useful technique to improve convergence is to restart CG after every n iterations. This is particularly true when n is small. This follows from the fact that CG can only generate n conjugate vectors in n-dimensional space.
In the non-linear CG, we could also use a fast algorithm to find the zero of the gradient transposed search vector.  If the gradient is a polynomial in step length, two iterative methods for zero-finding are the Newton Raphson method and the Secant method.  Newton Raphson (NR) method also requires that the second-derivative of the function on initial step and step-length in the direction of the search vector be computable. NR method  relies on Taylor series approximation in terms of the function, its first derivative and second derivative. By setting this approximation to zero and finding the steplength, we get a truncated Taylor series which approximates the function with a parabola. Using these, NR method constructs a quadratic approximation of the function and a new point is chosen at the base of the parabola. This procedure is iterated until convergence is reached. To perform an exact line search of the non-quadratic form, repeated steps may need to be taken along the line until the gradient transposed search direction is zero and therefore the CG iteration may include several Newton-Raphson iterations. This is inexpensive or expensive depending on the second derivative. To perform an exact line search without computing the second derivative, the secant method approximates the function by evaluating the first derivative at distinct points where the step length is zero and the step-length is an arbitrary small non-zero number. Like the NR method, the secant method also approximates the function with a parabola but instead of using the first and second derivative at a point, it finds the first derivative at two different points. Both the Newton-Raphson and the Secant methods iterations are done when the answer is reasonably close to the exact solution.
#codingexercise
Int GetDistinctMin (int [] A)
{
if (A == null) return 0;
return A.DistinctMin ();
}

Tuesday, November 25, 2014

We continue our discussion on Conjugate Gradient method. We review the non-linear conjugate gradient method. CG can be used not only to find the minimum point of a quadratic form but to  minimize any continuous function where the gradient can be computed. CG for the non-linear forms have the following challenges:
1) the recursive formula for residual cannot be calculated.
2) the step size alpha is difficult to calculate although we still use a linear expression using alpha to compute the next step but a function of it and we try to minimize  it.
3) and the Gram-Schmidt constants have many choices
We set the residual to be the negative of the gradient. The search directions are computed by the Gram-Schmidt conjugation of the residuals as with linear CG.
To overcome 1 we set the residual to be the negative of the gradient.
To overcome 2 we minimize the function
To overcome 3 we use one of two different techniques to choose the constants

Int GetDistinctMax (int [] A)

{

if (A == null) return 0;

return A.DistinctMax ();

}


Monday, November 24, 2014

In today's post we continue our discussion on Conjugate Gradients method. We looked at the effectiveness of a preconditioner in solving the linear matrix equation. CG can also be used to solve equations where the matrix A in the linear equation is not symmetric, not positive-definite, and even not square. In such a case we minimize the sum of squares of the errors because there may not be a solution. To find this minimum, we set the derivative of the linear expression to zero. We do this by applying A-transpose on both sides of the linear equation . When the matrix A is not a square, there are possibly more linearly independent equations than variables which may not have a solution.  This is called an over-constrained equation. But it is always possible to find a value of x that minimizes sum of squares. A-transpose A is symmetric and positive. In such cases, Steepest Descent and CG can be used to solve the linear equation. The only nuisance is that the condition number of A-transpose A is the square of A and the convergence is much slower. Also, the linear equation may be underconstrained when there are less equations than variables, then using the transpose doesn't help and CG cannot be applied.  That said, when we use this technique, we apply the A-transpose A, we never form it explicitly because it is less sparse than A. Instead it is formed by finding the product Ad, and then the transpose is applied to the product.
#codingexercise
Int GetDistinct (int [] A)
{
if (A == null) return 0;
return A.Distinct ();
}


Sunday, November 23, 2014

Sample python flask server to issue tokens based on OTT mentioned in earlier post:
# coding: utf-8

from datetime import datetime, timedelta
from flask import Flask
from flask import session, request
from flask import render_template, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import gen_salt
from flask_oauthlib.provider import OAuth2Provider
from tokenprovider import TokenProvider
from json import dumps
import random
import string

app = Flask(__name__, template_folder='templates')
app.debug = True
app.secret_key = ''.join([random.choice(string.digits +
                   string.ascii_uppercase) for x in range(0, 32)])
app.config.update({
    'SQLALCHEMY_DATABASE_URI': 'mysql://root:thepassword@127.0.0.1/token',
})
db = SQLAlchemy(app)
oauth = OAuth2Provider(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(40), unique=True)
    salt = db.Column(db.String(4))

class Token(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(
        db.Integer, db.ForeignKey('user.id')
    )
    user = db.relationship('User')

    # currently only bearer is supported
    token_type = db.Column(db.String(40))

    access_token = db.Column(db.String(6))


@app.route('/', methods=('GET', 'POST'))
def home():
    if request.method == 'POST':
        username = request.args.get('username','')
        user = User.query.filter_by(username=username).first()
        if not user:
            user = User(username=username,
             salt=''.join([random.choice(string.digits + string.ascii_uppercase)
            for x in range(0, 4)]
            ))
            db.session.add(user)
            db.session.commit()
        session['id'] = user.id
        print str(session)
        return redirect('/')
    user = None
    if 'id' in session:
         uid = session['id']
         user= User.query.get(uid)
    return jsonify({'msg': 'welcome,'+ str(user), 'success':'success'}), 200

@ott.tokengetter
def check_token(access_token=None):
    if access_token:
        return Token.query.filter_by(access_token=access_token).first()
    return None

@app.route('/session/', methods=('GET'))
def session():
     sessions = list()
     [sessions.append(i) for i in db.session]
     return jsonify ({'sessions': json.dumps(sessions)}), 200

@ott.tokensetter
def save_token(token, request, *args, **kwargs):
    id = User.query.filter_by(username=request.args.get('username','')).first().id
    toks = Token.query.filter_by(
       user_id = id
    ).all()
    # make sure that every client has only one token connected to a user
    db.session.delete(toks)
    tp = TokenProvider()
    tok = Token(user=request.args.get('username',''),
                token_type='bearer', access_token=tp.set_token())
    tok.save()
    tok.user_id = request.user.id
    db.session.add(tok)
    db.session.commit()
    return tok


if __name__ == '__main__':
    db.create_all()
    app.run(debug=True,port=8787)
In today's post we continue our discussion on how an OTP provider can replace the tokens used by an API for checking authorization. In this case, the we will call it an OTT provider. An OTT provider converts all users/ digests/sessions/cookies  to track users into tokens. A TOTP 6 digit number as usually provided by OTP  providers. These tokens not only replace the credentials but also serve to maintain sessions. With the API only accepting tokens, there is no need to track anything else. In a way there is no repository required fro the API implementations to see if there is a token associated with a user or a client. The token itself has both pieces - 'what you know' and 'what you have' and the API implementation can validate the token the same way as when the caller did after requesting it.
There are only three players:
A token provider that issues and validates token
An API client that requests tokens from the token provider and validates it
An API server that accepts only tokens and validates it from the same token provider.
Tamper proofing the request or encrypting the transport layer is not part of this discussion but considered necessary.
Although the OTT is enclosed with the request and sent over the wire, it is temporary and gives the api what is needed.
OTP is covered in RFC 2289 which states that there are two entities in the operation of the OneTimePassword system. The generator must produce the appropriate one-time password from the user's secret pass phrase,  and from the information provided in the challenge from the server. The server must send a challenge that includes the appropriate generation parameters to the generator, must verify the one time password received, must store the last one time password it received, and must store the corresponding one-time password sequence number. The server must also facilitate the changing of the users' secret passphrase in a secure manner.
Int GetDistinctMean (int [] A)
{

if (A == null) return 0;

return A.GetDistinctMean ();

}

Saturday, November 22, 2014

Int GetDistinctMedian (int [] A)

{

if (A == null) return 0;

return A.GetDistinctMedian ();

}
Here's what a token provider server would implement:

Class TokenProvider ()
        Def login(self, request):
                Token = OneTimeToken ()
                 Session.Add (token)
                 Return token
        Def logout (self, request, token):
                token= Token.lookup (request)
                If token:
                           Token.remove (token)
                            Session.remove (token)
        Def refresh_token (token):
                Return Token.refresh (token)
        Def validateToken (token):
                Return OTT.validateToken
OTT defined at https://github.com/ravibeta/pythonexamples/tokenprovider.py      
and https://github.com/ravibeta/PythonExamples/blob/master/tokenserver.py