text:
package com.taobao.taokeeper.monitor.core;

import java.util.Properties;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.taobao.taokeeper.common.GlobalInstance;
import com.taobao.taokeeper.common.SystemInfo;
import com.taobao.taokeeper.common.constant.SystemConstant;
import com.taobao.taokeeper.dao.SettingsDAO;
import com.taobao.taokeeper.model.TaoKeeperSettings;
import com.taobao.taokeeper.model.type.Message;
import com.taobao.taokeeper.monitor.core.task.ZooKeeperALiveCheckerJob;
import com.taobao.taokeeper.monitor.core.task.ZooKeeperClusterMapDumpJob;
import com.taobao.taokeeper.monitor.core2.ScheduleManager;
import com.taobao.taokeeper.reporter.alarm.TbMessageSender;
import common.toolkit.java.exception.DaoException;
import common.toolkit.java.util.ObjectUtil;
import common.toolkit.java.util.StringUtil;
import common.toolkit.java.util.ThreadUtil;
import common.toolkit.java.util.db.DbcpUtil;
import common.toolkit.java.util.number.IntegerUtil;
import common.toolkit.java.util.system.SystemUtil;

/**
 * Description: System Initialization
 * @author yinshi.nc
 * @Date 2011-10-27
 */
public class Initialization extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger( Initialization.class );

	public void init() {

		/** Init threadpool */
		ThreadPoolManager.init();

		initSystem();

		// Start the job of dump db info to memeory
		Thread zooKeeperClusterMapDumpJobThread = new Thread( new ZooKeeperClusterMapDumpJob() );
		zooKeeperClusterMapDumpJobThread.start();
		try {
			// 这里等待一下,因为第一次一定要dump成功,
			// TODO 这个等待逻辑要改。
			Thread.sleep( 5000 );
		} catch ( InterruptedException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

//		ThreadUtil.startThread( new ClientThroughputStatJob() );

		/** 启动ZooKeeper数据修改通知检测 */
		ThreadUtil.startThread( new ZooKeeperALiveCheckerJob() );

		/** 启动ZooKeeper集群状态收集 */
//		ThreadUtil.startThread( new ZooKeeperStatusCollectJob() );

		/** 收集机器CPU LOAD MEMEORY */
//		ThreadUtil.startThread( new HostPerformanceCollectTask() );

        /** */
//        ThreadUtil.startThread( new HostPerformanceCollectTask() );

//        SchedulerManager.init();

//        Timer timer = new Timer();
//		//开启ZooKeeper Node的Path检查
//		timer.schedule( new ZooKeeperNodeChecker(), 5000, //
//				           BaseConstant.MILLISECONDS_OF_ONE_HOUR  *
//				           SystemConstant.HOURS_RATE_OF_ZOOKEEPER_NODE_CHECK  );

        //开启ZooKeeper RT monitor
        /*
        timer.schedule( new ZooKeeperRTCollectJob(), 5000, //
                BaseConstant.MILLISECONDS_OF_ONE_MINUTE  *
                        SystemConstant.MINS_RATE_OF_ZOOKEEPER_RT_MONITOR);
          */

		//ThreadUtil.startThread( new CheckerJob( ) );

//		ThreadUtil.startThread( new CheckerJob( "/jingwei-v2/tasks/DAILY-TMALL-DPC-META/locks" ) );

		ScheduleManager.init();

		LOG.info( "*********************************************************" );
		LOG.info( "****************TaoKeeper Startup Success****************" );
		LOG.info( "*********************************************************" );
		LOG.info( "任何建议与问题,请到 http://jm-blog.aliapp.com/?p=1450 进行反馈。" );
	}

	/**
	 * 从数据库加载并初始化系统配置
	 */
	private void initSystem() {

		LOG.info( "=================================Start to init system===========================" );
		Properties properties = null;
		try {
			properties = SystemUtil.loadProperty();
			if ( ObjectUtil.isBlank( properties ) )
				throw new Exception( "Please defined,such as -DconfigFilePath=\"W:\\TaoKeeper\\taokeeper\\config\\config-test.properties\"" );
		} catch ( Exception e ) {
			LOG.error( e.getMessage() );
			throw new RuntimeException( e.getMessage(), e.getCause() );
		}

		SystemInfo.envName = StringUtil.defaultIfBlank( properties.getProperty( "systemInfo.envName" ), "TaoKeeper-Deploy" );

		DbcpUtil.driverClassName = StringUtil.defaultIfBlank( properties.getProperty( "dbcp.driverClassName" ), "com.mysql.jdbc.Driver" );
		DbcpUtil.dbJDBCUrl = StringUtil.defaultIfBlank( properties.getProperty( "dbcp.dbJDBCUrl" ), "jdbc:mysql://127.0.0.1:3306/taokeeper" );
		DbcpUtil.characterEncoding = StringUtil.defaultIfBlank( properties.getProperty( "dbcp.characterEncoding" ), "UTF-8" );
		DbcpUtil.username = StringUtil.trimToEmpty( properties.getProperty( "dbcp.username" ) );
		DbcpUtil.password = StringUtil.trimToEmpty( properties.getProperty( "dbcp.password" ) );
		DbcpUtil.maxActive = IntegerUtil.defaultIfError( properties.getProperty( "dbcp.maxActive" ), 30 );
		DbcpUtil.maxIdle = IntegerUtil.defaultIfError( properties.getProperty( "dbcp.maxIdle" ), 10 );
		DbcpUtil.maxWait = IntegerUtil.defaultIfError( properties.getProperty( "dbcp.maxWait" ), 10000 );

		SystemConstant.dataStoreBasePath = StringUtil.defaultIfBlank( properties.getProperty( "SystemConstent.dataStoreBasePath" ),
				"/home/yinshi.nc/taokeeper-monitor/" );
		SystemConstant.userNameOfSSH = StringUtil.defaultIfBlank( properties.getProperty( "SystemConstant.userNameOfSSH" ), "admin" );
		SystemConstant.passwordOfSSH = StringUtil.defaultIfBlank( properties.getProperty( "SystemConstant.passwordOfSSH" ), "123456" );
		SystemConstant.portOfSSH = IntegerUtil.defaultIfError( properties.getProperty( "SystemConstant.portOfSSH" ), 22 );

		SystemConstant.IP_OF_MESSAGE_SEND = StringUtil.trimToEmpty( properties.getProperty( "SystemConstant.IP_OF_MESSAGE_SEND" ) );

		LOG.info( "=================================Finish init system===========================" );
		ThreadPoolManager.addJobToMessageSendExecutor( new TbMessageSender( new Message( "银时", "TaoKeeper启动", "TaoKeeper启动",
				Message.MessageType.WANGWANG ) ) );

		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		SettingsDAO settingsDAO = ( SettingsDAO ) wac.getBean( "taoKeeperSettingsDAO" );

		TaoKeeperSettings taoKeeperSettings = null;
		try {
			taoKeeperSettings = settingsDAO.getTaoKeeperSettingsBySettingsId( 1 );
		} catch ( DaoException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if ( null != taoKeeperSettings )
			GlobalInstance.taoKeeperSettings = taoKeeperSettings;

	}

}


text:
package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
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.Libraries.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.util.*;

public class Disease_Vampirism extends Disease
{
	@Override
	public String ID()
	{
		return "Disease_Vampirism";
	}

	private final static String	localizedName	= CMLib.lang().L("Vampirism");

	@Override
	public String name()
	{
		return localizedName;
	}

	private final static String	localizedStaticDisplay	= CMLib.lang().L("(Vampirism)");

	@Override
	public String displayText()
	{
		return localizedStaticDisplay;
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_MOBS;
	}

	@Override
	protected int canTargetCode()
	{
		return CAN_MOBS;
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_MALICIOUS;
	}

	@Override
	public boolean putInCommandlist()
	{
		return false;
	}

	@Override
	protected int DISEASE_TICKS()
	{
		return CMProps.getIntVar(CMProps.Int.TICKSPERMUDDAY) * 6;
	}

	@Override
	protected int DISEASE_DELAY()
	{
		return CMProps.getIntVar(CMProps.Int.TICKSPERMUDDAY);
	}

	@Override
	protected String DISEASE_DONE()
	{
		return L("Your vampirism lifts.");
	}

	@Override
	protected String DISEASE_START()
	{
		return L("^G<S-NAME> seem(s) pale and cold.^?");
	}

	@Override
	protected String DISEASE_AFFECT()
	{
		return "";
	}

	@Override
	public int spreadBitmap()
	{
		return DiseaseAffect.SPREAD_CONSUMPTION;
	}

	@Override
	public int difficultyLevel()
	{
		return 9;
	}

	protected final static String cancelID="Spell_DarkSensitivity";

	protected volatile int	prevEat			= 1;
	protected int			chaBonus		= 0;
	protected boolean		bloodHeal		= true;
	protected boolean		bloodThirst		= true;
	protected boolean		lightSensitive	= true;
	protected boolean		noSwim			= true;
	protected boolean		drinkMobs		= true;

	@Override
	public void setMiscText(final String newMiscText)
	{
		super.setMiscText(newMiscText);
		chaBonus = CMParms.getParmInt(newMiscText, "CHABONUS", -1);
		bloodHeal = CMParms.getParmBool(newMiscText, "BLOODHEAL", true);
		bloodThirst = CMParms.getParmBool(newMiscText, "BLOODTHIRST", true);
		lightSensitive = CMParms.getParmBool(newMiscText, "LOWLIGHT", true);
		noSwim = CMParms.getParmBool(newMiscText, "NOSWIM", true);
		drinkMobs = CMParms.getParmBool(newMiscText, "DRINKMOBS", true);
	}

	@Override
	public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
		if((!(affected instanceof MOB))||(!lightSensitive))
			return;
		if(((MOB)affected).location()==null)
			return;
		if(CMLib.flags().isInDark(((MOB)affected).location()))
			affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_SEE_DARK);
		else
		{
			affectableStats.setAttackAdjustment(affectableStats.attackAdjustment()-50);
			affectableStats.setArmor(affectableStats.armor()+50);
		}
	}

	protected boolean isLightBlind(final MOB M)
	{
		if(!lightSensitive)
			return false;
		final Room R=M.location();
		if(R==null)
			return true;
		return !CMLib.flags().isInDark(R);
	}

	protected boolean isCharmedBy(final MOB M, final MOB mob)
	{
		final List<Ability> chAs = CMLib.flags().flaggedAffects(M, Ability.FLAG_CHARMING);
		if(chAs == null)
			return false;
		for(final Ability A : chAs)
		{
			if(A.invoker()==mob)
				return true;
		}
		return false;
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!super.okMessage(myHost, msg))
			return false;
		if(msg.source()==affected)
		{
			if((noSwim)
			&&(msg.tool() instanceof Ability)
			&&(msg.tool().ID().equals("Skill_Swim")))
			{
				msg.source().tell(L("You can't swim!"));
				return false;
			}
			switch(msg.sourceMinor())
			{
			case CMMsg.TYP_DRINK:
			{
				if(msg.target() instanceof Drink)
					this.prevEat = ((Drink)msg.target()).thirstQuenched();
				else
				if((msg.target() instanceof MOB) && (drinkMobs))
				{
						final MOB mob=msg.source();
						final Room R=mob.location();
					final MOB M=(MOB)msg.target();
					if((M!=null)
					&&(CMLib.flags().canBeSeenBy(M, mob))
					&&(M!=mob))
					{
						if(CMLib.flags().isGolem(M) || CMLib.flags().isAPlant(M))
							mob.tell(L("@x1 is bloodless.",M.name(mob)));
						else
						if((!CMLib.flags().isSleeping(M))
						&&(!CMLib.flags().isBoundOrHeld(M))
						&&(!isCharmedBy(M,mob)))
							mob.tell(L("@x1 won't let you.",M.name(mob)));
						else
						{
							final Drink dr = (Drink)CMClass.getItem("GenLiquidResource");
							dr.setLiquidType(RawMaterial.RESOURCE_BLOOD);
							final int heal = CMLib.dice().roll(1, M.phyStats().level(), 4);
							dr.setLiquidHeld(heal);
							dr.setLiquidRemaining(heal);
							dr.setThirstQuenched(heal);
							((Item)dr).setMaterial(RawMaterial.RESOURCE_BLOOD);
							((Item)dr).basePhyStats().setWeight(heal);
							((Item)dr).phyStats().setWeight(heal);
							final CMMsg dmsg = CMClass.getMsg(mob, dr, M,
									CMMsg.MASK_MALICIOUS|CMMsg.MSG_DRINK,
									CMMsg.MASK_MALICIOUS|CMMsg.MSG_DRINK,
									CMMsg.MASK_MALICIOUS|CMMsg.MSG_DRINK,
									L("<S-NAME> drink(s) <O-YOUPOSS> blood."));
							if(R.okMessage(mob, dmsg))
							{
								R.send(mob, dmsg);
								final Map<MOB,MOB> vicMap = new HashMap<MOB,MOB>();
								for(final Enumeration<MOB> m = R.inhabitants();m.hasMoreElements();)
								{
									final MOB M1=m.nextElement();
									if(M1!=null)
										vicMap.put(M1, M1.getVictim());
								}
								final int dmg = CMLib.dice().roll(1, Math.min(16, M.phyStats().level()), Math.min(16, M.phyStats().level())/4);
								CMLib.combat().postDamage(mob, M, null, dmg, CMMsg.TYP_JUSTICE, Weapon.TYPE_NATURAL, null);
								for(final MOB M1 : vicMap.keySet())
								{
									final MOB vicM = vicMap.get(M1);
									if(M1.getVictim()!=vicM)
										M1.setVictim(vicM);
								}
								if(CMLib.flags().isSleeping(M))
									CMLib.commands().postStand(M, true, true);
							}
						}
						return false;
					}
				}
				break;
			}
			case CMMsg.TYP_EXAMINE:
				if(isLightBlind(msg.source())
				&& (!(msg.target() instanceof Room))
				&&(msg.source().fetchEffect(cancelID)==null))
				{
					msg.source().tell(L("You can't seem to make it out that well in this bright light."));
					return false;
				}
				break;
			case CMMsg.TYP_JUSTICE:
			{
				if(!msg.targetMajor(CMMsg.MASK_DELICATE))
					return true;
			}
				//$FALL-THROUGH$
			case CMMsg.TYP_DELICATE_HANDS_ACT:
			case CMMsg.TYP_CAST_SPELL:
			{
				if((msg.target()!=null)
				&&(msg.target()!=msg.source())
				&&(!(msg.target() instanceof Room))
				&&(isLightBlind(msg.source()))
				&&(msg.source().fetchEffect(cancelID)==null))
				{
					msg.source().tell(msg.source(),msg.target(),null,L("You can't seem to make out <T-NAME> in this bright light."));
					return false;
				}
				break;
			}
			case CMMsg.TYP_EAT:
			{
				if(msg.target() instanceof Food)
				{
					final Food fI=(Food)msg.target();
					int amountEaten=fI.bite();
					if((amountEaten<1)||(amountEaten>fI.nourishment()))
						amountEaten=fI.nourishment();
					this.prevEat = amountEaten;
				}
				break;
			}
			/*
			case CMMsg.TYP_DRINK:
			{
				if(msg.target() instanceof Drink)
					this.prevEat = ((Drink)msg.target()).thirstQuenched();
				break;
			}
			*/
			}
		}
		return true;
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		super.okMessage(myHost, msg);
		if(((msg.targetMinor()==CMMsg.TYP_EAT)
			||(msg.targetMinor()==CMMsg.TYP_DRINK))
		&&(msg.source()==affected)
		&&(affected instanceof MOB)
		&&(msg.target() instanceof Item))
		{
			final MOB mob=msg.source();
			final Item I=(Item)msg.target();
			if((I.material()==RawMaterial.RESOURCE_BLOOD)
			||((I instanceof Drink)&&(((Drink)I).liquidType()==RawMaterial.RESOURCE_BLOOD)))
			{
				if (I.fetchEffect("Poison_Rotten")==null)
				{
					if(bloodThirst)
					{
						if(I instanceof Food)
							mob.curState().adjThirst(prevEat*2,mob.maxState().maxThirst(mob.baseWeight()));
						else
						if(I instanceof Drink)
							mob.curState().adjHunger(prevEat/2,mob.maxState().maxHunger(mob.baseWeight()));
					}
					if(bloodHeal)
					{
						final CMMsg msg2 = CMClass.getMsg(msg.source(),mob,msg.tool(),CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,CMMsg.MSG_HEALING,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null);
						msg2.setValue(prevEat);
						final Room R=CMLib.map().roomLocation(mob);
						if((R!=null)
						&&(R.okMessage(mob,msg2)))
							R.send(mob, msg2);
					}
				}
			}
			else
			if(bloodThirst)
			{
				if(I instanceof Food)
					mob.curState().adjHunger(-prevEat,mob.maxState().maxHunger(mob.baseWeight()));
				else
				if(I instanceof Drink)
					mob.curState().adjThirst(-prevEat,mob.maxState().maxThirst(mob.baseWeight()));
			}
		}
	}

	@Override
	public void affectCharStats(final MOB affected, final CharStats affectableStats)
	{
		super.affectCharStats(affected,affectableStats);
		if((affected==null)||(chaBonus==0))
			return;
		affectableStats.setStat(CharStats.STAT_CHARISMA,affectableStats.getStat(CharStats.STAT_CHARISMA)+chaBonus);
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.

package bolthold

import (
	"fmt"
	"reflect"
	"regexp"
	"strings"
	"unicode"
)

const (
	eq    = iota //==
	ne           // !=
	gt           // >
	lt           // <
	ge           // >=
	le           // <=
	in           // in
	re           // regular expression
	fn           // func
	isnil        // test's for nil
	hk           // match map keys

	contains // slice only
	any      // slice only
	all      // slice only
)

// Key is shorthand for specifying a query to run again the Key in a bolthold, simply returns ""
// Where(bolthold.Key).Eq("testkey")
const Key = ""

// BoltholdKeyTag is the struct tag used to define an a field as a key for use in a Find query
const BoltholdKeyTag = "boltholdKey"

// Query is a chained collection of criteria of which an object in the bolthold needs to match to be returned
// an empty query matches against all records
type Query struct {
	index         string
	currentField  string
	fieldCriteria map[string][]*Criterion
	ors           []*Query

	badIndex bool
	dataType reflect.Type
	source   BucketSource

	limit   int
	skip    int
	sort    []string
	reverse bool
}

// IsEmpty returns true if the query is an empty query
// an empty query matches against everything
func (q *Query) IsEmpty() bool {
	if q.index != "" {
		return false
	}
	if len(q.fieldCriteria) != 0 {
		return false
	}

	if q.ors != nil {
		return false
	}

	return true
}

// Criterion is an operator and a value that a given field needs to match on
type Criterion struct {
	query    *Query
	operator int
	value    interface{}
	values   []interface{}
	negate   bool
}

func hasMatchFunc(criteria []*Criterion) bool {
	for _, c := range criteria {
		if c.operator == fn {
			return true
		}
	}
	return false
}

// Slice turns a slice of any time into []interface{} by copying the slice values so it can be easily passed
// into queries that accept variadic parameters.
// Will panic if value is not a slice
func Slice(value interface{}) []interface{} {
	slc := reflect.ValueOf(value)

	s := make([]interface{}, slc.Len(), slc.Len()) // panics if value is not slice, array or map
	for i := range s {
		s[i] = slc.Index(i).Interface()
	}
	return s
}

// Field allows for referencing a field in structure being compared
type Field string

// Where starts a query for specifying the criteria that an object in the bolthold needs to match to
// be returned in a Find result
/*
Query API Example

	s.Find(bolthold.Where("FieldName").Eq(value).And("AnotherField").Lt(AnotherValue).Or(bolthold.Where("FieldName").Eq(anotherValue)

Since Gobs only encode exported fields, this will panic if you pass in a field with a lower case first letter
*/
func Where(field string) *Criterion {
	if !startsUpper(field) {
		panic("The first letter of a field in a bolthold query must be upper-case")
	}

	return &Criterion{
		query: &Query{
			currentField:  field,
			fieldCriteria: make(map[string][]*Criterion),
		},
	}
}

// And creates a nother set of criterion the needs to apply to a query
func (q *Query) And(field string) *Criterion {
	if !startsUpper(field) {
		panic("The first letter of a field in a bolthold query must be upper-case")
	}

	if q.fieldCriteria == nil {
		q.fieldCriteria = make(map[string][]*Criterion)
	}

	q.currentField = field
	return &Criterion{
		query: q,
	}
}

// Skip skips the number of records that match all the rest of the query criteria, and does not return them
// in the result set.  Setting skip multiple times, or to a negative value will panic
func (q *Query) Skip(amount int) *Query {
	if amount < 0 {
		panic("Skip must be set to a positive number")
	}

	if q.skip != 0 {
		panic(fmt.Sprintf("Skip has already been set to %d", q.skip))
	}

	q.skip = amount

	return q
}

// Limit sets the maximum number of records that can be returned by a query
// Setting Limit multiple times, or to a negative value will panic
func (q *Query) Limit(amount int) *Query {
	if amount < 0 {
		panic("Limit must be set to a positive number")
	}

	if q.limit != 0 {
		panic(fmt.Sprintf("Limit has already been set to %d", q.limit))
	}

	q.limit = amount

	return q
}

// SortBy sorts the results by the given fields name
// Multiple fields can be used
func (q *Query) SortBy(fields ...string) *Query {
	for i := range fields {
		if fields[i] == Key {
			panic("Cannot sort by Key.")
		}
		found := false
		for k := range q.sort {
			if q.sort[k] == fields[i] {
				found = true
				break
			}
		}
		if !found {
			q.sort = append(q.sort, fields[i])
		}
	}
	return q
}

// Reverse will reverse the current result set
// useful with SortBy
func (q *Query) Reverse() *Query {
	q.reverse = !q.reverse
	return q
}

// Index specifies the index to use when running this query
func (q *Query) Index(indexName string) *Query {
	q.index = indexName
	return q
}

// Or creates another separate query that gets unioned with any other results in the query
// Or will panic if the query passed in contains a limit or skip value, as they are only
// allowed on top level queries
func (q *Query) Or(query *Query) *Query {
	if query.skip != 0 || query.limit != 0 {
		panic("Or'd queries cannot contain skip or limit values")
	}
	q.ors = append(q.ors, query)
	return q
}

func (q *Query) matchesAllFields(s *Store, key []byte, value reflect.Value, currentRow interface{}) (bool, error) {
	if q.IsEmpty() {
		return true, nil
	}

	for field, criteria := range q.fieldCriteria {
		if field == q.index && !q.badIndex {
			// already handled by index Iterator
			continue
		}

		if field == Key {
			ok, err := matchesAllCriteria(s, criteria, key, true, currentRow)
			if err != nil {
				return false, err
			}
			if !ok {
				return false, nil
			}

			continue
		}

		fVal, err := fieldValue(value, field)
		if err != nil {
			return false, err
		}

		ok, err := matchesAllCriteria(s, criteria, fVal, false, currentRow)
		if err != nil {
			return false, err
		}
		if !ok {
			return false, nil
		}
	}

	return true, nil
}

func fieldValue(value reflect.Value, field string) (interface{}, error) {
	current := value

	if current.Kind() == reflect.Ptr {
		if current.IsNil() {
			return reflect.Value{}, nil
		}
		current = current.Elem()
	}

	if field == "" {
		if !value.IsValid() {
			return reflect.Value{}, fmt.Errorf("The field %s does not exist in the type %s", field,
				value.Interface())
		}
		return value.Interface(), nil
	}

	split := strings.SplitN(field, ".", 2)

	currentField := split[0]
	remainder := ""
	if len(split) != 1 {
		remainder = split[1]
	}

	typ := current.Type()
	f, ok := typ.FieldByNameFunc(func(name string) bool {
		return name == currentField
	})

	if !ok {
		return reflect.Value{}, fmt.Errorf("The field %s does not exist in the type %s", field,
			value.Interface())
	}

	// test is any fields in this index chain are anonymous and nil
	v := current
	for _, index := range f.Index {
		vField := v.Field(index)
		if vField.Kind() == reflect.Ptr {
			if vField.IsNil() {
				return reflect.Value{}, nil
			}
			vField = vField.Elem()
		}
		v = vField
	}

	return fieldValue(current.FieldByIndex(f.Index), remainder)

}

func (c *Criterion) op(op int, value interface{}) *Query {
	c.operator = op
	c.value = value

	q := c.query
	q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c)

	return q
}

