text:
Static Page.

## Contents

* About me
* Books & Lectures
* Projects
* Links
* Posts

## Bug Report

my email : kiss72k@다음.net

## Tech

Start Bootstrap was created by and is maintained by **David Miller**, Managing Parter at [Iron Summit Media Strategies](http://www.ironsummitmedia.com/).

* https://twitter.com/davidmillerskt
* https://github.com/davidtmiller

Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat).

## Copyright and License

Copyright 2012-2017 kiss nim'S Company.


text:
package exercise;

import java.util.Scanner;

/**
 * Created by bonismo
 * 14/10/27 下午10:23
 */
public class ParityNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int get = scanner.nextInt();
        String string = (get % 2) == 0 ? "偶数" : "奇数";
        System.out.println("该整数是:"+string);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Class SEOEditorCSVLoader
 */
class SEOEditorCSVLoader extends CsvBulkLoader
{

    /**
     * @var array
     */
    public $duplicateChecks = array(
        'ID' => 'ID',
    );

    /**
     * Update the columns needed when importing from CSV
     *
     * @param array $record
     * @param array $columnMap
     * @param BulkLoader_Result $results
     * @param bool $preview
     * @return bool|int
     */
    public function processRecord($record, $columnMap, &$results, $preview = false)
    {
        $page = $this->findExistingObject($record, $columnMap);

        if (!$page || !$page->exists()) {
            return false;
        }

        foreach ($record as $fieldName => $val) {
            if ($fieldName == 'MetaTitle' || $fieldName == 'MetaDescription') {
                $sqlValue = Convert::raw2sql($val);
                DB::query("UPDATE SiteTree SET {$fieldName} = '{$sqlValue}' WHERE ID = {$page->ID}");
                if ($page->isPublished()) {
                    DB::query("UPDATE SiteTree_Live SET {$fieldName} = '{$sqlValue}' WHERE ID = {$page->ID}");
                }
            }
        }

        return $page->ID;
    }

}


text:
namespace sudoku {

class SudukuServer {
 public:
  SudukuServer(voyager::EventLoop* ev, const voyager::SockAddr& addr)
      : server_(ev, addr, "SudukuServer", 4) {
    server_.SetConnectionCallback(
        std::bind(&SudukuServer::ConnectCallback, this, std::placeholders::_1));
    server_.SetMessageCallback(std::bind(&SudukuServer::MessageCallback, this,
                                         std::placeholders::_1,
                                         std::placeholders::_2));
  }

  void Start() { server_.Start(); }

 private:
  static const int kCells = 81;

  void ConnectCallback(const voyager::TcpConnectionPtr& ptr) {}

  void MessageCallback(const voyager::TcpConnectionPtr& ptr,
                       voyager::Buffer* buf) {
    size_t size = buf->ReadableSize();
    while (size >= kCells + 2) {
      const char* crlf = buf->FindCRLF();
      if (crlf) {
        std::string s(buf->Peek(), crlf);
        buf->RetrieveUntil(crlf + 2);
        size = buf->ReadableSize();

        if (!Slove(ptr, std::move(s))) {
          voyager::Slice bad("Bad Request!\r\n");
          ptr->SendMessage(bad);
          ptr->ShutDown();
          break;
        }
      } else {
        break;
      }
    }
  }

  bool Slove(const voyager::TcpConnectionPtr& ptr, std::string&& s) {
    std::string id;
    std::string puzzle;
    std::vector<std::string> v;
    voyager::SplitStringUsing(s, ":", &v);
    if (v.size() > 1) {
      id = v.at(0);
      puzzle = v.at(1);
    } else {
      puzzle = std::move(s);
    }

    if (puzzle.size() != static_cast<size_t>(kCells)) {
      return false;
    }
    SudokuSolver solver(puzzle);
    std::string res = solver.Solve();
    if (id.empty()) {
      ptr->SendMessage(res + "\r\n");
    } else {
      ptr->SendMessage(id + ":" + res + "\r\n");
    }
    return true;
  }

  voyager::TcpServer server_;
};

}  // namespace sudoku

int main(int argc, char** argv) {
  voyager::EventLoop ev;
  voyager::SockAddr addr(5666);
  sudoku::SudukuServer server(&ev, addr);
  server.Start();
  ev.Loop();
  return 0;
}


text:
define("dojox/mobile/_ListTouchMixin",["dojo/_base/declare","dojo/touch","./sniff","dijit/form/_ListBase"],function(_1,_2,_3,_4){
return _1("dojox.mobile._ListTouchMixin",_4,{postCreate:function(){
this.inherited(arguments);
if(!(_3("ie")>=10&&_3("touch"))){
this._listConnect("click","_onClick");
}else{
this._listConnect(_2.press,"_onPress");
var _5=this,_6=new MSGesture(),_7;
this._onPress=function(e){
_6.target=_5.domNode;
_6.addPointer(e.pointerId);
_7=e.target;
};
this.on("MSGestureTap",function(e){
_5._onClick(e,_7);
});
}
},_onClick:function(_8,_9){
this._setSelectedAttr(_9);
this.onClick(_9);
}});
});


text:
using System;
using System.Security.Cryptography.X509Certificates;

namespace Mono.WebServer
{
	//
	// ModMonoApplicationHost: The application host for mod_mono.
	//
	public class ModMonoApplicationHost : BaseApplicationHost
	{
		static byte[] FromPEM (string pem)
		{
			int start = pem.IndexOf ("-----BEGIN CERTIFICATE-----");
			if (start < 0)
				return null;

			start += 27; // 27 being the -----BEGIN CERTIFICATE----- length
			int end = pem.IndexOf ("-----END CERTIFICATE-----", start);
			if (end < start)
				return null;

			string base64 = pem.Substring (start, (end - start));
			return Convert.FromBase64String (base64);
		}

		public void ProcessRequest (int reqId, string verb, string queryString, string path,
					    string protocol, string localAddress, int serverPort, string remoteAddress,
					    int remotePort, string remoteName, string [] headers, string [] headerValues, object worker)
		{
			ModMonoWorkerRequest mwr = null;

			try {
				if (reqId > -1) {
					mwr = new ModMonoWorkerRequest (reqId, (ModMonoRequestBroker) RequestBroker, this, verb, path, queryString,
									protocol, localAddress, serverPort, remoteAddress,
									remotePort, remoteName, headers, headerValues);
				} else {
					mwr = new ModMonoWorkerRequest (worker, this, verb, path, queryString,
									protocol, localAddress, serverPort, remoteAddress,
									remotePort, remoteName, headers, headerValues);
				}

				if (mwr.IsSecure ()) {
					// note: we're only setting what we use (and not the whole lot)
					mwr.AddServerVariable ("CERT_KEYSIZE", mwr.GetServerVariable (reqId, "SSL_CIPHER_USEKEYSIZE"));
					mwr.AddServerVariable ("CERT_SECRETKEYSIZE", mwr.GetServerVariable (reqId, "SSL_CIPHER_ALGKEYSIZE"));

					string pem_cert = mwr.GetServerVariable (reqId, "SSL_CLIENT_CERT");
					// 52 is the minimal PEM size for certificate header/footer
					if ((pem_cert != null) && (pem_cert.Length > 52)) {
						byte[] certBytes = FromPEM (pem_cert);
						mwr.SetClientCertificate (certBytes);

						// check client certificate validity with Apache and/or Mono
						if (mwr.IsClientCertificateValid (certBytes)) {
							// client cert present (bit0 = 1) and valid (bit1 = 0)
							mwr.AddServerVariable ("CERT_FLAGS", "1");
						} else {
							// client cert present (bit0 = 1) but invalid (bit1 = 1)
							mwr.AddServerVariable ("CERT_FLAGS", "3");
						}
					} else {
						mwr.AddServerVariable ("CERT_FLAGS", "0");
					}

					pem_cert = mwr.GetServerVariable (reqId, "SSL_SERVER_CERT");
					// 52 is the minimal PEM size for certificate header/footer
					if ((pem_cert != null) && (pem_cert.Length > 52)) {
						byte[] certBytes = FromPEM (pem_cert);
						var cert = new X509Certificate (certBytes);
						mwr.AddServerVariable ("CERT_SERVER_ISSUER", cert.Issuer);
						mwr.AddServerVariable ("CERT_SERVER_SUBJECT", cert.Subject);
					}
				}
			} catch (Exception) {
				EndOfRequest (mwr);
				throw;
			}

			ProcessRequest (mwr);
		}
	}
}


text:
_CCGUI_NAMESPACE_BEGIN

class Button:public Widget
{

};

_CCGUI_NAMESPACE_END
#endif


text:
'use strict';

require('./ward-lib/index.js');


