text:
package org.apereo.cas.authentication;

import org.apereo.cas.authentication.principal.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * This is {@link AuthenticationTransaction}.
 *
 * @author Misagh Moayyed
 * @since 4.2.0
 */
public class AuthenticationTransaction implements Serializable {

    private static final long serialVersionUID = 6213904009424725484L;

    private Collection<Credential> credentials;
    private Service service;

    /**
     * Instantiates a new Default authentication transaction.
     *
     * @param service     the service
     * @param credentials the credentials
     */
    protected AuthenticationTransaction(final Service service, final Collection<Credential> credentials) {
        this.credentials = credentials;
        this.service = service;
    }

    public Collection<Credential> getCredentials() {
        return this.credentials;
    }

    /**
     * Wrap credentials into an authentication transaction, as a factory method,
     * and return the final result.
     *
     * @param service     the service
     * @param credentials the credentials
     * @return the authentication transaction
     */
    public static AuthenticationTransaction wrap(final Service service, final Credential... credentials) {
        return new AuthenticationTransaction(service, sanitizeCredentials(credentials));
    }

    /**
     * Wrap credentials into an authentication transaction, as a factory method,
     * and return the final result.
     *
     * @param credentials the credentials
     * @return the authentication transaction
     */
    public static AuthenticationTransaction wrap(final Credential... credentials) {
        return wrap(null, credentials);
    }

    public Service getService() {
        return this.service;
    }

    private static Set<Credential> sanitizeCredentials(final Credential[] credentials) {
        if (credentials != null && credentials.length > 0) {
            return Arrays.stream(credentials)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());
        }
        return Collections.emptySet();
    }
}


text:
var today;

var Kalendae = function (targetElement, options) {
	if (typeof document.addEventListener !== 'function' && !util.isIE8()) return;

	//if the first argument isn't an element and isn't a string, assume that it is the options object
	var is_element = false;
	try {
		is_element = targetElement instanceof Element;
	}
	catch (err) {
		is_element = !!targetElement && is_element.nodeType === 1;
	}
	if (!(is_element || typeof(targetElement) === 'string')) options = targetElement;

	var self = this,
		classes = self.classes,
		opts = self.settings = util.merge(self.defaults, {attachTo:targetElement}, options || {}),
		$container = self.container = util.make('div', {'class':classes.container}),
		calendars = self.calendars = [],
		startDay = moment().day(opts.weekStart),
		vsd,
		columnHeaders = [],
		$cal,
		$title,
		$caption,
		$header,
		$days, dayNodes = [],
		$span,
		i = 0,
		j = opts.months;

	if (util.isIE8()) util.addClassName($container, 'ie8');

	//generate the column headers (Su, Mo, Tu, etc)
	i = 7;
	while (i--) {
		columnHeaders.push( startDay.format('ddd').substr(0,opts.columnHeaderLength) );
		startDay.add('days',1);
	}

	//setup publish/subscribe and apply any subscriptions passed in settings
	MinPubSub(self);
	if (typeof opts.subscribe === 'object') {
		for (i in opts.subscribe) if (opts.subscribe.hasOwnProperty(i)) {
			self.subscribe(i, opts.subscribe[i]);
		}
	}

	//process default selected dates
	self._sel = [];
	if (!!opts.selected) self.setSelected(opts.selected, false);

	//set the view month
	if (!!opts.viewStartDate) {
		vsd = moment(opts.viewStartDate, opts.format);
	} else if (self._sel.length > 0) {
		vsd = moment(self._sel[0]);
	} else {
		vsd = moment();
	}
	self.viewStartDate = vsd.date(1);

	var viewDelta = ({
		'past'			: opts.months-1,
		'today-past'	: opts.months-1,
		'any'			: opts.months>2?Math.floor(opts.months/2):0,
		'today-future'	: 0,
		'future'		: 0
	})[this.settings.direction];

	if (viewDelta && moment().month()==moment(self.viewStartDate).month()){
		self.viewStartDate = moment(self.viewStartDate).subtract({M:viewDelta}).date(1);
	}

	if (typeof opts.blackout === 'function') {
		self.blackout = opts.blackout;
	} else if (!!opts.blackout) {
		var bdates = parseDates(opts.blackout, opts.parseSplitDelimiter);
		self.blackout = function (input) {
			input = moment(input).yearDay();
			if (input < 1 || !self._sel || self._sel.length < 1) return false;
			var i = bdates.length;
			while (i--) if (bdates[i].yearDay() === input) return true;
			return false;
		}
	} else {
		self.blackout = function () {return false;}
	}

	self.direction = self.directions[opts.direction] ? self.directions[opts.direction] : self.directions['any'];

	//for the total months setting, generate N calendar views and add them to the container
	j = Math.max(opts.months,1);
	while (j--) {
		$cal = util.make('div', {'class':classes.calendar}, $container);

		$cal.setAttribute('data-cal-index', j);
		if (opts.months > 1) {
			if (j == Math.max(opts.months-1,1)) util.addClassName($cal, classes.monthFirst);
			else if (j === 0) util.addClassName($cal, classes.monthLast);
			else util.addClassName($cal, classes.monthMiddle);
		}

		//title bar
		$title = util.make('div', {'class':classes.title}, $cal);
		if(!opts.useYearNav){
			util.addClassName($title, classes.disableYearNav);
		}
		util.make('a', {'class':classes.previousYear}, $title);	//previous button
		util.make('a', {'class':classes.previousMonth}, $title);	//previous button
		util.make('a', {'class':classes.nextYear}, $title);		//next button
		util.make('a', {'class':classes.nextMonth}, $title);		//next button
		$caption = util.make('span', {'class':classes.caption}, $title);	//title caption

		//column headers
		$header = util.make('div', {'class':classes.header}, $cal);
		i = 0;
		do {
			$span = util.make('span', {}, $header);
			$span.innerHTML = columnHeaders[i];
		} while (++i < 7)

		//individual day cells
		$days = util.make('div', {'class':classes.days}, $cal);
		i = 0;
		dayNodes = [];
		while (i++ < 42) {
			dayNodes.push(util.make('span', {}, $days));
		}

		//store each calendar view for easy redrawing
		calendars.push({
			caption:$caption,
			days:dayNodes
		});

		if (j) util.make('div', {'class':classes.monthSeparator}, $container);
	}

	self.draw();

	util.addEvent($container, 'mousedown', function (event, target) {
		var clickedDate;
		if (util.hasClassName(target, classes.nextMonth)) {
		//NEXT MONTH BUTTON
			if (!self.disableNext && self.publish('view-changed', self, ['next-month']) !== false) {
				self.viewStartDate.add('months',1);
				self.draw();
			}
			return false;

		} else if (util.hasClassName(target, classes.previousMonth)) {
		//PREVIOUS MONTH BUTTON
			if (!self.disablePreviousMonth && self.publish('view-changed', self, ['previous-month']) !== false) {
				self.viewStartDate.subtract('months',1);
				self.draw();
			}
			return false;

		} else if (util.hasClassName(target, classes.nextYear)) {
		//NEXT MONTH BUTTON
			if (!self.disableNext && self.publish('view-changed', self, ['next-year']) !== false) {
				self.viewStartDate.add('years',1);
				self.draw();
			}
			return false;

		} else if (util.hasClassName(target, classes.previousYear)) {
		//PREVIOUS MONTH BUTTON
			if (!self.disablePreviousMonth && self.publish('view-changed', self, ['previous-year']) !== false) {
				self.viewStartDate.subtract('years',1);
				self.draw();
			}
			return false;

		} else if (util.hasClassName(target.parentNode, classes.days) && util.hasClassName(target, classes.dayActive) && (clickedDate = target.getAttribute('data-date'))) {
		//DAY CLICK
			clickedDate = moment(clickedDate, opts.dayAttributeFormat).hours(12);
			if (self.publish('date-clicked', self, [clickedDate]) !== false) {

				switch (opts.mode) {
					case 'multiple':
						if (!self.addSelected(clickedDate)) self.removeSelected(clickedDate);
						break;
					case 'range':
						self.addSelected(clickedDate);
						break;
					case 'single':
						/* falls through */
					default:
						self.addSelected(clickedDate);
						break;
				}

			}
			return false;

		}
		return false;
	});

	if (!!(opts.attachTo = util.$(opts.attachTo))) {
		opts.attachTo.appendChild($container);
	}

};

