text:
"""A simple engine to query the index."""

import time
import operator
import pickle

import crawler
import preprocessor
import morphosyntactic
import indexer
import save_and_load

class NoIndexError(Exception):
    """
    Exception produced when the search engine's index hasn't been initialized.
    """

    def __init__(self):
        pass

    def __str__(self):
        return 'The search engine\'s index has not been initialized.'

class NoUrlMapError(Exception):
    """
    Exception produced when the search engine's id-to-url map (urls) hasn't
    been initialized.
    """

    def __init__(self):
        pass

    def __str__(self):
        return 'The search engine\'s id-to-url map has not been initialized.'

class SimpleSearchEngine:
    """A simple engine to query the index."""

    def __init__(self, index=None, urls=None):
        """
        __init__(self, index=None, urls=None): Create a new SearchEngine.
        'index' can be an existing index
        'urls' can be a list mapping page ids to urls
        """
        self._index = index
        self._urls = urls

    def query(self, input):
        """
        query(input): 'input' is a string. Clean, tokenize and lemmatize it,
        make the query and print the results.
        """
        # clean input:
        query = preprocessor.clean_query(input)
        lemmas = morphosyntactic.lemmatize_query(query)
        # make the query:
        results = self.simple_query(lemmas)
        return results

    def simple_query(self, lemmas):
        """
        simple_query(self, lemmas): Make a query to the index. 'lemmas' is
        a list of lemmas to search for.

        simple_query() returns a list of (url, weight) tuples sorted by weight
        in descending order.
        """
        if self._index == None:
            raise NoIndexError
        if self._urls == None:
            raise NoUrlMapError
        if len(lemmas) == 0:
            return []
        # a dict mapping urls to importance according to the query:
        results = {}
        for lemma in lemmas:
            try:
                for id, weight in self._index[lemma].iteritems():
                    # increase the page's importance by 'weight':
                    results[self._urls[id]] = results.get(self._urls[id],
                                                          0.0) + weight
            except KeyError:
                # 'lemma' was not in the index
                continue
        # sort by weight (descending order) and return
        return sorted(results.iteritems(), key=operator.itemgetter(1),
                      reverse=True)

    def evaluate(self, queries, repeat=1):
        """
        evaluate(self, queries, repeat=1): Run a series of queries 'repeat'
        times and return the average time. 'queries' is a list of lists
        containing strings.

        Each list is a query and each string (inside the lists) is a lemma
        to search for.
        """
        start = time.clock()
        for i in xrange(repeat):
            for query in queries:
                self.simple_query(query)
        stop = time.clock()
        return (stop - start) / (len(queries) * repeat)

    def load_index_and_urls(self, index_file=None, urls_file=None):
        """
        load_index(self, index_file=None, urls_file=None): Load the index
        and urls from files.
        """
        if index_file is None:
            index_file = 'index.xml'
        with open(index_file, 'r') as f:
            self._index = save_and_load.load_index(f)
        if urls_file is None:
            urls_file = 'urls.pickle'
        with open(urls_file, 'r') as f:
            self._urls = pickle.load(f)

    def set_index_and_urls(self, index, urls):
        """
        set_index_and_urls(self, index, urls): Use an existing index
        and url map.
        """
        self._index = index
        self._urls = urls

    def make_index_and_urls(self):
        """
        make_index_and_urls(self): Make an index and a url-map from scratch.
        """
        c = crawler.Crawler()
        c.crawl()
        self._urls = c.get_page_urls()
        preprocessor.clean_and_tokenize_all()
        self._index = indexer.make_index(tagged=False)


