text:
package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMSecurity.DisFlag;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.io.IOException;
import java.util.*;
import java.util.regex.*;

public class RawCMaterial extends StdLibrary implements MaterialLibrary
{
	@Override
	public String ID()
	{
		return "RawCMaterial";
	}

	@Override
	public int getRandomResourceOfMaterial(int material)
	{
		material=material&RawMaterial.MATERIAL_MASK;
		if((material<0)||(material>=RawMaterial.Material.values().length))
			return -1;
		final RawMaterial.CODES codes = RawMaterial.CODES.instance();
		final PairList<Integer, Double> rscs = codes.getValueSortedResources(material);
		if((rscs == null)||(rscs.size()==0))
			return -1;
		final int rscIndex=CMLib.dice().roll(1,rscs.size(),-1);
		return rscs.getFirst(rscIndex).intValue();
	}

	@Override
	public boolean quickDestroy(final Item I)
	{
		if(I==null)
			return false;
		final ItemPossessor O=I.owner();
		if(O instanceof MOB)
			((MOB)O).delItem(I);
		else
		if(O instanceof Room)
			((Room)O).delItem(I);
		I.setOwner(null);
		I.destroy();
		return true;
	}

	@Override
	public boolean rebundle(final Item item)
	{
		if((item==null)||(item.amDestroyed()))
			return false;
		final List<Item> found=new ArrayList<Item>();
		found.add(item);
		Item I=null;
		final Environmental owner=item.owner();
		long lowestNonZeroFoodNumber=Long.MAX_VALUE;
		final String subType=(item instanceof RawMaterial)?((RawMaterial)item).getSubType():"";
		if(subType.equals(RawMaterial.ResourceSubType.SEED.name()))
			return false;
		final CMFlagLibrary flags = CMLib.flags();
		if(owner instanceof Room)
		{
			final Room R=(Room)owner;
			for(int i=0;i<R.numItems();i++)
			{
				I=R.getItem(i);
				if((I instanceof RawMaterial)
				&&(I.material()==item.material())
				&&(I!=item)
				&&(I.container()==item.container())
				&&(((RawMaterial)I).getSubType().equals(subType))
				&&(I.rawSecretIdentity().equals(item.rawSecretIdentity()))
				&&(!flags.isOnFire(I))
				&&(!flags.isEnchanted(I)))
					found.add(I);
			}
		}
		else
		if(owner instanceof MOB)
		{
			final MOB M=(MOB)owner;
			for(int i=0;i<M.numItems();i++)
			{
				I=M.getItem(i);
				if((I instanceof RawMaterial)
				&&(I.material()==item.material())
				&&(I!=item)
				&&(I.container()==item.container())
				&&(((RawMaterial)I).getSubType().equals(subType))
				&&(I.rawSecretIdentity().equals(item.rawSecretIdentity()))
				&&(!flags.isOnFire(I))
				&&(!flags.isEnchanted(I)))
					found.add(I);
			}
		}
		else
			return false;
		if(found.size()<2)
			return false;
		Item bundle=null;
		int maxFound=1;
		int totalWeight=0;
		int totalValue=0;
		int totalNourishment=0;
		int totalThirstHeld=0;
		int totalThirstRemain=0;
		for(int i=0;i<found.size();i++)
		{
			I=found.get(i);
			final int weight=I.basePhyStats().weight();
			totalWeight+=weight;
			totalValue+=I.baseGoldValue();
			if(weight>maxFound)
			{
				maxFound=weight;
				bundle=I;
			}
			if((I instanceof Decayable)
			&&(((Decayable)I).decayTime()>0)
			&&(((Decayable)I).decayTime()<lowestNonZeroFoodNumber))
				lowestNonZeroFoodNumber=((Decayable)I).decayTime();
			if(I instanceof Food)
				totalNourishment+=((Food)I).nourishment();
			if(I instanceof Drink)
			{
				totalThirstHeld+=((Drink)I).liquidHeld();
				totalThirstRemain+=((Drink)I).liquidRemaining();
			}
		}
		if(bundle==null)
			bundle=item;
		found.remove(bundle);
		if(lowestNonZeroFoodNumber==Long.MAX_VALUE)
			lowestNonZeroFoodNumber=0;
		final Map<String,Ability> foundAblesH=new HashMap<String,Ability>();
		Ability A=null;
		for(int i=0;i<found.size();i++)
		{
			I=found.get(i);
			for(final Enumeration<Ability> a=I.effects();a.hasMoreElements();)
			{
				A=a.nextElement();
				if((A!=null)
				&&(!A.canBeUninvoked())
				&&(!foundAblesH.containsKey(A.ID())))
					foundAblesH.put(A.ID(),A);
			}
		}
		bundle.basePhyStats().setWeight(totalWeight);
		bundle.setBaseValue(totalValue);
		adjustResourceName(bundle);
		if(bundle instanceof Food)
			((Food)bundle).setNourishment(totalNourishment);
		if(bundle instanceof Drink)
		{
			((Drink)bundle).setLiquidHeld(totalThirstHeld);
			((Drink)bundle).setLiquidRemaining(totalThirstRemain);
		}
		if(bundle instanceof Decayable)
			((Decayable)bundle).setDecayTime(lowestNonZeroFoodNumber);
		for(final String key  : foundAblesH.keySet())
		{
			A=foundAblesH.get(key);
			if(bundle.fetchEffect(A.ID())==null)
				bundle.addNonUninvokableEffect((Ability)A.copyOf());
		}
		for(int i=0;i<found.size();i++)
			((RawMaterial)found.get(i)).quickDestroy();
		if((owner instanceof Room)
		&&(((Room)owner).numItems()>0)
		&&(((Room)owner).getItem(((Room)owner).numItems()-1)!=bundle))
		{
			final Container C=bundle.container();
			((Room)owner).delItem(bundle);
			((Room)owner).moveItemTo(bundle,ItemPossessor.Expire.Player_Drop);
			bundle.setContainer(C);
		}
		if((owner instanceof MOB)
		&&(((MOB)owner).numItems()>0)
		&&(((MOB)owner).getItem(((MOB)owner).numItems()-1)!=bundle))
		{
			final Container C=bundle.container();
			((MOB)owner).delItem(bundle);
			((MOB)owner).moveItemTo(bundle);
			bundle.setContainer(C);
		}
		final Room R=CMLib.map().roomLocation(bundle);
		if(R!=null)
			R.recoverRoomStats();
		return true;
	}

	@Override
	public Item splitBundle(final Item I, final int size, final Container C)
	{
		final List<Item> set=disBundle(I,1,size,C);
		if((set==null)||(set.size()==0))
			return null;
		return set.get(0);
	}

	@Override
	public Item unbundle(final Item I, final int number, final Container C)
	{
		final List<Item> set=disBundle(I,number,1,C);
		if((set==null)||(set.size()==0))
			return null;
		return set.get(0);
	}

	protected List<Item> disBundle(Item I, int number, final int bundleSize, final Container C)
	{
		if((I==null)||(I.amDestroyed())||(bundleSize<1))
			return null;
		if((I instanceof PackagedItems)
		&&(I.container()==C)
		&&(!CMLib.flags().isOnFire(I)))
		{
			final PackagedItems pkg=(PackagedItems)I;
			if(number<=0)
				number=pkg.numberOfItemsInPackage();
			if(number<=0)
				number=1;
			if(number>pkg.numberOfItemsInPackage())
				number=pkg.numberOfItemsInPackage();
			final Environmental owner=I.owner();
			final List<Item> parts=((PackagedItems)I).unPackage(number);
			if(parts.size()==0)
				return new XVector<Item>(I);
			final List<Item> bundle=new XVector<Item>();
			for(int p=0;p<parts.size();p+=bundleSize)
			{
				I=parts.get(p);
				if(bundleSize>1)
				{
					final PackagedItems thePackage=(PackagedItems)CMClass.getItem(pkg.ID());
					thePackage.packageMe(I, bundleSize);
					for(int pp=p;(pp<p+bundleSize) && (pp<parts.size());pp++)
						parts.get(pp).destroy();
					I=thePackage;
				}
				if(owner instanceof Room)
					((Room)owner).addItem(I,ItemPossessor.Expire.Player_Drop);
				else
				if(owner instanceof MOB)
					((MOB)owner).addItem(I);
				I.setContainer(C);
				bundle.add(I);
			}
			if(!pkg.amDestroyed())
			{
				if(owner instanceof Room)
				{
					((Room)owner).delItem(pkg);
					((Room)owner).addItem(pkg,ItemPossessor.Expire.Player_Drop);
					bundle.add(pkg);
				}
				else
				if(owner instanceof MOB)
				{
					((MOB)owner).delItem(pkg);
					((MOB)owner).addItem(pkg);
					bundle.add(pkg);
				}
				else
					pkg.destroy();
			}
			return bundle;
		}
		else
		if((I instanceof RawMaterial)
		&&(I.container()==C)
		&&(!CMLib.flags().isOnFire(I))
		&&(!CMLib.flags().isABonusItems(I))
		&&(!CMLib.flags().isEnchanted(I)))
		{
			final Ability rott=I.fetchEffect("Poison_Rotten");
			final Ability purt=I.fetchEffect("Poison_Purify");
			number = number * bundleSize;
			if(I.basePhyStats().weight()>1)
			{
				final Environmental owner=I.owner();
				if(number<=0)
					number=I.basePhyStats().weight();
				if(number<=0)
					number=1;
				if(number>=(I.basePhyStats().weight()-1))
					number=I.basePhyStats().weight();
				I.basePhyStats().setWeight(I.basePhyStats().weight()); // wtf?
				int loseValue=0;
				int loseNourishment=0;
				int loseThirstHeld=0;
				int loseThirstRemain=0;
				Item E=null;
				final List<Item> bundle=new XVector<Item>();
				for(int x=0;x<number;x+=bundleSize)
				{
					E=makeItemResource(I.material(),null,true,I.rawSecretIdentity(), ((RawMaterial)I).getSubType());
					if(E instanceof Item)
					{
						E.setContainer(C);
						loseValue+=E.baseGoldValue();
						for(final Enumeration<Ability> a=I.effects();a.hasMoreElements();)
						{
							final Ability A=a.nextElement();
							if((!A.canBeUninvoked())
							&&(!A.ID().equalsIgnoreCase("Poison_Rotten"))
							&&(!A.ID().equalsIgnoreCase("Poison_Purify")))
							{
								final Ability A2=(Ability)A.copyOf();
								E.addNonUninvokableEffect(A2);
							}
						}
						if((E instanceof RawMaterial)
						&&(I instanceof RawMaterial))
							((RawMaterial)E).setSubType(((RawMaterial)I).getSubType());
						if((E instanceof Decayable)
						&&(I instanceof Decayable))
							((Decayable)E).setDecayTime(((Decayable)I).decayTime());
						if((E instanceof Food)
						&&(I instanceof Food))
							loseNourishment+=((Food)E).nourishment();
						if((E instanceof Drink)
						&&(I instanceof Drink))
						{
							loseThirstHeld+=((Drink)E).liquidHeld();
							loseThirstRemain+=((Drink)E).liquidRemaining();
						}
						if((rott!=null)
						&&(!rott.canBeUninvoked())
						&&(!CMSecurity.isDisabled(DisFlag.FOODROT)))
							E.addNonUninvokableEffect((Ability)rott.copyOf());
						if((purt!=null)
						&&(!purt.canBeUninvoked())
						&&(!CMSecurity.isDisabled(DisFlag.FOODROT)))
							E.addNonUninvokableEffect((Ability)purt.copyOf());
						if(bundleSize>1)
						{
							E.basePhyStats().setWeight(bundleSize);
							E.phyStats().setWeight(bundleSize);
							adjustResourceName(E);
						}
						if(owner instanceof Room)
						{
							((Room)owner).addItem(E,ItemPossessor.Expire.Player_Drop);
							bundle.add(E);
						}
						else
						if(owner instanceof MOB)
						{
							((MOB)owner).addItem(E);
							bundle.add(E);
						}
					}
					else
						E=null;
				}
				if((I.basePhyStats().weight()-number)>1)
				{
					I.basePhyStats().setWeight(I.basePhyStats().weight()-number);
					I.setBaseValue(I.baseGoldValue()-loseValue);
					this.adjustResourceName(I);
					if(I instanceof Food)
					{
						((Food)I).setNourishment(((Food)I).nourishment()-loseNourishment);
						if(((Food)I).nourishment()<=0)
							((Food)I).setNourishment(0);
					}
					if(I instanceof Drink)
					{
						((Drink)I).setLiquidHeld(((Drink)I).liquidHeld()-loseThirstHeld);
						if(((Drink)I).liquidHeld()<=0)
							((Drink)I).setLiquidHeld(0);
						((Drink)I).setLiquidRemaining(((Drink)I).liquidRemaining()-loseThirstRemain);
						if(((Drink)I).liquidRemaining()<=0)
							((Drink)I).setLiquidRemaining(0);
					}
					I.recoverPhyStats();
					// now move it to the end!
					if(owner instanceof Room)
					{
						((Room)owner).delItem(I);
						((Room)owner).addItem(I,ItemPossessor.Expire.Player_Drop);
						bundle.add(I);
					}
					else
					if(owner instanceof MOB)
					{
						((MOB)owner).delItem(I);
						((MOB)owner).addItem(I);
						bundle.add(I);
					}
					else
						I.destroy();
				}
				else
					I.destroy();
				return bundle;
			}
			else
				return new XVector<Item>(I);
		}
		return null;
	}

