text:
import datetime
import random
import uuid

from keystone.common import sql
from keystone.common.sql import migration
from keystone.contrib.oauth1 import core
from keystone import exception
from keystone.openstack.common import jsonutils
from keystone.openstack.common import timeutils

class Consumer(sql.ModelBase, sql.DictBase):
    __tablename__ = 'consumer'
    attributes = ['id', 'description', 'secret']
    id = sql.Column(sql.String(64), primary_key=True, nullable=False)
    description = sql.Column(sql.String(64), nullable=True)
    secret = sql.Column(sql.String(64), nullable=False)
    extra = sql.Column(sql.JsonBlob(), nullable=False)

class RequestToken(sql.ModelBase, sql.DictBase):
    __tablename__ = 'request_token'
    attributes = ['id', 'request_secret',
                  'verifier', 'authorizing_user_id', 'requested_project_id',
                  'role_ids', 'consumer_id', 'expires_at']
    id = sql.Column(sql.String(64), primary_key=True, nullable=False)
    request_secret = sql.Column(sql.String(64), nullable=False)
    verifier = sql.Column(sql.String(64), nullable=True)
    authorizing_user_id = sql.Column(sql.String(64), nullable=True)
    requested_project_id = sql.Column(sql.String(64), nullable=False)
    role_ids = sql.Column(sql.Text(), nullable=True)
    consumer_id = sql.Column(sql.String(64), sql.ForeignKey('consumer.id'),
                             nullable=False, index=True)
    expires_at = sql.Column(sql.String(64), nullable=True)

    @classmethod
    def from_dict(cls, user_dict):
        return cls(**user_dict)

    def to_dict(self):
        return dict(self.iteritems())

class AccessToken(sql.ModelBase, sql.DictBase):
    __tablename__ = 'access_token'
    attributes = ['id', 'access_secret', 'authorizing_user_id',
                  'project_id', 'role_ids', 'consumer_id',
                  'expires_at']
    id = sql.Column(sql.String(64), primary_key=True, nullable=False)
    access_secret = sql.Column(sql.String(64), nullable=False)
    authorizing_user_id = sql.Column(sql.String(64), nullable=False,
                                     index=True)
    project_id = sql.Column(sql.String(64), nullable=False)
    role_ids = sql.Column(sql.Text(), nullable=False)
    consumer_id = sql.Column(sql.String(64), sql.ForeignKey('consumer.id'),
                             nullable=False)
    expires_at = sql.Column(sql.String(64), nullable=True)

    @classmethod
    def from_dict(cls, user_dict):
        return cls(**user_dict)

    def to_dict(self):
        return dict(self.iteritems())

class OAuth1(sql.Base):
    def db_sync(self):
        migration.db_sync()

    def _get_consumer(self, session, consumer_id):
        consumer_ref = session.query(Consumer).get(consumer_id)
        if consumer_ref is None:
            raise exception.NotFound(_('Consumer not found'))
        return consumer_ref

    def get_consumer_with_secret(self, consumer_id):
        session = self.get_session()
        consumer_ref = self._get_consumer(session, consumer_id)
        return consumer_ref.to_dict()

    def get_consumer(self, consumer_id):
        return core.filter_consumer(
            self.get_consumer_with_secret(consumer_id))

    def create_consumer(self, consumer):
        consumer['secret'] = uuid.uuid4().hex
        if not consumer.get('description'):
            consumer['description'] = None
        session = self.get_session()
        with session.begin():
            consumer_ref = Consumer.from_dict(consumer)
            session.add(consumer_ref)
            session.flush()
        return consumer_ref.to_dict()

    def _delete_consumer(self, session, consumer_id):
        consumer_ref = self._get_consumer(session, consumer_id)
        q = session.query(Consumer)
        q = q.filter_by(id=consumer_id)
        q.delete(False)
        session.delete(consumer_ref)

    def _delete_request_tokens(self, session, consumer_id):
        q = session.query(RequestToken)
        req_tokens = q.filter_by(consumer_id=consumer_id)
        req_tokens_list = set([x.id for x in req_tokens])
        for token_id in req_tokens_list:
            token_ref = self._get_request_token(session, token_id)
            q = session.query(RequestToken)
            q = q.filter_by(id=token_id)
            q.delete(False)
            session.delete(token_ref)

    def _delete_access_tokens(self, session, consumer_id):
        q = session.query(AccessToken)
        acc_tokens = q.filter_by(consumer_id=consumer_id)
        acc_tokens_list = set([x.id for x in acc_tokens])
        for token_id in acc_tokens_list:
            token_ref = self._get_access_token(session, token_id)
            q = session.query(AccessToken)
            q = q.filter_by(id=token_id)
            q.delete(False)
            session.delete(token_ref)

    def delete_consumer(self, consumer_id):
        session = self.get_session()
        with session.begin():
            self._delete_request_tokens(session, consumer_id)
            self._delete_access_tokens(session, consumer_id)
            self._delete_consumer(session, consumer_id)
            session.flush()

    def list_consumers(self):
        session = self.get_session()
        cons = session.query(Consumer)
        return [core.filter_consumer(x.to_dict()) for x in cons]

    def update_consumer(self, consumer_id, consumer):
        session = self.get_session()
        with session.begin():
            consumer_ref = self._get_consumer(session, consumer_id)
            old_consumer_dict = consumer_ref.to_dict()
            old_consumer_dict.update(consumer)
            new_consumer = Consumer.from_dict(old_consumer_dict)
            consumer_ref.description = new_consumer.description
            consumer_ref.extra = new_consumer.extra
            session.flush()
        return core.filter_consumer(consumer_ref.to_dict())

    def create_request_token(self, consumer_id, project_id, token_duration):
        expiry_date = None
        if token_duration:
            now = timeutils.utcnow()
            future = now + datetime.timedelta(seconds=token_duration)
            expiry_date = timeutils.isotime(future, subsecond=True)

        ref = {}
        request_token_id = uuid.uuid4().hex
        ref['id'] = request_token_id
        ref['request_secret'] = uuid.uuid4().hex
        ref['verifier'] = None
        ref['authorizing_user_id'] = None
        ref['requested_project_id'] = project_id
        ref['role_ids'] = None
        ref['consumer_id'] = consumer_id
        ref['expires_at'] = expiry_date
        session = self.get_session()
        with session.begin():
            token_ref = RequestToken.from_dict(ref)
            session.add(token_ref)
            session.flush()
        return token_ref.to_dict()

    def _get_request_token(self, session, request_token_id):
        token_ref = session.query(RequestToken).get(request_token_id)
        if token_ref is None:
            raise exception.NotFound(_('Request token not found'))
        return token_ref

    def get_request_token(self, request_token_id):
        session = self.get_session()
        token_ref = self._get_request_token(session, request_token_id)
        return token_ref.to_dict()

    def authorize_request_token(self, request_token_id, user_id,
                                role_ids):
        session = self.get_session()
        with session.begin():
            token_ref = self._get_request_token(session, request_token_id)
            token_dict = token_ref.to_dict()
            token_dict['authorizing_user_id'] = user_id
            token_dict['verifier'] = str(random.randint(1000, 9999))
            token_dict['role_ids'] = jsonutils.dumps(role_ids)

            new_token = RequestToken.from_dict(token_dict)
            for attr in RequestToken.attributes:
                if (attr == 'authorizing_user_id' or attr == 'verifier'
                        or attr == 'role_ids'):
                    setattr(token_ref, attr, getattr(new_token, attr))

            session.flush()
        return token_ref.to_dict()

    def create_access_token(self, request_token_id, token_duration):
        session = self.get_session()
        with session.begin():
            req_token_ref = self._get_request_token(session, request_token_id)
            token_dict = req_token_ref.to_dict()

            expiry_date = None
            if token_duration:
                now = timeutils.utcnow()
                future = now + datetime.timedelta(seconds=token_duration)
                expiry_date = timeutils.isotime(future, subsecond=True)

            # add Access Token
            ref = {}
            access_token_id = uuid.uuid4().hex
            ref['id'] = access_token_id
            ref['access_secret'] = uuid.uuid4().hex
            ref['authorizing_user_id'] = token_dict['authorizing_user_id']
            ref['project_id'] = token_dict['requested_project_id']
            ref['role_ids'] = token_dict['role_ids']
            ref['consumer_id'] = token_dict['consumer_id']
            ref['expires_at'] = expiry_date
            token_ref = AccessToken.from_dict(ref)
            session.add(token_ref)

            # remove request token, it's been used
            q = session.query(RequestToken)
            q = q.filter_by(id=request_token_id)
            q.delete(False)
            session.delete(req_token_ref)

            session.flush()
        return token_ref.to_dict()

    def _get_access_token(self, session, access_token_id):
        token_ref = session.query(AccessToken).get(access_token_id)
        if token_ref is None:
            raise exception.NotFound(_('Access token not found'))
        return token_ref

    def get_access_token(self, access_token_id):
        session = self.get_session()
        token_ref = self._get_access_token(session, access_token_id)
        return token_ref.to_dict()

    def list_access_tokens(self, user_id):
        session = self.get_session()
        q = session.query(AccessToken)
        user_auths = q.filter_by(authorizing_user_id=user_id)
        return [core.filter_token(x.to_dict()) for x in user_auths]

    def delete_access_token(self, user_id, access_token_id):
        session = self.get_session()
        with session.begin():
            token_ref = self._get_access_token(session, access_token_id)
            token_dict = token_ref.to_dict()
            if token_dict['authorizing_user_id'] != user_id:
                raise exception.Unauthorized(_('User IDs do not match'))

            q = session.query(AccessToken)
            q = q.filter_by(id=access_token_id)
            q.delete(False)

            session.delete(token_ref)
            session.flush()


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserVoteTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_vote', function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->integer('vote_id')->unsigned();
            $table->string('vote_type', 4);

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('vote_id')->references('id')->on('votes')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('user_vote');
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Hart 55th Anniversary
date: 2016-05-24
author: Edward Olsen
tags: weekly links, java
status: published
summary: Phasellus ac efficitur felis, ut maximus eros. Donec.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 08/10/2018
  endDate: 08/12/2018
  ctyhocn: BUFWSHX
  groupCode: H5A
