text:
package org.ec.jap.bo.saap.impl;

import java.util.List;

import javax.ejb.Stateless;

import org.ec.jap.bo.saap.AsistenciaBO;
import org.ec.jap.dao.saap.impl.AsistenciaDAOImpl;
import org.ec.jap.entiti.saap.Asistencia;
import org.ec.jap.entiti.saap.Usuario;

/**
 * Session Bean implementation class DatAuditoriaBO
 */
@Stateless
public class AsistenciaBOImpl extends AsistenciaDAOImpl implements AsistenciaBO {

	/**
	 * Default constructor.
	 */
	public AsistenciaBOImpl() {
	}

	@Override
	public void actualizarAsistencias(Usuario usuario, List<Asistencia> list) throws Exception {

		for (Asistencia asistencia : list) {
			if(asistencia.getNumeroRayas().equals(0.0)&&asistencia.getAsistio()){
				asistencia.setNumeroRayas(1.0);
			}
			update(usuario, asistencia);
		}
	}
}


text:
using System.Linq;
using System.Reflection;

namespace Omu.ValueInjecter.Injections
{
    public class PropertyInjection : ValueInjection
    {
        protected string[] ignoredProps;

        public PropertyInjection()
        {
        }

        public PropertyInjection(string[] ignoredProps)
        {
            this.ignoredProps = ignoredProps;
        }

        protected bool IsNotIgnored(string property)
        {
            return ignoredProps == null || !ignoredProps.Contains(property);
        }

        protected override void Inject(object source, object target)
        {
            var sourceProps = source.GetType().GetProps();
            foreach (var s in sourceProps)
            {
                Execute(s, source, target);
            }
        }

