text:
package base;

import housing.interfaces.HousingBase;
import housing.roles.HousingBaseRole;
import housing.roles.HousingLandlordRole;
import housing.roles.HousingRenterRole;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;

import market.interfaces.MarketCustomer;
import market.roles.MarketCashierRole;
import market.roles.MarketCustomerRole;
import market.roles.MarketDeliveryTruckRole;
import market.roles.MarketWorkerRole;
import restaurant.intermediate.RestaurantCashierRole;
import restaurant.intermediate.RestaurantCookRole;
import restaurant.intermediate.RestaurantCustomerRole;
import restaurant.intermediate.RestaurantHostRole;
import restaurant.intermediate.RestaurantWaiterRole;
import restaurant.restaurant_cwagoner.roles.CwagonerCustomerRole;
import restaurant.restaurant_davidmca.roles.DavidCustomerRole;
import restaurant.restaurant_duvoisin.roles.AndreCustomerRole;
import restaurant.restaurant_jerryweb.JerrywebCustomerRole;
import restaurant.restaurant_maggiyan.roles.MaggiyanCustomerRole;
import restaurant.restaurant_smileham.roles.SmilehamCustomerRole;
import restaurant.restaurant_tranac.roles.TranacCustomerRole;
import restaurant.restaurant_xurex.RexCustomerRole;
import transportation.roles.CommuterRole;
import transportation.roles.CommuterRole.PersonState;
import bank.BankAction;
import bank.roles.BankCustomerRole;
import bank.roles.BankCustomerRole.EnumAction;
import bank.roles.BankGuardRole;
import bank.roles.BankMasterTellerRole;
import bank.roles.BankTellerRole;
import bank.test.mock.MockTellerRole;
import base.Event.EnumEventType;
import base.Item.EnumItemType;
import base.interfaces.Person;
import base.interfaces.Role;
import city.gui.CityPerson;
import city.gui.SimCityGui;
import city.gui.trace.AlertTag;

public class PersonAgent extends Agent implements Person {
	//----------------------------------------------------------DATA----------------------------------------------------------
	//Static data
	public static int sSSN = 0;
	public static int sRestaurantCounter = 0;
	public static int sHouseCounter = 0;
	public static int sBaseInventory = 0;
	public static int sBaseWanted = 1;
	//Roles and Job
	public static enum EnumJobType {	HOUSING,	//master landlord
										BANK,		//master teller, teller, guard...
										MARKET, 	//cashier, worker...
										RESTAURANT, //...
										NONE};		//party person, non-norms (can add NN1, NN2, ...)
	public EnumJobType mJobType;
	public Map<Role, Boolean> mRoles; 	//roles, active -  i.e. WaiterRole, BankTellerRole, etc.

	//Lists
	private List<Person> mFriends; 						// best friends are those with same timeshift
	private List<Event> mEvents; 						// tree set ordered by time of event
	private Map<EnumItemType, Integer> mItemInventory; 	// personal inventory
	private Map<EnumItemType, Integer> mItemsDesired; 	// not ordered yet
	Set<Location> mHomeLocations; 						//multiple for landlord

	//Personal Variables
	private String mName;
	private int mSSN;
	private int mTimeShift;
	private double mCash;
	private double mLoan;
	private boolean mHasCar;
	private boolean mAtJob;		//used in PAEA

	// GUI/Commuter Stuff
	public CityPerson mPersonGui;
	public CommuterRole mCommuterRole;
	public EnumCommuteTo mCommutingTo;
	public static enum EnumCommuteTo {	JOB,
										HOUSE,
										MARKET,
										RESTAURANT,
										BANK,
										PARTY,
										INSPECT};
	public EventParty mCurrentParty = null;
	public Boolean firstRun = true;

	// Inspector
//	public int inspectCounter;

	//PAEA Helpers
	public Semaphore semAnimationDone = new Semaphore(0);
	public boolean mRoleFinished = true;
	public MockTellerRole mJobRole;

	// ----------------------------------------------------------CONSTRUCTOR----------------------------------------------------------

	public PersonAgent() {
		initializePerson();
	}

	public PersonAgent(EnumJobType jobType, double cash, String name){
		mJobType = jobType;
		mCash = cash;
		mName = name;
		initializePerson();

		//Get job role and location; set active if necessary
		Role jobRole = null;
		switch (jobType){
			case BANK:
				jobRole = SortingHat.getBankRole(mTimeShift);
				if(mTimeShift==Time.GetShift() && jobRole != null){
					print("Bank role person auto set: "+jobRole.toString());
					if (jobRole instanceof BankTellerRole){
						ContactList.sBankList.get(((BankTellerRole)jobRole).mBankID).mGuard.msgReadyToWork((BankTellerRole)jobRole);
						ContactList.sBankList.get(((BankTellerRole)jobRole).mBankID).addPerson(jobRole);
					}
				}
				break;
			case MARKET:
				jobRole = SortingHat.getMarketRole(mTimeShift);
				break;
			case RESTAURANT:
				jobRole = SortingHat.getRestaurantRole(mTimeShift);
				if(jobRole != null)
					print(jobRole.toString());
				break;
			case HOUSING:
				jobRole = SortingHat.getHousingRole(this, mTimeShift, false);
				break;
			case NONE:
				break;
		}

		//Link person and role
		boolean active = (mTimeShift == Time.GetShift());	//set active if job shift is now
		if (jobRole != null){
			mRoles.put(jobRole, active);					//give person a reference to the role (and if currently filling role)
		}
		if (active){
			for (Role iRole : mRoles.keySet()){
				iRole.setPerson(this);						//give role a reference to the person (only if currently filling role)
			}
		}

		//Add customer/rider role possibilities
		mCommuterRole = new CommuterRole(this);
		mCommuterRole.mActive = false;
		mCommutingTo = null;

		if (mName.contains("renter")) {
			print("made renter!");
			mRoles.put(SortingHat.getHousingRole(this, mTimeShift, true), true);
		}
		else {
			mRoles.put(SortingHat.getHousingRole(this, mTimeShift, false), true);
		}
		//mRoles.put(new CommuterRole(this), false);
		mRoles.put(new BankCustomerRole(this, mSSN%2), false);
		mRoles.put(new MarketCustomerRole(this, mSSN%2), false);
		mRoles.put(new RestaurantCustomerRole(this), false);
	}

	private void initializePerson(){
		//Roles and Job
		mRoles = new HashMap<Role, Boolean>(); //role to active
		mAtJob = false;

		//Lists
		mFriends = new ArrayList<Person>();
		mEvents = Collections.synchronizedList(new ArrayList<Event>());
		mItemInventory = Collections.synchronizedMap(new HashMap<EnumItemType, Integer>());
			//populate inventory
			mItemInventory.put(EnumItemType.CAR,0);
			mItemInventory.put(EnumItemType.CHICKEN,sBaseInventory);
			mItemInventory.put(EnumItemType.PIZZA,sBaseInventory);
			mItemInventory.put(EnumItemType.STEAK,sBaseInventory);
			mItemInventory.put(EnumItemType.SALAD,sBaseInventory);
		mItemsDesired = Collections.synchronizedMap(new HashMap<EnumItemType, Integer>());
			mItemInventory.put(EnumItemType.CAR,0);
			mItemInventory.put(EnumItemType.CHICKEN,0);
			mItemInventory.put(EnumItemType.PIZZA,0);
			mItemInventory.put(EnumItemType.STEAK,0);
			mItemInventory.put(EnumItemType.SALAD,0);

		mHomeLocations = Collections.synchronizedSet(new HashSet<Location>());

		//Personal Variables
		mSSN = sSSN++; // assign SSN
		//mTimeShift = 0;
		mTimeShift = (mSSN % ContactList.cNumTimeShifts); // assign time schedule
		mLoan = 0;
		mHasCar = true;

		//Role References
		//mPersonGui = new CityPerson(this, SimCityGui.getInstance(), sSSN * 5 % 600, sSSN % 10 + 250);
		//Role References
        Location startLocation = null;
        if (mSSN % 8 == 0) startLocation = new Location(60, 0);
        if (mSSN % 8 == 1) startLocation = new Location(0, 60);
        if (mSSN % 8 == 2) startLocation = new Location(540, 0);
        if (mSSN % 8 == 3) startLocation = new Location(0, 540);
        if (mSSN % 8 == 4) startLocation = new Location(60, 600);
        if (mSSN % 8 == 5) startLocation = new Location(600, 60);
        if (mSSN % 8 == 6) startLocation = new Location(540, 600);
        if (mSSN % 8 == 7) startLocation = new Location(600, 540);
        mPersonGui = new CityPerson(this, SimCityGui.getInstance(), startLocation);

		// Event Setup
		mEvents = Collections.synchronizedList(new ArrayList<Event>());

//		inspectCounter = -1;
	}

	// ----------------------------------------------------------MESSAGES----------------------------------------------------------
	public void msgTimeShift() {
		//if(mJobType == EnumJobType.BANK)
			//finished role if job
			mRoleFinished = true;
			if (Time.GetShift() == mTimeShift) {
				mRoles.put(getJobRole(), true);
			}
			//Leave job
			if ((mTimeShift + 1) % ContactList.cNumTimeShifts == Time.GetShift()){ //if job shift is over
				mAtJob = false;
				mRoles.put(getJobRole(), false); //set job role to false;
				mPersonGui.setPresent(true);
			}
			if(getJobRole()!=null)
				stateChanged();
	}

	public void msgStateChanged() {
		stateChanged();
	}

	public void msgAddEvent(Event event) {
		if(event.mEventType == EnumEventType.RSVP1){
			if(((EventParty)event).mHost.getName().equals("partyPersonFlake") && mSSN%ContactList.cNumTimeShifts==0){
				print("I am a deadbeat");
				return;
			}
		}
		mEvents.add(event);
	}

	public void msgAnimationDone(){
		if (semAnimationDone.availablePermits() == 0) semAnimationDone.release();
	}

	public void msgRoleFinished(){
		mRoleFinished = true;
		mPersonGui.setPresent(true);
		for (Role iRole : mRoles.keySet()){
			if(!(iRole instanceof HousingBase)){
				mRoles.put(iRole, false);
				iRole.setActive();
			}
		}
	}

	public void msgHereIsPayment(int senderSSN, double amount){
		mCash += amount;
	}

	public void msgOverdrawnAccount(double loan) {
		mLoan += loan;
	}

	// ----------------------------------------------------------SCHEDULER----------------------------------------------------------
	@Override
	public boolean pickAndExecuteAnAction() {
		if ((mRoleFinished) && (!mAtJob) ){
			// Process events (calendar)
			synchronized(mEvents){
				Collections.sort((mEvents));
			}
			if(mEvents.isEmpty()) {
//				//System.out.println("test");
				return false;
			}
			Event event = mEvents.get(0); //next event
			print("" + event.mEventType);
			if (event.mTime <= Time.GetTime()){ //only do events that have started
				if(!mName.contains("party") && !mName.contains("other") && !mName.contains("inter")) //required because party is not a role
					mRoleFinished = false; //doing a role
				processEvent(event);
				return true;
			}
		}

		// Do role actions
		for (Role iRole : mRoles.keySet()) {
			if (mRoles.get(iRole) && iRole!= null) {
				if (!iRole.hasPerson()) {
					print(iRole.toString());
					print("getPerson in iRole was null");
				}
				else if (mCommuterRole.mActive){
					if(mCommuterRole.pickAndExecuteAnAction()){
						return true;
					}
				}
				else if (iRole.pickAndExecuteAnAction()){
					return true;
				}
			}
		}

		//last choice - go home
		return false;
	}