// Eq tests if the current field is Equal to the passed in value
func (c *Criterion) Eq(value interface{}) *Query {
	return c.op(eq, value)
}

// Ne test if the current field is Not Equal to the passed in value
func (c *Criterion) Ne(value interface{}) *Query {
	return c.op(ne, value)
}

// Gt test if the current field is Greater Than the passed in value
func (c *Criterion) Gt(value interface{}) *Query {
	return c.op(gt, value)
}

// Lt test if the current field is Less Than the passed in value
func (c *Criterion) Lt(value interface{}) *Query {
	return c.op(lt, value)
}

// Ge test if the current field is Greater Than or Equal To the passed in value
func (c *Criterion) Ge(value interface{}) *Query {
	return c.op(ge, value)
}

// Le test if the current field is Less Than or Equal To the passed in value
func (c *Criterion) Le(value interface{}) *Query {
	return c.op(le, value)
}

// In test if the current field is a member of the slice of values passed in
func (c *Criterion) In(values ...interface{}) *Query {
	c.operator = in
	c.values = values

	q := c.query
	q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c)

	return q
}

// HasKey tests if the field has a map key matching the passed in value
func (c *Criterion) HasKey(value interface{}) *Query {
	return c.op(hk, value)
}

// RegExp will test if a field matches against the regular expression
// The Field Value will be converted to string (%s) before testing
func (c *Criterion) RegExp(expression *regexp.Regexp) *Query {
	return c.op(re, expression)
}