        protected virtual void Execute(PropertyInfo sp, object source, object target)
        {
            if (sp.CanRead && (ignoredProps == null || !ignoredProps.Contains(sp.Name)))
            {
                var tp = target.GetType().GetProperty(sp.Name);
                if (tp != null && tp.CanWrite && tp.PropertyType == sp.PropertyType)
                {
                    tp.SetValue(target, sp.GetValue(source));
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.oss4j.samples.groovy.mix.java.greeter.impl;

import org.oss4j.samples.groovy.mix.groovy.greeter.api.GroovyGreeter;

/**
 * Implementation of {@link GroovyGreeter}
 *
 * @author Krzysztof Sobkowiak
 */
public class JavaGreeterImpl implements GroovyGreeter {

    /**
     * {@inheritDoc}
     */
    @Override
    public void sayHello() {
        System.out.println("Hello from Java implementation");
    }

}


text:
<!doctype html>

		<title>jsPlumb 1.3.9 - Dynamic Anchors Demonstration - YUI3</title>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<link rel="stylesheet" href="../css/jsPlumbDemo.css">
		<link rel="stylesheet" href="../css/dynamicAnchorsDemo.css">

1

2

3

4

5

6

This is a demonstration of anchors that change position dependent on the location of the other element in a connection. Each connection is decorated with a jsPlumb.Overlays.Diamond, located halfway along the connector.

You can drag new connections between blue endpoints.

This demonstration uses jsPlumb 1.3.9 and YUI 3.3.0.


text:
package cn.com.easy.deploy.service.deployproject.deploytask;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;

import cn.com.easy.deploy.dto.deployproject.DeployTaskDTO;
import cn.com.easy.deploy.dto.deployproject.DeployTaskDetailDTO;
import cn.com.easy.deploy.dto.servermanage.ServerDTO;
import cn.com.easy.deploy.dto.servermanage.ServerGroupDTO;
import cn.com.easy.deploy.entity.DeployCommandEntity;
import cn.com.easy.deploy.entity.DeployFileEntity;
import cn.com.easy.deploy.entity.DeployTaskEntity;
import cn.com.easy.deploy.entity.DeployTaskFileCommandRelationEntity;
import cn.com.easy.deploy.entity.DeployType;
import cn.com.easy.deploy.entity.ServerEntity;
import cn.com.easy.deploy.entity.ServerGroupEntity;
import cn.com.easy.deploy.persistence.service.IBaseService;
import cn.com.easy.deploy.utils.SpringContextHolder;

import com.google.common.collect.Lists;

/**
 * 转换部署文件DTO
 *
 * @author nibili
 *
 */
public class TransDeployTaskDTO {

	private static IBaseService baseService = SpringContextHolder.getBean(IBaseService.class);

	/**
	 * 获取部署任务DTO
	 *
	 * @param deployTaskEntitys
	 * @return
	 * @throws Exception
	 */
	public static List<DeployTaskDTO> getDeployTaskDTOS(List<DeployTaskEntity> deployTaskEntitys) throws Exception {

		List<DeployTaskDTO> dtoList = Lists.newArrayList();
		DeployTaskDTO dto = null;
		for (DeployTaskEntity deployTaskEntity : deployTaskEntitys) {
			dto = getDeployTaskDto(deployTaskEntity);
			dtoList.add(dto);
		}
		return dtoList;
	}

	/**
	 * 获取部署任务DTO
	 *
	 * @param DeployTaskEntity
	 * @return
	 * @throws Exception
	 */
	public static DeployTaskDTO getDeployTaskDto(DeployTaskEntity deployTaskEntity) throws Exception {

		DeployTaskDTO dto = new DeployTaskDTO();
		BeanUtils.copyProperties(dto, deployTaskEntity);
		// 转换服务器组
		transServer(dto);
		// 转换详细任务
		transTaskDetail(dto);
		return dto;
	}

	/**
	 * 1、转换服务器组
	 *
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	private static void transServer(DeployTaskDTO deployTaskDTO) throws Exception {

		ServerGroupEntity serverGroup = baseService.findUniquePK(ServerGroupEntity.class, deployTaskDTO.getServerGroupId());
		if (serverGroup != null) {
			ServerGroupDTO serverGroupDTO = new ServerGroupDTO();
			BeanUtils.copyProperties(serverGroupDTO, serverGroup);
			deployTaskDTO.setServerGroup(serverGroupDTO);
			List<ServerEntity> servers = baseService.find("from ServerEntity where id in" + " (select serverId from ServerGroupRelationEntity where serverGroupId ="
					+ serverGroup.getId() + ") order by ip", ServerEntity.class);
			List<ServerDTO> serverDtos = Lists.newArrayList();
			ServerDTO serverDTO;
			for (ServerEntity serverEntity : servers) {
				serverDTO = new ServerDTO();
				BeanUtils.copyProperties(serverDTO, serverEntity);
				serverDtos.add(serverDTO);
			}
			deployTaskDTO.setServers(serverDtos);
		}
	}

	/**
	 * 2、 转换详细任务
	 *
	 * @param deployTaskDTO
	 * @throws Exception
	 */
	public static void transTaskDetail(DeployTaskDTO deployTaskDTO) throws Exception {

		// 取关系实体集合
		List<DeployTaskFileCommandRelationEntity> deployTaskFileCommandRelations = baseService.find(
				"from " + DeployTaskFileCommandRelationEntity.class.getName() + " f where f.deployTaskId =" + deployTaskDTO.getId() + " order by deployIndex",
				DeployTaskFileCommandRelationEntity.class);
		// 集合必须不为空
		if (CollectionUtils.isEmpty(deployTaskFileCommandRelations) == false) {
			Object o = null;// 实体
			DeployTaskDetailDTO taskDetailDTO;
			List<DeployTaskDetailDTO> list = Lists.newArrayList();
			for (DeployTaskFileCommandRelationEntity entity : deployTaskFileCommandRelations) {
				o = null;
				// 判断是部署文件、还是部署命令
				if (entity.getDeployType() == DeployType.TYPE_FILE) {
					o = baseService.findUniquePK(DeployFileEntity.class, entity.getDeployFileOrCommandId());
				} else {
					if (entity.getDeployType() == DeployType.TYPE_COMMAND) {
						o = baseService.findUniquePK(DeployCommandEntity.class, entity.getDeployFileOrCommandId());
					}
				}
				// 取得的实体转化为dto
				if (o != null) {
					taskDetailDTO = new DeployTaskDetailDTO();
					taskDetailDTO.setType(entity.getDeployType());
					BeanUtils.copyProperties(taskDetailDTO, o);
					list.add(taskDetailDTO);
				}
			}
			deployTaskDTO.setDeployTaskDetails(list);
		}
	}
}


text:
package org.jetbrains.plugins.scala.testingSupport.scalatest.generators

import org.jetbrains.plugins.scala.testingSupport.IntegrationTest

/**
 * @author Roman.Shein
 * @since 10.02.2015.
 */
trait FreeSpecPathGenerator extends IntegrationTest {
  def addPathFreeSpec() {
    addFileToProject("FreeSpecPathTest.scala",
      """
        |import org.scalatest._
        |
        |class FreeSpecPathTest extends path.FreeSpec {
        |  "A FreeSpecTest" - {
        |    "should be able to run single test" in {
        |      print(">>TEST: OK<<")
        |    }
        |
        |    "should not run tests that are not selected" in {
        |      print("nothing interesting: path.FreeSpec executes contexts anyway")
        |    }
        |  }
        |}
      """.stripMargin.trim())
  }
}


text:
package org.antlr.v4.runtime.atn;

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.misc.DoubleKeyMap;
import org.antlr.v4.runtime.misc.MurmurHash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class PredictionContext {
	/**
	 * Represents {@code $} in an array in full context mode, when {@code $}
	 * doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
	 * {@code $} = {@link #EMPTY_RETURN_STATE}.
	 */
	public static final int EMPTY_RETURN_STATE = Integer.MAX_VALUE;

	private static final int INITIAL_HASH = 1;

	private static final AtomicInteger globalNodeCount = new AtomicInteger();
	public final int id = globalNodeCount.getAndIncrement();

	/**
	 * Stores the computed hash code of this {@link PredictionContext}. The hash
	 * code is computed in parts to match the following reference algorithm.
	 *
	 *

	 *  private int referenceHashCode() {
	 *      int hash = {@link MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});
	 *
	 *      for (int i = 0; i < {@link #size()}; i++) {
	 *          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));
	 *      }
	 *
	 *      for (int i = 0; i < {@link #size()}; i++) {
	 *          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i));
	 *      }
	 *
	 *      hash = {@link MurmurHash#finish MurmurHash.finish}(hash, 2 * {@link #size()});
	 *      return hash;
	 *  }
	 *

	 */
	public final int cachedHashCode;

	protected PredictionContext(int cachedHashCode) {
		this.cachedHashCode = cachedHashCode;
	}

	/** Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.
	 *  Return {@link EmptyPredictionContext#Instance} if {@code outerContext} is empty or null.
	 */
	public static PredictionContext fromRuleContext(ATN atn, RuleContext outerContext) {
		if ( outerContext==null ) outerContext = ParserRuleContext.EMPTY;

		// if we are in RuleContext of start rule, s, then PredictionContext
		// is EMPTY. Nobody called us. (if we are empty, return empty)
		if ( outerContext.parent==null || outerContext==ParserRuleContext.EMPTY ) {
			return EmptyPredictionContext.Instance;
		}

		// If we have a parent, convert it to a PredictionContext graph
		PredictionContext parent = EmptyPredictionContext.Instance;
		parent = PredictionContext.fromRuleContext(atn, outerContext.parent);

		ATNState state = atn.states.get(outerContext.invokingState);
		RuleTransition transition = (RuleTransition)state.transition(0);
		return SingletonPredictionContext.create(parent, transition.followState.stateNumber);
	}

	public abstract int size();

	public abstract PredictionContext getParent(int index);

	public abstract int getReturnState(int index);

	/** This means only the {@link EmptyPredictionContext#Instance} (wildcard? not sure) context is in set. */
	public boolean isEmpty() {
		return this == EmptyPredictionContext.Instance;
	}

	public boolean hasEmptyPath() {
		// since EMPTY_RETURN_STATE can only appear in the last position, we check last one
		return getReturnState(size() - 1) == EMPTY_RETURN_STATE;
	}

	@Override
	public final int hashCode() {
		return cachedHashCode;
	}

	@Override
	public abstract boolean equals(Object obj);

	protected static int calculateEmptyHashCode() {
		int hash = MurmurHash.initialize(INITIAL_HASH);
		hash = MurmurHash.finish(hash, 0);
		return hash;
	}

	protected static int calculateHashCode(PredictionContext parent, int returnState) {
		int hash = MurmurHash.initialize(INITIAL_HASH);
		hash = MurmurHash.update(hash, parent);
		hash = MurmurHash.update(hash, returnState);
		hash = MurmurHash.finish(hash, 2);
		return hash;
	}

	protected static int calculateHashCode(PredictionContext[] parents, int[] returnStates) {
		int hash = MurmurHash.initialize(INITIAL_HASH);

		for (PredictionContext parent : parents) {
			hash = MurmurHash.update(hash, parent);
		}

		for (int returnState : returnStates) {
			hash = MurmurHash.update(hash, returnState);
		}

		hash = MurmurHash.finish(hash, 2 * parents.length);
		return hash;
	}

	// dispatch
	public static PredictionContext merge(
		PredictionContext a, PredictionContext b,
		boolean rootIsWildcard,
		DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)
	{
		assert a!=null && b!=null; // must be empty context, never null

		// share same graph if both same
		if ( a==b || a.equals(b) ) return a;

		if ( a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {
			return mergeSingletons((SingletonPredictionContext)a,
								   (SingletonPredictionContext)b,
								   rootIsWildcard, mergeCache);
		}

		// At least one of a or b is array
		// If one is $ and rootIsWildcard, return $ as * wildcard
		if ( rootIsWildcard ) {
			if ( a instanceof EmptyPredictionContext ) return a;
			if ( b instanceof EmptyPredictionContext ) return b;
		}

		// convert singleton so both are arrays to normalize
		if ( a instanceof SingletonPredictionContext ) {
			a = new ArrayPredictionContext((SingletonPredictionContext)a);
		}
		if ( b instanceof SingletonPredictionContext) {
			b = new ArrayPredictionContext((SingletonPredictionContext)b);
		}
		return mergeArrays((ArrayPredictionContext) a, (ArrayPredictionContext) b,
						   rootIsWildcard, mergeCache);
	}

	/**
	 * Merge two {@link SingletonPredictionContext} instances.
	 *
	 *
Stack tops equal, parents merge is same; return left graph.

	 * <embed src="images/SingletonMerge_SameRootSamePar.svg" type="image/svg+xml"/>

	 *
	 *
Same stack top, parents differ; merge parents giving array node, then
	 * remainders of those graphs. A new root node is created to point to the
	 * merged parents.

	 * <embed src="images/SingletonMerge_SameRootDiffPar.svg" type="image/svg+xml"/>

	 *
	 *
Different stack tops pointing to same parent. Make array node for the
	 * root where both element in the root point to the same (original)
	 * parent.

	 * <embed src="images/SingletonMerge_DiffRootSamePar.svg" type="image/svg+xml"/>

	 *
	 *
Different stack tops pointing to different parents. Make array node for
	 * the root where each element points to the corresponding original
	 * parent.

	 * <embed src="images/SingletonMerge_DiffRootDiffPar.svg" type="image/svg+xml"/>

	 *
	 * @param a the first {@link SingletonPredictionContext}
	 * @param b the second {@link SingletonPredictionContext}
	 * @param rootIsWildcard {@code true} if this is a local-context merge,
	 * otherwise false to indicate a full-context merge
	 * @param mergeCache
	 */
	public static PredictionContext mergeSingletons(
		SingletonPredictionContext a,
		SingletonPredictionContext b,
		boolean rootIsWildcard,
		DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)
	{
		if ( mergeCache!=null ) {
			PredictionContext previous = mergeCache.get(a,b);
			if ( previous!=null ) return previous;
			previous = mergeCache.get(b,a);
			if ( previous!=null ) return previous;
		}

		PredictionContext rootMerge = mergeRoot(a, b, rootIsWildcard);
		if ( rootMerge!=null ) {
			if ( mergeCache!=null ) mergeCache.put(a, b, rootMerge);
			return rootMerge;
		}

		if ( a.returnState==b.returnState ) { // a == b
			PredictionContext parent = merge(a.parent, b.parent, rootIsWildcard, mergeCache);
			// if parent is same as existing a or b parent or reduced to a parent, return it
			if ( parent == a.parent ) return a; // ax + bx = ax, if a=b
			if ( parent == b.parent ) return b; // ax + bx = bx, if a=b
			// else: ax + ay = a'[x,y]
			// merge parents x and y, giving array node with x,y then remainders
			// of those graphs.  dup a, a' points at merged array
			// new joined parent so create new singleton pointing to it, a'
			PredictionContext a_ = SingletonPredictionContext.create(parent, a.returnState);
			if ( mergeCache!=null ) mergeCache.put(a, b, a_);
			return a_;
		}
		else { // a != b payloads differ
			// see if we can collapse parents due to $+x parents if local ctx
			PredictionContext singleParent = null;
			if ( a==b || (a.parent!=null && a.parent.equals(b.parent)) ) { // ax + bx = [a,b]x
				singleParent = a.parent;
			}
			if ( singleParent!=null ) {	// parents are same
				// sort payloads and use same parent
				int[] payloads = {a.returnState, b.returnState};
				if ( a.returnState > b.returnState ) {
					payloads[0] = b.returnState;
					payloads[1] = a.returnState;
				}
				PredictionContext[] parents = {singleParent, singleParent};
				PredictionContext a_ = new ArrayPredictionContext(parents, payloads);
				if ( mergeCache!=null ) mergeCache.put(a, b, a_);
				return a_;
			}
			// parents differ and can't merge them. Just pack together
			// into array; can't merge.
			// ax + by = [ax,by]
			int[] payloads = {a.returnState, b.returnState};
			PredictionContext[] parents = {a.parent, b.parent};
			if ( a.returnState > b.returnState ) { // sort by payload
				payloads[0] = b.returnState;
				payloads[1] = a.returnState;
				parents = new PredictionContext[] {b.parent, a.parent};
			}
			PredictionContext a_ = new ArrayPredictionContext(parents, payloads);
			if ( mergeCache!=null ) mergeCache.put(a, b, a_);
			return a_;
		}
	}

	/**
	 * Handle case where at least one of {@code a} or {@code b} is
	 * {@link EmptyPredictionContext#Instance}. In the following diagrams, the symbol {@code $} is used
	 * to represent {@link EmptyPredictionContext#Instance}.
	 *
	 *
Local-Context Merges

	 *
	 *
These local-context merge operations are used when {@code rootIsWildcard}
	 * is true.

	 *
	 *
{@link EmptyPredictionContext#Instance} is superset of any graph; return {@link EmptyPredictionContext#Instance}.

	 * <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/>

	 *
	 *
{@link EmptyPredictionContext#Instance} and anything is {@code #EMPTY}, so merged parent is
	 * {@code #EMPTY}; return left graph.

	 * <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/>

	 *
	 *
Special case of last merge if local context.

	 * <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/>

	 *
	 *
Full-Context Merges

	 *
	 *
These full-context merge operations are used when {@code rootIsWildcard}
	 * is false.

	 *
	 *
<embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/>

	 *
	 *
Must keep all contexts; {@link EmptyPredictionContext#Instance} in array is a special value (and
	 * null parent).

	 * <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/>

	 *
	 *
<embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/>

	 *
	 * @param a the first {@link SingletonPredictionContext}
	 * @param b the second {@link SingletonPredictionContext}
	 * @param rootIsWildcard {@code true} if this is a local-context merge,
	 * otherwise false to indicate a full-context merge
	 */
	public static PredictionContext mergeRoot(SingletonPredictionContext a,
											  SingletonPredictionContext b,
											  boolean rootIsWildcard)
	{
		if ( rootIsWildcard ) {
			if ( a == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance;  // * + b = *
			if ( b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance;  // a + * = *
		}
		else {
			if ( a == EmptyPredictionContext.Instance && b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // $ + $ = $
			if ( a == EmptyPredictionContext.Instance) { // $ + x = [x,$]
				int[] payloads = {b.returnState, EMPTY_RETURN_STATE};
				PredictionContext[] parents = {b.parent, null};
				PredictionContext joined =
					new ArrayPredictionContext(parents, payloads);
				return joined;
			}
			if ( b == EmptyPredictionContext.Instance) { // x + $ = [x,$] ($ is always last if present)
				int[] payloads = {a.returnState, EMPTY_RETURN_STATE};
				PredictionContext[] parents = {a.parent, null};
				PredictionContext joined =
					new ArrayPredictionContext(parents, payloads);
				return joined;
			}
		}
		return null;
	}

	/**
	 * Merge two {@link ArrayPredictionContext} instances.
	 *
	 *
Different tops, different parents.

	 * <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/>

	 *
	 *
Shared top, same parents.

	 * <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/>

	 *
	 *
Shared top, different parents.

	 * <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/>

	 *
	 *
Shared top, all shared parents.

	 * <embed src="images/ArrayMerge_ShareTopSharePar.svg" type="image/svg+xml"/>

	 *
	 *
Equal tops, merge parents and reduce top to
	 * {@link SingletonPredictionContext}.

	 * <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/>

	 */
	public static PredictionContext mergeArrays(
		ArrayPredictionContext a,
		ArrayPredictionContext b,
		boolean rootIsWildcard,
		DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)
	{
		if ( mergeCache!=null ) {
			PredictionContext previous = mergeCache.get(a,b);
			if ( previous!=null ) return previous;
			previous = mergeCache.get(b,a);
			if ( previous!=null ) return previous;
		}

		// merge sorted payloads a + b => M
		int i = 0; // walks a
		int j = 0; // walks b
		int k = 0; // walks target M array

		int[] mergedReturnStates =
			new int[a.returnStates.length + b.returnStates.length];
		PredictionContext[] mergedParents =
			new PredictionContext[a.returnStates.length + b.returnStates.length];
		// walk and merge to yield mergedParents, mergedReturnStates
		while ( i<a.returnStates.length && j ax
				if ( both$ || ax_ax ) {
					mergedParents[k] = a_parent; // choose left
					mergedReturnStates[k] = payload;
				}
				else { // ax+ay -> a'[x,y]
					PredictionContext mergedParent =
						merge(a_parent, b_parent, rootIsWildcard, mergeCache);
					mergedParents[k] = mergedParent;
					mergedReturnStates[k] = payload;
				}
				i++; // hop over left one as usual
				j++; // but also skip one in right side since we merge
			}
			else if ( a.returnStates[i] a, copy b[j] to M
				mergedParents[k] = b_parent;
				mergedReturnStates[k] = b.returnStates[j];
				j++;
			}
			k++;
		}

		// copy over any payloads remaining in either array
		if (i < a.returnStates.length) {
			for (int p = i; p < a.returnStates.length; p++) {
				mergedParents[k] = a.parents[p];
				mergedReturnStates[k] = a.returnStates[p];
				k++;
			}
		}
		else {
			for (int p = j; p < b.returnStates.length; p++) {
				mergedParents[k] = b.parents[p];
				mergedReturnStates[k] = b.returnStates[p];
				k++;
			}
		}

		// trim merged if we combined a few that had same stack tops
		if ( k < mergedParents.length ) { // write index < last position; trim
			if ( k == 1 ) { // for just one merged element, return singleton top
				PredictionContext a_ =
					SingletonPredictionContext.create(mergedParents[0],
													  mergedReturnStates[0]);
				if ( mergeCache!=null ) mergeCache.put(a,b,a_);
				return a_;
			}
			mergedParents = Arrays.copyOf(mergedParents, k);
			mergedReturnStates = Arrays.copyOf(mergedReturnStates, k);
		}

		PredictionContext M =
			new ArrayPredictionContext(mergedParents, mergedReturnStates);

		// if we created same array as a or b, return that instead
		// TODO: track whether this is possible above during merge sort for speed
		if ( M.equals(a) ) {
			if ( mergeCache!=null ) mergeCache.put(a,b,a);
			return a;
		}
		if ( M.equals(b) ) {
			if ( mergeCache!=null ) mergeCache.put(a,b,b);
			return b;
		}

		combineCommonParents(mergedParents);

		if ( mergeCache!=null ) mergeCache.put(a,b,M);
		return M;
	}

	/**
	 * Make pass over all M {@code parents}; merge any {@code equals()}
	 * ones.
	 */
	protected static void combineCommonParents(PredictionContext[] parents) {
		Map<PredictionContext, PredictionContext> uniqueParents =
			new HashMap<PredictionContext, PredictionContext>();

		for (int p = 0; p < parents.length; p++) {
			PredictionContext parent = parents[p];
			if ( !uniqueParents.containsKey(parent) ) { // don't replace
				uniqueParents.put(parent, parent);
			}
		}

		for (int p = 0; p < parents.length; p++) {
			parents[p] = uniqueParents.get(parents[p]);
		}
	}

	public static String toDOTString(PredictionContext context) {
		if ( context==null ) return "";
		StringBuilder buf = new StringBuilder();
		buf.append("digraph G {\n");
		buf.append("rankdir=LR;\n");

		List<PredictionContext> nodes = getAllContextNodes(context);
		Collections.sort(nodes, new Comparator<PredictionContext>() {
			@Override
			public int compare(PredictionContext o1, PredictionContext o2) {
				return o1.id - o2.id;
			}
		});

		for (PredictionContext current : nodes) {
			if ( current instanceof SingletonPredictionContext ) {
				String s = String.valueOf(current.id);
				buf.append("  s").append(s);
				String returnState = String.valueOf(current.getReturnState(0));
				if ( current instanceof EmptyPredictionContext ) returnState = "$";
				buf.append(" [label=\"").append(returnState).append("\"];\n");
				continue;
			}
			ArrayPredictionContext arr = (ArrayPredictionContext)current;
			buf.append("  s").append(arr.id);
			buf.append(" [shape=box, label=\"");
			buf.append("[");
			boolean first = true;
			for (int inv : arr.returnStates) {
				if ( !first ) buf.append(", ");
				if ( inv == EMPTY_RETURN_STATE ) buf.append("$");
				else buf.append(inv);
				first = false;
			}
			buf.append("]");
			buf.append("\"];\n");
		}

		for (PredictionContext current : nodes) {
			if ( current== EmptyPredictionContext.Instance) continue;
			for (int i = 0; i < current.size(); i++) {
				if ( current.getParent(i)==null ) continue;
				String s = String.valueOf(current.id);
				buf.append("  s").append(s);
				buf.append("->");
				buf.append("s");
				buf.append(current.getParent(i).id);
				if ( current.size()>1 ) buf.append(" [label=\"parent["+i+"]\"];\n");
				else buf.append(";\n");
			}
		}

		buf.append("}\n");
		return buf.toString();
	}

	// From Sam
	public static PredictionContext getCachedContext(
		PredictionContext context,
		PredictionContextCache contextCache,
		IdentityHashMap<PredictionContext, PredictionContext> visited)
	{
		if (context.isEmpty()) {
			return context;
		}

		PredictionContext existing = visited.get(context);
		if (existing != null) {
			return existing;
		}

		existing = contextCache.get(context);
		if (existing != null) {
			visited.put(context, existing);
			return existing;
		}

		boolean changed = false;
		PredictionContext[] parents = new PredictionContext[context.size()];
		for (int i = 0; i < parents.length; i++) {
			PredictionContext parent = getCachedContext(context.getParent(i), contextCache, visited);
			if (changed || parent != context.getParent(i)) {
				if (!changed) {
					parents = new PredictionContext[context.size()];
					for (int j = 0; j < context.size(); j++) {
						parents[j] = context.getParent(j);
					}

					changed = true;
				}

				parents[i] = parent;
			}
		}

		if (!changed) {
			contextCache.add(context);
			visited.put(context, context);
			return context;
		}

		PredictionContext updated;
		if (parents.length == 0) {
			updated = EmptyPredictionContext.Instance;
		}
		else if (parents.length == 1) {
			updated = SingletonPredictionContext.create(parents[0], context.getReturnState(0));
		}
		else {
			ArrayPredictionContext arrayPredictionContext = (ArrayPredictionContext)context;
			updated = new ArrayPredictionContext(parents, arrayPredictionContext.returnStates);
		}

		contextCache.add(updated);
		visited.put(updated, updated);
		visited.put(context, updated);

		return updated;
	}

//	// extra structures, but cut/paste/morphed works, so leave it.
//	// seems to do a breadth-first walk
//	public static List<PredictionContext> getAllNodes(PredictionContext context) {
//		Map<PredictionContext, PredictionContext> visited =
//			new IdentityHashMap<PredictionContext, PredictionContext>();
//		Deque<PredictionContext> workList = new ArrayDeque<PredictionContext>();
//		workList.add(context);
//		visited.put(context, context);
//		List<PredictionContext> nodes = new ArrayList<PredictionContext>();
//		while (!workList.isEmpty()) {
//			PredictionContext current = workList.pop();
//			nodes.add(current);
//			for (int i = 0; i < current.size(); i++) {
//				PredictionContext parent = current.getParent(i);
//				if ( parent!=null && visited.put(parent, parent) == null) {
//					workList.push(parent);
//				}
//			}
//		}
//		return nodes;
//	}

	// ter's recursive version of Sam's getAllNodes()
	public static List<PredictionContext> getAllContextNodes(PredictionContext context) {
		List<PredictionContext> nodes = new ArrayList<PredictionContext>();
		Map<PredictionContext, PredictionContext> visited =
			new IdentityHashMap<PredictionContext, PredictionContext>();
		getAllContextNodes_(context, nodes, visited);
		return nodes;
	}

	public static void getAllContextNodes_(PredictionContext context,
										   List<PredictionContext> nodes,
										   Map<PredictionContext, PredictionContext> visited)
	{
		if ( context==null || visited.containsKey(context) ) return;
		visited.put(context, context);
		nodes.add(context);
		for (int i = 0; i < context.size(); i++) {
			getAllContextNodes_(context.getParent(i), nodes, visited);
		}
	}

	public String toString(Recognizer<?,?> recog) {
		return toString();
//		return toString(recog, ParserRuleContext.EMPTY);
	}

	public String[] toStrings(Recognizer<?, ?> recognizer, int currentState) {
		return toStrings(recognizer, EmptyPredictionContext.Instance, currentState);
	}

	// FROM SAM
	public String[] toStrings(Recognizer<?, ?> recognizer, PredictionContext stop, int currentState) {
		List<String> result = new ArrayList<String>();

		outer:
		for (int perm = 0; ; perm++) {
			int offset = 0;
			boolean last = true;
			PredictionContext p = this;
			int stateNumber = currentState;
			StringBuilder localBuffer = new StringBuilder();
			localBuffer.append("[");
			while ( !p.isEmpty() && p != stop ) {
				int index = 0;
				if (p.size() > 0) {
					int bits = 1;
					while ((1 << bits) < p.size()) {
						bits++;
					}

					int mask = (1 << bits) - 1;
					index = (perm >> offset) & mask;
					last &= index >= p.size() - 1;
					if (index >= p.size()) {
						continue outer;
					}
					offset += bits;
				}

				if ( recognizer!=null ) {
					if (localBuffer.length() > 1) {
						// first char is '[', if more than that this isn't the first rule
						localBuffer.append(' ');
					}

					ATN atn = recognizer.getATN();
					ATNState s = atn.states.get(stateNumber);
					String ruleName = recognizer.getRuleNames()[s.ruleIndex];
					localBuffer.append(ruleName);
				}
				else if ( p.getReturnState(index)!= EMPTY_RETURN_STATE) {
					if ( !p.isEmpty() ) {
						if (localBuffer.length() > 1) {
							// first char is '[', if more than that this isn't the first rule
							localBuffer.append(' ');
						}

						localBuffer.append(p.getReturnState(index));
					}
				}
				stateNumber = p.getReturnState(index);
				p = p.getParent(index);
			}
			localBuffer.append("]");
			result.add(localBuffer.toString());

			if (last) {
				break;
			}
		}

		return result.toArray(new String[0]);
	}
}


text:
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/bootmem.h>
#include <linux/gfp.h>

#include <asm/setup.h>
#include <asm/segment.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/machdep.h>

/*
 * ZERO_PAGE is a special page that is used for zero-initialized
 * data and COW.
 */
void *empty_zero_page;

extern unsigned long memory_start;
extern unsigned long memory_end;

/*
 * paging_init() continues the virtual memory environment setup which
 * was begun by the code in arch/head.S.
 * The parameters are pointers to where to stick the starting and ending
 * addresses of available kernel virtual memory.
 */
void __init paging_init(void)
{
	/*
	 * Make sure start_mem is page aligned, otherwise bootmem and
	 * page_alloc get different views of the world.
	 */
	unsigned long end_mem   = memory_end & PAGE_MASK;
	unsigned long zones_size[MAX_NR_ZONES] = {0, };

	empty_zero_page = alloc_bootmem_pages(PAGE_SIZE);
	memset(empty_zero_page, 0, PAGE_SIZE);

	/*
	 * Set up SFC/DFC registers (user data space).
	 */
	set_fs (USER_DS);

	zones_size[ZONE_DMA] = (end_mem - PAGE_OFFSET) >> PAGE_SHIFT;
	free_area_init(zones_size);
}

void __init mem_init(void)
{
	int codek = 0, datak = 0, initk = 0;
	unsigned long tmp;
	extern char _etext, _stext, _sdata, _ebss, __init_begin, __init_end;
	extern unsigned int _ramend, _rambase;
	unsigned long len = _ramend - _rambase;
	unsigned long start_mem = memory_start; /* DAVIDM - these must start at end of kernel */
	unsigned long end_mem   = memory_end; /* DAVIDM - this must not include kernel stack at top */

	pr_debug("Mem_init: start=%lx, end=%lx\n", start_mem, end_mem);

	end_mem &= PAGE_MASK;
	high_memory = (void *) end_mem;

	start_mem = PAGE_ALIGN(start_mem);
	max_mapnr = num_physpages = (((unsigned long) high_memory) - PAGE_OFFSET) >> PAGE_SHIFT;

	/* this will put all memory onto the freelists */
	totalram_pages = free_all_bootmem();

	codek = (&_etext - &_stext) >> 10;
	datak = (&_ebss - &_sdata) >> 10;
	initk = (&__init_begin - &__init_end) >> 10;

	tmp = nr_free_pages() << PAGE_SHIFT;
	printk(KERN_INFO "Memory available: %luk/%luk RAM, (%dk kernel code, %dk data)\n",
	       tmp >> 10,
	       len >> 10,
	       codek,
	       datak
	       );
}

#ifdef CONFIG_BLK_DEV_INITRD
void free_initrd_mem(unsigned long start, unsigned long end)
{
	int pages = 0;
	for (; start < end; start += PAGE_SIZE) {
		ClearPageReserved(virt_to_page(start));
		init_page_count(virt_to_page(start));
		free_page(start);
		totalram_pages++;
		pages++;
	}
	pr_notice("Freeing initrd memory: %luk freed\n",
		  pages * (PAGE_SIZE / 1024));
}
#endif

void free_initmem(void)
{
#ifdef CONFIG_RAMKERNEL
	unsigned long addr;
	extern char __init_begin, __init_end;
	/*
	 * The following code should be cool even if these sections
	 * are not page aligned.
	 */
	addr = PAGE_ALIGN((unsigned long)(&__init_begin));
	/* next to check that the page we free is not a partial page */
	for (; addr + PAGE_SIZE < (unsigned long)(&__init_end); addr +=PAGE_SIZE) {
		ClearPageReserved(virt_to_page(addr));
		init_page_count(virt_to_page(addr));
		free_page(addr);
		totalram_pages++;
	}
	pr_notice("Freeing unused kernel memory: %luk freed (0x%x - 0x%x)\n",
			(addr - PAGE_ALIGN((long) &__init_begin)) >> 10,
			(int)(PAGE_ALIGN((unsigned long)(&__init_begin))),
			(int)(addr - PAGE_SIZE));
#endif
}


text:
namespace Task2PrintStatistics
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class StatisticsPrint
    {
        public void PrintStatistics(double[] numbers)
        {
            Console.WriteLine("Statistics for {0}:", numbers);
            double smallestNumber = numbers.Min();
            this.PrintMin(smallestNumber);
            double largestNumber = numbers.Max();
            this.PrintMax(largestNumber);
            double average = numbers.Average();
            this.PrintAverage(average);
        }

        private void PrintMin(double smallestNumber)
        {
            Console.WriteLine("The smallest number is {0}.", smallestNumber);
        }

        private void PrintMax(double largestNumber)
        {
            Console.WriteLine("The largest number is {0}.", largestNumber);
        }

        private void PrintAverage(double average)
        {
            Console.WriteLine("The average of the numbers is {0}.", average);
        }
    }
}


text:
/*===========================
Framework7 Swiper Additions
===========================*/
app.swiper = function (container, params) {
    return new Swiper(container, params);
};
app.initPageSwiper = function (pageContainer) {
    var page = $(pageContainer);
    var swipers = page.find('.swiper-init');
    if (swipers.length === 0) return;
    function destroySwiperOnRemove(slider) {
        function destroySwiper() {
            slider.destroy();
            page.off('pageBeforeRemove', destroySwiper);
        }
        page.on('pageBeforeRemove', destroySwiper);
    }
    for (var i = 0; i < swipers.length; i++) {
        var swiper = swipers.eq(i);
        var params;
        if (swiper.data('swiper')) {
            params = JSON.parse(swiper.data('swiper'));
        }
        else {
            params = swiper.dataset();
        }
        var _slider = app.swiper(swiper[0], params);
        destroySwiperOnRemove(_slider);
    }
};
app.reinitPageSwiper = function (pageContainer) {
    var page = $(pageContainer);
    var sliders = page.find('.swiper-init');
    if (sliders.length === 0) return;
    for (var i = 0; i < sliders.length; i++) {
        var sliderInstance = sliders[0].swiper;
        if (sliderInstance) {
            sliderInstance.update(true);
        }
    }
};


text:
use std::iter::Peekable;
use std::str::*;
use super::token::*;

#[derive(Debug)]
pub struct Lexer<'a> {
    source: &'a str,
    chars: Peekable<CharIndices<'a>>,
    is_done: bool,
}

pub type Result<T> = ::std::result::Result<T, Error>;

impl<'a> Lexer<'a> {
    pub fn new(source: &str) -> Lexer {
        Lexer {
            source: source,
            chars: source.char_indices().peekable(),
            is_done: false,
        }
    }

    pub fn next(&mut self) -> Result<(Token, Span)> {
        // Start by eating all whitespace before the next valid token.
        let (start_index, character) = {
            let mut start = None;
            while let Some((index, character)) = self.chars.next() {
                if !character.is_whitespace() {
                    // This is the first character of the current token. Mark the starting index and
                    // break the loop so we can begin reading the token.
                    start = Some((index, character));
                    break;
                }
            }

            match start {
                Some(index_char) => index_char,
                None => {
                    self.is_done = true;

                    // Never found a non-whitespace character, so we're at the end of the file.
                    let span = Span::new(self.source.len(), self.source.len());
                    return Ok((Token::EndOfFile, span))
                },
            }
        };

        // See if token is an identifier.
        if character.is_ident() {
            return self.parse_ident(start_index)
        }

        // See if token is a number literal.
        if character.is_numeric_part() {
            return unimplemented!();
        }

        // See if character is string literal.
        if character == '"' {
            return unimplemented!();
        }

        // See if token is program literal.
        if character == '{' {
            return self.parse_program_literal(start_index);
        }

        // Single-character symbols.
        let token = match character {
            ';' => Token::SemiColon,
            '=' => Token::Eq,
            ':' => Token::Colon,

            _ => {
                self.is_done = true;

                return Err(Error {
                    span: Span::new(start_index, start_index + 1),
                    data: ErrorData::IllegalSymbol(character),
                });
            },
        };

        Ok((token, Span::new(start_index, start_index + 1)))
    }

    /// Checks if the lexer is done.
    ///
    /// Returns `true` if the lexer reached the end of the file or found a token error.
    pub fn is_done(&self) -> bool {
        self.is_done
    }

    fn parse_ident(&mut self, start_index: usize) -> Result<(Token, Span)> {
        while let Some(&(end_index, character)) = self.chars.peek() {
            if !character.is_ident() {
                let word = &self.source[start_index .. end_index];
                let span = Span::new(start_index, end_index);

                let token = match word {
                    "property" => Token::Property,
                    "program" => Token::Program,
                    _ => Token::Identifier,
                };

                return Ok((token, span))
            }

            // Consume the item we peeked at.
            self.chars.next();
        }

        Ok((Token::Identifier, Span::new(start_index, self.source.len())))
    }

    fn parse_program_literal(&mut self, start_index: usize) -> Result<(Token, Span)> {
        // Start at depth 1 because we've already removed the opening '{'.
        let mut depth = 1;

        // Walk through the source string
        while let Some((end_index, character)) = self.chars.next() {
            match character {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        // We're at the end.
                        return Ok((Token::ProgramLiteral, Span::new(start_index + 1, end_index)));
                    }
                },
                _ => {}
            }
        }

        // Uh-oh, we got to the end and never closed the braces.
        self.is_done = true;
        Err(Error {
            span: Span::new(start_index, self.source.len()),
            data: ErrorData::UnclosedProgramLiteral,
        })
    }
}

/// Represents a lex error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Error {
    pub span: Span,
    pub data: ErrorData,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorData {
    IllegalSymbol(char),
    UnclosedProgramLiteral,
}

trait CharacterParseExt {
    fn is_ident_start(self) -> bool;
    fn is_ident(self) -> bool;
    fn is_numeric_part(self) -> bool;
}

impl CharacterParseExt for char {
    fn is_ident_start(self) -> bool {
        self.is_alphabetic() || self == '_'
    }

    fn is_ident(self) -> bool {
        self.is_alphanumeric() || self == '_'
    }

    fn is_numeric_part(self) -> bool {
        self.is_numeric() || self == '-'
    }
}


text:
using Obd2Net.Decoders;
using Obd2Net.InfrastructureContracts.Enums;

namespace Obd2Net.Commands.Mode1
{
    internal class FuelStatusCommand : OBDCommandBase<FuelStatusDecoder, string>
    {
        public FuelStatusCommand(FuelStatusDecoder decoder) :
            base(decoder, Mode.Mode1, "FUEL_STATUS", "Fuel System Status", "0103", 2, ECU.Engine, true)
        {
        }
    }
}


text:
package org.dsngroup.broke.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.dsngroup.broke.client.ClientContext;
import org.dsngroup.broke.protocol.*;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Tests of the Mqtt Message Handler of the client side.
 */
public class MqttMessageHandlerTest {

    /**
     * Test the PUBLISH message handling.
     */
    @Test
    public void publishTest() {
        EmbeddedChannel channel = new EmbeddedChannel(new MqttMessageHandler(new ClientContext("client_01")));

        String topic = "Foo";
        int packetId = 123;
        String payloadString = "Bar";

        // create publish message
        MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_LEAST_ONCE, false, 0);

        MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic, packetId);

        ByteBuf payload = Unpooled.copiedBuffer(payloadString.getBytes());
        payload.retain();
        MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader, mqttPublishVariableHeader, payload);

        EmbeddedChannel channel2 =
                new EmbeddedChannel(new MqttDecoder(),
                        new MqttMessageHandler(new ClientContext("client_01")),
                        MqttEncoder.INSTANCE);

        channel2.writeOutbound(mqttPublishMessage);
        ByteBuf pubMsgBuffer = (ByteBuf) channel2.readOutbound();
        ByteBuf pubMsgBufferCopy = Unpooled.copiedBuffer(pubMsgBuffer);

        if(pubMsgBuffer.isReadable()) {
            byte byte1 = pubMsgBuffer.readByte();
            byte remainingLength = pubMsgBuffer.readByte();
            String s1 = String.format("%8s", Integer.toBinaryString(byte1 & 0xFF)).replace(' ', '0');
            assertEquals( "00110010", s1);
            assertEquals(pubMsgBuffer.readableBytes(), remainingLength);

            int topicLengthActual = pubMsgBuffer.readShort();   // length = 2
            assertEquals(topic.length(), topicLengthActual);

            String topicActual = pubMsgBuffer.readBytes(topicLengthActual).toString(StandardCharsets.UTF_8);
            assertEquals(topic, topicActual);

            int packetIdActual = pubMsgBuffer.readShort();  // length=2
            assertEquals(packetId, packetIdActual);

            int payloadLengthActual = remainingLength-2-2-topicLengthActual;
            assertEquals(payloadLengthActual, payloadString.length());
            String payloadActual = pubMsgBuffer.readBytes(payloadLengthActual).toString(StandardCharsets.UTF_8);
            assertEquals(payloadString, payloadActual);
        }
        assertEquals(pubMsgBuffer.isReadable(), false);

        assertEquals(pubMsgBufferCopy.isReadable(), true);

        EmbeddedChannel embeddedChannel = new EmbeddedChannel(new MqttDecoder());
        embeddedChannel.writeInbound(pubMsgBufferCopy);
        MqttPublishMessage mqttPublishMessageOut = (MqttPublishMessage) embeddedChannel.readInbound();
        // channel.writeInbound(pubMsgBufferCopy);
        // MqttPublishMessage mqttPublishMessageOut = channel.readInbound();

        assertEquals(mqttPublishMessageOut.fixedHeader().messageType(), MqttMessageType.PUBLISH);
        embeddedChannel.pipeline().addLast(new MqttMessageHandler(new ClientContext("client_02")));
        embeddedChannel.writeInbound(mqttPublishMessageOut);
    }
}


text:
datum_string_t::datum_string_t() {
    init(0, "");
}

datum_string_t::datum_string_t(size_t _size, const char *_data) {
    init(_size, _data);
}

datum_string_t::datum_string_t(const shared_buf_ref_t<char> &_ref)
    : data_(_ref) { }

datum_string_t::datum_string_t(shared_buf_ref_t<char> &&_ref)
    : data_(std::move(_ref)) { }

datum_string_t::datum_string_t(const char *c_str) {
    init(strlen(c_str), c_str);
}

datum_string_t::datum_string_t(const std::string &str) {
    init(str.size(), str.data());
}

void datum_string_t::init(size_t _size, const char *_data) {
    const size_t str_offset = varint_uint64_serialized_size(_size);
    counted_t<shared_buf_t> buffer = shared_buf_t::create(str_offset + _size);
    serialize_varint_uint64_into_buf(_size, reinterpret_cast<uint8_t *>(buffer->data()));
    memcpy(buffer->data() + str_offset, _data, _size);
    data_ = shared_buf_ref_t<char>(std::move(buffer), 0);
}

const char *datum_string_t::data() const {
    const size_t str_size = size();
    size_t data_offset = varint_uint64_serialized_size(str_size);
    data_.guarantee_in_boundary(data_offset + str_size);
    return data_.get() + data_offset;
}

size_t datum_string_t::size() const {
    uint64_t res = 0;
    static_assert(sizeof(uint8_t) == sizeof(char), "sizeof(uint8_t) != sizeof(char)");
    buffer_read_stream_t data_stream(data_.get(), data_.get_safety_boundary());
    guarantee_deserialization(deserialize_varint_uint64(&data_stream, &res),
                              "wire_string size");
    guarantee(res <= static_cast<uint64_t>(std::numeric_limits<size_t>::max()));
    return static_cast<size_t>(res);
}

bool datum_string_t::empty() const {
    return size() == 0;
}

int datum_string_t::compare(const datum_string_t &other) const {
    return compare(other.size(), other.data());
}

int datum_string_t::compare(size_t other_size, const char *other_data) const {
    const size_t this_size = size();
    size_t common_size = std::min(this_size, other_size);
    int content_compare = memcmp(data(), other_data, common_size);
    if (content_compare == 0) {
        // Both strings have the same first `content_compare` characters.
        // Compare their lengths.
        if (this_size < other_size) {
            return -1;
        } else if (this_size > other_size) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return content_compare;
    }
}

bool datum_string_t::operator==(const char *other) const {
    return compare(strlen(other), other) == 0;
}
bool datum_string_t::operator!=(const char *other) const {
    return !(*this == other);
}

bool datum_string_t::operator==(const datum_string_t &other) const {
    if (size() != other.size()) {
        return false;
    }

    return compare(other) == 0;
}
bool datum_string_t::operator!=(const datum_string_t &other) const {
    return !operator==(other);
}
bool datum_string_t::operator<(const datum_string_t &other) const {
    return compare(other) < 0;
}
bool datum_string_t::operator>(const datum_string_t &other) const {
    return compare(other) > 0;
}
bool datum_string_t::operator<=(const datum_string_t &other) const {
    return compare(other) <= 0;
}
bool datum_string_t::operator>=(const datum_string_t &other) const {
    return compare(other) >= 0;
}

std::string datum_string_t::to_std() const {
    return std::string(data(), size());
}

datum_string_t concat(const datum_string_t &a, const datum_string_t &b) {
    const size_t a_size = a.size();
    const size_t b_size = b.size();
    const size_t str_offset = varint_uint64_serialized_size(a_size + b_size);
    counted_t<shared_buf_t> buf = shared_buf_t::create(str_offset + a_size + b_size);
    serialize_varint_uint64_into_buf(a_size + b_size,
                                     reinterpret_cast<uint8_t *>(buf->data(0)));
    memcpy(buf->data(str_offset), a.data(), a.size());
    memcpy(buf->data(str_offset + a.size()), b.data(), b.size());
    return datum_string_t(shared_buf_ref_t<char>(std::move(buf), 0));
}

void debug_print(printf_buffer_t *buf, const datum_string_t &s) {
    debug_print_quoted_string(buf, reinterpret_cast<const uint8_t *>(s.data()),
                              s.size());
}


text:
package com.moonlightpixels.jrpg.combat.stats;

import lombok.Data;

import java.util.function.Function;

@Data
public abstract class StatModifier implements Function<Integer, Integer> {
    private final Stat.Key stat;
}


text:
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    '.molecule/ansible_inventory').get_hosts('pytn-2017-centos')

