text:
//! \todo multi-thread randproj moves

#pragma once

#include "drwnNNGraph.h"
#include "drwnNNGraphMoves.h"

using namespace std;
using namespace Eigen;

// drwnNNGraphThreadedMoves --------------------------------------------------
//! Templated drwnNNGraph search moves (multi-threaded).

namespace drwnNNGraphThreadedMoves {
    //! randomly initialize edges (matched) for all active images (keeps existing
    //! matches unless an improvement is found)
    template<class DistanceMetric>
    void initialize(drwnNNGraph& graph, const DistanceMetric& M);

    //! randomly initialize edges (matched) for all active images (keeps existing
    //! matches unless an improvement is found) using default metric
    inline void initialize(drwnNNGraph& graph) { initialize(graph, drwnNNGraphDefaultMetric()); }

    //! rescore all matches based on current features (which may have changed
    //! since graph was created)
    template<class DistanceMetric>
    double rescore(drwnNNGraph& graph, const DistanceMetric& M);

    //! rescore all matches based on current features (which may have changed
    //! since graph was created) using default metric
    inline double rescore(drwnNNGraph& graph) { return rescore(graph, drwnNNGraphDefaultMetric()); }

    //! perform one update iteration (including enrichment and exhaustive)
    //! on all active images
    template<class DistanceMetric>
    void update(drwnNNGraph& graph, const DistanceMetric& M);

    //! perform one update iteration (including enrichment and exhaustive)
    //! on all active images using default metric
    inline void update(drwnNNGraph& graph) { update(graph, drwnNNGraphDefaultMetric()); }

    //! perform single update iteration of propagate, local and search moves
    //! on a specific image
    template<class DistanceMetric>
    void updateImage(drwnNNGraph& graph, unsigned imgIndx, const DistanceMetric& M);

    //! random projection moves that project all superpixels onto a random
    //! direction, sort and compare adjacent superpixels if from different
    //! images (returns true if a better match was found)
    template<class DistanceMetric>
    bool randproj(drwnNNGraph& graph, const DistanceMetric& M);

    //! enrichment: inverse (from target to source) and forward (from
    //! source to target's target) (returns true if a better match was found)
    template<class DistanceMetric>
    bool enrichment(drwnNNGraph& graph, const DistanceMetric& M);

    //! threading initialize functor
    template<class DistanceMetric>
    class drwnNNGraphThreadedInitializeJob : public drwnThreadJob {
    protected:
        const DistanceMetric& _M;        //!< distance metric to use during moves
        set<unsigned> _imgIndxes;        //!< indexes of images for this job
        drwnNNGraph& _graph;             //!< graph for updating (includes features)

    public:
        drwnNNGraphThreadedInitializeJob(const set<unsigned>& imgIndxes, drwnNNGraph& g,
            const DistanceMetric& M) : _M(M), _imgIndxes(imgIndxes), _graph(g) { /* do nothing */ }
        ~drwnNNGraphThreadedInitializeJob() { /* do nothing */ }

        void operator()() {
            for (set<unsigned>::const_iterator it = _imgIndxes.begin(); it != _imgIndxes.end(); ++it) {
                drwnNNGraphMoves::initialize(_graph, *it, _M);
            }
        }
    };

    //! threading rescore functor
    template<class DistanceMetric>
    class drwnNNGraphThreadedRescoreJob : public drwnThreadJob {
    protected:
        const DistanceMetric& _M;        //!< distance metric to use during moves
        set<unsigned> _imgIndxes;        //!< indexes of images for this job
        drwnNNGraph& _graph;             //!< graph for updating (includes features)

    public:
        drwnNNGraphThreadedRescoreJob(const set<unsigned>& imgIndxes, drwnNNGraph& g,
            const DistanceMetric& M) : _M(M), _imgIndxes(imgIndxes), _graph(g) { /* do nothing */ }
        ~drwnNNGraphThreadedRescoreJob() { /* do nothing */ }

        void operator()() {
            for (set<unsigned>::const_iterator it = _imgIndxes.begin(); it != _imgIndxes.end(); ++it) {
                drwnNNGraphMoves::rescore(_graph, *it, _M);
            }
        }
    };

    //! threading update functor
    template<class DistanceMetric>
    class drwnNNGraphThreadedUpdateJob : public drwnThreadJob {
    protected:
        const DistanceMetric& _M;        //!< distance metric to use during moves
        set<unsigned> _imgIndxes;        //!< indexes of images for this job
        drwnNNGraph& _graph;             //!< graph for updating (includes features)

    public:
        drwnNNGraphThreadedUpdateJob(const set<unsigned>& imgIndxes, drwnNNGraph& g,
            const DistanceMetric& M) : _M(M), _imgIndxes(imgIndxes), _graph(g) { /* do nothing */ }
        ~drwnNNGraphThreadedUpdateJob() { /* do nothing */ }

        void operator()() {
            for (set<unsigned>::const_iterator it = _imgIndxes.begin(); it != _imgIndxes.end(); ++it) {
                drwnNNGraphThreadedMoves::updateImage(_graph, *it, _M);
            }
        }
    };

    //! threading exhaustive functor
    template<class DistanceMetric>
    class drwnNNGraphThreadedExhaustiveJob : public drwnThreadJob {
    protected:
        const DistanceMetric& _M;        //!< distance metric to use during moves
        set<drwnNNGraphNodeIndex> _nodeIndxes; //!< indexes of nodes for this job
        drwnNNGraph& _graph;             //!< graph for updating (includes features)

    public:
        drwnNNGraphThreadedExhaustiveJob(const set<drwnNNGraphNodeIndex>& nodeIndxes, drwnNNGraph& g,
            const DistanceMetric& M) : _M(M),  _nodeIndxes(nodeIndxes), _graph(g) { /* do nothing */ }
        ~drwnNNGraphThreadedExhaustiveJob() { /* do nothing */ }

        void operator()() {
            for (set<drwnNNGraphNodeIndex>::const_iterator it = _nodeIndxes.begin(); it != _nodeIndxes.end(); ++it) {
                drwnNNGraphMoves::exhaustive(_graph, *it, _M);
            }
        }
    };
};

// drwnNNGraphThreadedMoves implementation -----------------------------------

template<class DistanceMetric>
void drwnNNGraphThreadedMoves::initialize(drwnNNGraph& graph, const DistanceMetric& M)
{
    // prepare thread data
    const unsigned nJobs = std::min((unsigned)graph.numImages(),
        std::max((unsigned)1, drwnThreadPool::MAX_THREADS));
    vector<set<unsigned> > imgIndxes(nJobs);
    for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
        if (!graph[imgIndx].bSourceMatchable) {
            DRWN_LOG_DEBUG("...skipping initialization of " << graph[imgIndx].name());
            continue;
        }

        imgIndxes[imgIndx % nJobs].insert(imgIndx);
    }

    // start threads
    drwnThreadPool threadPool(nJobs);
    threadPool.start();
    vector<drwnNNGraphThreadedInitializeJob<DistanceMetric> *> jobs(nJobs);
    for (unsigned i = 0; i < nJobs; i++) {
        jobs[i] = new drwnNNGraphThreadedInitializeJob<DistanceMetric>(imgIndxes[i], graph, M);
        threadPool.addJob(jobs[i]);
    }
    threadPool.finish();

    for (unsigned i = 0; i < jobs.size(); i++) {
        delete jobs[i];
    }
    jobs.clear();
}

template<class DistanceMetric>
double drwnNNGraphThreadedMoves::rescore(drwnNNGraph& graph, const DistanceMetric& M)
{
    DRWN_FCN_TIC;

    // prepare thread data
    const unsigned nJobs = std::min((unsigned)graph.numImages(),
        std::max((unsigned)1, drwnThreadPool::MAX_THREADS));
    vector<set<unsigned> > imgIndxes(nJobs);
    for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
        imgIndxes[imgIndx % nJobs].insert(imgIndx);
    }

    // start threads
    drwnThreadPool threadPool(nJobs);
    threadPool.start();
    vector<drwnNNGraphThreadedRescoreJob<DistanceMetric> *> jobs(nJobs);
    for (unsigned i = 0; i < nJobs; i++) {
        jobs[i] = new drwnNNGraphThreadedRescoreJob<DistanceMetric>(imgIndxes[i], graph, M);
        threadPool.addJob(jobs[i]);
    }
    threadPool.finish();

    for (unsigned i = 0; i < jobs.size(); i++) {
        delete jobs[i];
    }
    jobs.clear();

    DRWN_FCN_TOC;
    return graph.energy().first;
}

template<class DistanceMetric>
void drwnNNGraphThreadedMoves::update(drwnNNGraph& graph, const DistanceMetric& M)
{
    DRWN_FCN_TIC;

    // try improve a bad match (from a random (active) image)
    if (drwnNNGraph::DO_EXHAUSTIVE > 0) {
        // sum scores of nodes from active images
        double totalWeight = 0.0;
        for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
            if (!graph[imgIndx].bSourceMatchable) continue;
            for (unsigned segId = 0; segId < graph[imgIndx].numNodes(); segId++) {
                const drwnNNGraphEdgeList& e = graph[imgIndx][segId].edges;
                if (e.empty()) continue;

                totalWeight += (double)e.front().weight;
            }
        }

        // randomly sample n nodes
        set<drwnNNGraphNodeIndex> sampledNodes;
        for (int i = 0; i < drwnNNGraph::DO_EXHAUSTIVE; i++) {

            // sample the weight
            double weight = totalWeight * drand48();

            // find the node
            for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
                if (!graph[imgIndx].bSourceMatchable) continue;
                for (unsigned segId = 0; segId < graph[imgIndx].numNodes(); segId++) {
                    const drwnNNGraphEdgeList& e = graph[imgIndx][segId].edges;
                    if (e.empty()) continue;

                    // skip if already sampled this node
                    if (sampledNodes.find(drwnNNGraphNodeIndex(imgIndx, segId)) != sampledNodes.end())
                        continue;

                    weight -= (double)e.front().weight;
                    if (weight <= 0.0) {
                        // add node to set of samples and remove from totalWeight
                        sampledNodes.insert(drwnNNGraphNodeIndex(imgIndx, segId));
                        totalWeight -= (double)e.front().weight;
                        break;
                    }
                }
                if (weight <= 0.0) break;
            }
        }

        // start threads for exhuastive search on nodes
        if (sampledNodes.size() == 1) {
            drwnNNGraphMoves::exhaustive(graph, *sampledNodes.begin(), M);
        } else {
            drwnThreadPool threadPool;
            threadPool.start();
            vector<drwnNNGraphThreadedExhaustiveJob<DistanceMetric> *> jobs;
            for (set<drwnNNGraphNodeIndex>::const_iterator it = sampledNodes.begin(); it != sampledNodes.end(); ++it) {
                set<drwnNNGraphNodeIndex> nodeIndexes;
                nodeIndexes.insert(*it);
                jobs.push_back(new drwnNNGraphThreadedExhaustiveJob<DistanceMetric>(nodeIndexes, graph, M));
                threadPool.addJob(jobs.back());
            }
            threadPool.finish();

            for (unsigned i = 0; i < jobs.size(); i++) {
                delete jobs[i];
            }
            jobs.clear();
        }
    }

    // random projection
    if (drwnNNGraph::DO_RANDPROJ > 0) {
        randproj(graph, M);
    }

    // propagation moves
    if (drwnNNGraph::DO_PROPAGATE || drwnNNGraph::DO_LOCAL || drwnNNGraph::DO_SEARCH) {
        // prepare thread data
        const unsigned nJobs = std::min((unsigned)graph.numImages(),
            std::max((unsigned)1, drwnThreadPool::MAX_THREADS));
        vector<set<unsigned> > imgIndxes(nJobs);
        for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
            if (!graph[imgIndx].bSourceMatchable) {
                DRWN_LOG_DEBUG("...skipping update of " << graph[imgIndx].name());
                continue;
            }

            imgIndxes[imgIndx % nJobs].insert(imgIndx);
        }

        // start threads
        drwnThreadPool threadPool(nJobs);
        threadPool.start();
        vector<drwnNNGraphThreadedUpdateJob<DistanceMetric> *> jobs(nJobs);
        for (unsigned i = 0; i < nJobs; i++) {
            jobs[i] = new drwnNNGraphThreadedUpdateJob<DistanceMetric>(imgIndxes[i], graph, M);
            threadPool.addJob(jobs[i]);
        }
        threadPool.finish();

        for (unsigned i = 0; i < jobs.size(); i++) {
            delete jobs[i];
        }
        jobs.clear();
    }

    // enrichment (forward and inverse)
    if (drwnNNGraph::DO_ENRICHMENT) {
        enrichment(graph, M);
    }

    DRWN_FCN_TOC;
}

