text:
#ifndef __CC_H__
#define __CC_H__

#include "cpu.h"
#include <sys/time.h>

typedef unsigned   char    u8_t;
typedef signed     char    s8_t;
typedef unsigned   short   u16_t;
typedef signed     short   s16_t;
typedef unsigned   int    u32_t;
typedef signed     long    s32_t;
typedef u32_t mem_ptr_t;
typedef int sys_prot_t;

#define U16_F "d"
#define S16_F "d"
#define X16_F "x"
#define U32_F "d"
#define S32_F "d"
#define X32_F "x"
#define SZT_F "uz"

/* define compiler specific symbols */
#if defined (__ICCARM__)
#if !defined (__IARSTDLIB__)
#define _STRING
#ifndef memcmp
#define memcmp(dst, src, sz)			_memcmp(dst, src, sz)
#endif
#ifndef memset
#define memset(dst, val, sz)			_memset(dst, val, sz)
#endif
#ifndef memcpy
#define memcpy(dst, src, sz)			_memcpy(dst, src, sz)
#endif
#endif // __IARSTDLIB__

#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x
#define PACK_STRUCT_USE_INCLUDES

#elif defined (__CC_ARM)

#define PACK_STRUCT_BEGIN __packed
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x

#elif defined (__GNUC__)

#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT __attribute__ ((__packed__))
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x

#elif defined (__TASKING__)

#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x

#endif

#define LWIP_PLATFORM_ASSERT(x) //do { if(!(x)) while(1); } while(0)

#endif /* __CC_H__ */