def test_nginx_user(User):
    u = User('nginx')

    assert u.exists
    assert u.home == '/var/lib/nginx'

def test_index_file(File):
    f = File('/usr/share/nginx/html/index.html')

    assert f.exists
    assert f.user == 'root'
    assert f.group == 'root'
    assert f.mode == 0o755

    assert f.contains('Test Your Automation!')
    assert f.contains('Molecule CentOS')
    assert f.contains('Ansible managed:')


text:
var stream = require('readable-stream');
var util = require('util');
var fs = require('fs');

function JSONLineReader(source) {
  stream.Readable.call(this); //<co id="callout-streams-json-line-1" />
  this._source = source;
  this._foundLineEnd = false;
  this._buffer = '';

  source.on('readable', function() {
    this.read(0); //<co id="callout-streams-json-line-2" />
  }.bind(this));
}

util.inherits(JSONLineReader, stream.Readable); //<co id="callout-streams-json-line-3" />

JSONLineReader.prototype._read = function(size) { //<co id="callout-streams-json-line-4" />
  var chunk;
  var line;
  var lineIndex;
  var result;

  if (this._buffer.length === 0) { //<co id="callout-streams-json-line-5" />
    chunk = this._source.read();
    this._buffer += chunk;
  }

  lineIndex = this._buffer.indexOf('\n');
  if (lineIndex !== -1) {
    line = this._buffer.slice(0, lineIndex); //<co id="callout-streams-json-line-6" />
    if (line) {
      result = JSON.parse(line);
      this._buffer = this._buffer.slice(lineIndex + 1);
      this.emit('object', result); //<co id="callout-streams-json-line-7" />
      this.push(util.inspect(result)); //<co id="callout-streams-json-line-8" />
    } else {
      this._buffer = this._buffer.slice(1);
    }
  }
};