text:
class ListsController < ApplicationController
  before_action :set_board
  before_action :set_list, only: [:show, :update, :destroy]

  def index
    redirect_to @board
  end

  def show
  end

  def create
    @list = @board.lists.build(list_params)

    respond_to do |format|
      if @list.save
        format.html { redirect_to board_path(@board), notice: 'リストを作成しました!' }
        format.json { render :show, status: :created, location: [@board, @list] }
      else
        format.html { redirect_to board_path(@board), alert: 'リスト名を入力してください' }
        format.json { render json: @list.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @list.update(list_params)
        format.html { redirect_to board_path(@board), notice: 'リストを更新しました!' }
        format.json { render :show, status: :ok, location: [@board, @list] }
      else
        format.html { render :edit }
        format.json { render json: @list.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @list.destroy
    respond_to do |format|
      format.html { redirect_to @board, notice: 'リストを削除しました。' }
      format.json { head :no_content }
    end
  end

  private
  def list_params
    params.require(:list).permit(:name, :board_id, :order)
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
* Collection of tests for issues on the tracker
*/

var assert = require("assert");
var vows = require("vows");
var RESTeasy = require("api-easy");
var http = require("http");
var request = require('request');
var querystring = require("querystring");
var events = require("events");
var fs = require("fs");
var lconfig = require('../Common/node/lconfig.js');

lconfig.load('config.json');

var tests = RESTeasy.describe("Locker Core Issues");

/* TODO reinstate once node-http-proxy supports redirects
tests.discuss("Issues #11 - Proxy should respond to redirects")
    .use(lconfig.lockerHost, lconfig.lockerPort)
    .followRedirect(false)
    .get("/Me/proxy-redirect-test/external")
        .expect(302)
        .expect("redirects to http://www.example.com", function(err, resp, body) {
            assert.equal(resp.headers.location, 'http://www.example.com');
        })
    .get('/Me/proxy-redirect-test/internal')
        .expect(302)
.undiscuss();
*/

tests.discuss("Issues #15 - Services do not spawn when called through the proxy")
    .use(lconfig.lockerHost, lconfig.lockerPort)
    // Two of these at once to test the error of the process stopping with multiple pending callbacks
    .get("/Me/slowStarter/firstPass")
        .expect(200)
    .post("/Me/slowStarter/firstPass")
        .expect(200)
    .next()
        // Now we make sure the startup callback list was cleared from the previous step
        .get("/Me/slowStarter/another")
            .expect(200)
        .get("/Me/slowStarter/more")
            .expect(200)
.undiscuss();

tests.export(module);


text:
/**
 *
 */
package net.oneandone.troilus.api;

/**
 * @author Jason Westra
 *
 */
public interface PaginationInvites {

	public static final String DDL = "com/unitedinternet/troilus/example/invites.ddl";

	public static final String TABLE_NAME = "invites_by_group";

	public static final String INVITE_DATE = "invite_date";

}


text:
package de.fzi.osh.core;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;

import de.fzi.osh.time.TimeService;

/**
 * This class simply provides a reference to the time service.
 * (Used for logging)
 *
 * @author K. Foerderer
 *
 */
@Component(enabled=true,immediate=true)
public class TimeProvider {

	private static TimeService timeService;

	@Reference(
			name = "TimeService",
			service = TimeService.class,
			cardinality = ReferenceCardinality.OPTIONAL,
			policy = ReferencePolicy.DYNAMIC,
			unbind = "unbindTimeService"
		)
	protected synchronized void bindTimeService(TimeService timeService) {
		TimeProvider.timeService = timeService;
	}
	protected synchronized void unbindTimeService(TimeService timeService) {
		TimeProvider.timeService = null;
	}

	public static TimeService getService() {
		return timeService;
	}
}


text:
package io.krom.lsh

import breeze.linalg.DenseVector
import io.krom.lsh.DistanceFunction._
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class DistanceFunctionSpec extends AnyFunSpec with Matchers {
  describe("calculating Euclidean distance score") {
    it(
      "should equal 1 over 1 plus the square root of the sum of the squares of the sides"
    ) {
      val point1 = DenseVector[Double](1.0, 0.0)
      val point2 = DenseVector[Double](0.0, 1.0)
      val point3 = DenseVector[Double](3.0, 0.0)

      euclideanDistance(point1, point1) should equal(1.0)
      euclideanDistance(point1, point2) should equal(
        1.0 / (1.0 + Math.sqrt(2.0))
      )
      euclideanDistance(point1, point3) should equal(
        1.0 / (1.0 + Math.sqrt(4.0))
      )
      euclideanDistance(point2, point3) should equal(
        1.0 / (1.0 + Math.sqrt(10.0))
      )
    }
  }
  describe("calculating Cosine distance score") {
    it("should equal 1 minus the cosine of the angle between the vectors") {
      val point1 = DenseVector(1.0, 0.0)
      val point2 = DenseVector(0.0, 1.0)
      val point3 = DenseVector(3.0, 0.0)

      val point4 = DenseVector(2.0, 3.0)
      val point5 = DenseVector(1.0, 1.5)
      val point6 = DenseVector(6.0, 9.0)

      cosineDistance(point1, point1) should equal(1.0)
      cosineDistance(point1, point2) should equal(0.0)
      cosineDistance(point2, point1) should equal(0.0)
      cosineDistance(point1, point3) should equal(1.0)
      cosineDistance(point4, point5) should equal(1.0)
      cosineDistance(point4, point6) should equal(1.0)

      val point7 = DenseVector(-1.0, 0.0)
      val point8 = DenseVector(0.0, -1.0)

      cosineDistance(point1, point7) should equal(1.0)
      cosineDistance(point1, point8) should equal(0.0)
      cosineDistance(point7, point8) should equal(0.0)

      val point9 = DenseVector(0.0, 0.0)
      cosineDistance(point9, point1).isNaN should be(true)
    }
  }
}


text:
using System;

namespace SotnWiki.DTOs.EditViewsDTOs
{
    public class EditsViewDTO
    {
        public Guid Id { get; set; }

        public string Content { get; set; }

        public Guid PageId { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meteor.JS Tutorial #1: Getting Started Guide for Meteor JS — Brian Wheeler</title>
    <link href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/assets/main.css">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/images/headshot.jpeg"/>
    <link href="/feed.xml" rel="alternate" type="application/rss+xml" title="Brian Wheeler" />
    <meta name="title" content="Meteor.JS Tutorial #1: Getting Started Guide for Meteor JS ">
    <link rel="canonical" href="http://brianw.io/blog/2014/01/28/meteor-dot-js-tutorial-number-1-getting-started-guide-for-meteor-js">

    <meta property="og:title" content="Meteor.JS Tutorial #1: Getting Started Guide for Meteor JS "/>
    <meta property="og:url" content="http://brianw.io/blog/2014/01/28/meteor-dot-js-tutorial-number-1-getting-started-guide-for-meteor-js"/>

    <meta property="og:description" content="Short and sweet meteor.js tutorials."/>
    <meta name="description" content="Short and sweet meteor.js tutorials."/>

    <meta property="og:site_name" content="Brian Wheeler">

            Home

            About

            Thoughts and stuff

                By <address>Brian Wheeler</address> —
                <time pubdate datetime="2014-28-January" title="January 28, 2014">January 28, 2014</time>

Meteor.JS Tutorial #1: Getting Started Guide for Meteor JS

If you're like me, you are cautiously optimistic about new technology, such as Meteor.js. I'm very excited to see how Meteor develops, and what it will mean for the future of web development.
I've been playing around with Meteor, so I wanted to do a quick tutorial.

To get started, go get yourself a copy of Meteor.js. Once you have done that, create a sample application by typing meteor create my_app at the console.
(This tutorial assumes you have basic web development and console skills.)

Now type cd my_app/ in terminal.

tree

├── my_app.css
├── my_app.html
└── my_app.js

Cool! You now have a single-page meteor app! You can put your styles in the css file (duh), now let's take a look at the MyApp.js file.

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "Welcome to my_app.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

The first thing I notice right off the bat is we have these Meteor.isClient and Meteor.isServer methods. Meteor has some sort of secret sauce that will make sure that
the code you put on the server side will not be exposed to the client, and vice versa (thankfully). There are certain things that you can and cannot do on the client side in
meteor, for the sake of data-security, but more on tht later.

The next thing I notice is the property on the Template object. If we look at our my_app.html file, we see

<head>
  <title>my_app</title>
</head>

<body>

</body>

<template name="hello">
  <h1>Hello World!</h1>

  <input type="button" value="Click" />
</template>

In Meteor, we don't use HTML in the old-school way of compiling pages with server variables (MVC style), now there is this new idea of MVM, or Model-View-Model.
In Meteor, you will find that the server code is bound almost directly to the view. If we want something to happen server-side on click, we can simply call the
events method the corresponding template. Meteor will bind Template.template_name to the corresponding template, defined by the name attribute.

I hope this tutorial was a helpful intro into Meteor JS! If you're looking for more meteor, don't miss my tutorial on how to listen for events in Meteor.js!

        Tweet

            <address>

Written by Brian Wheeler

                Programmer, Entrepreneur, Startup Enthusiast

            </address>

        © 2015

            Brian Wheeler
            Blog ·

            About

Incorporated theme by Inc


text:
// Authors: Konstantin Dols <dols@ient.rwth-aachen.de>
//          Mark Asbach <asbach@ient.rwth-aachen.de>
//
//          Institute of Communications Engineering
//          RWTH Aachen University

#include "_highgui.h"

// required to enable some functions used here...
#define XINE_ENABLE_EXPERIMENTAL_FEATURES

#include <cv.h>
#include <cassert>

extern "C"
{
#include <xine.h>
	//#include <xine/xineutils.h>

	// forward declaration from <xine/xineutils.h>
	const char *xine_get_homedir( void );
}

typedef struct CvCaptureAVI_XINE
{
	/// method call table
	CvCaptureVTable * vtable;

	xine_t * xine;
	xine_stream_t * stream;
	xine_video_port_t * vo_port;

	/// frame returned by xine_get_next_video_frame()
	xine_video_frame_t xine_frame;

	IplImage	* yuv_frame;
	IplImage	* bgr_frame;

	/// image dimansions of the input stream.
	CvSize	size;

	/// framenumber of the last frame received from xine_get_next_video_frame().
	/// note: always keep this value updated !!!!
	int	frame_number;

	/// framerate of the opened stream
	double	frame_rate;

	/// duration of a frame in stream
	double	frame_duration;

	/// indicated if input is seekable
	bool	seekable;

}
CvCaptureAVI_XINE;

// 4:2:2 interleaved -> BGR
static void icvYUY2toBGR( CvCaptureAVI_XINE * capture )
{
	uint8_t * v	= capture->xine_frame.data;
	int offset;
	for ( int y = 0; y < capture->yuv_frame->height; y++ )
	{
		offset	= y * capture->yuv_frame->widthStep;

		for ( int x = 0; x < capture->yuv_frame->width; x++, offset += 3 )
		{
			capture->yuv_frame->imageData[ offset + 1 ] = v[ 3 ];
			capture->yuv_frame->imageData[ offset + 2 ] = v[ 1 ];
			if ( x & 1 )
			{
				capture->yuv_frame->imageData[ offset ] = v[ 2 ];
				v += 4;
			}
			else
			{
				capture->yuv_frame->imageData[ offset ] = v[ 0 ];
			}
		}
	}

	// convert to BGR
	cvCvtColor( capture->yuv_frame, capture->bgr_frame, CV_YCrCb2BGR );
}

// 4:2:0 planary -> BGR
static void icvYV12toBGR( CvCaptureAVI_XINE * capture )
{
	IplImage * yuv	= capture->yuv_frame;
	int	w_Y	= capture->size.width;
	int	h_Y	= capture->size.height;

	int	w_UV	= w_Y >> 1;

	int	size_Y	= w_Y * h_Y;
	int	size_UV	= size_Y / 4;

	int	line	= yuv->widthStep;

	uint8_t * addr_Y = capture->xine_frame.data;
	uint8_t * addr_U = addr_Y + size_Y;
	uint8_t * addr_V = addr_U + size_UV;

	// YYYY..UU.VV. -> BGRBGRBGR...
	for ( int y = 0; y < h_Y; y++ )
	{
		int offset = y * line;
		for ( int x = 0; x < w_Y; x++, offset += 3 )
		{
			/*
			if ( x&1 )
			{
				addr_U++; addr_V++;
			}
			*/
			int one_zero = x & 1;
			addr_U += one_zero;
			addr_V += one_zero;

			yuv->imageData[ offset ] = *( addr_Y++ );
			yuv->imageData[ offset + 1 ] = *addr_U;
			yuv->imageData[ offset + 2 ] = *addr_V;
		}

		if ( y & 1 )
		{
			addr_U -= w_UV;
			addr_V -= w_UV;
		}
	}

	/* convert to BGR */
	cvCvtColor( capture->yuv_frame, capture->bgr_frame, CV_YCrCb2BGR );
}

static void icvCloseAVI_XINE( CvCaptureAVI_XINE* capture )
{
	xine_free_video_frame( capture->vo_port, &capture->xine_frame );

	if ( capture->yuv_frame ) cvReleaseImage( &capture->yuv_frame );
	if ( capture->bgr_frame ) cvReleaseImage( &capture->bgr_frame );

	xine_close( capture->stream );
	//	xine_dispose( capture->stream );

	if ( capture->vo_port ) xine_close_video_driver( capture->xine, capture->vo_port );

	xine_exit( capture->xine );
}

/**
 * CHECKS IF THE STREAM IN * capture IS SEEKABLE.
**/
static void icvCheckSeekAVI_XINE( CvCaptureAVI_XINE * capture )
{
	OPENCV_ASSERT ( capture,                        "icvCheckSeekAVI_XINE( CvCaptureAVI_XINE* )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvCheckSeekAVI_XINE( CvCaptureAVI_XINE* )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvCheckSeekAVI_XINE( CvCaptureAVI_XINE* )", "illegal capture->vo_port");

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvCheckSeekAVI_XINE ... start\n" );
#endif

	// temp. frame for testing.
	xine_video_frame_t tmp;
	// try to seek to a future frame...
	xine_play( capture->stream, 0, 300 ); /* 300msec */
	// try to receive the frame...
	xine_get_next_video_frame( capture->vo_port, &tmp );
	// if the framenumber is still 0, we can't use the xine seek functionality
	capture->seekable = ( tmp.frame_number != 0 );
	// reset stream
	xine_play( capture->stream, 0, 0 );
	// release xine_frame
	xine_free_video_frame( capture->vo_port, &tmp );

#ifndef NDEBUG
	if ( capture->seekable )
		fprintf( stderr, "(DEBUG) icvCheckSeekAVI_XINE: Input is seekable, using XINE seek implementation.\n" );
	else
		fprintf( stderr, "(DEBUG) icvCheckSeekAVI_XINE: Input is NOT seekable, using fallback function.\n" );

	fprintf( stderr, "(DEBUG) icvCheckSeekAVI_XINE ... end\n" );
#endif
}

static int icvOpenAVI_XINE( CvCaptureAVI_XINE* capture, const char* filename )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvOpenAVI_XINE ... start\n" );
#endif

	char configfile[ 2048 ];

	capture->xine = xine_new();
	sprintf( configfile, "%s%s", xine_get_homedir(), "/.xine/config" );

	xine_config_load( capture->xine, configfile );
	xine_init( capture->xine );

	xine_engine_set_param( capture->xine, 0, 0 );
	capture->vo_port = xine_new_framegrab_video_port( capture->xine );
	if ( capture->vo_port == NULL )
	{
		printf( "(ERROR)icvOpenAVI_XINE(): Unable to initialize video driver.\n" );
		return 0;
	}

	capture->stream = xine_stream_new( capture->xine, NULL, capture->vo_port );

	if ( !xine_open( capture->stream, filename ) )
	{
		printf( "(ERROR)icvOpenAVI_XINE(): Unable to open source '%s'\n", filename );
		return 0;
	}
	// reset stream...
	xine_play( capture->stream, 0, 0 );

	// initialize some internals...
	capture->frame_number = 0;

	if ( !xine_get_next_video_frame( capture->vo_port, &capture->xine_frame ) )
	{
#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvOpenAVI_XINE ... failed!\n" );
#endif
		return 0;
	}

	capture->size = cvSize( capture->xine_frame.width, capture->xine_frame.height );
	capture->yuv_frame = cvCreateImage( capture->size, IPL_DEPTH_8U, 3 );
	capture->bgr_frame = cvCreateImage( capture->size, IPL_DEPTH_8U, 3 );

	xine_free_video_frame( capture->vo_port, &capture->xine_frame );
	capture->xine_frame.data[ 0 ] = 0;

	icvCheckSeekAVI_XINE( capture );

	capture->frame_duration = xine_get_stream_info( capture->stream, XINE_STREAM_INFO_FRAME_DURATION ) / 90.;
	capture->frame_rate = 1000 / capture->frame_duration;

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) frame_duration = %f, framerate = %f\n", capture->frame_duration, capture->frame_rate );
#endif

	OPENCV_ASSERT ( capture->yuv_frame,
                        "icvOpenAVI_XINE( CvCaptureAVI_XINE *, const char *)", "couldn't create yuv frame");

	OPENCV_ASSERT ( capture->bgr_frame,
                        "icvOpenAVI_XINE( CvCaptureAVI_XINE *, const char *)", "couldn't create bgr frame");

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvOpenAVI_XINE ... end\n" );
#endif
	return 1;
}

static int icvGrabFrameAVI_XINE( CvCaptureAVI_XINE* capture )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvGrabFrameAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvGrabFrameAVI_XINE( CvCaptureAVI_XINE * )", "illegal capture");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvGrabFrameAVI_XINE( CvCaptureAVI_XINE * )", "illegal capture->vo_port");

	int res = xine_get_next_video_frame( capture->vo_port, &capture->xine_frame );

	/* always keep internal framenumber updated !!! */
	if ( res ) capture->frame_number++;

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvGrabFrameAVI_XINE ... end\n" );
#endif
	return res;
}

static const IplImage* icvRetrieveFrameAVI_XINE( CvCaptureAVI_XINE* capture )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvRetrieveFrameAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvRetrieveFrameAVI_XINE( CvCaptureAVI_XINE * )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvRetrieveFrameAVI_XINE( CvCaptureAVI_XINE * )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvRetrieveFrameAVI_XINE( CvCaptureAVI_XINE * )", "illegal capture->vo_port");

	/* no frame grabbed yet? so let's do it now! */
	int res = 0;
	if ( capture->xine_frame.data == 0 )
	{
		res = icvGrabFrameAVI_XINE( capture );
	}
	else
	{
		res = 1;
	}

	if ( res )
	{
		switch ( capture->xine_frame.colorspace )
		{
				case XINE_IMGFMT_YV12: icvYV12toBGR( capture );
#ifndef NDEBUG
				printf( "(DEBUG)icvRetrieveFrameAVI_XINE: converted YV12 to BGR.\n" );
#endif
				break;

				case XINE_IMGFMT_YUY2: icvYUY2toBGR( capture );
#ifndef NDEBUG
				printf( "(DEBUG)icvRetrieveFrameAVI_XINE: converted YUY2 to BGR.\n" );
#endif
				break;
				case XINE_IMGFMT_XVMC: printf( "(ERROR)icvRetrieveFrameAVI_XINE: XVMC format not supported!\n" );
				break;

				case XINE_IMGFMT_XXMC: printf( "(ERROR)icvRetrieveFrameAVI_XINE: XXMC format not supported!\n" );
				break;

				default: printf( "(ERROR)icvRetrieveFrameAVI_XINE: unknown color/pixel format!\n" );
		}

		/* always release last xine_frame, not needed anymore, but store its frame_number in *capture ! */
		xine_free_video_frame( capture->vo_port, &capture->xine_frame );
		capture->xine_frame.data = 0;

#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvRetrieveFrameAVI_XINE ... end\n" );
#endif
		return capture->bgr_frame;
	}

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvRetrieveFrameAVI_XINE ... failed!\n" );
#endif
	return 0;
}