text:
{-# LANGUAGE CPP #-}
module GHCJS.DOM.DelayNode (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
  module GHCJS.DOM.JSFFI.Generated.DelayNode
#else
#endif
  ) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.DelayNode
#else
#endif

redpajama_set_name: RedPajamaGithub


text:
#import "AKHotKeyManager.h"
#import "LoginUtil.h"

#import <Sparkle/SUUpdater.h>


text:
package com.torchmind.utility.cidr;

import edu.umd.cs.findbugs.annotations.NonNull;
import java.net.Inet4Address;

/**
 * Represents a 32-bit address range (as implemented by IPv4).
 *
 * @author Johannes Donath
 */
public final class AddressRange4 extends AbstractAddressRange<Inet4Address> {

  /**
   * Defines the maximum permitted amount of bits within an address prefix.
   */
  public static final int MAX_PREFIX_LENGTH = 32;

  protected AddressRange4(@NonNull Inet4Address base, int prefixLength) {
    super(base, prefixLength);
  }

  /**
   * {@inheritDoc}
   */
  @NonNull
  @Override
  public AddressRange base(@NonNull Inet4Address base) {
    return (new AddressRange4(base, this.prefixLength()));
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public long blockSize() {
    return ((long) Math.pow(2, (MAX_PREFIX_LENGTH - this.prefixLength())));
  }

  /**
   * {@inheritDoc}
   */
  @NonNull
  @Override
  public byte[] encoded() {
    return this.encoded(4);
  }

  /**
   * {@inheritDoc}
   */
  @NonNull
  @Override
  public AddressRange prefixLength(int prefixLength) {
    return (new AddressRange4(this.base(), prefixLength));
  }
}


text:
// A0IdentityProviderAuthenticator.h
//
// Copyright (c) 2014 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import "A0AuthenticationProvider.h"

@class A0Application, A0Strategy, A0UserProfile, A0Token, A0AuthParameters;

/**
 *  `A0IdentityProviderAuthenticator` provides a single interface to handle all interactions with different identity providers. Each identity provider (a class that conforms with the protocol `A0AuthenticationProvider`) to be used must be registered with this object.
 */
@interface A0IdentityProviderAuthenticator : NSObject

/**
 *  When no specific authentication provider is registered it will fallback to Safari Web Flow otherwise it will raise an error. Default is YES.
 */
@property (assign, nonatomic) BOOL useWebAsDefault;

/**
 *  Returns a shared instance of `A0IdentityProviderAuthenticator`
 *
 *  @return shared instance
 */
+ (A0IdentityProviderAuthenticator *)sharedInstance;

/**
 *  Register an array of identity providers.
 *
 *  @param authenticationProviders array of object that conforms `A0AuthenticationProvider` protocol
 *  @see -registerAuthenticationProvider:
 */
- (void)registerAuthenticationProviders:(NSArray *)authenticationProviders;

/**
 *  Register an identity provider using it's identifier, so if a provider was already registered with the same identifier, it will be replaced.
 *
 *  @param authenticationProvider object that conforms `A0AuthenticationProvider` protocol
 */
- (void)registerAuthenticationProvider:(id<A0AuthenticationProvider>)authenticationProvider;

/**
 *  Configures the authentication with the enabled identity providers in Auth0's application. Must be called at least once before trying to authenticate with any connection.
 *
 *  @param application Auth0 application with the identity provider configuration
 */
- (void)configureForApplication:(A0Application *)application;

/**
 *  Authenticates a user using an identity provider specified by `A0Strategy` and the registered method (Safari or Native).
 *  For the connection name it will use the first one by default.
 *  You can override the default connection name setting in parameters the key `connection` with the name of the connection that should be used instead.
 *
 *  @param strategy   object that represent an authentication strategy with an identity provider.
 *  @param parameters  authentication parameters for Auth0 API.
 *  @param success    block called on successful authentication with user's token info and profile
 *  @param failure    block called on error with the reason as a parameter
 */
- (void)authenticateForStrategy:(A0Strategy *)strategy
                     parameters:(A0AuthParameters *)parameters
                        success:(void(^)(A0UserProfile *profile, A0Token *token))success
                        failure:(void(^)(NSError *error))failure;

/**
 *  Checks if the given startegy has a registered authenticator (either Native or Safari).
 *
 *  @param strategy an Auth0 strategy
 *
 *  @return if the authenticator can authenticate with the strategy
 */
- (BOOL)canAuthenticateStrategy:(A0Strategy *)strategy;

/**
 *  Method to handle authentication performed by a third party native application e.g. Facebook App. It must be called from your app's AppDelegate `-application:openURL:sourceApplication:annotation:` method.
 *
 *  @param url         url with authentication result
 *  @param application application that performed the authentication
 *  @return if the URL could be handled by the application
 */
- (BOOL)handleURL:(NSURL *)url sourceApplication:(NSString *)application;

/**
 *  Clear all identity provider session information.
 */
- (void)clearSessions;

@end


text:
package info.dgjones.abora.white.collection.steppers;

import info.dgjones.abora.white.cache.InstanceCache;
import info.dgjones.abora.white.collection.arrays.SharedPtrArray;
import info.dgjones.abora.white.xpp.basic.Heaper;

public class HashSetStepper extends Stepper {
	protected SharedPtrArray myElements;
	protected int myCurrent;
	protected static InstanceCache SomeSteppers = InstanceCache.make(16);
	/*
	udanax-top.st:54158:
	Stepper subclass: #HashSetStepper
		instanceVariableNames: '
			myElements {SharedPtrArray}
			myCurrent {Int32}'
		classVariableNames: 'SomeSteppers {InstanceCache} '
		poolDictionaries: ''
		category: 'Xanadu-Collection-Steppers'!
	*/
	/*
	udanax-top.st:54164:
	(HashSetStepper getOrMakeCxxClassDescription)
		attributes: ((Set new) add: #CONCRETE; add: #NOT.A.TYPE; yourself)!
	*/
	/*
	udanax-top.st:54222:
	HashSetStepper class
		instanceVariableNames: ''!
	*/
	/*
	udanax-top.st:54225:
	(HashSetStepper getOrMakeCxxClassDescription)
		attributes: ((Set new) add: #CONCRETE; add: #NOT.A.TYPE; yourself)!
	*/

	public Heaper fetch() {
		if (myElements != null && (myCurrent < myElements.count())) {
			return myElements.fetch(myCurrent);
		} else {
			return null;
		}
		/*
		udanax-top.st:54169:HashSetStepper methodsFor: 'accessing'!
		{Heaper wimpy} fetch
			(myElements ~~ NULL and: [myCurrent < myElements count])
				ifTrue: [^myElements fetch: myCurrent]
				ifFalse: [^NULL]!
		*/
	}

	public boolean hasValue() {
		return myElements != null && (myCurrent < myElements.count());
		/*
		udanax-top.st:54174:HashSetStepper methodsFor: 'accessing'!
		{BooleanVar} hasValue
			^myElements ~~ NULL and: [myCurrent < myElements count]!
		*/
	}

	public void step() {
		myCurrent = myCurrent + 1;
		verifyEntry();
		/*
		udanax-top.st:54177:HashSetStepper methodsFor: 'accessing'!
		{void} step
			myCurrent _ myCurrent + 1.
			self verifyEntry!
		*/
	}

	public void destruct() {
		if (myElements != null) {
			myElements.shareLess();
		}
		super.destruct();
		/*
		udanax-top.st:54183:HashSetStepper methodsFor: 'protected: destruct'!
		{void} destruct
			myElements ~~ NULL ifTrue: [
				myElements shareLess].
			super destruct!
		*/
	}

	public HashSetStepper(SharedPtrArray elements, int current) {
		super();
		myElements = elements;
		myElements.shareMore();
		myCurrent = current;
		verifyEntry();
		/*
		udanax-top.st:54190:HashSetStepper methodsFor: 'protected: creation'!
		create: elements {SharedPtrArray} with: current {Int32}
			super create.
			myElements _ elements.
			myElements shareMore.
			myCurrent _ current.
			self verifyEntry!
		*/
	}

	public Stepper copy() {
		Heaper result = SomeSteppers.fetch();
		if (result == null) {
			return new HashSetStepper(myElements, myCurrent);
		} else {
			//TODO review
			return new HashSetStepper(myElements, myCurrent);
		}
		/*
		udanax-top.st:54199:HashSetStepper methodsFor: 'creation'!
		{Stepper} copy
			| result {Heaper} |
			result := SomeSteppers fetch.
			result == NULL
				ifTrue: [^ HashSetStepper create: myElements with: myCurrent]
				ifFalse: [^ (HashSetStepper new.Become: result) create: myElements with: myCurrent]!
		*/
	}

	public void destroy() {
		if (!(SomeSteppers.store(this))) {
			super.destroy();
		}
		/*
		udanax-top.st:54206:HashSetStepper methodsFor: 'creation'!
		{void} destroy
			(SomeSteppers store: self) ifFalse:
				[super destroy]!
		*/
	}

	public void verifyEntry() {
		if (myElements != null) {
			if (myCurrent < myElements.count()) {
				myCurrent = myElements.indexPast(null, myCurrent);
				if (myCurrent == -1) {
					myCurrent = myElements.count();
				}
			}
			if (!hasValue()) {
				myElements.shareLess();
				myElements = null;
			}
		}
		/*
		udanax-top.st:54212:HashSetStepper methodsFor: 'private:'!
		{void} verifyEntry
			myElements ~~ NULL ifTrue: [
				myCurrent < myElements count ifTrue: [
					myCurrent := myElements indexPast: NULL with: myCurrent.
					myCurrent == -1 ifTrue: [myCurrent := myElements count]].
				self hasValue ifFalse: [
					myElements shareLess.
					myElements := NULL]].!
		*/
	}

	public static HashSetStepper make(SharedPtrArray elements) {
		Heaper result = SomeSteppers.fetch();
		if (result == null) {
			return new HashSetStepper(elements, 0);
		} else {
			//TODO review
			return new HashSetStepper(elements, 0);
		}
		/*
		udanax-top.st:54230:HashSetStepper class methodsFor: 'pseudo constructors'!
		{Stepper} make: elements {SharedPtrArray}
			| result {Heaper} |
			result := SomeSteppers fetch.
			result == NULL
				ifTrue: [^ self create: elements with: Int32Zero]
				ifFalse: [^ (self new.Become: result) create: elements with: Int32Zero]!
		*/
	}

//	public static void initTimeNonInherited() {
//		SomeSteppers = InstanceCache.make(16);
//		/*
//		udanax-top.st:54239:HashSetStepper class methodsFor: 'smalltalk: init'!
//		initTimeNonInherited
//			SomeSteppers := InstanceCache make: 16.!
//		*/
//	}

//	public static void linkTimeNonInherited() {
//		SomeSteppers = null;
//		/*
//		udanax-top.st:54242:HashSetStepper class methodsFor: 'smalltalk: init'!
//		linkTimeNonInherited
//			SomeSteppers := NULL!
//		*/
//	}
}


text:
#ifndef MITKTWOCOMPARTMENTEXCHANGEMODELDIFFERENTIALEQUATIONS_H
#define MITKTWOCOMPARTMENTEXCHANGEMODELDIFFERENTIALEQUATIONS_H

#include "mitkNumericTwoCompartmentExchangeModel.h"

namespace mitk{
/** @class TwoCompartmentExchangeModelDifferentialEquations
 * @brief Helper Class for NumericTwoCompartmentExchangeModel: Defines the differential equations (Mass Balance Equations) in the 2 Compartment Exchange model.
 * The 2 Compartment Exchange model is defined via the mass balance equations
 * vp * dCp(t)/dt =  F * (CA(t) - Cp(t)) - PS * (Cp(t) - Ce(t))
 * ve * dCe(t)/dt = PS * (Cp(t) - Ce(t))
 * Boost ODEINT performs a stepwise numeric integration (e.g. via Runge-Kutta method) of the initial value problem
 * x' = dx/dt = f(x,t)
 * It needs an operator () (a functor) that calculates dx/dt = dxdt for a given x and t.
 * Parameters are F, PS, ve and vp and the time dependent Ca(t) =AIF, that is interpolated to the current step t
*/

class TwoCompartmentExchangeModelDifferentialEquations
{
public:

    typedef std::vector< double > AIFType;

    /** @brief Functor for differential equation of Physiological Pharmacokinetic Brix Model
     * Takes current state x = x(t) and time t and calculates the corresponding dxdt = dx/dt
    */
    void operator() (const mitk::NumericTwoCompartmentExchangeModel::state_type &x, mitk::NumericTwoCompartmentExchangeModel::state_type &dxdt, const double t)
    {
        double Ca_t = InterpolateAIFToCurrentTimeStep(t);

//        dxdt[0] = -(this->FVP + this->PSVP)*x[0] - this->PSVP*x[1]+this->FVP*Ca_t;
        dxdt[0] = (1/this->vp) * ( this->F*(Ca_t - x[0]) - this->PS*(x[0] - x[1]) );
        dxdt[1] = (1/this->ve) * this->PS * (x[0] - x[1]);

    }

    TwoCompartmentExchangeModelDifferentialEquations() : F(0), PS(0), ve(0), vp(0), m_AIF(0), m_AIFTimeGrid(0)
    {
    }

    /** @brief Initialize class with parameters F/Vp, PS/Vp, fi and fp that are free fit parameters*/
    void initialize(double Fp, double ps, double fi, double fp)
    {
        this->F = Fp;
        this->PS = ps;
        this->ve = fi;
        this->vp = fp;
    }

    void setAIF(AIFType &aif)
    {
        this->m_AIF = aif;
    }

    void setAIFTimeGrid(AIFType &grid)
    {
        this->m_AIFTimeGrid = grid;
    }

private:

    double F;
    double PS;
    double ve;
    double vp;

    AIFType m_AIF;
    AIFType m_AIFTimeGrid;

    /** @brief Internal routine to interpolate the AIF to the current time point t used for integration
     * The numerical integration of ODEINT is performed on an adaptive timegrid (adaptive step size dt) different from the time grid of the AIF and model function.
     * Thus, the AIF value Ca(t) has to be interpolated from the set AIF
     */
    double InterpolateAIFToCurrentTimeStep(double t)
    {
        double lastValue = m_AIF[0];
        double lastTime = std::numeric_limits<double>::min();

        AIFType::const_iterator posITime = m_AIFTimeGrid.begin();
        AIFType::const_iterator posValue = m_AIF.begin();

        while(t > *posITime)
        {
            lastValue = *posValue;
            lastTime = *posITime;
            ++posValue;
            ++posITime;
        }
        double weightLast = 1 - (t - lastTime)/(*posITime - lastTime);
        double weightNext = 1- (*posITime - t)/(*posITime - lastTime);
        double result = weightLast * lastValue + weightNext * (*posValue);

        return result;
    }

};
}

#endif // MITKTWOCOMPARTMENTEXCHANGEMODELDIFFERENTIALEQUATIONS_H


text:
package converter;

import tigerxml.*;
import conll.Token;
import conll.Field.Type;
import java.util.*;
import javax.xml.namespace.QName;

import framenet.corpus.AnnotationSet;

/**
 *
 *
This class is used to convert a tigerxml.Corpus object into a framenet.corpus.Corpus object or
 * a conll.Corpus object.

 *
 *

 * From TigerXML to CoNLL:

 * For each T a Token gets created. T's (and their parent Nts') features will be
 * mapped as follows:

 *

 *

 * 		T's feature attribute name
 * 		Token's Field name
 *

 *

 * 		word
 * 		FORM
 *

 *

 * 		lemma
 * 		LEMMA
 *

 *

 * 		pos
 * 		CPOSTAG
 *

 *

 * 		else
 * 		FEATS
 *

 *

 *

 *
 *

 * From TigerXML to FrameNet:

 * In FrameNet there are more elements with IDs than in TigerXML. So during the conversion they are generated sequentially according to
 * the following scheme of prefixes where the asterisk is replaced by the sequential number:
 *

 *

 *

 * 		Element
 * 		id attribute value
 *

 *

 * 		Document
 * 		d1
 *

 *

 * 		Paragraph
 * 		p1
 *

 *

 * 		AnnotationSet
 * 		as_*
 *

 *

 * 		Layer
 * 		lr_*
 *

 *

 * 		Label
 * 		lb_*
 *

 *

 * Additionally, embedded elements inherit the complete ID prefix of their parent elements, e.g. the AnnotationSets' IDs of the third
 * Sentence are as_3_1, as_3_1, as_3_1, ... .

 * The Ts' word values get concatenated to FrameNet's text element.

 * All other conversion rules are listed in the following table:
 *

 *

 * 		TigerXML
 * 		FrameNet
 *

 *

 * 		element
 * 		attribute
 * 		layer
 * 		label
 *

 *

 * 		start
 * 		end
 *

 *

 * 		edge
 * 		label
 * 		GF
 * 		first character below edge
 * 		last character below edge
 *

 *

 * 		nt
 * 		used feature
 * 		PT
 * 		first character below nt
 * 		last character below nt
 *

 *

 * 		t
 * 		for each used feature (except word)
 * 		Other
 * 		t's start index in text
 * 		t's end index in text
 *

 *

 *

 *
 */
public class TigerXmlConverter implements ConvertableIntoConll, ConvertableIntoFrameNet {

	private static final String NONTERMINAL_FEATURE_DOMAIN = "NT";

	private static final String DEFAULT_CORPUS_NAME = "Converted TigerXML Corpus";
	private static final String DEFAULT_DOCUMENT_ID = "d1";
	private static final String DEFAULT_PARAGRAPH_ID = "p1";
	private static final String DEFAULT_PARAGRAPH_DOCUMENT_ORDER = "1";
	private static final String DEFAULT_ANNOTATIONSET_ID_PREFIX = "as";
	private static final String DEFAULT_ANNOTATIONSET_STATUS = "";
	private static final String DEFAULT_LAYER_ID_PREFIX = "lr";
	private static final String DEFAULT_LABEL_ID_PREFIX = "lb";

	private static final String DEFAULT_WORD_FEATURE_NAME = "word";
	private static final String DEFAULT_LEMMA_FEATURE_NAME = "lemma";
	private static final String DEFAULT_POS_FEATURE_NAME = "pos";
	private static final String NOT_BOUND_FEATURE_VALUE = "--";

	private tigerxml.Corpus source;

	private Map<String, Type> conllFieldTypeMappings;

	private Map<String, Integer> framenetWordIndexes;

	public TigerXmlConverter(Corpus source) {
		this.source = source;
	}

	@Override
	public framenet.corpus.Corpus toFrameNet() {
		return toFrameNet(DEFAULT_CORPUS_NAME);
	}

	@Override
	public framenet.corpus.Corpus toFrameNet(String name) {
		framenetWordIndexes = new HashMap<String, Integer>();
		return convertToFramenet(name);
	}

	private framenet.corpus.Corpus convertToFramenet(String name) {
		framenet.corpus.Corpus result = new framenet.corpus.Corpus();
		result.setID(source.getId());
		result.setName(name);
		result.addDocument(createFramenetDocument(name));
		return result;
	}

	private framenet.corpus.Document createFramenetDocument(String name) {
		framenet.corpus.Document result = new framenet.corpus.Document();
		result.setID(DEFAULT_DOCUMENT_ID);
		result.setDescription(name + "'s content");
		result.addParagraph(createFramenetParagraph());
		return result;
	}

	private framenet.corpus.Paragraph createFramenetParagraph() {
		framenet.corpus.Paragraph result = new framenet.corpus.Paragraph();
		result.setID(DEFAULT_PARAGRAPH_ID);
		result.setDocumentOrder(DEFAULT_PARAGRAPH_DOCUMENT_ORDER);
		int sentenceCounter = 1;
		for (CorpusUnit sentence : getCollectedSentences()) {
			result.addSentence(createFramenetSentence(sentenceCounter++, (Sentence) sentence));
		}
		return result;
	}

	private framenet.corpus.Sentence createFramenetSentence(int sentenceNumber, Sentence sourceSentence) {
		framenet.corpus.Sentence result = new framenet.corpus.Sentence();
		result.setID(sourceSentence.getId());
		result.setText(createFramenetText(sourceSentence.getTerminals()));

		int asCounter = 1;
		String asIdSuffix = sentenceNumber + "_" + asCounter++;
		AnnotationSet defaultAnnotationSet = createFramenetAnnotationSet(asIdSuffix);

		int layerCounter = 1;
		if (source.getHead().getAnnotation().getEdgelabel() != null) {
			defaultAnnotationSet.addLayer(createGfLayer(asIdSuffix, layerCounter++, sourceSentence));
		}

		AnnotationSet remainingTerminalFeatures;
		for (Feature feature : source.getHead().getAnnotation().getFeature()) {
			if (feature.getDomain().equals(NONTERMINAL_FEATURE_DOMAIN)) {
				defaultAnnotationSet.addLayer(createPtLayer(asIdSuffix, layerCounter++, sourceSentence, feature.getName()));
			} else if (feature.getName().equals(DEFAULT_WORD_FEATURE_NAME)) {
				continue;
			} else {
				if (layerCounter > 1) {
					defaultAnnotationSet.addLayer(createOtherLayer(asIdSuffix, layerCounter, sourceSentence, feature.getName()));
					result.addAnnotationSet(defaultAnnotationSet);
					layerCounter = 1;
				} else {
					asIdSuffix = sentenceNumber + "_" + asCounter++;
					remainingTerminalFeatures = createFramenetAnnotationSet(asIdSuffix);
					remainingTerminalFeatures.addLayer(createOtherLayer(asIdSuffix, layerCounter, sourceSentence, feature.getName()));
					result.addAnnotationSet(remainingTerminalFeatures);
				}
			}
		}

		return result;
	}

	private String createFramenetText(List<T> terminals) {
		StringBuilder result = new StringBuilder();
		int wordIndex = 0;
		String word;
		for (T terminal : terminals) {
			word = terminal.getAttributeValue(DEFAULT_WORD_FEATURE_NAME);
			framenetWordIndexes.put(word, wordIndex);
			wordIndex += word.length() + 1;
			result.append(word + " ");
		}
		return result.toString().trim();
	}

	private AnnotationSet createFramenetAnnotationSet(String idSuffix) {
		AnnotationSet result = new AnnotationSet();
		result.setId(DEFAULT_ANNOTATIONSET_ID_PREFIX + idSuffix);
		result.setStatus(DEFAULT_ANNOTATIONSET_STATUS);
		return result;
	}

	private framenet.corpus.Layer createGfLayer(String idPath, int layerNumber, Sentence sourceSentence) {
		framenet.corpus.Layer result = createLayer(idPath, layerNumber, "GF");
		int labelCounter = 1;
		for (Nt nonterminal : sourceSentence.getGraph().getNonterminals().getNt()) {
			for (Edge edge : nonterminal.getEdge()) {
				if (edge.getLabel().equals(NOT_BOUND_FEATURE_VALUE)) continue;
				result.addLabel(createGfLabel(layerIdSuffix(idPath, layerNumber), labelCounter++, edge));
			}
		}
		return result;
	}

	private framenet.corpus.Layer createPtLayer(String idPath, int layerNumber, Sentence sourceSentence, String featureName) {
		framenet.corpus.Layer result = createLayer(idPath, layerNumber, "PT");
		int labelCounter = 1;
		for (Nt nt : sourceSentence.getGraph().getNonterminals().getNt()) {
			result.addLabel(createPtLabel(layerIdSuffix(idPath, layerNumber), labelCounter++, nt, featureName));
		}
		return result;
	}

	private framenet.corpus.Layer createOtherLayer(String idPath, int layerNumber, Sentence sourceSentence, String featureName) {
		framenet.corpus.Layer result = createLayer(idPath, layerNumber, "Other");
		int labelCounter = 1;
		for (T terminal : sourceSentence.getTerminals()) {
			if (terminal.getAttributeValue(featureName).equals(NOT_BOUND_FEATURE_VALUE)) continue;
			result.addLabel(createOtherLabel(layerIdSuffix(idPath, layerNumber), labelCounter++, terminal, featureName));
		}
		return result;
	}

	private framenet.corpus.Layer createLayer(String idPath, int layerNumber, String name) {
		framenet.corpus.Layer result = new framenet.corpus.Layer();
		result.setID(DEFAULT_LAYER_ID_PREFIX + layerIdSuffix(idPath, layerNumber));
		result.setName(name);
		return result;
	}

	private String layerIdSuffix(String idPath, int layerNumber) {
		return idPath + "_" + layerNumber;
	}

	private framenet.corpus.Label createGfLabel(String idPath, int labelNumber, Edge edge) {
		return createLabel(idPath, labelNumber, edge.getLabel(), edge);
	}

	private framenet.corpus.Label createPtLabel(String idPath, int labelNumber, Nt nonterminal, String featureName) {
		return createLabel(idPath, labelNumber, nonterminal.getAttributeValue(featureName), nonterminal);
	}

	private framenet.corpus.Label createOtherLabel(String idPath, int labelNumber, T terminal, String featureName) {
		return createLabel(idPath, labelNumber, terminal.getAttributeValue(featureName), terminal);
	}

	private framenet.corpus.Label createLabel(String idPath, int labelNumber, String name, Object sourceElement) {
		framenet.corpus.Label result = new framenet.corpus.Label();
		result.setID(DEFAULT_LABEL_ID_PREFIX + idPath + "_" + labelNumber);
		result.setName(name);
		result.setStart(String.valueOf(minStart(sourceElement)));
		result.setEnd(String.valueOf(maxEnd(sourceElement)));
		return result;
	}

	private int minStart(Object obj) {
		if (obj instanceof T) return startIndex((T) obj);
		if (obj instanceof Edge) return minStart(((Edge)obj).getIdref());

		int result = Integer.MAX_VALUE;
		for (Edge edge : ((Nt) obj).getEdge()) {
			if (minStart(edge) < result) {
				result = minStart(edge);
			}
		}
		return result;
	}

	private int maxEnd(Object obj) {
		if (obj instanceof T) return endIndex((T) obj);
		if (obj instanceof Edge) return maxEnd(((Edge) obj).getIdref());

		int result = 0;
		for (Edge edge : ((Nt) obj).getEdge()) {
			if (maxEnd(edge) > result) {
				result = maxEnd(edge);
			}
		}
		return result;
	}

	private int startIndex(T terminal) {
		return framenetWordIndexes.get((terminal).getAttributeValue(DEFAULT_WORD_FEATURE_NAME));
	}

	private int endIndex(T terminal) {
		String word = terminal.getAttributeValue(DEFAULT_WORD_FEATURE_NAME);
		return framenetWordIndexes.get(word) + word.length() - 1;
	}

	@Override
	public conll.Corpus toConll() {
		initConllMappings();
		return convertToConll();
	}

	private void initConllMappings() {
		conllFieldTypeMappings = new HashMap<String, Type>();
		conllFieldTypeMappings.put(DEFAULT_WORD_FEATURE_NAME, Type.FORM);
		conllFieldTypeMappings.put(DEFAULT_LEMMA_FEATURE_NAME, Type.LEMMA);
		conllFieldTypeMappings.put(DEFAULT_POS_FEATURE_NAME, Type.CPOSTAG);
	}

	private conll.Corpus convertToConll() {
		conll.Corpus result = new conll.Corpus(source.getId());
		for (CorpusUnit sentence : getCollectedSentences()) {
			result.addSentence(getSentenceFilledWithTerminals((Sentence) sentence));
		}
		return result;
	}

	private conll.Sentence getSentenceFilledWithTerminals(Sentence s) {
		conll.Sentence result = new conll.Sentence();
		for (T t : getTerminals(s)) {
			result.addToken(convertToToken(t));
		}
		return result;
	}

	private List<T> getTerminals(Sentence s) {
		return ((Sentence) s).getGraph().getTerminals().getT();
	}

	private conll.Token convertToToken(T t) {
		conll.Token result = Token.createEmptyToken();
		for (QName attributeQName : getAttributeNames(t)) {
			String attributeName = attributeQName.toString();
			String attributeValue = t.getAttributeValue(attributeQName);
			if (attributeValue.equals(NOT_BOUND_FEATURE_VALUE)) continue;
			if (isMappedToFeatureField(attributeName)) {
				result.addFeature(attributeToString(attributeName, attributeValue));
			} else {
				result.setField(conllFieldTypeMappings.get(attributeName), attributeValue);
			}
		}
		return result;
	}

	private Set<QName> getAttributeNames(T t) {
		return t.getOtherAttributes().keySet();
	}

	private boolean isMappedToFeatureField(String attributeName) {
		Type fieldToSet = conllFieldTypeMappings.get(attributeName);
		return fieldToSet == null || fieldToSet == Type.FEATS;
	}

	private String attributeToString(String attributeName, String attributeValue) {
		return attributeName + "=" + attributeValue;
	}

	private List<CorpusUnit> getCollectedSentences() {
		List<CorpusUnit> results = new LinkedList<CorpusUnit>();
		for (CorpusUnit cu : getTopLevelCorpusUnits()) {
			results.addAll(cu.getSentences());
		}
		return results;
	}

	private List<CorpusUnit> getTopLevelCorpusUnits() {
		return source.getBody().getSubcorpusOrS();
	}
}


text:
package org.geogit.web;

import org.geogit.api.GeoGIT;
import org.geogit.rest.repository.RepositoryProvider;
import org.restlet.data.Request;

import com.google.common.base.Optional;

public class SingleRepositoryProvider implements RepositoryProvider {

    private GeoGIT geogit;

    public SingleRepositoryProvider(GeoGIT geogit) {
        this.geogit = geogit;
    }

    @Override
    public Optional<GeoGIT> getGeogit(Request request) {
        return Optional.fromNullable(geogit);
    }

}


text:
$(function(){
  var video_exts = [ '.mov', '.mp4', '.flv', '.ogv' ],
  video_extension_types = {
    '.mov': 'video/mp4',
    '.mp4': 'video/mp4',
    '.ogv': 'video/ogg'
  },
  max_icons_size = 100,
  pdf_viewer = $('.pdfviewer');
  function $video_toggle_visibility($el, b)
  {
    var v = b ? 'visible' : 'hidden';
    $el.css('visibility', v);
     $el.find('.vjs-control-bar').css('visibility', v);
  }
  function video_size_update($vid_wrp, player)
  {
    var width = player.isFullWindow || player.isFullscreen()
      ? $(window).width() : player.width(),
    size = 200 / 640 * width;
    if(size > max_icons_size)
      size = max_icons_size;
    $vid_wrp.find('.vjs-control-bar')
      .css('fontSize', size + '%');
    $vid_wrp.find('.vjs-big-play-button')
      .css('fontSize', (size * 2) + '%');
  }
  pdf_viewer.bind('render-link', function(ev, data, page)
     {
       var url_str = data.url,
       file_ext = path.extname(url('path', url_str)),
       query = querystring.parse(url('?', url_str));
       // video file
       if(video_exts.indexOf(file_ext.toLowerCase()) != -1 &&
          query.waplay == 'auto' && !data.element)
       {
         data.element = $('
')[0];
         initVideo(data, page);
       }
     })
   .bind('openlink', function(ev, obj, page)
     {
       var data = obj.data,
       url_str = data.url,
       query = querystring.parse(url('?', url_str)),
       file_ext = path.extname(url('path', url_str));
       // video file
       if(video_exts.indexOf(file_ext.toLowerCase()) != -1 &&
          obj.return_value !== false)
       {
         var el = data.element._video_el || $('
')[0];
         el._link_el = data.element;
         if(!data.element._video_el)
         {
           $(data.element.parentNode).append(el);
           if(query.warect == 'full')
             $video_toggle_visibility($(data.element), false);
           data.element._video_el = el;
           data.element = el;
           data.play = 'auto';
           initVideo(data, page);
         }
         else
         {
           // this block of code is only for warect=full
           $video_toggle_visibility($(data.element), false);
           $video_toggle_visibility($(el), true);
           data.element = el;
           if(el.player)
             el.player.play();
         }
         obj.return_value = false;
       }
     })
  function initVideo(data, page)
  {
    function isAutoplay()
    {
      return query.waplay == 'auto' || data.play == 'auto';
    }
    var url_str = data.url,
    file_ext = path.extname(url('path', url_str)),
    query = querystring.parse(url('?', url_str)),
    qm_idx = url_str.indexOf('?'),
    src = qm_idx == -1 ? url_str : url_str.substring(0, qm_idx),
    type = video_extension_types[file_ext],
    $vid_wrp = $(data.element),
    $vid = $('<video class="video-js vjs-default-skin" controls ' +
             'poster="">' +
             '<source/>' +
             '
' +
             sprintf(_("To view this video please enable JavaScript, and consider upgrading to a web browser that %ssupports HTML5 video%s"),
                     '', '') + '
' +
             '</video>'),
    $source = $vid.find('source'),
    rect = data.rect,
    releaser = [],
    player, exit_proc,
    is_cur_page;
    $source.attr('src', src);
    if(type)
      $source.attr('type', type);
    $vid.attr('width', rect[2])
      .attr('height', rect[3]).appendTo($vid_wrp);
    $vid_wrp.css({
      position: 'absolute',
      left: rect[0],
      top: rect[1],
      width: rect[2],
      height: rect[3]
    });
    on($vid_wrp, null, 'click', false)
    ('mousedown', function()
      {
        pdf_viewer.pdfviewer('set', 'moveable', false);
      })
    ('mouseup', function()
      {
        setTimeout(function()
          {
            pdf_viewer.pdfviewer('set', 'moveable', true);
          });
      });
    on(pdf_viewer, releaser, 'pagecurl-start', function()
      {
        $vid_wrp.animate({ opacity: 0 }, {
          queue: false,
          duration: 200,
          complete: function()
          {
            $vid_wrp.css('visibility', 'hidden');
          }
        });
      })
    ('pagecurl-end', function()
      {
        if($vid_wrp[0] == data.element)
          $vid_wrp.css('visibility', 'visible');
        $vid_wrp.animate({ opacity: 1 }, {
          queue: false,
          duration: 200,
          complete: function()
          {
            if($vid_wrp[0] == data.element)
              $vid_wrp.css('visibility', 'visible');
          }
        });
      })
    ('curPages-changed', function(ev, curPages)
      {
        if(curPages.indexOf(page) != -1 && !is_cur_page)
        {
          is_cur_page = true;
          if(player && isAutoplay())
            player.play();
          return;
        }
        exit_proc = true;
        if(player)
          player.dispose();
        $vid_wrp.remove();
        funcListCall(releaser);
      });

    videojs($vid[0], {}, function()
      {
        player = this;
        $vid_wrp[0].player = player;
        var play_m = player.play;
        player.play = function()
        {
          play_m.apply(this, arguments);
          if(query.warect == 'full')
          {
            pdf_viewer.pdfviewer('set', 'auto_resizable', true);
            player.enterFullWindow();
            player.trigger('fullscreenchange');
          }
        }
        if(exit_proc)
        {
          player.pause();
          player.dispose();
          return;
        }
        on($vid_wrp.find('.vjs-fullscreen-control'),
           releaser, 'click', function()
          {
            pdf_viewer.pdfviewer('set', 'auto_resizable', false);
            setTimeout(function()
              {
                pdf_viewer.pdfviewer('set', 'auto_resizable', true);
              }, 500);
          });
        video_size_update($vid_wrp, player);
        var curPages = pdf_viewer.pdfviewer('get', 'curPages');
        on($vid_wrp, releaser, 'click',
           '.vjs-big-play-button,.vjs-tech,.vjs-play-control', function()
          {
            if(query.warect == 'full')
            {
              if(player.paused())
                if($vid_wrp[0]._link_el)
                {
                  $video_toggle_visibility($vid_wrp, false);
                  $video_toggle_visibility($($vid_wrp[0]._link_el), true);
                  data.element = $vid_wrp[0]._link_el;
                }
              var b = player.isFullWindow;
              pdf_viewer.pdfviewer('set', 'auto_resizable', b);
              if(!b)
                player.enterFullWindow();
              else
                player.exitFullWindow();
              player.trigger('fullscreenchange');
            }
          });
        player.on('fullscreenchange', function()
          {
            if(player.isFullWindow)
              $vid_wrp.css({
                opacity: 1,
                visibility: 'visible'
              });
            video_size_update($vid_wrp, player);
          });
        if(isAutoplay() && curPages.indexOf(page) != -1)
         player.play();
      });
  }
});


text:
import zmq
import json
import command

class Communication(object):
    """
    handles communication to/from the server
    """

    def __init__(self, host_name):
        """
        initializes Communication object
        """
        pub_socket_addr = "tcp://%s:%s" % (host_name, 5556)
        cmd_socket_addr = "tcp://%s:%s" % (host_name, 5557)

        self.context = zmq.Context()
        self.pub_socket = self.context.socket(zmq.SUB)
        self.pub_socket.connect(pub_socket_addr)

        self.cmd_socket = self.context.socket(zmq.REQ)
        self.cmd_socket.connect(cmd_socket_addr)

    def set_subscription(self, value):
        """
        sets the subscription for the publish socket
        otherwise it will receive no messages on the
        pub/sub channel
        """
        self.pub_socket.setsockopt(zmq.SUBSCRIBE, value)

    def send(self, message, key=None):
        """
        sends 'message' to the servers command socket
        extracts and returns 'key' from the servers reply
        if no 'key' specified, returns the entire reply
        """
        self.cmd_socket.send(message)
        reply = self.receive(Communication.Origin.CommandSocket)

        if key is None:
            return reply
        else:
            return json.loads(reply)[key]

    def receive(self, origin):
        """
        returns a message from the socket specified by 'origin'
        """
        reply = None
        if origin == Communication.Origin.PublishSocket:
            reply = self.pub_socket.recv()
        elif origin == Communication.Origin.CommandSocket:
            reply = self.cmd_socket.recv()
        else:
            print '[Communication receive] wrong origin specified'
            exit(1)

        return reply

    def match_ended(self):
        while True:
            try:
                reply = self.pub_socket.recv(zmq.NOBLOCK)
                try:
                    if json.loads(reply)[command.Command.COMM_TYPE] == command.Command.MATCH_END:
                        return True
                except ValueError:
                    continue
            except zmq.ZMQError:
                break

        return False

    def close(self):
        """
        close connections
        """
        self.cmd_socket.close()
        self.pub_socket.close()

    class Origin:
        def __init__(self):
            pass

        PublishSocket = 0
        CommandSocket = 1


text:
package com.frank.search.solr.core;

import com.frank.search.solr.core.query.Field;
import com.frank.search.solr.core.query.TermsOptions;
import com.frank.search.solr.core.query.TermsQuery;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.params.CommonParams;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * TermsQueryParser is capable of building
 * {@link org.apache.solr.client.solrj.SolrQuery} for {@link TermsQuery}
 *
 * @author Christoph Strobl
 */
public class TermsQueryParser extends QueryParserBase<TermsQuery> {

	@Override
	public SolrQuery doConstructSolrQuery(TermsQuery query) {
		Assert.notNull(query, "Cannot construct solrQuery from null value.");

		SolrQuery solrQuery = new SolrQuery();
		String queryString = getQueryString(query);
		if (StringUtils.hasText(queryString)) {
			solrQuery.setParam(CommonParams.Q, queryString);
		}
		appendTermsOptionsToSolrQuery(query.getTermsOptions(), solrQuery);
		processTermsFields(solrQuery, query);
		appendRequestHandler(solrQuery, query.getRequestHandler());
		return solrQuery;
	}

	protected void appendTermsOptionsToSolrQuery(TermsOptions options, SolrQuery solrQuery) {
		solrQuery.setTerms(true);
		if (options.getLimit() >= 0) {
			solrQuery.setTermsLimit(options.getLimit());
		}
		if (options.getMaxCount() >= -1) {
			solrQuery.setTermsMaxCount(options.getMaxCount());
		}
		if (options.getMinCount() >= 0) {
			solrQuery.setTermsMinCount(options.getMinCount());
		}
		if (StringUtils.hasText(options.getPrefix())) {
			solrQuery.setTermsPrefix(options.getPrefix());
		}
		if (StringUtils.hasText(options.getRegex())) {
			solrQuery.setTermsRegex(options.getRegex());
		}
		if (options.getRegexFlag() != null) {
			solrQuery.setTermsRegexFlag(options.getRegexFlag().toString().toLowerCase());
		}
		if (options.getSort() != null) {
			solrQuery.setTermsSortString(options.getSort().toString().toLowerCase());
		}
		if (options.getUpperBoundTerm() != null) {
			solrQuery.setTermsUpper(options.getUpperBoundTerm().getTerm());
			solrQuery.setTermsUpperInclusive(options.getUpperBoundTerm().isInclude());
		}
		if (options.getLowerBoundTerm() != null) {
			solrQuery.setTermsUpper(options.getLowerBoundTerm().getTerm());
			solrQuery.setTermsUpperInclusive(options.getLowerBoundTerm().isInclude());
		}
		if (!options.isRaw()) {
			solrQuery.setTermsRaw(options.isRaw());
		}

	}

	private void processTermsFields(SolrQuery solrQuery, TermsQuery query) {
		for (Field field : query.getTermsFields()) {
			appendTermsFieldToSolrQuery(field, solrQuery);
		}

	}

	protected void appendTermsFieldToSolrQuery(Field field, SolrQuery solrQuery) {
		if (field != null && StringUtils.hasText(field.getName())) {
			solrQuery.addTermsField(field.getName());
		}
	}

}


text:
class Config(object):
    SECRET_KEY = "wafjewiofjw;newifu"
    debug = False

class Production(Config):
    debug = True
    CSRF_ENABLED = False
    ADMIN = "kho0810@gmail.com"
    SQLALCHEMY_DATABASE_URI = 'mysql+gaerdbms:///flaskr?instance=hyung-ook:flaskr-instance'
    migration_directory = 'migrations'


text:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    name : String,
    lastName : String,
    email : {
        type : String,
        unique : true,
        required : true
    },
    password : {
        type : String,
        required : true
    },
    photo : String,
    birthday : Date,
    idCountry : Schema.Types.ObjectId,
    country : String,
    isoCountryCode : String,
    telephones : [{
        idCountryCodePhone : Schema.Types.ObjectId,
        CountryCodePhone : String,
        phone : String
    }],
    addresses : [
        {
            address : String,
            country : String,
            state : String,
            city : String,
            zip : String
        }
    ],
    enabled : Boolean
},{ versionKey: false });

// Execute before each user.save() call
userSchema.pre('save', function (callback) {
    var user = this;

    // Break out if the password hasn't changed
    if(!user.isModified('password')) return callback();

    // Password changed so we need to hash it
    bcrypt.genSalt(10, function(err, salt) {
        if(err) return callback(err);

        bcrypt.hash(user.password, salt, null, function (err, hash) {
            if(err) return callback(err);
            user.password = hash;
            callback();
        });
    });
});

// Verification methods
userSchema.methods.verifyPassword = function (password, callback) {
    bcrypt.compare(password, this.password, function (err, isMatch) {
        if(err){
            return callback(err);
        }
        callback(null, isMatch);
    });
};

// Export the mongoose model
module.exports = mongoose.model('Users', userSchema);


text:
namespace CalcSumOfInfinitSeries
{
    using System;
    using System.Collections.Generic;

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
"""Subprogram for GoogleCL which handles all requests
   using the Discovery service

This program uses the Discovery API to take interact with other APIs.
It is called when GoogleCL cannot identify a requested service as using gdata.
Syntax is generally similar to using gdata services.

General usage (omitting initial 'google'):
  > <service> <method path> <parameters>
  > help <service> <path>
  > format <service> <method path>

Examples:
  # Creating a new shortened goo.gl URL
  urlshortener insert --body {"longUrl":"<longUrl>"}

  # Getting data for a shortened goo.gl URL
  urlshortener url get <shortUrl>
"""

import httplib2
import logging

import googlecl

from apiclient.discovery import build_from_document
from googlecl.discovery import authentication
from googlecl.discovery import output
from googlecl.discovery import data
from googlecl.discovery import docs
import simplejson as json

LOG = logging.getLogger(googlecl.LOGGER_NAME)
DISCOVERY_URI = '%s/discovery/v1/apis/{api}/{apiVersion}/rest'

class DiscoveryManager():

  def __init__(self, email):
    self.dataManager = data.DefaultManager(email)
    self.docManager = docs.DocManager(self.dataManager.local_apis, self.dataManager.base_url)

  def run(self, argv):
   try:
    """Primary function for the program
    Executes methods, displays help, and organizes formatting for services
    using Discovery

    Args:
      cache: A cache, which may already contain objects to be used
      argv: The arguments, parsed into a list as from the command line
    """
    # Determines if the help, format, or default is being called
    LOG.debug('Running Discovery...')
    isHelp = argv[0]=='help'
    verbose = False
    if isHelp:
      argv = argv[1:]
      if argv[-1] == '--verbose' or argv[-1] == '-v':
        verbose = True
        argv = argv[:-1]

    http = httplib2.Http()

    LOG.debug('Parsing service...')
    # Fetches service, version, docs, etc.
    try:
      servicename, version, doc, args = self.docManager.run(argv, isHelp,
                                                            verbose)
    except TypeError:
      return

    LOG.debug('Managing auth...')
    # Checks if credentials are needed and, if so, whether they are possessed.
    # If not, gets appropriate credentials.
    if 'auth' in doc:
      if '--force-auth' in args:
        args.remove('--force-auth')
        force_auth = True
      else:
        force_auth = False
      http = authentication.authenticate(self.dataManager.email, servicename, doc, http,
        self.dataManager.client_id, self.dataManager.client_secret, force_auth)

      # Builds the service and finds the method
      service = build_from_document(json.dumps(doc), DISCOVERY_URI % self.dataManager.base_url, http=http)
    else:
      service = build_from_document(json.dumps(doc), DISCOVERY_URI % self.dataManager.base_url,
                      developerKey=self.dataManager.devkey2, http=http)
    LOG.debug('Determining task...')
    try:
      metinfo, method, args = getMethod(service, doc, args)
    except:
      #LOG.error('Did not recognize task.')
      return

    LOG.debug('Parsing parameters...')
    try:
      kwargs = self.dataManager.fill_out_options(metinfo, doc, args)
    except TypeError, err:
      raise
      return

    LOG.debug('Executing method...')
    try:
      resp = method(**kwargs).execute()
    except Exception, err:
      LOG.error(err)
      return

    LOG.debug('Displaying output...')
    # Displays formatted output
    output.output(resp, self.dataManager.formatting)
   except Exception, err:
    print 'Uncaught error'
    raise

  def apis_list(self):
    # Returns a list of the APIs that may be used
    return [str(d['name']) for d in self.docManager.directory['items']]

def getMethod(service, doc, args):
  """ Locates the method to be executed
  Capable of finding some methods implicitly
  Displays assistance if method isn't identified

  Args:
    service: The service object being used
    doc: Documentation describing the service
    args: List containing the method path to be followed

  Returns:
    A tuple of the meta-info describing the method,
    the method itself, and the parameters for the method
  """
  obj = doc
  attr = service
  i = 0
  while 'resources' in obj or 'methods' in obj:
    if i < len(args) and 'resources' in obj and args[i] in obj['resources']:
      attr = getattr(attr, args[i])
      obj = obj['resources'][args[i]]
      i=i+1
    elif i < len(args) and 'methods' in obj and args[i] in obj['methods']:
      attr = getattr(attr, args[i])
      obj = obj['methods'][args[i]]
      i=i+1
    elif ('resources' in obj and not 'methods' in obj and
        len(obj['resources'])==1):
      attr = getattr(attr, obj['resources'].keys()[0])
      obj = obj['resources'][obj['resources'].keys()[0]]
    elif 'methods' in obj and not 'resources' in obj and len(obj['methods'])==1:
      attr = getattr(attr, obj['methods'].keys()[0])
      obj = obj['methods'][obj['methods'].keys()[0]]
    else:
      print 'Did not recognize task.'
      if 'methods' in obj:
        LOG.error('Possible methods: ' + ', '.join(obj['methods']))
      if 'resources' in obj:
        LOG.error('Possible resources: ' + ', '.join(obj['resources']))
      return
    if not 'id' in obj:
      attr = attr()
  return obj, attr, args[i:]


text:
package org.kuali.rice.kew.actions;

import junit.framework.Assert;
import org.apache.commons.lang.ArrayUtils;
import org.junit.Test;
import org.kuali.rice.coreservice.api.parameter.Parameter;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.actionitem.ActionItem;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.api.action.ActionRequest;
import org.kuali.rice.kew.api.action.ActionRequestType;
import org.kuali.rice.kew.api.action.ActionType;
import org.kuali.rice.kew.api.action.InvalidActionTakenException;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.impl.KimDocumentTypeAuthorizer;
import org.kuali.rice.kew.framework.postprocessor.ActionTakenEvent;
import org.kuali.rice.kew.framework.postprocessor.ProcessDocReport;
import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.common.attribute.KimAttribute;
import org.kuali.rice.kim.api.common.template.Template;
import org.kuali.rice.kim.api.permission.Permission;
import org.kuali.rice.kim.api.role.Role;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.kim.api.type.KimType;
import org.kuali.rice.kim.api.type.KimTypeAttribute;
import org.kuali.rice.kim.impl.common.attribute.KimAttributeBo;
import org.kuali.rice.kim.impl.type.KimTypeBo;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.test.BaselineTestCase;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.*;

public class RecallActionTest extends KEWTestCase {
    /**
     * test postprocessor for testing afterActionTaken hook
     */
    public static class RecallTestPostProcessor extends DefaultPostProcessor {
        public static ActionType afterActionTakenType;
        public static ActionTakenEvent afterActionTakenEvent;
        @Override
        public ProcessDocReport afterActionTaken(ActionType performed, ActionTakenEvent event) throws Exception {
            afterActionTakenType = performed;
            afterActionTakenEvent = event;
            return super.afterActionTaken(performed, event);
        }
    }

    public static class RecallTestDocumentTypeAuthorizer extends KimDocumentTypeAuthorizer {
        public static String CUSTOM_RECALL_KIM_TYPE_NAME = "Dynamic Type";
        public static String CUSTOM_RECALL_QUALIFIER_NAME = "Dynamic Qualifier";
        public static String CUSTOM_RECALL_QUALIFIER_VALUE = "Dynamic Qualifier Value";
        // we have to use a detail already defined for the recall permission - app doc status seems the most application-controlled
        public static String CUSTOM_RECALL_DETAIL_NAME = KimConstants.AttributeConstants.APP_DOC_STATUS;
        public static String CUSTOM_RECALL_DETAIL_VALUE = "Dynamic Recall Permission Detail Value";

        public static boolean buildPermissionDetailsInvoked = false;
        public static boolean buildRoleQualifiersInvoked= false;

        @Override
        protected Map<String, String> buildDocumentTypePermissionDetails(DocumentType documentType, String documentStatus, String actionRequestedCode, String routeNodeName) {
            buildPermissionDetailsInvoked = true;
            Map<String, String> details = super.buildDocumentTypePermissionDetails(documentType, documentStatus, actionRequestedCode, routeNodeName);
            details.put(CUSTOM_RECALL_DETAIL_NAME, CUSTOM_RECALL_DETAIL_VALUE);
            return details;
        }

        @Override
        protected Map<String, String> buildDocumentRoleQualifiers(DocumentRouteHeaderValue document, String routeNodeName) {
            buildRoleQualifiersInvoked = true;
            Map<String, String> qualifiers = super.buildDocumentRoleQualifiers(document, routeNodeName);
            qualifiers.put(CUSTOM_RECALL_QUALIFIER_NAME, CUSTOM_RECALL_QUALIFIER_VALUE);
            return qualifiers;
        }
    }

    private static final String RECALL_TEST_DOC = "RecallTest";
    private static final String RECALL_TEST_RESTRICTED_DOC = "RecallTestRestricted";
    private static final String RECALL_TEST_NOROUTING_DOC = "RecallTestNoRouting";
    private static final String RECALL_TEST_ONLYADHOC_DOC = "RecallTestOnlyAdhoc";
    private static final String RECALL_NOTIFY_TEST_DOC = "RecallWithPrevNotifyTest";
    private static final String RECALL_NO_PENDING_NOTIFY_TEST_DOC = "RecallWithoutPendingNotifyTest";
    private static final String RECALL_NOTIFY_THIRDPARTY_TEST_DOC = "RecallWithThirdPartyNotifyTest";

    private String EWESTFAL = null;
    private String JHOPF = null;
    private String RKIRKEND = null;
    private String NATJOHNS = null;
    private String BMCGOUGH = null;

    protected void loadTestData() throws Exception {
        loadXmlFile("ActionsConfig.xml");
    }

    @Override
    protected void setUpAfterDataLoad() throws Exception {
        super.setUpAfterDataLoad();
        EWESTFAL = getPrincipalIdForName("ewestfal");
        JHOPF = getPrincipalIdForName("jhopf");
        RKIRKEND = getPrincipalIdForName("rkirkend");
        NATJOHNS = getPrincipalIdForName("natjohns");
        BMCGOUGH = getPrincipalIdForName("bmcgough");

        RecallTestPostProcessor.afterActionTakenType = null;
        RecallTestPostProcessor.afterActionTakenEvent = null;
    }

    protected void assertAfterActionTakenCalled(ActionType performed, ActionType taken) {
        assertEquals(performed, RecallTestPostProcessor.afterActionTakenType);
        assertNotNull(RecallTestPostProcessor.afterActionTakenEvent);
        assertEquals(taken, RecallTestPostProcessor.afterActionTakenEvent.getActionTaken().getActionTaken());
    }

    @Test(expected=InvalidActionTakenException.class) public void testCantRecallUnroutedDoc() {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.recall("recalling", true);
    }

    @Test public void testRecallAsInitiatorBeforeAnyApprovals() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        document.recall("recalling", true);

        assertTrue("Document should be recalled", document.isRecalled());
        assertAfterActionTakenCalled(ActionType.RECALL, ActionType.RECALL);

        //verify that the document is truly dead - no more action requests or action items.

        List requests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
        assertEquals("Should not have any active requests", 0, requests.size());

        Collection<ActionItem> actionItems = KEWServiceLocator.getActionListService().findByDocumentId(document.getDocumentId());
        assertEquals("Should not have any action items", 0, actionItems.size());
    }

    @Test public void testRecallValidActionsTaken() throws Exception {
        // just complete
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_RESTRICTED_DOC);
        document.route("routing");
        document.recall("recalling", true);

        // save and complete
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_RESTRICTED_DOC);
        document.saveDocument("saving");
        document.route("routing");
        document.recall("recalling", true);
    }

    @Test
    public void testRecallInvalidActionsTaken() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_RESTRICTED_DOC);
        document.route("");

        document = WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId());
        document.approve("");

        try {
            document.recall("recalling", true);
            fail("Recall should NOT have succeeded.  Expected InvalidActionTakenException due to invalid 'APROVE' prior action taken.");
        } catch (InvalidActionTakenException iate) {
            assertTrue(iate.getMessage().contains("Invalid prior action taken: 'APPROVE'"));
        }
    }

    @Test public void testRecallOnlyAdhocRouting() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_ONLYADHOC_DOC);
        // adhoc it to someone to prevent doc from going final - final is itself an invalid state for recall
        document.adHocToPrincipal(ActionRequestType.APPROVE, "adhoc approve to JHOPF", JHOPF, "adhocing to prevent finalization", true);
        document.route("routing");
        try {
            document.recall("recalling", true);
            fail("Recall should NOT have succeeded.  Expected InvalidActionTakenException due to absence of non-adhoc route nodes.");
        } catch (InvalidActionTakenException iate) {
            assertTrue(iate.getMessage().contains("No non-adhoc route nodes defined"));
        }
    }

    @Test public void testRecallAsInitiatorAfterSingleApproval() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        document = WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId());
        document.approve("");

        document = WorkflowDocumentFactory.loadDocument(EWESTFAL, document.getDocumentId());
        document.recall("recalling", true);

        assertTrue("Document should be recalled", document.isRecalled());
        assertAfterActionTakenCalled(ActionType.RECALL, ActionType.RECALL);

        //verify that the document is truly dead - no more action requests or action items.

        List requests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
        assertEquals("Should not have any active requests", 0, requests.size());

        Collection<ActionItem> actionItems = KEWServiceLocator.getActionListService().findByDocumentId(document.getDocumentId());
        assertEquals("Should not have any action items", 0, actionItems.size());

        // can't recall recalled doc
        assertFalse(document.getValidActions().getValidActions().contains(ActionType.RECALL));
    }

    @Test(expected=InvalidActionTakenException.class)
    public void testRecallInvalidWhenProcessed() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        for (String user: new String[] { JHOPF, EWESTFAL, RKIRKEND, NATJOHNS, BMCGOUGH }) {
            document = WorkflowDocumentFactory.loadDocument(user, document.getDocumentId());
            document.approve("");
        }

        document.refresh();
        assertTrue("Document should be processed", document.isProcessed());
        assertTrue("Document should be approved", document.isApproved());
        assertFalse("Document should not be final", document.isFinal());

        document = WorkflowDocumentFactory.loadDocument(EWESTFAL, document.getDocumentId());
        document.recall("recalling when processed should fail", true);
    }

    @Test(expected=InvalidActionTakenException.class)
    public void testRecallInvalidWhenFinal() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        for (String user: new String[] { JHOPF, EWESTFAL, RKIRKEND, NATJOHNS, BMCGOUGH }) {
            document = WorkflowDocumentFactory.loadDocument(user, document.getDocumentId());
            document.approve("");
        }
        document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("xqi"), document.getDocumentId());
        document.acknowledge("");

        document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jthomas"), document.getDocumentId());
        document.fyi();

        for (ActionRequest a: document.getRootActionRequests()) {
            System.err.println(a);
            if (a.isAcknowledgeRequest() || a.isFyiRequest()) {
                System.err.println(a.getPrincipalId());
                System.err.println(KimApiServiceLocator.getIdentityService().getPrincipal(a.getPrincipalId()).getPrincipalName());
            }
        }

        assertFalse("Document should not be processed", document.isProcessed());
        assertTrue("Document should be approved", document.isApproved());
        assertTrue("Document should be final", document.isFinal());

        document = WorkflowDocumentFactory.loadDocument(EWESTFAL, document.getDocumentId());
        document.recall("recalling when processed should fail", true);
    }

    @Test public void testRecallToActionListAsInitiatorBeforeAnyApprovals() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        document.recall("recalling", false);

        assertTrue("Document should be saved", document.isSaved());
        assertEquals(1, document.getCurrentNodeNames().size());
        assertTrue(document.getCurrentNodeNames().contains("AdHoc"));
        assertAfterActionTakenCalled(ActionType.RECALL, ActionType.COMPLETE);

        // initiator has completion request
        assertTrue(document.isCompletionRequested());
        // can't recall saved doc
        assertFalse(document.getValidActions().getValidActions().contains(ActionType.RECALL));

        // first approver has FYI
        assertTrue(WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId()).isFYIRequested());

        document.complete("completing");

        assertTrue("Document should be enroute", document.isEnroute());

        assertTrue(WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId()).isApprovalRequested());
    }

    private static final String PERM_APP_DOC_STATUS = "recallable by admins";
    private static final String ROUTE_NODE = "NotifyFirst";
    private static final String ROUTE_STATUS = "R";

    protected Permission createRecallPermission(String docType, String appDocStatus, String routeNode, String routeStatus) {
        return createPermissionForTemplate(KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION + " for test case", docType, appDocStatus, routeNode, routeStatus);
    }

    protected Permission createRouteDocumentPermission(String docType, String appDocStatus, String routeNode, String routeStatus) {
        return createPermissionForTemplate(KewApiConstants.KEW_NAMESPACE, KewApiConstants.ROUTE_PERMISSION, KewApiConstants.KEW_NAMESPACE, KewApiConstants.ROUTE_PERMISSION + " for test case", docType, appDocStatus, routeNode, routeStatus);
    }

    protected Permission createPermissionForTemplate(String template_ns, String template_name, String permission_ns, String permission_name, String docType, String appDocStatus, String routeNode, String routeStatus) {
        Template permTmpl = KimApiServiceLocator.getPermissionService().findPermTemplateByNamespaceCodeAndName(template_ns, template_name);
        assertNotNull(permTmpl);
        Permission.Builder permission = Permission.Builder.create(permission_ns, permission_name);
        permission.setDescription(permission_name);
        permission.setTemplate(Template.Builder.create(permTmpl));
        Map<String, String> attrs = new HashMap<String, String>();
        attrs.put(KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME, docType);
        attrs.put(KimConstants.AttributeConstants.APP_DOC_STATUS, appDocStatus);
        attrs.put(KimConstants.AttributeConstants.ROUTE_NODE_NAME, routeNode);
        attrs.put(KimConstants.AttributeConstants.ROUTE_STATUS_CODE, routeStatus);
        permission.setActive(true);
        permission.setAttributes(attrs);

        // save the permission and check that's it's wired up correctly
        Permission perm = KimApiServiceLocator.getPermissionService().createPermission(permission.build());
        assertEquals(perm.getTemplate().getId(), permTmpl.getId());
        int num = 1;
        if (appDocStatus != null) num++;
        if (routeNode != null) num++;
        if (routeStatus != null) num++;
        assertEquals(num, perm.getAttributes().size());
        assertEquals(docType, perm.getAttributes().get(KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME));
        assertEquals(appDocStatus, perm.getAttributes().get(KimConstants.AttributeConstants.APP_DOC_STATUS));
        assertEquals(routeNode, perm.getAttributes().get(KimConstants.AttributeConstants.ROUTE_NODE_NAME));
        assertEquals(routeStatus, perm.getAttributes().get(KimConstants.AttributeConstants.ROUTE_STATUS_CODE));

        return perm;
    }

    // disable the existing Recall Permission assigned to Initiator Role for test purposes
    protected void disableInitiatorRecallPermission() {
        Permission p = KimApiServiceLocator.getPermissionService().findPermByNamespaceCodeAndName("KR-WKFLW", "Recall Document");
        Permission.Builder pb = Permission.Builder.create(p);
        pb.setActive(false);
        KimApiServiceLocator.getPermissionService().updatePermission(pb.build());
    }

    // setter for Kim Priority Parameter (used for useKimPermission method call)
    protected void setKimPriorityOnDocumentTypeParameterValue(String parameterValue) {
        if(CoreFrameworkServiceLocator.getParameterService().parameterExists(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, KewApiConstants.KIM_PRIORITY_ON_DOC_TYP_PERMS_IND)) {
            Parameter kimPriorityOverDocTypePolicyParameter = CoreFrameworkServiceLocator.getParameterService().getParameter(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, KewApiConstants.KIM_PRIORITY_ON_DOC_TYP_PERMS_IND);
            Parameter.Builder b = Parameter.Builder.create(kimPriorityOverDocTypePolicyParameter);
            b.setValue(parameterValue);
            CoreFrameworkServiceLocator.getParameterService().updateParameter(b.build());
        }
    }

    protected String getKimPriorityOnDocumentTypeParameterValue() {
        if(CoreFrameworkServiceLocator.getParameterService().parameterExists(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, KewApiConstants.KIM_PRIORITY_ON_DOC_TYP_PERMS_IND)) {
            return CoreFrameworkServiceLocator.getParameterService().getParameter(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, KewApiConstants.KIM_PRIORITY_ON_DOC_TYP_PERMS_IND).getValue();
        }
        return null;
    }

    /**
     * Tests that a new permission can be configured with the Recall Permission template and that matching works correctly
     * against the new permission
     */
    @Test public void testRecallPermissionMatching() {
        disableInitiatorRecallPermission();
        createRecallPermission(RECALL_TEST_DOC, PERM_APP_DOC_STATUS, ROUTE_NODE, ROUTE_STATUS);

        Map<String, String> details = new HashMap<String, String>();
        details.put(KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME, RECALL_TEST_DOC);
        details.put(KimConstants.AttributeConstants.APP_DOC_STATUS, PERM_APP_DOC_STATUS);
        details.put(KimConstants.AttributeConstants.ROUTE_NODE_NAME, ROUTE_NODE);
        details.put(KimConstants.AttributeConstants.ROUTE_STATUS_CODE, ROUTE_STATUS);

        // test all single field mismatches
        for (Map.Entry<String, String> entry: details.entrySet()) {
            Map<String, String> testDetails = new HashMap<String, String>(details);
            // change a single detail to a non-matching value
            testDetails.put(entry.getKey(), entry.getValue() + " BOGUS ");
            assertFalse("non-matching " + entry.getKey() + " detail should cause template to not match", KimApiServiceLocator.getPermissionService().isPermissionDefinedByTemplate(KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, testDetails));
        }

        assertTrue("template should match details", KimApiServiceLocator.getPermissionService().isPermissionDefinedByTemplate(KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, details));
    }

    @Test public void testRecallPermissionTemplate() throws Exception {
        WorkflowDocument document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");

        // nope, technical admins can't recall
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));

        // create a recall permission for the RECALL_TEST_DOC doctype
        Permission perm = createRecallPermission(RECALL_TEST_DOC, PERM_APP_DOC_STATUS, ROUTE_NODE, ROUTE_STATUS);

        // assign the permission to Technical Administrator role
        Role techadmin = KimApiServiceLocator.getRoleService().getRoleByNamespaceCodeAndName("KR-SYS", "Technical Administrator");
        KimApiServiceLocator.getRoleService().assignPermissionToRole(perm.getId(), techadmin.getId());

        // our recall permission is assigned to the technical admin role

        // but the doc will not match...
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_NOTIFY_TEST_DOC);
        document.route(PERM_APP_DOC_STATUS);
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));

        // .. the app doc status will not match...
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");
        // technical admins can't recall since the app doc status is not correct
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));

        // ... the node will not match ...
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");
        WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId()).approve(""); // approve past notifyfirstnode
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));

        // ... the doc status will not match (not recallable anyway) ...
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.route("");
        document.cancel("cancelled");
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertFalse(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));

        // everything should match
        document = WorkflowDocumentFactory.createDocument(EWESTFAL, RECALL_TEST_DOC);
        document.setApplicationDocumentStatus(PERM_APP_DOC_STATUS);
        document.route("");
        // now technical admins can recall by virtue of having the recall permission on this doc
        assertTrue(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("admin"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
        assertTrue(WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), document.getDocumentId()).getValidActions().getValidActions().contains(ActionType.RECALL));
    }

    @Test public void testRecallToActionListAsInitiatorAfterApprovals() throws Exception {
        this.testRecallToActionListAsInitiatorAfterApprovals(RECALL_TEST_DOC);
    }

    @Test public void testRecallToActionListAsInitiatorWithNotificationAfterApprovals() throws Exception {
        this.testRecallToActionListAsInitiatorAfterApprovals(RECALL_NOTIFY_TEST_DOC);
    }

    @Test public void testRecallToActionListAsInitiatorWithoutPendingNotificationAfterApprovals() throws Exception {
        this.testRecallToActionListAsInitiatorAfterApprovals(RECALL_NO_PENDING_NOTIFY_TEST_DOC);
    }

    @Test public void testRecallToActionListAsInitiatorWithThirdPartyNotificationAfterApprovals() throws Exception {
        this.testRecallToActionListAsInitiatorAfterApprovals(RECALL_NOTIFY_THIRDPARTY_TEST_DOC);
    }

    /**
     * Tests that the document is returned to the *recaller*'s action list, not the original initiator
     * @throws Exception
     */
    @Test public void testRecallToActionListAsThirdParty() throws Exception {
        Permission perm = createRecallPermission(RECALL_TEST_DOC, null, null, null);
        // assign the permission to Technical Administrator role
        Role techadmin = KimApiServiceLocator.getRoleService().getRoleByNamespaceCodeAndName("KR-SYS", "Technical Administrator");
        KimApiServiceLocator.getRoleService().assignPermissionToRole(perm.getId(), techadmin.getId());
        // recall as 'admin' user
        testRecallToActionListAfterApprovals(EWESTFAL, getPrincipalIdForName("admin"), RECALL_TEST_DOC);
    }

    // the three tests below test permutations of recall permission and derived role assignment
    protected void assignRoutePermissionToTechAdmin() {
        // assign Route Document permission to the Technical Administrator role
        Permission routePerm = createRouteDocumentPermission(RECALL_TEST_DOC, null, null, null);
        Role techadmin = KimApiServiceLocator.getRoleService().getRoleByNamespaceCodeAndName("KR-SYS", "Technical Administrator");
        KimApiServiceLocator.getRoleService().assignPermissionToRole(routePerm.getId(), techadmin.getId());
    }
    protected void assignRecallPermissionToDocumentRouters() {
        // assign Recall permission to the Document Router derived role
        Permission recallPerm = createRecallPermission(RECALL_TEST_DOC, null, null, null);
        Role documentRouterDerivedRole = KimApiServiceLocator.getRoleService().getRoleByNamespaceCodeAndName("KR-WKFLW", "Document Router");
        KimApiServiceLocator.getRoleService().assignPermissionToRole(recallPerm.getId(), documentRouterDerivedRole.getId());
    }
    /**
     * Tests that simply assigning the Route Document permission to the Technical Admin role *without* assigning the
     * Recall permission to the Document Router derived role, is NOT sufficient to enable recall.
     */
    @Test public void testRoutePermissionAssignmentInsufficientForRouterToRecallDoc() throws Exception {
        assignRoutePermissionToTechAdmin();
        // recall as 'admin' (Tech Admin) user
        testRecallToActionListAfterApprovals(EWESTFAL, getPrincipalIdForName("admin"), RECALL_TEST_DOC, false);
    }
    /**
     * Tests that simply assigning the recall permission to the Document Router derived role *without* assigning the
     * Route Document permission to the Technical Admin role, is NOT sufficient to enable recall.
     */
    @Test public void testRecallPermissionAssignmentInsufficientForRouterToRecallDoc() throws Exception {
        assignRecallPermissionToDocumentRouters();
        // recall as 'admin' (Tech Admin) user
        testRecallToActionListAfterApprovals(EWESTFAL, getPrincipalIdForName("admin"), RECALL_TEST_DOC, false);
    }
    /**
     * Tests that we can use the Route Document derived role to assign Recall permission to document routers.
     */
    @Test public void testRecallToActionListAsRouterDerivedRole() throws Exception {
        // assign both! derived role works its magic
        assignRoutePermissionToTechAdmin();
        assignRecallPermissionToDocumentRouters();
        // recall as 'admin' user (Tech Admin) user
        testRecallToActionListAfterApprovals(EWESTFAL, getPrincipalIdForName("admin"), RECALL_TEST_DOC);
    }

    /**
     * Creates a new role with recall permission qualified with doc type and custom app doc status
     * @param ns role namespace
     * @param name role name
     * @param recallPerm the pre-created Recall permission
     * @return the new recall-capable Role
     */
    protected Role createRoleWithRecallPermission(String ns, String name, Permission recallPerm, String kimTypeName, String roleQualifierName) {
        // create a custom attribute for role qualification
        KimAttribute.Builder attribute = KimAttribute.Builder.create("org.kuali.rice.kim.bo.impl.KimAttributes", roleQualifierName, "KR-SYS");
        attribute.setAttributeLabel(roleQualifierName);
        attribute.setActive(true);
        KimAttributeBo customAttribute = KRADServiceLocator.getBusinessObjectService().save(KimAttributeBo.from(attribute.build()));

        // create a custom kim type for the custom attribute
        KimType.Builder kimType = KimType.Builder.create();
        kimType.setNamespaceCode("KR-SYS");
        kimType.setName(kimTypeName);
        kimType.setActive(true);
        KimTypeAttribute.Builder kimTypeAttribute = KimTypeAttribute.Builder.create();
        kimTypeAttribute.setKimAttribute(KimAttribute.Builder.create(customAttribute));
        kimTypeAttribute.setActive(true);
        kimType.setAttributeDefinitions(Collections.singletonList(kimTypeAttribute));
        KimTypeBo customKimType = KRADServiceLocator.getBusinessObjectService().save(KimTypeBo.from(kimType.build()));

        // create a new role
        Role.Builder role = Role.Builder.create();
        role.setActive(true);
        role.setDescription("RecallTest custom recall role");
        role.setName(ns);
        role.setNamespaceCode(name);
        role.setKimTypeId(customKimType.getId());
        Role customRole = KimApiServiceLocator.getRoleService().createRole(role.build());

        KimApiServiceLocator.getRoleService().assignPermissionToRole(recallPerm.getId(), customRole.getId());

        List<String> recallCapableRoleIds = KimApiServiceLocator.getPermissionService().getRoleIdsForPermission(recallPerm.getNamespaceCode(), recallPerm.getName());
        Assert.assertFalse("No recall-capable roles found", recallCapableRoleIds.isEmpty());
        Assert.assertTrue("New role is not associated with Recall permission", recallCapableRoleIds.contains(customRole.getId()));

        return customRole;
    }

    /**
     * Assigns user to role with single qualification
     * @param principalId the principal to assign to role
     * @param role the role object
     * @param roleQualifierName the role qualifier name
     * @param roleQualifierValue the role qualifier value
     */
    protected void assignUserQualifiedRole(String principalId, Role role, String roleQualifierName, String roleQualifierValue) {
        // assign user to role triggered by dynamic, custom role qualifications
        Map<String, String> qualifications = new HashMap<String, String>();
        qualifications.put(roleQualifierName, roleQualifierValue);
        KimApiServiceLocator.getRoleService().assignPrincipalToRole(getPrincipalIdForName("arh14"), role.getNamespaceCode(), role.getName(), qualifications);

        Collection<String> ids = KimApiServiceLocator.getRoleService().getRoleMemberPrincipalIds(role.getNamespaceCode(), role.getName(), qualifications);
        Assert.assertTrue("Qualified role assignment failed", ids.contains(principalId));
    }

    /**
     * Tests that an application can customize document type routing authorization via documenttypeauthorizer
     */
    @Test public void testRecallWithCustomDocumentTypeAuthorizer() throws Exception {
        // arh14 is not associated with our doc routing, will be authorized by custom documenttypeauthorizer
        final String ARH14 = getPrincipalIdForName("arh14");

        // remove existing initiator recall permission
        disableInitiatorRecallPermission();

        RecallTestDocumentTypeAuthorizer.buildPermissionDetailsInvoked = false;
        RecallTestDocumentTypeAuthorizer.buildRoleQualifiersInvoked = false;

        // confirm arh14 can't recall doc
        testRecallToActionListAfterApprovals(EWESTFAL, getPrincipalIdForName("arh14"), RECALL_TEST_DOC, false);

        final String RECALL_ROLE_NM = "CustomRecall";
        final String RECALL_ROLE_NS = "KR-SYS";

        // assign permission triggered by dynamic, custom permission details
        Permission recallPerm = createRecallPermission(RECALL_TEST_DOC, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_VALUE, null, null);
        Role recallRole = createRoleWithRecallPermission(RECALL_ROLE_NM, RECALL_ROLE_NS, recallPerm, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_KIM_TYPE_NAME, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_NAME);
        assignUserQualifiedRole(ARH14, recallRole, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_NAME, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_VALUE);

        Map<String, String> d = new HashMap<String, String>();
        d.put(RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_NAME, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_VALUE);
        d.put(KewApiConstants.DOCUMENT_TYPE_NAME_DETAIL, RECALL_TEST_DOC);
        d.put(KewApiConstants.ROUTE_NODE_NAME_DETAIL, ROUTE_NODE);
        d.put(KewApiConstants.DOCUMENT_STATUS_DETAIL, ROUTE_STATUS);
        Map<String, String> q = new HashMap<String, String>();
        q.put(RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_NAME, RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_VALUE);
        // test that arh14 has recall permission via new recall role with proper qualifications
        List<Permission> permissions = KimApiServiceLocator.getPermissionService().getAuthorizedPermissionsByTemplate(ARH14, KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, d, q);
        Assert.assertEquals(1, permissions.size());
        Assert.assertEquals(recallPerm.getId(), permissions.get(0).getId());

        // verify that arh14 *still* can't recall doc - we have to set the custom documenttypeauthorizer first
        testRecallToActionListAfterApprovals(EWESTFAL, ARH14, RECALL_TEST_DOC, false);

        // now update the doctype with custom documenttype authorizer
        org.kuali.rice.kew.api.doctype.DocumentType dt = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(RECALL_TEST_DOC);
        org.kuali.rice.kew.api.doctype.DocumentType.Builder b = org.kuali.rice.kew.api.doctype.DocumentType.Builder.create(dt);
        b.setAuthorizer(RecallTestDocumentTypeAuthorizer.class.getName());

        KEWServiceLocator.getDocumentTypeService().save(DocumentType.from(b));

        Assert.assertEquals(RecallTestDocumentTypeAuthorizer.class.getName(), KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(RECALL_TEST_DOC).getAuthorizer());

        // custom documenttypeauthorizer has not been invoked yet
        Assert.assertFalse(RecallTestDocumentTypeAuthorizer.buildPermissionDetailsInvoked);
        Assert.assertFalse(RecallTestDocumentTypeAuthorizer.buildRoleQualifiersInvoked);

        // arh14 should *now* be able to recall!
        testRecallToActionListAfterApprovals(EWESTFAL, ARH14, RECALL_TEST_DOC);

        Assert.assertTrue(RecallTestDocumentTypeAuthorizer.buildPermissionDetailsInvoked);
        Assert.assertTrue(RecallTestDocumentTypeAuthorizer.buildRoleQualifiersInvoked);

        // final counter tests - change the actual dynamic values to ensure match fails
        String orig = RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_VALUE;
        try {
            RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_VALUE = "I will not match";
            testRecallToActionListAfterApprovals(EWESTFAL, ARH14, RECALL_TEST_DOC, false);
        } finally {
            RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_QUALIFIER_VALUE = orig;
        }

        orig = RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_VALUE;
        try {
            RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_VALUE = "I won't match either";
            testRecallToActionListAfterApprovals(EWESTFAL, ARH14, RECALL_TEST_DOC, false);
        } finally {
            RecallTestDocumentTypeAuthorizer.CUSTOM_RECALL_DETAIL_VALUE = orig;
        }
    }

    protected void testRecallToActionListAsInitiatorAfterApprovals(String doctype) {
        testRecallToActionListAfterApprovals(EWESTFAL, EWESTFAL, doctype);
    }

    // Implements various permutations of recalls - with and without doctype policies/notifications of various sorts
    // and as initiator or a third party recaller
    protected void testRecallToActionListAfterApprovals(String initiator, String recaller, String doctype) {
        testRecallToActionListAfterApprovals(initiator, recaller, doctype, true);
    }
    protected void testRecallToActionListAfterApprovals(String initiator, String recaller, String doctype, boolean expect_recall_success) {
        boolean notifyPreviousRecipients = !RECALL_TEST_DOC.equals(doctype);
        boolean notifyPendingRecipients = !RECALL_NO_PENDING_NOTIFY_TEST_DOC.equals(doctype);
        String[] thirdPartiesNotified = RECALL_NOTIFY_THIRDPARTY_TEST_DOC.equals(doctype) ? new String[] { "quickstart", "admin" } : new String[] {};

        WorkflowDocument document = WorkflowDocumentFactory.createDocument(initiator, doctype);
        document.route("");

        WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId()).approve("");
        WorkflowDocumentFactory.loadDocument(initiator, document.getDocumentId()).approve("");
        WorkflowDocumentFactory.loadDocument(RKIRKEND, document.getDocumentId()).approve("");

        document = WorkflowDocumentFactory.loadDocument(recaller, document.getDocumentId());
        System.err.println(document.getValidActions().getValidActions());
        if (expect_recall_success) {
            assertTrue("recaller '" + recaller + "' should be able to RECALL", document.getValidActions().getValidActions().contains(ActionType.RECALL));
        } else {
            assertFalse("recaller '" + recaller + "' should NOT be able to RECALL", document.getValidActions().getValidActions().contains(ActionType.RECALL));
            return;
        }
        document.recall("recalling", false);

        assertTrue("Document should be saved", document.isSaved());
        assertAfterActionTakenCalled(ActionType.RECALL, ActionType.COMPLETE);

        // the recaller has a completion request
        assertTrue(document.isCompletionRequested());

        // pending approver has FYI
        assertEquals(notifyPendingRecipients, WorkflowDocumentFactory.loadDocument(NATJOHNS, document.getDocumentId()).isFYIRequested());
        // third approver has FYI
        assertEquals(notifyPreviousRecipients, WorkflowDocumentFactory.loadDocument(RKIRKEND, document.getDocumentId()).isFYIRequested());
        // second approver does not have FYI - approver is initiator, FYI is skipped
        assertFalse(WorkflowDocumentFactory.loadDocument(initiator, document.getDocumentId()).isFYIRequested());
        // first approver has FYI
        assertEquals(notifyPreviousRecipients, WorkflowDocumentFactory.loadDocument(JHOPF, document.getDocumentId()).isFYIRequested());

        if (!ArrayUtils.isEmpty(thirdPartiesNotified)) {
            for (String recipient: thirdPartiesNotified) {
                assertTrue("Expected FYI to be sent to: " + recipient, WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(recipient), document.getDocumentId()).isFYIRequested());
            }
        }

        // omit JHOPF, and see if FYI is subsumed by approval request
        for (String user: new String[] { RKIRKEND, NATJOHNS }) {
            WorkflowDocumentFactory.loadDocument(user, document.getDocumentId()).fyi();
        }

        document.complete("completing");

        assertTrue("Document should be enroute", document.isEnroute());

        // generation of approval requests nullify FYIs (?)
        // if JHOPF had an FYI, he doesn't any longer
        for (String user: new String[] { JHOPF, RKIRKEND, NATJOHNS }) {
            document = WorkflowDocumentFactory.loadDocument(user, document.getDocumentId());
            assertFalse(getPrincipalNameForId(user) + " should not have an FYI", document.isFYIRequested());
        }

        // submit all approvals
        for (String user: new String[] { JHOPF, initiator, RKIRKEND, NATJOHNS, BMCGOUGH }) {
            document = WorkflowDocumentFactory.loadDocument(user, document.getDocumentId());
            assertTrue(getPrincipalNameForId(user) + " should have approval request", document.isApprovalRequested());
            document.approve("approving");
        }

        // 2 acks outstanding, we're PROCESSED
        assertTrue("Document should be processed", document.isProcessed());
        assertTrue("Document should be approved", document.isApproved());

        document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("xqi"), document.getDocumentId());
        document.acknowledge("");

        document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jthomas"), document.getDocumentId());
        document.fyi();

        assertTrue("Document should be approved", document.isApproved());
        assertTrue("Document should be final", document.isFinal());
    }
}


