text:
// 'use strict';
//
// var gulp = require('gulp'),
//     sass = require('gulp-sass'),
//     postcss = require('gulp-postcss'),
//     autoprefixer = require('autoprefixer'),
//     lost = require('lost'),
//     globbing = require('gulp-css-globbing');
//
// var paths = {
//     cssSource: 'lib/css/src/',
//     cssDestination: 'lib/css/mod_ginger_admin/'
// };
//
// gulp.task('sass', function () {
//     gulp.src(paths.cssSource + 'screen.scss')
//     .pipe(globbing({ extensions: ['.scss'] }))
//     .pipe(sass({
//             outputStyle : 'compressed',
//             errLogToConsole: true
//         }))
//     .on('error', handleError)
//     .pipe(postcss([
//         lost(),
//         autoprefixer('last 2 versions', 'ie > 7')
//     ]))
//     .pipe(gulp.dest(paths.cssDestination));
// });
//
// gulp.task('sass:watch', function () {
//
//
//     var watchPaths = [
//         paths.cssSource + '/**/*.scss'
//     ]
//
//     gulp.watch(watchPaths, ['sass']);
// });
//
// function handleError(e) {
//     console.log('error...', e);
// }
//
// gulp.task('default', ['sass', 'sass:watch']);

const gulp = require('gulp');

// Scss
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const globbing = require('gulp-css-globbing');

// Javascript
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');

// Prevents the pipe/stream from breaking on error
const plumber = require('gulp-plumber');

// Livereload
const livereload = require('gulp-livereload');

// Locations of scss, javascript and template files
// Add scss file paths to de the modulesSrc array to trigger scss proccessing on file change
// e.g. '../../modules/mod_ginger_foundation/lib/css/src'
const paths = {
    modulesSrc: [],
    scssSrc: 'lib/css/src',
    scssDest: 'lib/css/mod_ginger_admin',
    templateSrc: 'templates'
};

// Reload page when .tpl file changes
gulp.task('tpl', () => gulp.src('/').pipe(livereload()));

// Process, minify and prefix scss files
gulp.task('sass', () => {
    gulp.src(`${paths.scssSrc}/screen.scss`)
        .pipe(plumber())
        .pipe(globbing({ extensions: ['.scss'] }))
        .pipe(sass({ outputStyle: 'compressed' }))
        .on('error', sass.logError)
        .pipe(postcss([
            autoprefixer('last 2 versions', 'ie > 7')
        ]))
        .pipe(gulp.dest(paths.scssDest))
        .pipe(livereload());
});

// Init livereload server and watch scss, javascript and template files for changes
gulp.task('watch', () => {
    livereload.listen();

    const scssCombinedPaths = paths.modulesSrc
        .map(x => `${x}/**/*.scss`)
        .concat(`${paths.scssSrc}/**/*.scss`);

    gulp.watch(scssCombinedPaths, ['sass']);
    gulp.watch(`${paths.templateSrc}/**/*.tpl`, ['tpl']);
});

gulp.task('default', ['sass', 'watch']);


text:
/*include:js/core/namespace.js*/
/*include:js/core/math.js*/
/*include:js/core/events.js*/
/*include:js/editor/core/renderer.js*/

(function () {
    var math = wd.math,
        events = wd.events,
        renderer = wd.renderer;

    wd.Wall = (function () {
        function Wall(config) {
            var normX, normY, length;

            this.aX = config.aX;
            this.aY = config.aY;
            this.bX = config.bX;
            this.bY = config.bY;
            this.door = config.door;

            normX = config.bX - config.aX;
            normY = config.bY - config.aY;
            length = math.length(normX, normY);

            this.x = -normY / length;
            this.y = normX / length;
        }

        Wall.INTERSECTING = 0;
        Wall.RIGHT = 1;
        Wall.LEFT = 2;

        Wall.prototype = {
            constructor: Wall,
            inFrontOf: function (otherWall) {
                var position, distanceA, distanceB;

                distanceA = math.directionalDistance(this.aX, this.aY, this.x, this.y, otherWall.aX, otherWall.aY);
                distanceB = math.directionalDistance(this.aX, this.aY, this.x, this.y, otherWall.bX, otherWall.bY);
                position = (distanceA + distanceB) * 0.5;

                return position >= 0;
            },
            getRelation: function (otherWall) {
                var distanceA, distanceB;

                if (this !== otherWall) {
                    distanceA = math.directionalDistance(this.aX, this.aY, this.x, this.y, otherWall.aX, otherWall.aY);
                    distanceB = math.directionalDistance(this.aX, this.aY, this.x, this.y, otherWall.bX, otherWall.bY);

                    if (distanceA * distanceB < -0.001) {
                        return Wall.INTERSECTING;
                    } else if ((distanceA + distanceB) * 0.5 < -0.001) {
                        return Wall.LEFT;
                    } else {
                        return Wall.RIGHT;
                    }
                } else {
                    return Wall.RIGHT;
                }
            }
        };

        return Wall;
    }());
}());

redpajama_set_name: RedPajamaGithub


text:
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;

namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
    [TestFixture]
    [Ignore("TODO: Issue not ported yet")]
    public class UseMethodIsInstanceOfTypeTests : CSharpDiagnosticTestBase
    {
        [Test]
        public void TestBasicUsage()
        {
            Test<UseMethodIsInstanceOfTypeAnalyzer>(@"using System;
class FooBar
{
	void Foo()
	{
		Type t;
		if (t.IsAssignableFrom (this.GetType ())) {
		}
	}
}
", @"using System;
class FooBar
{
	void Foo()
	{
		Type t;
		if (t.IsInstanceOfType (this)) {
		}
	}
}
");
        }

        [Test]
        public void TestDisable()
        {
            Analyze<UseMethodIsInstanceOfTypeAnalyzer>(@"using System;
class FooBar
{
	void Foo()
	{
		Type t;
		// ReSharper disable once UseMethodIsInstanceOfType
		if (t.IsAssignableFrom (this.GetType ())) {
		}
	}
}
");
        }

    }
}


text:
id: 304
title: How I set up Continuous Integration and Continuous Deployment on my new Web App
date: 2015-06-21T11:01:36+00:00
author: Gjermund Bjaanes
layout: post
permalink: /how-i-set-up-continuous-integration-and-continuous-deployment-on-my-new-web-app-2/
dsq_thread_id:
  - 3866297397
categories:
  - Uncategorized
tags:
  - Programming
  - Web
---
I recently started working on a brand new web app. It has been a blast, but I wanted to be able to show the app off and test it, even when I am not in front of my development environment. Also, I really wanted all my tests to run every time I pushed to GitHub.

These things exists and are called Continuous Deployment (CD) and Continuous Integration (CI).

Update: I Added how to set up the CI to run e2e tests with protractor.

# Continuous Integration with Travis

For doing CI, I found a very popular service called Travis CI. It's 10,000% free (according to their web site) for Open Source projects. It was super easy to set up. All I needed (almost) to do was to set up an account and connect to my Github Account.

The second thing I had to do for travis to work, was to set up a .travis.yml file. I have a pretty standard project so far, so I didn't have to do much work to get set up there.

language: node_js
node_js:
  - "0.10"

before_script:
  - export DISPLAY=:99.0
  - sh -e /etc/init.d/xvfb start
  - webdriver-manager update
  - npm install
  - npm install -g bower
  - bower install
  - gulp > /dev/null & # start server
  - sleep 10 # give server time to start

script:
  - node_modules/.bin/karma start karma.conf.js --no-auto-watch --single-run
  - node_modules/.bin/protractor protractor.conf.js --browser=firefox

All it really does is set up what it needs to be able to run the tests with karma on Travis. It has a setup set called "before_script" where any installation and other preparation needs to happen. The "script" step is where you run your tests. I will soon add a new line for starting my protractor test suite.

It does some setup so that I can run Firefox (for tests), but the thing I had to add to make it work for me was the bower setup ("- npm install -g bower" and "- bower install").

## Protractor

I have set up Travis to run protractor as well. The most important parts of the script for this is the "gulp > /dev/null &" which builds the project and start a local web server (it might be done a different way for you).

In my case the default gulp task starts a web server locally at port 8080. I then have a param in my protractor.conf.js file like this:

exports.config = {
    params: {
        client: 'http://localhost:8080/'
    },
    ...
};

That way, the tests can do the following and still understand which web server to pick:

browser.get(browser.params.client);

Finally, the tests are run using the:

- node_modules/.bin/protractor protractor.conf.js --browser=firefox

  <img class=" wp-image-308" src="http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25.png" alt="Screenshot from Travis website" width="731" height="205" srcset="http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25.png 1962w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25-300x84.png 300w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25-1024x287.png 1024w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25-945x265.png 945w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.14.25-600x168.png 600w" sizes="(max-width: 731px) 100vw, 731px" />

    Screenshot from Travis website

Feel free to use my travis script, it was taken from the angular seed project:

https://github.com/angular/angular-seed

# Continuous Deployment with dploy

I wanted my code to be pushed to a DigitalOcean droplet. The reason for that is because DigitalOcean is what I use to do these sort of things. It's also very cheap and easy to set up some droplets/vps for basically anything.

I started out by creating my account and connecting to GitHub and DigitalOcean.

After I had set up the dploy account I created a Droplet with the dploy and then created the deployment repository on my new dploy site.

On my droplet I installed node, npm, bower globally and gulp globally. I also installed a light weight web server called lighttpd. Not much setup needed. I just had to set up the environment on dploy to target /var/www on my droplet.

Finally, I had to set up a couple of Pre-launch commands to actually build the app.

npm install
bower install --allow-root --config.interactive=false
gulp build

Not much interesting. Installing npm dependencies, bower dependencies and then starting my gulp build script. Super easy!

  <img class=" wp-image-309" src="http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41.png" alt="Screen shot from dploy web site" width="725" height="976" srcset="http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41.png 1582w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41-223x300.png 223w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41-761x1024.png 761w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41-945x1272.png 945w, http://gjermundbjaanes.com/wp-content/uploads/2015/06/Screen-Shot-2015-06-15-at-19.13.41-600x808.png 600w" sizes="(max-width: 725px) 100vw, 725px" />

    Screenshot from dploy web site

The entire process took me no more than a couple of hours of fiddling, but it really feels good to have some automation set up. It will probably save me a lot of time later!

**NOTE!**

Dploy is now called DeployBot.

Since I wrote this article, the Digital Ocean API v.1 has been deprecated.
The guide should still be valid in most of it's form.


text:
var fs = require('fs');
var path = require('path');
var spawn = require('child-process-promise').spawn;
var Promise = require('bluebird');
var tmpName = Promise.promisify(require('tmp').tmpName);
var rimraf = require('rimraf');
var serviceLocator = require('../../service-locator');
var Context = require('../../context');

/**
 * @param {String} id
 * @param {Object} jobData
 * @param {Object} configuration
 * @constructor
 */
function AbstractJob(id, jobData, configuration) {

  /** @type {String} */
  this.id = id;

  /** @type {Object} */
  this._jobData = jobData;

  /** @type {Object} */
  this._configuration = configuration;

  /** @type {Promise} */
  this._promise = null;

  /** @type {ChildProcess} */
  this._process = null;

  /** @type {String|null} */
  this._workingDirectory = null;

  /** @type {Number} */
  this._maxRunningTime = 24 * 60 * 60 * 1000;

  /** @type {Number} */
  this._retryCount = 0;
}

/**
 * @returns {String}
 */
AbstractJob.prototype.getName = function() {
  return this.constructor.getPlugin() + ':' + this.constructor.getEvent();
};

AbstractJob.prototype.toString = function() {
  return 'Job' + JSON.stringify({id: this.id, name: this.getName(), workingDirectory: this._workingDirectory});
};

/**
 * @param {String} workingDirectory
 */
AbstractJob.prototype.setWorkingDirectory = function(workingDirectory) {
  this._workingDirectory = workingDirectory;
};

/**
 * @returns {String} workingDirectory
 */
AbstractJob.prototype.getWorkingDirectory = function() {
  if (null === this._workingDirectory) {
    throw new Error('Working directory not set');
  }
  return this._workingDirectory;
};

/**
 * @returns {Promise}
 */
AbstractJob.prototype.run = function() {
  this._promise = this._run().timeout(this._maxRunningTime);
  return this._promise;
};

/**
 * @returns {Promise}
 */
AbstractJob.prototype._run = function() {
  throw new Error('Not Implemented');
};

AbstractJob.prototype.cancel = function() {
  if (this._promise && this._promise.isPending()) {
    this._promise.cancel();
    this._promise = null;
  }
  this.cleanup();
};

AbstractJob.prototype.cleanup = function() {
  if (this._process) {
    this._process.kill('SIGKILL');
    this._process = null;
  }
  if (this._workingDirectory) {
    rimraf.sync(this._workingDirectory);
  }
};

/**
 * @returns {Context}
 */
AbstractJob.prototype.getContext = function() {
  return new Context({
    janus: {
      jobId: this.id,
      jobHandlerType: this.getName()
    }
  });
};

/**
 * @param {String} commandText
 * @returns {Promise}
 */
AbstractJob.prototype._runJobScript = function(commandText) {
  var context = this.getContext();
  var command = commandText;
  var commandArgs = [];
  if (commandText.indexOf(' ') >= 0) {
    var commandParts = commandText.split(' ');
    command = commandParts.shift();
    commandArgs = commandParts;
  }
  context.extend({janus: {command: commandText}});

  serviceLocator.get('logger').debug('Starting job process', context);
  var options = {
    cwd: this.getWorkingDirectory(),
    capture: ['stdout', 'stderr']
  };
  var self = this;
  return this._spawn(command, commandArgs, options)
    .progress(function(childProcess) {
      self._process = childProcess;
    })
    .then(function(result) {
      return result.stdout.toString();
    })
    .catch(function(error) {
      self._retryCount++;
      if (self._retryCount > 10) {
        error.failedRepeatedly = true;
      }
      if (self._retryCount > 20) {
        error.stderr = null;
        error.stdout = null;
      }
      context.extend({exception: error});
      serviceLocator.get('logger').error('Failed job process', context);
      throw error;
    })
    .finally(function() {
      self._process = null;
    });
};

/**
 * @param {String} extension
 * @returns {Promise}
 */
AbstractJob.prototype._tmpFilename = function(extension) {
  var options = {dir: this.getWorkingDirectory()};
  if (extension) {
    options['postfix'] = '.' + extension;
  }
  return tmpName(options);
};

/**
 * @returns {String}
 */
AbstractJob.getPlugin = function() {
  throw new Error('Not Implemented');
};

/**
 * @returns {String}
 */
AbstractJob.getEvent = function() {
  throw new Error('Not Implemented');
};

AbstractJob.prototype._spawn = spawn;

module.exports = AbstractJob;


text:
package xml

import (
	"io"

	"github.com/tdewolff/minify/v2"
	"github.com/tdewolff/parse/v2"
	"github.com/tdewolff/parse/v2/xml"
)

var (
	isBytes    = []byte("=")
	spaceBytes = []byte(" ")
	voidBytes  = []byte("/>")
)

////////////////////////////////////////////////////////////////

// Minifier is an XML minifier.
type Minifier struct {
	KeepWhitespace bool
}

// Minify minifies XML data, it reads from r and writes to w.
func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
	return (&Minifier{}).Minify(m, w, r, params)
}

