text:
namespace slang {

struct AssociativeArray;
struct SVQueue;
struct SVUnion;

/// Represents an IEEE754 double precision floating point number.
/// This is a separate type from `double` to make it less likely that
/// an implicit C++ conversion will mess us up somewhere.
struct SLANG_EXPORT real_t {
    double v;

    real_t() : v(0.0) {}
    real_t(double v) : v(v) {}
    operator double() const { return v; }
};

/// Represents an IEEE754 single precision floating point number.
/// This is a separate type from `double` to make it less likely that
/// an implicit C++ conversion will mess us up somewhere.
struct SLANG_EXPORT shortreal_t {
    float v;

    shortreal_t() : v(0.0) {}
    shortreal_t(float v) : v(v) {}
    operator float() const { return v; }
};

/// Represents a constant (compile-time evaluated) value, of one of a few possible types.
/// By default the value is indeterminate, or "bad". Expressions involving bad
/// values result in bad values, as you might expect.
///
class SLANG_EXPORT ConstantValue {
public:
    /// This type represents the null value (class handles, etc) in expressions.
    struct NullPlaceholder : std::monostate {};

    /// This type represents the unbounded value ($) in expressions.
    struct UnboundedPlaceholder : std::monostate {};

    using Elements = std::vector<ConstantValue>;
    using Map = CopyPtr<AssociativeArray>;
    using Queue = CopyPtr<SVQueue>;
    using Union = CopyPtr<SVUnion>;

    using Variant = std::variant<std::monostate, SVInt, real_t, shortreal_t, NullPlaceholder,
                                 Elements, std::string, Map, Queue, Union, UnboundedPlaceholder>;

    ConstantValue() = default;
    ConstantValue(nullptr_t) {}

    ConstantValue(const SVInt& integer) : value(integer) {}
    ConstantValue(SVInt&& integer) : value(std::move(integer)) {}
    ConstantValue(real_t real) : value(real) {}
    ConstantValue(shortreal_t real) : value(real) {}

    ConstantValue(NullPlaceholder nul) : value(nul) {}
    ConstantValue(UnboundedPlaceholder unbounded) : value(unbounded) {}
    ConstantValue(const Elements& elements) : value(elements) {}
    ConstantValue(Elements&& elements) : value(std::move(elements)) {}
    ConstantValue(const std::string& str) : value(str) {}
    ConstantValue(std::string&& str) : value(std::move(str)) {}

    ConstantValue(const Map& map) : value(map) {}
    ConstantValue(Map&& map) : value(std::move(map)) {}
    ConstantValue(const AssociativeArray& aa) : value(Map(aa)) {}
    ConstantValue(AssociativeArray&& aa) : value(Map(std::move(aa))) {}

    ConstantValue(const Queue& queue) : value(queue) {}
    ConstantValue(Queue&& queue) : value(std::move(queue)) {}
    ConstantValue(const SVQueue& queue) : value(Queue(queue)) {}
    ConstantValue(SVQueue&& queue) : value(Queue(std::move(queue))) {}

    ConstantValue(const Union& unionVal) : value(unionVal) {}
    ConstantValue(Union&& unionVal) : value(std::move(unionVal)) {}
    ConstantValue(const SVUnion& unionVal) : value(Union(unionVal)) {}
    ConstantValue(SVUnion&& unionVal) : value(Union(std::move(unionVal))) {}

    bool bad() const { return std::holds_alternative<std::monostate>(value); }
    explicit operator bool() const { return !bad(); }

    bool isInteger() const { return std::holds_alternative<SVInt>(value); }
    bool isReal() const { return std::holds_alternative<real_t>(value); }
    bool isShortReal() const { return std::holds_alternative<shortreal_t>(value); }
    bool isNullHandle() const { return std::holds_alternative<NullPlaceholder>(value); }
    bool isUnbounded() const { return std::holds_alternative<UnboundedPlaceholder>(value); }
    bool isUnpacked() const { return std::holds_alternative<Elements>(value); }
    bool isString() const { return std::holds_alternative<std::string>(value); }
    bool isMap() const { return std::holds_alternative<Map>(value); }
    bool isQueue() const { return std::holds_alternative<Queue>(value); }
    bool isUnion() const { return std::holds_alternative<Union>(value); }

    bool isContainer() const { return isUnpacked() || isQueue() || isMap(); }

    SVInt& integer() & { return std::get<SVInt>(value); }
    const SVInt& integer() const& { return std::get<SVInt>(value); }
    SVInt integer() && { return std::get<SVInt>(std::move(value)); }
    SVInt integer() const&& { return std::get<SVInt>(std::move(value)); }

    real_t real() const { return std::get<real_t>(value); }
    shortreal_t shortReal() const { return std::get<shortreal_t>(value); }

    span<ConstantValue> elements() { return std::get<Elements>(value); }
    span<ConstantValue const> elements() const { return std::get<Elements>(value); }

    std::string& str() & { return std::get<std::string>(value); }
    const std::string& str() const& { return std::get<std::string>(value); }
    std::string str() && { return std::get<std::string>(std::move(value)); }
    std::string str() const&& { return std::get<std::string>(std::move(value)); }

    Map& map() & { return std::get<Map>(value); }
    const Map& map() const& { return std::get<Map>(value); }
    Map map() && { return std::get<Map>(std::move(value)); }
    Map map() const&& { return std::get<Map>(std::move(value)); }

    Queue& queue() & { return std::get<Queue>(value); }
    const Queue& queue() const& { return std::get<Queue>(value); }
    Queue queue() && { return std::get<Queue>(std::move(value)); }
    Queue queue() const&& { return std::get<Queue>(std::move(value)); }

    Union& unionVal() & { return std::get<Union>(value); }
    const Union& unionVal() const& { return std::get<Union>(value); }
    Union unionVal() && { return std::get<Union>(std::move(value)); }
    Union unionVal() const&& { return std::get<Union>(std::move(value)); }

    ConstantValue getSlice(int32_t upper, int32_t lower, const ConstantValue& defaultValue) const;

    Variant& getVariant() { return value; }
    const Variant& getVariant() const { return value; }

    std::string toString(
        bitwidth_t abbreviateThresholdBits = SVInt::DefaultStringAbbreviationThresholdBits,
        bool exactUnknowns = false, bool useAssignmentPatterns = false) const;
    size_t hash() const;

    [[nodiscard]] bool empty() const;
    size_t size() const;

    ConstantValue& at(size_t index);
    const ConstantValue& at(size_t index) const;

    bool isTrue() const;
    bool isFalse() const;
    bool hasUnknown() const;

    ConstantValue convertToInt() const;
    ConstantValue convertToInt(bitwidth_t width, bool isSigned, bool isFourState) const;
    ConstantValue convertToReal() const;
    ConstantValue convertToShortReal() const;
    ConstantValue convertToStr() const;
    ConstantValue convertToByteArray(bitwidth_t size, bool isSigned) const;
    ConstantValue convertToByteQueue(bool isSigned) const;

    /// Gets the size of this value when converted to a bitstream.
    size_t bitstreamWidth() const;

    static const ConstantValue Invalid;

    SLANG_EXPORT friend std::ostream& operator<<(std::ostream& os, const ConstantValue& cv);
    SLANG_EXPORT friend bool operator==(const ConstantValue& lhs, const ConstantValue& rhs);
    SLANG_EXPORT friend bool operator!=(const ConstantValue& lhs, const ConstantValue& rhs);
    SLANG_EXPORT friend bool operator<(const ConstantValue& lhs, const ConstantValue& rhs);

private:
    Variant value;
};

/// Represents a SystemVerilog associative array, for use during constant evaluation.
struct SLANG_EXPORT AssociativeArray : public std::map<ConstantValue, ConstantValue> {
    using std::map<ConstantValue, ConstantValue>::map;
    ConstantValue defaultValue;
};

/// Represents a SystemVerilog queue, for use during constant evaluation.
struct SLANG_EXPORT SVQueue : public std::deque<ConstantValue> {
    using std::deque<ConstantValue>::deque;
    uint32_t maxBound = 0;

    void resizeToBound() {
        if (maxBound && size() > maxBound + 1)
            resize(maxBound + 1);
    }
};

/// Represents a SystemVerilog unpacked union, for use during constant evaluation.
struct SLANG_EXPORT SVUnion {
    ConstantValue value;
    std::optional<uint32_t> activeMember;
};

/// An iterator for child elements in a ConstantValue, if it represents an
/// array, map, or queue.
class CVIterator
    : public iterator_facade<CVIterator, std::bidirectional_iterator_tag, ConstantValue> {
public:
    CVIterator(ConstantValue::Elements::iterator it) : current(it) {}
    CVIterator(AssociativeArray::iterator it) : current(it) {}
    CVIterator(SVQueue::iterator it) : current(it) {}
    CVIterator(const CVIterator& other) : current(other.current) {}

    CVIterator& operator=(const CVIterator& other) {
        current = other.current;
        return *this;
    }

    bool operator==(const CVIterator& other) const { return current == other.current; }

    const ConstantValue& operator*() const;
    ConstantValue& operator*();

    using iterator_facade::operator++;
    using iterator_facade::operator--;
    CVIterator& operator++();
    CVIterator& operator--();

    const ConstantValue& key() const;

private:
    std::variant<ConstantValue::Elements::iterator, AssociativeArray::iterator, SVQueue::iterator>
        current;
};

/// A constant iterator for child elements in a ConstantValue, if it represents an
/// array, map, or queue.
class CVConstIterator : public iterator_facade<CVConstIterator, std::bidirectional_iterator_tag,
                                               const ConstantValue> {
public:
    CVConstIterator(ConstantValue::Elements::const_iterator it) : current(it) {}
    CVConstIterator(AssociativeArray::const_iterator it) : current(it) {}
    CVConstIterator(SVQueue::const_iterator it) : current(it) {}
    CVConstIterator(const CVConstIterator& other) : current(other.current) {}

    CVConstIterator& operator=(const CVConstIterator& other) {
        current = other.current;
        return *this;
    }

    bool operator==(const CVConstIterator& other) const { return current == other.current; }

    const ConstantValue& operator*() const;

    using iterator_facade::operator++;
    using iterator_facade::operator--;
    CVConstIterator& operator++();
    CVConstIterator& operator--();

    const ConstantValue& key() const;

private:
    std::variant<ConstantValue::Elements::const_iterator, AssociativeArray::const_iterator,
                 SVQueue::const_iterator>
        current;
};

CVIterator begin(ConstantValue& cv);
CVIterator end(ConstantValue& cv);
CVConstIterator begin(const ConstantValue& cv);
CVConstIterator end(const ConstantValue& cv);

/// Represents a simple constant range, fully inclusive. SystemVerilog allows negative
/// indices, and for the left side to be less, equal, or greater than the right.
///
/// Note that this class makes no attempt to handle overflow of the underlying integer;
/// SystemVerilog places tighter bounds on possible ranges anyway so it shouldn't be an issue.
///
struct SLANG_EXPORT ConstantRange {
    int32_t left = 0;
    int32_t right = 0;

    /// Gets the width of the range, regardless of the order in which
    /// the bounds are specified.
    bitwidth_t width() const {
        int32_t diff = left - right;
        return bitwidth_t(diff < 0 ? -diff : diff) + 1;
    }