// IsNil will test if a field is equal to nil
func (c *Criterion) IsNil() *Query {
	return c.op(isnil, nil)
}

// Not will negate the following critierion
func (c *Criterion) Not() *Criterion {
	c.negate = !c.negate
	return c
}

// Contains tests if the current field is a slice that contains the passed in value
func (c *Criterion) Contains(value interface{}) *Query {
	return c.op(contains, value)
}

// ContainsAll tests if the current field is a slice that contains all of the passed in values.  If any of the
// values are NOT contained in the slice, then no match is made
func (c *Criterion) ContainsAll(values ...interface{}) *Query {
	c.operator = all
	c.values = values

	q := c.query
	q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c)

	return q
}

// ContainsAny tests if the current field is a slice that contains any of the passed in values.  If any of the
// values are contained in the slice, then a match is made
func (c *Criterion) ContainsAny(values ...interface{}) *Query {
	c.operator = any
	c.values = values

	q := c.query
	q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c)

	return q
}

// MatchFunc is a function used to test an arbitrary matching value in a query
type MatchFunc func(ra interface{}) (bool, error)

// RecordAccess allows access to the current record, field or allows running a subquery within a
// MatchFunc
type RecordAccess struct {
	source BucketSource
	s      *Store
	record interface{}
	field  interface{}
}

// Field is the current field being queried
func (r *RecordAccess) Field() interface{} {
	return r.field
}

// Record is the complete record for a given row in bolthold
func (r *RecordAccess) Record() interface{} {
	return r.record
}

// SubQuery allows you to run another query in the same transaction for each
// record in a parent query
func (r *RecordAccess) SubQuery(result interface{}, query *Query) error {
	return r.s.findQuery(r.source, result, query)
}

// SubAggregateQuery allows you to run another aggregate query in the same transaction for each
// record in a parent query
func (r *RecordAccess) SubAggregateQuery(query *Query, groupBy ...string) ([]*AggregateResult, error) {
	return r.s.aggregateQuery(r.source, r.record, query, groupBy...)
}

// MatchFunc will test if a field matches the passed in function
func (c *Criterion) MatchFunc(match interface{}) *Query {
	if c.query.currentField == Key {
		panic("Match func cannot be used against Keys, as the Key type is unknown at runtime, and there is no value compare against")
	}

	return c.op(fn, match)
}