// Minify minifies XML data, it reads from r and writes to w.
func (o *Minifier) Minify(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
	omitSpace := true // on true the next text token must not start with a space

	attrByteBuffer := make([]byte, 0, 64)

	z := parse.NewInput(r)
	defer z.Restore()

	l := xml.NewLexer(z)
	tb := NewTokenBuffer(l)
	for {
		t := *tb.Shift()
		if t.TokenType == xml.CDATAToken {
			if len(t.Text) == 0 {
				continue
			}
			if text, useText := xml.EscapeCDATAVal(&attrByteBuffer, t.Text); useText {
				t.TokenType = xml.TextToken
				t.Data = text
			}
		}
		switch t.TokenType {
		case xml.ErrorToken:
			if _, err := w.Write(nil); err != nil {
				return err
			}
			if l.Err() == io.EOF {
				return nil
			}
			return l.Err()
		case xml.DOCTYPEToken:
			w.Write(t.Data)
		case xml.CDATAToken:
			w.Write(t.Data)
			if len(t.Text) > 0 && parse.IsWhitespace(t.Text[len(t.Text)-1]) {
				omitSpace = true
			}
		case xml.TextToken:
			t.Data = parse.ReplaceMultipleWhitespaceAndEntities(t.Data, EntitiesMap, TextRevEntitiesMap)

			// whitespace removal; trim left
			if omitSpace && parse.IsWhitespace(t.Data[0]) {
				t.Data = t.Data[1:]
			}

			// whitespace removal; trim right
			omitSpace = false
			if len(t.Data) == 0 {
				omitSpace = true
			} else if parse.IsWhitespace(t.Data[len(t.Data)-1]) {
				omitSpace = true
				i := 0
				for {
					next := tb.Peek(i)
					// trim if EOF, text token with whitespace begin or block token
					if next.TokenType == xml.ErrorToken {
						t.Data = t.Data[:len(t.Data)-1]
						omitSpace = false
						break
					} else if next.TokenType == xml.TextToken {
						// this only happens when a comment, doctype, cdata startpi tag was in between
						// remove if the text token starts with a whitespace
						if len(next.Data) > 0 && parse.IsWhitespace(next.Data[0]) {
							t.Data = t.Data[:len(t.Data)-1]
							omitSpace = false
						}
						break
					} else if next.TokenType == xml.CDATAToken {
						if len(next.Text) > 0 && parse.IsWhitespace(next.Text[0]) {
							t.Data = t.Data[:len(t.Data)-1]
							omitSpace = false
						}
						break
					} else if next.TokenType == xml.StartTagToken || next.TokenType == xml.EndTagToken {
						if !o.KeepWhitespace {
							t.Data = t.Data[:len(t.Data)-1]
							omitSpace = false
						}
						break
					}
					i++
				}
			}
			w.Write(t.Data)
		case xml.StartTagToken:
			if o.KeepWhitespace {
				omitSpace = false
			}
			w.Write(t.Data)
		case xml.StartTagPIToken:
			w.Write(t.Data)
		case xml.AttributeToken:
			w.Write(spaceBytes)
			w.Write(t.Text)
			w.Write(isBytes)

			if len(t.AttrVal) < 2 {
				w.Write(t.AttrVal)
			} else {
				val := t.AttrVal[1 : len(t.AttrVal)-1]
				val = parse.ReplaceEntities(val, EntitiesMap, nil)
				val = xml.EscapeAttrVal(&attrByteBuffer, val) // prefer single or double quotes depending on what occurs more often in value
				w.Write(val)
			}
		case xml.StartTagCloseToken:
			next := tb.Peek(0)
			skipExtra := false
			if next.TokenType == xml.TextToken && parse.IsAllWhitespace(next.Data) {
				next = tb.Peek(1)
				skipExtra = true
			}
			if next.TokenType == xml.EndTagToken {
				// collapse empty tags to single void tag
				tb.Shift()
				if skipExtra {
					tb.Shift()
				}
				w.Write(voidBytes)
			} else {
				w.Write(t.Data)
			}
		case xml.StartTagCloseVoidToken:
			w.Write(t.Data)
		case xml.StartTagClosePIToken:
			w.Write(t.Data)
		case xml.EndTagToken:
			if o.KeepWhitespace {
				omitSpace = false
			}
			if len(t.Data) > 3+len(t.Text) {
				t.Data[2+len(t.Text)] = '>'
				t.Data = t.Data[:3+len(t.Text)]
			}
			w.Write(t.Data)
		}
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SQLite4Unity3d;
using System;
using System.IO;
using System.Linq;

public class DataService
{
    public static DataService instance;

    private SQLiteConnection _connection;
    private string currentDbPath = "";
    private bool dbExists;

    public DataService()
    {

        string DatabaseName = "SatisfactionQuestDB";

#if UNITY_EDITOR
        var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
#else
        // check if file exists in Application.persistentDataPath
        var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);

        if (!File.Exists(filepath))
        {
            Debug.Log("Database not in Persistent path");
            // if it doesn't ->
            // open StreamingAssets directory and load the db ->

#if UNITY_ANDROID
            var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
            //while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
            // then save to Application.persistentDataPath
            File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
                 var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
#elif UNITY_WP8
                var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);

#elif UNITY_WINRT
		var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
		// then save to Application.persistentDataPath
		File.Copy(loadDb, filepath);
#else
	var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
	// then save to Application.persistentDataPath
	File.Copy(loadDb, filepath);

#endif

            Debug.Log("Database written");
        }

        var dbPath = filepath;
#endif
        _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
        Debug.Log("Final PATH: " + dbPath);

        CreateIfNotExists<PlayerDTO>();
        CreateIfNotExists<LocationDTO>();
        CreateIfNotExists<ExitDTO>();
        CreateIfNotExists<ItemDTO>();
        CreateIfNotExists<SessionDTO>();

    }

    public void DeleteDatabaseFile()
    {
        File.Delete("SatisfactionQuestDB");
    }

    public void Connect()
    {
        _connection = new SQLiteConnection(currentDbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
    }

    //create DTO table if it does not exist
    private void CreateIfNotExists<T>() where T : new()
    {
        _connection.CreateTable<T>();
    }

    //Check if username and password is valid. Return true if count greater than 0
    public bool CheckLogin(string pUsername, string pPassword)
    {
        int count = _connection.Table<PlayerDTO>().Where(x => x.Username == pUsername
                                             && x.Password == pPassword).Count();

        return count > 0;
    }

    //Check if username is taken. Can be combined with CheckLogin, but this is the method for now
    public bool CheckUsernameExists(string pUsername)
    {
        int count = _connection.Table<PlayerDTO>().Where(x => x.Username == pUsername).Count();

        return count > 0;
    }

    //Add a player to PlayerDTO table
    public void AddPlayer(string pUsername, string pPassword)
    {
        var player = _connection.Insert(new PlayerDTO()
        {
            Username = pUsername,
            Password = pPassword
        });
    }

    /**
     * Creates a new game session, returns sessionId
     */
    public int CreateGameSession(string pUsername)
    {
        SessionDTO sessionDTO = new SessionDTO
        {
            Name_Player1 = pUsername,
            Location_Player1 = Location.NAME.TOMB.ToString()
        };
        SetSession(sessionDTO);
        //_connection.Insert(sessionDTO);

        var q = _connection.Query<SessionDTO>(
            "select Id from SessionDTO"
            ).LastOrDefault();
        return q.Id;
    }

    public void SaveSession()
    {
        var session = GameManager.instance;

        SessionDTO sessionDTO = new SessionDTO
        {
            Id = session.Id,
            Name_Player1 = session.Player1.username,
            Location_Player1 = session.gameModel.currentLocation.name,
            Esteem_Player1 = session.Player1.esteem,
            Score_Player1 = session.Player1.score
            //Name_Player2 = session.player2.username,
            //Location_Player2 = session.gameModel.currentLocation.name,
            //Esteem_Player1 = session.player1.esteem,
            //Score_Player1 = session.player1.score
        };
        SetSession(sessionDTO);
    }

    public void LoadSession()
    {

    }

    /**
    * Save / create locations from the GameModel location map, including their exits and items
    * NB: Only used to create the game model, as these values are currently static
    */
    public void SaveLocations()
    {
        var lcLocationMap = GameManager.instance.gameModel.worldMap;

        foreach (var location in lcLocationMap)    //for every location in the location map
        {
            LocationDTO locationDTO = new LocationDTO
            {
                Name = location.Value.name,
                Description = location.Value.description,
                Background = location.Value.background
            };

            SetLocation(locationDTO);       //set location is slightly unnessary because Locations are static in this implementation

            foreach (var exit in location.Value.exits)      //for every exit in the location's exit dictionary
            {
                ExitDTO exitDTO = new ExitDTO
                {
                    FromLocation = location.Value.name,
                    Direction = (int)exit.Key,          //the key value corresponds to the enum's int value for that direction
                    ToLocation = exit.Value
                };
                SetExit(exitDTO);
            }
        }
    }

    /**
     *  Load location and exits from database to populate game model.
     *  NB:
     */
    public void LoadLocations()
    {
        foreach (var locationDTO in GetLocations())
        {
            GameManager.instance.gameModel.LoadWorldLocation(locationDTO);
            //GameManager.instance.gameModel.LoadWorldLocation(locationDTO.Name, locationDTO.Description, locationDTO.Background);
        }

        foreach (var exitDTO in GetExits())
        {
            GameManager.instance.gameModel.LoadWorldLocationExit(exitDTO);
            //GameManager.instance.gameModel.LoadWorldLocationExits(exitDTO.FromLocation, exitDTO.Direction, exitDTO.ToLocation);
        }
    }

    //create session items for new game session
    public void CreateSessionItems(int pSessionId)
    {
        var lcWorldItems = GameManager.instance.gameModel.worldItems;

        foreach (var item in lcWorldItems)
        {
            ItemDTO itemDTO = new ItemDTO
            {
                Name = item.Key,
                Description = item.Value.description,
                Location = item.Value.location,
                SecretLetter = item.Value.secretLetter,
                SessionId = pSessionId,
            };
            SetSessionItem(itemDTO);
        }
    }

    //Save or update db details of all session items for a session
    public void SaveSessionItems()
    {
        var lcWorldItems = GameManager.instance.gameModel.worldItems;

        foreach (var item in lcWorldItems)
        {
            ItemDTO itemDTO = new ItemDTO
            {
                Id = item.Value.id,
                Name = item.Key,
                Description = item.Value.description,
                Location = item.Value.location,
                SecretLetter = item.Value.secretLetter,
                SessionId = item.Value.sessionId
            };
            SetSessionItem(itemDTO);
        }
    }

    //Save or update db details of a single item
    private void SaveSessionItem(int pId, string pKey)
    {
        var item = GameManager.instance.gameModel.worldItems[pKey];

        ItemDTO itemDTO = new ItemDTO
        {
            Id = item.id,
            Description = item.description,
            Location = item.location,
            SecretLetter = item.secretLetter,
            SessionId = item.sessionId
        };
        SetSessionItem(itemDTO);
    }

    public void LoadSessionItems()
    {
        foreach (var item in GetSessionItems(GameManager.instance.Id))
        {

            GameManager.instance.gameModel.LoadWorldItem(item);
        }
    }

    //Update local model of session items from database
    public void UpdateLocalSessionItems()
    {
        foreach (var item in GetSessionItems(GameManager.instance.Id))
        {
            GameManager.instance.gameModel.UpdateWorldItem(item);
        }
    }

    public void UpdateLocalSessionState()
    {
        //GameManager.instance.gameModel

    }

    /**
     * Set methods to perform inserts or updates of records
     */

    private void SetSession(SessionDTO pSessionDTO)
    {
        CreateIfNotExists<SessionDTO>();

        if (SessionExists(pSessionDTO.Id))
        {
            Debug.Log("SetSession update sessionId = " + pSessionDTO.Id);
            _connection.Update(pSessionDTO);
        }
        else
        {
            Debug.Log("SetSession insert sessionId = " + pSessionDTO.Id);

            _connection.Insert(pSessionDTO);
        }
    }

    private void SetLocation(LocationDTO pLocationDTO)
    {
        CreateIfNotExists<LocationDTO>();

        if (LocationExists(pLocationDTO.Name))
        {
            _connection.Update(pLocationDTO);
        }
        else
        {
            _connection.Insert(pLocationDTO);
        }
    }

    private void SetExit(ExitDTO pExitDTO)
    {
        CreateIfNotExists<ExitDTO>();

        if (ExitExists(pExitDTO.Id))
        {
            _connection.Update(pExitDTO);
        }
        else
        {
            _connection.Insert(pExitDTO);
        }
    }

    private void SetSessionItem(ItemDTO pItemDTO)
    {
        CreateIfNotExists<ItemDTO>();

        if (SessionItemExists(pItemDTO.SessionId, pItemDTO.Name))
        {
            _connection.Update(pItemDTO);
        }
        else
        {
            _connection.Insert(pItemDTO);
        }
    }

    /**
     * Get methods to retrieve data
     */

    public IEnumerable<PlayerDTO> GetPlayers()
    {
        return _connection.Table<PlayerDTO>();
    }

    public PlayerDTO GetPlayer(string pUsername)
    {
        return _connection.Table<PlayerDTO>().Where(x => x.Username == pUsername).FirstOrDefault();
    }

    public IEnumerable<LocationDTO> GetLocations()
    {
        return _connection.Table<LocationDTO>();
    }

    public IEnumerable<ExitDTO> GetExits()
    {
        return _connection.Table<ExitDTO>();
    }

    public IEnumerable<ItemDTO> GetItems()
    {
        return _connection.Table<ItemDTO>();
    }

    public IEnumerable<SessionDTO> GetSessions()
    {
        return _connection.Table<SessionDTO>();
    }

    //returns last played session
    public SessionDTO GetPreviousSession(string pUsername)
    {
        return _connection.Table<SessionDTO>().Where(x => x.Name_Player1 == pUsername).LastOrDefault();
    }

    public IEnumerable<ItemDTO> GetSessionItems(int pSessionId)
    {
        return _connection.Table<ItemDTO>().Where(x => x.SessionId == pSessionId);
    }

    public IEnumerable<ItemDTO> GetSessionLocationItems(int pSessionId, string pLocation)
    {
        return _connection.Table<ItemDTO>().
            Where(x => x.SessionId == pSessionId && x.Location == pLocation);
    }

    public IEnumerable<ItemDTO> GetPlayerItems(int pSessionId, string pUsername)
    {
        return _connection.Table<ItemDTO>().
            Where(x => x.SessionId == pSessionId && x.Location == pUsername);
    }

    /**
     * Exist methods for determining whether records are present
     */

    private bool SessionExists(int pId)
    {
        var y = _connection.Table<ItemDTO>().Where(
                x => x.Id == pId).FirstOrDefault();

        return y != null;
    }

    //detects a previous game session by player username
    public bool PreviousSessionExists(string pUsername)
    {
        var y = _connection.Table<SessionDTO>().Where(x => x.Name_Player1 == pUsername).LastOrDefault();
        return y != null;
    }

    private bool LocationExists(string pLocationName)
    {
        var y = _connection.Table<LocationDTO>().Where(
                x => x.Name == pLocationName).FirstOrDefault();

        return y != null;
    }

    private bool ExitExists(int pExitId)
    {
        var y = _connection.Table<ExitDTO>().Where(
                x => x.Id == pExitId).FirstOrDefault();

        return y != null;
    }

    private bool ItemExists(int pItemId)
    {
        var y = _connection.Table<ItemDTO>().Where(
                x => x.Id == pItemId).FirstOrDefault();

        return y != null;
    }

    private bool SessionItemExists(int pSessionId, string pItemName)
    {
        var y = _connection.Table<ItemDTO>().Where(
                x => x.SessionId == pSessionId && x.Name == pItemName).FirstOrDefault();

        return y != null;
    }
}

//public bool DbExists(string DatabaseName)
//{
//    // Watch out! this method has a side effect
//    bool result = false;

//#if UNITY_EDITOR
//    var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
//    result = File.Exists(dbPath);
//#else
//		// check if file exists in Application.persistentDataPath
//		var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);

//		if (!File.Exists(filepath))
//		{
//		result = false;
//		Debug.Log("Database not in Persistent path");
//		// if it doesn't ->
//		// open StreamingAssets directory and load the db ->

//#if UNITY_ANDROID
//		var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
//		while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
//		// then save to Application.persistentDataPath
//		File.WriteAllBytes(filepath, loadDb.bytes);
//#elif UNITY_IOS
//		var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
//		// then save to Application.persistentDataPath
//		File.Copy(loadDb, filepath);
//#elif UNITY_WP8
//		var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
//		// then save to Application.persistentDataPath
//		File.Copy(loadDb, filepath);

//#elif UNITY_WINRT
//		var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
//		// then save to Application.persistentDataPath
//		File.Copy(loadDb, filepath);
//#else
//		var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
//		// then save to Application.persistentDataPath
//		File.Copy(loadDb, filepath);

//#endif

//		Debug.Log("Database written");
//		}

//		var dbPath = filepath;
//#endif

//    currentDbPath = dbPath;
//    Debug.Log("Final PATH: " + dbPath);

//    return result;
//}

/*
     * Get list of items from given session at given location
     * REFERENCE: https://stackoverflow.com/a/16007371 Author: chue x
     */
//public IEnumerable<SessionItemDTO> GetSessionLocationItems(int pSessionId, string pLocationName)
//{
//    var q = _connection.Query<SessionItemDTO>(
//        "select * from SessionItemDTO inner join ItemDTO"
//        + " on ItemDTO.Name = SessionItemDTO.ItemName where (SessionItemDTO.Location = ?"
//        + " and SessionItemDTO.SessionId = ?)", pLocationName, pSessionId);

//    return q;
//}


text:
'use strict';

angular.module('mean.system').controller('HeaderController', ['$scope', '$rootScope', 'Global', 'Menus',
  function($scope, $rootScope, Global, Menus) {
    $scope.global = Global;
    $scope.menus = {};

    // Default hard coded menu items for main menu
    var defaultMainMenu = [];

    // Query menus added by modules. Only returns menus that user is allowed to see.
    function queryMenu(name, defaultMenu) {

      Menus.query({
        name: name,
        defaultMenu: defaultMenu
      }, function(menu) {
        $scope.menus[name] = menu;
      });
    }

    // Query server for menus and check permissions
    queryMenu('main', defaultMainMenu);

    $scope.isCollapsed = false;

    $rootScope.$on('loggedin', function() {

      queryMenu('main', defaultMainMenu);

      $scope.global = {
        authenticated: !! $rootScope.user,
        user: $rootScope.user
      };
    });

  }
]);
/*
angular.module('mean.users')
  .controller('AuthCtrl', ['$scope', '$rootScope', '$http', '$location', 'Global',
    function($scope, $rootScope, $http, $location, Global) {
      // This object will contain list of available social buttons to authorize
      $scope.socialButtons = {};
      $scope.socialButtonsCounter = 0;
      $scope.global = Global;
      $http.get('/get-config')
        .success(function(config) {
          for (var conf in config) {
            // Do not show auth providers that have the value DEFAULT as their clientID
            if (config[conf].hasOwnProperty(clientIdProperty) && config[conf][clientIdProperty].indexOf(defaultPrefix) === -1) {
              $scope.socialButtons[conf] = true;
              $scope.socialButtonsCounter += 1;
            }
          }
        });
    }
  ])
*/


text:
#ifndef PAWGUI_DOCK_SYSTEM_H
#define PAWGUI_DOCK_SYSTEM_H

#include "pawgui_resource_dropdown.h"
#include "pawgui_general_resource.h"
#include "pawgui_buttons.h"
#include "pawgui_tab_basic.h"
#include "pawgui_panel_list.h"

namespace pawgui
{
    class widget_dock_panel: public pawgui::widget_basic
    {
    private:
        pawgui::widget_tabbar * panelBar;
        gpe::shape_rect * panelRect;
    public:
        pawgui::widget_basic * specialPanelElement;
        pawgui::widget_button_icon * dock_settings_button;
        bool just_resized;
        bool being_resized;
        bool menuResized;
        bool wasProcessed;
        pawgui::widget_panel_list * panelGuiList;
        gpe::shape_rect * containerRect;
        widget_dock_panel();
        ~widget_dock_panel();
        bool add_container( std::string name, bool openNew = false );
        void add_gui_element(pawgui::widget_basic * element, bool isNLElement = true );
        void add_gui_auto(pawgui::widget_basic * element);
        void add_gui_element_fullsize(pawgui::widget_basic * element);
        void clear_panel();
        bool container_in_view( std::string name );
        bool contains_tab( std::string name );
        int get_panel_height();
        std::string get_selected_container();
        int get_tab_count();
        std::string get_tab_name( int pos );
        bool has_content();
        void process_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr );
        bool save_panel_data_to_file(std::ofstream * fileTarget);
        void setup_panel( bool addSpacing = true, bool clearList = true );
        bool remove_container( std::string name );
        void render_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr );
        void reset_panel();
    };

    class widget_dock: public pawgui::widget_basic
    {
    private:
        bool is_hidden;
        int panel_x_count;
        int panel_y_count;
        int panel_max_count;

        std::vector< gpe::key_pair * > default_panels;
        std::vector< int > panel_column_width;
        std::vector< float > panel_width_percentage;
        std::vector< float > panel_height_percentages;
        int panel_primary_id_x;
        int panel_primary_id_y;
        int panel_primary_id;
        bool dock_updated_this_frame;
        int dock_padding_vertical;
        int dock_padding_horizontal;
        float dock_minimum_column_percentage;
        float dock_minimum_row_percentage;
        int current_column_count, current_row_count;
        float dock_width_minus_column_padding, dock_height_minus_column_padding;
        bool just_resized;
        bool being_resized;
        int hori_resize_start_x;
        int resize_pane_x1, resize_pane_x2;

        bool horizontal_resize;
        bool vertical_resize;

        //Reside related Data [ panel_height_percentagesSTART ]
        int column_being_resized_id;
        int row_being_resized_id;

        std::vector< widget_dock_panel * > panels;
        std::vector< std::string > panels_default_names;

        public:
        widget_dock();
        ~widget_dock();
        void add_to_panel(  std::string name, int panelId = 0,  bool open = false);
        void add_default_panel(  std::string name, int panelId = 0,  bool open = false );
        void clear_all_panels();
        void clear_defaults();
        bool column_is_open( int col_numb );
        bool container_in_view( std::string name );
        widget_dock_panel * contains_panel( std::string name );
        widget_dock_panel * find_panel( std::string name );

        int get_column(int panelId);

        int get_dock_left_width();
        int get_dock_right_width();
        bool get_hidden();

        widget_dock_panel * get_panel( int panel_id );
        int get_panel_count();
        int get_panel_x_count();
        int get_panel_y_count();

        int get_primary_panel();

        bool handle_resizing();
        void hide_dock();
        bool load_dock_setings( std::string filename );
        void process_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr );
        void remove_panel( std::string name );
        void remove_default_panel( std::string name );
        void render_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr );
        void reset_dock();
        bool resize_dock( int new_col, int new_row );

        bool save_dock_setings( std::string filename );
        bool set_primary_panel( int primaryXId, int primaryYId );

        void setup_dock( bool clear_panels_on_setup = true );
        void toggle_default_pane( std::string name );
        void toggle_panel(  std::string name, int panelId = 0,  bool open = true );
        void unhide_dock();
    };
}