text:
define("dojox/image/LightboxNano", ["dojo", "dojo/fx"], function(dojo, fx) {

	var abs = "absolute",
		vis = "visibility",
		getViewport = function(){
			// summary:
			//		Returns the dimensions and scroll position of the viewable area of a browser window
			var scrollRoot = (dojo.doc.compatMode == "BackCompat") ? dojo.body() : dojo.doc.documentElement,
				scroll = dojo._docScroll();
				return { w: scrollRoot.clientWidth, h: scrollRoot.clientHeight, l: scroll.x, t: scroll.y };
			}
	;

	return dojo.declare("dojox.image.LightboxNano", null, {
		// summary:
		//		A simple "nano" version of the lightbox.
		// description:
		//		Very lightweight lightbox which only displays a larger image.  There is
		//		no support for a caption or description.  The lightbox can be closed by
		//		clicking any where or pressing any key.  This widget is intended to be
		//		used on `<a>` and `<img>` tags.  Upon creation, if the domNode is `<img>` tag,
		//		then it is wrapped in an `<a>` tag, then a `<div class="enlarge">` is placed
		//		inside the `<a>` and can be styled to display an icon that the original
		//		can be enlarged.
		// example:
		//	|
		// example:
		//	|

		// href: string
		//		URL to the large image to show in the lightbox.
		href: "",

		// duration: int
		//		The delay in milliseconds of the LightboxNano open and close animation.
		duration: 500,

		// preloadDelay: int
		//		The delay in milliseconds after the LightboxNano is created before preloading the larger image.
		preloadDelay: 5000,

		constructor: function(/*Object?*/p, /*DomNode?*/n){
			// summary:
			//		Initializes the DOM node and connect onload event
			var _this = this;

			dojo.mixin(_this, p);
			n = _this._node = dojo.byId(n);

			// if we have a origin node, then prepare it to show the LightboxNano
			if(n){
				if(!/a/i.test(n.tagName)){
					var a = dojo.create("a", { href: _this.href, "class": n.className }, n, "after");
					n.className = "";
					a.appendChild(n);
					n = a;
				}

				dojo.style(n, "position", "relative");
				_this._createDiv("dojoxEnlarge", n);
				dojo.setSelectable(n, false);
				_this._onClickEvt = dojo.connect(n, "onclick", _this, "_load");
			}

			if(_this.href){
				setTimeout(function(){
					(new Image()).src = _this.href;
					_this._hideLoading();
				}, _this.preloadDelay);
			}
		},

		destroy: function(){
			// summary:
			//		Destroys the LightboxNano and it's DOM node
			var a = this._connects || [];
			a.push(this._onClickEvt);
			dojo.forEach(a, dojo.disconnect);
			dojo.destroy(this._node);
		},

		_createDiv: function(/*String*/cssClass, /*DomNode*/refNode, /*boolean*/display){
			// summary:
			//		Creates a div for the enlarge icon and loading indicator layers
			return dojo.create("div", { // DomNode
				"class": cssClass,
				style: {
					position: abs,
					display: display ? "" : "none"
				}
			}, refNode);
		},

		_load: function(/*Event*/e){
			// summary:
			//		Creates the large image and begins to show it
			var _this = this;

			e && dojo.stopEvent(e);

			if(!_this._loading){
				_this._loading = true;
				_this._reset();

				var i = _this._img = dojo.create("img", {
						style: {
							visibility: "hidden",
							cursor: "pointer",
							position: abs,
							top: 0,
							left: 0,
							zIndex: 9999999
						}
					}, dojo.body()),
					ln = _this._loadingNode,
					n = dojo.query("img", _this._node)[0] || _this._node,
					a = dojo.position(n, true),
					c = dojo.contentBox(n),
					b = dojo._getBorderExtents(n)
				;

				if(ln == null){
					_this._loadingNode = ln = _this._createDiv("dojoxLoading", _this._node, true);
					var l = dojo.marginBox(ln);
					dojo.style(ln, {
						left: parseInt((c.w - l.w) / 2) + "px",
						top: parseInt((c.h - l.h) / 2) + "px"
					});
				}

				c.x = a.x - 10 + b.l;
				c.y = a.y - 10 + b.t;
				_this._start = c;

				_this._connects = [dojo.connect(i, "onload", _this, "_show")];

				i.src = _this.href;
			}
		},

		_hideLoading: function(){
			// summary:
			//		Hides the animated loading indicator
			if(this._loadingNode){
				dojo.style(this._loadingNode, "display", "none");
			}
			this._loadingNode = false;
		},

		_show: function(){
			// summary:
			//		The image is now loaded, calculate size and display
			var _this = this,
				vp = getViewport(),
				w = _this._img.width,
				h = _this._img.height,
				vpw = parseInt((vp.w - 20) * 0.9),
				vph = parseInt((vp.h - 20) * 0.9),
				dd = dojo.doc,
				bg = _this._bg = dojo.create("div", {
					style: {
						backgroundColor: "#000",
						opacity: 0.0,
						position: abs,
						zIndex: 9999998
					}
				}, dojo.body()),
				ln = _this._loadingNode
			;

			if(_this._loadingNode){
				_this._hideLoading();
			}
			dojo.style(_this._img, {
				border: "10px solid #fff",
				visibility: "visible"
			});
			dojo.style(_this._node, vis, "hidden");

			_this._loading = false;

			_this._connects = _this._connects.concat([
				dojo.connect(dd, "onmousedown", _this, "_hide"),
				dojo.connect(dd, "onkeypress", _this, "_key"),
				dojo.connect(window, "onresize", _this, "_sizeBg")
			]);

			if(w > vpw){
				h = h * vpw / w;
				w = vpw;
			}
			if(h > vph){
				w = w * vph / h;
				h = vph;
			}

			_this._end = {
				x: (vp.w - 20 - w) / 2 + vp.l,
				y: (vp.h - 20 - h) / 2 + vp.t,
				w: w,
				h: h
			};

			_this._sizeBg();

			dojo.fx.combine([
				_this._anim(_this._img, _this._coords(_this._start, _this._end)),
				_this._anim(bg, { opacity: 0.5 })
			]).play();
		},

		_sizeBg: function(){
			// summary:
			//		Resize the background to fill the page
			var dd = dojo.doc.documentElement;
			dojo.style(this._bg, {
				top: 0,
				left: 0,
				width: dd.scrollWidth + "px",
				height: dd.scrollHeight + "px"
			});
		},

		_key: function(/*Event*/e){
			// summary:
			//		A key was pressed, so hide the lightbox
			dojo.stopEvent(e);
			this._hide();
		},

		_coords: function(/*Object*/s, /*Object*/e){
			// summary:
			//		Returns animation parameters with the start and end coords
			return { // Object
				left:	{ start: s.x, end: e.x },
				top:	{ start: s.y, end: e.y },
				width:	{ start: s.w, end: e.w },
				height:	{ start: s.h, end: e.h }
			};
		},

		_hide: function(){
			// summary:
			//		Closes the lightbox
			var _this = this;
			dojo.forEach(_this._connects, dojo.disconnect);
			_this._connects = [];
			dojo.fx.combine([
				_this._anim(_this._img, _this._coords(_this._end, _this._start), "_reset"),
				_this._anim(_this._bg, {opacity:0})
			]).play();
		},

		_reset: function(){
			// summary:
			//		Destroys the lightbox
			dojo.style(this._node, vis, "visible");
			dojo.destroy(this._img);
			dojo.destroy(this._bg);
			this._img = this._bg = null;
			this._node.focus();
		},

		_anim: function(/*DomNode*/node, /*Object*/args, /*Function*/onEnd){
			// summary:
			//		Creates the lightbox open/close and background fadein/out animations
			return dojo.animateProperty({ // dojo.Animation
				node: node,
				duration: this.duration,
				properties: args,
				onEnd: onEnd ? dojo.hitch(this, onEnd) : null
			});
		},

		show: function(/*Object?*/args){
			// summary:
			//		Shows this LightboxNano programatically. Allows passing a new href and
			//		a programmatic origin.
			// args: Object?
			//		An object with optional members of `href` and `origin`.
			//		`origin` can be be a String|Id of a DomNode to use when
			//		animating the opening of the image (the 'box' effect starts
			//		from this origin point. eg: { origin: e.target })
			//		If there's no origin, it will use the center of the viewport.
			//		The `href` member is a string URL for the image to be
			//		displayed. Omitting either of these members will revert to
			//		the default href (which could be absent in some cases) and
			//		the original srcNodeRef for the widget.
			args = args || {};
			this.href = args.href || this.href;

			var n = dojo.byId(args.origin),
				vp = getViewport();

			// if we don't have a valid origin node, then create one as a reference
			// that is centered in the viewport
			this._node = n || dojo.create("div", {
					style: {
						position: abs,
						width: 0,
						hieght: 0,
						left: (vp.l + (vp.w / 2)) + "px",
						top: (vp.t + (vp.h / 2)) + "px"
					}
				}, dojo.body())
			;

			this._load();

			// if we don't have a valid origin node, then destroy the centered reference
			// node since load() has already been called and it's not needed anymore.
			if(!n){
				dojo.destroy(this._node);
			}
		}
	});

});


text:
package org.datanucleus.samples.annotations.models.company;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

/**
 * User account for a person.
 */
@Entity
@Table(name="JPA_AN_ACCOUNT")
@TableGenerator(name="AccountGenerator")
public class Account implements Serializable
{
    private static final long serialVersionUID = -1883261101079091951L;

    @Id
    @GeneratedValue(strategy=GenerationType.TABLE, generator="AccountGenerator")
    private long id; // PK if app id

    @Basic
    @Column(name="USERNAME")
    private String username;

    @Basic
    @Column(name="ACTIVE")
    private boolean enabled;