template<class DistanceMetric>
void drwnNNGraphThreadedMoves::updateImage(drwnNNGraph& graph, unsigned imgIndx, const DistanceMetric& M)
{
    // perform update on each node
    drwnNNGraphNodeIndex u(imgIndx, 0);
    for (u.segId = 0; u.segId < graph[u.imgIndx].numNodes(); u.segId++) {
        if (drwnNNGraph::DO_LOCAL) {
            drwnNNGraphMoves::local(graph, u, M);
        }
        if (drwnNNGraph::DO_PROPAGATE) {
            drwnNNGraphMoves::propagate(graph, u, M);
        }
        if (drwnNNGraph::DO_SEARCH) {
            drwnNNGraphMoves::search(graph, u, M);
        }
    }
}

template<class DistanceMetric>
bool drwnNNGraphThreadedMoves::randproj(drwnNNGraph& graph, const DistanceMetric& M)
{
    DRWN_FCN_TIC;
    bool bChanged = false;

    // pick a random direction
    VectorXf mu(graph[0][0].features.size());
    for (int i = 0; i < mu.rows(); i++) {
        mu[i] = float(drand48() - 0.5);
    }
    mu /= mu.norm();

    // project all superpixels
    vector<pair<float, drwnNNGraphNodeIndex> > projections;
    projections.reserve(graph.numNodes());

    drwnNNGraphNodeIndex u;
    for (u.imgIndx = 0; u.imgIndx < graph.numImages(); u.imgIndx++) {
        for (u.segId = 0; u.segId < graph[u.imgIndx].numNodes(); u.segId++) {
            const float x = mu.dot(graph[u].features);
            projections.push_back(make_pair(x, u));
        }
    }

    // sort
    sort(projections.begin(), projections.end());

    // score
    unsigned dbCountChanged = 0;
    unsigned inext = 0;
    for (unsigned i = 0; i < projections.size() - 1; i++) {
        const drwnNNGraphNodeIndex &u = projections[i].second;

        // don't update inactive images
        if (!graph[u.imgIndx].bSourceMatchable || graph[u].edges.empty()) {
            if (inext <= i) inext += 1;
            continue;
        }

        // skip if images are in the same equivalence class
        while (inext != projections.size()) {
            if (graph[projections[inext].second.imgIndx].bTargetMatchable &&
                !graph.inSameEqvClass(u.imgIndx, projections[inext].second.imgIndx))
                break;
            inext += 1;
        }

        if (inext == projections.size()) break;

        float uworst = sqrt(graph[u].edges.back().weight);
        for (unsigned j = inext; j < std::min(projections.size(), (size_t)(inext + drwnNNGraph::DO_RANDPROJ)); j++) {
            // cauchy-schwarz check
            if ((projections[j].first - projections[i].first) >= uworst) {
                break;
            }

            // equivalence class check
            if (!graph[projections[j].second.imgIndx].bTargetMatchable) continue;
            if (graph.inSameEqvClass(u.imgIndx, projections[j].second.imgIndx))
                continue;

            // evaluate edge candidate
            const drwnNNGraphNodeIndex &v = projections[j].second;

            if (M.isFinite(graph[u], graph[v])) {
                const float w = M.score(graph[u], graph[v]);
                if (graph[u].insert(drwnNNGraphEdge(v, w))) {
                    uworst = sqrt(graph[u].edges.back().weight);
                    dbCountChanged += 1;
                    bChanged = true;
                }
            }
        }
    }

    DRWN_LOG_DEBUG("randproj() improved " << dbCountChanged << " matches");
    DRWN_FCN_TOC;
    return bChanged;
}

template<class DistanceMetric>
bool drwnNNGraphThreadedMoves::enrichment(drwnNNGraph& graph, const DistanceMetric& M)
{
    DRWN_FCN_TIC;
    bool bChanged = false;

    // inverse enrichment
    for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
        // skip image if not target matchable
        if (!graph[imgIndx].bTargetMatchable) continue;

        for (unsigned segId = 0; segId < graph[imgIndx].numNodes(); segId++) {
            const drwnNNGraphEdgeList& el = graph[imgIndx][segId].edges;
            for (drwnNNGraphEdgeList::const_iterator kt = el.begin(); kt != el.end(); ++kt) {

                // skip if not active
                if (!graph[kt->targetNode.imgIndx].bSourceMatchable)
                    continue;

                // evaluate reverse edge
                const drwnNNGraphEdge e(drwnNNGraphNodeIndex(imgIndx, segId), kt->weight);
                if (graph[kt->targetNode].insert(e)) {
                    bChanged = true;
                }
            }
        }
    }

    // forward enrichment
    for (unsigned imgIndx = 0; imgIndx < graph.numImages(); imgIndx++) {
        // only do forward enrichment on active images
        if (!graph[imgIndx].bSourceMatchable) continue;

        for (unsigned segId = 0; segId < graph[imgIndx].numNodes(); segId++) {
            // needed to prevent invalid iterators when updating e
            const drwnNNGraphEdgeList el(graph[imgIndx][segId].edges);

            int nCompared = (int)drwnNNGraph::K; // prevent quadratic growth in K
            for (drwnNNGraphEdgeList::const_iterator it = el.begin(); it != el.end(); ++it) {
                const drwnNNGraphEdgeList& r = graph[it->targetNode].edges;

                for (drwnNNGraphEdgeList::const_iterator kt = r.begin(); kt != r.end(); ++kt) {
                    // check that we're not matching back to ourself (or any other
                    // image in the same equivalence class) and is matchable
                    if (!graph[kt->targetNode.imgIndx].bTargetMatchable) continue;
                    if (graph.inSameEqvClass(kt->targetNode.imgIndx, imgIndx)) continue;

                    // check that we have processed this pair previously
                    if ((it->status == DRWN_NNG_PROCESSED_TWICE) &&
                        (kt->status == DRWN_NNG_PROCESSED_TWICE)) continue;

                    // check that edge is legal
                    if (!M.isFinite(graph[imgIndx][segId], graph[kt->targetNode]))
                        continue;

                    const float w = M.score(graph[imgIndx][segId], graph[kt->targetNode]);
                    if (graph[imgIndx][segId].insert(drwnNNGraphEdge(kt->targetNode, w))) {
                        bChanged = true;
                    }

                    nCompared -= 1;
                    if (nCompared < 0) break;
                }

                if (nCompared < 0) break;
            }
        }
    }

    DRWN_FCN_TOC;
    return bChanged;
}


text:
package ginglog

import (
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang/glog"
)

func setupLogging(duration time.Duration) {
	go func() {
		for range time.Tick(duration) {
			glog.Flush()
		}
	}()
}

var (
	green   = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
	white   = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
	yellow  = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
	red     = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
	blue    = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
	magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
	cyan    = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
	reset   = string([]byte{27, 91, 48, 109})
)

// ErrorLogger returns an ErrorLoggerT with parameter gin.ErrorTypeAny
func ErrorLogger() gin.HandlerFunc {
	return ErrorLoggerT(gin.ErrorTypeAny)
}

// ErrorLoggerT returns an ErrorLoggerT middleware with the given
// type gin.ErrorType.
func ErrorLoggerT(typ gin.ErrorType) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if !c.Writer.Written() {
			json := c.Errors.ByType(typ).JSON()
			if json != nil {
				c.JSON(-1, json)
			}
		}
	}
}

// Logger prints a logline for each request and measures the time to
// process for a call. It formats the log entries similar to
// http://godoc.org/github.com/gin-gonic/gin#Logger does.
//
// Example:
//        router := gin.New()
//        router.Use(ginglog.Logger(3 * time.Second))
func Logger(duration time.Duration) gin.HandlerFunc {
	setupLogging(duration)
	return func(c *gin.Context) {
		t := time.Now()

		// process request
		c.Next()

		latency := time.Since(t)
		clientIP := c.ClientIP()
		method := c.Request.Method
		statusCode := c.Writer.Status()
		statusColor := colorForStatus(statusCode)
		methodColor := colorForMethod(method)
		path := c.Request.URL.Path

		switch {
		case statusCode >= 400 && statusCode <= 499:
			{
				glog.Warningf("[GIN] |%s %3d %s| %12v | %s |%s  %s %-7s %s\n%s",
					statusColor, statusCode, reset,
					latency,
					clientIP,
					methodColor, reset, method,
					path,
					c.Errors.String(),
				)
			}
		case statusCode >= 500:
			{
				glog.Errorf("[GIN] |%s %3d %s| %12v | %s |%s  %s %-7s %s\n%s",
					statusColor, statusCode, reset,
					latency,
					clientIP,
					methodColor, reset, method,
					path,
					c.Errors.String(),
				)
			}
		default:
			glog.V(2).Infof("[GIN] |%s %3d %s| %12v | %s |%s  %s %-7s %s\n%s",
				statusColor, statusCode, reset,
				latency,
				clientIP,
				methodColor, reset, method,
				path,
				c.Errors.String(),
			)
		}

	}
}