	// ----------------------------------------------------------ACTIONS----------------------------------------------------------
	private synchronized void processEvent(Event event) {
		mAtJob = false;
		//One time events (Car)
		if (event.mEventType == EnumEventType.GET_CAR) {
			getCar();
		}
		else if (event.mEventType == EnumEventType.REQUEST_HOUSE) {
			requestHouse();
		}
		//Daily Recurring Events (Job, Eat)
		else if (event.mEventType == EnumEventType.JOB) {
			//bank is closed on weekends
			if (!(Time.IsWeekend()) || (mJobType != EnumJobType.BANK)){
				mAtJob = true;
				goToJob();
			}
		}
		else if (event.mEventType == EnumEventType.EAT) {
			eatFood();
		}

		//Intermittent Events (Deposit Check)
		else if (event.mEventType == EnumEventType.DEPOSIT_CHECK) {
			print("DepositCheck");
			depositCheck();
		}

		else if (event.mEventType == EnumEventType.ASK_FOR_RENT) {
			invokeRent();
		}

		else if (event.mEventType == EnumEventType.MAINTAIN_HOUSE) {
			invokeMaintenance();
		}

		//Party Events
		else if (event.mEventType == EnumEventType.INVITE1) {

			inviteToParty();
		}
		else if (event.mEventType == EnumEventType.INVITE2) {
			reinviteDeadbeats();
		}
		else if (event.mEventType == EnumEventType.RSVP1) {
			respondToRSVP();
		}
		else if (event.mEventType == EnumEventType.RSVP2) {
			respondToRSVP();
		}
		else if (event.mEventType == EnumEventType.PARTY) {
			if (event instanceof EventParty){
				if(((EventParty)event).mAttendees.isEmpty()){
					print("OMG THIS PARTY SUCKS and is cancelled");
					synchronized(mEvents){
						mEvents.remove(event);
					}
					return;
				}
				else{
					goParty((EventParty)event);
					mCurrentParty = (EventParty)event;
				}
			}
		}
		else if (event.mEventType == EnumEventType.PLANPARTY) {
			planParty(Time.GetTime());
		}

		//Inspection
		else if (event.mEventType == EnumEventType.INSPECTION) {
			inspect();
		}

		//Market
		else if (event.mEventType == EnumEventType.GO_TO_MARKET) {
			goToMarket();
		}

		mEvents.remove(event);
	}

/*************************************************************************/

	public void postCommute() {
		if(mCommutingTo != null) {
			switch(mCommutingTo) {
				case RESTAURANT:
					synchronized(ContactList.sOpenBuildings) {
						for (Role iRole : mRoles.keySet()){
							if (iRole instanceof RestaurantCustomerRole){
								((RestaurantCustomerRole) iRole).setPerson(this);

								if(((RestaurantCustomerRole)iRole).subRole instanceof AndreCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R0")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof CwagonerCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R1")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof JerrywebCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R2")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof MaggiyanCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R3")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof DavidCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R4")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof SmilehamCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R5")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof TranacCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R6")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else if(((RestaurantCustomerRole)iRole).subRole instanceof RexCustomerRole) {
									if(!ContactList.sOpenBuildings.get("R7")) {
										msgRoleFinished();
										assignNextEvent();
									}
								}
							}
						}
					}
					break;
				case BANK:
					synchronized(ContactList.sOpenBuildings) {
						for (Role iRole : mRoles.keySet()){
							if (iRole instanceof BankCustomerRole){
								BankCustomerRole bankCustomerRole = (BankCustomerRole)iRole;
								ContactList.sBankList.get(bankCustomerRole.getBankID()).addPerson(bankCustomerRole);

								//plan robbery
								if(mName.contains("robber")){
									print("Robbery action added to bank options");
									bankCustomerRole.mActions.add(new BankAction(EnumAction.Robbery, 100));
								}

								//deposit check
								int deposit = 50;
								bankCustomerRole.mActions.add(new BankAction(EnumAction.Deposit, deposit));

								//pay back loan if needed
								if(mLoan > 0){
									double payment = Math.max(mCash, mLoan);
									mCash -= payment;
									bankCustomerRole.mActions.add(new BankAction(EnumAction.Payment, payment));
								}

								if(mSSN % 2 == 0) {
									if(!ContactList.sOpenBuildings.get("B1")) {
										msgRoleFinished();
										assignNextEvent();
									}
								} else {
									if(!ContactList.sOpenBuildings.get("B2")) {
										msgRoleFinished();
										assignNextEvent();
									}
								}
							}
						}
					}
					break;
				case HOUSE:
					HousingBase housingRole = getHousingRole();
					if (!((Role) housingRole).hasPerson()) {
						((Role) housingRole).setPerson(this);
					}
					mRoles.put((Role) housingRole, true);
					((Role) housingRole).setActive();

					// If inspector, disable.
					for (Role iRole : mRoles.keySet()){
						if (iRole instanceof InspectorRole){
							mRoles.put((InspectorRole)iRole, false);
						}
					}
					break;
				case JOB:
					mAtJob = true; //set to false in msgTimeShift
					Role jobRole = getJobRole();
					if(!jobRole.hasPerson()) {
						jobRole.setPerson(this);
					}
					mRoles.put(jobRole, true); //set role to active
					jobRole.setActive();
					break;
				case MARKET:
					if(mSSN % 2 == 0) {
						if(!ContactList.sOpenBuildings.get("M1")) {
							msgRoleFinished();
							assignNextEvent();
						}
					} else {
						if(!ContactList.sOpenBuildings.get("M2")) {
							msgRoleFinished();
							assignNextEvent();
						}
					}
					break;
				case PARTY:
					PartyRole partyPerson = null;
					for (Role iRole : mRoles.keySet()){
						if (iRole instanceof PartyRole){
							partyPerson = (PartyRole)iRole;
						}
					}
					mRoles.put(partyPerson, false);

					print("going to house #" + mCurrentParty.mHost
							.getHousingRole().getHouse().mHouseNum);

					((HousingBaseRole) getHousingRole()).gui.setPresent(true);
					SimCityGui.getInstance().cityview.mCityHousingList.get(mCurrentParty.mHost
							.getHousingRole().getHouse().mHouseNum).mPanel
							.addGui((Gui) ((HousingBaseRole) getHousingRole()).gui);
					((HousingBaseRole) getHousingRole()).gui.DoParty();
					mCurrentParty = null;
					break;
//				case INSPECT:
//					msgRoleFinished();
//					msgAddEvent(new Event(EnumEventType.INSPECTION, -1));
//					mCommuterRole.mState = PersonState.walking;
//					stateChanged();
//					break;
				default:
					break;
			}
			mCommutingTo = null;
			mCommuterRole.mActive = false;

			stateChanged();
		}
	}