    public Account()
    {
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public long getId()
    {
        return id;
    }

    public boolean getEnabled()
    {
        return enabled;
    }

    public void setEnabled(boolean b)
    {
        enabled = b;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String s)
    {
        username = s;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet" type="text/css" href="mirador/css/mirador-combined.css">
  <title>Mirador Viewer</title>


text:
package com.github.kunai.source;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * This class is for extracting class name from Java bytecode.
 *
 * @author Haruaki Tamada
 */
class ClassNameExtractVisitor extends ClassVisitor{
    private String className;

    public static final String parseClassName(File file){
        try(FileInputStream in = new FileInputStream(file)) {
            ClassReader reader = new ClassReader(in);
            ClassNameExtractVisitor visitor = new ClassNameExtractVisitor();
            reader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

            return visitor.getClassName();

        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
        return null;
    }

    public static final String parseClassName(Path path){
        try (InputStream in = Files.newInputStream(path)){
            ClassReader reader = new ClassReader(in);
            ClassNameExtractVisitor visitor = new ClassNameExtractVisitor();
            reader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

            return visitor.getClassName();

        } catch(IOException e){
            e.printStackTrace();
        }
        return null;
    }

    public ClassNameExtractVisitor(){
        super(Opcodes.ASM5);
    }

    public String getClassName(){
        return className;
    }

    @Override
    public void visit(int version, int access, String origName, String signature,
            String superClassName, String[] interfaces){
        String name = origName.replace('/', '.').replace('\\', '.');
        className = name;
    }

    @Override
    public AnnotationVisitor visitAnnotation(String arg0, boolean arg1){
        return null;
    }

    @Override
    public void visitAttribute(Attribute arg0){
    }

    @Override
    public void visitEnd(){
    }

    @Override
    public FieldVisitor visitField(int arg0, String arg1, String arg2,
            String arg3, Object arg4){
        return null;
    }

    @Override
    public void visitInnerClass(String arg0, String arg1, String arg2,
            int arg3){
    }

    @Override
    public MethodVisitor visitMethod(int arg0, String arg1, String arg2,
            String arg3, String[] arg4){
        return null;
    }

    @Override
    public void visitOuterClass(String arg0, String arg1, String arg2){
    }

    @Override
    public void visitSource(String arg0, String arg1){

    }
}


text:
import cb from '../../helpers/CrossBrowser';

export default class VideoLocal extends React.Component {

    /**
     * @constructor
     * @return {VideoLocal}
     */
    constructor() {
        super();
        this.state = { stream: null };
    }

    /**
     * @method componentDidMount
     * @return {void}
     */
    componentDidMount() {

        let mediaOptions = { video: true, audio: true },
            url          = window.URL || window.webkitURL;

        // Attempt to fetch the user's media stream for their webcam.
        cb.getUserMedia(mediaOptions, (stream) => {
            let streamSource = url ? url.createObjectURL(stream) : stream;
            this.setState({ stream: streamSource });
        }, () => {

            console.log('Error!');

        });

    }

    /**
     * @method render
     * @return {Object}
     */
    render() {
        return React.createElement('video', { src: this.state.stream, muted: 'muted', autoPlay: 'autoplay' });
    }

}


text:
#ifndef __REDIS_UTIL_H
#define __REDIS_UTIL_H

int stringmatchlen(const char *p, int plen, const char *s, int slen, int nocase);
int stringmatch(const char *p, const char *s, int nocase);
long long memtoll(const char *p, int *err);
int ll2string(char *s, size_t len, long long value);
int string2ll(const char *s, size_t slen, long long *value);
int string2l(const char *s, size_t slen, long *value);
int d2string(char *buf, size_t len, double value);

#endif


text:
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission, AnonymousUser, Group
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, modify_settings

from chemtrails.contrib.permissions.backends import ChemoPermissionsBackend
from chemtrails.contrib.permissions.models import AccessRule
from chemtrails.neoutils import get_nodeset_for_queryset

from tests.utils import clear_neo4j_model_nodes
from tests.testapp.autofixtures import Author, AuthorFixture, Store, StoreFixture

User = get_user_model()

class ChemoPermissionsBackendTestCase(TestCase):

    backend = 'chemtrails.contrib.permissions.backends.ChemoPermissionsBackend'

    def setUp(self):
        super(ChemoPermissionsBackendTestCase, self).setUp()
        self.patched_settings = modify_settings(
            AUTHENTICATION_BACKENDS={'append': self.backend}
        )
        self.patched_settings.enable()
        clear_neo4j_model_nodes()

    def tearDown(self):
        super(ChemoPermissionsBackendTestCase, self).tearDown()
        self.patched_settings.disable()
        clear_neo4j_model_nodes()

    def test_authenticate(self):
        kwargs = {
            'username': 'testuser',
            'password': 'test123.'
        }
        User.objects.create_user(**kwargs)

        backend = ChemoPermissionsBackend()
        self.assertIsNone(backend.authenticate(**kwargs))

    def test_get_all_permissions_user(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        user.user_permissions.add(*permissions)

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )

    def test_get_all_permissions_group(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        group.user_set.add(user)
        group.permissions.add(*permissions)

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )

    def test_get_all_permissions_mixed_user_and_group(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        group.user_set.add(user)

        user.user_permissions.add(*permissions.filter(content_type__model='user'))
        group.permissions.add(*permissions.filter(content_type__model='group'))

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )

    def test_get_all_permissions_non_model_instance(self):
        class FooBar:
            pass

        obj = FooBar()
        user = User.objects.create_user(username='testuser', password='test123.')
        backend = ChemoPermissionsBackend()
        self.assertEqual(set(), backend.get_all_permissions(user, obj))

    def test_get_all_permissions_anonymous_user(self):
        class FooBar:
            pass

        obj = FooBar()
        user = AnonymousUser()
        backend = ChemoPermissionsBackend()
        self.assertEqual(set(), backend.get_all_permissions(user, obj))

    def test_has_perm_non_model_instance(self):
        class FooBar:
            pass

        obj = FooBar()
        user = User.objects.create_user(username='testuser', password='test123.')
        backend = ChemoPermissionsBackend()
        self.assertFalse(backend.has_perm(user, 'app_label.codename', obj))

    def test_has_perm_anonymous_user(self):
        user = AnonymousUser()
        group = Group.objects.create(name='group')

        backend = ChemoPermissionsBackend()
        self.assertFalse(backend.has_perm(user, 'app_label.codename', group))

    def test_check_permission(self):
        user = User.objects.create_user(username='testuser', password='test123.')

        group = Group.objects.create(name='group')
        group.user_set.add(user)

        access_rule = AccessRule.objects.create(
            ctype_source=ContentType.objects.get_for_model(User),
            ctype_target=ContentType.objects.get_for_model(Group),
            relation_types=[{'GROUPS': None}]
        )
        perm = Permission.objects.get(content_type__app_label='auth', codename='add_group')
        group.permissions.add(perm)
        access_rule.permissions.add(perm)

        backend = ChemoPermissionsBackend()
        self.assertTrue(backend.has_perm(user, 'add_group', group))       # Permission codename only
        self.assertTrue(backend.has_perm(user, 'auth.add_group', group))  # Full permission string

    def test_user_has_perm_single_relation_type(self):
        author = AuthorFixture(Author).create_one()
        permission = Permission.objects.get(codename='change_author')
        author.user.user_permissions.add(permission)
        access_rule = AccessRule.objects.create(
            ctype_source=ContentType.objects.get_for_model(author.user),
            ctype_target=ContentType.objects.get_for_model(author),
            relation_types=[{'AUTHOR': None}]
        )
        access_rule.permissions.add(permission)
        self.assertTrue(author.user.has_perm('testapp.change_author', author))

    def test_user_has_perm_multiple_relation_types(self):
        # Set up a bookstore graph
        store = StoreFixture(Store).create_one()
        get_nodeset_for_queryset(Store.objects.filter(pk=store.pk), sync=True)
        permissions = Permission.objects.filter(codename__in=['add_store', 'change_store', 'delete_store'])

        user = get_user_model().objects.latest('pk')
        user.user_permissions.add(*list(permissions))

        # Create an access rule which allows 'add_store' and 'change_store',
        # but not 'delete_store'
        access_rule = AccessRule.objects.create(
            ctype_source=ContentType.objects.get_for_model(user),
            ctype_target=ContentType.objects.get_for_model(Store),
            relation_types=[{'AUTHOR': None}, {'BOOK': None}, {'STORE': None}]
        )
        access_rule.permissions.add(*list(permissions.exclude(codename='delete_store')))

        self.assertTrue(user.has_perm('testapp.add_store', store))
        self.assertTrue(user.has_perm('testapp.change_store', store))
        self.assertFalse(user.has_perm('testapp.delete_store', store))


text:
from __future__ import print_function

import os
import yaml

from rospkg import RosPack, RosStack, ResourceNotFound

BASE_URL = 'https://github.com/ros/rosdistro/raw/master/rosdep/base.yaml'
PYTHON_URL = 'https://github.com/ros/rosdistro/raw/master/rosdep/python.yaml'

def get_test_dir():
    return os.path.abspath(os.path.dirname(__file__))

def get_test_tree_dir():
    return os.path.abspath(os.path.join(os.path.dirname(__file__), 'tree'))

def get_cache_dir():
    p = os.path.join(get_test_dir(), 'sources_cache')
    assert os.path.isdir(p)
    return p

def create_test_SourcesListLoader():
    from rosdep2.sources_list import SourcesListLoader
    return SourcesListLoader.create_default(sources_cache_dir=get_cache_dir(), verbose=True)

def get_cache_raw():
    cache_rosdep_path = os.path.join(get_cache_dir(), '0a12d6e7b0d47be9b76e7726720e4cb79528cbaa')
    with open(cache_rosdep_path) as f:
        cache_raw = yaml.load(f.read())
    return cache_raw

def get_cache_raw_python():
    cache_rosdep_path = os.path.join(get_cache_dir(), 'f6f4ef95664e373cd4754501337fa217f5b55d91')
    with open(cache_rosdep_path) as f:
        cache_raw = yaml.load(f.read())
    return cache_raw

def get_test_rospkgs():
    test_dir = get_test_tree_dir()
    ros_root = os.path.join(test_dir, 'ros')
    ros_package_path = os.path.join(test_dir, 'stacks')
    ros_paths = [ros_root, ros_package_path]
    rospack = RosPack(ros_paths=ros_paths)
    rosstack = RosStack(ros_paths=ros_paths)
    return rospack, rosstack

FAKE_TINYXML_RULE = """testtinyxml:
  ubuntu:
    lucid:
      apt:
        packages: libtinyxml-dev
  debian: libtinyxml-dev
  osx:
    source:
      uri: 'http://kforge.ros.org/rosrelease/viewvc/sourcedeps/tinyxml/tinyxml-2.6.2-1.rdmanifest'
      md5sum: 13760e61e08c9004493c302a16966c42
  fedora:
    yum:
      packages: tinyxml-devel"""

def test_RosdepDefinition():
    from rosdep2.lookup import RosdepDefinition, ResolutionError, InvalidData
    d = dict(a=1, b=2, c=3)
    def1 = RosdepDefinition('d', d)
    assert def1.rosdep_key == 'd'
    assert def1.data == d
    def2 = RosdepDefinition('d', d, 'file1.txt')
    assert def2.rosdep_key == 'd'
    assert def2.data == d
    assert def2.origin == 'file1.txt'

    # test get_rule_for_platform
    #  - test w/invalid data
    try:
        RosdepDefinition('dbad', 'foo', 'bad.txt').get_rule_for_platform('ubuntu', 'hardy', ['apt'], 'apt')
        assert False, "should have failed"
    except InvalidData: pass
    try:
        RosdepDefinition('dbad', {'ubuntu': 1}, 'bad2.txt').get_rule_for_platform('ubuntu', 'hardy', ['apt'], 'apt')
        assert False, "should have failed"
    except InvalidData: pass
    try:
        RosdepDefinition('dbad', {'ubuntu': {'hardy': 1}}, 'bad2.txt').get_rule_for_platform('ubuntu', 'hardy', ['apt'], 'apt')
        assert False, "should have failed"
    except InvalidData: pass

    #  - test w/valid data
    d2 = yaml.load(FAKE_TINYXML_RULE)['testtinyxml']
    definition = RosdepDefinition('d2', d2, 'file2.txt')
    #  - tripwire
    str(definition)

    val = definition.get_rule_for_platform('fedora', 'fake-version', ['yum', 'source', 'pip'], 'yum')
    assert val == ('yum', dict(packages='tinyxml-devel')), val

    val = definition.get_rule_for_platform('debian', 'sid', ['apt', 'source', 'pip'], 'apt')
    assert val == ('apt', 'libtinyxml-dev')

    val = definition.get_rule_for_platform('ubuntu', 'lucid', ['apt', 'source', 'pip'], 'apt')
    assert val == ('apt', dict(packages='libtinyxml-dev')), val

    val = definition.get_rule_for_platform('osx', 'snow', ['macports', 'source', 'pip'], 'macports')
    assert val == ('source', dict(md5sum='13760e61e08c9004493c302a16966c42', uri='http://kforge.ros.org/rosrelease/viewvc/sourcedeps/tinyxml/tinyxml-2.6.2-1.rdmanifest')), val

    # test bad resolutions
    try:
        val = definition.get_rule_for_platform('ubuntu', 'hardy', ['apt', 'source', 'pip'], 'apt')
        assert False, "should have raised: %s"%(str(val))
    except ResolutionError as e:
        assert e.rosdep_key == 'd2'
        assert e.rosdep_data == d2
        assert e.os_name == 'ubuntu'
        assert e.os_version == 'hardy'
        # tripwire
        str(e)

    try:
        val = definition.get_rule_for_platform('fakeos', 'fakeversion', ['apt', 'source', 'pip'], 'apt')
        assert False, "should have raised: %s"%(str(val))
    except ResolutionError as e:
        assert e.rosdep_key == 'd2'
        assert e.rosdep_data == d2
        assert e.os_name == 'fakeos'
        assert e.os_version == 'fakeversion'
        # tripwire
        str(e)

    # test reverse merging OS things (first is default)
    definition = RosdepDefinition('test', {'debian': 'libtest-dev'}, 'fake-1.txt')
    # rule should work as expected before reverse-merge
    val = definition.get_rule_for_platform('debian', 'sid', ['apt', 'source', 'pip'], 'apt')
    assert val == ('apt', 'libtest-dev'), val
    try:
        val = definition.get_rule_for_platform('ubuntu', 'precise', ['apt', 'source', 'pip'], 'apt')
        assert False, "should have failed"
    except ResolutionError as e:
        assert e.rosdep_key == 'test'
        assert e.os_name == 'ubuntu'
        assert e.os_version == 'precise'
        # tripwire?
        str(e)
    definition.reverse_merge({'ubuntu': {'precise': {'apt': 'ros-fuerte-test'}}}, 'fake-gbp.yaml')
    val = definition.get_rule_for_platform('ubuntu', 'precise', ['apt', 'source', 'pip'], 'apt')
    assert val == ('apt', 'ros-fuerte-test'), val
    val = definition.get_rule_for_platform('debian', 'sid', ['apt', 'source', 'pip'], 'apt')
    assert val == ('apt', 'libtest-dev'), val

def test_RosdepView_merge():
    from rosdep2.model import RosdepDatabaseEntry
    from rosdep2.lookup import RosdepView

    # rosdep data must be dictionary of dictionaries
    data = dict(a=dict(x=1), b=dict(y=2), c=dict(z=3))

    # create empty view and test
    view = RosdepView('common')
    assert len(view.keys()) == 0
    # - tripwire
    str(view)

    # make sure lookups fail if not found
    try:
        view.lookup('notfound')
        assert False, "should have raised KeyError"
    except KeyError as e:
        assert 'notfound' in str(e)

    # merge into empty view
    d = RosdepDatabaseEntry(data, [], 'origin')
    view.merge(d)
    assert set(view.keys()) == set(data.keys())
    for k, v in data.items():
        assert view.lookup(k).data == v, "%s vs. %s"%(view.lookup(k), v)

    # merge exact same data
    d2 = RosdepDatabaseEntry(data, [], 'origin2')
    view.merge(d2)
    assert set(view.keys()) == set(data.keys())
    for k, v in data.items():
        assert view.lookup(k).data == v

    # merge new for 'd', 'e'
    d3 = RosdepDatabaseEntry(dict(d=dict(o=4), e=dict(p=5)), [], 'origin3')
    view.merge(d3)
    assert set(view.keys()) == set(list(data.keys()) + ['d', 'e'])
    for k, v in data.items():
        assert view.lookup(k).data == v
    assert view.lookup('d').data == dict(o=4)
    assert view.lookup('e').data == dict(p=5)

    # merge different data for 'a'
    d4 = RosdepDatabaseEntry(dict(a=dict(x=2)), [], 'origin4')
    # - first w/o override, should not bump
    view.merge(d4, override=False)
    assert view.lookup('a').data == dict(x=1), view.lookup('a').data
    assert view.lookup('b').data == dict(y=2)
    assert view.lookup('c').data == dict(z=3)
    assert view.lookup('d').data == dict(o=4)
    assert view.lookup('e').data == dict(p=5)

    # - now w/ override
    view.merge(d4, override=True)
    assert view.lookup('a').data == dict(x=2)
    assert view.lookup('b').data == dict(y=2)
    assert view.lookup('c').data == dict(z=3)
    assert view.lookup('d').data == dict(o=4)
    assert view.lookup('e').data == dict(p=5)

    # - tripwire
    str(view)

def test_RosdepLookup_get_rosdeps():
    from rosdep2.loader import RosdepLoader
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rospack,
                                             sources_loader=sources_loader)
    assert lookup.get_loader() is not None
    assert isinstance(lookup.get_loader(), RosdepLoader)
    print(lookup.get_rosdeps('empty_package'))
    assert lookup.get_rosdeps('empty_package') == []

    try:
        assert lookup.get_rosdeps('not a resource') == []
        assert False, "should have raised"
    except ResourceNotFound:
        pass

    print(lookup.get_rosdeps('stack1_p1'))
    assert set(lookup.get_rosdeps('stack1_p1')) == set(['stack1_dep1', 'stack1_p1_dep1', 'stack1_p1_dep2'])
    assert set(lookup.get_rosdeps('stack1_p1', implicit=False)) == set(['stack1_dep1', 'stack1_p1_dep1', 'stack1_p1_dep2'])

    print(lookup.get_rosdeps('stack1_p2'))
    assert set(lookup.get_rosdeps('stack1_p2', implicit=False)) == set(['stack1_dep1', 'stack1_dep2', 'stack1_p2_dep1']), set(lookup.get_rosdeps('stack1_p2'))
    assert set(lookup.get_rosdeps('stack1_p2', implicit=True)) == set(['stack1_dep1', 'stack1_dep2', 'stack1_p1_dep1', 'stack1_p1_dep2', 'stack1_p2_dep1']), set(lookup.get_rosdeps('stack1_p2'))

def test_RosdepLookup_get_resources_that_need():
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rospack,
                                             sources_loader=sources_loader)

    assert lookup.get_resources_that_need('fake') ==  []
    assert set(lookup.get_resources_that_need('stack1_dep1')) ==  set(['stack1_p1', 'stack1_p2'])
    assert lookup.get_resources_that_need('stack1_dep2') ==  ['stack1_p2']
    assert lookup.get_resources_that_need('stack1_p1_dep1') ==  ['stack1_p1']

def test_RosdepLookup_create_from_rospkg():
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    # these are just tripwire, can't actually test as it depends on external env
    lookup = RosdepLookup.create_from_rospkg()

    lookup = RosdepLookup.create_from_rospkg(rospack=rospack)
    assert rospack == lookup.loader._rospack

    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack)
    assert rospack == lookup.loader._rospack
    assert rosstack == lookup.loader._rosstack

def test_RosdepLookup_get_rosdep_view_for_resource():
    from rosdep2.lookup import RosdepLookup
    from rosdep2.rospkg_loader import DEFAULT_VIEW_KEY, RosPkgLoader
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)
    # assumption of our tests
    assert isinstance(lookup.loader, RosPkgLoader)

    # depends on nothing
    cache_raw = get_cache_raw()
    py_cache_raw = get_cache_raw_python()
    # - first pass: no cache
    ros_view = lookup.get_rosdep_view_for_resource('roscpp_fake')
    libtool = ros_view.lookup('testlibtool')
    assert BASE_URL == libtool.origin
    assert cache_raw['testlibtool'] == libtool.data
    python = ros_view.lookup('testpython')
    assert PYTHON_URL == python.origin
    assert py_cache_raw['testpython'] == python.data

    # package not in stack, should return
    assert lookup.get_rosdep_view_for_resource('just_a_package').name is DEFAULT_VIEW_KEY