// test if the criterion passes with the passed in value
func (c *Criterion) test(s *Store, testValue interface{}, encoded bool, currentRow interface{}) (bool, error) {
	var recordValue interface{}
	if encoded {
		if len(testValue.([]byte)) != 0 {
			// used with keys
			if c.operator == in || c.operator == any || c.operator == all {
				// value is a slice of values, use c.values
				recordValue = newElemType(c.values[0])
			} else {
				recordValue = newElemType(c.value)
			}
			err := s.decode(testValue.([]byte), recordValue)
			if err != nil {
				return false, err
			}
		}

	} else {
		recordValue = testValue
	}

	switch c.operator {
	case in:
		for i := range c.values {
			result, err := c.compare(recordValue, c.values[i], currentRow)
			if err != nil {
				return false, err
			}
			if result == 0 {
				return true, nil
			}
		}

		return false, nil
	case hk:
		v := reflect.ValueOf(recordValue).MapIndex(reflect.ValueOf(c.value))
		return !reflect.ValueOf(v).IsZero(), nil
	case re:
		return c.value.(*regexp.Regexp).Match([]byte(fmt.Sprintf("%s", recordValue))), nil
	case fn:
		fnVal := reflect.ValueOf(c.value)
		fnType := reflect.TypeOf(c.value)
		ra := &RecordAccess{
			s:      s,
			field:  recordValue,
			record: currentRow,
			source: c.query.source,
		}

		var out []reflect.Value

		if fnType.In(0) == reflect.TypeOf(ra) {
			out = fnVal.Call([]reflect.Value{reflect.ValueOf(ra)})
		}

		if fnType.In(0) == reflect.TypeOf(ra.field) {
			out = fnVal.Call([]reflect.Value{reflect.ValueOf(ra.field)})
		}
		if fnType.In(0) == reflect.TypeOf(ra.record) {
			out = fnVal.Call([]reflect.Value{reflect.ValueOf(ra.record)})
		}

		if len(out) != 2 {
			return false, fmt.Errorf("MatchFunc does not return (bool, error)")
		}

		if out[1].IsNil() {
			return out[0].Interface().(bool), nil
		}
		return false, out[1].Interface().(error)
	case isnil:
		return reflect.ValueOf(recordValue).IsNil(), nil
	case contains, any, all:
		slc := reflect.ValueOf(recordValue)
		kind := slc.Kind()
		if kind != reflect.Slice && kind != reflect.Array {
			// make slice containing recordValue
			for slc.Kind() == reflect.Ptr {
				slc = slc.Elem()
			}
			slc = reflect.Append(reflect.MakeSlice(reflect.SliceOf(slc.Type()), 0, 1), slc)
		}

		if c.operator == contains {
			for i := 0; i < slc.Len(); i++ {
				result, err := c.compare(slc.Index(i), c.value, currentRow)
				if err != nil {
					return false, err
				}
				if result == 0 {
					return true, nil
				}
			}
			return false, nil
		}

		if c.operator == any {
			for i := 0; i < slc.Len(); i++ {
				for k := range c.values {
					result, err := c.compare(slc.Index(i), c.values[k], currentRow)
					if err != nil {
						return false, err
					}
					if result == 0 {
						return true, nil
					}
				}
			}

			return false, nil
		}

		// c.operator == all {
		for k := range c.values {
			found := false
			for i := 0; i < slc.Len(); i++ {
				result, err := c.compare(slc.Index(i), c.values[k], currentRow)
				if err != nil {
					return false, err
				}
				if result == 0 {
					found = true
					break
				}
			}
			if !found {
				return false, nil
			}
		}

		return true, nil

	default:
		//comparison operators
		result, err := c.compare(recordValue, c.value, currentRow)
		if err != nil {
			return false, err
		}

		switch c.operator {
		case eq:
			return result == 0, nil
		case ne:
			return result != 0, nil
		case gt:
			return result > 0, nil
		case lt:
			return result < 0, nil
		case le:
			return result < 0 || result == 0, nil
		case ge:
			return result > 0 || result == 0, nil
		default:
			panic("invalid operator")
		}
	}
}

func matchesAllCriteria(s *Store, criteria []*Criterion, value interface{}, encoded bool,
	currentRow interface{}) (bool, error) {
	for i := range criteria {
		ok, err := criteria[i].test(s, value, encoded, currentRow)
		if err != nil {
			return false, err
		}

		if criteria[i].negate == ok {
			return false, nil
		}
	}

	return true, nil
}

func startsUpper(str string) bool {
	if str == "" {
		return true
	}

	for _, r := range str {
		return unicode.IsUpper(r)
	}

	return false
}

func (q *Query) String() string {
	s := ""

	if q.index != "" {
		s += "Using Index [" + q.index + "] "
	}

	s += "Where "
	for field, criteria := range q.fieldCriteria {
		for i := range criteria {
			s += field + " " + criteria[i].String()
			s += "\n\tAND "
		}
	}

	// remove last AND
	s = s[:len(s)-6]

	for i := range q.ors {
		s += "\nOr " + q.ors[i].String()
	}

	return s
}

func (c *Criterion) String() string {
	s := ""
	if c.negate {
		s += "NOT "
	}
	switch c.operator {
	case eq:
		s += "=="
	case ne:
		s += "!="
	case gt:
		s += ">"
	case lt:
		s += "<"
	case le:
		s += "<="
	case ge:
		s += ">="
	case in:
		return "in " + fmt.Sprintf("%v", c.values)
	case re:
		s += "matches the regular expression"
	case fn:
		s += "matches the function"
	case isnil:
		return "is nil"
	case contains:
		s += "contains"
	case any:
		return "contains any of " + fmt.Sprintf("%v", c.values)
	case all:
		return "contains all of " + fmt.Sprintf("%v", c.values)
	default:
		panic("invalid operator")
	}
	return s + " " + fmt.Sprintf("%v", c.value)
}


text:
<resources>
    <string name="app_name">CatalogoWeb</string>
    <string name="title_activity_detalhe">Mercadoria Detalhe</string>
</resources>


text:
using System.Diagnostics.Contracts;

namespace System.Net.Http.Headers
{
    public class ProductInfoHeaderValue : ICloneable
    {
        private ProductHeaderValue _product;
        private string _comment;

        public ProductHeaderValue Product
        {
            get { return _product; }
        }

        public string Comment
        {
            get { return _comment; }
        }

        public ProductInfoHeaderValue(string productName, string productVersion)
            : this(new ProductHeaderValue(productName, productVersion))
        {
        }

        public ProductInfoHeaderValue(ProductHeaderValue product)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            _product = product;
        }

        public ProductInfoHeaderValue(string comment)
        {
            HeaderUtilities.CheckValidComment(comment, "comment");
            _comment = comment;
        }

        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Contract.Requires(source != null);

            _product = source._product;
            _comment = source._comment;
        }

        private ProductInfoHeaderValue()
        {
        }

        public override string ToString()
        {
            if (_product == null)
            {
                return _comment;
            }
            return _product.ToString();
        }

        public override bool Equals(object obj)
        {
            ProductInfoHeaderValue other = obj as ProductInfoHeaderValue;

            if (other == null)
            {
                return false;
            }

            if (_product == null)
            {
                // We compare comments using case-sensitive comparison.
                return string.Equals(_comment, other._comment, StringComparison.Ordinal);
            }

            return _product.Equals(other._product);
        }

        public override int GetHashCode()
        {
            if (_product == null)
            {
                return _comment.GetHashCode();
            }
            return _product.GetHashCode();
        }

        public static ProductInfoHeaderValue Parse(string input)
        {
            int index = 0;
            object result = ProductInfoHeaderParser.SingleValueParser.ParseValue(
                input, null, ref index);
            if (index < input.Length)
            {
                // There is some invalid leftover data. Normaly BaseHeaderParser.TryParseValue would
                // handle this, but ProductInfoHeaderValue does not derive from BaseHeaderParser.
                throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, input.Substring(index)));
            }
            return (ProductInfoHeaderValue)result;
        }

        public static bool TryParse(string input, out ProductInfoHeaderValue parsedValue)
        {
            int index = 0;
            object output;
            parsedValue = null;

            if (ProductInfoHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output))
            {
                if (index < input.Length)
                {
                    // There is some invalid leftover data. Normaly BaseHeaderParser.TryParseValue would
                    // handle this, but ProductInfoHeaderValue does not derive from BaseHeaderParser.
                    return false;
                }
                parsedValue = (ProductInfoHeaderValue)output;
                return true;
            }
            return false;
        }

        internal static int GetProductInfoLength(string input, int startIndex, out ProductInfoHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return 0;
            }

            int current = startIndex;

            // Caller must remove leading whitespaces.
            string comment = null;
            ProductHeaderValue product = null;
            if (input[current] == '(')
            {
                int commentLength = 0;
                if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
                {
                    return 0;
                }

                comment = input.Substring(current, commentLength);

                current = current + commentLength;
                current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            }
            else
            {
                // Trailing whitespaces are removed by GetProductLength().
                int productLength = ProductHeaderValue.GetProductLength(input, current, out product);

                if (productLength == 0)
                {
                    return 0;
                }

                current = current + productLength;
            }

            parsedValue = new ProductInfoHeaderValue();
            parsedValue._product = product;
            parsedValue._comment = comment;
            return current - startIndex;
        }

        object ICloneable.Clone()
        {
            return new ProductInfoHeaderValue(this);
        }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

Reading an RVT File without Revit

A huge number of developers have requested a possibility to read or even write an RVT file without running Revit, similar to the possibility to read and write a DWG file without AutoCAD installed.

For the latter, one option that has been around for ages is to make use of the RealDWG library for reading and writing DWG files.

A more recent and future oriented option is provided by the cloud-based AutoCAD I/O web service.

Here is yet another variation on this query:

Question: Is there any way that I can read a Revit model without having Revit installed on the users machine?

I'm thinking something similar to RealDWG for AutoCAD?

The closest I was able to find is your discussion
of Open Revit OLE Storage.

However, I got the impression that this provides very limited and that it would not enable to extract, say, specific wall properties.

Answer: Yes, the method that you refer to is extremely limited in the scope of information that can be accessed.

It is based on OLE structured storage, COM Structured Storage and the Compound File Binary Format.

