text:
package org.qi4j.runtime.unitofwork;

import org.qi4j.api.common.MetaInfo;
import org.qi4j.api.composite.AmbiguousTypeException;
import org.qi4j.api.entity.EntityComposite;
import org.qi4j.api.entity.EntityReference;
import org.qi4j.api.structure.Module;
import org.qi4j.api.unitofwork.*;
import org.qi4j.api.usecase.Usecase;
import org.qi4j.functional.Iterables;
import org.qi4j.runtime.entity.EntityInstance;
import org.qi4j.runtime.entity.EntityModel;
import org.qi4j.runtime.structure.ModelModule;
import org.qi4j.runtime.structure.ModuleInstance;
import org.qi4j.runtime.structure.ModuleUnitOfWork;
import org.qi4j.spi.entity.EntityState;
import org.qi4j.spi.entity.EntityStatus;
import org.qi4j.spi.entitystore.*;

import java.util.*;

import static org.qi4j.api.unitofwork.UnitOfWorkCallback.UnitOfWorkStatus.COMPLETED;
import static org.qi4j.api.unitofwork.UnitOfWorkCallback.UnitOfWorkStatus.DISCARDED;

public final class UnitOfWorkInstance
{
    private static final ThreadLocal<Stack<UnitOfWorkInstance>> current = new ThreadLocal<Stack<UnitOfWorkInstance>>();

    public static Stack<UnitOfWorkInstance> getCurrent()
    {
        Stack<UnitOfWorkInstance> stack = current.get();
        if( stack == null )
        {
            stack = new Stack<UnitOfWorkInstance>();
            current.set( stack );
        }

        return stack;
    }

    private long currentTime;
    final HashMap<EntityReference, EntityInstance> instanceCache;
    final HashMap<EntityStore, EntityStoreUnitOfWork> storeUnitOfWork;

    private boolean open;

    private boolean paused;

    /**
     * Lazy query builder factory.
     */
    private Usecase usecase;

    private MetaInfo metaInfo;

    private List<UnitOfWorkCallback> callbacks;

    public UnitOfWorkInstance( Usecase usecase, long currentTime )
    {
        this.currentTime = currentTime;
        this.open = true;
        instanceCache = new HashMap<EntityReference, EntityInstance>();
        storeUnitOfWork = new HashMap<EntityStore, EntityStoreUnitOfWork>();
        getCurrent().push( this );
        paused = false;
        this.usecase = usecase;
    }

    public long currentTime()
    {
        return currentTime;
    }

    public EntityStoreUnitOfWork getEntityStoreUnitOfWork( EntityStore store, Module module )
    {
        EntityStoreUnitOfWork uow = storeUnitOfWork.get( store );
        if( uow == null )
        {
            uow = store.newUnitOfWork( usecase, module, currentTime );
            storeUnitOfWork.put( store, uow );
        }
        return uow;
    }

    public <T> T get( EntityReference identity,
                               ModuleUnitOfWork uow,
                               Iterable<ModelModule<EntityModel>> potentialModels,
                               Class<T> mixinType
    )
        throws EntityTypeNotFoundException, NoSuchEntityException
    {
        checkOpen();

        EntityInstance entityInstance = instanceCache.get( identity );
        if( entityInstance == null )
        {   // Not yet in cache

            // Check if this is a root UoW, or if no parent UoW knows about this entity
            EntityState entityState = null;
            EntityModel model = null;
            ModuleInstance module = null;
            // Figure out what EntityStore to use
            for( ModelModule<EntityModel> potentialModule : potentialModels )
            {
                EntityStore store = potentialModule.module().entityStore();
                EntityStoreUnitOfWork storeUow = getEntityStoreUnitOfWork( store, potentialModule.module() );
                try
                {
                    entityState = storeUow.getEntityState( identity );
                }
                catch( EntityNotFoundException e )
                {
                    continue;
                }

                // Get the selected model
                model = (EntityModel) entityState.entityDescriptor();
                module = potentialModule.module();
            }

            // Check if model was found
            if( model == null )
            {
                // Check if state was found
                if( entityState == null )
                {
                    throw new NoSuchEntityException( identity );
                }
                else
                {
                    throw new EntityTypeNotFoundException( mixinType.getName() );
                }
            }

            // Create instance
            entityInstance = new EntityInstance( uow, module, model, entityState );

            instanceCache.put( identity, entityInstance );
        }
        else
        {
            // Check if it has been removed
            if( entityInstance.status() == EntityStatus.REMOVED )
            {
                throw new NoSuchEntityException( identity );
            }
        }

        return entityInstance.<T>proxy();
    }

    public Usecase usecase()
    {
        return usecase;
    }

    public MetaInfo metaInfo()
    {
        if( metaInfo == null )
        {
            metaInfo = new MetaInfo();
        }

        return metaInfo;
    }

    public void pause()
    {
        if( !paused )
        {
            paused = true;
            getCurrent().pop();

            UnitOfWorkOptions unitOfWorkOptions = metaInfo().get(UnitOfWorkOptions.class);
            if ( unitOfWorkOptions == null)
                unitOfWorkOptions = usecase().metaInfo( UnitOfWorkOptions.class );

            if (unitOfWorkOptions != null)
            {
                if (unitOfWorkOptions.isPruneOnPause())
                {
                    List<EntityReference> prunedInstances = null;
                    for( EntityInstance entityInstance : instanceCache.values() )
                    {
                        if (entityInstance.status() == EntityStatus.LOADED)
                        {
                            if (prunedInstances == null)
                                prunedInstances = new ArrayList<EntityReference>(  );
                            prunedInstances.add(entityInstance.identity());
                        }
                    }
                    if (prunedInstances != null)
                    {
                        for( EntityReference prunedInstance : prunedInstances )
                        {
                            instanceCache.remove( prunedInstance );
                        }
                    }
                }
            }

        }
        else
        {
            throw new UnitOfWorkException( "Unit of work is not active" );
        }
    }

    public void resume()
    {
        if( paused )
        {
            paused = false;
            getCurrent().push( this );
        }
        else
        {
            throw new UnitOfWorkException( "Unit of work has not been paused" );
        }
    }

    public void complete()
        throws UnitOfWorkCompletionException
    {
        checkOpen();

        // Copy list so that it cannot be modified during completion
        List<UnitOfWorkCallback> currentCallbacks = callbacks == null ? null : new ArrayList<UnitOfWorkCallback>( callbacks );

        // Check callbacks
        notifyBeforeCompletion( currentCallbacks );

        // Commit state to EntityStores
        List<StateCommitter> committers = applyChanges();

        // Commit all changes
        for( StateCommitter committer : committers )
        {
            committer.commit();
        }

        close();

        // Call callbacks
        notifyAfterCompletion( currentCallbacks, COMPLETED );

        callbacks = currentCallbacks;
    }

    public void discard()
    {
        if( !isOpen() )
        {
            return;
        }
        close();

        // Copy list so that it cannot be modified during completion
        List<UnitOfWorkCallback> currentCallbacks = callbacks == null ? null : new ArrayList<UnitOfWorkCallback>( callbacks );

        // Call callbacks
        notifyAfterCompletion( currentCallbacks, DISCARDED );

        for( EntityStoreUnitOfWork entityStoreUnitOfWork : storeUnitOfWork.values() )
        {
            entityStoreUnitOfWork.discard();
        }

        callbacks = currentCallbacks;
    }

    private void close()
    {
        checkOpen();

        if( !isPaused() )
        {
            getCurrent().pop();
        }
        open = false;
    }

    public boolean isOpen()
    {
        return open;
    }

    public void addUnitOfWorkCallback( UnitOfWorkCallback callback )
    {
        if( callbacks == null )
        {
            callbacks = new ArrayList<UnitOfWorkCallback>();
        }

        callbacks.add( callback );
    }

    public void removeUnitOfWorkCallback( UnitOfWorkCallback callback )
    {
        if( callbacks != null )
        {
            callbacks.remove( callback );
        }
    }

    public void addEntity( EntityInstance instance )
    {
        instanceCache.put( instance.identity(), instance );
    }

    private List<StateCommitter> applyChanges()
        throws UnitOfWorkCompletionException
    {
        List<StateCommitter> committers = new ArrayList<StateCommitter>();
        for( EntityStoreUnitOfWork entityStoreUnitOfWork : storeUnitOfWork.values() )
        {
            try
            {
                StateCommitter committer = entityStoreUnitOfWork.applyChanges();
                committers.add( committer );
            }
            catch( Exception e )
            {
                // Cancel all previously prepared stores
                for( StateCommitter committer : committers )
                {
                    committer.cancel();
                }

                if( e instanceof ConcurrentEntityStateModificationException )
                {
                    // If we cancelled due to concurrent modification, then create the proper exception for it!
                    ConcurrentEntityStateModificationException mee = (ConcurrentEntityStateModificationException) e;
                    Collection<EntityReference> modifiedEntityIdentities = mee.modifiedEntities();
                    Collection<EntityComposite> modifiedEntities = new ArrayList<EntityComposite>();
                    for( EntityReference modifiedEntityIdentity : modifiedEntityIdentities )
                    {
                        Collection<EntityInstance> instances = instanceCache.values();
                        for( EntityInstance instance : instances )
                        {
                            if( instance.identity().equals( modifiedEntityIdentity ) )
                            {
                                modifiedEntities.add( instance.<EntityComposite>proxy() );
                            }
                        }
                    }
                    throw new ConcurrentEntityModificationException( modifiedEntities );
                }
                else
                {
                    throw new UnitOfWorkCompletionException( e );
                }
            }
        }
        return committers;
    }

    private void notifyBeforeCompletion( List<UnitOfWorkCallback> callbacks )
        throws UnitOfWorkCompletionException
    {
        // Notify explicitly registered callbacks
        if( callbacks != null )
        {
            for( UnitOfWorkCallback callback : callbacks )
            {
                callback.beforeCompletion();
            }
        }

        // Notify entities
        try
        {
            for( EntityInstance instance : instanceCache.values() )
            {
                if( instance.<Object>proxy() instanceof UnitOfWorkCallback && !instance.status()
                    .equals( EntityStatus.REMOVED ) )
                {
                    UnitOfWorkCallback callback = UnitOfWorkCallback.class.cast( instance.proxy() );
                    callback.beforeCompletion();
                }
            }
        }
        catch( UnitOfWorkCompletionException e )
        {
            throw e;
        }
        catch( Exception e )
        {
            throw new UnitOfWorkCompletionException( e );
        }
    }