/**
 * THIS FUNCTION IS A FALLBACK FUNCTION FOR THE CASE THAT THE XINE SEEK IMPLEMENTATION
 * DOESN'T WORK WITH THE ACTUAL INPUT. THIS FUNCTION IS ONLY USED IN THE CASE OF AN EMERGENCY,
 * BECAUSE IT IS VERY SLOW !
**/
static int icvOldSeekFrameAVI_XINE( CvCaptureAVI_XINE* capture, int f )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvOldSeekFrameAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvRetricvOldSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvOldSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvOldSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->vo_port");

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream ) return 0;

	// no need to seek if we are already there...
	if ( f == capture->frame_number )
	{
#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvOldSeekFrameAVI_XINE ... end\n" );
#endif
		return 1;
	}
	// if the requested position is behind out actual position,
	// we just need to read the remaining amount of frames until we are there.
	else if ( f > capture->frame_number )
	{
		for ( ;capture->frame_number < f;capture->frame_number++ )
			/// un-increment framenumber grabbing failed
			if ( !xine_get_next_video_frame( capture->vo_port, &capture->xine_frame ) )
			{
				capture->frame_number--;
				break;
			}
			else
			{
				xine_free_video_frame( capture->vo_port, &capture->xine_frame );
			}
	}
	// otherwise we need to reset the stream and
	// start reading frames from the beginning.
	else // f < capture->frame_number
	{
		/// reset stream, should also work with non-seekable input
		xine_play( capture->stream, 0, 0 );
		/// read frames until we are at the requested frame
		for ( capture->frame_number = 0; capture->frame_number < f; capture->frame_number++ )
			/// un-increment last framenumber if grabbing failed
			if ( !xine_get_next_video_frame( capture->vo_port, &capture->xine_frame ) )
			{
				capture->frame_number--;
				break;
			}
			else
			{
				xine_free_video_frame( capture->vo_port, &capture->xine_frame );
			}
	}

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvOldSeekFrameAVI_XINE ... end\n" );
#endif
	return ( f == capture->frame_number ) ? 1 : 0;
}

static int icvSeekFrameAVI_XINE( CvCaptureAVI_XINE* capture, int f )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvSeekFrameAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->vo_port");

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream ) return 0;

	if ( capture->seekable )
	{

		/// use xinelib's seek functionality
		int new_time = ( int ) ( ( f + 1 ) * ( float ) capture->frame_duration );

#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) calling xine_play()" );
#endif
		if ( xine_play( capture->stream, 0, new_time ) )
		{
#ifndef NDEBUG
			fprintf( stderr, "ok\n" );
			fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... end\n" );
#endif
			capture->frame_number = f;
			return 1;
		}
		else
		{
#ifndef NDEBUG
			fprintf( stderr, "failed\n" );
			fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... failed\n" );
#endif
			return 0;
		}
	}
	else
	{
#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... end\n" );
#endif
		return icvOldSeekFrameAVI_XINE( capture, f );
	}
}

static int icvSeekTimeAVI_XINE( CvCaptureAVI_XINE* capture, int t )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSeekTimeAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvSeekTimeAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvSeekTimeAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvSeekTimeAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->vo_port");

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSeekTimeAVI_XINE ... start\n" );
#endif

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream ) return 0;

	if ( capture->seekable )
	{
		/// use xinelib's seek functionality
		if ( xine_play( capture->stream, 0, t ) )
		{
			capture->frame_number = ( int ) ( ( float ) t * capture->frame_rate / 1000 );
#ifndef NDEBUG
			fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... end\n" );
#endif
			return 1;
		}
		else
		{
#ifndef NDEBUG
			fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ... failed!\n" );
#endif
			return 0;
		}
	}
	else
	{
		int new_frame = ( int ) ( ( float ) t * capture->frame_rate / 1000 );
#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvSeekFrameAVI_XINE ....end\n" );
#endif
		return icvOldSeekFrameAVI_XINE( capture, new_frame );
	}
}

static int icvSeekRatioAVI_XINE( CvCaptureAVI_XINE* capture, double ratio )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSeekRatioAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvSeekRatioAVI_XINE( CvCaptureAVI_XINE *, double )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvSeekRatioAVI_XINE( CvCaptureAVI_XINE *, double )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvSeekRatioAVI_XINE( CvCaptureAVI_XINE *, double )", "illegal capture->vo_port");

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream ) return 0;

	/// ratio must be [0..1]
	if ( ratio > 1 || ratio < 0 ) return 0;

	if ( capture->seekable )
	{
	// TODO: FIX IT, DOESN'T WORK PROPERLY, YET...!
		int pos_t, pos_l, length;
		xine_get_pos_length( capture->stream, &pos_l, &pos_t, &length );
		fprintf( stderr, "ratio on GetProperty(): %n\n", pos_l );

		/// use xinelib's seek functionality
		if ( xine_play( capture->stream, (int)(ratio*(float)length), 0 ) )
		{
			capture->frame_number = ( int ) ( ratio*length / capture->frame_duration );
		}
		else
		{
#ifndef NDEBUG
			fprintf( stderr, "(DEBUG) icvSeekRatioAVI_XINE ... failed!\n" );
#endif
			return 0;
		}
	}
	else
	{
		/// TODO: fill it !
		fprintf( stderr, "icvSeekRatioAVI_XINE(): Seek not supported by stream !\n" );
		fprintf( stderr, "icvSeekRatioAVI_XINE(): (seek in stream with NO seek support NOT implemented...yet!)\n" );
#ifndef NDEBUG
		fprintf( stderr, "(DEBUG) icvSeekRatioAVI_XINE ... failed!\n" );
#endif
		return 0;
	}

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSeekRatioAVI_XINE ... end!\n" );
#endif
	return 1;
}

static double icvGetPropertyAVI_XINE( CvCaptureAVI_XINE* capture, int property_id )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvGetPropertyAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvGetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvGetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvGetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->vo_port");
	OPENCV_ASSERT ( capture->xine,
                        "icvGetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->xine");
	OPENCV_ASSERT ( capture->bgr_frame,
                        "icvGetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->bgr_frame");

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream || !capture->bgr_frame || !capture->xine || !capture->vo_port ) return 0

	int pos_t, pos_l, length;
	xine_get_pos_length( capture->stream, &pos_l, &pos_t, &length );
	fprintf( stderr, "ratio on GetProperty(): %i\n", pos_l );

	switch ( property_id )
	{
			/// return actual position in msec
			case CV_CAP_PROP_POS_MSEC:
			if ( !capture->seekable )
			{
				fprintf( stderr, "(ERROR) GetPropertyAVI_XINE(CV_CAP_PROP_POS_MSEC:\n" );
				fprintf( stderr, "	Stream is NOT seekable, so position info may NOT be valid !!\n" );
			}
			return pos_t;

			/// return actual frame number
			case CV_CAP_PROP_POS_FRAMES:
			/// we insist the capture->frame_number to be remain updated !!!!
			return capture->frame_number;

			/// return actual position ratio in the range [0..1] depending on
			/// the total length of the stream and the actual position
			case CV_CAP_PROP_POS_AVI_RATIO:
			if ( !capture->seekable )
			{
				fprintf( stderr, "(ERROR) GetPropertyAVI_XINE(CV_CAP_PROP_POS_AVI_RATIO:\n" );
				fprintf( stderr, "	Stream is NOT seekable, so ratio info may NOT be valid !!\n" );
			}
			if ( length == 0 ) break;
			else return pos_l / 65535;

			/// return width of image source
			case CV_CAP_PROP_FRAME_WIDTH:
			return capture->size.width;

			/// return height of image source
			case CV_CAP_PROP_FRAME_HEIGHT:
			return capture->size.height;

			/// return framerate of stream
			case CV_CAP_PROP_FPS:
			if ( !capture->seekable )
			{
				fprintf( stderr, "(ERROR) GetPropertyAVI_XINE(CV_CAP_PROP_FPS:\n" );
				fprintf( stderr, "	Stream is NOT seekable, so FPS info may NOT be valid !!\n" );
			}
			return capture->frame_rate;

			/// return four-character-code (FOURCC) of source's codec
			case CV_CAP_PROP_FOURCC:
			return ( double ) xine_get_stream_info( capture->stream, XINE_STREAM_INFO_VIDEO_FOURCC );
	}

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvGetPropertyAVI_XINE ... failed!\n" );
#endif

	return 0;
}