#endif //PAWGUI_DOCK_SYSTEM_H


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=medium-dpi" />
        <link rel="stylesheet" type="text/css" href="css/ionic.css">

        <title>Hello World</title>

        <ion-header-bar class="bar bar-header bar-stable">

注册Activiti

        </ion-header-bar>

        <ion-content scroll="false">

                    用户名
                    <input type="text" autofocus ng-model="signup.username">

                    昵称
                    <input type="text" ng-model="signup.nickname">

                    密码
                    <input type="password" ng-model="signup.password">

                    确认密码
                    <input type="password" ng-model="signup.passwordConfirmed">

            已有账号?点此登陆
        </ion-content>

        <ion-footer-bar class="bar bar-footer bar-calm">

注册

        </ion-footer-bar>


text:
===============================
markovmc
===============================

.. image:: https://img.shields.io/travis/dgiambra/markovmc.svg
        :target: https://travis-ci.org/dgiambra/markovmc

.. image:: https://pyup.io/repos/github/dgiambra/markovmc/shield.svg
     :target: https://pyup.io/repos/github/dgiambra/markovmc/
     :alt: Updates

.. image:: https://coveralls.io/repos/github/dgiambra/markovmc/badge.svg?branch=master
    :target: https://coveralls.io/github/dgiambra/markovmc?branch=master