def test_RosdepLookup_get_rosdep_view():
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)

    # depends on nothing
    cache_raw = get_cache_raw()
    py_cache_raw = get_cache_raw_python()
    # - first pass: no cache
    ros_view = lookup.get_rosdep_view('ros')
    libtool = ros_view.lookup('testlibtool')
    assert BASE_URL == libtool.origin
    assert cache_raw['testlibtool'] == libtool.data
    python = ros_view.lookup('testpython')
    assert PYTHON_URL == python.origin
    assert py_cache_raw['testpython'] == python.data, python.data

    # - second pass: with cache
    ros_view = lookup.get_rosdep_view('ros')
    libtool = ros_view.lookup('testlibtool')
    assert BASE_URL == libtool.origin
    assert cache_raw['testlibtool'] == libtool.data

    # depends on ros
    stack1_view = lookup.get_rosdep_view('stack1')
    stack1_rosdep_path = os.path.join(rosstack.get_path('stack1'), 'rosdep.yaml')

    # - make sure ros data is available
    libtool = stack1_view.lookup('testlibtool')
    assert BASE_URL == libtool.origin
    assert cache_raw['testlibtool'] == libtool.data
    python = stack1_view.lookup('testpython')
    assert PYTHON_URL == python.origin
    assert py_cache_raw['testpython'] == python.data