	@Override
	public String getMaterialDesc(final int materialCode)
	{
		final RawMaterial.Material m=RawMaterial.Material.findByMask(materialCode);
		if(m!=null)
			return m.desc();
		return "";
	}

	@Override
	public String getResourceDesc(final int resourceCode)
	{
		if(RawMaterial.CODES.IS_VALID(resourceCode))
			return RawMaterial.CODES.NAME(resourceCode);
		return "";
	}

	@Override
	public int findMaterialRelativeInt(final String s)
	{
		final RawMaterial.Material m=RawMaterial.Material.findIgnoreCase(s);
		if(m!=null)
			return m.ordinal();
		return -1;
	}

	@Override
	public int findMaterialCode(String s, final boolean exact)
	{
		RawMaterial.Material m=RawMaterial.Material.findIgnoreCase(s);
		if(m!=null)
			return m.mask();
		if(exact)
			return -1;
		s=s.toUpperCase();
		m=RawMaterial.Material.startsWith(s);
		if(m!=null)
			return m.mask();
		return -1;
	}

	@Override
	public int findResourceCode(String s, final boolean exact)
	{
		int code = RawMaterial.CODES.FIND_IgnoreCase(s);
		if(code>=0)
			return code;
		if(exact)
			return -1;
		s=s.toUpperCase();
		code = RawMaterial.CODES.FIND_StartsWith(s);
		return code;
	}

	@Override
	public void addEffectsToResource(final Item I)
	{
		if(I==null)
			return;
		final Ability[] As=RawMaterial.CODES.EFFECTA(I.material());
		if((As==null)||(As.length==0))
			return;
		for(final Ability A : As)
		{
			if(I.fetchEffect(A.ID())==null)
				I.addNonUninvokableEffect((Ability)A.copyOf());
		}
	}

	protected MOB makeMOBResource(final int myResource)
	{
		if(myResource<0)
			return null;
		switch(myResource)
		{
		case RawMaterial.RESOURCE_MUTTON:
		case RawMaterial.RESOURCE_WOOL:
			return CMClass.getMOB("Sheep");
		case RawMaterial.RESOURCE_LEATHER:
			switch(CMLib.dice().roll(1,10,0))
			{
			case 1:
			case 2:
			case 3:
				return CMClass.getMOB("Cow");
			case 4:
				return CMClass.getMOB("Bull");
			case 5:
			case 6:
			case 7:
				return CMClass.getMOB("Doe");
			case 8:
			case 9:
			case 10:
				return CMClass.getMOB("Buck");
			}
			break;
		case RawMaterial.RESOURCE_HIDE:
			switch(CMLib.dice().roll(1,10,0))
			{
			case 1:
			case 2:
				return CMClass.getMOB("Gorilla");
			case 3:
				return CMClass.getMOB("Lion");
			case 4:
				return CMClass.getMOB("Cheetah");
			case 5:
			case 6:
				return CMClass.getMOB("Ape");
			case 7:
			case 8:
				return CMClass.getMOB("Fox");
			case 9:
			case 10:
				return CMClass.getMOB("Monkey");
			}
			break;
		case RawMaterial.RESOURCE_PORK:
			return CMClass.getMOB("Pig");
		case RawMaterial.RESOURCE_FUR:
		case RawMaterial.RESOURCE_MEAT:
			switch(CMLib.dice().roll(1,10,0))
			{
			case 1:
			case 2:
			case 3:
			case 4:
				return CMClass.getMOB("Wolf");
			case 5:
			case 6:
			case 7:
				return CMClass.getMOB("Buffalo");
			case 8:
			case 9:
				return CMClass.getMOB("BrownBear");
			case 10:
				return CMClass.getMOB("BlackBear");
			}
			break;
		case RawMaterial.RESOURCE_SCALES:
			switch(CMLib.dice().roll(1,10,0))
			{
			case 1:
			case 2:
			case 3:
			case 4:
				return CMClass.getMOB("Lizard");
			case 5:
			case 6:
			case 7:
				return CMClass.getMOB("GardenSnake");
			case 8:
			case 9:
				return CMClass.getMOB("Cobra");
			case 10:
				return CMClass.getMOB("Python");
			}
			break;
		case RawMaterial.RESOURCE_POULTRY:
		case RawMaterial.RESOURCE_EGGS:
			return CMClass.getMOB("Chicken");
		case RawMaterial.RESOURCE_BEEF:
			switch(CMLib.dice().roll(1,5,0))
			{
			case 1:
			case 2:
			case 3:
			case 4:
				return CMClass.getMOB("Cow");
			case 5:
				return CMClass.getMOB("Bull");
			}
			break;
		case RawMaterial.RESOURCE_FEATHERS:
			switch(CMLib.dice().roll(1,4,0))
			{
			case 1:
				return CMClass.getMOB("WildEagle");
			case 2:
				return CMClass.getMOB("Falcon");
			case 3:
				return CMClass.getMOB("Chicken");
			case 4:
				return CMClass.getMOB("Parakeet");
			}
			break;
		}
		return null;
	}

	protected Item makeItemResource(final int myResource, final String localeCode, final boolean noAnimals, final String fullName, final String subType)
	{
		RawMaterial I=null;
		int material=(myResource&RawMaterial.MATERIAL_MASK);
		if(!noAnimals)
		{
			if((myResource==RawMaterial.RESOURCE_WOOL)
			||(myResource==RawMaterial.RESOURCE_FEATHERS)
			||(myResource==RawMaterial.RESOURCE_SCALES)
			||(myResource==RawMaterial.RESOURCE_HIDE)
			||(myResource==RawMaterial.RESOURCE_FUR))
			   material=RawMaterial.MATERIAL_LEATHER;
			if(CMParms.contains(RawMaterial.CODES.FISHES(), myResource))
				material=RawMaterial.MATERIAL_VEGETATION;
		}
		switch(material)
		{
		case RawMaterial.MATERIAL_FLESH:
			I=(RawMaterial)CMClass.getItem("GenFoodResource");
			break;
		case RawMaterial.MATERIAL_VEGETATION:
		{
			if((myResource==RawMaterial.RESOURCE_VINE)
			||(myResource==RawMaterial.RESOURCE_FLOWERS))
				I=(RawMaterial)CMClass.getItem("GenResource");
			else
			{
				I=(RawMaterial)CMClass.getItem("GenFoodResource");
				if(myResource==RawMaterial.RESOURCE_HERBS)
					((Food)I).setNourishment(1);
			}
			break;
		}
		case RawMaterial.MATERIAL_GAS:
		case 0:
		{
			//TODO!
			I=(RawMaterial)CMClass.getItem("GenLiquidResource");
			break;
		}
		case RawMaterial.MATERIAL_LIQUID:
		case RawMaterial.MATERIAL_ENERGY:
		{
			I=(RawMaterial)CMClass.getItem("GenLiquidResource");
			break;
		}
		case RawMaterial.MATERIAL_LEATHER:
		case RawMaterial.MATERIAL_CLOTH:
		case RawMaterial.MATERIAL_PAPER:
		case RawMaterial.MATERIAL_WOODEN:
		case RawMaterial.MATERIAL_GLASS:
		case RawMaterial.MATERIAL_SYNTHETIC:
		case RawMaterial.MATERIAL_ROCK:
		case RawMaterial.MATERIAL_PRECIOUS:
		{
			I=(RawMaterial)CMClass.getItem("GenResource");
			break;
		}
		case RawMaterial.MATERIAL_METAL:
		case RawMaterial.MATERIAL_MITHRIL:
		{
			I=(RawMaterial)CMClass.getItem("GenResource");
			break;
		}
		}
		switch(myResource)
		{
		case RawMaterial.RESOURCE_SALT:
			I=(RawMaterial)CMClass.getItem("GenFoodResource");
			break;
		default:
			break;
		}
		if(I!=null)
		{
			if((fullName!=null)&&(fullName.length()>0))
				I.setSecretIdentity(fullName);
			I.setMaterial(myResource);
			if(I instanceof LiquidHolder)
				((LiquidHolder)I).setLiquidType(myResource);
			I.setBaseValue(RawMaterial.CODES.VALUE(myResource));
			I.basePhyStats().setWeight(1);
			I.setDomainSource(localeCode);
			if(subType != null)
				I.setSubType(subType.toUpperCase().trim());
			adjustResourceName(I);
			I.setDescription("");
			addEffectsToResource(I);
			I.recoverPhyStats();
			return I;
		}
		return null;
	}

	@Override
	public PhysicalAgent makeResource(final int myResource, final String localeCode, final boolean noAnimals, final String fullName, final String subType)
	{
		if(myResource<0)
			return null;
		if(!noAnimals)
		{
			final MOB M = makeMOBResource(myResource);
			if(M!=null)
				return M;
		}
		return this.makeItemResource(myResource, localeCode, noAnimals, fullName, subType);
	}