var input = fs.createReadStream(__dirname + '/json-lines.txt', { encoding: 'utf8' }); //<co id="callout-streams-json-line-9" />
var jsonLineReader = new JSONLineReader(input);

jsonLineReader.on('object', function(obj) {
  console.log('pos:', obj.position, '- letter:', obj.letter);
});


text:
//
//  LGAutoPkgRecipe.m
//  AutoPkgr
//
//  Copyright 2015 The Linde Group, Inc.
//
//  Licensed 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.
//

#import "LGAutoPkgRecipe.h"
#import "LGAutoPkgTask.h"

#import <glob.h>

// MakeCatalogs recipe identifier string
static NSString *const kLGMakeCatalogsIdentifier = @"com.github.autopkg.munki.makecatalogs";

// Dispatch queue for enabling / disabling recipe
static dispatch_queue_t autopkgr_recipe_write_queue()
{
    static dispatch_queue_t autopkgr_recipe_write_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        autopkgr_recipe_write_queue = dispatch_queue_create("com.lindegroup.autopkgr.recipe.write.queue", DISPATCH_QUEUE_SERIAL );
    });

    return autopkgr_recipe_write_queue;
}

static NSMutableDictionary *_identifierURLStore = nil;

#pragma mark - Recipes
//////////////////////////////////////////////////////////////////////////
// Recipes                                                             ///
//////////////////////////////////////////////////////////////////////////