/*************************************************************************/

	public void requestHouse() {
		print("Requesting House");
		if (getHousingRole().getHouse() == null) {
			((HousingRenterRole) getHousingRole()).msgRequestHousing();
		}
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				mPersonGui.setPresent(true);
				mPersonGui.DoGoToDestination(getHousingRole().getLocation());
				acquireSemaphore(semAnimationDone);
				mPersonGui.setPresent(false);
			}
		}, 1000);
	}

	public void getCar(){
		//add desired item
		mItemsDesired.put(EnumItemType.CAR, 1); //want 1 car
		//PAEA for role will message market cashier to start transaction
		mHasCar = false;

		Location location;
		if(mSSN%2 == 0) {
			location = ContactList.getDoorLocation(ContactList.cMARKET1_LOCATION);
		} else {
			location = ContactList.getDoorLocation(ContactList.cMARKET2_LOCATION);
		}

		//activate marketcustomer role
		for (Role iRole : mRoles.keySet()){
			if (iRole instanceof MarketCustomer){
				mRoles.put(iRole, true); //set active
				iRole.setPerson(this);
			}
		}

		mCommuterRole.mActive = true;
		mCommuterRole.setLocation(location);
		mCommutingTo = EnumCommuteTo.MARKET;
		mCommuterRole.mState = PersonState.walking;
	}

	public void inspect() {
		print("I AM INSPECTING");

//		inspectCounter++;
//
//		if(inspectCounter < ContactList.sOpenPlaces.size()) {
//			InspectorRole inspector = null;
//			for (Role iRole : mRoles.keySet()){
//				if (iRole instanceof InspectorRole){
//					inspector = (InspectorRole)iRole;
//				}
//			}
//			if(inspector == null)
//				inspector = new InspectorRole(this);
//
//			mRoles.put(inspector, true);
//			AlertLog.getInstance().logError(AlertTag.PERSON, getName(), "INSPECTCOUNTER: " + inspectCounter);
//			mCommuterRole.mActive = true;
//			synchronized(ContactList.sOpenPlaces) {
//				if(inspectCounter != 0) {
//					Location deleteMe = (Location)((ContactList.sOpenPlaces.keySet().toArray())[inspectCounter - 1]);
//					Inspection.sInspectionImages.get(deleteMe).disable();
//				}
//
//				Location temp = (Location)((ContactList.sOpenPlaces.keySet().toArray())[inspectCounter]);
//				mCommuterRole.setLocation(temp);
//				Inspection.sInspectionImages.get(temp).enable();
//			}
//			mCommutingTo = EnumCommuteTo.INSPECT;
//			mCommuterRole.mState = PersonState.walking;
//		} else {
//			if(inspectCounter == ContactList.sOpenPlaces.size()) {
//				synchronized(ContactList.sOpenPlaces) {
//					Location deleteMe = (Location)((ContactList.sOpenPlaces.keySet().toArray())[inspectCounter - 1]);
//					Inspection.sInspectionImages.get(deleteMe).disable();
//				}
//			}
//
//			getHousingRole().msgTimeToMaintain();
//			mCommuterRole.mActive = true;
//			mCommuterRole.setLocation(ContactList.cHOUSE_LOCATIONS.get(getHousingRole().getHouse().mHouseNum));
//			mCommutingTo = EnumCommuteTo.HOUSE;
//			mCommuterRole.mState = PersonState.walking;
//		}

		// OLD

		mPersonGui.setPresent(true);

		Location[] myDestinations = null;
		Boolean[] isOpen = null;
		synchronized(ContactList.sOpenPlaces) {
			if(mSSN % 3 == 0) {
				myDestinations = ContactList.sOpenPlaces.keySet().toArray(new Location[0]);
				isOpen = ContactList.sOpenPlaces.values().toArray(new Boolean[0]);
			} else if(mSSN % 3 == 1) {
				Location[] temp = ContactList.sOpenPlaces.keySet().toArray(new Location[0]);
				Boolean[] tempBool = ContactList.sOpenPlaces.values().toArray(new Boolean[0]);
				myDestinations = new Location[ContactList.sOpenPlaces.size()];
				isOpen = new Boolean[ContactList.sOpenPlaces.size()];
				for(int i = ContactList.sOpenPlaces.size() - 1; i >= 0; i--) {
					myDestinations[i] = temp[i];
					isOpen[i] = tempBool[i];
				}
			} else if(mSSN % 3 == 2) {
				Location[] temp = ContactList.sOpenPlaces.keySet().toArray(new Location[0]);
				Boolean[] tempBool = ContactList.sOpenPlaces.values().toArray(new Boolean[0]);
				myDestinations = new Location[ContactList.sOpenPlaces.size()];
				isOpen = new Boolean[ContactList.sOpenPlaces.size()];
				int j = ContactList.sOpenPlaces.size() - 1;
				for(int i = ContactList.sOpenPlaces.size() / 2; i < ContactList.sOpenPlaces.size(); i++) {
					myDestinations[j] = temp[i];
					isOpen[j] = tempBool[i];
					j--;
				}
				j = 0;
				for(int i = ContactList.sOpenPlaces.size() / 2; i >= 0; i--) {
					myDestinations[j] = temp[i];
					isOpen[j] = tempBool[i];
					j++;
				}
			}
		}
		for(int iLocation = 0; iLocation < myDestinations.length; iLocation++){
			if(myDestinations[iLocation] != null) {
				if(isOpen[iLocation]) {
					Inspection.sInspectionImages.get(myDestinations[iLocation]).enable();
					mPersonGui.DoGoToDestination(myDestinations[iLocation]);
					acquireSemaphore(semAnimationDone);
					Inspection.sInspectionImages.get(myDestinations[iLocation]).disable();
					print("Visited "+myDestinations[iLocation].toString());
					mPersonGui.setPresent(true);
				}
			}
		}

//		synchronized(ContactList.sOpenPlaces){
//			for(Location iLocation : ContactList.sOpenPlaces.keySet()){
//				if(ContactList.sOpenPlaces.get(iLocation)){
//					Inspection.sInspectionImages.get(iLocation).enable();
//					mPersonGui.DoGoToDestination(iLocation);
//					acquireSemaphore(semAnimationDone);
//					Inspection.sInspectionImages.get(iLocation).disable();
//					print("Visited "+iLocation.toString());
//					mPersonGui.setPresent(true);
//				}
//			}
//		}
		getHousingRole().msgTimeToMaintain();
		mPersonGui.DoGoToDestination(ContactList.cHOUSE_LOCATIONS.get(getHousingRole().getHouse().mHouseNum));
		acquireSemaphore(semAnimationDone);
		mPersonGui.setPresent(false);
	}

	public void goToJob() {
		//print("goToJob");
		Role jobRole = getJobRole();
		if(jobRole == null){
			return;
		}
		mCommuterRole.mActive = true;
		mCommuterRole.setLocation(getJobLocation());
		mCommutingTo = EnumCommuteTo.JOB;
		mCommuterRole.mState = PersonState.walking;
	}

	public void eatFood() {
		if (isCheap() && getHousingRole().getHouse() != null){
			//DAVID I'm trying this out to see what happens...
			print("Going to market to buy food to eat at home");
			goToMarket();
			print("Going to eat at home");
			getHousingRole().msgEatAtHome();
			mCommuterRole.mActive = true;
			mCommuterRole.setLocation(getHousingRole().getLocation());
			mCommutingTo = EnumCommuteTo.HOUSE;
			mCommuterRole.mState = PersonState.walking;
		}else{
			print("Going to restaurant");

			//set random restaurant
			int restaurantChoice;
			Random rand = new Random();
			if (SimCityGui.TESTING) {
				restaurantChoice = SimCityGui.TESTNUM; //override if testing
			} else if(firstRun) {
				restaurantChoice = mSSN % 8;
				firstRun = false;
			} else {
				restaurantChoice = rand.nextInt(8);
			}

			RestaurantCustomerRole restCustRole = null;
			for (Role iRole : mRoles.keySet()){
				if (iRole instanceof RestaurantCustomerRole){
					restCustRole = (RestaurantCustomerRole)iRole;
				}
			}
			restCustRole.setRestaurant(restaurantChoice);

			mRoles.put(restCustRole, true);

			mCommuterRole.mActive = true;
			mCommuterRole.setLocation(ContactList.cRESTAURANT_LOCATIONS.get(restaurantChoice));
			mCommutingTo = EnumCommuteTo.RESTAURANT;
			mCommuterRole.mState = PersonState.walking;
			stateChanged();
		}
	}

	private void goToMarket() {

		switch(mSSN % 4) {
			case 0:
				mItemsDesired.put(EnumItemType.PIZZA, sBaseWanted);
				break;
			case 1:
				mItemsDesired.put(EnumItemType.STEAK, sBaseWanted);
				break;
			case 2:
				mItemsDesired.put(EnumItemType.CHICKEN, sBaseWanted);
				break;
			case 3:
				mItemsDesired.put(EnumItemType.SALAD, sBaseWanted);
				break;
		}

		//activate marketcustomer role
		for (Role iRole : mRoles.keySet()){
			if (iRole instanceof MarketCustomer){
				mRoles.put(iRole, true); //set active
				iRole.setPerson(this);
			}
		}

		Location location;
		if(mSSN%2 == 0) {
			location = ContactList.getDoorLocation(ContactList.cMARKET1_LOCATION);
		} else {
			location = ContactList.getDoorLocation(ContactList.cMARKET2_LOCATION);
		}

		mCommuterRole.mActive = true;
		mCommuterRole.setLocation(location);
		mCommutingTo = EnumCommuteTo.MARKET;
		mCommuterRole.mState = PersonState.walking;
	}

	private void depositCheck() {
		BankCustomerRole bankCustomerRole = null;
		for (Role iRole : mRoles.keySet()){
			if (iRole instanceof BankCustomerRole){
				bankCustomerRole = (BankCustomerRole)iRole;
			}
		}

		bankCustomerRole.setPerson(this);
		mRoles.put(bankCustomerRole, true);

		//GO TO BANK AND DO STUFF
		mCommuterRole.mActive = true;
		mCommuterRole.setLocation(bankCustomerRole.getBankID() == 0 ? ContactList.cBANK1_LOCATION:ContactList.cBANK2_LOCATION);
		mCommutingTo = EnumCommuteTo.BANK;
		mCommuterRole.mState = PersonState.walking;
	}

	private void planParty(int time){
		print("Planning a party");
		mEvents.add(new Event(EnumEventType.INVITE1, time));
		if(!mName.equals("partyPerson"))
			mEvents.add(new Event(EnumEventType.INVITE2, time+2));
		Location partyLocation = getHousingRole().getLocation();
		mEvents.add(new EventParty(EnumEventType.PARTY, time+4, partyLocation, this, mFriends));
		//mEvents.add(new EventParty(EnumEventType.PARTY, time+4, ((HousingBaseRole)getHousingRole()).getLocation(), this, mFriends));
	}

	private void goParty(EventParty event) {
		print("Going to party");

//		mPersonGui.DoGoToDestination(event.mLocation);
//		acquireSemaphore(semAnimationDone);
//		mPersonGui.setPresent(false);
//		((HousingBaseRole) getHousingRole()).gui.setPresent(true);
//		SimCityGui.getInstance().cityview.mCityHousingList.get(event.mHost
//				.getHousingRole().getHouse().mHouseNum).mPanel
//				.addGui((Gui) ((HousingBaseRole) getHousingRole()).gui);
//		((HousingBaseRole) getHousingRole()).gui.DoParty();

		PartyRole partyPerson = null;
		for (Role iRole : mRoles.keySet()){
			if (iRole instanceof PartyRole){
				partyPerson = (PartyRole)iRole;
			}
		}
		if(partyPerson == null)
			partyPerson = new PartyRole(this);

		mRoles.put(partyPerson, true);

		mCommuterRole.mActive = true;
		mCommuterRole.setLocation(event.mLocation);
		mCommutingTo = EnumCommuteTo.PARTY;
		mCommuterRole.mState = PersonState.walking;

		mRoleFinished = false;
	}

	private void inviteToParty() {
		if(mFriends.isEmpty()){
			for (Person iPerson : ContactList.sPersonList){
				mFriends.add(iPerson);
			}
			print("There are "+ContactList.sPersonList.size()+" people in the city");
			print("Created "+mFriends.size()+" friends for party host");
		}
		print("First RSVP is sent out");
		//party is in 3 days
		//send RSVP1 and event invite
		Location partyLocation = getHousingRole().getLocation();//new Location(100, 0);
		Event party = new EventParty(EnumEventType.PARTY, Time.GetTime()+4, partyLocation, this, mFriends);

		//Event party = new EventParty(EnumEventType.PARTY, Time.GetTime()+4, ((HousingBaseRole)getHousingRole()).getLocation(), this, mFriends);
		Event rsvp  = new EventParty(EnumEventType.RSVP1, -1, this); //respond immediately
		if(mName.equals("partyPersonFlake")){
			for (Person iFriend : mFriends){
				iFriend.msgAddEvent(rsvp);
				iFriend.msgAddEvent(party);
			}
		}
		else{ //partyPerson or partyPersonNO
			for (Person iFriend : mFriends){
				if(iFriend.getTimeShift()==mTimeShift){
					iFriend.msgAddEvent(rsvp);
					iFriend.msgAddEvent(party);
				}
			}
		}
	}

	private void reinviteDeadbeats() {
		print("Second RSVP is sent out");
		EventParty party = null;
		for (Event iEvent : mEvents){
			if (iEvent instanceof EventParty){
				if (((EventParty) iEvent).mHost == this){
					party = (EventParty) iEvent;
				}
			}
		}
		synchronized(party.mAttendees){
			for (Person iPerson : party.mAttendees.keySet()){
				if (party.mAttendees.get(iPerson) == false){ //haven't responded yet
					Event rsvp = new EventParty(EnumEventType.RSVP2, -1, this);
					iPerson.msgAddEvent(rsvp);
				}
			}
		}
	}

	private void respondToRSVP(){
		synchronized(mEvents){
		for (Event iEvent : mEvents){
			if (iEvent instanceof EventParty){
				if(((EventParty) iEvent).mHost.getName().equals("partyPersonNO")){
					synchronized(((EventParty)iEvent).mAttendees){
						((EventParty) iEvent).mAttendees.remove(this);
					}
					print("Responding to RSVP: NO"); mPersonGui.disable();
				}
				else if (((EventParty) iEvent).mHost.getTimeShift() == mTimeShift){
					synchronized(((EventParty)iEvent).mAttendees){
						((EventParty) iEvent).mAttendees.put(this, true);
					}
					print("Responding to RSVP: YES");
				}else{
					synchronized(((EventParty)iEvent).mAttendees){
						((EventParty) iEvent).mAttendees.remove(this);
					}
					print("Responding to RSVP: NO"); mPersonGui.disable();
				}
			}
		}
		}
	}

	public void invokeRent() {
		print("invokeRent");
		((HousingLandlordRole) getHousingRole()).mActive = true;
		((HousingLandlordRole) getHousingRole()).msgTimeToCheckRent(); //this role is always active
	}

	public void invokeMaintenance() {
		if (getHousingRole().getHouse() != null) {
			mCommuterRole.mActive = true;
			mCommuterRole.setLocation(getHousingRole().getLocation());
			mCommutingTo = EnumCommuteTo.HOUSE;
			mCommuterRole.mState = PersonState.walking;
			((HousingBaseRole) getHousingRole()).msgTimeToMaintain();
		}
	}

	/*private List<Person> getBestFriends(){
		List<Person> bestFriends = new ArrayList<Person>();
		for (Person iPerson : mFriends){
			if (iPerson.getTimeShift() == mTimeShift) bestFriends.add(iPerson);
		}
		return bestFriends;
	}*/

	private boolean isCheap(){
		return (mLoan == 0 && mCash < 30);
	}

	public void acquireSemaphore(Semaphore semaphore){
		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private Role getJobRole(){
		for (Role iRole : mRoles.keySet()){
			//Bank roles
			if (	//Bank jobs
					iRole instanceof BankGuardRole ||
					iRole instanceof BankMasterTellerRole ||
					iRole instanceof BankTellerRole ||
					//Market jobs
					iRole instanceof MarketCashierRole ||
					iRole instanceof MarketDeliveryTruckRole ||
					iRole instanceof MarketWorkerRole ||
					//Restaurant job
					iRole instanceof RestaurantCashierRole ||
					iRole instanceof RestaurantCookRole ||
					iRole instanceof RestaurantHostRole ||
					iRole instanceof RestaurantWaiterRole){
				return iRole;
			}
		}
		//print("job role null!");
		return null;
	}

	private Location getJobLocation(){
		if (getJobRole() == null)
			return null;
		return getJobRole().getLocation();
	}

	// ----------------------------------------------------------ACCESSORS----------------------------------------------------------

	public void addRole(Role role, boolean active) {
		mRoles.put(role, active);
		print(this.getName());
		if (role.getPerson() == null) {
			print("person is null in addrole");
		}
	}

	public void removeRole(Role r) {
		mRoles.put(r, false);
//		mRoles.remove(r);
	}

	public double getCash() {
		return mCash;
	}

	public void setCash(double cash) {
		mCash = cash;
	}

	public void addCash(double amount) {
		mCash += amount;

	}

	public void setLoan(double loan) {
		mLoan = loan;
	}

	public void subLoan(double loan) {
		mLoan -= loan;
	}

	public double getLoan() {
		return mLoan;
	}

	public Map<EnumItemType, Integer> getItemsDesired() {
		return mItemsDesired;
	}

	public int getSSN() {
		return mSSN;
	}

	public Map<EnumItemType, Integer> getItemInventory() {
		return mItemInventory;
	}

	public String getName(){
		return mName;
	}

	public int getTimeShift(){
		return mTimeShift;
	}

	public void setName(String name) {
		mName = name;
	}
	public void setSSN(int SSN) {
		mSSN = SSN;
	}

	@Override
	public void setItemsDesired(Map<EnumItemType, Integer> map) {
		mItemsDesired = map;
	}

	@Override
	public Map<Role, Boolean> getRoles() {
		return mRoles;
	}

	@Override
	public HousingBase getHousingRole() {
		for (Role iRole : mRoles.keySet()){
			if(iRole instanceof HousingBase){
				return (HousingBase) iRole;
			}
		}
		return null;
	}

	@Override
	public CityPerson getPersonGui() {
		return (CityPerson)mPersonGui;
	}

	@Override
	public void setGuiPresent() {
		mPersonGui.setPresent(true);
//		mPersonGui.setX(250);
//		mPersonGui.setY(300);
	}

	public CityPerson getGui(){
		return mPersonGui;
	}

	@Override
	public void setJobFalse() {
		mAtJob = false;
	}

	public boolean hasCar() {
		return mHasCar;
	}

	public void setHasCar(boolean c) {
		mHasCar = c;
	}

	public void Do(String msg) {
		super.Do(msg, AlertTag.PERSON);
	}

	public void print(String msg) {
		super.print(msg, AlertTag.PERSON);
	}

	public void print(String msg, Throwable e) {
		super.print(msg, AlertTag.PERSON, e);
	}

	public EnumJobType getJobType() {
		return mJobType;
	}

	public List<Event> getEvents() {
		return mEvents;
	}

	public boolean getAtJob(){
		return mAtJob;
	}

	public List<Person> getFriendList(){
		return mFriends;
	}

	public void assignNextEvent(){
		Random rand = new Random();
		mEvents.add(ContactList.sEventList.get(rand.nextInt(ContactList.sEventList.size())));
		mCommuterRole.mState = PersonState.walking;
		stateChanged();
	}

	@Override
	public void setJobType(EnumJobType type) {
		mJobType = type;
	}
}