    private void notifyAfterCompletion( List<UnitOfWorkCallback> callbacks,
                                        final UnitOfWorkCallback.UnitOfWorkStatus status
    )
    {
        if( callbacks != null )
        {
            for( UnitOfWorkCallback callback : callbacks )
            {
                try
                {
                    callback.afterCompletion( status );
                }
                catch( Exception e )
                {
                    // Ignore
                }
            }
        }

        // Notify entities
        try
        {
            for( EntityInstance instance : instanceCache.values() )
            {
                if( instance.<Object>proxy() instanceof UnitOfWorkCallback && !instance.status()
                    .equals( EntityStatus.REMOVED ) )
                {
                    UnitOfWorkCallback callback = UnitOfWorkCallback.class.cast( instance.proxy() );
                    callback.afterCompletion( status );
                }
            }
        }
        catch( Exception e )
        {
            // Ignore
        }
    }

    public void checkOpen()
    {
        if( !isOpen() )
        {
            throw new UnitOfWorkException( "Unit of work has been closed" );
        }
    }

    public boolean isPaused()
    {
        return paused;
    }

    @Override
    public String toString()
    {
        return "UnitOfWork " + hashCode() + "(" + usecase + "): entities:" + instanceCache.size();
    }

    public void remove( EntityReference entityReference )
    {
        instanceCache.remove( entityReference );
    }
}


text:
package ctmap