@implementation LGAutoPkgRecipe {
@private
    /* This is the actual iVar used for the `enabled` property
     * which when initialize is -1. We then check for that value
     * during the -enabled getter and know if we need to do a more
     * expensive check that initializes an array */
    OSStatus _enabledInitialized;
    NSURL *_recipeFileURL;
}

@synthesize Description = _Description, MinimumVersion = _MinimumVersion;

- (NSString *)description
{
    return [NSString stringWithFormat:@"Name: %@ Identifier: %@ Parent: %@", _Name, _Identifier, self.ParentRecipe];
}

- (instancetype)initWithRecipeFile:(NSURL *)recipeFile isOverride:(BOOL)isOverride
{
    // Don't Initialize anything if we can't determine a recipe identifier.
    NSDictionary *reciptPlist = [NSDictionary dictionaryWithContentsOfURL:recipeFile];
    NSString *identifier = reciptPlist[kLGAutoPkgRecipeIdentifierKey] ?: reciptPlist[@"Input"][@"IDENTIFIER"];

    if (identifier && (self = [super init])) {
        _recipePlist = reciptPlist;
        _Identifier = identifier;

        _recipeFileURL = recipeFile;
        _Name = [[recipeFile lastPathComponent] stringByDeletingPathExtension];

        _FilePath = recipeFile.path;
        _isOverride = isOverride;
        _enabledInitialized = -1;

        [_identifierURLStore setObject:_recipeFileURL forKey:_Identifier];
        return self;
    }
    return nil;
}

- (NSString *)Description
{
    return _recipePlist[NSStringFromSelector(_cmd)] ?: [self objectForKey:NSStringFromSelector(_cmd) ofIdentifier:self.ParentRecipe];
}

- (NSString *)MinimumVersion
{
    return _recipePlist[NSStringFromSelector(_cmd)] ?: [self objectForKey:NSStringFromSelector(_cmd) ofIdentifier:self.ParentRecipe];
}

- (NSString *)ParentRecipe
{
    return _recipePlist[kLGAutoPkgRecipeParentKey];
}

- (NSArray *)ParentRecipes
{
    NSMutableArray *parents;
    NSString *parentRecipeID = self.ParentRecipe;

    if (parentRecipeID) {
        // Don't back this up with an iVar since when new recipe repos are
        // added this could actually trace the origin further back.
        parents = [NSMutableArray arrayWithObject:parentRecipeID];

        while (true) {
            NSURL *parentRecipeURL = [_identifierURLStore objectForKey:parentRecipeID];
            if (parentRecipeURL) {
                NSDictionary *recipePlist = [NSDictionary dictionaryWithContentsOfURL:parentRecipeURL];
                parentRecipeID = recipePlist[kLGAutoPkgRecipeParentKey];
                if (parentRecipeID) {
                    [parents addObject:parentRecipeID];
                }
            } else {
                break;
            }
        }
    }
    return [parents copy];
}

- (BOOL)isMissingParent
{
    if (self.ParentRecipe) {
        return ([_identifierURLStore objectForKey:self.ParentRecipe] == nil);
    }
    return NO;
}

