text:
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com

#include <moaiext-fmod-ex/MOAIFmodEx.h>
#include <moaiext-fmod-ex/MOAIFmodExChannel.h>
#include <moaiext-fmod-ex/MOAIFmodExSound.h>
#include <fmod.hpp>

//================================================================//
// local
//================================================================//

//----------------------------------------------------------------//
/**	@name	getVolume
 @text	Returns the current volume of the channel.

 @in	MOAIFmodExChannel self
 @out	float Volume - the volume currently set in this channel.
 */
int MOAIFmodExChannel::_getVolume ( lua_State* L ) {

	MOAI_LUA_SETUP ( MOAIFmodExChannel, "U" )

	lua_pushnumber ( state, self->GetVolume ());
	return 1;
}

//----------------------------------------------------------------//
/**	@name	isPlaying
 @text	Returns true if channel is playing.

 @in	MOAIFmodExChannel self
 @out	boolean.
 */
int MOAIFmodExChannel::_isPlaying ( lua_State* L ) {

	MOAI_LUA_SETUP ( MOAIFmodExChannel, "U" )

	bool isPlaying = self->mPlayState == PLAYING;

	if ( self->mSound ) {
		lua_pushboolean ( state, isPlaying );
		return 1;
	}
	return 0;
}

//----------------------------------------------------------------//
/**	@name	moveVolume
	@text	Creates a new MOAIAction that will move the volume from it's current value to the value specified.

	@in		MOAIFmodExChannel self
	@in		number target			The target volume.
	@in		number delay			The delay until the action starts.
	@in		number mode				The interpolation mode for the action.
	@out	MOAIAction action		The new action.  It is automatically started by this function.
*/
int MOAIFmodExChannel::_moveVolume ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "UNN" )

	MOAIEaseDriver* action = new MOAIEaseDriver ();
	action->ReserveLinks ( 1 );

	float delta		= state.GetValue < float >( 2, 0.0f );
	float length	= state.GetValue < float >( 3, 0.0f );
	u32 mode		= state.GetValue < u32 >( 4, USInterpolate::kSmooth );

	action->SetLink ( 0, self, MOAIFmodExChannelAttr::Pack ( ATTR_VOLUME ), delta, mode );

	action->SetSpan ( length );
	action->Start ();
	action->PushLuaUserdata ( state );

	return 1;
}

//----------------------------------------------------------------//
/**	@name	play
	@text	Plays the specified sound, looping it if desired.

	@in		MOAIFmodExChannel self
	@in		MOAIFmodExSound sound		The sound to play.
	@in		boolean loop			Whether the sound should be looped.
	@out	nil
*/
int MOAIFmodExChannel::_play ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "UU" )

	self->mPlayState = PLAYING;
	MOAIFmodExSound* sound = state.GetLuaObject < MOAIFmodExSound >( 2, true );
	if ( !sound ) return 0;

	int loopCount = state.GetValue < int >( 3, 0 );

	self->Play ( sound, loopCount );

	return 0;
}

//----------------------------------------------------------------//
/**	@name	seekVolume
	@text	Creates a new MOAIAction that will move the volume from it's current value to the value specified.

	@in		MOAIFmodExChannel self
	@in		number target			The target volume.
	@in		number delay			The delay until the action starts.
	@in		number mode				The interpolation mode for the action.
	@out	MOAIAction action		The new action.  It is automatically started by this function.
*/
int MOAIFmodExChannel::_seekVolume ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "UNN" )

	MOAIEaseDriver* action = new MOAIEaseDriver ();
	action->ReserveLinks ( 1 );

	float target	= state.GetValue < float >( 2, 0.0f );
	float length	= state.GetValue < float >( 3, 0.0f );
	u32 mode		= state.GetValue < u32 >( 4, USInterpolate::kSmooth );

	action->SetLink ( 0, self, MOAIFmodExChannelAttr::Pack ( ATTR_VOLUME ), target - self->mVolume, mode );

	action->SetSpan ( length );
	action->Start ();
	action->PushLuaUserdata ( state );

	return 1;
}

//----------------------------------------------------------------//
/**	@name	setVolume
	@text	Immediately sets the volume of this channel.

	@in		MOAIFmodExChannel self
	@in		number volume			The volume of this channel.
	@out	nil
*/
int MOAIFmodExChannel::_setVolume ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "UN" )

	float volume = state.GetValue < float >( 2, 0.0f );
	self->SetVolume ( volume );

	return 0;
}

//----------------------------------------------------------------//
/**	@name	setPaused
	@text	Sets whether this channel is paused and hence does not play any sounds.

	@in		MOAIFmodExChannel self
	@in		boolean paused			Whether this channel is paused.
	@out	nil
*/
int MOAIFmodExChannel::_setPaused ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "UB" )

	self->mPlayState = PAUSED;
	bool paused = state.GetValue < bool >( 2, false );
	self->SetPaused ( paused );

	return 0;
}

//----------------------------------------------------------------//
/**	@name	setLooping
	@text	Immediately sets looping for this channel.

	@in		MOAIFmodExChannel self
	@in		boolean looping	  True if channel should loop.
	@out	nil
*/
int MOAIFmodExChannel::_setLooping ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "U" )

	float looping = state.GetValue < bool >( 2, false );
	self->mLooping = looping;

	return 0;
}

//----------------------------------------------------------------//
/**	@name	stop
	@text	Stops playing the sound on this channel.

	@in		MOAIFmodExChannel self
	@out	nil
*/
int MOAIFmodExChannel::_stop ( lua_State* L ) {
	MOAI_LUA_SETUP ( MOAIFmodExChannel, "U" )

	self->mPlayState = STOPPED;
	self->Stop ();

	return 0;
}

//================================================================//
// MOAIFmodExChannel
//================================================================//

//----------------------------------------------------------------//
bool MOAIFmodExChannel::ApplyAttrOp ( u32 attrID, MOAIAttrOp& attrOp, u32 op ) {

	if ( MOAIFmodExChannelAttr::Check ( attrID )) {
		attrID = UNPACK_ATTR ( attrID );

		if ( attrID == ATTR_VOLUME ) {
			this->mVolume = attrOp.Apply ( this->mVolume, op, MOAIAttrOp::ATTR_READ_WRITE );
			this->SetVolume ( this->mVolume );
			return true;
		}
	}
	return false;
}

//----------------------------------------------------------------//
float MOAIFmodExChannel::GetVolume () {
	return this->mVolume;
}

//----------------------------------------------------------------//
MOAIFmodExChannel::MOAIFmodExChannel () :
	mChannel ( 0 ),
	mVolume ( 1.0f ),
	mPaused ( false ) ,
	mLooping ( false ) {

	RTTI_SINGLE ( MOAINode )
}