func colorForStatus(code int) string {
	switch {
	case code >= 200 && code <= 299:
		return green
	case code >= 300 && code <= 399:
		return white
	case code >= 400 && code <= 499:
		return yellow
	default:
		return red
	}
}

func colorForMethod(method string) string {
	switch {
	case method == "GET":
		return blue
	case method == "POST":
		return cyan
	case method == "PUT":
		return yellow
	case method == "DELETE":
		return red
	case method == "PATCH":
		return green
	case method == "HEAD":
		return magenta
	case method == "OPTIONS":
		return white
	default:
		return reset
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.playfab;

import java.util.HashMap;
import java.util.Date;

public class RemoveFriendResult
{

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Engler & Prantl, Nat. Pflanzenfam. (Leipzig), Teil. <b>I</b> 1: 89 (1893)

#### Original name
Lagenidiaceae J. Schröt.

### Remarks
null


text:
<?php

use \Mockery as m;

class ClientTest extends TestCase {

    /** @test */
    public function client_can_be_instantiated()
    {
        $guzzle = m::mock('\GuzzleHttp\Client');

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);

        $this->assertInstanceOf(\DarkGold\Salesforce\Client::class, $sfClient);
    }

    /** @test */
    public function client_can_be_statically_instantiated()
    {
        $sfClient = \DarkGold\Salesforce\Client::create('loginUrl', 'clientId', 'clientSecret');

        $this->assertInstanceOf(\DarkGold\Salesforce\Client::class, $sfClient);
    }

    /** @test */
    public function client_will_get_record()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');
        $response->shouldReceive('getBody')->once()->andReturn(json_encode(['foo' => 'bar']));

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('get')->with(stringContainsInOrder('Test', $recordId, 'field1,field2') , \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $data = $sfClient->getRecord('Test', $recordId, ['field1', 'field2']);

        $this->assertEquals(['foo' => 'bar'], $data);
    }

    /** @test */
    public function client_can_search()
    {
        $response = m::mock('Psr\Http\Message\ResponseInterface');
        $response->shouldReceive('getBody')->once()->andReturn(json_encode(['records' => [], 'done' => true]));

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('get')->with(stringContainsInOrder('SELECT+Name+FROM+Lead+LIMIT+10') , \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $sfClient->search('SELECT Name FROM Lead LIMIT 10');
    }

    /** @test */
    public function client_can_create_record()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');
        $response->shouldReceive('getBody')->once()->andReturn(json_encode(['id' => $recordId]));

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('post')->with(containsString('Test') , \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $data = $sfClient->createRecord('Test', ['field1', 'field2']);

        $this->assertEquals($recordId, $data);
    }

    /** @test */
    public function client_can_update_record()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('patch')->with(stringContainsInOrder('Test', $recordId) , \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $data = $sfClient->updateRecord('Test', $recordId, ['field1', 'field2']);

        $this->assertTrue($data);
    }

    /** @test */
    public function client_can_delete_record()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('delete')->with(stringContainsInOrder('Test', $recordId), \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $data = $sfClient->deleteRecord('Test', $recordId);

        $this->assertTrue($data);
    }

    /** @test */
    public function client_can_complete_auth_process()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');
        $response->shouldReceive('getBody')->once()->andReturn(json_encode(['id' => $recordId]));

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('post')->with(stringContainsInOrder('services/oauth2/token'), \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $sfClient->authorizeConfirm('authCode', 'redirectUrl');
    }

    /** @test */
    public function client_can_complete_token_refresh_process()
    {
        $recordId = 'abc' . rand(1000, 9999999);

        $response = m::mock('Psr\Http\Message\ResponseInterface');
        $response->shouldReceive('getBody')->once()->andReturn(json_encode(['id' => $recordId]));

        $guzzle = m::mock('\GuzzleHttp\Client');
        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('post')->with(stringContainsInOrder('services/oauth2/token'), \Mockery::type('array'))->once()->andReturn($response);

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $accessToken = $this->getAccessTokenMock();
        $accessToken->shouldReceive('updateFromSalesforceRefresh');
        $sfClient->setAccessToken($accessToken);

        $sfClient->refreshToken();
    }

    /** @test */
    public function client_can_get_login_url()
    {
        $guzzle = m::mock('\GuzzleHttp\Client');

        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        $url = $sfClient->getLoginUrl('redirectUrl');

        $this->assertNotFalse(strpos($url, 'redirectUrl'));
    }

    /**
     * @test
     * @expectedException        DarkGold\Salesforce\Exceptions\RequestException
     * @expectedExceptionMessage expired authorization code
     */
    public function client_can_parse_auth_flow_error()
    {
        //Error Response
        $errorResponse = m::mock('Psr\Http\Message\ResponseInterface');
        $errorResponse->shouldReceive('getBody')->once()->andReturn('{"error_description":"expired authorization code","error":"invalid_grant"}');
        $errorResponse->shouldReceive('getStatusCode')->once()->andReturn(400);

        //Make guzzle throw an exception with the above message
        $guzzle = m::mock('\GuzzleHttp\Client');
        $guzzleException = m::mock('GuzzleHttp\Exception\RequestException');
        $guzzleException->shouldReceive('getResponse')->andReturn($errorResponse);

        //Make sure the url contains the passed in data
        $guzzle->shouldReceive('post')->with(stringContainsInOrder('services/oauth2/token'), \Mockery::type('array'))->once()->andThrow($guzzleException);

        //Setup the client
        $sfClient = new \DarkGold\Salesforce\Client($this->getClientConfigMock(), $guzzle);
        $sfClient->setAccessToken($this->getAccessTokenMock());

        //Try the auth flow - this should generate an exception
        $sfClient->authorizeConfirm('authCode', 'redirectUrl');
    }

    /**
     * Mock the client config interface
     * @return m\MockInterface
     */
    private function getClientConfigMock()
    {
        $config = m::mock('DarkGold\Salesforce\ClientConfigInterface');
        $config->shouldReceive('getLoginUrl')->once()->andReturn('http://login.example.com');
        $config->shouldReceive('getClientId')->once()->andReturn('client_id');
        $config->shouldReceive('getClientSecret')->once()->andReturn('client_secret');
        return $config;
    }

    private function getAccessTokenMock()
    {
        $accessToken = m::mock('DarkGold\Salesforce\AccessToken');
        $accessToken->shouldReceive('getApiUrl')->andReturn('http://api.example.com');
        $accessToken->shouldReceive('getAccessToken')->andReturn('123456789abcdefghijk');
        $accessToken->shouldReceive('getRefreshToken')->andReturn('refresh123456789abcdefghijk');
        return $accessToken;
    }
}


text:
package gov.nih.nci.rembrandt.queryservice.queryprocessing.ge.annotations;

import gov.nih.nci.rembrandt.dbbean.GenePathway;
import gov.nih.nci.rembrandt.dbbean.GeneOntology;

/**
 * User: Ram Bhattaru

 * Date: Feb 1, 2006

 * Version: 1.0

 */
public interface GeneDimension {
    Class getDimensionClass();
    String getGeneSymbolAttr();
    String getAttr();

    public class PathwayDimension implements GeneDimension {
        public Class getDimensionClass() {
            return GenePathway.class;
        }

        public String getGeneSymbolAttr() {
            return GenePathway.GENE_SYMBOL;
        }

        public String getAttr() {
            return GenePathway.PATHWAY_NAME;
        }
    }

    public class OntologyDimension implements GeneDimension {
        public Class getDimensionClass() {
            return GeneOntology.class;
        }

        public String getGeneSymbolAttr() {
            return GeneOntology.GENE_SYMBOL;
        }

        public String getAttr() {
            return GeneOntology.GO_ID;
        }
    }
}


text:
//===---- Mips16HardFloat.cpp for Mips16 Hard Float               --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a pass needed for Mips16 Hard Float
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "mips16-hard-float"
#include "Mips16HardFloat.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <string>

static void inlineAsmOut
  (LLVMContext &C, StringRef AsmString, BasicBlock *BB ) {
  std::vector<llvm::Type *> AsmArgTypes;
  std::vector<llvm::Value*> AsmArgs;
  llvm::FunctionType *AsmFTy =
    llvm::FunctionType::get(Type::getVoidTy(C),
                            AsmArgTypes, false);
  llvm::InlineAsm *IA =
    llvm::InlineAsm::get(AsmFTy, AsmString, "", true,
                         /* IsAlignStack */ false,
                         llvm::InlineAsm::AD_ATT);
  CallInst::Create(IA, AsmArgs, "", BB);
}

namespace {

class InlineAsmHelper {
  LLVMContext &C;
  BasicBlock *BB;
public:
  InlineAsmHelper(LLVMContext &C_, BasicBlock *BB_) :
    C(C_), BB(BB_) {
  }

  void Out(StringRef AsmString) {
    inlineAsmOut(C, AsmString, BB);
  }

};
}
//
// Return types that matter for hard float are:
// float, double, complex float, and complex double
//
enum FPReturnVariant {
  FRet, DRet, CFRet, CDRet, NoFPRet
};

//
// Determine which FP return type this function has
//
static FPReturnVariant whichFPReturnVariant(Type *T) {
  switch (T->getTypeID()) {
  case Type::FloatTyID:
    return FRet;
  case Type::DoubleTyID:
    return DRet;
  case Type::StructTyID:
    if (T->getStructNumElements() != 2)
      break;
    if ((T->getContainedType(0)->isFloatTy()) &&
        (T->getContainedType(1)->isFloatTy()))
      return CFRet;
    if ((T->getContainedType(0)->isDoubleTy()) &&
        (T->getContainedType(1)->isDoubleTy()))
      return CDRet;
    break;
  default:
    break;
  }
  return NoFPRet;
}

//
// Parameter type that matter are float, (float, float), (float, double),
// double, (double, double), (double, float)
//
enum FPParamVariant {
  FSig, FFSig, FDSig,
  DSig, DDSig, DFSig, NoSig
};

// which floating point parameter signature variant we are dealing with
//
typedef Type::TypeID TypeID;
const Type::TypeID FloatTyID = Type::FloatTyID;
const Type::TypeID DoubleTyID = Type::DoubleTyID;

static FPParamVariant whichFPParamVariantNeeded(Function &F) {
  switch (F.arg_size()) {
  case 0:
    return NoSig;
  case 1:{
    TypeID ArgTypeID = F.getFunctionType()->getParamType(0)->getTypeID();
    switch (ArgTypeID) {
    case FloatTyID:
      return FSig;
    case DoubleTyID:
      return DSig;
    default:
      return NoSig;
    }
  }
  default: {
    TypeID ArgTypeID0 = F.getFunctionType()->getParamType(0)->getTypeID();
    TypeID ArgTypeID1 = F.getFunctionType()->getParamType(1)->getTypeID();
    switch(ArgTypeID0) {
    case FloatTyID: {
      switch (ArgTypeID1) {
      case FloatTyID:
        return FFSig;
      case DoubleTyID:
        return FDSig;
      default:
        return FSig;
      }
    }
    case DoubleTyID: {
      switch (ArgTypeID1) {
      case FloatTyID:
        return DFSig;
      case DoubleTyID:
        return DDSig;
      default:
        return DSig;
      }
    }
    default:
      return NoSig;
    }
  }
  }
  llvm_unreachable("can't get here");
}

// Figure out if we need float point based on the function parameters.
// We need to move variables in and/or out of floating point
// registers because of the ABI
//
static bool needsFPStubFromParams(Function &F) {
  if (F.arg_size() >=1) {
    Type *ArgType = F.getFunctionType()->getParamType(0);
    switch (ArgType->getTypeID()) {
      case Type::FloatTyID:
      case Type::DoubleTyID:
        return true;
      default:
        break;
    }
  }
  return false;
}

static bool needsFPReturnHelper(Function &F) {
  Type* RetType = F.getReturnType();
  return whichFPReturnVariant(RetType) != NoFPRet;
}

static bool needsFPHelperFromSig(Function &F) {
  return needsFPStubFromParams(F) || needsFPReturnHelper(F);
}

//
// We swap between FP and Integer registers to allow Mips16 and Mips32 to
// interoperate
//

static void swapFPIntParams
  (FPParamVariant PV, Module *M, InlineAsmHelper &IAH,
   bool LE, bool ToFP) {
  //LLVMContext &Context = M->getContext();
  std::string MI = ToFP? "mtc1 ": "mfc1 ";
  switch (PV) {
  case FSig:
    IAH.Out(MI + "$$4,$$f12");
    break;
  case FFSig:
    IAH.Out(MI +"$$4,$$f12");
    IAH.Out(MI + "$$5,$$f14");
    break;
  case FDSig:
    IAH.Out(MI + "$$4,$$f12");
    if (LE) {
      IAH.Out(MI + "$$6,$$f14");
      IAH.Out(MI + "$$7,$$f15");
    } else {
      IAH.Out(MI + "$$7,$$f14");
      IAH.Out(MI + "$$6,$$f15");
    }
    break;
  case DSig:
    if (LE) {
      IAH.Out(MI + "$$4,$$f12");
      IAH.Out(MI + "$$5,$$f13");
    } else {
      IAH.Out(MI + "$$5,$$f12");
      IAH.Out(MI + "$$4,$$f13");
    }
    break;
  case DDSig:
    if (LE) {
      IAH.Out(MI + "$$4,$$f12");
      IAH.Out(MI + "$$5,$$f13");
      IAH.Out(MI + "$$6,$$f14");
      IAH.Out(MI + "$$7,$$f15");
    } else {
      IAH.Out(MI + "$$5,$$f12");
      IAH.Out(MI + "$$4,$$f13");
      IAH.Out(MI + "$$7,$$f14");
      IAH.Out(MI + "$$6,$$f15");
    }
    break;
  case DFSig:
    if (LE) {
      IAH.Out(MI + "$$4,$$f12");
      IAH.Out(MI + "$$5,$$f13");
    } else {
      IAH.Out(MI + "$$5,$$f12");
      IAH.Out(MI + "$$4,$$f13");
    }
    IAH.Out(MI + "$$6,$$f14");
    break;
  case NoSig:
    return;
  }
}
//
// Make sure that we know we already need a stub for this function.
// Having called needsFPHelperFromSig
//
static void assureFPCallStub(Function &F, Module *M,
                             const MipsSubtarget &Subtarget){
  // for now we only need them for static relocation
  if (Subtarget.getRelocationModel() == Reloc::PIC_)
    return;
  LLVMContext &Context = M->getContext();
  bool LE = Subtarget.isLittle();
  std::string Name = F.getName();
  std::string SectionName = ".mips16.call.fp." + Name;
  std::string StubName = "__call_stub_fp_" + Name;
  //
  // see if we already have the stub
  //
  Function *FStub = M->getFunction(StubName);
  if (FStub && !FStub->isDeclaration()) return;
  FStub = Function::Create(F.getFunctionType(),
                           Function::InternalLinkage, StubName, M);
  FStub->addFnAttr("mips16_fp_stub");
  FStub->addFnAttr(llvm::Attribute::Naked);
  FStub->addFnAttr(llvm::Attribute::NoInline);
  FStub->addFnAttr(llvm::Attribute::NoUnwind);
  FStub->addFnAttr("nomips16");
  FStub->setSection(SectionName);
  BasicBlock *BB = BasicBlock::Create(Context, "entry", FStub);
  InlineAsmHelper IAH(Context, BB);
  IAH.Out(".set reorder");
  FPReturnVariant RV = whichFPReturnVariant(FStub->getReturnType());
  FPParamVariant PV = whichFPParamVariantNeeded(F);
  swapFPIntParams(PV, M, IAH, LE, true);
  if (RV != NoFPRet) {
    IAH.Out("move $$18, $$31");
    IAH.Out("jal " + Name);
  } else {
    IAH.Out("lui  $$25,%hi(" + Name + ")");
    IAH.Out("addiu  $$25,$$25,%lo(" + Name + ")" );
  }
  switch (RV) {
  case FRet:
    IAH.Out("mfc1 $$2,$$f0");
    break;
  case DRet:
    if (LE) {
      IAH.Out("mfc1 $$2,$$f0");
      IAH.Out("mfc1 $$3,$$f1");
    } else {
      IAH.Out("mfc1 $$3,$$f0");
      IAH.Out("mfc1 $$2,$$f1");
    }
    break;
  case CFRet:
    if (LE) {
    IAH.Out("mfc1 $$2,$$f0");
    IAH.Out("mfc1 $$3,$$f2");
    } else {
      IAH.Out("mfc1 $$3,$$f0");
      IAH.Out("mfc1 $$3,$$f2");
    }
    break;
  case CDRet:
    if (LE) {
      IAH.Out("mfc1 $$4,$$f2");
      IAH.Out("mfc1 $$5,$$f3");
      IAH.Out("mfc1 $$2,$$f0");
      IAH.Out("mfc1 $$3,$$f1");

    } else {
      IAH.Out("mfc1 $$5,$$f2");
      IAH.Out("mfc1 $$4,$$f3");
      IAH.Out("mfc1 $$3,$$f0");
      IAH.Out("mfc1 $$2,$$f1");
    }
    break;
  case NoFPRet:
    break;
  }
  if (RV != NoFPRet)
    IAH.Out("jr $$18");
  else
    IAH.Out("jr $$25");
  new UnreachableInst(Context, BB);
}

//
// Returns of float, double and complex need to be handled with a helper
// function.
//
static bool fixupFPReturnAndCall
  (Function &F, Module *M,  const MipsSubtarget &Subtarget) {
  bool Modified = false;
  LLVMContext &C = M->getContext();
  Type *MyVoid = Type::getVoidTy(C);
  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    for (BasicBlock::iterator I = BB->begin(), E = BB->end();
         I != E; ++I) {
      Instruction &Inst = *I;
      if (const ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
        Value *RVal = RI->getReturnValue();
        if (!RVal) continue;
        //
        // If there is a return value and it needs a helper function,
        // figure out which one and add a call before the actual
        // return to this helper. The purpose of the helper is to move
        // floating point values from their soft float return mapping to
        // where they would have been mapped to in floating point registers.
        //
        Type *T = RVal->getType();
        FPReturnVariant RV = whichFPReturnVariant(T);
        if (RV == NoFPRet) continue;
        static const char* Helper[NoFPRet] =
          {"__mips16_ret_sf", "__mips16_ret_df", "__mips16_ret_sc",
           "__mips16_ret_dc"};
        const char *Name = Helper[RV];
        AttributeSet A;
        Value *Params[] = {RVal};
        Modified = true;
        //
        // These helper functions have a different calling ABI so
        // this __Mips16RetHelper indicates that so that later
        // during call setup, the proper call lowering to the helper
        // functions will take place.
        //
        A = A.addAttribute(C, AttributeSet::FunctionIndex,
                           "__Mips16RetHelper");
        A = A.addAttribute(C, AttributeSet::FunctionIndex,
                           Attribute::ReadNone);
        A = A.addAttribute(C, AttributeSet::FunctionIndex,
                           Attribute::NoInline);
        Value *F = (M->getOrInsertFunction(Name, A, MyVoid, T, NULL));
        CallInst::Create(F, Params, "", &Inst );
      } else if (const CallInst *CI = dyn_cast<CallInst>(I)) {
          // pic mode calls are handled by already defined
          // helper functions
          if (Subtarget.getRelocationModel() != Reloc::PIC_ ) {
            Function *F_ =  CI->getCalledFunction();
            if (F_ && needsFPHelperFromSig(*F_)) {
              assureFPCallStub(*F_, M, Subtarget);
              Modified=true;
            }
          }
      }
    }
  return Modified;
}

static void createFPFnStub(Function *F, Module *M, FPParamVariant PV,
                  const MipsSubtarget &Subtarget ) {
  bool PicMode = Subtarget.getRelocationModel() == Reloc::PIC_;
  bool LE = Subtarget.isLittle();
  LLVMContext &Context = M->getContext();
  std::string Name = F->getName();
  std::string SectionName = ".mips16.fn." + Name;
  std::string StubName = "__fn_stub_" + Name;
  std::string LocalName = "__fn_local_" + Name;
  Function *FStub = Function::Create
    (F->getFunctionType(),
     Function::InternalLinkage, StubName, M);
  FStub->addFnAttr("mips16_fp_stub");
  FStub->addFnAttr(llvm::Attribute::Naked);
  FStub->addFnAttr(llvm::Attribute::NoUnwind);
  FStub->addFnAttr(llvm::Attribute::NoInline);
  FStub->addFnAttr("nomips16");
  FStub->setSection(SectionName);
  BasicBlock *BB = BasicBlock::Create(Context, "entry", FStub);
  InlineAsmHelper IAH(Context, BB);
  IAH.Out(" .set  macro");
  if (PicMode) {
    IAH.Out(".set noreorder");
    IAH.Out(".cpload  $$2");
    IAH.Out(".set reorder");
    IAH.Out(".reloc 0,R_MIPS_NONE," + Name);
    IAH.Out("la $$25," + LocalName);
  }
  else
    IAH.Out("la $$25, " + Name);
  swapFPIntParams(PV, M, IAH, LE, false);
  IAH.Out("jr $$25");
  IAH.Out(LocalName + " = " + Name);
  new UnreachableInst(FStub->getContext(), BB);
}

namespace llvm {

//
// This pass only makes sense when the underlying chip has floating point but
// we are compiling as mips16.
// For all mips16 functions (that are not stubs we have already generated), or
// declared via attributes as nomips16, we must:
//    1) fixup all returns of float, double, single and double complex
//       by calling a helper function before the actual return.
//    2) generate helper functions (stubs) that can be called by mips32 functions
//       that will move parameters passed normally passed in floating point
//       registers the soft float equivalents.
//    3) in the case of static relocation, generate helper functions so that
//       mips16 functions can call extern functions of unknown type (mips16 or
//       mips32).
//    4) TBD. For pic, calls to extern functions of unknown type are handled by
//       predefined helper functions in libc but this work is currently done
//       during call lowering but it should be moved here in the future.
//
bool Mips16HardFloat::runOnModule(Module &M) {
  DEBUG(errs() << "Run on Module Mips16HardFloat\n");
  bool Modified = false;
  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
    if (F->isDeclaration() || F->hasFnAttribute("mips16_fp_stub") ||
        F->hasFnAttribute("nomips16")) continue;
    Modified |= fixupFPReturnAndCall(*F, &M, Subtarget);
    FPParamVariant V = whichFPParamVariantNeeded(*F);
    if (V != NoSig) {
      Modified = true;
      createFPFnStub(F, &M, V, Subtarget);
    }
  }
  return Modified;
}

char Mips16HardFloat::ID = 0;

}

ModulePass *llvm::createMips16HardFloat(MipsTargetMachine &TM) {
  return new Mips16HardFloat(TM);
}


text: Unknown Organization


text:
layout: post
title:  "Shoot 'em up tutorial: 4 - Projectiles"
date:   2017-6-10 18:48:11 +0200
author: arcadio
categories: tutorial shootemup
heropic: /pictures/shootemup0.png
---

It doesn't matter if your ship is able to make the Kessel Run in less than 12 parsecs if it is unable to defend against hordes of villainous aliens, so the next step will be to add some firepower.
First, let's add this spritesheet that defines some nice bright red projectiles:

{% highlight xml %}
  <spritesheet name="playerFire" src="images/spaceships.png">
    <states>
      <state name="Idle">
        <layer name="Idle"></layer>
      </state>
    </states>
    <layers>
      <layer name="Idle" x="-50" y="-30">
        <frame name="Idle1"></frame>
        <frame name="Idle2"></frame>
        <frame name="Idle1"></frame>
        <frame name="Idle3"></frame>
      </layer>
    </layers>
    <frames>
      <frame name="Idle1" x="400" y="0" w="100" h="100" t="50"></frame>
      <frame name="Idle2" x="400" y="100" w="100" h="100" t="50"></frame>
      <frame name="Idle3" x="400" y="200" w="100" h="100" t="50"></frame>
    </frames>
  </spritesheet>
{% endhighlight %}

Now, add this component to the list:
{% highlight js %}
{
        name: "playerFire",
        sprite: "playerFire",
        events: [
            {
                name: "#loop", code: function (event) {
                    this.var.$y -= 10;
                    if (this.var.$y < -50) {
                        this.engine.destroy(this);
                    }
                }
            },
            {
                name: "#collide", code: function (event) {
                    this.engine.destroy(this);
                }
            }]
    }
{% endhighlight %}

As you can see, it will use the desired spritesheet, and will move upwards 10 pixels each frame. When its position is 50 px above the upper edge of the screen, it will delete itself using the `this.engine.destroy` function. If you have not guessed it yet, methods of `this` interact with the current object, while methods of  `this.engine` interact with the whole level. It will also delete itself if it collides with something, but we will forget about that for now. Then, add the fire event to the list of events of playerShip:
{% highlight js %}
{
                name: "fire", code: function (event) {
                    if (Math.random() > 0.5) {
                        this.engine.spawn("somePlayerFire", "playerFire", { $x: this.var.$x + 40, $y: this.var.$y, $z: this.var.$z - 1 });
                    } else {
                        this.engine.spawn("somePlayerFire", "playerFire", { $x: this.var.$x + 70, $y: this.var.$y, $z: this.var.$z - 1 });
                    }
                }
            }
{% endhighlight %}

It will randomly shoot from either the left or right cannon, spawning a `playerFire` called somePlayerFire at the desired relative position. Deploy your game and press the space bar to see some nice fireworks!

You can continue to [part 5 of this tutorial]({{ site.baseurl }}{% post_url 2017-6-10-shootemup5 %}), where you will learn how to add some enemies.


text:
"""
Convenience functions for the construction of spatial weights based on
contiguity and distance criteria

"""

__author__ = "Sergio J. Rey <srey@asu.edu> "
__all__ = ['queen_from_shapefile', 'rook_from_shapefile', 'knnW_from_array', 'knnW_from_shapefile', 'threshold_binaryW_from_array', 'threshold_binaryW_from_shapefile', 'threshold_continuousW_from_array', 'threshold_continuousW_from_shapefile', 'kernelW', 'kernelW_from_shapefile', 'adaptive_kernelW', 'adaptive_kernelW_from_shapefile', 'min_threshold_dist_from_shapefile', 'build_lattice_shapefile']

import pysal
from Contiguity import buildContiguity
from Distance import knnW, Kernel, DistanceBand
from util import get_ids, get_points_array_from_shapefile, min_threshold_distance

def queen_from_shapefile(shapefile, idVariable=None, sparse=False):
    """
    Queen contiguity weights from a polygon shapefile

    Parameters
    ----------

    shapefile   : string
                  name of polygon shapefile including suffix.
    idVariable  : string
                  name of a column in the shapefile's DBF to use for ids.
    sparse    : boolean
                If True return WSP instance
                If False return W instance
    Returns
    -------

    w            : W
                   instance of spatial weights

    Examples
    --------
    >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"))
    >>> wq.pct_nonzero
    0.098292378175760101
    >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"),"POLYID")
    >>> wq.pct_nonzero
    0.098292378175760101
    >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True)
    >>> wq.sparse.nnz *1. / wq.n**2
    0.098292378175760101

    Notes
    -----

    Queen contiguity defines as neighbors any pair of polygons that share at
    least one vertex in their polygon definitions.

    See Also
    --------
    :class:`pysal.weights.W`

    """
    shp = pysal.open(shapefile)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
    else:
        ids = None
    w = buildContiguity(shp, criterion='queen', ids=ids)
    shp.close()

    if sparse:
        w = pysal.weights.WSP(w.sparse, id_order=ids)
    return w

def rook_from_shapefile(shapefile, idVariable=None, sparse=False):
    """
    Rook contiguity weights from a polygon shapefile

    Parameters
    ----------

    shapefile : string
                name of polygon shapefile including suffix.
    sparse    : boolean
                If True return WSP instance
                If False return W instance

    Returns
    -------

    w          : W
                 instance of spatial weights

    Examples
    --------
    >>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), "POLYID")
    >>> wr.pct_nonzero
    0.083298625572678045
    >>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True)
    >>> wr.sparse.nnz *1. / wr.n**2
    0.083298625572678045

    Notes
    -----

    Rook contiguity defines as neighbors any pair of polygons that share a
    common edge in their polygon definitions.

    See Also
    --------
    :class:`pysal.weights.W`

    """
    shp = pysal.open(shapefile)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
    else:
        ids = None
    w = buildContiguity(shp, criterion='rook', ids=ids)
    shp.close()
    if sparse:
        w = pysal.weights.WSP(w.sparse, id_order=ids)
    return w

def spw_from_gal(galfile):
    """
    Sparse scipy matrix for w from a gal file

    Parameters
    ----------

    galfile: string
             name of gal file including suffix

    Returns
    -------

    spw      : scipy sparse matrix in CSR format

    ids      : array
               identifiers for rows/cols of spw

    Examples
    --------

    >>> spw = pysal.weights.user.spw_from_gal(pysal.examples.get_path("sids2.gal"))
    >>> spw.sparse.nnz
    462
    """

    return pysal.open(galfile, 'r').read(sparse=True)

# Distance based weights

def knnW_from_array(array, k=2, p=2, ids=None, radius=None):
    """
    Nearest neighbor weights from a numpy array

    Parameters
    ----------

    data       : array (n,m)
                 attribute data, n observations on m attributes
    k          : int
                 number of nearest neighbors
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    ids        : list
                 identifiers to attach to each observation
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with binary weights

    Examples
    --------
    >>> import numpy as np
    >>> x,y=np.indices((5,5))
    >>> x.shape=(25,1)
    >>> y.shape=(25,1)
    >>> data=np.hstack([x,y])
    >>> wnn2=knnW_from_array(data,k=2)
    >>> wnn4=knnW_from_array(data,k=4)
    >>> wnn4.neighbors[0]
    [1, 5, 6, 2]
    >>> wnn4.neighbors[5]
    [0, 6, 10, 1]
    >>> wnn2.neighbors[0]
    [1, 5]
    >>> wnn2.neighbors[5]
    [0, 6]
    >>> wnn2.pct_nonzero
    0.080000000000000002
    >>> wnn4.pct_nonzero
    0.16
    >>> wnn4=knnW_from_array(data,k=4)
    >>> wnn4.neighbors[0]
    [1, 5, 6, 2]
    >>> wnn4=knnW_from_array(data,k=4)
    >>> wnn3e=knnW(data,p=2,k=3)
    >>> wnn3e.neighbors[0]
    [1, 5, 6]
    >>> wnn3m=knnW(data,p=1,k=3)
    >>> wnn3m.neighbors[0]
    [1, 5, 2]

    Notes
    -----

    Ties between neighbors of equal distance are arbitrarily broken.

    See Also
    --------
    :class:`pysal.weights.W`

    """
    if radius is not None:
        array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
    return knnW(array, k=k, p=p, ids=ids)

def knnW_from_shapefile(shapefile, k=2, p=2, idVariable=None, radius=None):
    """
    Nearest neighbor weights from a shapefile

    Parameters
    ----------

    shapefile  : string
                 shapefile name with shp suffix
    k          : int
                 number of nearest neighbors
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    idVariable : string
                 name of a column in the shapefile's DBF to use for ids
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with binary weights

    Examples
    --------

    Polygon shapefile

    >>> wc=knnW_from_shapefile(pysal.examples.get_path("columbus.shp"))
    >>> wc.pct_nonzero
    0.040816326530612242
    >>> wc3=knnW_from_shapefile(pysal.examples.get_path("columbus.shp"),k=3,idVariable="POLYID")
    >>> wc3.weights[1]
    [1, 1, 1]
    >>> wc3.neighbors[1]
    [3, 2, 4]
    >>> wc.neighbors[0]
    [2, 1]

    Point shapefile

    >>> w=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp"))
    >>> w.pct_nonzero
    0.011904761904761904
    >>> w1=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp"),k=1)
    >>> w1.pct_nonzero
    0.0059523809523809521
    >>>

    Notes
    -----

    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    Ties between neighbors of equal distance are arbitrarily broken.

    See Also
    --------
    :class:`pysal.weights.W`

    """

    data = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        data = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
        return knnW(data, k=k, p=p, ids=ids)
    return knnW(data, k=k, p=p)

def threshold_binaryW_from_array(array, threshold, p=2, radius=None):
    """
    Binary weights based on a distance threshold

    Parameters
    ----------

    array       : array (n,m)
                 attribute data, n observations on m attributes
    threshold  : float
                 distance band
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with binary weights

    Examples
    --------
    >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
    >>> w=threshold_binaryW_from_array(points,threshold=11.2)
    >>> w.weights
    {0: [1, 1], 1: [1, 1], 2: [], 3: [1, 1], 4: [1], 5: [1]}
    >>> w.neighbors
    {0: [1, 3], 1: [0, 3], 2: [], 3: [0, 1], 4: [5], 5: [4]}
    >>>
    """
    if radius is not None:
        array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
    return DistanceBand(array, threshold=threshold, p=p)

def threshold_binaryW_from_shapefile(shapefile, threshold, p=2, idVariable=None, radius=None):
    """
    Threshold distance based binary weights from a shapefile

    Parameters
    ----------

    shapefile  : string
                 shapefile name with shp suffix
    threshold  : float
                 distance band
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    idVariable : string
                 name of a column in the shapefile's DBF to use for ids
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with binary weights

    Examples
    --------
    >>> w = threshold_binaryW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID")
    >>> w.weights[1]
    [1, 1]

    Notes
    -----
    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    """
    data = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        data = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
        return DistanceBand(data, threshold=threshold, p=p, ids=ids)
    return threshold_binaryW_from_array(data, threshold, p=p)

def threshold_continuousW_from_array(array, threshold, p=2,
                                     alpha=-1, radius=None):

    """
    Continuous weights based on a distance threshold

    Parameters
    ----------

    array      : array (n,m)
                 attribute data, n observations on m attributes
    threshold  : float
                 distance band
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    alpha      : float
                 distance decay parameter for weight (default -1.0)
                 if alpha is positive the weights will not decline with
                 distance.
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with continuous weights

    Examples
    --------

    inverse distance weights

    >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
    >>> wid=threshold_continuousW_from_array(points,11.2)
    >>> wid.weights[0]
    [0.10000000000000001, 0.089442719099991588]

    gravity weights

    >>> wid2=threshold_continuousW_from_array(points,11.2,alpha=-2.0)
    >>> wid2.weights[0]
    [0.01, 0.0079999999999999984]

    """
    if radius is not None:
        array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
    w = DistanceBand(
        array, threshold=threshold, p=p, alpha=alpha, binary=False)
    return w

def threshold_continuousW_from_shapefile(shapefile, threshold, p=2,
                                         alpha=-1, idVariable=None, radius=None):
    """
    Threshold distance based continuous weights from a shapefile

    Parameters
    ----------

    shapefile  : string
                 shapefile name with shp suffix
    threshold  : float
                 distance band
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance
    alpha      : float
                 distance decay parameter for weight (default -1.0)
                 if alpha is positive the weights will not decline with
                 distance.
    idVariable : string
                 name of a column in the shapefile's DBF to use for ids
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w         : W instance
                Weights object with continuous weights

    Examples
    --------
    >>> w = threshold_continuousW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID")
    >>> w.weights[1]
    [1.6702346893743334, 1.7250729841938093]

    Notes
    -----
    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    """
    data = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        data = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
        return DistanceBand(data, threshold=threshold, p=p, alpha=alpha, binary=False, ids=ids)
    return threshold_continuousW_from_array(data, threshold, p=p, alpha=alpha)

# Kernel Weights

def kernelW(points, k=2, function='triangular', fixed=True, radius=None):
    """
    Kernel based weights

    Parameters
    ----------

    points      : array (n,k)
                  n observations on k characteristics used to measure
                  distances between the n objects
    k           : int
                  the number of nearest neighbors to use for determining
                  bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i`
                  where :math:`dknn` is a vector of k-nearest neighbor
                  distances (the distance to the kth nearest neighbor for each
                  observation).
    function    : string {'triangular','uniform','quadratic','epanechnikov',
                  'quartic','bisquare','gaussian'}

                  .. math::

                      z_{i,j} = d_{i,j}/h_i

                  triangular

                  .. math::

                      K(z) = (1 - |z|) \ if |z| \le 1

                  uniform

                  .. math::

                      K(z) = |z| \ if |z| \le 1

                  quadratic

                  .. math::

                      K(z) = (3/4)(1-z^2) \ if |z| \le 1

                  epanechnikov

                  .. math::

                      K(z) = (1-z^2) \ if |z| \le 1

                  quartic

                  .. math::

                      K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1

                  bisquare

                  .. math::

                      K(z) = (1-z^2)^2 \ if |z| \le 1

                  gaussian

                  .. math::

                      K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)

    fixed        : binary
                   If true then :math:`h_i=h \\forall i`. If false then
                   bandwidth is adaptive across observations.
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w            : W
                   instance of spatial weights

    Examples
    --------
    >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
    >>> kw=kernelW(points)
    >>> kw.weights[0]
    [1.0, 0.500000049999995, 0.4409830615267465]
    >>> kw.neighbors[0]
    [0, 1, 3]
    >>> kw.bandwidth
    array([[ 20.000002],
           [ 20.000002],
           [ 20.000002],
           [ 20.000002],
           [ 20.000002],
           [ 20.000002]])

    use different k

    >>> kw=kernelW(points,k=3)
    >>> kw.neighbors[0]
    [0, 1, 3, 4]
    >>> kw.bandwidth
    array([[ 22.36068201],
           [ 22.36068201],
           [ 22.36068201],
           [ 22.36068201],
           [ 22.36068201],
           [ 22.36068201]])
    """
    if radius is not None:
        points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
    return Kernel(points, function=function, k=k, fixed=fixed)

def kernelW_from_shapefile(shapefile, k=2, function='triangular', idVariable=None, fixed=True, radius=None):
    """
    Kernel based weights

    Parameters
    ----------

    shapefile   : string
                  shapefile name with shp suffix
    k           : int
                  the number of nearest neighbors to use for determining
                  bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i`
                  where :math:`dknn` is a vector of k-nearest neighbor
                  distances (the distance to the kth nearest neighbor for each
                  observation).
    function    : string {'triangular','uniform','quadratic','epanechnikov',
                  'quartic','bisquare','gaussian'}

                  .. math::

                      z_{i,j} = d_{i,j}/h_i

                  triangular

                  .. math::

                      K(z) = (1 - |z|) \ if |z| \le 1

                  uniform

                  .. math::

                      K(z) = |z| \ if |z| \le 1

                  quadratic

                  .. math::

                      K(z) = (3/4)(1-z^2) \ if |z| \le 1

                  epanechnikov

                  .. math::

                      K(z) = (1-z^2) \ if |z| \le 1

                  quartic

                  .. math::

                      K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1

                  bisquare

                  .. math::

                      K(z) = (1-z^2)^2 \ if |z| \le 1

                  gaussian

                  .. math::

                      K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
    idVariable   : string
                   name of a column in the shapefile's DBF to use for ids

    fixed        : binary
                   If true then :math:`h_i=h \\forall i`. If false then
                   bandwidth is adaptive across observations.
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w            : W
                   instance of spatial weights

    Examples
    --------
    >>> kw = kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"),idVariable='POLYID')
    >>> kw.weights[1]
    [0.2052478782400463, 0.007078773148450623, 1.0, 0.23051223027663237]
    >>> kw.bandwidth[:3]
    array([[ 0.75333961],
           [ 0.75333961],
           [ 0.75333961]])

    Notes
    -----
    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    """
    points = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
        return Kernel(points, function=function, k=k, ids=ids, fixed=fixed)
    return kernelW(points, k=k, function=function, fixed=fixed)

def adaptive_kernelW(points, bandwidths=None, k=2, function='triangular', radius=None):
    """
    Kernel weights with adaptive bandwidths

    Parameters
    ----------

    points      : array (n,k)
                  n observations on k characteristics used to measure
                  distances between the n objects
    bandwidths  : float or array-like (optional)
                  the bandwidth :math:`h_i` for the kernel.
                  if no bandwidth is specified k is used to determine the
                  adaptive bandwidth
    k           : int
                  the number of nearest neighbors to use for determining
                  bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i`
                  where :math:`dknn` is a vector of k-nearest neighbor
                  distances (the distance to the kth nearest neighbor for each
                  observation).  For adaptive bandwidths, :math:`h_i=dknn_i`
    function    : string {'triangular','uniform','quadratic','quartic','gaussian'}
                  kernel function defined as follows with

                  .. math::

                      z_{i,j} = d_{i,j}/h_i

                  triangular

                  .. math::

                      K(z) = (1 - |z|) \ if |z| \le 1

                  uniform

                  .. math::

                      K(z) = |z| \ if |z| \le 1

                  quadratic

                  .. math::

                      K(z) = (3/4)(1-z^2) \ if |z| \le 1

                  quartic

                  .. math::

                      K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1

                  gaussian

                  .. math::

                      K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)

    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w            : W
                   instance of spatial weights

    Examples
    --------

    User specified bandwidths

    >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
    >>> bw=[25.0,15.0,25.0,16.0,14.5,25.0]
    >>> kwa=adaptive_kernelW(points,bandwidths=bw)
    >>> kwa.weights[0]
    [1.0, 0.6, 0.552786404500042, 0.10557280900008403]
    >>> kwa.neighbors[0]
    [0, 1, 3, 4]
    >>> kwa.bandwidth
    array([[ 25. ],
           [ 15. ],
           [ 25. ],
           [ 16. ],
           [ 14.5],
           [ 25. ]])

    Endogenous adaptive bandwidths

    >>> kwea=adaptive_kernelW(points)
    >>> kwea.weights[0]
    [1.0, 0.10557289844279438, 9.99999900663795e-08]
    >>> kwea.neighbors[0]
    [0, 1, 3]
    >>> kwea.bandwidth
    array([[ 11.18034101],
           [ 11.18034101],
           [ 20.000002  ],
           [ 11.18034101],
           [ 14.14213704],
           [ 18.02775818]])

    Endogenous adaptive bandwidths with Gaussian kernel

    >>> kweag=adaptive_kernelW(points,function='gaussian')
    >>> kweag.weights[0]
    [0.3989422804014327, 0.2674190291577696, 0.2419707487162134]
    >>> kweag.bandwidth
    array([[ 11.18034101],
           [ 11.18034101],
           [ 20.000002  ],
           [ 11.18034101],
           [ 14.14213704],
           [ 18.02775818]])
    """
    if radius is not None:
        points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
    return Kernel(points, bandwidth=bandwidths, fixed=False, k=k, function=function)

def adaptive_kernelW_from_shapefile(shapefile, bandwidths=None, k=2, function='triangular',
                                    idVariable=None, radius=None):
    """
    Kernel weights with adaptive bandwidths

    Parameters
    ----------

    shapefile   : string
                  shapefile name with shp suffix
    bandwidths  : float or array-like (optional)
                  the bandwidth :math:`h_i` for the kernel.
                  if no bandwidth is specified k is used to determine the
                  adaptive bandwidth
    k           : int
                  the number of nearest neighbors to use for determining
                  bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i`
                  where :math:`dknn` is a vector of k-nearest neighbor
                  distances (the distance to the kth nearest neighbor for each
                  observation).  For adaptive bandwidths, :math:`h_i=dknn_i`
    function    : string {'triangular','uniform','quadratic','quartic','gaussian'}
                  kernel function defined as follows with

                  .. math::

                      z_{i,j} = d_{i,j}/h_i

                  triangular

                  .. math::

                      K(z) = (1 - |z|) \ if |z| \le 1

                  uniform

                  .. math::

                      K(z) = |z| \ if |z| \le 1

                  quadratic

                  .. math::

                      K(z) = (3/4)(1-z^2) \ if |z| \le 1

                  quartic

                  .. math::

                      K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1

                  gaussian

                  .. math::

                      K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
    idVariable   : string
                   name of a column in the shapefile's DBF to use for ids
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.

    Returns
    -------

    w            : W
                   instance of spatial weights

    Examples
    --------
    >>> kwa = adaptive_kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"))
    >>> kwa.weights[0]
    [1.0, 0.03178906767736345, 9.99999900663795e-08]
    >>> kwa.bandwidth[:3]
    array([[ 0.59871832],
           [ 0.59871832],
           [ 0.56095647]])

    Notes
    -----
    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    """
    points = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
    if idVariable:
        ids = get_ids(shapefile, idVariable)
        return Kernel(points, bandwidth=bandwidths, fixed=False, k=k, function=function, ids=ids)
    return adaptive_kernelW(points, bandwidths=bandwidths, k=k, function=function)

def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2):
    """
    Kernel weights with adaptive bandwidths

    Parameters
    ----------

    shapefile  : string
                 shapefile name with shp suffix
    radius     : If supplied arc_distances will be calculated
                 based on the given radius. p will be ignored.
    p          : float
                 Minkowski p-norm distance metric parameter:
                 1<=p<=infinity
                 2: Euclidean distance
                 1: Manhattan distance

    Returns
    -------
    d            : float
                   minimum nearest neighbor distance between the n observations

    Examples
    --------
    >>> md = min_threshold_dist_from_shapefile(pysal.examples.get_path("columbus.shp"))
    >>> md
    0.61886415807685413
    >>> min_threshold_dist_from_shapefile(pysal.examples.get_path("stl_hom.shp"), pysal.cg.sphere.RADIUS_EARTH_MILES)
    31.846942936393717

    Notes
    -----
    Supports polygon or point shapefiles. For polygon shapefiles, distance is
    based on polygon centroids. Distances are defined using coordinates in
    shapefile which are assumed to be projected and not geographical
    coordinates.

    """
    points = get_points_array_from_shapefile(shapefile)
    if radius is not None:
        points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
    return min_threshold_distance(points,p)

def build_lattice_shapefile(nrows, ncols, outFileName):
    """
    Build a lattice shapefile with nrows rows and ncols cols

    Parameters
    ----------

    nrows       : int
                  Number of rows
    ncols       : int
                  Number of cols
    outFileName : str
                  shapefile name with shp suffix

    Returns
    -------
    None
    """
    if not outFileName.endswith('.shp'):
        raise ValueError("outFileName must end with .shp")
    o = pysal.open(outFileName, 'w')
    for i in xrange(nrows):
        for j in xrange(ncols):
            ll = i, j
            ul = i, j + 1
            ur = i + 1, j + 1
            lr = i + 1, j
            o.write(pysal.cg.Polygon([ll, ul, ur, lr, ll]))
    o.close()


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

define('SMARTY_DIR', 'System/libraries/smarty/');
require SMARTY_DIR . 'Smarty.class.php';

class Welcome extends CI_Controller {

    protected $data = array();

    public function index() {
        $this->render_page('index', '');
    }

    function __construct() {
        parent::__construct();
    }

    function render_page($view) {
        // Smarty
        $smarty = new Smarty();
        $smarty->template_dir = 'Application/views/templates';
        $smarty->compile_dir = 'Application/views/templates_c';

        // Styling
        $this->load->helper('url');
        $style = base_url() . 'assets/css/style.css';
        $logo = base_url() . 'assets/pix/logo.png';
        $cart = base_url() . 'assets/pix/cart.png';
        $smarty->assign('style', $style);
        $smarty->assign('logo', $logo);
        $smarty->assign('cart', $cart);

        // Pages
        $smarty->assign('home', base_url() . 'index.php/Welcome/render_page/index');
        $smarty->assign('information', base_url() . 'index.php/Welcome/render_page/information');
        $smarty->assign('orderAndDeliviry', base_url() . 'index.php/Welcome/render_page/orderAndDeliviry');
        $smarty->assign('paymentInfo', base_url() . 'index.php/Welcome/render_page/paymentInfo');
        $smarty->assign('retourInfo', base_url() . 'index.php/Welcome/render_page/retourInfo');
        $smarty->assign('conditions', base_url() . 'index.php/Welcome/render_page/conditions');
        $smarty->assign('contact', base_url() . 'index.php/Welcome/render_page/contact');
        $smarty->assign('about', base_url() . 'index.php/Welcome/render_page/about');
        $smarty->assign('admin', base_url() . 'index.php/Welcome/render_page/admin');

        $smarty->assign('catalogue', base_url() . 'index.php/Welcome/render_page/catalogue');
        $smarty->assign('categorypage', base_url() . 'index.php/Welcome/render_page/category');
        $smarty->assign('productpage', base_url() . 'index.php/Welcome/render_page/productpage');

        // Data
//        $smarty->registerPlugin("function", "render", "render_page");

        $smarty->assign('categories', $this->getParentAndChildCategories());

        // Display
        $smarty->display($view . '.tpl');
    }

//    function redirectNavigation($view, $param) {
//
//    }

//    function getCategories() {
//        $this->load->model('Category');
//        $categoryModel = new Category();
//        $categories = $categoryModel->getCategories();
//        return $categories;
////        echo sizeof($categories);
//    }

    function getParentAndChildCategories() {
        $this->load->model('Category');
        $categoryModel = new Category();
        $categories = $categoryModel->getCategories();

        $catalogue_catagories = array();
        $children = array();

        $navigation = array();

        // Sort
        foreach ($categories as $cat) {
            if ($cat->parent === '0') {
                $catalogue_catagories[] = $cat;
            } else {
                $children[] = $cat;
            }
        }

        $navigation[] = $catalogue_catagories;
        $navigation[] = $children;

        return $navigation;
    }

//    function getParentAndChildCategories() {
//        $this->load->model('Category');
//        $categoryModel = new Category();
//        $categories = $categoryModel->getCategories();
//
//        $catalogue_catagories = array();
//        $children = array();
//
//        // Sort
//        foreach ($categories as $cat) {
//            if ($cat->parent === '0') {
//                $catalogue_catagories[] = $cat;
//            } else {
//                $children[] = $cat;
//            }
//        }
//
//        $navigation = array();
//        // Create list
//        foreach ($catalogue_catagories as $cat) {
//            $navigation[] = "
name'>$cat->name
";
//
//            $navigation[] = "
";
//            // Children
//            foreach ($children as $child) {
//                if ($child->parent === $cat->name) {
//                    $navigation[] = "
name'>$child->name
";
//                }
//            }
//            $navigation[] = "
";
//        }
//
//        return $navigation;
//    }
}


text:
// we want to test the built aerospike module
var aerospike = require('../build/Release/aerospike');
var options = require('./util/options');
var assert = require('assert');
var expect = require('expect.js');

var keygen = require('./generators/key');
var metagen = require('./generators/metadata');
var recgen = require('./generators/record');
var putgen = require('./generators/put');

var status = aerospike.status;
var policy = aerospike.policy;
var op = aerospike.operator;

describe('client.operate()', function() {

    var client = aerospike.client({
        hosts: [
            { addr: options.host, port: options.port }
        ],
        log: {
            level: options.log
        },
        policies: {
            timeout: options.timeout
        }
    });

    before(function(done) {
        client.connect(function(err){
            done();
        });
    });

    after(function(done) {
        client.close();
        client = null;
        done();
    });

    it('should increment a bin', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/get/"});
        var mgen = metagen.constant({ttl: 1000});
        var rgen = recgen.constant({i: 123, s: "abc"});

        // values
        var key     = kgen();
        var meta    = mgen(key);
        var record  = rgen(key, meta);

        // write the record then check
        client.put(key, record, meta, function(err, key) {

            var ops = [
                op.incr('i', 432)
            ];

            client.operate(key, ops, function(err, record1, metadata1, key1) {
                expect(err).to.be.ok();
                expect(err.code).to.equal(status.AEROSPIKE_OK);

                client.get(key, function(err, record2, metadata2, key2) {
                    expect(err).to.be.ok();
                    expect(err.code).to.equal(status.AEROSPIKE_OK);
                    expect(record['i'] + 432).to.equal(record2['i']);
                    expect(record['s']).to.equal(record2['s']);
					client.remove(key2, function(err, key){
						done();
					});
                });

            });
        });
    });

    it('should append a bin', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/get/"});
        var mgen = metagen.constant({ttl: 1000});
        var rgen = recgen.constant({i: 123, s: "abc"});

        // values
        var key     = kgen();
        var meta    = mgen(key);
        var record  = rgen(key, meta);

        // write the record then check
        client.put(key, record, meta, function(err, key) {

            var ops = [
                op.append('s', 'def')
            ];

            client.operate(key, ops, function(err, record1, metadata1, key1) {
                expect(err).to.be.ok();
                expect(err.code).to.equal(status.AEROSPIKE_OK);

                client.get(key, function(err, record2, metadata2, key2) {
                    expect(err).to.be.ok();
                    expect(err.code).to.equal(status.AEROSPIKE_OK);
                    expect(record['i']).to.equal(record2['i']);
                    expect(record['s'] + 'def').to.equal(record2['s']);
					client.remove(key2, function(err, key){
						done();
					});
                });

            });
        });
    });

    it('should prepend and read a bin', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/get/"});
        var mgen = metagen.constant({ttl: 1000});
        var rgen = recgen.constant({i: 123, s: "abc"});

        // values
        var key     = kgen();
        var meta    = mgen(key);
        var record  = rgen(key, meta);

        // write the record then check
        client.put(key, record, meta, function(err, key) {

            var ops = [
                op.prepend('s', 'def'),
                op.read('s'),
            ];

            client.operate(key, ops, function(err, record1, metadata1, key1) {
                expect(err).to.be.ok();
                expect(err.code).to.equal(status.AEROSPIKE_OK);
                expect(record1['i']).to.equal(undefined);
                expect('def' + record['s']).to.equal(record1['s']);

                client.get(key, function(err, record2, metadata2, key2) {
                    expect(err).to.be.ok();
                    expect(err.code).to.equal(status.AEROSPIKE_OK);
                    expect(record['i']).to.equal(record2['i']);
                    expect('def'+record['s'] ).to.equal(record2['s']);
					client.remove(key2, function(err, key){
						done();
					});
                });

            });
        });
    });
    it('should touch a record(refresh ttl) ', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/get/"});
        var mgen = metagen.constant({ttl: 1000});
        var rgen = recgen.constant({i: 123, s: "abc"});

        // values
        var key     = kgen();
        var meta    = mgen(key);
        var record  = rgen(key, meta);

        // TEST LOGIC
        // 1.Write a record to an aerospike server.
        // 2.Read the record, to get the ttl and calculate
        //   the difference in the ttl written and the ttl returned by server.
        // 3.Touch the record with a definite ttl.
        // 4.Read the record and calculate the difference in the ttl between the
        //  touch ttl value and read ttl value.
        // 5.Compare the difference with the earlier difference calculated.
        // 6.This is to account for the clock asynchronicity between
        //   the client and the server machines.
        // 7.Server returns a number, at which the record expires according the server clock.
        // 8.The client calculates the time in seconds, and gives back ttl. In the case , where
        //   clocks are not synchronous between server and client, the ttl client calculates may not
        //   be accurate to the user. Nevertheless server expires the record in the correct time.

        // write the record then check
        client.put(key, record, meta, function(err, key) {
            var ops = [
                op.touch(2592000)
            ];
            client.get(key, function(err, record3, metadata3, key3){
                expect(err).to.be.ok();
                ttl_diff = metadata3.ttl - meta.ttl;
                client.operate(key, ops, function(err, record1, metadata1, key1) {
                    expect(err).to.be.ok();
                    expect(err.code).to.equal(status.AEROSPIKE_OK);
                    client.get(key1, function(err, record2, metadata2, key2) {
                        expect(err).to.be.ok();
                        expect(err.code).to.equal(status.AEROSPIKE_OK);
                        expect(record['i']).to.equal(record2['i']);
                        expect(record['s']).to.equal(record2['s']);
                        expect(2592000 + ttl_diff+10).to.be.above(metadata2.ttl);
                        expect(2592000 + ttl_diff-10).to.be.below(metadata2.ttl);
						client.remove(key2, function(err, key){
							done();
						});
                    });

                });
            });
        });
    });

});