text:
package com.esri.vehiclecommander.view;

import com.esri.map.Layer;

/**
 * Fired for certain basemap events, such as becoming visible.
 */
public interface BasemapListener {

    public void basemapBecameVisible(Layer layer);

}

redpajama_set_name: RedPajamaGithub


text:
class Municipio < ActiveRecord::Base
	has_many :obras
	has_and_belongs_to_many  :providers
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:/bot/slave/nightly-dist-rustc-win-64/build/src/libstd\collections/mod.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>mod.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394

// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Collection types.
//!
//! Rust's standard collection library provides efficient implementations of the most common
//! general purpose programming data structures. By using the standard implementations,
//! it should be possible for two libraries to communicate without significant data conversion.
//!
//! To get this out of the way: you should probably just use `Vec` or `HashMap`. These two
//! collections cover most use cases for generic data storage and processing. They are
//! exceptionally good at doing what they do. All the other collections in the standard
//! library have specific use cases where they are the optimal choice, but these cases are
//! borderline *niche* in comparison. Even when `Vec` and `HashMap` are technically suboptimal,
//! they're probably a good enough choice to get started.
//!
//! Rust's collections can be grouped into four major categories:
//!
//! * Sequences: `Vec`, `VecDeque`, `LinkedList`, `BitVec`
//! * Maps: `HashMap`, `BTreeMap`, `VecMap`
//! * Sets: `HashSet`, `BTreeSet`, `BitSet`
//! * Misc: `BinaryHeap`
//!
//! # When Should You Use Which Collection?
//!
//! These are fairly high-level and quick break-downs of when each collection should be
//! considered. Detailed discussions of strengths and weaknesses of individual collections
//! can be found on their own documentation pages.
//!
//! ### Use a `Vec` when:
//! * You want to collect items up to be processed or sent elsewhere later, and don't care about
//! any properties of the actual values being stored.
//! * You want a sequence of elements in a particular order, and will only be appending to
//! (or near) the end.
//! * You want a stack.
//! * You want a resizable array.
//! * You want a heap-allocated array.
//!
//! ### Use a `VecDeque` when:
//! * You want a `Vec` that supports efficient insertion at both ends of the sequence.
//! * You want a queue.
//! * You want a double-ended queue (deque).
//!
//! ### Use a `LinkedList` when:
//! * You want a `Vec` or `VecDeque` of unknown size, and can't tolerate amortization.
//! * You want to efficiently split and append lists.
//! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list.
//!
//! ### Use a `HashMap` when:
//! * You want to associate arbitrary keys with an arbitrary value.
//! * You want a cache.
//! * You want a map, with no extra functionality.
//!
//! ### Use a `BTreeMap` when:
//! * You're interested in what the smallest or largest key-value pair is.
//! * You want to find the largest or smallest key that is smaller or larger than something
//! * You want to be able to get all of the entries in order on-demand.
//! * You want a sorted map.
//!
//! ### Use a `VecMap` when:
//! * You want a `HashMap` but with known to be small `usize` keys.
//! * You want a `BTreeMap`, but with known to be small `usize` keys.
//!
//! ### Use the `Set` variant of any of these `Map`s when:
//! * You just want to remember which keys you've seen.
//! * There is no meaningful value to associate with your keys.
//! * You just want a set.
//!
//! ### Use a `BitVec` when:
//! * You want to store an unbounded number of booleans in a small space.
//! * You want a bit vector.
//!
//! ### Use a `BitSet` when:
//! * You want a `BitVec`, but want `Set` properties
//!
//! ### Use a `BinaryHeap` when:
//! * You want to store a bunch of elements, but only ever want to process the "biggest"
//! or "most important" one at any given time.
//! * You want a priority queue.
//!
//! # Performance
//!
//! Choosing the right collection for the job requires an understanding of what each collection
//! is good at. Here we briefly summarize the performance of different collections for certain
//! important operations. For further details, see each type's documentation, and note that the
//! names of actual methods may differ from the tables below on certain collections.
//!
//! Throughout the documentation, we will follow a few conventions. For all operations,
//! the collection's size is denoted by n. If another collection is involved in the operation, it
//! contains m elements. Operations which have an *amortized* cost are suffixed with a `*`.
//! Operations with an *expected* cost are suffixed with a `~`.
//!
//! All amortized costs are for the potential need to resize when capacity is exhausted.
//! If a resize occurs it will take O(n) time. Our collections never automatically shrink,
//! so removal operations aren't amortized. Over a sufficiently large series of
//! operations, the average cost per operation will deterministically equal the given cost.
//!
//! Only HashMap has expected costs, due to the probabilistic nature of hashing. It is
//! theoretically possible, though very unlikely, for HashMap to experience worse performance.
//!
//! ## Sequences
//!
//! |              | get(i)         | insert(i)       | remove(i)      | append | split_off(i)   |
//! |--------------|----------------|-----------------|----------------|--------|----------------|
//! | Vec          | O(1)           | O(n-i)*         | O(n-i)         | O(m)*  | O(n-i)         |
//! | VecDeque     | O(1)           | O(min(i, n-i))* | O(min(i, n-i)) | O(m)*  | O(min(i, n-i)) |
//! | LinkedList   | O(min(i, n-i)) | O(min(i, n-i))  | O(min(i, n-i)) | O(1)   | O(min(i, n-i)) |
//! | BitVec       | O(1)           | O(n-i)*         | O(n-i)         | O(m)*  | O(n-i)         |
//!
//! Note that where ties occur, Vec is generally going to be faster than VecDeque, and VecDeque
//! is generally going to be faster than LinkedList. BitVec is not a general purpose collection, and
//! therefore cannot reasonably be compared.
//!
//! ## Maps
//!
//! For Sets, all operations have the cost of the equivalent Map operation. For BitSet,
//! refer to VecMap.
//!
//! |          | get       | insert   | remove   | predecessor |
//! |----------|-----------|----------|----------|-------------|
//! | HashMap  | O(1)~     | O(1)~*   | O(1)~    | N/A         |
//! | BTreeMap | O(log n)  | O(log n) | O(log n) | O(log n)    |
//! | VecMap   | O(1)      | O(1)?    | O(1)     | O(n)        |
//!
//! Note that VecMap is *incredibly* inefficient in terms of space. The O(1) insertion time
//! assumes space for the element is already allocated. Otherwise, a large key may require a
//! massive reallocation, with no direct relation to the number of elements in the collection.
//! VecMap should only be seriously considered for small keys.
//!
//! Note also that BTreeMap's precise preformance depends on the value of B.
//!
//! # Correct and Efficient Usage of Collections
//!
//! Of course, knowing which collection is the right one for the job doesn't instantly
//! permit you to use it correctly. Here are some quick tips for efficient and correct
//! usage of the standard collections in general. If you're interested in how to use a
//! specific collection in particular, consult its documentation for detailed discussion
//! and code examples.
//!
//! ## Capacity Management
//!
//! Many collections provide several constructors and methods that refer to "capacity".
//! These collections are generally built on top of an array. Optimally, this array would be
//! exactly the right size to fit only the elements stored in the collection, but for the
//! collection to do this would be very inefficient. If the backing array was exactly the
//! right size at all times, then every time an element is inserted, the collection would
//! have to grow the array to fit it. Due to the way memory is allocated and managed on most
//! computers, this would almost surely require allocating an entirely new array and
//! copying every single element from the old one into the new one. Hopefully you can
//! see that this wouldn't be very efficient to do on every operation.
//!
//! Most collections therefore use an *amortized* allocation strategy. They generally let
//! themselves have a fair amount of unoccupied space so that they only have to grow
//! on occasion. When they do grow, they allocate a substantially larger array to move
//! the elements into so that it will take a while for another grow to be required. While
//! this strategy is great in general, it would be even better if the collection *never*
//! had to resize its backing array. Unfortunately, the collection itself doesn't have
//! enough information to do this itself. Therefore, it is up to us programmers to give it
//! hints.
//!
//! Any `with_capacity` constructor will instruct the collection to allocate enough space
//! for the specified number of elements. Ideally this will be for exactly that many
//! elements, but some implementation details may prevent this. `Vec` and `VecDeque` can
//! be relied on to allocate exactly the requested amount, though. Use `with_capacity`
//! when you know exactly how many elements will be inserted, or at least have a
//! reasonable upper-bound on that number.
//!
//! When anticipating a large influx of elements, the `reserve` family of methods can
//! be used to hint to the collection how much room it should make for the coming items.
//! As with `with_capacity`, the precise behavior of these methods will be specific to
//! the collection of interest.
//!
//! For optimal performance, collections will generally avoid shrinking themselves.
//! If you believe that a collection will not soon contain any more elements, or
//! just really need the memory, the `shrink_to_fit` method prompts the collection
//! to shrink the backing array to the minimum size capable of holding its elements.
//!
//! Finally, if ever you're interested in what the actual capacity of the collection is,
//! most collections provide a `capacity` method to query this information on demand.
//! This can be useful for debugging purposes, or for use with the `reserve` methods.
//!
//! ## Iterators
//!
//! Iterators are a powerful and robust mechanism used throughout Rust's standard
//! libraries. Iterators provide a sequence of values in a generic, safe, efficient
//! and convenient way. The contents of an iterator are usually *lazily* evaluated,
//! so that only the values that are actually needed are ever actually produced, and
//! no allocation need be done to temporarily store them. Iterators are primarily
//! consumed using a `for` loop, although many functions also take iterators where
//! a collection or sequence of values is desired.
//!
//! All of the standard collections provide several iterators for performing bulk
//! manipulation of their contents. The three primary iterators almost every collection
//! should provide are `iter`, `iter_mut`, and `into_iter`. Some of these are not
//! provided on collections where it would be unsound or unreasonable to provide them.
//!
//! `iter` provides an iterator of immutable references to all the contents of a
//! collection in the most "natural" order. For sequence collections like `Vec`, this
//! means the items will be yielded in increasing order of index starting at 0. For ordered
//! collections like `BTreeMap`, this means that the items will be yielded in sorted order.
//! For unordered collections like `HashMap`, the items will be yielded in whatever order
//! the internal representation made most convenient. This is great for reading through
//! all the contents of the collection.
//!
//! ```</span>
<span class='doccomment'>//! let vec = vec![1, 2, 3, 4];</span>
<span class='doccomment'>//! for x in vec.iter() {</span>
<span class='doccomment'>//!    println!("vec contained {}", x);</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```
//!
//! `iter_mut` provides an iterator of *mutable* references in the same order as `iter`.
//! This is great for mutating all the contents of the collection.
//!
//! ```</span>
<span class='doccomment'>//! let mut vec = vec![1, 2, 3, 4];</span>
<span class='doccomment'>//! for x in vec.iter_mut() {</span>
<span class='doccomment'>//!    *x += 1;</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```
//!
//! `into_iter` transforms the actual collection into an iterator over its contents
//! by-value. This is great when the collection itself is no longer needed, and the
//! values are needed elsewhere. Using `extend` with `into_iter` is the main way that
//! contents of one collection are moved into another. Calling `collect` on an iterator
//! itself is also a great way to convert one collection into another. Both of these
//! methods should internally use the capacity management tools discussed in the
//! previous section to do this as efficiently as possible.
//!
//! ```</span>
<span class='doccomment'>//! let mut vec1 = vec![1, 2, 3, 4];</span>
<span class='doccomment'>//! let vec2 = vec![10, 20, 30, 40];</span>
<span class='doccomment'>//! vec1.extend(vec2.into_iter());</span>
<span class='doccomment'>//! ```
//!
//! ```</span>
<span class='doccomment'>//! use std::collections::VecDeque;</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! let vec = vec![1, 2, 3, 4];</span>
<span class='doccomment'>//! let buf: VecDeque<_> = vec.into_iter().collect();</span>
<span class='doccomment'>//! ```
//!
//! Iterators also provide a series of *adapter* methods for performing common tasks to
//! sequences. Among the adapters are functional favorites like `map`, `fold`, `skip`,
//! and `take`. Of particular interest to collections is the `rev` adapter, that
//! reverses any iterator that supports this operation. Most collections provide reversible
//! iterators as the way to iterate over them in reverse order.
//!
//! ```</span>
<span class='doccomment'>//! let vec = vec![1, 2, 3, 4];</span>
<span class='doccomment'>//! for x in vec.iter().rev() {</span>
<span class='doccomment'>//!    println!("vec contained {}", x);</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```
//!
//! Several other collection methods also return iterators to yield a sequence of results
//! but avoid allocating an entire collection to store the result in. This provides maximum
//! flexibility as `collect` or `extend` can be called to "pipe" the sequence into any
//! collection if desired. Otherwise, the sequence can be looped over with a `for` loop. The
//! iterator can also be discarded after partial use, preventing the computation of the unused
//! items.
//!
//! ## Entries
//!
//! The `entry` API is intended to provide an efficient mechanism for manipulating
//! the contents of a map conditionally on the presence of a key or not. The primary
//! motivating use case for this is to provide efficient accumulator maps. For instance,
//! if one wishes to maintain a count of the number of times each key has been seen,
//! they will have to perform some conditional logic on whether this is the first time
//! the key has been seen or not. Normally, this would require a `find` followed by an
//! `insert`, effectively duplicating the search effort on each insertion.
//!
//! When a user calls `map.entry(&key)`, the map will search for the key and then yield
//! a variant of the `Entry` enum.
//!
//! If a `Vacant(entry)` is yielded, then the key *was not* found. In this case the
//! only valid operation is to `insert` a value into the entry. When this is done,
//! the vacant entry is consumed and converted into a mutable reference to the
//! the value that was inserted. This allows for further manipulation of the value
//! beyond the lifetime of the search itself. This is useful if complex logic needs to
//! be performed on the value regardless of whether the value was just inserted.
//!
//! If an `Occupied(entry)` is yielded, then the key *was* found. In this case, the user
//! has several options: they can `get`, `insert`, or `remove` the value of the occupied
//! entry. Additionally, they can convert the occupied entry into a mutable reference
//! to its value, providing symmetry to the vacant `insert` case.
//!
//! ### Examples
//!
//! Here are the two primary ways in which `entry` is used. First, a simple example
//! where the logic performed on the values is trivial.
//!
//! #### Counting the number of times each character in a string occurs
//!
//! ```</span>
<span class='doccomment'>//! use std::collections::btree_map::{BTreeMap, Entry};</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! let mut count = BTreeMap::new();</span>
<span class='doccomment'>//! let message = "she sells sea shells by the sea shore";</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! for c in message.chars() {</span>
<span class='doccomment'>//!     match count.entry(c) {</span>
<span class='doccomment'>//!         Entry::Vacant(entry) => { entry.insert(1); },</span>
<span class='doccomment'>//!         Entry::Occupied(mut entry) => *entry.get_mut() += 1,</span>
<span class='doccomment'>//!     }</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! assert_eq!(count.get(&'s'), Some(&8));</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! println!("Number of occurrences of each character");</span>
<span class='doccomment'>//! for (char, count) in count.iter() {</span>
<span class='doccomment'>//!     println!("{}: {}", char, count);</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```
//!
//! When the logic to be performed on the value is more complex, we may simply use
//! the `entry` API to ensure that the value is initialized, and perform the logic
//! afterwards.
//!
//! #### Tracking the inebriation of customers at a bar
//!
//! ```</span>
<span class='doccomment'>//! use std::collections::btree_map::{BTreeMap, Entry};</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! // A client of the bar. They have an id and a blood alcohol level.</span>
<span class='doccomment'>//! struct Person { id: u32, blood_alcohol: f32 }</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! // All the orders made to the bar, by client id.</span>
<span class='doccomment'>//! let orders = vec![1,2,1,2,3,4,1,2,2,3,4,1,1,1];</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! // Our clients.</span>
<span class='doccomment'>//! let mut blood_alcohol = BTreeMap::new();</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! for id in orders.into_iter() {</span>
<span class='doccomment'>//!     // If this is the first time we've seen this customer, initialize them</span>
<span class='doccomment'>//!     // with no blood alcohol. Otherwise, just retrieve them.</span>
<span class='doccomment'>//!     let person = match blood_alcohol.entry(id) {</span>
<span class='doccomment'>//!         Entry::Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}),</span>
<span class='doccomment'>//!         Entry::Occupied(entry) => entry.into_mut(),</span>
<span class='doccomment'>//!     };</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//!     // Reduce their blood alcohol level. It takes time to order and drink a beer!</span>
<span class='doccomment'>//!     person.blood_alcohol *= 0.9;</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//!     // Check if they're sober enough to have another beer.</span>
<span class='doccomment'>//!     if person.blood_alcohol > 0.3 {</span>
<span class='doccomment'>//!         // Too drunk... for now.</span>
<span class='doccomment'>//!         println!("Sorry {}, I have to cut you off", person.id);</span>
<span class='doccomment'>//!     } else {</span>
<span class='doccomment'>//!         // Have another!</span>
<span class='doccomment'>//!         person.blood_alcohol += 0.1;</span>
<span class='doccomment'>//!     }</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```