- (BOOL)recipeConfigError
{
    return self.isMissingParent;
}

- (NSDictionary *)Input
{
    return _recipePlist[NSStringFromSelector(_cmd)];
}

- (NSArray *)Process
{
    return _recipePlist[NSStringFromSelector(_cmd)];
}

#pragma mark - Enabled
- (void)enableRecipe:(NSButton *)sender
{
    if ([sender isKindOfClass:[NSButton class]]) {
        self.enabled = sender.state;
        // Double check that enabling of the recipe was successful.
        dispatch_async(autopkgr_recipe_write_queue(), ^{
            sender.state = [[[self class] activeRecipes] containsObject:self.Identifier];
        });
    }
}

- (BOOL)isEnabled
{
    if (_enabledInitialized == -1) {
        _enabledInitialized = [[[self class] activeRecipes] containsObject:self.Identifier];
    }
    return _enabledInitialized;
}

- (void)setEnabled:(BOOL)enabled
{
    /* We automatically handle the enabling of the makecatalogs recipe
     * so don't do anything if that's the one getting enabled. */
    if ([self.Identifier isEqualToString:kLGMakeCatalogsIdentifier]) {
        return;
    }

    /* This is all dispatched to a serial queue so a race condition doesn't arise
     * when multiple recipes are added or removed in rapid succession */
    dispatch_async(autopkgr_recipe_write_queue(), ^{
        NSError *error;

        __block NSMutableArray *currentList = [[NSMutableArray alloc] init];

        NSString *recipeListFile = [[self class] defaultRecipeList];
        NSString *fileContents = [NSString stringWithContentsOfFile:recipeListFile encoding:NSUTF8StringEncoding error:nil];

        /* Get the recipe list and split it by lines and turn it into an array */
        NSArray *existingList;
        if ((existingList = fileContents.split_byLine.filtered_noEmptyStrings)) {
            [currentList addObjectsFromArray:existingList];
        }

        /* Start by removing any instance of makecatalogs from the list, it's added back in later */
        [currentList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj isEqualToString:kLGMakeCatalogsIdentifier]) {
                [currentList removeObject:obj];
            }
        }];

        if (enabled) {
            if (![currentList containsObject:self.Identifier]) {
                [currentList insertObject:self.Identifier atIndex:0];
            }
        } else {
            [currentList removeObject:self.Identifier];
        }

        /* Enumerate over the list to see if there are any .munki recipes
         * now listed. If so re-add the makecatalogs recipe. */
        [currentList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj rangeOfString:@"munki"].location != NSNotFound ) {
                [currentList addObject:kLGMakeCatalogsIdentifier];
                *stop = YES;
            }
        }];

        NSString *recipe_list = [currentList componentsJoinedByString:@"\n"];
        if (![recipe_list writeToFile:recipeListFile atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
            NSLog(@"Error while writing %@. %@", recipeListFile, error);
            return;
        }

        currentList = nil;
        _enabledInitialized = enabled;
    });
}

#pragma mark - Checks
- (BOOL)hasStepProcessor:(NSString *)step
{
    NSMutableArray *considered = [NSMutableArray arrayWithObject:_recipePlist];

    for (NSString *identifier in self.ParentRecipes) {
        NSDictionary *plist = [self recipePlistForIdentifier:identifier];
        if (plist) {
            [considered addObject:plist];
        }
    }

    for (NSDictionary *plist in considered) {
        NSArray *processes = plist[kLGAutoPkgRecipeProcessKey];
        if (processes) {
            if ([processes indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                return [obj[@"Processor"] isEqualToString:step];
                }] != NSNotFound) {
                return YES;
            }
        }
    };

    return NO;
}

- (BOOL)hasCheckPhase
{
    return [self hasStepProcessor:@"EndOfCheckPhase"];
}

- (BOOL)buildsPackage
{
    return [self hasStepProcessor:@"PkgCreator"];
}

#pragma mark - Value retrieval
- (NSDictionary *)recipePlistForIdentifier:(NSString *)identifier
{
    NSURL *recipeURL = [_identifierURLStore objectForKey:identifier];
    if (recipeURL) {
        return [NSDictionary dictionaryWithContentsOfURL:recipeURL];
    }
    return nil;
}

- (id)objectForKey:(NSString *)key ofIdentifier:(NSString *)identifier
{
    return [self recipePlistForIdentifier:identifier][key];
}

#pragma mark - Class Methods;
+ (NSArray *)allRecipes
{
    return [[self class] allRecipesFilteringOverlaps:YES];
}

+ (NSArray *)allRecipesFilteringOverlaps:(BOOL)filterOverlaps
{
    _identifierURLStore = [[NSMutableDictionary alloc] init];
    LGDefaults *defaults = [LGDefaults standardUserDefaults];

    NSMutableArray *allRecipes = [[NSMutableArray alloc] init];
    NSSet *activeRecipes = [self activeRecipes];

    NSArray *searchDirs = defaults.autoPkgRecipeSearchDirs;
    for (NSString *searchDir in searchDirs) {
        if (![searchDir isEqualToString:@"."]) {
            NSArray *recipeArray = [self findRecipesRecursivelyAtPath:searchDir.stringByExpandingTildeInPath isOverride:NO activeRecipes:activeRecipes];
            if (recipeArray.count) {
                [allRecipes addObjectsFromArray:recipeArray];
            }
        }
    }

    NSString *recipeOverridePath = defaults.autoPkgRecipeOverridesDir ?: @"~/Library/AutoPkg/RecipeOverrides".stringByExpandingTildeInPath;

    NSArray *overrideArray = [self findRecipesRecursivelyAtPath:recipeOverridePath isOverride:YES activeRecipes:activeRecipes];
    NSMutableArray *validOverrides = [[NSMutableArray alloc] init];

    for (LGAutoPkgRecipe *override in overrideArray) {
        // Only consider the recipe valid if the parent exists
        NSPredicate *parentExistsPredicate = [NSPredicate predicateWithFormat:@"%K contains %@", kLGAutoPkgRecipeIdentifierKey, override.ParentRecipe];

        if ([parentExistsPredicate evaluateWithObject:allRecipes]) {
            [validOverrides addObject:override];
        }
    }

    if (filterOverlaps) {
        for (LGAutoPkgRecipe *override in validOverrides) {
            /* Filter the array by removing the parent recipe if an override is found that matches
             * BOTH conditions: the value for the "Name" key of the override is same as the value
             * for the "Name" key of the Parent AND the value for the Parent Recipe's "Identifier" key
             * is the same as the value for override's "ParentRecipe" key */
            NSPredicate *overridePreferedPredicate = [NSPredicate predicateWithFormat:@"not (%K == %@ AND %K == %@)", kLGAutoPkgRecipeNameKey, override.Name, kLGAutoPkgRecipeIdentifierKey, override.ParentRecipe];

            [allRecipes filterUsingPredicate:overridePreferedPredicate];
        }
    }

    // Now add the valid overrides into the recipeArray
    if (validOverrides.count) {
        [allRecipes addObjectsFromArray:validOverrides];
    }

    // Make a sorted array using the recipe Name as the sort key.
    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:kLGAutoPkgRecipeNameKey
                                                               ascending:YES];

    [allRecipes sortUsingDescriptors:@[ descriptor ]];

    validOverrides = nil;

    return allRecipes.count ? [allRecipes copy] : nil;
}

+ (NSArray *)findRecipesRecursivelyAtPath:(NSString *)path isOverride:(BOOL)isOverride activeRecipes:(NSSet *)activeRecipes
{
    NSMutableArray *recipes = [[NSMutableArray alloc] init];

    if (path && (access(path.UTF8String, F_OK) == 0)) {
        NSString *matches = [NSString stringWithFormat:@"{%@/{*.recipe,*/*.recipe}}", path];

        glob_t results;
        glob(matches.UTF8String, GLOB_BRACE | GLOB_NOSORT, NULL, &results);
        for (int i = 0; i < results.gl_matchc; i++) {
            NSString *globPath = [NSString stringWithUTF8String:results.gl_pathv[i]];
            NSURL *fileURL = [NSURL fileURLWithPath:globPath isDirectory:NO];

            if (fileURL) {
                LGAutoPkgRecipe *recipe = [[LGAutoPkgRecipe alloc] initWithRecipeFile:fileURL isOverride:isOverride];
                if (recipe) {
                    [recipes addObject:recipe];
                    // If it's in the active recipe list, mark it as enabled.
                    if (activeRecipes) {
                        if ([activeRecipes containsObject:recipe.Identifier]) {
                            recipe->_enabledInitialized = YES;
                        } else {
                            recipe->_enabledInitialized = NO;
                        }
                    }
                }
            }
        }
        globfree(&results);
    }

    return [recipes copy];
}

+ (NSOrderedSet *)activeRecipes
{
    NSError *error;
    NSMutableOrderedSet *activeRecipes = [[NSMutableOrderedSet alloc] init];

    NSString *recipeList = [self defaultRecipeList];
    if (recipeList) {
        NSString *autoPkgrRecipeList = [NSString stringWithContentsOfFile:recipeList encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"Error reading %@.", autoPkgrRecipeList);
        } else {
            NSArray *recipes = autoPkgrRecipeList.split_byLine;
            if (recipes.count) {
                [activeRecipes addObjectsFromArray:recipes];
            }
        }
    }

    return [activeRecipes copy];
}

#pragma mark - Util
+ (NSString *)defaultRecipeList
{
    NSString *autoPkgrSupportDirectory = [LGHostInfo getAppSupportDirectory];
    if (autoPkgrSupportDirectory.length) {
        return [autoPkgrSupportDirectory stringByAppendingPathComponent:@"recipe_list.txt"];
    }
    return nil;
}

+ (BOOL)removeRecipeFromRecipeList:(NSString *)recipe
{
    NSError *error;
    NSMutableOrderedSet *recipes = [[LGAutoPkgRecipe activeRecipes] mutableCopy];
    [recipes removeObject:recipe];

    NSString *recipe_list = [recipes.array componentsJoinedByString:@"\n"];
    if (![recipe_list writeToFile:[self defaultRecipeList] atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
        NSLog(@"Error writing file: %@", error.localizedDescription);
        return NO;
    }
    return YES;
}

+ (BOOL)migrateToIdentifiers:(NSError *__autoreleasing *)error
{
    NSFileManager *manager = [[NSFileManager alloc] init];
    NSString *orig = [[self class] defaultRecipeList];

    LGDefaults *defaults = [LGDefaults new];
    BOOL check1 = [defaults boolForKey:@"MigratedToIdentifiers"];

    BOOL check2 = [manager fileExistsAtPath:orig];

    if (check1 || !check2) {
        [defaults setBool:YES forKey:@"MigratedToIdentifiers"];
        return YES;
    }

    NSLog(@"Prompting user to upgrade recipe list to new identifier format...");

    NSString *infoText = @"AutoPkgr now uses recipe identifiers instead of short names to specify recipes. This makes it possible to schedule and run identically-named recipes from separate repos.";

    NSAlert *alert = [NSAlert alertWithMessageText:@"AutoPkgr needs to convert your recipe list."
                                     defaultButton:@"Upgrade"
                                   alternateButton:@"Quit"
                                       otherButton:nil
                         informativeTextWithFormat:@"%@", infoText];

    if ([alert runModal] == NSAlertDefaultReturn) {

        NSLog(@"Permission granted. Upgrading recipe list...");
        NSString *bak = [orig stringByAppendingPathExtension:@"v1.bak"];
        if ([manager fileExistsAtPath:orig] && ![manager fileExistsAtPath:bak]) {
            [manager copyItemAtPath:orig toPath:bak error:nil];
        }

        // Migrate Preferences
        __block int i = 0; // number of changed recipes
        NSArray *recipes = [self allRecipes];
        NSArray *activeRecipes = [[self activeRecipes] copy];

        [activeRecipes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            for (LGAutoPkgRecipe *recipe in recipes) {
                if ([recipe.Name isEqualToString:obj]) {
                    recipe.enabled = YES;
                    i++;
                }
            }
        }];

        BOOL success = (i == activeRecipes.count);
        [defaults setBool:YES forKey:@"MigratedToIdentifiers"];
        // return NO if any were unable to be converted
        if (!success) {
            NSLog(@"An error may have occurred while converting the recipe list. We successfully converted %d out of %lu recipes. However it's also possible your recipe list was already converted. Please double check your enabled recipes now.", i, (unsigned long)activeRecipes.count);
        } else {
            NSLog(@"The recipe list was upgraded successfully.");
        }
        return YES;
    }
    NSLog(@"User chose not to upgrade recipe list.");
    return NO;
}
@end