    /// Gets the lower bound of the range, regardless of the order in which
    /// the bounds are specified.
    int32_t lower() const { return std::min(left, right); }

    /// Gets the upper bound of the range, regardless of the order in which
    /// the bounds are specified.
    int32_t upper() const { return std::max(left, right); }

    /// "Little endian" bit order is when the msb is >= the lsb.
    bool isLittleEndian() const { return left >= right; }

    /// Reverses the bit ordering of the range.
    [[nodiscard]] ConstantRange reverse() const { return {right, left}; }

    /// Selects a subrange of this range, correctly handling both forms of
    /// bit endianness. This will assert that the given subrange is not wider.
    [[nodiscard]] ConstantRange subrange(ConstantRange select) const;

    /// Translates the given index to be relative to the range.
    /// For example, if the range is [7:2] and you pass in 3, the result will be 1.
    /// If the range is [2:7] and you pass in 3, the result will be 4.
    int32_t translateIndex(int32_t index) const;

    /// Determines whether the given point is within the range.
    bool containsPoint(int32_t index) const;

    /// Determines whether the given range overlaps with this one
    /// (including cases where one is wholly contained in the other).
    bool overlaps(ConstantRange other) const;

    /// Creates a constant range based on a left / right value that is either indexed up
    /// or indexed down. This implements the SystemVerilog range operators of '+:' and '-:'
    static std::optional<ConstantRange> getIndexedRange(int32_t l, int32_t r, bool littleEndian,
                                                        bool indexedUp);

    std::string toString() const;

    bool operator==(const ConstantRange& rhs) const {
        return left == rhs.left && right == rhs.right;
    }

    bool operator!=(const ConstantRange& rhs) const { return !(*this == rhs); }
    SLANG_EXPORT friend std::ostream& operator<<(std::ostream& os, const ConstantRange& cr);
};

} // namespace slang

namespace std {

template<>
struct hash<slang::ConstantValue> {
    size_t operator()(const slang::ConstantValue& cv) const { return cv.hash(); }
};

} // namespace std


text:
package manager

import (
	"fmt"
	"sort"
	"strings"
	"time"

	"github.com/apache/incubator-trafficcontrol/lib/go-log"
	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/health"
	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/peer"
	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/todata"
)

// StartStateCombiner starts the State Combiner goroutine, and returns the threadsafe CombinedStates, and a func to signal to combine states.
func StartStateCombiner(events health.ThreadsafeEvents, peerStates peer.CRStatesPeersThreadsafe, localStates peer.CRStatesThreadsafe, toData todata.TODataThreadsafe) (peer.CRStatesThreadsafe, func()) {
	combinedStates := peer.NewCRStatesThreadsafe()

	// the chan buffer just reduces the number of goroutines on our infinite buffer hack in combineState(), no real writer will block, since combineState() writes in a goroutine.
	combineStateChan := make(chan struct{}, 5)
	combineState := func() {
		go func() { combineStateChan <- struct{}{} }()
	}

	drain := func(c <-chan struct{}) {
	outer:
		for {
			select {
			case <-c:
				continue
			default:
				break outer
			}
		}
	}

	go func() {
		overrideMap := map[tc.CacheName]bool{}
		for range combineStateChan {
			drain(combineStateChan)
			combineCrStates(events, true, peerStates, localStates.Get(), combinedStates, overrideMap, toData.Get())
		}
	}()

	return combinedStates, combineState
}

func combineCacheState(cacheName tc.CacheName, localCacheState tc.IsAvailable, events health.ThreadsafeEvents, peerOptimistic bool, peerStates peer.CRStatesPeersThreadsafe, localStates tc.CRStates, combinedStates peer.CRStatesThreadsafe, overrideMap map[tc.CacheName]bool, toData todata.TOData) {
	overrideCondition := ""
	available := false
	override := overrideMap[cacheName]

	if localCacheState.IsAvailable {
		available = true // we don't care about the peers, we got a "good one", and we're optimistic

		if override {
			overrideCondition = "cleared; healthy locally"
			overrideMap[cacheName] = false
		}
	} else if peerOptimistic {
		if !peerStates.HasAvailablePeers() {
			if override {
				overrideCondition = "irrelevant; no peers online"
				overrideMap[cacheName] = false
			}
		} else {
			onlineOnPeers := make([]string, 0)

			for peer, peerCrStates := range peerStates.GetCrstates() {
				if peerStates.GetPeerAvailability(peer) {
					if peerCrStates.Caches[cacheName].IsAvailable {
						onlineOnPeers = append(onlineOnPeers, peer.String())
					}
				}
			}

			if len(onlineOnPeers) > 0 {
				available = true

				if !override {
					overrideCondition = fmt.Sprintf("detected; healthy on (at least) %s", strings.Join(onlineOnPeers, ", "))
					overrideMap[cacheName] = true
				}
			} else {
				if override {
					overrideCondition = "irrelevant; not online on any peers"
					overrideMap[cacheName] = false
				}
			}
		}
	}

	if overrideCondition != "" {
		events.Add(health.Event{Time: health.Time(time.Now()), Description: fmt.Sprintf("Health protocol override condition %s", overrideCondition), Name: cacheName.String(), Hostname: cacheName.String(), Type: toData.ServerTypes[cacheName].String(), Available: available})
	}

	combinedStates.AddCache(cacheName, tc.IsAvailable{IsAvailable: available})
}

func combineDSState(
	deliveryServiceName tc.DeliveryServiceName,
	localDeliveryService tc.CRStatesDeliveryService,
	events health.ThreadsafeEvents,
	peerOptimistic bool,
	peerStates peer.CRStatesPeersThreadsafe,
	localStates tc.CRStates,
	combinedStates peer.CRStatesThreadsafe,
	overrideMap map[tc.CacheName]bool,
	toData todata.TOData,
) {
	deliveryService := tc.CRStatesDeliveryService{IsAvailable: false, DisabledLocations: []tc.CacheGroupName{}} // important to initialize DisabledLocations, so JSON is `[]` not `null`
	if localDeliveryService.IsAvailable {
		deliveryService.IsAvailable = true
	}
	deliveryService.DisabledLocations = localDeliveryService.DisabledLocations

	for peerName, iPeerStates := range peerStates.GetCrstates() {
		peerDeliveryService, ok := iPeerStates.DeliveryService[deliveryServiceName]
		if !ok {
			log.Infof("local delivery service %s not found in peer %s\n", deliveryServiceName, peerName)
			continue
		}
		if peerDeliveryService.IsAvailable {
			deliveryService.IsAvailable = true
		}
		deliveryService.DisabledLocations = intersection(deliveryService.DisabledLocations, peerDeliveryService.DisabledLocations)
	}
	combinedStates.SetDeliveryService(deliveryServiceName, deliveryService)
}

// pruneCombinedCaches deletes caches in combined states which have been removed from localStates.
func pruneCombinedCaches(combinedStates peer.CRStatesThreadsafe, localStates tc.CRStates) {
	combinedCaches := combinedStates.GetCaches()
	for cacheName, _ := range combinedCaches {
		if _, ok := localStates.Caches[cacheName]; !ok {
			combinedStates.DeleteCache(cacheName)
		}
	}
}

func combineCrStates(events health.ThreadsafeEvents, peerOptimistic bool, peerStates peer.CRStatesPeersThreadsafe, localStates tc.CRStates, combinedStates peer.CRStatesThreadsafe, overrideMap map[tc.CacheName]bool, toData todata.TOData) {
	for cacheName, localCacheState := range localStates.Caches { // localStates gets pruned when servers are disabled, it's the source of truth
		combineCacheState(cacheName, localCacheState, events, peerOptimistic, peerStates, localStates, combinedStates, overrideMap, toData)
	}

	for deliveryServiceName, localDeliveryService := range localStates.DeliveryService {
		combineDSState(deliveryServiceName, localDeliveryService, events, peerOptimistic, peerStates, localStates, combinedStates, overrideMap, toData)
	}

	pruneCombinedCaches(combinedStates, localStates)
}

// CacheNameSlice is a slice of cache names, which fulfills the `sort.Interface` interface.
type CacheGroupNameSlice []tc.CacheGroupName