def test_RosdepLookup_get_errors():
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()
    tree_dir = get_test_tree_dir()
    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)

    # shouldn't be any errors (yet)
    assert lookup.get_errors() == []

    # force errors
    lookup._load_all_views(lookup.loader)

    #TODO: force errors.  Previous tests relied on bad stack views.
    #Now we need a bad sources cache.

def test_RosdepLookup_get_views_that_define():
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()
    tree_dir = get_test_tree_dir()
    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)

    val = lookup.get_views_that_define('testboost')
    assert len(val) == 1
    entry = val[0]
    assert entry == (BASE_URL, BASE_URL), entry

    val = lookup.get_views_that_define('testpython')
    assert len(val) == 1
    entry = val[0]
    assert entry == (PYTHON_URL, PYTHON_URL), entry

def test_RosdepLookup_resolve_all_errors():
    from rosdep2.installers import InstallerContext
    from rosdep2.lookup import RosdepLookup, ResolutionError
    rospack, rosstack = get_test_rospkgs()
    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)
    # the installer context has nothing in it, lookups will fail
    installer_context = InstallerContext()
    installer_context.set_os_override('ubuntu', 'lucid')

    resolutions, errors = lookup.resolve_all(['rospack_fake'], installer_context)
    assert 'rospack_fake' in errors

    resolutions, errors = lookup.resolve_all(['not_a_resource'], installer_context)
    assert 'not_a_resource' in errors, errors

def test_RosdepLookup_resolve_errors():
    from rosdep2.installers import InstallerContext
    from rosdep2.lookup import RosdepLookup, ResolutionError
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)
    # the installer context has nothing in it, lookups will fail
    installer_context = InstallerContext()
    installer_context.set_os_override('ubuntu', 'lucid')

    try:
        lookup.resolve('testtinyxml', 'rospack_fake', installer_context)
        assert False, "should have raised"
    except ResolutionError as e:
        assert "Unsupported OS" in str(e), str(e)

    try:
        lookup.resolve('fakedep', 'rospack_fake', installer_context)
        assert False, "should have raised"
    except ResolutionError as e:
        assert "Cannot locate rosdep definition" in str(e), str(e)

def test_RosdepLookup_resolve():
    from rosdep2 import create_default_installer_context
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)
    installer_context = create_default_installer_context()
    installer_context.set_os_override('ubuntu', 'lucid')

    # repeat for caching
    for count in range(0, 2):
        installer_key, resolution, dependencies = lookup.resolve('testtinyxml', 'rospack_fake', installer_context)
        assert 'apt' == installer_key
        assert ['libtinyxml-dev'] == resolution
        assert [] == dependencies

        installer_key, resolution, dependencies = lookup.resolve('testboost', 'roscpp_fake', installer_context)
        assert 'apt' == installer_key
        assert ['libboost1.40-all-dev'] == resolution
        assert [] == dependencies

        installer_key, resolution, dependencies = lookup.resolve('testlibtool', 'roscpp_fake', installer_context)
        assert 'apt' == installer_key
        assert set(['libtool', 'libltdl-dev']) == set(resolution)
        assert [] == dependencies

def test_RosdepLookup_resolve_all():
    from rosdep2 import create_default_installer_context
    from rosdep2.lookup import RosdepLookup
    rospack, rosstack = get_test_rospkgs()

    sources_loader = create_test_SourcesListLoader()
    lookup = RosdepLookup.create_from_rospkg(rospack=rospack, rosstack=rosstack,
                                             sources_loader=sources_loader)
    installer_context = create_default_installer_context()
    installer_context.set_os_override('ubuntu', 'lucid')

    # repeat for caching
    lookup.verbose = True
    for count in range(0, 2):
        resolutions, errors = lookup.resolve_all(['rospack_fake', 'roscpp_fake'], installer_context)
        assert not errors, errors
        installer_keys, resolveds = zip(*resolutions)
        assert 'apt' in installer_keys
        apt_resolutions = []
        for k, v in resolutions:
            if k == 'apt':
                apt_resolutions.extend(v)
        assert set(apt_resolutions) == set(['libtinyxml-dev', 'libboost1.40-all-dev', 'libtool', 'libltdl-dev']), set(apt_resolutions)


text:
package org.opentosca.toscana.core.transformation;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

import org.opentosca.toscana.core.BaseUnitTest;
import org.opentosca.toscana.core.csar.Csar;
import org.opentosca.toscana.core.csar.CsarDao;
import org.opentosca.toscana.core.csar.CsarImpl;
import org.opentosca.toscana.core.parse.InvalidCsarException;
import org.opentosca.toscana.core.transformation.logging.Log;
import org.opentosca.toscana.core.transformation.platform.PlatformService;
import org.opentosca.toscana.core.util.Preferences;
import org.opentosca.toscana.model.EffectiveModel;
import org.opentosca.toscana.model.EffectiveModelFactory;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.opentosca.toscana.core.testdata.TestPlugins.PLATFORM1;

public class TransformationDaoUnitTest extends BaseUnitTest {

    @Mock
    private Preferences preferences;
    @Mock
    private PlatformService platformService;
    @Mock
    private CsarDao csarDao;
    private File platformDir;
    private Transformation transformation;
    private Csar csar;
    private TransformationDao dao;

    @Before
    public void setUp() throws IOException, InvalidCsarException {
        when(platformService.findPlatformById(PLATFORM1.id)).thenReturn(Optional.ofNullable(PLATFORM1));
        when(preferences.getDataDir()).thenReturn(tmpdir);
        Log log = logMock();
        csar = spy(new CsarImpl(new File(""), "csarIdentifier", log));
        doReturn(new File("")).when(csar).getTemplate();
        File csarTransformationDir = new File(tmpdir, "transformationDir");
        csarTransformationDir.mkdir();
        when(csarDao.getTransformationsDir(csar)).thenReturn(csarTransformationDir);
        platformDir = new File(csarTransformationDir, PLATFORM1.id);
        platformDir.mkdir();
        File someTransformationFile = new File(platformDir, "some-file");
        someTransformationFile.createNewFile();
        EffectiveModelFactory modelFactory = mock(EffectiveModelFactory.class);
        EffectiveModel model = modelMock();
        when(modelFactory.create(any(File.class), any(Log.class))).thenReturn(model);

        dao = new TransformationFilesystemDao(platformService, modelFactory);
        dao.setCsarDao(csarDao);
    }

    @Test
    public void initializeTransformationStateDone() throws IOException {
        // create fake transformation on disk
        String successfulArtifactName = "csarname-platformid_somedate.zip";
        // assert filename for test data is correct
        assertTrue(successfulArtifactName.matches(TransformationFilesystemDao.ARTIFACT_SUCCESSFUL_REGEX));
        File artifactFileSuccess = new File(platformDir, successfulArtifactName);
        artifactFileSuccess.createNewFile();

        transformation = dao.find(csar, PLATFORM1).get();

        assertEquals(TransformationState.DONE, transformation.getState());
        assertTrue(transformation.getTargetArtifact().isPresent());
    }

    @Test
    public void initializeTransformationStateError() throws IOException {
        // create fake failed transformation on disk
        String failedArtifactName = "csarname-platformid_somedate_failed.zip";
        assertTrue(failedArtifactName.matches(TransformationFilesystemDao.ARTIFACT_FAILED_REGEX));
        File artifactFileFailed = new File(platformDir, failedArtifactName);
        artifactFileFailed.createNewFile();

        transformation = dao.find(csar, PLATFORM1).get();

        assertEquals(TransformationState.ERROR, transformation.getState());
        assertTrue(transformation.getTargetArtifact().isPresent());
    }
}


text:
<!--
  ~ Copyright (c) 2017.
  ~ By chinaume@163.com
  -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.goav.helper">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:supportsRtl="true">

    </application>

</manifest>


text:
from datetime import datetime

from ..extensions import db

class Notification(db.Model):
    __tablename__ = "notifications"
    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime(), default=datetime.now)
    message = db.Column(db.String(255), nullable=False)
    category = db.Column(db.String(32))
    action = db.Column(db.String(32))
    seen = db.Column(db.Boolean(), default=False)
    # Relations
    user_id = db.Column(db.Integer(),
                        db.ForeignKey('users.id'))

    def __init__(self, *args, **kwargs):
        super(Notification, self).__init__(*args, **kwargs)

    def __repr__(self):
        return u"<Notification #{0}>".format(self.id)


text:
package com.google.api.ads.dfp.jaxws.v201508;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for OrderError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="OrderError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UPDATE_CANCELED_ORDER_NOT_ALLOWED"/>
 *     <enumeration value="UPDATE_PENDING_APPROVAL_ORDER_NOT_ALLOWED"/>
 *     <enumeration value="UPDATE_ARCHIVED_ORDER_NOT_ALLOWED"/>
 *     <enumeration value="CANNOT_MODIFY_PROPOSAL_ID"/>
 *     <enumeration value="PRIMARY_USER_REQUIRED"/>
 *     <enumeration value="PRIMARY_USER_CANNOT_BE_SECONDARY"/>
 *     <enumeration value="ORDER_TEAM_NOT_ASSOCIATED_WITH_ADVERTISER"/>
 *     <enumeration value="USER_NOT_ON_ORDERS_TEAMS"/>
 *     <enumeration value="AGENCY_NOT_ON_ORDERS_TEAMS"/>
 *     <enumeration value="INVALID_FIELDS_SET_FOR_NON_PROGRAMMATIC_ORDER"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "OrderError.Reason")
@XmlEnum
public enum OrderErrorReason {

    /**
     *
     *                 Updating a canceled order is not allowed.
     *
     *
     */
    UPDATE_CANCELED_ORDER_NOT_ALLOWED,