One additional aspect of the structure storage format is that it also enables access to
so-called custom file properties on RVT and RFA files,
since they are standard Windows properties stored there.

Here is another recent short overview
on programmatically generating Revit family RFA files.

There is a little bit more data that can indeed be accessed from family definition RFA files without running Revit using the Application ExtractPartAtomFromFamilyFile method:

Extract Part Atoms

Extract Part Atom Revisited

Regarding the question you raise on full access to the RVT file contents without a Revit session up and running, we recently published a request for wishes concerning that area:

What Can Revit on the Cloud Do For You?

If you have a serious need and a clear vision of what you would like to see, please contact Jim Quanci and let him know.

It will be much appreciated.

Thank you!

Addendum

This  question was raised again shortly afterwards in the Revit API discussion forum thread
on accessing Revit data without opening Revit:

Question: How can I access Revit information without opening the Revit application, e.g. from an external application such as content studio?

I would like to explore some parameters without opening the application.
I know this kind of thread has been created few times but I discovered that Content Studio can do this.
Does anyone know how to deal with this?

Answer: I assume you are referring to the Revit Content Studio application by Content Studio Limited?

Just as you already noted, this question has been discussed repeatedly in the past, e.g., in the Revit API discussion forum thread
on Revit API code without user interaction in application.

In general, as noted in both there and in the summary above, it is not possible to access Revit data or make any use whatsoever of the Revit API from outside of Revit.

Moreover, you need to be in a valid Revit API context to make any Revit API calls.

A valid Revit API context is only available within call back functions, i.e. event handlers that are actively called by Revit after registering to the corresponding API events.

This is described in detail in numerous discussions in The Building Coder topic group
on Idling and External Events for Modeless Access and Driving Revit from Outside.

I assume that the information provided by Content Studio is accessible through the OLE and COM Structured Storage of the RVT and RFA file formats and the part atom functionality and the Application ExtractPartAtomFromFamilyFile method provided by the Revit API and described above.

Oh, and before signing off, here is another thought-provoking idea:

A House for $20000 – but it's Nicer Than Yours

Check out this Rural Studio architectural project to
build a house that costs just $20,000 – but it's nicer than yours.

Look at their list of beautiful low-budget 5th year architecture projects.

I bet they made many people very happy with those!


text:
This file is used to list changes made in each version of the netdata cookbook.

## 0.1.0
- Sergio Pena - Initial release of netdata

## 0.1.1
- Sergio Pena - Add tests and kitchen specs

## 0.1.2
- Sergio Pena - Add Ubuntu deps and tests.

## 0.1.4
- João Madureira - Do not run install if there are no changes in git repo

## 0.2.0
- Nick Willever - Change install to a resource
                - Create new generic resource for all python.d plugins
                - Deprecated netdata_bind_rndc_conf resource
                - Deprecated netdata_nginx_conf resource
                - Deprecate use of attributes
                - Deprecate use of default and install_netdata recipes
                - Convert to inspec for test-kitchen verifier framework

## 0.3.0
- Serge A. Salamanka - add update property
                     - add netdata_stream resource

## 0.3.1
- Serge A. Salamanka - use cookbook dependencies with all tested major version numbers

## 0.4.0
- João Madureira - Support for statsd plugin configuration
- Serge A. Salamanka - Support for binary installation

- - -


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsDNSPrefetch_h___
#define nsDNSPrefetch_h___

#include "nsCOMPtr.h"
#include "nsString.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Attributes.h"

#include "nsIDNSListener.h"

class nsIURI;
class nsIDNSService;

class nsDNSPrefetch MOZ_FINAL : public nsIDNSListener
{
public:
    NS_DECL_ISUPPORTS
    NS_DECL_NSIDNSLISTENER

    nsDNSPrefetch(nsIURI *aURI, bool storeTiming);
    bool TimingsValid() const {
        return !mStartTimestamp.IsNull() && !mEndTimestamp.IsNull();
    }
    // Only use the two timings if TimingsValid() returns true
    const mozilla::TimeStamp& StartTimestamp() const { return mStartTimestamp; }
    const mozilla::TimeStamp& EndTimestamp() const { return mEndTimestamp; }

    static nsresult Initialize(nsIDNSService *aDNSService);
    static nsresult Shutdown();

    // Call one of the following methods to start the Prefetch.
    nsresult PrefetchHigh();
    nsresult PrefetchMedium();
    nsresult PrefetchLow();

private:
    nsCString mHostname;
    bool mStoreTiming;
    mozilla::TimeStamp mStartTimestamp;
    mozilla::TimeStamp mEndTimestamp;

    nsresult Prefetch(uint16_t flags);
};

#endif


text:
<assembly
	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
	<id>release</id>
	<formats>
		<format>tar.gz</format>
	</formats>
    <files>
        <file>
            <outputDirectory>/</outputDirectory>
            <source>${project.basedir}/README.md</source>
        </file>
        <file>
            <outputDirectory>/</outputDirectory>
            <source>${project.basedir}/LICENSE.txt</source>
        </file>
        <file>
            <outputDirectory>/</outputDirectory>
            <source>${project.basedir}/NOTICE.txt</source>
        </file>
        <file>
            <outputDirectory>/etc</outputDirectory>
            <source>${project.build.directory}/classes/log4j2.xml</source>
        </file>
        <file>
            <outputDirectory>/bin</outputDirectory>
            <source>${project.build.directory}/classes/main.py</source>
            <fileMode>0755</fileMode>
        </file>
        <file>
            <outputDirectory>/etc</outputDirectory>
            <source>${project.basedir}/src/main/resources/reference.conf</source>
            <destName>safari.conf</destName>
        </file>
    </files>
	<fileSets>
        <fileSet>
            <outputDirectory>/lib</outputDirectory>
            <directory>${project.build.directory}/lib/compile</directory>
        </fileSet>
        <fileSet>
            <outputDirectory>/lib</outputDirectory>
            <directory>${project.build.directory}</directory>
            <includes>
                <include>${project.build.finalName}.jar</include>
            </includes>
        </fileSet>
	</fileSets>
</assembly>


text:
    <input type="text" placeholder="New artist name here" ng-model="createArtistName.name"/>
    <input type="button" value="Create new" ng-click="createArtist()"/>

        <input type="button" value="Delete" ng-click="deleteArtist(artist._id)"/>

        {{artist.name}}


text:
package com.camunda.demo.versicherungsneuantrag.cockpit.dto;

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

public class InstanceCountChart {

  private List<String> categories = new ArrayList<String>();
  private Map<String, InstanceCountSeries> series = new HashMap<String, InstanceCountSeries>();

  public List<String> getCategories() {
    return this.categories;
  }

  public void setCategories(final List<String> categories) {
    this.categories = categories;
  }

  public Collection<InstanceCountSeries> getSeries() {
    return this.series.values();
  }

  public void addSeriesValue(final String key, final long count) {
    if (!this.series.containsKey(key)) {
      InstanceCountSeries processInstanceCountSeries = new InstanceCountSeries();
      processInstanceCountSeries.setName(key);
      this.series.put(key, processInstanceCountSeries);
    }
    this.series.get(key).getData().add(count);
  }

}


text:
<?php

namespace Foil\Kernel;

use Traversable;
use JsonSerializable;

/**
 * Class that recursively converts any data into an array.
 *
 * Optionally convert all "atomic" items to strings and optionally HTML-encode all strings.
 * Array and traversable objects are all recursively converted.
 * Non-traversable objects are converted to array, using 1st available among following methods:
 *  - if a transformer callback is provided, than it's called passing the object as param
 *  - if a transformer class is provided, than its transform() method is called passing the object
 *    as param
 *  - if a transformer object is provided, than its transform() method is called passing the object
 *    as param
 *  - if the object has a method toArray() it is called
 *  - if the object has a method asArray() it is called
 *  - if the object is an instance of JsonSerializable then jsonSerialize() is called
 *  - get_object_vars() is called
 * The obtained array is recursively parsed.
 *
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @package foil\foil
 * @license http://opensource.org/licenses/MIT MIT
 */
class Arraize
{
    const TOSTRING = 1;
    const ESCAPE   = 2;

    /**
     * @var mixed
     */
    private $rawData;

    /**
     * @var array
     */
    private $data = [];

    /**
     * @var array
     */
    private $transformers = [];

    /**
     * @var int
     */
    private $flags = 0;

    /**
     * @var bool
     */
    private $done = false;

    /**
     * Constructor.
     *
     * Stores data to convert an options.
     *
     * @param mixed    $data         Data to convert
     * @param array    $transformers Array of object transformers
     * @param int|null $flags        Bitmask of class constants flags
     */
    public function __construct($data, array $transformers = [], $flags = null)
    {
        $this->rawData = $data;
        $this->transformers = $transformers;
        if (is_int($flags)) {
            $this->flags = $flags;
        }
    }

    /**
     * Run the conversion or just return the result if conversion was already done.
     *
     * @return array
     */
    public function __invoke()
    {
        if (! $this->done && ! empty($this->rawData)) {
            $collect = $this->collect($this->rawData);
            $this->data = empty($collect) ? [] : (array) $collect;
            $this->done = true;
        }

        return $this->data;
    }

    /**
     * Recursively called to convert items. If given item is traversable than every items is parsed
     * otherwise it is returned maybe transformed according to settings.
     *
     * @param  mixed $var
     * @return mixed
     */
    private function collect($var)
    {
        return is_array($var) || $var instanceof Traversable
            ? $this->walk($var)
            : $this->atomic($var);
    }