published: true
---
In nec orci lacus. Mauris ac leo vel nisi posuere scelerisque. In vitae sagittis turpis. Aenean tincidunt ultricies arcu in venenatis. Maecenas varius libero turpis, nec lobortis orci molestie placerat. Aliquam id diam nisi. Quisque faucibus, arcu lobortis ornare finibus, sem metus finibus lorem, a euismod dui nunc sit amet nunc. Donec venenatis libero a leo elementum sollicitudin. Ut condimentum lectus turpis.

* Duis id est vel nulla lacinia egestas
* Maecenas fringilla enim et justo auctor suscipit
* Nulla et augue non ligula pulvinar egestas
* Nulla et tortor blandit, tincidunt felis a, aliquam nisl
* Maecenas a nunc finibus, laoreet libero quis, gravida mi.

Phasellus posuere mattis nisi a rhoncus. Phasellus malesuada, nisi vel euismod tincidunt, justo ex tincidunt est, non facilisis purus turpis eget dolor. Praesent ac tempus erat, et elementum eros. Nunc venenatis pellentesque eros, a convallis nibh malesuada sit amet. Morbi dolor nisl, lobortis nec dui ut, fermentum eleifend ante. Maecenas dictum eget est vel consequat. Duis eu pulvinar eros. Morbi arcu sapien, vestibulum ullamcorper metus a, venenatis blandit sapien. Sed ut neque pellentesque nunc rhoncus imperdiet a tincidunt velit. Donec tortor velit, rutrum eget consectetur in, auctor vel velit. Sed at lacinia nibh, ut ullamcorper mauris. Suspendisse sit amet eleifend velit. Aliquam quis tempus est. Ut fermentum a orci vitae pretium.


text:
#include "xinput.h"
#include <string.h>

#define INVALID_EVENT_TYPE	-1

static int           motion_type = INVALID_EVENT_TYPE;
static int           button_press_type = INVALID_EVENT_TYPE;
static int           button_release_type = INVALID_EVENT_TYPE;
static int           key_press_type = INVALID_EVENT_TYPE;
static int           key_release_type = INVALID_EVENT_TYPE;
static int           proximity_in_type = INVALID_EVENT_TYPE;
static int           proximity_out_type = INVALID_EVENT_TYPE;

static int
register_events(Display		*dpy,
		XDeviceInfo	*info,
		char		*dev_name,
		Bool		handle_proximity)
{
    int			number = 0;	/* number of events registered */
    XEventClass		event_list[7];
    int			i;
    XDevice		*device;
    Window		root_win;
    unsigned long	screen;
    XInputClassInfo	*ip;

    screen = DefaultScreen(dpy);
    root_win = RootWindow(dpy, screen);

    device = XOpenDevice(dpy, info->id);

    if (!device) {
	fprintf(stderr, "unable to open device '%s'\n", dev_name);
	return 0;
    }

    if (device->num_classes > 0) {
	for (ip = device->classes, i=0; i<info->num_classes; ip++, i++) {
	    switch (ip->input_class) {
	    case KeyClass:
		DeviceKeyPress(device, key_press_type, event_list[number]); number++;
		DeviceKeyRelease(device, key_release_type, event_list[number]); number++;
		break;

	    case ButtonClass:
		DeviceButtonPress(device, button_press_type, event_list[number]); number++;
		DeviceButtonRelease(device, button_release_type, event_list[number]); number++;
		break;

	    case ValuatorClass:
		DeviceMotionNotify(device, motion_type, event_list[number]); number++;
		if (handle_proximity) {
		    ProximityIn(device, proximity_in_type, event_list[number]); number++;
		    ProximityOut(device, proximity_out_type, event_list[number]); number++;
		}
		break;

	    default:
		fprintf(stderr, "unknown class\n");
		break;
	    }
	}

	if (XSelectExtensionEvent(dpy, root_win, event_list, number)) {
	    fprintf(stderr, "error selecting extended events\n");
	    return 0;
	}
    }
    return number;
}

static void
print_events(Display	*dpy)
{
    XEvent        Event;

    while(1) {
	XNextEvent(dpy, &Event);

	if (Event.type == motion_type) {
	    int	loop;
	    XDeviceMotionEvent *motion = (XDeviceMotionEvent *) &Event;

	    printf("motion ");

	    for(loop=0; loop<motion->axes_count; loop++) {
		printf("a[%d]=%d ", motion->first_axis + loop, motion->axis_data[loop]);
	    }
	    printf("\n");
	} else if ((Event.type == button_press_type) ||
		   (Event.type == button_release_type)) {
	    int	loop;
	    XDeviceButtonEvent *button = (XDeviceButtonEvent *) &Event;

	    printf("button %s %d ", (Event.type == button_release_type) ? "release" : "press  ",
		   button->button);

	    for(loop=0; loop<button->axes_count; loop++) {
		printf("a[%d]=%d ", button->first_axis + loop, button->axis_data[loop]);
	    }
	    printf("\n");
	} else if ((Event.type == key_press_type) ||
		   (Event.type == key_release_type)) {
	    int	loop;
	    XDeviceKeyEvent *key = (XDeviceKeyEvent *) &Event;

	    printf("key %s %d ", (Event.type == key_release_type) ? "release" : "press  ",
		   key->keycode);

	    for(loop=0; loop<key->axes_count; loop++) {
		printf("a[%d]=%d ", key->first_axis + loop, key->axis_data[loop]);
	    }
	    printf("\n");
	} else if ((Event.type == proximity_out_type) ||
		   (Event.type == proximity_in_type)) {
	    int	loop;
	    XProximityNotifyEvent *prox = (XProximityNotifyEvent *) &Event;

	    printf("proximity %s ", (Event.type == proximity_in_type) ? "in " : "out");

	    for(loop=0; loop<prox->axes_count; loop++) {
		printf("a[%d]=%d ", prox->first_axis + loop, prox->axis_data[loop]);
	    }
	    printf("\n");
	}
	else {
	    printf("what's that %d\n", Event.type);
	}
    }
}

int
test(Display	*display,
     int	argc,
     char	*argv[],
     char	*name,
     char	*desc)
{
    XDeviceInfo		*info;

    if (argc != 1 && argc != 2) {
	fprintf(stderr, "usage: xinput %s %s\n", name, desc);
	return EXIT_FAILURE;
    } else {
	Bool	handle_proximity = False;
	int	idx = 0;

	if (argc == 2) {
	    if (strcmp("-proximity", argv[0]) != 0) {
		fprintf(stderr, "usage: xinput %s %s\n", name, desc);
		return EXIT_FAILURE;
	    }
	    handle_proximity = 1;
	    idx = 1;
	}

	info = find_device_info(display, argv[idx], True);

	if (!info) {
	    fprintf(stderr, "unable to find device '%s'\n", argv[idx]);
	    return EXIT_FAILURE;
	} else {
	    if (register_events(display, info, argv[idx], handle_proximity)) {
		print_events(display);
	    }
	    else {
		fprintf(stderr, "no event registered...\n");
		return EXIT_FAILURE;
	    }
	}
    }
    return EXIT_FAILURE;
}

/* end of test.c */


text:
class AddFields < ActiveRecord::Migration
  def change
     change_table :articles do |t|
      t.string :title
      t.string :body
      t.integer :visit_count

    end
  end
end