import (
	"errors"
	"fmt"
	"io"
	"math"
	"net"
	"os"
	"reflect"
	"strings"
	"time"
	"unsafe"

	"github.com/cilium/cilium/api/v1/models"
	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/defaults"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/logging"
	"github.com/cilium/cilium/pkg/logging/logfields"
	"github.com/cilium/cilium/pkg/maps/nat"
	"github.com/cilium/cilium/pkg/metrics"
	"github.com/cilium/cilium/pkg/option"
	"github.com/cilium/cilium/pkg/tuple"
	"github.com/cilium/cilium/pkg/u8proto"

	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

var (
	log = logging.DefaultLogger.WithField(logfields.LogSubsys, "map-ct")

	// labelIPv6CTDumpInterrupts marks the count for conntrack dump resets (IPv6).
	labelIPv6CTDumpInterrupts = map[string]string{
		metrics.LabelDatapathArea:   "conntrack",
		metrics.LabelDatapathName:   "dump_interrupts",
		metrics.LabelDatapathFamily: "ipv6",
	}
	// labelIPv4CTDumpInterrupts marks the count for conntrack dump resets (IPv4).
	labelIPv4CTDumpInterrupts = map[string]string{
		metrics.LabelDatapathArea:   "conntrack",
		metrics.LabelDatapathName:   "dump_interrupts",
		metrics.LabelDatapathFamily: "ipv4",
	}

	mapInfo map[mapType]mapAttributes
)

const (
	// mapCount counts the maximum number of CT maps that one endpoint may
	// access at once.
	mapCount = 4

	// Map names for TCP CT tables are retained from Cilium 1.0 naming
	// scheme to minimize disruption of ongoing connections during upgrade.
	MapNamePrefix     = "cilium_ct"
	MapNameTCP6       = MapNamePrefix + "6_"
	MapNameTCP4       = MapNamePrefix + "4_"
	MapNameTCP6Global = MapNameTCP6 + "global"
	MapNameTCP4Global = MapNameTCP4 + "global"

	// Map names for "any" protocols indicate CT for non-TCP protocols.
	MapNameAny6       = MapNamePrefix + "_any6_"
	MapNameAny4       = MapNamePrefix + "_any4_"
	MapNameAny6Global = MapNameAny6 + "global"
	MapNameAny4Global = MapNameAny4 + "global"

	mapNumEntriesLocal = 64000

	TUPLE_F_OUT     = 0
	TUPLE_F_IN      = 1
	TUPLE_F_RELATED = 2
	TUPLE_F_SERVICE = 4

	// MaxTime specifies the last possible time for GCFilter.Time
	MaxTime = math.MaxUint32

	metricsAlive   = "alive"
	metricsDeleted = "deleted"

	metricsIngress = "ingress"
	metricsEgress  = "egress"
)

type action int

const (
	noAction action = iota
	deleteEntry
)

var globalDeleteLock [mapTypeMax]lock.Mutex

type mapAttributes struct {
	mapKey     bpf.MapKey
	keySize    int
	mapValue   bpf.MapValue
	valueSize  int
	maxEntries int
	parser     bpf.DumpParser
	bpfDefine  string
	natMap     *nat.Map
}

// CtMap interface represents a CT map, and can be reused to implement mock
// maps for unit tests.
type CtMap interface {
	Open() error
	Close() error
	Path() (string, error)
	DumpEntries() (string, error)
	DumpWithCallback(bpf.DumpCallback) error
}

// A "Record" designates a map entry (key + value), but avoid "entry" because of
// possible confusion with "CtEntry" (actually the value part).
// This type is used for JSON dump and mock maps.
type CtMapRecord struct {
	Key   CtKey
	Value CtEntry
}

func setupMapInfo(m mapType, define string, mapKey bpf.MapKey, keySize int, maxEntries int, nat *nat.Map) {
	mapInfo[m] = mapAttributes{
		bpfDefine: define,
		mapKey:    mapKey,
		keySize:   keySize,
		// the value type is CtEntry for all CT maps
		mapValue:   &CtEntry{},
		valueSize:  SizeofCtEntry,
		maxEntries: maxEntries,
		parser:     bpf.ConvertKeyValue,
		natMap:     nat,
	}
}

// InitMapInfo builds the information about different CT maps for the
// combination of L3/L4 protocols, using the specified limits on TCP vs non-TCP
// maps.
func InitMapInfo(tcpMaxEntries, anyMaxEntries int, v4, v6, nodeport bool) {
	mapInfo = make(map[mapType]mapAttributes, mapTypeMax)

	global4Map, global6Map := nat.GlobalMaps(v4, v6, nodeport)

	// SNAT also only works if the CT map is global so all local maps will be nil
	natMaps := map[mapType]*nat.Map{
		mapTypeIPv4TCPLocal:  nil,
		mapTypeIPv6TCPLocal:  nil,
		mapTypeIPv4TCPGlobal: global4Map,
		mapTypeIPv6TCPGlobal: global6Map,
		mapTypeIPv4AnyLocal:  nil,
		mapTypeIPv6AnyLocal:  nil,
		mapTypeIPv4AnyGlobal: global4Map,
		mapTypeIPv6AnyGlobal: global6Map,
	}

	setupMapInfo(mapTypeIPv4TCPLocal, "CT_MAP_TCP4",
		&CtKey4{}, int(unsafe.Sizeof(CtKey4{})),
		mapNumEntriesLocal, natMaps[mapTypeIPv4TCPLocal])

	setupMapInfo(mapTypeIPv6TCPLocal, "CT_MAP_TCP6",
		&CtKey6{}, int(unsafe.Sizeof(CtKey6{})),
		mapNumEntriesLocal, natMaps[mapTypeIPv6TCPLocal])

	setupMapInfo(mapTypeIPv4TCPGlobal, "CT_MAP_TCP4",
		&CtKey4Global{}, int(unsafe.Sizeof(CtKey4Global{})),
		tcpMaxEntries, natMaps[mapTypeIPv4TCPGlobal])

	setupMapInfo(mapTypeIPv6TCPGlobal, "CT_MAP_TCP6",
		&CtKey6Global{}, int(unsafe.Sizeof(CtKey6Global{})),
		tcpMaxEntries, natMaps[mapTypeIPv6TCPGlobal])

	setupMapInfo(mapTypeIPv4AnyLocal, "CT_MAP_ANY4",
		&CtKey4{}, int(unsafe.Sizeof(CtKey4{})),
		mapNumEntriesLocal, natMaps[mapTypeIPv4AnyLocal])

	setupMapInfo(mapTypeIPv6AnyLocal, "CT_MAP_ANY6",
		&CtKey6{}, int(unsafe.Sizeof(CtKey6{})),
		mapNumEntriesLocal, natMaps[mapTypeIPv6AnyLocal])

	setupMapInfo(mapTypeIPv4AnyGlobal, "CT_MAP_ANY4",
		&CtKey4Global{}, int(unsafe.Sizeof(CtKey4Global{})),
		anyMaxEntries, natMaps[mapTypeIPv4AnyGlobal])

	setupMapInfo(mapTypeIPv6AnyGlobal, "CT_MAP_ANY6",
		&CtKey6Global{}, int(unsafe.Sizeof(CtKey6Global{})),
		anyMaxEntries, natMaps[mapTypeIPv6AnyGlobal])
}

// CtEndpoint represents an endpoint for the functions required to manage
// conntrack maps for the endpoint.
type CtEndpoint interface {
	GetID() uint64
}

// Map represents an instance of a BPF connection tracking map.
// It also implements the CtMap interface.
type Map struct {
	bpf.Map

	mapType mapType
	// define maps to the macro used in the datapath portion for the map
	// name, for example 'CT_MAP4'.
	define string
}

// GCFilter contains the necessary fields to filter the CT maps.
// Filtering by endpoint requires both EndpointID to be > 0 and
// EndpointIP to be not nil.
type GCFilter struct {
	// RemoveExpired enables removal of all entries that have expired
	RemoveExpired bool

	// Time is the reference timestamp to remove expired entries. If
	// RemoveExpired is true and lifetime is lesser than Time, the entry is
	// removed
	Time uint32

	// ValidIPs is the list of valid IPs to scrub all entries for which the
	// source or destination IP is *not* matching one of the valid IPs.
	// The key is the IP in string form: net.IP.String()
	ValidIPs map[string]struct{}

	// MatchIPs is the list of IPs to remove from the conntrack table
	MatchIPs map[string]struct{}

	// EmitCTEntry is called, when non-nil, if filtering by ValidIPs and MatchIPs
	// passes. It has no impact on CT GC, but can be used to iterate over valid
	// CT entries.
	EmitCTEntryCB EmitCTEntryCBFunc
}

// EmitCTEntryCBFunc is the type used for the EmitCTEntryCB callback in GCFilter
type EmitCTEntryCBFunc func(srcIP, dstIP net.IP, srcPort, dstPort uint16, nextHdr, flags uint8, entry *CtEntry)

// DumpEntriesWithTimeDiff iterates through Map m and writes the values of the
// ct entries in m to a string. If clockSource is not nil, it uses it to
// compute the time difference of each entry from now and prints that too.
func DumpEntriesWithTimeDiff(m CtMap, clockSource *models.ClockSource) (string, error) {
	var toRemSecs func(uint32) string

	if clockSource == nil {
		toRemSecs = nil
	} else if clockSource.Mode == models.ClockSourceModeKtime {
		now, err := bpf.GetMtime()
		if err != nil {
			return "", err
		}
		now = now / 1000000000
		toRemSecs = func(t uint32) string {
			diff := int64(t) - int64(now)
			return fmt.Sprintf("remaining: %d sec(s)", diff)
		}
	} else if clockSource.Mode == models.ClockSourceModeJiffies {
		now, err := bpf.GetJtime()
		if err != nil {
			return "", err
		}
		if clockSource.Hertz == 0 {
			return "", fmt.Errorf("invalid clock Hertz value (0)")
		}
		toRemSecs = func(t uint32) string {
			diff := int64(t) - int64(now)
			diff = diff << 8
			diff = diff / int64(clockSource.Hertz)
			return fmt.Sprintf("remaining: %d sec(s)", diff)
		}
	} else {
		return "", fmt.Errorf("unknown clock source: %s", clockSource.Mode)
	}

	var sb strings.Builder
	cb := func(k bpf.MapKey, v bpf.MapValue) {
		// No need to deep copy as the values are used to create new strings
		key := k.(CtKey)
		if !key.ToHost().Dump(&sb, true) {
			return
		}
		value := v.(*CtEntry)
		sb.WriteString(value.StringWithTimeDiff(toRemSecs))
	}
	// DumpWithCallback() must be called before sb.String().
	err := m.DumpWithCallback(cb)
	if err != nil {
		return "", err
	}
	return sb.String(), err
}

// DoDumpEntries iterates through Map m and writes the values of the ct entries
// in m to a string.
func DoDumpEntries(m CtMap) (string, error) {
	return DumpEntriesWithTimeDiff(m, nil)
}

// DumpEntries iterates through Map m and writes the values of the ct entries
// in m to a string.
func (m *Map) DumpEntries() (string, error) {
	return DoDumpEntries(m)
}

// newMap creates a new CT map of the specified type with the specified name.
func newMap(mapName string, m mapType) *Map {
	result := &Map{
		Map: *bpf.NewMap(mapName,
			bpf.MapTypeLRUHash,
			mapInfo[m].mapKey,
			mapInfo[m].keySize,
			mapInfo[m].mapValue,
			mapInfo[m].valueSize,
			mapInfo[m].maxEntries,
			0, 0,
			mapInfo[m].parser,
		),
		mapType: m,
		define:  mapInfo[m].bpfDefine,
	}
	return result
}

func purgeCtEntry6(m *Map, key CtKey, natMap *nat.Map) error {
	err := m.Delete(key)
	if err == nil && natMap != nil {
		natMap.DeleteMapping(key.GetTupleKey())
	}
	return err
}

// doGC6 iterates through a CTv6 map and drops entries based on the given
// filter.
func doGC6(m *Map, filter *GCFilter) gcStats {
	natMap := mapInfo[m.mapType].natMap
	stats := statStartGc(m)
	defer stats.finish()

	if natMap != nil {
		err := natMap.Open()
		if err == nil {
			defer natMap.Close()
		} else {
			natMap = nil
		}
	}

	filterCallback := func(key bpf.MapKey, value bpf.MapValue) {
		entry := value.(*CtEntry)

		switch obj := key.(type) {
		case *CtKey6Global:
			currentKey6Global := obj
			// In CT entries, the source address of the conntrack entry (`SourceAddr`) is
			// the destination of the packet received, therefore it's the packet's
			// destination IP
			action := filter.doFiltering(currentKey6Global.DestAddr.IP(), currentKey6Global.SourceAddr.IP(),
				currentKey6Global.DestPort, currentKey6Global.SourcePort,
				uint8(currentKey6Global.NextHeader), currentKey6Global.Flags, entry)

			switch action {
			case deleteEntry:
				err := purgeCtEntry6(m, currentKey6Global, natMap)
				if err != nil {
					log.WithError(err).WithField(logfields.Key, currentKey6Global.String()).Error("Unable to delete CT entry")
				} else {
					stats.deleted++
				}
			default:
				stats.aliveEntries++
			}
		case *CtKey6:
			currentKey6 := obj
			// In CT entries, the source address of the conntrack entry (`SourceAddr`) is
			// the destination of the packet received, therefore it's the packet's
			// destination IP
			action := filter.doFiltering(currentKey6.DestAddr.IP(), currentKey6.SourceAddr.IP(),
				currentKey6.DestPort, currentKey6.SourcePort,
				uint8(currentKey6.NextHeader), currentKey6.Flags, entry)

			switch action {
			case deleteEntry:
				err := purgeCtEntry6(m, currentKey6, natMap)
				if err != nil {
					log.WithError(err).WithField(logfields.Key, currentKey6.String()).Error("Unable to delete CT entry")
				} else {
					stats.deleted++
				}
			default:
				stats.aliveEntries++
			}
		default:
			log.Warningf("Encountered unknown type while scanning conntrack table: %v", reflect.TypeOf(key))
		}
	}

	// See doGC4() comment.
	globalDeleteLock[m.mapType].Lock()
	stats.dumpError = m.DumpReliablyWithCallback(filterCallback, stats.DumpStats)
	globalDeleteLock[m.mapType].Unlock()
	return stats
}

func purgeCtEntry4(m *Map, key CtKey, natMap *nat.Map) error {
	err := m.Delete(key)
	if err == nil && natMap != nil {
		natMap.DeleteMapping(key.GetTupleKey())
	}
	return err
}

// doGC4 iterates through a CTv4 map and drops entries based on the given
// filter.
func doGC4(m *Map, filter *GCFilter) gcStats {
	natMap := mapInfo[m.mapType].natMap
	stats := statStartGc(m)
	defer stats.finish()

	if natMap != nil {
		if err := natMap.Open(); err == nil {
			defer natMap.Close()
		} else {
			natMap = nil
		}
	}

	filterCallback := func(key bpf.MapKey, value bpf.MapValue) {
		entry := value.(*CtEntry)

		switch obj := key.(type) {
		case *CtKey4Global:
			currentKey4Global := obj
			// In CT entries, the source address of the conntrack entry (`SourceAddr`) is
			// the destination of the packet received, therefore it's the packet's
			// destination IP
			action := filter.doFiltering(currentKey4Global.DestAddr.IP(), currentKey4Global.SourceAddr.IP(),
				currentKey4Global.DestPort, currentKey4Global.SourcePort,
				uint8(currentKey4Global.NextHeader), currentKey4Global.Flags, entry)

			switch action {
			case deleteEntry:
				err := purgeCtEntry4(m, currentKey4Global, natMap)
				if err != nil {
					log.WithError(err).WithField(logfields.Key, currentKey4Global.String()).Error("Unable to delete CT entry")
				} else {
					stats.deleted++
				}
			default:
				stats.aliveEntries++
			}
		case *CtKey4:
			currentKey4 := obj
			// In CT entries, the source address of the conntrack entry (`SourceAddr`) is
			// the destination of the packet received, therefore it's the packet's
			// destination IP
			action := filter.doFiltering(currentKey4.DestAddr.IP(), currentKey4.SourceAddr.IP(),
				currentKey4.DestPort, currentKey4.SourcePort,
				uint8(currentKey4.NextHeader), currentKey4.Flags, entry)

			switch action {
			case deleteEntry:
				err := purgeCtEntry4(m, currentKey4, natMap)
				if err != nil {
					log.WithError(err).WithField(logfields.Key, currentKey4.String()).Error("Unable to delete CT entry")
				} else {
					stats.deleted++
				}
			default:
				stats.aliveEntries++
			}
		default:
			log.Warningf("Encountered unknown type while scanning conntrack table: %v", reflect.TypeOf(key))
		}
	}

	// We serialize the deletions in order to avoid forced map walk restarts
	// when keys are being evicted underneath us from concurrent go routines.
	globalDeleteLock[m.mapType].Lock()
	stats.dumpError = m.DumpReliablyWithCallback(filterCallback, stats.DumpStats)
	globalDeleteLock[m.mapType].Unlock()
	return stats
}

func (f *GCFilter) doFiltering(srcIP, dstIP net.IP, srcPort, dstPort uint16, nextHdr, flags uint8, entry *CtEntry) action {
	if f.RemoveExpired && entry.Lifetime < f.Time {
		return deleteEntry
	}

	if f.ValidIPs != nil {
		_, srcIPExists := f.ValidIPs[srcIP.String()]
		_, dstIPExists := f.ValidIPs[dstIP.String()]
		if !srcIPExists && !dstIPExists {
			return deleteEntry
		}
	}

	if f.MatchIPs != nil {
		_, srcIPExists := f.MatchIPs[srcIP.String()]
		_, dstIPExists := f.MatchIPs[dstIP.String()]
		if srcIPExists || dstIPExists {
			return deleteEntry
		}
	}

	if f.EmitCTEntryCB != nil {
		f.EmitCTEntryCB(srcIP, dstIP, srcPort, dstPort, nextHdr, flags, entry)
	}

	return noAction
}

func doGC(m *Map, filter *GCFilter) int {
	if m.mapType.isIPv6() {
		return int(doGC6(m, filter).deleted)
	} else if m.mapType.isIPv4() {
		return int(doGC4(m, filter).deleted)
	}
	log.Fatalf("Unsupported ct map type: %s", m.mapType.String())
	return 0
}

// GC runs garbage collection for map m with name mapType with the given filter.
// It returns how many items were deleted from m.
func GC(m *Map, filter *GCFilter) int {
	if filter.RemoveExpired {
		var t uint64
		if option.Config.ClockSource == option.ClockSourceKtime {
			t, _ = bpf.GetMtime()
			t = t / 1000000000
		} else {
			t, _ = bpf.GetJtime()
		}
		filter.Time = uint32(t)
	}

	return doGC(m, filter)
}

// PurgeOrphanNATEntries removes orphan SNAT entries. We call an SNAT entry
// orphan if it does not have a corresponding CT entry.
//
// This can happen when the CT entry is removed by the LRU eviction which
// happens when the CT map becomes full.
//
// PurgeOrphanNATEntries() is triggered by the datapath via the GC signaling
// mechanism. When the datapath SNAT fails to find free mapping after
// SNAT_SIGNAL_THRES attempts, it sends the signal via the perf ring buffer.
// The consumer of the buffer invokes the function.
//
// The SNAT is being used for the following cases:
// 1. By NodePort BPF on an intermediate node before fwd'ing request from outside
//     to a destination node.
// 2. A packet from local endpoint sent to outside (BPF-masq).
// 3. A packet from a host local application (i.e. running in the host netns)
//    This is needed to prevent SNAT from hijacking such connections.
// 4. By DSR on a backend node to SNAT responses with service IP+port before
//    sending to a client.
//
// In the case of 1-3, we always create a CT_EGRESS CT entry. This allows the
// CT GC to remove corresponding SNAT entries. In the case of 4, will create
// CT_INGRESS CT entry. See the unit test TestOrphanNatGC for more examples.
//
// The function only handles 1-3 cases, the 4. case is TODO(brb).
func PurgeOrphanNATEntries(ctMapTCP, ctMapAny *Map) *NatGCStats {
	if option.Config.NodePortMode == option.NodePortModeDSR ||
		option.Config.NodePortMode == option.NodePortModeHybrid {
		return nil
	}

	// Both CT maps should point to the same natMap, so use the first one
	// to determine natMap
	natMap := mapInfo[ctMapTCP.mapType].natMap
	if natMap == nil {
		return nil
	}

	family := gcFamilyIPv4
	if ctMapTCP.mapType.isIPv6() {
		family = gcFamilyIPv6
	}
	stats := newNatGCStats(natMap, family)
	defer stats.finish()

	cb := func(key bpf.MapKey, value bpf.MapValue) {
		natKey := key.(nat.NatKey)
		natVal := value.(nat.NatEntry)

		ctMap := ctMapAny
		if natKey.GetNextHeader() == u8proto.TCP {
			ctMap = ctMapTCP
		}

		if natKey.GetFlags()&tuple.TUPLE_F_IN == 1 { // natKey is r(everse)tuple
			ctKey := egressCTKeyFromIngressNatKeyAndVal(natKey, natVal)
			if _, err := ctMap.Lookup(ctKey); errors.Is(err, unix.ENOENT) {
				// No CT entry is found, so delete SNAT for both original and
				// reverse flows
				oNatKey := oNatKeyFromReverse(natKey, natVal)
				if deleted, _ := natMap.Delete(oNatKey); deleted {
					stats.EgressDeleted += 1
				}
				if deleted, _ := natMap.Delete(natKey); deleted {
					stats.IngressDeleted += 1
				}
			} else {
				stats.IngressAlive += 1
			}
		}
	}

	natMap.DumpReliablyWithCallback(cb, stats.DumpStats)

	return &stats
}

// Flush runs garbage collection for map m with the name mapType, deleting all
// entries. The specified map must be already opened using bpf.OpenMap().
func (m *Map) Flush() int {
	return doGC(m, &GCFilter{
		RemoveExpired: true,
		Time:          MaxTime,
	})
}

// DeleteIfUpgradeNeeded attempts to open the conntrack maps associated with
// the specified endpoint, and delete the maps from the filesystem if any
// properties do not match the properties defined in this package.
//
// The typical trigger for this is when, for example, the CT entry size changes
// from one version of Cilium to the next. When Cilium restarts, it may opt
// to restore endpoints from the prior life. Existing endpoints that use the
// old map style are incompatible with the new version, so the CT map must be
// destroyed and recreated during upgrade. By removing the old map location
// from the filesystem, we ensure that the next time that the endpoint is
// regenerated, it will recreate a new CT map with the new properties.
//
// Note that if an existing BPF program refers to the map at the canonical
// paths (as fetched via the getMapPathsToKeySize() call below), then that BPF
// program will continue to operate on the old map, even once the map is
// removed from the filesystem. The old map will only be completely cleaned up
// once all referenced to the map are cleared - that is, all BPF programs which
// refer to the old map and removed/reloaded.
func DeleteIfUpgradeNeeded(e CtEndpoint) {
	for _, newMap := range maps(e, true, true) {
		path, err := newMap.Path()
		if err != nil {
			log.WithError(err).Warning("Failed to get path for CT map")
			continue
		}
		scopedLog := log.WithField(logfields.Path, path)
		oldMap, err := bpf.OpenMap(path)
		if err != nil {
			scopedLog.WithError(err).Debug("Couldn't open CT map for upgrade")
			continue
		}
		if oldMap.CheckAndUpgrade(&newMap.Map.MapInfo) {
			scopedLog.Warning("CT Map upgraded, expect brief disruption of ongoing connections")
		}
		oldMap.Close()
	}
}

// maps returns all connecting tracking maps associated with endpoint 'e' (or
// the global maps if 'e' is nil).
func maps(e CtEndpoint, ipv4, ipv6 bool) []*Map {
	result := make([]*Map, 0, mapCount)
	if e == nil {
		if ipv4 {
			result = append(result, newMap(MapNameTCP4Global, mapTypeIPv4TCPGlobal))
			result = append(result, newMap(MapNameAny4Global, mapTypeIPv4AnyGlobal))
		}
		if ipv6 {
			result = append(result, newMap(MapNameTCP6Global, mapTypeIPv6TCPGlobal))
			result = append(result, newMap(MapNameAny6Global, mapTypeIPv6AnyGlobal))
		}
	} else {
		if ipv4 {
			result = append(result, newMap(bpf.LocalMapName(MapNameTCP4, uint16(e.GetID())),
				mapTypeIPv4TCPLocal))
			result = append(result, newMap(bpf.LocalMapName(MapNameAny4, uint16(e.GetID())),
				mapTypeIPv4AnyLocal))
		}
		if ipv6 {
			result = append(result, newMap(bpf.LocalMapName(MapNameTCP6, uint16(e.GetID())),
				mapTypeIPv6TCPLocal))
			result = append(result, newMap(bpf.LocalMapName(MapNameAny6, uint16(e.GetID())),
				mapTypeIPv6AnyLocal))
		}
	}
	return result
}

// LocalMaps returns a slice of CT maps for the endpoint, which are local to
// the endpoint and not shared with other endpoints. If ipv4 or ipv6 are false,
// the maps for that protocol will not be returned.
//
// The returned maps are not yet opened.
func LocalMaps(e CtEndpoint, ipv4, ipv6 bool) []*Map {
	return maps(e, ipv4, ipv6)
}

// GlobalMaps returns a slice of CT maps that are used globally by all
// endpoints that are not otherwise configured to use their own local maps.
// If ipv4 or ipv6 are false, the maps for that protocol will not be returned.
//
// The returned maps are not yet opened.
func GlobalMaps(ipv4, ipv6 bool) []*Map {
	return maps(nil, ipv4, ipv6)
}

// NameIsGlobal returns true if the specified filename (basename) denotes a
// global conntrack map.
func NameIsGlobal(filename string) bool {
	switch filename {
	case MapNameTCP4Global, MapNameAny4Global, MapNameTCP6Global, MapNameAny6Global:
		return true
	}
	return false
}

// WriteBPFMacros writes the map names for conntrack maps into the specified
// writer, defining usage of the global map or local maps depending on whether
// the specified CtEndpoint is nil.
func WriteBPFMacros(fw io.Writer, e CtEndpoint) {
	var mapEntriesTCP, mapEntriesAny int
	for _, m := range maps(e, true, true) {
		fmt.Fprintf(fw, "#define %s %s\n", m.define, m.Name())
		if m.mapType.isTCP() {
			mapEntriesTCP = mapInfo[m.mapType].maxEntries
		} else {
			mapEntriesAny = mapInfo[m.mapType].maxEntries
		}
	}
	fmt.Fprintf(fw, "#define CT_MAP_SIZE_TCP %d\n", mapEntriesTCP)
	fmt.Fprintf(fw, "#define CT_MAP_SIZE_ANY %d\n", mapEntriesAny)
}

// Exists returns false if the CT maps for the specified endpoint (or global
// maps if nil) are not pinned to the filesystem, or true if they exist or
// an internal error occurs.
func Exists(e CtEndpoint, ipv4, ipv6 bool) bool {
	result := true
	for _, m := range maps(e, ipv4, ipv6) {
		path, err := m.Path()
		if err != nil {
			// Catch this error early
			return true
		}
		if _, err = os.Stat(path); os.IsNotExist(err) {
			result = false
		}
	}

	return result
}

var cachedGCInterval time.Duration

// GetInterval returns the interval adjusted based on the deletion ratio of the
// last run
func GetInterval(mapType bpf.MapType, maxDeleteRatio float64) (interval time.Duration) {
	if val := option.Config.ConntrackGCInterval; val != time.Duration(0) {
		interval = val
		return
	}

	if interval = cachedGCInterval; interval == time.Duration(0) {
		interval = defaults.ConntrackGCStartingInterval
	}

	return calculateInterval(mapType, interval, maxDeleteRatio)
}

func calculateInterval(mapType bpf.MapType, prevInterval time.Duration, maxDeleteRatio float64) (interval time.Duration) {
	interval = prevInterval

	if maxDeleteRatio == 0.0 {
		return
	}

	switch {
	case maxDeleteRatio > 0.25:
		if maxDeleteRatio > 0.9 {
			maxDeleteRatio = 0.9
		}
		// 25%..90% => 1.3x..10x shorter
		interval = time.Duration(float64(interval) * (1.0 - maxDeleteRatio)).Round(time.Second)

		if interval < defaults.ConntrackGCMinInterval {
			interval = defaults.ConntrackGCMinInterval
		}

	case maxDeleteRatio < 0.05:
		// When less than 5% of entries were deleted, increase the
		// interval. Use a simple 1.5x multiplier to start growing slowly
		// as a new node may not be seeing workloads yet and thus the
		// scan will return a low deletion ratio at first.
		interval = time.Duration(float64(interval) * 1.5).Round(time.Second)

		switch mapType {
		case bpf.MapTypeLRUHash:
			if interval > defaults.ConntrackGCMaxLRUInterval {
				interval = defaults.ConntrackGCMaxLRUInterval
			}
		default:
			if interval > defaults.ConntrackGCMaxInterval {
				interval = defaults.ConntrackGCMaxInterval
			}
		}
	}

	if interval != prevInterval {
		log.WithFields(logrus.Fields{
			"newInterval": interval,
			"deleteRatio": maxDeleteRatio,
		}).Info("Conntrack garbage collector interval recalculated")
	}

	cachedGCInterval = interval

	return
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using WindowsStoreServices.V1.Common;

namespace WindowsStoreServices.V1
{
    public class GroupableRequestBuilder<TRequestBuilder, TRequest, TOrderByFields, TGroupByFields>
        : RequestBuilder<TRequestBuilder, TRequest, TOrderByFields>
        where TRequestBuilder : GroupableRequestBuilder<TRequestBuilder, TRequest, TOrderByFields, TGroupByFields>
        where TRequest : GroupableRequest<TOrderByFields, TGroupByFields>, new()
    {
        public GroupableRequestBuilder(string applicationId)
            : base(applicationId)
        {
            Request.GroupBy = new List<TGroupByFields>();
        }

        public TRequestBuilder GroupBy(TGroupByFields groupByValue)
        {
            Request.GroupBy = new List<TGroupByFields>()
            {
                groupByValue
            };
            return this as TRequestBuilder;
        }

        public TRequestBuilder ThenGroupBy(TGroupByFields groupByValue)
        {
            Request.GroupBy.Add(groupByValue);
            return this as TRequestBuilder;
        }
    }
}


text:
package com.ivan.xinput;

/**
 * Represents the delta (change) of the buttons between two successive polls.
 *
 * @author Ivan "StrikerX3" Oliveira
 */
public class XInputButtonsDelta {
	private final XInputButtons lastButtons;
	private final XInputButtons buttons;

	protected XInputButtonsDelta(final XInputButtons lastButtons, final XInputButtons buttons) {
		this.lastButtons = lastButtons;
		this.buttons = buttons;
	}

	/**
	 * Returns true if the button was pressed (i.e. changed from released to pressed between two consecutive polls).
	 *
	 * @param button the button
	 * @return true if the button was pressed, false otherwise
	 */
	public boolean isPressed(final XInputButton button) {
		return delta(lastButtons, buttons, button);
	}

	/**
	 * Returns true if the button was released (i.e. changed from pressed to released between two consecutive polls).
	 *
	 * @param button the button
	 * @return true if the button was released, false otherwise
	 */
	public boolean isReleased(final XInputButton button) {
		return delta(buttons, lastButtons, button);
	}

	/**
	 * Determines if the state of a button was changed from one poll to the following poll.
	 *
	 * @param from the old state
	 * @param to the new state
	 * @param button the button
	 * @return true if there was a change, false otherwise
	 */
	private boolean delta(final XInputButtons from, final XInputButtons to, final XInputButton button) {
		switch (button) {
			case A:
				return !from.a && to.a;
			case B:
				return !from.b && to.b;
			case X:
				return !from.x && to.x;
			case Y:
				return !from.y && to.y;
			case BACK:
				return !from.back && to.back;
			case START:
				return !from.start && to.start;
			case LEFT_SHOULDER:
				return !from.lShoulder && to.lShoulder;
			case RIGHT_SHOULDER:
				return !from.rShoulder && to.rShoulder;
			case LEFT_THUMBSTICK:
				return !from.lThumb && to.lThumb;
			case RIGHT_THUMBSTICK:
				return !from.rThumb && to.rThumb;
			case UP:
				return !from.up && to.up;
			case DOWN:
				return !from.down && to.down;
			case LEFT:
				return !from.left && to.left;
			case RIGHT:
				return !from.right && to.right;
		}
		return false;
	}
}


text:
using UnityEngine;
using System.Collections;

public class DestroyByExplosion : MonoBehaviour {
	private Transform originStart;
	private Vector3 direction;
	private float colRadius;
	public float maxDamage = 200f;
	public float minDamage = 75f;
	//public GameObject blood;
	public LayerMask obstacleLayerMask;
	public LayerMask colliderLayerMask;
	public float explosionForce;

	private PlayerStats playerStats;
	private EnemyStats enemyStats;
	private Collider[] hitColliders;

	public void ExplodeAndDamage(){
		colRadius = GetComponent<SphereCollider> ().radius;

		Collider[] hitColliders = Physics.OverlapSphere(transform.position, colRadius, colliderLayerMask);

		foreach(Collider other in hitColliders){
			if ((other.gameObject.transform.parent.tag == Tags.enemy || other.gameObject.transform.parent.tag == Tags.npc || other.gameObject.transform.parent.tag == Tags.neutral) && !other.isTrigger) {
				enemyStats = other.gameObject.transform.GetComponentInParent<EnemyStats>();

				RaycastHit hit;
				originStart = gameObject.transform;
				//Debug.Log (originStart);
				direction = other.transform.position - transform.position;

				//Debug.Log (direction);
				if(Physics.Raycast (originStart.position, direction.normalized, out hit, direction.magnitude, obstacleLayerMask)){
					//Debug.Log ("Hit environment!");
					if(hit.distance > direction.magnitude){
						//Debug.Log ("Damage Enemy");
						//Calculate Damage:
						float damage = (minDamage-maxDamage)/colRadius*direction.magnitude + maxDamage;
						enemyStats.enemyHealth -= damage;
						enemyStats.explosionForce = explosionForce*(damage-minDamage)/(maxDamage-minDamage);
						enemyStats.explosionLocation = transform.position;
						//enemyStats.explosionRadius = colRadius;

						Quaternion newRotation = Quaternion.LookRotation(new Vector3(other.transform.position.x - transform.position.x, 0.0f, other.transform.position.z-transform.position.z), Vector3.up);
						newRotation *= Quaternion.Euler(90,0,0);
						enemyStats.BloodEffects("highVelocityBlunt", other.transform.position, newRotation);
						//Instantiate (blood, other.transform.position, newRotation);
						//Destroy (other.gameObject);
					}

				}
				else {
					//Debug.Log ("Damage Enemy");
					float damage = (minDamage-maxDamage)/colRadius*direction.magnitude + maxDamage;
					enemyStats.enemyHealth -= damage;
					enemyStats.explosionForce = explosionForce*(damage-minDamage)/(maxDamage-minDamage);
					enemyStats.explosionLocation = transform.position;
					//enemyStats.explosionRadius = colRadius;
					Quaternion newRotation = Quaternion.LookRotation(new Vector3(other.transform.position.x - transform.position.x, 0.0f, other.transform.position.z-transform.position.z), Vector3.up);
					newRotation *= Quaternion.Euler(90,0,0);
					enemyStats.BloodEffects("highVelocityBlunt", other.transform.position, newRotation);
					//Instantiate (blood, other.transform.position, newRotation);
					//Destroy (other.gameObject);
				}
			}

			if (other.gameObject.transform.parent.tag == Tags.player && !other.isTrigger) {
				playerStats = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<PlayerStats>();
				//Debug.Log (other.gameObject.name);
				RaycastHit hit;
				originStart = gameObject.transform;
				//Debug.Log (originStart);
				direction = other.transform.position - transform.position;
				//Debug.Log (direction);
				if(Physics.Raycast (originStart.position, direction.normalized, out hit, direction.magnitude, obstacleLayerMask)){
					//Debug.Log ("Hit environment!");
					if(hit.distance > direction.magnitude){
						//Debug.Log ("But it was behind the explosion!");
						float damage = (minDamage-maxDamage)/colRadius*direction.magnitude + maxDamage;
						//Debug.Log ("Damage Player");
						playerStats.playerHealth -= damage;
						playerStats.explosionForce = explosionForce*(damage-minDamage)/(maxDamage-minDamage);
						playerStats.explosionLocation = transform.position;
						//playerStats.explosionRadius = colRadius;
						Quaternion newRotation = Quaternion.LookRotation(new Vector3(other.transform.position.x - transform.position.x, 0.0f, other.transform.position.z-transform.position.z), Vector3.up);
						newRotation *= Quaternion.Euler(90,0,0);
						playerStats.BloodEffects("highVelocityBlunt", other.transform.position, newRotation);
						//Instantiate (blood, other.transform.position, newRotation);
						//Destroy (other.gameObject);
					}

				}
				else {

					float damage = (minDamage-maxDamage)/colRadius*direction.magnitude + maxDamage;

					playerStats.playerHealth -= damage;
					playerStats.explosionForce = explosionForce*(damage-minDamage)/(maxDamage-minDamage);
					playerStats.explosionLocation = transform.position;
					//playerStats.explosionRadius = colRadius;
					Quaternion newRotation = Quaternion.LookRotation(new Vector3(other.transform.position.x - transform.position.x, 0.0f, other.transform.position.z-transform.position.z), Vector3.up);
					newRotation *= Quaternion.Euler(90,0,0);
					playerStats.BloodEffects("highVelocityBlunt", other.transform.position, newRotation);
					//Instantiate (blood, other.transform.position, newRotation);

				}
			}
			// Explosion affecting other Physics objects...
			if (other.gameObject.transform.parent.tag == Tags.physicsInteractable && !other.isTrigger) {

				RaycastHit hit;
				originStart = gameObject.transform;
				//Determine vector to explosion interactable collider parent
				direction = other.transform.parent.position - transform.position;

				//Test to see if an obstacle is within range...
				if(Physics.Raycast (originStart.position, direction.normalized, out hit, direction.magnitude, obstacleLayerMask)){

					//There is an obstacle.  Test to see if the obstacle is a PhysicsInteractable obstacle...
					if (hit.transform.tag != Tags.physicsInteractable){
						//If it is not PhysicsInteractable, it is a solid barrier.  Test to see if the obstacle is behind the object...
						if(hit.distance > direction.magnitude){
							//The obstacle is behind the object, so it is unprotected and an explosion force is added...
							other.gameObject.transform.parent.GetComponent<Rigidbody>().AddExplosionForce(explosionForce, transform.position, colRadius);
						}
					}
					else {
						//The obstacle is PhysicsInteractable, so an explosion force is added...
						other.gameObject.transform.parent.GetComponent<Rigidbody>().AddExplosionForce(explosionForce, transform.position, colRadius);
					}
				}
				else {
					//There is no obstacle in the way, and an explosion force is added...
					other.gameObject.transform.parent.GetComponent<Rigidbody>().AddExplosionForce(explosionForce, transform.position, colRadius);
				}
			}
		}
	}
}


text:
require 'rails_helper'

RSpec.describe "AllFieldTypes", :type => :request do
  describe "GET /all_field_types" do
    it "works! (now write some real specs)" do
      get all_field_types_path
      expect(response.status).to be(200)
    end
  end
end


text:
<?php

/**
 * @ignore
 */
if (!defined('LOG4PHP_DIR')) define('LOG4PHP_DIR', dirname(__FILE__));

require_once(LOG4PHP_DIR . '/spi/LoggerConfigurator.php');
require_once(LOG4PHP_DIR . '/layouts/LoggerLayoutTTCC.php');
require_once(LOG4PHP_DIR . '/appenders/LoggerAppenderConsole.php');
require_once(LOG4PHP_DIR . '/LoggerManager.php');

/**
 * Use this class to quickly configure the package.
 *
 *
For file based configuration see {@link LoggerPropertyConfigurator}.
 *
For XML based configuration see {@link LoggerDOMConfigurator}.
 *
 * @author  Marco Vassura
 * @version $Revision: 635069 $
 * @package log4php
 */
class LoggerBasicConfigurator implements LoggerConfigurator {

    /**
     * Add a {@link LoggerAppenderConsole} that uses
     * the {@link LoggerLayoutTTCC} to the root category.
     *
     * @param string $url not used here
     */
    public static function configure($url = null)
    {
        $root = LoggerManager::getRootLogger();
        $appender = new LoggerAppenderConsole('A1');
        $appender->setLayout( new LoggerLayoutTTCC() );
        $root->addAppender($appender);
    }

    /**
     * Reset the default hierarchy to its default.
     * It is equivalent to
     *
     * LoggerManager::resetConfiguration();
     *
     *
     * @see LoggerHierarchy::resetConfiguration()
     * @static
     */
    public static function resetConfiguration()
    {
        LoggerManager::resetConfiguration();
    }
}


text:
import _extends from "@babel/runtime/helpers/extends";
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { TextInputWithUnit } from '../../../../form/input/text-input-with-unit';
import { Context } from '../context';
export const Input = _ref => {
  let {
    valid,
    onChange,
    className,
    ...props
  } = _ref;
  return /*#__PURE__*/React.createElement(Context.Consumer, null, _ref2 => {
    let {
      setEmptyInput
    } = _ref2;
    return /*#__PURE__*/React.createElement(TextInputWithUnit, _extends({
      wrapperProps: {
        className: 'k-ContributionCard__inputWrapper'
      },
      valid: valid,
      className: classNames('k-ContributionCard__input', className),
      onChange: event => {
        var _event$target, _event$target$value;

        setEmptyInput(((_event$target = event.target) == null ? void 0 : (_event$target$value = _event$target.value) == null ? void 0 : _event$target$value.length) === 0);
        onChange(event);
      }
    }, props));
  });
};
Input.propTypes = {
  valid: PropTypes.bool,
  onChange: PropTypes.func,
  className: PropTypes.string
};
Input.defaultProps = {
  onChange: () => null
};


text:
 #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
from setuptools import setup

setup(
    name='django-digest',
    version='1.14',
    description=('An implementation of HTTP Digest Authentication for Django.'),
    long_description=(
"""
django-digest supplies a middleware (HttpDigestMiddleware) that may installed to protect access
to all URLs, a decorator (@httpdigest) that may be applied to selected view functions, and a
simple class (HttpDigestAuthenticator) that can be used to implement custom authentication
scenarios.

django-digest also supplies a subclass of django.test.Client that is able to perform Digest and
Basic authentication.
"""
    ),
    author='Akoha Inc.',
    author_email='adminmail@akoha.com',
    url='http://bitbucket.org/akoha/django-digest/',
    packages=['django_digest',
              'django_digest.backend',
              'django_digest.migrations',
              'django_digest.test',
              'django_digest.test.methods'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
     ],
    zip_safe=False,
)


text:
"""
The implementation of parsed XPath expression tokens.
"""

from amara.xpath import datatypes
from amara.xpath.compiler import xpathcompiler

__all__ = ['expression']

class expression(object):

    return_type = datatypes.xpathobject

    class __metaclass__(type):
        pass

    def compile(self, compiler):
        raise NotImplementedError('%s.compile' % (self.__class__.__name__,))

    def compile_as_boolean(self, compiler):
        """Compiles the expression into a boolean result."""
        # Load the callable object
        compiler.emit('LOAD_CONST', datatypes.boolean)
        # Build the argument(s)
        self.compile(compiler)
        compiler.emit('CALL_FUNCTION', 1)
        return

    def compile_as_number(self, compiler):
        """Compiles the expression into a number result."""
        # Load the callable object
        compiler.emit('LOAD_CONST', datatypes.number)
        # Build the argument(s)
        self.compile(compiler)
        compiler.emit('CALL_FUNCTION', 1)

    def compile_as_string(self, compiler):
        """Compiles the expression into a string result."""
        # Load the callable object
        compiler.emit('LOAD_CONST', datatypes.string)
        # Build the argument(s)
        self.compile(compiler)
        compiler.emit('CALL_FUNCTION', 1)

    def compile_as_nodeset(self, compiler):
        """Compiles the expression into a nodeset result.
        By default, this is an error.
        """
        raise TypeError('cannot convert to a nodeset')

    def compile_iterable(self, compiler):
        """Compiles the expression into an iterable.
        By default, this is an error.
        """
        raise TypeError('cannot convert to a nodeset')

    def evaluate(self, context):
        # Lazily generate the Python function for the expression.
        compiler = xpathcompiler(context)
        self.compile(compiler)
        self.evaluate = compiler.compile('evaluate',
                                         docstring=unicode(self))
        return self.evaluate(context)

    def evaluate_as_boolean(self, context):
        # Lazily generate the Python function for the expression.
        compiler = xpathcompiler(context)
        self.compile_as_boolean(compiler)
        self.evaluate_as_boolean = compiler.compile('evaluate_as_boolean',
                                                    docstring=unicode(self))
        return self.evaluate_as_boolean(context)

    def evaluate_as_number(self, context):
        # Lazily generate the Python function for the expression.
        compiler = xpathcompiler(context)
        self.compile_as_number(compiler)
        self.evaluate_as_number = compiler.compile('evaluate_as_number',
                                                   docstring=unicode(self))
        return self.evaluate_as_number(context)

    def evaluate_as_string(self, context):
        # Lazily generate the Python function for the expression.
        compiler = xpathcompiler(context)
        self.compile_as_string(compiler)
        self.evaluate_as_string = compiler.compile('evaluate_as_string',
                                                   docstring=unicode(self))
        return self.evaluate_as_string(context)

    def evaluate_as_nodeset(self, context):
        # Lazily generate the Python function for the expression.
        compiler = xpathcompiler(context)
        self.compile_as_nodeset(compiler)
        self.evaluate_as_nodeset = compiler.compile('evaluate_as_nodeset',
                                                    docstring=unicode(self))
        return self.evaluate_as_nodeset(context)

    def __str__(self):
        return self.__unicode__().encode('utf-8')

    def __unicode__(self):
        raise NotImplementedError('subclass %r must override' %
                                  self.__class__.__name__)

    def __repr__(self):
        ptr = id(self)
        if ptr < 0: ptr += 0x100000000L
        return '<%s at 0x%x: %s>' % (self.__class__.__name__, ptr, self)


text:
package y2w.model.messages;

import com.y2w.uikit.utils.StringUtil;
import com.yun2win.utils.Json;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by maa2 on 2016/3/18.
 */
public class MessageCrypto {
    private static MessageCrypto build;
    public static MessageCrypto getInstance(){
        if(build == null){
            build = new MessageCrypto();
        }
        return build;
    }

    public String encryText(String text){
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("text",text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonobject.toString();
    }

    public String decryText(String content){
        Json json = new Json(content);
        if(!StringUtil.isEmpty(json.getStr(MessageType.Text))){
            content =  json.getStr(MessageType.Text);
        }
        return content;
    }

}


text:
package reka.config.parser.handlers;

import static com.google.common.base.Preconditions.checkState;
import static java.lang.Character.isWhitespace;

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

import reka.config.Config;
import reka.config.parser.ParseContext;
import reka.config.parser.ParseHandler;
import reka.config.parser.values.BodyVal;

public class BodyHandler implements ParseHandler {

	private final boolean isRoot;

	public BodyHandler(boolean isRoot) {
		this.isRoot = isRoot;
	}

	private final List<Config> configs = new ArrayList<>();

	public void receive(Config config) {
		configs.add(config);
	}

	@Override
	public void accept(ParseContext ctx) {

		while (!ctx.isEOF()) {
			char c = ctx.peekChar();
			if (isWhitespace(c)) {
				ctx.popChar();
			} else if (c == '}') {
				checkState(!isRoot, "unexpected }");
				ctx.popChar();
				ctx.emit("body", new BodyVal(configs));
				break;
			} else {
				ctx.parse(new ItemHandler());
			}
		}

	}

	public List<Config> configs() {
		return configs;
	}

}


text:
'use strict';

angular.module('smartHome')
  .factory('trelloService', function($q, $http, smartHomeConfig) {
    let self = this;
    self.lists = [];

    return {
      getLists: function() {
        var deferred = $q.defer();
        console.log('Loading check lists');
        $http.get('http://' + smartHomeConfig.endpoint + ':' + smartHomeConfig.port + '/api/trello/bh02mtqQ').success(function(lists) {
          self.lists = lists.reduce((arr,list)=>{
            list.checkItems.forEach(function(element) {
              arr.push(element);
            }, this);

            return arr;
          },[]);
          deferred.resolve(lists);
        });

        return deferred.promise;
      },
      getIncompleteTasks: function(){
        let tmp = 0;
        console.log(self.lists);
        for (var key in self.lists) {
          if(self.lists[key].state !== 'complete'){
            tmp += 1;
          }
        }
        return tmp;
      }
    };
  });


text:
package OpenXPKI::Client::Enrollment::DevDie;
use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;

# This action will render a template
sub dev_die {
    my $self = shift;

    die "We expect the process to die here."

}

1;


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

	class AltaArticulo_c extends CI_Controller {

		function __construct(){

				parent::__construct();

				$this-> load ->helper(array('url', 'html'));//puedo enlistar la lista de controladores que vaya a necesitar mediate comas
				$this-> config ->base_url();
				$this->load->library(array('user_agent'));
				$this-> load ->model(array('altaArticulo_m'));//puedo enlistar la lista de modelos que vaya a necesitar mediate comas
			}

		public function index(){

			$datos['cat_tipo']=$this->altaArticulo_m->traerTipos();
			$datos['cat_estatus']=$this->altaArticulo_m->traerEstatus();

			$this->load->view('altaArticulo_v',$datos);
		}//FinIdex

		public function traerCatalogos(){
			$datos['cat_tipo']=$this->altaArticulo_m->traerTipos();
			$datos['cat_estatus']=$this->altaArticulo_m->traerEstatus();

			if($datos){

				$respuesta_json= array(
			 		'code' => 200,
			 		'message' => 'Catalogo correcto',
			 		'data' => $datos
			 	 );
				echo json_encode($respuesta_json);
			}else{
				$respuesta_json= array(
			 		'code' => 600,
			 		'message' => 'Catalogo incorrecto',
			 		'data' => 'Error'
			 	 );
				echo json_encode($respuesta_json);
			}
		}

		public function traerTipos(){
			$tipos=$this->altaArticulo_m->traerTipos();

			if($tipos){

				$respuesta_json= array(
			 		'code' => 200,
			 		'message' => 'Tipo correcto',
			 		'data' => json_encode($tipos)
			 	 );
				echo json_encode($respuesta_json);
			}else{
				$respuesta_json= array(
			 		'code' => 600,
			 		'message' => 'Tipo incorrecto',
			 		'data' => 'Error'
			 	 );
				echo json_encode($respuesta_json);
			}
		}//FinTraerTipos

		public function traerEstatus(){
			$tipos=$this->altaArticulo_m->traerEstatus();

			if($tipos){

				$respuesta_json= array(
			 		'code' => 200,
			 		'message' => 'Estatus correcto',
			 		'data' => json_encode($tipos)
			 	 );
				echo json_encode($respuesta_json);
			}else{
				$respuesta_json= array(
			 		'code' => 600,
			 		'message' => 'Estatus incorrecto',
			 		'data' => 'Error'
			 	 );
				echo json_encode($respuesta_json);
			}
		}//FinTraerTipos

		public function altaArticulo(){

			$idTipoMueble = $this->input->post('id_tipo_mueble');
			$progresivo = $this->input->post('progresivo');
			$caracteristicas = $this->input->post('caracteristicas');
			$idEstatus = $this->input->post('id_estatus');
			$email = $this->input->post('email');

			$resultado = $this->altaArticulo_m->guardarArticulo($idTipoMueble, $progresivo, $caracteristicas, $idEstatus,$email);

			if($resultado){
				if($this->agent->mobile() && !$this->agent->is_browser()){
					$respuesta_json= array(
				 		'code' => 200,
				 		'message' => 'Alta de articulo exitosa',
				 		'data' => 'No aplica'
				 	 );
					echo json_encode($respuesta_json);
				}else{
					redirect(base_url().'consultarArticuloGral_c');
				}

			}else{
				if($this->agent->mobile() && !$this->agent->is_browser()){
					$respuesta_json= array(
				 		'code' => 600,
				 		'message' => 'Fallo al dar de alta',
				 		'data' => 'No aplica'
				 	 );
					echo json_encode($respuesta_json);
				}else{
					echo "No se realizo la inserción del artículo verifique los datos y si el email existe";
				}
			}
		}//FinAltaArticulo
	}//FinController
?>


text:
const FirebaseTokenGenerator = require ("firebase-token-generator");
const Readline = require ("readline");

const readline = Readline .createInterface ({
  input: process.stdin,
  output: process.stdout
});

readline .question ('FireBase secret: ', (answer) => {
  const tokenGenerator = new FirebaseTokenGenerator (answer);
  const token = tokenGenerator .createToken (
     { uid: "stripe-gateway"
     , version: "1"
     },
     { expires: 1e10 });
  console .log ('token:', token);
  readline .close ();
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.ma.masked_array.filled — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

NumPy v1.8 Manual »

numpy.ma.masked_array.filled¶

<tt class="descclassname">masked_array.</tt><tt class="descname">filled</tt><big>(</big>fill_value=None<big>)</big>[source]¶

Return a copy of self, with masked values filled with a given value.

<col class="field-name" />
<col class="field-body" />

Parameters:
fill_value : scalar, optional

The value to use for invalid entries (None by default).
If None, the <tt class="xref py py-obj docutils literal">fill_value</tt> attribute of the array is used instead.

Returns:
filled_array : ndarray

A copy of <tt class="docutils literal">self</tt> with invalid entries replaced by fill_value
(be it the function argument or the attribute of <tt class="docutils literal">self</tt>.

Notes

The result is not a MaskedArray!

Examples

>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
>>> x.filled()
array([1, 2, -999, 4, -999])
>>> type(x.filled())
<type 'numpy.ndarray'>

Subclassing is preserved. This means that if the data part of the masked
array is a matrix, <tt class="xref py py-obj docutils literal">filled</tt> returns a matrix:

>>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.filled()
matrix([[     1, 999999],
        [999999,      4]])

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
let's leaning javascript, start here with codes.

### API
check this file: `index.js`

### Contributing
- Fork this repo
- Clone your repo
- Install dependencies
- Checkout a feature branch
- Feel free to add your features
- Make sure your features are fully tested
- Open a pull request, and enjoy <3

### MIT license
Copyright (c) 2013 turing <o.u.turing@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---
![docor](https://cdn1.iconfinder.com/data/icons/windows8_icons_iconpharm/26/doctor.png)
generated using [docor](https://github.com/turingou/docor.git) @ 0.1.0. brought to you by [turingou](https://github.com/turingou)


text:
GitHub issue #69 - fetching an empty nvarchar using client buffer
--SKIPIF--
<?php require('skipif_mid-refactor.inc'); ?>
--FILE--
<?php
// Connect
require_once("MsCommon_mid-refactor.inc");

try {
    $conn = connect();

    $sql = "EXEC dbo.sp_executesql
    N'DECLARE @x nvarchar(max)
    SET @x = '''' -- empty string
    SELECT @x AS [Empty_Nvarchar_Max]'";

    $stmt = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED));
    $stmt->execute();

    $return = $stmt->fetchAll(PDO::FETCH_ASSOC);
    print_r($return);

    // Free the statement and connection resources.
    unset($stmt);
    unset($conn);

    print "Done";
} catch (PDOException $e) {
    var_dump($e->errorInfo);
}
?>
--EXPECT--
Array
(
    [0] => Array
        (
            [Empty_Nvarchar_Max] =>
        )

)
Done


text:
package org.elasticsearch.search.aggregations.metrics;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ScoreMode;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.DoubleArray;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.List;
import java.util.Map;

class SumAggregator extends NumericMetricsAggregator.SingleValue {

    private final ValuesSource.Numeric valuesSource;
    private final DocValueFormat format;

    private DoubleArray sums;
    private DoubleArray compensations;

    SumAggregator(String name, ValuesSource.Numeric valuesSource, DocValueFormat formatter, SearchContext context,
            Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException {
        super(name, context, parent, pipelineAggregators, metaData);
        this.valuesSource = valuesSource;
        this.format = formatter;
        if (valuesSource != null) {
            sums = context.bigArrays().newDoubleArray(1, true);
            compensations = context.bigArrays().newDoubleArray(1, true);
        }
    }

    @Override
    public ScoreMode scoreMode() {
        return valuesSource != null && valuesSource.needsScores() ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES;
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
            final LeafBucketCollector sub) throws IOException {
        if (valuesSource == null) {
            return LeafBucketCollector.NO_OP_COLLECTOR;
        }
        final BigArrays bigArrays = context.bigArrays();
        final SortedNumericDoubleValues values = valuesSource.doubleValues(ctx);
        return new LeafBucketCollectorBase(sub, values) {
            @Override
            public void collect(int doc, long bucket) throws IOException {
                sums = bigArrays.grow(sums, bucket + 1);
                compensations = bigArrays.grow(compensations, bucket + 1);

                if (values.advanceExact(doc)) {
                    final int valuesCount = values.docValueCount();
                    // Compute the sum of double values with Kahan summation algorithm which is more
                    // accurate than naive summation.
                    double sum = sums.get(bucket);
                    double compensation = compensations.get(bucket);
                    for (int i = 0; i < valuesCount; i++) {
                        double value = values.nextValue();
                        if (Double.isFinite(value) == false) {
                            sum += value;
                        } else if (Double.isFinite(sum)) {
                            double corrected = value - compensation;
                            double newSum = sum + corrected;
                            compensation = (newSum - sum) - corrected;
                            sum = newSum;
                        }
                    }
                    compensations.set(bucket, compensation);
                    sums.set(bucket, sum);
                }
            }
        };
    }

    @Override
    public double metric(long owningBucketOrd) {
        if (valuesSource == null || owningBucketOrd >= sums.size()) {
            return 0.0;
        }
        return sums.get(owningBucketOrd);
    }

    @Override
    public InternalAggregation buildAggregation(long bucket) {
        if (valuesSource == null || bucket >= sums.size()) {
            return buildEmptyAggregation();
        }
        return new InternalSum(name, sums.get(bucket), format, pipelineAggregators(), metaData());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalSum(name, 0.0, format, pipelineAggregators(), metaData());
    }

    @Override
    public void doClose() {
        Releasables.close(sums, compensations);
    }
}


text:
package com.amazonaws.services.glue.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.glue.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * BatchUpdatePartitionFailureEntryMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BatchUpdatePartitionFailureEntryMarshaller {

    private static final MarshallingInfo<List> PARTITIONVALUELIST_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PartitionValueList").build();
    private static final MarshallingInfo<StructuredPojo> ERRORDETAIL_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ErrorDetail").build();

    private static final BatchUpdatePartitionFailureEntryMarshaller instance = new BatchUpdatePartitionFailureEntryMarshaller();

    public static BatchUpdatePartitionFailureEntryMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(BatchUpdatePartitionFailureEntry batchUpdatePartitionFailureEntry, ProtocolMarshaller protocolMarshaller) {

        if (batchUpdatePartitionFailureEntry == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(batchUpdatePartitionFailureEntry.getPartitionValueList(), PARTITIONVALUELIST_BINDING);
            protocolMarshaller.marshall(batchUpdatePartitionFailureEntry.getErrorDetail(), ERRORDETAIL_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package org.hisp.dhis.trackedentity.action.program;

import com.opensymphony.xwork2.Action;
import org.hisp.dhis.attribute.Attribute;
import org.hisp.dhis.attribute.AttributeService;
import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator;
import org.hisp.dhis.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramTrackedEntityAttribute;
import org.hisp.dhis.relationship.RelationshipType;
import org.hisp.dhis.relationship.RelationshipTypeService;
import org.hisp.dhis.system.util.AttributeUtils;
import org.hisp.dhis.trackedentity.TrackedEntity;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityAttributeService;
import org.hisp.dhis.trackedentity.TrackedEntityService;
import org.hisp.dhis.user.UserGroup;
import org.hisp.dhis.user.UserGroupService;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author Chau Thu Tran
 * @version $Id$
 */
public class ShowUpdateProgramFormAction
    implements Action
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private ProgramService programService;

    public void setProgramService( ProgramService programService )
    {
        this.programService = programService;
    }

    private TrackedEntityAttributeService trackedEntityAttributeService;

    public void setTrackedEntityAttributeService( TrackedEntityAttributeService trackedEntityAttributeService )
    {
        this.trackedEntityAttributeService = trackedEntityAttributeService;
    }

    private UserGroupService userGroupService;

    public void setUserGroupService( UserGroupService userGroupService )
    {
        this.userGroupService = userGroupService;
    }

    private RelationshipTypeService relationshipTypeService;

    public void setRelationshipTypeService( RelationshipTypeService relationshipTypeService )
    {
        this.relationshipTypeService = relationshipTypeService;
    }

    @Autowired
    private TrackedEntityService trackedEntityService;

    @Autowired
    private AttributeService attributeService;

    // -------------------------------------------------------------------------
    // Input/Output
    // -------------------------------------------------------------------------

    private int id;

    public int getId()
    {
        return id;
    }

    public void setId( int id )
    {
        this.id = id;
    }

    private Program program;

    public Program getProgram()
    {
        return program;
    }

    private List<OrganisationUnitLevel> levels;

    public List<OrganisationUnitLevel> getLevels()
    {
        return levels;
    }

    private List<OrganisationUnitGroup> groups;

    public List<OrganisationUnitGroup> getGroups()
    {
        return groups;
    }

    private Integer level;

    public Integer getLevel()
    {
        return level;
    }

    public void setLevel( Integer level )
    {
        this.level = level;
    }

    private Integer organisationUnitGroupId;

    public Integer getOrganisationUnitGroupId()
    {
        return organisationUnitGroupId;
    }

    public void setOrganisationUnitGroupId( Integer organisationUnitGroupId )
    {
        this.organisationUnitGroupId = organisationUnitGroupId;
    }

    private List<TrackedEntityAttribute> availableAttributes;

    public List<TrackedEntityAttribute> getAvailableAttributes()
    {
        return availableAttributes;
    }

    private List<UserGroup> userGroups;

    public List<UserGroup> getUserGroups()
    {
        return userGroups;
    }

    private List<RelationshipType> relationshipTypes;

    public List<RelationshipType> getRelationshipTypes()
    {
        return relationshipTypes;
    }

    private List<Program> programs;

    public List<Program> getPrograms()
    {
        return programs;
    }

    private List<TrackedEntity> trackedEntities;

    public List<TrackedEntity> getTrackedEntities()
    {
        return trackedEntities;
    }

    private List<Attribute> attributes;

    public List<Attribute> getAttributes()
    {
        return attributes;
    }

    private Map<Integer, String> attributeValues = new HashMap<>();

    public Map<Integer, String> getAttributeValues()
    {
        return attributeValues;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
        throws Exception
    {
        program = programService.getProgram( id );

        attributeValues = AttributeUtils.getAttributeValueMap( program.getAttributeValues() );

        availableAttributes = new ArrayList<>( trackedEntityAttributeService.getAllTrackedEntityAttributes() );

        for ( ProgramTrackedEntityAttribute programTrackedEntityAttribute : program.getProgramAttributes() )
        {
            availableAttributes.remove( programTrackedEntityAttribute.getAttribute() );
        }

        Collections.sort( availableAttributes, IdentifiableObjectNameComparator.INSTANCE );

        programs = new ArrayList<>( programService.getAllPrograms() );
        programs.removeAll( programService.getPrograms( Program.SINGLE_EVENT_WITHOUT_REGISTRATION ) );
        programs.remove( program );
        Collections.sort( programs, IdentifiableObjectNameComparator.INSTANCE );

        userGroups = new ArrayList<>( userGroupService.getAllUserGroups() );

        relationshipTypes = new ArrayList<>( relationshipTypeService.getAllRelationshipTypes() );
        Collections.sort( relationshipTypes, IdentifiableObjectNameComparator.INSTANCE );

        trackedEntities = new ArrayList<>( trackedEntityService.getAllTrackedEntity() );
        Collections.sort( trackedEntities, IdentifiableObjectNameComparator.INSTANCE );

        attributes = new ArrayList<>( attributeService.getProgramAttributes() );

        return SUCCESS;
    }
}


text:
package org.apache.catalina.connector;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

import org.apache.catalina.security.SecurityUtil;
import org.apache.tomcat.util.res.StringManager;

/**
 * This class handles reading bytes.
 *
 * @author Remy Maucherat
 */
public class CoyoteInputStream extends ServletInputStream {

    protected static final StringManager sm = StringManager.getManager(CoyoteInputStream.class);

    protected InputBuffer ib;

    protected CoyoteInputStream(InputBuffer ib) {
        this.ib = ib;
    }

    /**
     * Clear facade.
     */
    void clear() {
        ib = null;
    }

    /**
     * Prevent cloning the facade.
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    @Override
    public int read() throws IOException {
        checkNonBlockingRead();

        if (SecurityUtil.isPackageProtectionEnabled()) {

            try {
                Integer result = AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Integer>() {

                            @Override
                            public Integer run() throws IOException {
                                Integer integer = Integer.valueOf(ib.readByte());
                                return integer;
                            }

                        });
                return result.intValue();
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            return ib.readByte();
        }
    }

    @Override
    public int available() throws IOException {

        if (SecurityUtil.isPackageProtectionEnabled()) {
            try {
                Integer result = AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Integer>() {

                            @Override
                            public Integer run() throws IOException {
                                Integer integer = Integer.valueOf(ib.available());
                                return integer;
                            }

                        });
                return result.intValue();
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            return ib.available();
        }
    }

    @Override
    public int read(final byte[] b) throws IOException {
        checkNonBlockingRead();

        if (SecurityUtil.isPackageProtectionEnabled()) {
            try {
                Integer result = AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Integer>() {

                            @Override
                            public Integer run() throws IOException {
                                Integer integer = Integer.valueOf(ib.read(b, 0, b.length));
                                return integer;
                            }

                        });
                return result.intValue();
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            return ib.read(b, 0, b.length);
        }
    }

    @Override
    public int read(final byte[] b, final int off, final int len) throws IOException {
        checkNonBlockingRead();

        if (SecurityUtil.isPackageProtectionEnabled()) {
            try {
                Integer result = AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Integer>() {

                            @Override
                            public Integer run() throws IOException {
                                Integer integer = Integer.valueOf(ib.read(b, off, len));
                                return integer;
                            }

                        });
                return result.intValue();
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            return ib.read(b, off, len);
        }
    }

    /**
     * Transfers bytes from the buffer to the specified ByteBuffer. After the
     * operation the position of the ByteBuffer will be returned to the one
     * before the operation, the limit will be the position incremented by
     * the number of the transfered bytes.
     *
     * @param b the ByteBuffer into which bytes are to be written.
     * @return an integer specifying the actual number of bytes read, or -1 if
     *         the end of the stream is reached
     * @throws IOException if an input or output exception has occurred
     */
    public int read(final ByteBuffer b) throws IOException {
        checkNonBlockingRead();

        if (SecurityUtil.isPackageProtectionEnabled()) {
            try {
                Integer result = AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Integer>() {

                            @Override
                            public Integer run() throws IOException {
                                Integer integer = Integer.valueOf(ib.read(b));
                                return integer;
                            }

                        });
                return result.intValue();
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            return ib.read(b);
        }
    }

    @Override
    public int readLine(byte[] b, int off, int len) throws IOException {
        return super.readLine(b, off, len);
    }

    /**
     * Close the stream
     * Since we re-cycle, we can't allow the call to super.close()
     * which would permanently disable us.
     */
    @Override
    public void close() throws IOException {

        if (SecurityUtil.isPackageProtectionEnabled()) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {

                    @Override
                    public Void run() throws IOException {
                        ib.close();
                        return null;
                    }

                });
            } catch (PrivilegedActionException pae) {
                Exception e = pae.getException();
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } else {
            ib.close();
        }
    }

    @Override
    public boolean isFinished() {
        return ib.isFinished();
    }

    @Override
    public boolean isReady() {
        return ib.isReady();
    }

    @Override
    public void setReadListener(ReadListener listener) {
        ib.setReadListener(listener);
    }

    private void checkNonBlockingRead() {
        if (!ib.isBlocking() && !ib.isReady()) {
            throw new IllegalStateException(sm.getString("coyoteInputStream.nbNotready"));
        }
    }
}


text:
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext, Row

conf = SparkConf().setAppName("spark_sql_table_join")

sc = SparkContext(conf=conf)

sqlCtx = SQLContext(sc)

line1 = sc.parallelize(["name1 a", "name3 c", "name4 d"])

line2 = sc.parallelize(["name1 1", "name2 2", "name3 3"])

word1 = line1.map(lambda line: line.split(" "))

word2 = line2.map(lambda line: line.split(" "))

table1 = word1.map(lambda words: Row(name=words[0], title=words[1]))

table2 = word2.map(lambda words: Row(name=words[0], fraction=words[1]))

tableSchema1 = sqlCtx.inferSchema(table1)

tableSchema2 = sqlCtx.inferSchema(table2)

tableSchema1.registerTempTable("table1")

tableSchema2.registerTempTable("table2")

def printRows(rows):
    if rows:
        for row in rows:
            print row

# inner join
rows = sqlCtx.sql(
    "select table1.name, table1.title, table2.fraction from table1 join table2 on table1.name = table2.name").collect()

printRows(rows)

print "============================================="

# left outer join
rows = sqlCtx.sql(
    "select table1.name, table1.title, table2.fraction from table1 left outer join table2 on table1.name = table2.name").collect()

printRows(rows)

# right outer join
rows = sqlCtx.sql(
    "select table1.name, table1.title, table2.fraction from table1 right outer join table2 on table1.name = table2.name").collect()

print "============================================="

printRows(rows)

# full outer join
rows = sqlCtx.sql(
    "select table1.name, table1.title, table2.fraction from table1 full outer join table2 on table1.name = table2.name").collect()

print "============================================="

printRows(rows)

"""
Row(name=u'name1', title=u'a', fraction=u'1')
Row(name=u'name3', title=u'c', fraction=u'3')
=============================================
Row(name=u'name1', title=u'a', fraction=u'1')
Row(name=u'name3', title=u'c', fraction=u'3')
Row(name=u'name4', title=u'd', fraction=None)
=============================================
Row(name=u'name1', title=u'a', fraction=u'1')
Row(name=None, title=None, fraction=u'2')
Row(name=u'name3', title=u'c', fraction=u'3')
=============================================
Row(name=u'name1', title=u'a', fraction=u'1')
Row(name=None, title=None, fraction=u'2')
Row(name=u'name3', title=u'c', fraction=u'3')
Row(name=u'name4', title=u'd', fraction=None)
"""

sc.stop()


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('contributions', '0005_auto_20150202_1135'),
        ('geokey_epicollect', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='EpiCollectMedia',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('file_name', models.CharField(max_length=500)),
                ('contribution', models.ForeignKey(to='contributions.Observation')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
'use strict';

module.exports = {
  CodeViewEngine: require('./services/code-view-engine'),
  DefaultThemeSelector: require('./services/default-theme-selector'),
  DustViewEngine: require('./services/dust-view-engine'),
  FilePlacementStrategy: require('./services/file-placement-strategy'),
  RenderStream: require('./services/render-stream'),
  Shape: require('./services/shape'),
  ShapeItemPromiseHandler: require('./services/shape-item-promise-handler'),
  TemplateRenderingStrategy: require('./services/template-rendering-strategy')
};


text:
import pytest
from _pytest.main import EXIT_OK

@pytest.mark.usefixtures('monkeypatch_github3')
def test_xfail_particular_parametrize_test_ids(testdir, capsys):
    src = """
import pytest
@pytest.mark.github('https://github.com/some/open/issues/1', ids=['even2', 'even4'])
@pytest.mark.parametrize("count", [1, 2, 3, 4], ids=["odd1", "even2", "odd3", "even4"])
def test_will_xfail(count):
    assert count % 2
    """
    result = testdir.inline_runsource(src)
    stdout, stderr = capsys.readouterr()
    assert '2 xfailed' in stdout
    assert '2 passed' in stdout
    assert result.ret == EXIT_OK


text:
package com.pugnascotia.reactdemo.errors;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * The sole purpose of this controller is to explode as soon as the /explode route
 * is accessed. In so doing, we can test the rendering of server errors, and whether
 * the "auth" state key is correctly populated for an authenticated user.
 */

@Controller
public class ExplodeController {

	@RequestMapping("/explode")
	public String explode() {
		throw new RuntimeException("Explode!");
	}
}