A Markov Chain Monte Carlo Algorithm

* Free software: MIT license
* Documentation: https://markovmc.readthedocs.io.

Features
--------
* A software package containing a main grapher function and multiple functions for meaningful statistical analysis

Grapher
-------
* Given a distribution of nodes, this algorithm calculates the most likely graphs to be produced from those nodes based on relative probability.
*   Uses the Metripolis-Hastings Algorithm
*   To use, call markovmc.grapher(x, N, r, T)
*    x: list of tuples representing nodes
*   N: int, number of iterations
*   r & T : int, adjustable Parameters
*   Outputs a list of graphs, each one is the more likely graph of its pair

topOnePercent
-------------
*   Given a list of elements, this function returns the 1% of elements most likely to occur
*   To use, call markovmc.topOnePercent(graphs)
*   graphs: list of graphs
*   Outputs a list of graphs, with the last graph being th most likely of the 1%

expectedDegree
--------------
*   given a list of graphs and a node, this computes the expected degree of the node
*   To use, call markovmc.expectedDegree(graphs, node):
*   graphs: list of graphs
*   node: node of interest
*   Output a value for expected degree

expectedNumberofEdges
---------------------
*   Given a list of graphs, computes the expected number of edges
*   To use, call markovmc.expectedNumberofEdges(graphs)
*   graphs: list of graphs
*   Outputs a value for expected number of edges

expectedShortestPathLength
--------------------------
*   Given a list of graphs and two nodes, it computes the average shortest path length between the two
*   To use, call markovmc.expectedShortestPathLength(graphs, nodeA, nodeB)
*   graphs: list of graphs
*   nodeA: first node
*   nodeB: second nodes
*   Outputs a value for expectedShortestPathLength

Credits
---------
* Dominic Giambra
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage


text:
package org.jfrog.artifactory.client.impl.jackson;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.jfrog.artifactory.client.model.repository.settings.RepositorySettings;
import org.jfrog.artifactory.client.model.repository.settings.impl.*;