text:
from __future__ import absolute_import

from django.utils.http import urlquote

from django.core.urlresolvers import reverse
from exam import fixture

from sentry import options
from sentry.testutils import TestCase
from sentry.models import OrganizationMember, User

# TODO(dcramer): need tests for SSO behavior and single org behavior
class AuthLoginTest(TestCase):
    @fixture
    def path(self):
        return reverse('sentry-login')

    def test_renders_correct_template(self):
        resp = self.client.get(self.path)

        assert resp.status_code == 200
        self.assertTemplateUsed('sentry/login.html')

    def test_renders_session_expire_message(self):
        self.client.cookies['session_expired'] = '1'
        resp = self.client.get(self.path)

        assert resp.status_code == 200
        self.assertTemplateUsed(resp, 'sentry/login.html')
        assert len(resp.context['messages']) == 1

    def test_login_invalid_password(self):
        # load it once for test cookie
        self.client.get(self.path)

        resp = self.client.post(
            self.path, {
                'username': self.user.username,
                'password': 'bizbar',
                'op': 'login',
            }
        )
        assert resp.status_code == 200
        assert resp.context['login_form'].errors['__all__'] == [
            u'Please enter a correct username and password. Note that both fields may be case-sensitive.'
        ]

    def test_login_valid_credentials(self):
        # load it once for test cookie
        self.client.get(self.path)

        resp = self.client.post(
            self.path, {
                'username': self.user.username,
                'password': 'admin',
                'op': 'login',
            }
        )
        assert resp.status_code == 302

    def test_registration_disabled(self):
        options.set('auth.allow-registration', True)
        with self.feature({'auth:register': False}):
            resp = self.client.get(self.path)
            assert resp.context['register_form'] is None

    def test_registration_valid(self):
        options.set('auth.allow-registration', True)
        with self.feature('auth:register'):
            resp = self.client.post(
                self.path, {
                    'username': 'test-a-really-long-email-address@example.com',
                    'password': 'foobar',
                    'name': 'Foo Bar',
                    'op': 'register',
                }
            )
        assert resp.status_code == 302
        user = User.objects.get(username='test-a-really-long-email-address@example.com')
        assert user.email == 'test-a-really-long-email-address@example.com'
        assert user.check_password('foobar')
        assert user.name == 'Foo Bar'
        assert not OrganizationMember.objects.filter(
            user=user,
        ).exists()

    def test_register_renders_correct_template(self):
        options.set('auth.allow-registration', True)
        register_path = reverse('sentry-register')
        resp = self.client.get(register_path)

        assert resp.status_code == 200
        assert resp.context['op'] == 'register'
        self.assertTemplateUsed('sentry/login.html')

    def test_register_prefills_invite_email(self):
        self.session['invite_email'] = 'foo@example.com'
        self.session['can_register'] = True
        self.save_session()

        register_path = reverse('sentry-register')
        resp = self.client.get(register_path)

        assert resp.status_code == 200
        assert resp.context['op'] == 'register'
        assert resp.context['register_form'].initial['username'] == 'foo@example.com'
        self.assertTemplateUsed('sentry/login.html')

    def test_redirects_to_relative_next_url(self):
        next = '/welcome'
        self.client.get(self.path + '?next=' + next)

        resp = self.client.post(
            self.path, {
                'username': self.user.username,
                'password': 'admin',
                'op': 'login',
            }
        )
        assert resp.status_code == 302
        assert resp.get('Location', '').endswith(next)

    def test_doesnt_redirect_to_external_next_url(self):
        next = "http://example.com"
        self.client.get(self.path + '?next=' + urlquote(next))

        resp = self.client.post(
            self.path, {
                'username': self.user.username,
                'password': 'admin',
                'op': 'login',
            }
        )
        assert resp.status_code == 302
        assert next not in resp['Location']
        assert resp['Location'] == 'http://testserver/auth/login/'

    def test_redirects_already_authed_non_superuser(self):
        self.user.update(is_superuser=False)
        self.login_as(self.user)
        with self.feature('organizations:create'):
            resp = self.client.get(self.path)

        assert resp.status_code == 302
        assert resp['Location'] == 'http://testserver/organizations/new/'

    def test_doesnt_redirect_already_authed_superuser(self):
        self.login_as(self.user, superuser=False)

        resp = self.client.get(self.path)

        assert resp.status_code == 200


text:
dbserver_container:
	sudo docker build -t ansible-ms-dbserver .

run_dbserver_container_bash:
	sudo docker run -i -t ansible-ms-dbserver /bin/bash

run_dbserver_container_mysql:
	sudo docker run --name db -d ansible-ms-dbserver /usr/sbin/mysqld