    /**
     *
     *                 Updating an order that has its approval pending is not allowed.
     *
     *
     */
    UPDATE_PENDING_APPROVAL_ORDER_NOT_ALLOWED,

    /**
     *
     *                 Updating an archived order is not allowed.
     *
     *
     */
    UPDATE_ARCHIVED_ORDER_NOT_ALLOWED,

    /**
     *
     *                 DSM can set the proposal ID only at the time of creation of order.
     *                 Setting or changing proposal ID at the time of order update is not
     *                 allowed.
     *
     *
     */
    CANNOT_MODIFY_PROPOSAL_ID,

    /**
     *
     *                 Cannot have secondary user without a primary user.
     *
     *
     */
    PRIMARY_USER_REQUIRED,

    /**
     *
     *                 Primary user cannot be added as a secondary user too.
     *
     *
     */
    PRIMARY_USER_CANNOT_BE_SECONDARY,

    /**
     *
     *                 A team associated with the order must also be associated with the
     *                 advertiser.
     *
     *
     */
    ORDER_TEAM_NOT_ASSOCIATED_WITH_ADVERTISER,

    /**
     *
     *                 The user assigned to the order, like salesperson or trafficker, must
     *                 be on one of the order's teams.
     *
     *
     */
    USER_NOT_ON_ORDERS_TEAMS,

    /**
     *
     *                 The agency assigned to the order must belong to one of the order's teams.
     *
     *
     */
    AGENCY_NOT_ON_ORDERS_TEAMS,

    /**
     *
     *                 Programmatic info fields should not be set for a non-programmatic order.
     *
     *
     */
    INVALID_FIELDS_SET_FOR_NON_PROGRAMMATIC_ORDER,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static OrderErrorReason fromValue(String v) {
        return valueOf(v);
    }

}


text:
<TITLE>Review for Preacher's Wife, The (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Preacher's Wife, The (1996)

reviewed by
Tim Voon

                        THE PREACHER'S WIFE 1996
                      A film review by Timothy Voon
                       Copyright 1997 Timothy Voon
         One :-) for Whitney's singing and the Grey Armani Suit

Cast: Denzel Washington, Whitney Houston, Courtney B. Vance, Gregory
Hines, Jenifer Lewis, Loretta Devine, Justin Pierre Edmund Director:
Penny Marshall Screenplay: Nat Mauldin and Allan Scott based on a
screenplay by Robert E. Sherwood and Leonardo Bercovici

"Father I ask of You this day,
Keep my loved ones safe and guide their ways.
Bless the selfless heart that freely gives,
And strengthen those who truthfully live.
Bid your angels to watch these humble souls,
And send that angel 'Dudley' to fulfil Your goals ."
   Amen. A prayer by TMT Voon.

Angels once walked on the earth as did men. Able to disguise themselves
as human kind they walked unnoticed amongst the people doing God's
bidding. Whether you believe there are angels or not, does not
discourage the hope of some, that these messengers of God protect and
encourage His own. So when the pastor of a rough neighbourhood begins
to feel the emotional and physical drains of daily service to the
community, God sends an angel called 'Dudley' to help lighten his
burdens.

Denzel Washington is the cuddly 'Dudley', wearing a very well made,
?Armani? grey suit with matching tie and overcoat. This suit is the envy
of every well dressed person; and since Whitney Houston has good taste
in clothes, she just can't keep her hands of this cuddly 'Dudley' in the
Armani. Whitney goes shopping with the angel in the grey suit. Then goes
dancing with the angel still in the grey suit, before skating with the
angel who is still wearing the grey suit. One wonders at this stage
whether this angel has anything to wear beside the grey suit????

This movie is another well-meant project by Penny Marshall which has
perhaps fallen short of great expectations. I'm not sure whether Whitney
gave them hell on the set of this movie, but she sure sings like an
angel. Denzel smiles sweetly, and is all pleasantness as the angel
Dudley. However, such restraint begins to wear thin behind those
white-tooth grins - let that 'Devil In A Blue Dress' out Denzel.

To the depressed and disillusioned pastors of this world, I have a few
simple words of advice. The business of church work, sacrifice and
giving is an important testimony for the Christian faith, but don't
forget why you are doing it in the first place. Like any other job, one
needs to rest, or you'll end up neglecting yourself and your family.
Remember even God needed a "Kit Kat" on that 7th day.

Timothy Voon
e-mail: stirling@netlink.com.au

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.vladmihalcea.flexypool;

import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * DataSourceIntegrationTest - DataSource Integration Test
 *
 * @author Vlad Mihalcea
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-test.xml")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class DataSourceIntegrationTest extends AbstractPoolAdapterIntegrationTest {

    protected boolean hasMoreConnections(int index) {
        return index < 5;
    }
}


text:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/fragment_search"
          android:name="com.slavaware.spotifystreamer.fragments.SpotifySearchFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginLeft="16dp"
          android:layout_marginRight="16dp"
          tools:context="com.slavaware.spotifystreamer.fragments.SpotifySearchFragment"
          tools:layout="@android:layout/list_content" />


text:
__author__ = 'ariyatan'
import csv

#list of adjectives that have synthetic forms of degree of comparison
synth_form_list = []
with open('adj_comp_ex.csv', 'rb') as dc:
    for line in dc:
        synth_form_list.append(line[:-1])
        #I use [:-1] to get rid of '\n' symbol at the end of each row

#list of adjectives that double last consonant in synthetic form
double_cons_list = []
with open('adj_double_consonant.csv', 'rb') as lst:
    for line in lst:
        double_cons_list.append(line[:-1])
        #I use [:-1] to get rid of '\n' symbol at the end of each row

#stem ending in 'y' don't change if it's part of a diphtong and follows a vowel
no_change_list = ['shy', 'gray', 'sly', 'spry', 'wry']

#Synthetic forms are by adjectives with 1-syllable stem, or with 2-syllable stem, if it ends in 'er' (like 'clever'), 'y' (like 'dirty'), 'le' (like 'simple') or 'ow' (like 'narrow')
#Adjectives of 2 and more syllables usually have analytic forms of comparison

class adj_form(object):
    def __init__(self, stem, degree = '0'):
        self.stem = stem
        self.degree = degree

    def add_er(self):
        if self.stem[-1] == 'y':
            if self.stem in no_change_list:
                return self.stem + 'er'
            else:
                return self.stem[:-1] + 'ier'
        if self.stem[-1] == 'e':
            return self.stem + 'r'
        if self.stem in double_cons_list:
            return self.stem + self.stem[-1] + 'er'
        else:
            return self.stem + 'er'

    def add_est(self):
        if self.stem[-1] == 'y':
            if self.stem in no_change_list:
                return self.stem + 'er'
            else:
                return self.stem[:-1] + 'iest'
        if self.stem[-1] == 'e':
            return self.stem + 'st'
        if self.stem in double_cons_list:
            return self.stem + self.stem[-1] + 'est'
        else:
            return self.stem + 'est'

    def comparative(self):
        if self.stem == 'good':
            return 'better'
        if self.stem == 'bad':
            return 'worse'
        if self.stem == 'little':
            return 'lesser'
        if self.stem in synth_form_list:
            return self.add_er()
        else:
            return 'more' + ' ' + self.stem

    def superlative(self):
        if self.stem == 'good':
            return 'best'
        if self.stem == 'bad':
            return 'worst'
        if self.stem == 'little':
            return 'least'
        if self.stem in synth_form_list:
            return self.add_est()
        else:
            return 'the most' + ' ' + self.stem


text:
from oslo_log import log as logging

from django.core.exceptions import ValidationError
from django.utils import safestring
from django.utils.translation import gettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import workflows
from openstack_dashboard.api import neutron

from sahara_dashboard.api import sahara as saharaclient
from sahara_dashboard import utils

LOG = logging.getLogger(__name__)

class Parameter(object):
    def __init__(self, config):
        self.name = config['name']
        self.description = config.get('description', "No description")
        self.required = not config['is_optional']
        self.default_value = config.get('default_value', None)
        self.initial_value = self.default_value
        self.param_type = config['config_type']
        self.priority = int(config.get('priority', 2))
        self.choices = config.get('config_values', None)

def build_control(parameter):
    attrs = {"priority": parameter.priority,
             "placeholder": parameter.default_value}
    if parameter.param_type == "string":
        return forms.CharField(
            widget=forms.TextInput(attrs=attrs),
            label=parameter.name,
            required=(parameter.required and
                      parameter.default_value is None),
            help_text=parameter.description,
            initial=parameter.initial_value)

    if parameter.param_type == "int":
        return forms.IntegerField(
            widget=forms.TextInput(attrs=attrs),
            label=parameter.name,
            required=parameter.required,
            help_text=parameter.description,
            initial=parameter.initial_value)

    elif parameter.param_type == "bool":
        return forms.BooleanField(
            widget=forms.CheckboxInput(attrs=attrs),
            label=parameter.name,
            required=False,
            initial=parameter.initial_value,
            help_text=parameter.description)

    elif parameter.param_type == "dropdown":
        return forms.ChoiceField(
            widget=forms.Select(attrs=attrs),
            label=parameter.name,
            required=parameter.required,
            choices=parameter.choices,
            help_text=parameter.description)

def _create_step_action(name, title, parameters, advanced_fields=None,
                        service=None):
    class_fields = {}
    contributes_field = ()
    for param in parameters:
        field_name = "CONF:" + service + ":" + param.name
        contributes_field += (field_name,)
        class_fields[field_name] = build_control(param)

    if advanced_fields is not None:
        for ad_field_name, ad_field_value in advanced_fields:
            class_fields[ad_field_name] = ad_field_value

    action_meta = type('Meta', (object, ),
                       dict(help_text_template=("nodegroup_templates/"
                                                "_fields_help.html")))

    class_fields['Meta'] = action_meta
    action = type(str(title),
                  (workflows.Action,),
                  class_fields)

    step_meta = type('Meta', (object,), dict(name=title))
    step = type(str(name),
                (workflows.Step, ),
                dict(name=name,
                     process_name=name,
                     action_class=action,
                     contributes=contributes_field,
                     Meta=step_meta))

    return step