/**
 * special serialization / deserialization handling for {@link RepositorySettings}
 *
 * @author Ivan Vasylivskyi (ivanvas@jfrog.com)
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "packageType", defaultImpl = GenericRepositorySettingsImpl.class)
@JsonSubTypes({
    @JsonSubTypes.Type(value = BowerRepositorySettingsImpl.class, name = "bower"),
    @JsonSubTypes.Type(value = CocoaPodsRepositorySettingsImpl.class, name = "cocoapods"),
    @JsonSubTypes.Type(value = DebianRepositorySettingsImpl.class, name = "debian"),
    @JsonSubTypes.Type(value = DockerRepositorySettingsImpl.class, name = "docker"),
    @JsonSubTypes.Type(value = GemsRepositorySettingsImpl.class, name = "gems"),
    @JsonSubTypes.Type(value = GenericRepositorySettingsImpl.class, name = "generic"),
    @JsonSubTypes.Type(value = GitLfsRepositorySettingsImpl.class, name = "gitlfs"),
    @JsonSubTypes.Type(value = GradleRepositorySettingsImpl.class, name = "gradle"),
    @JsonSubTypes.Type(value = IvyRepositorySettingsImpl.class, name = "ivy"),
    @JsonSubTypes.Type(value = MavenRepositorySettingsImpl.class, name = "maven"),
    @JsonSubTypes.Type(value = NpmRepositorySettingsImpl.class, name = "npm"),
    @JsonSubTypes.Type(value = NugetRepositorySettingsImpl.class, name = "nuget"),
    @JsonSubTypes.Type(value = OpkgRepositorySettingsImpl.class, name = "opkg"),
    @JsonSubTypes.Type(value = P2RepositorySettingsImpl.class, name = "p2"),
    @JsonSubTypes.Type(value = PypiRepositorySettingsImpl.class, name = "pypi"),
    @JsonSubTypes.Type(value = SbtRepositorySettingsImpl.class, name = "sbt"),
    @JsonSubTypes.Type(value = VagrantRepositorySettingsImpl.class, name = "vagrant"),
    @JsonSubTypes.Type(value = VcsRepositorySettingsImpl.class, name = "vcs"),
    @JsonSubTypes.Type(value = YumRepositorySettingsImpl.class, name = "yum"),
    @JsonSubTypes.Type(value = RpmRepositorySettingsImpl.class, name = "rpm"),
    @JsonSubTypes.Type(value = ComposerRepositorySettingsImpl.class, name = "composer"),
    @JsonSubTypes.Type(value = ConanRepositorySettingsImpl.class, name = "conan"),
    @JsonSubTypes.Type(value = ChefRepositorySettingsImpl.class, name = "chef"),
    @JsonSubTypes.Type(value = PuppetRepositorySettingsImpl.class, name = "puppet")
})
public interface RepositorySettingsMixIn {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="tabTitle">#3199ff</color>
    <color name="tabTitle_selected">#ffffff</color>
    <color name="tabBackground">#ffffff</color>
    <color name="tabBackground_selected">#3199ff</color>
</resources>


text:
/**
 * This file contains bad JavaScript.
 */

function ok() { return null; }

// Lots of space here, to exercise the code that shows only
// a snippet
// of the source
// around the failed code.

// Ok, back to where we put the syntax error.

function name with spaces() { this.will not.compile(); }

// Meanwhile, down here,
// we have code that is OK again.