text:
class HumanPlayer : Player
{
    public override void Play(CellGrid cellGrid)
    {
        cellGrid.CellGridState = new CellGridStateWaitingForInput(cellGrid);
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require_once($CFG->dirroot.'/user/filters/lib.php');

/**
 * User filter based on values of custom profile fields.
 *
 * @copyright 1999 Martin Dougiamas  http://dougiamas.com
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class user_filter_profilefield extends user_filter_type {

    /**
     * Constructor
     * @param string $name the name of the filter instance
     * @param string $label the label of the filter instance
     * @param boolean $advanced advanced form element flag
     */
    public function user_filter_profilefield($name, $label, $advanced) {
        parent::user_filter_type($name, $label, $advanced);
    }

    /**
     * Returns an array of comparison operators
     * @return array of comparison operators
     */
    public function get_operators() {
        return array(0 => get_string('contains', 'filters'),
                     1 => get_string('doesnotcontain', 'filters'),
                     2 => get_string('isequalto', 'filters'),
                     3 => get_string('startswith', 'filters'),
                     4 => get_string('endswith', 'filters'),
                     5 => get_string('isempty', 'filters'),
                     6 => get_string('isnotdefined', 'filters'),
                     7 => get_string('isdefined', 'filters'));
    }

    /**
     * Returns an array of custom profile fields
     * @return array of profile fields
     */
    public function get_profile_fields() {
        global $DB;
        if (!$fields = $DB->get_records('user_info_field', null, 'shortname', 'id,shortname')) {
            return null;
        }
        $res = array(0 => get_string('anyfield', 'filters'));
        foreach ($fields as $k => $v) {
            $res[$k] = $v->shortname;
        }
        return $res;
    }

    /**
     * Adds controls specific to this filter in the form.
     * @param object $mform a MoodleForm object to setup
     */
    public function setupForm(&$mform) {
        $profilefields = $this->get_profile_fields();
        if (empty($profilefields)) {
            return;
        }
        $objs = array();
        $objs['field'] = $mform->createElement('select', $this->_name.'_fld', null, $profilefields);
        $objs['op'] = $mform->createElement('select', $this->_name.'_op', null, $this->get_operators());
        $objs['value'] = $mform->createElement('text', $this->_name, null);
        $objs['field']->setLabel(get_string('profilefilterfield', 'filters'));
        $objs['op']->setLabel(get_string('profilefilterlimiter', 'filters'));
        $objs['value']->setLabel(get_string('valuefor', 'filters', $this->_label));
        $grp =& $mform->addElement('group', $this->_name.'_grp', $this->_label, $objs, '', false);
        $mform->setType($this->_name, PARAM_RAW);
        if ($this->_advanced) {
            $mform->setAdvanced($this->_name.'_grp');
        }
    }

    /**
     * Retrieves data from the form data
     * @param object $formdata data submited with the form
     * @return mixed array filter data or false when filter not set
     */
    public function check_data($formdata) {
        $profilefields = $this->get_profile_fields();

        if (empty($profilefields)) {
            return false;
        }

        $field    = $this->_name;
        $operator = $field.'_op';
        $profile  = $field.'_fld';

        if (array_key_exists($profile, $formdata)) {
            if ($formdata->$operator < 5 and $formdata->$field === '') {
                return false;
            }

            return array('value'    => (string)$formdata->$field,
                         'operator' => (int)$formdata->$operator,
                         'profile'  => (int)$formdata->$profile);
        }
    }

    /**
     * Returns the condition to be used with SQL where
     * @param array $data filter settings
     * @return array sql string and $params
     */
    public function get_sql_filter($data) {
        global $CFG, $DB;
        static $counter = 0;
        $name = 'ex_profilefield'.$counter++;

        $profilefields = $this->get_profile_fields();
        if (empty($profilefields)) {
            return '';
        }

        $profile  = $data['profile'];
        $operator = $data['operator'];
        $value    = $data['value'];

        $params = array();
        if (!array_key_exists($profile, $profilefields)) {
            return array('', array());
        }

        $where = "";
        $op = " IN ";

        if ($operator < 5 and $value === '') {
            return '';
        }

        switch($operator) {
            case 0: // Contains.
                $where = $DB->sql_like('data', ":$name", false, false);
                $params[$name] = "%$value%";
                break;
            case 1: // Does not contain.
                $where = $DB->sql_like('data', ":$name", false, false, true);
                $params[$name] = "%$value%";
                break;
            case 2: // Equal to.
                $where = $DB->sql_like('data', ":$name", false, false);
                $params[$name] = "$value";
                break;
            case 3: // Starts with.
                $where = $DB->sql_like('data', ":$name", false, false);
                $params[$name] = "$value%";
                break;
            case 4: // Ends with.
                $where = $DB->sql_like('data', ":$name", false, false);
                $params[$name] = "%$value";
                break;
            case 5: // Empty.
                $where = "data = :$name";
                $params[$name] = "";
                break;
            case 6: // Is not defined.
                $op = " NOT IN ";
                break;
            case 7: // Is defined.
                break;
        }
        if ($profile) {
            if ($where !== '') {
                $where = " AND $where";
            }
            $where = "fieldid=$profile $where";
        }
        if ($where !== '') {
            $where = "WHERE $where";
        }
        return array("id $op (SELECT userid FROM {user_info_data} $where)", $params);
    }

    /**
     * Returns a human friendly description of the filter used as label.
     * @param array $data filter settings
     * @return string active filter label
     */
    public function get_label($data) {
        $operators      = $this->get_operators();
        $profilefields = $this->get_profile_fields();

        if (empty($profilefields)) {
            return '';
        }

        $profile  = $data['profile'];
        $operator = $data['operator'];
        $value    = $data['value'];

        if (!array_key_exists($profile, $profilefields)) {
            return '';
        }

        $a = new stdClass();
        $a->label    = $this->_label;
        $a->value    = $value;
        $a->profile  = $profilefields[$profile];
        $a->operator = $operators[$operator];

        switch($operator) {
            case 0: // Contains.
            case 1: // Doesn't contain.
            case 2: // Equal to.
            case 3: // Starts with.
            case 4: // Ends with.
                return get_string('profilelabel', 'filters', $a);
            case 5: // Empty.
            case 6: // Is not defined.
            case 7: // Is defined.
                return get_string('profilelabelnovalue', 'filters', $a);
        }
        return '';
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace ApiPortVS
{
    internal static class Guids
    {
        public const string ApiPortVSPkgString = "05b3d9f1-6699-4f10-a9e4-da2ed1248523";
        private const string AnalyzeMenuItemCmdSetString = "d4c08529-d7a0-4ee1-8093-fb5d4b54e36c";
        private const string ProjectContextMenuItemCmdSetString = "5AD32A4E-F8D4-4675-9914-CD514C32FF6D";
        private const string SolutionContextMenuItemCmdSetString = "1A55772C-AEA4-41D1-99EF-0A8278AED5AE";

        public static readonly Guid AnalyzeMenuItemCmdSet = new Guid(AnalyzeMenuItemCmdSetString);
        public static readonly Guid ProjectContextMenuItemCmdSet = new Guid(ProjectContextMenuItemCmdSetString);
        public static readonly Guid SolutionContextMenuItemCmdSet = new Guid(SolutionContextMenuItemCmdSetString);
    }
}