	@Override
	public String getGeneralItemType(final Item I)
	{
		if(I instanceof RawMaterial)
			return CMStrings.capitalizeAndLower(getMaterialDesc(I.material()));
		if(I instanceof Weapon)
			return "weapons";
		if(I instanceof Armor)
			return "armor";
		if(I instanceof Coins)
			return "currency";
		if(I instanceof Drink)
			return "liquid";
		if(I instanceof Food)
			return "food";
		if(I instanceof Pill)
			return "pills";
		if(I instanceof Light)
			return "light sources";
		if(I instanceof com.planet_ink.coffee_mud.Items.interfaces.RoomMap)
			return "papers";
		if(I instanceof Scroll)
			return "papers";
		if(I instanceof Electronics)
			return "technology";
		if(I instanceof DoorKey)
			return "keys";
		if((I.material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_PAPER)
			return "papers";
		if(I instanceof DeadBody)
			return "corpses";
		if((I instanceof Container)&&(((Container)I).capacity()>0))
			return "containers";
		return "items";
	}

	@Override
	public String makeResourceBetterName(final int rscCode, String subType, final boolean plural)
	{
		String name=RawMaterial.CODES.NAME(rscCode).toLowerCase();
		final int iMat = rscCode&RawMaterial.MATERIAL_MASK;
		if((subType!=null)&&(subType.length()>0))
		{
			subType = subType.toLowerCase();
			if(subType.equals(name)
			&& ((iMat==RawMaterial.MATERIAL_CLOTH)||(iMat==RawMaterial.MATERIAL_PAPER)))
				name=L("@x1 bolt", name);
			else
				name=subType;
		}
		else
		if((iMat==RawMaterial.MATERIAL_MITHRIL)
		||(iMat==RawMaterial.MATERIAL_METAL))
		{
			if((iMat!=RawMaterial.RESOURCE_ADAMANTITE)
			&&(iMat!=RawMaterial.RESOURCE_BRASS)
			&&(iMat!=RawMaterial.RESOURCE_BRONZE)
			&&(iMat!=RawMaterial.RESOURCE_STEEL))
				name=L("@x1 ore",name);
		}

		if(!plural)
		{
			if((rscCode&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
				return L("some @x1",name);
			else
				return L("a pound of @x1",name);
		}
		else
		{
			if((rscCode&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
				return L("a pool of @x1", name);
			else
				return L("a bundle of @x1", name);
		}
	}

	@Override
	public String makeResourceSimpleName(final int rscCode, String subType)
	{
		String name=RawMaterial.CODES.NAME(rscCode).toLowerCase();
		final int iMat = rscCode&RawMaterial.MATERIAL_MASK;
		if((subType!=null)&&(subType.length()>0))
		{
			subType = subType.toLowerCase();
			if(subType.equals(name)
			&& ((iMat==RawMaterial.MATERIAL_CLOTH)||(iMat==RawMaterial.MATERIAL_PAPER)))
				name=L("@x1 bolt", name);
			else
				name=subType;
		}
		else
		if((iMat==RawMaterial.MATERIAL_MITHRIL)
		||(iMat==RawMaterial.MATERIAL_METAL))
		{
			if((iMat!=RawMaterial.RESOURCE_ADAMANTITE)
			&&(iMat!=RawMaterial.RESOURCE_BRASS)
			&&(iMat!=RawMaterial.RESOURCE_BRONZE)
			&&(iMat!=RawMaterial.RESOURCE_STEEL))
				name=L("@x1 ore",name);
		}
		return name;
	}

	@Override
	public void adjustResourceName(final Item I)
	{
		String name=RawMaterial.CODES.NAME(I.material()).toLowerCase();
		I.setDescription(L("It's just @x1.",name));
		final int iMat=I.material()&RawMaterial.MATERIAL_MASK;
		if((I instanceof RawMaterial)
		&&(((RawMaterial)I).getSubType().length()>0))
		{
			final String subType = ((RawMaterial)I).getSubType().toLowerCase();
			if(subType.equals(name)
			&& ((iMat==RawMaterial.MATERIAL_CLOTH)||(iMat==RawMaterial.MATERIAL_PAPER)))
				name=L("@x1 bolt", name);
			else
			{
				name=subType;
				I.setDescription(L("'@x1' is a special type of @x2 that retains its uniqueness.",name,RawMaterial.CODES.NAME(I.material()).toLowerCase()));
			}
		}
		else
		if((I.rawSecretIdentity()!=null)
		&&(I.rawSecretIdentity().length()>0))
			name = CMLib.english().removeArticleLead(I.rawSecretIdentity().toLowerCase());
		else
		if((iMat==RawMaterial.MATERIAL_MITHRIL)
		||(iMat==RawMaterial.MATERIAL_METAL))
		{
			if((I.material()!=RawMaterial.RESOURCE_ADAMANTITE)
			&&(I.material()!=RawMaterial.RESOURCE_BRASS)
			&&(I.material()!=RawMaterial.RESOURCE_BRONZE)
			&&(I.material()!=RawMaterial.RESOURCE_STEEL))
				name=L("@x1 ore",name);
		}

		if(I.basePhyStats().weight()==1)
		{
			if((I.rawSecretIdentity()!=null)
			&&(I.rawSecretIdentity().length()>0))
			{
				I.setName(I.rawSecretIdentity());
				I.setDisplayText(L("@x1 sits here.", I.rawSecretIdentity()));
			}
			else
			{
				if(I instanceof Drink)
				{
					I.setName(L("some @x1",name));
					I.setDisplayText(L("some @x1 sits here.", name));
				}
				else
				{
					I.setName(L("a pound of @x1",name));
					I.setDisplayText(L("some @x1 sits here.", name));
				}
			}
		}
		else
		{
			if(I instanceof Drink)
				I.setName(L(CMLib.english().startWithAorAn(L("@x1# pool of @x2",""+I.basePhyStats().weight(), name))));
			else
				I.setName(L(CMLib.english().startWithAorAn(L("@x1# @x2 bundle",""+I.basePhyStats().weight(), name))));
			I.setDisplayText(L("@x1 is here.",I.name()));
		}
	}

	@Override
	public Item makeItemResource(final int type)
	{
		return makeItemResource(type, "");
	}
	@Override
	public Item makeItemResource(final int type, final String subType)
	{
		Item I=null;
		if(((type&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_FLESH)
		||((type&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_VEGETATION))
			I=CMClass.getItem("GenFoodResource");
		else
		if((type&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
			I=CMClass.getItem("GenLiquidResource");
		else
			I=CMClass.getItem("GenResource");
		((RawMaterial)I).setSubType(subType.toUpperCase().trim());
		I.basePhyStats().setWeight(1);
		I.setMaterial(type);
		adjustResourceName(I);
		I.setBaseValue(RawMaterial.CODES.VALUE(type));
		addEffectsToResource(I);
		I.recoverPhyStats();
		return I;
	}

	@Override
	public int destroyResourcesAmt(final MOB E, final int howMuch, final int finalMaterial, final String subType, final Container C)
	{
		return destroyResourcesAmt(getAllItems(E), howMuch, finalMaterial, subType, C);
	}

	@Override
	public int destroyResourcesAmt(final Room E, final int howMuch, final int finalMaterial, final String subType, final Container C)
	{
		return destroyResourcesAmt(getAllItems(E), howMuch, finalMaterial, subType, C);
	}

	@Override
	public int destroyResourcesAmt(final List<Item> V, final int howMuch, final int resourceCode, final String subType, final Container C)
	{
		if((V==null)||(V.size()==0))
			return 0;
		if(howMuch<=0)
			return 0;
		final RawMaterial firstMaterialI = (resourceCode>0)?this.findFirstResource(V, resourceCode, C, subType):null;
		return destroyResources(V, howMuch, resourceCode, -1, null, C, firstMaterialI, null).getLostAmt();
	}

	@Override
	public int destroyResourcesValue(final Room E, final int howMuch, final int finalMaterial, final int finalSubHash, final int otherMaterial, final int otherSubHash)
	{
		final List<Item> materials = this.getSomeRawMaterial(E, finalMaterial, finalSubHash, otherMaterial, otherSubHash);
		return destroyResourcesValue(materials, howMuch, finalMaterial, otherMaterial, null, null);
	}

	@Override
	public int destroyResourcesValue(final MOB E, final int howMuch, final int finalMaterial, final int finalSubHash, final int otherMaterial, final int otherSubHash)
	{
		final List<Item> materials = this.getSomeRawMaterial(E, finalMaterial, finalSubHash, otherMaterial, otherSubHash);
		return destroyResourcesValue(materials, howMuch, finalMaterial,  otherMaterial, null, null);
	}

	@Override
	public int destroyResourcesValue(final List<Item> V, final int howMuch, final int finalMaterial, final int otherMaterial, final Item never, final Container C)
	{
		return destroyResources(V, howMuch, finalMaterial, otherMaterial, never, C, null, null).getLostValue();
	}

	@Override
	public DeadResourceRecord destroyResources(final Room R, final int howMuch, final int finalMaterial, final int finalSubHash, final int otherMaterial, final int otherSubHash)
	{
		final List<Item> materials = this.getSomeRawMaterial(R, finalMaterial, finalSubHash, otherMaterial, otherSubHash);
		return destroyResources(materials,howMuch,finalMaterial,otherMaterial,null, null, null, null);
	}

	protected DeadResourceRecord destroyResources(final List<Item> V, int howMuch, int finalMaterial, int otherMaterial, final Item never,
												  final Container C, RawMaterial firstMaterialI, RawMaterial otherMaterialI)
	{
		int lostValue=0;
		int lostAmt=0;
		int resCode=-1;
		String subType="";
		XVector<CMObject> lostProps = null;
		final CMFlagLibrary flags=CMLib.flags();
		if((V!=null)
		&&(V.size()>0)
		&&((howMuch>0)||(otherMaterial>0)))
		{
			lostProps = new XVector<CMObject>();
			if(firstMaterialI == null)
				firstMaterialI = (finalMaterial>0)?this.findFirstResource(V, finalMaterial, C, null):null;
			if(otherMaterialI == null)
				otherMaterialI = (otherMaterial>0)?this.findFirstResource(V, otherMaterial, C, null):null;
			final int firstResourceType = (firstMaterialI != null)?firstMaterialI.material():-1;
			final int otherResourceType = (otherMaterialI != null)?otherMaterialI.material():-1;
			for(int i=V.size()-1;i>=0;i--)
			{
				final Item I=V.get(i);
				if(!(I instanceof RawMaterial)
				||(I==never))
					continue;
				final RawMaterial rI=(RawMaterial)I;
				if((otherResourceType>0)
				&&(rI.material()==otherResourceType)
				&&(rI.container()==C)
				&&(otherMaterialI!=null)
				&&(rI.getSubType().equals(otherMaterialI.getSubType()))
				&&(rI.rawSecretIdentity().equals(otherMaterialI.rawSecretIdentity()))
				&&(!flags.isOnFire(I))
				&&(!flags.isEnchanted(I)))
				{
					if(I.basePhyStats().weight()>1)
					{
						final List<Item> set=disBundle(I,1,1,C);
						if((set==null)||(set.size()==0))
							continue;
						final Item uI=set.get(0);
						lostValue+=uI.value();
						lostProps.addAll(uI.effects());
						lostProps.addAll(uI.behaviors());
						uI.destroy();
					}
					else
					{
						lostValue+=I.value();
						lostProps.addAll(I.effects());
						lostProps.addAll(I.behaviors());
						((RawMaterial)I).quickDestroy();
					}
					otherMaterial=-1;
					if((finalMaterial<0)||(howMuch<=0))
						break;
				}
				else
				if((rI.material()==firstResourceType)
				&&(howMuch>0)
				&&(I.container()==C)
				&&(firstMaterialI!=null)
				&&(rI.getSubType().equals(firstMaterialI.getSubType()))
				&&(rI.rawSecretIdentity().equals(firstMaterialI.rawSecretIdentity()))
				&&(!flags.isOnFire(I))
				&&(!flags.isEnchanted(I)))
				{
					if(I.basePhyStats().weight()>howMuch)
					{
						final List<Item> set=disBundle(I,1,howMuch,C);
						if((set==null)||(set.size()==0))
							continue;
						final Item uI=set.get(0);
						lostAmt+=howMuch;
						resCode=I.material();
						lostValue+=(uI.value());
						subType=rI.getSubType();
						lostProps.addAll(uI.effects());
						lostProps.addAll(uI.behaviors());
						uI.destroy();
						howMuch=0;
					}
					else
					{
						lostAmt+=I.basePhyStats().weight();
						subType=rI.getSubType();
						resCode=I.material();
						howMuch-=I.basePhyStats().weight();
						lostProps.addAll(I.effects());
						lostValue+=I.value();
						((RawMaterial)I).quickDestroy();
					}
					if(howMuch<=0)
					{
						finalMaterial=-1;
						if(otherMaterial<=0)
							break;
					}
				}
			}
		}
		return new DeadResourceRecord()
		{
			int lostValue=0;
			int lostAmt=0;
			int resCode=-1;
			String subType="";
			List<CMObject> lostProps = null;

			public DeadResourceRecord set(final int lostValue, final int lostAmt, final int resCode, final String subType, final List<CMObject> lostProps)
			{
				this.lostValue = lostValue;
				this.lostAmt = lostAmt;
				this.resCode = resCode;
				this.subType = subType;
				this.lostProps = lostProps;
				return this;
			}

			@Override
			public int getLostValue()
			{
				return lostValue;
			}

			@Override
			public int getLostAmt()
			{
				return lostAmt;
			}

			@Override
			public int getResCode()
			{
				return resCode;
			}

			@Override
			public String getSubType()
			{
				return subType;
			}

			@Override
			public List<CMObject> getLostProps()
			{
				return lostProps;
			}
		}.set(lostValue, lostAmt, resCode, subType, lostProps);
	}

	@Override
	public RawMaterial findFirstResource(final Room E, final String other)
	{
		return findFirstResource(getAllItems(E), other);
	}

	@Override
	public RawMaterial findFirstResource(final MOB E, final String other)
	{
		return findFirstResource(getAllItems(E), other);
	}

	public RawMaterial findFirstResource(final List<Item> V, String other)
	{
		if((other==null)||(other.length()==0))
			return null;
		String subType = "";
		final int x=other.indexOf('(');
		if((x>0)&&(other.endsWith(")")))
		{
			subType=other.substring(x+1,other.length()-1).toUpperCase().trim();
			other=other.substring(0, x);
		}
		final int code = RawMaterial.CODES.FIND_IgnoreCase(other);
		if(code >=0 )
			return findFirstResource(V,code, null,subType);
		return null;
	}

	@Override
	public RawMaterial findFirstResource(final Room E, final int resource)
	{
		return findFirstResource(getAllItems(E), resource, null, null);
	}

	@Override
	public RawMaterial findFirstResource(final MOB E, final int resource)
	{
		return findFirstResource(getAllItems(E), resource, null, null);
	}

	protected RawMaterial findFirstResource(final List<Item> V, final int resource, final Container C, final String subType)
	{
		final CMFlagLibrary flags=CMLib.flags();
		for(int i=0;i<V.size();i++)
		{
			final Item I=V.get(i);
			if((I instanceof RawMaterial)
			&&(I.material()==resource)
			&&((subType==null)||(((RawMaterial)I).getSubType().equalsIgnoreCase(subType)))
			&&(I.container()==C)
			&&(!flags.isOnFire(I))
			&&(!flags.isEnchanted(I)))
				return (RawMaterial)I;
		}
		return null;
	}

	protected RawMaterial findMostResource(final List<Item> V, final int resource, final Container C)
	{
		int most=0;
		int mostMaterial=-1;
		RawMaterial mostItem=null;
		final CMFlagLibrary flags=CMLib.flags();
		for(int i=0;i<V.size();i++)
		{
			final Item I=V.get(i);
			if((I instanceof RawMaterial)
			&&(I.material()==resource)
			&&(I.material()!=mostMaterial)
			&&(I.container()==C)
			&&(!flags.isOnFire(I))
			&&(!flags.isEnchanted(I)))
			{
				final int num=findNumberOfResource(V,i,(RawMaterial)I);
				if(num>most)
				{
					mostItem=(RawMaterial)I;
					most=num;
					mostMaterial=I.material();
				}
			}
		}
		return mostItem;
	}

	@Override
	public RawMaterial findMostOfMaterial(final Room E, final String other)
	{
		return findMostOfMaterial(getAllItems(E), other);
	}

	@Override
	public RawMaterial findMostOfMaterial(final MOB E, final String other)
	{
		return findMostOfMaterial(getAllItems(E), other);
	}

	protected RawMaterial findMostOfMaterial(final List<Item> V, String other)
	{
		if((other==null)||(other.length()==0))
			return null;
		String subType="";
		final int x=other.indexOf('(');
		if((x>0)&&(other.endsWith(")")))
		{
			subType=other.substring(x+1,other.length()-1).toUpperCase().trim();
			other=other.substring(0, x);
		}
		final RawMaterial.Material m=RawMaterial.Material.findIgnoreCase(other);
		if(m!=null)
			return findMostOfMaterial(V,m.mask(),subType);
		return null;
	}

	@Override
	public int findNumberOfResourceLike(final Room E, final RawMaterial resource)
	{
		return findNumberOfResource(getAllItems(E), 0, resource);
	}

	@Override
	public int findNumberOfResourceLike(final MOB E, final RawMaterial resource)
	{
		return findNumberOfResource(getAllItems(E), 0, resource);
	}

	protected int findNumberOfResource(final List<Item> V, final int startAt, final RawMaterial resource)
	{
		int foundWood=0;
		final CMFlagLibrary flags=CMLib.flags();
		for(int i=startAt;i<V.size();i++)
		{
			final Item I=V.get(i);
			if((I instanceof RawMaterial)
			&&(I.material()==resource.material())
			&&(((RawMaterial)I).getSubType().equals(resource.getSubType()))
			&&(I.rawSecretIdentity().equals(resource.rawSecretIdentity()))
			&&(I.container()==null)
			&&(!flags.isOnFire(I))
			&&(!flags.isEnchanted(I)))
				foundWood+=I.phyStats().weight();
		}
		return foundWood;
	}

	@Override
	public RawMaterial findMostOfMaterial(final Room E, final int material)
	{
		return findMostOfMaterial(getAllItems(E), material, null);
	}

	@Override
	public RawMaterial findMostOfMaterial(final MOB E, final int material)
	{
		return findMostOfMaterial(getAllItems(E), material, null);
	}

	protected RawMaterial findMostOfMaterial(final List<Item> V, final int material, final String subType)
	{
		int most=0;
		int mostMaterial=-1;
		RawMaterial mostItem=null;
		final CMFlagLibrary flags=CMLib.flags();
		for(int i=0;i<V.size();i++)
		{
			final Item I=V.get(i);
			if((I instanceof RawMaterial)
			&&(((I.material()&RawMaterial.MATERIAL_MASK)==material)
				||(I.material()==material))
			&&(I.material()!=mostMaterial)
			&&((subType==null)||(((RawMaterial)I).getSubType().equalsIgnoreCase(subType)))
			&&(I.container()==null)
			&&(!flags.isOnFire(I))
			&&(!flags.isEnchanted(I)))
			{
				final int num=findNumberOfResource(V,i,(RawMaterial)I);
				if(num>most)
				{
					mostItem=(RawMaterial)I;
					most=num;
					mostMaterial=I.material();
				}
			}
		}
		return mostItem;
	}

	@Override
	public boolean isResourceCodeRoomMapped(final int resourceCode)
	{
		final Integer I=Integer.valueOf(resourceCode);
		for(final Enumeration<Room> e=CMClass.locales();e.hasMoreElements();)
		{
			final Room R=e.nextElement();
			if(!(R instanceof GridLocale))
			{
				if((R.resourceChoices()!=null)&&(R.resourceChoices().contains(I)))
					return true;
			}
		}
		return false;
	}

	protected List<Item> getSomeRawMaterial(final Room R, final int material1, final int subTypeHash1, final int material2, final int subTypeHash2)
	{
		final List<Item> V;
		Item I=null;
		if(R!=null)
		{
			V=new ArrayList<Item>(R.numItems());
			for(int r=0;r<R.numItems();r++)
			{
				I=R.getItem(r);
				if(I instanceof RawMaterial)
				{
					final int rawMaterialCode=((RawMaterial)I).material();
					final int subHashCode = ((RawMaterial)I).getSubType().hashCode();
					if((material1 > 0)
					&&(material1==rawMaterialCode)
					&&(subHashCode == subTypeHash1))
						V.add(I);
					else
					if((material2 > 0)
					&&(material2==rawMaterialCode)
					&&(subHashCode == subTypeHash2))
						V.add(I);
				}
			}
		}
		else
			V=new ArrayList<Item>(1);
		return V;
	}

	protected List<Item> getAllRawMaterial(final Room R, final int material1, final int material2)
	{
		final List<Item> V;
		Item I=null;
		if(R!=null)
		{
			V=new ArrayList<Item>(R.numItems());
			for(int r=0;r<R.numItems();r++)
			{
				I=R.getItem(r);
				if(I instanceof RawMaterial)
				{
					final int rawMaterialCode=((RawMaterial)I).material();
					if((material1 > 0)
					&&(material1==rawMaterialCode))
						V.add(I);
					else
					if((material2 > 0)
					&&(material2==rawMaterialCode))
						V.add(I);
				}
			}
		}
		else
			V=new ArrayList<Item>(1);
		return V;
	}

	protected List<Item> getAllItems(final ItemPossessor P)
	{
		final List<Item> V;
		Item I=null;
		if(P!=null)
		{
			V=new ArrayList<Item>(P.numItems());
			for(int i=0;i<P.numItems();i++)
			{
				I=P.getItem(i);
				if(I!=null)
					V.add(I);
			}
		}
		else
			V=new ArrayList<Item>(1);
		return V;
	}

	protected List<Item> getSomeRawMaterial(final MOB M, final int material1, final int subTypeHash1, final int material2, final int subTypeHash2)
	{
		final List<Item> V=new Vector<Item>();
		Item I=null;
		if(M!=null)
		{
			for(int r=0;r<M.numItems();r++)
			{
				I=M.getItem(r);
				if((I instanceof RawMaterial)
				&&((material1==0)
					||((I.material()==material1)&&(((RawMaterial)I).getSubType().hashCode()==subTypeHash1)))
				&&((material2==0)
					||((I.material()==material2)&&(((RawMaterial)I).getSubType().hashCode()==subTypeHash2)))
				)
					V.add(I);
			}
		}
		return V;
	}

	protected List<Item> getAllRawMaterial(final MOB M, final int material1, final int material2)
	{
		final List<Item> V=new Vector<Item>();
		Item I=null;
		if(M!=null)
		{
			for(int r=0;r<M.numItems();r++)
			{
				I=M.getItem(r);
				if((I instanceof RawMaterial)
				&&((material1==0)||(I.material()==material1))
				&&((material2==0)||(I.material()==material2))
				)
					V.add(I);
			}
		}
		return V;
	}

	@Override
	public RawMaterial fetchFoundOtherEncoded(final Room E, final String otherRequired)
	{
		return fetchFoundOtherEncoded(getAllItems(E), otherRequired);
	}

	@Override
	public RawMaterial fetchFoundOtherEncoded(final MOB E, final String otherRequired)
	{
		return fetchFoundOtherEncoded(getAllItems(E), otherRequired);
	}

	protected RawMaterial fetchFoundOtherEncoded(final List<Item> V, String otherRequired)
	{
		if((otherRequired==null)||(otherRequired.trim().length()==0))
			return null;
		final boolean resourceOther=otherRequired.startsWith("!");
		if(resourceOther)
			otherRequired=otherRequired.substring(1);
		final RawMaterial firstOther;
		if(otherRequired.length()>0)
		{
			if(!resourceOther)
				firstOther=findMostOfMaterial(V,otherRequired);
			else
				firstOther=findFirstResource(V,otherRequired);
		}
		else
			firstOther=null;
		return firstOther;
	}

	@Override
	public int getBurnDuration(final Environmental E)
	{
		if(E instanceof Item)
		{
			final Item lighting=(Item)E;
			switch(lighting.material())
			{
			case RawMaterial.RESOURCE_COAL:
				if(E instanceof RawMaterial)
					return 40;
				return 20*(1+lighting.phyStats().weight());
			case RawMaterial.RESOURCE_LAMPOIL:
				return 5+lighting.phyStats().weight();
			default:
				break;
			}
			switch(lighting.material()&RawMaterial.MATERIAL_MASK)
			{
			case RawMaterial.MATERIAL_LEATHER:
				return 20+lighting.phyStats().weight();
			case RawMaterial.MATERIAL_CLOTH:
			case RawMaterial.MATERIAL_PAPER:
			case RawMaterial.MATERIAL_SYNTHETIC:
				return 5+lighting.phyStats().weight();
			case RawMaterial.MATERIAL_WOODEN:
				if(E instanceof RawMaterial)
					return 20;
				return 20*(1+lighting.phyStats().weight());
			case RawMaterial.MATERIAL_VEGETATION:
			case RawMaterial.MATERIAL_FLESH:
				return -1;
			case RawMaterial.MATERIAL_UNKNOWN:
			case RawMaterial.MATERIAL_GLASS:
			case RawMaterial.MATERIAL_LIQUID:
			case RawMaterial.MATERIAL_METAL:
			case RawMaterial.MATERIAL_ENERGY:
			case RawMaterial.MATERIAL_GAS:
			case RawMaterial.MATERIAL_MITHRIL:
			case RawMaterial.MATERIAL_ROCK:
			case RawMaterial.MATERIAL_PRECIOUS:
				return 0;
			}
		}
		return 0;
	}
}


text:
<?php

namespace Magento\Framework\View\Design\Theme\Customization;

/**
 * Theme asset file interface
 */
interface FileAssetInterface
{
    /**
     * Get content type of file
     *
     * @return string
     */
    public function getContentType();
}

redpajama_set_name: RedPajamaGithub


text:
@interface FSTBackgroundLayer : NSObject

+(CAGradientLayer*) greyGradient;
+(CAGradientLayer*) blueGradient;

@end


text:
<!doctype html>

    <title>Just the Links Options</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="/options/options.css">

    <form>

            Mode

                What text should be displayed on a page?

            <select id="mode" class="form-control">
                <option value="hyperlinks">Hyperlinks only</option>
                <option value="hyperlinks+exact">Hyperlinks + exact matches</option>
                <option value="hyperlinks+break">Hyperlinks + all words in the hyperlink</option>
            </select>

            Sites

               Sites to process.

            <textarea id="sites"
                class="form-control"
                aria-describedby="elementsHelp"></textarea>

        <button id="save">save</button>
        <button id="reset">Reset</button>
    </form>


text:
package com.infinityraider.agricraft.handler;

import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;

public class BonemealHandler {
    private static final BonemealHandler INSTANCE = new BonemealHandler();

    public static BonemealHandler getInstance() {
        return INSTANCE;
    }

    private BonemealHandler() {}

    /*
     * Event handler to deny bonemeal while sneaking on crops that are not
     * allowed to have bonemeal applied to them
     */
    @SuppressWarnings("unused")
    @SubscribeEvent(priority = EventPriority.HIGHEST)
    public void denyBonemeal(PlayerInteractEvent.RightClickBlock event) {
        if (!event.getEntityLiving().isSneaking()) {
            return;
        }
        ItemStack heldItem = event.getEntityLiving().getActiveItemStack();
        if (!heldItem.isEmpty() && heldItem.getItem() == Items.BONE_MEAL) {
            AgriApi.getCrop(event.getWorld(), event.getPos()).ifPresent(crop -> event.setUseItem(Event.Result.DENY));
        }
    }
}


text:
namespace NTPoly {
class SolverParameters;
class Matrix_ps;
////////////////////////////////////////////////////////////////////////////////
//! A Class For Computing The Square Root of a Matrix.
class SquareRootSolvers : public SolverBase {
public:
  //! Compute the square root of a matrix.
  //!\param InputMat matrix to compute the inversesquareroot of.
  //!\param OutputMat = InputMat^1/2.
  //!\param solver_parameters parameters for the solver
  static void SquareRoot(const Matrix_ps &InputMat, Matrix_ps &OutputMat,
                         const SolverParameters &solver_parameters);
  //! Compute the inverse square root of a matrix.
  //!\param InputMat matrix to compute the inversesquareroot of.
  //!\param OutputMat = InputMat^-1/2.
  //!\param solver_parameters parameters for the solver
  static void InverseSquareRoot(const Matrix_ps &InputMat, Matrix_ps &OutputMat,
                                const SolverParameters &solver_parameters);
};
} // namespace NTPoly
#endif


text:
Navd::Application.routes.draw do
  resource :dashboard, :only => [:show] do
    get :menu, :on => :member
  end
  root :to => "dashboards#show"
  match 'technoexperts' => 'pages#technoexperts'

  resources :notes, :only => [:index,:show]
  resources :memes, :only => [:index,:show] do
    resources :notes, :only => [:index,:show]
    collection do
      get :stats
      get :top
    end
    get :stat, :on => :member
  end
  resources :shows, :only => [:index,:show] do
    resources :notes, :only => [:index,:show]
    resources :memes, :only => [:index,:show]
    resources :videos, :only => [:index]
    get :mediawidget, :on => :member
    get :stat, :on => :member
  end
  resources :videos, :only => [:index]
end


text:
package com.cionik.aguit.graphics;

import com.cionik.aguit.geometry.Dimensions;

public interface Font {

	RasterFactory getPaintFactory();

	Font withPaint(RasterFactory paintFactory);

	int getSize();

	Font withSize(int size);

	int getHeight();

	int getWidth(String text);

	int getWidth(char c);

	Dimensions getDimensions(String text);

	Raster createRaster(String text);

}


text:
using System.Web.Mvc;

namespace FluentSecurity.SampleApplication.Controllers
{
	public abstract class CrudController : Controller
	{
		public ActionResult Index()
		{
			return View();
		}

		public ActionResult Create()
		{
			return View();
		}

		public ActionResult Edit()
		{
			return View();
		}

		public ActionResult Delete()
		{
			return View();
		}

		public ActionResult Details()
		{
			return View();
		}
	}
}


text:
package razerdp.basepopup;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

/**
 * Created by 大灯泡 on 2017/1/12.
 *

 * 与basePopupWindow强引用(或者说与PopupController强引用)
 */

public class PopupWindowProxy extends PopupWindow {
    private final boolean isFixAndroidN = Build.VERSION.SDK_INT == 24;
    private final boolean isOverAndroidN = Build.VERSION.SDK_INT > 24;

    private PopupController mController;

    public PopupWindowProxy(Context context, PopupController mController) {
        super(context);
        this.mController = mController;
    }

    public PopupWindowProxy(Context context, AttributeSet attrs, PopupController mController) {
        super(context, attrs);
        this.mController = mController;
    }

    public PopupWindowProxy(Context context, AttributeSet attrs, int defStyleAttr, PopupController mController) {
        super(context, attrs, defStyleAttr);
        this.mController = mController;
    }

    public PopupWindowProxy(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, PopupController mController) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.mController = mController;
    }

    public PopupWindowProxy(PopupController mController) {
        this.mController = mController;
    }

    public PopupWindowProxy(View contentView, PopupController mController) {
        super(contentView);
        this.mController = mController;
    }

    public PopupWindowProxy(int width, int height, PopupController mController) {
        super(width, height);
        this.mController = mController;
    }

    public PopupWindowProxy(View contentView, int width, int height, PopupController mController) {
        super(contentView, width, height);
        this.mController = mController;
    }

    public PopupWindowProxy(View contentView, int width, int height, boolean focusable, PopupController mController) {
        super(contentView, width, height, focusable);
        this.mController = mController;
    }

    /**
     * fix showAsDropDown when android api ver is over N
     *

     * https://code.google.com/p/android/issues/detail?id=221001
     *
     * @param anchor
     * @param xoff
     * @param yoff
     * @param gravity
     */
    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
        if (isFixAndroidN && anchor != null) {
            int[] anchorLocation = new int[2];
            anchor.getLocationInWindow(anchorLocation);
            Activity activity = (Activity) anchor.getContext();

            xoff = anchorLocation[0] + xoff;
            yoff = anchorLocation[1] + anchor.getHeight() + yoff;
            setFocusable(false);
            super.showAtLocation((activity).getWindow().getDecorView(), Gravity.NO_GRAVITY, xoff, yoff);
            initSystemBar(getContentView());
            setFocusable(true);
            update();
        } else {
            if (isOverAndroidN) {
                setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            setFocusable(false);
            super.showAsDropDown(anchor, xoff, yoff, gravity);
            initSystemBar(getContentView());
            setFocusable(true);
            update();
        }
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        setFocusable(false);
        super.showAtLocation(parent, gravity, x, y);
        initSystemBar(getContentView());
        setFocusable(true);
        update();
    }

    /**
     * 修复popup显示时退出沉浸的问题
     *
     * @param view
     */
    void initSystemBar(View view) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_FULLSCREEN;
                boolean isFullScreen = view.getSystemUiVisibility() == uiOptions;
                if (isFullScreen) {
                    hideSystemUI(view);
                } else {
                    //showSystemUI(view);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hideSystemUI(View view) {
        if (view == null) return;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
                view.setSystemUiVisibility(uiOptions);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSystemUI(View view) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                view.setSystemUiVisibility(uiOptions);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void dismiss() {
        if (mController == null) return;

        boolean performDismiss = mController.onBeforeDismiss();
        if (!performDismiss) return;
        boolean dismissAtOnce = mController.callDismissAtOnce();
        if (dismissAtOnce) {
            callSuperDismiss();
        }
    }

    void callSuperDismiss() {
        super.dismiss();
    }
}


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

namespace Crevice.GestureMachine
{
    using Crevice.Config;
    using Crevice.DSL;

    public class GestureMachineProfile
        : IDisposable
    {
        private readonly CallbackManager callbackManager = new CallbackManager();

        public readonly RootElement RootElement = new RootElement();

        public readonly GestureMachine GestureMachine;

        public readonly UserConfig UserConfig;

        public readonly string ProfileName;

        public GestureMachineProfile(string profileName)
        {
            ProfileName = profileName;
            UserConfig = new UserConfig(callbackManager.Callback);
            GestureMachine = new GestureMachine(UserConfig.Core, callbackManager);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                GestureMachine.Dispose();
                callbackManager.Dispose();
            }
        }

        ~GestureMachineProfile() => Dispose(false);
    }

    public class GestureMachineProfileManager
    {
        private readonly List<GestureMachineProfile> profiles = new List<GestureMachineProfile>();

        public IReadOnlyList<GestureMachineProfile> Profiles => profiles;

        public void DeclareProfile(string profileName)
            => profiles.Add(new GestureMachineProfile(profileName));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>shardingsphere-ui</artifactId>
        <version>5.0.0-RC1-SNAPSHOT</version>
    </parent>
    <artifactId>shardingsphere-ui-frontend</artifactId>
    <name>${project.artifactId}</name>

    <properties>
        <node.version>v8.11.1</node.version>
        <npm.version>5.6.0</npm.version>
    </properties>

    <profiles>
        <profile>
            <id>node</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>${frontend-maven-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>install node and npm</id>
                                <goals>
                                    <goal>install-node-and-npm</goal>
                                </goals>
                                <configuration>
                                    <nodeVersion>${node.version}</nodeVersion>
                                    <npmVersion>${npm.version}</npmVersion>
                                </configuration>
                            </execution>
                            <execution>
                                <id>npm run rimraf</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <configuration>
                                    <arguments>run rimraf</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>npm install</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <phase>generate-resources</phase>
                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>npm run unit</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <configuration>
                                    <arguments>run unit</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>npm run build</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <configuration>
                                    <arguments>run build</arguments>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>node-cn</id>
            <activation>
                <property>
                    <name>node</name>
                    <value>cn</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>exec-npm-install</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>cnpm</executable>
                                    <arguments>
                                        <argument>install</argument>
                                    </arguments>
                                    <workingDirectory>${basedir}</workingDirectory>
                                </configuration>
                            </execution>
                            <execution>
                                <id>exec-npm-run-unit</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>cnpm</executable>
                                    <arguments>
                                        <argument>run</argument>
                                        <argument>unit</argument>
                                    </arguments>
                                    <workingDirectory>${basedir}</workingDirectory>
                                </configuration>
                            </execution>
                            <execution>
                              <id>exec-npm-run-build</id>
                              <phase>prepare-package</phase>
                              <goals>
                                <goal>exec</goal>
                              </goals>
                              <configuration>
                                <executable>cnpm</executable>
                                <arguments>
                                  <argument>run</argument>
                                  <argument>build</argument>
                                </arguments>
                                <workingDirectory>${basedir}</workingDirectory>
                              </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
from benchmarks import silk_flags
import page_sets
from measurements import smoothness
from telemetry import benchmark

class SmoothnessTop25(benchmark.Benchmark):
  """Measures rendering statistics while scrolling down the top 25 web pages.

  http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
  test = smoothness.Smoothness
  page_set = page_sets.Top25PageSet

class SmoothnessToughFiltersCases(benchmark.Benchmark):
  test = smoothness.Smoothness
  page_set = page_sets.ToughFiltersCasesPageSet

@benchmark.Disabled('mac', 'win')  # crbug.com/388877, crbug.com/396127
class SmoothnessToughCanvasCases(benchmark.Benchmark):
  test = smoothness.Smoothness
  page_set = page_sets.ToughCanvasCasesPageSet

@benchmark.Disabled('android', 'mac')  # crbug.com/373812
class SmoothnessToughWebGLCases(benchmark.Benchmark):
  test = smoothness.Smoothness
  page_set = page_sets.ToughWebglCasesPageSet

class SmoothnessMaps(benchmark.Benchmark):
  test = smoothness.Smoothness
  page_set = page_sets.MapsPageSet

class SmoothnessKeyMobileSites(benchmark.Benchmark):
  """Measures rendering statistics while scrolling down the key mobile sites.

  http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
  test = smoothness.Smoothness
  page_set = page_sets.KeyMobileSitesPageSet

@benchmark.Disabled('android')  # crbug.com/350692
class SmoothnessToughAnimationCases(benchmark.Benchmark):
  test = smoothness.Smoothness
  page_set = page_sets.ToughAnimationCasesPageSet

class SmoothnessKeySilkCases(benchmark.Benchmark):
  """Measures rendering statistics for the key silk cases without GPU
  rasterization
  """
  test = smoothness.Smoothness
  page_set = page_sets.KeySilkCasesPageSet

class SmoothnessFastPathKeySilkCases(benchmark.Benchmark):
  """Measures rendering statistics for the key silk cases without GPU
  rasterization using bleeding edge rendering fast paths.
  """
  tag = 'fast_path'
  test = smoothness.Smoothness
  page_set = page_sets.KeySilkCasesPageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForFastPath(options)

# GPU rasterization does not work on J devices
@benchmark.Disabled('j', 'android')  # crbug.com/399125
class SmoothnessGpuRasterizationTop25(benchmark.Benchmark):
  """Measures rendering statistics for the top 25 with GPU rasterization
  """
  tag = 'gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.Top25PageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)

# GPU rasterization does not work on J devices
@benchmark.Disabled('j', 'android')  # crbug.com/399125
class SmoothnessGpuRasterizationKeyMobileSites(benchmark.Benchmark):
  """Measures rendering statistics for the key mobile sites with GPU
  rasterization
  """
  tag = 'gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.KeyMobileSitesPageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)

@benchmark.Disabled('android')  # crbug.com/399125
class SmoothnessGpuRasterizationKeySilkCases(benchmark.Benchmark):
  """Measures rendering statistics for the key silk cases with GPU rasterization
  """
  tag = 'gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.KeySilkCasesPageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)

@benchmark.Disabled('android')  # crbug.com/399125
class SmoothnessFastPathGpuRasterizationKeySilkCases(
    SmoothnessGpuRasterizationKeySilkCases):
  """Measures rendering statistics for the key silk cases with GPU rasterization
  using bleeding edge rendering fast paths.
  """
  tag = 'fast_path_gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.KeySilkCasesPageSet
  def CustomizeBrowserOptions(self, options):
    super(SmoothnessFastPathGpuRasterizationKeySilkCases, self). \
        CustomizeBrowserOptions(options)
    silk_flags.CustomizeBrowserOptionsForFastPath(options)

@benchmark.Enabled('android')
class SmoothnessSimpleMobilePages(benchmark.Benchmark):
  """Measures rendering statistics for pinch-zooming into the tough pinch zoom
  cases
  """
  test = smoothness.Smoothness
  page_set = page_sets.SimpleMobileSitesPageSet

@benchmark.Enabled('android')
class SmoothnessToughPinchZoomCases(benchmark.Benchmark):
  """Measures rendering statistics for pinch-zooming into the tough pinch zoom
  cases
  """
  test = smoothness.Smoothness
  page_set = page_sets.ToughPinchZoomCasesPageSet

class SmoothnessPolymer(benchmark.Benchmark):
  """Measures rendering statistics for Polymer cases.
  """
  test = smoothness.Smoothness
  page_set = page_sets.PolymerPageSet

class SmoothnessFastPathPolymer(benchmark.Benchmark):
  """Measures rendering statistics for the Polymer cases without GPU
  rasterization using bleeding edge rendering fast paths.
  """
  tag = 'fast_path'
  test = smoothness.Smoothness
  page_set = page_sets.PolymerPageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForFastPath(options)

# GPU rasterization does not work on J devices
@benchmark.Disabled('j', 'android')  # crbug.com/399125
class SmoothnessGpuRasterizationPolymer(benchmark.Benchmark):
  """Measures rendering statistics for the Polymer cases with GPU rasterization
  """
  tag = 'gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.PolymerPageSet
  def CustomizeBrowserOptions(self, options):
    silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)

@benchmark.Disabled('android')  # crbug.com/399125
class SmoothnessFastPathGpuRasterizationPolymer(
    SmoothnessGpuRasterizationPolymer):
  """Measures rendering statistics for the Polymer cases with GPU rasterization
  using bleeding edge rendering fast paths.
  """
  tag = 'fast_path_gpu_rasterization'
  test = smoothness.Smoothness
  page_set = page_sets.PolymerPageSet
  def CustomizeBrowserOptions(self, options):
    super(SmoothnessFastPathGpuRasterizationPolymer, self). \
        CustomizeBrowserOptions(options)
    silk_flags.CustomizeBrowserOptionsForFastPath(options)


text:
<!DOCTYPE html>
<html ng-app="blocChat">
<head lang="en">
    <meta charset="UTF-8">
    <title>Bloc Chat</title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
    <link rel="stylesheet" href="/styles/home.css">
</head>
<body>

    <ui-view></ui-view>

    	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
    	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
		<script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>
        <script src="/scripts/ui-bootstrap.js"></script>
		<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyAvQsA8XRudXjPg_wFJhWw066Ly9ug7zMU",
    authDomain: "bloc-chat-5ad53.firebaseapp.com",
    databaseURL: "https://bloc-chat-5ad53.firebaseio.com",
    projectId: "bloc-chat-5ad53",
    storageBucket: "bloc-chat-5ad53.appspot.com",
    messagingSenderId: "737048615376"
  };
  firebase.initializeApp(config);
</script>
	<script src="/scripts/app.js"></script>
    <script src="/scripts/services/Room.js"></script>
    <script src="/scripts/controllers/RoomCtrl.js"></script>
    <script src="/scripts/controllers/NewRoomCtrl.js"></script>
    <script src="/scripts/services/Messages.js"></script>
	<script src="/scripts/services/Cookies.js"></script>
	<script src="/scripts/controllers/UserNameCtrl.js"></script>

</body>
</html>


text:
#include "cld2nlpt.h"

#include <cstddef>
#include <string.h>
#include <stdio.h>
#include <string>

#include "compact_lang_det.h"

const char* CLD2_Static_ExtDetectLanguageSummary(char *data) {

    bool is_plain_text = true;
    CLD2::CLDHints cldhints = {NULL, NULL, 0, CLD2::UNKNOWN_LANGUAGE};
    bool allow_extended_lang = true;
    int flags = 0;
    CLD2::Language language3[3];
    int percent3[3];
    double normalized_score3[3];
    CLD2::ResultChunkVector resultchunkvector;
    int text_bytes;
    bool is_reliable;

    int length = strlen(data);

    CLD2::Language summary_lang = CLD2::UNKNOWN_LANGUAGE;

    summary_lang = CLD2::ExtDetectLanguageSummary(data,
            length,
            is_plain_text,
            &cldhints,
            flags,
            language3,
            percent3,
            normalized_score3,
            &resultchunkvector,
            &text_bytes,
            &is_reliable);

    return CLD2::LanguageCode(summary_lang);
}

/*
ResultChunks *CLD2_ResultChunkVector_new() {
    return static_cast<ResultChunks*>(new CLD2::ResultChunkVector());
}

const ResultChunk *CLD2_ResultChunkVector_data(const ResultChunks *chunks) {
    const CLD2::ResultChunkVector *vec =
        static_cast<const CLD2::ResultChunkVector *>(chunks);
    return static_cast<const ResultChunk*>(static_cast<const void*>(&(*vec)[0]));
}

size_t CLD2_ResultChunkVector_size(const ResultChunks *chunks) {
    const CLD2::ResultChunkVector *vec =
        static_cast<const CLD2::ResultChunkVector *>(chunks);
    return vec->size();
}

void CLD2_ResultChunkVector_delete(ResultChunks *chunks) {
    CLD2::ResultChunkVector *vec =
        static_cast<CLD2::ResultChunkVector *>(chunks);
    delete vec;
}
*/

const char* CLD2_LanguageName(Language lang) {
    return CLD2::LanguageName(lang);
}

const char* CLD2_LanguageCode(Language lang) {
    return CLD2::LanguageCode(lang);
}

const char* CLD2_LanguageDeclaredName(Language lang) {
    return CLD2::LanguageDeclaredName(lang);
}

const char* CLD2_DetectLanguageVersion() {
    return CLD2::DetectLanguageVersion();
}

Language CLD2_GetLanguageFromName(const char* src) {
    return CLD2::GetLanguageFromName(src);
}

Language CLD2_DetectLanguage(const char* buffer,int buffer_length) {
  bool is_plain_text = true;
  bool is_reliable = true;
  if (buffer_length <= 0) {
      buffer_length = strlen(buffer);
  }
  return CLD2::DetectLanguage(buffer, buffer_length, is_plain_text, &is_reliable);
}

// TODO: add support for passing language hints. will require mapping table for the c++ table of supported languages.
Language CLD2_DetectExtendLanguageSummary(const char *buffer, int buffer_length, int rank, int percent, int normal_score) {
    bool is_plain_text = true;
    bool allow_extended_lang = true;
    bool is_reliable = true;
    CLD2::CLDHints cldhints = {NULL, NULL, 0, CLD2::UNKNOWN_LANGUAGE};
    int flags = 0;
    CLD2::Language language3[rank]; //3
    int percent3[percent]; //3
    double normalized_score3[normal_score]; //3
    CLD2::ResultChunkVector resultchunkvector;
    int text_bytes;
    if (buffer_length <= 0) {
      buffer_length = strlen(buffer);
    }

    return CLD2::ExtDetectLanguageSummary(buffer,
            buffer_length,
            is_plain_text,
            &cldhints,
            flags,
            language3,
            percent3,
            normalized_score3,
            &resultchunkvector,
            &text_bytes,
            &is_reliable);
}
/*
Language CLD2_DetectLanguageSummary(const char* buffer, int buffer_length, Language* language3, int* percent3, int* text_bytes) {
  bool is_plain_text = true;
  bool is_reliable = true;
  if (buffer_length <= 0) {
      buffer_length = strlen(buffer);
  }
  return CLD2::DetectLanguageSummary(buffer,buffer_length,is_plain_text,language3,percent3,text_bytes,&is_reliable);
}

Language CLD2_DetectLanguageSummary2(const char* buffer,
                                     int buffer_length,
                                     bool is_plain_text,
                                     const char* tld_hint,
                                     int encoding_hint,
                                     Language language_hint,
                                     Language* language3,
                                     int* percent3,
                                     int* text_bytes,
                                     bool* is_reliable)
{
    return CLD2::DetectLanguageSummary(buffer, buffer_length, is_plain_text,
                                       tld_hint, encoding_hint, language_hint,
                                       language3, percent3, text_bytes,
                                       is_reliable);
}

Language CLD2_ExtDetectLanguageSummary(const char* buffer,
                                       int buffer_length,
                                       bool is_plain_text,
                                       Language* language3,
                                       int* percent3,
                                       int* text_bytes,
                                       bool* is_reliable)
{
    return CLD2::ExtDetectLanguageSummary(buffer, buffer_length, is_plain_text,
                                          language3, percent3, text_bytes,
                                          is_reliable);
}

Language CLD2_ExtDetectLanguageSummary2(const char* buffer,
                                        int buffer_length,
                                        bool is_plain_text,
                                        const char* tld_hint,
                                        int encoding_hint,
                                        Language language_hint,
                                        Language* language3,
                                        int* percent3,
                                        int* text_bytes,
                                        bool* is_reliable)
{
    return CLD2::ExtDetectLanguageSummary(buffer, buffer_length, is_plain_text,
                                          tld_hint, encoding_hint,
                                          language_hint, language3, percent3,
                                          text_bytes, is_reliable);
}

Language CLD2_ExtDetectLanguageSummary3(const char* buffer,
                                        int buffer_length,
                                        bool is_plain_text,
                                        const char* tld_hint,
                                        int encoding_hint,
                                        Language language_hint,
                                        Language* language3,
                                        int* percent3,
                                        double* normalized_score3,
                                        int* text_bytes,
                                        bool* is_reliable)
{
    return CLD2::ExtDetectLanguageSummary(buffer, buffer_length, is_plain_text,
                                          tld_hint, encoding_hint, language_hint,
                                          language3, percent3, normalized_score3,
                                          text_bytes, is_reliable);
}

Language CLD2_ExtDetectLanguageSummary4(const char* buffer,
                                        int buffer_length,
                                        bool is_plain_text,
                                        const CLDHints* cld_hints,
                                        int flags,
                                        Language* language3,
                                        int* percent3,
                                        double* normalized_score3,
                                        ResultChunks *resultchunkvector,
                                        int* text_bytes,
                                        bool* is_reliable)
{
    const CLD2::CLDHints *hints =
        static_cast<const CLD2::CLDHints *>(static_cast<const void*>(cld_hints));
    CLD2::ResultChunkVector *vec =
        static_cast<CLD2::ResultChunkVector *>(resultchunkvector);
    return CLD2::ExtDetectLanguageSummary(buffer, buffer_length, is_plain_text,
                                          hints, flags, language3, percent3,
                                          normalized_score3, vec, text_bytes,
                                          is_reliable);
}
*/


text:
namespace Cik.PP.Web.Data.Repository
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;

    public class PlanningPokerRepository : IPlanningPokerRepository
    {
        private readonly PlanningPokerContext _dbContext;
        public PlanningPokerRepository(PlanningPokerContext context)
        {
            _dbContext = context;
        }

        public IQueryable<Game> GetGames()
        {
            return _dbContext.Games;
        }

        public IQueryable<Game> GetGamesIncludeAll()
        {
            return _dbContext.Games.Include("Stories");
        }

        public Game SaveGame(Game game)
        {
            game.Id = Guid.NewGuid();
            game.Created = DateTime.UtcNow;
            var newGame = _dbContext.Games.Add(game);
            _dbContext.SaveChanges();

            return newGame;
        }

        public Game UpdateGame(Game game)
        {
            var originalGame = GetGames().FirstOrDefault(x => x.Id == game.Id);
            if (originalGame != null)
            {
                _dbContext.Entry(originalGame).CurrentValues.SetValues(game);
                _dbContext.SaveChanges();
            }

            return originalGame;
        }

        public bool DeleteGame(Guid id)
        {
            var originalGame = GetGames().FirstOrDefault(x => x.Id == id);
            _dbContext.Games.Remove(originalGame);
            _dbContext.SaveChanges();
            return true;
        }

        public Story SaveStory(Story story)
        {
            var game = _dbContext.Games.FirstOrDefault(x => x.Id == story.GameId);
            if(game == null)
                throw new NullReferenceException(string.Format("Could not find any game with Id = {0}", story.GameId));
            if(game.Stories == null) game.Stories = new Collection<Story>();
            story.Id = Guid.NewGuid();
            story.Created = DateTime.UtcNow;
            game.Stories.Add(story);
            _dbContext.SaveChanges();

            return story;
        }
    }
}


text:
layout: post
title: "CSS border"
subtitle: "The edges of the rectangle"
section: css
---

Because an HTML element is rendered as a rectangle, it can have up to **4 borders**: top, bottom, left and right. You can set a border on all sides at once, or on each side individually.

### Border types and location

A CSS border has 3 properties:

* `border-color` defined by using a [color unit](css-color-units.html)
* `border-style` can be solid, dashed, dotted...
* `border-width` defined by using a [size unit](css-size-units.html)

It also has 4 possible sides:

* `border-top`
* `border-bottom`
* `border-left`
* `border-right`

{% highlight css %}
blockquote{ border-color: yellow; border-style: solid; border-width: 1px;}
{% endhighlight %}

The shorthand property `border` allows to define all 3 properties at once:

{% highlight css %}
blockquote{ border: 1px solid yellow;}
{% endhighlight %}

### Single border

If you want to set a border on only one of the four sides, you need to include the border's **position** in the CSS property. For example, for a bottom border, you can write:

{% highlight css %}
blockquote{ border-bottom-color: yellow; border-bottom-style: solid; border-bottom-width: 1px;}
{% endhighlight %}

As for the `border` property, _each_ side has its shorthand version:

{% highlight css %}
blockquote{ border-bottom: 1px solid yellow;}
{% endhighlight %}

#### What if I want 3 borders? Do I have to set them individually?

As you would have guessed, the quickest way to have 3 borders is to set all 4 of them and then remove the one you don't want:

{% highlight css %}
blockquote{ border: 1px solid yellow; border-left: none;}
{% endhighlight %}

### Shorthand combinations

Because there exist 3 border _properties_ and 4 border _locations_, there are **12** combinations possible:

      border
      border-color
      border-style
      border-width

      border-top
      border-top-color
      border-top-style
      border-top-width

      border-bottom
      border-bottom-color
      border-bottom-style
      border-bottom-width

      border-left
      border-left-color
      border-left-style
      border-left-width

      border-right
      border-right-color
      border-right-style
      border-right-width

That's a lot of CSS properties available. You'll usually end up using the **5 shorthand versions** only:

* `border`
* `border-top`
* `border-bottom`
* `border-left`
* `border-right`


text:
%% |contourfcmap.m|: filled contour plot with precise colormap
% Author: Kelly Kearney
%
% This repository includes the code for the |contourfcmap.m| Matlab function,
% along with all dependent functions required to run it.
%
% This function creates a shaded contour map, similar to that created by
% the contourf function.  However, the relationship between a contourf plot
% and its colormap (i.e. exactly which color corresponds to each contour
% interval), can often be confusing and inconsistent.  This
% function instead allows the user to specify exactly which colors to use
% in each interval, and also to choose colors for regions that exceed the
% contour line limits.
%
%% Getting started
%
% *Prerequisites*
%
% This function requires Matlab R14 or later.
%
% *Downloading and installation*
%
% This code can be downloaded from <https://github.com/kakearney/contourfcmap-pkg/ Github>
% or the
% <http://www.mathworks.com/matlabcentral/fileexchange/29638
% MatlabCentral File Exchange>.  The File Exchange entry is updated daily
% from the GitHub repository.
%
% *Matlab Search Path*
%
% The following folders need to be added to your Matlab Search path (via
% |addpath|, |pathtool|, etc.):
%
%   contourfcmap-pkg/FEX-function_handle
%   contourfcmap-pkg/arclength
%   contourfcmap-pkg/contourcs
%   contourfcmap-pkg/contourfcmap
%   contourfcmap-pkg/distance2curve
%   contourfcmap-pkg/fillnan
%   contourfcmap-pkg/interparc
%   contourfcmap-pkg/minmax
%   contourfcmap-pkg/multiplepolyint
%   contourfcmap-pkg/parsepv
%   contourfcmap-pkg/pcolorbar

%% Syntax
%
%   contourfcmap(x,y,z,clev,cmap)
%   contourfcmap(x,y,z,clev,cmap, Name, Value)
%   h = contourfcmap(...)

%% Description
%
% |contourfcmap(x,y,z,clev,cmap)| plots a filled contour plot of the matrix
% |z| with coordinates |x| and |y|.  |z| must be at least a 2x2 matrix; |x|
% and |y| can either be matrices defining the grid for |z|, or vectors that
% correspond to the column and row coordinates, respectively. |clev| is an
% n x 1 vector defining the contour line levels, and |cmap| is an n-1 x 1
% colormap array defining the colors to be used between each of the contour
% levels.
%
% |contourfcmap(x,y,z,clev,cmap, 'lo', lo)| indicates the color value |lo|
% (a 1 x 3 RGB array) to be used for any region with data lower than the
% first contour level. Default is white.
%
% |contourfcmap(x,y,z,clev,cmap, 'hi', hi)| indicates the color value |hi|
% (a 1 x 3 RGB array) to be used for any region with data higher than the
% last contour level.  Default is white.
%
% |contourfcmap(x,y,z,clev,cmap, 'method', method)| allows
% you to switch between the 'recolor' and 'calccontour' algorithms (see
% below for details).  Default is 'recolor' (though I now recommend
% 'calccontour' for R2017b or later).
%
% |contourfcmap(x,y,z,clev,cmap, 'cbarloc', cbarloc)| adds a
% psuedo-colorbar using the colorbar location indicator |cbarloc|.  Default
% is no colorbar.
%
% |contourfcmap(x,y,z,clev,cmap, 'evencb', evencb)| indicates whether to
% space the colors on the colorbar evenly (evencb = true) or to size them
% according to the clev values (evencb = false).  Default is false.
%
% |h = contourfcmap(...)| returns a structure |h| whose fields hold the
% colorbar axis handle structure (|h.cb|, see |pcolorbar.m| for details),
% contour object (|h.h|), contour matrix (|h.c|), and patch object (|h.p|).

%% Examples
%
% First we'll plot a contourf plot using the standard Matlab functions.
% Without labeling the contour lines, it's difficult to tell which values
% in the colorbar correspond to the color intervals in the contourf plot.

count = 0;

% Data

[x,y] = meshgrid(linspace(0,1,100));
z = peaks(100);
clev = [-5 -3 -2:.5:2 3 5];

% Set up axes

h.fig = figure('color', 'w');
h.ax(1) = axes('position', [0.05  0.25 0.425 0.5]);
h.ax(2) = axes('position', [0.525 0.25 0.425 0.5]);

% Plot

axes(h.ax(1));
contourf(x,y,z,clev);
cb = colorbar('eastoutside');
colormap(h.ax(1), jet);
title(h.ax(1), 'contourf');

%%
% Using contourfcmap, we can set the colors explictly, so it's much easier
% to tell exactly which color corresponds to which value.

axes(h.ax(2));
hc = contourfcmap(x,y,z,clev,jet(12), ...
     'lo', [.8 .8 .8], ...
     'hi', [.2 .2 .2], ...
     'cbarloc', 'eastoutside', ...
     'method', 'calccontour');
title(h.ax(2), 'contourfcmap');

%%
% If you prefer, you can set the colorbar to show the contour intervals
% evenly-spaced, even if the values aren't.

delete(hc.cb.cb);
delete(hc.cb.ax);
cla;

hc = contourfcmap(x,y,z,clev,jet(12), ...
     'lo', [.8 .8 .8], ...
     'hi', [.2 .2 .2], ...
     'cbarloc', 'eastoutside', ...
     'method', 'calccontour', ...
     'evencb', true);
title(h.ax(2), 'contourfcmap');

%% The algorithms behind contourfcmap
%
% This function began its life as a very simple function back in 2010.  At
% that time, it was just a wrapper around |contourf|.  A contour
% object in Maltab circa 2010 was a combination of some lines (the
% contour lines) and some patches (the shaded regions), and my function
% just looped over those patches and assigned new colors to their CData
% properties.
%
% Then the 2014b release came along, and with it, a complete overhaul of
% Matlab's graphics objects.  Under these new second-generation handle
% graphics (i.e. HG2), contour objects became more complex.  They now were
% composed of TriangleStrips, a low-level, mostly-undocumented graphics
% object that really wasn't designed to be tampered with.
%
% I updated my function to repeat its old processes, looping over the
% contours and changing the colors.  But those color changes weren't very
% permanent. Changing the colormap, adding a colorbar, and most
% frustratingly, printing figures to file (using anything that relies on
% the print command, including print, saveas, export_fig, etc) undoes it.
% My function was pretty useless if I couldn't get changes to stick.
%
% So in 2014, I introduced a new algorithm to contourfcmap, the 'calccontour'
% method.  This version still uses the contour function to do the heavy
% lifting of the contouring calculations (contouring is hard!), but then tries to draw the
% shaded region using patches, as in the old HG1 version.  I originally
% considered this just a hacky stand-in until I could get recoloring to
% stick.  It worked pretty well for simple datasets, but fell apart for
% more complicated ones, especially those involving NaNs and non-cartesian
% grids.  But the recoloring option reset issue has persisted through newer
% releases of Matlab (actually, it's gotten worse).
%
% I've now (March 2018) just completed an overhaul of the calccontour
% option.  This update may break back-compatibility with older code that
% uses contourfcmap, since I've modified some of the output variables
% (though it should still support all the older syntax in terms of input
% variables). I've expanded the code to be much more robust to non-cartesian
% grids and NaNs, and with the introduction of polyshape objects, the
% polygon calculations no longer require the Mapping Toolbox.  Though still
% a bit slow to plot, this algorithm also fixes a few issues with the way
% Matlab colors (or rather, doesn't color) lower-than-lowest-contour
% regions.  And finally, I've altered the colorbar code to rely on my
% pcolorbar function, which provides for more robust resizing (similar to a
% real colorbar) when one makes changes to the axis.
%
% This example walks you through my thought process with this algorithm,
% and some of the issues with contourf that I'm trying to address.
%
% We'll start with the peaks data:

close all;
figure;

[x,y,z] = peaks;

hs = scatter(x(:),y(:),10,z(:),'filled');
hcb = colorbar;
set(gca, 'clim', [-15 15], 'xlim', [-4.5 4.5], 'ylim', [-4.5 4.5]);
hold on;

%%
% Most of Matlab's example contour data assumes a cartesian grid (i.e. data
% aligned along the x- and y-axes, like an image).  But it doesn't need to
% be... any structured grid will work.  Let's add some skew and rotation, to
% make sure this example covers the more complicated cases:

y = y + sin(x);
th = pi/3;
R = [cos(th) -sin(th); sin(th) cos(th)];
xy = R * [x(:) y(:)]';
x = reshape(xy(1,:), size(x));
y = reshape(xy(2,:), size(y));

delete(hs);
hs = scatter(x(:),y(:),10,z(:),'filled');

%%
% Contour data can also include NaNs.  Sometimes these represent a missing
% data point or two.  But they can also occur in bigger blocks; for
% example, a map of ocean data might represent land with NaNs.  We'll add
% both enclosed (surrounded by data) and unenclosed (connecting to side of
% grid) NaNs, and make sure we have some extra data islands of high and low
% data in there too (you'll see why in a bit):

z(z < 0.2 & z > 0) = NaN;
z(1:3,1:3) = -15;
z(end-3:end,end-3:end) = 15;
z(25:30, 1:2) = -15;

delete(hs);
hs = scatter(x(:),y(:),10,z(:),'filled');

%%
% Let's say we want to plot some contours, with specific colors between
% each interval.  We can show this by plotting a scatter plot of the
% discretized values:

% Discretize

bin = discretize(z, clev);
bin(z < clev(1)) = 0;
bin(z > clev(end)) = length(clev)+1;

% Colors

clev = [-5 -3 -2:.5:2 3 5];
cmap = [...
      0.65098      0.80784       0.8902
      0.12157      0.47059      0.70588
      0.69804      0.87451      0.54118
          0.2      0.62745      0.17255
      0.98431      0.60392          0.6
       0.8902      0.10196       0.1098
      0.99216      0.74902      0.43529
            1      0.49804            0
      0.79216      0.69804      0.83922
      0.41569      0.23922      0.60392
            1            1          0.6
      0.69412      0.34902      0.15686];
lo = [0.57255      0.58431      0.56863];
hi = [0.84706      0.86275      0.83922];

% Plot

delete(hs);
hs = scatter(x(:),y(:),10,bin(:),'filled');
colormap([lo; cmap; hi]);
set(gca, 'clim', [-0.5 length(clev)+0.5]);

tklabel = ['lo' ...
    arrayfun(@(a,b) sprintf('%.1f - %.1f',a,b), ...
             clev(1:end-1), clev(2:end), 'uni', 0) ...
    'hi'];
set(hcb, 'ticks', 0:length(clev), 'ticklabels', tklabel);

%%
% We can try to use the same discretization trick to try to get our desired
% filled contour plot.

delete(hs);
[cc, hc] = contourf(x,y,bin,0.5:1:length(clev));

%%
% But that sacrifices the resolution of the contouring.  We can also try
% fiddle with the colormap, trying to get the colors to match our contour
% levels.  I do this via the
% <https://www.mathworks.com/matlabcentral/fileexchange/28943-color-palette-tables---cpt--for-matlab cptcmap>
% function.

loval = clev(1) - (clev(end)-clev(1))*0.1;
hival = clev(end) + (clev(end)-clev(1))*0.1;

ctable = [[loval clev]' [lo;cmap;hi]*255 [clev hival]' [lo;cmap;hi]*255]';
fid = fopen('cmaptemp.cpt', 'wt');
fprintf(fid, '%.2f %.0f %.0f %.0f %.2f %.0f %.0f %.0f\n', ctable);
fclose(fid);
[cmap2, lims] = cptcmap('cmaptemp');
delete('cmaptemp.cpt');

delete(hc);
[cc, hc] = contourf(x,y,z,clev);
set(gca, 'clim', lims);
colormap(cmap2);
set(hcb, 'Ticks', clev, 'TickLabelsMode', 'auto');

%%
% That mostly works, with a few drawbacks.  First, tweaking the colormap to
% look like it has uneven color intervals requires some manaul calculation.
% Even with cptcmap, you have to do some setup ahead of time.  Also, if we
% add the scatter plot on top, we'll see a few issues:

hs = scatter(x(:), y(:), 10, z(:), 'filled');
set(hs, 'markeredgecolor', 'w');

%%
% Most of the regions match the dots... except where there should be dark
% gray contours, i.e. where the data is lower than the specified lowest
% contour.  Depending on your Matlab version, when you run this, the
% enclosed circle on the right may or may not be shaded.  In all Matlab
% versions, the unenclosed areas (the bits that hit up against the wall of
% the grid) are unshaded.
%
% So this is where the extra calculations in contourfcmap come in handy:

delete(hs);
delete(hc);
delete(hcb);

h = contourfcmap(x,y,z,clev,cmap, ...
    'lo', lo, ...
    'hi', hi, ...
    'cbarloc', 'eastoutside', ...
    'method', 'calccontour');

%%
% Verdict: It's slower than a simple contour plot.  But it colors the
% patches properly, including the lower-than-lowest-contour regions.  And
% there's no need to do any tricky colormap calculations.  If your
% application needs extremely fast rendering, and the lower-than-lowest
% thing isn't a problem for you,  you might be better off using one of the
% tricks above.  Otherwise, contourfcmap should be the easier solution.

%% Contributions
%
% Community contributions to this package are welcome!
%
% To report bugs, please submit
% <https://github.com/kakearney/contourfcmap-pkg/issues an issue> on GitHub and
% include:
%
% * your operating system
% * your version of Matlab and all relevant toolboxes (type |ver| at the Matlab command line to get this info)
% * code/data to reproduce the error or buggy behavior, and the full text of any error messages received
%
% Please also feel free to submit enhancement requests, or to send pull
% requests (via GitHub) for bug fixes or new features.
%
% I do monitor the MatlabCentral FileExchange entry for any issues raised
% in the comments, but would prefer to track issues on GitHub.
%


text:
from .api import API
#Filter NYI - not yet importing


text:
package gobblin.writer.partitioner;

import java.util.List;

import org.apache.avro.generic.GenericRecord;

import com.google.common.base.Optional;

import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.State;
import gobblin.util.AvroUtils;
import gobblin.util.ForkOperatorUtils;

/**
 * A {@link TimeBasedWriterPartitioner} for {@link GenericRecord}s.
 *
 * The {@link org.apache.avro.Schema.Field} that contains the timestamp can be specified using
 * {@link WRITER_PARTITION_COLUMNS}, and multiple values can be specified, e.g., "header.timestamp,device.timestamp".
 *
 * If multiple values are specified, they will be tried in order. In the above example, if a record contains a valid
 * "header.timestamp" field, its value will be used, otherwise "device.timestamp" will be used.
 *
 * If a record contains none of the specified fields, or if no field is specified, the current timestamp will be used.
 */
public class TimeBasedAvroWriterPartitioner extends TimeBasedWriterPartitioner<GenericRecord> {

  public static final String WRITER_PARTITION_COLUMNS = ConfigurationKeys.WRITER_PREFIX + ".partition.columns";

  private final Optional<List<String>> partitionColumns;

  public TimeBasedAvroWriterPartitioner(State state) {
    this(state, 1, 0);
  }

  public TimeBasedAvroWriterPartitioner(State state, int numBranches, int branchId) {
    super(state, numBranches, branchId);
    this.partitionColumns = getWriterPartitionColumns(state, numBranches, branchId);
  }

  private Optional<List<String>> getWriterPartitionColumns(State state, int numBranches, int branchId) {
    String propName = ForkOperatorUtils.getPropertyNameForBranch(WRITER_PARTITION_COLUMNS, numBranches, branchId);
    return state.contains(propName) ? Optional.of(state.getPropAsList(propName)) : Optional.<List<String>> absent();
  }

  @Override
  public long getRecordTimestamp(GenericRecord record) {
    return getRecordTimestamp(getWriterPartitionColumnValue(record));
  }

  /**
   *  Check if the partition column value is present and is a Long object. Otherwise, use current system time.
   */
  private long getRecordTimestamp(Optional<Object> writerPartitionColumnValue) {
    return writerPartitionColumnValue.orNull() instanceof Long ? (Long) writerPartitionColumnValue.get()
        : System.currentTimeMillis();
  }

  /**
   * Retrieve the value of the partition column field specified by this.partitionColumns
   */
  private Optional<Object> getWriterPartitionColumnValue(GenericRecord record) {
    if (!this.partitionColumns.isPresent()) {
      return Optional.absent();
    }

    for (String partitionColumn : this.partitionColumns.get()) {
      Optional<Object> fieldValue = AvroUtils.getFieldValue(record, partitionColumn);
      if (fieldValue.isPresent()) {
        return fieldValue;
      }
    }
    return Optional.absent();
  }
}