text:
/* http://prismjs.com/download.html?themes=prism-okaidia&languages=markup+css+clike+javascript+jsx&plugins=line-numbers+command-line */
var _self = (typeof window !== 'undefined')
	? window   // if in browser
	: (
		(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
		? self // if in worker
		: {}   // if in node js
	);

/**
 * Prism: Lightweight, robust, elegant syntax highlighting
 * MIT license http://www.opensource.org/licenses/mit-license.php/
 * @author Lea Verou http://lea.verou.me
 */

var Prism = (function(){

// Private helper vars
var lang = /\blang(?:uage)?-(\w+)\b/i;

var _ = _self.Prism = {
	util: {
		encode: function (tokens) {
			if (tokens instanceof Token) {
				return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
			} else if (_.util.type(tokens) === 'Array') {
				return tokens.map(_.util.encode);
			} else {
				return tokens.replace(/&/g, '&').replace(/</g, '<').replace(/\u00a0/g, ' ');
			}
		},

		type: function (o) {
			return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
		},

		// Deep clone a language definition (e.g. to extend it)
		clone: function (o) {
			var type = _.util.type(o);

			switch (type) {
				case 'Object':
					var clone = {};

					for (var key in o) {
						if (o.hasOwnProperty(key)) {
							clone[key] = _.util.clone(o[key]);
						}
					}

					return clone;

				case 'Array':
					// Check for existence for IE8
					return o.map && o.map(function(v) { return _.util.clone(v); });
			}

			return o;
		}
	},

	languages: {
		extend: function (id, redef) {
			var lang = _.util.clone(_.languages[id]);

			for (var key in redef) {
				lang[key] = redef[key];
			}

			return lang;
		},

		/**
		 * Insert a token before another token in a language literal
		 * As this needs to recreate the object (we cannot actually insert before keys in object literals),
		 * we cannot just provide an object, we need anobject and a key.
		 * @param inside The key (or language id) of the parent
		 * @param before The key to insert before. If not provided, the function appends instead.
		 * @param insert Object with the key/value pairs to insert
		 * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
		 */
		insertBefore: function (inside, before, insert, root) {
			root = root || _.languages;
			var grammar = root[inside];

			if (arguments.length == 2) {
				insert = arguments[1];

				for (var newToken in insert) {
					if (insert.hasOwnProperty(newToken)) {
						grammar[newToken] = insert[newToken];
					}
				}

				return grammar;
			}

			var ret = {};

			for (var token in grammar) {

				if (grammar.hasOwnProperty(token)) {

					if (token == before) {

						for (var newToken in insert) {

							if (insert.hasOwnProperty(newToken)) {
								ret[newToken] = insert[newToken];
							}
						}
					}

					ret[token] = grammar[token];
				}
			}

			// Update references in other language definitions
			_.languages.DFS(_.languages, function(key, value) {
				if (value === root[inside] && key != inside) {
					this[key] = ret;
				}
			});

			return root[inside] = ret;
		},

		// Traverse a language definition with Depth First Search
		DFS: function(o, callback, type, visited) {
			visited = visited || {};
			for (var i in o) {
				if (o.hasOwnProperty(i)) {
					callback.call(o, i, o[i], type || i);

					if (_.util.type(o[i]) === 'Object' && !visited[o[i]]) {
						visited[o[i]] = true;
						_.languages.DFS(o[i], callback, null, visited);
					}
					else if (_.util.type(o[i]) === 'Array' && !visited[o[i]]) {
						visited[o[i]] = true;
						_.languages.DFS(o[i], callback, i, visited);
					}
				}
			}
		}
	},
	plugins: {},

	highlightAll: function(async, callback) {
		var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');

		for (var i=0, element; element = elements[i++];) {
			_.highlightElement(element, async === true, callback);
		}
	},

	highlightElement: function(element, async, callback) {
		// Find language
		var language, grammar, parent = element;

		while (parent && !lang.test(parent.className)) {
			parent = parent.parentNode;
		}

		if (parent) {
			language = (parent.className.match(lang) || [,''])[1];
			grammar = _.languages[language];
		}

		// Set language on the element, if not present
		element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;

		// Set language on the parent, for styling
		parent = element.parentNode;

		if (/pre/i.test(parent.nodeName)) {
			parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
		}

		var code = element.textContent;

		var env = {
			element: element,
			language: language,
			grammar: grammar,
			code: code
		};

		if (!code || !grammar) {
			_.hooks.run('complete', env);
			return;
		}

		_.hooks.run('before-highlight', env);

		if (async && _self.Worker) {
			var worker = new Worker(_.filename);

			worker.onmessage = function(evt) {
				env.highlightedCode = evt.data;

				_.hooks.run('before-insert', env);

				env.element.innerHTML = env.highlightedCode;

				callback && callback.call(env.element);
				_.hooks.run('after-highlight', env);
				_.hooks.run('complete', env);
			};

			worker.postMessage(JSON.stringify({
				language: env.language,
				code: env.code,
				immediateClose: true
			}));
		}
		else {
			env.highlightedCode = _.highlight(env.code, env.grammar, env.language);

			_.hooks.run('before-insert', env);

			env.element.innerHTML = env.highlightedCode;

			callback && callback.call(element);

			_.hooks.run('after-highlight', env);
			_.hooks.run('complete', env);
		}
	},

	highlight: function (text, grammar, language) {
		var tokens = _.tokenize(text, grammar);
		return Token.stringify(_.util.encode(tokens), language);
	},

	tokenize: function(text, grammar, language) {
		var Token = _.Token;

		var strarr = [text];

		var rest = grammar.rest;

		if (rest) {
			for (var token in rest) {
				grammar[token] = rest[token];
			}

			delete grammar.rest;
		}

		tokenloop: for (var token in grammar) {
			if(!grammar.hasOwnProperty(token) || !grammar[token]) {
				continue;
			}

			var patterns = grammar[token];
			patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];

			for (var j = 0; j < patterns.length; ++j) {
				var pattern = patterns[j],
					inside = pattern.inside,
					lookbehind = !!pattern.lookbehind,
					lookbehindLength = 0,
					alias = pattern.alias;

				pattern = pattern.pattern || pattern;

				for (var i=0; i<strarr.length; i++) { // Don't cache length as it changes during the loop

					var str = strarr[i];

					if (strarr.length > text.length) {
						// Something went terribly wrong, ABORT, ABORT!
						break tokenloop;
					}

					if (str instanceof Token) {
						continue;
					}

					pattern.lastIndex = 0;

					var match = pattern.exec(str);

					if (match) {
						if(lookbehind) {
							lookbehindLength = match[1].length;
						}

						var from = match.index - 1 + lookbehindLength,
							match = match[0].slice(lookbehindLength),
							len = match.length,
							to = from + len,
							before = str.slice(0, from + 1),
							after = str.slice(to + 1);

						var args = [i, 1];

						if (before) {
							args.push(before);
						}

						var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias);

						args.push(wrapped);

						if (after) {
							args.push(after);
						}

						Array.prototype.splice.apply(strarr, args);
					}
				}
			}
		}

		return strarr;
	},

	hooks: {
		all: {},

		add: function (name, callback) {
			var hooks = _.hooks.all;

			hooks[name] = hooks[name] || [];

			hooks[name].push(callback);
		},

		run: function (name, env) {
			var callbacks = _.hooks.all[name];

			if (!callbacks || !callbacks.length) {
				return;
			}

			for (var i=0, callback; callback = callbacks[i++];) {
				callback(env);
			}
		}
	}
};

var Token = _.Token = function(type, content, alias) {
	this.type = type;
	this.content = content;
	this.alias = alias;
};

Token.stringify = function(o, language, parent) {
	if (typeof o == 'string') {
		return o;
	}

	if (_.util.type(o) === 'Array') {
		return o.map(function(element) {
			return Token.stringify(element, language, o);
		}).join('');
	}

	var env = {
		type: o.type,
		content: Token.stringify(o.content, language, parent),
		tag: 'span',
		classes: ['token', o.type],
		attributes: {},
		language: language,
		parent: parent
	};

	if (env.type == 'comment') {
		env.attributes['spellcheck'] = 'true';
	}

	if (o.alias) {
		var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
		Array.prototype.push.apply(env.classes, aliases);
	}

	_.hooks.run('wrap', env);

	var attributes = '';

	for (var name in env.attributes) {
		attributes += (attributes ? ' ' : '') + name + '="' + (env.attributes[name] || '') + '"';
	}

	return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';

};

if (!_self.document) {
	if (!_self.addEventListener) {
		// in Node.js
		return _self.Prism;
	}
 	// In worker
	_self.addEventListener('message', function(evt) {
		var message = JSON.parse(evt.data),
		    lang = message.language,
		    code = message.code,
		    immediateClose = message.immediateClose;

		_self.postMessage(_.highlight(code, _.languages[lang], lang));
		if (immediateClose) {
			_self.close();
		}
	}, false);

	return _self.Prism;
}

//Get current script and highlight
var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop();

if (script) {
	_.filename = script.src;

	if (document.addEventListener && !script.hasAttribute('data-manual')) {
		document.addEventListener('DOMContentLoaded', _.highlightAll);
	}
}

return _self.Prism;

})();

if (typeof module !== 'undefined' && module.exports) {
	module.exports = Prism;
}

// hack for components to work correctly in node.js
if (typeof global !== 'undefined') {
	global.Prism = Prism;
}
;
Prism.languages.markup = {
	'comment': //,
	'prolog': /<\?[\w\W]+?\?>/,
	'doctype': /<!DOCTYPE[\w\W]+?>/,
	'cdata': /<!\[CDATA\[[\w\W]*?]]>/i,
	'tag': {
		pattern: /<\/?(?!\d)[^\s>\/=.$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
		inside: {
			'tag': {
				pattern: /^<\/?[^\s>\/]+/i,
				inside: {
					'punctuation': /^<\/?/,
					'namespace': /^[^\s>\/:]+:/
				}
			},
			'attr-value': {
				pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
				inside: {
					'punctuation': /[=>"']/
				}
			},
			'punctuation': /\/?>/,
			'attr-name': {
				pattern: /[^\s>\/]+/,
				inside: {
					'namespace': /^[^\s>\/:]+:/
				}
			}

		}
	},
	'entity': /&#?[\da-z]{1,8};/i
};

// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function(env) {

	if (env.type === 'entity') {
		env.attributes['title'] = env.content.replace(/&/, '&');
	}
});

Prism.languages.xml = Prism.languages.markup;
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;

Prism.languages.css = {
	'comment': /\/\*[\w\W]*?\*\//,
	'atrule': {
		pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
		inside: {
			'rule': /@[\w-]+/
			// See rest below
		}
	},
	'url': /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
	'selector': /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
	'string': /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
	'property': /(\b|\B)[\w-]+(?=\s*:)/i,
	'important': /\B!important\b/i,
	'function': /[-a-z0-9]+(?=\()/i,
	'punctuation': /[(){};:]/
};

Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css);