static int icvSetPropertyAVI_XINE( CvCaptureAVI_XINE* capture,
                                   int property_id, double value )
{
#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSetPropertyAVI_XINE ... start\n" );
#endif

	OPENCV_ASSERT ( capture,
                        "icvSetPropertyAVI_XINE( CvCaptureAVI_XINE *, int, double )", "illegal capture");
	OPENCV_ASSERT ( capture->stream,
                        "icvGetPropericvSetPropertyAVI_XINE( CvCaptureAVI_XINE *, int )", "illegal capture->stream");
	OPENCV_ASSERT ( capture->vo_port,
                        "icvSetPropertyAVI_XINE( CvCaptureAVI_XINE *, int, double )", "illegal capture->vo_port");

// not needed tnx to asserts...
	// we need a valid capture context and it's stream to seek through
//	if ( !capture || !capture->stream || !capture->bgr_frame || !capture->xine || !capture->vo_port ) return 0

#ifndef NDEBUG
	fprintf( stderr, "(DEBUG) icvSetPropertyAVI_XINE: seeking to value %f ... ", value );
#endif

	switch ( property_id )
	{
			/// set (seek to) position in msec
			case CV_CAP_PROP_POS_MSEC:
			return icvSeekTimeAVI_XINE( capture, ( int ) value );

			/// set (seek to) frame number
			case CV_CAP_PROP_POS_FRAMES:
			return icvSeekFrameAVI_XINE( capture, ( int ) value );

			/// set (seek to) position ratio in the range [0..1] depending on
			/// the total length of the stream and the actual position
			case CV_CAP_PROP_POS_AVI_RATIO:
			return icvSeekRatioAVI_XINE( capture, value );

			default:
#ifndef NDEBUG
			fprintf( stderr, "(DEBUG) icvSetPropertyAVI_XINE ... failed!\n" );
#endif

			return 0;
	}
}

static CvCaptureVTable captureAVI_XINE_vtable =
{
	6,
	( CvCaptureCloseFunc ) icvCloseAVI_XINE,
	( CvCaptureGrabFrameFunc ) icvGrabFrameAVI_XINE,
	( CvCaptureRetrieveFrameFunc ) icvRetrieveFrameAVI_XINE,
	( CvCaptureGetPropertyFunc ) icvGetPropertyAVI_XINE,
	( CvCaptureSetPropertyFunc ) icvSetPropertyAVI_XINE,
	( CvCaptureGetDescriptionFunc ) 0
};

CvCapture* cvCaptureFromFile_XINE( const char* filename )
{
	// construct capture struct
	CvCaptureAVI_XINE * capture = ( CvCaptureAVI_XINE* ) cvAlloc ( sizeof ( CvCaptureAVI_XINE ) );
	memset( capture, 0, sizeof ( CvCaptureAVI_XINE ) );
	capture->vtable = &captureAVI_XINE_vtable;

	// initialize XINE
	if ( !icvOpenAVI_XINE( capture, filename ) )
		return 0;

	OPENCV_ASSERT ( capture,
                        "cvCaptureFromFile_XINE( const char * )", "couldn't create capture");

	return ( CvCapture* ) capture;

}

#undef NDEBUG


text:
<?php

namespace ZF\Apigility\Admin\InputFilter\Validator;

class ServiceNameValidator extends AbstractValidator
{
    const SERVICE_NAME = 'serviceName';

    /**
     * @var array
     */
    protected $messageTemplates = [
        self::SERVICE_NAME => "'%value%' is not a valid service name"
    ];

    /**
     * @param  mixed $value
     * @return bool
     */
    public function isValid($value)
    {
        $this->setValue($value);

        if (! $this->isValidWordInPhp($value)) {
            $this->error(self::SERVICE_NAME);
            return false;
        }

        return true;
    }
}


text:
package gov.nist.registry.common2.registry;