    /**
     * Function called for non-traversable items. If the given item is an object it is transformed,
     * otherwise returned maybe casted to string and may HTML-encoded, according to settings.
     *
     * @param  mixed $var
     * @return mixed
     */
    private function atomic($var)
    {
        return is_object($var)
            ? $this->collect($this->transform($var, get_class($var)))
            : $this->scalar($var);
    }

    /**
     * Function called for traversable items. Methods loops every item and if it is traversable
     * it is recursively parsed, otherwise it is returned maybe transformed according to settings.
     *
     * @param  array|Traversable $var
     * @return array
     */
    private function walk($var)
    {
        $output = [];
        foreach ($var as $index => $item) {
            $output[$index] = is_array($item) || $item instanceof Traversable
                ? $this->collect($item)
                : $this->atomic($item);
        }

        return $output;
    }

    /**
     * Takes an object and transform it to an array, using a transformer class or callback if
     * available, calling jsonSerialize() if the object is JsonSerializable or just getting
     * array of object vars.
     *
     * @param  object $object
     * @return array
     */
    private function transform($object)
    {
        $class = trim(get_class($object), '\\');
        $transformer = array_key_exists($class, $this->transformers)
            ? $this->transformers[$class]
            : false;
        if (! $transformer) {
            return $this->convert($object);
        }

        return is_callable(($cb = $this->transformer($transformer)))
            ? $this->forceArray(call_user_func($cb, $object))
            : $this->convert($object);
    }

    /**
     * Return a transformer callback from a settings
     *
     * @param  mixed         $transformer
     * @return callable|bool
     */
    private function transformer($transformer)
    {
        if (is_string($transformer) && class_exists($transformer)) {
            $transformer = new $transformer();
        }
        if (is_object($transformer) && method_exists($transformer, 'transform')) {
            $transformer = [$transformer, 'transform'];
        }

        return is_callable($transformer) ? $transformer : false;
    }

    /**
     * @param  object $object
     * @return array
     */
    private function convert($object)
    {
        $toArray = array_reduce(['toArray', 'asArray'], function ($obj, $name) {
            return is_object($obj) && method_exists($obj, $name) ? (array) $obj->$name() : $obj;
        }, $object);

        return is_array($toArray) ? $toArray : $this->forceArray($object);
    }

    /**
     * Return an array from any variable.
     * If the variable is an object that implements JsonSerializable calls jsonSerialize() on it
     * before returning result casted to an array.
     *
     * @param  mixed $var
     * @return array
     */
    private function forceArray($var)
    {
        if ($var instanceof JsonSerializable) {
            $var = $var->jsonSerialize();
        }

        return is_object($var) ? get_object_vars($var) : (array) $var;
    }

    /**
     * Run on every scalar items, optionally convert them to string and optionally escape strings
     * for HTML entities according to settings.
     *
     * @param  mixed $var
     * @return mixed
     */
    private function scalar($var)
    {
        if (($this->flags & self::ESCAPE) && is_string($var)) {
            return htmlentities($var, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        }

        return ($this->flags & self::TOSTRING) && ! is_string($var)
            ? $this->scalar((string) $var)
            : $var;
    }
}


text:
package com.javarush.test.level26.lesson15.big01;

import com.javarush.test.level26.lesson15.big01.exception.InterruptOperationException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Alex on 28.04.2014.
 */
public class ConsoleHelper
{
    private static ResourceBundle res = ResourceBundle.getBundle(CashMachine.RESOURCE_PATH + "common_en");

    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void writeMessage(String message)
    {
        System.out.println(message);
    }

    public static void printExitMessage()
    {
        ConsoleHelper.writeMessage(res.getString("the.end"));
    }

    public static String readString() throws InterruptOperationException
    {
        String message = "";
        try
        {
            message = reader.readLine();
            if (message.equalsIgnoreCase(res.getString("operation.EXIT")))
                throw new InterruptOperationException();
        }
        catch (IOException ignored)
        {
        }
        return message;
    }

    public static String askCurrencyCode() throws InterruptOperationException
    {
        String test;
        writeMessage(res.getString("choose.currency.code"));
        while (true)
        {
            test = readString();
            if (test.length() == 3)
                break;
            else
                writeMessage(res.getString("invalid.data"));

        }
        test = test.toUpperCase();
        return test;
    }

    public static String[] getValidTwoDigits(String currencyCode) throws InterruptOperationException
    {
        String[] array;
        writeMessage(String.format(res.getString("choose.denomination.and.count.format"), currencyCode));

        while (true)
        {
            String s = readString();
            array = s.split(" ");
            int k;
            int l;
            try
            {
                k = Integer.parseInt(array[0]);
                l = Integer.parseInt(array[1]);
            }
            catch (Exception e)
            {
                writeMessage(res.getString("invalid.data"));
                continue;
            }
            if (k <= 0 || l <= 0 || array.length > 2)
            {
                writeMessage(res.getString("invalid.data"));
                continue;
            }
            break;
        }
        return array;
    }

    public static Operation askOperation() throws InterruptOperationException
    {
        while (true)
        {
            String line = readString();
            if (checkWithRegExp(line))
                return Operation.getAllowableOperationByOrdinal(Integer.parseInt(line));
            else
                writeMessage(res.getString("invalid.data"));
        }

    }

    public static boolean checkWithRegExp(String Name)
    {
        Pattern p = Pattern.compile("^[1-4]$");
        Matcher m = p.matcher(Name);
        return m.matches();
    }
}


text:
#pragma once
#include <aws/securityhub/SecurityHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace SecurityHub
{
namespace Model
{

  /**
   *
Error messages for environment variables that couldn't be
   * applied.

See Also:
   AWS
   * API Reference

   */
  class AWS_SECURITYHUB_API AwsLambdaFunctionEnvironmentError
  {
  public:
    AwsLambdaFunctionEnvironmentError();
    AwsLambdaFunctionEnvironmentError(Aws::Utils::Json::JsonView jsonValue);
    AwsLambdaFunctionEnvironmentError& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The error code.

     */
    inline const Aws::String& GetErrorCode() const{ return m_errorCode; }

    /**
     *
The error code.

     */
    inline bool ErrorCodeHasBeenSet() const { return m_errorCodeHasBeenSet; }

    /**
     *
The error code.

     */
    inline void SetErrorCode(const Aws::String& value) { m_errorCodeHasBeenSet = true; m_errorCode = value; }

    /**
     *
The error code.

     */
    inline void SetErrorCode(Aws::String&& value) { m_errorCodeHasBeenSet = true; m_errorCode = std::move(value); }

    /**
     *
The error code.

     */
    inline void SetErrorCode(const char* value) { m_errorCodeHasBeenSet = true; m_errorCode.assign(value); }

    /**
     *
The error code.

     */
    inline AwsLambdaFunctionEnvironmentError& WithErrorCode(const Aws::String& value) { SetErrorCode(value); return *this;}

    /**
     *
The error code.

     */
    inline AwsLambdaFunctionEnvironmentError& WithErrorCode(Aws::String&& value) { SetErrorCode(std::move(value)); return *this;}

    /**
     *
The error code.

     */
    inline AwsLambdaFunctionEnvironmentError& WithErrorCode(const char* value) { SetErrorCode(value); return *this;}

    /**
     *
The error message.

     */
    inline const Aws::String& GetMessage() const{ return m_message; }

    /**
     *
The error message.

     */
    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    /**
     *
The error message.

     */
    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    /**
     *
The error message.

     */
    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    /**
     *
The error message.

     */
    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    /**
     *
The error message.

     */
    inline AwsLambdaFunctionEnvironmentError& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    /**
     *
The error message.

     */
    inline AwsLambdaFunctionEnvironmentError& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    /**
     *
The error message.

     */
    inline AwsLambdaFunctionEnvironmentError& WithMessage(const char* value) { SetMessage(value); return *this;}

  private:

    Aws::String m_errorCode;
    bool m_errorCodeHasBeenSet;

    Aws::String m_message;
    bool m_messageHasBeenSet;
  };

} // namespace Model
} // namespace SecurityHub
} // namespace Aws


text:
package org.oscm.test.data;

import java.math.BigDecimal;
import java.util.Date;

import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.RevenueShareModelHistory;
import org.oscm.domobjects.enums.ModificationType;
import org.oscm.domobjects.enums.RevenueShareModelType;

/**
 * @author tokoda
 *
 */
public class RevenueShareModels {