function also_ok() {
    return "no worries, mate!";
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhotoSort
{
    public interface ILocationProvider
    {
        Location Resolve(GPSCoordinates coordinates);
    }
}


text:
author: rob-smith
title: 'Join The Revolt'
date: '2019-1-7 8:00:00'
cover: 'zucksafety.png'
category: users
---
#In 2019, Say "No" To The Robber Barons Of The Internet

A lot of people want to look back at last year, and set short term goals for this year.

We're going to do something different here.

Let's look forward to the end of 2019. Two ends, two possibilities.

There is one timeline where things are like 2018, but worse. More user's rights are violated, more restrictions on user freedom. The content you like is less available, more of your rights are stolen from you, and the people creating the very things you love are shut down or censored out of existence. Facebook, Google, and governments around the world stand to profit from keeping you on this path.

There is a better world, though. A world where on New Year's Eve 2019 your rights aren't being trampled in the name of next quarter's profits. A world where the people who use the internet are in charge of the internet. A world where you choose to not "Like" a page, or where you own your data outright. You download the LBRY app, and other dapps, and tell your friends about them.

The powers that be do not want this to happen.

So a question…

How do you want to celebrate New Year's Eve 2019?

It requires that you make a choice today, right now.

You choose you. You choose your rights. You choose your favorite content.

This is a revolt, and people have already started. They are shutting off their Facebook account, or they are parking their Twitter permanently. They are using ProtonMail instead of Gmail.  They are sharing content on Spee.ch.

[They are using LBRY.](/get)


text:
Clazz.load(["java.io.ObjectStreamException"],"java.io.NotSerializableException",null,function(){
c$=Clazz.declareType(java.io,"NotSerializableException",java.io.ObjectStreamException);
});


text:
use strict;
use warnings;
use English;
use XML::Feed;
use XML::Simple;
use Config;

# Define your gmake. Needed for Unixes which have both gmake and make installed.
# On Linux it could be named just 'make'.
my $MAKE = 'make';

# define your path here if run_test.pl is not in path
# e.g.
# my $run_test = '/Users/klink/dev/openxpki/tools/automated_test_reports/run_test.pl';
my $run_test;

# define an installation prefix (passed to perl Makefile.PL) if necessary
# e.g.
# my $PREFIX = 'PREFIX=~/usr/local';
my $PREFIX = '';

# add installation prefix to PERL5LIB
my $PREFIX_DIR = $PREFIX;
$PREFIX_DIR =~ s{ \A \s* PREFIX=}{}xms if ($PREFIX ne '');

if ($PREFIX_DIR ne '') {
    my $installstyle = $Config{installstyle};
    my $perlversion = $Config{version};
    my $archname = $Config{archname};
    $ENV{"PERL5LIB"} = $PREFIX_DIR . "/$installstyle/site_perl/$perlversion/:" .
                       $PREFIX_DIR . "/$installstyle/site_perl/$perlversion/$archname/:" .
                       $PREFIX_DIR . "/$installstyle/site_perl/$perlversion/mach/";
    print STDERR "PERL5LIB contains the following dirs: ".$ENV{"PERL5LIB"}."\n";
}

# define a deployment prefix (passed to ./configure in trunk/deployment)
# if necessary
# e.g.
# my $DEPLOYMENT_PREFIX = '--prefix ~/usr/local';
my $DEPLOYMENT_PREFIX = '';

# add deployment prefix to PATH
# define DEPLOYMENT_PREFIX variable (to be used in OpenXPKI/Tests.pm)
my $DEPLOYMENT_DIR = $DEPLOYMENT_PREFIX;
$DEPLOYMENT_DIR =~ s{ \A \s* --prefix \s* (\S+)}{$1}xms if ($DEPLOYMENT_PREFIX ne '');

if ($DEPLOYMENT_DIR ne '') {
    $ENV{"PATH"} = $DEPLOYMENT_DIR."/bin:" . $ENV{"PATH"};
    $ENV{"DEPLOYMENT_PREFIX"} = $DEPLOYMENT_DIR."/bin";
}

# define the format of the feed (see XML::Feed)
my $FEED_FORMAT = 'Atom';

# define the title and location of the feed
my $FEED_TITLE = "OpenXPKI tests at " . `hostname`;
my $FEED_LINK  = "http://build0.cynops.de/openxpki_tests/";

# define how many revisions you want to show at the HTML page and how
# many you want in the Atom feed
my $MAX_HTML_REVISIONS = 20;
my $MAX_ATOM_REVISIONS = 20;

if (! defined $run_test) {
    $run_test = `which run_test.pl`;
    chomp($run_test);
    if ($CHILD_ERROR) {
        die "Could not find run_test.pl, configure it in generate_report.pl or put it in your PATH";
    }
}

if (! -e 'perl-modules/core/trunk/t') {
    # only run from the correct directory
    die "Please start from main OpenXPKI trunk directory\n";
}
my $basedir = `pwd`;
chomp $basedir;

my $output_dir = $ARGV[0];
if (! defined $output_dir) {
    die "Usage: $0 <output directory>";
}

# Numbers added to the test names to provide correct sequence of installation:
# server, client, other clients. Needed for testing on machines with no
# pre-installed OpenXPKI.

my $tests = {
    '0_server'       => {
        DIRECTORY => $basedir . "/perl-modules/core/trunk",
        NAME      => 'Server',
    },
    '1_client'       => {
        DIRECTORY => $basedir . "/clients/perl/OpenXPKI-Client",
        NAME      => 'Client',
    },
    '2_client_mason' => {
        DIRECTORY => $basedir . "/clients/perl/OpenXPKI-Client-HTML-Mason",
        NAME      => 'Mason client',
    },
    '3_client_scep'  => {
        DIRECTORY => $basedir . "/clients/perl/OpenXPKI-Client-SCEP",
        NAME      => 'SCEP client',
    },
};

my $revision = sprintf("%04d", `vergen --format SVN_REVISION`);
if (! $revision) {
    die "Could not determine SVN revision";
}
if (! -x $run_test) {
    die "run_test.pl not found or not executable";
}

# will contain test name without a number
my $test;

INSTALL:
foreach my $testname (sort keys %{ $tests }) {
    $test = $testname;
    $test =~ s{\d_}{}xms;

    print STDERR "Compiling and installing for $test\n";
    chdir $tests->{$testname}->{DIRECTORY};
    if (system("perl Makefile.PL $PREFIX && $MAKE && $MAKE install") != 0) {
        die "Could not compile for $test test";
    }
}

# install new deployment tools before testing
chdir $basedir . '/deployment';
if (system("./configure $DEPLOYMENT_PREFIX && $MAKE && $MAKE install") != 0) {
    die "Could not install new deployment tools";
}

TEST:
foreach my $testname (sort keys %{ $tests }) {
    $test = $testname;
    $test =~ s{\d_}{}xms;

    print STDERR "Running test for $test (revision $revision)\n";
    chdir $tests->{$testname}->{DIRECTORY};

    # compile and run each test
    my $output_filename = $revision . '_output.txt';
    if (-e $output_filename) {
        # test has already been run, skip
        next TEST;
    }
    my $ENV = '';
    if ($test eq 'client_mason') {
        # we need to set this here, because any attempt to set it within
        # the test file itself fails for some reason ...
        $ENV = 'OPENXPKI_SOCKET_FILE=t/20_webserver/test_instance/var/openxpki/openxpki.socket';
    }
    system("$ENV $run_test $revision $test");
}

chdir $tests->{'0_server'}->{DIRECTORY};
my @tested_revisions = reverse glob('*_output.txt');
map { s/_output.txt// } @tested_revisions;

open INDEX, '>', $output_dir . '/index.html';
print INDEX << "XEOF";
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>OpenXPKI automated test report</title>

          Coverage report
          Good files
          Bad files
          Total files
          Skipped files
          Good tests
          Bad tests
          Total tests
          TODO tests
          passed TODO tests
          skipped tests
          CPU time used

XEOF

print STDERR "Generating report ... ";
REV_REPORT:
foreach my $rev (@tested_revisions[0..$MAX_HTML_REVISIONS-1]) {
    next REV_REPORT if (!$rev);
    print STDERR "r$rev ";
    chdir $basedir;
    open my $SVN, "svn log -qr $rev ..|";

    # my $line = <$SVN>;
    # my $svn_info = <$SVN>;
    ## execution of the two previous lines fails on FreeBSD
    ## with 'Broken pipe' error message

    my $svn_info;
    my $i = 0;
    while (my $line = <$SVN>) {
        chomp $line;
        $svn_info = $line if ($i == 1);
        $i++;
    }
    close $SVN;
    $svn_info =~ s{ (.*) \|\ \d+\ lines}{$1}xms;

    print INDEX "
Report for $svn_info
";
    foreach my $testname (sort keys %{ $tests }) {
        $test = $testname;
        $test =~ s{\d_}{}xms;

        chdir $tests->{$testname}->{DIRECTORY};
        my $files = $rev . '_coverage ' . $rev . '_output.txt ';
        system("mkdir $output_dir/$test 2>/dev/null");

        ## 'cp -r' does not work on FreeBSD
        system("cp -R $files $output_dir/$test");

        my $summary_filename = $rev . '_summary.html';
        my $opened = open my $SUMMARY, '<', $summary_filename;
        my $summary;
        if (! $opened) {
            $summary = '
' . $tests->{$testname}->{NAME} . ' summary unavailable
' . "\n";
        }
        else {
            $summary = <$SUMMARY>;
            $summary =~ s{Coverage\ report}{$tests->{$testname}->{NAME} coverage report}xms;
            close $SUMMARY;
        }
        print INDEX $summary;
    }
}
print STDERR "\n";
close INDEX;

print STDERR "Generating feed ... ";
my $feed = XML::Feed->new($FEED_FORMAT);
$feed->title($FEED_TITLE);
$feed->link($FEED_LINK);

REV_FEED:
foreach my $rev (@tested_revisions[0..$MAX_ATOM_REVISIONS-1]) {
    next REV_FEED if (!$rev);
    my $entry = XML::Feed::Entry->new($FEED_FORMAT);

    print STDERR "r$rev ";
    chdir $basedir;
    open my $SVN, "svn log -qr $rev ..|";

    # my $line = <$SVN>;
    # my $svn_info = <$SVN>;
    ## execution of the two previous lines fails on FreeBSD
    ## with 'Broken pipe' error message

    my $svn_info;
    my $i = 0;
    while (my $line = <$SVN>) {
        chomp $line;
        $svn_info = $line if ($i == 1);
        $i++;
    }
    close $SVN;

    my @svn_info = split(/ \| /, $svn_info);
    my $author = $svn_info[1];
    my $date   = $svn_info[2];
    my ($year, $month, $day, $hour, $minute, $second, $tz) =
        ($date =~ m{\A (\d{4}) \- (\d{2}) \- (\d{2}) [ ]
                       (\d{2}) : (\d{2}) : (\d{2}) [ ] ([\+\-]\d{4})}xms);
    my $dt = DateTime->new(
        year   => $year,
        month  => $month,
        day    => $day,
        hour   => $hour,
        minute => $minute,
        second => $second,
        time_zone => $tz,
    );

    my $svn_changes = do {
        local $INPUT_RECORD_SEPARATOR;
        open my $SVN, "svn log -vr $rev ..|";
        <$SVN>;
    };

    my $all_green = 1;
    my $all_summaries = '
';
    my @failed;
    foreach my $testname (sort keys %{ $tests }) {
        $test = $testname;
        $test =~ s{\d_}{}xms;

        chdir $tests->{$testname}->{DIRECTORY};
        my $summary_filename = $rev . '_summary.html';
        my $opened = open my $SUMMARY, '<', $summary_filename;
        if (! $opened) {
            $all_green = 0;
            push @failed, "$test n/a";
        }
        else {
            my $summary = <$SUMMARY>;
            $summary =~ s{Coverage\ report}{$tests->{$testname}->{NAME} coverage report}xms;
            my $xs = XML::Simple->new();
            my $summary_ref = $xs->XMLin($summary);
            if ($summary_ref->{'td'}->[6] ne '0 (0.00%)') {
                $all_green = 0;
                # push failed total tests
                push @failed, "$test: " . $summary_ref->{'td'}->[6];
            }
            $all_summaries .= $summary;
            close $SUMMARY;
        }
    }
    $all_summaries .= '
';
    if ($all_green) {
        $entry->title("$rev: All green");
    }
    else {
        $entry->title("$rev: Failed: " . join q{, }, @failed);
    }
    $entry->author($author);
    my $body = "
Report for $rev
" . $all_summaries;
    $body   .= "
Changes

" . $svn_changes . "
";
    $entry->content(XML::Feed::Content->new({body => $body }));
    $entry->modified($dt);
    $entry->link($FEED_LINK);

    $feed->add_entry($entry);
}
$feed->modified(DateTime->now);
open FEED, '>', "$output_dir/" . lc($FEED_FORMAT);
print FEED $feed->as_xml();
close(FEED);
print STDERR "\n";


text:
Choose a city

{{voucherData.listing.name}}

  {{voucherData.listing.public_address}}

{{voucherData.listing.neighborhood}}

{{voucherData.listing.public_address}}

{{voucherData.listing.reviews_count}}

{{voucherData.listing.star_rating}}

{{voucherData.listing.beds}}

{{voucherData.listing.bathrooms}}


text:
.PHONY: run clean requirements install pylint jslint lint deploy

run:
	# requires APP_SETTINGS=config.[ProductionConfig|StagingConfig|DevelopmentConfig|TestingConfig]
	# and DATABASE_URL="xxx"
	python manage.py runserver

clean:
	find . -type f -name '*.py[cod]' -delete
	find . -type f -name '*.*~' -delete

requirements:
	pip install -r requirements.txt

install: clean requirements env

pylint:
	-flake8 .

jslint:
	-jshint -c .jshintrc --exclude-path .jshintignore .

lint: clean pylint jslint

deploy: lint
	git push heroku master


text:
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var util = require('util');
var glob = require('glob');
var _ = require('lodash');
var extend = _.assign;

// Helpers
var betterTypeErrors = function(expected, obj) {
  var type = typeof obj;
  throw new TypeError('Expected ' + expected + ' but got ' +  type);
};

// Perform a shallow copy of an object ignoring specified properties
var copyExcept = function(obj, except) {
  var result = {};

  if (!_.isArray(except)) {
    betterTypeErrors('an array', obj);
  }

  if (!_.isObject(obj)) {
    betterTypeErrors('an object', obj);
  }

  for (var prop in obj) {
    if (except.indexOf(prop) >= 0 && obj.hasOwnProperty(prop)) {
      continue ;
    }
    result[prop] = obj[prop];
  }

  return result;
};

// Generator initialization
var Generator = module.exports = function() {
  yeoman.Base.apply(this, arguments);
};

util.inherits(Generator, yeoman.Base);

Generator.prototype.welcome = function() {
  if (this.options['skip-welcome-message']) {
    return ;
  }

  var title = 'Welcome!';
  var text = [
    'You\'re using the fantastic generator for scaffolding an',
    'application with AngularJS, SASS, Gulp, and Browserify!'
  ].join(' ');

  this.log(yosay([chalk.red(title), chalk.yellow(text)].join('\n')));
};

Generator.prototype.askForGeneratorName = function() {
  var done = this.async();
  var prompts = [{
    name: 'appname',
    message: 'What\'s the name of your app?',
    default: 'app'
  }];

  this.prompt(prompts, function(props) {
    this.appname = props.appname;
    done();
  }.bind(this));
};

Generator.prototype.copyAll = function() {
  var files = glob.sync('**', { dot: true, nodir: true, cwd: this.sourceRoot() });
  var exclude = ['package.json', '.gitignore', '.npmignore'];
  var diff = _.difference(files, exclude);

  diff.forEach(function(value) {
    this.fs.copy(this.templatePath(value), this.destinationPath(value));
  }.bind(this));
};

Generator.prototype.gitignore = function() {
  if (this.fs.exists(this.templatePath('.gitignore'))) {
    this.copy('.gitignore', '.gitignore');
    return ;
  }

  if (this.fs.exists(this.templatePath('.npmignore'))) {
    this.copy('.npmignore', '.gitignore');
  }
};

Generator.prototype.packageJSON = function() {
  var templateRoot = this.sourceRoot();
  var pkg = this.fs.readJSON(templateRoot + '/package.json');
  var exclude = [
    'author',
    'repository',
    'private',
    'engines'
  ];
  var newValues = {
    name: this.appname,
    version: '1.0.0'
  };
  var copy = extend(copyExcept(pkg, exclude), newValues);
  this.fs.writeJSON(this.destinationPath('package.json'), copy);
};

Generator.prototype.npm = function() {
  this.npmInstall();
};


text:
package de.javax.util.eventbinding.source;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Indicates that the object of the annotated field is a provider of event
 * sources.

 * The value defines an identifier for the provider which is used as a prefix
 * for the identifiers of the event sources from the provider. A period
 * character is used as a separator for the identifiers of the provider and its
 * sources. Example: SomeEventSourceProvider.SomeEventSource

 * The identifiers have to follow the naming rules of java identifiers.
 *
 * @author Frank Hardy
 *
 * @see EventSource
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface EventSourceProvider {

	/**
	 * @return the identifier of the event source provider which serves as a
	 *         prefix for the identifiers of the provided event sources.
	 */
	String value() default "";
}


text:
if [ $# -ne 4 ]; then
    echo "usage: $0 <number of threads> <reference indexed with bwa index> <path to picard.jar> <novoalign index>"
    exit 65
fi

if [ ! -e $3 ]; then
    echo "cannot find SamToFastq.jar"
    exit 65
fi

if [ ! -e $4 ]; then
    echo "cannot find novoalign index"
    exit 65
fi

if [ ! -e $2 ]; then
    echo "can't find reference .fasta: $2, please supply a bwa-indexed .fasta"
    exit 65
fi

if [ ! -e $2.bwt ]; then
    echo "can't find $2.bwt: is $2 indexed with bwa?"
    exit 65
fi

python3 -O ../bin/addindel.py -v ../test_data/test_indels.txt -f ../test_data/testregion_novo_realign.bam -r $2 -o ../test_data/testregion_novo_mut.bam -p $1 --picardjar $3 --aligner novoalign --alignopts novoref:$4
if [ $? -ne 0 ]; then
    echo "python3 -O ../bin/addindel.py failed."
    exit 65
else
    samtools sort -T ../test_data/testregion_novo_mut.sorted.bam -o ../test_data/testregion_novo_mut.sorted.bam ../test_data/testregion_novo_mut.bam
    mv ../test_data/testregion_novo_mut.sorted.bam ../test_data/testregion_novo_mut.bam
    samtools index ../test_data/testregion_novo_mut.bam
    samtools mpileup -ugf $2 ../test_data/testregion_novo_mut.bam | bcftools call -vm
fi


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.share;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

import androidx.appcompat.content.res.AppCompatResources;

import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ActivityTabProvider;
import org.chromium.chrome.browser.printing.TabPrinter;
import org.chromium.chrome.browser.send_tab_to_self.SendTabToSelfShareActivity;
import org.chromium.chrome.browser.share.qrcode.QrCodeCoordinator;
import org.chromium.chrome.browser.share.screenshot.ScreenshotCoordinator;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController.SheetState;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetObserver;
import org.chromium.chrome.browser.widget.bottomsheet.EmptyBottomSheetObserver;
import org.chromium.content_public.browser.NavigationEntry;
import org.chromium.printing.PrintManagerDelegateImpl;
import org.chromium.printing.PrintingController;
import org.chromium.printing.PrintingControllerImpl;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.widget.Toast;

/**
 * Provides {@code PropertyModel}s of Chrome-provided sharing options.
 */
class ChromeProvidedSharingOptionsProvider {
    private final Activity mActivity;
    private final ActivityTabProvider mActivityTabProvider;
    private final BottomSheetController mBottomSheetController;
    private final ShareSheetBottomSheetContent mBottomSheetContent;
    private final long mShareStartTime;
    private ScreenshotCoordinator mScreenshotCoordinator;

    /**
     * Constructs a new {@link ChromeProvidedSharingOptionsProvider}.
     *
     * @param activity              The current {@link Activity}.
     * @param activityTabProvider   The {@link ActivityTabProvider} for the current visible tab.
     * @param bottomSheetController The {@link BottomSheetController} for the current activity.
     * @param bottomSheetContent    The {@link ShareSheetBottomSheetContent} for the current
     *                              activity.
     * @param shareStartTime        The start time of the current share.
     */
    ChromeProvidedSharingOptionsProvider(Activity activity, ActivityTabProvider activityTabProvider,
            BottomSheetController bottomSheetController,
            ShareSheetBottomSheetContent bottomSheetContent, long shareStartTime) {
        mActivity = activity;
        mActivityTabProvider = activityTabProvider;
        mBottomSheetController = bottomSheetController;
        mBottomSheetContent = bottomSheetContent;
        mShareStartTime = shareStartTime;
    }

    /**
     * Used to initiate the screenshot flow once the bottom sheet is fully hidden. Removes itself
     * from {@link BottomSheetController} afterwards.
     */
    private final BottomSheetObserver mSheetObserver = new EmptyBottomSheetObserver() {
        @Override
        public void onSheetStateChanged(int newState) {
            if (newState == SheetState.HIDDEN) {
                assert mScreenshotCoordinator != null;
                mScreenshotCoordinator.captureScreenshot();
                // Clean up the observer since the coordinator is discarded when sheet is hidden.
                mBottomSheetController.removeObserver(mSheetObserver);
            }
        }
    };

    PropertyModel createScreenshotPropertyModel() {
        return ShareSheetPropertyModelBuilder.createPropertyModel(
                AppCompatResources.getDrawable(mActivity, R.drawable.screenshot),
                mActivity.getResources().getString(R.string.sharing_screenshot),
                (shareParams)
                        -> {
                    RecordUserAction.record("SharingHubAndroid.ScreenshotSelected");
                    RecordHistogram.recordMediumTimesHistogram(
                            "Sharing.SharingHubAndroid.TimeToShare",
                            System.currentTimeMillis() - mShareStartTime);
                    mScreenshotCoordinator =
                            new ScreenshotCoordinator(mActivity, mActivityTabProvider.get());
                    // Capture a screenshot once the bottom sheet is fully hidden. The observer
                    // will then remove itself.
                    mBottomSheetController.addObserver(mSheetObserver);
                    mBottomSheetController.hideContent(mBottomSheetContent, true);
                },
                /*isFirstParty=*/true);
    }

    PropertyModel createCopyLinkPropertyModel() {
        return ShareSheetPropertyModelBuilder.createPropertyModel(
                AppCompatResources.getDrawable(mActivity, R.drawable.ic_content_copy_black),
                mActivity.getResources().getString(R.string.sharing_copy_url), (shareParams) -> {
                    RecordUserAction.record("SharingHubAndroid.CopyURLSelected");
                    RecordHistogram.recordMediumTimesHistogram(
                            "Sharing.SharingHubAndroid.TimeToShare",
                            System.currentTimeMillis() - mShareStartTime);
                    mBottomSheetController.hideContent(mBottomSheetContent, true);
                    Tab tab = mActivityTabProvider.get();
                    NavigationEntry entry =
                            tab.getWebContents().getNavigationController().getVisibleEntry();
                    ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(
                            Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText(entry.getTitle(), entry.getUrl());
                    clipboard.setPrimaryClip(clip);
                    Toast toast =
                            Toast.makeText(mActivity, R.string.link_copied, Toast.LENGTH_SHORT);
                    toast.show();
                }, /*isFirstParty=*/true);
    }

    PropertyModel createSendTabToSelfPropertyModel() {
        return ShareSheetPropertyModelBuilder.createPropertyModel(
                AppCompatResources.getDrawable(mActivity, R.drawable.send_tab),
                mActivity.getResources().getString(R.string.send_tab_to_self_share_activity_title),
                (shareParams)
                        -> {
                    RecordUserAction.record("SharingHubAndroid.SendTabToSelfSelected");
                    RecordHistogram.recordMediumTimesHistogram(
                            "Sharing.SharingHubAndroid.TimeToShare",
                            System.currentTimeMillis() - mShareStartTime);
                    mBottomSheetController.hideContent(mBottomSheetContent, true);
                    SendTabToSelfShareActivity.actionHandler(mActivity,
                            mActivityTabProvider.get()
                                    .getWebContents()
                                    .getNavigationController()
                                    .getVisibleEntry(),
                            mBottomSheetController, mActivityTabProvider.get().getWebContents());
                },
                /*isFirstParty=*/true);
    }

    PropertyModel createQrCodePropertyModel() {
        return ShareSheetPropertyModelBuilder.createPropertyModel(
                AppCompatResources.getDrawable(mActivity, R.drawable.qr_code),
                mActivity.getResources().getString(R.string.qr_code_share_icon_label),
                (currentActivity)
                        -> {
                    RecordUserAction.record("SharingHubAndroid.QRCodeSelected");
                    RecordHistogram.recordMediumTimesHistogram(
                            "Sharing.SharingHubAndroid.TimeToShare",
                            System.currentTimeMillis() - mShareStartTime);
                    mBottomSheetController.hideContent(mBottomSheetContent, true);
                    QrCodeCoordinator qrCodeCoordinator = new QrCodeCoordinator(mActivity);
                    qrCodeCoordinator.show();
                },
                /*isFirstParty=*/true);
    }

    PropertyModel createPrintingPropertyModel() {
        return ShareSheetPropertyModelBuilder.createPropertyModel(
                AppCompatResources.getDrawable(mActivity, R.drawable.sharing_print),
                mActivity.getResources().getString(R.string.print_share_activity_title),
                (currentActivity)
                        -> {
                    RecordUserAction.record("SharingHubAndroid.PrintSelected");
                    RecordHistogram.recordMediumTimesHistogram(
                            "Sharing.SharingHubAndroid.TimeToShare",
                            System.currentTimeMillis() - mShareStartTime);
                    mBottomSheetController.hideContent(mBottomSheetContent, true);
                    PrintingController printingController = PrintingControllerImpl.getInstance();
                    if (printingController != null && !printingController.isBusy()) {
                        printingController.startPrint(new TabPrinter(mActivityTabProvider.get()),
                                new PrintManagerDelegateImpl(mActivity));
                    }
                },
                /*isFirstParty=*/true);
    }
}


text:
#ifndef GLSPAWNPOINTS_HPP
#define GLSPAWNPOINTS_HPP

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif
#include <glm/gtc/matrix_transform.hpp>
#include "globject.hpp"
#include "../map/pmsstructs.hpp"

/**
 * \brief Handles the drawing of spawn points.
 */
class GLSpawnPoints : GLObject
{
    public:
        void Render(glm::mat4 transform);
        using GLObject::SetupShaderProgram;
        void SetupShaderProgram();
        void SetupTextures();
        void SetupVAO(wxVector<PMSSpawnPoint> spawnPoints);

    private:
        GLuint m_texture;
        int m_spawnPointsCount;
};

#endif


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Twitter.Response
{
    [DataContract]
    public class URL
    {
        [DataMember(Name = "url")]
        private string UrlString
        {
            get { return Url.ToString(); }
            set { Url = new Uri(value); }
        }

        public Uri Url { get; private set; }

        [DataMember(Name = "expanded_url")]
        private string ExpandedUrlString
        {
            get { return ExpandedUrl.ToString(); }
            set { ExpandedUrl = new Uri(value); }
        }

        public Uri ExpandedUrl { get; private set; }

        [DataMember(Name = "display_url")]
        public string DisplayUrl { get; private set; }

        [DataMember(Name = "indices")]
        public List<long> Indices { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
}


text:
require 'spec_helper'

describe 'adding an event' do
  let(:event) do
    AASM::Core::Event.new(:close_order, {:success => :success_callback}) do
      before :before_callback
      after :after_callback
      transitions :to => :closed, :from => [:open, :received]
    end
  end

  it 'should set the name' do
    expect(event.name).to eq(:close_order)
  end

  it 'should set the success callback' do
    expect(event.options[:success]).to eq(:success_callback)
  end

  it 'should set the after callback' do
    expect(event.options[:after]).to eq([:after_callback])
  end

  it 'should set the before callback' do
    expect(event.options[:before]).to eq([:before_callback])
  end

  it 'should create transitions' do
    transitions = event.transitions
    expect(transitions[0].from).to eq(:open)
    expect(transitions[0].to).to eq(:closed)
    expect(transitions[1].from).to eq(:received)
    expect(transitions[1].to).to eq(:closed)
  end
end

describe 'transition inspection' do
  let(:event) do
    AASM::Core::Event.new(:run) do
      transitions :to => :running, :from => :sleeping
    end
  end

  it 'should support inspecting transitions from other states' do
    expect(event.transitions_from_state(:sleeping).map(&:to)).to eq([:running])
    expect(event.transitions_from_state?(:sleeping)).to be_truthy

    expect(event.transitions_from_state(:cleaning).map(&:to)).to eq([])
    expect(event.transitions_from_state?(:cleaning)).to be_falsey
  end

  it 'should support inspecting transitions to other states' do
    expect(event.transitions_to_state(:running).map(&:from)).to eq([:sleeping])
    expect(event.transitions_to_state?(:running)).to be_truthy

    expect(event.transitions_to_state(:cleaning).map(&:to)).to eq([])
    expect(event.transitions_to_state?(:cleaning)).to be_falsey
  end
end

describe 'transition inspection without from' do
  let(:event) do
    AASM::Core::Event.new(:run) do
      transitions :to => :running
    end
  end

  it 'should support inspecting transitions from other states' do
    expect(event.transitions_from_state(:sleeping).map(&:to)).to eq([:running])
    expect(event.transitions_from_state?(:sleeping)).to be_truthy

    expect(event.transitions_from_state(:cleaning).map(&:to)).to eq([:running])
    expect(event.transitions_from_state?(:cleaning)).to be_truthy
  end

end

describe 'firing an event' do
  it 'should return nil if the transitions are empty' do
    obj = double('object', :aasm => double('aasm', :current_state => 'open'))

    event = AASM::Core::Event.new(:event)
    expect(event.fire(obj)).to be_nil
  end

  it 'should return the state of the first matching transition it finds' do
    event = AASM::Core::Event.new(:event) do
      transitions :to => :closed, :from => [:open, :received]
    end

    obj = double('object', :aasm => double('aasm', :current_state => :open))

    expect(event.fire(obj)).to eq(:closed)
  end

  it 'should call the guard with the params passed in' do
    event = AASM::Core::Event.new(:event) do
      transitions :to => :closed, :from => [:open, :received], :guard => :guard_fn
    end

    obj = double('object', :aasm => double('aasm', :current_state => :open))
    expect(obj).to receive(:guard_fn).with('arg1', 'arg2').and_return(true)

    expect(event.fire(obj, {}, nil, 'arg1', 'arg2')).to eq(:closed)
  end

end

describe 'should fire callbacks' do
  describe 'success' do
    it "if it's a symbol" do
      ThisNameBetterNotBeInUse.instance_eval {
        aasm do
          event :with_symbol, :success => :symbol_success_callback do
            transitions :to => :symbol, :from => [:initial]
          end
        end
      }

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:symbol_success_callback)
      model.with_symbol!
    end

    it "if it's a string" do
      ThisNameBetterNotBeInUse.instance_eval {
        aasm do
          event :with_string, :success => 'string_success_callback' do
            transitions :to => :string, :from => [:initial]
          end
        end
      }

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:string_success_callback)
      model.with_string!
    end

    it "if passed an array of strings and/or symbols" do
      ThisNameBetterNotBeInUse.instance_eval {
        aasm do
          event :with_array, :success => [:success_callback1, 'success_callback2'] do
            transitions :to => :array, :from => [:initial]
          end
        end
      }

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:success_callback1)
      expect(model).to receive(:success_callback2)
      model.with_array!
    end

    it "if passed an array of strings and/or symbols and/or procs" do
      ThisNameBetterNotBeInUse.instance_eval {
        aasm do
          event :with_array_including_procs, :success => [:success_callback1, 'success_callback2', lambda { proc_success_callback }] do
            transitions :to => :array, :from => [:initial]
          end
        end
      }

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:success_callback1)
      expect(model).to receive(:success_callback2)
      expect(model).to receive(:proc_success_callback)
      model.with_array_including_procs!
    end

    it "if it's a proc" do
      ThisNameBetterNotBeInUse.instance_eval {
        aasm do
          event :with_proc, :success => lambda { proc_success_callback } do
            transitions :to => :proc, :from => [:initial]
          end
        end
      }

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:proc_success_callback)
      model.with_proc!
    end
  end

  describe 'after' do
    it "if they set different ways" do
      ThisNameBetterNotBeInUse.instance_eval do
        aasm do
          event :with_afters, :after => :do_one_thing_after do
            after do
              do_another_thing_after_too
            end
            after do
              do_third_thing_at_last
            end
            transitions :to => :proc, :from => [:initial]
          end
        end
      end

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:do_one_thing_after).once.ordered
      expect(model).to receive(:do_another_thing_after_too).once.ordered
      expect(model).to receive(:do_third_thing_at_last).once.ordered
      model.with_afters!
    end
  end

  describe 'before' do
    it "if it's a proc" do
      ThisNameBetterNotBeInUse.instance_eval do
        aasm do
          event :before_as_proc do
            before do
              do_something_before
            end
            transitions :to => :proc, :from => [:initial]
          end
        end
      end

      model = ThisNameBetterNotBeInUse.new
      expect(model).to receive(:do_something_before).once
      model.before_as_proc!
    end
  end

  it 'in right order' do
    ThisNameBetterNotBeInUse.instance_eval do
      aasm do
        event :in_right_order, :after => :do_something_after do
          before do
            do_something_before
          end
          transitions :to => :proc, :from => [:initial]
        end
      end
    end

    model = ThisNameBetterNotBeInUse.new
    expect(model).to receive(:do_something_before).once.ordered
    expect(model).to receive(:do_something_after).once.ordered
    model.in_right_order!
  end