import gov.nist.registry.common2.exception.MetadataException;
import gov.nist.registry.common2.exception.MetadataValidationException;
import gov.nist.registry.common2.exception.XdsInternalException;
import gov.nist.registry.common2.xml.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Validator {
	private static final Log log = LogFactory.getLog(Validator.class);
	Metadata m;
	StringBuffer errs = new StringBuffer();
	boolean error = false;
	OMElement test_assertions;

	public Validator(Metadata m) {
		this.m = m;
	}

	public Validator(OMElement test_assertions) {
		this.test_assertions = test_assertions;
	}

	public Validator(File test_assertion_file, String subset_name) throws XdsInternalException {
		test_assertions = Util.parse_xml(test_assertion_file);
		if (subset_name != null) {
			test_assertions = MetadataSupport.firstChildWithLocalName(test_assertions, subset_name);
			if ( test_assertions == null)
				throw new XdsInternalException("Validator: assertion subset " + subset_name + " not found in file " + test_assertion_file);
		}
	}

	// return is ArrayList of ArrayLists.  Each internal ArrayList has two elements, The first is testname, the second is status, third
	// is errors
	public List<List> getPatterns() throws MetadataException {
		List<List> patterns = new ArrayList<List>();

		clearError();
		List<String> stat = buildStatus("hasSubmissionSet",hasSubmissionSet());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("ssApproved",ssApproved());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("docsApproved",docsApproved());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("ss1Doc",ss1Doc());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("ss2Doc",ss2Doc());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("sswithOneFol",sswithOneFol());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("sswithOneDocOneFol",sswithOneDocOneFol());
		if (stat != null) patterns.add(stat);

		clearError();
		stat = buildStatus("sswithTwoDocOneFolOneDocInFol", sswithTwoDocOneFolOneDocInFol());
		if (stat != null) patterns.add(stat);

		return patterns;
	}

	List<String> mkList(String s1, String s2, String s3) {
		List<String> al = new ArrayList<String> ();
		al.add(s1);
		al.add(s2);
		al.add(s3);
		return al;
	}

	List<String> buildStatus(String testname, boolean status) {
		if (status) return mkList(testname, "true", null);
		return null;
//		String errs = getErrors();
//		if (errs == null || errs.equals("")) return mkArrayList(testname, "false", null);
//		return mkArrayList(testname, "false", errs);
	}

	void err(String msg) {
		errs.append("\nValidator: ");
		errs.append(msg);
		errs.append('\n');
		error = true;
	}

	void clearError() {
		error = false;
		errs = new StringBuffer();
	}

	public boolean hasError() {
		return error;
	}

	public String getErrors() {
		return errs.toString();
	}

	public boolean hasObjectRefs(int count) throws XdsInternalException {
		if (m.getOriginal().size() != count) {
			err("Found " + m.getOriginal().size() + " ObjectRefs instead of " + count);
			return false;
		}
		return true;
	}

	public boolean hasSubmissionSet() {
		if (m.getSubmissionSet() == null) {
			err("No Submission Set found");
			return false;
		}
		return true;
	}

	public boolean hasNoSubmissionSet() {
		if (m.getSubmissionSet() != null)  {
			err("Submission Set found");
			return false;
		}
		return true;
	}

	public boolean hasDocuments(int count) {
		if (m.getExtrinsicObjects().size() != count) {
			err("Found " + m.getExtrinsicObjects().size() + " Documents instead of " + count);
			return false;
		}
		return true;
	}

	public boolean hasFolders(int count) {
		if (m.getFolders().size() != count)  {
			err("Found " + m.getFolders().size() + " Folders instead of " + count);
			return false;
		}
		return true;
	}

	public boolean hasSubmissionSets(int count) {
		if (m.getSubmissionSets().size() != count)  {
			err("Found " + m.getSubmissionSets().size() + " SubmissionSets instead of " + count);
			return false;
		}
		return true;
	}

	public boolean hasAssociations(int count) {
		if (m.getAssociations().size() != count) {
			err("Found " + m.getAssociations().size() + " Associations instead of " + count);
			return false;
		}
		return true;
	}

	String att_val(OMElement ele, QName att_name) {
		String val = ele.getAttributeValue(att_name);
		if (val == null)
			val = "";
		return val;
	}

	public OMElement hasAssociation(OMElement source, OMElement target, String type) throws MetadataException {
		String source_id = att_val(source, MetadataSupport.id_qname);
		String target_id = att_val(target, MetadataSupport.id_qname);
		String type1 = (m.isVersion2()) ? type : MetadataSupport.association_type_namespace + type;

		List asss = m.getAssociations();
		for (int i=0; i<asss.size(); i++) {
			OMElement a = (OMElement) asss.get(i);
			if (  !att_val(a, MetadataSupport.source_object_qname).equals(source_id) )
				continue;
			if (  !att_val(a, MetadataSupport.target_object_qname).equals(target_id) )
				continue;
			if (  !att_val(a, MetadataSupport.association_type_qname).equals(type1) )
				continue;
			return a;
		}
		err(type + " assocation missing between sourceObject " +
				m.getIdentifyingString(source_id) +
				" and targetObject " +
				m.getIdentifyingString(target_id) +
				" expected " + type1);
		return null;
	}

	public OMElement hasAssociationWithOneTarget(OMElement source, List<OMElement> targets, String type) throws MetadataException {
		String source_id = att_val(source, MetadataSupport.id_qname);
		List<String> target_ids = new ArrayList<String>();
		for (OMElement tgt : targets) {
			String id = att_val(tgt, MetadataSupport.id_qname);
			target_ids.add(id);
		}
		String type1 = (m.isVersion2()) ? type : MetadataSupport.association_type_namespace + type;

		List asss = m.getAssociations();
		for (int i=0; i<asss.size(); i++) {
			OMElement a = (OMElement) asss.get(i);
			if (  !att_val(a, MetadataSupport.source_object_qname).equals(source_id) )
				continue; //error

			boolean found_target = false;
			for (String id : target_ids) {
				if (  att_val(a, MetadataSupport.target_object_qname).equals(id) )
					found_target = true;
			}
			if ( !found_target )
				continue; //error

			if (  !att_val(a, MetadataSupport.association_type_qname).equals(type1) )
				continue; // error
			return a;
		}
		err(type + " assocation missing between sourceObject " +
				m.getIdentifyingString(source_id) +
				" and targetObject (one of) " +
				getIdentifyingStrings(target_ids) +
				" expected " + type1);
		return null;
	}

	List<String> getIdentifyingStrings(List<String> target_ids) throws MetadataException {
		List<String> idents = new ArrayList<String>();
		for (String id : target_ids) {
			idents.add(m.getIdentifyingString(id));
		}
		return idents;
	}

	public boolean ss1Doc() throws MetadataException {
		this.hasSubmissionSet();
		this.hasDocuments(1);
		this.hasAssociations(1);
		if (this.hasError())
			return false;

		if (this.hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember") != null)
			return true;
		return false;
	}

	public boolean ss2Doc() throws MetadataException {
		this.hasSubmissionSet();
		this.hasDocuments(2);
		this.hasAssociations(2);
		if (this.hasError())
			return false;

		if ( this.hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember") != null) return false;
		if ( this.hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(1), "HasMember") != null) return false;
		return true;
	}

	public boolean hasRplc() throws MetadataException {
		String docUuid = null;
		boolean found = false;

		for (OMElement a : m.getAssociations()) {
			String type = m.getSimpleAssocType(a);
			if (type.equals("RPLC")) {
				found = true;
				if (docUuid == null)
					docUuid = m.getAssocTarget(a);
				else {
					if (docUuid.equals(m.getAssocTarget(a)))
						throw new MetadataException("HasRPLC test: multiple RPLC associations found for same Document");
				}
			}
		}

		return found;
	}

	public boolean docsApproved() throws MetadataException {
		boolean stat = false;
		for (OMElement eo : m.getExtrinsicObjects()) {
			String status = m.stripNamespace(eo.getAttributeValue(MetadataSupport.status_qname));
			if ( status == null || !status.equals("Approved")) {
				err("ExtrinsicObject " + eo.getAttributeValue(MetadataSupport.id_qname) + " has status " + status + " instead of 'Approved'");
				return false;
			}
			stat = true;
		}
		return stat;
	}

	public boolean folsApproved() throws MetadataException {
		for (OMElement fol : m.getFolders()) {
			String status = m.stripNamespace(fol.getAttributeValue(MetadataSupport.status_qname));
			if ( status == null || !status.equals("Approved")) {
				err("Folder " + fol.getAttributeValue(MetadataSupport.id_qname) + " has status " + status + " instead of 'Approved'");
				return false;
			}
		}
		return true;
	}

	public boolean ssApproved() throws MetadataException {
		OMElement ss = m.getSubmissionSet();
		if (ss == null) {
			err("No Submission Set");
			return false;
		}
		String status = m.stripNamespace(ss.getAttributeValue(MetadataSupport.status_qname));
		if ( status == null || !status.equals("Approved")) {
			err("SubmissionSet " + ss.getAttributeValue(MetadataSupport.id_qname) + " has status " + status + " instead of 'Approved'");
			return false;
		}
		return true;
	}

	public boolean docsDeprecated() throws MetadataException {
		for (OMElement eo : m.getExtrinsicObjects()) {
			String status = m.stripNamespace(eo.getAttributeValue(MetadataSupport.status_qname));
			if ( !status.equals("Deprecated")) {
				err("ExtrinsicObject " + eo.getAttributeValue(MetadataSupport.id_qname) + " has status " + status + " instead of 'Deprecated'");
				return false;
			}
		}
		return true;
	}

	public boolean oneDocDeprecated() throws MetadataException {
		int count = 0;
		for (OMElement eo : m.getExtrinsicObjects()) {
			String status = m.stripNamespace(eo.getAttributeValue(MetadataSupport.status_qname));
			if ( status.equals("Deprecated"))
				count++;
		}
		if (count == 1)
			return true;
		err("Found " + count + " Deprecated ExtrinsicObjects instead of one");
		return false;
	}

	public boolean oneDocApproved() throws MetadataException {
		int count = 0;
		for (OMElement eo : m.getExtrinsicObjects()) {
			String status = m.stripNamespace(eo.getAttributeValue(MetadataSupport.status_qname));
			if ( status.equals("Approved"))
				count++;
		}
		if (count == 1)
			return true;
		err("Found " + count + " Approved ExtrinsicObjects instead of one");
		return false;
	}

	public void run_test_assertions(OMElement xml)  throws MetadataException, XdsInternalException, MetadataValidationException {
		Metadata m = new Metadata(xml);

		run_test_assertions(m);
	}

	public void run_test_assertions(Metadata m) throws MetadataException, XdsInternalException {
		this.m = m;

		for (Iterator it=test_assertions.getChildElements(); it.hasNext(); ) {
			OMElement ec = (OMElement) it.next();
			String ec_name = ec.getLocalName();

			if (ec_name.equals("SSwithOneDoc")) {
				ss1Doc();
				ssApproved();
			}
			else if (ec_name.equals("SSApproved")) {
				ssApproved();
			}
			else if (ec_name.equals("DocDep")) {
				docsDeprecated();
			}
			else if (ec_name.equals("DocApp")) {
				docsApproved();
			}
			else if (ec_name.equals("HasRPLC")) {
				hasRplc();
			}
			else if (ec_name.equals("OneDocDep")) {
				oneDocDeprecated();
			}
			else if (ec_name.equals("OneDocApp")) {
				oneDocApproved();
			}
			else if (ec_name.equals("FolApp")) {
				folsApproved();
			}
			else if (ec_name.equals("SSwithTwoDoc")) {
				ss2Doc();
				ssApproved();
			}
			else if (ec_name.equals("SSwithOneDocOneFol")) {
				sswithOneDocOneFol();
			}
			else if (ec_name.equals("SSwithTwoDocOneFol")) {
				sswithTwoDocOneFol();
			}
			else if (ec_name.equals("SSwithTwoDocOneFolOneDocInFol")) {
				sswithTwoDocOneFolOneDocInFol();
			}
			else if (ec_name.equals("SSwithOneFol")) {
				sswithOneFol();
			}
			else if (ec_name.equals("None")) {
				hasNoSubmissionSet();
				hasDocuments(0);
				hasFolders(0);
				if (hasError())
					continue;
				hasAssociations(0);
			}
			else if (ec_name.equals("ObjectRefs")) {
				int count = Integer.parseInt(ec.getAttributeValue(new QName("count")));
				hasObjectRefs(count);
				hasNoSubmissionSet();
				hasDocuments(0);
				hasFolders(0);
				hasAssociations(0);
			}
			else if (ec_name.equals("Documents")) {
				int count = Integer.parseInt(ec.getAttributeValue(new QName("count")));
				hasDocuments(count);
			}
			else if (ec_name.equals("Folders")) {
				int count = Integer.parseInt(ec.getAttributeValue(new QName("count")));
				hasFolders(count);
			}
			else if (ec_name.equals("SubmissionSets")) {
				int count = Integer.parseInt(ec.getAttributeValue(new QName("count")));
				hasSubmissionSets(count);
			}
			else if (ec_name.equals("Associations")) {
				int count = Integer.parseInt(ec.getAttributeValue(new QName("count")));
				hasAssociations(count);
			}
			else {
				throw new XdsInternalException("QueryTransaction: validate_expected_contents(): don't understand verification request " + ec_name);
			}

		}
	}

	public boolean sswithOneFol() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(0);
		hasFolders(1);
		if ( !hasError()) {
			hasAssociations(1);
			hasAssociation(m.getSubmissionSet(), m.getFolder(0), "HasMember");
		}
		return !hasError();
	}

	protected List<?> clone(List<?> lst) {
		List<Object> lst2 = new ArrayList<Object>();

		for (int i=0; i<lst.size(); i++)
			lst2.add(lst.get(i));

		return lst2;
	}

	public boolean addDocToExistingFolder() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(1);
		hasFolders(0);
		if ( !hasError()) {
			hasAssociations(3);
			OMElement ssA = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember");
			String ssId = m.getId(m.getSubmissionSet());

			List<OMElement> otherA = (List<OMElement>) clone(m.getAssociations());
			otherA.remove(ssA);

			OMElement doc = m.getExtrinsicObject(0);
			String docId = m.getId(doc);
			OMElement assocA = otherA.get(0);
			OMElement assocB = otherA.get(1);

			OMElement ssAssocAssoc = null;
			OMElement folDocAssoc = null;

			if (m.getSourceObject(assocA).equals(ssId)) {
				ssAssocAssoc = assocA;
				folDocAssoc = assocB;
			} else {
				ssAssocAssoc = assocB;
				folDocAssoc = assocA;
			}

			if ( 	!m.getSimpleAssocType(ssAssocAssoc).equals("HasMember") ||
					!m.getSourceObject(ssAssocAssoc).equals(ssId) ||
					!m.getTargetObject(ssAssocAssoc).equals(m.getId(folDocAssoc))
			) {
				String msg = "";
				if (!m.getSimpleAssocType(ssAssocAssoc).equals("HasMember")) msg = "association type";
				if (!m.getSourceObject(ssAssocAssoc).equals(ssId)) msg = msg + ", sourceObject";
				if (!m.getTargetObject(ssAssocAssoc).equals(m.getId(folDocAssoc))) msg = msg + ", targetObject is not the Folder-Document association";
				err("A HasMember association must link the SubmissionSet and the new Folder-to-Document Association (" + msg + ")");
			}

			if (	!m.getSimpleAssocType(folDocAssoc).equals("HasMember") ||
					!m.getTargetObject(folDocAssoc).equals(docId)
			)
				err("A HasMember association must link the existing folder and the new Document");

		}
		return !hasError();
	}

	public boolean addExistingDocToExistingFolder() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(0);
		hasFolders(0);
		if ( !hasError()) {
			hasAssociations(2);

			String ssId = m.getId(m.getSubmissionSet());

			List<OMElement> otherA = (List<OMElement>) m.getAssociations();

			OMElement assocA = otherA.get(0);
			OMElement assocB = otherA.get(1);

			OMElement ssAssocAssoc = null;
			OMElement folDocAssoc = null;

			if (m.getSourceObject(assocA).equals(ssId)) {
				ssAssocAssoc = assocA;
				folDocAssoc = assocB;
			} else {
				ssAssocAssoc = assocB;
				folDocAssoc = assocA;
			}

			if ( 	!m.getSimpleAssocType(ssAssocAssoc).equals("HasMember") ||
					!m.getSourceObject(ssAssocAssoc).equals(ssId) ||
					!m.getTargetObject(ssAssocAssoc).equals(m.getId(folDocAssoc))
			) {
				String msg = "";
				if (!m.getSimpleAssocType(ssAssocAssoc).equals("HasMember")) msg = "association type";
				if (!m.getSourceObject(ssAssocAssoc).equals(ssId)) msg = msg + ", sourceObject";
				if (!m.getTargetObject(ssAssocAssoc).equals(m.getId(folDocAssoc))) msg = msg + ", targetObject is not the Folder-Document association";
				err("A HasMember association must link the SubmissionSet and the new Folder-to-Document Association (" + msg + ")");
			}

			if (	!m.getSimpleAssocType(folDocAssoc).equals("HasMember")
			)
				err("A HasMember association must link the existing folder and the existing Document");

		}
		return !hasError();
	}

	public boolean replaceDocument() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(1);
		hasFolders(0);
		if ( !hasError()) {
			hasAssociations(2);

			String ssId = m.getId(m.getSubmissionSet());
			String docId = m.getId(m.getExtrinsicObject(0));

			List<OMElement> otherA = (List<OMElement>) m.getAssociations();

			OMElement assocA = otherA.get(0);
			OMElement assocB = otherA.get(1);

			OMElement ssDocAssoc = null;
			OMElement rplcAssoc = null;

			if (m.getSourceObject(assocA).equals(ssId)) {
				ssDocAssoc = assocA;
				rplcAssoc = assocB;
			} else {
				ssDocAssoc = assocB;
				rplcAssoc = assocA;
			}

			if ( 	!m.getSimpleAssocType(ssDocAssoc).equals("HasMember") ||
					!m.getSourceObject(ssDocAssoc).equals(ssId) ||
					!m.getTargetObject(ssDocAssoc).equals(docId)
			) {
				String msg = "";
				if (!m.getSimpleAssocType(ssDocAssoc).equals("HasMember")) msg = "association type";
				if (!m.getSourceObject(ssDocAssoc).equals(ssId)) msg = msg + ", sourceObject";
				if (!m.getTargetObject(ssDocAssoc).equals(docId)) msg = msg + ", targetObject is not the submitted document";
				err("A HasMember association must link the SubmissionSet and the new Document (" + msg + ")");
			}

			if (	!m.getSimpleAssocType(rplcAssoc).equals("RPLC") ||
					!m.getSourceObject(rplcAssoc).equals(docId)
			)
				err("A RPLC association must link the submitted Document and the existing Document");

		}
		return !hasError();
	}

	public boolean xfrmDocument() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(1);
		hasFolders(0);
		if ( !hasError()) {
			hasAssociations(2);

			String ssId = m.getId(m.getSubmissionSet());
			String docId = m.getId(m.getExtrinsicObject(0));

			List<OMElement> otherA = (List<OMElement>) m.getAssociations();

			OMElement assocA = otherA.get(0);
			OMElement assocB = otherA.get(1);

			OMElement ssDocAssoc = null;
			OMElement rplcAssoc = null;

			if (m.getSourceObject(assocA).equals(ssId)) {
				ssDocAssoc = assocA;
				rplcAssoc = assocB;
			} else {
				ssDocAssoc = assocB;
				rplcAssoc = assocA;
			}

			if ( 	!m.getSimpleAssocType(ssDocAssoc).equals("HasMember") ||
					!m.getSourceObject(ssDocAssoc).equals(ssId) ||
					!m.getTargetObject(ssDocAssoc).equals(docId)
			) {
				String msg = "";
				if (!m.getSimpleAssocType(ssDocAssoc).equals("HasMember")) msg = "association type";
				if (!m.getSourceObject(ssDocAssoc).equals(ssId)) msg = msg + ", sourceObject";
				if (!m.getTargetObject(ssDocAssoc).equals(docId)) msg = msg + ", targetObject is not the submitted document";
				err("A HasMember association must link the SubmissionSet and the new Document (" + msg + ")");
			}

			if (	!m.getSimpleAssocType(rplcAssoc).equals("XFRM") ||
					!m.getSourceObject(rplcAssoc).equals(docId)
			)
				err("A XFRM association must link the submitted Document and the existing Document");

		}
		return !hasError();
	}

	public boolean sswithOneDocOneFol() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(1);
		hasFolders(1);
		if ( !hasError()) {
			hasAssociations(4);
			List<OMElement> unknownAssocs = m.getAssociations();
			List<OMElement> folderDocAssocs = new ArrayList<OMElement>();
			OMElement a;

			a = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getSubmissionSet(), m.getFolder(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getFolder(0), m.getExtrinsicObject(0), "HasMember");
			if (a != null) {
				unknownAssocs.remove(a);
				folderDocAssocs.add(a);
			}

			a = hasAssociationWithOneTarget(m.getSubmissionSet(), folderDocAssocs, "HasMember");

		}
		return !hasError();
	}

	public boolean sswithTwoDocOneFol() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(2);
		hasFolders(1);
		if ( !hasError()) {
			hasAssociations(7);
			List<OMElement> unknownAssocs = m.getAssociations();
			List<OMElement> folderDocAssocs = new ArrayList<OMElement>();
			OMElement a;

			a = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(1), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getSubmissionSet(), m.getFolder(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getFolder(0), m.getExtrinsicObject(0), "HasMember");
			if (a != null) {
				unknownAssocs.remove(a);
				folderDocAssocs.add(a);
			}

			a = hasAssociation(m.getFolder(0), m.getExtrinsicObject(1), "HasMember");
			if (a != null) {
				unknownAssocs.remove(a);
				folderDocAssocs.add(a);
			}

			a = hasAssociationWithOneTarget(m.getSubmissionSet(), folderDocAssocs, "HasMember");
			if (a != null) {
				unknownAssocs.remove(a);
				folderDocAssocs.remove(a);
			}

			a = hasAssociationWithOneTarget(m.getSubmissionSet(), folderDocAssocs, "HasMember");

		}
		return !hasError();
	}

	public boolean sswithTwoDocOneFolOneDocInFol() throws MetadataException {
		hasSubmissionSet();
		hasDocuments(2);
		hasFolders(1);
		if ( !hasError()) {
			hasAssociations(5);
			List<OMElement> unknownAssocs = m.getAssociations();
			List<OMElement> folderDocAssocs = new ArrayList<OMElement>();
			OMElement a;

			a = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getSubmissionSet(), m.getExtrinsicObject(1), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociation(m.getSubmissionSet(), m.getFolder(0), "HasMember");
			if (a != null)
				unknownAssocs.remove(a);

			a = hasAssociationWithOneTarget(m.getFolder(0), m.getExtrinsicObjects(), "HasMember");
			if (a != null) {
				unknownAssocs.remove(a);
				a = this.hasAssociation(m.getSubmissionSet(), a, "HasMember");
				if (a != null)
					unknownAssocs.remove(a);
			}

		}
		return !hasError();
	}

	static void println(String x) { System.out.println(x); }

	static void usage() {
		println("metav ");
		println("\t[-h] - print usage message and exit");
		println("\t[-af <assertion file name>]");
		println("\t[-as <assertion set name>]");
		println("\t[-teststep <test step name>]");
		println("\t\tThe input file is inspected assuming it is in the format of a log.xml file. ");
		println("\t\tTestStep <test step name> is found ");
		println("\t\tand the query result is extracted from the Result element.");
		println("\tfile");
		System.exit(-1);
	}

	static public void main(String[] args) {
		String filename = null;
		String assertion_filename = null;
		String assertion_set_name = null;
		String test_step = null;

		for (int i=0; i<args.length; i++) {
			if (args[i].equals("-af")) {
				if (i+1 < args.length) {
					i++;
					assertion_filename = args[i];
				} else
					usage();
			}
			else if (args[i].equals("-h") ) {
				usage();
			}
			else if (args[i].equals("-teststep")) {
				if (i+1 < args.length) {
					i++;
					test_step = args[i];
				} else
					usage();
			}
			else if(args[i].equals("-as")) {
				if (i+1 < args.length) {
					i++;
					assertion_set_name = args[i];
				} else
					usage();
			}
			else if (i == args.length-1) {
				filename = args[i];
			}
			else
				usage();
		}

		if (assertion_filename == null ||
				filename == null)
			usage();

		try {
			Validator v;

			v = new Validator(new File(assertion_filename), assertion_set_name);
			OMElement input = Util.parse_xml(new File(filename));
			if (test_step == null) {
				List<String> path = new ArrayList<String>();
				path.add("TestStep");
				path.add("StoredQueryTransaction");
				path.add("Result");
				path.add("AdhocQueryResponse");
//				path.add("RegistryObjectList");
				OMElement ele_of_focus = v.find_nested_element(input, path);
				v.run_test_assertions(ele_of_focus);
			}
			else {
				OMElement step = MetadataSupport.firstChildWithLocalName(input, test_step);
				if (step == null) throw new Exception("TestStep " + test_step + " not found in file " + filename);
			}
		}
		catch (Exception e) {
			log.error(e.getClass().getName() + ": " + e.getMessage());
			System.exit(-1);
		}

	}

	OMElement find_nested_element(OMElement top_element, List<String> path) throws Exception {
		OMElement current_ele = top_element;

		for (String name : path) {
			OMElement ele = MetadataSupport.firstChildWithLocalName(current_ele, name);
			if (ele == null) throw new Exception("find_nexted_element: Cannot find element " + name + " in path " + path);
			current_ele = ele;
		}

		return current_ele;
	}

}