    public static RevenueShareModelHistory createRevenueShareModelHistory(
            DataService ds, final long objKey, final Date modDate,
            final int version, final ModificationType modificationType,
            final BigDecimal revenueShare,
            final RevenueShareModelType revenueShareModelType) throws Exception {

        RevenueShareModelHistory rsmh = new RevenueShareModelHistory();
        rsmh.setObjKey(objKey);
        rsmh.setInvocationDate(new Date());
        rsmh.setObjVersion(version);
        rsmh.setModdate(modDate);
        rsmh.setModtype(modificationType);
        rsmh.setModuser("moduser");
        rsmh.getDataContainer().setRevenueShare(revenueShare);
        rsmh.getDataContainer().setRevenueShareModelType(revenueShareModelType);
        ds.persist(rsmh);
        return rsmh;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/chat_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="@android:color/black"
            />
        <TextView
            android:id="@+id/last_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textColor="@android:color/black"
            />
    </LinearLayout>

</LinearLayout>


text:
"""Define database schemas."""

import sqlalchemy

from ndscheduler.corescheduler import utils

#
# Jobs
# It's defined by apscheduler library.
#

def get_execution_table(metadata, tablename):
    return sqlalchemy.Table(
        tablename, metadata,
        sqlalchemy.Column('eid', sqlalchemy.Unicode(191, _warn_on_bytestring=False),
                          primary_key=True),
        sqlalchemy.Column('hostname', sqlalchemy.Text, nullable=True),
        sqlalchemy.Column('pid', sqlalchemy.Integer, nullable=True),
        sqlalchemy.Column('state', sqlalchemy.Integer, nullable=False),
        sqlalchemy.Column('scheduled_time', sqlalchemy.DateTime(timezone=True), nullable=False,
                          default=utils.get_current_datetime),
        sqlalchemy.Column('updated_time', sqlalchemy.DateTime(timezone=True),
                          default=utils.get_current_datetime, onupdate=utils.get_current_datetime),
        sqlalchemy.Column('description', sqlalchemy.Text, nullable=True),
        sqlalchemy.Column('result', sqlalchemy.Text, nullable=True),
        sqlalchemy.Column('job_id', sqlalchemy.Text, nullable=False),
        sqlalchemy.Column('task_id', sqlalchemy.Text, nullable=True))

def get_auditlogs_table(metadata, tablename):
    return sqlalchemy.Table(
        tablename, metadata,
        sqlalchemy.Column('job_id', sqlalchemy.Text, nullable=False),
        sqlalchemy.Column('job_name', sqlalchemy.Text, nullable=False),
        sqlalchemy.Column('event', sqlalchemy.Integer, nullable=False),
        sqlalchemy.Column('user', sqlalchemy.Text, nullable=True),
        sqlalchemy.Column('created_time', sqlalchemy.DateTime(timezone=True), nullable=False,
                          default=utils.get_current_datetime),
        sqlalchemy.Column('description', sqlalchemy.Text, nullable=True))


text:
package set

import (
	"errors"
	"fmt"

	"github.com/spf13/cobra"
	"k8s.io/klog"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/cli-runtime/pkg/genericclioptions/printers"
	"k8s.io/cli-runtime/pkg/genericclioptions/resource"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
	"k8s.io/kubernetes/pkg/kubectl/scheme"
	"k8s.io/kubernetes/pkg/kubectl/util/i18n"
	"k8s.io/kubernetes/pkg/kubectl/util/templates"
)

var (
	serviceaccountResources = `
	replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs), statefulset`

	serviceaccountLong = templates.LongDesc(i18n.T(`
	Update ServiceAccount of pod template resources.

	Possible resources (case insensitive) can be:
	` + serviceaccountResources))

	serviceaccountExample = templates.Examples(i18n.T(`
	# Set Deployment nginx-deployment's ServiceAccount to serviceaccount1
	kubectl set serviceaccount deployment nginx-deployment serviceaccount1

	# Print the result (in yaml format) of updated nginx deployment with serviceaccount from local file, without hitting apiserver
	kubectl set sa -f nginx-deployment.yaml serviceaccount1 --local --dry-run -o yaml
	`))
)

// SetServiceAccountOptions encapsulates the data required to perform the operation.
type SetServiceAccountOptions struct {
	PrintFlags  *genericclioptions.PrintFlags
	RecordFlags *genericclioptions.RecordFlags

	fileNameOptions        resource.FilenameOptions
	dryRun                 bool
	shortOutput            bool
	all                    bool
	output                 string
	local                  bool
	updatePodSpecForObject polymorphichelpers.UpdatePodSpecForObjectFunc
	infos                  []*resource.Info
	serviceAccountName     string

	PrintObj printers.ResourcePrinterFunc
	Recorder genericclioptions.Recorder

	genericclioptions.IOStreams
}

// NewSetServiceAccountOptions returns an initialized SetServiceAccountOptions instance
func NewSetServiceAccountOptions(streams genericclioptions.IOStreams) *SetServiceAccountOptions {
	return &SetServiceAccountOptions{
		PrintFlags:  genericclioptions.NewPrintFlags("serviceaccount updated").WithTypeSetter(scheme.Scheme),
		RecordFlags: genericclioptions.NewRecordFlags(),

		Recorder: genericclioptions.NoopRecorder{},

		IOStreams: streams,
	}
}

// NewCmdServiceAccount returns the "set serviceaccount" command.
func NewCmdServiceAccount(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewSetServiceAccountOptions(streams)

	cmd := &cobra.Command{
		Use:                   "serviceaccount (-f FILENAME | TYPE NAME) SERVICE_ACCOUNT",
		DisableFlagsInUseLine: true,
		Aliases:               []string{"sa"},
		Short:                 i18n.T("Update ServiceAccount of a resource"),
		Long:                  serviceaccountLong,
		Example:               serviceaccountExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Run())
		},
	}

	o.PrintFlags.AddFlags(cmd)
	o.RecordFlags.AddFlags(cmd)

	usage := "identifying the resource to get from a server."
	cmdutil.AddFilenameOptionFlags(cmd, &o.fileNameOptions, usage)
	cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
	cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, set serviceaccount will NOT contact api-server but run locally.")
	cmdutil.AddDryRunFlag(cmd)
	cmdutil.AddIncludeUninitializedFlag(cmd)
	return cmd
}

// Complete configures serviceAccountConfig from command line args.
func (o *SetServiceAccountOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
	var err error

	o.RecordFlags.Complete(cmd)
	o.Recorder, err = o.RecordFlags.ToRecorder()
	if err != nil {
		return err
	}

	o.shortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
	o.dryRun = cmdutil.GetDryRunFlag(cmd)
	o.output = cmdutil.GetFlagString(cmd, "output")
	o.updatePodSpecForObject = polymorphichelpers.UpdatePodSpecForObjectFn

	if o.dryRun {
		o.PrintFlags.Complete("%s (dry run)")
	}
	printer, err := o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}
	o.PrintObj = printer.PrintObj

	cmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()
	if err != nil {
		return err
	}
	if len(args) == 0 {
		return errors.New("serviceaccount is required")
	}
	o.serviceAccountName = args[len(args)-1]
	resources := args[:len(args)-1]
	builder := f.NewBuilder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		LocalParam(o.local).
		ContinueOnError().
		NamespaceParam(cmdNamespace).DefaultNamespace().
		FilenameParam(enforceNamespace, &o.fileNameOptions).
		Flatten()
	if !o.local {
		builder.ResourceTypeOrNameArgs(o.all, resources...).
			Latest()
	}
	o.infos, err = builder.Do().Infos()
	if err != nil {
		return err
	}
	return nil
}

// Run creates and applies the patch either locally or calling apiserver.
func (o *SetServiceAccountOptions) Run() error {
	patchErrs := []error{}
	patchFn := func(obj runtime.Object) ([]byte, error) {
		_, err := o.updatePodSpecForObject(obj, func(podSpec *v1.PodSpec) error {
			podSpec.ServiceAccountName = o.serviceAccountName
			return nil
		})
		if err != nil {
			return nil, err
		}
		// record this change (for rollout history)
		if err := o.Recorder.Record(obj); err != nil {
			klog.V(4).Infof("error recording current command: %v", err)
		}

		return runtime.Encode(scheme.DefaultJSONEncoder(), obj)
	}

	patches := CalculatePatches(o.infos, scheme.DefaultJSONEncoder(), patchFn)
	for _, patch := range patches {
		info := patch.Info
		if patch.Err != nil {
			patchErrs = append(patchErrs, fmt.Errorf("error: %s/%s %v", info.Mapping.Resource, info.Name, patch.Err))
			continue
		}
		if o.local || o.dryRun {
			if err := o.PrintObj(info.Object, o.Out); err != nil {
				patchErrs = append(patchErrs, err)
			}
			continue
		}
		actual, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)
		if err != nil {
			patchErrs = append(patchErrs, fmt.Errorf("failed to patch ServiceAccountName %v", err))
			continue
		}

		if err := o.PrintObj(actual, o.Out); err != nil {
			patchErrs = append(patchErrs, err)
		}
	}
	return utilerrors.NewAggregate(patchErrs)
}


text:
<?php

require_once "include/skin.inc.php";
require_once 'include/skinlet.inc.php';
require_once "include/beContent.inc.php";
require_once "include/entities.inc.php";
require_once "include/content.inc.php";

require_once(realpath(dirname(__FILE__)).'/include/view/template/InitGraphic.php');

$main = new Skin();

InitGraphic::getInstance()->createGraphic($main,false,false);

$news = new Content($newsEntity, $usersEntity);
$news->setOrderFields("date DESC");

$main->setContent("body", $news->get());
$main->close();
?>


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization;
using TerrainQuest.Generator.Blending;
using TerrainQuest.Generator.Helpers;
using TerrainQuest.Generator.Serialization;

namespace TerrainQuest.Generator.Graph
{
    /// <summary>
    /// A node that blends the the <see cref="HeightMap"/>s of each dependency,
    /// based on a given blending mode.
    /// The dependencies are blended in the order they are inserted as a dependency.
    /// </summary>
    public class BlendingNode : HeightMapNode
    {

        private List<SerializedNode> _dependencies = new List<SerializedNode>();

        /// <summary>
        /// Get the blendmode being performed by this blendnode
        /// </summary>
        public IBlendMode BlendMode { get; private set; }

        /// <summary>
        /// Get the dimensions of the resulting heightmap
        /// </summary>
        public Size? Dimensions { get; private set; }

        /// <summary>
        /// Get all nodes getting blended.
        /// </summary>
        public override IEnumerable<INode> Dependencies
        {
            get
            {
                return _dependencies.Select(x => x.Node);
            }
        }

        /// <summary>
        /// Create a <see cref="BlendingNode"/> where the dimensions of the result,
        /// equals the dimensions of the first dependency.
        /// </summary>
        public BlendingNode(IBlendMode blendMode)
        {
            Check.NotNull(blendMode, nameof(blendMode));

            BlendMode = blendMode;
        }

        /// <summary>
        /// Create a <see cref="BlendingNode"/> where the result will have the given dimensions
        /// </summary>
        public BlendingNode(int height, int width, IBlendMode blendMode)
        {
            Check.NotNull(blendMode, nameof(blendMode));

            Dimensions = new Size(width, height);
            BlendMode = blendMode;
        }