Kalendae.prototype = {
	defaults : {
		attachTo:				null,			/* the element to attach the root container to. can be string or DOMElement */
		months:					1,				/* total number of months to display side by side */
		weekStart:				0,				/* day to use for the start of the week. 0 is Sunday */
		direction:				'any',			/* past, today-past, any, today-future, future */
		directionScrolling:		true,			/* if a direction other than any is defined, prevent scrolling out of range */
		viewStartDate:			null,			/* date in the month to display.  When multiple months, this is the left most */
		blackout:				null,			/* array of dates, or function to be passed a date */
		selected:				null,			/* dates already selected.  can be string, date, or array of strings or dates. */
		mode:					'single',		/* single, multiple, range */
		dayOutOfMonthClickable: false,
		format:					null,			/* string used for parsing dates. */
		subscribe:				null,			/* object containing events to subscribe to */

		columnHeaderLength:		2,				/* number of characters to show in the column headers */
		titleFormat:			'MMMM, YYYY',	/* format mask for month titles. See momentjs.com for rules */
		dayNumberFormat:		'D',			/* format mask for individual days */
		dayAttributeFormat:		'YYYY-MM-DD',	/* format mask for the data-date attribute set on every span */
		parseSplitDelimiter:	/,\s*|\s+-\s+/,	/* regex to use for splitting multiple dates from a passed string */
		rangeDelimiter:			' - ',			/* string to use between dates when outputting in range mode */
		multipleDelimiter:		', ',			/* string to use between dates when outputting in multiple mode */
		useYearNav: 			true,

		dateClassMap:			{}
	},
	classes : {
		container		:'kalendae',
		calendar		:'k-calendar',
		monthFirst		:'k-first-month',
		monthMiddle		:'k-middle-month',
		monthLast		:'k-last-month',
		title			:'k-title',
		previousMonth	:'k-btn-previous-month',
		nextMonth		:'k-btn-next-month',
		previousYear	:'k-btn-previous-year',
		nextYear		:'k-btn-next-year',
		caption			:'k-caption',
		header			:'k-header',
		days			:'k-days',
		dayOutOfMonth	:'k-out-of-month',
		dayInMonth: 'k-in-month',
		dayActive		:'k-active',
		daySelected		:'k-selected',
		dayInRange		:'k-range',
		dayToday		:'k-today',
		monthSeparator	:'k-separator',
		disablePreviousMonth	:'k-disable-previous-month-btn',
		disableNextMonth		:'k-disable-next-month-btn',
		disablePreviousYear		:'k-disable-previous-year-btn',
		disableNextYear			:'k-disable-next-year-btn',
		disableYearNav 			:'k-disable-year-nav'
	},

	disablePreviousMonth: false,
	disableNextMonth: false,
	disablePreviousYear: false,
	disableNextYear: false,

	directions: {
		'past'			:function (date) {return moment(date).yearDay() >= today.yearDay();},
		'today-past'	:function (date) {return moment(date).yearDay() > today.yearDay();},
		'any'			:function (date) {return false;},
		'today-future'	:function (date) {return moment(date).yearDay() < today.yearDay();},
		'future'		:function (date) {return moment(date).yearDay() <= today.yearDay();}
	},

	getSelectedAsDates : function () {
		var out = [];
		var i=0, c = this._sel.length;
		for (;i<c;i++) {
			out.push(this._sel[i].toDate());
		}
		return out;
	},

	getSelectedAsText : function (format) {
		var out = [];
		var i=0, c = this._sel.length;
		for (;i<c;i++) {
			out.push(this._sel[i].format(format || this.settings.format || 'YYYY-MM-DD'))
		}
		return out;
	},

	getSelectedRaw : function () {
		var out = [];
		var i=0, c = this._sel.length;
		for (;i<c;i++) {
			out.push(moment(this._sel[i]))
		}
		return out;
	},

	getSelected : function (format) {
		var sel = this.getSelectedAsText(format);
		switch (this.settings.mode) {
			case 'range':
				sel.splice(2); //shouldn't be more than two, but lets just make sure.
				return sel.join(this.settings.rangeDelimiter);

			case 'multiple':
				return sel.join(this.settings.multipleDelimiter);

			case 'single':
				/* falls through */
			default:
				return sel[0];
		}
	},

	isSelected : function (input) {
		input = moment(input).yearDay();
		if (input < 1 || !this._sel || this._sel.length < 1) return false;

		switch (this.settings.mode) {
			case 'range':
				var a = this._sel[0] ? this._sel[0].yearDay() : 0,
					b = this._sel[1] ? this._sel[1].yearDay() : 0;

				if (a === input || b === input) return 1;
				if (!a || !b) return 0;

				if ((input > a && input < b) || (a<b && input < a && input > b))  return -1;
				return false;

			case 'multiple':
				var i = this._sel.length;
				while (i--) {
					if (this._sel[i].yearDay() === input) {
						return true;
					}
				}
				return false;

			case 'single':
				/* falls through */
			default:
				return (this._sel[0] && (this._sel[0].yearDay() === input));
		}

		return false;
	},

	setSelected : function (input, draw) {
		this._sel = parseDates(input, this.settings.parseSplitDelimiter, this.settings.format);
		this._sel.sort(function (a,b) {return a.yearDay() - b.yearDay();});

		if (draw !== false) this.draw();
	},

	addSelected : function (date, draw) {
		date = moment(date).hours(12);

		if(this.settings.dayOutOfMonthClickable && this.settings.mode !== 'range'){ this.makeSelectedDateVisible(date); }

		switch (this.settings.mode) {
			case 'multiple':
				if (!this.isSelected(date)) this._sel.push(date);
				else return false;
				break;
			case 'range':

				if (this._sel.length !== 1) this._sel = [date];
				else {
					if (date.yearDay() > this._sel[0].yearDay()) this._sel[1] = date;
					else this._sel = [date, this._sel[0]];
				}
				break;
			case 'single':
				/* falls through */
			default:
				this._sel = [date];
				break;
		}
		this._sel.sort(function (a,b) {return a.yearDay() - b.yearDay();});
		this.publish('change', this);
		if (draw !== false) this.draw();
		return true;
	},

	makeSelectedDateVisible: function (date) {
		outOfViewMonth = moment(date).date('1').diff(this.viewStartDate,'months')

		if(outOfViewMonth < 0){
			this.viewStartDate.subtract('months',1);
		}
		else if(outOfViewMonth > 0 && outOfViewMonth >= this.settings.months){
			this.viewStartDate.add('months',1);
		}
	},

	removeSelected : function (date, draw) {
		date = moment(date).yearDay();
		var i = this._sel.length;
		while (i--) {
			if (this._sel[i].yearDay() === date) {
				this._sel.splice(i,1);
				this.publish('change', this);
				if (draw !== false) this.draw();
				return true;
			}
		}
		return false;
	},

	draw : function draw() {
		// return;
		var month = moment(this.viewStartDate).hours(12), //force middle of the day to avoid any weird date shifts
			day,
			classes = this.classes,
			cal,
			$span,
			klass,
			i=0, c,
			j=0, k,
			s,
			dateString,
			opts = this.settings;

		c = this.calendars.length;

		do {
			day = moment(month).date(1);
			day.day( day.day() < this.settings.weekStart ? this.settings.weekStart-7 : this.settings.weekStart);
			//if the first day of the month is less than our week start, back up a week

			cal = this.calendars[i];
			cal.caption.innerHTML = month.format(this.settings.titleFormat);
			j = 0;
			do {
				$span = cal.days[j];

				klass = [];

				s = this.isSelected(day);

				if (s) klass.push(({'-1':classes.dayInRange,'1':classes.daySelected, 'true':classes.daySelected})[s]);

				if (day.month() != month.month()) klass.push(classes.dayOutOfMonth);
				else klass.push(classes.dayInMonth);

				if (!(this.blackout(day) || this.direction(day) || (day.month() != month.month() && opts.dayOutOfMonthClickable === false)) || s>0) klass.push(classes.dayActive);

				if (day.yearDay() === today.yearDay()) klass.push(classes.dayToday);

				dateString = day.format(this.settings.dayAttributeFormat);
				if (opts.dateClassMap[dateString]) klass.push(opts.dateClassMap[dateString]);

				$span.innerHTML = day.format(opts.dayNumberFormat);
				$span.className = klass.join(' ');
				$span.setAttribute('data-date', dateString);

				day.add('days',1);
			} while (++j < 42);
			month.add('months',1);
		} while (++i < c);

		if (opts.directionScrolling) {
			var diff = -(moment().diff(month, 'months'));
			if (opts.direction==='today-past' || opts.direction==='past') {

				if (diff < 0) {
					this.disableNextMonth = false;
					util.removeClassName(this.container, classes.disableNextMonth);
				} else {
					this.disableNextMonth = true;
					util.addClassName(this.container, classes.disableNextMonth);
				}

			} else if (opts.direction==='today-future' || opts.direction==='future') {

				if (diff >= opts.months) {
					this.disablePreviousMonth = false;
					util.removeClassName(this.container, classes.disablePreviousMonth);
				} else {
					this.disablePreviousMonth = true;
					util.addClassName(this.container, classes.disablePreviousMonth);
				}

			}

			if (opts.direction==='today-past' || opts.direction==='past') {
				if (month.add({y:1}).diff(moment(), 'months') <= 0) {
					this.disableNextYear = false;
					util.removeClassName(this.container, classes.disableNextYear);
				} else {
					this.disableNextYear = true;
					util.addClassName(this.container, classes.disableNextYear);
				}

			} else if (opts.direction==='today-future' || opts.direction==='future') {
				if ((month.subtract({y:1}).diff(moment(), 'months') - (opts.months-1)) >= 0) {
					this.disablePreviousYear = false;
					util.removeClassName(this.container, classes.disablePreviousYear);
				} else {
					this.disablePreviousYear = true;
					util.addClassName(this.container, classes.disablePreviousYear);
				}

			}

		}
	}
}

var parseDates = function (input, delimiter, format) {
	var output = [];

	if (typeof input === 'string') {
		input = input.split(delimiter);
	} else if (!util.isArray(input)) {
		input = [input];
	}

	var c = input.length;
	i = 0;
	do {
		if (input[i]) output.push( moment(input[i], format).hours(12) );
	} while (++i < c);

	return output;
}

window.Kalendae = Kalendae;

redpajama_set_name: RedPajamaGithub


text:
var torii, app;

import { configure } from 'torii/configuration';
import startApp from '../../helpers/start-app';
import lookup from '../../helpers/lookup';
import QUnit from 'qunit';

const { module, test } = QUnit;

var opened, mockPopup, providerConfig;

module('Google Bearer- Integration', {
  setup: function(){
    mockPopup = {
      open: function(){
        opened = true;
        return Ember.RSVP.resolve({ access_token: 'test' });
      }
    };
    app = startApp({loadInitializers: true});
    app.register('torii-service:mock-popup', mockPopup, {instantiate: false});
    app.inject('torii-provider', 'popup', 'torii-service:mock-popup');

    torii = lookup(app, "service:torii");
    providerConfig = { apiKey: 'dummy' };
    configure({
      providers: {
        'google-oauth2-bearer': providerConfig
      }
    });
  },
  teardown: function(){
    opened = false;
    Ember.run(app, 'destroy');
  }
});

test("Opens a popup to Google", function(assert){
  assert.expect(1);
  Ember.run(function(){
    torii.open('google-oauth2-bearer').finally(function(){
      assert.ok(opened, "Popup service is opened");
    });
  });
});

test("Opens a popup to Google with request_visible_actions", function(assert){
  assert.expect(1);
  configure({
    providers: {
      'google-oauth2-bearer': Ember.merge(providerConfig, {
        requestVisibleActions: "http://some-url.com"
      })
    }
  });
  mockPopup.open = function(url){
    assert.ok(
      url.indexOf("request_visible_actions=http%3A%2F%2Fsome-url.com") > -1,
      "request_visible_actions is present" );
    return Ember.RSVP.resolve({ access_token: 'test' });
  };
  Ember.run(function(){
    torii.open('google-oauth2-bearer');
  });
});


text:
<?php
namespace App\Modules\Kagi\Providers;

use App;
use Config;
use Lang;
use View;
use Illuminate\Support\ServiceProvider;

class KagiServiceProvider extends ServiceProvider
{
	/**
	 * Register the Kagi module service provider.
	 *
	 * @return void
	 */
	public function register()
	{

		App::register('App\Modules\Kagi\Providers\RouteServiceProvider');
		App::register('App\Modules\Kagi\Providers\KagiMenuProvider');

		$this->mergeConfigFrom(
			__DIR__.'/../Config/kagi.php', 'kagi'
		);
		$this->mergeConfigFrom(
			__DIR__.'/../Config/kagi_services.php', 'kagi_services'
		);

		$this->registerNamespaces();

// Broken .. not sure why yet ...
//		$this->registerConsoleCommands();

	}