text:
package controller.client;
import shared.utils.PingPong;

import java.io.*;
import java.net.Socket;

/**
 * Created by niralittle on 26.10.2014.
 */
public class SocketClient {

    private static boolean isConnectionEstablished = false;

    private static final String HOST = "localhost";
    private static final int PORT = 12350;

    private static Socket socket;
    private static ObjectOutputStream oos;
    private static ObjectInputStream ois;

    public static void connect() {
        if (isConnectionEstablished) {
            return;
        }
        int tryNumber = 1;
        while (!isConnectionEstablished) {
            if (++tryNumber > 25) {
                throw new RuntimeException("Something went badly wrong.");
            }
            try {
                getConnection();
            } catch (Exception e) {
                System.out.println(SocketClient.class.getSimpleName() + ": Error while trying to establish connection but trying again.");
                //e.printStackTrace();
            }
        }
    }

    public static void getConnection() throws IOException {
        socket = new Socket(HOST, PORT);
        System.out.println(SocketClient.class.getSimpleName() + ": Connection successfully established");
        isConnectionEstablished = true;
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());

    }

    public static PingPong.ServerResponse retrieveOnRequest(PingPong.ClientRequest clientRequest)
            throws IOException {
        PingPong.ServerResponse serverResponse = null;
        if (socket == null) connect();
        oos.writeObject(clientRequest);

        try {
            serverResponse = (PingPong.ServerResponse) ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(SocketClient.class.getSimpleName() + ": Server response to request is: " + serverResponse.getParams());
        isConnectionEstablished = false;
        return serverResponse;
    }
}