if (Prism.languages.markup) {
	Prism.languages.insertBefore('markup', 'tag', {
		'style': {
			pattern: /(


text:
package edu.hws.eck.mdb;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This applet appears on the screen as a single button.  When the user
 * clicks the button, a window of type MandelbrotFrame is opened.  Clicking
 * the button while the window is open will close the window.  After the
 * window has been closed, the button can be used to open a new one.
 * Obviously, the applet should be rather small, just large enough to
 * show one button.    Note that in an applet tag on a web page, this
 * class should be referred to as code="edu.hws.eck.mdb.LauncherApplet.class".
 */
public class LauncherApplet extends JApplet {

   private String launchCommand;  // Text for the button.
   private String closeCommand;   // Text for the button if the window is open.

   private JButton launchButton;
   private MandelbrotFrame frame;

   /**
    * Set up the applet to show just the launchButton, and add
    * an ActionListener to that button.
    */
   public void init() {
      launchCommand = I18n.tr("launcherApplet.launchCommand");
      closeCommand = I18n.tr("launcherApplet.closeCommand");
      launchButton = new JButton(launchCommand);
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(launchButton,BorderLayout.CENTER);
      launchButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            doClick();
         }
      } );
   }

   /**
    * Called by the ActionListener when the user clicks on the launcher
    * button.  If frame is null, a new frame is created and made visible.
    * If frame is not null, the frame is closed.  The launchButton is
    * disabled (briefly) while the frame is opening or closing. A
    * window listener on the frame re-enables the button and sets
    * its text when the window is finished opening or closing.  Also,
    * when the window closes, the frame variable is set to null which
    * will indicate to this routine that a new window can be opened.
    */
   private void doClick() {
      launchButton.setEnabled(false);
      if (frame == null) {
         frame = new MandelbrotFrame(true);
         frame.adjustToScreenIfNecessary();
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.addWindowListener( new WindowAdapter() {
            public void windowOpened(WindowEvent evt) {
                  // Called when window opens; this only happens when
                  // the frame is created by the doClick() method.
               launchButton.setText(closeCommand);
               launchButton.setEnabled(true);
            }
            public void windowClosed(WindowEvent evt) {
                  // Called when the window closes for any reason.
                  // This can be because the user clicks the button
                  // again or because the user closes the frame with
                  // its "Close" command or by clicking its close box.
               launchButton.setText(launchCommand);
               launchButton.setEnabled(true);
               frame = null;
            }
         });
         frame.setVisible(true);
      }
      else {
         frame.dispose();
         frame.getMandelbrotPanel().getDisplay().shutDownThreads();
      }
   }

   /**
    * This is called when the applet is about to be destroyed.
    * Clean up by disposing the frame and making sure that the
    * worker threads in the MandebrotPanel get shut down.
    */
   public void destroy() {
      if (frame != null) {
         frame.dispose();
         frame.getMandelbrotPanel().getDisplay().shutDownThreads();
         frame = null;
      }
   }

}


text:
Nanpy
=====

Use your Arduino board with Python.

Description
-----------

The main purpose of Nanpy is making programmers' life easier, giving them something to create prototypes faster and use Arduino in a simpler way, thanks to a simple and powerful language like Python. Also Nanpy can run on RaspberryPi (tested with Raspbian http://www.raspbian.org/) so you can use it for communicating with Arduino :)

Let's start with a classic example, turn on a led placed in the 13th pin..

	Arduino.pinMode(13, Arduino.OUTPUT)
	Arduino.digitalWrite(13, Arduino.HIGH)

There are a lot of projects able to do that. Nanpy can do more!
Nanpy is easily extensible and can theoretically use every library, allowing you to create how many objects you want.
We started supporting OneWire, Lcd, Stepper and Servo library and they're still incomplete.
Let's try to connect our 16x2 lcd screen on pins 7, 8, 9, 10, 11, 12 and print something!

	lcd = Lcd([7, 8, 9, 10, 11, 12], [16, 2])
	lcd.printString("Hello World!")

really straightforward now, isn't it? :)

Dependencies
------------

#### Python (2.2 or later)
- python-setuptools
- python-serial

How to build and install
------------------------

Nanpy is composed by a Python part, that provides a library to use Arduino via Python and a server firmware. You can install Nanpy on a Raspberry too :)

To install Nanpy just type (as root, requires python-setuptools):

	python setup.py install

To build the firmware type:

	cd firmware
	export BOARD=uno (in case you use UNO board. Type 'make boards' for a complete list)
	make

and then upload it on your board:

	make upload

Optionally you can also set the baud rate:

	export BAUDRATE=115200 (default value is 9600)

How to use
----------

### Serial communication

Nanpy autodetects the serial port for you, anyway you can specify another serial port and baudrate manually:

	from nanpy import serial_manager
	serial_manager.connect('/dev/ttyACM1', 9600)

### Import modules

Import all the modules you need :)

	from nanpy import Arduino
	from nanpy import (OneWire, Lcd)
	...

How to contribute
-----------------

Nanpy needs a lot of work to be a great instrument. You can contribute with patches (bugfixing, writing improvements, creating support for a new library not included in Nanpy yet, writing examples and so on), writing documentation, reporting bugs or simply spreading Nanpy through the web if you like it :) If you have any doubt or problem, please contact me at <stagi.andrea@gmail.com>

License
-------

This software is released under MIT License. Copyright (c) 2012 Andrea Stagi <stagi.andrea@gmail.com>


text:
from wsme import exc
from wsme.rest import json as wsme_json
from wsme import types as wsme_types

from octavia.api.v2.types import member as member_type
from octavia.common import constants
from octavia.tests.unit.api.v2.types import base

class TestMemberPOST(base.BaseTypesTest):

    _type = member_type.MemberPOST

    def test_member(self):
        body = {"name": "member1", "address": "10.0.0.1",
                "protocol_port": 80, "tags": ['test_tag']}
        member = wsme_json.fromjson(self._type, body)
        self.assertTrue(member.admin_state_up)
        self.assertEqual(1, member.weight)
        self.assertEqual(wsme_types.Unset, member.subnet_id)

    def test_address_mandatory(self):
        body = {}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_protocol_mandatory(self):
        body = {}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_invalid_address(self):
        body = {"address": "test", "protocol_port": 443}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_invalid_subnet_id(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "subnet_id": "invalid_uuid"}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_invalid_admin_state_up(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "admin_state_up": "notvalid"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type,
                          body)

    def test_invalid_protocol_port(self):
        body = {"address": "10.0.0.1", "protocol_port": "test"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type, body)

    def test_invalid_weight(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "weight": "test"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type, body)

    def test_invalid_tags(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "tags": "invalid_tag"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type,
                          body)
        body = {"address": "10.0.0.1", "protocol_port": 443, "tags": [1, 2]}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_min_weight(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "weight": constants.MIN_WEIGHT - 1}
        self.assertRaises(
            exc.InvalidInput, wsme_json.fromjson, self._type, body)
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "weight": constants.MIN_WEIGHT}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(constants.MIN_WEIGHT, member.weight)

    def test_max_weight(self):
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "weight": constants.MAX_WEIGHT + 1}
        self.assertRaises(
            exc.InvalidInput, wsme_json.fromjson, self._type, body)
        body = {"address": "10.0.0.1", "protocol_port": 443,
                "weight": constants.MAX_WEIGHT}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(constants.MAX_WEIGHT, member.weight)

    def test_non_uuid_project_id(self):
        body = {"address": "10.0.0.1", "protocol_port": 80,
                "project_id": "non-uuid"}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(member.project_id, body['project_id'])

class TestMemberPUT(base.BaseTypesTest):

    _type = member_type.MemberPUT

    def test_member(self):
        body = {"name": "new_name", "tags": ['new_tag']}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(wsme_types.Unset, member.weight)
        self.assertEqual(wsme_types.Unset, member.admin_state_up)

    def test_member_full(self):
        name = "new_name"
        weight = 1
        admin_state = True
        body = {"name": name, "weight": weight, "admin_state_up": admin_state}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(name, member.name)
        self.assertEqual(weight, member.weight)
        self.assertEqual(admin_state, member.admin_state_up)

    def test_invalid_admin_state(self):
        body = {"admin_state_up": "test"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type, body)

    def test_invalid_weight(self):
        body = {"weight": "test"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type, body)

    def test_invalid_tags(self):
        body = {"tags": "invalid_tag"}
        self.assertRaises(ValueError, wsme_json.fromjson, self._type,
                          body)
        body = {"tags": [1, 2]}
        self.assertRaises(exc.InvalidInput, wsme_json.fromjson, self._type,
                          body)

    def test_min_weight(self):
        body = {"weight": constants.MIN_WEIGHT - 1}
        self.assertRaises(
            exc.InvalidInput, wsme_json.fromjson, self._type, body)
        body = {"weight": constants.MIN_WEIGHT}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(constants.MIN_WEIGHT, member.weight)

    def test_max_weight(self):
        body = {"weight": constants.MAX_WEIGHT + 1}
        self.assertRaises(
            exc.InvalidInput, wsme_json.fromjson, self._type, body)
        body = {"weight": constants.MAX_WEIGHT}
        member = wsme_json.fromjson(self._type, body)
        self.assertEqual(constants.MAX_WEIGHT, member.weight)


text:
package funcs

import (
	"github.com/Cepave/open-falcon-backend/common/model"
	"strings"
)

func NewMetricValue(metric string, val interface{}, dataType string, tags ...string) *model.MetricValue {
	mv := model.MetricValue{
		Metric: metric,
		Value:  val,
		Type:   dataType,
	}

	size := len(tags)

	if size > 0 {
		mv.Tags = strings.Join(tags, ",")
	}

	return &mv
}

func GaugeValue(metric string, val interface{}, tags ...string) *model.MetricValue {
	return NewMetricValue(metric, val, "GAUGE", tags...)
}

func CounterValue(metric string, val interface{}, tags ...string) *model.MetricValue {
	return NewMetricValue(metric, val, "COUNTER", tags...)
}


text:
/* TODO: add print queries */

