text:
To learn from others and help others reach their goals

## Profiles
- [Email](mailto:bbondy@gmail.com) - bbondy@gmail.com
- [Blog](https://brianbondy.com) - https://brianbondy.com
- [Github](https://github.com/bbondy) - https://github.com/bbondy
- [Stackoverflow](http://stackoverflow.com/users/3153/brian-r-bondy) (Top 0.01%) - http://stackoverflow.com/users/3153/brian-r-bondy
- [Twitter](https://twitter.com/brianbondy) - https://twitter.com/brianbondy
- [LinkedIn](https://www.linkedin.com/in/bbondy) - https://www.linkedin.com/in/bbondy
- [Khan Academy](https://www.khanacademy.org/profile/bbondy/) - https://www.khanacademy.org/profile/bbondy/

## Experience
- **Favorite Languages and APIs**: C, expert level C++ (Templates, STL, boost, COM, MFC, Win32 API, OpenGL, Qt...), JavaScript (Node, client side, app development), Python (Django, pyWin32, list comprehensions, modules, packages, ...), C# (Winforms, WPF, Silverlight, WCF, LINQ, Entity Framework, Remote Objects, Generics, Nullable types, Extension methods, ...), F#, SQL, Matlab, Haskell, Scheme
- **Server Side Development**: Node, IIS (5,6,7, extensions), Apache, CGI, Google App Engine (Python GAE runtime, Flask, webapp, datastore, transactions, GQL, memcache, administration console, bulkdata loaders/exporters, remote API), Django, ASP, ASP .NET, ASP .NET MVC3 (ASPX, Razor), PHP, SOAP, REST ROA, template engines (Jade, jinja2)
- **Front end Development**: DOM, CSS, Stlyus, JavaScript, jQuery, jQueryUI, Backbone, React, debugging, AJAX, JSON HTML5 (canvas, video, local storage, web workers, offline web applications, geolocation, forms, microdata), XML (XPath, XPointer, XSLT, SAX, DTDs), SVG, MathML
- **Operating Systems**: macOS, Windows (all client / server, PE), Android, UNIX, Solaris, Linux, BSD, macOS, Windows Phone
- **Source Control**: Git, Mercurial (hg), Subversion (SVN), CVS, MS Source Safe, database IDEs
- **IDEs, and Debuggers**: Vi, Xcode, MS Visual Studio v5, v6, v7, v8 (2005), v9 (2008), v10 (2010), v11, Borland C++ v4.2, GDB
- **Networking**: Low level socket programming, UDP, TCP, deep protocol knowledge (HTTP, HTTPS, FTP, FTPS, POP), extensive use of Ethereal. (Please see the 'Internet Library' project in the 'projects' section below for a full list of implemented protocols)
- **Database**: MS SQL Server (2000, 2005, 2008, partitions, index design, ...), SQLite, DB2, mySQL, PostgreSQL, Oracle, Corel Paradox, MS Access
- **Other Software Development Experience**: ZLIB, libxml2, Image analysis, cryptography, steganography, LZW and Huffman compression, tape drives, CD burning libraries, Windows LAN programming, and creating installers with NSIS. Static/Shared libraries DLLs/.so, semaphores, Windows Multi threading, pthreads, shared mem, free type lib, Video4Linux

## Qualities
- Ability to work well independently and/or as a member of a team
- Adaptable, hard working, reliable, self motivated, and a quick learner
- Ability to make projects 'happen' quickly, mentoring, management
- Bilingual (English and French)
- Have been actively programming for over 20 years

## Education
- **University of Waterloo**: Honours Bachelor of Mathematics in Computer Science
  Waterloo, Ontario, Canada - Aug 2000 through April 2005
  Computer Graphics, Networking, Artificial Intelligence, Operating Systems, Algorithms, Concurrent Programming and Control Structures, Theory of Computation, Data Structures and Data Management, Number Theory, Mathematics of Investment, Statistics and Probability Theory, Combinatorics and Optimization, Logic Math, Calculus, Classical and Linear Algebra

- **Khan Academy**
  Windsor, Ontario, Canada - 2010 through Forever

## Employment
- **Khan Academy: Developer Lead**
  Offsite employee - April 2014 through Present
  - Developed SQL environment for learning SQL on Khan Academy using emscripten + sqljs + sqlite
  - Developed peer based project evaluations for computer science students on KA
  - Leaded development on LearnStorm, a bay area 3 month math competition
  - Hundreds of fixes, enhancements and patches throughout the tree

- **Mozilla: Senior Firefox Platform Engineer**
  Offsite employee - July 2011 through April 2014
  - Working on Firefox and core code across the tree
  - Windows 8 Metro Firefox browser
  - Installer, silent update, Windows service
  - Hundreds of fixes, enhancements and patches throughout the tree
  - Languages: C++, JavaScript, Python

- **VisionWorks Solutions Inc: Co-founder, Software Developer**
  Windsor, Ontario, Canada - Jan 2004 through July 2011
  - Developed enterprise backup software ROBOBAK, including several hundred thousand lines of code. Features include Deduplication, Journaling, Indexing, Archiving, etc.
  - Developed backup software Vision Backup including over 130 thousand lines of code, and over 3000 copies sold. Features include LAN backup, FTP backup, schedules, compression, email notifications, incremental backups, online software updates, and online software activation.
  - Managed and developed several custom software projects.
  - Managed/Worked on/Maintained an "Encrypted Drive" application
  - Worked on a SPAM and PHISHING fighting project which is based on a TDI filter driver.
  - Developed COM SDKs for several different products that I created.

- **Army Simulation Centre: Linux Software Developer**
  Kingston, Ontario, Canada - Aug 2002 through Aug 2003
  - Started during a Co-op term, also worked part time during school throughout 2003.
  - Created a briefcase program which synchronizes one or more remote directories
  - Created an application that integrates into their simulation software. It sniffs network packets and displays complex results (displayed on my custom built graphing Qt widget)
  - Created several other small utilities using C++, Qt and the File Alteration Monitor.
  - Documented the project and created an RPM as well as user guides.

- **ALT Software: Device Driver Developer**
  Waterloo, Ontario, Canada - Aug 2003 through Dec 2004
  - Developed a device driver for a security video capture camera, debugged several other projects

- **Corel Corporation: Researcher and Software Developer**
  Ottawa, Ontario, Canada - Aug 2001 through Aug 2002
  - Rewrote printing functionality in Paradox 10 as well as worked on SP1 & SP2 for Paradox 10
  - Worked on .NET related projects including performing XSLT transformation on SOAP documents
  - Created a generic web site update notification system, which is used company wide
  - Evaluated new technologies to see if they would fit in at Corel, came up with new company ideas

- Other software developer positions not included to save space.

## Projects

- **CodeFirefox**: Outlines the process of becoming a Mozilla contributor, from start to finish, with 2-10 minute videos and exercises.
- **Codecheck.JS**: Parses JavaScript code structure with acorn.js into an abstract syntax tree, then compares it against a set of assertions for use in online exercise frameworks.
- **Internet Library**: Sole developer of a massive C++ library coded from scratch which includes FTP, FTPS (FTP over SSL), SFTP (FTP over SSH), SMTP, SMTP SSL, POP3, HTTP/S clients (with support for cookies), HTTPS clients, HTTP/S server, FTP/S server.
- **Vision Backup**: Over 130 thousand lines of C++ code, written from scratch which allows backups to several different media. COM based plugin system.
- **File Access Manager**: File System Filter Driver used for allowing access to exclusively opened and locked files. Over 50 thousand outstanding licenses sold, several backup software companies license FAM.
- **Cryptex**: Virtual Encrypted hard drive built as an NTFS driver. Allows the user to lock files in the vault, they can be retrieved later by providing your password.
- **Firefox Extensions**: Several Firefox extensions built using XUL, XBL, and Javascript. Some experience with XPCOM.
- **Virtual Disk Drive**: Allows you to work with any application off of a network hard drive, all operations are sent to an offsite IIS Extension.
- **SPAM Filter**: TDI Filter which allows filtering network traffic. Outlook & Outlook express plugins created.
- **Null Share**: Sole developer of an open source peer to peer application based on the Gnutella protocol.
- **Pyroflow MSN**: Complete multi platform MSN Messenger implementation.
- **Stego Flow**: Library to open, manipulate, extract info and save images, with steganography support
- **Pyroflow Archiving**: An alternative to Unix's tar with built in compression
- **Data Structures**: Several template based data structures, including Adaptive Huffman compression

## Interests, Hobbies, and Other

- Coding: Working on programming projects, learning new technologies
- Reading: Reviewing O'Reilly and Manning books
- Music: Piano & guitar
- Exercise: Marathon runner, Black belt (Shodan) Karate Meibukan Goju Ryu
- Microsoft MVP (For Visual C++ July 2010 - July 2011):


text:
#ifndef SRC_BGP_ROUTING_INSTANCE_ISERVICE_CHAIN_MGR_H_
#define SRC_BGP_ROUTING_INSTANCE_ISERVICE_CHAIN_MGR_H_

#include <stddef.h>
#include <stdint.h>

class RoutingInstance;
class ServiceChainConfig;
class ShowServicechainInfo;

class IServiceChainMgr {
public:
    virtual ~IServiceChainMgr() { }

    virtual void StopServiceChain(RoutingInstance *src) = 0;
    virtual bool LocateServiceChain(RoutingInstance *rtinstance,
        const ServiceChainConfig &config) = 0;
    virtual size_t PendingQueueSize() const = 0;
    virtual size_t ResolvedQueueSize() const = 0;
    virtual uint32_t GetDownServiceChainCount() const = 0;
    virtual bool IsQueueEmpty() const = 0;
    virtual bool FillServiceChainInfo(RoutingInstance *rtinstance,
                                      ShowServicechainInfo *info) const = 0;
    virtual bool IsPending(RoutingInstance *rtinstance) const = 0;

private:
    template <typename U> friend class ServiceChainIntegrationTest;
    template <typename U> friend class ServiceChainTest;

    virtual void set_aggregate_host_route(bool value) = 0;
    virtual void DisableResolveTrigger() = 0;
    virtual void EnableResolveTrigger() = 0;
    virtual void DisableQueue() = 0;
    virtual void EnableQueue() = 0;
};

#endif  // SRC_BGP_ROUTING_INSTANCE_ISERVICE_CHAIN_MGR_H_

redpajama_set_name: RedPajamaGithub


text:
$key = 'AutoHotkey StartupScript'
$path = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
$value = "$env:userprofile\AutoHotkey\StartupScript.ahk"

Set-ItemProperty -Path $path -Name $key -Value """$value""" -Type String

Write-Output "Setting key: '$key' at path: '$path' to value: '""$value""'"


text:
package com.dcp.sm.logic.model;

import java.io.Serializable;

import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.List;
import org.apache.pivot.wtk.content.TreeBranch;

import com.dcp.sm.logic.factory.CastFactory;
import com.dcp.sm.logic.factory.GroupFactory;

/**
 * Group Model
 * @author Said
 *
 */
public class Group implements Comparable<Group>, Serializable
{
    /**
     * Class written into save file
     */
    private static final long serialVersionUID = 7019635543387148548L;

    //Groups
    private String installGroups = "";//Install Groups *
    //Attributes
    private String name;//Group name
    private Group parent = null;//Parent group, if any
    private String description = "";//Group's description
    //Childs
    private List<Group> children = new ArrayList<Group>();//Childs, if is parent
    public void addChild(Group G) { children.add(G); }//Add child to Group
    public void removeChild(Group G) { children.remove(G); }//Delete Child Cascade
    public List<Group> getChildren() { return children; }//Returns the childs

    //Constructors
    public Group() {
    }
    public Group(String name) {
        this.name = name;
    }
    public Group(String name, Group parent) {
        this.name = name;
        setParent(parent);
    }
    public Group(Group group) {
        this.name = group.getName();
        if (group.getParent() != null)
        	setParent(group.getParent());
        setDescription(group.getDescription());
        setInstallGroups(group.getInstallGroups());
    }

    /**
     * Cast group model from Non-Maven data (<v1.2.1)
     * @param group
     */
    public Group(dcp.logic.model.Group group) {
        assert group != null;
        this.name = group.name;
        if (group.parent != null)
        	setParent(new Group(group.parent));
        setDescription(group.description);
        setInstallGroups(group.installGroups);
	}
	//Getters & Setters
    public String getInstallGroups() { return installGroups; }
    public void setInstallGroups(String installGroups) { this.installGroups = installGroups; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public Group getParent() { return parent; }
    public void setParent(Group PARENT) { this.parent = PARENT; }
    public boolean hasParent(Group PARENT) {
        return GroupFactory.hasParent(this, PARENT);
    }

    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    public String getPath() {
        return CastFactory.pathToString(GroupFactory.getPath(this));
    }

    //Comparison function
    @Override
    public boolean equals(Object obj)//Groups compare
    {
        if (obj==null) return false;
        if (obj instanceof Group) {
            Group G = (Group) obj;
            if (G.getParent() != null)
                return this.name.equalsIgnoreCase(G.getName()) && this.getPath().equalsIgnoreCase(G.getPath());
            else//Group has no parent
                return this.name.equalsIgnoreCase(G.getName()) && this.parent == null;
        }
        else if (obj instanceof TreeBranch) {
            TreeBranch branch = (TreeBranch) obj;
            return this.name.equalsIgnoreCase(branch.getText()) &&
                    ( (this.getParent() != null && branch.getParent() != null && this.getParent().equals(branch.getParent())) ||
                            (this.getParent() == null && branch.getParent() == null) );
        }
        else return false;
    }

    @Override
    public String toString()
    {
        return this.getPath();
    }
    @Override
    public int compareTo(Group o)
    {
        if (this.equals(o))
            return 0;//Equal
        else {
            int string_compare = (this.getName().compareTo(o.getName()));//Name comparison
            if (string_compare != 0)
                return string_compare;
            else
                return -1;
        }
    }

}


text:
/*
 *	drivers/pci/setup-res.c
 *
 * Extruded from code written by
 *      Dave Rusling (david.rusling@reo.mts.dec.com)
 *      David Mosberger (davidm@cs.arizona.edu)
 *	David Miller (davem@redhat.com)
 *
 * Support routines for initializing a PCI subsystem.
 */

/* fixed for multiple pci buses, 1999 Andrea Arcangeli <andrea@suse.de> */

/*
 * Nov 2000, Ivan Kokshaysky <ink@jurassic.park.msu.ru>
 *	     Resource sorting
 */

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/pci.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/cache.h>
#include <linux/slab.h>
#include "pci.h"

void pci_update_resource(struct pci_dev *dev, int resno)
{
	struct pci_bus_region region;
	bool disable;
	u16 cmd;
	u32 new, check, mask;
	int reg;
	enum pci_bar_type type;
	struct resource *res = dev->resource + resno;

	/*
	 * Ignore resources for unimplemented BARs and unused resource slots
	 * for 64 bit BARs.
	 */
	if (!res->flags)
		return;

	/*
	 * Ignore non-moveable resources.  This might be legacy resources for
	 * which no functional BAR register exists or another important
	 * system resource we shouldn't move around.
	 */
	if (res->flags & IORESOURCE_PCI_FIXED)
		return;

	pcibios_resource_to_bus(dev->bus, &region, res);

	new = region.start | (res->flags & PCI_REGION_FLAG_MASK);
	if (res->flags & IORESOURCE_IO)
		mask = (u32)PCI_BASE_ADDRESS_IO_MASK;
	else
		mask = (u32)PCI_BASE_ADDRESS_MEM_MASK;

	reg = pci_resource_bar(dev, resno, &type);
	if (!reg)
		return;
	if (type != pci_bar_unknown) {
		if (!(res->flags & IORESOURCE_ROM_ENABLE))
			return;
		new |= PCI_ROM_ADDRESS_ENABLE;
	}

	/*
	 * We can't update a 64-bit BAR atomically, so when possible,
	 * disable decoding so that a half-updated BAR won't conflict
	 * with another device.
	 */
	disable = (res->flags & IORESOURCE_MEM_64) && !dev->mmio_always_on;
	if (disable) {
		pci_read_config_word(dev, PCI_COMMAND, &cmd);
		pci_write_config_word(dev, PCI_COMMAND,
				      cmd & ~PCI_COMMAND_MEMORY);
	}

	pci_write_config_dword(dev, reg, new);
	pci_read_config_dword(dev, reg, &check);

	if ((new ^ check) & mask) {
		dev_err(&dev->dev, "BAR %d: error updating (%#08x != %#08x)\n",
			resno, new, check);
	}

	if (res->flags & IORESOURCE_MEM_64) {
		new = region.start >> 16 >> 16;
		pci_write_config_dword(dev, reg + 4, new);
		pci_read_config_dword(dev, reg + 4, &check);
		if (check != new) {
			dev_err(&dev->dev, "BAR %d: error updating "
			       "(high %#08x != %#08x)\n", resno, new, check);
		}
	}

	if (disable)
		pci_write_config_word(dev, PCI_COMMAND, cmd);

	res->flags &= ~IORESOURCE_UNSET;
	dev_dbg(&dev->dev, "BAR %d: set to %pR (PCI address [%#llx-%#llx])\n",
		resno, res, (unsigned long long)region.start,
		(unsigned long long)region.end);
}

int pci_claim_resource(struct pci_dev *dev, int resource)
{
	struct resource *res = &dev->resource[resource];
	struct resource *root, *conflict;

	root = pci_find_parent_resource(dev, res);
	if (!root) {
		dev_info(&dev->dev, "no compatible bridge window for %pR\n",
			 res);
		return -EINVAL;
	}

	conflict = request_resource_conflict(root, res);
	if (conflict) {
		dev_info(&dev->dev,
			 "address space collision: %pR conflicts with %s %pR\n",
			 res, conflict->name, conflict);
		return -EBUSY;
	}

	return 0;
}
EXPORT_SYMBOL(pci_claim_resource);

void pci_disable_bridge_window(struct pci_dev *dev)
{
	dev_info(&dev->dev, "disabling bridge mem windows\n");

	/* MMIO Base/Limit */
	pci_write_config_dword(dev, PCI_MEMORY_BASE, 0x0000fff0);

	/* Prefetchable MMIO Base/Limit */
	pci_write_config_dword(dev, PCI_PREF_LIMIT_UPPER32, 0);
	pci_write_config_dword(dev, PCI_PREF_MEMORY_BASE, 0x0000fff0);
	pci_write_config_dword(dev, PCI_PREF_BASE_UPPER32, 0xffffffff);
}

/*
 * Generic function that returns a value indicating that the device's
 * original BIOS BAR address was not saved and so is not available for
 * reinstatement.
 *
 * Can be over-ridden by architecture specific code that implements
 * reinstatement functionality rather than leaving it disabled when
 * normal allocation attempts fail.
 */
resource_size_t __weak pcibios_retrieve_fw_addr(struct pci_dev *dev, int idx)
{
	return 0;
}

static int pci_revert_fw_address(struct resource *res, struct pci_dev *dev,
		int resno, resource_size_t size)
{
	struct resource *root, *conflict;
	resource_size_t fw_addr, start, end;
	int ret = 0;

	fw_addr = pcibios_retrieve_fw_addr(dev, resno);
	if (!fw_addr)
		return 1;

	start = res->start;
	end = res->end;
	res->start = fw_addr;
	res->end = res->start + size - 1;

	root = pci_find_parent_resource(dev, res);
	if (!root) {
		if (res->flags & IORESOURCE_IO)
			root = &ioport_resource;
		else
			root = &iomem_resource;
	}

	dev_info(&dev->dev, "BAR %d: trying firmware assignment %pR\n",
		 resno, res);
	conflict = request_resource_conflict(root, res);
	if (conflict) {
		dev_info(&dev->dev,
			 "BAR %d: %pR conflicts with %s %pR\n", resno,
			 res, conflict->name, conflict);
		res->start = start;
		res->end = end;
		ret = 1;
	}
	return ret;
}

static int __pci_assign_resource(struct pci_bus *bus, struct pci_dev *dev,
		int resno, resource_size_t size, resource_size_t align)
{
	struct resource *res = dev->resource + resno;
	resource_size_t min;
	int ret;

	min = (res->flags & IORESOURCE_IO) ? PCIBIOS_MIN_IO : PCIBIOS_MIN_MEM;

	/* First, try exact prefetching match.. */
	ret = pci_bus_alloc_resource(bus, res, size, align, min,
				     IORESOURCE_PREFETCH,
				     pcibios_align_resource, dev);

	if (ret < 0 && (res->flags & IORESOURCE_PREFETCH)) {
		/*
		 * That failed.
		 *
		 * But a prefetching area can handle a non-prefetching
		 * window (it will just not perform as well).
		 */
		ret = pci_bus_alloc_resource(bus, res, size, align, min, 0,
					     pcibios_align_resource, dev);
	}
	return ret;
}

static int _pci_assign_resource(struct pci_dev *dev, int resno,
				resource_size_t size, resource_size_t min_align)
{
	struct resource *res = dev->resource + resno;
	struct pci_bus *bus;
	int ret;
	char *type;

	bus = dev->bus;
	while ((ret = __pci_assign_resource(bus, dev, resno, size, min_align))) {
		if (!bus->parent || !bus->self->transparent)
			break;
		bus = bus->parent;
	}

	if (ret) {
		if (res->flags & IORESOURCE_MEM)
			if (res->flags & IORESOURCE_PREFETCH)
				type = "mem pref";
			else
				type = "mem";
		else if (res->flags & IORESOURCE_IO)
			type = "io";
		else
			type = "unknown";
		dev_info(&dev->dev,
			 "BAR %d: can't assign %s (size %#llx)\n",
			 resno, type, (unsigned long long) resource_size(res));
	}

	return ret;
}

int pci_assign_resource(struct pci_dev *dev, int resno)
{
	struct resource *res = dev->resource + resno;
	resource_size_t align, size;
	int ret;

	align = pci_resource_alignment(dev, res);
	if (!align) {
		dev_info(&dev->dev, "BAR %d: can't assign %pR "
			 "(bogus alignment)\n", resno, res);
		return -EINVAL;
	}

	size = resource_size(res);
	ret = _pci_assign_resource(dev, resno, size, align);

	/*
	 * If we failed to assign anything, let's try the address
	 * where firmware left it.  That at least has a chance of
	 * working, which is better than just leaving it disabled.
	 */
	if (ret < 0)
		ret = pci_revert_fw_address(res, dev, resno, size);

	if (!ret) {
		res->flags &= ~IORESOURCE_STARTALIGN;
		dev_info(&dev->dev, "BAR %d: assigned %pR\n", resno, res);
		if (resno < PCI_BRIDGE_RESOURCES)
			pci_update_resource(dev, resno);
	}
	return ret;
}

int pci_reassign_resource(struct pci_dev *dev, int resno, resource_size_t addsize,
			resource_size_t min_align)
{
	struct resource *res = dev->resource + resno;
	resource_size_t new_size;
	int ret;

	if (!res->parent) {
		dev_info(&dev->dev, "BAR %d: can't reassign an unassigned resource %pR "
			 "\n", resno, res);
		return -EINVAL;
	}

	/* already aligned with min_align */
	new_size = resource_size(res) + addsize;
	ret = _pci_assign_resource(dev, resno, new_size, min_align);
	if (!ret) {
		res->flags &= ~IORESOURCE_STARTALIGN;
		dev_info(&dev->dev, "BAR %d: reassigned %pR\n", resno, res);
		if (resno < PCI_BRIDGE_RESOURCES)
			pci_update_resource(dev, resno);
	}
	return ret;
}

int pci_enable_resources(struct pci_dev *dev, int mask)
{
	u16 cmd, old_cmd;
	int i;
	struct resource *r;

	pci_read_config_word(dev, PCI_COMMAND, &cmd);
	old_cmd = cmd;

	for (i = 0; i < PCI_NUM_RESOURCES; i++) {
		if (!(mask & (1 << i)))
			continue;

		r = &dev->resource[i];

		if (!(r->flags & (IORESOURCE_IO | IORESOURCE_MEM)))
			continue;
		if ((i == PCI_ROM_RESOURCE) &&
				(!(r->flags & IORESOURCE_ROM_ENABLE)))
			continue;

		if (!r->parent) {
			dev_err(&dev->dev, "device not available "
				"(can't reserve %pR)\n", r);
			return -EINVAL;
		}

		if (r->flags & IORESOURCE_IO)
			cmd |= PCI_COMMAND_IO;
		if (r->flags & IORESOURCE_MEM)
			cmd |= PCI_COMMAND_MEMORY;
	}

	if (cmd != old_cmd) {
		dev_info(&dev->dev, "enabling device (%04x -> %04x)\n",
			 old_cmd, cmd);
		pci_write_config_word(dev, PCI_COMMAND, cmd);
	}
	return 0;
}


text:
var assert = require('assert')
var decode = require('../decoder.js')

function isPlatformLittleEndian () {
  var buffer = new ArrayBuffer(2)
  new DataView(buffer).setInt16(0, 256, true)
  return new Int16Array(buffer)[0] === 256
}

describe('decoder', function() {
  it('should perform endianness conversion', function() {
    var data = [14, 1, 2888, 4543222]
    var typedArr = new Uint32Array(data.length)
    for (var i=0; i < data.length; i++) {
      typedArr[i] = data[i]
    }

    // change endianness
    var little = isPlatformLittleEndian()
    var dv = new DataView(typedArr.buffer)
    for (var i=0; i < typedArr.length; i++) {
      dv.setUint32(i*4, typedArr[i], !little)
    }

    // check if the decoder can read it
    var arr = new Uint8Array(typedArr.buffer)
    var tag = little ? 66 : 70
    var result = decode(arr, tag)
    var resultArr = Array.prototype.slice.call(result)

    assert.deepEqual(resultArr, data)
  })
  it('should choose the correct array type', function() {
    var arr = new Uint8Array(16)
    // null = unsupported in current browsers
    var types = {
      64: Uint8Array,
      65: Uint16Array,
      66: Uint32Array,
      67: null, // Uint64
      68: Uint8ClampedArray,
      69: Uint16Array,
      70: Uint32Array,
      71: null, // Uint64
      72: Int8Array,
      73: Int16Array,
      74: Int32Array,
      75: null, // Int64
      77: Int16Array,
      78: Int32Array,
      79: null, // Int64
      80: null, // Float16
      81: Float32Array,
      82: Float64Array,
      83: null, // Float128
      84: null, // Float16
      85: Float32Array,
      86: Float64Array,
      87: null // Float128
    }

    for (tag in types) {
      if (types[tag] === null) {
        assert.throws(function() {decode(arr, tag)}, Error)
      } else {
        var ta = decode(arr, tag)
        assert(ta instanceof types[tag])
      }
    }
  })
})


text:
create table if not exists AGENT (
    id bigint auto_increment unique,
    approved char(1) not null,
    hostName varchar(255),
    ip varchar(255),
    primary key (id)
);
#########################################################
create table if not exists NUSER (
    id bigint auto_increment unique,
    created_date timestamp NULL DEFAULT NULL,
    last_modified_date timestamp NULL DEFAULT NULL,
    authentication_provider_class varchar(255),
    description varchar(255),
    email varchar(255),
    enabled char(1) not null,
    is_external char(1),
    mobile_phone varchar(255),
    password varchar(255),
    role_name varchar(255) not null,
    timeZone varchar(255),
    user_id varchar(255) not null unique,
    user_language varchar(255),
    user_name varchar(255),
    created_user bigint,
    last_modified_user bigint,
    primary key (id)
);
#########################################################
create table if not exists PERF_TEST (
    id bigint auto_increment unique,
    created_date timestamp NULL DEFAULT NULL,
    last_modified_date timestamp NULL DEFAULT NULL,
    agent_count int,
    description text,
    distribution_path varchar(255),
    duration bigint,
    errors bigint,
    finish_time timestamp NULL DEFAULT NULL,
    ignore_sample_count int,
    ramp_up_init_count int,
    ramp_up_init_sleep_time int,
    last_progress_message text,
    mean_test_time double,
    peak_tps double,
    port int,
    ramp_up_step int,
    ramp_up_increment_interval int,
    processes int,
    progress_message text,
    run_count int,
    scheduled_time timestamp NULL DEFAULT NULL,
    script_name varchar(255),
    script_revision varchar(255),
    send_mail char(1),
    start_time timestamp NULL DEFAULT NULL,
    status varchar(255),
    stop_request char(1),
    tag_string varchar(255),
    target_hosts text,
    test_comment text,
    test_error_cause varchar(255),
    name varchar(255),
    test_time_standard_deviation double,
    tests bigint,
    threads int,
    threshold varchar(255),
    tps double,
    use_rampup char(1),
    vuser_per_agent int,
    created_user bigint,
    last_modified_user bigint,
    region varchar(255),
    safe_distribution char(1) default 'F',
    sampling_interval int default 1,
    param varchar(256) default '',
    ramp_up_type varchar(10) default 'PROCESS',
    scm varchar(30) default 'svn',
    ignore_too_many_error char(1) default 'F',
    primary key (id)
);
#########################################################
create table if not exists PERF_TEST_TAG (
    perf_test_id bigint not null,
    tag_id bigint not null,
    primary key (perf_test_id, tag_id)
);
#########################################################
create table if not exists TAG (
    id bigint auto_increment unique,
    created_date timestamp NULL DEFAULT NULL,
    last_modified_date timestamp NULL DEFAULT NULL,
    tagValue varchar(255),
    created_user bigint,
    last_modified_user bigint,
    primary key (id)
);
#########################################################
create table if not exists SHARED_USER (
    owner_id bigint not null,
    follow_id bigint not null,
    primary key (owner_id, follow_id)
);


text:
The ango tool takes a file with ango definitions to generate the communication protocol. This file describes the syntax for these definitions.

### Specifications
The `.ango` definition file  specifies the protocol name, and several services.

#### Comments
Comments can be placed on any line and are started with `//`. Everything until newline (`\n`) is ignored.

#### Letters and digits

```
letter = "a" … "z" | "A" … "Z" .
digit = "0" … "9" .
```

#### Identifier
Identifiers in ango syntax are not entirely equal to Go identifiers. Ango identifiers only allow `a-z` and `A-Z` letters.

`identifier = letter { letter | digit } .`

Some identifiers are predeclared.

#### Service name
The first actual statement should be the `name` statement:

```
ServiceClause = "name" ServiceName .
ServiceName = identifier .
```

It is good practice to match the filename. e.g. `name myService` for `myService.ango`.

#### Types
Type description:

```
Type      = TypeName | TypeLit .
TypeName  = identifier .
TypeLit   = SliceType | MapType | StructType .
```

##### Slice types
A slice type translates to a `slice` in Go. In javascript it is translated to an array. Defining the length or capacity of elements is not possible at this moment.

```
SliceType    = "[" "]" ElementType .
ElementType  = Type .
```

##### Map types
A map translates to a `map` in Go. In javascript this is translated to an object.

```
MapType  = "map" "[" KeyType "]" ElementType .
KeyType  = Type .
```

##### Struct types
A struct type is directly compatible Go code. In javascript this is represented as an object.

```
StructType  = "struct" "{" { FieldDecl } "}" .
FieldDecl   = identifier Type .
```

##### Builtin types
Ango provides a set of builtin types such as integers and strings. Because javascript has less types than Go, different Go types translate to the same javascript type. For instance Go's `uint8`, `uint64`, `int8` and `int32` all translate to javascripts `number`. Read more details about the builtin types in [types.md](types.md).

#### Type declarations:
Custom types can be declared within a ango file.

```
TypeDecl  = "type" TypeSpec .
TypeSpec  = identifier Type .
```

#### Procedure
Procedure description:

```
ProcedureDecl                = ServerProcedureSpec | ClientProcedureSpec .
ServerProcedureSpec          = "server" (OnewayProcedureSpec|ReturningProcedureSpec) .
ClientProcedureSpec          = "client" (OnewayProcedureDecl|ReturningProcedureSpec) .
OnewayProcedureSignature     = "oneway" ProcedureName Parameters .
ReturningProcedureSignature  = ProcedureName Parameters [ Result ] .
ProcedureName                = identifier .
Result                       = Parameters .
Parameters                   = "(" [ ParameterList ] ")" .
ParameterList                = ParameterDecl { "," ParameterDecl } .
ParameterDecl                = identifier Type .
```

The first keyword, `'server'` or `'client'`, indicates which side provides/implements the procedure.

A `oneway` procedure does not wait for a response from the other side. A call to a `oneway` procedure returns immediately after the call has been sent over the websocket. There's no result possible. Any possible error should be handled at the called side only, as none can be sent back.

A `returning` procedure call retuns when the procedure implementation has returned (with or without error). Optionally, some return values can be sent back.

### Example
There's an example `.ango` file at [/example/example.ango](/example/example.ango)


text:
// ----------------------------------------------------------------------
// This code is developed as part of the Java CoG Kit project
// The terms of the license can be found at http://www.cogkit.org/license
// This message may not be removed or altered.
// ----------------------------------------------------------------------

/*
 * Created on Jul 2, 2004
 */
package org.globus.cog.karajan.compiled.nodes.functions;

import k.rt.Stack;
import k.thr.LWThread;

import org.apache.log4j.Logger;
import org.globus.cog.karajan.analyzer.ChannelRef;
import org.globus.cog.karajan.analyzer.CompilationException;
import org.globus.cog.karajan.analyzer.Param;
import org.globus.cog.karajan.analyzer.Scope;
import org.globus.cog.karajan.analyzer.Var;
import org.globus.cog.karajan.analyzer.VarRef;
import org.globus.cog.karajan.compiled.nodes.Node;
import org.globus.cog.karajan.parser.WrapperNode;

public class Variable extends Node {
	final static Logger logger = Logger.getLogger(Variable.class);

	private VarRef<Object> ref;
	private ChannelRef<Object> _vargs;

	@Override
	public void run(LWThread thr) {
		Stack stack = thr.getStack();
		_vargs.append(stack, ref.getValue(stack));
	}

	@Override
	public Node compile(WrapperNode wn, Scope scope) throws CompilationException {
		super.compile(wn, scope);
		String name = wn.getText();

		ref = scope.getVarRef(name, this);
		Var.Channel vargs = scope.lookupChannel(Param.VARGS);

		if (ref.isStatic()) {
			if (vargs.append(ref.getValue())) {
				return null;
			}
			else {
				_vargs = scope.getChannelRef(vargs);
				return this;
			}
		}
		else {
			vargs.appendDynamic();
			_vargs = scope.getChannelRef(vargs);
			return this;
		}
	}
}


text:
namespace Slang
{

IRTypeSet::IRTypeSet(Session* session)
{
    m_module = IRModule::create(session);

    m_sharedBuilder.init(m_module);
    m_builder.init(m_sharedBuilder);

    m_builder.setInsertInto(m_module->getModuleInst());
}

IRTypeSet::~IRTypeSet()
{
    _clearTypes();
}

void IRTypeSet::clear()
{
    _clearTypes();

    m_cloneMap.Clear();

    m_module = IRModule::create(m_sharedBuilder.getSession());

    m_sharedBuilder.init(m_module);
    m_builder.init(m_sharedBuilder);

    m_builder.setInsertInto(m_module->getModuleInst());
}

void IRTypeSet::_clearTypes()
{
    List<IRType*> types;
    getTypes(types);

    for (auto type : types)
    {
        // We need to destroy references to instructions in other modules
        if (type->getModule() == m_module)
        {
            // We want to remove arguments because an argument *could* be an instruction in another module,
            // and we don't want to those modules insts to have uses, in this module which is being destroyed
            type->removeArguments();
        }
    }
}

IRInst* IRTypeSet::cloneInst(IRInst* inst)
{
    if (inst == nullptr)
    {
        return nullptr;
    }

    // See if it's already cloned
    if (IRInst*const* newInstPtr = m_cloneMap.TryGetValue(inst))
    {
        return *newInstPtr;
    }

    IRModule* module = inst->getModule();
    // All inst's must belong to a module
    SLANG_ASSERT(module);

    // If it's in this module then we don't need to clone
    if (module == m_module)
    {
        return inst;
    }

    if (isNominalOp(inst->getOp()))
    {
        // We can clone without any definition, and add the linkage

        // TODO(JS)
        // This is arguably problematic - I'm adding an instruction from another module to the map, to be it's self.
        // I did have code which created a copy of the nominal instruction and name hint, but because nominality means
        // 'same address' other code would generate a different name for that instruction (say as compared to being a member in
        // the original instruction)
        //
        // Because I use findOrAddInst which doesn't hoist instructions, the hoisting doesn't rely on parenting, that would
        // break.

        // If nominal, we just use the original inst
        m_cloneMap.Add(inst, inst);
        return inst;
    }

    // It would be nice if I could use ir-clone.cpp to do this -> but it doesn't clone
    // operands. We wouldn't want to clone decorations, and it can't clone IRConstant(!) so
    // it's no use

    IRInst* clone = nullptr;
    switch (inst->getOp())
    {
        case kIROp_IntLit:
        {
            auto intLit = static_cast<IRConstant*>(inst);
            IRType* clonedType = cloneType(intLit->getDataType());
            clone = m_builder.getIntValue(clonedType, intLit->value.intVal);
            break;
        }
        case kIROp_StringLit:
        {
            auto stringLit = static_cast<IRStringLit*>(inst);
            clone = m_builder.getStringValue(stringLit->getStringSlice());
            break;
        }
        case kIROp_VectorType:
        {
            auto vecType = static_cast<IRVectorType*>(inst);
            const Index elementCount = Index(getIntVal(vecType->getElementCount()));

            if (elementCount <= 1)
            {
                clone = cloneType(vecType->getElementType());
            }
            break;
        }
        case kIROp_MatrixType:
        {
            auto matType = static_cast<IRMatrixType*>(inst);
            const Index columnCount = Index(getIntVal(matType->getColumnCount()));
            const Index rowCount = Index(getIntVal(matType->getRowCount()));

            if (columnCount <= 1 && rowCount <= 1)
            {
                clone = cloneType(matType->getElementType());
            }
            break;
        }
        default: break;
    }

    if (!clone)
    {
        if (IRBasicType::isaImpl(inst->getOp()))
        {
            clone = m_builder.getType(inst->getOp());
        }
        else
        {
            IRType* irType = dynamicCast<IRType>(inst);
            if (irType)
            {
                auto clonedType = cloneType(inst->getFullType());
                Index operandCount = Index(inst->getOperandCount());

                List<IRInst*> cloneOperands;
                cloneOperands.setCount(operandCount);

                for (Index i = 0; i < operandCount; ++i)
                {
                    cloneOperands[i] = cloneInst(inst->getOperand(i));
                }

                //clone = m_irBuilder.findOrEmitHoistableInst(cloneType, inst->op, operandCount, cloneOperands.getBuffer());

                UInt operandCounts[1] = { UInt(operandCount) };
                IRInst*const* listOperands[1] = { cloneOperands.getBuffer() };

                clone = m_builder.findOrAddInst(clonedType, inst->getOp(), 1, operandCounts, listOperands);
            }
            else
            {
                // This cloning style only works on insts that are not unique
                auto clonedType = cloneType(inst->getFullType());

                Index operandCount = Index(inst->getOperandCount());
                clone = m_builder.emitIntrinsicInst(clonedType, inst->getOp(), operandCount, nullptr);
                for (Index i = 0; i < operandCount; ++i)
                {
                    auto cloneOperand = cloneInst(inst->getOperand(i));
                    clone->getOperands()[i].init(clone, cloneOperand);
                }
            }
        }
    }

    m_cloneMap.Add(inst, clone);
    return clone;
}

IRType* IRTypeSet::add(IRType* irType)
{
    if (irType->getModule() == m_module)
    {
        return irType;
    }
    // We need to clone the type
    return cloneType(irType);
}

void IRTypeSet::getTypes(List<IRType*>& outTypes) const
{
    outTypes.clear();
    for (auto inst : m_module->getModuleInst()->getChildren())
    {
        if (IRType* type = as<IRType>(inst))
        {
            outTypes.add(type);
        }
    }
}

void IRTypeSet::getTypes(Kind kind, List<IRType*>& outTypes) const
{
    outTypes.clear();

    for (auto inst : m_module->getModuleInst()->getChildren())
    {
        IRType* type = nullptr;

        switch (kind)
        {
            case Kind::Scalar:
            {
                type = as<IRBasicType>(inst);
                break;
            }
            case Kind::Vector:
            {
                type = as<IRVectorType>(inst);
                break;
            }
            case Kind::Matrix:
            {
                type = as<IRMatrixType>(inst);
                break;
            }
            default: break;
        }

        if (type)
        {
            outTypes.add(type);
        }
    }
}

IRType* IRTypeSet::addVectorType(IRType* inElementType, int colsCount)
{
    IRType* elementType = cloneType(inElementType);
    if (colsCount == 1)
    {
        return elementType;
    }
    return m_builder.getVectorType(elementType, m_builder.getIntValue(m_builder.getIntType(), colsCount));
}

void IRTypeSet::addVectorForMatrixTypes()
{
    // Make a copy so we can alter m_types dictionary
    List<IRType*> types;
    getTypes(Kind::Matrix, types);
    for (IRType* type : types)
    {
        SLANG_ASSERT(as<IRMatrixType>(type));
        IRMatrixType* matType = static_cast<IRMatrixType*>(type);
        m_builder.getVectorType(matType->getElementType(), matType->getColumnCount());
    }
}

static bool _hasNominalOperand(IRInst* inst)
{
    const Index operandCount = Index(inst->getOperandCount());
    auto operands = inst->getOperands();

    for (Index i = 0; i < operandCount; ++i)
    {
        IRInst* operand = operands[i].get();
        if (isNominalOp(operand->getOp()))
        {
            return true;
        }
    }

    return false;
}

void IRTypeSet::_addAllBuiltinTypesRec(IRInst* inst)
{
    for (IRInst* child = inst->getFirstDecorationOrChild(); child; child = child->getNextInst())
    {
        IRType* type = nullptr;

        if (auto vectorType = as<IRVectorType>(child))
        {
            type = vectorType;
        }
        else if (auto matrixType = as<IRMatrixType>(child))
        {
            type = matrixType;
        }
        if (type && !_hasNominalOperand(type))
        {
            add(type);
        }
        else
        {
            _addAllBuiltinTypesRec(child);
        }
    }
}

void IRTypeSet::addAllBuiltinTypes(IRModule* module)
{
    _addAllBuiltinTypesRec(module->getModuleInst());
}

}


text:
set -e
set -x

export LC_ALL=C

env >> test_env.log

$CC -v || true
valgrind --version || true

./autogen.sh

./configure \
    --enable-experimental="$EXPERIMENTAL" \
    --with-test-override-wide-multiply="$WIDEMUL" --with-asm="$ASM" \
    --enable-ecmult-static-precomputation="$STATICPRECOMPUTATION" --with-ecmult-gen-precision="$ECMULTGENPRECISION" \
    --enable-module-ecdh="$ECDH" --enable-module-recovery="$RECOVERY" \
    --enable-module-schnorrsig="$SCHNORRSIG" \
    --with-valgrind="$WITH_VALGRIND" \
    --host="$HOST" $EXTRAFLAGS

# We have set "-j<n>" in MAKEFLAGS.
make

# Print information about binaries so that we can see that the architecture is correct
file *tests || true
file bench_* || true
file .libs/* || true

if [ -n "$BUILD" ]
then
    make "$BUILD"
fi

if [ "$RUN_VALGRIND" = "yes" ]
then
    # the `--error-exitcode` is required to make the test fail if valgrind found errors, otherwise it'll return 0 (https://www.valgrind.org/docs/manual/manual-core.html)
    valgrind --error-exitcode=42 ./tests 16
    valgrind --error-exitcode=42 ./exhaustive_tests
fi

if [ -n "$QEMU_CMD" ]
then
    $QEMU_CMD ./tests 16
    $QEMU_CMD ./exhaustive_tests
fi

if [ "$BENCH" = "yes" ]
then
    # Using the local `libtool` because on macOS the system's libtool has nothing to do with GNU libtool
    EXEC='./libtool --mode=execute'
    if [ -n "$QEMU_CMD" ]
    then
       EXEC="$EXEC $QEMU_CMD"
    fi
    if [ "$RUN_VALGRIND" = "yes" ]
    then
        EXEC="$EXEC valgrind --error-exitcode=42"
    fi
    # This limits the iterations in the benchmarks below to ITER iterations.
    export SECP256K1_BENCH_ITERS="$ITERS"
    {
        $EXEC ./bench_ecmult
        $EXEC ./bench_internal
        $EXEC ./bench_sign
        $EXEC ./bench_verify
    } >> bench.log 2>&1
    if [ "$RECOVERY" = "yes" ]
    then
        $EXEC ./bench_recover >> bench.log 2>&1
    fi
    if [ "$ECDH" = "yes" ]
    then
        $EXEC ./bench_ecdh >> bench.log 2>&1
    fi
    if [ "$SCHNORRSIG" = "yes" ]
    then
        $EXEC ./bench_schnorrsig >> bench.log 2>&1
    fi
fi
if [ "$CTIMETEST" = "yes" ]
then
    ./libtool --mode=execute valgrind --error-exitcode=42 ./valgrind_ctime_test > valgrind_ctime_test.log 2>&1
fi


text:
package http

import (
	"net/http"
	"strings"

	auth "github.com/abbot/go-http-auth"
	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/openstack"
	tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens"
	tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens"
	"github.com/gorilla/context"
	"github.com/mitchellh/mapstructure"
	"github.com/skydive-project/skydive/config"
	"github.com/skydive-project/skydive/logging"
)

type KeystoneAuthenticationBackend struct {
	AuthURL string
	Tenant  string
	Domain  string
}

type User struct {
	ID   string `mapstructure:"id"`
	Name string `mapstructure:"name"`
}

func (b *KeystoneAuthenticationBackend) checkUserV2(client *gophercloud.ServiceClient, tokenID string) (string, error) {
	result := tokens2.Get(client, tokenID)

	user, err := result.ExtractUser()
	if err != nil {
		return "", err
	}

	token, err := result.ExtractToken()
	if err != nil {
		return "", err
	}

	if token.Tenant.Name != b.Tenant {
		return "", WrongCredentials
	}

	isAdmin := false
	for _, role := range user.Roles {
		if role.Name == "admin" {
			isAdmin = true
			break
		}
	}

	if !isAdmin {
		return "", WrongCredentials
	}

	return user.UserName, nil
}

func (b *KeystoneAuthenticationBackend) checkUserV3(client *gophercloud.ServiceClient, tokenID string) (string, error) {
	result := tokens3.Get(client, tokenID)

	type Role struct {
		Name string `mapstructure:"name"`
	}

	var response struct {
		Token struct {
			User    User   `mapstructure:"user"`
			Roles   []Role `mapstructure:"roles"`
			Project struct {
				Name   string `mapstructure:"name"`
				Domain struct {
					Name string `mapstructure:"name"`
				} `mapstructure:"domain"`
			}
		} `mapstructure:"token"`
	}
	mapstructure.Decode(result.Body, &response)

	// test that the project is the same as the one provided in the conf file
	if response.Token.Project.Name != b.Tenant || response.Token.Project.Domain.Name != b.Domain {
		return "", WrongCredentials
	}

	// test that the user is the admin of the project
	isAdmin := false
	for _, role := range response.Token.Roles {
		if role.Name == "admin" {
			isAdmin = true
			break
		}
	}

	if !isAdmin {
		return "", WrongCredentials
	}

	return response.Token.User.Name, nil
}

func (b *KeystoneAuthenticationBackend) CheckUser(r *http.Request) (string, error) {
	cookie, err := r.Cookie("authtok")
	if err != nil {
		return "", WrongCredentials
	}

	tokenID := cookie.Value
	if tokenID == "" {
		return "", WrongCredentials
	}

	provider, err := openstack.NewClient(b.AuthURL)
	if err != nil {
		return "", err
	}
	provider.TokenID = cookie.Value

	client := &gophercloud.ServiceClient{
		ProviderClient: provider,
		Endpoint:       b.AuthURL,
	}

	if b.Domain != "" {
		return b.checkUserV3(client, tokenID)
	}

	return b.checkUserV2(client, tokenID)
}

func (b *KeystoneAuthenticationBackend) Authenticate(username string, password string) (string, error) {
	opts := gophercloud.AuthOptions{
		IdentityEndpoint: b.AuthURL,
		Username:         username,
		Password:         password,
		TenantName:       b.Tenant,
		DomainName:       b.Domain,
	}

	provider, err := openstack.NewClient(b.AuthURL)
	if err != nil {
		return "", err
	}

	if err := openstack.Authenticate(provider, opts); err != nil {
		logging.GetLogger().Noticef("Keystone authentication error : %s", err)
		return "", err
	}

	return provider.TokenID, nil
}

func (b *KeystoneAuthenticationBackend) Wrap(wrapped auth.AuthenticatedHandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if username, err := b.CheckUser(r); username == "" {
			if err != nil {
				logging.GetLogger().Warningf("Failed to check token: %s", err.Error())
			}
			unauthorized(w, r)
		} else {
			ar := &auth.AuthenticatedRequest{Request: *r, Username: username}
			copyRequestVars(r, &ar.Request)
			wrapped(w, ar)
			context.Clear(&ar.Request)
		}
	}
}

func NewKeystoneBackend(authURL string, tenant string, domain string) *KeystoneAuthenticationBackend {
	if !strings.HasSuffix(authURL, "/") {
		authURL += "/"
	}

	return &KeystoneAuthenticationBackend{
		AuthURL: authURL,
		Tenant:  tenant,
		Domain:  domain,
	}
}

func NewKeystoneAuthenticationBackendFromConfig() *KeystoneAuthenticationBackend {
	authURL := config.GetConfig().GetString("openstack.auth_url")
	tenant := config.GetConfig().GetString("openstack.tenant_name")
	domain := config.GetConfig().GetString("openstack.domain_name")

	return NewKeystoneBackend(authURL, tenant, domain)
}


text:
/* jshint browser: true */
/* global Backbone, $, window, arangoHelper, templateEngine, _ */
(function () {
  'use strict';

  window.ApplicationsView = Backbone.View.extend({
    el: '#content',

    template: templateEngine.createTemplate('applicationsView.ejs'),

    events: {
      'click #addApp': 'createInstallModal',
      'click #foxxToggle': 'slideToggle',
      'click #checkDevel': 'toggleDevel',
      'click #checkProduction': 'toggleProduction',
      'click #checkSystem': 'toggleSystem'
    },

    fixCheckboxes: function () {
      if (this._showDevel) {
        $('#checkDevel').attr('checked', 'checked');
      } else {
        $('#checkDevel').removeAttr('checked');
      }
      if (this._showSystem) {
        $('#checkSystem').attr('checked', 'checked');
      } else {
        $('#checkSystem').removeAttr('checked');
      }
      if (this._showProd) {
        $('#checkProduction').attr('checked', 'checked');
      } else {
        $('#checkProduction').removeAttr('checked');
      }
      $('#checkDevel').next().removeClass('fa fa-check-square-o fa-square-o').addClass('fa');
      $('#checkSystem').next().removeClass('fa fa-check-square-o fa-square-o').addClass('fa');
      $('#checkProduction').next().removeClass('fa fa-check-square-o fa-square-o').addClass('fa');
      arangoHelper.setCheckboxStatus('#foxxDropdown');
    },

    toggleDevel: function () {
      var self = this;
      this._showDevel = !this._showDevel;
      _.each(this._installedSubViews, function (v) {
        v.toggle('devel', self._showDevel);
      });
      this.fixCheckboxes();
    },

    toggleProduction: function () {
      var self = this;
      this._showProd = !this._showProd;
      _.each(this._installedSubViews, function (v) {
        v.toggle('production', self._showProd);
      });
      this.fixCheckboxes();
    },

    toggleSystem: function () {
      this._showSystem = !this._showSystem;
      var self = this;
      _.each(this._installedSubViews, function (v) {
        v.toggle('system', self._showSystem);
      });
      this.fixCheckboxes();
    },

    reload: function () {
      var self = this;

      // unbind and remove any unused views
      _.each(this._installedSubViews, function (v) {
        v.undelegateEvents();
      });

      this.collection.fetch({
        success: function () {
          self.createSubViews();
          self.render();
        }
      });
    },

    createSubViews: function () {
      var self = this;
      this._installedSubViews = { };

      self.collection.each(function (foxx) {
        var subView = new window.FoxxActiveView({
          model: foxx,
          appsView: self
        });
        self._installedSubViews[foxx.get('mount')] = subView;
      });
    },

    initialize: function () {
      this._installedSubViews = {};
      this._showDevel = true;
      this._showProd = true;
      this._showSystem = false;
    },

    slideToggle: function () {
      $('#foxxToggle').toggleClass('activated');
      $('#foxxDropdownOut').slideToggle(200);
    },

    createInstallModal: function (event) {
      event.preventDefault();
      window.foxxInstallView.install(this.reload.bind(this));
    },

    render: function () {
      this.collection.sort();

      $(this.el).html(this.template.render({}));
      _.each(this._installedSubViews, function (v) {
        $('#installedList').append(v.render());
      });
      this.delegateEvents();
      $('#checkDevel').attr('checked', this._showDevel);
      $('#checkProduction').attr('checked', this._showProd);
      $('#checkSystem').attr('checked', this._showSystem);
      arangoHelper.setCheckboxStatus('#foxxDropdown');

      var self = this;
      _.each(this._installedSubViews, function (v) {
        v.toggle('devel', self._showDevel);
        v.toggle('system', self._showSystem);
      });

      arangoHelper.fixTooltips('icon_arangodb', 'left');
      return this;
    }

  });

/* Info for mountpoint
 *
 *
    window.modalView.createTextEntry(
      "mount-point",
      "Mount",
      "",
      "The path the app will be mounted. Has to start with /. Is not allowed to start with /_",
      "/my/app",
      true,
      [
        {
          rule: Joi.string().required(),
          msg: "No mountpoint given."
        },
        {
          rule: Joi.string().regex(/^\/[^_]/),
          msg: "Mountpoints with _ are reserved for internal use."
        },
        {
          rule: Joi.string().regex(/^(\/[a-zA-Z0-9_\-%]+)+$/),
          msg: "Mountpoints have to start with / and can only contain [a-zA-Z0-9_-%]"
        }
      ]
    )
 */
}());


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/contentwarehouse/v1/document_schema.proto

package com.google.cloud.contentwarehouse.v1;

public interface EnumTypeOptionsOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.contentwarehouse.v1.EnumTypeOptions)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. List of possible enum values.
   *

   *
   * repeated string possible_values = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return A list containing the possibleValues.
   */
  java.util.List<java.lang.String> getPossibleValuesList();
  /**
   *
   *
   *

   * Required. List of possible enum values.
   *

   *
   * repeated string possible_values = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The count of possibleValues.
   */
  int getPossibleValuesCount();
  /**
   *
   *
   *

   * Required. List of possible enum values.
   *

   *
   * repeated string possible_values = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @param index The index of the element to return.
   * @return The possibleValues at the given index.
   */
  java.lang.String getPossibleValues(int index);
  /**
   *
   *
   *

   * Required. List of possible enum values.
   *

   *
   * repeated string possible_values = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @param index The index of the value to return.
   * @return The bytes of the possibleValues at the given index.
   */
  com.google.protobuf.ByteString getPossibleValuesBytes(int index);

  /**
   *
   *
   *

   * Make sure the Enum property value provided in the document is in the
   * possile value list during document creation. The validation check runs by
   * default.
   *

   *
   * bool validation_check_disabled = 2;
   *
   * @return The validationCheckDisabled.
   */
  boolean getValidationCheckDisabled();
}


text:
using System;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;

namespace Grpc.Core.Internal.Tests
{
    public class CompletionQueueSafeHandleTest
    {
        [Test]
        public void CreateSyncAndDestroy()
        {
            GrpcEnvironment.AddRef();
            var cq = CompletionQueueSafeHandle.CreateSync();
            cq.Dispose();
            GrpcEnvironment.ReleaseAsync().Wait();
        }

        [Test]
        public void CreateAsyncAndShutdown()
        {
            var env = GrpcEnvironment.AddRef();
            var cq = CompletionQueueSafeHandle.CreateAsync(new CompletionRegistry(env, () => BatchContextSafeHandle.Create(), () => RequestCallContextSafeHandle.Create()));
            cq.Shutdown();
            var ev = cq.Next();
            cq.Dispose();
            GrpcEnvironment.ReleaseAsync().Wait();
            Assert.AreEqual(CompletionQueueEvent.CompletionType.Shutdown, ev.type);
            Assert.AreNotEqual(IntPtr.Zero, ev.success);
            Assert.AreEqual(IntPtr.Zero, ev.tag);
        }
    }
}


text:
const registry = require('package-stream')()
const JSONStream = require('JSONStream');
const fs = require('fs');
const outFileName = './data/graph.in';

const outgoing = JSONStream.stringify(false);
  var fileStream = fs.createWriteStream(outFileName, {
    encoding: 'utf8',
  });
  outgoing.pipe(fileStream);
let found = 0;

registry
  .on('package', function (pkg, seq) {
    let packageNode = {
      id: pkg.name
    };
    if (pkg.dependencies) {
      packageNode.dependencies = pkg.dependencies;
    }
    if (pkg.devDependencies) {
      packageNode.devDependencies = pkg.devDependencies;
    }
    if (pkg.keywords) {
      packageNode.keywords = pkg.keywords;
    }
    if (pkg.tags) {
      packageNode.tags = pkg.tags;
    }
    const maintainers = pkg.other && pkg.other.maintainers;
    if (maintainers) {
      packageNode.maintainers = maintainers;
    }
    outgoing.write(packageNode)
    found += 1;
    if (found % 15000 === 0) console.log('Processed ' + found);
  })
  .on('up-to-date', function () {
    // consumed all changes (for now)
    // The stream will remain open and continue receiving package
    // updates from the registry as they occur in real time.
    console.log('All done. Found ' + found + 'packages');
    process.exit(0)
  })


text:
package info.archinnov.achilles.internals.codegen.dsl.select.cassandra2_2;

import static info.archinnov.achilles.internals.parser.TypeUtils.*;

import java.util.List;
import java.util.Optional;

import com.squareup.javapoet.TypeSpec;

import info.archinnov.achilles.internals.codegen.dsl.JSONFunctionCallSupport;
import info.archinnov.achilles.internals.codegen.dsl.select.SelectWhereDSLCodeGen;
import info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen;
import info.archinnov.achilles.internals.parser.context.GlobalParsingContext;

public class SelectWhereDSLCodeGen2_2 extends SelectWhereDSLCodeGen
        implements JSONFunctionCallSupport {

    @Override
    public void augmentSelectEndClass(TypeSpec.Builder selectEndClassBuilder, ClassSignatureInfo lastSignature) {
        //No Op
    }

    @Override
    public List<TypeSpec> generateExtraWhereClasses(GlobalParsingContext context,
                                                    EntityMetaCodeGen.EntityMetaSignature signature,
                                                    List<FieldSignatureInfo> partitionKeys,
                                                    List<FieldSignatureInfo> clusteringCols) {
        final ClassSignatureParams jsonClassSignatureParams = ClassSignatureParams.of(SELECT_DSL_SUFFIX,
                WHERE_JSON_DSL_SUFFIX, END_JSON_DSL_SUFFIX,
                ABSTRACT_SELECT_WHERE_PARTITION_JSON, ABSTRACT_SELECT_WHERE_JSON);

        return buildWhereClassesInternal(signature, context.selectWhereDSLCodeGen(),
                partitionKeys, clusteringCols,
                jsonClassSignatureParams);

    }

    @Override
    public void augmentRelationClassForWhereClause(TypeSpec.Builder relationClassBuilder,
                                                   FieldSignatureInfo fieldInfo,
                                                   ClassSignatureInfo nextSignature, ReturnType returnType) {
        buildEqFromJSONToRelationClass(relationClassBuilder, fieldInfo, nextSignature);
    }
}


text:
<?php

// Copyright © Captcha, Inc. (formerly Lanapsoft, Inc.) 2004-2016. All rights reserved.
// BotDetect, BotDetect CAPTCHA, Lanap, Lanap CAPTCHA, Lanap BotDetect, Lanap BotDetect CAPTCHA, Lanapsoft, Lanapsoft CAPTCHA, Lanapsoft BotDetect, Lanapsoft BotDetect CAPTCHA, and Lanap Software are trademarks or registered trademarks of Captcha, Inc.

// PHP 5.2.x compatibility workaround
if (!defined('__DIR__')) { define('__DIR__', dirname(__FILE__)); }

// 1. define BotDetect paths

// physical path to Captcha library files (the BotDetect folder)
$BDC_Include_Path = __DIR__ . '/../../../captcha/lib/botdetect/';

// BotDetect Url prefix (base Url of the BotDetect public resources)
$BDC_Url_Root = \LaravelCaptcha\Support\LaravelInformation::getBaseUrl() . '/captcha-handler?get=';

// physical path to the folder with the (optional!) config override file
$BDC_Config_Override_Path = __DIR__;

// normalize paths
if (is_file(__DIR__ . '/botdetect/CaptchaIncludes.php')) {
  // in case a local copy of the library exists, it is always used
  $BDC_Include_Path = __DIR__ . '/botdetect/';
  $BDC_Url_Root = 'botdetect/public/';
} else {
  // clean-up path specifications
  $BDC_Include_Path = BDC_NormalizePath($BDC_Include_Path);
  $BDC_Url_Root = rtrim(BDC_NormalizePath($BDC_Url_Root), '/');
  $BDC_Config_Override_Path = BDC_NormalizePath($BDC_Config_Override_Path);
}
define('BDC_INCLUDE_PATH', $BDC_Include_Path);
define('BDC_URL_ROOT', $BDC_Url_Root);
define('BDC_CONFIG_OVERRIDE_PATH', $BDC_Config_Override_Path);

function BDC_NormalizePath($p_Path) {
  // replace backslashes with forward slashes
  $canonical = str_replace('\\', '/', $p_Path);
  // ensure ending slash
  $canonical = rtrim($canonical, '/');
  $canonical .= '/';
  return $canonical;
}

// 2. include required base class declarations
require_once (BDC_INCLUDE_PATH . 'CaptchaIncludes.php');

// 3. include BotDetect configuration

// a) mandatory global config, located in lib path
require_once(BDC_INCLUDE_PATH . 'CaptchaConfigDefaults.php');

// b) optional config override
function BDC_ApplyUserConfigOverride($CaptchaConfig, $CurrentCaptchaId) {
  $BotDetect = clone $CaptchaConfig;
  $BDC_ConfigOverridePath = BDC_CONFIG_OVERRIDE_PATH . 'CaptchaConfig.php';
  if (is_file($BDC_ConfigOverridePath)) {
    include($BDC_ConfigOverridePath);
    CaptchaConfiguration::ProcessGlobalDeclarations($BotDetect);
    // 2nd pass correctly takes global declarations such as DisabledImageStyles into account
    // even if they're declared after affected values in the CaptchaConfig.php file
    // e.g. ImageStyle setting needs to be re-calculated according to DisabledImageStyles value
    include($BDC_ConfigOverridePath);
  }
  return $BotDetect;
}

// 4. determine is this file included in a form/class, or requested directly
$BDC_RequestFilename = basename($_SERVER['REQUEST_URI']);
if (BDC_StringHelper::StartsWith($BDC_RequestFilename, 'botdetect.php')) {
  // direct access, proceed as Captcha handler (serving images and sounds)
  require_once(BDC_INCLUDE_PATH . 'CaptchaHandler.php');
} else {
  // included in another file, proceed as Captcha class (form helper)
  require_once(BDC_INCLUDE_PATH . 'CaptchaClass.php');
}


text:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class UserController extends Controller
{
    public function actionT()
    {
        echo '.....';
        var_dump(get_called_class());
    }
}


text:
define([
    'jquery',
    'mage/utils/wrapper'
], function ($, wrapper) {
    'use strict';
    var agreementsConfig = window.checkoutConfig.checkoutAgreements;

    return function (setPaymentAction) {
        return wrapper.wrap(setPaymentAction, function(originalAction, messageContainer, paymentData) {
            if (!agreementsConfig.isEnabled) {
                return originalAction(messageContainer, paymentData);
            }

            var agreementForm = $('#iwd-checkout-agreements-form'),
                agreementData = agreementForm.serializeArray(),
                agreementIds = [];

            agreementData.forEach(function(item) {
                agreementIds.push(item.value);
            });

            if(typeof(paymentData.extension_attributes) === 'undefined'
            || paymentData.extension_attributes === null
            ){
                paymentData.extension_attributes = {agreement_ids: agreementIds};
            }else{
                paymentData.extension_attributes.agreement_ids =  agreementIds;
            }
            return originalAction(messageContainer, paymentData);
        });
    };
});


text:
goog.provide('weapi.EditablePolygon');

goog.require('goog.color');

goog.require('weapi.PolyIcon');
goog.require('weapi.Polygon');
goog.require('weapi.markers.PolyDragger');

/**
 * @param {!weapi.App} app .
 * @param {!weapi.markers.MarkerManager} markermanager MarkerManager to use.
 * @constructor
 */
weapi.EditablePolygon = function(app, markermanager) {
  /**
   * @type {!weapi.App}
   * @protected
   */
  this.app = app;

  /**
   * @type {!weapi.markers.MarkerManager}
   * @private
   */
  this.markermanager_ = markermanager;

  /**
   * @type {!weapi.Polygon}
   * @private
   */
  this.polygon_ = new weapi.Polygon();

  this.app.addPrimitive(this.polygon_.primitive);
  this.app.addPrimitive(this.polygon_.primitiveLineCol);
  this.app.sceneChanged = true;

  /**
   * @type {!Object.<number, string>}
   * @private
   */
  this.draggers_ = {};

  /**
   * @type {!Object.<number, !weapi.markers.PolyDragger>}
   * @private
   */
  this.midMap_ = {};

  /**
   * @type {!Object.<number, string>}
   * @private
   */
  this.midDraggers_ = {};

  /**
   * @type {goog.events.ListenableKey|null|number}
   * @private
   */
  this.clickListenKey_ = null;

  /**
   * @type {!weapi.PolyIcon}
   * @private
   */
  this.icon_ = new weapi.PolyIcon(0, 0, this.app);
  //this.icon_.setImage('47.png', 100);

  /**
   * @type {!function()}
   * @private
   */
  this.onchange_ = goog.nullFunction;

  /**
   * @type {number}
   * @private
   */
  this.lastClickToAdd_ = 0;
};

/**
 */
weapi.EditablePolygon.prototype.destroy = function() {
  this.disableClickToAdd();
  this.app.removePrimitive(this.polygon_.primitive);
  this.app.removePrimitive(this.polygon_.primitiveLineCol);
  this.app.sceneChanged = true;
  this.onchange_ = goog.nullFunction;
  this.icon_.destroy();
  goog.object.forEach(this.midDraggers_, function(el, key, obj) {
    this.markermanager_.removeMarker(el);
  }, this);
  goog.object.forEach(this.draggers_, function(el, key, obj) {
    this.markermanager_.removeMarker(el);
  }, this);
  delete this.midMap_;
  delete this.polygon_;
};

/**
 */
weapi.EditablePolygon.prototype.enableClickToAdd = function() {
  if (goog.isDefAndNotNull(this.clickListenKey_)) return;
  // when mouse is down, wait for mouseup and check, if it wasn't a dragging..
  this.clickListenKey_ = goog.events.listen(this.app.canvas,
      goog.events.EventType.MOUSEDOWN, function(e) {
        goog.events.listenOnce(this.app.canvas,
            goog.events.EventType.MOUSEUP, function(e_) {
              if (e_.button == 0 && !goog.isNull(this.clickListenKey_)) {
                if (Math.max(Math.abs(e.offsetX - e_.offsetX),
                    Math.abs(e.offsetY - e_.offsetY)) <= 3) {
                  var cartesian = this.app.camera.camera.pickEllipsoid(
                      new Cesium.Cartesian2(e_.offsetX, e_.offsetY));
                  if (goog.isDefAndNotNull(cartesian)) {
                    var carto = Cesium.Ellipsoid.WGS84.
                        cartesianToCartographic(cartesian);
                    this.addPoint(goog.math.toDegrees(carto.latitude),
                                  goog.math.toDegrees(carto.longitude));
                    e_.preventDefault();
                    this.lastClickToAdd_ = goog.now();
                  }
                }
              }
            }, false, this);
      }, false, this);
};

/**
 */
weapi.EditablePolygon.prototype.disableClickToAdd = function() {
  goog.events.unlistenByKey(this.clickListenKey_);
  this.clickListenKey_ = null;
};

/**
 * @param {string} hexColor #rrggbb.
 * @param {number=} opt_a [0-1], defaults to 1.
 */
weapi.EditablePolygon.prototype.setFillColor = function(hexColor, opt_a) {
  hexColor = goog.color.normalizeHex(hexColor);
  var r = parseInt(hexColor.substr(1, 2), 16) / 255;
  var g = parseInt(hexColor.substr(3, 2), 16) / 255;
  var b = parseInt(hexColor.substr(5, 2), 16) / 255;

  this.polygon_.primitive.material.uniforms['color'] =
      new Cesium.Color(r, g, b, opt_a);

  this.app.sceneChanged = true;
};

/**
 * @param {string} hexColor #rrggbb.
 * @param {number=} opt_a [0-1], defaults to 1.
 */
weapi.EditablePolygon.prototype.setStrokeColor = function(hexColor, opt_a) {
  hexColor = goog.color.normalizeHex(hexColor);
  var r = parseInt(hexColor.substr(1, 2), 16) / 255;
  var g = parseInt(hexColor.substr(3, 2), 16) / 255;
  var b = parseInt(hexColor.substr(5, 2), 16) / 255;

  this.polygon_.primitiveLine.material.uniforms['color'] =
      new Cesium.Color(r, g, b, opt_a);

  this.app.sceneChanged = true;
};

/**
 * @param {string} src URL of the image to use.
 * @param {number} width Desired width of the image in meters.
 * @param {number} height Desired height of the image in meters.
 */
weapi.EditablePolygon.prototype.setIcon = function(src, width, height) {
  this.icon_.setImage(src, width, height);
  this.repositionIcon_();
  this.app.sceneChanged = true;
};

/**
 * @param {!function()} onchange Function to be called whenever polygon changes.
 */
weapi.EditablePolygon.prototype.setOnChange = function(onchange) {
  this.onchange_ = onchange;
};

/**
 * @return {boolean} Is the polygon valid (non self-intersecting,...) ?
 */
weapi.EditablePolygon.prototype.isValid = function() {
  return this.polygon_.isValid();
};

/**
 * @return {number} Rough area of the polygon in m^2.
 */
weapi.EditablePolygon.prototype.getRoughArea = function() {
  return this.polygon_.getRoughArea();
};

/**
 * in degrees
 * @return {{lat: number, lng: number}|null}
 *                                 Centroid of the polygon or null if not valid.
 */
weapi.EditablePolygon.prototype.getCentroid = function() {
  var centroid = this.polygon_.calcCentroid();
  return {'lat': centroid[1], 'lng': centroid[0]};
};

/**
 * in degrees
 * @param {number} lat .
 * @param {number} lng .
 * @return {boolean} True if inside the polygon.
 */
weapi.EditablePolygon.prototype.isPointIn = function(lat, lng) {
  //workaround: the mousedown/up events cause point adding,
  // but the click event can not be easily canceled so
  // it always causes polygon selection when click-to-adding
  if (goog.now() - this.lastClickToAdd_ < 100) return false;
  return this.polygon_.isPointIn(lat, lng);
};

/**
 * @param {!weapi.EditablePolygon} other .
 * @return {boolean} True if the two polygons overlap.
 */
weapi.EditablePolygon.prototype.intersects = function(other) {
  return this.polygon_.intersects(other.polygon_);
};

/**
 * @private
 */
weapi.EditablePolygon.prototype.repositionIcon_ = function() {
  var avg = this.polygon_.calcCentroid() || this.polygon_.calcAverage();

  this.icon_.setLatLng(goog.math.toRadians(avg[1]),
                       goog.math.toRadians(avg[0]));
  this.icon_.enable(this.polygon_.isValid());
};

/**
 * @param {boolean} visible .
 * @param {boolean=} opt_midOnly .
 */
weapi.EditablePolygon.prototype.showDraggers = function(visible, opt_midOnly) {
  goog.object.forEach(this.midMap_, function(el, key, obj) {
    el.enable(visible);
  }, this);
  if (opt_midOnly !== true) {
    goog.object.forEach(this.draggers_, function(el, key, obj) {
      this.markermanager_.getMarker(el).enable(visible);
    }, this);
  }
  this.app.sceneChanged = true;
};

/**
 * @return {!Array.<!{lat: number, lng: number}>} .
 */
weapi.EditablePolygon.prototype.getPoints = function() {
  return this.polygon_.getAllCoords();
};

/**
 * Recalculates position of the two mid-edge draggers neighboring given point.
 * @param {number} fixedId .
 * @private
 */
weapi.EditablePolygon.prototype.repositionMidsAround_ = function(fixedId) {
  var neighs = this.polygon_.getNeighbors(fixedId);
  if (neighs.length > 0) {
    var coordsPrev = this.polygon_.getCoords(neighs[0]);
    var coordsHere = this.polygon_.getCoords(fixedId);
    var coordsNext = this.polygon_.getCoords(neighs[1]);
    this.midMap_[fixedId].lat =
        goog.math.toRadians((coordsHere[1] + coordsNext[1]) / 2);
    this.midMap_[fixedId].lon =
        goog.math.toRadians((coordsHere[0] + coordsNext[0]) / 2);
    this.midMap_[neighs[0]].lat =
        goog.math.toRadians((coordsPrev[1] + coordsHere[1]) / 2);
    this.midMap_[neighs[0]].lon =
        goog.math.toRadians((coordsPrev[0] + coordsHere[0]) / 2);
  }
  this.app.sceneChanged = true;
};

/**
 * Checks, whether the polygon has just changed CW/CCW orientation
 * and performs necessary adjustments.
 * @private
 */
weapi.EditablePolygon.prototype.checkPointOrientationChange_ = function() {
  if (this.polygon_.orientationChanged()) {
    goog.object.forEach(this.midMap_, function(el, key, obj) {
      this.repositionMidsAround_(key);
    }, this);
  }
};

/**
 * @param {!Array.<number>} coords
 */
weapi.EditablePolygon.prototype.addPoints = function(coords) {
  var l = coords.length;
  for (var i = 0; i < l - 1; i++) {
    this.addPoint(coords[i][0], coords[i][1], undefined, undefined, true);
  }
  this.addPoint(coords[i][0], coords[i][1]);
};

/**
 * @param {number} lat in degrees.
 * @param {number} lng in degrees.
 * @param {number=} opt_parent .
 * @param {boolean=} opt_fromMid .
 * @param {boolean=} opt_more More points coming?
 * @return {number} fixedId.
 */
weapi.EditablePolygon.prototype.addPoint = function(lat, lng,
                                                    opt_parent, opt_fromMid,
                                                    opt_more) {
  var fixedId = this.polygon_.addPoint(lat, lng, opt_parent, opt_more);

  if (opt_fromMid && goog.isDefAndNotNull(opt_parent)) {
    this.draggers_[fixedId] = this.midDraggers_[opt_parent];
    delete this.midDraggers_[opt_parent];
  } else {
    var dragger = new weapi.markers.PolyDragger(
        goog.math.toRadians(lat), goog.math.toRadians(lng), this.app, fixedId,
        goog.bind(this.movePoint, this), goog.bind(this.removePoint, this));
    this.draggers_[fixedId] = this.markermanager_.addMarker(null, dragger);
  }
  this.repositionIcon_();

  var neighs = this.polygon_.getNeighbors(fixedId);
  if (neighs.length > 0) {
    var adderAfter = goog.bind(function(parentP) {
      return goog.bind(function(lat, lng) {
        return this.addPoint(lat, lng, parentP, true);
      }, this);
    }, this);
    var mid1 = new weapi.markers.PolyDragger(
        goog.math.toRadians(lat), goog.math.toRadians(lng), this.app, null,
        goog.bind(this.movePoint, this),
        goog.bind(this.removePoint, this),
        adderAfter(fixedId));
    this.midMap_[fixedId] = mid1;
    this.midDraggers_[fixedId] = this.markermanager_.addMarker(null, mid1);

    if (opt_fromMid) {
      var mid2 = new weapi.markers.PolyDragger(
          goog.math.toRadians(lat), goog.math.toRadians(lng), this.app, null,
          goog.bind(this.movePoint, this),
          goog.bind(this.removePoint, this),
          adderAfter(neighs[0]));
      this.midMap_[neighs[0]] = mid2;
      this.midDraggers_[neighs[0]] = this.markermanager_.addMarker(null, mid2);
    }
    this.repositionMidsAround_(neighs[0]);
    this.repositionMidsAround_(fixedId);
    this.repositionMidsAround_(neighs[1]);
  }

  this.checkPointOrientationChange_();
  this.onchange_();

  this.app.sceneChanged = true;

  return fixedId;
};

/**
 * @param {number} fixedId .
 * @param {number} lat in degrees.
 * @param {number} lng in degrees.
 */
weapi.EditablePolygon.prototype.movePoint = function(fixedId, lat, lng) {
  this.polygon_.movePoint(fixedId, lat, lng);
  var marker = this.markermanager_.getMarker(this.draggers_[fixedId]);
  marker.lat = goog.math.toRadians(lat);
  marker.lon = goog.math.toRadians(lng);
  this.checkPointOrientationChange_();
  this.repositionMidsAround_(fixedId);
  this.repositionIcon_();

  this.app.sceneChanged = true;

  this.onchange_();
};

/**
 * @param {number} fixedId .
 */
weapi.EditablePolygon.prototype.removePoint = function(fixedId) {
  var neighs = this.polygon_.getNeighbors(fixedId);

  this.polygon_.removePoint(fixedId);

  this.repositionIcon_();
  if (goog.isDefAndNotNull(this.draggers_[fixedId])) {
    this.markermanager_.removeMarker(this.draggers_[fixedId]);
    delete this.draggers_[fixedId];

    delete this.midMap_[fixedId];
    if (goog.isDefAndNotNull(this.midDraggers_[fixedId])) {
      this.markermanager_.removeMarker(this.midDraggers_[fixedId]);
      delete this.midDraggers_[fixedId];
    }
  }

  this.checkPointOrientationChange_();

  if (neighs.length > 0) {
    this.repositionMidsAround_(neighs[0]);
    this.repositionMidsAround_(fixedId);
    this.repositionMidsAround_(neighs[1]);
  }

  this.app.sceneChanged = true;

  this.onchange_();
};