text:
package innerclasses;
//: innerclasses/GreenhouseController.java
// Configure and execute the greenhouse system.
// {Args: 5000}
import innerclasses.controller.*;

public class GreenhouseController {
  public static void main(String[] args) {
    GreenhouseControls gc = new GreenhouseControls();
    // Instead of hard-wiring, you could parse
    // configuration information from a text file here:
    gc.addEvent(gc.new Bell(900));
    Event[] eventList = {
      gc.new ThermostatNight(0),
      gc.new LightOn(200),
      gc.new LightOff(400),
      gc.new WaterOn(600),
      gc.new WaterOff(800),
      gc.new ThermostatDay(1400)
    };
    gc.addEvent(gc.new Restart(2000, eventList));
    if(args.length == 1)
      gc.addEvent(
        new GreenhouseControls.Terminate(
          new Integer(args[0])));
    gc.run();
  }
} /* Output:
Bing!
Thermostat on night setting
Light is on
Light is off
Greenhouse water is on
Greenhouse water is off
Thermostat on day setting
Restarting system
Terminating
*///:~


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

namespace Ontrack.AWS.Kinesis.Model
{
    public abstract class Response
    {
    }
}


text:
package com.nimura.dialogs;

import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

/**
 * Created by Limi on 05.08.2015.
 */
public class CustomEmbeddableDialogFragment extends DialogFragment {

    /** The system calls this to get the DialogFragment's layout, regardless
     of whether it's being displayed as a dialog or an embedded fragment. */

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.custom_dialog, container, false);
    }

    /** The system calls this only when creating the layout in a dialog. */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dlg = super.onCreateDialog(savedInstanceState);
        dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dlg;
    }
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="linux">
    <words>
      <w>gruppe</w>
      <w>loginstatus</w>
    </words>
  </dictionary>
</component>


text:
package ru.ulanov.rpg.character;

import ru.ulanov.rpg.action.MeleeAttack;

/**
 * class Undead fighter.
 */
public class UndeadFighter extends Fighter {

    /**
     * constructor.
     * @param name - name.
     * @param side - side.
     */
    public UndeadFighter(String name, String side) {
        super(name, side);
        getActionBehavior().add(new MeleeAttack());
        setDamage(18);
        setNameType("Zombi");
    }

    /**
     * metod make action.
     * @param target - target.
     * @param numberOfAction - action.
     * @return boolean.
     */
    public boolean takeAction(UserChar target, int numberOfAction) {
        return getActionBehavior().get(0).action(target, this.getDamage());
    }
}


text:
"""Tests for health-related functionality."""

import python_pachyderm

def test_health():
    python_pachyderm.Client().health()


text:
import pytest
import six
from verta._internal_utils import _utils

from .. import utils

class TestMakeRequest:
    def test_200_no_history(self, client):
        """
        The util manually tracks and assigns the response history after resolving redirects.

        If no redirects occurred, the history should be empty.

        """
        response = _utils.make_request(
            "GET",
            "http://httpbin.org/status/200",
            client._conn,
        )

        assert response.status_code == 200
        assert not response.history

    # https://github.com/postmanlabs/httpbin/issues/617
    @pytest.mark.skip(reason="httpbin's /redirect-to is currently returning 404s")
    def test_301_continue(self, client):
        response = _utils.make_request(
            "GET",
            "http://httpbin.org/redirect-to",
            client._conn,
            params={
                "url": "http://httpbin.org/get",
                "status_code": 301,
            },
        )

        assert response.status_code == 200
        assert len(response.history) == 1
        assert response.history[0].status_code == 301

    # https://github.com/postmanlabs/httpbin/issues/617
    @pytest.mark.skip(reason="httpbin's /redirect-to is currently returning 404s")
    def test_302_stop(self, client):
        with pytest.raises(RuntimeError) as excinfo:
            _utils.make_request(
                "GET",
                "http://httpbin.org/redirect-to",
                client._conn,
                params={
                    "url": "http://httpbin.org/get",
                    "status_code": 302,
                },
            )
        assert str(excinfo.value).strip().startswith("received status 302")

    @pytest.mark.parametrize("status_code", [302, 400, 500])
    def test_ignore_conn_err(self, client, status_code):
        previous_setting = client.ignore_conn_err

        client.ignore_conn_err = True
        try:
            response = _utils.make_request(
                "GET",
                "http://httpbin.org/status/{}".format(status_code),
                client._conn,
            )

            assert response.status_code == 200
            assert response.json() == {}
        finally:
            client.ignore_conn_err = previous_setting

class TestBodyToJson:
    def test_json_response(self, client):
        response = _utils.make_request(
            "GET",
            "http://httpbin.org/json",
            client._conn,
        )

        assert isinstance(_utils.body_to_json(response), dict)

    def test_empty_response_error(self, client):
        response = _utils.make_request(
            "GET",
            "http://httpbin.org/status/200",
            client._conn,
        )

        with pytest.raises(ValueError) as excinfo:
            _utils.body_to_json(response)
        msg = str(excinfo.value).strip()
        assert msg.startswith("expected JSON response")
        assert "<empty response>" in msg

    def test_html_response_error(self, client):
        response = _utils.make_request(
            "GET",
            "http://httpbin.org/html",
            client._conn,
        )

        with pytest.raises(ValueError) as excinfo:
            _utils.body_to_json(response)
        msg = str(excinfo.value).strip()
        assert msg.startswith("expected JSON response")
        assert "<!DOCTYPE html>" in msg

class TestToBuiltin:
    def test_string(self):
        val = "banana"

        assert _utils.to_builtin(val) == "banana"

    def test_unicode(self):
        val = u"banana"

        assert _utils.to_builtin(val) == "banana"

    def test_bytes(self):
        val = b"banana"

        assert _utils.to_builtin(val) == "banana"

    def test_numpy_numbers(self):
        np = pytest.importorskip("numpy")

        ints = (
            np.int8(),
            np.int16(),
            np.int32(),
            np.int64(),
            np.uint8(),
            np.uint16(),
            np.uint32(),
            np.uint64(),
        )
        floats = (
            np.float32(),
            np.float64(),
        )

        for val in ints:
            assert type(_utils.to_builtin(val)) in six.integer_types

        for val in floats:
            assert type(_utils.to_builtin(val)) is float

    def test_ndarray(self):
        np = pytest.importorskip("numpy")

        int_array = np.random.randint(-36, 36, size=(12, 24))
        float_array = np.random.uniform(-36, 36, size=(12, 24))
        str_array = np.array([list("banana"), list("coconut"), list("date")])

        builtin_int_array = _utils.to_builtin(int_array)
        assert type(builtin_int_array) is list
        assert all(
            type(val) in six.integer_types for row in builtin_int_array for val in row
        )

        builtin_float_array = _utils.to_builtin(float_array)
        assert type(builtin_float_array) is list
        assert all(type(val) is float for row in builtin_float_array for val in row)

        builtin_str_array = _utils.to_builtin(str_array)
        assert type(builtin_str_array) is list
        assert all(type(val) is str for row in builtin_str_array for val in row)

    def test_series(self):
        pd = pytest.importorskip("pandas")

        int_series = pd.Series([1, 2, 3])
        float_series = pd.Series([1.0, 2.0, 3.0])
        str_series = pd.Series(["one", "two", "thr"])

        builtin_int_series = _utils.to_builtin(int_series)
        assert type(builtin_int_series) is list
        assert all(type(val) in six.integer_types for val in builtin_int_series)

        builtin_float_series = _utils.to_builtin(float_series)
        assert type(builtin_float_series) is list
        assert all(type(val) is float for val in builtin_float_series)

        builtin_str_series = _utils.to_builtin(str_series)
        assert type(builtin_str_series) is list
        assert all(type(val) is str for val in builtin_str_series)

    def test_dataframe(self):
        pd = pytest.importorskip("pandas")

        int_frame = pd.DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
        float_frame = pd.DataFrame([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]])
        str_frame = pd.DataFrame(
            [["one", "one", "one"], ["two", "two", "two"], ["thr", "thr", "thr"]]
        )

        builtin_int_frame = _utils.to_builtin(int_frame)
        assert type(builtin_int_frame) is list
        assert all(
            type(val) in six.integer_types for row in builtin_int_frame for val in row
        )

        builtin_float_frame = _utils.to_builtin(float_frame)
        assert type(builtin_float_frame) is list
        assert all(type(val) is float for row in builtin_float_frame for val in row)

        builtin_str_frame = _utils.to_builtin(str_frame)
        assert type(builtin_str_frame) is list
        assert all(type(val) is str for row in builtin_str_frame for val in row)

    def test_dict(self):
        np = pytest.importorskip("numpy")

        val = {
            "banana": np.array([1, 2, 3]),
            u"coconut": np.array([1.0, 2.0, 3.0]),
            b"date": np.array(list("banana")),
        }

        builtin_val = _utils.to_builtin(val)

        assert set(builtin_val.keys()) == {"banana", "coconut", "date"}
        assert builtin_val["banana"] == [1, 2, 3]
        assert builtin_val["coconut"] == [1.0, 2.0, 3.0]
        assert builtin_val["date"] == list("banana")

    def test_list(self):
        np = pytest.importorskip("numpy")

        int_list = list(np.array([1, 2, 3]))
        float_list = list(np.array([1.0, 2.0, 3.0]))
        str_list = list(np.array(list("banana")))

        assert not any(type(val) in six.integer_types for val in int_list)
        assert not any(type(val) is float for val in float_list)
        assert not any(type(val) is str for val in str_list)

        builtin_int_list = _utils.to_builtin(int_list)
        assert type(builtin_int_list) is list
        assert all(type(val) in six.integer_types for val in builtin_int_list)

        builtin_float_list = _utils.to_builtin(float_list)
        assert type(builtin_float_list) is list
        assert all(type(val) is float for val in builtin_float_list)

        builtin_str_list = _utils.to_builtin(str_list)
        assert type(builtin_str_list) is list
        assert all(type(val) is str for val in builtin_str_list)