func (p CacheGroupNameSlice) Len() int           { return len(p) }
func (p CacheGroupNameSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p CacheGroupNameSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// intersection returns strings in both a and b.
// Note this modifies a and b. Specifically, it sorts them. If that isn't acceptable, pass copies of your real data.
func intersection(a []tc.CacheGroupName, b []tc.CacheGroupName) []tc.CacheGroupName {
	sort.Sort(CacheGroupNameSlice(a))
	sort.Sort(CacheGroupNameSlice(b))
	c := []tc.CacheGroupName{} // important to initialize, so JSON is `[]` not `null`
	for _, s := range a {
		i := sort.Search(len(b), func(i int) bool { return b[i] >= s })
		if i < len(b) && b[i] == s {
			c = append(c, s)
		}
	}
	return c
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This is a lightweight annotation-based dependency injection container for typescript.
 *
 * Visit the project page on [GitHub] (https://github.com/thiagobustamante/typescript-ioc).
 */

import 'reflect-metadata';
import { Config, ValueConfig, ObjectFactory, Scope, ContainerConfiguration, ConstantConfiguration, NamespaceConfiguration, Snapshot, BuildContext } from './model';
import { IoCContainer } from './container/container';
import { LocalScope, SingletonScope, RequestScope } from './scopes';

export { Config };
export { ValueConfig };
export { ObjectFactory };
export { BuildContext };
export { Scope };
export { ContainerConfiguration };
export { ConstantConfiguration };
export { Inject, Factory, Singleton, Scoped, OnlyInstantiableByContainer, InRequestScope, InjectValue } from './decorators';
export { Snapshot };

Scope.Local = new LocalScope();
Scope.Singleton = new SingletonScope();
Scope.Request = new RequestScope();

/**
 * The IoC Container class. Can be used to register and to retrieve your dependencies.
 * You can also use de decorators [[OnlyInstantiableByContainer]], [[Scoped]], [[Singleton]], [[Factory]]
 * to configure the dependency directly on the class.
 */
export class Container {

    /**
     * Add a dependency to the Container. If this type is already present, just return its associated
     * configuration object.
     * Example of usage:
     *
     * ```
     * Container.bind(PersonDAO).to(ProgrammerDAO).scope(Scope.Singleton);
     * ```
     * @param source The type that will be bound to the Container
     * @return a container configuration
     */
    public static bind(source: Function): Config {
        return IoCContainer.bind(source);
    }

    /**
     * Retrieve an object from the container. It will resolve all dependencies and apply any type replacement
     * before return the object.
     * If there is no declared dependency to the given source type, an implicity bind is performed to this type.
     * @param source The dependency type to resolve
     * @return an object resolved for the given source type;
     */
    public static get<T>(source: Function & { prototype: T }): T {
        return IoCContainer.get(source, new ContainerBuildContext());
    }

    /**
     * Retrieve a type associated with the type provided from the container
     * @param source The dependency type to resolve
     * @return an object resolved for the given source type;
     */
    public static getType(source: Function) {
        return IoCContainer.getType(source);
    }

    /**
     *
     * @param name
     */
    public static bindName(name: string): ValueConfig {
        return IoCContainer.bindName(name);
    }

    /**
     * Retrieve a constant from the container.
     * @param name The name of the constant used to identify these binding
     * @return the constant value
     */
    public static getValue(name: string) {
        return IoCContainer.getValue(name);
    }

    /**
     * Select the current namespace to work.
     * @param name The namespace name, or null to select the default namespace
     */
    public static namespace(name: string) {
        return IoCContainer.namespace(name);
    }

    /**
     * An alias to namespace method.
     * @param name The namespace name, or null to select the default namespace
     */
    public static environment(name: string) {
        return Container.namespace(name);
    }

    /**
     * Store the state for a specified binding.  Can then be restored later.   Useful for testing.
     * @param source The dependency type
     */
    // _args is here to ensure backward compatibility
    public static snapshot(_args?: any): Snapshot {
        return IoCContainer.snapshot();
    }

    /**
     * Import an array of configurations to the Container
     * @param configurations
     */
    public static configure(...configurations: Array<ContainerConfiguration | ConstantConfiguration | NamespaceConfiguration>) {
        configurations.forEach(config => {
            if ((config as ContainerConfiguration).bind) {
                Container.configureType(config as ContainerConfiguration);
            } else if ((config as ConstantConfiguration).bindName) {
                Container.configureConstant(config as ConstantConfiguration);
            } else if ((config as NamespaceConfiguration).env || (config as NamespaceConfiguration).namespace) {
                Container.configureNamespace(config as NamespaceConfiguration);
            }
        });
    }

    private static configureNamespace(config: NamespaceConfiguration) {
        const selectedNamespace = IoCContainer.selectedNamespace();
        const env = config.env || config.namespace;
        Object.keys(env).forEach(namespace => {
            Container.namespace(namespace);
            const namespaceConfig = env[namespace];
            Container.configure(...namespaceConfig);
        });

        Container.namespace(selectedNamespace);
    }

    private static configureConstant(config: ConstantConfiguration) {
        const bind = IoCContainer.bindName(config.bindName);
        if (bind) {
            if (config.to) {
                bind.to(config.to);
            }
        }
    }

    private static configureType(config: ContainerConfiguration) {
        const bind = IoCContainer.bind(config.bind);
        if (bind) {
            if (config.to) {
                bind.to(config.to);
            }
            else if (config.factory) {
                bind.factory(config.factory);
            }
            if (config.scope) {
                bind.scope(config.scope);
            }
            if (config.withParams) {
                bind.withParams(config.withParams);
            }
        }
    }
}

class ContainerBuildContext extends BuildContext {
    private context = new Map<Function, any>();

    public build<T>(source: Function & { prototype: T; }, factory: ObjectFactory): T {
        let instance = this.context.get(source);
        if (!instance) {
            instance = factory(this);
            this.context.set(source, instance);
        }
        return instance;
    }

    public resolve<T>(source: Function & { prototype: T }): T {
        return IoCContainer.get(source, this);
    }
}


text:
Alternative car/furniture sketch training data (svg): https://www.dropbox.com/s/5p52chxrjdfr6c2/car_furniture_sketch_baseline.csv?dl=0

Implementation multi-layer recurrent neural network (RNN, LSTM GRU) used to model and generate sketches stored in .svg vector graphic files.  The methodology used is to combine Mixture Density Networks with a RNN, along with modelling dynamic end-of-stroke and end-of-content probabilities learned from a large corpus of similar .svg files, to generate drawings that is simlar to the vector training data.

See my blog post at [blog.otoro.net](http://blog.otoro.net/2015/12/28/recurrent-net-dreams-up-fake-chinese-characters-in-vector-format-with-tensorflow/) for a detailed description on applying `sketch-rnn`  to learn to generate fake Chinese characters in vector format.

Example Training Sketches (20 randomly chosen out of 11000 [KanjiVG](http://kanjivg.tagaini.net/) dataset):

![Example Training Sketches](https://cdn.rawgit.com/hardmaru/sketch-rnn/master/example/training.svg)

Generated Sketches (Temperature = 0.1):

![Generated Sketches](https://cdn.rawgit.com/hardmaru/sketch-rnn/master/example/output.svg)

# Basic Usage

I tested the implementation on TensorFlow 0.50.  I also used the following libraries to help:

```
svgwrite
IPython.display.SVG
IPython.display.display
xml.etree.ElementTree
argparse
cPickle
svg.path
```

## Loading in Training Data

The training data is located inside the `data` subdirectory.  In this repo, I've included `kanji.cpkl` which is a preprocessed array of KanjiVG characters.

To add a new set of training data, for example, from the [TU Berlin Sketch Database](http://cybertron.cg.tu-berlin.de/eitz/projects/classifysketch/), you have to create a subdirectory, say `tuberlin` inside the `data` directory, and in addition create a directory of the same name in the `save` directory.  So you end up with `data/tuberlin/` and `save/tuberlin`, where `tuberlin` is defined as a name field for flags in the training and sample programs later on.  `save/tuberlin` will contain the check-pointed trained models later on.

Now, put a large collection of .svg files into `data/tuberlin/`.  You can even create subdirectories within `data/tuberlin/` and it will work, as the `SketchLoader` class will scan the entire subdirectory tree.

Currently, `sketch-rnn` only processes `path` elements inside svg files, and within the `path` elements, it only cares about lines and belzier curves at the moment.  I found this sufficient to handle TUBerlin and KanjiVG databases, although it wouldn't be difficult to extent to process the other curve elements, even shape elements in the future.

You can use `utils.py` to play out some random training data after the svg files have been copied in:

```
%run -i utils.py
loader = SketchLoader(data_filename = 'tuberlin')
draw_stroke_color(random.choice(loader.raw_data))
```

![Example Elephant from TU Berlin database](https://cdn.rawgit.com/hardmaru/sketch-rnn/master/example/elephant.svg)

For this algorithm to work, I recommend the data be similar in size, and similar in style / content.  For examples if we have bananas, buildings, elephants, rockets, insects of varying shapes and sizes, it would most likely just produce gibberish.

## Training the Model

After the data is loaded, let's continue with the 'tuberlin' example, you can run `python train.py --dataset_name tuberlin`

A number of flags can be set for training if you wish to experiment with the parameters.  You probably want to change these around, especially the scaling factors to better suit the sizes of your .svg data.

The default values are in `train.py`

```
--rnn_size RNN_SIZE             size of RNN hidden state (256)
--num_layers NUM_LAYERS         number of layers in the RNN (2)
--model MODEL                   rnn, gru, or lstm (lstm)
--batch_size BATCH_SIZE         minibatch size (100)
--seq_length SEQ_LENGTH         RNN sequence length (300)
--num_epochs NUM_EPOCHS         number of epochs (500)
--save_every SAVE_EVERY         save frequency (250)
--grad_clip GRAD_CLIP           clip gradients at this value (5.0)
--learning_rate LEARNING_RATE   learning rate (0.005)
--decay_rate DECAY_RATE         decay rate after each epoch (adam is used) (0.99)
--num_mixture NUM_MIXTURE       number of gaussian mixtures (24)
--data_scale DATA_SCALE         factor to scale raw data down by (15.0)
--keep_prob KEEP_PROB           dropout keep probability (0.8)
--stroke_importance_factor F    gradient boosting of sketch-finish event (200.0)
--dataset_name DATASET_NAME     name of directory containing training data (kanji)
```

## Sampling a Sketch

I've included a pretrained model in `/save` so it should work out of the box.  Running `python sample.py --filename output --num_picture 10 --dataset_name kanji` will generate an .svg file containing 10 fake Kanji characters using the pretrained model.  Please run `python sample.py --help` to examine extra flags, to see how to change things like number of sketches per row, etc.

It should be straight forward to examine `sample.py` to be able to generate sketches interactively using an IPython prompt rather than in the command line.  Running `%run -i sample.py` in an IPython interactive session would generate sketches shown in the IPython interface as well as generating an .svg output.

## More useful links, pointers, datasets

- Alex Graves' [paper](http://arxiv.org/abs/1308.0850) on text sequence and handwriting generation.

- Karpathy's [char-rnn](https://github.com/karpathy/char-rnn) tool, motivation for creating sketch-rnn.

- [KanjiVG](http://kanjivg.tagaini.net/).  Fantastic Database of Kanji Stroke Order.

- Very clean TensorFlow implementation of [char-rnn](https://github.com/sherjilozair/char-rnn-tensorflow), written by [Sherjil Ozair](https://github.com/sherjilozair), where I based the skeleton of this code off of.

- [svg.path](https://pypi.python.org/pypi/svg.path).  I used this well written tool to help convert path data into line data.

- CASIA Online and Offline Chinese [Handwriting Databases](http://www.nlpr.ia.ac.cn/databases/handwriting/Download.html).  Download stroke data for written cursive Simplifed Chinese.

- How Do Humans Sketch Objects?  [TU Berlin Sketch Database](http://cybertron.cg.tu-berlin.de/eitz/projects/classifysketch/).  Would be interesting to extend this work and generate random vector art of real life stuff.

- Doraemon in [SVG format](http://yylam.blogspot.hk/2012/04/doraemon-in-svg-format-doraemonsvg.html).

- [Potrace](https://en.wikipedia.org/wiki/Potrace).  Beautiful looking tool to convert raster bitmapped drawings into SVG for potentially scaling up resolution of drawings.  Could potentially apply this to generate large amounts of training data.

- [Rendering Belzier Curve Codes](http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic).  I used this very useful code to convert Belzier curves into line segments.

# License

MIT


text:
<?php

/**
 * namespace definition and usage
 */
namespace User\Authentication;

use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * User authentication service factory
 *
 * Generates the user authentication service object
 *
 * @package    User
 */
class ServiceFactory implements FactoryInterface
{
    /**
     * Create Service Factory
     *
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $authAdapter = $serviceLocator->get('User\Auth\Adapter');

        $auth = new AuthenticationService();
        $auth->setAdapter($authAdapter);
        return $auth;
    }
}


text:
Create a new thread, ask a question

        	<form action="<?php echo site_url('forum/new/createthread') ?>" method="POST">

                  Topic
                  <input type="text" name="topic" class="form-control">

                  Content
                  <textarea type="text" name="content" class="form-control"></textarea>

        		<button class="btn btn-primary" type="submit">Submit</button>
        	</form>


text:
layout: post
title: The End
categories: []
tags: [CS373 Summer 2015]
fullview: true
---

This past week was the final week of classes. Monday started off with a guest lecture from MutualMobile. Mobile App development is not my interest at heart, but I did take away a lot from his speech, regardless, such as contributing to open source and becoming an active member in learning all of the new technologies that are available for us.

Wednesday and Friday were the days of our presentations. I was particularly fond of the Star Wars database (link: http://intergalacticdb.me/). Their user interface made for a very pleasant experience, and the information was shown in a format that was not confusing.

Monday marks our Final Test, and last day of class. I'm quite unsure of what to study, since all Downing truly gives are bullet-points on what to look over, and that it will all be writing Python code. I think what my main focuses will be on are decorators, since I am unfamiliar with the functionality of them. My focuses will also be centered around writing SQL code in python and reviewing material from the previous Test. Since Test 1 focused on writing classes and unpacking/packing dictionaries in method parameters, reviewing for that test will really help solidify my confidence in writing Python code.

**Tip of the Week:**

Decorators are an amazing feature in Python that I have yet to see in other languages (so it is exciting for me to finally get my hands dirty writing code with them). I wrote the following example, amongst the other little scripts I'm writing in preporation. The function, pi, is declared and basically a function wrapper around the area function. The following is a way to calculate the area of a circle:

		def pi(f) :
		   def a(p) :
		       result = 3.14 * f(p)
		   return a

		@pi
		def area(r) :
		   result = r*r
		   return result

		area(2)

If you want further exploration into Decorators, check out this article: http://thecodeship.com/patterns/guide-to-python-function-decorators/


text:
import {stringValue} from 'vega-util';

export default function(obj, key, value) {
  return obj + '[' + stringValue(key) + ']=' + value + ';';
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/InfinitePager/InfinitePager.iml" filepath="$PROJECT_DIR$/InfinitePager/InfinitePager.iml" />
      <module fileurl="file://$PROJECT_DIR$/InfinitePager-demo/InfinitePager-demo.iml" filepath="$PROJECT_DIR$/InfinitePager-demo/InfinitePager-demo.iml" />
      <module fileurl="file://$PROJECT_DIR$/InfinitePager-project.iml" filepath="$PROJECT_DIR$/InfinitePager-project.iml" />
    </modules>
  </component>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.dbourdette</groupId>
    <artifactId>otto-auth-ldap</artifactId>
    <version>0.2.0</version>
    <name>otto-auth-ldap</name>
    <packaging>jar</packaging>
    <inceptionYear>2012</inceptionYear>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-archive</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
            <version>3.1.0.RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>


text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.core;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.TString;

/**
 * Computes the number of complete elements in the given barrier.
 */
@OpMetadata(
    opType = BarrierReadySize.OP_NAME,
    inputsClass = BarrierReadySize.Inputs.class
)
@Operator
public final class BarrierReadySize extends RawOp implements Operand<TInt32> {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "BarrierReadySize";

  private Output<TInt32> output;

  public BarrierReadySize(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    output = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new BarrierReadySize operation.
   *
   * @param scope current scope
   * @param handle The handle to a barrier.
   * @return a new instance of BarrierReadySize
   */
  @Endpoint(
      describeByClass = true
  )
  public static BarrierReadySize create(Scope scope, Operand<TString> handle) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "BarrierReadySize");
    opBuilder.addInput(handle.asOutput());
    return new BarrierReadySize(opBuilder.build());
  }

  /**
   * Gets output.
   * The number of complete elements (i.e. those with all of their value
   * components set) in the barrier.
   * @return output.
   */
  public Output<TInt32> output() {
    return output;
  }

  @Override
  public Output<TInt32> asOutput() {
    return output;
  }

  @OpInputsMetadata(
      outputsClass = BarrierReadySize.class
  )
  public static class Inputs extends RawOpInputs<BarrierReadySize> {
    /**
     * The handle to a barrier.
     */
    public final Operand<TString> handle;

    public Inputs(GraphOperation op) {
      super(new BarrierReadySize(op), op, Arrays.asList());
      int inputIndex = 0;
      handle = (Operand<TString>) op.input(inputIndex++);
    }
  }
}


text:
package org.chikoo.core.service.util;

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

import org.chikoo.core.model.entity.Blog;

public class BlogList {

	private List<Blog> blogs = new ArrayList<Blog>();

	public BlogList(List<Blog> listOfBlogs) {
		this.blogs = listOfBlogs;
	}

	public List<Blog> getBlogs() {
		return blogs;
	}

	public void setBlogs(List<Blog> blogs) {
		this.blogs = blogs;
	}
}


text:
namespace swift {

class WebView {

 ///////////////////////////////////////////////////////////////////////////////
 // ----------------------------------------------------------- public interface
 public:

  WebView(const std::string& url, int width, int height);
  virtual ~WebView();

  void SetDrawCallback(DrawCallback const& callback);
  void SetDrawCallback(DrawSettings const& settings, DrawCallback const& callback);

  template<typename ...Args>
  void CallJavascript(std::string const& function, Args&& ... a) const {
    std::vector<std::string> args = {(utils::to_string(a))...};
    CallJavascriptImpl(function, args);
  }

  void RegisterCallback(std::string const& name, std::function<void()> callback) {
    RegisterJSCallbackImpl(name, [this, callback](std::vector<Any> const& args) {
      callback();
    });
  }

  template<typename A>
  void RegisterCallback(std::string const& name, std::function<void(A)> callback) {
    RegisterJSCallbackImpl(name, [this, callback](std::vector<Any> const& args){
      callback(args[0].cast<A>());
    });
  }

  template<typename A, typename B>
  void RegisterCallback(std::string const& name, std::function<void(A, B)> callback) {
    RegisterJSCallbackImpl(name, [this, callback](std::vector<Any> const& args){
      callback(args[0].cast<A>(), args[1].cast<B>());
    });
  }

  template<typename A, typename B, typename C>
  void RegisterCallback(std::string const& name, std::function<void(A, B, C)> callback) {
    RegisterJSCallbackImpl(name, [this, callback](std::vector<Any> const& args){
      callback(args[0].cast<A>(), args[1].cast<B>(), args[2].cast<C>());
    });
  }

  template<typename A, typename B, typename C, typename D>
  void RegisterCallback(std::string const& name, std::function<void(A, B, C, D)> callback) {
    RegisterJSCallbackImpl(name, [this, callback](std::vector<Any> const& args){
      callback(args[0].cast<A>(), args[1].cast<B>(), args[2].cast<C>(), args[3].cast<D>());
    });
  }

  void Resize(int width, int height) const;
  void Reload(bool ignoreCache = false) const;

  void InjectMouseEvent(MouseEvent const& event);
  void InjectKeyEvent(KeyEvent const& event);

  void ToggleDevTools();
  void ShowDevTools();
  void CloseDevTools();

 ///////////////////////////////////////////////////////////////////////////////
 // ---------------------------------------------------------- private interface
 private:
  void CallJavascriptImpl(std::string const& function, std::vector<std::string> const& args) const;

  void RegisterJSCallbackImpl(std::string const& name, std::function<void(std::vector<Any> const&)> callback);

  detail::WebViewClient* client_;

  bool devToolsOpen_;

  // input state
  int mouse_x_;
  int mouse_y_;
  int mouse_modifiers_;
};

}

#endif // SWIFT_WEBVIEW_HPP


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Palaso.BuildTasks.UpdateBuildTypeFile
{
	public class UpdateBuildTypeFile : Task
	{
		public class VersionParts
		{
			public string[] parts = new string[4];

			public override string ToString()
			{
				return string.Format("{0}.{1}.{2}.{3}", parts[0], parts[1], parts[2], parts[3]);
			}
		}

		[Required]
		public ITaskItem[] InputAssemblyPaths { get; set; }

		[Required]
		public string Version { get; set; }

		public string FileVersion { get; set; }

		public override bool Execute()
		{
			foreach (var inputAssemblyPath in InputAssemblyPaths)
			{
				var path = inputAssemblyPath.ItemSpec;
				var contents = File.ReadAllText(path);

				SafeLog("StampAssemblies: Stamping {0}", inputAssemblyPath);
				//SafeLog("StampAssemblies: Contents: {0}",contents);

				File.WriteAllText(path,  GetModifiedContents(contents, Version, FileVersion));
			}
			return true;
		}

		public string GetModifiedContents(string contents, string incomingVersion, string incomingFileVersion)
		{
			var versionTemplateInFile = GetExistingAssemblyVersion(contents);
			var fileVersionTemplateInFile = GetExistingAssemblyFileVersion(contents);
			var versionTemplateInBuildScript = ParseVersionString(incomingVersion);
			VersionParts fileVersionTemplateInScript = null;
			fileVersionTemplateInScript = incomingFileVersion != null ? ParseVersionString(incomingFileVersion)
																	  : versionTemplateInBuildScript;

			var newVersion = MergeTemplates(versionTemplateInBuildScript, versionTemplateInFile);
			var newFileVersion = MergeTemplates(fileVersionTemplateInScript, fileVersionTemplateInFile);

			SafeLog("StampAssemblies: Merging existing {0} with incoming {1} to produce {2}.",
				versionTemplateInFile.ToString(), incomingVersion, newVersion);
			SafeLog("StampAssemblies: Merging existing {0} with incoming {1} to produce {2}.",
				fileVersionTemplateInFile.ToString(), incomingFileVersion, newFileVersion);

			var replacement = string.Format(
				"[assembly: AssemblyVersion(\"{0}\")]",
				newVersion);
			contents = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement);
			replacement = string.Format(
				"[assembly: AssemblyFileVersion(\"{0}\")]",
				newFileVersion);
			contents = Regex.Replace(contents, @"\[assembly: AssemblyFileVersion\("".*""\)\]", replacement);
			return contents;
		}

		private void SafeLog(string msg, params object[] args)
		{
			try
			{
				Debug.WriteLine(string.Format(msg,args));
				Log.LogMessage(msg,args);
			}
			catch (Exception)
			{
				//swallow... logging fails in the unit test environment, where the log isn't really set up
			}
		}

		public string MergeTemplates(VersionParts incoming, VersionParts existing)
		{
			string result = "";
			for (int i = 0; i < 4; i++)
			{
				//SafeLog("StampAssemblies: incoming[{0}]={1}", i, incoming.parts[i]);
				//SafeLog("StampAssemblies: existing[{0}]={1}", i, existing.parts[i]);
				if(incoming.parts[i] != "*")
				{
					result += incoming.parts[i] + ".";
				}
				else
				{
					if(existing.parts[i] == "*")
					{
						//SafeLog("StampAssemblies: existing.parts[i] == '*'");
						result += "0.";
					}
					else
					{
						result += existing.parts[i] + ".";
					}
				}
			}
			return result.TrimEnd(new char[] {'.'});
		}

		public VersionParts GetExistingAssemblyVersion(string contents)
		{
			try
			{
				var result = Regex.Match(contents, @"\[assembly\: AssemblyVersion\(""(.+)""");
				return ParseVersionString(result.Groups[1].Value);
			}
			catch (Exception e)
			{
				Log.LogError("Could not parse the AssemblyVersion attribute, which should be something like 0.7.*.* or 1.0.0.0");
				Log.LogErrorFromException(e);
				throw e;
			}
		}

		public VersionParts GetExistingAssemblyFileVersion(string contents)
		{
			try
			{
				var result = Regex.Match(contents, @"\[assembly\: AssemblyFileVersion\(""(.+)""");
				return ParseVersionString(result.Groups[1].Value);
			}
			catch (Exception e)
			{
				Log.LogError("Could not parse the AssemblyVersion attribute, which should be something like 0.7.*.* or 1.0.0.0");
				Log.LogErrorFromException(e);
				throw e;
			}
		}

		public VersionParts ParseVersionString(string contents)
		{
			var result = Regex.Match(contents, @"(.+)\.(.+)\.(.+)\.(.+)");
			if(!result.Success)
			{
				//handle 1.0.*  (I'm not good enough with regex to
				//overcome greediness and get a single pattern to work for both situations).
				result = Regex.Match(contents, @"(.+)\.(.+)\.(\*)");
			}
			if (!result.Success)
			{
				//handle 0.0.12
				result = Regex.Match(contents, @"(.+)\.(.+)\.(.+)");
			}
			var v = new VersionParts();
			v.parts[0] = result.Groups[1].Value;
			v.parts[1] = result.Groups[2].Value;
			v.parts[2] = result.Groups[3].Value;
			v.parts[3] = result.Groups[4].Value;

			for (int i = 0; i < 4; i++)
			{
				if(string.IsNullOrEmpty(v.parts[i]))
				{
					v.parts[i] = "*";
				}
			}
			//can't propogate a hash code, though it's nice (for build server display purposes)
			//to send it through to us. So for now, we just strip it out.
			if(v.parts[3].IndexOfAny(new char[]{'a','b','c','d','e','f'}) >-1)
			{
				v.parts[3] = "0";
			}

			return v;
		}
	}
}


text:
import { DIPage } from './app.po';

describe('di App', () => {
  let page: DIPage;

  beforeEach(() => {
    page = new DIPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
package cards;

import java.util.Set;
import java.util.stream.Collectors;

import server.Card;
import server.Game;
import server.Player;

public class Mint extends Card {

	@Override
	public String name() {
		return "Mint";
	}

	@Override
	public Set<Type> types() {
		return types(Type.ACTION);
	}

	@Override
	public int cost() {
		return 5;
	}

	@Override
	public String[] description() {
		return new String[] {"You may reveal a_Treasure card from your_hand. Gain a_copy of_it."};
	}

	@Override
	public void onPlay(Player player, Game game) {
		Set<Card> treasures = player.getHand().stream()
				.filter(Card::isTreasure)
				.collect(Collectors.toSet());
		if (!treasures.isEmpty()) {
			Card card = promptChooseGainCopyOfCardInHand(
					player,
					game,
					treasures,
					this.toString() + ": Choose a card to reveal from your hand and gain a copy of.",
					false
			);
			if (card != null) {
				if (game.supply.get(card) != 0) {
					game.messageAll("revealing " + card.htmlName() + " and gaining a copy of it");
					game.gain(player, card);
				} else {
					game.messageAll("revealing " + card.htmlName() + " and gaining nothing");
				}
			} else {
				game.messageAll("revealing nothing");
			}
		} else {
			game.message(player, "having no treasure in your hand");
			game.messageOpponents(player, "having no treasure in their hand");
		}
	}

}


text:
function [isLength isUnlimited] = The_dimensions(ncInfo,dim_name)

%initialisation
isLength=[];
isUnlimited=[];

found = 1;%=0 if dimension not found

%position in ncInfo (ncInfo = nc.getInfo; where nc is a mDataset object)
position = 1;
%check in ncInfo where is dim_name
dim_to_find = '';
while(~strcmp(dim_to_find,dim_name))
    dim_to_find=ncInfo(position:position+length(dim_name)-1);
    position=position+1;%next character
    if position ==(length(ncInfo)-length(dim_name))
        disp('dimension not found')
        found = 0;
    break
    end
end

%position is on the second character of dim_name

if (found == 1)%dimension exist
    position = position + length(dim_name) + 2; %position is now at the begining of its value (+2 for =' ')
    if (ncInfo(position) == 'U')%this dimension is unlimited
        isUnlimited = 'yes';
        position = position + 17;%17 characters for "UNLIMITED;   // (." where . is the first character of the dimension length
        isLength = '';
        number_in_isLength = 1;
        while (ncInfo(position)~=' ')%the dimension length is finish when we get the space character
            isLength(number_in_isLength) = ncInfo(position);%get all the numbers in isLength
            number_in_isLength = number_in_isLength +1;
            position = position + 1;
        end
        isLength = str2num(isLength);%convert to number
    else%not unlimited
        isUnlimited = 'no';
        isLength = '';
        number_in_isLength = 1;
        while (ncInfo(position)~=' ')%the dimension length is finish when we get the space character
            isLength(number_in_isLength) = ncInfo(position);%get all the numbers in isLength
            number_in_isLength = number_in_isLength +1;
            position = position + 1;
        end
        isLength = str2num(isLength);%convert to number
    end
end


text:
"""Tests for the Viper analysis plugin."""

import unittest

try:
  import mock  # pylint: disable=import-error
except ImportError:
  from unittest import mock

from dfvfs.path import fake_path_spec

from plaso.analysis import viper
from plaso.lib import definitions

from tests.analysis import test_lib

class MockResponse(dict):
  """A mock object to simulate a response object from the requests library."""

  # Note: that the following functions do not follow the style guide
  # because they are part of the requests response interface.
  # pylint: disable=invalid-name

  def json(self):
    """Provided for compatibility with the requests library."""
    return self

  def raise_for_status(self):
    """Provided for compatibility with the requests library."""
    return

class ViperTest(test_lib.AnalysisPluginTestCase):
  """Tests for the Viper analysis plugin."""

  _EVENT_1_HASH = (
      '2d79fcc6b02a2e183a0cb30e0e25d103f42badda9fbf86bbee06f93aa3855aff')

  _TEST_EVENTS = [{
      'data_type': 'pe:compilation:compilation_time',
      'path_spec': fake_path_spec.FakePathSpec(
          location='C:\\WINDOWS\\system32\\evil.exe'),
      'pe_type': 'Executable (EXE)',
      'sha256_hash': _EVENT_1_HASH,
      'timestamp': '2015-01-01 17:00:00',
      'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN}]

  # pylint: disable=unused-argument
  def _MockPost(self, url, data=None):
    """Mock function to simulate a Viper API request.

    Args:
      url (str): URL being requested.
      data (dict[str, object]): simulated form data for the Viper API request.

    Returns:
      MockResponse: mocked response that simulates a real response object
          returned by the requests library from the Viper API.
    """
    sha256_hash = data.get('sha256', None)
    if sha256_hash != self._EVENT_1_HASH:
      self.fail('Unexpected data in request.post().')

    response = MockResponse()
    response['default'] = ({
        'sha1': '13da502ab0d75daca5e5075c60e81bfe3b7a637f',
        'name': 'darkcomet.exe',
        'tags': [
            'rat',
            'darkcomet'],
        'sha512': '7e81e0c4f49f1884ebebdf6e53531e7836721c2ae417'
                  '29cf5bc0340f3369e7d37fe4168a7434b2b0420b299f5c'
                  '1d9a4f482f1bda8e66e40345757d97e5602b2d',
        'created_at': '2015-03-30 23:13:20.595238',
        'crc32': '2238B48E',
        'ssdeep': '12288:D9HFJ9rJxRX1uVVjoaWSoynxdO1FVBaOiRZTERfIhNk'
                  'NCCLo9Ek5C/hlg:NZ1xuVVjfFoynPaVBUR8f+kN10EB/g',
        'sha256': '2d79fcc6b02a2e183a0cb30e0e25d103f42badda9fbf86bbee06f9'
                  '3aa3855aff',
        'type': 'PE32 executable (GUI) Intel 80386, for MS Windows',
        'id': 10,
        'md5': '9f2520a3056543d49bb0f822d85ce5dd',
        'size': 774144},)

    return response

  def setUp(self):
    """Makes preparations before running an individual test."""
    self.requests_patcher = mock.patch('requests.post', self._MockPost)
    self.requests_patcher.start()

  def tearDown(self):
    """Cleans up after running an individual test."""
    self.requests_patcher.stop()

  def testExamineEventAndCompileReport(self):
    """Tests the ExamineEvent and CompileReport functions."""
    plugin = viper.ViperAnalysisPlugin()
    plugin.SetHost('localhost')
    plugin.SetPort(8080)
    plugin.SetProtocol('http')

    storage_writer = self._AnalyzeEvents(self._TEST_EVENTS, plugin)

    self.assertEqual(len(storage_writer.analysis_reports), 1)
    self.assertEqual(storage_writer.number_of_event_tags, 1)

    report = storage_writer.analysis_reports[0]
    self.assertIsNotNone(report)

    expected_text = (
        'viper hash tagging results\n'
        '1 path specifications tagged with label: viper_present\n'
        '1 path specifications tagged with label: viper_project_default\n'
        '1 path specifications tagged with label: viper_tag_darkcomet\n'
        '1 path specifications tagged with label: viper_tag_rat\n')

    self.assertEqual(report.text, expected_text)

    labels = []
    for event_tag in storage_writer.GetEventTags():
      labels.extend(event_tag.labels)
    self.assertEqual(len(labels), 4)

    expected_labels = [
        'viper_present', 'viper_project_default', 'viper_tag_darkcomet',
        'viper_tag_rat']
    self.assertEqual(sorted(labels), expected_labels)

if __name__ == '__main__':
  unittest.main()


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
	<entry>
		<title type="text/html" mode="escaped">
Entry Title
</title>
	</entry>
</feed>


text:
import logging

from lcm.pub.database.models import VNFFGInstModel, FPInstModel
from lcm.pub.exceptions import NSLCMException
from lcm.pub.utils.share_lock import do_biz_with_share_lock

logger = logging.getLogger(__name__)

class SfcInstance(object):
    def __init__(self, data):
        self.ns_inst_id = data["nsinstid"]
        self.ns_model_data = data["ns_model_data"]
        self.fp_id = data["fpindex"]
        self.fp_inst_id = data["fpinstid"]
        self.sdnControllerId = data["sdncontrollerid"]

    def do_biz(self):
        self.init_data()
        return self.save()

    def init_data(self):
        self.fp_model = self.get_fp_model_by_fp_id()
        logger.info("fp_model.properties:%s, fp_id:%s" % (self.fp_model["properties"], self.fp_id))
        if not self.fp_model:
            return
        logger.info("sfc_inst_symmetric %s" % self.fp_model["properties"].get("symmetric"))
        self.symmetric = self.fp_model["properties"].get("symmetric")
        logger.info("sfc_inst_symmetric %s" % self.symmetric)
        self.policyinfo = self.fp_model["properties"].get("policy")
        self.status = "processing"
        vnffg_database_info = VNFFGInstModel.objects.filter(vnffgdid=self.get_vnffgdid_by_fp_id(),
                                                            nsinstid=self.ns_inst_id).get()
        self.vnffg_inst_id = vnffg_database_info.vnffginstid

    def get_fp_model_by_fp_id(self):
        fps_model = self.ns_model_data["fps"]
        for fp_model in fps_model:
            if fp_model["fp_id"] == self.fp_id:
                return fp_model
        return None

    def get_vnffgdid_by_fp_id(self):
        vnffgs_model = self.ns_model_data["vnffgs"]
        for vnffg_model in vnffgs_model:
            fp_ids = vnffg_model["members"]
            for fp_id in fp_ids:
                if fp_id == self.fp_id:
                    return vnffg_model["vnffg_id"]

    def save(self):
        try:
            logger.info("Sfc Instanciate save2db start : ")
            FPInstModel(fpid=self.fp_id,
                        fpinstid=self.fp_inst_id,
                        nsinstid=self.ns_inst_id,
                        vnffginstid=self.vnffg_inst_id,
                        symmetric=1 if self.symmetric else 0,
                        policyinfo=self.policyinfo,
                        status=self.status,
                        sdncontrollerid=self.sdnControllerId
                        ).save()

            do_biz_with_share_lock("update-sfclist-in-vnffg-%s" % self.ns_inst_id, self.update_vnfffg_info)
            logger.info("Sfc Instanciate save2db end : ")

        except:
            logger.error('SFC instantiation failed')
            raise NSLCMException('SFC instantiation failed.')
        return {
            "fpinstid": self.fp_inst_id
        }

    def update_vnfffg_info(self):
        vnffg_database_info = VNFFGInstModel.objects.filter(vnffginstid=self.vnffg_inst_id).get()
        fp_inst_list = vnffg_database_info.fplist
        fp_inst_list = fp_inst_list + ',' + self.fp_inst_id if fp_inst_list else self.fp_inst_id
        VNFFGInstModel.objects.filter(vnffginstid=self.vnffg_inst_id).update(fplist=fp_inst_list)


text:
layout: default
title: Changes between ROS 1 and ROS 2
permalink: articles/changes.html
abstract:
  This article provides an overview about the changes being made in ROS 2 compared to ROS 1.
published: true
author: '[Dirk Thomas](https://github.com/dirk-thomas)'
date_written: 2015-09
last_modified: 2017-06
categories: Overview
---

{:toc}

# {{ page.title }}

{{ page.abstract }}

Authors: {{ page.author }}

Date Written: {{ page.date_written }}

Last Modified: {% if page.last_modified %}{{ page.last_modified }}{% else %}{{ page.date_written }}{% endif %}

## Preface

Each change is described as briefly as possible but giving enough context and rationale for a reader familiar with ROS 1.
If further external information is available (e.g. other articles) it should be linked to.

  Some of the described features are not yet available and are marked with ⏳.

## Platforms and dependencies

### Platforms

ROS 1 is only being CI tested on Ubuntu.
It is actively supported by the community on other Linux flavors as well as OS X.

ROS 2 is currently being CI tested and supported on Ubuntu Xenial, OS X El Capitan as well as Windows 10 (see [ci.ros2.org](http://ci.ros2.org/)).

### Languages

#### C++ standard

The core of ROS 1 is targeting C++03 and doesn't make use of C++11 features in its API.
ROS 2 uses C++11 extensively and uses some parts from C++14.
In the future ROS 2 might start using C++17 as long as it is supported on all major platforms.

#### Python

ROS 1 is targeting Python 2.
ROS 2 requires at least Python version 3.5.

### Reusing existing middleware

ROS 1 uses a custom serialization format, a custom transport protocol as well as a custom central discovery mechanism.
ROS 2 has an [abstract middleware interface](http://design.ros2.org/articles/ros_middleware_interface.html), through which serialization, transport, and discovery is being provided.
Currently all implementations of this interface are based on the DDS standard.
This enables ROS 2 to provide various [Quality of Service policies](http://design.ros2.org/articles/qos.html) which improve communication over different networks.

## Build system

For more information about the build system please see the [ament](http://design.ros2.org/articles/ament.html) article.

### Support other build systems beside CMake

Every ROS package is a CMake project.
In ROS 2 other build systems can be easily supported.
For now the build tool supports plain Python packages beside CMake.

### Python packages

In ROS 1 a package with Python code can only use a small subset of the features available in setup.py files since the setup.py file is being processed by custom logic from within CMake.
In ROS 2 a Python package can use anything in setup.py files, e.g. entry points since they are being invoked with `python3 setup.py install`.

### Environment setup

In ROS 1 the build tool generates scripts which must be sourced in order to setup the environment before being able to use the built ROS packages.
This approach only works when the ROS packages are being built with ROS specific build tool.

In ROS 2 the environment setup is separated into package-specific scripts and workspace-specific scripts.
Each package provides the necessary scripts to make itself usable after being built.
The build tool only invokes the workspace-specific scripts which then call the package-specific scripts.

### No non-isolated build

In ROS 1 multiple packages can be built in a single CMake context.
While this speeds up the build step, every package needs to ensure that cross package target dependencies are defined correctly.
Additionally all packages share the same namespace which leads to colliding target names, etc.

In ROS 2 only isolated builds are supported, i.e. every package is built separately on its own.
The install spaces can be either isolated or merged.

### No devel space

In ROS 1 packages can be built without installing them.
From the devel space in combination with the source space the system is already usable.
But every package has to actively support the devel space, e.g. in environment hooks and CMake code.

In ROS 2 a package must be installed after building it before it can be used.

One reason for the devel space in ROS 1 is to enable the developer to change files, e.g. Python code or launch files, and use the modified code directly without the need to rebuild the package.
This benefit is preserved in ROS 2 by optionally replacing copy operations in the install steps with symlinks.

### Support catkin_simple use case

In ROS 1 the package catkin_simple is aiming to make writing the CMake code of ROS packages easier.
In many cases it is not achieving this goal which is often due to restrictions of the design necessary for support features like the devel space.

In ROS 2 the CMake API was restructured to support this use case.

### Minimal support for packages without manifest

In ROS 1 only packages with a manifest file are considered by the build system.
In ROS 2 it is possible to detect packages with supported build system in folders without a manifest file.
If the package follows common practice it might even be possible to detect some of the missing meta information (like dependencies).

## Messages, Services

For more information please see the [ROS interface definition](http://design.ros2.org/articles/interface_definition.html) article.

### Separated namespaces in C++

In ROS 1 .msg and .srv files can have the same name but the generated code collides.
The same is the case for the request and response parts of services.

In ROS 2 the generated code uses separate namespaces to guarantee it is collision-free.

### Same names in Python

The generated Python code for messages and service is currently using the same module and class names in ROS 1 and ROS 2.
Therefore they can not be imported both in a single application.
This decision might be revisited if required.

### Optional default values in message definitions

In ROS 2 primitive values in messages can now have default values, set when the message is constructed.
Default values for non-primitive fields, i.e. array of strings, nested messages, are not yet possible (⏳).

### Optional upper bounds for arrays and strings

This is necessary in order to calculate the maximum size of a message in memory, which allows for preallocation of messages with a dynamic sizes.
This is useful for performance and for use cases like real-time.

### Unify duration and time types

In ROS 1 the duration and time types are defined in the client libraries.
The member names of the data structures are different in C++ (sec, nsec) and Python (secs, nsecs).

In ROS 2 these types are defined as messages and therefore are consistent across languages.

### Remove sequence field from Header message

The field has been deprecated for a long time and was not set consistently in ROS 1.

## Client libraries

### Across languages

#### Topic namespaces (⏳)

Currently ROS 2 does not support namespaces in topic names.
This is mostly due to restrictions of valid characters in DDS topic names.
A [design document](http://design.ros2.org/articles/topic_and_service_names.html) describes how this should be added in the future.

#### Notifications

In ROS 1 all information about the ROS graph must be polled from the master.
In ROS 2 changes will be published instead, e.g. notifications if a parameter has been changed.

#### Components with life cycle

In ROS 1 every node usually has its own main function.
In ROS 2 it is recommended to subclass from a component which has a life cycle.

The life cycle can be used by tools like roslaunch to start a system composed of many components in a deterministic way (⏳).

For more information please see the [node life cycle](http://design.ros2.org/articles/node_lifecycle.html) article.

#### Parameters and Dynamic Reconfigure

In ROS 1 global parameters and node-specific dynamic reconfigure parameters are two separate concepts.
In ROS 2 a unified approach is being used.
It is similar to dynamic reconfigure and a node named "global parameter server" (⏳) will accept requests to set values unconditionally.
In ROS 1 all this information needs to be polled for changes in ROS 2 changes will be published to notify other entities.

For more information please see the [parameter design](http://design.ros2.org/articles/ros_parameters.html) article.

#### Actions (⏳)

ROS 2 currently doesn't have the concept of actions.
It will be added in the future as a combination of a preemptable server and a feedback publisher.

#### Threading model

In ROS 1 the developer can only choose between single-threaded execution or multi-threaded execution.
In ROS 2 more granular execution models are available in C++ (e.g. across multiple nodes) and custom executors can be implemented easily.
For Python the execution models haven't been implemented yet.

#### ROS Graph

In ROS 1 nodes and topics can be remapped at startup time only.
In ROS 2 support for remapping hasn't been implemented yet (⏳).
The goal is to enable remapping as well as aliasing not only during startup time but also during runtime.

In ROS 1 node names are unique and this is being enforced by shutting down existing nodes when a new node with the same name is started.
In ROS 2 the uniqueness of node names is not yet enforced.

### C and C++

#### Support for real-time

ROS 1 does not support writing real-time code but relies on external frameworks like Orocos.
In ROS 2 it will be possible to write real-time nodes when using a proper RTOS and with carefully written user code.

### C++

#### Node vs. Nodelet

In ROS 1 the API's for nodes and nodelets are different and requires the developer to decide the mapping of nodes to processes at programming time.
In ROS 2 it is recommended to compile each component into a shared library which can then be loaded in a separate process or share the same process with other components (like ROS 1 nodelets).
This enables to choose the process layout at deploy-time.

#### Allow multiple nodes per process

In ROS 1 it is not possible to create more than one node in a process.
This is due to the API itself but also because of internal implementation decisions.
In ROS 2 it it possible to create multiple nodes in a process.

## Tools

### roslaunch (⏳)

In ROS 1 roslaunch files are defined in XML with very limited capabilities.
In ROS 2 launch file are written in Python which enables to use more complex logic like conditionals etc.
The current state only provides minimal functionality to run tests using multiple processes.

## Resource lookup

In ROS 1 various resources (packages, messages, plugins, etc.) are looked up by crawling the file system based on the ROS_PACKAGE_PATH.
This can cause poor performance when the trees in the ROS_PACKAGE_PATH are large, and caching produces inconsistent state.

In ROS 2 resources can be registered at an index at compile time and then be queried efficiently at runtime.
For more information please see the documentation of the [resource index](https://github.com/ament/ament_cmake/blob/master/ament_cmake_core/doc/resource_index.md).

## Packaging

### ABI versioning (⏳)

ROS 1 rebuilds all downstream packages since it assumes ABI incompatibility.
To avoid this significant overhead a ROS 2 package should be able to declare its ABI to avoid rebuilding downstream packages whenever possible.

### Binary packages for Windows (⏳)

ROS 1 can only be built from source on Windows (which also only works for a few ROS packages and is not supported).
ROS 2 will provide binary package based on Chocolatey.


text:
"""Module defining the Sqlite3Connector class."""

import os

from model.types import *

SQLITE_TYPES = {
    Integer: "integer",
    String: "text",
}

driver = True

try:
    import sqlite3
except ImportError:
    driver = False

from dc.connector import DataConnector
from dc import exceptions
from model import exceptions as mod_exceptions
from model.functions import *

class Sqlite3Connector(DataConnector):

    """Data connector for sqlite3.

    This data connector should read and write datas using the sqlite3
    module (part of the python standard library).

    """

    name = "sqlite3"
    def __init__(self):
        """Check the driver presence.

        If not found, raise a DriverNotFound exception.

        """
        if not driver:
            raise exceptions.DriverNotFound(
                    "the sqlite3 library can not be found")

        self.location = None
        self.created_tables = ()

    def setup(self, location=None):
        """Setup the data connector."""
        if location is None:
            raise exceptions.InsufficientConfiguration(
                    "the location for storing datas was not specified for " \
                    "the sqlite3 data connector")

        location = location.replace("\\", "/")
        if location.startswith("~"):
            location = os.path.expanduser("~") + location[1:]

        location_dir = os.path.split(location)[0]
        if location_dir and not os.path.exists(location_dir):
            # Try to create it
            os.makedirs(location_dir)

        DataConnector.__init__(self)
        self.location = location
        self.connection = sqlite3.connect(self.location)

    def close(self):
        """Close the data connector."""
        self.connection.close()

    def destroy(self):
        """Erase EVERY stored data."""
        self.clear_cache()
        self.connection.close()
        os.remove(self.location)

    def record_models(self, models):
        """Record the tables."""
        cursor = self.connection.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = [row[0] for row in cursor.fetchall()]
        self.created_tables = tuple(tables)
        DataConnector.record_models(self, models)
        self.connection.commit()

    def record_model(self, model):
        """Record a single model."""
        DataConnector.record_model(self, model)
        name = get_plural_name(model)
        if name not in self.created_tables:
            self.create_table(name, model)

    def create_table(self, name, model):
        """Create the sqlite table related to the specified model."""
        fields = get_fields(model)
        sql_fields = []
        for field in fields:
            sql_field = SQLITE_TYPES[type(field)]
            instruction = field.field_name + " " + sql_field
            if field.pkey:
                instruction += " PRIMARY KEY"
            if field.auto_increment:
                instruction += " AUTOINCREMENT"
            sql_fields.append(instruction)

        query = "CREATE TABLE {} ({})".format(name, ", ".join(sql_fields))

        cursor = self.connection.cursor()
        cursor.execute(query)

    def loop(self):
        """Commit the database."""
        self.connection.commit()

    def get_all_objects(self, model):
        """Return all the model's objects in a list."""
        name = get_name(model)
        plural_name = get_plural_name(model)
        fields = get_fields(model)
        objects = []
        query = "SELECT * FROM " + plural_name
        cursor = self.connection.cursor()
        cursor.execute(query)
        for row in cursor.fetchall():
            dict_fields = {}
            for i, field in enumerate(fields):
                dict_fields[field.field_name] = row[i]

            object = self.get_from_cache(model, dict_fields)
            if object is None:
                object = model.build(**dict_fields)
                self.cache_object(object)
            objects.append(object)

        return objects

    def find_object(self, model, pkey_values):
        """Return, if found, the specified object."""
        # First, look for the object in the cached tree
        pkey_values_list = list(pkey_values.values())
        object = self.get_from_cache(model, pkey_values)
        if object:
            return object

        query = "SELECT * FROM {} WHERE ".format(get_plural_name(model))
        params = []
        filters = []
        for name, value in pkey_values.items():
            filters.append("{}=?".format(name))
            params.append(value)

        query += " AND ".join(filters)
        cursor = self.connection.cursor()
        cursor.execute(query, tuple(params))
        row = cursor.fetchone()
        if row is None:
            raise mod_exceptions.ObjectNotFound(model, pkey_values)

        dict_fields = {}
        for i, field in enumerate(get_fields(model)):
            dict_fields[field.field_name] = row[i]

        object = model.build(**dict_fields)
        self.cache_object(object)
        return object

    def add_object(self, object):
        """Save the object, issued from a model."""
        name = get_name(type(object))
        fields = get_fields(type(object))
        plural_name = get_plural_name(type(object))
        query = "INSERT INTO " + plural_name + " ("
        names = []
        values = []
        auto_increments = []
        for field in fields:
            if field.auto_increment:
                auto_increments.append(field.field_name)
                continue

            names.append(field.field_name)
            values.append(getattr(object, field.field_name))

        query += ", ".join(names) + ") values("
        query += ", ".join("?" * len(values)) + ")"
        cursor = self.connection.cursor()
        cursor.execute(query, tuple(values))

        for field in auto_increments:
            query = "SELECT max(" + field + ") FROM " + plural_name
            cursor.execute(query)
            row = cursor.fetchone()
            value = row[0]
            update_attr(object, field, value)

        self.cache_object(object)

    def update_object(self, object, attribute):
        """Update an object."""
        self.check_update(object)
        plural_name = get_plural_name(type(object))
        keys = get_pkey_names(type(object))
        params = [getattr(object, attribute)] + list(get_pkey_values(object))
        names = [name + "=?" for name in keys]
        query = "UPDATE " + plural_name + " SET " + attribute + "=?"
        query += " WHERE " + " AND ".join(names)
        cursor = self.connection.cursor()
        cursor.execute(query, tuple(params))

    def remove_object(self, object):
        """Delete the object."""
        name = get_name(type(object))
        plural_name = get_plural_name(type(object))
        keys = get_pkey_names(type(object))
        names = [name + "=?" for name in keys]
        values = tuple(get_pkey_values(object))
        query = "DELETE FROM " + plural_name
        query += " WHERE " + " AND ".join(names)
        cursor = self.connection.cursor()
        cursor.execute(query, values)

        # Delete from cache
        self.uncache_object(object)


text:
package cdb.view;

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

import cdb.controller.servlet.fields.AllFields;

/**
 * List of data represented as a page in order to be displayed.
 * @author aserre
 * @param <T> generic type
 */
public class Page<T> implements AllFields {
    private static final int DEFAULT_BORDER_SIZE = 4;

    private List<T> data;
    private int limit;
    private int totalPage;
    private int pageNb;
    private int paginationBorders;
    private int totalCount;
    private String col;
    private String order;
    private String search;

    /**
     * Constructor.
     * @param data data representing a page of a request
     * @param pageNb the current page
     * @param totalCount total size of a request
     * @param col column to order by
     * @param order "ASC" or "DESC"
     * @param limit number of entries per page
     */
    public Page(List<T> data, int pageNb, int limit, int totalCount, String col, String order) {
        this.data = new ArrayList<T>(data);
        this.limit = limit;
        this.pageNb = pageNb;
        this.totalCount = totalCount;
        this.col = col;
        this.order = order;
        this.totalPage = 1 + totalCount / this.limit;
        this.paginationBorders = DEFAULT_BORDER_SIZE;
    }

    /**
     * Configure the input stream to invert the sorting order.
     * <p>
     * If the input is different from the stored column, return the input.
     * Otherwise, return the inversion of the stored value.
     * @param col New column to sort by
     * @return the exact value format for the sort
     */
    public String getNewOrder(String col) {
        if (this.col.equals(col)) {
            if (this.order.equals("ASC")) {
                return "DESC";
            } else {
                return "ASC";
            }
        } else {
            return "ASC";
        }
    }

    public List<T> getData() {
        return this.data;
    }

    public int getTotalPage() {
        return this.totalPage;
    }

    public int getPageNb() {
        return this.pageNb;
    }

    /**
     * Sets {@link Page#pageNb} to a specific value. Checks for overflow
     * and underflow.
     * @param nb index of the new page
     * @return current page number, after affectation.
     */
    public int setPageNb(int nb) {
        if (nb > 0 && nb <= this.totalPage) {
            this.pageNb = nb;
        }
        return this.pageNb;
    }

    public int getTotalCount() {
        return this.totalCount;
    }

    public int getLimit() {
        return this.limit;
    }

    /**
     * Sets the maximum number of item per page, and consequently updates the value
     * of {@link Page#totalPage} and {@link Page#pageNb}.
     * @param i new maximum number of item per page
     */
    public void setLimit(int i) {
        this.limit = i;
        this.totalPage = 1 + this.totalCount / this.limit;
        this.pageNb = Math.min(this.pageNb, this.totalPage);
    }

    public int getPaginationBorders() {
        return this.paginationBorders;
    }

    public void setPaginationBorders(int paginationBorders) {
        this.paginationBorders = paginationBorders;
    }

    public String getSearch() {
        return this.search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    public String getCol() {
        return this.col;
    }

    public void setCol(String col) {
        this.col = col;
    }

    public String getOrder() {
        return this.order;
    }

    public void setOrder(String order) {
        this.order = order;
    }
}


text:
package org.kie.workbench.common.services.backend.builder.ala;

import org.guvnor.ala.source.Source;
import org.uberfire.java.nio.file.Path;

/**
 * Internal representation of the sources in the local build system.
 */
public class LocalSource implements Source {

    private Path path;

    public LocalSource( Path path ) {
        this.path = path;
    }

    /**
     * @return the path where the sources are located.
     */
    @Override
    public Path getPath( ) {
        return path;
    }
}


text:
@interface ActivityEnrollViewController : MainBaseViewController

@end


text:
<?php

namespace Cs278\BankModulus\ModulusAlgorithm;

final class Mod11 extends BaseAlgorithm
{
    /**
     * @param string $input
     * @param int[]  $weights
     */
    public function __construct($input, array $weights)
    {
        $result = array_sum($this->applyWeights($input, $weights));
        \assert(\is_int($result));

        parent::__construct(
            $result,
            11
        );
    }
}


text:
  <title>Leaderboard</title>

    {{> leaderboard}}

<template name="leaderboard">

    {{#each players}}
      {{> player}}
    {{/each}}

  {{#if selected_name}}

{{selected_name}}

    <input type="button" class="inc" value="Give 5 points" />

  {{/if}}

  {{#unless selected_name}}

Click a player to select

  {{/unless}}
</template>

<template name="player">

    {{name}}
    {{score}}

</template>


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

  <copyright>
    <year>2020</year><year>2021</year>
    <holder>wxWidgets team.</holder></copyright>
  <legalnotice>Licensed under the wxWindows Free Documentation Licence, Version 3
  </legalnotice>
  <title>wxMDIParentFrame</title>

<module>wxMDIParentFrame</module>
<modulesummary>Functions for wxMDIParentFrame class</modulesummary>
<description>
An MDI (Multiple Document Interface) parent frame is a window which can contain MDI child frames in its client area which emulates the full desktop.

MDI is a user-interface model in which all the window reside inside the single parent window as opposed to being separate from each other. It remains popular despite dire warnings from Microsoft itself (which popularized this model in the first model) that MDI is obsolete.

An MDI parent frame always has a <seeerl marker="wxMDIClientWindow"><c>wxMDIClientWindow</c></seeerl> associated with it, which is the parent for MDI child frames. In the simplest case, the client window takes up the entire parent frame area but it is also possible to resize it to be smaller in order to have other windows in the frame, a typical example is using a sidebar along one of the window edges.

The appearance of MDI applications differs between different ports. The classic MDI model, with child windows which can be independently moved, resized etc, is only available under MSW, which provides native support for it. In Mac ports, multiple top level windows are used for the MDI children too and the MDI parent frame itself is invisible, to accommodate the native look and feel requirements. In all the other ports, a tab-based MDI implementation (sometimes called TDI) is used and so at most one MDI child is visible at any moment (child frames are always maximized).

 Although it is possible to have multiple MDI parent frames, a typical MDI application has a single MDI parent frame window inside which multiple MDI child frames, i.e. objects of class <seeerl marker="wxMDIChildFrame"><c>wxMDIChildFrame</c></seeerl>, can be created.

Styles

This class supports the following styles:

There are no special styles for this class, all <seeerl marker="wxFrame"><c>wxFrame</c></seeerl> styles apply to it in the usual way. The only exception is that wxHSCROLL and wxVSCROLL styles apply not to the frame itself but to the client window, so that using them enables horizontal and vertical scrollbars for this window and not the frame.

See: <seeerl marker="wxMDIChildFrame"><c>wxMDIChildFrame</c></seeerl>, <seeerl marker="wxMDIClientWindow"><c>wxMDIClientWindow</c></seeerl>, <seeerl marker="wxFrame"><c>wxFrame</c></seeerl>, <seeerl marker="wxDialog"><c>wxDialog</c></seeerl>

This class is derived (and can use functions) from:
    <seeerl marker="wxFrame"><c>wxFrame</c></seeerl> <seeerl marker="wxTopLevelWindow"><c>wxTopLevelWindow</c></seeerl> <seeerl marker="wxWindow"><c>wxWindow</c></seeerl> <seeerl marker="wxEvtHandler"><c>wxEvtHandler</c></seeerl>

wxWidgets docs: <url href="https://docs.wxwidgets.org/3.1/classwx_m_d_i_parent_frame.html">wxMDIParentFrame</url>

  </description>
<datatypes><datatype><name name="wxMDIParentFrame"/></datatype></datatypes>

<funcs>
  <func>
    <name name="new" arity="0" clause_i="1" since=""/>
    <fsummary>Default constructor. </fsummary>
    <desc>
Default constructor.

Use <seemfa marker="#create/5"><c>create/5</c></seemfa> for the objects created using this constructor.

</desc>
  </func>

  <func>
    <name name="new" arity="3" clause_i="1" since=""/>
    <fsummary>See: <c>new/4</c></fsummary>
  </func>

  <func>
    <name name="new" arity="4" clause_i="1" since=""/>
    <fsummary>Constructor, creating the window. </fsummary>
    <desc>
Constructor, creating the window.

Notice that if you override virtual <c>OnCreateClient()</c> (not implemented in wx) method you shouldn't be using this constructor but the default constructor and <seemfa marker="#create/5"><c>create/5</c></seemfa> as otherwise your overridden method is never going to be called because of the usual C++ virtual call resolution rules.

 Under wxMSW, the client window will automatically have a sunken border style when the active child is not maximized, and no border style when a child is maximized.

See: <seemfa marker="#create/5"><c>create/5</c></seemfa>, <c>OnCreateClient()</c> (not implemented in wx)

</desc>
  </func>

  <func>
    <name name="destroy" arity="1" clause_i="1" since=""/>
    <fsummary>Destructor. </fsummary>
    <desc>
Destructor.

Destroys all child windows and menu bar if present.

</desc>
  </func>

  <func>
    <name name="activateNext" arity="1" clause_i="1" since=""/>
    <fsummary>Activates the MDI child following the currently active one. </fsummary>
    <desc>
Activates the MDI child following the currently active one.

The MDI children are maintained in an ordered list and this function switches to the next element in this list, wrapping around the end of it if the currently active child is the last one.

See: <seemfa marker="#activatePrevious/1"><c>activatePrevious/1</c></seemfa>

</desc>
  </func>

  <func>
    <name name="activatePrevious" arity="1" clause_i="1" since=""/>
    <fsummary>Activates the MDI child preceding the currently active one. </fsummary>
    <desc>
Activates the MDI child preceding the currently active one.

See: <seemfa marker="#activateNext/1"><c>activateNext/1</c></seemfa>

</desc>
  </func>

  <func>
    <name name="arrangeIcons" arity="1" clause_i="1" since=""/>
    <fsummary>Arranges any iconized (minimized) MDI child windows. </fsummary>
    <desc>
Arranges any iconized (minimized) MDI child windows.

This method is only implemented in MSW MDI implementation and does nothing under the other platforms.

See: <seemfa marker="#cascade/1"><c>cascade/1</c></seemfa>, <seemfa marker="#tile/2"><c>tile/2</c></seemfa>

</desc>
  </func>

  <func>
    <name name="cascade" arity="1" clause_i="1" since=""/>
    <fsummary>Arranges the MDI child windows in a cascade. </fsummary>
    <desc>
Arranges the MDI child windows in a cascade.

This method is only implemented in MSW MDI implementation and does nothing under the other platforms.

See: <seemfa marker="#tile/2"><c>tile/2</c></seemfa>, <seemfa marker="#arrangeIcons/1"><c>arrangeIcons/1</c></seemfa>

</desc>
  </func>

  <func>
    <name name="create" arity="4" clause_i="1" since=""/>
    <fsummary>See: <c>create/5</c></fsummary>
  </func>

  <func>
    <name name="create" arity="5" clause_i="1" since=""/>
    <fsummary>Used in two-step frame construction. </fsummary>
    <desc>
Used in two-step frame construction.

See <seemfa marker="#new/4"><c>new/4</c></seemfa> for further details.

</desc>
  </func>

  <func>
    <name name="getActiveChild" arity="1" clause_i="1" since=""/>
    <fsummary>Returns a pointer to the active MDI child, if there is one. </fsummary>
    <desc>
Returns a pointer to the active MDI child, if there is one.

If there are any children at all this function returns a non-NULL pointer.

</desc>
  </func>

  <func>
    <name name="getClientWindow" arity="1" clause_i="1" since=""/>
    <fsummary>Returns a pointer to the client window. </fsummary>
    <desc>
Returns a pointer to the client window.

See: <c>OnCreateClient()</c> (not implemented in wx)

</desc>
  </func>

  <func>
    <name name="tile" arity="1" clause_i="1" since=""/>
    <fsummary>See: <c>tile/2</c></fsummary>
  </func>

  <func>
    <name name="tile" arity="2" clause_i="1" since=""/>
    <fsummary>Tiles the MDI child windows either horizontally or vertically depending on whether <c>orient</c> is <c>wxHORIZONTAL</c> or <c>wxVERTICAL</c>. </fsummary>
    <desc>
Tiles the MDI child windows either horizontally or vertically depending on whether <c>orient</c> is <c>wxHORIZONTAL</c> or <c>wxVERTICAL</c>.

This method is only implemented in MSW MDI implementation and does nothing under the other platforms.

</desc>
  </func>
  </funcs>
</erlref>


text:
@interface PodsDummy_OCMockito : NSObject
@end
@implementation PodsDummy_OCMockito
@end


text:
#ifndef _AMINOFONTS_H
#define _AMINOFONTS_H

#include "freetype-gl.h"
#include "vertex-buffer.h"

#include <map>

#include "base_js.h"
#include "gfx.h"
#include "shaders.h"

class AminoFontsFactory;

/**
 * AminoFonts class.
 */
class AminoFonts : public AminoJSObject {
public:
    AminoFonts();
    ~AminoFonts();

    //creation
    static AminoFontsFactory* getFactory();

    //init
    static NAN_MODULE_INIT(Init);

private:
    //JS constructor
    static NAN_METHOD(New);
};

/**
 * AminoFonts class factory.
 */
class AminoFontsFactory : public AminoJSObjectFactory {
public:
    AminoFontsFactory(Nan::FunctionCallback callback);

    AminoJSObject* create() override;
};

class AminoFontFactory;

/**
 * AminoFont class.
 */
class AminoFont : public AminoJSObject {
public:
    std::string fontName;
    int fontWeight;
    std::string fontStyle;

    AminoFont();
    ~AminoFont();

    texture_font_t *getFontWithSize(int size);
    std::string getFontInfo();

    //creation
    static AminoFontFactory* getFactory();

    //init
    static v8::Local<v8::FunctionTemplate> GetInitFunction();

private:
    //Note: instance kept
    static FT_Library library;

    //JS constructor
    static NAN_METHOD(New);

    void preInit(Nan::NAN_METHOD_ARGS_TYPE info) override;

protected:
    AminoFonts *fonts = NULL;
    texture_atlas_t *atlas = NULL;
    Nan::Persistent<v8::Object> fontData;
    std::map<int, texture_font_t *> fontSizes;

    void destroy() override;
    void destroyAminoFont();
};

/**
 * AminoFont class factory.
 */
class AminoFontFactory : public AminoJSObjectFactory {
public:
    AminoFontFactory(Nan::FunctionCallback callback);

    AminoJSObject* create() override;
};

class AminoFontSizeFactory;

/**
 * AminoFontSize class.
 */
class AminoFontSize : public AminoJSObject {
public:
    texture_font_t *fontTexture = NULL;
    AminoFont *font = NULL;

    AminoFontSize();
    ~AminoFontSize();

    float getTextWidth(const char *text);

    //creation
    static AminoFontSizeFactory* getFactory();

    //init
    static v8::Local<v8::FunctionTemplate> GetInitFunction();

private:
    //JS constructor
    static NAN_METHOD(New);

    //JS methods
    static NAN_METHOD(CalcTextWidth);
    static NAN_METHOD(GetFontMetrics);

    void preInit(Nan::NAN_METHOD_ARGS_TYPE info) override;
};

/**
 * AminoFontSize class factory.
 */
class AminoFontSizeFactory : public AminoJSObjectFactory {
public:
    AminoFontSizeFactory(Nan::FunctionCallback callback);

    AminoJSObject* create() override;
};

/**
 * Atlas texture (per AminoGfx instance).
 */
struct amino_atlas_t {
    GLuint textureId;
};

/**
 * Font Shader.
 */
class AminoFontShader : public TextureShader {
public:
    AminoFontShader();

    void setColor(GLfloat color[3]);

    amino_atlas_t getAtlasTexture(texture_atlas_t *atlas, bool createIfMissing, bool &newTexture);

protected:
    GLint uColor;

    //textures (Note: never destroyed)
    std::map<texture_atlas_t *, amino_atlas_t> atlasTextures;

    void initShader() override;
};

#endif


text:
using NodeGames.Network.Network.Messages;

namespace NodeGames.Network.Network
{
    public interface INetworkedActor
    {
        int Id { get; }
        bool ReplicateProperties { get; }
        bool ReplicateMovement { get; }
        bool IsDirty { get; set; }
        bool IsMovementDirty { get; set; }
        bool IsMarkedToDestroy { get; set; }

        void Serialize(INetworkMessageOut message);
        void Deserialize(INetworkMessageIn message);

        void SetLocation(int x, int y);
        Point GetLocation();

        void RemoteDestroyed();
    }
}


text:
package com.helicalinsight.hwf.core;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;

public interface IResponse {
    public JSONObject setOutPutResponse(HttpServletResponse response, JSONObject outputTag, String outputFromInputTag);

}


text:
package io.quarkus.vertx.http.runtime.webjar;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.jboss.logging.Logger;

import io.quarkus.runtime.ShutdownContext;
import io.quarkus.runtime.annotations.Recorder;

@Recorder
public class WebJarRecorder {

    private static final Logger LOG = Logger.getLogger(WebJarRecorder.class);

    public void shutdownTask(ShutdownContext shutdownContext, String deploymentBasePath) {

        shutdownContext.addShutdownTask(new DeleteDirectoryRunnable(deploymentBasePath));
    }

    private static final class DeleteDirectoryRunnable implements Runnable {

        private final Path directory;

        private DeleteDirectoryRunnable(String directory) {
            this.directory = Paths.get(directory);
        }

        @Override
        public void run() {
            try {
                Files.walkFileTree(directory,
                        new SimpleFileVisitor<Path>() {
                            @Override
                            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                                Files.delete(dir);
                                return FileVisitResult.CONTINUE;
                            }

                            @Override
                            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                                Files.delete(file);
                                return FileVisitResult.CONTINUE;
                            }
                        });
            } catch (IOException e) {
                LOG.error("Error cleaning up webjar temporary directory: " + directory, e);
            }
        }
    }
}


text:
function loc = match_sorted(a,s)
%MATCH_SORTED   Location of matches in a sorted set.
% MATCH_SORTED(A,S) returns LOC such that S(LOC(i)) = A(i).
% If A(i) is not in S, LOC(i) = 0.
% S must be sorted and unique.
%
% This function is a special case of ISMEMBER_SORTED.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

loc = ismembc2(a,s);