        /// <summary>
        /// Add an add dependency with a weight,
        /// where the weight is a percentage of how much of the dependency is added.
        /// </summary>
        public void AddDependency(HeightMapNode dependency)
        {
            Check.NotNull(dependency, nameof(dependency));

            lock (_dependencies)
            {
                _dependencies.Add(new SerializedNode(dependency));
            }
        }

        protected override void Process()
        {
            lock (_dependencies)
            {
                if (!_dependencies.Any())
                    throw new InvalidOperationException("Cannot perform blending without any dependencies to blend.");

                var sources = Dependencies.Cast<HeightMapNode>();
                var result = sources.First().Result;

                if (Dimensions.HasValue)
                    result = new HeightMap(Dimensions.Value.Height, Dimensions.Value.Width, result.Data);

                foreach(var source in sources.Skip(1))
                {
                    result = BlendMode.Blend(result, source.Result);
                }

                Result = result;
            }
        }

        #region Serialization

        /// <summary>
        /// Object deserialization constructor
        /// </summary>
        public BlendingNode(SerializationInfo info, StreamingContext context)
        {
            Dimensions = (Size?)info.GetValue("Dimensions", typeof(Size?));
            _dependencies = (List<SerializedNode>)info.GetValue(nameof(Dependencies), typeof(List<SerializedNode>));
            BlendMode = info.GetTypedValue<IBlendMode>(nameof(BlendMode));
        }

        /// <summary>
        /// Object serialization method
        /// </summary>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Dimensions", Dimensions, typeof(Size?));
            info.AddValue(nameof(Dependencies), _dependencies, _dependencies.GetType());
            info.AddTypedValue(nameof(BlendMode), BlendMode);
        }

        #endregion
    }
}


text:
package com.facebook.imagepipeline.animated.testing;

import android.graphics.Bitmap;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.internal.Shadow;
import org.robolectric.internal.ShadowExtractor;

/**
 * A shadow of {@link Bitmap} that works with the tests in this package.
 */
@Implements(Bitmap.class)
public class MyShadowBitmap {

  private int width;
  private int height;
  private int[] mPixels;

  @Implementation
  public int getWidth() {
    return width;
  }

  @Implementation
  public int getHeight() {
    return height;
  }

  @Implementation
  public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
    Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class);
    MyShadowBitmap shadowBitmap = (MyShadowBitmap) ShadowExtractor.extract(bitmap);
    shadowBitmap.width = width;
    shadowBitmap.height = height;
    shadowBitmap.mPixels = new int[width * height];
    return bitmap;
  }

  @Implementation
  public static Bitmap createBitmap(int colors[], int width, int height, Bitmap.Config config) {
    Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class);
    MyShadowBitmap shadowBitmap = (MyShadowBitmap) ShadowExtractor.extract(bitmap);
    shadowBitmap.width = width;
    shadowBitmap.height = height;
    shadowBitmap.mPixels = new int[width * height];
    for (int i = 0; i < colors.length; i++) {
      shadowBitmap.mPixels[i] = colors[i];
    }
    return bitmap;
  }

  @Implementation
  public void setPixel(int x, int y, int color) {
    mPixels[y * width + x] = color;
  }

  @Implementation
  public int getPixel(int x, int y) {
    return mPixels[y * width + x];
  }

  @Implementation
  public void eraseColor(int c) {
    for (int i = 0; i < mPixels.length; i++) {
      mPixels[i] = c;
    }
  }
}


text:
NCSUServer
==========

www folder archive from ncsu unity server


text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Tables.AbstractCell;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

/** Collectors utilities for {@code common.collect.Table} internals. */
@GwtCompatible
final class TableCollectors {

  static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
      Function<? super T, ? extends R> rowFunction,
      Function<? super T, ? extends C> columnFunction,
      Function<? super T, ? extends V> valueFunction) {
    checkNotNull(rowFunction, "rowFunction");
    checkNotNull(columnFunction, "columnFunction");
    checkNotNull(valueFunction, "valueFunction");
    return Collector.of(
        (Supplier<ImmutableTable.Builder<R, C, V>>) ImmutableTable.Builder::new,
        (builder, t) ->
            builder.put(rowFunction.apply(t), columnFunction.apply(t), valueFunction.apply(t)),
        ImmutableTable.Builder::combine,
        ImmutableTable.Builder::build);
  }

  static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
      Function<? super T, ? extends R> rowFunction,
      Function<? super T, ? extends C> columnFunction,
      Function<? super T, ? extends V> valueFunction,
      BinaryOperator<V> mergeFunction) {

    checkNotNull(rowFunction, "rowFunction");
    checkNotNull(columnFunction, "columnFunction");
    checkNotNull(valueFunction, "valueFunction");
    checkNotNull(mergeFunction, "mergeFunction");

    /*
     * No mutable Table exactly matches the insertion order behavior of ImmutableTable.Builder, but
     * the Builder can't efficiently support merging of duplicate values.  Getting around this
     * requires some work.
     */

    return Collector.of(
        () -> new ImmutableTableCollectorState<R, C, V>()
        /* GWT isn't currently playing nicely with constructor references? */ ,
        (state, input) ->
            state.put(
                rowFunction.apply(input),
                columnFunction.apply(input),
                valueFunction.apply(input),
                mergeFunction),
        (s1, s2) -> s1.combine(s2, mergeFunction),
        state -> state.toTable());
  }

  static <T, R, C, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable(
      java.util.function.Function<? super T, ? extends R> rowFunction,
      java.util.function.Function<? super T, ? extends C> columnFunction,
      java.util.function.Function<? super T, ? extends V> valueFunction,
      java.util.function.Supplier<I> tableSupplier) {
    return toTable(
        rowFunction,
        columnFunction,
        valueFunction,
        (v1, v2) -> {
          throw new IllegalStateException("Conflicting values " + v1 + " and " + v2);
        },
        tableSupplier);
  }

  static <T, R, C, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable(
      java.util.function.Function<? super T, ? extends R> rowFunction,
      java.util.function.Function<? super T, ? extends C> columnFunction,
      java.util.function.Function<? super T, ? extends V> valueFunction,
      BinaryOperator<V> mergeFunction,
      java.util.function.Supplier<I> tableSupplier) {
    checkNotNull(rowFunction);
    checkNotNull(columnFunction);
    checkNotNull(valueFunction);
    checkNotNull(mergeFunction);
    checkNotNull(tableSupplier);
    return Collector.of(
        tableSupplier,
        (table, input) ->
            mergeTables(
                table,
                rowFunction.apply(input),
                columnFunction.apply(input),
                valueFunction.apply(input),
                mergeFunction),
        (table1, table2) -> {
          for (Table.Cell<R, C, V> cell2 : table2.cellSet()) {
            mergeTables(
                table1, cell2.getRowKey(), cell2.getColumnKey(), cell2.getValue(), mergeFunction);
          }
          return table1;
        });
  }

  private static final class ImmutableTableCollectorState<R, C, V> {
    final List<MutableCell<R, C, V>> insertionOrder = new ArrayList<>();
    final Table<R, C, MutableCell<R, C, V>> table = HashBasedTable.create();

    void put(R row, C column, V value, BinaryOperator<V> merger) {
      MutableCell<R, C, V> oldCell = table.get(row, column);
      if (oldCell == null) {
        MutableCell<R, C, V> cell = new MutableCell<>(row, column, value);
        insertionOrder.add(cell);
        table.put(row, column, cell);
      } else {
        oldCell.merge(value, merger);
      }
    }

    ImmutableTableCollectorState<R, C, V> combine(
        ImmutableTableCollectorState<R, C, V> other, BinaryOperator<V> merger) {
      for (MutableCell<R, C, V> cell : other.insertionOrder) {
        put(cell.getRowKey(), cell.getColumnKey(), cell.getValue(), merger);
      }
      return this;
    }

    ImmutableTable<R, C, V> toTable() {
      return ImmutableTable.copyOf(insertionOrder);
    }
  }

  private static final class MutableCell<R, C, V> extends AbstractCell<R, C, V> {
    private final R row;
    private final C column;
    private V value;

    MutableCell(R row, C column, V value) {
      this.row = checkNotNull(row, "row");
      this.column = checkNotNull(column, "column");
      this.value = checkNotNull(value, "value");
    }

    @Override
    public R getRowKey() {
      return row;
    }

    @Override
    public C getColumnKey() {
      return column;
    }

    @Override
    public V getValue() {
      return value;
    }

    void merge(V value, BinaryOperator<V> mergeFunction) {
      checkNotNull(value, "value");
      this.value = checkNotNull(mergeFunction.apply(this.value, value), "mergeFunction.apply");
    }
  }

  private static <R, C, V> void mergeTables(
      Table<R, C, V> table, R row, C column, V value, BinaryOperator<V> mergeFunction) {
    checkNotNull(value);
    V oldValue = table.get(row, column);
    if (oldValue == null) {
      table.put(row, column, value);
    } else {
      V newValue = mergeFunction.apply(oldValue, value);
      if (newValue == null) {
        table.remove(row, column);
      } else {
        table.put(row, column, newValue);
      }
    }
  }

  private TableCollectors() {}
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />

    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/sb-admin-2.css">
    <link rel="stylesheet" href="styles/timeline.css">
    <link rel="stylesheet" href="bower_components/metisMenu/dist/metisMenu.min.css">
    <link rel="stylesheet" href="bower_components/angular-loading-bar/build/loading-bar.min.css">
    <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="bower_components/datatables/media/css/dataTables.bootstrap.min.css" type="text/css">


text: package bigdata