def build_node_group_fields(action, name, template, count, serialized=None):
    action.fields[name] = forms.CharField(
        label=_("Name"),
        widget=forms.TextInput())

    action.fields[template] = forms.CharField(
        label=_("Node group cluster"),
        widget=forms.HiddenInput())

    action.fields[count] = forms.IntegerField(
        label=_("Count"),
        min_value=0,
        widget=forms.HiddenInput())
    action.fields[serialized] = forms.CharField(
        widget=forms.HiddenInput())

def build_interface_argument_fields(
        action, name, description, mapping_type, location, value_type,
        required, default_value):
    action.fields[name] = forms.CharField(
        label=_("Name"),
        widget=forms.TextInput(),
        required=True)
    action.fields[description] = forms.CharField(
        label=_("Description"),
        widget=forms.TextInput(),
        required=False)
    action.fields[mapping_type] = forms.ChoiceField(
        label=_("Mapping Type"),
        widget=forms.Select(),
        required=True,
        choices=[("args", _("Positional Argument")),
                 ("configs", _("Configuration Value")),
                 ("params", _("Named Parameter"))])
    action.fields[location] = forms.CharField(
        label=_("Location"),
        widget=forms.TextInput(),
        required=True)
    action.fields[value_type] = forms.ChoiceField(
        label=_("Value Type"),
        widget=forms.Select(),
        required=True,
        choices=[("string", _("String")),
                 ("number", _("Number")),
                 ("data_source", _("Data Source"))])
    action.fields[required] = forms.BooleanField(
        widget=forms.CheckboxInput(),
        label=_("Required"),
        required=False,
        initial=True)
    action.fields[default_value] = forms.CharField(
        label=_("Default Value"),
        widget=forms.TextInput(),
        required=False)

def parse_configs_from_context(context, defaults):
    configs_dict = dict()
    for key, val in context.items():
        if str(key).startswith("CONF"):
            key_split = str(key).split(":")
            service = key_split[1]
            config = key_split[2]
            if service not in configs_dict:
                configs_dict[service] = dict()
            if val is None:
                continue
            if str(defaults[service][config]) == str(val):
                continue
            configs_dict[service][config] = val
    return configs_dict

def get_security_groups(request, security_group_ids):
    security_groups = []
    for group in security_group_ids or []:
        try:
            security_groups.append(neutron.security_group_get(
                request, group))
        except Exception:
            LOG.info(_('Unable to retrieve security group %(group)s.') %
                     {'group': group})
            security_groups.append({'name': group})

    return security_groups

def get_plugin_and_hadoop_version(request):
    plugin_name = None
    hadoop_version = None
    # In some cases request contains valuable info in both GET and POST methods
    req = request.GET.copy()
    req.update(request.POST)
    if req.get("plugin_name"):
        plugin_name = req["plugin_name"]
        hadoop_version = (
            req.get("plugin_version", None) or req["hadoop_version"]
        )
    return plugin_name, hadoop_version

def clean_node_group(node_group):
    node_group_copy = dict((key, value)
                           for key, value in node_group.items() if value)

    for key in ["id", "created_at", "updated_at"]:
        if key in node_group_copy:
            node_group_copy.pop(key)

    return node_group_copy

def populate_image_choices(self, request, context, empty_choice=False):
    try:
        all_images = saharaclient.image_list(request)

        plugin, hadoop_version = get_plugin_and_hadoop_version(request)

        details = saharaclient.plugin_get_version_details(request,
                                                          plugin,
                                                          hadoop_version)
        choices = [(image.id, image.name) for image in all_images
                   if (set(details.required_image_tags).
                       issubset(set(image.tags)))]
    except Exception:
        exceptions.handle(request,
                          _("Unable to fetch image choices."))
        choices = []
    if empty_choice:
        choices = [(None, _('No image specified'))] + choices
    if not choices:
        choices.append(("", _("No Images Available")))

    return choices

class PluginAndVersionMixin(object):
    def _generate_plugin_version_fields(self, sahara):
        plugins = [p for p in sahara.plugins.list()
                   if is_plugin_not_hidden_for_user(p)]
        plugin_choices = [(plugin.name, plugin.title) for plugin in plugins]

        self.fields["plugin_name"] = forms.ChoiceField(
            label=_("Plugin Name"),
            choices=plugin_choices,
            widget=forms.Select(
                attrs={"class": "plugin_name_choice switchable",
                       'data-slug': 'pluginname'}))

        for plugin in plugins:
            versions = [(version, version)
                        for version in get_enabled_versions(plugin)]
            version_choices = sorted(
                versions,
                reverse=True,
                key=lambda v: utils.smart_sort_helper(v[0]))
            field_name = plugin.name + "_version"
            choice_field = forms.ChoiceField(
                label=_("Version"),
                choices=version_choices,
                widget=forms.Select(
                    attrs={"class": "plugin_version_choice switched "
                           + field_name + "_choice",
                           "data-switch-on": "pluginname",
                           "data-pluginname-%s" % plugin.name: _("Version")})
            )
            self.fields[field_name] = choice_field

class PatchedDynamicWorkflow(workflows.Workflow):
    """Overrides Workflow to fix its issues."""

    def _ensure_dynamic_exist(self):
        if not hasattr(self, 'dynamic_steps'):
            self.dynamic_steps = list()

    def _register_step(self, step):
        # Use that method instead of 'register' to register step.
        # Note that a step could be registered in descendant class constructor
        # only before this class constructor is invoked.
        self._ensure_dynamic_exist()
        self.dynamic_steps.append(step)

    def _order_steps(self):
        # overrides method of Workflow
        # crutch to fix https://bugs.launchpad.net/horizon/+bug/1196717
        # and another not filed issue that dynamic creation of tabs is
        # not thread safe
        self._ensure_dynamic_exist()

        self._registry = dict([(step, step(self))
                               for step in self.dynamic_steps])

        return list(self.default_steps) + self.dynamic_steps

class ServiceParametersWorkflow(PatchedDynamicWorkflow):
    """Base class for Workflows having services tabs with parameters."""

    def _populate_tabs(self, general_parameters, service_parameters):
        # Populates tabs for 'general' and service parameters
        # Also populates defaults and initial values
        self.defaults = dict()

        self._init_step('general', 'General Parameters', general_parameters)

        for service, parameters in service_parameters.items():
            self._init_step(service, service + ' Parameters', parameters)

    def _init_step(self, service, title, parameters):
        if not parameters:
            return

        self._populate_initial_values(service, parameters)

        step = _create_step_action(service, title=title, parameters=parameters,
                                   service=service)

        self.defaults[service] = dict()
        for param in parameters:
            self.defaults[service][param.name] = param.default_value

        self._register_step(step)

    def _set_configs_to_copy(self, configs):
        self.configs_to_copy = configs

    def _populate_initial_values(self, service, parameters):
        if not hasattr(self, 'configs_to_copy'):
            return

        configs = self.configs_to_copy

        for param in parameters:
            if (service in configs and
                    param.name in configs[service]):
                param.initial_value = configs[service][param.name]

class StatusFormatMixin(workflows.Workflow):
    def __init__(self, request, context_seed, entry_point, *args, **kwargs):
        super(StatusFormatMixin, self).__init__(request,
                                                context_seed,
                                                entry_point,
                                                *args,
                                                **kwargs)

    def format_status_message(self, message):
        error_description = getattr(self, 'error_description', None)

        if error_description:
            return error_description
        else:
            return message % self.context[self.name_property]