#![stable(feature = "rust1", since = "1.0.0")]

pub use core_collections::Bound;
pub use core_collections::{BinaryHeap, BitVec, BitSet, BTreeMap, BTreeSet};
pub use core_collections::{LinkedList, VecDeque, VecMap};

pub use core_collections::{binary_heap, bit_vec, bit_set, btree_map, btree_set};
pub use core_collections::{linked_list, vec_deque, vec_map};

pub use self::hash_map::HashMap;
pub use self::hash_set::HashSet;

mod hash;

#[stable(feature = "rust1", since = "1.0.0")]
pub mod hash_map {
    //! A hashmap
    pub use super::hash::map::*;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod hash_set {
    //! A hashset
    pub use super::hash::set::*;
}

/// Experimental support for providing custom hash algorithms to a HashMap and
/// HashSet.
#[unstable(feature = "std_misc", reason = "module was recently added")]
pub mod hash_state {
    pub use super::hash::state::*;
}

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
(function () {
    var path = require('path'),
        fs = require('fs'),
        glob = require('glob');

    var validExit = false;

    /** Handle event handling when an exit occurs. */
    process.on('exit', function () {
        if (!validExit) {
            console.log('Install exited unexpectedly');
            exit(1)
        }
    });

    /**
     * Handles a valid exit.
     * @param code The exit code.
     */
    function exit(code) {
        validExit = true;
        process.exit(code || 0)
    }

    glob.sync('**/lcov.info', {cwd: process.cwd() + '/results/karma/coverage', root: '/', realpath: true}).forEach(function (file) {
        var result = String(fs.readFileSync(file)).replace(new RegExp('(SF:)' + process.cwd() + '(.*)', 'g'), '$1/path/to$2');
        fs.writeFileSync(file, result);
    });

    exit(0);
})();


text: A collection of simple POCs (Proof of Concept).


text:
package siren;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.ArrayList;
import java.util.List;

/**
 * Represents the common lineage of all entities.
 * @author jonfreer
 * @since 8/13/17
 */
public abstract class EntityBase {

    /**
     * Describes the nature of an entity's content based on the current representation.
     * Possible values are implementation-dependent and should be documented.
     */
    private List<String> klass;

    /**
     * Descriptive text about the entity.
     */
    private String title;

    /**
     * Constructs an instance of {@link EntityBase}.
     */
    public EntityBase(){}