end

describe 'current event' do
  let(:pe) {ParametrisedEvent.new}

  it 'if no event has been triggered' do
    expect(pe.aasm.current_event).to be_nil
  end

  it 'if a event has been triggered' do
    pe.wakeup
    expect(pe.aasm.current_event).to eql :wakeup
  end

  it 'if no event has been triggered' do
    pe.wakeup!
    expect(pe.aasm.current_event).to eql :wakeup!
  end
end

describe 'parametrised events' do
  let(:pe) {ParametrisedEvent.new}

  it 'should transition to specified next state (sleeping to showering)' do
    pe.wakeup!(:showering)
    expect(pe.aasm.current_state).to eq(:showering)
  end

  it 'should transition to specified next state (sleeping to working)' do
    pe.wakeup!(:working)
    expect(pe.aasm.current_state).to eq(:working)
  end

  it 'should transition to default (first or showering) state' do
    pe.wakeup!
    expect(pe.aasm.current_state).to eq(:showering)
  end

  it 'should transition to default state when :after transition invoked' do
    pe.dress!(nil, 'purple', 'dressy')
    expect(pe.aasm.current_state).to eq(:working)
  end

  it 'should call :after transition method with args' do
    pe.wakeup!(:showering)
    expect(pe).to receive(:wear_clothes).with('blue', 'jeans')
    pe.dress!(:working, 'blue', 'jeans')
  end

  it 'should call :after transition proc' do
    pe.wakeup!(:showering)
    expect(pe).to receive(:wear_clothes).with('purple', 'slacks')
    pe.dress!(:dating, 'purple', 'slacks')
  end

  it 'should call :after transition with an array of methods' do
    pe.wakeup!(:showering)
    expect(pe).to receive(:condition_hair)
    expect(pe).to receive(:fix_hair)
    pe.dress!(:prettying_up)
  end