text:
from django.contrib import admin
from lithium.wiki.models import Page, Revision, Text

class PageAdmin(admin.ModelAdmin):
    list_display = ('title',)
    search_fields = ('title',)
    prepopulated_fields = {'slug': ['title']}

class RevisionAdmin(admin.ModelAdmin):
    list_display = ('pk', 'comment',)
    list_filter = ('pub_date',)
    ordering = ('-pub_date',)
    date_hierarchy = 'pub_date'

admin.site.register(Page, PageAdmin)
admin.site.register(Revision, RevisionAdmin)
admin.site.register(Text)


text:
import time
from locust import HttpUser, task, between
import os
import requests

class NB_PerfTest(HttpUser):
    wait_time = between(1, 2.5)

    @task
    def homepage(self):
        url = "/"
        self.client.get(url, verify=False)

    @task
    def river(self):
        url = "/api#/reader/river_stories"
        self.client.get(url, verify=False)

    @task
    def load_single_feed(self):
        url = "/site/1186180/best-of-metafilter"


text:
<?php

use Tester\Assert;

require __DIR__ . '/bootstrap.php';

$logger = new Deployment\Logger('php://temp');
$processor = new Deployment\Preprocessor($logger);

$file = __DIR__ . '/fixtures/js/combined.js';
Assert::same('/* combined JS */

alert();

console.log();

', $processor->expandApacheImports(file_get_contents($file), $file));


text:
@ECHO OFF

REM this script supposes you set the chocolatey API key by running this command:
REM   choco apikey -s"https://chocolatey.org/" -k="<your key here>"
REM Mind the trailing slash!

cd .\deploy\chocolatey\

choco push pickles.%1.nupkg
choco push picklesui.%1.nupkg

cd ..\..\


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

namespace StarRodSpriteCompatibilityConverter
{
    [XmlRoot("SpriteSheet")]
    public class SpritesheetSkeleton
    {
        [XmlAttribute("a")]
        public string a { get; set; }
        [XmlAttribute("b")]
        public string b { get; set; }

        [XmlArray("PaletteList"), XmlArrayItem(typeof(PaletteSkeleton), ElementName = "Palette")]
        public List<PaletteSkeleton> PaletteList { get; set; }
        [XmlArray("RasterList"), XmlArrayItem(typeof(RasterSkeleton), ElementName = "Raster")]
        public List<RasterSkeleton> RasterList { get; set; }
        [XmlArray("AnimationList"), XmlArrayItem(typeof(AnimationSkeleton), ElementName = "Animation")]
        public List<AnimationSkeleton> AnimationList { get; set; }
    }
    public class PaletteSkeleton
    {
        [XmlAttribute("id")]
        public string id { get; set; }
        [XmlAttribute("src")]
        public string src { get; set; }
    }
    public class RasterSkeleton
    {
        [XmlAttribute("id")]
        public string id { get; set; }
        [XmlAttribute("palette")]
        public string palette { get; set; }
        [XmlAttribute("src")]
        public string src { get; set; }
    }
    public class AnimationSkeleton
    {
        [XmlElement("Component")]
        public List<ComponentSkeleton> Components { get; set; }
    }
    public class ComponentSkeleton
    {
        [XmlAttribute("x")]
        public string x { get; set; }
        [XmlAttribute("y")]
        public string y { get; set; }
        [XmlAttribute("z")]
        public string z { get; set; }

        [XmlElement("Command")]
        public List<CommandSkeleton> Commands { get; set; }

        [XmlElement("Label")]
        public List<LabelSkeleton> Labels { get; set; }
    }
    public class CommandSkeleton
    {
        [XmlAttribute("val")]
        public string val { get; set; }
    }
    public class LabelSkeleton
    {
        [XmlAttribute("name")]
        public string name { get; set; }
        [XmlAttribute("pos")]
        public string pos { get; set; }
    }

}


text:
        First Name
        <input data-id="test" class="form-control" type="text" ng-change="changed(this)" ng-model="person.firstName"/>

        Last Name
        <input class="form-control" type="text" ng-change="changed(this)" ng-model="person.lastName"/>


text:
package com.example.android.wearable.wear.wearnotifications;

import androidx.core.app.NotificationCompat;

/**
 * We use a Singleton for a global copy of the NotificationCompat.Builder to update active
 * Notifications from other Services/Activities.
 *
 * You have two options for updating your notifications:
 *
 *  1. Use a new NotificationCompatBuilder to create the Notification. This approach requires you
 *  to get *ALL* the information and pass it to the builder. We get all the information from a Mock
 *  Database and this is the approach used in the MainActivity.
 *
 *  2. Use an existing NotificationCompatBuilder to create a Notification. This approach requires
 *  you to store a reference to the original builder. The benefit is you only need the new/updated
 *  information for an existing notification. We use this approach in the IntentService handlers to
 *  update existing notifications.
 *
 *  IMPORTANT NOTE 1: You shouldn't save/modify the resulting Notification object using
 *  its member variables and/or legacy APIs. If you want to retain anything from update
 *  to update, retain the Builder as option 2 outlines.
 *
 *  IMPORTANT NOTE 2: If the global Notification Builder is lost because the process is killed, you
 *  should have a way to recreate the Notification Builder from a persistent state. (We do this as
 *  well in the sample, check the IntentServices.)
 */
public final class GlobalNotificationBuilder {

    private static NotificationCompat.Builder sGlobalNotificationCompatBuilder = null;

    /*
     * Empty constructor - We don't initialize builder because we rely on a null state to let us
     * know the Application's process was killed.
     */
    private GlobalNotificationBuilder() { }

    public static void setNotificationCompatBuilderInstance(NotificationCompat.Builder builder) {
        sGlobalNotificationCompatBuilder = builder;
    }

    public static NotificationCompat.Builder getNotificationCompatBuilderInstance() {
        return sGlobalNotificationCompatBuilder;
    }
}


text:
namespace EnergyTrading.MDM.Mappers
{
    using EnergyTrading.Mapping;

    public class PersonDetailsMapper :
        Mapper<PersonDetails, Contracts.Sample.PersonDetails>
    {
        public override void Map(
            PersonDetails source,
            Contracts.Sample.PersonDetails destination)
        {
            destination.Forename = source.FirstName;
            destination.Surname = source.LastName;
            destination.TelephoneNumber = source.Phone;
            destination.FaxNumber = source.Fax;
            destination.Role = source.Role;
            destination.Email = source.Email;
        }
    }
}


text:
import os
from gps import *
import time
import threading

gpsd = None  # seting the global variable

os.system('clear')  # clear the terminal (optional)

class GpsPoller(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        global gpsd  # bring it in scope
        gpsd = gps(mode=WATCH_ENABLE)  # starting the stream of info
        self.current_value = None
        self.running = True  # setting the thread running to true

    def run(self):
        global gpsd
        while gpsp.running:
            gpsd.next()  # this will continue to loop and grab EACH set of gpsd info to clear the buffer

if __name__ == '__main__':
    gpsp = GpsPoller()  # create the thread
    try:
        gpsp.start()  # start it up
        while True:
            # It may take a second or two to get good data
            # print gpsd.fix.latitude,', ',gpsd.fix.longitude,'  Time: ',gpsd.utc

            os.system('clear')

            print()
            print (' GPS reading')
            print('----------------------------------------')
            print('latitude    ', gpsd.fix.latitude)
            print('longitude   ', gpsd.fix.longitude)
            print('time utc    ', gpsd.utc, ' + ', gpsd.fix.time)
            print('altitude (m)', gpsd.fix.altitude)
            print('eps         ', gpsd.fix.eps)
            print('epx         ', gpsd.fix.epx)
            print('epv         ', gpsd.fix.epv)
            print('ept         ', gpsd.fix.ept)
            print('speed (m/s) ', gpsd.fix.speed)
            print('climb       ', gpsd.fix.climb)
            print('track       ', gpsd.fix.track)
            print('mode        ', gpsd.fix.mode)
            print ()
            #print('sats        ', gpsd.satellites)

            time.sleep(0.5)  # set to whatever

    except (KeyboardInterrupt, SystemExit):  # when you press ctrl+c
        print("\nKilling Thread...")
        gpsp.running = False
        gpsp.join()  # wait for the thread to finish what it's doing
    print("Done.\nExiting.")


text:
  Zeinheim est
       un village
       géographiquement positionné dans le département de Bas-Rhin en Alsace. Elle comptait 182 habitants en 2008.

Le nombre de logements, à Zeinheim, se décomposait en 2011 en trois appartements et 74 maisons soit
 un marché relativement équilibré.

À proximité de Zeinheim sont localisées les villes de
Westhouse-Marmoutier située à 2 km, 253 habitants,
Kleingoeft à 3 km, 130 habitants,
Zehnacker à 2 km, 229 habitants,
Neugartheim-Ittlenheim localisée à 3 km, 687 habitants,
Hohengoeft située à 1 km, 517 habitants,
Willgottheim située à 1 km, 1 072 habitants,
 entre autres. De plus, Zeinheim est située à seulement 21 km de Strasbourg.

Si vous envisagez de demenager à Zeinheim, vous pourrez facilement trouver une maison à vendre.


text:
package vidada.server;

import com.google.inject.AbstractModule;
import vidada.model.security.CredentialManager;
import vidada.model.security.ICredentialManager;
import vidada.server.services.*;
import vidada.server.services.impl.*;
import vidada.server.services.impl.media.MediaService;
import vidada.server.services.impl.sync.MediaImportService;

/**
 * Vidada Server Module
 */
public class ServerModule extends AbstractModule {
    @Override
    protected void configure() {

        bind(IDatabaseSettingsService.class).to(DataBaseSettingsService.class);
        bind(IJobService.class).to(JobService.class);
        bind(IMediaImportService.class).to(MediaImportService.class);
        bind(IMediaLibraryService.class).to(MediaLibraryService.class);
        bind(ITagService.class).to(TagService.class);
        bind(IMediaService.class).to(MediaService.class);
        bind(IPrivacyService.class).to(PrivacyService.class);
        bind(ICredentialManager.class).to(CredentialManager.class);
        bind(IMediaThumbCacheService.class).to(MediaThumbCacheService.class);
        bind(IThumbnailService.class).to(ThumbnailService.class);
        bind(IUserService.class).to(UserService.class);

    }
}


text:
external help file: Microsoft.Azure.Commands.ResourceManager.Cmdlets.dll-Help.xml
ms.assetid: 4E5C059B-36F3-41C8-9FDB-69F5318CF39B
online version:
schema: 2.0.0
---

# Set-AzureRmResourceGroup

## SYNOPSIS
Modifies a resource group.

## SYNTAX

### Lists the resource group based in the name. (Default)
```
Set-AzureRmResourceGroup [-Name] <String> [-Tag] <Hashtable> [-ApiVersion <String>] [-Pre] [<CommonParameters>]
```

### Lists the resource group based in the Id.
```
Set-AzureRmResourceGroup [-Tag] <Hashtable> [-Id] <String> [-ApiVersion <String>] [-Pre] [<CommonParameters>]
```

## DESCRIPTION
The **Set-AzureRmResourceGroup** cmdlet modifies the properties of a resource group.
You can use this cmdlet to add, change, or delete the Azure tags applied to a resource group.
Specify the *Name* parameter to identify the resource group and the *Tag* parameter to modify the tags.

You cannot use this cmdlet to change the name of a resource group.

## EXAMPLES

### Example 1: Apply a tag to a resource group
```
PS C:\>Set-AzureRmResourceGroup -Name "ContosoRG" -Tag @{Name="Department";Value="IT"}
```

This command applies a Department tag with a value of IT to a resource group that has no existing tags.

### Example 2: Add tags to a resource group
```
PS C:\>$Tags = (Get-AzureRmResourceGroup -Name "ContosoRG").Tags
PS C:\> $Tags
PS C:\> $Tags += @{Name="Status";Value="Approved"}, @{Name="FY2016"}
PS C:\> Set-AzureRmResourceGroup -Name "ContosoRG" -Tag $Tags
PS C:> (Get-AzureRmResourceGroup -Name "ContosoRG").Tags
```

This example adds a Status tag with a value of Approved and an FY2016 tag to a resource group that has existing tags.
Because the tags you specify replace the existing tags, you must include the existing tags in the new tag collection or you will lose them.

The first command gets the ContosoRG resource group and uses the dot method to get the value of its Tags property.
The command stores the tags in the $Tags variable.

The second command gets the tags in the $Tags variable.

The third command uses the += assignment operator to add the Status and FY2016 tags to the array of tags in the $Tags variable.

The fourth command uses the *Tag* parameter of **Set-AzureRmResourceGroup** to apply the tags in the $Tags variable to the ContosoRG resource group.

The fifth command gets all of the tags applied to the ContosoRG resource group.
The output shows that the resource group has the Department tag and the two new tags, Status and FY2015.

### Example 3: Delete all tags for a resource group
```
PS C:\>Set-AzureRmResourceGroup -Name "ContosoRG" -Tag @{}
```

This command specifies the *Tag* parameter with an empty hash table value to delete all tags from the ContosoRG resource group.

## PARAMETERS

### -ApiVersion
Specifies the API version that is supported by the resource Provider.
You can specify a different version than the default version.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Id
Specifies the ID of the resource group to modify.

```yaml
Type: String
Parameter Sets: Lists the resource group based in the Id.
Aliases: ResourceGroupId, ResourceId

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Specifies the name of the resource group to modify.

```yaml
Type: String
Parameter Sets: Lists the resource group based in the name.
Aliases: ResourceGroupName

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Pre
Indicates that this cmdlet considers pre-release API versions when it automatically determines which version to use.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Tag
Specifies a hash table of tags.
To add or change a tag, you must replace the collection of tags for the resource group.

A tag is a name-value pair that you can create and apply to resources and resource groups.
After you assign tags to resources and groups, you can use the *Tag* parameter of Get-AzureRmResource and Get-AzureRmResourceGroup to search for resources and groups by tag name or name and value.
You can use tags to categorize your resources, such as by department or cost center, or to track notes or comments about the resources.

Each tag must have a Name key.
It can also have an optional Value key with one value.
To specify a tag, use a hash table, such as `@{Name="FY2015"}` or `@{Name="Department";Value="IT"}`.
To specify multiple tags, use commas to separate the hash tables, such as `@{Name="FY2015"}, @{Name="Department";Value="IT"}`.

To delete a tag, enter a hash table with all tags currently applied to the resource group, from **Get-AzureRmResourceGroup**, except for the tag you want to delete.
To delete all tags from a resource group, specify an empty hash table: `@{}`.

```yaml
Type: Hashtable
Parameter Sets: (All)
Aliases: Tags

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### Microsoft.Azure.Commands.Resources.Models.PSResourceGroup

## NOTES

## RELATED LINKS

[Get-AzureRmResource](./Get-AzureRmResource.md)

[Get-AzureRmResourceGroup](./Get-AzureRmResourceGroup.md)

[New-AzureRmResourceGroup](./New-AzureRmResourceGroup.md)

[Remove-AzureRmResourceGroup](./Remove-AzureRmResourceGroup.md)


text:
ALTER TABLE KV_RECORD ADD COlUMN USER_ID VARCHAR(64);
ALTER TABLE KV_RECORD ADD COLUMN CREATE_TIME TIMESTAMP;


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_rand_sub_62b.cpp
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 191 Integer Underflow
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Set data to a small, non-zero number (negative two)
 * Sinks: sub
 *    GoodSink: Ensure there will not be an underflow before subtracting 1 from data
 *    BadSink : Subtract 1 from data, which can cause an Underflow
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

namespace CWE191_Integer_Underflow__int_rand_sub_62
{

#ifndef OMITBAD

void badSource(int &data)
{
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(int &data)
{
    /* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */
    data = -2;
}

/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(int &data)
{
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
}

#endif /* OMITGOOD */

} /* close namespace */


text:
package org.apache.axis2.jaxws.message;

import org.apache.axiom.soap.SOAP12Constants;

import javax.xml.namespace.QName;

/**
 * Agnostic representation of SOAP 1.1 and SOAP 1.2 fault code values.
 *
 * @see XMLFault
 */
public class XMLFaultCode {

    //   SENDER             -> SOAP 1.2 Sender              / SOAP 1.1  Client
    //   RECEIVER           -> SOAP 1.2 Receiver            / SOAP 1.1  Server
    //   MUSTUNDERSTAND     -> SOAP 1.2 MustUnderstand      / SOAP 1.1  MustUnderstand
    //   DATAENCODINGUNKNOWN-> SOAP 1.2 DataEncodingUnknown / SOAP 1.1  Server
    //   VERSIONMISMATCH    -> SOAP 1.2 VersionMismatch     / SOAP 1.1  VersionMismatch
    //   CUSTOM_SOAP11_ONLY -> SOAP 1.2 Receiver            / SOAP 1.1  "custom qname"

    // Rendered as qnames with the following local names
    //     (the namespace is the corresponding envelope namespace)

    public static final XMLFaultCode SENDER = (new XMLFaultCode() {
        public QName toQName(String namespace) {
            String localPart;
            if (namespace.equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
                localPart = "Sender";
            } else {
                localPart = "Client";
            }
            return new QName(namespace, localPart);
        }
    });

    public static final XMLFaultCode RECEIVER = (new XMLFaultCode() {
        public QName toQName(String namespace) {
            String localPart;
            if (namespace.equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
                localPart = "Receiver";
            } else {
                localPart = "Server";
            }
            return new QName(namespace, localPart);
        }
    });

    public static final XMLFaultCode MUSTUNDERSTAND = (new XMLFaultCode() {
        public QName toQName(String namespace) {
            return new QName(namespace, "MustUnderstand");
        }
    });

    public static final XMLFaultCode DATAENCODINGUNKNOWN = (new XMLFaultCode() {
        public QName toQName(String namespace) {
            String localPart;
            if (namespace.equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
                localPart = "DataEncodingUnknown";
            } else {
                localPart = "Server";
            }
            return new QName(namespace, localPart);
        }
    });

    public static final XMLFaultCode VERSIONMISMATCH = (new XMLFaultCode() {
        public QName toQName(String namespace) {
            return new QName(namespace, "VersionMismatch");
        }
    });

    private QName faultCode;

    private XMLFaultCode() {
    }

    public XMLFaultCode(QName faultCode) {
        if (faultCode == null) {
            throw new NullPointerException("Null fault code");
        }
        this.faultCode = faultCode;
    }

    // Utility Methods

    /**
     * Return QName for the given protocol
     *
     * @param namespace of the envelope for the protocol
     * @return
     */
    public QName toQName(String protocolNamespace) {
        return this.faultCode;
    }

    /**
     * get the XMLPart corresponding to this specified QName
     *
     * @param qName
     * @return corresponding XMLPart
     */
    public static XMLFaultCode fromQName(QName qName) {
        if (qName == null) {
            // Spec indicates that the default is receiver
            return RECEIVER;
        }
        String namespace = qName.getNamespaceURI();
        String localPart = qName.getLocalPart();
        XMLFaultCode xmlFaultCode = null;
        // Due to problems in the OM, sometimes that qname is not retrieved correctly.
        // So use the localName to find the XMLFaultCode
        if (localPart.equalsIgnoreCase("Sender")) {          // SOAP 1.2
            xmlFaultCode = SENDER;
        } else if (localPart.equalsIgnoreCase("Receiver")) { // SOAP 1.2
            xmlFaultCode = RECEIVER;
        } else if (localPart.equalsIgnoreCase("Client")) {   // SOAP 1.1
            xmlFaultCode = SENDER;
        } else if (localPart.equalsIgnoreCase("Server")) {   // SOAP 1.1
            xmlFaultCode = RECEIVER;
        } else if (localPart.equalsIgnoreCase("MustUnderstand")) {  // Both
            xmlFaultCode = MUSTUNDERSTAND;
        } else if (localPart.equalsIgnoreCase("DataEncodingUnknown")) {  // SOAP 1.2
            xmlFaultCode = DATAENCODINGUNKNOWN;
        } else if (localPart.equalsIgnoreCase("VersionMismatch")) { // Both
            xmlFaultCode = VERSIONMISMATCH;
        } else {
            xmlFaultCode = new XMLFaultCode(qName);
        }

        return xmlFaultCode;
    }
}


text:
"""Game-specific query example."""

from absl import app
from absl import flags

import pyspiel

FLAGS = flags.FLAGS

flags.DEFINE_string("game", "negotiation", "Name of the game")

def main(_):
  print("Creating game: " + FLAGS.game)
  game = pyspiel.load_game(FLAGS.game)

  state = game.new_initial_state()

  print(str(state))

  # Need to apply the first chance node for items and utilities to be generated
  state.apply_action(0)

  print("Item pool: {}".format(state.item_pool()))
  print("Player 0 utils: {}".format(state.agent_utils(0)))
  print("Player 1 utils: {}".format(state.agent_utils(1)))

  state = game.new_initial_state()

  print(str(state))

  # Need to apply the first chance node for items and utilities to be generated
  state.apply_action(0)

  print("Item pool: {}".format(state.item_pool()))
  print("Player 0 utils: {}".format(state.agent_utils(0)))
  print("Player 1 utils: {}".format(state.agent_utils(1)))

if __name__ == "__main__":
  app.run(main)