    /**
     * Constructs an instance of {@link EntityBase}.
     * @param klass Describes the nature of an entity's content based on the current representation.
     *              Possible values are implementation-dependent and should be documented.
     * @param title Descriptive text about the entity.
     */
    public EntityBase(List<String> klass, String title){
        this.klass = klass;
        this.title = title;
    }

    /**
     * Retrieves the class of the entity.
     * @return The class of the entity.
     */
    @JsonProperty("class")
    public List<String> getKlass(){
        if(this.klass == null) return this.klass;
        List<String> classesCopy = new ArrayList<>();
        classesCopy.addAll(this.klass);
        return classesCopy;
    }

    /**
     * Retrieves the title of the entity.
     * @return The title of the entity.
     */
    public String getTitle(){
        return this.title;
    }

    /**
     * Determines if the instance of {@link Object} provided is
     * equal to the calling {@link EntityBase} instance.
     * @param obj The instance of {@link Object} being examined.
     * @return {@code true} if the instances are equal; {@code false} otherwise.
     */
    public boolean equals(Object obj){
        if(obj == null || this.getClass() != obj.getClass()) return false;

        EntityBase entity = (EntityBase)obj;

        boolean sameClass =
                this.klass == null && entity.klass == null ||
                this.klass != null && entity.klass != null &&
                this.klass.equals(entity.klass);

        boolean sameTitle =
                this.title == null && entity.title == null ||
                this.title != null && entity.title != null &&
                this.title.equals(entity.title);

        return sameClass && sameTitle;
    }