class ShareWidget(forms.MultiWidget):
    def __init__(self, choices=()):
        widgets = []
        for choice in choices:
            widgets.append(forms.CheckboxInput(
                attrs={
                    "label": choice[1],
                    "value": choice[0],
                }))
            widgets.append(forms.TextInput())
            widgets.append(forms.Select(
                choices=(("rw", _("Read/Write")), ("ro", _("Read only")))))
        super(ShareWidget, self).__init__(widgets)

    def decompress(self, value):
        if value:
            values = []
            for share in value:
                values.append(value[share]["id"])
                values.append(value[share]["path"])
                values.append(value[share]["access_level"])
            return values
        return [None] * len(self.widgets)

    def format_output(self, rendered_widgets):
        output = []
        output.append("
")
        output.append("
Share	Enabled	"
                      "Path	Permissions
")
        for i, widget in enumerate(rendered_widgets):
            item_widget_index = i % 3
            if item_widget_index == 0:
                output.append("
")
                output.append(
                    "%s	" %
                    self.widgets[i].attrs["label"])
            # The last 2 form field td need get a larger size
            if item_widget_index in [1, 2]:
                size = 4
            else:
                size = 2
            output.append("" % size
                          + widget + "	")
            if item_widget_index == 2:
                output.append("
")
        output.append("
")
        return safestring.mark_safe('\n'.join(output))

class MultipleShareChoiceField(forms.MultipleChoiceField):
    def validate(self, value):
        if self.required and not value:
            raise ValidationError(
                self.error_messages['required'], code='required')
        if not isinstance(value, list):
            raise ValidationError(
                _("The value of shares must be a list of values")
            )

def is_plugin_not_hidden_for_user(plugin):
    hidden_lbl = plugin.plugin_labels.get('hidden')
    if hidden_lbl and hidden_lbl['status']:
        return False
    if get_enabled_versions(plugin):
        return True
    return False

def get_enabled_versions(plugin):
    lbs = plugin.version_labels

    versions = []
    for version, data in lbs.items():
        if data.get('enabled', {'status': True}).get('status', True):
            versions.append(version)

    if not plugin.plugin_labels.get(
            'enabled', {'status': True}).get('status', True):
        versions = []
    return versions

def is_version_of_plugin_deprecated(plugin, version):
    lbs = plugin.version_labels
    for iter_version, data in lbs.items():
        if iter_version == version:
            if data.get('deprecated', {'status': False}).get('status', False):
                return True
            else:
                return False


text:
export * from './auth.guard';
export * from './storage.guard';


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/exit_pressed"></item>
    <item android:state_pressed="false" android:drawable="@drawable/exit_default"></item>
    <item android:drawable="@drawable/exit_default"></item>

</selector>


text:
using Orchard.ContentManagement;

namespace Orchard.Layers.Models
{
    public class LayerMetadata : ContentPart
    {
        public string Title { get; set; }
        public bool RenderTitle { get; set; }
        public double Position { get; set; }
		public string Zone { get; set; }
		public string Layer { get; set; }
	}
}


text:
package io.fabric8.openshift.client.mock.impl.doneables;

import io.fabric8.kubernetes.api.builder.Visitor;
import io.fabric8.kubernetes.api.model.Doneable;
import io.fabric8.kubernetes.client.mock.MockDoneable;
import io.fabric8.openshift.api.model.DoneableRoute;
import io.fabric8.openshift.api.model.Route;
import io.fabric8.openshift.api.model.RouteBuilder;
import io.fabric8.openshift.api.model.RouteFluent;
import io.fabric8.openshift.api.model.RouteFluentImpl;
import io.fabric8.openshift.api.model.RouteStatus;
import org.easymock.EasyMock;
import org.easymock.IExpectationSetters;

public class MockDoneableRoute extends RouteFluentImpl<MockDoneableRoute> implements MockDoneable<Route> {

  private interface DelegateInterface extends Doneable<Route>, RouteFluent<DoneableRoute> {}
  private final Visitor<Route> visitor = new Visitor<Route>() {
    @Override
    public void visit(Route pod) {
    }
  };

  private final DelegateInterface delegate;

  public MockDoneableRoute() {
    super(new RouteBuilder()
      .withNewMetadata().endMetadata()
      .withNewSpec().endSpec()
      .withStatus(new RouteStatus())
      .build());
    this.delegate = EasyMock.createMock(DelegateInterface.class);
  }

  @Override
  public IExpectationSetters<Route> done() {
    return EasyMock.expect(delegate.done());
  }

  @Override
  public Void replay() {
    EasyMock.replay(delegate);
    return null;
  }

  @Override
  public void verify() {
    EasyMock.verify(delegate);
  }

  @Override
  public Doneable<Route> getDelegate() {
    return new DoneableRoute(new RouteBuilder(this).build(), visitor) {
      @Override
      public Route done() {
        return delegate.done();
      }
    };
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="allout58.jambot">
    <Appenders>
        <Console name="SysOut" target="SYSTEM_OUT">
            <PatternLayout
                    pattern="[%d{HH:mm:ss}] [%t/%level] [%logger]: %msg%n"/>
        </Console>
        <RollingRandomAccessFile name="File" fileName="logs/latest.log"
                                 filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout
                    pattern="[%d{HH:mm:ss}] [%t/%level] [%logger]: %msg%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <OnStartupTriggeringPolicy/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <Root level="all">
            <!--<AppenderRef ref="SysOut" level="INFO"/>-->
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>


text:
package com.softwaremill.bootzooka.user.application

import java.util.UUID

import com.softwaremill.bootzooka.common.crypto.{Argon2dPasswordHashing, CryptoConfig}
import com.softwaremill.bootzooka.test.{FlatSpecWithDb, TestHelpersWithDb}
import com.typesafe.config.Config
import org.scalatest.{Matchers, OptionValues}

class UserServiceSpec extends FlatSpecWithDb with Matchers with TestHelpersWithDb with OptionValues {

  override protected def beforeEach() = {
    super.beforeEach()

    userDao.add(newUser("Admin", "admin@sml.com", "pass", "salt")).futureValue
    userDao.add(newUser("Admin2", "admin2@sml.com", "pass", "salt")).futureValue
  }

  "registerNewUser" should "add user with unique lowercase login info" in {
    // When
    val result = userService.registerNewUser("John", "newUser@sml.com", "password").futureValue

    // Then
    result should be(UserRegisterResult.Success)

    val userOpt = userDao.findByLowerCasedLogin("John").futureValue
    userOpt should be('defined)
    val user = userOpt.get

    user.login should be("John")
    user.loginLowerCased should be("john")

    emailService.wasEmailSentTo("newUser@sml.com") should be(true)
  }

  "registerNewUser" should "not register a user if a user with the given login/e-mail exists" in {
    // when
    val resultInitial   = userService.registerNewUser("John", "newUser@sml.com", "password").futureValue
    val resultSameLogin = userService.registerNewUser("John", "newUser2@sml.com", "password").futureValue
    val resultSameEmail = userService.registerNewUser("John2", "newUser@sml.com", "password").futureValue

    // then
    resultInitial should be(UserRegisterResult.Success)
    resultSameLogin should matchPattern { case UserRegisterResult.UserExists(_) => }
    resultSameEmail should matchPattern { case UserRegisterResult.UserExists(_) => }

    userDao.findByLoginOrEmail("newUser2@sml.com").futureValue should be(None)
    userDao.findByLoginOrEmail("John2").futureValue should be(None)
  }

  "registerNewUser" should "not schedule an email on existing login" in {
    // When
    userService.registerNewUser("Admin", "secondEmail@sml.com", "password").futureValue

    // Then
    emailService.wasEmailSentTo("secondEmail@sml.com") should be(false)
  }

  "changeEmail" should "change email for specified user" in {
    val user     = userDao.findByLowerCasedLogin("admin").futureValue
    val newEmail = "new@email.com"
    userService.changeEmail(user.get.id, newEmail).futureValue should be('right)
    userDao.findByEmail(newEmail).futureValue match {
      case Some(cu) => // ok
      case None     => fail("User not found. Maybe e-mail wasn't really changed?")
    }
  }

  "changeEmail" should "not change email if already used by someone else" in {
    userService.changeEmail(UUID.randomUUID(), "admin2@sml.com").futureValue should be('left)
  }

  "changeLogin" should "change login for specified user" in {
    val user     = userDao.findByLowerCasedLogin("admin").futureValue
    val newLogin = "newadmin"
    userService.changeLogin(user.get.id, newLogin).futureValue should be('right)
    userDao.findByLowerCasedLogin(newLogin).futureValue match {
      case Some(cu) =>
      case None     => fail("User not found. Maybe login wasn't really changed?")
    }
  }

  "changeLogin" should "not change login if already used by someone else" in {
    userService.changeLogin(UUID.randomUUID(), "admin2").futureValue should be('left)
  }

  "changePassword" should "change password if current is correct and new is present" in {
    // Given
    val user            = userDao.findByLowerCasedLogin("admin").futureValue.get
    val currentPassword = "pass"
    val newPassword     = "newPass"

    // When
    val changePassResult = userService.changePassword(user.id, currentPassword, newPassword).futureValue

    // Then
    changePassResult should be('right)
    userDao.findByLowerCasedLogin("admin").futureValue match {
      case Some(cu) => passwordHashing.verifyPassword(cu.password, newPassword, cu.salt)
      case None     => fail("Something bad happened, maybe mocked Dao is broken?")
    }
  }

  "changePassword" should "not change password if current is incorrect" in {
    // Given
    val user = userDao.findByLowerCasedLogin("admin").futureValue.get

    // When, Then
    userService.changePassword(user.id, "someillegalpass", "newpass").futureValue should be('left)
  }

  "changePassword" should "complain when user cannot be found" in {
    userService.changePassword(UUID.randomUUID(), "pass", "newpass").futureValue should be('left)
  }

  "authenticate" should "rehash password when configuration changes" in {
    //given
    val user = userDao.findByLoginOrEmail("Admin").futureValue.value
    val reconfiguredHashing = new Argon2dPasswordHashing(new CryptoConfig {
      override def rootConfig: Config = ???
      override lazy val iterations    = 3
      override lazy val memory        = 1024
      override lazy val parallelism   = 3
    })
    val reconfiguredUserService = new UserService(userDao, emailService, emailTemplatingEngine, reconfiguredHashing)

    //when
    reconfiguredUserService.authenticate("Admin", "pass").futureValue

    //then
    val updatedUser = userDao.findByLoginOrEmail("Admin").futureValue.value
    updatedUser.password shouldNot be(user.password)
  }

  "authenticate" should "not rehash password for the same configuration" in {
    //given
    val user = userDao.findByLoginOrEmail("Admin").futureValue.value

    //when
    userService.authenticate("Admin", "pass").futureValue

    //then
    val updatedUser = userDao.findByLoginOrEmail("Admin").futureValue.value
    updatedUser.password shouldBe user.password
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright 2015 Synced Synapse. All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/status_bar_latest_event_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/background_floating_material_dark">

    <ImageView android:id="@+id/icon"
        android:layout_width="@dimen/notification_art_default_width"
        android:layout_height="@dimen/notification_art_default_height"
        android:layout_weight="0"
        android:padding="12dp"
        android:scaleType="centerInside"
        android:contentDescription="@string/poster"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="fill_vertical"
        android:minHeight="@dimen/notification_height"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/small_padding"
            android:textAppearance="@style/TextAppearance.Notification.Title"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal"/>
        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/TextAppearance.Notification.Details"
            android:singleLine="true"
            android:fadingEdge="horizontal"
            android:ellipsize="marquee"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/media_actions"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="6dp"
        android:layout_marginEnd="6dp"
        android:layout_gravity="center_vertical|end"
        android:orientation="horizontal"
        android:layoutDirection="ltr">

        <ImageButton
            android:id="@+id/rewind"
            style="@style/Widget.Button.Borderless"
            android:layout_width="@dimen/default_icon_size"
            android:layout_height="match_parent"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:gravity="center"
            android:contentDescription="@string/rewind"/>
        <ImageButton
            android:id="@+id/play"
            style="@style/Widget.Button.Borderless"
            android:layout_width="@dimen/default_icon_size"
            android:layout_height="match_parent"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:gravity="center"
            android:contentDescription="@string/play"/>
        <ImageButton
            android:id="@+id/fast_forward"
            style="@style/Widget.Button.Borderless"
            android:layout_width="@dimen/default_icon_size"
            android:layout_height="match_parent"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:gravity="center"
            android:contentDescription="@string/fast_forward"/>

    </LinearLayout>
</LinearLayout>