end

describe 'event firing without persistence' do
  it 'should attempt to persist if aasm_write_state is defined' do
    foo = Foo.new
    def foo.aasm_write_state; end
    expect(foo).to be_open

    expect(foo).to receive(:aasm_write_state_without_persistence)
    foo.close
  end
end


text:
namespace g2o
{

class G2O_TYPES_SLAM3D_ADDONS_API EdgePlane : public BaseBinaryEdge<4, Vector4D, VertexPlane, VertexPlane>
{
public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    EdgePlane();

    void computeError()
    {
        const VertexPlane* v1 = static_cast<const VertexPlane*>(_vertices[0]);
        const VertexPlane* v2 = static_cast<const VertexPlane*>(_vertices[1]);
        _error = (v2->estimate().toVector() - v1->estimate().toVector() ) - _measurement;
    }
    virtual bool read(std::istream& is);
    virtual bool write(std::ostream& os) const;

    virtual void setMeasurement(const Vector4D& m){
        _measurement = m;
    }

    virtual bool setMeasurementData(const double* d){
        Eigen::Map<const Vector4D> m(d);
        _measurement=m;
        return true;
    }

    virtual bool getMeasurementData(double* d) const {
        Eigen::Map<Vector4D> m(d);
        m=_measurement;
        return true;
    }

    virtual int measurementDimension() const {return 4;}

    virtual bool setMeasurementFromState() {

        const VertexPlane* v1 = static_cast<const VertexPlane*>(_vertices[0]);
        const VertexPlane* v2 = static_cast<const VertexPlane*>(_vertices[1]);
        _measurement = (v2->estimate().toVector())-v1->estimate().toVector();

        return true;
    }

    virtual double initialEstimatePossible(const OptimizableGraph::VertexSet& , OptimizableGraph::Vertex* ) { return 0.;}
#if 0
#ifndef NUMERIC_JACOBIAN_THREE_D_TYPES
    virtual void linearizeOplus();
#endif
#endif
};

} // end namespace

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> Admin </title>

     <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet'

type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700" rel='stylesheet' type='text/css'>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}}
    {{--<link rel="stylesheet" href="{{URL::asset('assets/css/home.css')}}">--}}

                      GET READY

Home

Places

Bus

Bus Type

Routes

All Routes

Company

All Companies

                        Edit and Delete Places

                            Place

                            @foreach($allPlaces as $allPlace)

                                    {{$allPlace->place_name}}

                                        <form action="/place/{{ $allPlace->id }}" method="POST">
                                            {{ csrf_field() }}
                                            {{ method_field('DELETE') }}

                                            <button type="submit" id="delete-place-{{ $allPlace->id }}" class="btn btn-danger">
                                                Delete
                                            </button>
                                        </form>

                            @endforeach

Add New Place

                @yield('content')

        {{--  --}}


text:
package com.appdynamics.monitors.VMWare.metrics;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

/**
 * @author Satish Muddam
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class MetricConverter {
    @XmlAttribute(name = "str")
    private String label;
    @XmlAttribute(name = "value")
    private String value;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}