	/**
	 * Register the Kagi module resource namespaces.
	 *
	 * @return void
	 */
	protected function registerNamespaces()
	{
//		Lang::addNamespace('kagi', __DIR__.'/../Resources/Lang/');
		View::addNamespace('kagi', __DIR__.'/../Resources/Views/');
	}

	/**
	 * Boot the service provider.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->publishes([
			__DIR__.'/../Config/kagi.php' => config_path('kagi.php'),
		]);
		$this->publishes([
			__DIR__.'/../Config/kagi_services.php' => config_path('kagi_services.php'),
		]);
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return string
	 */
	public function provides()
	{
//		return ['kagi'];
	}

	/**
	 * Register the package console commands.
	 *
	 * @return void
	 */
	protected function registerConsoleCommands()
	{
// 		$this->registerInstallCommand();
//
// 		$this->commands([
// 			'kagi.install'
// 		]);
	}

	/**
	 * Register the "module:seed" console command.
	 *
	 * @return Console\ModuleSeedCommand
	 */
	protected function registerInstallCommand()
	{
// 		$this->app->bindShared('kagi.install', function() {
// 			return new App\Modules\Kagi\Console\Commands\KagiCommand;
// 		});
	}

}


text:
package main

import (
	"flag"
	"github.com/yvasiyarov/gorelic"
	"github.com/yvasiyarov/newrelic_platform_go"
)

var newRelicLicense = flag.String("newreliclicense", "", "New Relic License")

type connectionsMetric int

func (metric *connectionsMetric) GetName() string {
	return "Sessions"
}

func (metric *connectionsMetric) GetUnits() string {
	return "Sessions"
}

func (metric *connectionsMetric) GetValue() (float64, error) {
	return float64(*metric), nil
}

func (metric *connectionsMetric) SessionCreated() {
	*metric = connectionsMetric(int(*metric) + 1)
}

func (metric *connectionsMetric) SessionClosed() {
	*metric = connectionsMetric(int(*metric) - 1)
}

func init() {
	if *newRelicLicense != "" {
		agent := gorelic.NewAgent()
		agent.Verbose = false
		agent.NewrelicLicense = *newRelicLicense
		agent.NewrelicName = "Avalon Web System"
		agent.Run()

		plugin := newrelic_platform_go.NewNewrelicPlugin("0.0.1", *newRelicLicense, 20)
		component := newrelic_platform_go.NewPluginComponent("Avalon Web App", "cc.hij.avalon.webapp")
		plugin.AddComponent(component)

		metric := new(connectionsMetric)
		component.AddMetrica(metric)
		go plugin.Run()

		trace = metric
	}
}


text:
using System;
using System.Collections.Generic;

namespace Tera.Analytics
{
    [Serializable]
    public class AnalysisResult
    {
        public IReadOnlyDictionary<ushort, string> PacketNamesByOpcode { get; set; }
        public IList<string> SystemMessageReadableIds { get; set; }
        public byte[] DataCenterKey { get; set; }
        public byte[] DataCenterIv { get; set; }
    }
}


text:
@extends('backend.layouts.admin_app')

@section('content')

            Department Type

       @include('adminlte-templates::common.errors')

                   {!! Form::model($departmentType, ['route' => ['admin.departmentTypes.update', $departmentType->id], 'method' => 'patch']) !!}

                        @include('backend.department_types.fields')

                   {!! Form::close() !!}

@endsection