@media print {

	*::after,
	*::before,
	footer,
	a {
		display: none;
		width: 0;
		height: 0;
	}

	body {
		padding: 5%;
	}

	header {
		display: flex;
		flex-wrap: wrap;
	}

	.col-md-6 {
		width: 50%;
	}

	img,
	.col-md-4 {
	    page-break-inside: avoid;
	}

	/* Bug fix:
	Browser: Chrome
	Issue: Chrome used to render only first page,
	not the entire content
	in the print preview.

	Though it would render rest of the content on small screen size,
	probably because of some bootstrap grid restrictions for different column sizes*/
	.col-md-4 {
		width: 100%;
	}

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.vamaraju.vamaraju_reflex.Buzzer4PlayerActivity"
    android:background="@color/material_blue_grey_950"
    android:id="@+id/activity_buzzer_4player">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true">

        <Button
            android:layout_width="175dp"
            android:layout_height="240dp"
            android:layout_row="0"
            android:layout_column="0"
            android:text="@string/buzzer4Player_player1"
            android:id="@+id/button_4player_player1_buzzer"
            android:onClick="onclickPlayer1Buzzer" />

        <Button
            android:layout_width="175dp"
            android:layout_height="240dp"
            android:layout_row="0"
            android:layout_column="2"
            android:text="@string/buzzer4Player_player2"
            android:id="@+id/button_4player_player2_buzzer"
            android:onClick="onclickPlayer2Buzzer" />

        <Button
            android:layout_width="175dp"
            android:layout_height="240dp"
            android:layout_row="2"
            android:layout_column="0"
            android:text="@string/buzzer4Player_player3"
            android:id="@+id/button_4player_player3_buzzer"
            android:onClick="onclickPlayer3Buzzer" />

        <Button
            android:layout_width="175dp"
            android:layout_height="240dp"
            android:layout_row="2"
            android:layout_column="2"
            android:text="@string/buzzer4Player_player4"
            android:id="@+id/button_4player_player4_buzzer"
            android:onClick="onclickPlayer4Buzzer" />
    </GridLayout>
</RelativeLayout>


text:
namespace Kachuwa.Identity.ViewModels
{
    public class RemoveLoginViewModel
    {
        public string LoginProvider { get; set; }
        public string ProviderKey { get; set; }
    }
}


text:
"""Unit tests for servicediscovery-supported APIs."""
import boto3
import pytest
import sure  # noqa # pylint: disable=unused-import

from botocore.exceptions import ClientError
from moto import mock_servicediscovery

# See our Development Tips on writing tests for hints on how to write good tests:
# http://docs.getmoto.org/en/latest/docs/contributing/development_tips/tests.html

@mock_servicediscovery
def test_create_service_minimal():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")
    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]

    resp = client.create_service(Name="my service", NamespaceId=namespace_id)

    resp.should.have.key("Service")
    resp["Service"].should.have.key("Id")
    resp["Service"].should.have.key("Arn")
    resp["Service"].should.have.key("Name").equals("my service")
    resp["Service"].should.have.key("NamespaceId").equals(namespace_id)
    resp["Service"].should.have.key("CreateDate")

@mock_servicediscovery
def test_create_service():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")
    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]

    resp = client.create_service(
        Name="my service",
        CreatorRequestId="crid",
        Description="my service",
        DnsConfig={
            "NamespaceId": namespace_id,
            "RoutingPolicy": "WEIGHTED",
            "DnsRecords": [{"Type": "SRV", "TTL": 0}],
        },
        HealthCheckConfig={"Type": "TCP", "ResourcePath": "/sth"},
        HealthCheckCustomConfig={"FailureThreshold": 125},
        Type="HTTP",
    )

    resp.should.have.key("Service")
    resp["Service"].should.have.key("Id")
    resp["Service"].should.have.key("Arn")
    resp["Service"].should.have.key("Name").equals("my service")
    resp["Service"].shouldnt.have.key("NamespaceId")
    resp["Service"].should.have.key("Description").equals("my service")
    resp["Service"].should.have.key("DnsConfig").equals(
        {
            "NamespaceId": namespace_id,
            "RoutingPolicy": "WEIGHTED",
            "DnsRecords": [{"Type": "SRV", "TTL": 0}],
        }
    )
    resp["Service"].should.have.key("HealthCheckConfig").equals(
        {"Type": "TCP", "ResourcePath": "/sth"}
    )
    resp["Service"].should.have.key("HealthCheckCustomConfig").equals(
        {"FailureThreshold": 125}
    )
    resp["Service"].should.have.key("Type").equals("HTTP")
    resp["Service"].should.have.key("CreatorRequestId").equals("crid")

@mock_servicediscovery
def test_get_service():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")

    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]

    service_id = client.create_service(Name="my service", NamespaceId=namespace_id)[
        "Service"
    ]["Id"]

    resp = client.get_service(Id=service_id)

    resp.should.have.key("Service")
    resp["Service"].should.have.key("Id")
    resp["Service"].should.have.key("Arn")
    resp["Service"].should.have.key("Name").equals("my service")
    resp["Service"].should.have.key("NamespaceId").equals(namespace_id)

@mock_servicediscovery
def test_get_unknown_service():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")

    with pytest.raises(ClientError) as exc:
        client.get_service(Id="unknown")
    err = exc.value.response["Error"]
    err["Code"].should.equal("ServiceNotFound")
    err["Message"].should.equal("unknown")

@mock_servicediscovery
def test_delete_service():
    client = boto3.client("servicediscovery", region_name="eu-west-1")

    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]
    service_id = client.create_service(Name="my service", NamespaceId=namespace_id)[
        "Service"
    ]["Id"]

    client.delete_service(Id=service_id)

    with pytest.raises(ClientError) as exc:
        client.get_service(Id=service_id)
    err = exc.value.response["Error"]
    err["Code"].should.equal("ServiceNotFound")
    err["Message"].should.equal(service_id)

@mock_servicediscovery
def test_update_service_description():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")
    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]

    service_id = client.create_service(
        Name="my service",
        NamespaceId=namespace_id,
        Description="first desc",
        DnsConfig={
            "NamespaceId": namespace_id,
            "RoutingPolicy": "WEIGHTED",
            "DnsRecords": [{"Type": "SRV", "TTL": 0}],
        },
        HealthCheckConfig={"Type": "TCP", "ResourcePath": "/sth"},
    )["Service"]["Id"]

    client.update_service(Id=service_id, Service={"Description": "updated desc"})

    resp = client.get_service(Id=service_id)

    resp.should.have.key("Service")
    resp["Service"].should.have.key("Id").equals(service_id)
    resp["Service"].should.have.key("Arn")
    resp["Service"].should.have.key("Name").equals("my service")
    resp["Service"].should.have.key("NamespaceId").equals(namespace_id)
    resp["Service"].should.have.key("Description").equals("updated desc")
    # From the docs:
    #    If you omit any existing DnsRecords or HealthCheckConfig configurations from an UpdateService request,
    #    the configurations are deleted from the service.
    resp["Service"].shouldnt.have.key("DnsConfig")
    resp["Service"].should.have.key("HealthCheckConfig").equals(
        {"Type": "TCP", "ResourcePath": "/sth"}
    )

@mock_servicediscovery
def test_update_service_others():
    client = boto3.client("servicediscovery", region_name="ap-southeast-1")
    operation_id = client.create_http_namespace(Name="mynamespace")["OperationId"]
    namespace_id = client.get_operation(OperationId=operation_id)["Operation"][
        "Targets"
    ]["NAMESPACE"]

    service_id = client.create_service(
        Name="my service",
        NamespaceId=namespace_id,
        Description="first desc",
        DnsConfig={
            "RoutingPolicy": "WEIGHTED",
            "DnsRecords": [{"Type": "SRV", "TTL": 0}],
        },
    )["Service"]["Id"]

    client.update_service(
        Id=service_id,
        Service={
            "DnsConfig": {"DnsRecords": [{"Type": "SRV", "TTL": 12}]},
            "HealthCheckConfig": {"Type": "TCP", "ResourcePath": "/sth"},
        },
    )

    resp = client.get_service(Id=service_id)

    resp.should.have.key("Service")
    resp["Service"].should.have.key("Id").equals(service_id)
    resp["Service"].should.have.key("Arn")
    resp["Service"].should.have.key("Name").equals("my service")
    resp["Service"].should.have.key("NamespaceId").equals(namespace_id)
    resp["Service"].should.have.key("Description").equals("first desc")
    resp["Service"].should.have.key("DnsConfig").equals(
        {"RoutingPolicy": "WEIGHTED", "DnsRecords": [{"Type": "SRV", "TTL": 12}]}
    )
    resp["Service"].should.have.key("HealthCheckConfig").equals(
        {"Type": "TCP", "ResourcePath": "/sth"}
    )


text:
package org.basex.query.func;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.value.item.*;

/**
 * This is a simple XQuery demo module written in Java.
 * It is derived from the abstract {@link QueryModule} class.
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Christian Gruen
 */
public final class QueryModuleTest extends QueryModule {
  /** Fruits array. */
  private static final String[] FRUITS = { "Apple", "Banana", "Cherry" };
  /** Lock string. */
  public static final String LOCK1 = "foo";
  /** Lock string. */
  public static final String LOCK2 = "bar";

  /**
   * Returns the specified fruit modulo number of fruits.
   * This variant is more convenient, as it uses Java's standard data types.
   *
   * @param fruit index of fruit to be returned
   * @return fruit string
   */
  @Requires(Permission.NONE)
  @Deterministic
  public String convenient(final int fruit) {
    final int i = fruit;
    return FRUITS[i % FRUITS.length];
  }

  /**
   * Returns the specified fruit modulo number of fruits.
   * This variant is faster, as it uses the internal data types of BaseX.
   *
   * @param fruit index of fruit to be returned
   * @return fruit string
   */
  @Requires(Permission.NONE)
  @Deterministic
  public Str fast(final Int fruit) {
    final int i = (int) fruit.itr();
    final String f = FRUITS[i % FRUITS.length];
    return Str.get(f);
  }