//----------------------------------------------------------------//
MOAIFmodExChannel::~MOAIFmodExChannel () {

	this->Stop ();
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::Play ( MOAIFmodExSound* sound, int loopCount ) {

	this->Stop ();
	this->mSound = sound;
	if ( !sound ) return;
	if ( !sound->mSound ) return;

	FMOD::System* soundSys = MOAIFmodEx::Get ().GetSoundSys ();
	if ( !soundSys ) return;

	FMOD_RESULT result;
	FMOD::Channel* channel = 0;

	//printf ( "PLAY SOUND %s, @ %f\n", sound->GetFileName (), USDeviceTime::GetTimeInSeconds () );
	result = soundSys->playSound ( FMOD_CHANNEL_FREE, sound->mSound, true, &channel );
	if ( result != FMOD_OK ) {
		printf (" FMOD ERROR: Sound did not play\n" );
		return;
	}

	this->mChannel = channel;
	this->mChannel->setMode ( FMOD_LOOP_NORMAL );

	if ( mLooping ) {
		this->mChannel->setLoopCount ( -1 );
	}
	else {
		this->mChannel->setLoopCount ( loopCount );
	}

	this->SetVolume ( this->mVolume );
	this->SetPaused ( this->mPaused );
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::RegisterLuaClass ( MOAILuaState& state ) {

	state.SetField ( -1, "ATTR_VOLUME", MOAIFmodExChannelAttr::Pack ( ATTR_VOLUME ));
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::RegisterLuaFuncs ( MOAILuaState& state ) {

	luaL_Reg regTable [] = {
		{ "getVolume",		_getVolume },
		{ "isPlaying",		_isPlaying },
		{ "moveVolume",		_moveVolume },
		{ "play",			_play },
		{ "seekVolume",		_seekVolume },
		{ "setPaused",		_setPaused },
		{ "setLooping",		_setLooping },
		{ "setVolume",		_setVolume },
		{ "stop",			_stop },
		{ NULL, NULL }
	};

	luaL_register ( state, 0, regTable );
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::SetPaused ( bool paused ) {

	this->mPaused = paused;
	if ( !this->mChannel ) return;
	this->mChannel->setPaused ( this->mPaused );
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::SetVolume ( float volume ) {

	this->mVolume = volume;
	if ( !this->mChannel ) return;
	this->mChannel->setVolume ( this->mVolume );
}

//----------------------------------------------------------------//
void MOAIFmodExChannel::Stop () {

	if ( !this->mChannel ) return;
	this->mChannel->stop();
}


text:
<title>
Exposing Israel's nuclear arsenal
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Mordechai Vanunu freed after 18 years behind bars for...

Exposing Israel's nuclear arsenal

By Phil Gasper | April 30, 2004 | Page 12

"I WILL continue to speak against all kinds of nuclear weapons, against all the world's nuclear weapons. Those were the defiant words of Mordechai Vanunu--the whistleblower who exposed Israel's secret nuclear weapons program--as he was released from prison April 21 after 18 years behind bars.

Vanunu was a technician at Israel's Dimona nuclear installation in the Negrev Desert from 1976 to 1985. In 1986, Vanunu traveled to Britain--where he gave the London Sunday Times extensive details and photos demonstrating that Israel was producing plutonium for nuclear bombs and that it possessed up to 200 nuclear warheads. Even before Vanunu's revelations were published, however, he was abducted by Israeli agents and taken back to Israel. After a secret trial, he was given the maximum sentence.

For 12 years, Vanunu was kept in solitary confinement in a tiny 6-by-9-foot cell--in conditions described by Amnesty International as "cruel, inhuman and degrading."

Now that Vanunu has finally been released, the Israeli government has placed unprecedented restrictions on him. He can't travel freely, is forbidden from leaving Israel and can't contact any foreign citizens without permission.

Israel claims that the restrictions are necessary to prevent Vanunu from revealing further secrets. But the idea that Vanunu has any new information to disclose is absurd.

The real reason for his continued harsh treatment is that Israel still refuses to acknowledge officially that it is a nuclear power. Israel is the only country in the Middle East that has refused to sign the Nuclear Non-Proliferation Treaty. Washington sends billions of dollars in military and economic aid to Israel every year--even though U.S. law forbids such aid to countries that are developing nuclear weapons and that don't permit international inspections of their facilities.

So both Israel and the U.S. maintain the fiction that Israel does not have a nuclear weapons program. In 1970, President Richard Nixon told the Israeli government that if they kept their weapons "in the basement," the U.S. would turn a blind eye. In 1998, Bill Clinton promised to support the improvement of Israel's "deterrent capabilities,"--which, as Britain's Guardian newspaper pointed out, is "a euphemism for nuclear weapons."

According to the Guardian, "The Israeli armed forces now possess missiles capable of delivering a nuclear payload up to 1,500 kilometers away and are developing others with much longer range. They have acquired more than 200 nuclear-capable aircraft, and have completed the land-air-and-sea triad by buying three nuclear-capable submarines. They probably have more nuclear warheads than Britain, including thermonuclear warheads."

If Vanunu were free to speak out about Israel's nuclear program, it would be a continuing embarrassment to both Washington and Tel Aviv--especially at a time when the Bush administration is pressuring other Middle Eastern countries not to develop nuclear weapons.

Israeli officials condemn Vanunu as a traitor. But his decision to reveal Israel's nuclear secrets was a courageous act in the cause of world peace. Antiwar activists must protest his continued outrageous treatment by the Israeli government.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>

redpajama_set_name: RedPajamaGithub


text:
package org.knowm.xchange.btcchina.service.fix.fix44;

import org.knowm.xchange.btcchina.service.fix.field.AccReqID;

import quickfix.FieldNotFound;
import quickfix.field.Account;
import quickfix.field.MsgType;
import quickfix.fix44.Message;

public class AccountInfoRequest extends Message {

  private static final long serialVersionUID = 20141122L;

  public static final String MSGTYPE = "U1000";

  public AccountInfoRequest() {

    getHeader().setField(new MsgType(MSGTYPE));
  }

  public void set(Account value) {

    setField(value);
  }

  public Account get(Account value) throws FieldNotFound {

    getField(value);
    return value;
  }

  public Account getAccount() throws FieldNotFound {

    Account value = new Account();
    getField(value);
    return value;
  }

  public boolean isSet(Account field) {

    return isSetField(field);
  }

  public boolean isSetAccount() {

    return isSetField(Account.FIELD);
  }

  public void set(AccReqID value) {

    setField(value);
  }

  public AccReqID get(AccReqID value) throws FieldNotFound {

    getField(value);
    return value;
  }

  public AccReqID getAccReqID() throws FieldNotFound {

    AccReqID value = new AccReqID();
    getField(value);
    return value;
  }

  public boolean isSet(AccReqID field) {

    return isSetField(field);
  }

  public boolean isSetAccReqID() {

    return isSetField(AccReqID.FIELD);
  }

}


text:
    {posts}

    {subject} - #{postnum} Posted by {username}  at {date}:

{message}

    {actions}

    {/posts}


text:
package cucumber.formatter;

import gherkin.formatter.Formatter;
import gherkin.formatter.model.Background;
import gherkin.formatter.model.Examples;
import gherkin.formatter.model.Feature;
import gherkin.formatter.model.Scenario;
import gherkin.formatter.model.ScenarioOutline;
import gherkin.formatter.model.Step;

import java.util.List;

public class NullFormatter implements Formatter {
    public NullFormatter(Appendable ignore) {
    }

    @Override
    public void uri(String uri) {
    }

    @Override
    public void feature(Feature feature) {
    }

    @Override
    public void background(Background background) {
    }

    @Override
    public void scenario(Scenario scenario) {
    }

    @Override
    public void scenarioOutline(ScenarioOutline scenarioOutline) {
    }

    @Override
    public void examples(Examples examples) {
    }

    @Override
    public void step(Step step) {
    }

    @Override
    public void eof() {
    }

    @Override
    public void syntaxError(String state, String event, List<String> legalEvents, String uri, int line) {
    }

    @Override
    public void done() {
    }

    @Override
    public void close() {
    }
}


text:
var Map = (function(THREE) {
  var GROUND_LEVEL = -10;
  var COLOR_SKY = 0x0000ff;
  var COLOR_GROUND = 0xc8c8c8;
  var COLOR_OBJECT = 0xc8c8c8;

  function generateSpike(radius, height) {
    var geometry = new THREE.CylinderGeometry(0, radius, height, 8);
    var material = new THREE.MeshLambertMaterial({ color: COLOR_OBJECT });
    var spike = new THREE.Mesh(geometry, material);
    spike.position.y = GROUND_LEVEL;
    return spike;
  }

  function createWorld() {
    /*
    var ambient = new THREE.AmbientLight(0x444444);
    scene.add(ambient);

    var light = new THREE.DirectionalLight(0x4444cc, 2);
    light.position.set(1, -1, 1).normalize();
    scene.add(light);

    var spotLight = new THREE.SpotLight(0x00FF00);
    spotLight.target.position.set(0, 0, 0);
    spotLight.position.set(0, 200, 1000);
    spotLight.castShadow = true;
    scene.add(spotLight);
*/
    var directionalLight = new THREE.DirectionalLight( COLOR_SKY, 1 );
    directionalLight.target.position.set( 0, 0, 0);
    directionalLight.castShadow = true;
    scene.add( directionalLight );

    var sphere = new THREE.SphereGeometry( 0.5, 16, 8 );
    var light1 = new THREE.PointLight( 0xff00ff, 0, 50 );
    light1.position.set( 0, 50, 1000 );
    light1.add( new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xff00ff } ) ) );
    scene.add( light1 );

    var light = new THREE.HemisphereLight( COLOR_SKY, COLOR_GROUND, 1 );
    light.position.set( 0, 500, 0 );
    scene.add( light );

    // add ground
    var groundGeo = new THREE.PlaneBufferGeometry( 10000, 10000 );
    var groundMat = new THREE.MeshPhongMaterial( {
      color    : COLOR_GROUND,
      shading    : THREE.SmoothShading
    } );
    var ground = new THREE.Mesh( groundGeo, groundMat );
    ground.scale.multiplyScalar(3);
    ground.rotation.x = -Math.PI/2;
    ground.position.y = GROUND_LEVEL;
    ground.receiveShadow = true;
    scene.add( ground );
  }
  return {
    generateSpike: generateSpike,
    createWorld: createWorld
  };
})(THREE);


text:
from django.conf.urls import url
from django.http import HttpResponseRedirect

from oauth2_provider.views import (AuthorizationView, TokenView,
    ApplicationList, ApplicationRegistration, ApplicationDetail,
    ApplicationDelete, ApplicationUpdate)

class CustomAuthorizationView(AuthorizationView):
    def render_to_response(self, context, **kwargs):
        application = context.get('application')
        scopes = context.get('scopes')
        if application is not None and application.can_auto_approve(scopes):
            uri, headers, body, status = self.create_authorization_response(
                request=self.request, scopes=" ".join(scopes),
                credentials=context, allow=True)
            return HttpResponseRedirect(uri)
        context['oauth_request'] = context.get('request')
        context['request'] = self.request
        return super(CustomAuthorizationView, self).render_to_response(context,
                                                                       **kwargs)

urlpatterns = [
    url(r'^authorize/$', CustomAuthorizationView.as_view(), name="authorize"),
    url(r'^token/$', TokenView.as_view(), name="token"),
]

class CustomApplicationUpdate(ApplicationUpdate):
    fields = ['name', 'redirect_uris', 'description', 'homepage', 'image_url']

# Application management views
app_name = 'account'
urlpatterns += [
    url(r'^applications/$', ApplicationList.as_view(), name="list"),
    url(r'^applications/register/$', ApplicationRegistration.as_view(), name="register"),
    url(r'^applications/(?P<pk>\d+)/$', ApplicationDetail.as_view(), name="detail"),
    url(r'^applications/(?P<pk>\d+)/delete/$', ApplicationDelete.as_view(), name="delete"),
    url(r'^applications/(?P<pk>\d+)/update/$', CustomApplicationUpdate.as_view(), name="update"),
]


text:
"""This module provides wrappers for different segment types."""

from edifact.segments.base import Composite, Segment

class DTM(Segment):
    """Date/Time/Period segment."""

    qualifier = Composite(index=0, max_length=3, required=True)
    value = Composite(index=1, max_length=35, required=True)
    format = Composite(index=2, max_length=3, required=True)

    class Meta:
        identifier = 'DTM'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;

namespace IronMock
{
    public class DuckTyper
    {
        const string Template =
@"class {0}
  include ::{1}

  def initialize(wrapped)
    @wrapped = wrapped
  end

  def method_missing(sym, *args, &block)
    @wrapped.send sym.ToString, *args, &block
  end
end";

        private static readonly ScriptEngine Engine = IronRuby.Ruby.CreateEngine();
        private static readonly Dictionary<Type, string> Types = new Dictionary<Type, string>();
        private static readonly object Sync = new object();

        /// <summary>
        /// Applies an interface to an object.
        /// </summary>
        /// <typeparam name="T">The interface to apply</typeparam>
        /// <param name="objectToWrap">The object to wrap.</param>
        /// <returns>A wrapper around the object which implements the interface.</returns>
        public static T ApplyInterface<T>(object objectToWrap)
            where T : class
        {
            if (objectToWrap == null) throw new ArgumentNullException("objectToWrap");
            if (!typeof(T).IsInterface) throw new ArgumentException("T must be an interface type.");

            PrepareType(typeof(T));

            return WrapObject<T>(objectToWrap);
        }

        private static T WrapObject<T>(object objectToWrap)
            where T : class
        {
            var scope = Engine.CreateScope();
            scope.SetVariable("object_to_wrap", objectToWrap);

            string newCode = Types[typeof(T)] + ".new(object_to_wrap)";
            return Engine.Execute(newCode, scope) as T;
        }

        private static void PrepareType(Type interfaceType)
        {
            if (Types.ContainsKey(interfaceType)) return;

            lock (Sync)
            {
                if (!Types.ContainsKey(interfaceType))
                {
                    Engine.Runtime.LoadAssembly(interfaceType.Assembly);
                    Engine.Execute(GenerateClassCode(interfaceType));
                    Types.Add(interfaceType, GenerateClassName(interfaceType));
                }
            }
        }

        private static string GenerateClassCode(Type interfaceType)
        {
            if (interfaceType == null) throw new ArgumentNullException("interfaceType");
            return string.Format(Template, GenerateClassName(interfaceType), interfaceType.FullName.Replace(".", "::"));
        }

        private static string GenerateClassName(Type interfaceType)
        {
            if (interfaceType == null) throw new ArgumentNullException("interfaceType");
            return interfaceType.FullName.Replace(".", "") + "DuckType";
        }
    }
}


text:
package snitch

import (
	"strconv"
	"strings"

	"github.com/xjewer/snitch/lib/config"
)

type keyPath struct {
	val   string
	match int
	isVar bool
}

type metric struct {
	keyPaths   []keyPath
	count      bool
	timing     bool
	timingData int
	delimiter  string
}

// makeMetrics makes metrics, that have to send to statsd with specific keys
func makeMetrics(keys []config.Key, prefix string) ([]*metric, error) {
	metrics := make([]*metric, 0)
	for _, k := range keys {
		m := &metric{keyPaths: make([]keyPath, 0), count: k.Count}
		if k.Timing != "" {
			td, err := getVarName(k.Timing)
			if err != nil {
				return metrics, err
			}
			m.timing = true
			m.timingData = td
		}

		m.keyPaths = append(m.keyPaths, keyPath{val: prefix})
		for _, p := range strings.Split(k.Key, ".") {
			if string(p[0]) == "$" {
				match, err := getVarName(p)
				if err != nil {
					return metrics, err
				}
				m.keyPaths = append(m.keyPaths, keyPath{isVar: true, match: match})
			} else {
				m.keyPaths = append(m.keyPaths, keyPath{val: p})
			}
		}
		m.delimiter = k.Delimiter

		metrics = append(metrics, m)
	}
	return metrics, nil
}

// getVarName returns a var name
func getVarName(v string) (int, error) {
	if len(v) <= 1 {
		return 0, ErrEmptyVarName
	}

	n, err := strconv.Atoi(v[1:])
	if err != nil {
		return 0, err
	}
	return n, nil
}


text:
<?php

namespace Dafiti\Correios\Lib;

class CodVerificadorTest extends \PHPUnit_Framework_TestCase
{
    public function testCalculate()
    {
        $this->assertEquals('156538500',CodVerificador::calculate('15653850'));
        $this->assertEquals('156538513',CodVerificador::calculate('15653851'));
        $this->assertEquals('156538527',CodVerificador::calculate('15653852'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider invalidArgumentProvider
     */
    public function testCalculateWithInvalidArgument($num)
    {
        CodVerificador::calculate($num);
    }

    public function invalidArgumentProvider()
    {
        return [
            [0],
            [""],
            ["123123"],
            ["123123123"],
        ];
    }
}


text:
@interface Mediator : NSObject

+ (instancetype)sharedInstance;

// 本地组件调用入口
- (id)mediatorActionNativFetchController:(NSString *)targetName;

- (id)performTarget:(NSString *)targetName action:(NSString *)actionName withObject:(id)object;
- (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params;

// 远程App调用入口
- (id)performActionWithUrl:(NSURL *)url completion:(void(^)(NSDictionary *info))completion;

@end


text:
class CTimerThread
{
private:
	CTimerThread();
	~CTimerThread();
private:
	HANDLE hThread;
	DWORD  dwThreadID;
public:
	static CTimerThread* GetInstance()
	{
		static CTimerThread instance;
		return &instance;
	}
};


text:
package org.xtreemfs.common.libxtreemfs;

import java.net.MalformedURLException;
import java.util.Vector;

import org.xtreemfs.foundation.SSLOptions;
import org.xtreemfs.foundation.VersionManagement;

/**
 *
 * <br>
 * Sep 2, 2011
 */
public class Options {

    enum XtreemFSServiceType {
        kDIR, kMRC
    };

    // XtreemFS URL Options.
    /**
     * URL to the Volume, Form: [pbrpc://]service-hostname[:port]/volume_name.
     *
     * Depending on the type of operation the service-hostname has to point to the DIR (to open/"mount" a
     * volume) or the MRC (create/delete/list volumes). Depending on this type, the default port differs (DIR:
     * 32638; MRC: 32636).
     */
    String      xtreemfsUrl;

    /** Usually extracted from xtreemfs_url (Form: ip-address:port). */
    String      serviceAddress;
    /** Usually extracted from xtreemfs_url. */
    String      volumeName;
    /** Usually extracted from xtreemfs_url. */
    String      protocol;
    /** Mount point on local system (set by ParseCommandLine()). */
    String      mountPoint;

    // General options.
    /** Log level as string (EMERG|ALERT|CRIT|ERR|WARNING|NOTICE|INFO|DEBUG). */
    String      logLevelString;
    /** If not empty, the output will be logged to a file. */
    String      logFilePath;
    /** True, if "-h" was specified. */
    boolean     showHelp;
    /** True, if argc == 1 was at ParseCommandLine(). */
    boolean     emptyArgumentsList;
    /** True, if -V/--version was specified and the version will be shown only . */
    boolean     showVersion;

    // Optimizations.
    /**
     * Maximum number of entries of the StatCache
     */
    long        metadataCacheSize;

    /**
     * Time to live for MetadataCache entries.
     */
    long        metadataCacheTTLs;

    /**
     * Maximum number of pending bytes (of async writes) per file.
     */
    int         maxWriteahead;

    /**
     * Maximum number of pending async write requests per file.
     */
    int         maxWriteaheadRequests;

    /**
     * Number of retrieved entries per readdir request.
     */
    int         readdirChunkSize;

    // Error Handling options.
    /**
     * How often shall a failed operation get retried?
     */
    int         maxTries;
    /**
     * How often shall a failed read operation get retried?
     */
    int         maxReadTries;
    /**
     * How often shall a failed write operation get retried?
     */
    int         maxWriteTries;
    /**
     * How long to wait after a failed request?
     */
    int         retryDelay_s;

    /**
     * Stops retrying to execute a synchronous request if this signal was send to the thread responsible for
     * the execution of the request.
     */
    int         interruptSignal;

    /**
     * Maximum time until a connection attempt will be aborted.
     */
    private int connectTimeout_s;
    /**
     * Maximum time until a request will be aborted and the response returned.
     */
    private int requestTimeout_s;

    /**
     * The RPC Client closes connections after "linger_timeout_s" time of inactivity.
     */
    private int lingerTimeout_s;

    public long getMetadataCacheSize() {
        return metadataCacheSize;
    }

    public long getMetadataCacheTTLs() {
        return metadataCacheTTLs;
    }

    public int getInterruptSignal() {
        return interruptSignal;
    }

    public int getConnectTimeout_s() {
        return connectTimeout_s;
    }

    public int getRequestTimeout_s() {
        return requestTimeout_s;
    }

    public int getLingerTimeout_s() {
        return lingerTimeout_s;
    }

    // SSL options.
    String  sslPemCertPath;
    String  sslPemPath;
    String  sslPemKeyPass;
    String  sslPKCS2Path;
    String  sslPKCS12Pass;

    // Grid Support options.
    /**
     * True, if the XtreemFS Grid-SSL Mode (only SSL handshake, no encryption of data itself) shall be used.
     */
    boolean gridSSL;
    /** True if the Globus user mapping shall be used. */
    boolean gridAuthModeGlobus;
    /** True if the Unicore user mapping shall be used. */
    boolean gridAuthModeUnicore;
    /** Location of the gridmap file. */
    String  gridGridmapLocation;
    /** Default Location of the Globus gridmap file. */
    String  gridGridmapLocationDefaultGlobus;
    /** Default Location of the Unicore gridmap file. */
    String  gridGridmapLocationDefaultUnicore;
    /** Periodic interval after which the gridmap file will be reloaded. */
    int     gridGridmapReloadInterval_m;

    // Advanced XtreemFS options

    /**
     * Interval for periodic file size updates in seconds.
     * TODO: Find out default values
     */
    int     periodicFileSizeUpdatesIntervalS = 60;

    /**
     * Interval for periodic xcap renewal in seconds.
     */
    int     periodicXcapRenewalIntervalS = 60;

    protected int getPeriodicXcapRenewalIntervalS() {
        return periodicXcapRenewalIntervalS;
    }

    protected int getPeriodicFileSizeUpdatesIntervalS() {
        return periodicFileSizeUpdatesIntervalS;
    }

    // User mapping.
    /** Type of the UserMapping used to resolve user and group IDs to names. */
    // TODO: Find out what this is.
    // UserMapping::UserMappingType user_mapping_type;

    // private:
    // Sums of options.
    /**
     * Contains all boost program options, needed for parsing and by ShowCommandLineHelp().
     */
    // boost::program_options::options_description all_descriptions_;

    /** Contains descriptions of advanced options. */
    // boost::program_options::options_description hidden_descriptions_;

    /** Set to true if GenerateProgramOptionsDescriptions() was executed. */
    boolean all_descriptions_initialized_;

    // Options itself.
    /** Description of general options (Logging, help). */
    // boost::program_options::options_description general_;

    /** Description of options which improve performance. */
    // boost::program_options::options_description optimizations_;

    /** Description of timeout options etc. */
    // boost::program_options::options_description error_handling_;

    /** Description of SSL related options. */
    // boost::program_options::options_description ssl_options_;

    /** Description of options of the Grid support. */
    // boost::program_options::options_description grid_options_;

    // Hidden options.
    /** Description of options of the Grid support. */
    // boost::program_options::options_description xtreemfs_advanced_options_;

    /**
    *
    */
    public Options() {

    }

    /**
     * Temporary constructor for testing. Remove if commandline parsing is implemented
     */
    public Options(int requestTimeout_s, int connectionTimeout_s, int maxTries, int retryDelay_s) {
        this.requestTimeout_s = requestTimeout_s;
        this.connectTimeout_s = connectionTimeout_s;
        this.maxTries = maxTries;
        this.retryDelay_s = retryDelay_s;

        readdirChunkSize = 1024;
    }

    /**
     * Set options parsed from command line.
     *
     * However, it does not set dir_volume_url and does not call ParseVolumeAndDir().
     *
     * @throws InvalidCommandLineParametersException
     * @throws {@link MalformedURLException}
     */
    public Vector<String> parseCommandLine(String[] args) throws MalformedURLException {
        // TODO: Implement! Find equvivalent of InvalidCommmanLineParameterException
        return new Vector<String>();
    }

    /**
     * Outputs usage of the command line parameters of all options.
     */
    public String showCommandLineHelp() {
        // TODO: Implement!
        return "";
    }

    /**
     * Outputs usage of the command line parameters of volume creation relevant options.
     */
    public String showCommandLineHelpVolumeCreation() {
        // TODO: Implement!
        return "";
    }

    /**
     * Outputs usage of the command line parameters of volume deletion/listing relevant options.
     */
    public String showCommandLineHelpVolumeDeletionAndListing() {
        // TODO: Implement!
        return "";
    }

    /**
     * Returns the version string and prepends "component".
     */
    String showVersion(String component) {
        return component + VersionManagement.RELEASE_VERSION;
    }

    /**
     * Return the version.
     *
     */
    String getVersion() {
        return VersionManagement.RELEASE_VERSION;
    }

    /**
     * Creates a new SSLOptions object based on the value of the members: - ssl_pem_path - ssl_pem_cert_path -
     * ssl_pem_key_pass - ssl_pkcs12_path - ssl_pkcs12_pass - grid_ssl || protocol.
     *
     */
    public SSLOptions generateSSLOptions() {
        // TODO: Implement
        return null;
    }

    /** Extract volume name and dir service address from dir_volume_url. */
    protected void parseURL(XtreemFSServiceType service_type) {
        // TODO: Implement!
    }

    /**
     * Return maxTries.
     */
    public int getMaxTries() {
        return maxTries;
    }

    protected int getMaxWriteTries() {
        return maxWriteTries;
    }

    /**
     * Return retryDelay_s.
     */
    public int getRetryDelay_s() {
        return retryDelay_s;
    }

    public int getMaxWriteahead() {
        return maxWriteahead;
    }

    protected int getMaxWriteaheadRequests() {
        return maxWriteaheadRequests;
    }

    public int getReaddirChunkSize() {
        return readdirChunkSize;
    }

}


text:
require_relative 'base'

module Wordpress::Object
  class Test < Base
    attr_parameter :method_id_matches_query_id, :method_id, :id, :default_string, :default_int, :boolean_whitelist_defaults_to_false, :boolean_whitelist_defaults_to_true, :string_whitelist_defaults_to_foo, :url, :datetime
  end
end


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

namespace ShogiCore.CSA {
    /// <summary>
    /// CSAClientからのイベント発生時の引数
    /// </summary>
    public class CSAClientEventArgs : EventArgs {
        /// <summary>
        /// CSAClient
        /// </summary>
        public CSAClient CSAClient { get; private set; }

        public CSAClientEventArgs(CSAClient client) {
            CSAClient = client;
        }
    }
}


text:
package net.researchgate.azkaban;

import azkaban.user.Role;
import azkaban.user.User;
import azkaban.user.UserManagerException;
import azkaban.utils.Props;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.zapodot.junit.ldap.EmbeddedLdapRule;
import org.zapodot.junit.ldap.EmbeddedLdapRuleBuilder;

import static org.junit.Assert.*;

public class LdapUserManagerTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Rule
    public EmbeddedLdapRule embeddedLdapRule = EmbeddedLdapRuleBuilder
            .newInstance()
            .usingDomainDsn("dc=example,dc=com")
            .withSchema("custom-schema.ldif")
            .importingLdifs("default.ldif")
            .bindingToPort(11389)
            .usingBindDSN("cn=read-only-admin,dc=example,dc=com")
            .usingBindCredentials("password")
            .build();

    private LdapUserManager userManager;

    @Before
    public void setUp() throws Exception {
        Props props = getProps();
        userManager = new LdapUserManager(props);
    }

    private Props getProps() {
        Props props = new Props();
        props.put(LdapUserManager.LDAP_HOST, "localhost");
        props.put(LdapUserManager.LDAP_PORT, "11389");
        props.put(LdapUserManager.LDAP_USE_SSL, "false");
        props.put(LdapUserManager.LDAP_USER_BASE, "dc=example,dc=com");
        props.put(LdapUserManager.LDAP_USERID_PROPERTY, "uid");
        props.put(LdapUserManager.LDAP_EMAIL_PROPERTY, "mail");
        props.put(LdapUserManager.LDAP_BIND_ACCOUNT, "cn=read-only-admin,dc=example,dc=com");
        props.put(LdapUserManager.LDAP_BIND_PASSWORD, "password");
        props.put(LdapUserManager.LDAP_ALLOWED_GROUPS, "");
        props.put(LdapUserManager.LDAP_GROUP_SEARCH_BASE, "dc=example,dc=com");
        return props;
    }

    @Test
    public void testGetUser() throws Exception {
        User user = userManager.getUser("gauss", "password");

        assertEquals("gauss", user.getUserId());
        assertEquals("gauss@ldap.example.com", user.getEmail());
    }

    @Test
    public void testGetUserWithAllowedGroup() throws Exception {
        Props props = getProps();
        props.put(LdapUserManager.LDAP_ALLOWED_GROUPS, "svc-test");
        final LdapUserManager manager = new LdapUserManager(props);

        User user = manager.getUser("gauss", "password");

        assertEquals("gauss", user.getUserId());
        assertEquals("gauss@ldap.example.com", user.getEmail());
    }

    @Test
    public void testGetUserWithAllowedGroupThatGroupOfNames() throws Exception {
        Props props = getProps();
        props.put(LdapUserManager.LDAP_ALLOWED_GROUPS, "svc-test2");
        final LdapUserManager manager = new LdapUserManager(props);

        User user = manager.getUser("gauss", "password");

        assertEquals("gauss", user.getUserId());
        assertEquals("gauss@ldap.example.com", user.getEmail());
    }

    @Test
    public void testGetUserWithEmbeddedGroup() throws Exception {
        Props props = getProps();
        props.put(LdapUserManager.LDAP_ALLOWED_GROUPS, "svc-test");
        props.put(LdapUserManager.LDAP_EMBEDDED_GROUPS, "true");
        final LdapUserManager manager = new LdapUserManager(props);

        User user = manager.getUser("gauss", "password");

        assertEquals("gauss", user.getUserId());
        assertEquals("gauss@ldap.example.com", user.getEmail());
    }

    @Test
    public void testGetUserWithInvalidPasswordThrowsUserManagerException() throws Exception {
        thrown.expect(UserManagerException.class);
        userManager.getUser("gauss", "invalid");
    }

    @Test
    public void testGetUserWithInvalidUsernameThrowsUserManagerException() throws Exception {
        thrown.expect(UserManagerException.class);
        userManager.getUser("invalid", "password");
    }

    @Test
    public void testGetUserWithEmptyPasswordThrowsUserManagerException() throws Exception {
        thrown.expect(UserManagerException.class);
        userManager.getUser("gauss", "");
    }

    @Test
    public void testGetUserWithEmptyUsernameThrowsUserManagerException() throws Exception {
        thrown.expect(UserManagerException.class);
        userManager.getUser("", "invalid");
    }

    @Test
    public void testValidateUser() throws Exception {
        assertTrue(userManager.validateUser("gauss"));
        assertFalse(userManager.validateUser("invalid"));
    }

    @Test
    public void testGetRole() throws Exception {
        Role role = userManager.getRole("admin");

        assertTrue(role.getPermission().isPermissionNameSet("ADMIN"));
    }

    @Test
    public void testInvalidEmailPropertyDoesNotThrowNullPointerException() throws Exception {
        Props props = getProps();
        props.put(LdapUserManager.LDAP_EMAIL_PROPERTY, "invalidField");
        userManager = new LdapUserManager(props);
        User user = userManager.getUser("gauss", "password");

        assertEquals("gauss", user.getUserId());
        assertEquals("", user.getEmail());
    }

    @Test
    public void testInvalidIdPropertyThrowsUserManagerException() throws Exception {
        thrown.expect(UserManagerException.class);

        Props props = getProps();
        props.put(LdapUserManager.LDAP_USERID_PROPERTY, "invalidField");
        userManager = new LdapUserManager(props);
        userManager.getUser("gauss", "password");
    }

    @Test
    public void testEscapeLDAPSearchFilter() throws Exception {
        assertEquals("No special characters to escape", "Hi This is a test #çà", LdapUserManager.escapeLDAPSearchFilter("Hi This is a test #çà"));
        assertEquals("LDAP Christams Tree", "Hi \\28This\\29 = is \\2A a \\5C test # ç à ô", LdapUserManager.escapeLDAPSearchFilter("Hi (This) = is * a \\ test # ç à ô"));
    }
}


text:
require 'rails_helper'

RSpec.describe TransamGeocodable do

  context 'geocode an organization' do
    let(:test_org) { create(:organization, address1: "123 Fake Street", city: "Bloston", state: "MA", zip: "00000") }

    it 'icon_class' do
      expect(test_org.icon_class).to eq('blueIcon')
    end

    it 'is located in Massachusetts', skip: true do # geocoder seems to change the coordinates when this loose
      expect(test_org.latitude).to be_within(0.000001).of(42.360083)
      expect(test_org.longitude).to be_within(0.000001).of(-71.05888)
    end

    it 'is located in Medford', skip: true do # geocoder seems to change the coordinates when this loose
      test_org.city = "Medford"
      test_org.geocode
      expect(test_org.latitude).to be_within(0.000001).of(42.418430)
      expect(test_org.longitude).to be_within(0.000001).of(-71.106164)
    end

    it 'is located in the 02155 zip code' do
      test_org.zip = "02155"
      test_org.geocode
      expect(test_org.latitude).to be_within(0.000001).of(42.427497)
      expect(test_org.longitude).to be_within(0.000001).of(-71.109201)
    end

    it 'is located at CS' do
      test_org.address1 = "101 Station Landing"
      test_org.geocode
      expect(test_org.latitude).to be_within(0.000001).of(42.401721)
      expect(test_org.longitude).to be_within(0.000001).of(-71.081997)
    end
  end

  context 'geocode a vendor' do
    let(:test_vendor) { create(:vendor) }

    it 'icon_class' do
      expect(test_vendor.icon_class).to eq('blueIcon')
    end

    it 'has default state (PA)' do
      expect(test_vendor.latitude).to be_within(0.000001).of(41.2033216)
      expect(test_vendor.longitude).to be_within(0.000001).of(-77.1945247)
    end

    it 'is located in Harrisburg' do
      test_vendor.city = "Harrisburg"
      test_vendor.geocode
      expect(test_vendor.latitude).to be_within(0.000001).of(40.2731911)
      expect(test_vendor.longitude).to be_within(0.000001).of(-76.8867008)
    end

    it 'is located in the 17120 zip code' do
      test_vendor.zip = "17120"
      test_vendor.geocode
      expect(test_vendor.latitude).to be_within(0.000001).of(40.2651105)
      expect(test_vendor.longitude).to be_within(0.000001).of(-76.8843467)
    end

    it 'is located at 400 North Street' do
      test_vendor.address1 = "400 North Street"
      test_vendor.geocode
      expect(test_vendor.latitude).to be_within(0.000001).of(40.2664611)
      expect(test_vendor.longitude).to be_within(0.000001).of(-76.8838063)
    end
  end
end


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

namespace EZOper.TechTester.DModels.Entities.WorksBigsail.Honor3
{
    [Table("EquipmentUnitPrice", Schema = "dbo")]
    public class EquipmentUnitPrice
    {
        [Key]
        [Required(ErrorMessage = "{0}是必填字段")]
        [Column("EquipmentID", Order = 0, TypeName = "bigint")]
        [Display(Name = "设备标识", Description = "设备标识")]
        public Int64 EquipmentID { get; set; }

        [Key]
        [Required(ErrorMessage = "{0}是必填字段")]
        [Column("ProjectID", Order = 1, TypeName = "bigint")]
        [Display(Name = "项目标识", Description = "项目标识")]
        public Int64 ProjectID { get; set; }

        [Required(ErrorMessage = "{0}是必填字段")]
        [Column("UnitPrice", TypeName = "money")]
        [Display(Name = "单价(元)", Description = "单价(元)")]
        public decimal UnitPrice { get; set; }

        [MaxLength(1024, ErrorMessage = "{0}限制长度为1024位")]
        [Required(ErrorMessage = "{0}是必填字段")]
        [Column("Memo", TypeName = "nvarchar")]
        [Display(Name = "说明", Description = "备注")]
        public string Memo { get; set; }

        [ForeignKey("ProjectID")]
        public virtual EquipmentUnitPriceProject EquipmentUnitPriceProject { get; set; }

        [ForeignKey("EquipmentID")]
        public virtual EquipmentItem EquipmentItem { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Barber.Models
{
    public class Employee
    {
        public Employee()
        {
            Activities = new List<Activity>();
        }

        [Key]
        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public List<Activity> Activities { get; set; }
    }
}


text:
package May2021Leetcode;

public class _0709ToLowerCase {
	public static void main(String[] args) {
		System.out.println(toLowerCase("Hello"));
		System.out.println(toLowerCase("here"));
		System.out.println(toLowerCase("LOVELY"));
		System.out.println(toLowerCase("al&phaBET"));
	}

	public static String toLowerCase(String str) {
	}
}


text:
package gribbit.response;

import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * A text-based error response.
 */
public class ErrorResponse extends TextResponse {
    public ErrorResponse(HttpResponseStatus status, String content) {
        super(status, content);
    }
}


text:
namespace ExCSS
{
    internal sealed class HeightMediaFeature : MediaFeature
    {
        public HeightMediaFeature(string name) : base(name)
        {
        }

        internal override IValueConverter Converter => Converters.LengthConverter;
    }
}


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

    <eat-comment/>
    <plurals name="tw__time_hours">
        <item quantity="one">[[59358]] 1h</item>
        <item quantity="other">[[59359]] %dh</item>
    </plurals>
    <plurals name="tw__time_mins">
        <item quantity="one">[[59356]] 1m</item>
        <item quantity="other">[[59357]] %dm</item>
    </plurals>
    <plurals name="tw__time_secs">
        <item quantity="one">[[59354]] 1s</item>
        <item quantity="other">[[59355]] %ds</item>
    </plurals>

    <eat-comment/>
    <string name="dgts__cancel">[[59330]] Cancel</string>
    <string name="dgts__communication_error">[[59338]] Communication Error</string>
    <string name="dgts__confirmation_code">[[59318]] Confirmation code</string>
    <string name="dgts__confirmation_edit_hint">[[59324]] Enter confirmation code</string>
    <string name="dgts__confirmation_error">[[59343]] Unable to confirm your phone number</string>
    <string name="dgts__confirmation_error_alternative">[[59344]] Sorry, we are having trouble sending you a\
        confirmation code. Please try signing in below.</string>
    <string name="dgts__confirmation_expired">[[59337]] This code has expired. Please resend\
        confirmation code.</string>
    <string name="dgts__confirmation_send_text">[[59320]] Send confirmation code</string>
    <string name="dgts__confirmation_sending_text">[[59322]] Sending confirmation code</string>
    <string name="dgts__confirmation_sent_text">[[59321]] Sent confirmation code</string>
    <string name="dgts__confirmation_sms">[[59319]] Confirmation code: %1$s. Enter this code in %2$s</string>
    <string name="dgts__create_account_text">[[59325]] Create account</string>
    <string name="dgts__creating_account_text">[[59326]] Creating account</string>
    <string name="dgts__dismiss">[[59340]] Dismiss</string>
    <string name="dgts__find_your_friends">[[59346]] Find your friends</string>
    <string name="dgts__image_header_description">[[60972]] Image header for login</string>
    <string name="dgts__login_digits_text">[[59315]] Use my phone number</string>
    <string name="dgts__network_error">[[59339]] Please check your network and try again.</string>
    <string name="dgts__not_now">[[59332]] Not now</string>
    <string name="dgts__okay">[[59331]] Okay</string>
    <string name="dgts__phone_number_edit_hint">[[59317]] Your Number</string>
    <string name="dgts__phone_number_text">[[59316]] Enter your phone number</string>
    <string name="dgts__resend">[[59341]] Resend</string>
    <string name="dgts__resend_confirmation_text">[[59329]] Resend confirmation code</string>
    <string name="dgts__sign_in">[[59333]] Sign in</string>
    <string name="dgts__sign_in_error">[[59361]] We could not sign you in with Twitter at this time.\
        Please try again later.</string>
    <string name="dgts__sign_in_twitter">[[59345]] Sign in with Twitter</string>
    <string name="dgts__signing_in">[[59334]] Signing in</string>
    <string name="dgts__success_desc">[[60971]] Success Icon</string>
    <string name="dgts__terms_text">[[60968]] By tapping \"Send confirmation code\" above,\
        Digits by Twitter, will send you a SMS message to confirm your phone number.</string>
    <string name="dgts__terms_text_create">[[60969]] By tapping \"Create account\" above, you agree to the Terms\
        of Service, Privacy Policy, and Cookies Policy of Digits by Twitter, and that other\
        users of this app can discover you by phone number and/or email.</string>
    <string name="dgts__terms_text_create_app">[[60970]] By tapping \"Create account\" above, you agree to the\
        Terms of Service, Privacy Policy, and Cookies Policy of Digits by Twitter, and that other\
        users of %1$s can discover you by phone number and/or email.</string>
    <string name="dgts__try_again">[[59342]] Try Again</string>
    <string name="dgts__try_again_confirmation">[[59336]] Please check your code and try again.</string>
    <string name="dgts__try_again_phone_number">[[59335]] Please check your number and try again.</string>
    <string name="dgts__try_another_phone">[[59360]] Try a different phone number</string>
    <string name="dgts__upload_contacts">[[59347]] We use Digits by Twitter to find more of your friends who use\
        this app. When you tap Okay, we\'ll upload your address book to Digits by Twitter and\
        enable other users of our app to discover you.</string>

    <eat-comment/>
    <string name="tw__loading_tweet">[[60974]] Loading Tweet</string>

    <eat-comment/>
    <string name="tw__login_btn_txt">[[45095]] Sign in with Twitter</string>

    <eat-comment/>
    <string name="tw__relative_date_format_long">[[59353]] MM/dd/yy</string>
    <string name="tw__relative_date_format_short">[[59352]] MMM dd</string>
    <string name="tw__share_content_format">[[60977]] Check out \@%1$s\'s Tweet: https://twitter.com/%1$s/status/%2$s</string>
    <string name="tw__share_subject_format">[[60978]] Tweet from %1$s (\@%2$s)</string>
    <string name="tw__share_tweet">[[60976]] Share Tweet</string>
    <string name="tw__tweet_content_description">[[60975]] %1$s. %2$s. %3$s.</string>
</resources>


text:
package gov.nasa.pds.services.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import gov.nasa.pds.entities.ElementAlias;
import gov.nasa.pds.entities.MetadataObject;
import gov.nasa.pds.entities.ObjectAlias;
import gov.nasa.pds.entities.Property;
import gov.nasa.pds.entities.TargetType;
import gov.nasa.pds.entities.UnitAlias;
import gov.nasa.pds.services.DataDictionaryImportPersistence;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.JUnit4TestAdapter;

/**
 *

 * The unit test of {@link JDBCDataDictionaryImportPersistence} class.
 *

 *
 * @author TCSASSEMBLER
 * @version 1.0
 */
public class JDBCDataDictionaryImportPersistenceTest {
    /**
     * The sql connection for test.
     */
    private Connection conn;

    /**
     * The application context for test.
     */
    private ApplicationContext context;

    /**
     * The data dictionary import persistence for test.
     */
    private DataDictionaryImportPersistence dataDictionaryImportPersistence;

    /**
     * Adapter for JUnit 3.
     *
     * @return a test suite.
     */
    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(JDBCDataDictionaryImportPersistenceTest.class);
    }

    /**
     * Sets up the unit tests.
     *
     * @throws Exception to JUnit.
     */
    @Before
    public void setUp() throws Exception {
        conn = TestHelper.getConnection();
        context = new ClassPathXmlApplicationContext("beans.xml");
        dataDictionaryImportPersistence = (DataDictionaryImportPersistence) context.getBean(
                "dataDictionaryImportPersistence");
    }

    /**
     * Tears down the test environment.
     *
     * @throws Exception to JUnit.
     */
    @After
    public void tearDown() throws Exception {
        try {
            TestHelper.deleteData(conn);
        } finally {
            TestHelper.closeConnection(conn);
        }
    }

    /**
     * Test method insertObjectAliases(List<ObjectAlias> objectAliases).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertObjectAliases() throws Exception {
        List<ObjectAlias> objectAliases = new ArrayList<ObjectAlias>();
        ObjectAlias objectAlias = new ObjectAlias();
        objectAlias.setAlias("alias1");
        objectAlias.setFullName("fullName1");
        objectAliases.add(objectAlias);
        objectAlias = new ObjectAlias();
        objectAlias.setAlias("alias2");
        objectAlias.setFullName("fullName2");
        objectAliases.add(objectAlias);
        objectAlias = new ObjectAlias();
        objectAlias.setAlias("alias3");
        objectAlias.setFullName("fullName3");
        objectAliases.add(objectAlias);

        dataDictionaryImportPersistence.insertObjectAliases(objectAliases);
        ResultSet resultSet = TestHelper.query(conn, "Select * from object_alias order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'alias' should be correct", objectAliases.get(i).getAlias(),
                    resultSet.getString("alias"));
            assertEquals("'full_name' should be correct", objectAliases.get(i).getFullName(),
                    resultSet.getString("full_name"));
            assertEquals("'id' should be correct", objectAliases.get(i).getId(),
                    resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);
    }

    /**
     * Test method insertElementAliases(List<ElementAlias> elementAliases).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertElementAliases() throws Exception {
        List<ElementAlias> elementAliases = new ArrayList<ElementAlias>();
        ElementAlias elementAlias = new ElementAlias();
        elementAlias.setAlias("alias1");
        elementAlias.setAnotherName("anotherName1");
        elementAlias.setFullName("fullName1");
        elementAliases.add(elementAlias);
        elementAlias = new ElementAlias();
        elementAlias.setAlias("alias2");
        elementAlias.setAnotherName("anotherName2");
        elementAlias.setFullName("fullName2");
        elementAliases.add(elementAlias);
        elementAlias = new ElementAlias();
        elementAlias.setAlias("alias3");
        elementAlias.setAnotherName("anotherName3");
        elementAlias.setFullName("fullName3");
        elementAliases.add(elementAlias);

        dataDictionaryImportPersistence.insertElementAliases(elementAliases);
        ResultSet resultSet = TestHelper.query(conn, "Select * from element_alias order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'alias' should be correct", elementAliases.get(i).getAlias(),
                    resultSet.getString("alias"));
            assertEquals("'another_name' should be correct", elementAliases.get(i).getAnotherName(),
                    resultSet.getString("another_name"));
            assertEquals("'full_name' should be correct", elementAliases.get(i).getFullName(),
                    resultSet.getString("full_name"));
            assertEquals("'id' should be correct", elementAliases.get(i).getId(),
                    resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);
    }

    /**
     * Test method insertUnitAliases(List<UnitAlias> unitAliases).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertUnitAliases() throws Exception {
        List<UnitAlias> unitAliases = new ArrayList<UnitAlias>();
        UnitAlias unitAlias = new UnitAlias();
        unitAlias.setAlias("alias1");
        unitAlias.setFullName("fullName1");
        unitAliases.add(unitAlias);
        unitAlias = new UnitAlias();
        unitAlias.setAlias("alias2");
        unitAlias.setFullName("fullName2");
        unitAliases.add(unitAlias);
        unitAlias = new UnitAlias();
        unitAlias.setAlias("alias3");
        unitAlias.setFullName("fullName3");
        unitAliases.add(unitAlias);

        dataDictionaryImportPersistence.insertUnitAliases(unitAliases);
        ResultSet resultSet = TestHelper.query(conn, "Select * from unit_alias order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'alias' should be correct", unitAliases.get(i).getAlias(),
                    resultSet.getString("alias"));
            assertEquals("'full_name' should be correct", unitAliases.get(i).getFullName(),
                    resultSet.getString("full_name"));
            assertEquals("'id' should be correct", unitAliases.get(i).getId(),
                    resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);
    }

    /**
     * Test method insertTargetTypes(List<TargetType> targetTypes).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertTargetTypes() throws Exception {
        List<TargetType> targetTypes = new ArrayList<TargetType>();
        TargetType targetType = new TargetType();
        targetType.setName("name1");
        targetTypes.add(targetType);
        targetType = new TargetType();
        targetType.setName("name2");
        targetTypes.add(targetType);
        targetType = new TargetType();
        targetType.setName("name3");
        targetTypes.add(targetType);

        dataDictionaryImportPersistence.insertTargetTypes(targetTypes);
        ResultSet resultSet = TestHelper.query(conn, "Select * from target_type order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'name' should be correct", targetTypes.get(i).getName(),
                    resultSet.getString("name"));
            assertEquals("'id' should be correct", targetTypes.get(i).getId(),
                    resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);
    }

    /**
     * Test method insertElementDefinitions(List<MetadataObject> elementDefinitions).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertElementDefinitions() throws Exception {
        final String metadataObjectName = "ELEMENT_DEFINITION";

        List<MetadataObject> elementDefinitions = new ArrayList<MetadataObject>();

        // Each element definition object should have 'NAME' property defined. It's a property that
        // get stored into the database. There is a difference between 'NAME' property of the element
        // definition object (it can be any string value) and the name of the object itself, which is
        // always 'ELEMENT_DEFINITION' for element definition objects.

        List<String> names = Arrays.asList(
                "MRO:MS_TRUSS_LEG_240_A_TEMPERATURE",
                "CENTRAL_BODY_DISTANCE",
                "CH1:STATISTICAL_POLISHER_FILE_NAME");

        MetadataObject elementDefinition = new MetadataObject(metadataObjectName);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(0)));
        elementDefinition.getProperties().add(
                TestHelper.createProperty("propertyName1", "value1", "value2", "value3"));
        elementDefinition.getProperties().add(TestHelper.createProperty("propertyName2", "value4"));
        elementDefinition.getProperties().add(TestHelper.createProperty("propertyName3", "value5"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(1)));
        elementDefinition.getProperties().add(TestHelper.createProperty("propertyName4", "value6"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(2)));
        elementDefinitions.add(elementDefinition);

        dataDictionaryImportPersistence.insertElementDefinitions(elementDefinitions);

        ResultSet resultSet = TestHelper.query(conn, "Select * from element_definition order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'name' should be correct", names.get(i), resultSet.getString("name"));
            assertEquals("'id' should be correct", elementDefinitions.get(i).getId(), resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);

        resultSet = TestHelper.query(conn, "Select * from element_definition_lookup inner join"
            + " element_definition on element_definition.id = element_definition_lookup.element_id inner"
            + " join lookup_value on lookup_value.id = element_definition_lookup.lookup_id inner join"
            + " keyword on keyword.id = lookup_value.keyword_id order by element_definition_lookup.id");
        i = 0;
        String[] keywordNames = new String[] {"propertyName1", "propertyName1", "propertyName1",
            "propertyName2", "propertyName3", "propertyName4"};
        String[] values = new String[] {"value1", "value2", "value3", "value4", "value5", "value6"};
        String[] elementDefinitionName = new String[] {names.get(0), names.get(0), names.get(0), names.get(0),
                names.get(0), names.get(1)};
        while (resultSet.next()) {
            assertEquals("'keyword.name' should be correct", keywordNames[i],
                    resultSet.getString("keyword.name"));
            assertEquals("'value' should be correct", values[i], resultSet.getString("value"));
            assertEquals("'element_definition.name' should be correct", elementDefinitionName[i],
                    resultSet.getString("element_definition.name"));
            i++;
        }
        assertEquals("should be five records", 6, i);
    }

    /**
     * Test method insertObjectDefinitions(List<MetadataObject> objectDefinitions).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertObjectDefinitions() throws Exception {
        // Metadata objects that represent object definitions can have two possible names
        final String metadataObjectName1 = "GENERIC_OBJECT_DEFINITION";
        final String metadataObjectName2 = "SPECIFIC_OBJECT_DEFINITION";

        List<MetadataObject> objectDefinitions = new ArrayList<MetadataObject>();

        // Each object definition object should have 'NAME' property defined. It's a property that
        // get stored into the database. There is a difference between 'NAME' property of the element
        // definition object (it can be any string value) and the name of the object itself, which is
        // always either 'GENERIC_OBJECT_DEFINITION' or 'SPECIFIC_OBJECT_DEFINITION' for element definition objects.

        List<String> names = Arrays.asList(
                "DATA_SET_HOUSEKEEPING",
                "DATA_SET_COLLECTION_INFO",
                "DATA_SET_HOST");

        MetadataObject objectDefinition = new MetadataObject(metadataObjectName1);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(0)));
        objectDefinition.getProperties().add(
                TestHelper.createProperty("propertyName1", "value1", "value2", "value3"));
        objectDefinition.getProperties().add(TestHelper.createProperty("propertyName2", "value4"));
        objectDefinition.getProperties().add(TestHelper.createProperty("propertyName3", "value5"));
        objectDefinition.getProperties().add(TestHelper.createProperty("REQUIRED_ELEMENT_SET", "value6"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName2);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(1)));
        objectDefinition.getProperties().add(TestHelper.createProperty("propertyName4", "value7"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_ELEMENT_SET", "value8"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName2);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", names.get(2)));
        objectDefinition.getProperties().add(TestHelper.createProperty("REQUIRED_OBJECT_SET", "value9"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_OBJECT_SET", "value10"));
        objectDefinitions.add(objectDefinition);

        dataDictionaryImportPersistence.insertObjectDefinitions(objectDefinitions);

        ResultSet resultSet = TestHelper.query(conn, "Select * from object_definition order by id");
        int i = 0;
        while (resultSet.next()) {
            assertEquals("'name' should be correct", names.get(i), resultSet.getString("name"));
            assertEquals("'id' should be correct", objectDefinitions.get(i).getId(), resultSet.getLong("id"));
            i++;
        }
        assertEquals("should be three records", 3, i);

        resultSet = TestHelper.query(conn, "Select * from object_definition_lookup inner join"
            + " object_definition on object_definition.id = object_definition_lookup.object_id inner"
            + " join lookup_value on lookup_value.id = object_definition_lookup.lookup_id inner join"
            + " keyword on keyword.id = lookup_value.keyword_id order by object_definition_lookup.id");
        i = 0;
        String[] keywordNames = new String[] {"propertyName1", "propertyName1", "propertyName1",
            "propertyName2", "propertyName3", "propertyName4"};
        String[] values = new String[] {"value1", "value2", "value3", "value4", "value5", "value7"};
        String[] objectDefinitionName = new String[] {names.get(0), names.get(0), names.get(0), names.get(0),
                names.get(0), names.get(1)};
        while (resultSet.next()) {
            assertEquals("'keyword.name' should be correct", keywordNames[i],
                    resultSet.getString("keyword.name"));
            assertEquals("'value' should be correct", values[i], resultSet.getString("value"));
            assertEquals("'object_definition.name' should be correct", objectDefinitionName[i],
                    resultSet.getString("object_definition.name"));
            i++;
        }
        assertEquals("should be five records", 6, i);
    }

    /**
     * Test method insertValidationRules(List<MetadataObject> objectDefinitions,
     * List<MetadataObject> elementDefinitions).
     *
     * @throws Exception to JUnit.
     */
    @Test
    public void testInsertValidationRules() throws Exception {
        final String metadataObjectName_objectDefinition =  "GENERIC_OBJECT_DEFINITION";
        final String metadataObjectName_elementDefinition = "ELEMENT_DEFINITION";

        List<MetadataObject> objectDefinitions = new ArrayList<MetadataObject>();

        // 1. Create objects that have REQUIRED_... OR OPTIONAL_... properties
        MetadataObject objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "some_object"));
        objectDefinition.getProperties().add(
                TestHelper.createProperty("propertyName1", "value1", "value2", "value3"));
        objectDefinition.getProperties().add(TestHelper.createProperty("propertyName2", "value4"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_ELEMENT_SET", "PSDD2"));
        objectDefinition.getProperties().add(TestHelper.createProperty("REQUIRED_ELEMENT_SET", "value5"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "another_object"));
        objectDefinition.getProperties().add(TestHelper.createProperty("propertyName4", "value6"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_ELEMENT_SET", "PSDD"));
        objectDefinition.getProperties().add(TestHelper.createProperty("REQUIRED_OBJECT_SET", "value7", "value8"));
        objectDefinition.getProperties().add(TestHelper.createProperty("REQUIRED_ELEMENT_SET", "value9"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "third_object"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_ELEMENT_SET", "value10"));
        objectDefinition.getProperties().add(TestHelper.createProperty("OPTIONAL_OBJECT_SET", "value11"));
        objectDefinitions.add(objectDefinition);

        // 2a. Create objects that represent required or optional objects
        objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "value11"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "value7"));
        objectDefinitions.add(objectDefinition);

        objectDefinition = new MetadataObject(metadataObjectName_objectDefinition);
        objectDefinition.setProperties(new ArrayList<Property>());
        objectDefinition.getProperties().add(TestHelper.createProperty("NAME", "value8"));
        objectDefinitions.add(objectDefinition);

        // 2b. Create elements that represent required or optional elements
        List<MetadataObject> elementDefinitions = new ArrayList<MetadataObject>();

        MetadataObject elementDefinition = new MetadataObject(metadataObjectName_elementDefinition);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", "value5"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName_elementDefinition);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", "PSDD2"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName_elementDefinition);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", "otherValue"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName_elementDefinition);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", "value9"));
        elementDefinitions.add(elementDefinition);

        elementDefinition = new MetadataObject(metadataObjectName_elementDefinition);
        elementDefinition.setProperties(new ArrayList<Property>());
        elementDefinition.getProperties().add(TestHelper.createProperty("NAME", "value10"));
        elementDefinitions.add(elementDefinition);

        dataDictionaryImportPersistence.insertObjectDefinitions(objectDefinitions);
        dataDictionaryImportPersistence.insertElementDefinitions(elementDefinitions);
        dataDictionaryImportPersistence.insertValidationRules(objectDefinitions, elementDefinitions);

        ResultSet resultSet = TestHelper.query(conn, "Select * from object_validation order by id");
        int i = 0;
        long[] objectIds = new long[] {objectDefinitions.get(1).getId(), objectDefinitions.get(1).getId(),
                objectDefinitions.get(2).getId()};
        long[] innerObjectIds = new long[] {objectDefinitions.get(4).getId(),
                objectDefinitions.get(5).getId(), objectDefinitions.get(3).getId()};
        boolean[] requireds = new boolean[] {true, true, false};
        while (resultSet.next()) {
            assertEquals("'object_id' should be correct", objectIds[i],
                    resultSet.getLong("object_id"));
            assertEquals("'inner_object_id' should be correct", innerObjectIds[i],
                    resultSet.getLong("inner_object_id"));
            assertEquals("'required' should be correct", requireds[i],
                    resultSet.getBoolean("required"));
            i++;
        }
        assertEquals("should be two records", 3, i);

        resultSet = TestHelper.query(conn, "Select * from element_validation order by id");
        i = 0;
        objectIds = new long[] {objectDefinitions.get(0).getId(), objectDefinitions.get(0).getId(),
                objectDefinitions.get(1).getId(), objectDefinitions.get(2).getId()};
        innerObjectIds = new long[] {elementDefinitions.get(0).getId(), elementDefinitions.get(1).getId(),
                elementDefinitions.get(3).getId(), elementDefinitions.get(4).getId()};
        requireds = new boolean[] {true, false, true, false};
        while (resultSet.next()) {
            assertEquals("'object_id' should be correct" + i, objectIds[i],
                    resultSet.getLong("object_id"));
            assertEquals("'inner_element_id' should be correct" + i, innerObjectIds[i],
                    resultSet.getLong("inner_element_id"));
            assertEquals("'required' should be correct" + i, requireds[i],
                    resultSet.getBoolean("required"));
            i++;
        }
        assertEquals("should be two records", 4, i);

        resultSet = TestHelper.query(conn,
                "Select * from object_definition where id = " + objectDefinitions.get(1).getId());
        i = 0;
        while (resultSet.next()) {
            assertTrue("'globally_allowed_elements' should be correct",
                    resultSet.getBoolean("globally_allowed_elements"));
            i++;
        }
        assertEquals("should be only one record", 1, i);
    }
}


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as TestUtils from 'react-addons-test-utils';

import { DialogComponent } from '../src/components/DialogComponent';
import { IUpdates } from '../src/entities/IUpdates';
import { Position } from '../src/enums/Position';

describe('Dialog Component', () => {
    let renderer: React.ShallowRenderer;

    beforeEach(() => {
        const update: IUpdates = {
            color: '#eee',
            fontSize: 20,
            position: Position.BOTTOM_CENTER,
            value: 'Chan'
        };

        renderer = TestUtils.createRenderer();
        renderer.render(<DialogComponent heading='Hi' formProps={update} />);
    });

    it('should render correctly', () => {
        const result = renderer.getRenderOutput();
        chai.assert.strictEqual(result.type, 'div');
    });

    it('should have correct prop values', () => {
        const result = renderer.getRenderOutput();
        const propValues = result.props;
        chai.assert.strictEqual(propValues.className, 'ms-Dialog');
    });
});


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">


text:
'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$rootScope', '$http', '$location', 'Authentication', 'Users', '$window',
	function($scope, $rootScope, $http, $location, Authentication, Users, $window) {
		$scope.authentication = Authentication;
		$scope.users = {};

		//retrieve a list of users in the website
		$scope.findAllUsers = function(){
			$scope.users = Users.query();
		};

		// If user is signed in then redirect back home
		if ($scope.authentication.user) $location.path('/');

		$scope.signup = function() {
			// PIN Setting
	        var testPIN = 0;
	        var PINFound = false;

	        var i = 0;
	        do{
	          // Format the PIN so it is 4 digits
	          testPIN = ('000' + i).slice(-4);
	            // Check the PIN against every user in users for matches
	            for(var j = 0; j < $scope.users.length; j++){
	              // If the PIN matches a user, move on to the next try
	              if($scope.users[j].PIN === testPIN){
	                break;
	              }
	              // If we have checked it against every user and there were no matches
	              // we have found a good PIN
	              if(j === ($scope.users.length-1)){
	                PINFound = true;
	              }
	            }
	            i++;
	        }
	        while (i < 9999 && PINFound !== true);

			$scope.credentials.PIN = testPIN;
			console.log('test in signup');
			$http.post('/auth/signup', $scope.credentials).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.authentication.user = response;

				// And redirect to the children/create page
				//$location.path('/children/create');
				$location.path('/success');
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		$scope.signin = function() {
			$http.post('/auth/signin', $scope.credentials).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.authentication.user = response;
				// And redirect to the index page
				$location.path('/');
				// HERE IS THE "SOLUTION"
        /*$rootScope.$on('$stateChangeSuccess', function(){
            $window.location.reload();
        });*/

			}).error(function(response) {
				$scope.error = response.message;
			});
		};
	}
]);


text:
require 'net/ssh'
require 'json'

module CEPH
  class Radosgw

    attr_reader :username, :ipaddress, :user_password, :uid

    def initialize(options)
      raise ArgumentError, "Missing :username." if !options[:username]
      raise ArgumentError, "Missing :ipaddress." if !options[:ipaddress]
      raise ArgumentError, "Missing :user_password." if !options[:user_password]

      @username = options.fetch(:username)
      @ipaddress = options.fetch(:ipaddress)
      @user_password = options.fetch(:user_password)
    end

    def user_create(uid)
	ceph_user_json = ""
	Net::SSH.start( @ipaddress, @username, :password => @user_password ) do|ssh|
		ceph_user_json = ssh.exec!("sudo radosgw-admin user create --uid='#{uid}'  --display-name='radosgw demo user from s3 gem'")
	end

    ceph_user_hash = JSON.parse(ceph_user_json)
    secret_hash = {"access_key" => "#{ceph_user_hash['keys'][0]['access_key']}", "secret_key" => "#{ceph_user_hash['keys'][0]['secret_key']}" }
    secret_hash
    end

  end
end


text:
> Come let us arrange
> These lovely flowers in the bowl
> Since there is no rice
>                           - Basho

Create BMP files from scratch using pure bash. No external dependencies.

Currently used in [BitBar](https://github.com/matryer/bitbar) plugins like [mtop](https://github.com/ganeshv/mtop)
to draw small graphs to display on the Mac OS menubar.

## Usage

`bitbash` supports two versions of BMP files.

  * Version 1 corresponds to BITMAPINFOHEADER as described [on Wikipedia](https://en.wikipedia.org/wiki/BMP_file_format). This is the most compatible version of BMP, but most viewers don't honour the alpha channel.
  * Version 5 corresponds to BITMAPV5HEADER, which officially supports alpha.

Note that `file` doesn't recognize the v5 files we make, or that ImageMagick
makes, but Preview et al do.

Drawing primitives set the current color. No alpha blending is done.

    pixels=()             # set pixels to empty or with background of same size
                          # as will be declared in init_bmp
    curcol=(bb 66 44 aa)  # set current color, BGRA, hex (%02x)
    init_bmp 1 25 16      # initialize BMP, version 1 width 25 height 16
                          # if pixels not valid, initialize to $curcol
    curcol=(00 00 00 ff)  # set current color to fully opaque black
    point $x $y           # set ($x, $y) to $curcol. (0, 0) is bottom left
    line $x1 $y1 $x2 $y2  # draw horizontal or vertical line
    rect $x $y $w $h      # draw rectangle. ($x, $y) is bottom left
    fill $x $y $w $h      # draw filled rectangle. ($x, $y) is bottom left
    output_bmp            # output BMP to stdout

## Examples

### Swiss flag

    pixels=()                   # clear pixels
    curcol=(00 00 ff ff)        # set color to red
    init_bmp 1 32 32            # declare 32x32 BMP, version 1
    fill 0 0 $width $height     # fill the whole thing with red (current color)
    curcol=(ff ff ff ff)        # set color to white
    fill 13 6 6 20              # vertical stripe
    fill 6 13 20 6              # horizontal strip
    output_bmp >/tmp/flag.bmp   # write BMP to file

produces this 32x32 BMP: ![swiss flag](https://raw.github.com/ganeshv/bitbash/master/test/ref/swiss.v1.bmp)

### Bar graph

    pixels=()                                               # clear pixels
    curcol=(00 00 00 00)                                    # transparent back
    init_bmp 5 25 16                                        # 25x16, v5
    curcol=(00 00 00 ff)                                    # opaque black
    fill 0 0 $width 2                                       # 2px bottom border
    line 0 $((height - 1)) $((width - 1)) $((height - 1))   # 1px top border
    heights=(0 1 2 3 4 5 6 7 8 9 10 11 12 13 12 11 8 4 0 0) # height of bars
    for ((i = 0; i < ${#heights[@]}; i++)); do
        line $i 1 $i $((1 + ${heights[$i]}))                # draw 1px bars
    done
    output_bmp >/tmp/graph.bmp                              # write BMP to file

produces the following 25x16 BMP: ![bar graph](https://raw.github.com/ganeshv/bitbash/master/test/ref/mtop2.v5.bmp)