text:
star-polygon
============
Generates a regular [star polygon](http://en.wikipedia.org/wiki/Star_polygon).

## Example

```javascript
console.log(require("star-polygon")(5, 2))

//Prints:
//
//  [[0,2], [2,4], [4,1], [1,3], [3,0]]
//
```

## Install

    npm install star-polygon

### `require("star-polygon")(n, k)`
Generates a star polygon.

* `n` is the number of vertices
* `k` is the step size between vertices

**Returns** A list of edges

## Credits
(c) 2013 Mikola Lysenko. MIT License


text:
import React, { Component } from 'react';
import { Row } from 'reactstrap';
import LazyLoad from "react-lazyload";
import Loading from "../images/Loading";
import Product from "./Product";
import { connect } from 'react-redux';
import { productsApi } from '../../actions/products';
import { isNull } from '../../util/util';

class ProductList extends Component {
  componentWillMount() {
    // get products
    this.props.productsApi();
  }

  renderProducts() {
    const { isFetching, products } = this.props.products;
    if (isFetching) {
      return <Loading />;
    }

    if (!isNull(products) && products.length) {
      return products.map(({ product }) => (
        <LazyLoad placeholder={<Loading />} key={product.id} height="50px">
          <Product product={product} size={this.props.itemSize}/>
        </LazyLoad>
      ));
    }
  }

  render() {
    return (
      <Row>
        {this.renderProducts()}
      </Row>
    );
  }
}

const mapSateToProps = state => ({
  products: state.products
});

export default connect(mapSateToProps, { productsApi })(ProductList);


text:
import {Options, GLOBAL_OPTIONS, DIRECTION} from './options';
import {Dragula} from './dragula';
import {moveBefore} from './move-before';
import {PLATFORM} from 'aurelia-pal';

export {Dragula, Options, DIRECTION, moveBefore};

export function configure(config, callback) {
  let defaults = new Options();
  config.container.registerInstance(GLOBAL_OPTIONS, defaults);

  if (callback !== undefined && typeof callback === 'function') {
    callback(defaults);
  }

  config.globalResources([PLATFORM.moduleName('./dragula-and-drop')]);
}


text:
namespace net {

class ChannelIDSigner;
class CryptoHandshakeMessage;
class ProofVerifier;
class ProofVerifyDetails;
class QuicRandom;
class QuicServerInfo;
class QuicServerInfoFactory;

// QuicCryptoClientConfig contains crypto-related configuration settings for a
// client. Note that this object isn't thread-safe. It's designed to be used on
// a single thread at a time.
class NET_EXPORT_PRIVATE QuicCryptoClientConfig : public QuicCryptoConfig {
 public:
  // A CachedState contains the information that the client needs in order to
  // perform a 0-RTT handshake with a server. This information can be reused
  // over several connections to the same server.
  class NET_EXPORT_PRIVATE CachedState {
   public:
    CachedState();
    explicit CachedState(scoped_ptr<QuicServerInfo> quic_server_info);
    ~CachedState();

    // IsComplete returns true if this object contains enough information to
    // perform a handshake with the server. |now| is used to judge whether any
    // cached server config has expired.
    bool IsComplete(QuicWallTime now) const;

    // IsEmpty returns true if |server_config_| is empty.
    bool IsEmpty() const;

    // GetServerConfig returns the parsed contents of |server_config|, or NULL
    // if |server_config| is empty. The return value is owned by this object
    // and is destroyed when this object is.
    const CryptoHandshakeMessage* GetServerConfig() const;

    // SetServerConfig checks that |server_config| parses correctly and stores
    // it in |server_config_|. |now| is used to judge whether |server_config|
    // has expired.
    QuicErrorCode SetServerConfig(base::StringPiece server_config,
                                  QuicWallTime now,
                                  std::string* error_details);

    // InvalidateServerConfig clears the cached server config (if any).
    void InvalidateServerConfig();

    // SetProof stores a certificate chain and signature.
    void SetProof(const std::vector<std::string>& certs,
                  base::StringPiece signature);

    // Clears the certificate chain and signature and invalidates the proof.
    void ClearProof();

    // SetProofValid records that the certificate chain and signature have been
    // validated and that it's safe to assume that the server is legitimate. It
    // persists the server config information to disk cache.
    // (Note: this does not check the chain or signature.)
    void SetProofValid();

    // If the server config or the proof has changed then it needs to be
    // revalidated. Helper function to keep server_config_valid_ and
    // generation_counter_ in sync.
    void SetProofInvalid();

    const std::string& server_config() const;
    const std::string& source_address_token() const;
    const std::vector<std::string>& certs() const;
    const std::string& signature() const;
    bool proof_valid() const;
    uint64 generation_counter() const;
    const ProofVerifyDetails* proof_verify_details() const;
    QuicServerInfo* quic_server_info() const;

    void set_source_address_token(base::StringPiece token);

    // SetProofVerifyDetails takes ownership of |details|.
    void SetProofVerifyDetails(ProofVerifyDetails* details);

    // Copy the |server_config_|, |source_address_token_|, |certs_| and
    // |server_config_sig_| from the |other|.  The remaining fields,
    // |generation_counter_|, |proof_verify_details_|, and |scfg_| remain
    // unchanged.
    void InitializeFrom(const CachedState& other);

    // Fill out the |server_config_|, |source_address_token_|, |certs_| and
    // |server_config_sig_| fields from |quic_server_info_|. |quic_server_info_|
    // reads this information from the disk cache. |now| is used to judge
    // whether server config from disk cache has expired. Returns true if it has
    // loaded the data from disk cache successfully.
    bool LoadQuicServerInfo(QuicWallTime now);

    // Save the server config information so that we can perform 0-RTT handshake
    // with a server.
    void SaveQuicServerInfo();

   private:
    std::string server_config_;         // A serialized handshake message.
    std::string source_address_token_;  // An opaque proof of IP ownership.
    std::vector<std::string> certs_;    // A list of certificates in leaf-first
                                        // order.
    std::string server_config_sig_;     // A signature of |server_config_|.
    bool server_config_valid_;          // True if |server_config_| is correctly
                                        // signed and |certs_| has been
                                        // validated.
    bool need_to_persist_;              // Persist to disk if True.
    // Generation counter associated with the |server_config_|, |certs_| and
    // |server_config_sig_| combination. It is incremented whenever we set
    // server_config_valid_ to false.
    uint64 generation_counter_;

    scoped_ptr<ProofVerifyDetails> proof_verify_details_;

    // scfg contains the cached, parsed value of |server_config|.
    mutable scoped_ptr<CryptoHandshakeMessage> scfg_;

    // |quic_server_info_| is used to fetch crypto config information from disk.
    scoped_ptr<QuicServerInfo> quic_server_info_;

    DISALLOW_COPY_AND_ASSIGN(CachedState);
  };

  QuicCryptoClientConfig();
  ~QuicCryptoClientConfig();

  // Sets the members to reasonable, default values.
  void SetDefaults();

  // Create returns a CachedState for the given hostname. It creates a
  // CachedState and caches it. If |quic_server_info_factory| is not NULL, then
  // it is used to create QuicServerInfo which is used to fetch crypto config
  // information from disk for the given hostname.
  CachedState* Create(const std::string& server_hostname,
                      QuicServerInfoFactory* quic_server_info_factory);

  // LookupOrCreate returns a CachedState for the given hostname. If no such
  // CachedState currently exists, it will be created and cached.
  // TODO(rtenneti): fix the server code and pass QuicServerInfoFactory as
  // argument.
  CachedState* LookupOrCreate(const std::string& server_hostname);

  // FillInchoateClientHello sets |out| to be a CHLO message that elicits a
  // source-address token or SCFG from a server. If |cached| is non-NULL, the
  // source-address token will be taken from it. |out_params| is used in order
  // to store the cached certs that were sent as hints to the server in
  // |out_params->cached_certs|. |preferred_version| is the version of the QUIC
  // protocol that this client chose to use initially. This allows the server to
  // detect downgrade attacks.
  void FillInchoateClientHello(const std::string& server_hostname,
                               const QuicVersion preferred_version,
                               const CachedState* cached,
                               QuicCryptoNegotiatedParameters* out_params,
                               CryptoHandshakeMessage* out) const;

  // FillClientHello sets |out| to be a CHLO message based on the configuration
  // of this object. This object must have cached enough information about
  // |server_hostname| in order to perform a handshake. This can be checked
  // with the |IsComplete| member of |CachedState|.
  //
  // |clock| and |rand| are used to generate the nonce and |out_params| is
  // filled with the results of the handshake that the server is expected to
  // accept. |preferred_version| is the version of the QUIC protocol that this
  // client chose to use initially. This allows the server to detect downgrade
  // attacks.
  QuicErrorCode FillClientHello(const std::string& server_hostname,
                                QuicGuid guid,
                                const QuicVersion preferred_version,
                                const CachedState* cached,
                                QuicWallTime now,
                                QuicRandom* rand,
                                QuicCryptoNegotiatedParameters* out_params,
                                CryptoHandshakeMessage* out,
                                std::string* error_details) const;

  // ProcessRejection processes a REJ message from a server and updates the
  // cached information about that server. After this, |IsComplete| may return
  // true for that server's CachedState. If the rejection message contains
  // state about a future handshake (i.e. an nonce value from the server), then
  // it will be saved in |out_params|. |now| is used to judge whether the
  // server config in the rejection message has expired.
  QuicErrorCode ProcessRejection(const CryptoHandshakeMessage& rej,
                                 QuicWallTime now,
                                 CachedState* cached,
                                 QuicCryptoNegotiatedParameters* out_params,
                                 std::string* error_details);

  // ProcessServerHello processes the message in |server_hello|, updates the
  // cached information about that server, writes the negotiated parameters to
  // |out_params| and returns QUIC_NO_ERROR. If |server_hello| is unacceptable
  // then it puts an error message in |error_details| and returns an error
  // code. |negotiated_versions| contains the list of version, if any, that were
  // present in a version negotiation packet previously recevied from the
  // server. The contents of this list will be compared against the list of
  // versions provided in the VER tag of the server hello.
  QuicErrorCode ProcessServerHello(const CryptoHandshakeMessage& server_hello,
                                   QuicGuid guid,
                                   const QuicVersionVector& negotiated_versions,
                                   CachedState* cached,
                                   QuicCryptoNegotiatedParameters* out_params,
                                   std::string* error_details);

  ProofVerifier* proof_verifier() const;

  // SetProofVerifier takes ownership of a |ProofVerifier| that clients are
  // free to use in order to verify certificate chains from servers. If a
  // ProofVerifier is set then the client will request a certificate chain from
  // the server.
  void SetProofVerifier(ProofVerifier* verifier);

  ChannelIDSigner* channel_id_signer() const;

  // SetChannelIDSigner sets a ChannelIDSigner that will be called when the
  // server supports channel IDs to sign a message proving possession of the
  // given ChannelID. This object takes ownership of |signer|.
  void SetChannelIDSigner(ChannelIDSigner* signer);

  // Initialize the CachedState from |canonical_crypto_config| for the
  // |canonical_server_hostname| as the initial CachedState for
  // |server_hostname|. We will copy config data only if
  // |canonical_crypto_config| has valid proof.
  void InitializeFrom(const std::string& server_hostname,
                      const std::string& canonical_server_hostname,
                      QuicCryptoClientConfig* canonical_crypto_config);

 private:
  // cached_states_ maps from the server hostname to the cached information
  // about that server.
  std::map<std::string, CachedState*> cached_states_;

  scoped_ptr<ProofVerifier> proof_verifier_;
  scoped_ptr<ChannelIDSigner> channel_id_signer_;

  DISALLOW_COPY_AND_ASSIGN(QuicCryptoClientConfig);
};

}  // namespace net

#endif  // NET_QUIC_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_


text:
<idea-plugin>
    <depends>com.intellij.completion.ml.ranking</depends>
    <depends optional="true" config-file="scala-ml-completion-property-files-support.xml">com.intellij.properties</depends>

    <extensions defaultExtensionNs="com.intellij.completion.ml">
        <ranking.features.policy language="Scala" implementationClass="org.jetbrains.plugins.scala.mlCompletion.ScalaCompletionFeaturesPolicy"/>
        <elementFeatures language="Scala" implementationClass="org.jetbrains.plugins.scala.lang.completion.ml.ScalaElementFeatureProvider"/>
        <contextFeatures language="Scala" implementationClass="org.jetbrains.plugins.scala.lang.completion.ml.ScalaContextFeatureProvider"/>
        <model implementation="org.jetbrains.plugins.scala.mlCompletion.ScalaMlRankingProvider"/>

        <ranking.policy language="sbt" implementationClass="org.jetbrains.plugins.sbt.completion.ml.SbtDependencyVersionInSbtAndScalaFilesCompletionMLPolicy"/>
        <ranking.policy language="Scala" implementationClass="org.jetbrains.plugins.sbt.completion.ml.SbtDependencyVersionInSbtAndScalaFilesCompletionMLPolicy"/>
    </extensions>
</idea-plugin>


text:
package org.springframework.boot.jdbc.init;

import java.nio.charset.Charset;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer;
import org.springframework.boot.sql.init.DatabaseInitializationSettings;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

/**
 * {@link InitializingBean} that performs {@link DataSource} initialization using schema
 * (DDL) and data (DML) scripts.
 *
 * @author Andy Wilkinson
 * @since 2.5.0
 */
public class DataSourceScriptDatabaseInitializer extends AbstractScriptDatabaseInitializer {

	private static final Log logger = LogFactory.getLog(DataSourceScriptDatabaseInitializer.class);

	private final DataSource dataSource;

	/**
	 * Creates a new {@link DataSourceScriptDatabaseInitializer} that will initialize the
	 * given {@code DataSource} using the given settings.
	 * @param dataSource data source to initialize
	 * @param settings the initialization settings
	 */
	public DataSourceScriptDatabaseInitializer(DataSource dataSource, DatabaseInitializationSettings settings) {
		super(settings);
		this.dataSource = dataSource;
	}

	/**
	 * Returns the {@code DataSource} that will be initialized.
	 * @return the initialization data source
	 */
	protected final DataSource getDataSource() {
		return this.dataSource;
	}

	@Override
	protected boolean isEmbeddedDatabase() {
		try {
			return EmbeddedDatabaseConnection.isEmbedded(this.dataSource);
		}
		catch (Exception ex) {
			logger.debug("Could not determine if datasource is embedded", ex);
			return false;
		}
	}

	@Override
	protected void runScripts(List<Resource> resources, boolean continueOnError, String separator, Charset encoding) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.setContinueOnError(continueOnError);
		populator.setSeparator(separator);
		if (encoding != null) {
			populator.setSqlScriptEncoding(encoding.name());
		}
		for (Resource resource : resources) {
			populator.addScript(resource);
		}
		customize(populator);
		DatabasePopulatorUtils.execute(populator, this.dataSource);
	}

	/**
	 * Customize the {@link ResourceDatabasePopulator}.
	 * @param populator the configured database populator
	 * @since 2.6.2
	 */
	protected void customize(ResourceDatabasePopulator populator) {

	}

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Modules model
 *
*
* Ananas
*
* A simple, fast, development framework for web applications and software licenses software
*
* @package		Ananas
* @author		Ananas Dev Team
// ------------------------------------------------------------------------
*/
class Module_m extends My_Model
{
	protected $_table = 'modules';

	/**
	 * Caches modules that exist
	 */
	private $_module_exists = array();

	/**
	 * Caches modules that are enabled
	 */
	private $_module_enabled = array();

	/**
	 * Caches modules that are installed
	 */
	private $_module_installed = array();

	/**
	 * Get
	 *
	 * Return an array containing module data
	 *
	 * @param	string	$slug		The name of the module to load
	 * @return	array
	 */
	public function get($slug = '')
	{
		// Have to return an associative array of null values for backwards compatibility.
		$null_array = array(
			'name' => null,
			'slug' => null,
			'version' => null,
			'description' => null,
			'skip_xss' => null,
			'is_frontend' => null,
			'is_backend' => null,
			'menu' => false,
			'enabled' => 1,
			'sections' => array(),
			'shortcuts' => array(),
			'is_core' => null,
			'is_current' => null,
			'current_version' => null,
			'updated_on' => null
		);

		if (is_array($slug) || empty($slug))
		{
			return $null_array;
		}

		$row = $this->db
			->where('slug', $slug)
			->get($this->_table)
			->row();

		// store these
		$this->_module_exists[$slug] = count($row) > 0;
		$this->_module_enabled[$slug] = $row->enabled;
		$this->_module_installed[$slug] = $row->installed;

		if ($row)
		{
			// Let's get REAL
			if ( ! $module = $this->_spawn_class($slug, $row->is_core))
			{
				return false;
			}

			list($class, $location) = $module;
			$info = $class->info();

			// Return false if the module is disabled
			if ($row->enabled == 0)
			{
				return false;
			}

			$name = ! isset($info['name'][CURRENT_LANGUAGE]) ? $info['name']['english'] : $info['name'][CURRENT_LANGUAGE];
			$description = ! isset($info['description'][CURRENT_LANGUAGE]) ? $info['description']['english'] : $info['description'][CURRENT_LANGUAGE];

			return array(
				'name' => $name,
				'slug' => $row->slug,
				'version' => $row->version,
				'description' => $description,
				'skip_xss' => $row->skip_xss,
				'is_frontend' => $row->is_frontend,
				'is_backend' => $row->is_backend,
				'menu' => $row->menu,
				'enabled' => $row->enabled,
				'sections' => ! empty($info['sections']) ? $info['sections'] : array(),
				'shortcuts' => ! empty($info['shortcuts']) ? $info['shortcuts'] : array(),
				'is_core' => $row->is_core,
				'is_current' => version_compare($row->version, $this->version($row->slug),  '>='),
				'current_version' => $this->version($row->slug),
				'path' => $location,
				'updated_on' => $row->updated_on
			);
		}

		return $null_array;
	}

	/**
	 * Get Modules
	 *
	 * Return an array of objects containing module related data
	 *
	 * @param   array   $params             The array containing the modules to load
	 * @param   bool    $return_disabled    Whether to return disabled modules
	 * @return  array
	 */
	public function get_all($params = array(), $return_disabled = false)
	{
		$modules = array();

		// We have some parameters for the list of modules we want
		if ($params)
		{
			foreach ($params as $field => $value)
			{
				if (in_array($field, array('is_frontend', 'is_backend', 'menu', 'is_core')))
				{
					$this->db->where($field, $value);
				}
			}
		}

		// Skip the disabled modules
		if ($return_disabled === false)
		{
			$this->db->where('enabled', 1);
		}

		$result = $this->db->get($this->_table)->result();

		foreach ($result as $row)
		{
			// Check if module can spawn itself
			if ( ! $module = $this->_spawn_class($row->slug, $row->is_core))
			{
				continue;
			}

			list($class, $location) = $module;
			$info = $class->info();

			$name = ! isset($info['name'][CURRENT_LANGUAGE]) ? $info['name']['english'] : $info['name'][CURRENT_LANGUAGE];
			$description = ! isset($info['description'][CURRENT_LANGUAGE]) ? $info['description']['english'] : $info['description'][CURRENT_LANGUAGE];

			$module = array(
				'name'            => $name,
				'module'          => $class,
				'slug'            => $row->slug,
				'version'         => $row->version,
				'description'     => $description,
				'skip_xss'        => $row->skip_xss,
				'is_frontend'     => $row->is_frontend,
				'is_backend'      => $row->is_backend,
				'menu'            => $row->menu,
				'enabled'         => $row->enabled,
				'sections'        => ! empty($info['sections']) ? $info['sections'] : array(),
				'shortcuts'       => ! empty($info['shortcuts']) ? $info['shortcuts'] : array(),
				'installed'       => $row->installed,
				'is_core'         => $row->is_core,
				'is_current'      => version_compare($row->version, $this->version($row->slug),  '>='),
				'current_version' => $this->version($row->slug),
				'path'            => $location,
				'updated_on'      => $row->updated_on
			);

			// store these
			$this->_module_exists[$row->slug] = true;
			$this->_module_enabled[$row->slug] = $row->enabled;
			$this->_module_installed[$row->slug] = $row->installed;

			if ( ! empty($params['is_backend']))
			{
				// This user has no permissions for this module
				if ( $this->current_user->group !== 'admin' and empty($this->permissions[$row->slug]) )
				{
					continue;
				}
			}

			$modules[$module['name']] = $module;
		}

		ksort($modules);

		return array_values($modules);
	}

	/**
	 * Add
	 *
	 * Adds a module to the database
	 *
	 * @access	public
	 * @param	array	$module		Information about the module
	 * @return	object
	 */
	public function add($module)
	{
		return $this->db->replace($this->_table, array(
			'name'        => serialize($module['name']),
			'slug'        => $module['slug'],
			'version'     => $module['version'],
			'description' => serialize($module['description']),
			'skip_xss'    => ! empty($module['skip_xss']),
			'is_frontend' => ! empty($module['frontend']),
			'is_backend'  => ! empty($module['backend']),
			'menu'        => ! empty($module['menu']) ? $module['menu'] : false,
			'enabled'     => ! empty($module['enabled']),
			'installed'   => ! empty($module['installed']),
			'is_core'     => ! empty($module['is_core']),
			'updated_on'  => now()
		));
	}

	/**
	 * Update
	 *
	 * Updates a module in the database
	 *
	 * @access  public
	 * @param   array   $slug   Module slug to update
	 * @param   array   $module Information about the module
	 * @return  object
	 */
	public function update($slug, $module, $skip_validation = false)
	{
		$module['updated_on'] = time();

		return $this->db->where('slug', $slug)->update($this->_table, $module);
	}

	/**
	 * Delete
	 *
	 * Delete a module from the database
	 *
	 * @param	array	$slug	The module slug
	 * @access	public
	 * @return	object
	 */
	public function delete($slug)
	{
		return $this->db->delete($this->_table, array('slug' => $slug));
	}

	/**
	 * Exists
	 *
	 * Checks if a module exists
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function exists($slug)
	{
		if ( ! $slug)
		{
			return false;
		}

		// We already know about this module
		if (isset($this->_module_exists[$slug]))
		{
			return $this->_module_exists[$slug];
		}

		return $this->_module_exists[$slug] = $this->db
			->where('slug', $slug)
			->count_all_results($this->_table) > 0;
	}

	/**
	 * Enabled
	 *
	 * Checks if a module is enabled
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function enabled($slug)
	{
		if ( ! $slug)
		{
			return false;
		}

		// We already know about this module
		if (isset($this->_module_enabled[$slug]))
		{
			return $this->_module_enabled[$slug];
		}

		return $this->_module_enabled[$slug] = $this->db
			->where('slug', $slug)
			->where('enabled', 1)
			->count_all_results($this->_table) > 0;
	}

	/**
	 * Installed
	 *
	 * Checks if a module is installed
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function installed($slug)
	{
		if ( ! $slug)
		{
			return false;
		}

		// We already know about this module
		if (isset($this->_module_installed[$slug]))
		{
			return $this->_module_installed[$slug];
		}

		return $this->_module_installed[$slug] = $this->db
			->where('slug', $slug)
			->where('installed', 1)
			->count_all_results($this->_table) > 0;
	}

	/**
	 * Enable
	 *
	 * Enables a module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function enable($slug)
	{
		if ($this->exists($slug))
		{

			$this->db->where('slug', $slug)->update($this->_table, array('enabled' => 1));
			$this->_module_enabled[$slug] = true;
			$this->module_widget_task($slug, 'enable');

			return true;
		}
		return false;
	}

	/**
	 * Disable
	 *
	 * Disables a module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function disable($slug)
	{
		if ($this->exists($slug))
		{
			$this->db->where('slug', $slug)->update($this->_table, array('enabled' => 0));
			$this->_module_enabled[$slug] = false;
			$this->module_widget_task($slug, 'disable');

			return true;
		}
		return false;
	}

	/**
	 * Module_widget_task
	 *
	 * Enable | disable widgets inside module folder
	 *
	 * @param	string	$slug	The module slug
	 * @param	string	$task	enable | disable
	 * @return	NULL
	 */
	private function module_widget_task($slug, $task)
	{
		foreach(array(APPPATH) as $path)
		{
			foreach((array) glob($path.'modules/'.$slug.'/widgets/*', GLOB_ONLYDIR) as $widget_path)
			{
				$widget = basename($widget_path);

				switch($task)
				{
					case 'enable':
						$this->db
							->where('slug', $widget)
							->where('enabled', 0)
							->update('widgets', array('enabled' => 1));
					break;
					case 'disable':
						$this->db
							->where('slug', $widget)
							->where('enabled', 1)
							->update('widgets', array('enabled' => 0));
					break;
				}
			}
		}
	}

	/**
	 * Install
	 *
	 * Installs a module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function install($slug, $is_core = false, $insert = false)
	{
		if ( ! $module = $this->_spawn_class($slug, $is_core))
		{
			return false;
		}

		list($class) = $module;

		// They've just finished uploading it so we need to make a record
		if ($insert)
		{
			// Get some info for the db
			$input = $class->info();

			// Now lets set some details ourselves
			$input['slug']			= $slug;
			$input['version']		= $class->version;
			$input['enabled']		= $is_core; // enable if core
			$input['installed']	= $is_core; // install if core
			$input['is_core']		= $is_core; // is core if core

			// It's a valid module let's make a record of it
			$this->add($input);
		}

		// set the site_ref and upload_path for third-party devs
		$class->site_ref 	= SITE_REF;
		$class->upload_path	= 'uploads/'.SITE_REF.'/';

		// Run the install method to get it into the database
		if ($class->install())
		{

			// TURN ME ON BABY!
			$this->db->where('slug', $slug)->update($this->_table, array('enabled' => 1, 'installed' => 1));

			// enable it
			$this->_module_exists[$slug] = true;
			$this->_module_enabled[$slug] = true;
			$this->_module_installed[$slug] = true;

			return true;
		}

		return false;
	}

	/**
	 * Uninstall
	 *
	 * Unnstalls a module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function uninstall($slug, $is_core = false)
	{
		if ( ! $module = $this->_spawn_class($slug, $is_core))
		{
			// the files are missing so let's clean the "modules" table
			return $this->delete($slug);
		}

		list($class) = $module;

		// set the site_ref and upload_path for third-party devs
		$class->site_ref 	= SITE_REF;
		$class->upload_path	= 'uploads/'.SITE_REF.'/';

		// Run the uninstall method to drop the module's tables
		if ( ! $class->uninstall())
		{
			return false;
		}

		if ($this->delete($slug))
		{
			// Get some info for the db
			$input = $class->info();

			// Now lets set some details ourselves
			$input['slug']      = $slug;
			$input['version']   = $class->version;
			$input['enabled']   = $is_core; // enable if core
			$input['installed'] = $is_core; // install if core
			$input['is_core']   = $is_core; // is core if core

			// We record it again here. If they really want to get rid of it they'll use Delete
			return $this->add($input);
		}
		return false;
	}

	/**
	 * Upgrade
	 *
	 * Upgrade a module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function upgrade($slug)
	{
		// Get info on the new module
		if ( ! ($module = $this->_spawn_class($slug, true) or $module = $this->_spawn_class($slug, false)))
		{
			return false;
		}

		// Get info on the old module
		if ( ! $old_module = $this->get($slug))
		{
			return false;
		}

		list($class) = $module;

		// Get the old module version number
		$old_version = $old_module['version'];

		// set the site_ref and upload_path for third-party devs
		$class->site_ref 	= SITE_REF;
		$class->upload_path	= 'uploads/'.SITE_REF.'/';

		// Run the update method to get it into the database
		if ($class->upgrade($old_version))
		{
			// Update version number
			$this->db->where('slug', $slug)->update($this->_table, array('version' => $class->version));

			return true;
		}

		// The upgrade failed
		return false;
	}

	public function import_unknown()
    {
    	$modules = array();

		$is_core = true;

		$known = $this->get_all(array(), true);
		$known_array = array();
		$known_mtime = array();

		// Loop through the known array and assign it to a single dimension because
		// in_array can not search a multi array.
		if (is_array($known) && count($known) > 0)
		{
			foreach ($known as $item)
			{
				array_unshift($known_array, $item['slug']);
				$known_mtime[$item['slug']] = $item;
			}
		}

		foreach (array(APPPATH) as $directory)
    	{
			// some servers return false instead of an empty array
			if ( ! $directory or ! ($temp_modules = glob($directory.'modules/*', GLOB_ONLYDIR)))
			{
				continue;
			}

			foreach ($temp_modules as $path)
			{
				$slug = basename($path);

				// Yeah yeah we know
				if (in_array($slug, $known_array))
				{
					$details_file = $directory.'modules/'.$slug.'/details'.EXT;

					if (file_exists($details_file) &&
						filemtime($details_file) > $known_mtime[$slug]['updated_on'] &&
						$module = $this->_spawn_class($slug, $is_core))
					{
						list($class) = $module;

						// Get some basic info
						$input = $class->info();

						$this->update($slug, array(
							'name'        => serialize($input['name']),
							'description' => serialize($input['description']),
							'is_frontend' => ! empty($input['frontend']),
							'is_backend'  => ! empty($input['backend']),
							'skip_xss'    => ! empty($input['skip_xss']),
							'menu'        => ! empty($input['menu']) ? $input['menu'] : false,
							'updated_on'  => now()
						));

						log_message('debug', sprintf('The information of the module "%s" has been updated', $slug));
					}

					continue;
				}

				// This doesn't have a valid details.php file! :o
				if ( ! $module = $this->_spawn_class($slug, $is_core))
				{
					continue;
				}

				list ($class) = $module;

				// Get some basic info
				$input = $class->info();

				// Now lets set some details ourselves
				$input['slug']      = $slug;
				$input['version']   = $class->version;
				$input['enabled']   = $is_core; // enable if core
				$input['installed'] = $is_core; // install if core
				$input['is_core']   = $is_core; // is core if core

				// Looks like it installed ok, add a record
				$this->add($input);
			}
			unset($temp_modules);

			// Going back around, 2nd time is addons
			$is_core = false;
		}

		return true;
	}

	/**
	 * Spawn Class
	 *
	 * Checks to see if a details.php exists and returns a class
	 *
	 * @param	string	$slug	The folder name of the module
	 * @return	array
	 */
	private function _spawn_class($slug, $is_core = false)
	{
		$path = $is_core ? APPPATH : APPPATH;

		// Before we can install anything we need to know some details about the module
		$details_file = $path.'modules/'.$slug.'/details'.EXT;

		// Check the details file exists
		if ( ! is_file($details_file))
		{
			if ( ! is_file($details_file))
			{
				// we return false to let them know that the module isn't here, keep looking
				return false;
			}
		}

		// Sweet, include the file
		include_once $details_file;

		// Now call the details class
		$class = 'Module_'.ucfirst(strtolower($slug));

		// Now we need to talk to it
		if ( ! class_exists($class))
		{
			throw new Exception("Module $slug has an incorrect details.php class. It should be called '$class'.");
		}

		return array(new $class, dirname($details_file));
	}

	/**
	 * Help
	 *
	 * Retrieves help string from details.php
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function help($slug)
	{
		foreach (array(0, 1) as $is_core)
    	{
			$languages = $this->config->item('supported_languages');
			$default = $languages[$this->config->item('default_language')]['folder'];

			//first try it as a core module
			if ($module = $this->_spawn_class($slug, $is_core))
			{
				list ($class, $location) = $module;

				// Check for a hep language file, if not show the default help text from the details.php file
				if (file_exists($location.'/language/'.$default.'/help_lang.php'))
				{
					$this->lang->load($slug.'/help');

					if (lang('help_body'))
					{
						return lang('help_body');
					}
				}
				else
				{
					return $class->help();
				}
			}
		}

		return false;
	}

	/**
	 * Roles
	 *
	 * Retrieves roles for a specific module
	 *
	 * @param	string	$slug	The module slug
	 * @return	bool
	 */
	public function roles($slug)
	{
		foreach (array(0, 1) as $is_core)
		{
			//first try it as a core module
			if ($module = $this->_spawn_class($slug, $is_core))
			{
				list($class) = $module;
				$info = $class->info();

				if ( ! empty($info['roles']))
				{
//					$this->lang->load($slug.'/permission');
					$this->lang->load('permissions');
					return $info['roles'];
				}
			}
		}

		return array();
	}

	/**
	 * Help
	 *
	 * Retrieves version number from details.php
	 *
	 * @param   string  $slug   The module slug
	 * @return  bool
	 */
	public function version($slug)
	{
		if ($module = $this->_spawn_class($slug, true) or $module = $this->_spawn_class($slug))
		{
			list($class) = $module;
			return $class->version;
		}

		return false;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">
  <com.mapswithme.maps.widget.ObservableScrollView
    android:id="@+id/pp__details"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?ppBackground"
    android:overScrollMode="never">

    <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:clipChildren="false">

      <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="?attr/dividerHorizontal"
        android:paddingLeft="@dimen/margin_base_plus"
        android:paddingRight="@dimen/margin_base_plus"/>

      <RelativeLayout
        android:id="@+id/rl__details_attrs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/margin_half"
        android:paddingLeft="@dimen/margin_base_plus"
        android:paddingRight="@dimen/margin_base_plus"
        android:paddingTop="@dimen/margin_half">

        <View
          android:id="@+id/anchor_center"
          android:layout_width="0px"
          android:layout_height="match_parent"
          android:layout_centerHorizontal="true"
          android:layout_marginLeft="@dimen/margin_base"
          android:layout_marginRight="@dimen/margin_base"/>

        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_toLeftOf="@id/anchor_center"
          android:layout_toStartOf="@id/anchor_center"
          android:orientation="vertical">
          <include layout="@layout/place_page_placename"/>

          <include layout="@layout/place_page_entrance"/>

          <include layout="@layout/place_page_phone"/>

          <include layout="@layout/place_page_website"/>

          <include layout="@layout/place_page_wiki"/>

          <include layout="@layout/place_page_editor"/>

          <include layout="@layout/place_page_add_business"/>
        </LinearLayout>

        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_toRightOf="@id/anchor_center"
          android:layout_toEndOf="@id/anchor_center"
          android:orientation="vertical">
          <include layout="@layout/place_page_email"/>

          <include layout="@layout/place_page_opening_hours"/>

          <include layout="@layout/place_page_latlon"/>

          <include layout="@layout/place_page_wifi"/>

          <include layout="@layout/place_page_operator"/>

          <include layout="@layout/place_page_cuisine"/>
        </LinearLayout>
      </RelativeLayout>

      <include
        layout="@layout/place_page_bookmark_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/rl__details_attrs"
        android:layout_marginLeft="@dimen/margin_base_plus"
        android:layout_marginRight="@dimen/margin_base_plus"/>
    </RelativeLayout>
  </com.mapswithme.maps.widget.ObservableScrollView>

  <include layout="@layout/shadow_top"/>

  <include layout="@layout/shadow_bottom"/>
</FrameLayout>


text:
"""
Model objects which are used in providing the Python API to JPER
"""

from octopus.lib import dataobj
from service.models.notifications import NotificationMetadata, UnroutedNotification
from copy import deepcopy

class IncomingNotification(NotificationMetadata):
    """
    Class to represent a notification delivered to the system via the API.

    It extends the basic NotificationMetadata and adds some contextual information about the
    notification and associated content and embargoes.
    """

    def __init__(self, raw=None):
        """
        Create a new instance of the IncomingNotification object, optionally around the
        raw python dictionary.

        You may obtain the raw dictionary from - for example - a POST to the web API.

        If supplied, the raw dictionary will be validated against the allowed structure of this
        object, and an exception will be raised if it does not validate
        """
        struct = {
            "fields" : {
                "event" : {"coerce" : "unicode"},
            },
            "objects" : [
                "provider", "content", "embargo"
            ],
            "lists" : {
                "links" : {"contains" : "object"}
            },
            "required" : [],

            "structs" : {
                "provider" : {
                    "fields" : {
                        "agent" : {"coerce" :"unicode"},
                        "ref" : {"coerce" :"unicode"}
                    },
                    "required" : []
                },
                "content" : {
                    "fields" : {
                        "packaging_format" : {"coerce" :"unicode"}
                    },
                    "required" : []
                },
                "embargo" : {
                    "fields" : {
                        "end" : {"coerce" : "utcdatetime"},
                        "start" : {"coerce" : "utcdatetime"},
                        "duration" : {"coerce" : "integer"}
                    },
                    "required" : []
                },
                "links" : {
                    "fields" : {
                        "type" : {"coerce" :"unicode"},
                        "format" : {"coerce" :"unicode"},
                        "url" : {"coerce" :"url"}
                    }
                }
            }
        }

        self._add_struct(struct)
        super(IncomingNotification, self).__init__(raw=raw)

    def make_unrouted(self):
        """
        Convert this object to a models.UnroutenNotification object, which is
        suitable for serialisation into the index
        """
        return UnroutedNotification(deepcopy(self.data))

class OutgoingNotification(NotificationMetadata):
    """
    Class to represent a notification being sent out of the system via the API.

    It extends the basic NotificationMetadata and adds some contextual information about the
    notification and associated content and embargoes.

    Note that while it has strong similarities to the IncomingNotification, in differs in several
    ways:

    1. It contains the created_date and (if available) the analysis_date
    2. It does not contain the provider information (as the person retrieving the notification may not be the original provider)
    3. Links may contain the "packaging" element
    """
    def __init__(self, raw=None):
        """
        Create a new instance of the OutgoingNotification object, optionally around the
        raw python dictionary.

        You may obtain the raw dictionary from - for example - the Unrouted or Routed notification in the index.

        If supplied, the raw dictionary will be validated against the allowed structure of this
        object, and an exception will be raised if it does not validate
        """
        struct = {
            "fields" : {
                "id" : {"coerce" : "unicode"},
                "created_date" : {"coerce" : "utcdatetime"},
                "analysis_date" : {"coerce" : "utcdatetime"},
                "event" : {"coerce" : "unicode"},
            },
            "objects" : [
                "content", "embargo"
            ],
            "lists" : {
                "links" : {"contains" : "object"}
            },
            "reqired" : [],

            "structs" : {
                "content" : {
                    "fields" : {
                        "packaging_format" : {"coerce" :"unicode"}
                    },
                    "required" : []
                },
                "embargo" : {
                    "fields" : {
                        "end" : {"coerce" : "utcdatetime"},
                        "start" : {"coerce" : "utcdatetime"},
                        "duration" : {"coerce" : "integer"}
                    }
                },
                "links" : {
                    "fields" : {
                        "type" : {"coerce" :"unicode"},
                        "format" : {"coerce" :"unicode"},
                        "url" : {"coerce" :"url"},
                        "packaging" : {"coerce" : "unicode"}
                    }
                }
            }
        }

        self._add_struct(struct)
        super(OutgoingNotification, self).__init__(raw=raw)

    @property
    def links(self):
        """
        Get a list of the links associated with the notification
        """
        return self._get_list("links")

class ProviderOutgoingNotification(OutgoingNotification):
    """
    Class to represent a notification being sent out of the system via the API to the original provider of that notification

    It extens on the basic OutgoingNotification (which can be consumed by anyone, not only the original provider), and adds the
    following information:

    ::

        {
            "provider" : {
                "id" : "<user account id of the provider>",
                "agent" : "<string defining the software/process which put the content here, provided by provider - is this useful?>",
                "ref" : "<provider's globally unique reference for this research object>",
                "route" : "<method by which notification was received: native api, sword, ftp>"
            },
        }
    """
    def __init__(self, raw=None):
        """
        Create a new instance of the ProviderOutgoingNotification object, optionally around the
        raw python dictionary.

        You may obtain the raw dictionary from - for example - the Unrouted or Routed notification in the index.

        If supplied, the raw dictionary will be validated against the allowed structure of this
        object, and an exception will be raised if it does not validate
        """
        struct = {
            "objects" : [
                "provider"
            ],
            "structs" : {
                "provider" : {
                    "fields" : {
                        "id" : {"coerce" :"unicode"},
                        "agent" : {"coerce" :"unicode"},
                        "ref" : {"coerce" :"unicode"},
                        "route" : {"coerce" :"unicode"}
                    },
                    "required" : []
                }
            }
        }

        self._add_struct(struct)
        super(ProviderOutgoingNotification, self).__init__(raw=raw)

class NotificationList(dataobj.DataObj):
    """
    Class to represent a list of notifications, as a response to an API request for notifications
    matching a specified set of criteria.

    It reflects back the original parameters of the request, and includes a list of serialised (to dict objects)
    OutgoingNotification objects

    ::

        {
            "since" : "<date from which results start in the form YYYY-MM-DDThh:mm:ssZ>",
            "page" : "<page number of results>,
            "pageSize" : "<number of results per page>,
            "timestamp" : "<timestamp of this request in the form YYYY-MM-DDThh:mm:ssZ>",
            "total" : "<total number of results at this time>",
            "notifications" : [
                "<ordered list of OutgoingNotification JSON objects>"
            ]
        }
    """

    @property
    def since(self):
        """
        The requested "since" date of the request

        :return: The requested "since" date of the request
        """
        return self._get_single("since", coerce=self._date_str())

    @since.setter
    def since(self, val):
        """
        Set the requested since date of the request

        :param val: the requested since date of the request
        :return:
        """
        self._set_single("since", val, coerce=self._date_str())

    @property
    def page(self):
        """
        The requested page of the response

        :return: The requested page of the response
        """
        return self._get_single("page", coerce=self._int())

    @page.setter
    def page(self, val):
        """
        Set the requested page of the response

        :param val: the requested page of the response
        :return:
        """
        self._set_single("page", val, coerce=self._int())

    @property
    def page_size(self):
        """
        The requested page size

        :return: the requested page size
        """
        return self._get_single("pageSize", coerce=self._int())

    @page_size.setter
    def page_size(self, val):
        """
        Set the requested page size

        :param val: the requested page size
        :return:
        """
        self._set_single("pageSize", val, coerce=self._int())

    @property
    def timestamp(self):
        """
        The timestamp of the request

        :return: the timestamp of the request in the form YYYY-MM-DDTHH:MM:SSZ
        """
        return self._get_single("timestamp", coerce=self._date_str())

    @timestamp.setter
    def timestamp(self, val):
        """
        Set the timestamp of the request

        :param val: the timestamp of the request in the form YYYY-MM-DDTHH:MM:SSZ
        :return:
        """
        self._set_single("timestamp", val, coerce=self._date_str())

    @property
    def total(self):
        """
        The total number of notifications in the full list (not necessarily included here) at the time of request

        :return: number of available notifications
        """
        return self._get_single("total", coerce=self._int())

    @total.setter
    def total(self, val):
        """
        Set the number of available notifications

        :param val: the number of available notifications
        :return:
        """
        self._set_single("total", val, coerce=self._int())

    @property
    def notifications(self):
        """
        The list of notifications included in this specific response

        :return: the list of notifications
        """
        return self._get_list("notifications")

    @notifications.setter
    def notifications(self, val):
        """
        Set the list of notifications for this response

        :param val: the list of notifications
        :return:
        """
        self._set_list("notifications", val)


text:
SpecBegin(AddAccountViewModel)

describe(@"Add Account View Model", ^{

    __block Database *database;
    __block Account *account;
    __block AddAccountViewModel *viewModel;

    beforeEach(^{
        database = [Database new];
        account = [[Account alloc] initWithName:@"HSBC" value:@(10)];
        viewModel = [[AddAccountViewModel alloc] initWithDatabase:database];
    });

    it (@"should not be able to create an account without a name and value", ^{
        __block BOOL enabled = YES;
        [viewModel.enableSignal subscribeNext:^(NSNumber *enabledValue) {
            enabled = [enabledValue boolValue];
        }];

        expect(enabled).to.beFalsy();

    });

    it (@"should not be able to create an account with only a name", ^{
        RAC(viewModel, accountName) = [RACSignal return:@"HSBC"];

        __block BOOL enabled = YES;
        [viewModel.enableSignal subscribeNext:^(NSNumber *enabledValue) {
            enabled = [enabledValue boolValue];
        }];

        expect(enabled).to.beFalsy();
    });

    it (@"should not be able to create an account with only a value", ^{
        RAC(viewModel, value) = [RACSignal return:@"10"];

        __block BOOL enabled = YES;
        [viewModel.enableSignal subscribeNext:^(NSNumber *enabledValue) {
            enabled = [enabledValue boolValue];
        }];

        expect(enabled).to.beFalsy();
    });

    it (@"should be able to create an account having value and name", ^{
        RAC(viewModel, value) = [RACSignal return:@"10"];
        RAC(viewModel, accountName) = [RACSignal return:@"HSBC"];

        __block BOOL enabled = NO;
        [viewModel.enableSignal subscribeNext:^(NSNumber *enabledValue) {
            enabled = [enabledValue boolValue];
        }];

        expect(enabled).to.beTruthy();
    });

    it (@"should call the database when adding an account", ^{
        id databaseMock = [OCMockObject partialMockForObject:database];
        [[databaseMock expect] addAccountSignal:OCMOCK_ANY];

        RAC(viewModel, accountName) = [RACSignal return:@"HSBC"];

        RAC(viewModel, value) = [RACSignal return:@"10"];

        [[viewModel createAccountSignal] subscribeNext:^(id x) {}];

        [databaseMock verify];
    });

    it (@"should return after creating an account", ^{
        RAC(viewModel, accountName) = [RACSignal return:@"HSBC"];
        RAC(viewModel, value) = [RACSignal return:@"10"];

        __block BOOL completed = NO;
        __block BOOL sentYES = NO;
        [viewModel.createAccountSignal subscribeNext:^(id x) {
            sentYES = [x boolValue];
        } completed:^{
            completed = YES;
        }];
        expect(completed).will.beTruthy();
        expect(sentYES).will.beTruthy();
    });

});

SpecEnd


text:
<?php
namespace PhpDescribe;

use PhpDescribe\EventListener\EventListenerInterface,
    PhpDescribe\EventListener\InspectFileAndLineListener,
    \ErrorException,
    PhpDescribe\Reporter\ResultReporter;

class Runner {

    static private $instance;
    static private $suspendedInstance;
    private $phpdescribe;

    /**
     * @return Runner
     */
    static function build() {
        $path = __DIR__ . '/../vendor/Doctrine/Common/ClassLoader.php';

        if(!class_exists('\Doctrine\Common\ClassLoader')) {
            require_once $path;
        }
        $classLoader = new \Doctrine\Common\ClassLoader('PhpDescribe', __DIR__.'/..');
        $classLoader->register();
        error_reporting(E_ALL);
        set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
            $e = new ErrorException($errstr, 0, $errno, $errfile, $errline);
            throw $e;
        });
        require_once(__DIR__.'/Spec/spec_functions.php');
        $runner = new Runner;
        $runner->addListener(new InspectFileAndLineListener());
        return $runner;
    }

    /**
     * @return Runner
     */
    private function __construct() {
        $this->phpdescribe = PhpDescribe::build();
    }

    function setSpec($filePath) {
        $this->phpdescribe->addDescriptionFilePath($filePath);
        return $this;
    }

    /**
     * @return Runner
     */
    function addSuiteDir($dir) {
        include_once $dir . '/index.php';
        return $this;
    }

    function addListener(EventListenerInterface $e) {
        $this->phpdescribe->addEventListener($e);
        return $this;
    }

    /**
     * @return Runner
     */
    function runAndReport($parameters = array(), $decorate = true) {
        $resultGroup = $this->run($parameters);
        $reportHtml = ResultReporter::build()->report($resultGroup);

        if($decorate) {
            return $this->decorateHtml($reportHtml);
        }
        else {
            return $reportHtml;
        }

    }

    /**
     * @param array $parameters
     * @return PhpDescribe\Result\ResultGroup
     */
    function run($parameters = array()) {
        $this->phpdescribe->addParameters($parameters);
        try {
            $resultGroup = $this->phpdescribe->run();
        }
        catch(\Exception $e) {
            echo (get_class($e)) . ' - ';
            echo ($e->getMessage()) . '

';
            echo nl2br($e->getTraceAsString());
            die('exception error running the suite');
        }
        return $resultGroup;
    }

    private function decorateHtml($reportHtml) {
        return
"

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>

        Legenda:
        . Working
        . Not Working
        . Incomplete
        . Error

    $reportHtml
";
//
//

//PhpDescribe, propriedade da
//Humanidade
//é licenciado sob uma Licença Creative Commons Atribuição 3.0 Brasil.
O repositório oficial esta no
//github.com.
//
//        ";
    }
}


text:
package org.wso2.carbon.apimgt.ballerina.util;

import org.ballerinalang.bre.Context;
import org.ballerinalang.model.types.TypeEnum;
import org.ballerinalang.model.values.BMessage;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.natives.AbstractNativeFunction;
import org.ballerinalang.natives.annotations.Argument;
import org.ballerinalang.natives.annotations.Attribute;
import org.ballerinalang.natives.annotations.BallerinaAnnotation;
import org.ballerinalang.natives.annotations.BallerinaFunction;
import org.ballerinalang.natives.annotations.ReturnType;

/**
 * Ballerina function to set a message property.
 * <br>
 * ballerina.model.messages:getProperty
 */
@BallerinaFunction(
        packageName = "org.wso2.carbon.apimgt.ballerina.util",
        functionName = "getProperty",
        args = {@Argument(name = "msg", type = TypeEnum.MESSAGE),
                @Argument(name = "propertyName", type = TypeEnum.STRING)},
        returnType = {@ReturnType(type = TypeEnum.ANY)},
        isPublic = true
)
@BallerinaAnnotation(annotationName = "Description", attributes = {@Attribute(name = "value",
        value = "Retrieve a message property")})
@BallerinaAnnotation(annotationName = "Param", attributes = {@Attribute(name = "msg",
        value = "The current message object")})
@BallerinaAnnotation(annotationName = "Param", attributes = {@Attribute(name = "propertyName",
        value = "The name of the property")})
@BallerinaAnnotation(annotationName = "Return", attributes = {@Attribute(name = "string",
        value = "The property value")})
public class GetProperty extends AbstractNativeFunction {

    @Override
    public BValue[] execute(Context context) {
        BMessage msg = (BMessage) getRefArgument(context, 0);
        String propertyName = getStringArgument(context, 0);

        BValue propertyValue = (BValue) msg.getProperty(propertyName);

        if (propertyValue == null) {
            return VOID_RETURN;
        }
        return getBValues(propertyValue);
    }
}


text:
use simple_kbuckets::Table;

use node::{Address, Node, ADDRESS_BITS};

/// Returns by a request to find a node's path and public key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GetNodeResult<'a> {
    /// The exact node, if it was found.
    FoundNode(&'a Node),
    /// Nodes close to the searched node. They should be queried about
    /// the searched node.
    ClosestNodes(Vec<(Address, &'a Node)>),
    /// This table knows of no node at all. It should be bootstrapped
    /// using an external way (ie. find some peers).
    Nothing,
}

pub struct NodeStore {
    pub table: Table<Address, Node>,
}

impl NodeStore {
    /// Creates a new empty NodeStore.
    pub fn new(my_address: Address) -> NodeStore {
        let bucket_size = 32;
        let max_distance = ADDRESS_BITS;
        NodeStore {
            table: Table::new(my_address, bucket_size, max_distance),
        }
    }

    /// Inserts a node in the NodeStore, poping nodes from full
    /// buckets if necessary.
    pub fn update(&mut self, address: Address, node: Node) {
        self.table.update(address, node);
    }

    /// Retrurns an ordered vector of nodes, which are the closest to the
    /// target address this NodeStore knows about.
    pub fn find_closest_nodes(&self, target: &Address, count: usize) -> Vec<(Address, &Node)> {
        self.table.find(target, count)
    }

    /// Tries to get a node. On failure, returns `nb_closest` nodes (or all
    /// nodes in the store, if `nb_closest` is too high) that should be
    /// queried about the searched node.
    pub fn get_node(&self, target: &Address, nb_closest: usize) -> GetNodeResult {
        let closest_nodes = self.find_closest_nodes(target, nb_closest);
        match closest_nodes.clone().get(0) { // TODO: do not clone
            Some(&(ref closest_addr, ref closest_node)) => {
                if closest_addr == target {
                    GetNodeResult::FoundNode(closest_node)
                }
                else {
                    GetNodeResult::ClosestNodes(closest_nodes)
                }
            }
            None => GetNodeResult::Nothing,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv6Addr;
    use std::str::FromStr;
    use node::Address;
    use node::Node;

    #[test]
    fn test_get_one_node() {
        let mut ns = NodeStore::new(Address::from(Ipv6Addr::from_str("fc8f:a188:1b5:4de9:b0cb:5729:23a1:60f9").unwrap()));
        let addr = Address::from(Ipv6Addr::from_str("fc7c:8316:ec7d:1308:d3c2:6db7:5ad9:6ebc").unwrap());
        let target = Address::from(Ipv6Addr::from_str("fcb9:326d:37d5:c57b:7ee5:28b5:7aa5:525").unwrap());
        let node = Node::new([14, 212, 108, 34, 167, 28, 34, 202, 98, 134, 15, 159, 58, 151, 12, 228, 58, 163, 181, 163, 40, 102,  66, 125, 212, 44, 203, 100, 174, 56, 120, 61], [0, 0, 0, 0, 0, 0, 0, 11], 17);
        ns.update(addr.clone(), node.clone());
        let res = ns.get_node(&target, 42);
        assert_eq!(res, GetNodeResult::ClosestNodes(vec![(addr, &node)]));
    }
}


text:
package com.izgoy.txttr;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

public class SmsHandlerService extends IntentService {

    public static final String TAG = "SmsHandlerService";

    public static final String ACTION_HANDLE_SMS = "com.izgoy.txttr.action.HANDLE_SMS";

    public static final String EXTRA_ADDRESS = "com.izgoy.txttr.extra.ADDRESS";
    public static final String EXTRA_BODY = "com.izgoy.txttr.extra.BODY";

    private UserManager userManager;

    public static void startHandleSMS(Context context, String address, String body) {
        Intent intent = new Intent(context, SmsHandlerService.class);
        intent.setAction(ACTION_HANDLE_SMS);
        intent.putExtra(EXTRA_ADDRESS, address);
        intent.putExtra(EXTRA_BODY, body);
        context.startService(intent);
    }

    public SmsHandlerService() {
        super("SmsHandlerService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();
        userManager = new UserManager(this);
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_HANDLE_SMS.equals(action)) {
                final String address = intent.getStringExtra(EXTRA_ADDRESS);
                final String body = intent.getStringExtra(EXTRA_BODY);
                handleSMS(address, body);
            }
        }
        wakeLock.release();
    }

    private void handleSMS(String address, String body) {
        Log.d(TAG, address + " >>> " + body);
        String[] args = body.split(" ");
        if (args.length > 0) {
            String command = args[0].toLowerCase();
            if (command.equals("on")) {
                handleCommandOn(address, args);
                return;
            }
            if (command.equals("list")) {
                handleCommandList(address, args);
                return;
            }
            if (command.equals("off")) {
                handleCommandOff(address, args);
                return;
            }
        }
        if (userManager.isAddressRegistered(address)) {
            String nick = userManager.getAll().get(address);
            String body2 = String.format("%s: %s", nick.toUpperCase(), body);
            userManager.sendTextMessageToAll(body2, address);
            userManager.sendTextMessage(address, getString(R.string.message_sent));
        }
    }

    private void handleCommandOn(String address, String[] args) {

        if (args.length < 2) {
            userManager.sendTextMessage(address, getString(R.string.message_error_nick_required));
            return;
        }

        String nick = args[1].toUpperCase();

        if (userManager.isNickRegistered(nick)) {
            userManager.sendTextMessage(address, getString(R.string.message_error_nick_taken));
            return;
        }

        if (nick.length() < TxttrApplication.MIN_NICK_LENGTH) {
            userManager.sendTextMessage(address, getString(R.string.message_error_nick_too_short, TxttrApplication.MIN_NICK_LENGTH));
            return;
        }

        if (nick.length() > TxttrApplication.MAX_NICK_LENGTH) {
            userManager.sendTextMessage(address, getString(R.string.message_error_nick_too_long, TxttrApplication.MAX_NICK_LENGTH));
            return;
        }

        userManager.register(address, nick);
        String msgUsers = getString(R.string.message_registered_users, TextUtils.join(", ", userManager.getAll().values()));
        String msgRegistered = getString(R.string.message_success_registration) + " " + msgUsers;
        String msgPleaseWelcome = getString(R.string.message_success_registration_all, nick) + " " + msgUsers;
        userManager.sendTextMessage(address, msgRegistered);
        userManager.sendTextMessageToAll(msgPleaseWelcome, address);
    }

    private void handleCommandOff(String address, String[] args) {
        String nick = userManager.getNick(address);
        userManager.unregister(address);
        userManager.sendTextMessage(address, getString(R.string.message_success_unregistration));
        if (nick != null) {
            userManager.sendTextMessageToAll(getString(R.string.message_success_unregistration_all, nick), address);
        }
    }

    private void handleCommandList(String address, String[] args) {
        String reply = getString(R.string.message_registered_users,
                TextUtils.join(", ", userManager.getAll().values()));
        userManager.sendTextMessage(address, reply);
    }

}


text:
import sys

from util.training import generate_reduced_training_set_from_cellular, save_training_set

def main(argv):
    opt_processing_function_rule_location = 'resource/rule/2DA/2x2'
    opt_world_size = [50, 50]
    opt_world_percentage = 65
    opt_cycles_count = 50
    opt_output_location = 'resource/training_set/2x2_all'
    if len(argv) == 5:
        opt_processing_function_rule_location = argv[0]
        opt_world_size = [int(x) for x in argv[1].split('-')]
        opt_world_percentage = int(argv[2])
        opt_cycles_count = int(argv[3])
        opt_output_location = argv[4]

    training_set = generate_reduced_training_set_from_cellular(
        opt_processing_function_rule_location,
        world_size=opt_world_size,
        world_percentage=opt_world_percentage,
        cycles_count=opt_cycles_count
    )

    size_cur = len(training_set[0])
    size_max = 2 ** len(training_set[0][0])
    percent = 100.0 * size_cur / size_max

    print('Training set size: %d of %d (%.2f%%)' % (size_cur, size_max, percent))

    save_training_set(training_set, opt_output_location)

if __name__ == "__main__":
    main(sys.argv[1:])


text:
if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
clear

docker rm -f "cheri-cart" > /dev/null

#/usr/bin/docker run -i -d -v ~/development/chericart:/source/chericart --name=cheri-cart -p 8001:8001 -t "drlinux/chicagoboss" > /dev/null
/usr/bin/docker run -i -d -v ~/development/chericart:/source/chericart:rw --name=cheri-cart -p 8001:8001 -t "drlinux/chicagoboss" > /dev/null

CONTAINER_IP=$(/usr/bin/docker inspect --format="{{ .NetworkSettings.IPAddress }}" cheri-cart)

echo "Congrats! Chéri Chart started";

echo "Please visit : http://"$CONTAINER_IP":8001"

echo "You can access the source files by type :"

echo "cd ~/development/chericart/"


text:
require 'cocoapods/browser/version'

module Cocoapods
  module Browser
    # Your code goes here...
  end
end