  /**
   * Returns the default function namespace.
   * @return default function namespace
   */
  @Requires(Permission.NONE)
  @ContextDependent
  public Str functionNS() {
    return Str.get(staticContext.funcNS);
  }

  /**
   * Read lock.
   */
  @Lock(read = { LOCK1, LOCK2 })
  public void readLock() { }

  /**
   * Write locks.
   */
  @Lock(write = { LOCK1, LOCK2 })
  public void writeLock() { }

  /**
   * Ignore argument.
   * @param e expression
   */
  public void ignore(@SuppressWarnings("unused") final Expr e) { }

  /**
   * Compute faculty.
   * @param e expression
   * @return resulting value
   * @throws QueryException query exception
   */
  public Int faculty(final Expr e) throws QueryException {
    final Iter iter = e.iter(queryContext);
    long c = 1;
    for(Item item; (item = iter.next()) != null;) {
      c *= item.itr(null);
    }
    return Int.get(c);
  }

  /**
   * Throws an exception.
   * @throws QueryException query exception
   */
  public void error() throws QueryException {
    throw new QueryException("Stopped with an error.");
  }
}


text:
#ifndef PROP_DICT_H
#define PROP_DICT_H

#include "properties.h"
#include "dia_xml.h"

typedef struct {
  Property common;
  GHashTable *dict; /* subprops[i] is a GPtrArray of (Property *) */
} DictProperty;

void prop_dicttypes_register(void);
#endif


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="fsi_teryt_db.http_client.class">Guzzle\Http\Client</parameter>
    </parameters>

    <services>
        <service id="fsi_teryt_db.http_client" class="%fsi_teryt_db.http_client.class%" />
    </services>
</container>


text:
package org.societies.api.privacytrust.privacy.model.privacypolicy;

/**
 * @author Elizabeth
 *
 */
public enum NegotiationStatus {

	SUCCESSFUL("successful"), FAILED("failed"), ONGOING("ongoing");