text:
var BaseMaster = function() {
    'use strict';
    this.cargar = function() {
        cargarMascarasInputs();
        cargarSidenav();
        cargarModals();
        cargarCombos();
    }

    function cargarSidenav() {
        $(".button-collapse").sideNav();
    }

    function cargarMascarasInputs() {
        var $inputsFecha = $('input.fecha'),
            $inputsHora = $('input.hora');

          $inputsFecha.mask('00/00/0000');
          $inputsHora.mask('00:00');
    }

    function cargarModals() {
        $('.modal-trigger').leanModal();
    }

    function cargarCombos() {
        $('select').material_select();
    }
};

var Mapas = function () {
    'use strict';

    this.cargar = function () {

        function initMap(lat, lon) {
            var map = new google.maps.Map(document.getElementById('modal-mapa-contenedor'), {
                center: { lat: lat, lng: lon },
                scrollwheel: false,
                zoom: 16
            });
            var marker = new google.maps.Marker({
                position: { lat: lat, lng: lon },
                map: map,
                title: 'Ubicación de cochera'
            });
        };

        $('.btn-modal-mapa').on('click', function() {
            var lat = parseFloat($(this).data('latitud'));
            var lon = parseFloat($(this).data('longitud'));
            initMap(lat, lon);
        });
    }
};

var Clientes = function () {
    'use strict';

    this.cargar = function () {
        cargarCamposIdReserva();
    }

    this.GuardarFechasInicioFinReserva = function () {
        $('.btn-reservar').on('click', function () {
            var fechaInicio = $('#txtFechaInicio')[0].value || false;
            var fechaFin = $('#txtFechaFin')[0].value || false;

            if (fechaInicio && fechaFin) {
                sessionStorage.setItem('fechaInicio', fechaInicio);
                sessionStorage.setItem('fechaFin', fechaFin);
            }

        });
    }

    this.ConfirmarCochera = function () {
        setearFechasInicioFinReserva();
        $('#txtHorarioInicio, #txtHorarioFin, #txtFechaInicio, #txtFechaFin').keyup(bindiarFechasYHorarios);

    }

    function setearFechasInicioFinReserva() {
        $('#txtFechaInicio')[0].value = sessionStorage.getItem('fechaInicio') || "";
        $('#txtFechaFin')[0].value = sessionStorage.getItem('fechaFin') || "";

        sessionStorage.removeItem('fechaInicio');
        sessionStorage.removeItem('fechaFin');
    }

    function bindiarFechasYHorarios() {
        var fechaInicio = $('#txtFechaInicio')[0].value;
        var fechaFin = $('#txtFechaFin')[0].value;
        var horarioInicio = $('#txtHorarioInicio')[0].value;
        var horarioFin = $('#txtHorarioFin')[0].value;

        $('#lblFechaInicio').text('Fecha de inicio: ' + fechaInicio);
        $('#lblFechaFin').text('Fecha de fin: ' + fechaFin);

        $('#lblHoraInicio').text('Horario de inicio: ' + horarioInicio);
        $('#lblHorarioFin').text('Horario de fin: ' + horarioFin);

        calcularPrecioFinal(fechaInicio, fechaFin, horarioInicio, horarioFin);

    }

    function cargarCamposIdReserva() {
        $('.btn-reserva').on('click', function () {
            var idReserva = $(this).data('idreserva');

            $('#hdIdReserva').attr('value', idReserva);
        });
    }

    function calcularPrecioFinal(fechaInicio, fechaFin, horarioInicio, horarioFin) {
        var lblPrecioTotal = $('#lblPrecioTotal');
        var fecha1 = fechaInicio.split('/');
        var horario1 = horarioInicio.split(':');

        var fecha2 = fechaFin.split('/');
        var horario2 = horarioFin.split(':');

        try {

            var date1 = new Date(fecha1[2], fecha1[1], fecha1[0] - 1 , horario1[1], horario1[0], 0, 0);
            var date2 = new Date(fecha2[2], fecha2[1], fecha2[0] - 1, horario2[1] , horario2[0], 0, 0);

            var totalHoras = Math.abs(date1 - date2) / 36e5;;
            var precioPorhora = parseFloat($('#hdPrecioHora')[0].value);
            var precioTotal = totalHoras * precioPorhora || 0;
            lblPrecioTotal.text('Precio total: $' + precioTotal);

        } catch (e) {

        }
    }
};


text:
import { PlywoodValue } from '../datatypes/index';
import { SQLDialect } from '../dialect/baseDialect';

import { ChainableExpression, Expression, ExpressionJS, ExpressionValue } from './baseExpression';

export class LookupExpression extends ChainableExpression {
  static op = 'Lookup';
  static fromJS(parameters: ExpressionJS): LookupExpression {
    const value = ChainableExpression.jsToValue(parameters);
    value.lookupFn = parameters.lookupFn || (parameters as any).lookup;
    return new LookupExpression(value);
  }

  public lookupFn: string;

  constructor(parameters: ExpressionValue) {
    super(parameters, dummyObject);
    this._ensureOp('lookup');
    this._checkOperandTypes('STRING');
    this.lookupFn = parameters.lookupFn;
    this.type = this.operand.type;
  }

  public valueOf(): ExpressionValue {
    const value = super.valueOf();
    value.lookupFn = this.lookupFn;
    return value;
  }

  public toJS(): ExpressionJS {
    const js = super.toJS();
    js.lookupFn = this.lookupFn;
    return js;
  }

  public equals(other: LookupExpression | undefined): boolean {
    return super.equals(other) && this.lookupFn === other.lookupFn;
  }

  protected _toStringParameters(_indent?: int): string[] {
    return [Expression.safeString(this.lookupFn)];
  }

  public fullyDefined(): boolean {
    return false;
  }

  protected _calcChainableHelper(_operandValue: any): PlywoodValue {
    throw new Error('can not express as JS');
  }

  protected _getSQLChainableHelper(dialect: SQLDialect, operandSQL: string): string {
    return dialect.lookupExpression(operandSQL, this.lookupFn);
  }
}

Expression.register(LookupExpression);


text:
namespace AddinX.Ribbon.Contract.Control.Button
{
    public interface IButton : IButtonId, IButtonImage
        , IButtonExtra, IButtonSize, IButtonLabel
    {

    }
}


text:
angular.module('app.components.timer', ['ngRoute', 'app.components.TimerController'])

.config(function($routeProvider) {
  $routeProvider.when('/timer', {
    templateUrl: 'components/timer/timer.html',
    controller: 'TimerController',
    controllerAs: 'tm'
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
                               "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
	<action-mappings>
		<!--RmLoginAction的struts跳转规则-->
	    <action type="org.quickbundle.project.login.RmLoginAction" scope="request"	path="/RmLoginAction" parameter="cmd">
			<forward name="toLogin" path="/project/sample/login/login.jsp"/>
		<forward name="loginForceConfirm" path="/project/sample/login/loginForceConfirm.jsp"/>
		</action>
	</action-mappings>
</struts-config>


text:
package org.springframework.security.ldap.userdetails;

import static org.assertj.core.api.Assertions.*;

import java.util.Collection;
import java.util.Set;

import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.authentication.MockUserSearch;
import org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator;

/**
 * Tests for {@link LdapUserDetailsService}
 *
 * @author Luke Taylor
 */
public class LdapUserDetailsServiceTests {

	@Test(expected = IllegalArgumentException.class)
	public void rejectsNullSearchObject() {
		new LdapUserDetailsService(null, new NullLdapAuthoritiesPopulator());
	}

	@Test(expected = IllegalArgumentException.class)
	public void rejectsNullAuthoritiesPopulator() {
		new LdapUserDetailsService(new MockUserSearch(), null);
	}

	@Test
	public void correctAuthoritiesAreReturned() {
		DirContextAdapter userData = new DirContextAdapter(new DistinguishedName(
				"uid=joe"));

		LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch(
				userData), new MockAuthoritiesPopulator());
		service.setUserDetailsMapper(new LdapUserDetailsMapper());

		UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway");

		Set<String> authorities = AuthorityUtils
				.authorityListToSet(user.getAuthorities());
		assertThat(authorities).hasSize(1);
		assertThat(authorities.contains("ROLE_FROM_POPULATOR")).isTrue();
	}

	@Test
	public void nullPopulatorConstructorReturnsEmptyAuthoritiesList() throws Exception {
		DirContextAdapter userData = new DirContextAdapter(new DistinguishedName(
				"uid=joe"));

		LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch(
				userData));
		UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway");
		assertThat(user.getAuthorities()).isEmpty();
	}

	class MockAuthoritiesPopulator implements LdapAuthoritiesPopulator {
		public Collection<GrantedAuthority> getGrantedAuthorities(
				DirContextOperations userCtx, String username) {
			return AuthorityUtils.createAuthorityList("ROLE_FROM_POPULATOR");
		}
	}
}


text:
package com.open.tomcat.configurator;

import org.junit.Test;
import com.open.tomcat.core.ServerXMLBuilder;
import com.open.tomcat.core.TomcatCongurator;

public class ServerXMLTesting
{

    @Test
    public  void test1()
    {
        try
        {
            ServerXMLBuilder parser = new ServerXMLBuilder(TomcatCongurator.SERVER_XML_DEFAULT);

            parser.newhttpPort(7070).save();

        }catch (Exception e) {
        }
    }

}