    /**
     * Generates hashcode represented as an integer for the calling {@link EntityBase} sub-class instance.
     * @return The hashcode for the calling {@link EntityBase} sub-class instance.
     */
    public int hashCode(){

        final int PRIME = 31;
        int hashCode = 1;

        if(this.klass != null){
            hashCode *= PRIME + this.klass.hashCode();
        }

        if(this.title != null){
            hashCode *= PRIME + this.title.hashCode();
        }

        return hashCode;
    }
}


text:
Busca Rápida

<form method="get" action="<?php echo $arquivo; ?>?subacao=localizar" name="localizar">
	<input type="hidden" name="modulo" id="modulo" value="<?php echo $modulo; ?>" />
	<input type="text"  name="palavra" class="texto1"  id="palavra" value="">
	<input type="submit" name="buscar" class="botao1" value="Buscar" style="margin-left:10px;" >
</form>


text:
module IntroexamsHelper
end


text:
:setvar DLL_PATH D:\GIT\MindFlavor\MindFlavor.RESP\MindFlavor.RESP.SQLCLR\bin\Debug\MindFlavor.RESP.SQLCLR.dll

USE [master];
GO

CREATE ASYMMETRIC KEY [MindFlavor_Key] FROM EXECUTABLE FILE = '$(DLL_PATH)'

CREATE LOGIN [MindFlavor_Login] FROM ASYMMETRIC KEY [MindFlavor_Key];

GRANT EXTERNAL ACCESS ASSEMBLY TO [MindFlavor_Login];
GO

CREATE DATABASE [MindFlavor];
GO
ALTER DATABASE [MindFlavor] SET RECOVERY SIMPLE;
GO
USE [MindFlavor];
GO
EXEC sp_changedbowner 'sa';
GO

CREATE SCHEMA [Redis];
GO

CREATE ASSEMBLY [MindFlavor.RESP.SQLCLR] FROM '$(DLL_PATH)'
WITH PERMISSION_SET=EXTERNAL_ACCESS;
GO

CREATE PROCEDURE Redis.Publish(@RedisServerAddress NVARCHAR(1024), @RedisServerPort INT, @Channel NVARCHAR(1024), @Message NVARCHAR(MAX))
AS EXTERNAL NAME [MindFlavor.RESP.SQLCLR].[MindFlavor.RESP.SQLCLR.Redis].Publish;
GO

USE [master];
GO


text:
/* eslint-disable no-console */
import React from "react"
import { renderToString } from "react-dom/server"
import { StaticRouter } from "react-router"
import Helmet from "react-helmet"
import { ApolloProvider } from "react-apollo"
import { IntlProvider } from "react-intl"

import renderPage from "./renderPage"
import { createReduxStore } from "../common/State"
import { createApolloClient } from "../common/Apollo"
import deepFetch from "../common/deepFetch"

import { ensureIntlSupport, ensureReactIntlSupport } from "../server"

/**
 * Using Apollo logic to recursively resolve all queries needed for
 * initial rendering. The convention is to use the full JSX tree,
 * traverse it and look for all occurrences of a static `fetchData() => Promise`
 * method which is being executed and waited for.
 *
 * See also:
 * https://www.npmjs.com/package/react-redux-universal-hot-example#server-side-data-fetching
 */
function renderToStringWithData(component) {
  //return deepFetch(component).then(() => {
    //var result = renderToString(component)
    //return result
  //})

  return Promise.resolve(renderToString(component))
}

// SSR is disabled so we will just return an empty html page and will
// rely on the client to populate the initial react application state.
function renderLight({ request, response, nonce, initialState, language, region, loadMessages }) {
  /* eslint-disable no-magic-numbers */
  try {
    const html = renderPage({
      // Provide the redux store state, this will be bound to the window.APP_STATE
      // so that we can rehydrate the state on the client.
      initialState,

      // Nonce which allows us to safely declare inline scripts.
      nonce,

      // Send detected language and region for HTML tag info
      language,
      region
    })

    response.status(200).send(html)
  } catch (error) {
    response.status(500).send(`Error during rendering: ${error}!: ${error.stack}`)
  }
}

async function renderFull({ request, response, nonce, Root, apolloClient, reduxStore, language, region, loadMessages }) {
  const routingContext = {}
  const locale = `${language}-${region}`
  const reduxState = reduxStore.getState()
  const ssrData = reduxState.ssr

  const [ intl, reactIntl, messages ] = await Promise.all([
    ensureIntlSupport(locale),
    ensureReactIntlSupport(language),
    loadMessages(language)
  ])

  console.log("Server: Rendering app with data...")

  let WrappedRoot = (
    <IntlProvider locale={locale} messages={messages}>
      <StaticRouter location={request.url} context={routingContext}>
        <ApolloProvider client={apolloClient} store={reduxStore}>
          <Root/>
        </ApolloProvider>
      </StaticRouter>
    </IntlProvider>
  )

  const renderedApp = await renderToStringWithData(WrappedRoot)

  // Render the app to a string.
  const html = renderPage({
    // Provide the full rendered App react element.
    renderedApp,

    // Provide the redux store state, this will be bound to the window.APP_STATE
    // so that we can rehydrate the state on the client.
    initialState: reduxState,

    // Nonce which allows us to safely declare inline scripts.
    nonce,

    // Running this gets all the helmet properties (e.g. headers/scripts/title etc)
    // that need to be included within our html. It's based on the rendered app.
    // @see https://github.com/nfl/react-helmet
    helmet: Helmet.rewind(),

    // Send detected language and region for HTML tag info
    language,
    region
  })

  // console.log("Server: Routing Context:", routingContext)
  console.log("Server: Sending Page...")

  /* eslint-disable no-magic-numbers */

  // Check if the render result contains a redirect, if so we need to set
  // the specific status and redirect header and end the response.
  if (routingContext.url) {
    response.status(302).setHeader("Location", routingContext.url)
    response.end()
    return
  }

  // If the renderedResult contains a "missed" match then we set a 404 code.
  // Our App component will handle the rendering of an Error404 view.
  // Otherwise everything is all good and we send a 200 OK status.
  response.status(routingContext.status || 200).send(html)
}

/**
 * An express middleware that is capable of doing React server side rendering.
 */
export default function createUniversalMiddleware({ Root, State, ssrData, loadMessages, batchRequests = false, trustNetwork = true })
{
  if (Root == null) {
    throw new Error("Server: Universal Middleware: Missing Root!")
  }

  if (State == null) {
    throw new Error("Server: Universal Middleware: Missing State!")
  }

  return function middleware(request, response)
  {
    if (typeof response.locals.nonce !== "string") {
      throw new TypeError(`Server: A "nonce" value has not been attached to the response`)
    }
    const nonce = response.locals.nonce

    if (!request.locale) {
      throw new Error("Cannot correctly deal with locale configuration!")
    }

    const { language, region } = request.locale
    const locale = `${language}-${region}`

    console.log(
      "Incoming URL:",
      request.originalUrl,
      process.env.DISABLE_SSR ? "[SSR: disabled]" : "[SSR: enabled]",
      `[Locale: ${language}-${region}]`
    )

    // After matching locales with configuration we send the accepted locale
    // back to the client using a simple session cookie
    response.cookie("locale", locale)

    // Pass object with all Server Side Rendering (SSR) related data to the client
    const initialState = {
      ssr: {
        ...ssrData,
        locale,
        language,
        region
      }
    }

    if (process.env.DISABLE_SSR)
    {
      renderLight({
        request,
        response,
        nonce,
        initialState,
        language,
        region,
        loadMessages
      })
    }
    else
    {
      const apolloClient = createApolloClient({
        headers: request.headers,
        initialState,
        batchRequests,
        trustNetwork
      })

      const reduxStore = createReduxStore({
        reducers: State.getReducers(),
        enhancers: State.getEnhancers(),
        middlewares: State.getMiddlewares(),
        apolloClient,
        initialState
      })

      renderFull({
        request,
        response,
        nonce,
        Root,
        apolloClient,
        reduxStore,
        language,
        region,
        loadMessages
      })
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:paddingLeft="8dp"
        android:paddingRight="8dp" >

        <TextView
            android:id="@+id/title"
            style="@style/CardTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="title" />

    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginTop="4dp"
        android:background="@color/stroke" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/selectable_background_cardbank"
        android:gravity="center_vertical"
        android:padding="8dp" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="154dp"
            android:layout_height="127dp"
            android:adjustViewBounds="true"
            android:baselineAlignBottom="true"
            android:scaleType="centerCrop"
            android:src="@drawable/url1" />

        <TextView
            android:id="@+id/description"
            style="@style/CardText"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="8dp"
            android:ellipsize="end"
            android:maxLines="7"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec viverra metus et ligula accumsan auctor. Nullam luctus neque quis nibh porttitor sagittis. Nunc dignissim quam nec quam scelerisque faucibus. Maecenas elementum ante eget felis vestibulum quis pharetra dui condimentum. In a ligula lectus, aliquet interdum diam. Fusce luctus bibendum tellus, sed iaculis mi vehicula vitae. Fusce quis ipsum in est ultricies egestas a vel orci." />
    </LinearLayout>

</LinearLayout>


text:
# Build script for docs

source ../_common/common-build.sh

DEFAULT_XML="../../cdap-common/src/main/resources/cdap-default.xml"
DEFAULT_XML_MD5_HASH="8b574d59b5390f5adce4a932f8f0d45b"

DEFAULT_TOOL="../tools/doc-cdap-default.py"
DEFAULT_RST="cdap-default-table.rst"
CHECK_INCLUDES=${TRUE}

function rewrite_references_sed() {
  local source_rst=${1}
  local target_rst=${2}
  local source_pattern=${3}
  local target_pattern=${4}
  sed -e "s|${source_pattern}|${target_pattern}|g" ${source_rst} > ${target_rst}
  echo "Copied file ${source_rst} changing '${source_pattern}' to '${target_pattern}'"
}

function download_includes() {
  local target_includes_dir=${1}

  echo_red_bold "Check guarded files for changes."
  test_an_include "${DEFAULT_XML_MD5_HASH}" "${DEFAULT_XML}"

  echo "Building rst file from cdap-default.xml..."
  python "${DEFAULT_TOOL}" -g -t "${target_includes_dir}/${DEFAULT_RST}"

  echo "Copying files, changing references..."
  local source_rst="${target_includes_dir}/../../source/_includes/installation"

  rewrite_references_sed "${source_rst}/installation.txt"          "${target_includes_dir}/ambari-installation.rst"          ".. _distribution-" ".. _ambari-"
  echo

  rewrite_references_sed "${source_rst}/configuration.txt"         "${target_includes_dir}/hadoop-configuration.rst"         ".. _distribution-" ".. _hadoop-"
  rewrite_references_sed "${source_rst}/installation.txt"          "${target_includes_dir}/hadoop-installation.rst"          ".. _distribution-" ".. _hadoop-"
  rewrite_references_sed "${source_rst}/starting-verification.txt" "${target_includes_dir}/hadoop-starting-verification.rst" ".. _distribution-" ".. _hadoop-"
  rewrite_references_sed "${source_rst}/upgrading.txt"             "${target_includes_dir}/hadoop-upgrading.rst"             ".. _distribution-" ".. _hadoop-"
  echo

  rewrite_references_sed "${source_rst}/configuration.txt"         "${target_includes_dir}/mapr-configuration.rst"         ".. _distribution-" ".. _mapr-"
  rewrite_references_sed "${source_rst}/installation.txt"          "${target_includes_dir}/mapr-installation.rst"          ".. _distribution-" ".. _mapr-"
  rewrite_references_sed "${source_rst}/starting-verification.txt" "${target_includes_dir}/mapr-starting-verification.rst" ".. _distribution-" ".. _mapr-"
  rewrite_references_sed "${source_rst}/upgrading.txt"             "${target_includes_dir}/mapr-upgrading.rst"             ".. _distribution-" ".. _mapr-"
}

run_command ${1}


text:
import argparse
import errno
import os
import shutil
import sys

def Main():
  parser = argparse.ArgumentParser(description='Create Mac Framework symlinks')
  parser.add_argument('--framework', action='store', type=str, required=True)
  parser.add_argument('--version', action='store', type=str)
  parser.add_argument('--contents', action='store', type=str, nargs='+')
  parser.add_argument('--stamp', action='store', type=str, required=True)
  args = parser.parse_args()

  VERSIONS = 'Versions'
  CURRENT = 'Current'

  # Ensure the Foo.framework/Versions/A/ directory exists and create the
  # Foo.framework/Versions/Current symlink to it.
  if args.version:
    try:
      os.makedirs(os.path.join(args.framework, VERSIONS, args.version), 0744)
    except OSError as e:
      if e.errno != errno.EEXIST:
        raise e
    _Relink(os.path.join(args.version),
            os.path.join(args.framework, VERSIONS, CURRENT))

  # Establish the top-level symlinks in the framework bundle. The dest of
  # the symlinks may not exist yet.
  if args.contents:
    for item in args.contents:
      _Relink(os.path.join(VERSIONS, CURRENT, item),
              os.path.join(args.framework, item))

  # Write out a stamp file.
  if args.stamp:
    with open(args.stamp, 'w') as f:
      f.write(str(args))

  return 0

def _Relink(dest, link):
  """Creates a symlink to |dest| named |link|. If |link| already exists,
  it is overwritten."""
  try:
    os.remove(link)
  except OSError as e:
    if e.errno != errno.ENOENT:
      shutil.rmtree(link)
  os.symlink(dest, link)

if __name__ == '__main__':
  sys.exit(Main())


text:
namespace MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.Shape
{
  using System;
  using System.Collections.Generic;
  using System.Globalization;
  using System.Xml;
  using MiniUML.Model.ViewModels;
  using MiniUML.Model.ViewModels.Shapes;
  using MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.Shape.Base;
  using MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.UmlElements;
  using MiniUML.Plugins.UmlClassDiagram.Converter;

  /// <summary>
  /// This class implements the viewmodel for Uml shapes
  /// with a node or circular point shape that users can
  /// draw on a UML canvas. Typically, these are
  /// Activity Start or Activity End shapes or other items.
  /// </summary>
  public class UmlNodeShapeViewModel : UmlShapeBaseViewModel
  {
    #region fields
    private string mShapeImageUrl = string.Empty;
    private string mStereotype = string.Empty;
    #endregion fields

    #region constructor
    /// <summary>
    /// Standard contructor hidding XElement constructor
    /// </summary>
    public UmlNodeShapeViewModel(IShapeParent parent,
                                 UmlTypes umlType)
      : base(parent,
             ShapeViewModelKey.NodeShape, ShapeViewModelSubKeys.None, umlType)
    {
    }
    #endregion constructor

    #region properties
    /// <summary>
    /// Get/set property to determine whether the view should show
    /// an additional image or not.
    ///
    /// Todo: This should be implemented via converter based on UmlShapeKey ???
    /// </summary>
    public string ShapeImageUrl
    {
      get
      {
        return this.mShapeImageUrl;
      }

      set
      {
        if (this.mShapeImageUrl != value)
        {
          this.mShapeImageUrl = value;
          this.NotifyPropertyChanged(() => this.ShapeImageUrl);
        }
      }
    }

    /// <summary>
    /// Get/set stereotype for the corresponding shape displayed in the view.
    /// </summary>
    public string Stereotype
    {
      get
      {
        return this.mStereotype;
      }

      set
      {
        if (this.mStereotype != value)
        {
          this.mStereotype = value;
          this.NotifyPropertyChanged(() => this.Stereotype);
        }
      }
    }
    #endregion properties

    #region methods
    /// <summary>
    /// Read shape data from XML stream and return it.
    /// </summary>
    /// <param name="reader"></param>
    /// <param name="parent"></param>
    /// <param name="umlType"></param>
    /// <returns></returns>
    public static UmlNodeShapeViewModel ReadDocument(XmlReader reader,
                                                IShapeParent parent,
                                                UmlTypes umlType)
    {
      UmlNodeShapeViewModel ret = UmlElementDataDef.CreateShape(umlType, new System.Windows.Point(UmlTypeToStringConverter.DefaultX,
                                                                                UmlTypeToStringConverter.DefaultY), parent)
                                                                                as UmlNodeShapeViewModel;
      reader.ReadToNextSibling(ret.UmlDataTypeString);

      while (reader.MoveToNextAttribute())
      {
        if (ret.ReadAttributes(reader.Name, reader.Value) == false)
        {
          if (reader.Name.Trim().Length > 0 && reader.Name != UmlShapeBaseViewModel.XmlComment)
            throw new ArgumentException("XML node:'" + reader.Name + "' as child of '" + ret.XElementName + "' is not supported.");
        }
      }

      // Read common model information (eg. comments)
      UmlShapeBaseViewModel.ReadDocument(reader, ret);

      return ret;
    }

    /// <summary>
    /// Persist the contents of this object into the given
    /// parameter <paramref name="writer"/> object.
    /// </summary>
    /// <param name="writer"></param>
    public override void SaveDocument(System.Xml.XmlWriter writer,
                                      IEnumerable<ShapeViewModelBase> root)
    {
      writer.WriteStartElement(this.mElementName);

      this.SaveAttributes(writer);

      // Save common model information (eg. comments)
      base.SaveDocument(writer);

      if (root != null)
      {
        foreach (var item in root)
        {
          item.SaveDocument(writer, item.Elements());
        }
      }

      writer.WriteEndElement();
    }

    /// <summary>
    /// Read the attribute values of this class from XML.
    /// </summary>
    /// <param name="readerName"></param>
    /// <param name="readerValue"></param>
    /// <returns></returns>
    protected override bool ReadAttributes(string readerName, string readerValue)
    {
      if (base.ReadAttributes(readerName, readerValue) == true)
        return true;

      switch (readerName)
      {
        case "Stereotype":
          this.Stereotype = readerValue;
          return true;

        case "ID":
          this.ID = readerValue;
          return true;

        case "xmlns":
          if (readerValue != UmlShapeBaseViewModel.NameSpace)
            throw new ArgumentException("XML namespace:'" + readerValue + "' is not supported.");
          return true;

        default:
          return false;
      }
    }

    /// <summary>
    /// Save the attribute values of this class to XML.
    /// </summary>
    /// <param name="writer"></param>
    protected override void SaveAttributes(System.Xml.XmlWriter writer)
    {
      base.SaveAttributes(writer);

      writer.WriteAttributeString("Stereotype", string.Format("{0}", this.Stereotype));
    }
    #endregion methods
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Sound</title>
<meta name="date" content="2015-07-06">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

engine.audio

Class Sound

java.lang.Object

engine.audio.Sound

public class Sound
extends java.lang.Object

Represents a playable sound.

Author:

Benny Bobaganoosh (thebennybox@gmail.com)

Constructor Summary

Constructors

Constructor and Description

Sound(IAudioDevice device,
     SoundData data,
     double volume,
     double pitch,
     boolean shouldLoop)

Creates a new Sound.

Method Summary

Methods

Modifier and Type
Method and Description

void
dispose()

Releases this object.

double
getDefaultVolume()

Gets the volume this object was initially created with.

void
pause()

Stops playing this sound, but leaves its position alone.

void
play()

Plays this sound.

void
setVolume(double amt)

Sets the volume of this sound to a new value.

void
stop()

Stops playing this sound and resets its position to the start of the
 audio.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Sound

public Sound(IAudioDevice device,
     SoundData data,
     double volume,
     double pitch,
     boolean shouldLoop)

Creates a new Sound. It is preferred to use this object instead of
 manipulating an IAudioDevice's audio object methods directly.

Parameters:

device - The device that plays this sound

data - The SoundData for the sound being played.

volume - How loud the sound should be. 1.0 specifies normal volume, and
            lower or higher values specify quieter or louder volumes,
            respectively.

pitch - What pitch the audio should be played at. 1.0 specifies normal
            pitch, and lower or higher values specify higher or lower
            pitches, respectively.

shouldLoop - Whether the audio should automatically restart when finished
            playing.

Method Detail

dispose

public void dispose()

Releases this object. This should be called when the object will no
 longer be used, and no methods or fields should be used after this method
 is called.

play

public void play()

Plays this sound. If it is already playing, it is stopped and restarted.
 When the audio is finished playing, it will stop if the object's
 shouldLoop is false, or it will restart if the object's shouldLoop is
 true.

pause

public void pause()

Stops playing this sound, but leaves its position alone. When the object
 is played again, it should start where it left off.

stop

public void stop()

Stops playing this sound and resets its position to the start of the
 audio. When the object is played again, it should start at the beginning.

getDefaultVolume

public double getDefaultVolume()

Gets the volume this object was initially created with.

Returns:

The volume this object was initially created with.

setVolume

public void setVolume(double amt)

Sets the volume of this sound to a new value.

Parameters:

amt - The new volume to be set to. 1.0 specifies normal volume, and
            lower or higher values specify quieter or louder volumes,
            respectively.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Version 5.0.0 of MediumEditor introduces a significantly simpler system for building custom extensions as well as extending existing buttons and extensions. As part of moving towards this extendable model, there were significant changes to the way options are passed to MediumEditor, as well as the extensions and buttons themselves.

In addition to extension related changes, there were several other potential breaking changes related to API methods, as well as utility helper methods.

## MediumEditor Options

For details on all the currently supported MediumEditor options, refer to the [Medium Editor Options Wiki Page](https://github.com/yabwe/medium-editor/wiki/Options).

### Toolbar Options
* Options controlling the toolbar are now passed as a `'toolbar'` object inside the outer options object.
  * `buttons` -> `toolbar.buttons`
  * `toolbarAlign` -> `toolbar.align`
  * `diffTop` -> `toolbar.diffTop`
  * `diffLeft` -> `toolbar.diffLeft`
  * `staticToolbar` -> `toolbar.static`
  * `stickyToolbar` -> `toolbar.sticky`
  * `firstButtonClass` -> `toolbar.firstButtonClass`
  * `lastButtonClass` -> `toolbar.lastButtonClass`
  * `updateOnEmptySelection` -> `toolbar.updateOnEmptySelection`
  * `standardizeSelectionStart` -> `toolbar.standardizeSelectionStart`

### Anchor Options
* Options controlling the anchor input extension are now passed as a `'anchor'` object inside the outer options object.
  * `anchorInputPlaceholder` -> `anchor.placeholderText`
  * `checkLinkFormat` -> `anchor.linkValidation`
  * `anchorButton` & `anchorButtonClass` -> `anchor.customClassOption`
  * `anchorTarget` -> `anchor.targetCheckbox`
  * `anchorInputCheckboxLabel` -> `anchor.targetCheckboxText`

### Anchor Preview Options
* Options controlling the anchor preview extension are now passed as a `'anchorPreview'` object inside the outer options object.
  * `anchorPreviewHideDelay` -> `anchorPreview.hideDelay`

### Paste Options
* Options controlling paste are now passed as a `'paste'` object inside the outer options object.
  * `forcePlainText` -> `paste.forcePlainText`
  * `cleanPastedHTML` -> `paste.cleanPastedHTML`

### Placeholder Options
* Options controlling the placeholder extension are now passed as a `'placeholder'` object inside the outer options object.
  * `placeholder` -> `placeholder.text`

### Other Options

#### `disableToolbar`
* Disabling the toolbar extension is now done by setting the `toolbar` option to `false`

#### `disableAnchorPreview`
* Disabling the anchor preview extension is now done by setting the `anchorPreview` option to `false`

#### `disablePlaceholders`
* Disabling the placeholder extension is now done by setting the `placeholder` option to `false`

#### `onShowToolbar` & `onHideToolbar`
* The `onShowToolbar` and `onHideToolbar` options are no longer supported. Instead, attach to the `'showToolbar'` and `'hideToolbar'` [custom events](https://github.com/yabwe/medium-editor/wiki/Custom-Events) via `MediumEditor.subscribe()`

#### `firstHeader` & `secondHeader`
* The `firstHeader` & `secondHeader` options have been removed.  Instead, any number of the 6 header types can be passed as button names into the `toolbar.buttons` option array.
  * Example: Where before the code may have sent `firstHeader: 'h2'` and `secondHeader: 'h3'`, it should now pass `['bold', 'italic', 'quote', 'h2', 'h3']` via the `toolbar.buttons` property of the MediumEditor options object.

#### `buttonLabels`
* The `buttonLabels` option no longer supports taking an object in that specifies custom labels for all buttons. Instead, pass an object into the `toolbar.buttons` option array that contains a `.name` property for the name of the button, a either a `contentDefault` or a `contentFA` property that should be in the innerHTML of the button (for default of `fontawesome` buttonLabels respectively)

## MediumEditor Extensions
#### `.parent`
* `Extension.parent` is no longer supported.  All extensions will have a reference to the MediumEditor instance via their `.base` property, unless the property already exists.

#### `.init()`
* `Extension.init()` will no longer be passed any arguments. Previously, `.init(instance)` received an instance of MediumEditor as an argument, but this is not needed now that `.base` will be populated before `.init()` is called.

#### `.deactivate()`
* `Extension.deactivate()` will no longer be called by MediumEditor. `.destroy()` will be called instead when MediumEditor is destroyed.

#### `.options`
* The `.options` property of any built-in extensions or buttons has been removed.  All of the properties should be retrieved and set from the prototype of the object itself.
  * Example: Instead of buttons using `this.options.action`, they should now use `this.action`.
  * Not all extensions had options before, or saved them via the `.options` property.

## MediumEditor API

#### `.id`
* The unique identifier used for MediumEditor elements will now remain unique and remain regardless of how many instances are created. After calling `.destroy()` and `.setup()`, the id will remain the same. This id was used to generate unique element ids for things like the id attribute of the toolbar element (`'medium-editor-toolbar-[ID]'`)

#### `.toolbar`
* The MediumEditor toolbar is now an extension, so `MediumEditor.toolbar` is no longer a valid reference.  Use `MediumEditor.getExtensionByName('toolbar')` instead.

#### `.statics`
* All of the `.statics` references have been removed as the new style of extensions and buttons has been introduced. The objects exposed via `.statics` have also been changed, so code which uses them may require additonal changes.
  * `MediumEditor.statics.ButtonsData` -> `MediumEditor.extensions.button.prototype.defaults` (ideally this reference should no longer be needed)
  * `MediumEditor.statics.DefaultButton` -> `MediumEditor.extensions.button`
  * `MediumEditor.statics.AnchorExtension` -> `MediumEditor.extensions.anchor`
  * `MediumEditor.statics.FontSizeExtension` -> `MediumEditor.extensions.fontSize`
  * `MediumEditor.statics.Toolbar` -> `MediumEditor.extensions.toolbar`
  * `MediumEditor.statics.AnchorPreview` -> `MediumEditor.extensions.anchorPreview`

#### `.activate()`
* `MediumEditor.activate()` has been replaced with `MediumEditor.setup()`

#### `.deactivate()`
* `MediumEditor.deactivate()` has been replaced with `MediumEditor.destroy()`

#### `.createEvent()`
* `MediumEditor.createEvent()` is no longer needed in order to fire custom events. It has been removed.

#### `.hideToolbarDefaultActions()`
* `MediumEditor.hideToolbarDefaultActions()` has been removed.  Use the `hideToolbarDefaultActions()` method of the toolbar extension instead.

#### `.setToolbarPosition()`
* `MediumEditor.setToolbarPosition()` has been removed.  Use the `setToolbarPosition()` method of the toolbar extension instead.

#### `.callExtensions()`
* `MediumEditor.callExtensions()` has been removed and is no longer supported.

## MediumEditor Utility Methods

### MediumEditor.util
* `MediumEditor.util.getSelectionRange()` has been moved to `MediumEditor.selection.getSelectionRange()`
* `MediumEditor.util.getSelectionStart()` has been moved to `MediumEditor.selection.getSelectionStart()`
* `MediumEditor.util.unwrapElement()` has been removed. Use `MediumEditor.util.unwrap()` instead
* `MediumEditor.util.getSelectionData()` has been removed
* `MediumEditor.util.setObject()` has been removed
* `MediumEditor.util.getObject()` has been removed
* `MediumEditor.util.derives()` has been removed. Objects that can be drived from (like extensions and buttons) will have a `.extend()` method for extending.
* `MediumEditor.util.now()` has been removed.  Use `Date.now()` instead.
* `MediumEditor.util.parentElements` has been renamed `MediumEditor.util.blockContainerElementNames`

### MediumEditor.selection
* `MediumEditor.selection.getSelectionData()` has been removed

## MediumEditor CSS & Markup
* The `.clearfix` class has been removed, and `.clearfix` class is no longer added to the toolbar element.
* All references to `'medium'` in CSS classes has been replaced with `'medium-editor'`
  * Example: The image element added by the image dragging extension will now have a `medium-editor-image-loading` class on instead of `medium-image-loading`
* The `data-medium-element` attribute on all MediumEditor elements has been renamed to `data-medium-editor-element`
* Toolbar classes `sticky-toolbar` and `static-toolbar` have been renamed `medium-editor-sticky-toolbar` and `medium-editor-static-toolbar` respectively

## Other Changes

* The `getFocusedElement()` method of the toolbar extension has been removed. Use `MediumEditor.getFocusedElement()` instead.
* Keyboard Shortcuts are now controlled via the Keyboard Commands extension.  The `.key` option on buttons is not longer supported for mapping keyboard shortcuts.


text:
define(['jquery', 'cfgs', 'API',
  'core/core-modules/framework.event',
  'core/core-modules/framework.ajax',
  'core/core-modules/framework.base64',
  'core/core-modules/framework.block',
  'core/core-modules/framework.dialog',
  'core/core-modules/framework.generator',
  'core/core-modules/framework.layout',
  'core/core-modules/framework.util',
  'core/core-modules/framework.form',
  'core/core-modules/framework.table',
  'core/core-modules/framework.dict',
  'core/core-plugins/plugins-logging'],
  function ($, cfgs, api, event, ajax, base64, block, dialog, generator, layout, util, form, table, dict) {

    String.prototype.startWith = function (str) {
      var reg = new RegExp("^" + str);
      return reg.test(this);
    }

    String.prototype.endWith = function (str) {
      var reg = new RegExp(str + "$");
      return reg.test(this);
    }

    form.source = layout;

    var exportModule = {
      event: event,
      ajax: ajax,
      base64: base64,
      block: block,
      generator: generator,
      layout: layout,
      util: util,
      config: cfgs,
      api: api,
      form: form,
      table: table,
      dict: dict,

      alertText: dialog.alertText,
      confirm: dialog.confirm,
      Start: function () {
        layout.init();
      }
    };

    return exportModule
  });


text:
package resource

// ResourceTuple groups together CPU, memory and disk space. This could be
// total, available or consumed. It could also be used by job resource requirements.
type ResourceTuple struct {
	// in hundreds, ie 100=1core, 50=0.5core, 200=2cores, etc
	Cores int
	// in MB
	Memory int
	// in MB
	Disk int
}

// Empty returns true if all components of the ResourceTuple are zero.
func (rt ResourceTuple) Empty() bool {
	return rt.Cores == 0 && rt.Memory == 0 && rt.Disk == 0
}

const (
	// TODO(jonboulle): make these configurable
	HostCores  = 100
	HostMemory = 256
	HostDisk   = 0
)

// HostResources represents a set of resources that fleet considers reserved
// for the host, i.e. outside of any units it is running
var HostResources = ResourceTuple{
	HostCores,
	HostMemory,
	HostDisk,
}

// Sum aggregates a number of ResourceTuples into a single entity
func Sum(resources ...ResourceTuple) (res ResourceTuple) {
	for _, r := range resources {
		res.Cores += r.Cores
		res.Memory += r.Memory
		res.Disk += r.Disk
	}
	return
}

// Sub returns a ResourceTuple representing the difference between two
// ResourceTuples
func Sub(r1, r2 ResourceTuple) (res ResourceTuple) {
	res.Cores = r1.Cores - r2.Cores
	res.Memory = r1.Memory - r2.Memory
	res.Disk = r1.Disk - r2.Disk
	return
}


text:
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace Abc.NCrafts.Quizz.Questions._027
{
    [CorrectAnswer(Difficulty = Difficulty.Hard)]
    public class Answer1
    {
        private static List<Key> _keys
            = new List<Key> { new Key() };

        public static void Run()
        {
            // begin
            for (var index = 0; index < _keys.Count; index++)
            {
                var key = _keys[index];
                key.Value++;
            }
            var result = _keys[0].Value == 0
                ? _keys[0].Value.GetHashCode()
                : _keys[0].GetHashCode();
            // end

            Logger.Log("Result: {0}", result);
        }

        private struct Key
        {
            public int Value;

            public override int GetHashCode()
            {
                return RuntimeHelpers.GetHashCode(this);
            }
        }
    }
}