	private String status;
	NegotiationStatus(String status){
		this.status = status;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:gedmo="http://gediminasm.org/schemas/orm/doctrine-extensions-mapping">

    <mapped-superclass name="Sylius\Bundle\TaxationBundle\Model\TaxRate" table="sylius_tax_rate">
        <id name="id" column="id" type="integer">
            <generator strategy="AUTO" />
        </id>

        <field name="name" column="name" type="string" />
        <field name="amount" column="amount" type="decimal" precision="10" scale="5" />
        <field name="includedInPrice" column="included_in_price" type="boolean" />
        <field name="calculator" column="calculator" type="string" />

        <many-to-one field="category" target-entity="Sylius\Bundle\TaxationBundle\Model\TaxCategoryInterface" inversed-by="rates">
            <join-column name="category_id" referenced-column-name="id" nullable="false" />
        </many-to-one>

        <field name="createdAt" column="created_at" type="datetime">
            <gedmo:timestampable on="create"/>
        </field>
        <field name="updatedAt" column="updated_at" type="datetime" nullable="true">
            <gedmo:timestampable on="update"/>
        </field>
    </mapped-superclass>

</doctrine-mapping>


text:
some stuff here
# blah


text:
Date: 2018

## Status

Accepted

## Context

We encountered a bug where one Diaper Bank edited / deleted Items from the Item list (they weren't using specific Item types). Because Item types were shared globally, this deleted those types for everyone. That needs to not be the case.

## Decision

We've decided to have all items be sandboxed on a per-organization basis. There is a list of templated starting items ("Base Items") that will be created for every new organization when they are first added. Each of those starting items (and all other items) will all be connected back to a Base Item (a generic type). This will allow the Diaper Banks to rename and customize the items to their heart's content without (a) affecting other Diaper Banks and (b) while keeping it possible for Partner Base to request items without needing to know specifically what kinds of items they have on-hand. An "Other" base item will accommodate any items we've not factored in already.

## Consequences

There's some obvious data duplication. If we want to add additional Base Items in the future, we will need to propagate that change out to everyone.


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

    <title>
                    Documentation
            </title>

    <link href="/theme/app/app.css" rel="stylesheet" type="text/css"/>
    <link href="/theme/fonts/css/fontello.css" rel="stylesheet" type="text/css"/>
    <link href="/theme/highlight/styles/grayscale.css" rel="stylesheet" type="text/css"/>

                            Alberto Piu

                                    /
                                            Pine

            / Documentation

                Documentation

Introduction

Configuration

Content

Themes

Pine is a static site generator. It uses Branches at its core to
convert a directory of content to a static collection of HTML and CSS.
You can download the latest .phar executable here.

After that, you can add the executable to the $PATH and just use
pine from the command line. At this point, you can create a new site with:

pine new blog # Where blog is the name of your site
cd blog

To serve the file at http://127.0.0.1:8080 for development, use the serve command:

pine serve

Finally, use the command build to generate the static site.

pine build

Configuration

To generate a website, Pine needs content and a theme. A pine website will look like this:

The configuration file allows you to customize the name of the directories. The default
configuration looks like this:

theme: default
content: content
build: build
plugins: []

The options content and build refer to what directories are to be used for storing
respectively the content files and the generated site.
With theme, you can choose the active theme, which is to be found in the themes directory.
And finally, plugins is a list of PHP classes that pine will use as plugins.

Content

Content files reside in the content directory (or in the directory that is set in the configuration
file under content). As described in the documentation of Branches, every folder contained
in this directory is a post, where the folder itself is considered the root post.

Pine will look for a markdown file in every post, to be used as the content file. This file
will contain a YAML front matter where the post meta data can be specified, and a markdown
body.

---
title: A post title
layout: blog
---

The post *content*.

As you can see here, a title is included, as well as a layout. Pine will use this layout,
or it will use default if none is specified. More on layouts can be found on the next section.

Every other file in a post is considered an attachment.

Themes

A single pine theme will contain some configuration, public files (like JavaScript, or CSS), and twig templates.

When the site is generated, all contents of the theme public directory will be moved to the
generated site directory, where they will be under a folder called theme.

The templates can access the configuration of the theme and the site by using the variables
theme and site, respectively. For example, a theme could support both "serif" and "sans-serif"
styles by having the configuration on the theme config directory:

style: serif

And in the templates, the configuration value can be accessed with:

<body class="style-{{ theme.config.style }}">
    <h1>{{ site.config.title }}</h1>
    ...


text:
#import "NSMutableArray+QueueAdditions.h"

@implementation NSMutableArray (QueueAdditions)

- (id) queueHead
{
    if ([self count] == 0) {
		return nil;
	}

    return [self objectAtIndex:0];
}

- (id) dequeue
{
    if ([self count] == 0) {
		return nil;
	}

    id head = [self objectAtIndex:0];
    if (head != nil) {
        [[head retain] autorelease];
        [self removeObjectAtIndex:0];
    }

    return head;
}

- (id) pop
{
	return [self dequeue];
}

- (void) enqueue:(id)object
{
    [self addObject:object];
}

@end


text:
require_relative 'test_helper' #require 'test_helper'
require_relative 'async_minitest_helper' #require 'async_minitest_helper'

module AE

  module ConsolePlugin

    require 'ae_console/features/fileobserver.rb'

    unless defined?(Sketchup)
      # Create a Mock for UI.start_timer.
      module UI
        @next_id = 0
        @threads = {}

        def self.start_timer(duration, repeat=false, &block)
          id = @next_id
          @next_id += 1
          if repeat
            @threads[id] = true
            @threads[id] = Thread.new{
              while @threads.include?(id)
                sleep(duration)
                Thread.new{
                  block.call()
                }
              end
            }
          else
            @threads[id] = Thread.new{
              sleep(duration)
              Thread.new{
                block.call()
              }
            }
          end
          return id
        end

        def self.stop_timer(id)
          if @threads.include?(id)
            @threads[id].terminate
            @threads.delete(id)
          end
        end
      end # module UI
    end

    class TC_FileObserver < TestCase
      # This test suite fails when run in SketchUp because AsyncMiniTestHelper
      # does not work with SketchUp's UI module's use of threading.

      def setup
        dir = File.dirname(__FILE__)
        @filename = File.join(dir, "test")
        @filename2 = File.join(dir, "test2")
        File.delete(@filename) if File.exist?(@filename)
        File.delete(@filename2) if File.exist?(@filename2)
        @observer = FileObserver.new(0.01)
      end

      def shutdown
        @observer.unregister_all
        @observer = nil
        File.delete(@filename) if File.exist?(@filename)
        File.delete(@filename2) if File.exist?(@filename2)
      end

      def test_created
        async = AsyncMiniTestHelper.new(self, 1)
        @observer.register(@filename, :created) { async.done() }

        File.open(@filename, "w"){ |f| f.puts("test") }
        async.await()
      end

      def test_changed
        async = AsyncMiniTestHelper.new(self, 2, 4.0)
        File.open(@filename, "w"){ |f| f.puts("test") }
        @observer.register(@filename, :changed) { async.done() }

        UI.start_timer(0.5, false) {
          File.open(@filename, "a"){ |f| f.puts("2") }
        }
        UI.start_timer(1.5, false) {
          File.open(@filename, "w"){ |f| f.puts("hello") }
        }
        async.await()
      end

      def test_deleted
        async = AsyncMiniTestHelper.new(self, 1)
        File.open(@filename, "w"){ |f| f.puts("test") }
        @observer.register(@filename, :deleted) { async.done() }
        UI.start_timer(0.5, false) {
          File.delete(@filename)
        }
        async.await()
      end

      def test_unregister
        async = AsyncMiniTestHelper.new(self, 1, 0.5)
        @observer.register(@filename, :created) { async.done() }
        @observer.register(@filename, :deleted) { async.done() }
        # Unregister a file with a specific event
        @observer.unregister(@filename, :created)
        File.open(@filename, "w"){ |f| f.puts("test") }
        async.await_timeout()

        # Other events for that file should still trigger
        async = AsyncMiniTestHelper.new(self, 1)
        File.delete(@filename)
        async.await()

        # Unregister all events for a file
        async = AsyncMiniTestHelper.new(self, 1, 0.5)
        @observer.unregister(@filename)
        async.await_timeout()
      end

      def test_unregister_all
        async = AsyncMiniTestHelper.new(self, 2, 0.5)
        @observer.register(@filename, :created) { async.done() }
        @observer.register(@filename2, :created) { async.done() }
        # Unregister all files
        @observer.unregister_all()
        File.open(@filename, "w"){ |f| f.puts("test") }
        File.open(@filename2, "w"){ |f| f.puts("test2") }
        async.await_timeout()
      end

    end # class TC_FileObserver

  end

end


text:
struct winerr_wrapper
{
    DWORD err;
    winerr_wrapper(DWORD e):err(e) {}
};

winerr_wrapper getWinError();
winerr_wrapper getWinErrorFromHr(HRESULT hr);

template<typename STREAM>
STREAM& operator<<(STREAM& s, const GUID& g)
{
    s << (void*)g.Data1 << '-' << (void*)g.Data2 << '-' << (void*)g.Data3;
    for(const auto c: g.Data4)
    {
        s << '-';
        s << (void*)c;
    }
    return s;
}

template<typename STREAM>
STREAM& operator<<(STREAM& s, const DDCOLORKEY& ck)
{
    s << "Color key: " << ck.dwColorSpaceLowValue << "-" << ck.dwColorSpaceHighValue;
    return s;
}

template<typename STREAM>
STREAM& operator<<(STREAM& s, const RECT& rc)
{
    s << "RECT: left: " << rc.left << " right: " << rc.right << " top: " << rc.top << " bottom: " << rc.bottom;
    return s;
}

template<typename STREAM>
STREAM& operator<<(STREAM& s, const winerr_wrapper& e)
{
    LPTSTR lpMsgBuf = nullptr;
    const DWORD size = ::FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            nullptr,
            e.err,
            MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0, nullptr);
    for(DWORD i = 0; i < size; ++i)
    {
        if(('\r' == lpMsgBuf[i]) || ('\n' == lpMsgBuf[i]))
        {
            lpMsgBuf[i] = ' ';
        }
    }
    s << '\"' << lpMsgBuf << "\", code " << e.err;
    LocalFree(lpMsgBuf);
    return s;
}

#define LOG_ERROR()   WRITE_LOG(*mLog,logger::logERROR)
#define LOG_WARNING() WRITE_LOG(*mLog,logger::logWARNING)
#define LOG_INFO()    WRITE_LOG(*mLog,logger::logINFO)
#define LOG_DEBUG()   WRITE_LOG(*mLog,logger::logDEBUG)

#ifdef __GNUC__
#define FUNC_NAME __PRETTY_FUNCTION__
#else
#define FUNC_NAME __func__
#endif

#define WRITE_VAR(var)       LOG_INFO()  << #var << "=\"" << var << '\"'
#define WRITE_VAR_DEBUG(var) LOG_DEBUG() << #var << "=\"" << var << '\"'
#define WRITE_FLAG(var,flag) if((var) & (flag)) do{ LOG_INFO() << #var ": \"" #flag << "\" set"; }while(false)
#define WRITE_THIS() WRITE_VAR_DEBUG(this)

#define LOG_STATIC_FUNCTION() LOG_SCOPE((FUNC_NAME),*mLog,logger::logDEBUG);

#define LOG_FUNCTION() LOG_SCOPE((FUNC_NAME),*mLog,logger::logDEBUG); \
    WRITE_THIS()
#define LOG_FUNCTION_E() LOG_SCOPE((FUNC_NAME),*mLog,logger::logINFO); \
    WRITE_THIS(); \
    LOG_ERROR() << (FUNC_NAME) << " not implemented;"; return E_NOTIMPL;

#define CHECK_PARAM(param) do{ if(!(param)) { LOG_ERROR() << "Param \"" #param "\" failed"; return DDERR_INVALIDPARAMS; } }while(false)

template<typename BaseT, typename SrcT>
BaseT* adjust_pointer(SrcT* src)
{
    if(nullptr == src) return nullptr;
    const BaseT* dummy1 = nullptr;
    const SrcT*  dummy2 = static_cast<const SrcT*>(dummy1);
    const auto offset = reinterpret_cast<const char*>(dummy2) - reinterpret_cast<const char*>(dummy1);
    char* p = reinterpret_cast<char*>(src);
    p -= offset;
    return reinterpret_cast<BaseT*>(p);
}

#endif // COMMON_HPP


text:
using namespace System;
using namespace System::Drawing;

namespace SwitchUnitTests {
  TEST(CharacterRangeTest, DefaultConstructor) {
    CharacterRange characterRange;

    ASSERT_EQ(0, characterRange.First);
    ASSERT_EQ(0, characterRange.Length);
  }

  TEST(CharacterRangeTest, Constructor) {
    CharacterRange characterRange(1, 2);

    ASSERT_EQ(1, characterRange.First);
    ASSERT_EQ(2, characterRange.Length);
  }

  TEST(CharacterRangeTest, CopyConstructor) {
    CharacterRange characterRange1(1, 2);

    CharacterRange characterRange2 = characterRange1;

    ASSERT_EQ(1, characterRange2.First);
    ASSERT_EQ(2, characterRange2.Length);
  }

  TEST(CharacterRangeTest, CopyOperator) {
    CharacterRange characterRange1(1, 2);
    CharacterRange characterRange2;

    characterRange2 = characterRange1;

    ASSERT_EQ(1, characterRange2.First);
    ASSERT_EQ(2, characterRange2.Length);
  }

  TEST(CharacterRangeTest, Equals) {
    CharacterRange characterRange1(1, 2);
    CharacterRange characterRange2;

    characterRange2 = characterRange1;

    ASSERT_TRUE(characterRange1.Equals(characterRange2));
  }

  TEST(CharacterRangeTest, Inequals) {
    CharacterRange characterRange1(1, 2);
    CharacterRange characterRange2;

    characterRange2 = characterRange1;
    characterRange2.Length = 3;

    ASSERT_FALSE(characterRange1.Equals(characterRange2));
  }
}


text:
define({
    root: {
        clear: 'Clear',
        output: 'Output',
        showOnNewMessage: 'Show on new messages',
        scrollLock: 'Scroll lock',
    },
    'en-us': true,
    'zh-cn': true
});


text: require("!style!css!./style.css");


text:
WINRT_EXPORT namespace winrt {

namespace ABI::Windows::Devices::Printers::Extensions {

struct __declspec(uuid("c56f74bd-3669-4a66-ab42-c8151930cd34")) __declspec(novtable) IPrint3DWorkflow : Windows::IInspectable
{
    virtual HRESULT __stdcall get_DeviceID(hstring * value) = 0;
    virtual HRESULT __stdcall abi_GetPrintModelPackage(Windows::IInspectable ** printModelPackage) = 0;
    virtual HRESULT __stdcall get_IsPrintReady(bool * value) = 0;
    virtual HRESULT __stdcall put_IsPrintReady(bool value) = 0;
    virtual HRESULT __stdcall add_PrintRequested(Windows::Foundation::TypedEventHandler<Windows::Devices::Printers::Extensions::Print3DWorkflow, Windows::Devices::Printers::Extensions::Print3DWorkflowPrintRequestedEventArgs> * eventHandler, event_token * eventCookie) = 0;
    virtual HRESULT __stdcall remove_PrintRequested(event_token eventCookie) = 0;
};

struct __declspec(uuid("a2a6c54f-8ac1-4918-9741-e34f3004239e")) __declspec(novtable) IPrint3DWorkflow2 : Windows::IInspectable
{
    virtual HRESULT __stdcall add_PrinterChanged(Windows::Foundation::TypedEventHandler<Windows::Devices::Printers::Extensions::Print3DWorkflow, Windows::Devices::Printers::Extensions::Print3DWorkflowPrinterChangedEventArgs> * eventHandler, event_token * eventCookie) = 0;
    virtual HRESULT __stdcall remove_PrinterChanged(event_token eventCookie) = 0;
};

struct __declspec(uuid("19f8c858-5ac8-4b55-8a5f-e61567dafb4d")) __declspec(novtable) IPrint3DWorkflowPrintRequestedEventArgs : Windows::IInspectable
{
    virtual HRESULT __stdcall get_Status(winrt::Windows::Devices::Printers::Extensions::Print3DWorkflowStatus * value) = 0;
    virtual HRESULT __stdcall abi_SetExtendedStatus(winrt::Windows::Devices::Printers::Extensions::Print3DWorkflowDetail value) = 0;
    virtual HRESULT __stdcall abi_SetSource(Windows::IInspectable * source) = 0;
    virtual HRESULT __stdcall abi_SetSourceChanged(bool value) = 0;
};

struct __declspec(uuid("45226402-95fc-4847-93b3-134dbf5c60f7")) __declspec(novtable) IPrint3DWorkflowPrinterChangedEventArgs : Windows::IInspectable
{
    virtual HRESULT __stdcall get_NewDeviceId(hstring * value) = 0;
};

struct __declspec(uuid("e70d9fc1-ff79-4aa4-8c9b-0c93aedfde8a")) __declspec(novtable) IPrintExtensionContextStatic : Windows::IInspectable
{
    virtual HRESULT __stdcall abi_FromDeviceId(hstring deviceId, Windows::IInspectable ** context) = 0;
};

struct __declspec(uuid("e00e4c8a-4828-4da1-8bb8-8672df8515e7")) __declspec(novtable) IPrintNotificationEventDetails : Windows::IInspectable
{
    virtual HRESULT __stdcall get_PrinterName(hstring * value) = 0;
    virtual HRESULT __stdcall get_EventData(hstring * value) = 0;
    virtual HRESULT __stdcall put_EventData(hstring value) = 0;
};

struct __declspec(uuid("e3c22451-3aa4-4885-9240-311f5f8fbe9d")) __declspec(novtable) IPrintTaskConfiguration : Windows::IInspectable
{
    virtual HRESULT __stdcall get_PrinterExtensionContext(Windows::IInspectable ** context) = 0;
    virtual HRESULT __stdcall add_SaveRequested(Windows::Foundation::TypedEventHandler<Windows::Devices::Printers::Extensions::PrintTaskConfiguration, Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedEventArgs> * eventHandler, event_token * eventCookie) = 0;
    virtual HRESULT __stdcall remove_SaveRequested(event_token eventCookie) = 0;
};

struct __declspec(uuid("eeaf2fcb-621e-4b62-ac77-b281cce08d60")) __declspec(novtable) IPrintTaskConfigurationSaveRequest : Windows::IInspectable
{
    virtual HRESULT __stdcall abi_Cancel() = 0;
    virtual HRESULT __stdcall abi_Save(Windows::IInspectable * printerExtensionContext) = 0;
    virtual HRESULT __stdcall abi_GetDeferral(Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedDeferral ** deferral) = 0;
    virtual HRESULT __stdcall get_Deadline(Windows::Foundation::DateTime * value) = 0;
};

struct __declspec(uuid("e959d568-f729-44a4-871d-bd0628696a33")) __declspec(novtable) IPrintTaskConfigurationSaveRequestedDeferral : Windows::IInspectable
{
    virtual HRESULT __stdcall abi_Complete() = 0;
};

struct __declspec(uuid("e06c2879-0d61-4938-91d0-96a45bee8479")) __declspec(novtable) IPrintTaskConfigurationSaveRequestedEventArgs : Windows::IInspectable
{
    virtual HRESULT __stdcall get_Request(Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequest ** context) = 0;
};

}

namespace ABI {

template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflow> { using default_interface = Windows::Devices::Printers::Extensions::IPrint3DWorkflow; };
template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflowPrintRequestedEventArgs> { using default_interface = Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrintRequestedEventArgs; };
template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflowPrinterChangedEventArgs> { using default_interface = Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrinterChangedEventArgs; };
template <> struct traits<Windows::Devices::Printers::Extensions::PrintNotificationEventDetails> { using default_interface = Windows::Devices::Printers::Extensions::IPrintNotificationEventDetails; };
template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfiguration> { using default_interface = Windows::Devices::Printers::Extensions::IPrintTaskConfiguration; };
template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequest> { using default_interface = Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequest; };
template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedDeferral> { using default_interface = Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedDeferral; };
template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedEventArgs> { using default_interface = Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedEventArgs; };

}

namespace Windows::Devices::Printers::Extensions {

template <typename T> struct impl_IPrint3DWorkflow;
template <typename T> struct impl_IPrint3DWorkflow2;
template <typename T> struct impl_IPrint3DWorkflowPrintRequestedEventArgs;
template <typename T> struct impl_IPrint3DWorkflowPrinterChangedEventArgs;
template <typename T> struct impl_IPrintExtensionContextStatic;
template <typename T> struct impl_IPrintNotificationEventDetails;
template <typename T> struct impl_IPrintTaskConfiguration;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequest;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequestedDeferral;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequestedEventArgs;

}

namespace impl {

template <> struct traits<Windows::Devices::Printers::Extensions::IPrint3DWorkflow>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrint3DWorkflow;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrint3DWorkflow<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrint3DWorkflow2>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrint3DWorkflow2;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrint3DWorkflow2<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrintRequestedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrintRequestedEventArgs;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrint3DWorkflowPrintRequestedEventArgs<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrinterChangedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrint3DWorkflowPrinterChangedEventArgs;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrint3DWorkflowPrinterChangedEventArgs<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintExtensionContextStatic>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintExtensionContextStatic;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintExtensionContextStatic<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintNotificationEventDetails>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintNotificationEventDetails;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintNotificationEventDetails<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintTaskConfiguration>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintTaskConfiguration;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintTaskConfiguration<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequest>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequest;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintTaskConfigurationSaveRequest<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedDeferral>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedDeferral;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintTaskConfigurationSaveRequestedDeferral<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::IPrintTaskConfigurationSaveRequestedEventArgs;
    template <typename D> using consume = Windows::Devices::Printers::Extensions::impl_IPrintTaskConfigurationSaveRequestedEventArgs<D>;
};

template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflow>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::Print3DWorkflow;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.Print3DWorkflow"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflowPrintRequestedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::Print3DWorkflowPrintRequestedEventArgs;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.Print3DWorkflowPrintRequestedEventArgs"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::Print3DWorkflowPrinterChangedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::Print3DWorkflowPrinterChangedEventArgs;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.Print3DWorkflowPrinterChangedEventArgs"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintExtensionContext>
{
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintExtensionContext"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintNotificationEventDetails>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::PrintNotificationEventDetails;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintNotificationEventDetails"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfiguration>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::PrintTaskConfiguration;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintTaskConfiguration"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequest>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequest;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequest"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedDeferral>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedDeferral;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedDeferral"; }
};

template <> struct traits<Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedEventArgs>
{
    using abi = ABI::Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedEventArgs;
    static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedEventArgs"; }
};

}

}


text:
from neutron import manager
from neutron.tests.unit.bigswitch import test_base
from neutron.tests.unit import test_extension_security_group as test_sg
from neutron.tests.unit import test_security_groups_rpc as test_sg_rpc

class RestProxySecurityGroupsTestCase(test_sg.SecurityGroupDBTestCase,
                                      test_base.BigSwitchTestBase):
    plugin_str = ('%s.NeutronRestProxyV2' %
                  test_base.RESTPROXY_PKG_PATH)

    def setUp(self, plugin=None):
        test_sg_rpc.set_firewall_driver(test_sg_rpc.FIREWALL_HYBRID_DRIVER)
        self.setup_config_files()
        self.setup_patches()
        self._attribute_map_bk_ = {}
        super(RestProxySecurityGroupsTestCase, self).setUp(self.plugin_str)
        plugin = manager.NeutronManager.get_plugin()
        self.notifier = plugin.notifier
        self.rpc = plugin.callbacks
        self.startHttpPatch()

class TestSecServerRpcCallBack(test_sg_rpc.SGServerRpcCallBackMixinTestCase,
                               RestProxySecurityGroupsTestCase):
    pass

class TestSecurityGroupsMixin(test_sg.TestSecurityGroups,
                              test_sg_rpc.SGNotificationTestMixin,
                              RestProxySecurityGroupsTestCase):
    pass


text:
<?xml version="1.0"?>
<package>
  <name>xm_arm_bringup</name>
  <version>0.0.1</version>
  <description>The xm_arm_bringup package provides roslaunch for starting xmbot's arm motion planning and simulation test.</description>

  <maintainer email="myyerrol@126.com">myyerrol</maintainer>

  <license>BSD</license>

  <author email="myyerrol@126.com">myyerrol</author>

  <buildtool_depend>catkin</buildtool_depend>

</package>


text:
#include "xvmaininc.h"
#include "defines.h"
#include "rtlintproto.h"
#include "declares.h"
#include "externs.h"

/************************************************************************/
/* Common Preprocessing (before process_optionals)			*/
/************************************************************************/

int p_xlget(int unit)
{

   if (first_call)
      v2_general_initialize();		/* one-time setup */

   current_access = G;			/* Set up the current access */
   current_call = LGET;

   if (v2_valid_unit(unit) != SUCCESS)
      return NO_SUCH_UNIT;

/* The rest of the checks were moved to c_xlget so err_act would work */

   v2_initialize_value_table(label_options, N_LABEL_TABLE_ENTRIES,
			label_table[unit],
			label_default_table);
   v2_initialize_value_table(unit_table, N_UNIT_TABLE_ENTRIES,
			current_table[unit],
			default_table);

   return SUCCESS;

}


text:
export function getRepoRedirect(repo) {
  if (repo.local) {
    return repo.name;
  } else {
    return repo.id
  }
}


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

package org.chromium.chrome.browser.download.home.list.mutator;

import org.chromium.chrome.browser.download.home.filter.Filters;
import org.chromium.chrome.browser.download.home.list.ListUtils;
import org.chromium.components.offline_items_collection.OfflineItem;

import java.util.Comparator;

/**
 * Comparator based on score. Comparison is done first based on the score. For items having same
 * score, filter type and timestamp will be used to further compare.
 */
public class ScoreComparator implements Comparator<OfflineItem> {
    @Override
    public int compare(OfflineItem lhs, OfflineItem rhs) {
        int comparison = compareItemByScore(lhs, rhs);
        if (comparison != 0) return comparison;

        comparison = ListUtils.compareFilterTypesTo(
                Filters.fromOfflineItem(lhs), Filters.fromOfflineItem(rhs));
        if (comparison != 0) return comparison;

        comparison = ListUtils.compareItemByTimestamp(lhs, rhs);
        if (comparison != 0) return comparison;

        return ListUtils.compareItemByID(lhs, rhs);
    }

    private int compareItemByScore(OfflineItem lhs, OfflineItem rhs) {
        return Double.compare(rhs.contentQualityScore, lhs.contentQualityScore);
    }
}